diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWCurrentUserIdentityInfo.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWCurrentUserIdentityInfo.swift index bee51c0eca..1e1a0c0080 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWCurrentUserIdentityInfo.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWCurrentUserIdentityInfo.swift @@ -520,7 +520,10 @@ public final class DWCurrentUserIdentityInfo: NSObject { }) { usernames.insert(usernames.remove(at: index), at: 0) } else if persisted.dpnsNames.contains(where: { - DWContestedNameStatusService.labelsMatch($0.label, mainName) + // `isOwned == false` rows are sold/transferred-away labels + // retained for trade history β€” without this check a stale + // pick of a SOLD name resurfaces through the label cache. + $0.isOwned && DWContestedNameStatusService.labelsMatch($0.label, mainName) }) { usernames.insert(mainName, at: 0) } diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift index f8f69572f4..1e54afcf74 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift @@ -328,6 +328,7 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { case identityRegistration(Error) case dpnsRegistration(Error) case availabilityCheck(Error) + case purchase(Error) case insufficientPlatformCredits(required: UInt64, available: UInt64) case insufficientShieldedBalance(requiredCredits: UInt64, availableCredits: UInt64) case shieldedBalanceImmature(readyAt: Date) @@ -357,6 +358,10 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { return underlying.localizedDescription case .dpnsRegistration(let underlying): return underlying.localizedDescription + case .purchase(let underlying): + // Marketplace-typed failures (price changed, delisted, + // insufficient credits) get their friendly wording. + return UsernameMarketplaceService.userFacingMessage(for: underlying) case .availabilityCheck(let underlying): return underlying.localizedDescription case .insufficientPlatformCredits(let required, let available): @@ -823,6 +828,188 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { invitationURI: invitationURI) } + /// Direct purchase of a marketplace-listed name from the + /// create-username flow: ensure this wallet's identity exists and + /// holds enough credits β€” creating it Core-funded, or topping it up + /// from the wallet balance β€” then buy at exactly `priceCredits`. + /// + /// Core funding only: the form offers this purchase against the + /// wallet balance, and the marketplace's own buy sheet remains the + /// path for already-funded identities + /// (`UsernameMarketplaceService.purchase`). Same PIN gate / + /// single-flight / phase reporting as `startCreateUsername`; the + /// `.completed` transition performs the DWGlobalOptions mirror + /// writes (a purchase never writes a contested bookmark, so the + /// deferral branch in `handlePhaseChange` cannot trigger). + @discardableResult + func startPurchaseUsername(name: String, priceCredits: UInt64) async throws -> Identifier { + Self.logger.info("πŸͺͺ IDENT-COORD :: startPurchaseUsername name=\(name, privacy: .public) priceCredits=\(priceCredits, privacy: .public)") + + guard let wallet = SwiftDashSDKHost.shared.wallet else { + throw CoordinatorError.noWallet + } + guard let network = SwiftDashSDKHost.shared.runningNetwork else { + throw CoordinatorError.noNetwork + } + guard let modelContainer = SwiftDashSDKHost.shared.modelContainer else { + throw CoordinatorError.noModelContainer + } + + // Single-flight β€” same rationale as `startCreateUsername`: the + // funding FFI calls race to their terminal even if we stop + // observing, and two funding attempts must never overlap. + let currentPhase = phase + switch currentPhase { + case .preparingKeys, .inFlight: + Self.logger.warning("πŸͺͺ IDENT-COORD :: rejecting concurrent purchase; phase=\(String(describing: currentPhase), privacy: .public)") + throw CoordinatorError.alreadyInFlight + case .idle, .completed, .failed: + break + } + resetState() + currentUsername = name + currentFundingSource = .core + + let newController = DWIdentityRegistrationController() + controller = newController + wireController(newController) + // Both funding branches below (IdentityCreate, top-up) move value + // through a Core asset lock, so the polling applies as in the + // Core-funded registration path. + startAssetLockPolling(walletId: wallet.walletId, modelContainer: modelContainer) + + do { + try await authorizer.authorize() + } catch DWIdentityAuthorizer.AuthError.cancelled { + resetState() + throw CoordinatorError.authCancelled + } catch { + lastErrorMessage = CoordinatorError.authFailed.localizedDescription + newController.enterFailed(lastErrorMessage ?? "") + throw CoordinatorError.authFailed + } + + // Credits the buyer identity must hold: the sale price plus the + // same 0.03-DASH headroom a fresh registration funds itself with, + // covering the purchase transition fee (and Core-side asset-lock + // conversion losses). + let headroomDuffs = DWDP_MIN_BALANCE_TO_CREATE_USERNAME + let requiredCredits = priceCredits + headroomDuffs * 1_000 + let signer = KeychainSigner(modelContainer: modelContainer) + + let identityId: Identifier + do { + if let existingId = lookupExistingIdentityId( + walletId: wallet.walletId, + modelContainer: modelContainer) + { + identityId = existingId + newController.enterInFlight() + // Top up only the shortfall. The persisted balance can lag + // the chain; the headroom absorbs small drift, and the SDK + // still pre-flights the real balance inside the purchase. + let heldCredits = UsernameMarketplaceService.identityBalanceCredits( + identityId: existingId, + container: modelContainer) + if heldCredits < requiredCredits { + // Same floor as `topUpResumedIdentityIfNeeded`: Rust + // rejects Core top-ups below `minimumCoreTopUpDuffs`, + // and a near-covered identity can shortfall under it. + let shortfallDuffs = max( + (requiredCredits - heldCredits + 999) / 1_000, + Self.minimumCoreTopUpDuffs) + Self.logger.info("πŸͺͺ IDENT-COORD :: purchase top-up shortfallDuffs=\(shortfallDuffs, privacy: .public)") + _ = try await wallet.topUpIdentityWithFunding( + identityId: existingId, + amountDuffs: shortfallDuffs, + accountIndex: Self.defaultAccountIndex) + } + } else { + // Fresh identity, funded with the full purchase amount. + // Key prep is identical to the registration path. + newController.enterPreparingKeys() + var pubkeys = try wallet.prePersistIdentityKeysForRegistration( + identityIndex: Self.pinnedIdentityIndex, + keyCount: Self.defaultKeyCount, + network: network) + pubkeys.append(contentsOf: try DWDashPayIdentityKeys.deriveAndPersist( + wallet: wallet, + identityIdString: "", + identityIndex: Self.pinnedIdentityIndex, + specifications: DWDashPayIdentityKeys.registrationSpecifications( + firstKeyId: Self.defaultKeyCount), + network: network)) + newController.enterInFlight() + let fundingDuffs = (requiredCredits + 999) / 1_000 + let result = try await wallet.registerIdentityWithFunding( + amountDuffs: fundingDuffs, + accountIndex: Self.defaultAccountIndex, + identityIndex: Self.pinnedIdentityIndex, + identityPubkeys: pubkeys, + signer: signer) + identityId = result.0 + } + } catch { + Self.logger.error("πŸͺͺ IDENT-COORD :: purchase funding failed: \(String(describing: error), privacy: .public)") + failedAtPhase = assetLockStatus < 2 ? .processingPayment : .creatingID + lastErrorMessage = error.localizedDescription + newController.enterFailed(error.localizedDescription) + throw CoordinatorError.identityRegistration(error) + } + + // The purchase itself β€” exact-price: the SDK pre-flights the + // listing and the buyer's balance, and consensus rejects any + // seller-side price change (typed `.priceChanged`). The trade + // index keys on the normalized label. + do { + let normalized = (try? SwiftDashSDKHost.shared.sdk?.dpnsNormalizeLabel(name)) + .flatMap { $0 } ?? name.lowercased() + _ = try await wallet.purchaseDpnsName( + purchaserIdentityId: identityId, + name: normalized, + expectedPriceCredits: priceCredits, + signer: signer) + Self.logger.info("πŸͺͺ IDENT-COORD :: purchased \(name, privacy: .public) for \(priceCredits, privacy: .public) credits") + } catch { + Self.logger.error("πŸͺͺ IDENT-COORD :: purchase failed: \(String(describing: error), privacy: .public)") + failedAtPhase = .registrationUsername + let coordError = CoordinatorError.purchase(error) + lastErrorMessage = coordError.localizedDescription + newController.enterFailed(lastErrorMessage ?? "") + throw coordError + } + + // The name now points at this identity β€” but a purchase writes + // marketplace rows, not the `dpns_names` cache every username + // surface reads. Pull the name into that cache, then adopt the + // identity through the same reconciliation the seed-recovery path + // uses: main-identity bookmark, DWGlobalOptions mirrors from SDK + // truth, contacts refresh, and the canonical registration + // notification that installs the DashPay tabs. (The bare + // phase-completion below is NOT enough for an identity that + // arrived outside the bridge β€” DWDashPayModel deliberately + // ignores bridge events without a registration username.) + do { + _ = try await wallet.syncDpnsNames(identityId: identityId) + } catch { + // The reconcile falls back to persisted rows; the Home-appear + // syncFromNetwork retries the cache pull. + Self.logger.warning("πŸͺͺ IDENT-COORD :: post-purchase syncDpnsNames failed: \(String(describing: error), privacy: .public)") + } + _ = DWCurrentUserIdentityInfo.shared.reconcileRecoveredIdentity() + // The reconcile adopted the CANONICAL SDK label into the mirrors. + // Align `currentUsername` with it before the `.completed` + // transition, whose mirror write would otherwise overwrite the + // adopted label with the buyer's raw typed form (any casing that + // normalizes equal can buy the name). + if let adopted = DWGlobalOptions.sharedInstance().dashpayUsername, !adopted.isEmpty { + currentUsername = adopted + } + newController.enterCompleted(identityId: identityId) + Self.logger.info("πŸͺͺ IDENT-COORD :: purchase complete") + return identityId + } + /// Restart the flow after a `.failed` terminal phase. Identical /// to `startCreateUsername(_:fundingSource:)` β€” the prior /// controller is discarded and a fresh attempt runs end-to-end. diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 7517d4d971..bfd4fdfe51 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -281,7 +281,23 @@ struct UsernameMarketplaceService { guard let wallet = SwiftDashSDKHost.shared.wallet else { throw ServiceError.noIdentity } - return try await wallet.syncDpnsMarketplace() + let summary = try await wallet.syncDpnsMarketplace() + // The sync can move names between identities (a sale or transfer + // prunes the seller's dpns_names cache) β€” bump the identity-info + // snapshot so every username surface re-reads instead of serving + // the pre-sale list until the next unrelated invalidation. + DWCurrentUserIdentityInfo.shared.refreshFromSDK() + // If the departed name was the one the app displays everywhere + // (the DWGlobalOptions mirror), re-adopt from SDK truth β€” the + // same reconciliation the recovery path uses, which rewrites the + // mirror and posts the canonical registration notification. + if let mirror = DWGlobalOptions.sharedInstance().dashpayUsername, !mirror.isEmpty, + !DWCurrentUserIdentityInfo.shared.usernames.contains(where: { + DWContestedNameStatusService.labelsMatch($0, mirror) + }) { + _ = DWCurrentUserIdentityInfo.shared.reconcileRecoveredIdentity() + } + return summary } // MARK: Trade actions (all PIN-gated; SDK errors are typed) @@ -526,7 +542,10 @@ struct UsernameMarketplaceService { /// Friendlier wording for the typed SDK failures a user acts on; /// everything else keeps the SDK's own description. - static func userFacingMessage(for error: Error) -> String { + /// Pure errorβ†’wording mapping β€” `nonisolated` so nonisolated + /// LocalizedError conformances (e.g. the registration coordinator's + /// `.purchase` case) can call it. + nonisolated static func userFacingMessage(for error: Error) -> String { if let walletError = error as? PlatformWalletError { switch walletError { case .notForSale: diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift index 09e8ce9f08..126a4917b2 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift @@ -111,6 +111,16 @@ struct CreateUsernameView: View { /// through this alert (instead of submitting directly) when the /// typed name is contested-eligible β€” `viewModel.isContestedCandidate`. @State private var showContestedConfirmation: Bool = false + /// Tracks the buy-listed-name confirmation alert; the button routes + /// here when `viewModel.canPurchaseListedNameDirectly`. + @State private var showPurchaseConfirmation: Bool = false + /// Terminal success alert of a direct listing purchase; OK finishes + /// the flow like a completed registration. + @State private var showPurchaseSuccess: Bool = false + /// The name captured when the purchase started β€” the text field stays + /// editable across the PIN gate + funding + purchase, so the success + /// alert must not read the live field. + @State private var purchasedUsername: String = "" /// Drives the success alert shown when registration reaches the /// terminal `.completed` phase. OK dismisses the screen. @State private var showSuccess: Bool = false @@ -194,9 +204,10 @@ struct CreateUsernameView: View { // Taken-but-listed pointer: the owner has put the name up for // sale in the Username Marketplace, so "taken" isn't the end - // of the road. - if let salePriceDuffs = viewModel.takenNameSalePriceDuffs { - forSaleHint(priceDuffs: salePriceDuffs) + // of the road β€” affordable listings under the direct-purchase + // ceiling are buyable right here via the Buy button below. + if let salePriceCredits = viewModel.takenNameSalePriceCredits { + forSaleHint(priceCredits: salePriceCredits) .padding(.top, 20) } @@ -254,22 +265,26 @@ struct CreateUsernameView: View { Spacer() DashButton( - text: viewModel.hasPendingRegistrationRecovery - ? NSLocalizedString("Finish registration", comment: "DashPay registration recovery") - : NSLocalizedString("Continue", comment: ""), - isEnabled: viewModel.uiState.canContinue && !screenLockedAfterAuth, + text: primaryButtonText, + isEnabled: (viewModel.uiState.canContinue || viewModel.canPurchaseListedNameDirectly) + && !screenLockedAfterAuth, isLoading: inProgress ) { // `viewModel.uiState.canContinue` is only true after // `checkIfBlocked` flips `usernameBlockedRule` to - // `.valid`, so the button is gated on the same condition - // β€” no `if .valid` check needed here. + // `.valid`, so the registration branches are gated on the + // same condition. A taken-but-listed name never reaches + // `.valid`; its buyable state enables the button through + // `canPurchaseListedNameDirectly` and routes to the + // purchase confirmation instead. // // Contested-name submissions go through a confirmation // alert first so the user explicitly acknowledges the // ~45 min testnet / ~2 weeks mainnet voting wait and // the locked Dash. Non-contested names submit directly. - if viewModel.isContestedCandidate { + if viewModel.canPurchaseListedNameDirectly { + showPurchaseConfirmation = true + } else if viewModel.isContestedCandidate { showContestedConfirmation = true } else { performSubmit() @@ -335,6 +350,32 @@ struct CreateUsernameView: View { "This name requires voting. Your Dash will be locked until voting completes.", comment: "Usernames")) } + .alert( + NSLocalizedString("Buy username", comment: "Usernames"), + isPresented: $showPurchaseConfirmation + ) { + Button(NSLocalizedString("Buy", comment: "")) { + performPurchase() + } + Button(NSLocalizedString("Cancel", comment: ""), role: .cancel) { } + } message: { + Text(String.localizedStringWithFormat( + NSLocalizedString( + "β€œ%1$@” will be purchased for %2$@ Dash. The price is paid from your wallet balance.", + comment: "Usernames"), + viewModel.username, + ((viewModel.takenNameSalePriceCredits ?? 0) / 1_000).dashAmount.formattedDashAmountWithoutCurrencySymbol)) + } + .alert( + NSLocalizedString("Username purchased", comment: "Usernames"), + isPresented: $showPurchaseSuccess + ) { + Button(NSLocalizedString("OK", comment: "")) { finish() } + } message: { + Text(String.localizedStringWithFormat( + NSLocalizedString("β€œ%@” is now your username.", comment: "Usernames"), + purchasedUsername)) + } .alert( NSLocalizedString("Username registered", comment: "Usernames"), isPresented: $showSuccess @@ -482,6 +523,21 @@ struct CreateUsernameView: View { } } + /// Primary button label: registration recovery > direct listing + /// purchase (priced) > plain Continue. + private var primaryButtonText: String { + if viewModel.hasPendingRegistrationRecovery { + return NSLocalizedString("Finish registration", comment: "DashPay registration recovery") + } + if viewModel.canPurchaseListedNameDirectly, + let credits = viewModel.takenNameSalePriceCredits { + return String.localizedStringWithFormat( + NSLocalizedString("Buy for %@ Dash", comment: "Usernames"), + (credits / 1_000).dashAmount.formattedDashAmountWithoutCurrencySymbol) + } + return NSLocalizedString("Continue", comment: "") + } + /// Deadline as "Today 20:33"-style text (DWDateFormatter's relative /// short date + time). Testnet contest windows are minutes long, so /// the time matters; a locale-formatted full date alone would bury it. @@ -553,10 +609,35 @@ struct CreateUsernameView: View { } /// Blue informational callout when the typed name is taken but its - /// owner has listed it in the Username Marketplace: buying it there - /// is the actual way to get this name. - private func forSaleHint(priceDuffs: UInt64) -> some View { - HStack(alignment: .top, spacing: 12) { + /// owner has listed it in the Username Marketplace. Three variants: + /// buyable right here (under the ceiling, wallet covers it), listed + /// at or above the direct-purchase ceiling (pointed at the + /// marketplace, with the suggestion to pick another name for now), + /// or listed but not currently affordable (plain pointer). + private func forSaleHint(priceCredits: UInt64) -> some View { + let priceText = (priceCredits / 1_000).dashAmount.formattedDashAmountWithoutCurrencySymbol + let body: String + if viewModel.canPurchaseListedNameDirectly { + body = String.localizedStringWithFormat( + NSLocalizedString( + "The owner of this username has listed it for %@ Dash. You can buy it right now β€” the price is paid from your wallet balance.", + comment: "Usernames"), + priceText) + } else if viewModel.listedNameExceedsDirectPurchaseLimit { + body = String.localizedStringWithFormat( + NSLocalizedString( + "The owner of this username has listed it for %1$@ Dash. Purchases over %2$@ Dash must be made from the Username Marketplace β€” choose another username for now; you can decide on buying this one later.", + comment: "Usernames"), + priceText, + CreateUsernameViewModel.directPurchaseMaxDuffs.dashAmount.formattedDashAmountWithoutCurrencySymbol) + } else { + body = String.localizedStringWithFormat( + NSLocalizedString( + "The owner of this username has listed it in the Username Marketplace for %@ Dash. You can buy it there instead.", + comment: "Usernames"), + priceText) + } + return HStack(alignment: .top, spacing: 12) { Image(systemName: "tag.fill") .foregroundColor(.dash.blue) .font(.system(size: 20)) @@ -564,11 +645,7 @@ struct CreateUsernameView: View { Text(NSLocalizedString("For sale", comment: "Usernames")) .font(.subheadline.bold()) .foregroundColor(.dash.blue) - Text(String.localizedStringWithFormat( - NSLocalizedString( - "The owner of this username has listed it in the Username Marketplace for %@ Dash. You can buy it there instead.", - comment: "Usernames"), - priceDuffs.dashAmount.formattedDashAmountWithoutCurrencySymbol)) + Text(body) .font(.caption) .foregroundColor(.dash.secondaryText) .fixedSize(horizontal: false, vertical: true) @@ -614,6 +691,32 @@ struct CreateUsernameView: View { } } + /// Buy the listed name at its captured price. Mirrors + /// `performSubmit`'s spinner discipline: `inProgress` keeps the + /// screen alive across the PIN gate, funding, and the purchase + /// itself; the outcome drives the purchase-success / error alert. + private func performPurchase() { + purchasedUsername = viewModel.username.trimmingCharacters(in: .whitespacesAndNewlines) + Task { + inProgress = true + screenLockedAfterAuth = false + let outcome = await viewModel.purchaseListedUsername(name: purchasedUsername) + inProgress = false + switch outcome { + case .success: + showPurchaseSuccess = true + case .cancelled: + break + case .failure(let message): + registrationErrorMessage = message + case .submittedForVoting: + // A purchase never enters a vote; the outcome enum is + // shared with registration, this arm is unreachable. + break + } + } + } + /// Encapsulates the submit-to-bridge dance so both the direct /// Continue path and the contested-name alert's "Submit anyway" /// button can share the code. Writes the funding-source pick diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift index 5dfd914406..dd89324d74 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift @@ -126,11 +126,40 @@ class CreateUsernameViewModel: ObservableObject { /// passes β€” instead of an unverifiable "in progress" claim. @Published private(set) var activeContestEndsAt: Date? - /// Sale price (duffs) when the typed name is TAKEN but its owner has - /// listed it in the Username Marketplace. Turns the dead-end - /// "Username taken" into a pointer to the listing. nil when the name - /// is not for sale or the best-effort lookup failed. - @Published private(set) var takenNameSalePriceDuffs: UInt64? + /// Sale price (CREDITS, exactly as listed β€” the purchase call must + /// echo the listed price verbatim or the SDK refuses it as changed) + /// when the typed name is TAKEN but its owner has listed it in the + /// Username Marketplace. Turns the dead-end "Username taken" into a + /// pointer to the listing β€” or a direct buy, below. nil when the + /// name is not for sale or the best-effort lookup failed. + @Published private(set) var takenNameSalePriceCredits: UInt64? + + /// App policy ceiling for buying a listed name straight from this + /// form: at 10 DASH or more the purchase belongs in the Username + /// Marketplace, where the full listing context (trade history, + /// owner, fiat price) is visible before committing that much. + static let directPurchaseMaxDuffs: UInt64 = 10 * 100_000_000 + + /// The typed name's listing can be bought right here: priced under + /// the direct-purchase ceiling, with a wallet balance that covers + /// the price plus the identity fee headroom. Not offered in + /// invitation mode (the voucher funds a registration, not a trade) + /// or while a registration recovery is pending. + var canPurchaseListedNameDirectly: Bool { + guard let credits = takenNameSalePriceCredits, + !isInvitationMode, + !hasPendingRegistrationRecovery else { return false } + let priceDuffs = credits / 1_000 + guard priceDuffs < Self.directPurchaseMaxDuffs else { return false } + return coreSpendableDuffs >= priceDuffs + DWDP_MIN_BALANCE_TO_CREATE_USERNAME + } + + /// Listed at or above the direct-purchase ceiling β€” the form points + /// at the marketplace instead of offering the buy. + var listedNameExceedsDirectPurchaseLimit: Bool { + guard let credits = takenNameSalePriceCredits else { return false } + return credits / 1_000 >= Self.directPurchaseMaxDuffs + } /// The active vote's deadline has passed β€” the poll is being /// finalized on-chain. "Join as a contender" would be a stale claim @@ -368,6 +397,35 @@ class CreateUsernameViewModel: ObservableObject { } } + /// Buy `name` (the taken, listed label captured by the caller at + /// confirmation time β€” the text field stays editable during the + /// flow) at the exact price captured by the availability check. + /// Routes through + /// `DWIdentityRegistrationCoordinator.startPurchaseUsername`, which + /// creates or tops up this wallet's identity from the Core balance + /// and buys at exactly the captured credits β€” a seller-side price + /// change is refused by consensus and surfaces as a typed failure, + /// as does a price/name mismatch from a mid-flight edit. + func purchaseListedUsername(name: String) async -> UsernameRegistrationOutcome { + guard let credits = takenNameSalePriceCredits else { + // The gate (`canPurchaseListedNameDirectly`) shouldn't let a + // priceless state reach here; answer with the marketplace's + // canonical wording rather than crashing. + return .failure(NSLocalizedString("This username is not for sale.", comment: "Username marketplace")) + } + do { + _ = try await DWIdentityRegistrationCoordinator.shared.startPurchaseUsername( + name: name, + priceCredits: credits) + return .success + } catch DWIdentityRegistrationCoordinator.CoordinatorError.authCancelled { + return .cancelled + } catch { + DWLogger.log("CreateUsername: purchase failed for '\(name)': \(error.localizedDescription)") + return .failure(error.localizedDescription) + } + } + /// Human wording for a failed registration. Platform surfaces its refusals /// as a Rust debug dump of the whole state transition β€” hundreds of /// characters of `ContestedDocumentResourceVotePoll { … }` that fill the @@ -444,7 +502,7 @@ class CreateUsernameViewModel: ObservableObject { isLockedContestedName = false activeContestContenders = nil activeContestEndsAt = nil - takenNameSalePriceDuffs = nil + takenNameSalePriceCredits = nil } guard !username.isEmpty else { @@ -550,7 +608,7 @@ class CreateUsernameViewModel: ObservableObject { /// `.invalidCritical`; our OWN pending contested submission β†’ /// `.warning` ("in voting"); RPC failure β†’ `.error` (re-runs on the /// next keystroke or balance publish). A taken name additionally gets - /// a best-effort marketplace lookup β€” `takenNameSalePriceDuffs` when + /// a best-effort marketplace lookup β€” `takenNameSalePriceCredits` when /// its owner listed it for sale. `canContinue` is true only for /// `.valid` β€” the submit-time `registerDpnsName` failure remains the /// second line of defense. @@ -564,7 +622,7 @@ class CreateUsernameViewModel: ObservableObject { var locked = false var activeContenders: Int? var activeContestEnd: Date? - var salePriceDuffs: UInt64? + var salePriceCredits: UInt64? do { // Two independent questions about the same label, so ask both at // once. Chaining them put a second DAPI round trip behind the @@ -642,7 +700,7 @@ class CreateUsernameViewModel: ObservableObject { // plain "taken" wording. if let sale = try? await marketplaceService.nameState(username), sale.isForSale { - salePriceDuffs = sale.priceDuffs + salePriceCredits = sale.priceCredits } result = .invalidCritical } @@ -660,7 +718,7 @@ class CreateUsernameViewModel: ObservableObject { isLockedContestedName = locked activeContestContenders = activeContenders activeContestEndsAt = activeContestEnd - takenNameSalePriceDuffs = salePriceDuffs + takenNameSalePriceCredits = salePriceCredits uiState.usernameBlockedRule = result uiState.canContinue = (result == .valid) armContestBoundaryRevalidation() diff --git a/DashWallet/Sources/UI/Menu/Security/Wallets/IdentitiesViewModel.swift b/DashWallet/Sources/UI/Menu/Security/Wallets/IdentitiesViewModel.swift index 80d110b434..b97fb8b334 100644 --- a/DashWallet/Sources/UI/Menu/Security/Wallets/IdentitiesViewModel.swift +++ b/DashWallet/Sources/UI/Menu/Security/Wallets/IdentitiesViewModel.swift @@ -296,7 +296,16 @@ final class IdentitiesViewModel: ObservableObject { guard let candidate, let pendingLabel else { return false } return DWContestedNameStatusService.labelsMatch(candidate, pendingLabel) } - let allNames = identity.dpnsNames.map(\.label) + // Sold / transferred-away labels stay in the cache as rows with + // `isOwned == false` (their trade history remains browsable) β€” + // they are no longer this identity's names and must not appear + // in the picker or count toward "has a name". + let allNames = identity.dpnsNames.filter(\.isOwned).map(\.label) + let departedLabels = identity.dpnsNames.filter { !$0.isOwned }.map(\.label) + let isSoldAway: (String?) -> Bool = { candidate in + guard let candidate else { return false } + return departedLabels.contains { DWContestedNameStatusService.labelsMatch($0, candidate) } + } let pendingBelongsToIdentity = pendingLabel != nil && ( isPending(identity.mainDpnsName) || isPending(identity.dpnsName) @@ -304,10 +313,14 @@ final class IdentitiesViewModel: ObservableObject { ) let ownedNames = allNames.filter { !isPending($0) } let alias = identity.alias?.nonEmptyString - let mainName = isPending(identity.mainDpnsName) + // The display-pick scalars can outlive a sale of the picked name; + // a KNOWN-departed label falls through to the next candidate. + // (Scalars are still trusted while the label cache is empty β€” + // they double as the hydration fallback.) + let mainName = isPending(identity.mainDpnsName) || isSoldAway(identity.mainDpnsName) ? nil : identity.mainDpnsName?.nonEmptyString - let preferredName = isPending(identity.dpnsName) + let preferredName = isPending(identity.dpnsName) || isSoldAway(identity.dpnsName) ? nil : identity.dpnsName?.nonEmptyString let displayedName = mainName ?? preferredName ?? ownedNames.first diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index d74a6a9846..117d686ab9 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -4384,6 +4384,27 @@ /* Usernames */ "The owner of this username has listed it in the Username Marketplace for %@ Dash. You can buy it there instead." = "The owner of this username has listed it in the Username Marketplace for %@ Dash. You can buy it there instead."; +/* Usernames */ +"The owner of this username has listed it for %@ Dash. You can buy it right now β€” the price is paid from your wallet balance." = "The owner of this username has listed it for %@ Dash. You can buy it right now β€” the price is paid from your wallet balance."; + +/* Usernames */ +"The owner of this username has listed it for %1$@ Dash. Purchases over %2$@ Dash must be made from the Username Marketplace β€” choose another username for now; you can decide on buying this one later." = "The owner of this username has listed it for %1$@ Dash. Purchases over %2$@ Dash must be made from the Username Marketplace β€” choose another username for now; you can decide on buying this one later."; + +/* Usernames */ +"Buy for %@ Dash" = "Buy for %@ Dash"; + +/* Usernames */ +"Buy username" = "Buy username"; + +/* Usernames */ +"β€œ%1$@” will be purchased for %2$@ Dash. The price is paid from your wallet balance." = "β€œ%1$@” will be purchased for %2$@ Dash. The price is paid from your wallet balance."; + +/* Usernames */ +"Username purchased" = "Username purchased"; + +/* Usernames */ +"β€œ%@” is now your username." = "β€œ%@” is now your username."; + /* Usernames */ "The masternode vote for this name has ended and the result is being finalized. Check back soon." = "The masternode vote for this name has ended and the result is being finalized. Check back soon.";