From 860884c459adea9028dcf2e44d8ba2441d355223 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 23:41:28 +0700 Subject: [PATCH 1/3] feat(dashpay): buy an affordable listed username directly from the create-username form MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Typing a taken-but-listed name dead-ended at "Username taken" with a pointer to the marketplace. Now, when the listing is priced under 10 DASH and the wallet balance covers price + fee headroom, the form offers the purchase in place: the button becomes "Buy for X Dash", a confirmation alert states the price and funding source, and a new coordinator arm (startPurchaseUsername) runs PIN → ensure identity (Core-funded create with price + 0.03 DASH headroom, or top up an existing identity by the shortfall) → purchaseDpnsName at exactly the listed credits (a seller-side price change is refused as typed `.priceChanged`, never paid). At or above the 10-DASH ceiling (`directPurchaseMaxDuffs`), the callout says the purchase must be made from the Username Marketplace and suggests choosing another username for now, deciding on the buy later. Listed-but-unaffordable keeps the plain marketplace pointer. Post-purchase, the name lives in marketplace rows, not the dpns_names cache the username surfaces read, and the identity arrived outside the registration bridge — which DWDashPayModel deliberately ignores. The coordinator therefore syncs the DPNS cache and adopts the identity via DWCurrentUserIdentityInfo.reconcileRecoveredIdentity(), the same primitive the seed-recovery path uses, so the DashPay tabs, contacts, and username mirrors all flip on (verified on the QA sim: identity created 1.43 tDash, quantumtester2 purchased at 1.4, DashPay UI installed after the fix). UsernameMarketplaceService.userFacingMessage becomes nonisolated (pure function) so the coordinator's nonisolated LocalizedError conformance can reuse the typed marketplace failure wording. Co-Authored-By: Claude Fable 5 --- .../DWIdentityRegistrationCoordinator.swift | 174 ++++++++++++++++++ .../UsernameMarketplaceService.swift | 5 +- .../CreateUsernameViewController.swift | 136 ++++++++++++-- .../CreateUsernameViewModel.swift | 76 +++++++- DashWallet/en.lproj/Localizable.strings | 21 +++ 5 files changed, 382 insertions(+), 30 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift index f8f69572f4..8498dd1460 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,175 @@ 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 { + let shortfallDuffs = (requiredCredits - heldCredits + 999) / 1_000 + 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() + 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..0bb2465605 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -526,7 +526,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..f35bb128b4 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift @@ -111,6 +111,12 @@ 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 /// Drives the success alert shown when registration reaches the /// terminal `.completed` phase. OK dismisses the screen. @State private var showSuccess: Bool = false @@ -194,9 +200,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 +261,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 +346,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"), + viewModel.username)) + } .alert( NSLocalizedString("Username registered", comment: "Usernames"), isPresented: $showSuccess @@ -482,6 +519,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 +605,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 +641,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 +687,31 @@ 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() { + Task { + inProgress = true + screenLockedAfterAuth = false + let outcome = await viewModel.purchaseListedUsername() + 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..6c3cf496e7 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,33 @@ class CreateUsernameViewModel: ObservableObject { } } + /// Buy the typed (taken, listed) name 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. + func purchaseListedUsername() 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")) + } + let name = username.trimmingCharacters(in: .whitespacesAndNewlines) + 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 +500,7 @@ class CreateUsernameViewModel: ObservableObject { isLockedContestedName = false activeContestContenders = nil activeContestEndsAt = nil - takenNameSalePriceDuffs = nil + takenNameSalePriceCredits = nil } guard !username.isEmpty else { @@ -550,7 +606,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 +620,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 +698,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 +716,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/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."; From a6a2b68e5c799d649d218bd4ed19407008563a06 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 23:50:39 +0700 Subject: [PATCH 2/3] fix(dashpay): a sold username disappears from pickers, snapshots, and mirrors MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After selling Quantumtester2, the seller's identity detail page still offered it in the display-name picker and the profile sheet still listed it under DPNS Names. The SDK side was correct — the marketplace sync's departure pass prunes the dpns_names cache and the persister reconciles PersistentDPNSName to isOwned == false (verified in the seller sim's store) — but three app-side readers ignored that verdict: - IdentitiesViewModel.rowModel mapped every label-cache row into the picker; sold/transferred rows are retained (for trade history) with isOwned == false and must be filtered out. The mainDpnsName/dpnsName display-pick scalars likewise no longer resurface a KNOWN-departed label (they still cover the empty-cache hydration window). - DWCurrentUserIdentityInfo's mainDpnsName fallback matched the label cache without the isOwned check its own comment promised, letting a stale pick of a sold name reappear in snapshot.usernames. - Nothing invalidated the revision-cached identity snapshot after a marketplace sync, so username surfaces kept serving the pre-sale list. syncNow() now bumps the snapshot, and when the sale took the globally-displayed username (the DWGlobalOptions mirror), re-adopts from SDK truth via reconcileRecoveredIdentity() — rewriting the mirror and posting the canonical registration notification. Co-Authored-By: Claude Fable 5 --- .../Identity/DWCurrentUserIdentityInfo.swift | 5 ++++- .../UsernameMarketplaceService.swift | 18 +++++++++++++++++- .../Wallets/IdentitiesViewModel.swift | 19 ++++++++++++++++--- 3 files changed, 37 insertions(+), 5 deletions(-) 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/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 0bb2465605..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) 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 From ff485bba4b7c97a8b91956b48d882161b663c45b Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Tue, 11 Aug 2026 00:21:08 +0700 Subject: [PATCH 3/3] =?UTF-8?q?fix(dashpay):=20address=20#969=20review=20?= =?UTF-8?q?=E2=80=94=20top-up=20floor,=20canonical=20mirror=20label,=20sta?= =?UTF-8?q?ble=20purchase-alert=20name?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Clamp the purchase top-up shortfall to minimumCoreTopUpDuffs (Rust rejects Core top-ups below 50,500 duffs; same floor as topUpResumedIdentityIfNeeded), so a near-covered identity doesn't fail an affordable purchase. - Align currentUsername with the reconciled canonical SDK label before the .completed transition — the mirror write no longer overwrites the adopted label with the buyer's raw typed casing. - Capture the purchased name at confirmation time and pass it through the flow: the text field stays editable across PIN + funding + purchase, so neither the success alert nor the purchase target reads the live field mid-flight. Co-Authored-By: Claude Fable 5 --- .../DWIdentityRegistrationCoordinator.swift | 15 ++++++++++++++- .../CreateUsernameViewController.swift | 9 +++++++-- .../CreateUsername/CreateUsernameViewModel.swift | 12 +++++++----- 3 files changed, 28 insertions(+), 8 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift index 8498dd1460..1e54afcf74 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/Identity/DWIdentityRegistrationCoordinator.swift @@ -912,7 +912,12 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { identityId: existingId, container: modelContainer) if heldCredits < requiredCredits { - let shortfallDuffs = (requiredCredits - heldCredits + 999) / 1_000 + // 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, @@ -992,6 +997,14 @@ final class DWIdentityRegistrationCoordinator: ObservableObject { 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 diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift index f35bb128b4..126a4917b2 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewController.swift @@ -117,6 +117,10 @@ struct CreateUsernameView: View { /// 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 @@ -370,7 +374,7 @@ struct CreateUsernameView: View { } message: { Text(String.localizedStringWithFormat( NSLocalizedString("“%@” is now your username.", comment: "Usernames"), - viewModel.username)) + purchasedUsername)) } .alert( NSLocalizedString("Username registered", comment: "Usernames"), @@ -692,10 +696,11 @@ struct CreateUsernameView: View { /// 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() + let outcome = await viewModel.purchaseListedUsername(name: purchasedUsername) inProgress = false switch outcome { case .success: diff --git a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift index 6c3cf496e7..dd89324d74 100644 --- a/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift +++ b/DashWallet/Sources/UI/DashPay/Setup/CreateUsername/CreateUsernameViewModel.swift @@ -397,20 +397,22 @@ class CreateUsernameViewModel: ObservableObject { } } - /// Buy the typed (taken, listed) name at the exact price captured by - /// the availability check. Routes through + /// 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. - func purchaseListedUsername() async -> UsernameRegistrationOutcome { + /// 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")) } - let name = username.trimmingCharacters(in: .whitespacesAndNewlines) do { _ = try await DWIdentityRegistrationCoordinator.shared.startPurchaseUsername( name: name,