diff --git a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift index 0fb8e65d4e..5c762c59ac 100644 --- a/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift +++ b/DashWallet/Sources/Infrastructure/SwiftDashSDK/UsernameMarketplaceService.swift @@ -97,6 +97,156 @@ struct UsernameMarketplaceService { return try await wallet.searchDpnsMarketplace(prefix: prefix, limit: limit) } + /// 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 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 { + /// 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 + /// Purchase events only: buyer (`$ownerId`) and seller, base58. + let buyerIdBase58: String? + let sellerIdBase58: String? + } + + /// 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 { + // "<=", 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( + dataContractId: Self.documentHistoryContractId, + documentType: documentType, + whereClause: conditions, + // 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]] { + 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 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, + 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 + } + + /// 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 ownerId: Data + let priceCredits: UInt64? + + var isForSale: Bool { priceCredits != nil } + var priceDuffs: UInt64? { priceCredits.map { $0 / 1_000 } } + } + + 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] } + } + var out: [String: LiveDomainName] = [:] + for doc in docs { + 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 } + // 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) + } + return out + } + /// 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..ed6c5d2b9d 100644 --- a/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift +++ b/DashWallet/Sources/UI/Explore Dash/UsernameMarketplaceScreen.swift @@ -34,15 +34,38 @@ 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 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 live state (from the batched domain read). + struct BrowseEventRow: Identifiable { + let id: String + let label: String + let event: UsernameMarketplaceService.MarketplaceEvent + let live: UsernameMarketplaceService.LiveDomainName? + } + @Published var segment: Segment = .find @Published var query = "" @Published var searchResults: [DpnsMarketplaceName] = [] @@ -73,6 +96,155 @@ final class UsernameMarketplaceViewModel: ObservableObject { /// claim "Available" for a name already being contested. @Published var queryContest: UsernameMarketplaceService.ContestPrecheck? + // MARK: Browse (recent activity) state + // + // `$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. + /// 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] { + browseFeed == .priceChanges ? browsePriceChanges : browsePurchases + } + + var browseFeedExhausted: Bool { + browseFeed == .priceChanges ? browsePriceChangesExhausted : browsePurchasesExhausted + } + + /// 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) { + 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 + browseLoadGeneration += 1 + let generation = browseLoadGeneration + browseTask = Task { [weak self] in + guard let self else { return } + 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 + // 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 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) + .filter { browseNameCache[$0] == nil })) + if !unknownIds.isEmpty { + for (id, live) in try await service.liveDomainNames(forDocumentIds: unknownIds) { + 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.eventIdBase58, + 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) + } + // 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 = rawEvents.last?.createdAtMs ?? cursor + if exhausted { browsePriceChangesExhausted = true } + } else { + browsePurchases.append(contentsOf: rows) + 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? @@ -293,6 +465,8 @@ struct UsernameMarketplaceScreen: View { findSection case .mine: mySection + case .browse: + browseSection } Spacer(minLength: 0) @@ -394,6 +568,140 @@ struct UsernameMarketplaceScreen: View { } } + // MARK: Browse segment + + /// Recent marketplace activity, newest first: price changes + /// (listings / re-prices) and purchases, straight off the + /// document-history trail's [dataContractId, $createdAt] index. + /// Event price and time are historical facts; the trailing badge is + /// the name's LIVE state, so a stale listing can't read as an offer. + private var browseSection: some View { + VStack(alignment: .leading, spacing: 0) { + Picker("", selection: $viewModel.browseFeed) { + ForEach(UsernameMarketplaceViewModel.BrowseFeed.allCases, id: \.self) { feed in + Text(feed.title).tag(feed) + } + } + .pickerStyle(.segmented) + .padding(.horizontal, 20) + .padding(.bottom, 8) + .onChange(of: viewModel.browseFeed) { _, _ in + if viewModel.browseRows.isEmpty { + viewModel.loadBrowse() + } + } + + ScrollView { + LazyVStack(spacing: 6) { + ForEach(viewModel.browseRows) { row in + browseEventRow(row) + } + if viewModel.browseRows.isEmpty && !viewModel.isBrowseLoading { + emptyHint(viewModel.browseFeed == .priceChanges + ? 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 { + HStack(spacing: 8) { + SwiftUI.ProgressView() + Text(NSLocalizedString("Loading activity…", comment: "Username marketplace: browse feed loading")) + .font(.system(size: 12)) + .foregroundColor(.dash.secondaryText) + } + .frame(maxWidth: .infinity) + .padding(.vertical, 14) + } else if !viewModel.browseFeedExhausted && !viewModel.browseRows.isEmpty { + Button { + viewModel.loadBrowse() + } label: { + Text(NSLocalizedString("Show more", comment: "Username marketplace: load older browse activity")) + .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 { + await viewModel.refreshBrowse() + } + } + .onAppear { + if viewModel.browseRows.isEmpty { + viewModel.loadBrowse() + } + } + } + + private func browseEventRow(_ row: UsernameMarketplaceViewModel.BrowseEventRow) -> some View { + let eventDash = (row.event.priceCredits / 1000).dashAmount.formattedDashAmountWithoutCurrencySymbol + let eventDate = DWDateFormatter.sharedInstance.shortStringFromDate( + Date(timeIntervalSince1970: Double(row.event.createdAtMs) / 1000)) + 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) + } 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: { + 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 private var mySection: some View { @@ -661,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 6b3dfb7bb4..cb38ac9b81 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 feed of recent listings and re-prices */ +"Price changes" = "Price changes"; + +/* Username marketplace: browse feed of recent sales */ +"Purchases" = "Purchases"; + +/* Username marketplace: price-change feed row — event price, then date */ +"Listed for %1$@ DASH · %2$@" = "Listed for %1$@ DASH · %2$@"; + +/* 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"; + +/* 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."; + +/* Username marketplace: browse feed loading */ +"Loading activity…" = "Loading activity…"; + +/* Username marketplace: load older browse activity */ +"Show more" = "Show more"; + /* Username marketplace: contest tallies card title */ "Network vote so far" = "Network vote so far";