From f4a74b14f8a28dc55a73735b9a207b9f39ea4815 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 20:43:43 +0700 Subject: [PATCH 1/7] =?UTF-8?q?feat(dashpay):=20Browse=20tab=20=E2=80=94?= =?UTF-8?q?=20names=20for=20sale=20across=20the=20network,=20sorted=20by?= =?UTF-8?q?=20price?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Third marketplace segment (Find Names / My Names / Browse): an alphabetical scan over ALL DPNS names via the SDK's empty-prefix searchDpnsMarketplace with its documentId cursor, keeping the listed ones and sorting client-side (highest price first by default, menu toggle for lowest). Honesty by construction: $price is not an indexable property on Dash Platform — there is no server-side "everything for sale ordered by price" at any layer — so the sort is over what the scan has covered, and the coverage line says exactly that ("500 names scanned · 12 for sale", "All N names scanned" once exhausted). Each pass fetches 5 pages of 100; "Scan more names" continues, pull-to-refresh restarts so listings re-read fresh. Rows reuse the search row (seller-clarity line included) and open the standard detail sheet with the Buy flow. Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceService.swift | 10 ++ .../UsernameMarketplaceScreen.swift | 167 ++++++++++++++++++ DashWallet/en.lproj/Localizable.strings | 33 ++++ 3 files changed, 210 insertions(+) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 0fb8e65d4e..2756d820ca 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -97,6 +97,16 @@ struct UsernameMarketplaceService { return try await wallet.searchDpnsMarketplace(prefix: prefix, limit: limit) } + /// One alphabetical page of ALL names (the SDK's empty-prefix browse), + /// each with live sale state. `startAfter` is the cursor: the previous + /// page's last documentId. Powers the Browse tab's scan — there is no + /// server-side price filter or ordering to lean on ($price is not + /// indexable), so callers filter and sort what the scan returns. + func browsePage(startAfter: Data?, limit: UInt32 = 100) async throws -> [DpnsMarketplaceName] { + guard let wallet = SwiftDashSDKHost.shared.wallet else { return [] } + return try await wallet.searchDpnsMarketplace(prefix: "", limit: limit, startAfter: startAfter) + } + /// The main identity's tracked names from the wallet's local rows — /// no network round-trip. Includes retained `.sold` / `.transferred` /// departures so the UI can show what left and to whom. diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index 790eaffb9c..7bb979df64 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -34,15 +34,22 @@ final class UsernameMarketplaceViewModel: ObservableObject { enum Segment: Int, CaseIterable { case find case mine + case browse var title: String { switch self { case .find: return NSLocalizedString("Find Names", comment: "Username marketplace: search segment") case .mine: return NSLocalizedString("My Names", comment: "Username marketplace: owned names segment") + case .browse: return NSLocalizedString("Browse", comment: "Username marketplace: browse-for-sale segment") } } } + enum BrowseSort { + case priceHighFirst + case priceLowFirst + } + @Published var segment: Segment = .find @Published var query = "" @Published var searchResults: [DpnsMarketplaceName] = [] @@ -73,6 +80,72 @@ final class UsernameMarketplaceViewModel: ObservableObject { /// claim "Available" for a name already being contested. @Published var queryContest: UsernameMarketplaceService.ContestPrecheck? + // MARK: Browse (for-sale) state + // + // `$price` is not an indexable property on Dash Platform, so there is + // no server-side "everything for sale, ordered by price" query at any + // layer. Browse is an honest client-side pass instead: page through + // ALL names alphabetically (empty-prefix search with a documentId + // cursor), keep the listed ones, and sort locally. The coverage label + // says how much of the network the sort currently reflects. + + /// For-sale names accumulated by the alphabetical scan. + @Published var browseForSale: [DpnsMarketplaceName] = [] + /// Total names scanned so far (listed or not) — the coverage label. + @Published var browseScannedCount = 0 + /// True while a scan pass is fetching pages. + @Published var isBrowseScanning = false + /// True once the alphabetical scan has walked every name. + @Published var browseExhausted = false + @Published var browseSort: BrowseSort = .priceHighFirst + + /// Cursor: last page's final documentId; nil = scan from the start. + private var browseCursor: Data? + /// Pages per scan pass — bounds one tap's network cost (100 names each). + private static let browsePagesPerPass = 5 + + var sortedBrowseForSale: [DpnsMarketplaceName] { + browseForSale.sorted { + let l = $0.priceCredits ?? 0 + let r = $1.priceCredits ?? 0 + return browseSort == .priceHighFirst ? l > r : l < r + } + } + + /// Scan another batch of pages. `reset` restarts from the top + /// (pull-to-refresh) so re-listed/delisted names re-read fresh. + func scanBrowsePages(reset: Bool = false) { + guard !isBrowseScanning else { return } + if reset { + browseCursor = nil + browseForSale = [] + browseScannedCount = 0 + browseExhausted = false + } + guard !browseExhausted else { return } + isBrowseScanning = true + Task { [weak self] in + guard let self else { return } + defer { self.isBrowseScanning = false } + let pageSize: UInt32 = 100 + for _ in 0..? @@ -293,6 +366,8 @@ struct UsernameMarketplaceScreen: View { findSection case .mine: mySection + case .browse: + browseSection } Spacer(minLength: 0) @@ -394,6 +469,98 @@ struct UsernameMarketplaceScreen: View { } } + // MARK: Browse segment + + /// Names for sale across the network, sorted by price client-side. + /// The coverage line keeps the sort honest: Platform cannot order by + /// $price, so "most expensive" means "among the names scanned so far". + private var browseSection: some View { + VStack(alignment: .leading, spacing: 0) { + HStack { + Text(viewModel.browseExhausted + ? String.localizedStringWithFormat( + NSLocalizedString("All %1$d names scanned · %2$d for sale", comment: "Username marketplace: browse coverage line once the whole network was scanned"), + viewModel.browseScannedCount, viewModel.browseForSale.count) + : String.localizedStringWithFormat( + NSLocalizedString("%1$d names scanned · %2$d for sale", comment: "Username marketplace: browse coverage line while the scan is partial"), + viewModel.browseScannedCount, viewModel.browseForSale.count)) + .font(.system(size: 12)) + .foregroundColor(.dash.secondaryText) + Spacer() + Menu { + Button { + viewModel.browseSort = .priceHighFirst + } label: { + Label(NSLocalizedString("Highest price first", comment: "Username marketplace: browse sort option"), + systemImage: viewModel.browseSort == .priceHighFirst ? "checkmark" : "arrow.down") + } + Button { + viewModel.browseSort = .priceLowFirst + } label: { + Label(NSLocalizedString("Lowest price first", comment: "Username marketplace: browse sort option"), + systemImage: viewModel.browseSort == .priceLowFirst ? "checkmark" : "arrow.up") + } + } label: { + HStack(spacing: 4) { + Image(systemName: "arrow.up.arrow.down") + Text(viewModel.browseSort == .priceHighFirst + ? NSLocalizedString("Highest price", comment: "Username marketplace: current browse sort label") + : NSLocalizedString("Lowest price", comment: "Username marketplace: current browse sort label")) + } + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.dash.blue) + } + } + .padding(.horizontal, 20) + .padding(.bottom, 8) + + ScrollView { + LazyVStack(spacing: 6) { + ForEach(viewModel.sortedBrowseForSale) { name in + searchRow(name) + } + if viewModel.browseForSale.isEmpty && !viewModel.isBrowseScanning { + emptyHint(viewModel.browseExhausted + ? NSLocalizedString("No names are for sale right now.", comment: "Username marketplace: browse scanned everything, nothing listed") + : NSLocalizedString("No names for sale found yet — scan more of the network below.", comment: "Username marketplace: browse partial scan found nothing listed")) + } + if viewModel.isBrowseScanning { + HStack(spacing: 8) { + SwiftUI.ProgressView() + Text(NSLocalizedString("Scanning names…", comment: "Username marketplace: browse scan in progress")) + .font(.system(size: 12)) + .foregroundColor(.dash.secondaryText) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 14) + } else if !viewModel.browseExhausted { + Button { + viewModel.scanBrowsePages() + } label: { + Text(NSLocalizedString("Scan more names", comment: "Username marketplace: continue the browse scan")) + .font(.system(size: 14, weight: .semibold)) + .foregroundColor(.dash.blue) + .frame(maxWidth: .infinity) + .padding(.vertical, 12) + } + .buttonStyle(.plain) + } + } + .padding(.horizontal, 15) + .padding(.top, 4) + .padding(.bottom, 24) + } + .refreshable { + viewModel.scanBrowsePages(reset: true) + } + } + .onAppear { + if viewModel.browseScannedCount == 0 { + viewModel.scanBrowsePages() + } + } + } + // MARK: My Names segment private var mySection: some View { diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 6b3dfb7bb4..bf4a07a23f 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -803,6 +803,39 @@ /* Username marketplace: activity overlay while the contested request transition runs */ "Submitting your username request…" = "Submitting your username request…"; +/* Username marketplace: browse-for-sale segment */ +"Browse" = "Browse"; + +/* Username marketplace: browse coverage line while the scan is partial */ +"%1$d names scanned · %2$d for sale" = "%1$d names scanned · %2$d for sale"; + +/* Username marketplace: browse coverage line once the whole network was scanned */ +"All %1$d names scanned · %2$d for sale" = "All %1$d names scanned · %2$d for sale"; + +/* Username marketplace: browse sort option */ +"Highest price first" = "Highest price first"; + +/* Username marketplace: browse sort option */ +"Lowest price first" = "Lowest price first"; + +/* Username marketplace: current browse sort label */ +"Highest price" = "Highest price"; + +/* Username marketplace: current browse sort label */ +"Lowest price" = "Lowest price"; + +/* Username marketplace: browse scanned everything, nothing listed */ +"No names are for sale right now." = "No names are for sale right now."; + +/* Username marketplace: browse partial scan found nothing listed */ +"No names for sale found yet — scan more of the network below." = "No names for sale found yet — scan more of the network below."; + +/* Username marketplace: browse scan in progress */ +"Scanning names…" = "Scanning names…"; + +/* Username marketplace: continue the browse scan */ +"Scan more names" = "Scan more names"; + /* Username marketplace: contest tallies card title */ "Network vote so far" = "Network vote so far"; From 15efdffef85348dc0841a19dff7a93d2b305dd81 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 20:51:16 +0700 Subject: [PATCH 2/7] feat(dashpay): browse via the document-history contract's listing trail MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The alphabetical namespace scan was the wrong primitive: the document-history system contract (platform #4348) records a priceUpdate event for EVERY listing, indexed by [dataContractId, $createdAt]. Browse now walks that trail newest-first — every listed name necessarily has an event, so exhausting the trail yields the complete current listing set at a cost proportional to listing activity, not namespace size. Each event's domain document resolves to its LIVE marketplace state before it can appear (events say nothing about later re-prices, delists, or purchases; the recorded event price is deliberately never displayed), deduped so a many-times-relisted name costs one check. Coverage line now counts listings checked; sort unchanged (client-side high/low toggle — $price itself is still not indexable, so ordering remains local). Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceService.swift | 77 +++++++++++++++++-- .../UsernameMarketplaceScreen.swift | 71 ++++++++++------- DashWallet/en.lproj/Localizable.strings | 16 ++-- 3 files changed, 120 insertions(+), 44 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 2756d820ca..ca6e4d9142 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -97,14 +97,75 @@ struct UsernameMarketplaceService { return try await wallet.searchDpnsMarketplace(prefix: prefix, limit: limit) } - /// One alphabetical page of ALL names (the SDK's empty-prefix browse), - /// each with live sale state. `startAfter` is the cursor: the previous - /// page's last documentId. Powers the Browse tab's scan — there is no - /// server-side price filter or ordering to lean on ($price is not - /// indexable), so callers filter and sort what the scan returns. - func browsePage(startAfter: Data?, limit: UInt32 = 100) async throws -> [DpnsMarketplaceName] { - guard let wallet = SwiftDashSDKHost.shared.wallet else { return [] } - return try await wallet.searchDpnsMarketplace(prefix: "", limit: limit, startAfter: startAfter) + /// The document-history system contract (platform #4348, + /// `document_history_contract::ID_BYTES`). Every `setDocumentPrice` + /// also writes a `priceUpdate` row here, indexed by + /// `[dataContractId, $createdAt]` — the queryable listing trail the + /// DPNS contract itself lacks ($price is not indexable). Browse + /// walks it newest-first, so its cost scales with LISTING EVENTS, + /// not with the size of the namespace. + private static let documentHistoryContractId = "6voHRaoiPcfmMhbqCA9dixH98xcgPQ9UEcuaXjpVu3LD" + + /// One DPNS `priceUpdate` history row: which domain document was + /// (re)listed and when. The recorded price is deliberately NOT + /// carried — the live document is the only honest price source + /// (later re-prices, delists, and purchases all invalidate it). + struct ListingEvent { + let dpnsDocumentIdBase58: String + let createdAtMs: UInt64 + } + + /// One page of DPNS listing events, newest first. `beforeMs` is the + /// pagination cursor: pass the previous page's last `createdAtMs`. + func listingEventsPage(beforeMs: UInt64?, limit: UInt32 = 100) async throws -> [ListingEvent] { + guard let sdk = SwiftDashSDKHost.shared.sdk else { return [] } + var conditions = "[[\"dataContractId\",\"==\",\"\(DPNSVotePoll.contractId)\"]" + if let beforeMs { + conditions += ",[\"$createdAt\",\"<\",\(beforeMs)]" + } + conditions += "]" + let result = try await sdk.documentList( + dataContractId: Self.documentHistoryContractId, + documentType: "priceUpdate", + whereClause: conditions, + orderByClause: "[[\"$createdAt\",\"desc\"]]", + limit: limit) + let docs: [[String: Any]] + if let array = result["documents"] as? [[String: Any]] { + docs = array + } else if let array = result["items"] as? [[String: Any]] { + docs = array + } else { + docs = result.values.compactMap { $0 as? [String: Any] } + } + return docs.compactMap { doc in + guard let documentId = doc["documentId"] as? String, + let createdAt = (doc["$createdAt"] as? NSNumber)?.uint64Value else { return nil } + return ListingEvent(dpnsDocumentIdBase58: documentId, createdAtMs: createdAt) + } + } + + /// Live marketplace state of the domain document behind a listing + /// event — nil when the document no longer exists. The caller checks + /// `isForSale`; an old event for a since-delisted or sold name + /// resolves to a live row without a price. + func liveName(forDomainDocumentId documentIdBase58: String) async throws -> DpnsMarketplaceName? { + guard let sdk = SwiftDashSDKHost.shared.sdk, + let wallet = SwiftDashSDKHost.shared.wallet else { return nil } + let doc: [String: Any] + do { + doc = try await sdk.documentGet( + dataContractId: DPNSVotePoll.contractId, + documentType: DPNSVotePoll.documentTypeName, + documentId: documentIdBase58) + } catch { + // Gone documents are an expected outcome for old events. + return nil + } + guard let label = (doc["label"] as? String) ?? (doc["normalizedLabel"] as? String) else { + return nil + } + return try await wallet.dpnsMarketplaceNameState(name: label) } /// The main identity's tracked names from the wallet's local rows — diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index 7bb979df64..cf31c94044 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -82,27 +82,34 @@ final class UsernameMarketplaceViewModel: ObservableObject { // MARK: Browse (for-sale) state // - // `$price` is not an indexable property on Dash Platform, so there is - // no server-side "everything for sale, ordered by price" query at any - // layer. Browse is an honest client-side pass instead: page through - // ALL names alphabetically (empty-prefix search with a documentId - // cursor), keep the listed ones, and sort locally. The coverage label - // says how much of the network the sort currently reflects. - - /// For-sale names accumulated by the alphabetical scan. + // `$price` is not indexable on Dash Platform, so the DPNS contract + // has no server-side "everything for sale, ordered by price" query. + // What DOES exist is the document-history system contract: every + // listing writes a `priceUpdate` event queryable newest-first by + // [dataContractId, $createdAt]. Browse walks that trail — every + // listed name necessarily has such an event, so exhausting the trail + // yields the COMPLETE current listing set at a cost proportional to + // listing activity, not namespace size — then verifies each + // candidate's LIVE document (events say nothing about later + // re-prices, delists, or purchases) and sorts locally. + + /// Live for-sale names, verified against the current documents. @Published var browseForSale: [DpnsMarketplaceName] = [] - /// Total names scanned so far (listed or not) — the coverage label. + /// Listing events checked so far — the coverage label. @Published var browseScannedCount = 0 /// True while a scan pass is fetching pages. @Published var isBrowseScanning = false - /// True once the alphabetical scan has walked every name. + /// True once the whole listing-event trail was walked. @Published var browseExhausted = false @Published var browseSort: BrowseSort = .priceHighFirst - /// Cursor: last page's final documentId; nil = scan from the start. - private var browseCursor: Data? - /// Pages per scan pass — bounds one tap's network cost (100 names each). - private static let browsePagesPerPass = 5 + /// Pagination cursor: the oldest event's $createdAt seen so far. + private var browseCursorMs: UInt64? + /// Domain documents already resolved this scan — a re-listed name has + /// many events; one live check answers them all. + private var browseSeenDocumentIds: Set = [] + /// Event pages per scan pass (100 events each) — bounds one tap's cost. + private static let browsePagesPerPass = 3 var sortedBrowseForSale: [DpnsMarketplaceName] { browseForSale.sorted { @@ -112,14 +119,15 @@ final class UsernameMarketplaceViewModel: ObservableObject { } } - /// Scan another batch of pages. `reset` restarts from the top - /// (pull-to-refresh) so re-listed/delisted names re-read fresh. + /// Walk another batch of listing events. `reset` restarts from the + /// newest (pull-to-refresh) so prices and delists re-read fresh. func scanBrowsePages(reset: Bool = false) { guard !isBrowseScanning else { return } if reset { - browseCursor = nil + browseCursorMs = nil browseForSale = [] browseScannedCount = 0 + browseSeenDocumentIds = [] browseExhausted = false } guard !browseExhausted else { return } @@ -130,11 +138,18 @@ final class UsernameMarketplaceViewModel: ObservableObject { let pageSize: UInt32 = 100 for _ in 0.. Date: Mon, 10 Aug 2026 21:04:33 +0700 Subject: [PATCH 3/7] fix(dashpay): documentList orderBy tuples take an ascending BOOL, not "desc" MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The listing-trail query failed at runtime: "Invalid order by JSON: invalid type: string \"desc\", expected a boolean". The FFI's order-by tuples are [field, ascending-bool] — [["$createdAt",false]] for newest first. Co-Authored-By: Claude Fable 5 --- .../SwiftDashSDK/UsernameMarketplaceService.swift | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index ca6e4d9142..44c829ca37 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -128,7 +128,9 @@ struct UsernameMarketplaceService { dataContractId: Self.documentHistoryContractId, documentType: "priceUpdate", whereClause: conditions, - orderByClause: "[[\"$createdAt\",\"desc\"]]", + // Order-by tuples here are [field, ascending-bool] — the FFI + // rejects "asc"/"desc" strings. false = newest first. + orderByClause: "[[\"$createdAt\",false]]", limit: limit) let docs: [[String: Any]] if let array = result["documents"] as? [[String: Any]] { From 27a0e806dc39b39142c5c678be65690dc433e9dd Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 21:40:28 +0700 Subject: [PATCH 4/7] =?UTF-8?q?feat(dashpay):=20Browse=20is=20a=20recent-a?= =?UTF-8?q?ctivity=20feed=20=E2=80=94=20price=20changes=20and=20purchases?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Price sorting is not buildable server-side ($price is not indexable anywhere), so stop approximating it. What the document-history trail DOES index is recency — so Browse now shows exactly that, newest first, in two feeds: - Price changes: priceUpdate events ("Listed for 0.8 DASH · Aug 5"). - Purchases: purchase events with the price paid ("Sold for 0.002 DASH · Aug 3"); buyer/seller ride along for the detail sheet. Event price and time render as historical facts; the trailing badge is the name's LIVE state (current For-sale price, or "Not for sale now"), resolved per name with a per-refresh cache, so a stale listing can't read as an offer. Cursor pagination ($createdAt) with Show more; pull-to-refresh restarts both feeds. Also fixes identifier decoding for this query path: custom identifier properties (documentId, sellerId) arrive base64 while system fields are base58 — accepted strictly as 32-byte identifiers either way. Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceService.swift | 79 ++++- .../UsernameMarketplaceScreen.swift | 308 +++++++++++------- DashWallet/en.lproj/Localizable.strings | 39 +-- 3 files changed, 264 insertions(+), 162 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 44c829ca37..40f66e6ca9 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -106,18 +106,32 @@ struct UsernameMarketplaceService { /// not with the size of the namespace. private static let documentHistoryContractId = "6voHRaoiPcfmMhbqCA9dixH98xcgPQ9UEcuaXjpVu3LD" - /// One DPNS `priceUpdate` history row: which domain document was - /// (re)listed and when. The recorded price is deliberately NOT - /// carried — the live document is the only honest price source - /// (later re-prices, delists, and purchases all invalidate it). - struct ListingEvent { + /// One DPNS trade event from the history trail — a `priceUpdate` + /// (listing / re-price) or a `purchase`. The event's own price and + /// time are historical FACTS and safe to show as such; only claims + /// about the PRESENT ("for sale now") require the live document. + struct MarketplaceEvent { let dpnsDocumentIdBase58: String + let priceCredits: UInt64 let createdAtMs: UInt64 + /// Purchase events only: buyer (`$ownerId`) and seller, base58. + let buyerIdBase58: String? + let sellerIdBase58: String? } - /// One page of DPNS listing events, newest first. `beforeMs` is the - /// pagination cursor: pass the previous page's last `createdAtMs`. - func listingEventsPage(beforeMs: UInt64?, limit: UInt32 = 100) async throws -> [ListingEvent] { + /// Newest-first page of DPNS listing / re-price events. `beforeMs` + /// is the pagination cursor (previous page's last `createdAtMs`). + func recentPriceChanges(beforeMs: UInt64?, limit: UInt32 = 25) async throws -> [MarketplaceEvent] { + try await eventsPage(documentType: "priceUpdate", beforeMs: beforeMs, limit: limit) + } + + /// Newest-first page of DPNS purchase events, with price paid and + /// both counterparties. + func recentPurchases(beforeMs: UInt64?, limit: UInt32 = 25) async throws -> [MarketplaceEvent] { + try await eventsPage(documentType: "purchase", beforeMs: beforeMs, limit: limit) + } + + private func eventsPage(documentType: String, beforeMs: UInt64?, limit: UInt32) async throws -> [MarketplaceEvent] { guard let sdk = SwiftDashSDKHost.shared.sdk else { return [] } var conditions = "[[\"dataContractId\",\"==\",\"\(DPNSVotePoll.contractId)\"]" if let beforeMs { @@ -126,7 +140,7 @@ struct UsernameMarketplaceService { conditions += "]" let result = try await sdk.documentList( dataContractId: Self.documentHistoryContractId, - documentType: "priceUpdate", + documentType: documentType, whereClause: conditions, // Order-by tuples here are [field, ascending-bool] — the FFI // rejects "asc"/"desc" strings. false = newest first. @@ -141,17 +155,46 @@ struct UsernameMarketplaceService { docs = result.values.compactMap { $0 as? [String: Any] } } return docs.compactMap { doc in - guard let documentId = doc["documentId"] as? String, + guard let raw = doc["documentId"] as? String, + let documentId = Self.identifier32(raw), + let price = (doc["price"] as? NSNumber)?.uint64Value, let createdAt = (doc["$createdAt"] as? NSNumber)?.uint64Value else { return nil } - return ListingEvent(dpnsDocumentIdBase58: documentId, createdAtMs: createdAt) + let buyer = (doc["$ownerId"] as? String).flatMap(Self.identifier32) + let seller = (doc["sellerId"] as? String).flatMap(Self.identifier32) + return MarketplaceEvent( + dpnsDocumentIdBase58: documentId.toBase58String(), + priceCredits: price, + createdAtMs: createdAt, + buyerIdBase58: documentType == "purchase" ? buyer?.toBase58String() : nil, + sellerIdBase58: documentType == "purchase" ? seller?.toBase58String() : nil) + } + } + + /// Identifier-typed CUSTOM properties serialize as base64 in this + /// query path's JSON, while SYSTEM fields ($id, $ownerId) are base58. + /// Accept either, but only an exact 32-byte identifier — anything + /// else is nil, never a guess. + private static func identifier32(_ string: String) -> Data? { + if let data = Data(base64Encoded: string), data.count == 32 { + return data + } + if let data = Data.identifier(fromBase58: string), data.count == 32 { + return data } + return nil + } + + /// The name behind an event's domain document: its label plus its + /// live marketplace state. nil when the document is gone entirely; + /// `live` nil when the name currently resolves to no queryable + /// state. Only `live` may claim anything about the PRESENT — the + /// event's own price/time are already history. + struct EventName { + let label: String + let live: DpnsMarketplaceName? } - /// Live marketplace state of the domain document behind a listing - /// event — nil when the document no longer exists. The caller checks - /// `isForSale`; an old event for a since-delisted or sold name - /// resolves to a live row without a price. - func liveName(forDomainDocumentId documentIdBase58: String) async throws -> DpnsMarketplaceName? { + func eventName(forDomainDocumentId documentIdBase58: String) async throws -> EventName? { guard let sdk = SwiftDashSDKHost.shared.sdk, let wallet = SwiftDashSDKHost.shared.wallet else { return nil } let doc: [String: Any] @@ -167,7 +210,9 @@ struct UsernameMarketplaceService { guard let label = (doc["label"] as? String) ?? (doc["normalizedLabel"] as? String) else { return nil } - return try await wallet.dpnsMarketplaceNameState(name: label) + return EventName( + label: label, + live: try await wallet.dpnsMarketplaceNameState(name: label)) } /// The main identity's tracked names from the wallet's local rows — diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index cf31c94044..412e2275a6 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -45,9 +45,25 @@ final class UsernameMarketplaceViewModel: ObservableObject { } } - enum BrowseSort { - case priceHighFirst - case priceLowFirst + enum BrowseFeed: Int, CaseIterable { + case priceChanges + case purchases + + var title: String { + switch self { + case .priceChanges: return NSLocalizedString("Price changes", comment: "Username marketplace: browse feed of recent listings and re-prices") + case .purchases: return NSLocalizedString("Purchases", comment: "Username marketplace: browse feed of recent sales") + } + } + } + + /// One rendered browse-feed row: the historical event plus the + /// name's label and (best-effort) live state. + struct BrowseEventRow: Identifiable { + let id: String + let label: String + let event: UsernameMarketplaceService.MarketplaceEvent + let live: DpnsMarketplaceName? } @Published var segment: Segment = .find @@ -80,83 +96,92 @@ final class UsernameMarketplaceViewModel: ObservableObject { /// claim "Available" for a name already being contested. @Published var queryContest: UsernameMarketplaceService.ContestPrecheck? - // MARK: Browse (for-sale) state + // MARK: Browse (recent activity) state // - // `$price` is not indexable on Dash Platform, so the DPNS contract - // has no server-side "everything for sale, ordered by price" query. - // What DOES exist is the document-history system contract: every - // listing writes a `priceUpdate` event queryable newest-first by - // [dataContractId, $createdAt]. Browse walks that trail — every - // listed name necessarily has such an event, so exhausting the trail - // yields the COMPLETE current listing set at a cost proportional to - // listing activity, not namespace size — then verifies each - // candidate's LIVE document (events say nothing about later - // re-prices, delists, or purchases) and sorts locally. - - /// Live for-sale names, verified against the current documents. - @Published var browseForSale: [DpnsMarketplaceName] = [] - /// Listing events checked so far — the coverage label. - @Published var browseScannedCount = 0 - /// True while a scan pass is fetching pages. - @Published var isBrowseScanning = false - /// True once the whole listing-event trail was walked. - @Published var browseExhausted = false - @Published var browseSort: BrowseSort = .priceHighFirst - - /// Pagination cursor: the oldest event's $createdAt seen so far. - private var browseCursorMs: UInt64? - /// Domain documents already resolved this scan — a re-listed name has - /// many events; one live check answers them all. - private var browseSeenDocumentIds: Set = [] - /// Event pages per scan pass (100 events each) — bounds one tap's cost. - private static let browsePagesPerPass = 3 - - var sortedBrowseForSale: [DpnsMarketplaceName] { - browseForSale.sorted { - let l = $0.priceCredits ?? 0 - let r = $1.priceCredits ?? 0 - return browseSort == .priceHighFirst ? l > r : l < r - } - } - - /// Walk another batch of listing events. `reset` restarts from the - /// newest (pull-to-refresh) so prices and delists re-read fresh. - func scanBrowsePages(reset: Bool = false) { - guard !isBrowseScanning else { return } + // `$price` is not indexable on Dash Platform, so no query at any + // layer can order names by price. What the document-history system + // contract DOES index is RECENCY ([dataContractId, $createdAt]) — + // so Browse is an honest activity feed: recent price changes + // (listings / re-prices) and recent purchases, newest first. Each + // event's price and time are historical facts shown as such; each + // row also resolves the name's LIVE state for what's true now. + + @Published var browseFeed: BrowseFeed = .priceChanges + @Published var browsePriceChanges: [BrowseEventRow] = [] + @Published var browsePurchases: [BrowseEventRow] = [] + @Published var isBrowseLoading = false + @Published var browsePriceChangesExhausted = false + @Published var browsePurchasesExhausted = false + + /// Per-feed pagination cursors: oldest $createdAt fetched so far. + private var priceChangesCursorMs: UInt64? + private var purchasesCursorMs: UInt64? + /// documentId → resolved name, shared across both feeds — a name + /// with many events costs one resolution per refresh. + private var browseNameCache: [String: UsernameMarketplaceService.EventName] = [:] + /// Events per fetch — each new name costs up to 2 extra round trips. + private static let browseEventsPerPage: UInt32 = 25 + + var browseRows: [BrowseEventRow] { + browseFeed == .priceChanges ? browsePriceChanges : browsePurchases + } + + var browseFeedExhausted: Bool { + browseFeed == .priceChanges ? browsePriceChangesExhausted : browsePurchasesExhausted + } + + /// Load the next page of the CURRENT feed. `reset` restarts both + /// feeds from the newest event (pull-to-refresh) so live states and + /// prices re-read fresh. + func loadBrowse(reset: Bool = false) { + guard !isBrowseLoading else { return } if reset { - browseCursorMs = nil - browseForSale = [] - browseScannedCount = 0 - browseSeenDocumentIds = [] - browseExhausted = false - } - guard !browseExhausted else { return } - isBrowseScanning = true + browsePriceChanges = [] + browsePurchases = [] + priceChangesCursorMs = nil + purchasesCursorMs = nil + browsePriceChangesExhausted = false + browsePurchasesExhausted = false + browseNameCache = [:] + } + let feed = browseFeed + guard !browseFeedExhausted else { return } + isBrowseLoading = true Task { [weak self] in guard let self else { return } - defer { self.isBrowseScanning = false } - let pageSize: UInt32 = 100 - for _ in 0.. some View { + let eventDash = (row.event.priceCredits / 1000).dashAmount.formattedDashAmountWithoutCurrencySymbol + let eventDate = DWDateFormatter.sharedInstance.shortStringFromDate( + Date(timeIntervalSince1970: Double(row.event.createdAtMs) / 1000)) + let subtitle = viewModel.browseFeed == .priceChanges + ? String.localizedStringWithFormat( + NSLocalizedString("Listed for %1$@ DASH · %2$@", comment: "Username marketplace: price-change feed row — event price, then date"), + eventDash, eventDate) + : String.localizedStringWithFormat( + NSLocalizedString("Sold for %1$@ DASH · %2$@", comment: "Username marketplace: purchases feed row — price paid, then date"), + eventDash, eventDate) + return Button { + selectedLabel = SelectedMarketplaceLabel(label: row.label) + } label: { + HStack(spacing: 10) { + ContactAvatarView( + title: row.label, + avatarURL: nil, + identitySeed: row.live?.ownerId ?? Data()) + VStack(alignment: .leading, spacing: 2) { + Text(row.label) + .font(.system(size: 16, weight: .semibold)) + .foregroundColor(.dash.primaryText) + .lineLimit(1) + Text(subtitle) + .font(.system(size: 11)) + .foregroundColor(.dash.tertiaryText) + .lineLimit(1) + } + Spacer() + if let live = row.live, live.isForSale, let priceDuffs = live.priceDuffs { + VStack(alignment: .trailing, spacing: 1) { + Text(NSLocalizedString("For sale", comment: "Username marketplace: listed badge")) + .font(.system(size: 10, weight: .semibold)) + .foregroundColor(.dashGolden) + Text("\(priceDuffs.dashAmount.formattedDashAmountWithoutCurrencySymbol) DASH") + .font(.system(size: 13, weight: .semibold)) + .foregroundColor(.dash.primaryText) + } + } else { + Text(NSLocalizedString("Not for sale now", comment: "Username marketplace: browse row whose name is no longer listed")) + .font(.system(size: 10, weight: .medium)) + .foregroundColor(.dash.tertiaryText) + } + Image(systemName: "chevron.right") + .font(.system(size: 12, weight: .semibold)) + .foregroundColor(.dash.secondaryText) } + .padding(12) + .background( + RoundedRectangle(cornerRadius: 8, style: .continuous) + .fill(Color.dash.secondaryBackground)) + .contentShape(Rectangle()) } + .buttonStyle(.plain) } // MARK: My Names segment diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 75cce2850e..7948b6968f 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -806,35 +806,32 @@ /* Username marketplace: browse-for-sale segment */ "Browse" = "Browse"; -/* Username marketplace: browse coverage line while the scan is partial */ -"%1$d listings checked · %2$d for sale now" = "%1$d listings checked · %2$d for sale now"; +/* Username marketplace: browse feed of recent listings and re-prices */ +"Price changes" = "Price changes"; -/* Username marketplace: browse coverage line once the whole listing trail was walked */ -"All %1$d listings checked · %2$d for sale now" = "All %1$d listings checked · %2$d for sale now"; +/* Username marketplace: browse feed of recent sales */ +"Purchases" = "Purchases"; -/* Username marketplace: browse sort option */ -"Highest price first" = "Highest price first"; +/* Username marketplace: price-change feed row — event price, then date */ +"Listed for %1$@ DASH · %2$@" = "Listed for %1$@ DASH · %2$@"; -/* Username marketplace: browse sort option */ -"Lowest price first" = "Lowest price first"; +/* Username marketplace: purchases feed row — price paid, then date */ +"Sold for %1$@ DASH · %2$@" = "Sold for %1$@ DASH · %2$@"; -/* Username marketplace: current browse sort label */ -"Highest price" = "Highest price"; +/* Username marketplace: browse row whose name is no longer listed */ +"Not for sale now" = "Not for sale now"; -/* Username marketplace: current browse sort label */ -"Lowest price" = "Lowest price"; +/* Username marketplace: empty price-changes feed */ +"No price changes on the network yet." = "No price changes on the network yet."; -/* Username marketplace: browse walked every listing event, nothing currently listed */ -"No names are for sale right now." = "No names are for sale right now."; +/* Username marketplace: empty purchases feed */ +"No purchases on the network yet." = "No purchases on the network yet."; -/* Username marketplace: browse partial scan found nothing currently listed */ -"No live listings found yet — check more of the listing history below." = "No live listings found yet — check more of the listing history below."; +/* Username marketplace: browse feed loading */ +"Loading activity…" = "Loading activity…"; -/* Username marketplace: browse scan in progress */ -"Checking listings…" = "Checking listings…"; - -/* Username marketplace: continue the browse scan */ -"Check more listings" = "Check more listings"; +/* Username marketplace: load older browse activity */ +"Show more" = "Show more"; /* Username marketplace: contest tallies card title */ "Network vote so far" = "Network vote so far"; From 0d888e7e1784990f05b5a4ce494fa3aa21889073 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 21:47:55 +0700 Subject: [PATCH 5/7] perf(dashpay): browse page costs exactly 2 platform queries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 25-event page resolved names one at a time — documentGet + nameState per name, ~51 serialized round trips per page. The events already carry the domain documentId and DPNS's primary index supports an "in" clause, so all live states now come back in ONE batched documentList (the domain document itself carries the full live state a row claims: label, owner, current $price). Page cost: one events query + one batched $id lookup, verified against live testnet via evo-sdk. Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceService.swift | 65 ++++++++++++------- .../UsernameMarketplaceScreen.swift | 35 +++++----- 2 files changed, 60 insertions(+), 40 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 40f66e6ca9..9429065750 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -184,35 +184,52 @@ struct UsernameMarketplaceService { return nil } - /// The name behind an event's domain document: its label plus its - /// live marketplace state. nil when the document is gone entirely; - /// `live` nil when the name currently resolves to no queryable - /// state. Only `live` may claim anything about the PRESENT — the - /// event's own price/time are already history. - struct EventName { + /// Live DPNS state for a BATCH of domain document ids — one + /// `documentList` on the primary `$id` index (`in` clause) instead of + /// two round trips per name. The domain document itself carries the + /// entire live state a feed row claims about the present: label, + /// owner, and current `$price` (nil = not for sale). Ids absent from + /// the result no longer exist. + struct LiveDomainName { + let documentIdBase58: String let label: String - let live: DpnsMarketplaceName? + let ownerId: Data + let priceCredits: UInt64? + + var isForSale: Bool { priceCredits != nil } + var priceDuffs: UInt64? { priceCredits.map { $0 / 1_000 } } } - func eventName(forDomainDocumentId documentIdBase58: String) async throws -> EventName? { - guard let sdk = SwiftDashSDKHost.shared.sdk, - let wallet = SwiftDashSDKHost.shared.wallet else { return nil } - let doc: [String: Any] - do { - doc = try await sdk.documentGet( - dataContractId: DPNSVotePoll.contractId, - documentType: DPNSVotePoll.documentTypeName, - documentId: documentIdBase58) - } catch { - // Gone documents are an expected outcome for old events. - return nil + func liveDomainNames(forDocumentIds ids: [String]) async throws -> [String: LiveDomainName] { + guard let sdk = SwiftDashSDKHost.shared.sdk, !ids.isEmpty else { return [:] } + let idList = ids.map { "\"\($0)\"" }.joined(separator: ",") + let result = try await sdk.documentList( + dataContractId: DPNSVotePoll.contractId, + documentType: DPNSVotePoll.documentTypeName, + whereClause: "[[\"$id\",\"in\",[\(idList)]]]", + orderByClause: "[[\"$id\",true]]", + limit: UInt32(ids.count)) + let docs: [[String: Any]] + if let array = result["documents"] as? [[String: Any]] { + docs = array + } else if let array = result["items"] as? [[String: Any]] { + docs = array + } else { + docs = result.values.compactMap { $0 as? [String: Any] } } - guard let label = (doc["label"] as? String) ?? (doc["normalizedLabel"] as? String) else { - return nil + var out: [String: LiveDomainName] = [:] + for doc in docs { + guard let id = doc["$id"] as? String, + let ownerBase58 = doc["$ownerId"] as? String, + let ownerId = Data.identifier(fromBase58: ownerBase58), + let label = (doc["label"] as? String) ?? (doc["normalizedLabel"] as? String) else { continue } + out[id] = LiveDomainName( + documentIdBase58: id, + label: label, + ownerId: ownerId, + priceCredits: (doc["$price"] as? NSNumber)?.uint64Value) } - return EventName( - label: label, - live: try await wallet.dpnsMarketplaceNameState(name: label)) + return out } /// The main identity's tracked names from the wallet's local rows — diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index 412e2275a6..d1c49d561a 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -58,12 +58,12 @@ final class UsernameMarketplaceViewModel: ObservableObject { } /// One rendered browse-feed row: the historical event plus the - /// name's label and (best-effort) live state. + /// name's label and live state (from the batched domain read). struct BrowseEventRow: Identifiable { let id: String let label: String let event: UsernameMarketplaceService.MarketplaceEvent - let live: DpnsMarketplaceName? + let live: UsernameMarketplaceService.LiveDomainName? } @Published var segment: Segment = .find @@ -116,10 +116,10 @@ final class UsernameMarketplaceViewModel: ObservableObject { /// Per-feed pagination cursors: oldest $createdAt fetched so far. private var priceChangesCursorMs: UInt64? private var purchasesCursorMs: UInt64? - /// documentId → resolved name, shared across both feeds — a name - /// with many events costs one resolution per refresh. - private var browseNameCache: [String: UsernameMarketplaceService.EventName] = [:] - /// Events per fetch — each new name costs up to 2 extra round trips. + /// documentId → live domain state, shared across both feeds and + /// filled by ONE batched read per page — a page costs exactly two + /// platform queries (events + batched $id lookup) regardless of size. + private var browseNameCache: [String: UsernameMarketplaceService.LiveDomainName] = [:] private static let browseEventsPerPage: UInt32 = 25 var browseRows: [BrowseEventRow] { @@ -155,21 +155,24 @@ final class UsernameMarketplaceViewModel: ObservableObject { let events = feed == .priceChanges ? try await service.recentPriceChanges(beforeMs: cursor, limit: Self.browseEventsPerPage) : try await service.recentPurchases(beforeMs: cursor, limit: Self.browseEventsPerPage) + // One batched $id lookup covers every name this page + // mentions that we haven't resolved yet. + let unknownIds = Array(Set(events.map(\.dpnsDocumentIdBase58) + .filter { browseNameCache[$0] == nil })) + if !unknownIds.isEmpty { + for (id, live) in try await service.liveDomainNames(forDocumentIds: unknownIds) { + browseNameCache[id] = live + } + } var rows: [BrowseEventRow] = [] for event in events { - let name: UsernameMarketplaceService.EventName? - if let cached = browseNameCache[event.dpnsDocumentIdBase58] { - name = cached - } else { - name = try await service.eventName(forDomainDocumentId: event.dpnsDocumentIdBase58) - if let name { browseNameCache[event.dpnsDocumentIdBase58] = name } - } - guard let name else { continue } // document gone — nothing to show + // Absent from the batch = the document is gone. + guard let live = browseNameCache[event.dpnsDocumentIdBase58] else { continue } rows.append(BrowseEventRow( id: "\(event.dpnsDocumentIdBase58)-\(event.createdAtMs)", - label: name.label, + label: live.label, event: event, - live: name.live)) + live: live)) } if feed == .priceChanges { browsePriceChanges.append(contentsOf: rows) From 8dae11656b3294b938f7f289e449ddc6f3f89675 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 21:54:42 +0700 Subject: [PATCH 6/7] feat(dashpay): price-changes feed shows only names actually for sale MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The live batch read now FILTERS instead of badging: events whose name was since delisted or sold are dropped, and each for-sale name renders once (its newest event — whose price is by consensus the live price). A pass keeps paging (bounded, 4 pages) when filtering leaves a page empty. Purchases stay a history feed. Still exactly 2 platform queries per page — the batch read is what makes the for-sale filter possible at all, since the append-only trail can't testify about the present and $price isn't indexable. Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceScreen.swift | 81 ++++++++++++------- DashWallet/en.lproj/Localizable.strings | 4 +- 2 files changed, 52 insertions(+), 33 deletions(-) diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index d1c49d561a..d7a80f8bfa 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -151,37 +151,56 @@ final class UsernameMarketplaceViewModel: ObservableObject { guard let self else { return } defer { self.isBrowseLoading = false } do { - let cursor = feed == .priceChanges ? priceChangesCursorMs : purchasesCursorMs - let events = feed == .priceChanges - ? try await service.recentPriceChanges(beforeMs: cursor, limit: Self.browseEventsPerPage) - : try await service.recentPurchases(beforeMs: cursor, limit: Self.browseEventsPerPage) - // One batched $id lookup covers every name this page - // mentions that we haven't resolved yet. - let unknownIds = Array(Set(events.map(\.dpnsDocumentIdBase58) - .filter { browseNameCache[$0] == nil })) - if !unknownIds.isEmpty { - for (id, live) in try await service.liveDomainNames(forDocumentIds: unknownIds) { - browseNameCache[id] = live + // Price changes is a FOR-SALE feed: rows whose name was + // since delisted or sold are dropped, and each name + // renders once (its newest event — whose price, by + // consensus, IS the live price of a still-listed name). + // Dropped rows can leave a page thin, so keep paging + // within a bounded pass until something showed. + var pagesLeft = feed == .priceChanges ? 4 : 1 + while pagesLeft > 0 { + pagesLeft -= 1 + let cursor = feed == .priceChanges ? priceChangesCursorMs : purchasesCursorMs + let events = feed == .priceChanges + ? try await service.recentPriceChanges(beforeMs: cursor, limit: Self.browseEventsPerPage) + : try await service.recentPurchases(beforeMs: cursor, limit: Self.browseEventsPerPage) + // One batched $id lookup covers every name this page + // mentions that we haven't resolved yet. + let unknownIds = Array(Set(events.map(\.dpnsDocumentIdBase58) + .filter { browseNameCache[$0] == nil })) + if !unknownIds.isEmpty { + for (id, live) in try await service.liveDomainNames(forDocumentIds: unknownIds) { + browseNameCache[id] = live + } } - } - var rows: [BrowseEventRow] = [] - for event in events { - // Absent from the batch = the document is gone. - guard let live = browseNameCache[event.dpnsDocumentIdBase58] else { continue } - rows.append(BrowseEventRow( - id: "\(event.dpnsDocumentIdBase58)-\(event.createdAtMs)", - label: live.label, - event: event, - live: live)) - } - if feed == .priceChanges { - browsePriceChanges.append(contentsOf: rows) - priceChangesCursorMs = events.last?.createdAtMs - if events.count < Int(Self.browseEventsPerPage) { browsePriceChangesExhausted = true } - } else { - browsePurchases.append(contentsOf: rows) - purchasesCursorMs = events.last?.createdAtMs - if events.count < Int(Self.browseEventsPerPage) { browsePurchasesExhausted = true } + var rows: [BrowseEventRow] = [] + for event in events { + // Absent from the batch = the document is gone. + guard let live = browseNameCache[event.dpnsDocumentIdBase58] else { continue } + let row = BrowseEventRow( + id: "\(event.dpnsDocumentIdBase58)-\(event.createdAtMs)", + label: live.label, + event: event, + live: live) + if feed == .priceChanges { + guard live.isForSale, + !browsePriceChanges.contains(where: { $0.event.dpnsDocumentIdBase58 == event.dpnsDocumentIdBase58 }), + !rows.contains(where: { $0.event.dpnsDocumentIdBase58 == event.dpnsDocumentIdBase58 }) + else { continue } + } + rows.append(row) + } + let exhausted = events.count < Int(Self.browseEventsPerPage) + if feed == .priceChanges { + browsePriceChanges.append(contentsOf: rows) + priceChangesCursorMs = events.last?.createdAtMs + if exhausted { browsePriceChangesExhausted = true } + } else { + browsePurchases.append(contentsOf: rows) + purchasesCursorMs = events.last?.createdAtMs + if exhausted { browsePurchasesExhausted = true } + } + if exhausted || !rows.isEmpty { break } } } catch { errorMessage = UsernameMarketplaceService.userFacingMessage(for: error) @@ -542,7 +561,7 @@ struct UsernameMarketplaceScreen: View { } if viewModel.browseRows.isEmpty && !viewModel.isBrowseLoading { emptyHint(viewModel.browseFeed == .priceChanges - ? NSLocalizedString("No price changes on the network yet.", comment: "Username marketplace: empty price-changes feed") + ? NSLocalizedString("No names are for sale in the recent listing activity. Show more reaches further back.", comment: "Username marketplace: price-changes feed found no live listings yet") : NSLocalizedString("No purchases on the network yet.", comment: "Username marketplace: empty purchases feed")) } if viewModel.isBrowseLoading { diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 7948b6968f..f30555b745 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -821,8 +821,8 @@ /* Username marketplace: browse row whose name is no longer listed */ "Not for sale now" = "Not for sale now"; -/* Username marketplace: empty price-changes feed */ -"No price changes on the network yet." = "No price changes on the network yet."; +/* Username marketplace: price-changes feed found no live listings yet */ +"No names are for sale in the recent listing activity. Show more reaches further back." = "No names are for sale in the recent listing activity. Show more reaches further back."; /* Username marketplace: empty purchases feed */ "No purchases on the network yet." = "No purchases on the network yet."; From 1e0d64132f41d8c336298148711773f61770483f Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Mon, 10 Aug 2026 22:02:59 +0700 Subject: [PATCH 7/7] =?UTF-8?q?fix(dashpay):=20browse=20review=20feedback?= =?UTF-8?q?=20=E2=80=94=20cursor=20overlap,=20cancellable=20refresh,=20id?= =?UTF-8?q?=20validation,=20purchase=20counterparties?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Pagination pages with "<=" and dedupes on the history row's own $id: a strict "<" cursor dropped the rest of a timestamp group at a page boundary (several events can share one block's $createdAt). Exhaustion reads the RAW page size; a full page of only-seen rows (cursor unable to advance) stops rather than spins. - Pull-to-refresh awaits the restarted load (.refreshable spinner stays honest) and a reset cancels the in-flight task instead of bouncing off the busy guard; a generation counter keeps the cancelled task's cleanup from clearing the replacement's loading flag. - liveDomainNames validates $id and $ownerId as exact 32-byte identifiers and keys the result by the canonical base58 form. - Purchase rows show both counterparties ("seller → buyer" short ids); events missing either fall back to the price-and-date form. Co-Authored-By: Claude Fable 5 --- .../UsernameMarketplaceService.swift | 29 +++++-- .../UsernameMarketplaceScreen.swift | 78 +++++++++++++++---- DashWallet/en.lproj/Localizable.strings | 3 + 3 files changed, 88 insertions(+), 22 deletions(-) diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 9429065750..5c762c59ac 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -111,6 +111,9 @@ struct UsernameMarketplaceService { /// time are historical FACTS and safe to show as such; only claims /// about the PRESENT ("for sale now") require the live document. struct MarketplaceEvent { + /// The history row's own `$id` — the dedupe key that makes the + /// overlap-tolerant pagination cursor safe (see `eventsPage`). + let eventIdBase58: String let dpnsDocumentIdBase58: String let priceCredits: UInt64 let createdAtMs: UInt64 @@ -135,7 +138,12 @@ struct UsernameMarketplaceService { guard let sdk = SwiftDashSDKHost.shared.sdk else { return [] } var conditions = "[[\"dataContractId\",\"==\",\"\(DPNSVotePoll.contractId)\"]" if let beforeMs { - conditions += ",[\"$createdAt\",\"<\",\(beforeMs)]" + // "<=", not "<": several events can share one block's + // $createdAt, and a strict cursor at a page boundary would + // silently drop the rest of that timestamp group. The + // deliberate overlap re-fetches the boundary rows; callers + // dedupe on `eventIdBase58`. + conditions += ",[\"$createdAt\",\"<=\",\(beforeMs)]" } conditions += "]" let result = try await sdk.documentList( @@ -155,13 +163,16 @@ struct UsernameMarketplaceService { docs = result.values.compactMap { $0 as? [String: Any] } } return docs.compactMap { doc in - guard let raw = doc["documentId"] as? String, + guard let rawEventId = doc["$id"] as? String, + let eventId = Self.identifier32(rawEventId), + let raw = doc["documentId"] as? String, let documentId = Self.identifier32(raw), let price = (doc["price"] as? NSNumber)?.uint64Value, let createdAt = (doc["$createdAt"] as? NSNumber)?.uint64Value else { return nil } let buyer = (doc["$ownerId"] as? String).flatMap(Self.identifier32) let seller = (doc["sellerId"] as? String).flatMap(Self.identifier32) return MarketplaceEvent( + eventIdBase58: eventId.toBase58String(), dpnsDocumentIdBase58: documentId.toBase58String(), priceCredits: price, createdAtMs: createdAt, @@ -219,12 +230,16 @@ struct UsernameMarketplaceService { } var out: [String: LiveDomainName] = [:] for doc in docs { - guard let id = doc["$id"] as? String, - let ownerBase58 = doc["$ownerId"] as? String, - let ownerId = Data.identifier(fromBase58: ownerBase58), + guard let rawId = doc["$id"] as? String, + let id = Self.identifier32(rawId), + let rawOwnerId = doc["$ownerId"] as? String, + let ownerId = Self.identifier32(rawOwnerId), let label = (doc["label"] as? String) ?? (doc["normalizedLabel"] as? String) else { continue } - out[id] = LiveDomainName( - documentIdBase58: id, + // Canonical base58 key — must byte-match the event side's + // dpnsDocumentIdBase58, which is produced the same way. + let documentIdBase58 = id.toBase58String() + out[documentIdBase58] = LiveDomainName( + documentIdBase58: documentIdBase58, label: label, ownerId: ownerId, priceCredits: (doc["$price"] as? NSNumber)?.uint64Value) diff --git a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift index d7a80f8bfa..ed6c5d2b9d 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -114,12 +114,21 @@ final class UsernameMarketplaceViewModel: ObservableObject { @Published var browsePurchasesExhausted = false /// Per-feed pagination cursors: oldest $createdAt fetched so far. + /// The service pages with "<=" (a timestamp can span many events), + /// so pages overlap at the boundary; `browseSeenEventIds` dedupes. private var priceChangesCursorMs: UInt64? private var purchasesCursorMs: UInt64? + private var browseSeenEventIds: Set = [] /// documentId → live domain state, shared across both feeds and /// filled by ONE batched read per page — a page costs exactly two /// platform queries (events + batched $id lookup) regardless of size. private var browseNameCache: [String: UsernameMarketplaceService.LiveDomainName] = [:] + /// In-flight load — cancelled by a reset so pull-to-refresh can + /// always restart, never silently bounce off the busy guard. The + /// generation counter keeps a cancelled task's cleanup from clearing + /// the loading flag of the load that replaced it. + private var browseTask: Task? + private var browseLoadGeneration = 0 private static let browseEventsPerPage: UInt32 = 25 var browseRows: [BrowseEventRow] { @@ -130,26 +139,35 @@ final class UsernameMarketplaceViewModel: ObservableObject { browseFeed == .priceChanges ? browsePriceChangesExhausted : browsePurchasesExhausted } - /// Load the next page of the CURRENT feed. `reset` restarts both - /// feeds from the newest event (pull-to-refresh) so live states and - /// prices re-read fresh. + /// Load the next page of the CURRENT feed. `reset` cancels any + /// in-flight load and restarts both feeds from the newest event + /// (pull-to-refresh) so live states and prices re-read fresh. func loadBrowse(reset: Bool = false) { - guard !isBrowseLoading else { return } if reset { + browseTask?.cancel() browsePriceChanges = [] browsePurchases = [] priceChangesCursorMs = nil purchasesCursorMs = nil browsePriceChangesExhausted = false browsePurchasesExhausted = false + browseSeenEventIds = [] browseNameCache = [:] + } else { + guard !isBrowseLoading else { return } } let feed = browseFeed guard !browseFeedExhausted else { return } isBrowseLoading = true - Task { [weak self] in + browseLoadGeneration += 1 + let generation = browseLoadGeneration + browseTask = Task { [weak self] in guard let self else { return } - defer { self.isBrowseLoading = false } + defer { + if self.browseLoadGeneration == generation { + self.isBrowseLoading = false + } + } do { // Price changes is a FOR-SALE feed: rows whose name was // since delisted or sold are dropped, and each name @@ -161,9 +179,14 @@ final class UsernameMarketplaceViewModel: ObservableObject { while pagesLeft > 0 { pagesLeft -= 1 let cursor = feed == .priceChanges ? priceChangesCursorMs : purchasesCursorMs - let events = feed == .priceChanges + let rawEvents = feed == .priceChanges ? try await service.recentPriceChanges(beforeMs: cursor, limit: Self.browseEventsPerPage) : try await service.recentPurchases(beforeMs: cursor, limit: Self.browseEventsPerPage) + guard !Task.isCancelled else { return } + // Boundary rows reappear by design (the "<=" cursor); + // the event-id set drops what was already consumed. + let events = rawEvents.filter { !browseSeenEventIds.contains($0.eventIdBase58) } + events.forEach { browseSeenEventIds.insert($0.eventIdBase58) } // One batched $id lookup covers every name this page // mentions that we haven't resolved yet. let unknownIds = Array(Set(events.map(\.dpnsDocumentIdBase58) @@ -173,12 +196,13 @@ final class UsernameMarketplaceViewModel: ObservableObject { browseNameCache[id] = live } } + guard !Task.isCancelled else { return } var rows: [BrowseEventRow] = [] for event in events { // Absent from the batch = the document is gone. guard let live = browseNameCache[event.dpnsDocumentIdBase58] else { continue } let row = BrowseEventRow( - id: "\(event.dpnsDocumentIdBase58)-\(event.createdAtMs)", + id: event.eventIdBase58, label: live.label, event: event, live: live) @@ -190,24 +214,37 @@ final class UsernameMarketplaceViewModel: ObservableObject { } rows.append(row) } - let exhausted = events.count < Int(Self.browseEventsPerPage) + // Exhaustion reads the RAW page: a short page means the + // trail ended. A full page of only-seen rows means the + // cursor cannot advance (>page-size events sharing one + // timestamp) — stop rather than spin. + let exhausted = rawEvents.count < Int(Self.browseEventsPerPage) + || (events.isEmpty && rawEvents.count == Int(Self.browseEventsPerPage)) if feed == .priceChanges { browsePriceChanges.append(contentsOf: rows) - priceChangesCursorMs = events.last?.createdAtMs + priceChangesCursorMs = rawEvents.last?.createdAtMs ?? cursor if exhausted { browsePriceChangesExhausted = true } } else { browsePurchases.append(contentsOf: rows) - purchasesCursorMs = events.last?.createdAtMs + purchasesCursorMs = rawEvents.last?.createdAtMs ?? cursor if exhausted { browsePurchasesExhausted = true } } if exhausted || !rows.isEmpty { break } } } catch { + guard !Task.isCancelled else { return } errorMessage = UsernameMarketplaceService.userFacingMessage(for: error) } } } + /// Awaitable refresh for `.refreshable` — the spinner stays until + /// the restarted load actually finishes. + func refreshBrowse() async { + loadBrowse(reset: true) + await browseTask?.value + } + let service = UsernameMarketplaceService() private var searchTask: Task? @@ -591,7 +628,7 @@ struct UsernameMarketplaceScreen: View { .padding(.bottom, 24) } .refreshable { - viewModel.loadBrowse(reset: true) + await viewModel.refreshBrowse() } } .onAppear { @@ -605,13 +642,20 @@ struct UsernameMarketplaceScreen: View { let eventDash = (row.event.priceCredits / 1000).dashAmount.formattedDashAmountWithoutCurrencySymbol let eventDate = DWDateFormatter.sharedInstance.shortStringFromDate( Date(timeIntervalSince1970: Double(row.event.createdAtMs) / 1000)) - let subtitle = viewModel.browseFeed == .priceChanges - ? String.localizedStringWithFormat( + let subtitle: String + if viewModel.browseFeed == .priceChanges { + subtitle = String.localizedStringWithFormat( NSLocalizedString("Listed for %1$@ DASH · %2$@", comment: "Username marketplace: price-change feed row — event price, then date"), eventDash, eventDate) - : String.localizedStringWithFormat( + } else if let seller = row.event.sellerIdBase58, let buyer = row.event.buyerIdBase58 { + subtitle = String.localizedStringWithFormat( + NSLocalizedString("Sold for %1$@ DASH · %2$@ · %3$@ → %4$@", comment: "Username marketplace: purchases feed row — price paid, date, then seller → buyer short ids"), + eventDash, eventDate, shortBase58(seller), shortBase58(buyer)) + } else { + subtitle = String.localizedStringWithFormat( NSLocalizedString("Sold for %1$@ DASH · %2$@", comment: "Username marketplace: purchases feed row — price paid, then date"), eventDash, eventDate) + } return Button { selectedLabel = SelectedMarketplaceLabel(label: row.label) } label: { @@ -925,6 +969,10 @@ struct UsernameMarketplaceScreen: View { .buttonStyle(.plain) } + private func shortBase58(_ base58: String) -> String { + String(base58.prefix(8)) + "…" + String(base58.suffix(4)) + } + private func sectionHeader(_ text: String) -> some View { HStack { Text(text) diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index f30555b745..cb38ac9b81 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -818,6 +818,9 @@ /* Username marketplace: purchases feed row — price paid, then date */ "Sold for %1$@ DASH · %2$@" = "Sold for %1$@ DASH · %2$@"; +/* Username marketplace: purchases feed row — price paid, date, then seller → buyer short ids */ +"Sold for %1$@ DASH · %2$@ · %3$@ → %4$@" = "Sold for %1$@ DASH · %2$@ · %3$@ → %4$@"; + /* Username marketplace: browse row whose name is no longer listed */ "Not for sale now" = "Not for sale now";