From 1db5c159eeda5f14c1cce1c8b6b635d9a737bc0b Mon Sep 17 00:00:00 2001 From: romchornyi Date: Mon, 2 Nov 2026 21:48:13 +0200 Subject: [PATCH 1/8] fix(swap): show which provider can swap each coin right now The coin picker labelled and offered coins from SwapKit's static /tokens lists, so a coin stayed selectable while neither NEAR nor Maya could route it, and the address screen then reported a 404 noRoutesFound as a connection problem. Probe each coin with a quote forced to one provider (about $50 of the sold asset, at most two requests in flight, cached): NEAR is checked on sentinel coins first and treated as down for every coin when they have no route; Maya is checked per coin. Both usable -> "Multiple", one -> that provider, none -> the existing halted row. Buy is included. The address screen reads the error body: a refused address keeps the address copy, a missing route is re-checked without the address, and only a transport failure says "check your connection". Co-Authored-By: Claude Opus 5.5 --- DashWallet.xcodeproj/project.pbxproj | 10 + .../Models/Maya/MayaSwapProvider.swift | 1 - .../Models/Swap/SwapKitErrorCopy.swift | 34 +- .../Sources/Models/Swap/SwapProvider.swift | 33 +- .../Models/SwapKit/SwapKitSwapProvider.swift | 462 ++++++++++------ .../SwapKit/SwapRouteAvailability.swift | 492 ++++++++++++++++++ .../Buy/RefundAddress/RefundAddressView.swift | 5 +- .../UI/Swap/SelectCoin/SelectCoinView.swift | 5 +- .../Swap/SelectCoin/SelectCoinViewModel.swift | 136 +++-- .../SwapKitQuoteDecodingTests.swift | 187 ++++++- .../SwapRouteAvailabilityTests.swift | 482 +++++++++++++++++ 11 files changed, 1608 insertions(+), 239 deletions(-) create mode 100644 DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift create mode 100644 DashWalletTests/SwapRouteAvailabilityTests.swift diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 4d12e0e7b2..07610077c6 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1160,9 +1160,12 @@ AA00100B2CA0B10001A0B10B /* SwapKitAPIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */; }; AA00100C2CA0B10001A0B10C /* SwapKitAPIService.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */; }; AA00100E2CA0B10001A0B10E /* SwapKitQuoteDecodingTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA00100D2CA0B10001A0B10D /* SwapKitQuoteDecodingTests.swift */; }; + C5A11E000000000000000005 /* SwapRouteAvailabilityTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000004 /* SwapRouteAvailabilityTests.swift */; }; AA00100F2CA0B10001A0B10F /* swapkit_quote_response.json in Resources */ = {isa = PBXBuildFile; fileRef = AA0010102CA0B10001A0B110 /* swapkit_quote_response.json */; }; AA0010122CA0B10001A0B112 /* SwapKitSwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */; }; AA0010132CA0B10001A0B113 /* SwapKitSwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */; }; + C5A11E000000000000000002 /* SwapRouteAvailability.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000001 /* SwapRouteAvailability.swift */; }; + C5A11E000000000000000003 /* SwapRouteAvailability.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000001 /* SwapRouteAvailability.swift */; }; AA0020012FA0000000000014 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; AA0020012FA0000000000015 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; AA0020032FA0000000000003 /* SwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020022FA0000000000002 /* SwapProvider.swift */; }; @@ -3399,8 +3402,10 @@ AA0010072CA0B10001A0B107 /* SwapKitModels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitModels.swift; sourceTree = ""; }; AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitAPIService.swift; sourceTree = ""; }; AA00100D2CA0B10001A0B10D /* SwapKitQuoteDecodingTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitQuoteDecodingTests.swift; sourceTree = ""; }; + C5A11E000000000000000004 /* SwapRouteAvailabilityTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapRouteAvailabilityTests.swift; sourceTree = ""; }; AA0010102CA0B10001A0B110 /* swapkit_quote_response.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = swapkit_quote_response.json; sourceTree = ""; }; AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitSwapProvider.swift; sourceTree = ""; }; + C5A11E000000000000000001 /* SwapRouteAvailability.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapRouteAvailability.swift; sourceTree = ""; }; AA0020012FA0000000000013 /* SwapExecutionData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapExecutionData.swift; sourceTree = ""; }; AA0020022FA0000000000002 /* SwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapProvider.swift; sourceTree = ""; }; AA0020052FA0000000000005 /* SwapBackend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapBackend.swift; sourceTree = ""; }; @@ -7687,6 +7692,7 @@ 5A7E0C1D2E3F405162738498 /* VotingKeyImportTests.swift */, AA00F1002FF0A10000A1B402 /* ExchangeAddressLookupContextTests.swift */, AA00100D2CA0B10001A0B10D /* SwapKitQuoteDecodingTests.swift */, + C5A11E000000000000000004 /* SwapRouteAvailabilityTests.swift */, 5EAD222130A0000000A1B202 /* DashAmountFormatterTests.swift */, DA57A1010000000000000001 /* PastedAmountNormalizationTests.swift */, DA5A00000000000000000005 /* DashPayIdentityKeysTests.swift */, @@ -7959,6 +7965,7 @@ AA0010072CA0B10001A0B107 /* SwapKitModels.swift */, AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */, AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */, + C5A11E000000000000000001 /* SwapRouteAvailability.swift */, ); path = SwapKit; sourceTree = ""; @@ -10818,6 +10825,7 @@ AA0010082CA0B10001A0B108 /* SwapKitModels.swift in Sources */, AA00100B2CA0B10001A0B10B /* SwapKitAPIService.swift in Sources */, AA0010122CA0B10001A0B112 /* SwapKitSwapProvider.swift in Sources */, + C5A11E000000000000000002 /* SwapRouteAvailability.swift in Sources */, AA0020012FA0000000000014 /* SwapExecutionData.swift in Sources */, AA00020E2BA0F58E00A1B305 /* SelectCoinViewModel.swift in Sources */, AA0002142BA0F58E00A1B307 /* SelectCoinView.swift in Sources */, @@ -11053,6 +11061,7 @@ 5A7E0C1D2E3F405162738497 /* VotingKeyImportTests.swift in Sources */, AA00F1012FF0A10000A1B402 /* ExchangeAddressLookupContextTests.swift in Sources */, AA00100E2CA0B10001A0B10E /* SwapKitQuoteDecodingTests.swift in Sources */, + C5A11E000000000000000005 /* SwapRouteAvailabilityTests.swift in Sources */, 5EAD222230A0000000A1B202 /* DashAmountFormatterTests.swift in Sources */, DA57A1010000000000000002 /* PastedAmountNormalizationTests.swift in Sources */, DA5A00000000000000000004 /* DashPayIdentityKeysTests.swift in Sources */, @@ -11922,6 +11931,7 @@ AA0010092CA0B10001A0B109 /* SwapKitModels.swift in Sources */, AA00100C2CA0B10001A0B10C /* SwapKitAPIService.swift in Sources */, AA0010132CA0B10001A0B113 /* SwapKitSwapProvider.swift in Sources */, + C5A11E000000000000000003 /* SwapRouteAvailability.swift in Sources */, AA0020012FA0000000000015 /* SwapExecutionData.swift in Sources */, AA00020F2BA0F58E00A1B305 /* SelectCoinViewModel.swift in Sources */, AA0002152BA0F58E00A1B307 /* SelectCoinView.swift in Sources */, diff --git a/DashWallet/Sources/Models/Maya/MayaSwapProvider.swift b/DashWallet/Sources/Models/Maya/MayaSwapProvider.swift index d9996b28ce..bd8ffe8a39 100644 --- a/DashWallet/Sources/Models/Maya/MayaSwapProvider.swift +++ b/DashWallet/Sources/Models/Maya/MayaSwapProvider.swift @@ -23,7 +23,6 @@ import Foundation /// Maps Maya-specific DTOs (`MayaSwapQuote`, `MayaSwapTransactionInfo`) to the neutral result types. final class MayaSwapProvider: SwapProvider { var displayName: String { "Maya" } - var onBuyRoutabilityChanged: (() -> Void)? func fetchPools() async throws -> [SwapPool] { try await MayaAPIService.shared.fetchPools() diff --git a/DashWallet/Sources/Models/Swap/SwapKitErrorCopy.swift b/DashWallet/Sources/Models/Swap/SwapKitErrorCopy.swift index df4ef8acd8..33cfe250c7 100644 --- a/DashWallet/Sources/Models/Swap/SwapKitErrorCopy.swift +++ b/DashWallet/Sources/Models/Swap/SwapKitErrorCopy.swift @@ -66,6 +66,12 @@ enum SwapKitErrorCopy { ) } + // A provider's trading halt (`swapHalted` today) is not something the user can fix with a + // different amount or address: the coin cannot be swapped until the provider resumes. + if isHaltedCode(code) { + return unavailableNowMessage(coin: coin) + } + switch code { // `memoTooLongForSourceChain` is SwapKit's own name for what the wallet also detects // locally before broadcasting; both mean the OP_RETURN will not fit. @@ -85,10 +91,7 @@ enum SwapKitErrorCopy { comment: "Dash DEX / dex_error_no_route" ) case "blacklistasset", "invalidasset": - return String(format: NSLocalizedString( - "%@ can't be swapped at the moment.", - comment: "Dash DEX / dex_error_blacklisted" - ), coin.code) + return unavailableNowMessage(coin: coin) case "invalidrequest", "validation_error": return NSLocalizedString( "We couldn't set up your swap. Please check the amount and address, then try again.", @@ -163,7 +166,9 @@ enum SwapKitErrorCopy { /// amount far below a route's floor as well as for a pair it cannot carry: measured /// 2026-08-28, DASH → BTC returned it at 0.01 DASH, `sellAssetAmountTooSmall` (min 0.175) at /// 0.05, and a route at 0.3. Callers must not read the top-level form as "this cannot be - /// swapped at all" — hence the neutral copy, and `routability(from:)` ignoring it. + /// swapped at all" — hence the neutral copy. The live-availability probes + /// (`LiveRouteState.classify`, `classifyPerProvider`) take it as conclusive because they are sized + /// well above every route floor; the address screen re-asks without the address before trusting it. static func isNoRoute(_ rawError: String?) -> Bool { code(of: rawError) == noRoutesFoundCode } @@ -176,6 +181,25 @@ enum SwapKitErrorCopy { isBelowMinimumCode(code(of: rawError)) } + /// " can't be swapped at the moment." — for a coin no provider can carry right now, where + /// neither the amount nor the address is the user's to change. + static func unavailableNowMessage(coin: SwapCryptoCurrency) -> String { + String(format: NSLocalizedString( + "%@ can't be swapped at the moment.", + comment: "Dash DEX / dex_error_blacklisted" + ), coin.code) + } + + /// True when a provider reported a trading halt for the pair (`swapHalted`, as Maya does while a + /// chain's trading is paused). SwapKit does not enumerate the halt codes, so the family is matched. + static func isHalted(_ rawError: String?) -> Bool { + isHaltedCode(code(of: rawError)) + } + + private static func isHaltedCode(_ code: String) -> Bool { + code.contains("halted") + } + private static func isBelowMinimumCode(_ code: String) -> Bool { code.hasSuffix("amounttoosmall") || code.hasSuffix("amounttoolow") } diff --git a/DashWallet/Sources/Models/Swap/SwapProvider.swift b/DashWallet/Sources/Models/Swap/SwapProvider.swift index 557ded7dc6..f1ee3d8e0c 100644 --- a/DashWallet/Sources/Models/Swap/SwapProvider.swift +++ b/DashWallet/Sources/Models/Swap/SwapProvider.swift @@ -17,6 +17,7 @@ // limitations under the License. // +import Combine import Foundation // MARK: - Result types @@ -136,12 +137,24 @@ extension SwapProvider { /// Returns a map of asset identifier (uppercased) → routing network label /// for display in the coin picker ("Maya", "NEAR", "Multiple networks"). /// Default: empty — non-SwapKit providers don't have multi-provider routing. - func networkLabels(for pools: [SwapPool]) async -> [String: String] { [:] } + func networkLabels(for pools: [SwapPool], direction: SwapDirection) async -> [String: String] { [:] } /// Returns the set of asset identifiers (uppercased) that are halted due to - /// provider-specific halt logic (e.g. Maya chain halt for mayaOnly assets). + /// provider-specific halt logic (SwapKit: no provider can carry the coin right now). /// Default: empty set (use chain-based halt from inbound addresses). - func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool]) async -> Set { [] } + func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool], direction: SwapDirection) async -> Set { [] } + + /// Starts checking, in the background, whether the shown coins can be swapped right now. + /// Default: nothing to check — the provider's pools and inbound addresses are already live. + func refreshRouteAvailability(for pools: [SwapPool], direction: SwapDirection) {} + + /// Stops the background check started by `refreshRouteAvailability`. Default: nothing runs. + func stopRouteAvailabilityRefresh(direction: SwapDirection) {} + + /// Directions whose live route availability changed. Default: never. + var routeAvailabilityChanges: AnyPublisher { + Empty().eraseToAnyPublisher() + } } // MARK: - Protocol @@ -156,7 +169,9 @@ protocol SwapProvider { var displayName: String { get } var usesGenericFeeLabel: Bool { get } var buildsSwapKitDeposit: Bool { get } - var onBuyRoutabilityChanged: (() -> Void)? { get set } + /// Directions whose live route availability changed, so the picker can re-label. MUST be a + /// protocol requirement for dynamic dispatch. + var routeAvailabilityChanges: AnyPublisher { get } func fetchPools() async throws -> [SwapPool] func fetchInboundAddresses() async throws -> [SwapInboundAddress] @@ -167,10 +182,16 @@ protocol SwapProvider { func fetchPools(direction: SwapDirection) async throws -> [SwapPool] /// Routing network labels per asset. MUST be a protocol requirement for dynamic dispatch. - func networkLabels(for pools: [SwapPool]) async -> [String: String] + func networkLabels(for pools: [SwapPool], direction: SwapDirection) async -> [String: String] /// Provider-specific halted assets. MUST be a protocol requirement for dynamic dispatch. - func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool]) async -> Set + func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool], direction: SwapDirection) async -> Set + + /// Live route checks for the shown coins. MUST be a protocol requirement for dynamic dispatch. + func refreshRouteAvailability(for pools: [SwapPool], direction: SwapDirection) + + /// Stops the live route checks for `direction`. MUST be a protocol requirement for dynamic dispatch. + func stopRouteAvailabilityRefresh(direction: SwapDirection) /// Returns `nil` if the destination address is valid, otherwise an error string. func validateAddress(destination: String, toAsset: String) async -> String? diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index 83db49c3bb..cd3878c55b 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -17,6 +17,7 @@ // limitations under the License. // +import Combine import Foundation /// `SwapProvider` backed by `SwapKitAPIService`. @@ -28,8 +29,11 @@ import Foundation /// MAYACHAIN, NEAR, Chainflip, etc. — AC#4 "choose best price (Maya vs NEAR)". /// - The DASH tx is still built locally from `vaultAddress + memo` — no PSBT parsing. /// -/// @MainActor ensures all mutable caches (classification sets, routability cache, price cache, -/// etc.) are accessed from a single isolation domain, eliminating concurrent read/write races. +/// Live per-provider availability (what the picker labels and halts on) lives in +/// `SwapRouteAvailability`; this type supplies it with the static classification and the probes. +/// +/// @MainActor ensures all mutable caches (classification sets, price cache, etc.) are accessed +/// from a single isolation domain, eliminating concurrent read/write races. @MainActor final class SwapKitSwapProvider: SwapProvider { private enum Constants { @@ -39,7 +43,19 @@ final class SwapKitSwapProvider: SwapProvider { nonisolated var displayName: String { "SwapKit" } nonisolated var usesGenericFeeLabel: Bool { true } nonisolated var buildsSwapKitDeposit: Bool { true } - var onBuyRoutabilityChanged: (() -> Void)? + + private let routeAvailability: SwapRouteAvailability + /// The running live-availability refresh per direction, so leaving the picker can stop it. + private var routeRefreshTasks: [SwapDirection: (id: UUID, task: Task)] = [:] + + init(routeAvailability: SwapRouteAvailability = .shared) { + self.routeAvailability = routeAvailability + } + + /// One event per stored answer that changed something; subscribers batch them. + var routeAvailabilityChanges: AnyPublisher { + routeAvailability.changes.eraseToAnyPublisher() + } // MARK: - Cache @@ -66,21 +82,6 @@ final class SwapKitSwapProvider: SwapProvider { private var classificationUsable = false /// Identifier (uppercased) → logoURI, populated from both Maya and NEAR token lists. private var logoURIByIdentifier: [String: String] = [:] - /// Cached NEAR→DASH buy routability decisions for buy-list pruning. - private var buyRoutabilityCache: [String: (value: BuyRoutability, checkedAt: Date)] = [:] - /// Prevents duplicate probes while a candidate is already being checked. - private var buyRoutabilityInFlight: Set = [] - /// Buy routability cache TTL, mirroring Android's preferred-route cache cadence. - private let buyRoutabilityTTL: TimeInterval = 600 - /// Small batch size to keep verification bounded without spamming the quote endpoint. - private let buyRoutabilityProbeBatchSize: Int = 8 - - /// Internal rather than private so the tests can assert `routability(from:)` directly. - enum BuyRoutability { - case routable - case notRoutable - } - private var isCacheValid: Bool { guard let cachedAt = poolsCachedAt else { return false } return Date().timeIntervalSince(cachedAt) < cacheMaxAge @@ -164,58 +165,79 @@ final class SwapKitSwapProvider: SwapProvider { ) } - // Cheap pre-filter: only assets that classification says can reach NEAR. - let candidates = pools.filter { - let key = $0.asset.uppercased() - return nearOnlyAssets.contains(key) || bothAssets.contains(key) - } - - // Pass original-case identifiers — uppercased contract addresses differ from what - // the quote endpoint accepts, causing all contract-token probes to error → never pruned. - // Uppercasing is kept only for the Set-membership keys (nearOnlyAssets / bothAssets above). - scheduleBuyRoutabilityVerification(for: candidates.map { $0.asset }) - - // Optimistic filter: show until a probe conclusively proves the asset cannot route - // NEAR→DASH — which now means NEAR itself reporting a no-route in `providerErrors`, the - // only unambiguous negative (see `routability(from:)`). This keeps first-open responsive - // while background verification prunes. - return candidates.filter { pool in - cachedBuyRoutability(for: pool.asset) != .notRoutable - } + // Only assets the classification says NEAR can carry: Buy routes through NEAR alone. + // Whether NEAR carries them right now is live state — a coin it cannot carry is shown + // halted (`haltedAssets`), not dropped. + return pools.filter { !capableProviders(for: $0.asset, direction: .buy).isEmpty } } - func networkLabels(for pools: [SwapPool]) async -> [String: String] { + /// The label is the set of providers that can carry the coin *now* (live probes over the static + /// classification): both → "Multiple", one → that provider. A coin no provider can carry gets + /// no label; `haltedAssets` reports it instead. + func networkLabels(for pools: [SwapPool], direction: SwapDirection) async -> [String: String] { if !classificationBuilt { await buildClassification() } var result: [String: String] = [:] for pool in pools { - let key = pool.asset.uppercased() - if mayaOnlyAssets.contains(key) { - result[key] = RouteProvider.maya.shortLabel - } else if nearOnlyAssets.contains(key) { - result[key] = RouteProvider.near.shortLabel - } else if bothAssets.contains(key) { - result[key] = RouteProvider.multiple.shortLabel + if let label = RouteProvider.label(forUsable: usableProviders(for: pool.asset, direction: direction)) { + result[pool.asset.uppercased()] = label.shortLabel } } return result } - func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool]) async -> Set { + /// Coins some provider can ever carry but none can carry now — a halt, or no route at all. + /// `fetchInboundAddresses` reports no halted chains for SwapKit, so this is its only halt source. + func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool], direction: SwapDirection) async -> Set { if !classificationBuilt { await buildClassification() } - let haltedChains = Set(inboundAddresses.filter { $0.halted }.map { $0.chain.uppercased() }) - guard !haltedChains.isEmpty else { return [] } - // Only mayaOnly assets are halted when the Maya chain is halted. - // Assets routed via NEAR ("both" or "nearOnly") remain available. var halted = Set() - for asset in mayaOnlyAssets { - let chain = asset.components(separatedBy: ".").first ?? "" - if haltedChains.contains(chain) { - halted.insert(asset) + for pool in pools { + let capable = capableProviders(for: pool.asset, direction: direction) + guard !capable.isEmpty else { continue } + if routeAvailability.usableProviders(for: pool.asset, capable: capable, direction: direction).isEmpty { + halted.insert(pool.asset.uppercased()) } } return halted } + /// Starts the live probes for the coins the picker shows, in its display order. Returns at once; + /// answers arrive through `routeAvailabilityChanges`. + /// + /// Assets are passed in their original case: an uppercased contract address is not what the + /// quote endpoint accepts. + func refreshRouteAvailability(for pools: [SwapPool], direction: SwapDirection) { + guard classificationUsable, routeRefreshTasks[direction] == nil else { return } + let assets = pools.map { $0.asset } + let capability = Dictionary( + assets.map { ($0.uppercased(), capableProviders(for: $0, direction: direction)) }, + uniquingKeysWith: { first, _ in first } + ) + let id = UUID() + let task = Task { [weak self, routeAvailability] in + await routeAvailability.refresh( + assets: assets, + direction: direction, + capable: { capability[$0.uppercased()] ?? [] }, + probe: { asset, provider, direction in + guard let self else { return .unknown } + return await self.probeRoute(asset: asset, provider: provider, direction: direction) + } + ) + // A newer refresh may have replaced this one after a stop; leave its handle alone. + if self?.routeRefreshTasks[direction]?.id == id { + self?.routeRefreshTasks[direction] = nil + } + } + routeRefreshTasks[direction] = (id, task) + } + + /// Stops the live-availability refresh for `direction`: queued probes are dropped, the one or + /// two in flight finish. Answers already in keep counting. + func stopRouteAvailabilityRefresh(direction: SwapDirection) { + routeRefreshTasks[direction]?.task.cancel() + routeRefreshTasks[direction] = nil + } + func fetchInboundAddresses() async throws -> [SwapInboundAddress] { // SwapKit returns vault address inline per-swap; no vault-list endpoint. // Synthesise one SwapInboundAddress(chain:, halted: false) per reachable chain @@ -246,23 +268,153 @@ final class SwapKitSwapProvider: SwapProvider { } } + /// What the address screen does with the nominal quote to the user's address. + enum AddressCheck: Equatable { + /// Let the user through; the amount screen quotes the real amount. + case pass + /// The request itself was refused (`validation_error`, `invalidDestinationAddress`, …); + /// the associated value is SwapKit's code for `SwapKitErrorCopy.message(for:coin:)`. + case refused(String) + /// No asked provider can carry the coin, and these said no-route — which, to the user's own + /// address, may be about the address: re-ask them without it before deciding. + case confirmNoRoute(Set) + /// No asked provider can carry the coin, and none blamed a missing route (all halted). + case unavailable + } + + /// Codes that are about the request or the address, not about the route. + private static let requestCodes: Set = [ + "validation_error", "invalidrequest", "invaliddestinationaddress", "issanctionedaddress", + ] + /// Codes SwapKit uses to refuse the coin itself, whatever the provider. + private static let refusedCoinCodes: Set = ["blacklistasset", "invalidasset"] + + /// Pure decision for `validateAddress`, internal for the tests. `requested` empty means the + /// quote let SwapKit pick providers (no classification), so availability is not judged. + static func addressCheck(_ response: SwapKitQuoteResponse, requested: Set) -> AddressCheck { + if response.routes?.isEmpty == false { + return .pass + } + + func code(_ raw: String?) -> String? { + raw?.components(separatedBy: ":").first?.trimmingCharacters(in: .whitespacesAndNewlines) + } + // A top-level refusal is about the whole request. + if let top = code(response.error), + requestCodes.contains(top.lowercased()) || refusedCoinCodes.contains(top.lowercased()) { + return .refused(top) + } + + // A provider's refusal only counts for that provider: another one may still accept it. + var refusedBy: [RouteProvider: String] = [:] + for error in response.providerErrors ?? [] { + guard let raw = code(error.errorCode), + requestCodes.contains(raw.lowercased()) || refusedCoinCodes.contains(raw.lowercased()) else { continue } + if let name = error.provider, let provider = RouteProvider(swapKitProvider: name) { + refusedBy[provider] = raw + } else if requested.isEmpty { + return .refused(raw) + } + } + + guard !requested.isEmpty else { + return refusedBy.values.first.map { .refused($0) } ?? .pass + } + // The quote asked every usable provider at once; each one is judged on its own answer. + var states = LiveRouteState.classifyPerProvider(response, requested: requested) + for provider in refusedBy.keys { + states[provider] = nil + } + if states.values.contains(where: { $0.isUsable }) { + return .pass + } + if let refusal = refusedBy.values.first { + return .refused(refusal) + } + let noRoute = Set(states.filter { $0.value == .noRoute }.map { $0.key }) + return noRoute.isEmpty ? .unavailable : .confirmNoRoute(noRoute) + } + + /// A nominal Sell quote to the entered address. Its real use is the last check before the + /// amount screen that the coin can be swapped right now (`addressCheck` decides). + /// + /// The user is stopped when SwapKit refuses the request or the address, or when no asked + /// provider can carry the coin. Anything inconclusive (an upstream failure, a below-minimum for + /// the nominal amount) lets them through to the amount screen, which quotes the real amount + /// and reports what is wrong with it. func validateAddress(destination: String, toAsset: String) async -> String? { + if !classificationBuilt { await buildClassification() } + // Without a classification there is nothing to judge availability by: let SwapKit pick + // providers, as this check always did. + let providers = classificationUsable ? sellQuoteProviders(for: toAsset) : nil let request = SwapKitQuoteRequest( sellAsset: SwapKitConstants.dashAsset, buyAsset: toAsset, - sellAmount: "1", // nominal — only the address format is being validated + sellAmount: "1", // nominal; one DASH is far above every route floor slippage: SwapKitConstants.defaultSlippagePercent, sourceAddress: nil, destinationAddress: destination, - providers: nil, + providers: providers, affiliateFee: nil ) + + let response: SwapKitQuoteResponse do { - let response = try await SwapKitAPIService.shared.quote(request) - return response.error + response = try await SwapKitAPIService.shared.quote(request) } catch { - DWLogger.log("SwapKit: address validation request failed: \(error)") - return NSLocalizedString("Address validation unavailable — please check your connection", comment: "SwapKit") + // A non-2xx carrying a SwapKit body (404 `noRoutesFound`, 400 `validation_error`) is an + // answer, not a connection problem. + guard let decoded = Self.decodedQuoteResponse(from: error) else { + DWLogger.log("SwapKit: address validation request failed: \(error)") + return NSLocalizedString("Address validation unavailable — please check your connection", comment: "SwapKit") + } + response = decoded + } + + let requested = Set((providers ?? []).compactMap { RouteProvider(swapKitProvider: $0) }) + recordQuoteOutcome(response, requested: requested, asset: toAsset, direction: .sell) + + let check = Self.addressCheck(response, requested: requested) + if check != .pass { + DWLogger.log("SwapKit: address check for \(toAsset) → \(check) — \(response.error ?? SwapKitErrorCopy.providerErrorMessage(response.providerErrors?.first) ?? "no code")") + } + let coin = SwapCryptoCurrency.knownCoin(for: toAsset) + + switch check { + case .pass: + return nil + case .refused(let code): + guard let coin else { return code } + // On this screen the address is the thing to check; the generic deposit copy for + // `invalidDestinationAddress` would only say "try again". + if code.lowercased() == "invaliddestinationaddress" { + return SwapKitErrorCopy.message(for: "validation_error", coin: coin) + } + return SwapKitErrorCopy.message(for: code, coin: coin) + case .unavailable: + guard let coin else { return NSLocalizedString("No route available", comment: "SwapKit") } + return SwapKitErrorCopy.unavailableNowMessage(coin: coin) + case .confirmNoRoute(let noRouteProviders): + // Ask again without the address, the way the picker probes: if a provider routes + // there, the address is what to fix. + var reAsked: [LiveRouteState] = [] + for provider in [RouteProvider.near, .maya] where noRouteProviders.contains(provider) { + reAsked.append(await routeAvailability.probeNow(asset: toAsset, provider: provider, direction: .sell) { [weak self] asset, provider, direction in + guard let self else { return .unknown } + return await self.probeRoute(asset: asset, provider: provider, direction: direction) + }) + } + if reAsked.contains(.available) { + guard let coin else { return "validation_error" } + return SwapKitErrorCopy.message(for: "validation_error", coin: coin) + } + // The re-ask could not settle it: nothing proved the coin unavailable, so the amount + // screen gets to quote it. + if reAsked.contains(.unknown) { + return nil + } + guard let coin else { return NSLocalizedString("No route available", comment: "SwapKit") } + return SwapKitErrorCopy.unavailableNowMessage(coin: coin) } } @@ -647,135 +799,104 @@ final class SwapKitSwapProvider: SwapProvider { return best } - // MARK: - Private: Buy Routability + // MARK: - Private: Live Route Availability - private func scheduleBuyRoutabilityVerification(for assets: [String]) { - let pending = assets.filter { shouldProbeBuyRoutability(for: $0) } - guard !pending.isEmpty else { return } - - pending.forEach { buyRoutabilityInFlight.insert($0) } - - Task(priority: .utility) { [weak self] in - guard let self else { return } - await self.verifyBuyRoutability(for: pending) + /// The providers the `/tokens` classification says can ever carry `asset` in `direction`. + /// Buy routes only through NEAR (the counterparty builds the deposit, and Maya needs an + /// OP_RETURN memo an external wallet will not add), so Maya never counts for Buy. + private func capableProviders(for asset: String, direction: SwapDirection) -> Set { + let key = asset.uppercased() + var providers = Set() + if nearOnlyAssets.contains(key) || bothAssets.contains(key) { + providers.insert(.near) } - } - - private func verifyBuyRoutability(for assets: [String]) async { - var updatedAny = false - - for chunk in assets.chunked(into: buyRoutabilityProbeBatchSize) { - let probeResults = await withTaskGroup(of: (String, BuyRoutability?).self) { group -> [(String, BuyRoutability?)] in - for asset in chunk { - let sellAmount = buyProbeSellAmount(for: asset) - group.addTask { [sellAmount] in - (asset, await Self.probeBuyRoutability(for: asset, sellAmount: sellAmount)) - } - } - - var results: [(String, BuyRoutability?)] = [] - results.reserveCapacity(chunk.count) - for await result in group { - results.append(result) - } - return results - } - - // @MainActor class — caches are already on the main actor; no MainActor.run hop needed. - let now = Date() - var changed = false - for (asset, result) in probeResults { - buyRoutabilityInFlight.remove(asset) - guard let result else { continue } - - let previous = buyRoutabilityCache[asset]?.value - buyRoutabilityCache[asset] = (value: result, checkedAt: now) - if previous != result { - changed = true - } - } - updatedAny = updatedAny || changed + if direction == .sell, mayaOnlyAssets.contains(key) || bothAssets.contains(key) { + providers.insert(.maya) } - - guard updatedAny else { return } - onBuyRoutabilityChanged?() - } - - private func shouldProbeBuyRoutability(for asset: String) -> Bool { - guard cachedBuyRoutability(for: asset) == nil else { return false } - return !buyRoutabilityInFlight.contains(asset) + return providers } - private func cachedBuyRoutability(for asset: String) -> BuyRoutability? { - guard let entry = buyRoutabilityCache[asset] else { return nil } - guard Date().timeIntervalSince(entry.checkedAt) < buyRoutabilityTTL else { return nil } - return entry.value + /// The providers that can carry `asset` now: capable ones the live probes have not ruled out. + private func usableProviders(for asset: String, direction: SwapDirection) -> Set { + routeAvailability.usableProviders( + for: asset, + capable: capableProviders(for: asset, direction: direction), + direction: direction + ) } - private func buyProbeSellAmount(for asset: String) -> String { - guard let priceUSD = usdPriceCache[asset.uppercased()], priceUSD > 0 else { - return "1" + /// The amount a probe sells: about $50 of the sold asset, so a top-level `noRoutesFound` can be + /// read as a real no-route (see `LiveRouteState.classify`). `nil` when that size is unknown — + /// a Buy coin with no cached USD price — and the probe must not run. + private func probeAmount(for asset: String, direction: SwapDirection) -> String? { + let soldAsset = direction == .sell ? SwapKitConstants.dashAsset : asset + if let priceUSD = usdPriceCache[soldAsset.uppercased()], priceUSD > 0 { + return Self.plainDecimalString(Decimal(50) / Decimal(priceUSD), scale: 8) } - - let nominal = Decimal(50) / Decimal(priceUSD) - return Self.plainDecimalString(nominal, scale: 8) + // One DASH is worth tens of dollars, far above any route floor, so Sell can still probe + // without a DASH price. One unit of an arbitrary Buy coin can be worth a fraction of a cent. + return direction == .sell ? "1" : nil } - private static func probeBuyRoutability(for asset: String, sellAmount: String) async -> BuyRoutability? { + /// One quote forced to `provider`'s SwapKit providers, classified. + private func probeRoute(asset: String, provider: RouteProvider, direction: SwapDirection) async -> LiveRouteState { + guard let amount = probeAmount(for: asset, direction: direction) else { + return .unknown + } let request = SwapKitQuoteRequest( - sellAsset: asset, - buyAsset: SwapKitConstants.dashAsset, - sellAmount: sellAmount, + sellAsset: direction == .sell ? SwapKitConstants.dashAsset : asset, + buyAsset: direction == .sell ? asset : SwapKitConstants.dashAsset, + sellAmount: amount, slippage: SwapKitConstants.defaultSlippagePercent, sourceAddress: nil, destinationAddress: nil, - // Buy routability is still about counterparty-built deposits, so keep probing NEAR. - providers: [SwapKitConstants.providerNear], + providers: provider.swapKitProviders, affiliateFee: nil ) do { - let response = try await SwapKitAPIService.shared.quote(request) - return routability(from: response) + return LiveRouteState.classify(try await SwapKitAPIService.shared.quote(request)) } catch { - if let response = decodedQuoteResponse(from: error) { - return routability(from: response) + if let response = Self.decodedQuoteResponse(from: error) { + return LiveRouteState.classify(response) } - return nil + return .unknown } } - /// Internal rather than private so the tests can drive the picker-pruning rule with recorded - /// responses; nothing outside this type calls it. - static func routability(from response: SwapKitQuoteResponse) -> BuyRoutability? { - if response.routes?.isEmpty == false { - return .routable + /// Feeds what a quote to the user's address said about `asset` into the live store. Only what + /// cannot depend on the address is recorded: a route names the providers that carry it, and a + /// provider's halt names the provider that is halted. A no-route is left to the address-free + /// re-probe in `validateAddress`. + private func recordQuoteOutcome( + _ response: SwapKitQuoteResponse, + requested: Set, + asset: String, + direction: SwapDirection + ) { + if let routes = response.routes, !routes.isEmpty { + let carrying = Set(routes.flatMap { $0.providers }.compactMap { RouteProvider(swapKitProvider: $0) }) + for provider in carrying.intersection(requested) { + routeAvailability.record(.available, provider: provider, asset: asset, direction: direction) + } + return } - // Classify on the codes, not the prose: a provider reports its reason in - // `providerErrors[].errorCode`, and only the code is a stable identifier. - let providerCode = SwapKitErrorCopy.providerErrorMessage(response.providerErrors?.first) - - guard let providerCode else { - // A top-level `noRoutesFound` is deliberately NOT treated as proof of unroutability. - // SwapKit answers with it for an amount far below a route's floor as well as for a - // pair it cannot carry — measured 2026-08-28, DASH → BTC returned it at 0.01 DASH - // and quoted a route at 0.3 — and the probe amount is a $50 estimate that falls back - // to one whole unit when no USD price is cached. Pruning on it would drop a routable - // asset out of the picker for the whole cache window. - return nil + // Both Maya flavours answer for `.maya`: it is halted only when no flavour says otherwise. + var halted = Set() + var notHalted = Set() + for error in response.providerErrors ?? [] { + guard let name = error.provider, let provider = RouteProvider(swapKitProvider: name), + requested.contains(provider) else { continue } + if SwapKitErrorCopy.isHalted(error.errorCode) { + halted.insert(provider) + } else { + notHalted.insert(provider) + } } - - if SwapKitErrorCopy.isBelowMinimum(providerCode) { - // The probe amount was under this route's floor, which says nothing about whether - // the asset is routable — the picker must not hide it on this evidence. - return .routable + for provider in halted.subtracting(notHalted) { + routeAvailability.record(.halted, provider: provider, asset: asset, direction: direction) } - - // A provider naming its own no-route is the one conclusive negative: it is answering for - // the single provider the probe asked about. Anything else it reports (an upstream - // `apiRequestFailed`, say) leaves the question open. - return SwapKitErrorCopy.isNoRoute(providerCode) ? .notRoutable : nil } private static func decodedQuoteResponse(from error: Error) -> SwapKitQuoteResponse? { @@ -835,20 +956,23 @@ final class SwapKitSwapProvider: SwapProvider { /// Consequence to keep in mind: a MAYACHAIN route can now win for a coin that previously /// always deposited memo-less, so the 80-byte memo ceiling and Maya's dust floor apply to /// dual-routable coins too. Both guards already run on the fresh pre-commit quote. + /// + /// Providers the live probes have ruled out for this coin are left out, so a halted Maya leg + /// cannot crowd the answer of a working NEAR one. When the probes ruled out every provider, the + /// static set is sent anyway and SwapKit's own answer reaches the user. private func sellQuoteProviders(for toAsset: String) -> [String]? { guard classificationUsable else { return [SwapKitConstants.providerNear] } - let key = toAsset.uppercased() - if mayaOnlyAssets.contains(key) { - return SwapKitConstants.mayaProviders - } - if bothAssets.contains(key) { - return [SwapKitConstants.providerNear] + SwapKitConstants.mayaProviders + let capable = capableProviders(for: toAsset, direction: .sell) + guard !capable.isEmpty else { + return [SwapKitConstants.providerNear] } - - return [SwapKitConstants.providerNear] + let usable = routeAvailability.usableProviders(for: toAsset, capable: capable, direction: .sell, freshOnly: true) + let chosen = usable.isEmpty ? capable : usable + // NEAR first, then Maya — the order the request has always used. + return [RouteProvider.near, .maya].filter { chosen.contains($0) }.flatMap { $0.swapKitProviders } } // MARK: - Private: Amount Conversion diff --git a/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift new file mode 100644 index 0000000000..4e33eacccb --- /dev/null +++ b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift @@ -0,0 +1,492 @@ +// +// SwapRouteAvailability.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Combine +import Foundation + +// MARK: - LiveRouteState + +/// What one routing provider answered, right now, for one asset in one direction. +/// +/// The `/tokens` classification says which provider *can ever* carry an asset; this says whether it +/// carries it at the moment. The two disagree whenever a chain is halted on Maya, or NEAR's DASH leg +/// is down, or SwapKit's own leg to a provider fails for a chain the provider itself still quotes. +enum LiveRouteState: Equatable { + /// The provider returned a route (or only complained that the probe amount was too small). + case available + /// The provider reported a trading halt for this pair. + case halted + /// The provider has no route for this pair. + case noRoute + /// The answer said nothing conclusive: a transport failure, an upstream error, an empty reply. + case unknown + + /// Whether the provider may be offered for the asset. An inconclusive answer keeps the + /// provider: a flaky request must not halt a coin that may well be routable. + var isUsable: Bool { + switch self { + case .available, .unknown: return true + case .halted, .noRoute: return false + } + } + + /// Classifies a quote that was forced to the SwapKit providers of ONE `RouteProvider` (both + /// Maya flavours count as one). + /// + /// Each provider error is read on its own and the most favourable reading wins: a flavour that + /// routes (or only found the amount too small) means the provider can carry the coin, and a + /// flavour that failed inconclusively leaves the question open. Only when every flavour that + /// spoke said halt or no-route is the answer conclusive. A flavour that is not listed has no + /// opinion. + /// + /// A top-level `noRoutesFound` with no provider errors counts as a conclusive no-route here, + /// unlike on the amount screens: SwapKit also answers it for an amount far below a route's + /// floor, but the probes this classifies are sized at ~$50 (`SwapKitSwapProvider.probeAmount`), + /// well above every floor measured (the DASH → BTC minimum was 0.175 DASH on 2026-08-28). + static func classify(_ response: SwapKitQuoteResponse) -> LiveRouteState { + if response.routes?.isEmpty == false { + return .available + } + + let states = (response.providerErrors ?? []).compactMap { error -> LiveRouteState? in + guard let code = error.errorCode?.trimmingCharacters(in: .whitespacesAndNewlines), !code.isEmpty else { + return nil + } + if SwapKitErrorCopy.isBelowMinimum(code) { return .available } + if SwapKitErrorCopy.isHalted(code) { return .halted } + if SwapKitErrorCopy.isNoRoute(code) { return .noRoute } + return .unknown + } + + guard !states.isEmpty else { + return SwapKitErrorCopy.isNoRoute(response.error) ? .noRoute : .unknown + } + if states.contains(.available) { return .available } + if states.contains(.unknown) { return .unknown } + if states.contains(.halted) { return .halted } + return .noRoute + } + + /// The answer of each of `requested` in a quote that asked several route providers at once: + /// every provider's own errors are classified on their own. A provider with no error and no + /// route is `.unknown`, except under a bare top-level no-route, which covers everyone asked. + static func classifyPerProvider(_ response: SwapKitQuoteResponse, requested: Set) -> [RouteProvider: LiveRouteState] { + var result: [RouteProvider: LiveRouteState] = [:] + let routed = Set((response.routes ?? []).flatMap { $0.providers }.compactMap { RouteProvider(swapKitProvider: $0) }) + let errors = response.providerErrors ?? [] + let bareNoRoute = errors.isEmpty && SwapKitErrorCopy.isNoRoute(response.error) + for provider in requested { + if routed.contains(provider) { + result[provider] = .available + continue + } + let own = errors.filter { $0.provider.flatMap { RouteProvider(swapKitProvider: $0) } == provider } + if own.isEmpty { + result[provider] = bareNoRoute ? .noRoute : .unknown + } else { + result[provider] = classify(SwapKitQuoteResponse(quoteId: nil, routes: nil, providerErrors: own, error: nil, message: nil)) + } + } + return result + } +} + +// MARK: - RouteProvider live label + +extension RouteProvider { + /// The provider label for the set of providers that can carry an asset right now: + /// both → `.multiple`, one → that one, none → `nil` (the coin is shown halted instead). + static func label(forUsable usable: Set) -> RouteProvider? { + let near = usable.contains(.near) + let maya = usable.contains(.maya) + switch (near, maya) { + case (true, true): return .multiple + case (true, false): return .near + case (false, true): return .maya + case (false, false): return nil + } + } + + /// SwapKit provider names this route provider stands for in a quote's `providers` filter. + var swapKitProviders: [String] { + switch self { + case .near: return [SwapKitConstants.providerNear] + case .maya: return SwapKitConstants.mayaProviders + case .multiple: return [SwapKitConstants.providerNear] + SwapKitConstants.mayaProviders + } + } + + /// The route provider a SwapKit provider name belongs to, or `nil` for one this wallet does not route through. + init?(swapKitProvider name: String) { + let upper = name.uppercased() + if upper == SwapKitConstants.providerNear { + self = .near + } else if SwapKitConstants.mayaProviders.contains(upper) { + self = .maya + } else { + return nil + } + } +} + +// MARK: - SwapRouteAvailability + +/// Live per-provider route availability for the swap coin pickers, probed with forced quotes. +/// +/// Shared (`shared`) because every swap flow builds its own `SwapKitSwapProvider` +/// (`SwapBackend.makeProvider()`), while availability is a fact about SwapKit, not about one flow: +/// a second opening of a picker reuses the answers instead of re-probing every coin. Tests build +/// their own instance. +/// +/// Probing rules: +/// - At most `maxInFlight` quotes are in flight across all directions, so opening a picker never +/// fires a burst of ~200 requests. +/// - NEAR is checked on a couple of liquid sentinel coins first. If two of them have no route and +/// none routes, NEAR is treated as down for every coin of that direction and no per-coin NEAR +/// probes run; if one routes, every NEAR-capable coin is probed on its own. Halted or +/// inconclusive sentinels keep the previous verdict. +/// - Maya is probed per coin: its halts are per chain, so one coin says nothing about the next. +/// +/// Answers age in two steps: after `probeAfter` (`nearDownProbeAfter` for a NEAR outage) a refresh +/// asks again, but the last conclusive answer keeps being read until the new one arrives or +/// `forgetAfter` passes — so a label does not flip back to the static guess between the two. +/// Inconclusive answers (`.unknown`) are never stored: they would only block the next attempt. +@MainActor +final class SwapRouteAvailability { + static let shared = SwapRouteAvailability() + + /// Runs one forced quote for `asset` against `provider` in `direction` and classifies it. + typealias Probe = @MainActor (_ asset: String, _ provider: RouteProvider, _ direction: SwapDirection) async -> LiveRouteState + + enum NearVerdict: Equatable { + case up + case down + } + + /// Liquid NEAR-capable coins on different chains. The third is asked only when one of the first + /// two gave no conclusive answer. + static let nearSentinels = ["BTC.BTC", "ETH.ETH", "SOL.SOL"] + + /// Emits the direction whose availability changed. + let changes = PassthroughSubject() + + private struct Key: Hashable { + let direction: SwapDirection + let provider: RouteProvider + let asset: String + + init(_ direction: SwapDirection, _ provider: RouteProvider, _ asset: String) { + self.direction = direction + self.provider = provider + self.asset = asset.uppercased() + } + } + + private struct Entry { + let state: LiveRouteState + let checkedAt: Date + } + + private struct Verdict { + let verdict: NearVerdict + /// When this verdict was last confirmed — what makes it due for a re-check. + let checkedAt: Date + /// When the verdict last changed to this value. A coin's own answer newer than this wins + /// over an outage, even after the outage was re-confirmed. + let since: Date + } + + private let probeAfter: TimeInterval + private let nearDownProbeAfter: TimeInterval + private let forgetAfter: TimeInterval + private let now: () -> Date + + private var entries: [Key: Entry] = [:] + /// When a key last got an inconclusive answer, which is not stored as an answer. It is not + /// asked again before `nearDownProbeAfter`, so an upstream outage is not polled every tick. + private var inconclusiveAt: [Key: Date] = [:] + /// When a sentinel round last ended without a verdict, per direction; same back-off. + private var inconclusiveRoundAt: [SwapDirection: Date] = [:] + private var nearVerdicts: [SwapDirection: Verdict] = [:] + private var refreshing: Set = [] + private var refreshWaiters: [SwapDirection: [CheckedContinuation]] = [:] + private var freePermits: Int + private let workerCount: Int + private var permitWaiters: [CheckedContinuation] = [] + + init( + probeAfter: TimeInterval = 600, + nearDownProbeAfter: TimeInterval = 120, + forgetAfter: TimeInterval = 1800, + maxInFlight: Int = 2, + now: @escaping () -> Date = Date.init + ) { + self.probeAfter = probeAfter + self.nearDownProbeAfter = nearDownProbeAfter + self.forgetAfter = forgetAfter + self.freePermits = maxInFlight + self.workerCount = maxInFlight + self.now = now + } + + // MARK: Reading + + /// The last conclusive state of `provider` for `asset`, or `nil` when nothing usable is known. + /// A NEAR outage applies to every coin, except one whose own answer is newer than the outage. + /// + /// `freshOnly` ignores answers that are due for a re-probe — for building a real quote, which + /// must not leave out a provider on an answer the picker has not refreshed for a while. + func state(of provider: RouteProvider, for asset: String, direction: SwapDirection, freshOnly: Bool = false) -> LiveRouteState? { + let key = Key(direction, provider, asset) + let entry = readableEntry(key).flatMap { freshOnly && now().timeIntervalSince($0.checkedAt) >= probeAfter ? nil : $0 } + let verdict = readableVerdict(direction).flatMap { freshOnly && isDue($0) ? nil : $0 } + if provider == .near, let verdict, verdict.verdict == .down { + if let entry, entry.checkedAt > verdict.since { + return entry.state + } + return .noRoute + } + return entry?.state + } + + /// The providers of `capable` that can carry `asset` now. A provider with no known answer stays in. + func usableProviders( + for asset: String, + capable: Set, + direction: SwapDirection, + freshOnly: Bool = false + ) -> Set { + capable.filter { state(of: $0, for: asset, direction: direction, freshOnly: freshOnly)?.isUsable ?? true } + } + + /// The last NEAR verdict for `direction` the sentinels gave, while it is still readable. + func nearVerdict(for direction: SwapDirection) -> NearVerdict? { + readableVerdict(direction)?.verdict + } + + // MARK: Writing + + /// Records a conclusive answer learned outside the probes (a quote on the address screen, say). + /// An inconclusive one is dropped. + func record(_ state: LiveRouteState, provider: RouteProvider, asset: String, direction: SwapDirection) { + guard state != .unknown else { return } + store(state, for: Key(direction, provider, asset)) + } + + // MARK: Probing + + /// Probes what is due for `assets` (in the given order) and reports changes on `changes`. + /// One refresh runs per direction: a second one waits for the first to finish (a cancelled + /// one finishes once its one or two in-flight requests return) and then probes what is still + /// due. Cancelling the calling task stops it: queued probes are dropped without a request. + func refresh( + assets: [String], + direction: SwapDirection, + capable: (String) -> Set, + probe: @escaping Probe + ) async { + while refreshing.contains(direction) { + await withCheckedContinuation { refreshWaiters[direction, default: []].append($0) } + } + guard !Task.isCancelled else { return } + refreshing.insert(direction) + defer { + refreshing.remove(direction) + refreshWaiters.removeValue(forKey: direction)?.forEach { $0.resume() } + } + + var probeNearPerCoin = false + if assets.contains(where: { capable($0).contains(.near) }) { + probeNearPerCoin = await resolveNearVerdict(direction: direction, probe: probe) == .up + } + + var jobs: [(key: Key, asset: String)] = [] + for asset in assets { + let providers = capable(asset) + for provider in [RouteProvider.maya, .near] where providers.contains(provider) { + if provider == .near, !probeNearPerCoin { continue } + let key = Key(direction, provider, asset) + guard isDue(key) else { continue } + jobs.append((key, asset)) + } + } + guard !jobs.isEmpty, !Task.isCancelled else { return } + + // As many workers as in-flight permits pull jobs in order, so a long list does not park a + // waiting task per coin. + let queue = JobQueue(jobs) + await withTaskGroup(of: Void.self) { group in + for _ in 0.. (key: Key, asset: String)? { + guard index < jobs.count else { return nil } + defer { index += 1 } + return jobs[index] + } + } + + /// Asks `provider` about `asset` now, whatever is cached — for confirming an answer that came + /// from a quote the probes cannot vouch for (one to a user-typed address). + @discardableResult + func probeNow(asset: String, provider: RouteProvider, direction: SwapDirection, probe: Probe) async -> LiveRouteState { + await probeOne(Key(direction, provider, asset), asset: asset, force: true, probe: probe) + } + + /// Re-asks the sentinels once the last verdict is due (2 minutes after an outage, 10 after + /// "up"), bypassing their cached answers. They are asked until one routes or two give a + /// conclusive no; the third only stands in for an inconclusive one. Two conclusive no-routes + /// and none routing → NEAR is down. Fewer keeps the previous verdict. + private func resolveNearVerdict(direction: SwapDirection, probe: @escaping Probe) async -> NearVerdict? { + if let verdict = readableVerdict(direction), !isDue(verdict) { + return verdict.verdict + } + if let last = inconclusiveRoundAt[direction], now().timeIntervalSince(last) < nearDownProbeAfter { + return readableVerdict(direction)?.verdict + } + + var noRoutes = 0 + for sentinel in Self.nearSentinels where noRoutes < 2 { + if Task.isCancelled { + return readableVerdict(direction)?.verdict + } + let state = await probeOne(Key(direction, .near, sentinel), asset: sentinel, force: true, probe: probe) + if state == .available { + inconclusiveRoundAt[direction] = nil + setNearVerdict(.up, direction: direction) + return .up + } + // Only a no-route says something about NEAR as a whole; a halt is about that chain. + if state == .noRoute { + noRoutes += 1 + } + } + + guard noRoutes >= 2 else { + inconclusiveRoundAt[direction] = now() + return readableVerdict(direction)?.verdict + } + inconclusiveRoundAt[direction] = nil + setNearVerdict(.down, direction: direction) + return .down + } + + private func setNearVerdict(_ verdict: NearVerdict, direction: SwapDirection) { + let previous = readableVerdict(direction) + let since = previous?.verdict == verdict ? previous?.since ?? now() : now() + nearVerdicts[direction] = Verdict(verdict: verdict, checkedAt: now(), since: since) + let previousVerdict = previous?.verdict + if previousVerdict != verdict { + changes.send(direction) + } + } + + /// One probe under the in-flight limit. Unless `force`d, an answer that is not yet due is + /// reused — checked again after waiting for a permit, since another writer may have answered + /// meanwhile. A cancelled task gets `.unknown` without a request. + private func probeOne(_ key: Key, asset: String, force: Bool, probe: Probe) async -> LiveRouteState { + if !force, !isDue(key) { + return readableEntry(key)?.state ?? .unknown + } + await acquirePermit() + defer { releasePermit() } + if Task.isCancelled { + return .unknown + } + if !force, !isDue(key) { + return readableEntry(key)?.state ?? .unknown + } + let state = await probe(asset, key.provider, key.direction) + if state == .unknown { + inconclusiveAt[key] = now() + } else { + inconclusiveAt[key] = nil + store(state, for: key) + } + return state + } + + private func store(_ state: LiveRouteState, for key: Key) { + let previous = self.state(of: key.provider, for: key.asset, direction: key.direction) + entries[key] = Entry(state: state, checkedAt: now()) + if previous != self.state(of: key.provider, for: key.asset, direction: key.direction) { + changes.send(key.direction) + } + } + + // MARK: Ageing + + private func readableEntry(_ key: Key) -> Entry? { + guard let entry = entries[key], now().timeIntervalSince(entry.checkedAt) < forgetAfter else { return nil } + return entry + } + + private func readableVerdict(_ direction: SwapDirection) -> Verdict? { + guard let verdict = nearVerdicts[direction], now().timeIntervalSince(verdict.checkedAt) < forgetAfter else { return nil } + return verdict + } + + private func isDue(_ key: Key) -> Bool { + if let last = inconclusiveAt[key], now().timeIntervalSince(last) < nearDownProbeAfter { + return false + } + guard let entry = entries[key] else { return true } + return now().timeIntervalSince(entry.checkedAt) >= probeAfter + } + + private func isDue(_ verdict: Verdict) -> Bool { + let interval = verdict.verdict == .down ? nearDownProbeAfter : probeAfter + return now().timeIntervalSince(verdict.checkedAt) >= interval + } + + // MARK: In-flight limit + + private func acquirePermit() async { + if freePermits > 0 { + freePermits -= 1 + return + } + await withCheckedContinuation { permitWaiters.append($0) } + } + + private func releasePermit() { + if permitWaiters.isEmpty { + freePermits += 1 + } else { + // The permit passes straight to the next waiter; `freePermits` stays as it is. + permitWaiters.removeFirst().resume() + } + } +} diff --git a/DashWallet/Sources/UI/Swap/Buy/RefundAddress/RefundAddressView.swift b/DashWallet/Sources/UI/Swap/Buy/RefundAddress/RefundAddressView.swift index 31460e7480..80db715592 100644 --- a/DashWallet/Sources/UI/Swap/Buy/RefundAddress/RefundAddressView.swift +++ b/DashWallet/Sources/UI/Swap/Buy/RefundAddress/RefundAddressView.swift @@ -134,13 +134,12 @@ private final class RefundAddressPreviewSwapProvider: SwapProvider { var displayName: String { "Preview" } var usesGenericFeeLabel: Bool { true } var buildsSwapKitDeposit: Bool { true } - var onBuyRoutabilityChanged: (() -> Void)? func fetchPools() async throws -> [SwapPool] { [] } func fetchInboundAddresses() async throws -> [SwapInboundAddress] { [] } func fetchPools(direction: SwapDirection) async throws -> [SwapPool] { [] } - func networkLabels(for pools: [SwapPool]) async -> [String: String] { [:] } - func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool]) async -> Set { [] } + func networkLabels(for pools: [SwapPool], direction: SwapDirection) async -> [String: String] { [:] } + func haltedAssets(from inboundAddresses: [SwapInboundAddress], pools: [SwapPool], direction: SwapDirection) async -> Set { [] } func validateAddress(destination: String, toAsset: String) async -> String? { nil } func fetchQuote(dashSatoshis: Int64, toAsset: String, destination: String) async throws -> SwapQuoteResult { SwapQuoteResult(error: nil, expectedAmountOut: "1000000", fees: nil, inboundAddress: nil, memo: nil, executionNetwork: nil) diff --git a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift index 7d585df5e6..590cbed0be 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift @@ -79,7 +79,10 @@ struct SelectCoinView: View { } .animation(.easeInOut(duration: 0.3), value: viewModel.showHaltedToast) .dexOfflineToast(isOnline: viewModel.isOnline) - .task { await viewModel.loadCoins() } + .task { + await viewModel.loadCoins() + await viewModel.keepRouteAvailabilityFresh() + } } // MARK: - Main Content diff --git a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift index 1542946db1..1f24f832fa 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift @@ -35,28 +35,46 @@ struct CoinDisplayItem: Identifiable { @MainActor class SelectCoinViewModel: ObservableObject { - private var swapProvider: SwapProvider + private let swapProvider: SwapProvider private let direction: SwapDirection private var lastLoadedCoinSignature: [String] = [] + /// What the last successful load fetched, so a live-availability change re-labels the list + /// without fetching pools again. + private var loadedPools: [SwapPool]? + private var loadedInboundAddresses: [SwapInboundAddress] = [] + /// The loaded pools in display order — the order the live checks walk. + private var displayedPools: [SwapPool] = [] private let networkStatus: NetworkStatusProviding private var networkCancellable: AnyCancellable? + private var routeAvailabilityCancellable: AnyCancellable? + /// The halted toast is shown once per picker: live answers keep re-rendering the list, and a + /// dismissed toast must not come back with them. + private var haltedToastShown = false + /// Identifies the `keepRouteAvailabilityFresh` run of the picker on screen; 0 when none runs. + /// A run that ends after a newer one started must not stop the newer one's checks. + private var routeFreshnessRun = 0 + private var routeFreshnessRuns = 0 + /// Identifies the latest render, so a slower older one does not publish over it. + private var renderGeneration = 0 + + /// How often the live checks are re-run while the picker is on screen. Only answers that are due + /// are asked again, so most ticks send nothing. + private let routeRefreshInterval: UInt64 = 60_000_000_000 init(swapProvider: SwapProvider = MayaSwapProvider(), direction: SwapDirection = .sell, networkStatus: NetworkStatusProviding = NetworkStatusService.shared) { self.swapProvider = swapProvider self.direction = direction self.networkStatus = networkStatus self.isOnline = networkStatus.isOnline - if direction == .buy { - self.swapProvider.onBuyRoutabilityChanged = { [weak self] in - Task { await self?.loadCoins(force: true) } + // Answers arrive one by one while a refresh runs; re-render once they pause. + routeAvailabilityCancellable = swapProvider.routeAvailabilityChanges + .filter { $0 == direction } + .debounce(for: .milliseconds(300), scheduler: DispatchQueue.main) + .sink { [weak self] _ in + Task { await self?.reloadRouteAvailability() } } - } subscribeToNetworkStatus() } - - deinit { - swapProvider.onBuyRoutabilityChanged = nil - } // MARK: - Published State @Published var coins: [CoinDisplayItem] = [] @@ -127,33 +145,89 @@ class SelectCoinViewModel: ObservableObject { // would then filter out every pool via inboundChains. let pools = try await swapProvider.fetchPools(direction: direction) let inboundAddresses = try await swapProvider.fetchInboundAddresses() - - let fiatCurrency = App.fiatCurrency - let formatter = makePriceFormatter(for: fiatCurrency) - let networkLabels = await swapProvider.networkLabels(for: pools) - let haltedAssets = await swapProvider.haltedAssets(from: inboundAddresses, pools: pools) - let items = makeCoinItems( - pools: pools, - inboundAddresses: inboundAddresses, - fiatCurrency: fiatCurrency, - formatter: formatter, - networkLabels: networkLabels, - haltedAssets: haltedAssets - ) - - let disambiguated = appendChainLabels(items) - let sorted = sortCoins(disambiguated) - let signature = coinSignature(sorted) - guard signature != lastLoadedCoinSignature else { return } - lastLoadedCoinSignature = signature - coins = sorted - hasHaltedCoins = sorted.contains { $0.isHalted } - showHaltedToast = hasHaltedCoins + loadedPools = pools + loadedInboundAddresses = inboundAddresses + let sorted = await render(pools: pools, inboundAddresses: inboundAddresses) + let poolsByAsset = Dictionary(pools.map { ($0.asset.uppercased(), $0) }, uniquingKeysWith: { first, _ in first }) + displayedPools = sorted.compactMap { poolsByAsset[$0.coin.swapAsset.uppercased()] } + // A load that lands while the picker is on screen (after reconnecting, say) starts the + // checks now rather than at the next tick. + if routeFreshnessRun != 0 { + swapProvider.refreshRouteAvailability(for: displayedPools, direction: direction) + } } catch { errorMessage = error.localizedDescription } } + /// Keeps the live route checks running while the picker is on screen: once now, then every + /// `routeRefreshInterval`. Runs until the calling task is cancelled — the view's `.task`, which + /// SwiftUI cancels when the picker leaves the screen — and then stops the checks, so they do + /// not spend the SwapKit quota while the user is on another screen. + func keepRouteAvailabilityFresh() async { + // A `.task` cancelled while its load was still running must not stop the refresh that the + // re-shown picker's own `.task` has started meanwhile. + guard !Task.isCancelled else { return } + routeFreshnessRuns += 1 + let run = routeFreshnessRuns + routeFreshnessRun = run + defer { + if routeFreshnessRun == run { + routeFreshnessRun = 0 + swapProvider.stopRouteAvailabilityRefresh(direction: direction) + } + } + while !Task.isCancelled { + if !displayedPools.isEmpty { + swapProvider.refreshRouteAvailability(for: displayedPools, direction: direction) + } + try? await Task.sleep(nanoseconds: routeRefreshInterval) + } + } + + /// Re-labels the loaded coins after live route answers changed. Nothing loaded yet (or a failed + /// load) means there is nothing to re-label: the next load renders the current answers. + private func reloadRouteAvailability() async { + guard let pools = loadedPools, errorMessage == nil else { return } + await render(pools: pools, inboundAddresses: loadedInboundAddresses) + } + + /// Builds the rows for `pools` with the provider's current labels and halts and publishes them + /// when they changed. Returns the rows in display order. + @discardableResult + private func render(pools: [SwapPool], inboundAddresses: [SwapInboundAddress]) async -> [CoinDisplayItem] { + renderGeneration += 1 + let generation = renderGeneration + let fiatCurrency = App.fiatCurrency + let formatter = makePriceFormatter(for: fiatCurrency) + let networkLabels = await swapProvider.networkLabels(for: pools, direction: direction) + let haltedAssets = await swapProvider.haltedAssets(from: inboundAddresses, pools: pools, direction: direction) + let items = makeCoinItems( + pools: pools, + inboundAddresses: inboundAddresses, + fiatCurrency: fiatCurrency, + formatter: formatter, + networkLabels: networkLabels, + haltedAssets: haltedAssets + ) + + let disambiguated = appendChainLabels(items) + let sorted = sortCoins(disambiguated) + + let signature = coinSignature(sorted) + guard generation == renderGeneration, signature != lastLoadedCoinSignature else { return sorted } + lastLoadedCoinSignature = signature + coins = sorted + hasHaltedCoins = sorted.contains { $0.isHalted } + if !hasHaltedCoins { + showHaltedToast = false + } else if !haltedToastShown { + haltedToastShown = true + showHaltedToast = true + } + return sorted + } + // MARK: - Private: Item Creation private func makeCoinItems( diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 48cf01caf2..e252f68377 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -198,9 +198,9 @@ final class SwapKitErrorCopyTests: XCTestCase { // MARK: - Production boundary /// Drives the two functions that apply the rules above to a real SwapKit reply — -/// `decodeQuoteError(from:)` for a non-2xx body and `routability(from:)` for the Buy picker's -/// probe — so reverting either one (prose before the code, or pruning on a top-level -/// `noRoutesFound`) fails here even while every helper test still passes. +/// `decodeQuoteError(from:)` for a non-2xx body and `LiveRouteState.classify` for the coin +/// pickers' live probes — so reverting either one fails here even while every helper test still +/// passes. @MainActor final class SwapKitQuoteBoundaryTests: XCTestCase { private func statusError(_ json: String, statusCode: Int = 404) -> Error { @@ -251,45 +251,186 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertNil(SwapKitSwapProvider.decodeQuoteError(from: URLError(.notConnectedToInternet))) } - // MARK: routability(from:) + // MARK: LiveRouteState.classify - func testAnyRouteIsConclusivelyRoutable() throws { + private func decoded(_ json: String) throws -> SwapKitQuoteResponse { + try JSONDecoder().decode(SwapKitQuoteResponse.self, from: Data(json.utf8)) + } + + func testAnyRouteIsAvailable() throws { let recorded = try JSONDecoder().decode(SwapKitQuoteResponse.self, from: loadFixture(named: "swapkit_quote_response")) // The fixture also carries a THORCHAIN `noRoutesFound`; a route elsewhere outranks it. - XCTAssertEqual(SwapKitSwapProvider.routability(from: recorded), .routable) + XCTAssertEqual(LiveRouteState.classify(recorded), .available) + } + + /// Recorded 2026-11-02, DASH → ETH.USDT forced to Maya while Maya's ETH trading was halted: + /// HTTP 200, no routes, the halt only in `providerErrors`. + func testMayaHaltOnA200IsHalted() throws { + let halted = try decoded(#""" + {"quoteId":"ab4e61a9-6366-47a6-a7e3-46493bf5f519","createdAt":"2026-11-02T15:42:32.214Z","routes":[], + "providerErrors":[{"provider":"MAYACHAIN_STREAMING","errorCode":"swapHalted","message":"swap is halted"}]} + """#) + XCTAssertEqual(LiveRouteState.classify(halted), .halted) } - /// The ambiguous case: SwapKit gives a top-level `noRoutesFound` for an amount far below the - /// floor as well as for a pair it cannot carry, so it must not prune the picker. - func testTopLevelNoRouteLeavesTheQuestionOpen() { - let noRoute = response(error: "noRoutesFound", message: "No routes found for DASH.DASH -> BTC.BTC") - XCTAssertNil(SwapKitSwapProvider.routability(from: noRoute)) + /// Recorded 2026-11-02, DASH → ARB.USDT: the 404 body the address screen turned into + /// "check your connection". A probe is sized at ~$50, so the top-level form is a real no-route. + func testTopLevelNoRouteIsNoRoute() throws { + let noRoute = try decoded(#""" + {"error":"noRoutesFound","message":"No routes found for DASH.DASH -> ARB.USDT-0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9", + "data":{"sellAsset":"DASH.DASH","buyAsset":"ARB.USDT-0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9"}} + """#) + XCTAssertEqual(LiveRouteState.classify(noRoute), .noRoute) } - func testAbsentOrBlankProviderErrorsLeaveTheQuestionOpen() { - XCTAssertNil(SwapKitSwapProvider.routability(from: response())) - XCTAssertNil(SwapKitSwapProvider.routability(from: response(providerErrors: []))) - XCTAssertNil(SwapKitSwapProvider.routability(from: response(providerErrors: [providerError(" ", message: "")]))) + /// Next to a provider's upstream failure, the top-level code is SwapKit summing up a failed + /// request, not the provider's verdict. + func testTopLevelNoRouteBesideAnUpstreamFailureIsUnknown() { + let blip = response(providerErrors: [providerError("apiRequestFailed")], error: "noRoutesFound") + XCTAssertEqual(LiveRouteState.classify(blip), .unknown) } - func testProviderNoRouteIsConclusivelyNotRoutable() { - let noRoute = response(providerErrors: [providerError("noRoutesFound")]) - XCTAssertEqual(SwapKitSwapProvider.routability(from: noRoute), .notRoutable) + func testProviderNoRouteIsNoRoute() { + XCTAssertEqual(LiveRouteState.classify(response(providerErrors: [providerError("noRoutesFound")])), .noRoute) } /// The probe amount was under the floor — evidence the route exists, not that it does not. - func testProviderBelowMinimumCountsAsRoutable() { + func testProviderBelowMinimumCountsAsAvailable() { let tooSmall = response(providerErrors: [ providerError("sellAssetAmountTooSmall", message: "Min amount is 0.175 DASH.DASH"), ]) - XCTAssertEqual(SwapKitSwapProvider.routability(from: tooSmall), .routable) + XCTAssertEqual(LiveRouteState.classify(tooSmall), .available) + } + + /// Both Maya flavours answer one probe: one under its floor means Maya can carry the coin, even + /// while the other reports a halt. + func testBelowMinimumOutranksAHaltFromTheOtherFlavour() { + let mixed = response(providerErrors: [ + SwapKitProviderError(provider: "MAYACHAIN_STREAMING", errorCode: "swapHalted", message: nil), + SwapKitProviderError(provider: "MAYACHAIN", errorCode: "sellAssetAmountTooSmall", message: nil), + ]) + XCTAssertEqual(LiveRouteState.classify(mixed), .available) + } + + /// One Maya flavour failing upstream leaves the question open even if the other has no route. + func testAnInconclusiveFlavourOutranksTheOthersNoRoute() { + let mixed = response(providerErrors: [ + SwapKitProviderError(provider: "MAYACHAIN", errorCode: "apiRequestFailed", message: nil), + SwapKitProviderError(provider: "MAYACHAIN_STREAMING", errorCode: "noRoutesFound", message: nil), + ]) + XCTAssertEqual(LiveRouteState.classify(mixed), .unknown) + } + + /// A quote that asked NEAR and Maya at once: each is judged on its own errors. + func testPerProviderSplitsAJointQuote() { + let joint = response(providerErrors: [ + SwapKitProviderError(provider: "NEAR", errorCode: "apiRequestFailed", message: nil), + SwapKitProviderError(provider: "MAYACHAIN_STREAMING", errorCode: "swapHalted", message: nil), + ]) + XCTAssertEqual(LiveRouteState.classifyPerProvider(joint, requested: [.near, .maya]), [.near: .unknown, .maya: .halted]) + } + + func testPerProviderReadsABareTopLevelNoRouteAsEveryonesAnswer() throws { + let bare = try decoded(#"{"error":"noRoutesFound","message":"No routes found"}"#) + XCTAssertEqual(LiveRouteState.classifyPerProvider(bare, requested: [.near, .maya]), [.near: .noRoute, .maya: .noRoute]) + } + + func testPerProviderCreditsTheRoutingProvider() throws { + let recorded = try JSONDecoder().decode(SwapKitQuoteResponse.self, from: loadFixture(named: "swapkit_quote_response")) + let providers = Set(recorded.routes!.flatMap { $0.providers }.compactMap { RouteProvider(swapKitProvider: $0) }) + let states = LiveRouteState.classifyPerProvider(recorded, requested: providers) + XCTAssertFalse(providers.isEmpty) + XCTAssertTrue(states.values.allSatisfy { $0 == .available }) + } + + // MARK: SwapKitSwapProvider.addressCheck + + private func pe(_ provider: String, _ code: String) -> SwapKitProviderError { + SwapKitProviderError(provider: provider, errorCode: code, message: nil) + } + + func testAddressCheckPassesOnAnyRoute() throws { + let recorded = try JSONDecoder().decode(SwapKitQuoteResponse.self, from: loadFixture(named: "swapkit_quote_response")) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(recorded, requested: [.near, .maya]), .pass) + } + + /// The bug report: DASH → ARB.USDT, 404 `noRoutesFound` for every provider asked. + func testAddressCheckReAsksAfterABareNoRoute() throws { + let bare = try decoded(#"{"error":"noRoutesFound","message":"No routes found for DASH.DASH -> ARB.USDT-0xFd08"}"#) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(bare, requested: [.near, .maya]), .confirmNoRoute([.near, .maya])) + } + + /// Maya halted, NEAR answered nothing conclusive: NEAR may carry it, so the user goes on. + func testAddressCheckPassesWhenOneProviderIsHaltedAndTheOtherInconclusive() { + let joint = response(providerErrors: [pe("NEAR", "apiRequestFailed"), pe("MAYACHAIN_STREAMING", "swapHalted")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(joint, requested: [.near, .maya]), .pass) + } + + /// NEAR without a route, Maya halted: nobody can carry it; only NEAR's no-route is re-asked. + func testAddressCheckReAsksOnlyTheNoRouteProvider() { + let joint = response(providerErrors: [pe("NEAR", "noRoutesFound"), pe("MAYACHAIN_STREAMING", "swapHalted")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(joint, requested: [.near, .maya]), .confirmNoRoute([.near])) + } + + /// ETH.USDT on 2026-11-02 when only Maya was asked: halted, nothing to re-ask. + func testAddressCheckStopsAHaltedOnlyProvider() { + let halted = response(providerErrors: [pe("MAYACHAIN_STREAMING", "swapHalted")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(halted, requested: [.maya]), .unavailable) + } + + func testAddressCheckRefusesAnAddressErrorEvenInsideProviderErrors() { + let refused = response(providerErrors: [pe("NEAR", "invalidDestinationAddress")], error: "noRoutesFound") + XCTAssertEqual(SwapKitSwapProvider.addressCheck(refused, requested: [.near]), .refused("invalidDestinationAddress"), + "the only provider asked refused it") + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "validation_error"), requested: [.near]), .refused("validation_error")) + } + + func testAddressCheckRefusesACoinSwapKitRefuses() { + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "blackListAsset"), requested: [.near, .maya]), .refused("blackListAsset")) + } + + /// One provider refusing the address does not stop a coin another provider may still carry. + func testAddressCheckPassesWhenOnlyOneProviderRefuses() { + let joint = response(providerErrors: [pe("MAYACHAIN_STREAMING", "invalidDestinationAddress"), pe("NEAR", "apiRequestFailed")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(joint, requested: [.near, .maya]), .pass) + let both = response(providerErrors: [pe("MAYACHAIN_STREAMING", "invalidDestinationAddress"), pe("NEAR", "noRoutesFound")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(both, requested: [.near, .maya]), .refused("invalidDestinationAddress")) + } + + /// An upstream failure is not the user's to fix on this screen. + func testAddressCheckPassesAnUpstreamFailure() { + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "apiRequestFailed"), requested: [.near, .maya]), .pass) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(providerErrors: [pe("NEAR", "apiRequestFailed")]), requested: [.near]), .pass) + } + + /// Without a classification no providers were named; availability is not judged. + func testAddressCheckWithoutRequestedProvidersOnlyRefusesRequestErrors() { + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "noRoutesFound"), requested: []), .pass) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "isSanctionedAddress"), requested: []), .refused("isSanctionedAddress")) + } + + func testInconclusiveAnswersAreUnknown() { + XCTAssertEqual(LiveRouteState.classify(response()), .unknown) + XCTAssertEqual(LiveRouteState.classify(response(providerErrors: [])), .unknown) + XCTAssertEqual(LiveRouteState.classify(response(providerErrors: [providerError(" ", message: "")])), .unknown) + XCTAssertEqual(LiveRouteState.classify(response(providerErrors: [providerError("apiRequestFailed")])), .unknown) + XCTAssertEqual(LiveRouteState.classify(response(error: "validation_error")), .unknown) + } + + func testOnlyAConclusiveNegativeMakesAProviderUnusable() { + XCTAssertTrue(LiveRouteState.available.isUsable) + XCTAssertTrue(LiveRouteState.unknown.isUsable) + XCTAssertFalse(LiveRouteState.halted.isUsable) + XCTAssertFalse(LiveRouteState.noRoute.isUsable) } - func testProviderUpstreamFailureLeavesTheQuestionOpen() { - let upstream = response(providerErrors: [providerError("apiRequestFailed")]) - XCTAssertNil(SwapKitSwapProvider.routability(from: upstream)) + func testHaltCodesAreMatchedAsAFamily() { + XCTAssertTrue(SwapKitErrorCopy.isHalted("swapHalted")) + XCTAssertTrue(SwapKitErrorCopy.isHalted("tradingHalted: ETH")) + XCTAssertFalse(SwapKitErrorCopy.isHalted("noRoutesFound")) + XCTAssertFalse(SwapKitErrorCopy.isHalted(nil)) } } diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift new file mode 100644 index 0000000000..89557b424f --- /dev/null +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -0,0 +1,482 @@ +// +// SwapRouteAvailabilityTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import Combine +import XCTest + +/// Scripted probe answers, keyed by provider and asset; anything unscripted routes. +@MainActor +private final class ProbeScript { + var answers: [String: LiveRouteState] = [:] + private(set) var calls: [String] = [] + private(set) var maxInFlight = 0 + private var inFlight = 0 + /// Holds each probe open for a moment so concurrent probes overlap and the limit is observable. + var holdNanoseconds: UInt64 = 0 + /// When closed, every probe waits until `openGate()`. + private var gateClosed = false + private var gateWaiters: [CheckedContinuation] = [] + + func closeGate() { gateClosed = true } + + func openGate() { + gateClosed = false + gateWaiters.forEach { $0.resume() } + gateWaiters.removeAll() + } + + func set(_ state: LiveRouteState, _ provider: RouteProvider, _ asset: String) { + answers[Self.key(provider, asset)] = state + } + + func calls(to provider: RouteProvider) -> [String] { + let prefix = "\(provider)|" + return calls.filter { $0.hasPrefix(prefix) }.map { String($0.dropFirst(prefix.count)) } + } + + var probe: SwapRouteAvailability.Probe { + { [unowned self] asset, provider, _ in + let key = Self.key(provider, asset) + self.calls.append(key) + self.inFlight += 1 + self.maxInFlight = max(self.maxInFlight, self.inFlight) + if self.holdNanoseconds > 0 { + try? await Task.sleep(nanoseconds: self.holdNanoseconds) + } + if self.gateClosed { + await withCheckedContinuation { self.gateWaiters.append($0) } + } + self.inFlight -= 1 + return self.answers[key] ?? .available + } + } + + private static func key(_ provider: RouteProvider, _ asset: String) -> String { + "\(provider)|\(asset.uppercased())" + } +} + +@MainActor +final class SwapRouteAvailabilityTests: XCTestCase { + private let both: Set = [.near, .maya] + + private var clock = Date(timeIntervalSince1970: 1_800_000_000) + private var script: ProbeScript! + private var store: SwapRouteAvailability! + + override func setUp() async throws { + clock = Date(timeIntervalSince1970: 1_800_000_000) + script = ProbeScript() + store = SwapRouteAvailability(now: { [unowned self] in self.clock }) + } + + /// Refreshes Sell for `capability` (asset → capable providers) in the dictionary's key order. + private func refresh(_ capability: KeyValuePairs>, direction: SwapDirection = .sell) async { + let map = Dictionary(capability.map { ($0.key.uppercased(), $0.value) }, uniquingKeysWith: { a, _ in a }) + await store.refresh( + assets: capability.map { $0.key }, + direction: direction, + capable: { map[$0.uppercased()] ?? [] }, + probe: script.probe + ) + } + + private func label(_ asset: String, capable: Set, direction: SwapDirection = .sell) -> RouteProvider? { + RouteProvider.label(forUsable: store.usableProviders(for: asset, capable: capable, direction: direction)) + } + + // MARK: Labels + + func testLabelFollowsTheUsableProviders() { + XCTAssertEqual(RouteProvider.label(forUsable: [.near, .maya]), .multiple) + XCTAssertEqual(RouteProvider.label(forUsable: [.near]), .near) + XCTAssertEqual(RouteProvider.label(forUsable: [.maya]), .maya) + XCTAssertNil(RouteProvider.label(forUsable: [])) + } + + func testNothingKnownKeepsTheStaticCapability() { + XCTAssertEqual(label("BTC.BTC", capable: both), .multiple) + XCTAssertEqual(label("MAYA.CACAO", capable: [.maya]), .maya) + } + + // MARK: NEAR and Maya, each up or down + + func testBothProvidersRoutingIsMultiple() async { + await refresh(["ETH.USDT": both]) + + XCTAssertEqual(label("ETH.USDT", capable: both), .multiple) + } + + /// NEAR up, Maya halted for the coin's chain (ETH trading paused on Maya, 2026-11-02). + func testNearUpMayaHaltedLeavesNear() async { + script.set(.halted, .maya, "ETH.USDT") + + await refresh(["ETH.USDT": both]) + + XCTAssertEqual(label("ETH.USDT", capable: both), .near) + } + + /// NEAR up in general but without a route for this coin, Maya routing it. + func testNearNoRouteForTheCoinMayaUpLeavesMaya() async { + script.set(.noRoute, .near, "ARB.USDT") + + await refresh(["ARB.USDT": both]) + + XCTAssertEqual(label("ARB.USDT", capable: both), .maya) + } + + /// NEAR down for DASH (every sentinel without a route, 2026-11-02), Maya routing. + func testNearDownMayaUpLeavesMayaAndHaltsNearOnlyCoins() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + + await refresh(["MAYA.CACAO": [.maya], "ARB.ETH": both, "SOL.SOL": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(label("ARB.ETH", capable: both), .maya) + XCTAssertEqual(label("MAYA.CACAO", capable: [.maya]), .maya) + XCTAssertTrue(store.usableProviders(for: "SOL.SOL", capable: [.near], direction: .sell).isEmpty) + } + + func testNearDownMayaHaltedHaltsTheCoin() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.set(.halted, .maya, "ETH.USDT") + script.set(.halted, .maya, "MAYA.CACAO") + + await refresh(["ETH.USDT": both, "MAYA.CACAO": [.maya]]) + + XCTAssertTrue(store.usableProviders(for: "ETH.USDT", capable: both, direction: .sell).isEmpty) + XCTAssertTrue(store.usableProviders(for: "MAYA.CACAO", capable: [.maya], direction: .sell).isEmpty) + } + + /// The case from the bug report: ARB.USDT with no route on either provider. + func testNoRouteOnEitherProviderHaltsTheCoin() async { + script.set(.noRoute, .near, "ARB.USDT") + script.set(.noRoute, .maya, "ARB.USDT") + + await refresh(["ARB.USDT": both]) + + XCTAssertTrue(store.usableProviders(for: "ARB.USDT", capable: both, direction: .sell).isEmpty) + } + + func testMayaOnlyCoinIsUnaffectedByNear() async { + script.set(.noRoute, .near, "MAYA.CACAO") + + await refresh(["MAYA.CACAO": [.maya]]) + + XCTAssertEqual(label("MAYA.CACAO", capable: [.maya]), .maya) + XCTAssertFalse(script.calls(to: .near).contains("MAYA.CACAO")) + } + + // MARK: NEAR sentinels + + func testNearDownSkipsEveryPerCoinNearProbe() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + + await refresh(["ETH.USDT": both, "AVAX.AVAX": [.near], "TRON.TRX": [.near]]) + + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH"], "two conclusive sentinels, nothing per coin") + XCTAssertEqual(script.calls(to: .maya), ["ETH.USDT"]) + } + + func testOneRoutingSentinelProbesEveryNearCoin() async { + script.set(.noRoute, .near, "BTC.BTC") + + await refresh(["ETH.USDT": both, "AVAX.AVAX": [.near], "TRON.TRX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(Set(script.calls(to: .near)), ["BTC.BTC", "ETH.ETH", "ETH.USDT", "AVAX.AVAX", "TRON.TRX"]) + } + + func testAnInconclusiveSentinelAsksTheThird() async { + script.set(.unknown, .near, "BTC.BTC") + script.set(.noRoute, .near, "ETH.ETH") + + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "SOL.SOL", "AVAX.AVAX"]) + XCTAssertEqual(store.nearVerdict(for: .sell), .up, "SOL.SOL routed") + } + + /// The third sentinel stands in for an inconclusive one: two conclusive no-routes out of three + /// still mean NEAR is down. + func testTwoNoRoutesBesideAnInconclusiveSentinelMeanDown() async { + script.set(.unknown, .near, "BTC.BTC") + script.set(.noRoute, .near, "ETH.ETH") + script.set(.noRoute, .near, "SOL.SOL") + + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertFalse(script.calls(to: .near).contains("AVAX.AVAX")) + } + + /// Halts on the sentinels' chains are about those chains, not about NEAR. + func testHaltedSentinelsDoNotMeanNearIsDown() async { + script.set(.halted, .near, "BTC.BTC") + script.set(.halted, .near, "ETH.ETH") + script.set(.halted, .near, "SOL.SOL") + + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertNil(store.nearVerdict(for: .sell)) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + } + + /// No sentinel routes, but fewer than two answered conclusively: NEAR is not declared down, no + /// coin is probed on its own, and the static labels stay. + func testInconclusiveSentinelsLeaveNearOpen() async { + script.set(.unknown, .near, "BTC.BTC") + script.set(.noRoute, .near, "ETH.ETH") + script.set(.unknown, .near, "SOL.SOL") + + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertNil(store.nearVerdict(for: .sell)) + XCTAssertFalse(script.calls(to: .near).contains("AVAX.AVAX")) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + } + + func testNoNearCapableCoinSkipsTheSentinels() async { + await refresh(["MAYA.CACAO": [.maya]]) + + XCTAssertTrue(script.calls(to: .near).isEmpty) + } + + // MARK: Cache + + func testFreshAnswersAreNotAskedAgain() async { + await refresh(["ETH.USDT": both]) + let first = script.calls.count + + await refresh(["ETH.USDT": both]) + + XCTAssertEqual(script.calls.count, first) + } + + /// A due answer is asked again, but keeps counting until the new one is in: the label does not + /// fall back to the static guess in between. + func testDueAnswersAreAskedAgainAndKeepCountingMeanwhile() async { + script.set(.halted, .maya, "ETH.USDT") + await refresh(["ETH.USDT": both]) + XCTAssertEqual(label("ETH.USDT", capable: both), .near) + + clock += 601 + XCTAssertEqual(label("ETH.USDT", capable: both), .near, "still the last conclusive answer") + + script.set(.available, .maya, "ETH.USDT") + await refresh(["ETH.USDT": both]) + XCTAssertEqual(script.calls(to: .maya), ["ETH.USDT", "ETH.USDT"]) + XCTAssertEqual(label("ETH.USDT", capable: both), .multiple) + } + + func testAnswersAreForgottenAfterHalfAnHour() async { + script.set(.halted, .maya, "ETH.USDT") + await refresh(["ETH.USDT": both]) + + clock += 1801 + + XCTAssertNil(store.state(of: .maya, for: "ETH.USDT", direction: .sell)) + XCTAssertEqual(label("ETH.USDT", capable: both), .multiple) + } + + /// A NEAR outage is re-checked after two minutes — with real requests, not the sentinels' + /// cached no-routes — so a recovery shows quickly. + func testNearOutageIsReCheckedAfterTwoMinutes() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + + clock += 60 + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH"], "not due yet") + + clock += 61 + XCTAssertEqual(store.nearVerdict(for: .sell), .down, "still counts until re-checked") + script.set(.available, .near, "BTC.BTC") + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "BTC.BTC", "AVAX.AVAX"]) + } + + /// Re-confirming an outage does not bury a coin's own answer given after the outage began. + func testAReConfirmedOutageKeepsANewerPerCoinAnswer() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["ARB.USDT": [.near]]) + clock += 1 + store.record(.available, provider: .near, asset: "ARB.USDT", direction: .sell) + + clock += 121 + await refresh(["ARB.USDT": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(label("ARB.USDT", capable: [.near]), .near) + } + + /// A coin's own answer newer than the outage verdict wins over it. + func testANewerPerCoinAnswerOverridesTheNearOutage() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["ARB.USDT": [.near]]) + XCTAssertTrue(store.usableProviders(for: "ARB.USDT", capable: [.near], direction: .sell).isEmpty) + + clock += 1 + store.record(.available, provider: .near, asset: "ARB.USDT", direction: .sell) + + XCTAssertEqual(label("ARB.USDT", capable: [.near]), .near) + } + + // MARK: Inconclusive answers + + func testAnInconclusiveAnswerIsNotCached() async { + script.set(.unknown, .maya, "ETH.USDT") + await refresh(["ETH.USDT": [.maya]]) + await refresh(["ETH.USDT": [.maya]]) + XCTAssertEqual(script.calls(to: .maya), ["ETH.USDT"], "backed off for two minutes, not polled every tick") + + clock += 121 + await refresh(["ETH.USDT": [.maya]]) + + XCTAssertEqual(script.calls(to: .maya), ["ETH.USDT", "ETH.USDT"], "asked again, not blocked for ten minutes") + XCTAssertEqual(label("ETH.USDT", capable: [.maya]), .maya) + } + + func testAnInconclusiveAnswerDoesNotEraseAConclusiveOne() async { + store.record(.halted, provider: .maya, asset: "ETH.USDT", direction: .sell) + store.record(.unknown, provider: .maya, asset: "ETH.USDT", direction: .sell) + + XCTAssertEqual(store.state(of: .maya, for: "ETH.USDT", direction: .sell), .halted) + } + + /// An inconclusive sentinel round keeps the verdict it had instead of dropping it. + func testAnInconclusiveSentinelRoundKeepsThePreviousVerdict() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + + clock += 121 + SwapRouteAvailability.nearSentinels.forEach { script.set(.unknown, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + } + + // MARK: Cancellation + + func testCancellingTheRefreshDropsTheQueuedProbes() async { + let coins = (1...10).map { "ETH.TOKEN\($0)" } + let map = Dictionary(uniqueKeysWithValues: coins.map { ($0.uppercased(), Set([.maya])) }) + let store = self.store! + let probe = script.probe + script.closeGate() + + let task = Task { @MainActor in + await store.refresh(assets: coins, direction: .sell, capable: { map[$0.uppercased()] ?? [] }, probe: probe) + } + await waitUntil { self.script.calls.count == 2 } + task.cancel() + script.openGate() + await task.value + + XCTAssertEqual(script.calls.count, 2, "only the two in flight were sent") + let answered = coins.filter { store.state(of: .maya, for: $0, direction: .sell) != nil } + XCTAssertEqual(answered.count, 2, "dropped probes left no answer behind") + } + + /// A refresh started while a stopped one still drains waits for it instead of doing nothing. + func testARefreshStartedDuringADrainRunsAfterIt() async { + let store = self.store! + let probe = script.probe + let first: [String: Set] = ["ETH.A": [.maya], "ETH.B": [.maya], "ETH.C": [.maya]] + script.closeGate() + + let old = Task { @MainActor in + await store.refresh(assets: ["ETH.A", "ETH.B", "ETH.C"], direction: .sell, capable: { first[$0] ?? [] }, probe: probe) + } + await waitUntil { self.script.calls.count == 2 } + old.cancel() + + let new = Task { @MainActor in + await store.refresh(assets: ["ETH.C"], direction: .sell, capable: { first[$0] ?? [] }, probe: probe) + } + await Task.yield() + script.openGate() + await old.value + await new.value + + let calls = script.calls(to: .maya) + XCTAssertEqual(Set(calls.prefix(2)), ["ETH.A", "ETH.B"], "the two the old refresh had in flight") + XCTAssertEqual(calls.dropFirst(2).map { $0 }, ["ETH.C"], "the new refresh probed ETH.C after the drain") + } + + // MARK: Quoting + + /// A real quote only leaves out a provider on an answer that is not yet due for a re-probe. + func testQuotingIgnoresAnswersDueForAReProbe() async { + store.record(.halted, provider: .maya, asset: "ETH.USDT", direction: .sell) + XCTAssertEqual(store.usableProviders(for: "ETH.USDT", capable: both, direction: .sell, freshOnly: true), [.near]) + + clock += 601 + + XCTAssertEqual(store.usableProviders(for: "ETH.USDT", capable: both, direction: .sell), [.near], "the picker still reads it") + XCTAssertEqual(store.usableProviders(for: "ETH.USDT", capable: both, direction: .sell, freshOnly: true), both) + } + + private func waitUntil(_ condition: @escaping @MainActor () -> Bool) async { + for _ in 0..<1000 where !condition() { + await Task.yield() + } + XCTAssertTrue(condition(), "condition never became true") + } + + func testDirectionsAreIndependent() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]], direction: .sell) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertNil(store.nearVerdict(for: .buy)) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near], direction: .buy), .near) + } + + // MARK: Answers from outside the probes + + func testARecordedAnswerChangesTheLabelAndIsReported() { + var reported: [SwapDirection] = [] + let cancellable = store.changes.sink { reported.append($0) } + defer { cancellable.cancel() } + + store.record(.noRoute, provider: .maya, asset: "ARB.USDT", direction: .sell) + store.record(.noRoute, provider: .maya, asset: "ARB.USDT", direction: .sell) + + XCTAssertEqual(label("ARB.USDT", capable: both), .near) + XCTAssertEqual(reported, [.sell], "an unchanged answer is not reported again") + } + + // MARK: Load + + func testNoMoreThanTwoProbesAreInFlight() async { + script.holdNanoseconds = 5_000_000 + let coins = (1...10).map { "ETH.TOKEN\($0)" } + let map = Dictionary(uniqueKeysWithValues: coins.map { ($0.uppercased(), both) }) + + await store.refresh(assets: coins, direction: .sell, capable: { map[$0.uppercased()] ?? [] }, probe: script.probe) + + XCTAssertEqual(script.maxInFlight, 2) + XCTAssertEqual(script.calls.count, 1 + 20, "the first sentinel routes, then both providers for every coin") + } +} From c7fcc41d131fc15f5250469a5fc7e27dabbc6d38 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 5 Nov 2026 17:35:09 +0200 Subject: [PATCH 2/8] fix(swap): judge each provider's answer more carefully in the route checks SDD-Published-From: ed9c59385523bdfdc167485480c5aced6e69ce52 --- .../Models/SwapKit/SwapKitSwapProvider.swift | 105 +++++++++--------- .../SwapKit/SwapRouteAvailability.swift | 46 +++++--- .../SwapKitQuoteDecodingTests.swift | 97 +++++++++++++++- .../SwapRouteAvailabilityTests.swift | 85 +++++++++++++- ...e-answers-in-one-shared-in-memory-store.md | 2 +- ...etect-a-near-outage-from-sentinel-coins.md | 2 +- docs/features/swap-live-routes/README.md | 8 +- 7 files changed, 262 insertions(+), 83 deletions(-) diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index cbfe772dba..56b11af941 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -289,8 +289,9 @@ final class SwapKitSwapProvider: SwapProvider { /// Codes SwapKit uses to refuse the coin itself, whatever the provider. private static let refusedCoinCodes: Set = ["blacklistasset", "invalidasset"] - /// Pure decision for `validateAddress`, internal for the tests. `requested` empty means the - /// quote let SwapKit pick providers (no classification), so availability is not judged. + /// Pure decision for `validateAddress`, internal for the tests. `requested` is the providers + /// the quote named (`addressCheckRequest`), never empty: `sellQuoteProviders` always names NEAR + /// or Maya. static func addressCheck(_ response: SwapKitQuoteResponse, requested: Set) -> AddressCheck { if response.routes?.isEmpty == false { return .pass @@ -305,36 +306,54 @@ final class SwapKitSwapProvider: SwapProvider { return .refused(top) } - // A provider's refusal only counts for that provider: another one may still accept it. - var refusedBy: [RouteProvider: String] = [:] - for error in response.providerErrors ?? [] { + // A refusal only counts for the SwapKit provider (a Maya flavour, say) that gave it: another + // one may still accept the request. A refusal from any other provider, or from none named, + // is ignored. When several refuse, the first in SwapKit's order is shown. + let errors = response.providerErrors ?? [] + var refusedBy: Set = [] + var firstRefusal: String? + for error in errors { guard let raw = code(error.errorCode), requestCodes.contains(raw.lowercased()) || refusedCoinCodes.contains(raw.lowercased()) else { continue } - if let name = error.provider, let provider = RouteProvider(swapKitProvider: name) { - refusedBy[provider] = raw - } else if requested.isEmpty { - return .refused(raw) - } + guard let name = error.provider, RouteProvider(swapKitProvider: name) != nil else { continue } + refusedBy.insert(name.uppercased()) + firstRefusal = firstRefusal ?? raw } - guard !requested.isEmpty else { - return refusedBy.values.first.map { .refused($0) } ?? .pass - } // The quote asked every usable provider at once; each one is judged on its own answer. - var states = LiveRouteState.classifyPerProvider(response, requested: requested) - for provider in refusedBy.keys { - states[provider] = nil - } + let states = judgedWithoutRefusals(LiveRouteState.classifyPerProvider(response, requested: requested), + errors: errors, refusedBy: refusedBy) if states.values.contains(where: { $0.isUsable }) { return .pass } - if let refusal = refusedBy.values.first { + if let refusal = firstRefusal { return .refused(refusal) } let noRoute = Set(states.filter { $0.value == .noRoute }.map { $0.key }) return noRoute.isEmpty ? .unavailable : .confirmNoRoute(noRoute) } + /// `states` with each provider whose flavours (SwapKit provider names) are partly in + /// `refusedBy` judged on the other flavours' errors alone, and left out when every flavour + /// that spoke refused. + private static func judgedWithoutRefusals( + _ states: [RouteProvider: LiveRouteState], + errors: [SwapKitProviderError], + refusedBy: Set + ) -> [RouteProvider: LiveRouteState] { + var judged = states + for provider in states.keys { + let spoke = errors.filter { $0.provider.flatMap { RouteProvider(swapKitProvider: $0) } == provider } + let rest = spoke.filter { !refusedBy.contains($0.provider?.uppercased() ?? "") } + guard rest.count < spoke.count else { continue } + judged[provider] = rest.isEmpty + ? nil + : LiveRouteState.classify(SwapKitQuoteResponse(quoteId: nil, routes: nil, providerErrors: rest, + error: nil, message: nil)) + } + return judged + } + /// A nominal Sell quote to the entered address. Its real use is the last check before the /// amount screen that the coin can be swapped right now (`addressCheck` decides). /// @@ -344,19 +363,7 @@ final class SwapKitSwapProvider: SwapProvider { /// and reports what is wrong with it. func validateAddress(destination: String, toAsset: String) async -> String? { if !classificationBuilt { await buildClassification() } - // Without a classification there is nothing to judge availability by: let SwapKit pick - // providers, as this check always did. - let providers = classificationUsable ? sellQuoteProviders(for: toAsset) : nil - let request = SwapKitQuoteRequest( - sellAsset: SwapKitConstants.dashAsset, - buyAsset: toAsset, - sellAmount: "1", // nominal; one DASH is far above every route floor - slippage: SwapKitConstants.defaultSlippagePercent, - sourceAddress: nil, - destinationAddress: destination, - providers: providers, - affiliateFee: nil - ) + let request = addressCheckRequest(destination: destination, toAsset: toAsset) let response: SwapKitQuoteResponse do { @@ -371,7 +378,7 @@ final class SwapKitSwapProvider: SwapProvider { response = decoded } - let requested = Set((providers ?? []).compactMap { RouteProvider(swapKitProvider: $0) }) + let requested = Set((request.providers ?? []).compactMap { RouteProvider(swapKitProvider: $0) }) recordQuoteOutcome(response, requested: requested, asset: toAsset, direction: .sell) let check = Self.addressCheck(response, requested: requested) @@ -408,6 +415,21 @@ final class SwapKitSwapProvider: SwapProvider { } } + /// The nominal quote `validateAddress` sends: the providers the real Sell quote would ask + /// (`sellQuoteProviders`), so no provider the swap can't use decides the address. + func addressCheckRequest(destination: String, toAsset: String) -> SwapKitQuoteRequest { + SwapKitQuoteRequest( + sellAsset: SwapKitConstants.dashAsset, + buyAsset: toAsset, + sellAmount: "1", // nominal; one DASH is far above every route floor + slippage: SwapKitConstants.defaultSlippagePercent, + sourceAddress: nil, + destinationAddress: destination, + providers: sellQuoteProviders(for: toAsset), + affiliateFee: nil + ) + } + /// What the address screen says after the providers that answered "no route" were asked again /// without the address: a route → the address is what to fix; nothing conclusive → nil, the /// amount screen gets to quote the coin; no route confirmed → the coin can't be swapped now. @@ -1007,7 +1029,7 @@ final class SwapKitSwapProvider: SwapProvider { /// Providers the live probes have ruled out for this coin are left out, so a halted Maya leg /// cannot crowd the answer of a working NEAR one. When the probes ruled out every provider, the /// static set is sent anyway and SwapKit's own answer reaches the user. - private func sellQuoteProviders(for toAsset: String) -> [String]? { + private func sellQuoteProviders(for toAsset: String) -> [String] { guard classificationUsable else { return [SwapKitConstants.providerNear] } @@ -1221,20 +1243,3 @@ private func errorResult(_ message: String) -> SwapQuoteResult { return SwapQuoteResult(error: message, expectedAmountOut: nil, fees: nil, inboundAddress: nil, memo: nil, executionNetwork: nil) } } - -private extension Array { - func chunked(into size: Int) -> [[Element]] { - guard size > 0, !isEmpty else { return [self] } - var result: [[Element]] = [] - result.reserveCapacity((count + size - 1) / size) - - var index = startIndex - while index < endIndex { - let nextIndex = self.index(index, offsetBy: size, limitedBy: endIndex) ?? endIndex - result.append(Array(self[index.. LiveRouteState? in + let states = (response.providerErrors ?? []).map { error -> LiveRouteState in guard let code = error.errorCode?.trimmingCharacters(in: .whitespacesAndNewlines), !code.isEmpty else { - return nil + return .unknown } if SwapKitErrorCopy.isBelowMinimum(code) { return .available } if SwapKitErrorCopy.isHalted(code) { return .halted } @@ -159,13 +159,16 @@ extension RouteProvider { /// fires a burst of ~200 requests. /// - NEAR is checked on a couple of liquid sentinel coins first. If two of them have no route and /// none routes, NEAR is treated as down for every coin of that direction and no per-coin NEAR -/// probes run; if one routes, every NEAR-capable coin is probed on its own. Halted or -/// inconclusive sentinels keep the previous verdict. +/// probes run; if one routes, every NEAR-capable coin is probed on its own. A halted or +/// inconclusive sentinel counts toward neither, and a round that settles neither keeps the +/// previous verdict. /// - Maya is probed per coin: its halts are per chain, so one coin says nothing about the next. /// /// Answers age in two steps: after `probeAfter` (`nearDownProbeAfter` for a NEAR outage) a refresh /// asks again, but the last conclusive answer keeps being read until the new one arrives or /// `forgetAfter` passes — so a label does not flip back to the static guess between the two. +/// A refresh drops what passed `forgetAfter` in its direction and reports it on `changes`, so a +/// row halted by a forgotten answer comes back even when the re-check stores nothing. /// Inconclusive answers (`.unknown`) are never stored: they would only block the next attempt. @MainActor final class SwapRouteAvailability { @@ -179,8 +182,8 @@ final class SwapRouteAvailability { case down } - /// Liquid NEAR-capable coins on different chains. The third is asked only when one of the first - /// two gave no conclusive answer. + /// Liquid NEAR-capable coins on different chains. The third is asked only when the first two + /// settled neither outcome: neither routes and they are not both a no-route. static let nearSentinels = ["BTC.BTC", "ETH.ETH", "SOL.SOL"] /// Emits the direction whose availability changed. @@ -310,6 +313,7 @@ final class SwapRouteAvailability { refreshing.remove(direction) refreshWaiters.removeValue(forKey: direction)?.forEach { $0.resume() } } + forgetExpired(direction) var probeNearPerCoin = false if assets.contains(where: { capable($0).contains(.near) }) { @@ -367,8 +371,8 @@ final class SwapRouteAvailability { /// Re-asks the sentinels once the last verdict is due (2 minutes after an outage, 10 after /// "up"), bypassing their cached answers. They are asked until one routes or two give a - /// conclusive no; the third only stands in for an inconclusive one. Two conclusive no-routes - /// and none routing → NEAR is down. Fewer keeps the previous verdict. + /// conclusive no, so the third stands in for a halted or an inconclusive one. Two conclusive + /// no-routes and none routing → NEAR is down. Fewer keeps the previous verdict. private func resolveNearVerdict(direction: SwapDirection, probe: @escaping Probe) async -> NearVerdict? { if let verdict = readableVerdict(direction), !isDue(verdict) { return verdict.verdict @@ -378,12 +382,7 @@ final class SwapRouteAvailability { } var noRoutes = 0 - var inconclusive = 0 - for (index, sentinel) in Self.nearSentinels.enumerated() where noRoutes < 2 { - // The third sentinel only stands in for one that gave no conclusive answer. - if index >= 2, inconclusive == 0 { - break - } + for sentinel in Self.nearSentinels where noRoutes < 2 { if Task.isCancelled { return readableVerdict(direction)?.verdict } @@ -396,8 +395,6 @@ final class SwapRouteAvailability { // Only a no-route says something about NEAR as a whole; a halt is about that chain. if state == .noRoute { noRoutes += 1 - } else if state == .unknown { - inconclusive += 1 } } @@ -455,6 +452,21 @@ final class SwapRouteAvailability { // MARK: Ageing + /// Drops the answers and the NEAR verdict of `direction` that passed `forgetAfter`, and reports + /// the direction when anything was dropped. + private func forgetExpired(_ direction: SwapDirection) { + let expired = entries.filter { $0.key.direction == direction && readableEntry($0.key) == nil }.map { $0.key } + expired.forEach { entries.removeValue(forKey: $0) } + var forgot = !expired.isEmpty + if nearVerdicts[direction] != nil, readableVerdict(direction) == nil { + nearVerdicts.removeValue(forKey: direction) + forgot = true + } + if forgot { + changes.send(direction) + } + } + private func readableEntry(_ key: Key) -> Entry? { guard let entry = entries[key], now().timeIntervalSince(entry.checkedAt) < forgetAfter else { return nil } return entry diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 85bb5e87ff..481c3778bc 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -292,6 +292,36 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertEqual(LiveRouteState.classify(blip), .unknown) } + /// A provider that failed without saying why is as inconclusive as one that named an upstream + /// failure: the top-level no-route beside it is not that provider's verdict. + func testTopLevelNoRouteBesideACodelessProviderErrorIsUnknown() { + for code in [nil, "", " "] as [String?] { + let codeless = response(providerErrors: [providerError(code, message: "Quote failed")], + error: "noRoutesFound") + XCTAssertEqual(LiveRouteState.classify(codeless), .unknown, "code \(String(describing: code))") + XCTAssertEqual(LiveRouteState.classifyPerProvider(codeless, requested: [.near]), [.near: .unknown], + "code \(String(describing: code))") + } + } + + /// One Maya flavour failing without a code outranks the other flavour's halt. + func testACodelessFlavourOutranksTheOthersHalt() { + let mixed = response(providerErrors: [ + SwapKitProviderError(provider: "MAYACHAIN", errorCode: nil, message: nil), + SwapKitProviderError(provider: "MAYACHAIN_STREAMING", errorCode: "swapHalted", message: nil), + ], error: "noRoutesFound") + XCTAssertEqual(LiveRouteState.classify(mixed), .unknown) + } + + /// A route still wins over a codeless error beside it. + func testARouteOutranksACodelessProviderError() throws { + let recorded = try JSONDecoder().decode(SwapKitQuoteResponse.self, + from: loadFixture(named: "swapkit_quote_response")) + let routed = SwapKitQuoteResponse(quoteId: nil, routes: recorded.routes, providerErrors: [providerError(nil)], + error: nil, message: nil) + XCTAssertEqual(LiveRouteState.classify(routed), .available) + } + func testProviderNoRouteIsNoRoute() { XCTAssertEqual(LiveRouteState.classify(response(providerErrors: [providerError("noRoutesFound")])), .noRoute) } @@ -399,16 +429,75 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertEqual(SwapKitSwapProvider.addressCheck(both, requested: [.near, .maya]), .refused("invalidDestinationAddress")) } + /// One Maya flavour refusing does not hide what the other flavour said: Maya counts as refused + /// only when every flavour that spoke refused. A route from the other flavour already passes + /// before any refusal is read, so "can carry it" here is the other flavour's below-minimum. + func testAddressCheckJudgesEachMayaFlavourOnItsOwn() { + let refusal = pe("MAYACHAIN", "validation_error") + let otherCarries = response(providerErrors: [refusal, pe("MAYACHAIN_STREAMING", "sellAssetAmountTooSmall")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(otherCarries, requested: [.maya]), .pass) + + let otherUnsure = response(providerErrors: [refusal, pe("MAYACHAIN_STREAMING", "apiRequestFailed")], + error: "noRoutesFound") + XCTAssertEqual(SwapKitSwapProvider.addressCheck(otherUnsure, requested: [.maya]), .pass) + + let otherRefusal = pe("MAYACHAIN_STREAMING", "isSanctionedAddress") + let refusalFirst = response(providerErrors: [refusal, otherRefusal]) + let otherFirst = response(providerErrors: [otherRefusal, refusal]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(refusalFirst, requested: [.maya]), .refused("validation_error"), + "both refuse: the first refusal in SwapKit's order is the one shown") + XCTAssertEqual(SwapKitSwapProvider.addressCheck(otherFirst, requested: [.maya]), + .refused("isSanctionedAddress")) + + let otherNoRoute = response(providerErrors: [refusal, pe("MAYACHAIN_STREAMING", "noRoutesFound")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(otherNoRoute, requested: [.maya]), .refused("validation_error"), + "nothing usable is left, so the refusal is what the holder hears") + } + + /// NEAR has one flavour: its refusal still takes NEAR out, and Maya decides. + func testAddressCheckANearRefusalStillRemovesNear() { + let mayaCarries = response(providerErrors: [pe("NEAR", "invalidDestinationAddress"), + pe("MAYACHAIN", "sellAssetAmountTooSmall")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(mayaCarries, requested: [.near, .maya]), .pass) + let mayaHalted = response(providerErrors: [pe("NEAR", "invalidDestinationAddress"), + pe("MAYACHAIN", "swapHalted")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(mayaHalted, requested: [.near, .maya]), + .refused("invalidDestinationAddress")) + } + + /// A Maya flavour that failed without a code beside the other flavour's halt: Maya is + /// inconclusive, not halted, so the holder goes on instead of hearing "can't be swapped". + func testAddressCheckPassesACodelessProviderError() { + let codeless = response(providerErrors: [ + SwapKitProviderError(provider: "MAYACHAIN", errorCode: nil, message: "Quote failed"), + pe("MAYACHAIN_STREAMING", "swapHalted"), + ], error: "noRoutesFound") + XCTAssertEqual(SwapKitSwapProvider.addressCheck(codeless, requested: [.maya]), .pass) + } + /// An upstream failure is not the user's to fix on this screen. func testAddressCheckPassesAnUpstreamFailure() { XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "apiRequestFailed"), requested: [.near, .maya]), .pass) XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(providerErrors: [pe("NEAR", "apiRequestFailed")]), requested: [.near]), .pass) } - /// Without a classification no providers were named; availability is not judged. - func testAddressCheckWithoutRequestedProvidersOnlyRefusesRequestErrors() { - XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "noRoutesFound"), requested: []), .pass) - XCTAssertEqual(SwapKitSwapProvider.addressCheck(response(error: "isSanctionedAddress"), requested: []), .refused("isSanctionedAddress")) + /// Without a classification the address check still asks only what the real Sell quote asks + /// (NEAR), never every SwapKit provider. + @MainActor + func testAddressCheckWithoutAClassificationAsksNear() { + let request = SwapKitSwapProvider().addressCheckRequest(destination: "0xabc", toAsset: "ETH.ETH") + XCTAssertEqual(request.providers, [SwapKitConstants.providerNear]) + XCTAssertEqual(request.destinationAddress, "0xabc") + } + + /// A provider the swap never uses does not decide the address: NEAR's own answer does, even + /// when it leaves nothing usable and so the refusals are read. + func testAddressCheckIgnoresAProviderOutsideNearAndMaya() { + let thorRefuses = pe("THORCHAIN", "invalidDestinationAddress") + let nearNoRoute = response(providerErrors: [thorRefuses, pe("NEAR", "noRoutesFound")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(nearNoRoute, requested: [.near]), .confirmNoRoute([.near])) + let nearHalted = response(providerErrors: [thorRefuses, pe("NEAR", "swapHalted")]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(nearHalted, requested: [.near]), .unavailable) } // MARK: Address check after the address-free re-check (AC-05) diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift index 81788427ce..2a8148952c 100644 --- a/DashWalletTests/SwapRouteAvailabilityTests.swift +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -239,18 +239,42 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) } - /// The third sentinel stands in only for an inconclusive one, not for a halted one: a halt is - /// a conclusive answer about that chain, so the round ends without a verdict. - func testAHaltedSentinelIsNotStoodInFor() async { + /// A halted sentinel counts toward neither outcome, so SOL is asked in its place: halted beside + /// one no-route settles nothing on its own. + func testAHaltedSentinelIsStoodInFor() async { script.set(.halted, .near, "BTC.BTC") script.set(.noRoute, .near, "ETH.ETH") script.set(.noRoute, .near, "SOL.SOL") await refresh(["AVAX.AVAX": [.near]]) - XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH"]) - XCTAssertNil(store.nearVerdict(for: .sell)) - XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "SOL.SOL"]) + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + } + + func testAHaltedSentinelStoodInForByARoutingSOLMeansUp() async { + script.set(.halted, .near, "BTC.BTC") + script.set(.noRoute, .near, "ETH.ETH") + + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "SOL.SOL", "AVAX.AVAX"]) + } + + /// Two halted chains do not freeze an old outage: SOL routing shows the recovery. + func testTwoHaltedSentinelsDoNotHideARecovery() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + + clock += 121 + script.set(.halted, .near, "BTC.BTC") + script.set(.halted, .near, "ETH.ETH") + script.set(.available, .near, "SOL.SOL") + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) } /// No sentinel routes, but fewer than two answered conclusively: NEAR is not declared down, no @@ -327,6 +351,55 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(label("ETH.USDT", capable: both), .multiple) } + /// A forgotten answer is reported, so the picker re-renders a halted row even when the re-check + /// is inconclusive and stores nothing. + func testAForgottenAnswerIsReported() async { + script.set(.halted, .maya, "ETH.USDT") + await refresh(["ETH.USDT": [.maya]]) + XCTAssertEqual(store.state(of: .maya, for: "ETH.USDT", direction: .sell), .halted) + + var reported: [SwapDirection] = [] + let cancellable = store.changes.sink { reported.append($0) } + defer { cancellable.cancel() } + clock += 1801 + script.set(.unknown, .maya, "ETH.USDT") + await refresh(["ETH.USDT": [.maya]]) + + XCTAssertEqual(reported, [.sell]) + XCTAssertNil(store.state(of: .maya, for: "ETH.USDT", direction: .sell)) + } + + func testAForgottenNearOutageIsReported() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + + var reported: [SwapDirection] = [] + let cancellable = store.changes.sink { reported.append($0) } + defer { cancellable.cancel() } + clock += 1801 + SwapRouteAvailability.nearSentinels.forEach { script.set(.unknown, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(reported, [.sell]) + XCTAssertNil(store.nearVerdict(for: .sell)) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + } + + /// Nothing aged out: a refresh that learns nothing new reports nothing. + func testARefreshWithNothingForgottenReportsNothing() async { + script.set(.halted, .maya, "ETH.USDT") + await refresh(["ETH.USDT": [.maya]]) + + var reported: [SwapDirection] = [] + let cancellable = store.changes.sink { reported.append($0) } + defer { cancellable.cancel() } + clock += 601 + await refresh(["ETH.USDT": [.maya]]) + + XCTAssertTrue(reported.isEmpty) + } + /// A NEAR outage is re-checked after two minutes — with real requests, not the sentinels' /// cached no-routes — so a recovery shows quickly. func testNearOutageIsReCheckedAfterTwoMinutes() async { diff --git a/docs/adr/0007-keep-live-swap-route-answers-in-one-shared-in-memory-store.md b/docs/adr/0007-keep-live-swap-route-answers-in-one-shared-in-memory-store.md index eb1c7ccf97..aa1263e19e 100644 --- a/docs/adr/0007-keep-live-swap-route-answers-in-one-shared-in-memory-store.md +++ b/docs/adr/0007-keep-live-swap-route-answers-in-one-shared-in-memory-store.md @@ -35,7 +35,7 @@ unknown answers out of the store is what makes "unknown never halts" hold by con ## Consequences **Positive** -- The picker, the address screen and the quote paths read one truth; a no-route the address screen confirms shows as halted when the Wallet holder goes back. +- The picker, the address screen and the quote paths read one truth; a no-route the address screen confirms shows as halted when the Wallet holder goes back, when the published token lists name the coin. - One place enforces the in-flight cap and the NEAR verdict for both directions. - Testable with an injected clock and an injected probe. diff --git a/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md b/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md index 6d17eea176..320463203a 100644 --- a/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md +++ b/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md @@ -18,7 +18,7 @@ chain, so one Maya coin says nothing about the next. ## Considered options -1. **Sentinel coins first** — BTC and ETH are asked first, SOL only in place of one that gave no conclusive answer, not in place of a halted one; two conclusive no-routes and none routing → NEAR is down for that direction; one routing → every NEAR-capable coin is checked on its own; a halted sentinel counts toward neither; a round with neither outcome keeps the previous verdict and is retried after 2 min. +1. **Sentinel coins first** — BTC and ETH are asked first, SOL whenever those two settle neither outcome (an inconclusive or a halted one beside them); two conclusive no-routes and none routing → NEAR is down for that direction; one routing → every NEAR-capable coin is checked on its own; a halted sentinel counts toward neither; a round with neither outcome keeps the previous verdict and is retried after 2 min. 2. **Always check NEAR per coin** — no verdict, each coin's NEAR state is its own answer. 3. **Infer the outage from the per-coin checks** — stop checking NEAR once the first K per-coin answers in display order are all no-route. diff --git a/docs/features/swap-live-routes/README.md b/docs/features/swap-live-routes/README.md index df3abf0cf7..5821571a4b 100644 --- a/docs/features/swap-live-routes/README.md +++ b/docs/features/swap-live-routes/README.md @@ -21,9 +21,9 @@ the address screen reported every refusal as a connection problem. and the quote paths read: a conclusive answer is re-checked after 10 minutes and forgotten after 30, an inconclusive one is never stored and is re-asked after 2 minutes. See [ADR-0007](../../adr/0007-keep-live-swap-route-answers-in-one-shared-in-memory-store.md). -- **NEAR outages cost a few checks.** NEAR is checked on sentinel coins (BTC, ETH, SOL in place of - an inconclusive one) first; if none routes, NEAR is down for that direction and no per-coin NEAR - checks are sent. Maya is checked per coin, since its halts are per chain. See +- **NEAR outages cost a few checks.** NEAR is checked on sentinel coins first: BTC and ETH, and SOL + whenever those two settle neither outcome. Two "no route" answers and none routing → NEAR is down + for that direction and no per-coin NEAR checks are sent. Maya is checked per coin, since its halts are per chain. See [ADR-0008](../../adr/0008-detect-a-near-outage-from-sentinel-coins.md). - **The address screen names the real problem.** A refused address gets the address copy; a "no route" is re-checked without the address and, when confirmed, says " can't be swapped at the @@ -34,7 +34,7 @@ the address screen reported every refusal as a connection problem. ## What it guarantees -- A coin no provider can route right now is shown halted and cannot be picked. +- A coin no provider can route right now is shown halted and cannot be picked, when the published token lists name it. - An inconclusive answer never halts a coin; the coin keeps its published label. - At most two checks are in flight; checks run only while the picker is open; no address leaves the device in a check. From 0c83910f4e73fd0f0aac2deea5d5a86c917e0854 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 6 Nov 2026 13:14:07 +0200 Subject: [PATCH 3/8] Address re-check at the quote's amount, stale probe guard, sentinel recovery PR feedback round 10: - Re-check a no-route on the address screen at the address quote's amount without the address; a below-minimum there lets the holder continue instead of blaming the address (thread 4483087473). - A probe that returns after its coin got a newer answer no longer overwrites it (thread 4483087481). - When NEAR recovers, the other sentinels' no-routes from the outage are dropped so their coins are checked in the same refresh; a no-route from the recovery round itself is kept (thread 4483087490). - Tests for the re-check wiring, the stale probe and the recovery; ADR-0008 updated. SDD-Published-From: 6b816f1cd4a6a5863876e92346a3e486174c9838 --- .../Models/SwapKit/SwapKitSwapProvider.swift | 63 ++++++++++++++++--- .../SwapKit/SwapRouteAvailability.swift | 49 ++++++++++++--- .../SwapKitQuoteDecodingTests.swift | 53 ++++++++++++++++ .../SwapRouteAvailabilityTests.swift | 51 +++++++++++++++ ...etect-a-near-outage-from-sentinel-coins.md | 2 +- 5 files changed, 200 insertions(+), 18 deletions(-) diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index 56b11af941..5023b11456 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -402,26 +402,69 @@ final class SwapKitSwapProvider: SwapProvider { guard let coin else { return NSLocalizedString("No route available", comment: "SwapKit") } return SwapKitErrorCopy.unavailableNowMessage(coin: coin) case .confirmNoRoute(let noRouteProviders): - // Ask again without the address, the way the picker probes: if a provider routes - // there, the address is what to fix. - var reAsked: [LiveRouteState] = [] - for provider in [RouteProvider.near, .maya] where noRouteProviders.contains(provider) { - reAsked.append(await routeAvailability.probeNow(asset: toAsset, provider: provider, direction: .sell) { [weak self] asset, provider, direction in - guard let self else { return .unknown } - return await self.probeRoute(asset: asset, provider: provider, direction: direction) - }) - } + let reAsked = await Self.reCheckNoRoute(noRouteProviders, asset: toAsset, store: routeAvailability) return Self.addressReCheckMessage(reAsked, coin: coin) } } + /// The amount of the address quote, and of its re-check without the address. + nonisolated static let addressCheckAmount = "1" // one DASH is far above every route floor + + /// The re-check of a no-route on the address screen: the address quote's amount, forced to + /// `provider`, with no address — so only the address differs from the quote it confirms. + nonisolated static func addressReCheckRequest(asset: String, provider: RouteProvider) -> SwapKitQuoteRequest { + probeRequest(asset: asset, provider: provider, direction: .sell, amount: addressCheckAmount) + } + + /// Asks each of `noRouteProviders` (NEAR, then Maya) again through `quote` at the address + /// quote's amount without the address: if a provider routes there, the address is what to fix. + /// Returns each answer as read for the address (`addressReCheckState`); `store` records the + /// usual classification (`LiveRouteState.classify`). + static func reCheckNoRoute( + _ noRouteProviders: Set, + asset: String, + store: SwapRouteAvailability, + quote: (SwapKitQuoteRequest) async -> SwapKitQuoteResponse? = addressReCheckResponse + ) async -> [LiveRouteState] { + var reAsked: [LiveRouteState] = [] + for provider in [RouteProvider.near, .maya] where noRouteProviders.contains(provider) { + var reCheck = LiveRouteState.unknown + await store.probeNow(asset: asset, provider: provider, direction: .sell) { asset, provider, _ in + let response = await quote(addressReCheckRequest(asset: asset, provider: provider)) + reCheck = addressReCheckState(response) + return response.map(LiveRouteState.classify) ?? .unknown + } + reAsked.append(reCheck) + } + return reAsked + } + + /// Sends a re-check request; nil when no SwapKit answer came back. + private static func addressReCheckResponse(_ request: SwapKitQuoteRequest) async -> SwapKitQuoteResponse? { + do { + return try await SwapKitAPIService.shared.quote(request) + } catch { + return decodedQuoteResponse(from: error) + } + } + + /// What a re-check answer says about the address: a route → `.available`; a below-minimum is + /// about the amount, so `.unknown` here (the amount screen quotes the real amount); otherwise + /// as `LiveRouteState.classify`. No answer → `.unknown`. + nonisolated static func addressReCheckState(_ response: SwapKitQuoteResponse?) -> LiveRouteState { + guard let response else { return .unknown } + if response.routes?.isEmpty == false { return .available } + let state = LiveRouteState.classify(response) + return state == .available ? .unknown : state + } + /// The nominal quote `validateAddress` sends: the providers the real Sell quote would ask /// (`sellQuoteProviders`), so no provider the swap can't use decides the address. func addressCheckRequest(destination: String, toAsset: String) -> SwapKitQuoteRequest { SwapKitQuoteRequest( sellAsset: SwapKitConstants.dashAsset, buyAsset: toAsset, - sellAmount: "1", // nominal; one DASH is far above every route floor + sellAmount: Self.addressCheckAmount, slippage: SwapKitConstants.defaultSlippagePercent, sourceAddress: nil, destinationAddress: destination, diff --git a/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift index 07b85bbabb..4b57211d71 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift @@ -57,8 +57,9 @@ enum LiveRouteState: Equatable { /// /// A top-level `noRoutesFound` with no provider errors counts as a conclusive no-route here, /// unlike on the amount screens: SwapKit also answers it for an amount far below a route's - /// floor, but the probes this classifies are sized at ~$50 (`SwapKitSwapProvider.probeAmount`), - /// well above every floor measured (the DASH → BTC minimum was 0.175 DASH on 2026-08-28). + /// floor, but the probes this classifies are sized at ~$50 (`SwapKitSwapProvider.probeAmount`) + /// and the address screen's no-route re-check at 1 DASH (`addressCheckAmount`), both well above + /// every floor measured (the DASH → BTC minimum was 0.175 DASH on 2026-08-28). static func classify(_ response: SwapKitQuoteResponse) -> LiveRouteState { if response.routes?.isEmpty == false { return .available @@ -221,6 +222,10 @@ final class SwapRouteAvailability { private let now: () -> Date private var entries: [Key: Entry] = [:] + /// Orders the answers: each stored answer carries the sequence number taken when it was asked + /// (a probe) or learned (`record`), so an older probe that returns late does not overwrite it. + private var sequence = 0 + private var storedSequence: [Key: Int] = [:] /// When a key last got an inconclusive answer, which is not stored as an answer. It is not /// asked again before `nearDownProbeAfter`, so an upstream outage is not polled every tick. private var inconclusiveAt: [Key: Date] = [:] @@ -289,7 +294,7 @@ final class SwapRouteAvailability { /// An inconclusive one is dropped. func record(_ state: LiveRouteState, provider: RouteProvider, asset: String, direction: SwapDirection) { guard state != .unknown else { return } - store(state, for: Key(direction, provider, asset)) + store(state, for: Key(direction, provider, asset), asked: nextSequence()) } // MARK: Probing @@ -372,7 +377,9 @@ final class SwapRouteAvailability { /// Re-asks the sentinels once the last verdict is due (2 minutes after an outage, 10 after /// "up"), bypassing their cached answers. They are asked until one routes or two give a /// conclusive no, so the third stands in for a halted or an inconclusive one. Two conclusive - /// no-routes and none routing → NEAR is down. Fewer keeps the previous verdict. + /// no-routes and none routing → NEAR is down. Fewer keeps the previous verdict. A route after + /// a "down" verdict also drops the other sentinels' no-routes stored before this round, so + /// their coins are asked again. private func resolveNearVerdict(direction: SwapDirection, probe: @escaping Probe) async -> NearVerdict? { if let verdict = readableVerdict(direction), !isDue(verdict) { return verdict.verdict @@ -381,6 +388,7 @@ final class SwapRouteAvailability { return readableVerdict(direction)?.verdict } + let roundStart = sequence var noRoutes = 0 for sentinel in Self.nearSentinels where noRoutes < 2 { if Task.isCancelled { @@ -389,6 +397,9 @@ final class SwapRouteAvailability { let state = await probeOne(Key(direction, .near, sentinel), asset: sentinel, force: true, probe: probe) if state == .available { inconclusiveRoundAt[direction] = nil + if readableVerdict(direction)?.verdict == .down { + forgetSentinelNoRoutes(direction: direction, storedBefore: roundStart) + } setNearVerdict(.up, direction: direction) return .up } @@ -407,6 +418,18 @@ final class SwapRouteAvailability { return .down } + /// When NEAR recovers, the sentinels' no-routes stored before this round (`roundStart`) come + /// from the outage, not from their own coins: drop them so this refresh asks those coins again + /// instead of waiting ten minutes. A no-route measured in this round is the coin's own answer. + private func forgetSentinelNoRoutes(direction: SwapDirection, storedBefore roundStart: Int) { + for sentinel in Self.nearSentinels { + let key = Key(direction, .near, sentinel) + if entries[key]?.state == .noRoute, storedSequence[key, default: 0] <= roundStart { + entries.removeValue(forKey: key) + } + } + } + private func setNearVerdict(_ verdict: NearVerdict, direction: SwapDirection) { let previous = readableVerdict(direction) let since = previous?.verdict == verdict ? previous?.since ?? now() : now() @@ -419,7 +442,9 @@ final class SwapRouteAvailability { /// One probe under the in-flight limit. Unless `force`d, an answer that is not yet due is /// reused — checked again after waiting for a permit, since another writer may have answered - /// meanwhile. A cancelled task gets `.unknown` without a request. + /// meanwhile. A cancelled task gets `.unknown` without a request. When the key got an answer + /// asked after this one while the request was in flight, the probe's answer is returned but + /// not stored. private func probeOne(_ key: Key, asset: String, force: Bool, probe: Probe) async -> LiveRouteState { if !force, !isDue(key) { return readableEntry(key)?.state ?? .unknown @@ -432,19 +457,29 @@ final class SwapRouteAvailability { if !force, !isDue(key) { return readableEntry(key)?.state ?? .unknown } + let asked = nextSequence() let state = await probe(asset, key.provider, key.direction) + guard storedSequence[key, default: -1] < asked else { + return state + } if state == .unknown { inconclusiveAt[key] = now() } else { inconclusiveAt[key] = nil - store(state, for: key) + store(state, for: key, asked: asked) } return state } - private func store(_ state: LiveRouteState, for key: Key) { + private func nextSequence() -> Int { + sequence += 1 + return sequence + } + + private func store(_ state: LiveRouteState, for key: Key, asked: Int) { let previous = self.state(of: key.provider, for: key.asset, direction: key.direction) entries[key] = Entry(state: state, checkedAt: now()) + storedSequence[key] = asked if previous != self.state(of: key.provider, for: key.asset, direction: key.direction) { changes.send(key.direction) } diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 481c3778bc..4df5664137 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -535,6 +535,59 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertFalse(message?.contains("connection") ?? true) } + /// The re-check changes only the address: same amount as the address quote, forced to the one + /// provider, no address at all (a different amount could change a no-route on its own). + func testTheReCheckAsksAtTheAddressQuotesAmountWithoutAnAddress() { + let addressQuote = SwapKitSwapProvider().addressCheckRequest(destination: "0xabc", toAsset: "ETH.ETH") + for provider in [RouteProvider.near, .maya] { + let reCheck = SwapKitSwapProvider.addressReCheckRequest(asset: "ETH.ETH", provider: provider) + XCTAssertEqual(reCheck.sellAmount, addressQuote.sellAmount, "\(provider)") + XCTAssertEqual(reCheck.buyAsset, "ETH.ETH") + XCTAssertNil(reCheck.destinationAddress) + XCTAssertNil(reCheck.sourceAddress) + XCTAssertEqual(reCheck.providers, provider.swapKitProviders) + } + } + + /// A below-minimum on the re-check is about the amount, not the address: the holder goes on to + /// the amount screen. A real route still means the address is what to fix. + func testABelowMinimumReCheckDoesNotBlameTheAddress() throws { + let coin = try reCheckedCoin() + let belowMinimum = SwapKitSwapProvider.addressReCheckState( + response(providerErrors: [providerError("sellAssetAmountTooSmall")])) + XCTAssertEqual(belowMinimum, .unknown) + XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([belowMinimum], coin: coin)) + + let routed = try JSONDecoder().decode(SwapKitQuoteResponse.self, + from: loadFixture(named: "swapkit_quote_response")) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckState(routed), .available) + let noRoute = response(providerErrors: [providerError("noRoutesFound")]) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckState(noRoute), .noRoute) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckState(nil), .unknown, "no answer is inconclusive") + } + + /// The address screen's no-route re-check as `validateAddress` runs it: one request per + /// no-route provider at the address quote's amount without an address; a below-minimum lets + /// the holder continue while the picker's store still records the route as available. + func testTheNoRouteReCheckReadsTheAnswerForTheAddressAndTheStoreApart() async { + let store = SwapRouteAvailability() + var sent: [SwapKitQuoteRequest] = [] + let belowMinimum = response(providerErrors: [providerError("sellAssetAmountTooSmall")]) + + let reAsked = await SwapKitSwapProvider.reCheckNoRoute([.near], asset: "ETH.ETH", store: store) { request in + sent.append(request) + return belowMinimum + } + + XCTAssertEqual(reAsked, [.unknown], "a below-minimum does not blame the address") + XCTAssertEqual(store.state(of: .near, for: "ETH.ETH", direction: .sell), .available) + XCTAssertEqual(sent.count, 1) + XCTAssertEqual(sent.first?.sellAmount, SwapKitSwapProvider.addressCheckAmount) + XCTAssertNil(sent.first?.destinationAddress) + XCTAssertNil(sent.first?.sourceAddress) + XCTAssertEqual(sent.first?.providers, RouteProvider.near.swapKitProviders) + } + func testAReCheckForAnUnknownCoinStillGivesAnAnswer() { XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.available], coin: nil), "validation_error") XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([.unknown], coin: nil)) diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift index 2a8148952c..a67f310a74 100644 --- a/DashWalletTests/SwapRouteAvailabilityTests.swift +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -420,6 +420,38 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "BTC.BTC", "AVAX.AVAX"]) } + /// When NEAR recovers, the other sentinels' no-routes from the outage are asked again in the + /// same refresh instead of keeping those coins halted for ten minutes. + func testARecoveryAsksTheOtherSentinelsAgain() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["ETH.ETH": [.near], "AVAX.AVAX": [.near]]) + XCTAssertEqual(store.state(of: .near, for: "ETH.ETH", direction: .sell), .noRoute) + + clock += 121 + SwapRouteAvailability.nearSentinels.forEach { script.set(.available, .near, $0) } + await refresh(["ETH.ETH": [.near], "AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "BTC.BTC", "ETH.ETH", "AVAX.AVAX"]) + XCTAssertEqual(store.state(of: .near, for: "ETH.ETH", direction: .sell), .available) + } + + /// A recovery keeps a sentinel's no-route measured in the same round: that coin is not asked + /// a second time in the refresh. + func testARecoveryKeepsANoRouteFromItsOwnRound() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["BTC.BTC": [.near], "AVAX.AVAX": [.near]]) + + clock += 121 + script.set(.available, .near, "ETH.ETH") + script.set(.available, .near, "AVAX.AVAX") + await refresh(["BTC.BTC": [.near], "AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "BTC.BTC", "ETH.ETH", "AVAX.AVAX"]) + XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .noRoute) + } + /// Re-confirming an outage does not bury a coin's own answer given after the outage began. func testAReConfirmedOutageKeepsANewerPerCoinAnswer() async { SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } @@ -593,6 +625,25 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(reported, [.sell], "an unchanged answer is not reported again") } + /// A picker probe still in flight when the address screen records a newer answer for the same + /// coin does not overwrite it when it returns. + func testAProbeThatReturnsAfterANewerAnswerIsDropped() async { + script.set(.noRoute, .maya, "ETH.USDT") + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let task = Task { @MainActor in + await store.refresh(assets: ["ETH.USDT"], direction: .sell, capable: { _ in [.maya] }, probe: probe) + } + await waitUntil { self.script.calls.count == 1 } + + store.record(.available, provider: .maya, asset: "ETH.USDT", direction: .sell) + script.openGate() + await task.value + + XCTAssertEqual(store.state(of: .maya, for: "ETH.USDT", direction: .sell), .available) + } + // MARK: Load func testNoMoreThanTwoProbesAreInFlight() async { diff --git a/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md b/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md index 320463203a..ac128eefd8 100644 --- a/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md +++ b/docs/adr/0008-detect-a-near-outage-from-sentinel-coins.md @@ -33,7 +33,7 @@ provider-wide verdict. **Positive** - A NEAR outage costs at most three checks per direction per two minutes. -- Recovery shows up while the picker is open; a coin whose own conclusive NEAR answer is newer than the outage keeps that answer. +- Recovery shows up while the picker is open; a coin whose own conclusive NEAR answer is newer than the outage keeps that answer. When a sentinel routes after a "down" verdict, the other sentinels' no-routes from the outage are dropped, so their coins are asked again in the same refresh. **Negative** - The sentinel list is hard-coded (`SwapRouteAvailability.nearSentinels`); if NEAR stops listing these coins, rounds end inconclusive and NEAR stays in the labels from the published lists. From 1638ae51a03557b9a6c69e3d3a8591052db7afb9 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 6 Nov 2026 16:04:55 +0200 Subject: [PATCH 4/8] Address PR review: requested-provider refusals and current sentinel answers - The address check counts a refusal only from a provider the quote asked for, so an unrequested provider's error cannot block a valid address. - The NEAR sentinel round reads the answers stored since it started, both to decide when to stop and for the verdict, so an older probe answer overtaken by a newer one (e.g. from the address quote) no longer declares NEAR down, and a no-route overtaken by a halt makes the round ask the third sentinel. Co-Authored-By: Claude Opus 5.5 SDD-Published-From: 9f2cf3bb437c434f74a7e704a00b72a71abbb30e --- .../Models/SwapKit/SwapKitSwapProvider.swift | 9 ++- .../SwapKit/SwapRouteAvailability.swift | 54 +++++++++------ .../SwapKitQuoteDecodingTests.swift | 15 ++++ .../SwapRouteAvailabilityTests.swift | 68 +++++++++++++++++++ 4 files changed, 124 insertions(+), 22 deletions(-) diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index 5023b11456..0d1b5123ff 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -307,15 +307,18 @@ final class SwapKitSwapProvider: SwapProvider { } // A refusal only counts for the SwapKit provider (a Maya flavour, say) that gave it: another - // one may still accept the request. A refusal from any other provider, or from none named, - // is ignored. When several refuse, the first in SwapKit's order is shown. + // one may still accept the request. A refusal from a provider the quote did not ask, from any + // other provider, or from none named, is ignored. When several refuse, the first in + // SwapKit's order is shown. let errors = response.providerErrors ?? [] var refusedBy: Set = [] var firstRefusal: String? for error in errors { guard let raw = code(error.errorCode), requestCodes.contains(raw.lowercased()) || refusedCoinCodes.contains(raw.lowercased()) else { continue } - guard let name = error.provider, RouteProvider(swapKitProvider: name) != nil else { continue } + guard let name = error.provider, + let provider = RouteProvider(swapKitProvider: name), + requested.contains(provider) else { continue } refusedBy.insert(name.uppercased()) firstRefusal = firstRefusal ?? raw } diff --git a/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift index 4b57211d71..58aee76641 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapRouteAvailability.swift @@ -369,6 +369,8 @@ final class SwapRouteAvailability { /// Asks `provider` about `asset` now, whatever is cached — for confirming an answer that came /// from a quote the probes cannot vouch for (one to a user-typed address). + /// Returns the probe's answer, or the newer stored one when the coin got an answer asked after + /// this probe (`probeOne`). @discardableResult func probeNow(asset: String, provider: RouteProvider, direction: SwapDirection, probe: Probe) async -> LiveRouteState { await probeOne(Key(direction, provider, asset), asset: asset, force: true, probe: probe) @@ -379,7 +381,8 @@ final class SwapRouteAvailability { /// conclusive no, so the third stands in for a halted or an inconclusive one. Two conclusive /// no-routes and none routing → NEAR is down. Fewer keeps the previous verdict. A route after /// a "down" verdict also drops the other sentinels' no-routes stored before this round, so - /// their coins are asked again. + /// their coins are asked again. Counting reads the sentinels' answers stored since the round + /// started, so an answer recorded meanwhile replaces the one asked. private func resolveNearVerdict(direction: SwapDirection, probe: @escaping Probe) async -> NearVerdict? { if let verdict = readableVerdict(direction), !isDue(verdict) { return verdict.verdict @@ -389,27 +392,29 @@ final class SwapRouteAvailability { } let roundStart = sequence - var noRoutes = 0 - for sentinel in Self.nearSentinels where noRoutes < 2 { + // An answer recorded for a sentinel while the round is asking (an address quote) replaces + // the one asked, so the round reads the sentinels' answers stored since it started. + // Only a no-route says something about NEAR as a whole; a halt is about that chain. + func thisRound() -> [LiveRouteState] { + Self.nearSentinels.compactMap { sentinel in + let key = Key(direction, .near, sentinel) + guard storedSequence[key, default: 0] > roundStart else { return nil } + return readableEntry(key)?.state + } + } + func noRoutes() -> Int { thisRound().filter { $0 == .noRoute }.count } + + for sentinel in Self.nearSentinels where noRoutes() < 2 { if Task.isCancelled { return readableVerdict(direction)?.verdict } - let state = await probeOne(Key(direction, .near, sentinel), asset: sentinel, force: true, probe: probe) - if state == .available { - inconclusiveRoundAt[direction] = nil - if readableVerdict(direction)?.verdict == .down { - forgetSentinelNoRoutes(direction: direction, storedBefore: roundStart) - } - setNearVerdict(.up, direction: direction) - return .up - } - // Only a no-route says something about NEAR as a whole; a halt is about that chain. - if state == .noRoute { - noRoutes += 1 + _ = await probeOne(Key(direction, .near, sentinel), asset: sentinel, force: true, probe: probe) + if thisRound().contains(.available) { + return nearIsUp(direction: direction, roundStart: roundStart) } } - guard noRoutes >= 2 else { + guard noRoutes() >= 2 else { inconclusiveRoundAt[direction] = now() return readableVerdict(direction)?.verdict } @@ -418,6 +423,17 @@ final class SwapRouteAvailability { return .down } + /// A sentinel routes: NEAR is up. After a "down" verdict, the other sentinels' outage-era + /// no-routes are dropped (`forgetSentinelNoRoutes`). + private func nearIsUp(direction: SwapDirection, roundStart: Int) -> NearVerdict { + inconclusiveRoundAt[direction] = nil + if readableVerdict(direction)?.verdict == .down { + forgetSentinelNoRoutes(direction: direction, storedBefore: roundStart) + } + setNearVerdict(.up, direction: direction) + return .up + } + /// When NEAR recovers, the sentinels' no-routes stored before this round (`roundStart`) come /// from the outage, not from their own coins: drop them so this refresh asks those coins again /// instead of waiting ten minutes. A no-route measured in this round is the coin's own answer. @@ -443,8 +459,8 @@ final class SwapRouteAvailability { /// One probe under the in-flight limit. Unless `force`d, an answer that is not yet due is /// reused — checked again after waiting for a permit, since another writer may have answered /// meanwhile. A cancelled task gets `.unknown` without a request. When the key got an answer - /// asked after this one while the request was in flight, the probe's answer is returned but - /// not stored. + /// asked after this one while the request was in flight, the probe's answer is dropped and the + /// newer stored answer is returned instead (`.unknown` when it is no longer readable). private func probeOne(_ key: Key, asset: String, force: Bool, probe: Probe) async -> LiveRouteState { if !force, !isDue(key) { return readableEntry(key)?.state ?? .unknown @@ -460,7 +476,7 @@ final class SwapRouteAvailability { let asked = nextSequence() let state = await probe(asset, key.provider, key.direction) guard storedSequence[key, default: -1] < asked else { - return state + return readableEntry(key)?.state ?? .unknown } if state == .unknown { inconclusiveAt[key] = now() diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 4df5664137..53110496a5 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -500,6 +500,21 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertEqual(SwapKitSwapProvider.addressCheck(nearHalted, requested: [.near]), .unavailable) } + /// A NEAR or Maya refusal counts only when the quote asked that provider: the swap would not + /// use one it did not ask. + func testAddressCheckIgnoresARefusalFromAnUnrequestedProvider() { + let mayaRefuses = response(providerErrors: [ + pe("MAYACHAIN", "invalidDestinationAddress"), pe("NEAR", "noRoutesFound"), + ]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(mayaRefuses, requested: [.near]), .confirmNoRoute([.near])) + let nearRefuses = response(providerErrors: [ + pe("NEAR", "invalidDestinationAddress"), pe("MAYACHAIN", "noRoutesFound"), + ]) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(nearRefuses, requested: [.maya]), .confirmNoRoute([.maya])) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(mayaRefuses, requested: [.near, .maya]), + .refused("invalidDestinationAddress")) + } + // MARK: Address check after the address-free re-check (AC-05) private let addressCopy = "We couldn't set up your swap. Please check the amount and address, then try again." diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift index a67f310a74..3de63a15f1 100644 --- a/DashWalletTests/SwapRouteAvailabilityTests.swift +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -644,6 +644,74 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(store.state(of: .maya, for: "ETH.USDT", direction: .sell), .available) } + /// A sentinel's answer overtaken by a newer one for the same coin does not count in the round: + /// BTC's stale no-route and ETH's no-route do not declare NEAR down over BTC's newer route. + func testASentinelAnswerOvertakenByANewerOneIsNotCounted() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let task = Task { @MainActor in + await store.refresh(assets: ["AVAX.AVAX"], direction: .sell, capable: { _ in [.near] }, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC"] } + + store.record(.available, provider: .near, asset: "BTC.BTC", direction: .sell) + script.openGate() + await task.value + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .available) + } + + /// A sentinel no-route already counted is overtaken by a route for that coin while the next + /// sentinel is asked: the round decides from what the store holds, so NEAR is up. + func testACountedSentinelNoRouteOvertakenLaterInTheRoundIsNotCounted() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let task = Task { @MainActor in + await store.refresh(assets: ["AVAX.AVAX"], direction: .sell, capable: { _ in [.near] }, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC"] } + script.openGate() + script.closeGate() + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC", "ETH.ETH"] } + XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .noRoute, "BTC's answer is stored") + + store.record(.available, provider: .near, asset: "BTC.BTC", direction: .sell) + script.openGate() + await task.value + + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .available) + } + + /// A counted sentinel no-route overtaken by a halt leaves BTC and ETH settling neither outcome, + /// so SOL is asked as the stand-in and its route decides. + func testACountedSentinelNoRouteOvertakenByAHaltAsksTheThird() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.set(.available, .near, "SOL.SOL") + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let task = Task { @MainActor in + await store.refresh(assets: ["AVAX.AVAX"], direction: .sell, capable: { _ in [.near] }, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC"] } + script.openGate() + script.closeGate() + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC", "ETH.ETH"] } + + store.record(.halted, provider: .near, asset: "BTC.BTC", direction: .sell) + script.openGate() + await task.value + + XCTAssertEqual(Array(script.calls(to: .near).prefix(3)), ["BTC.BTC", "ETH.ETH", "SOL.SOL"]) + XCTAssertEqual(store.nearVerdict(for: .sell), .up) + } + // MARK: Load func testNoMoreThanTwoProbesAreInFlight() async { From 884dea4a14b0c109b3c50dd25c69154ff797d1bb Mon Sep 17 00:00:00 2001 From: romchornyi Date: Tue, 10 Nov 2026 13:59:49 +0200 Subject: [PATCH 5/8] Order a NEAR outage by its round's start and log SwapKit failures Review: a NEAR "down" verdict took its boundary from the clock when the sentinel round finished, so a coin's route recorded while the round was still asking was hidden as "no route". The verdict now keeps the sequence at the start of the round that first found the outage; a coin's answer asked or recorded after it wins, one from before it does not. Spec wording, ADR-0012 and tests pin both sides. QA: the coin picker showed "Status Code: 403, Data Length: 4545" and the exported logs held no trace of it. A failed coin-list load and a failed route check now log the HTTP status, the path and a short body excerpt (an HTML page by its title); NEAR verdict changes and sentinel rounds that settle nothing are logged too. No key, query or address is logged. Co-Authored-By: Claude Opus 5.5 SDD-Published-From: af4a07dcbc494f1d6c12dff7d7162e7fc81926fb --- DashWallet.xcodeproj/project.pbxproj | 10 +++ .../Models/SwapKit/SwapKitFailureDetail.swift | 56 +++++++++++++ .../Models/SwapKit/SwapKitSwapProvider.swift | 10 ++- .../SwapKit/SwapRouteAvailability.swift | 26 +++--- .../Swap/SelectCoin/SelectCoinViewModel.swift | 2 + .../SwapKitFailureDetailTests.swift | 84 +++++++++++++++++++ .../SwapRouteAvailabilityTests.swift | 67 ++++++++++++++- ...etect-a-near-outage-from-sentinel-coins.md | 2 +- 8 files changed, 241 insertions(+), 16 deletions(-) create mode 100644 DashWallet/Sources/Models/SwapKit/SwapKitFailureDetail.swift create mode 100644 DashWalletTests/SwapKitFailureDetailTests.swift diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 2ccc7476b0..1a5e860009 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1178,6 +1178,9 @@ AA0010132CA0B10001A0B113 /* SwapKitSwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */; }; C5A11E000000000000000002 /* SwapRouteAvailability.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000001 /* SwapRouteAvailability.swift */; }; C5A11E000000000000000003 /* SwapRouteAvailability.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000001 /* SwapRouteAvailability.swift */; }; + C5A11E0000000000000000F2 /* SwapKitFailureDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */; }; + C5A11E0000000000000000F3 /* SwapKitFailureDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */; }; + C5A11E0000000000000000F5 /* SwapKitFailureDetailTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */; }; AA0020012FA0000000000014 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; AA0020012FA0000000000015 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; AA0020032FA0000000000003 /* SwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020022FA0000000000002 /* SwapProvider.swift */; }; @@ -3428,6 +3431,8 @@ AA0010102CA0B10001A0B110 /* swapkit_quote_response.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = swapkit_quote_response.json; sourceTree = ""; }; AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitSwapProvider.swift; sourceTree = ""; }; C5A11E000000000000000001 /* SwapRouteAvailability.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapRouteAvailability.swift; sourceTree = ""; }; + C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitFailureDetail.swift; sourceTree = ""; }; + C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitFailureDetailTests.swift; sourceTree = ""; }; AA0020012FA0000000000013 /* SwapExecutionData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapExecutionData.swift; sourceTree = ""; }; AA0020022FA0000000000002 /* SwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapProvider.swift; sourceTree = ""; }; AA0020052FA0000000000005 /* SwapBackend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapBackend.swift; sourceTree = ""; }; @@ -7724,6 +7729,7 @@ 7A11E5E70000000000000011 /* ResetWalletInfoWipeForwardingTests.swift */, CB9200012FE3000000000001 /* PassiveWalletStateUITailTests.swift */, AA0003032CA0F58E00A1B402 /* SwapAddressValidatorTests.swift */, + C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */, 5A7E0C1D2E3F405162738496 /* VotingKeyFormatTests.swift */, 5A7E0C1D2E3F405162738498 /* VotingKeyImportTests.swift */, AA00F1002FF0A10000A1B402 /* ExchangeAddressLookupContextTests.swift */, @@ -8003,6 +8009,7 @@ AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */, AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */, C5A11E000000000000000001 /* SwapRouteAvailability.swift */, + C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */, ); path = SwapKit; sourceTree = ""; @@ -10866,6 +10873,7 @@ AA00100B2CA0B10001A0B10B /* SwapKitAPIService.swift in Sources */, AA0010122CA0B10001A0B112 /* SwapKitSwapProvider.swift in Sources */, C5A11E000000000000000002 /* SwapRouteAvailability.swift in Sources */, + C5A11E0000000000000000F2 /* SwapKitFailureDetail.swift in Sources */, AA0020012FA0000000000014 /* SwapExecutionData.swift in Sources */, AA00020E2BA0F58E00A1B305 /* SelectCoinViewModel.swift in Sources */, AA0002142BA0F58E00A1B307 /* SelectCoinView.swift in Sources */, @@ -11105,6 +11113,7 @@ 7A11E5E70000000000000012 /* ResetWalletInfoWipeForwardingTests.swift in Sources */, CB9200022FE3000000000002 /* PassiveWalletStateUITailTests.swift in Sources */, AA0003042CA0F58E00A1B402 /* SwapAddressValidatorTests.swift in Sources */, + C5A11E0000000000000000F5 /* SwapKitFailureDetailTests.swift in Sources */, 5A7E0C1D2E3F405162738495 /* VotingKeyFormatTests.swift in Sources */, 5A7E0C1D2E3F405162738497 /* VotingKeyImportTests.swift in Sources */, AA00F1012FF0A10000A1B402 /* ExchangeAddressLookupContextTests.swift in Sources */, @@ -11984,6 +11993,7 @@ AA00100C2CA0B10001A0B10C /* SwapKitAPIService.swift in Sources */, AA0010132CA0B10001A0B113 /* SwapKitSwapProvider.swift in Sources */, C5A11E000000000000000003 /* SwapRouteAvailability.swift in Sources */, + C5A11E0000000000000000F3 /* SwapKitFailureDetail.swift in Sources */, AA0020012FA0000000000015 /* SwapExecutionData.swift in Sources */, AA00020F2BA0F58E00A1B305 /* SelectCoinViewModel.swift in Sources */, AA0002152BA0F58E00A1B307 /* SelectCoinView.swift in Sources */, diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitFailureDetail.swift b/DashWallet/Sources/Models/SwapKit/SwapKitFailureDetail.swift new file mode 100644 index 0000000000..f18ce2d35a --- /dev/null +++ b/DashWallet/Sources/Models/SwapKit/SwapKitFailureDetail.swift @@ -0,0 +1,56 @@ +// +// SwapKitFailureDetail.swift +// DashWallet +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +import Foundation + +/// One log line about a failed SwapKit request. `HTTPClientError.statusCode` renders as +/// "Status Code: 403, Data Length: 4545", which cannot tell SwapKit's own refusal (a JSON body) from +/// a page served in front of it (an HTML block page). This names the path (never the query or the +/// headers, so never the API key) and the body: an HTML page by its `` (any case, with or +/// without attributes; an empty one falls back to the body), anything else by its first characters +/// on one line. +enum SwapKitFailureDetail { + static let excerptLength = 200 + + static func describe(_ error: Error) -> String { + guard let clientError = error as? HTTPClientError, case .statusCode(let response) = clientError else { + return error.localizedDescription + } + let path = response.request?.url?.path ?? "?" + return "HTTP \(response.statusCode) \(path) (\(response.data.count) bytes): \(excerpt(of: response.data))" + } + + private static func excerpt(of data: Data) -> String { + guard let body = String(data: data, encoding: .utf8) else { return "<non-utf8 body>" } + let text = title(in: body).flatMap { $0.allSatisfy(\.isWhitespace) ? nil : $0 } ?? body + let line = text.split(whereSeparator: \.isWhitespace).joined(separator: " ") + return line.count > excerptLength ? line.prefix(excerptLength) + "…" : line + } + + private static func title(in html: String) -> String? { + guard let open = html.range(of: "<title", options: .caseInsensitive), + let tagEnd = html.range(of: ">", range: open.upperBound..<html.endIndex), + let close = html.range(of: "", options: .caseInsensitive, + range: tagEnd.upperBound..= probeAfter ? nil : $0 } let verdict = readableVerdict(direction).flatMap { freshOnly && isDue($0) ? nil : $0 } if provider == .near, let verdict, verdict.verdict == .down { - if let entry, entry.checkedAt > verdict.since { + if let entry, storedSequence[key, default: 0] > verdict.sinceSequence { return entry.state } return .noRoute @@ -415,11 +417,13 @@ final class SwapRouteAvailability { } guard noRoutes() >= 2 else { + let kept = readableVerdict(direction).map { "\($0.verdict)" } ?? "none" + DWLogger.log("SwapKit: NEAR sentinel round (\(direction)) settled nothing; keeping \(kept)") inconclusiveRoundAt[direction] = now() return readableVerdict(direction)?.verdict } inconclusiveRoundAt[direction] = nil - setNearVerdict(.down, direction: direction) + setNearVerdict(.down, direction: direction, roundStart: roundStart) return .down } @@ -430,7 +434,7 @@ final class SwapRouteAvailability { if readableVerdict(direction)?.verdict == .down { forgetSentinelNoRoutes(direction: direction, storedBefore: roundStart) } - setNearVerdict(.up, direction: direction) + setNearVerdict(.up, direction: direction, roundStart: roundStart) return .up } @@ -446,12 +450,14 @@ final class SwapRouteAvailability { } } - private func setNearVerdict(_ verdict: NearVerdict, direction: SwapDirection) { + private func setNearVerdict(_ verdict: NearVerdict, direction: SwapDirection, roundStart: Int) { let previous = readableVerdict(direction) - let since = previous?.verdict == verdict ? previous?.since ?? now() : now() - nearVerdicts[direction] = Verdict(verdict: verdict, checkedAt: now(), since: since) + let sinceSequence = previous?.verdict == verdict ? previous?.sinceSequence ?? roundStart : roundStart + nearVerdicts[direction] = Verdict(verdict: verdict, checkedAt: now(), sinceSequence: sinceSequence) let previousVerdict = previous?.verdict if previousVerdict != verdict { + let was = previousVerdict.map { "\($0)" } ?? "none" + DWLogger.log("SwapKit: NEAR verdict (\(direction)) \(was) → \(verdict)") changes.send(direction) } } diff --git a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift index 1f24f832fa..9df4f46b06 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift @@ -156,6 +156,8 @@ class SelectCoinViewModel: ObservableObject { swapProvider.refreshRouteAvailability(for: displayedPools, direction: direction) } } catch { + let detail = SwapKitFailureDetail.describe(error) + DWLogger.log("Swap: \(type(of: swapProvider)) coin list (\(direction)) failed to load — \(detail)") errorMessage = error.localizedDescription } } diff --git a/DashWalletTests/SwapKitFailureDetailTests.swift b/DashWalletTests/SwapKitFailureDetailTests.swift new file mode 100644 index 0000000000..db50a5027e --- /dev/null +++ b/DashWalletTests/SwapKitFailureDetailTests.swift @@ -0,0 +1,84 @@ +// +// SwapKitFailureDetailTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import Moya +import XCTest + +final class SwapKitFailureDetailTests: XCTestCase { + private static let swapToURL = "https://api.swapkit.dev/swapTo?sellAsset=DASH.DASH" + + private func statusError(_ code: Int, _ body: Data, url: String = swapToURL) throws -> Error { + let request = URLRequest(url: try XCTUnwrap(URL(string: url))) + return HTTPClientError.statusCode(Response(statusCode: code, data: body, request: request)) + } + + func testAnHTMLRefusalShowsItsTitleAndThePathWithoutTheQuery() throws { + let html = "\n\nAttention Required! | Cloudflare\n" + + "blocked" + let error = try statusError(403, Data(html.utf8)) + + XCTAssertEqual( + SwapKitFailureDetail.describe(error), + "HTTP 403 /swapTo (\(html.utf8.count) bytes): Attention Required! | Cloudflare" + ) + } + + func testATitleTagWithAttributesInAnyCaseIsRead() throws { + let html = "Blockedx" + let detail = SwapKitFailureDetail.describe(try statusError(403, Data(html.utf8))) + + XCTAssertEqual(detail, "HTTP 403 /swapTo (\(html.utf8.count) bytes): Blocked") + } + + func testAnEmptyTitleFallsBackToTheBody() throws { + let html = "

Access denied

" + let detail = SwapKitFailureDetail.describe(try statusError(403, Data(html.utf8))) + + XCTAssertEqual(detail, "HTTP 403 /swapTo (\(html.utf8.count) bytes):

Access denied

") + } + + func testAJSONBodyIsShownOnOneLine() throws { + let json = "{\"error\":\"apiKeyInvalid\",\n \"message\":\"apiKeyInvalid\",\"data\":{}}" + let error = try statusError(401, Data(json.utf8)) + let oneLine = "{\"error\":\"apiKeyInvalid\", \"message\":\"apiKeyInvalid\",\"data\":{}}" + + XCTAssertEqual(SwapKitFailureDetail.describe(error), "HTTP 401 /swapTo (\(json.utf8.count) bytes): \(oneLine)") + } + + func testALongBodyIsCut() throws { + let body = String(repeating: "a", count: 500) + let error = try statusError(429, Data(body.utf8), url: "https://api.swapkit.dev/v3/quote") + let detail = SwapKitFailureDetail.describe(error) + + XCTAssertEqual(detail, "HTTP 429 /v3/quote (500 bytes): " + String(repeating: "a", count: 200) + "…") + } + + func testANonUTF8BodyIsNamedNotPrinted() throws { + let detail = SwapKitFailureDetail.describe(try statusError(403, Data([0xFF, 0xFE, 0x00]))) + + XCTAssertEqual(detail, "HTTP 403 /swapTo (3 bytes): ") + } + + func testAnErrorWithoutAResponseUsesItsDescription() { + let error = URLError(.notConnectedToInternet) + + XCTAssertEqual(SwapKitFailureDetail.describe(error), error.localizedDescription) + } +} diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift index 3de63a15f1..ccfbe1ccc5 100644 --- a/DashWalletTests/SwapRouteAvailabilityTests.swift +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -250,6 +250,7 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(script.calls(to: .near), ["BTC.BTC", "ETH.ETH", "SOL.SOL"]) XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .halted, "its own answer") } func testAHaltedSentinelStoodInForByARoutingSOLMeansUp() async { @@ -452,7 +453,8 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(store.state(of: .near, for: "BTC.BTC", direction: .sell), .noRoute) } - /// Re-confirming an outage does not bury a coin's own answer given after the outage began. + /// Re-confirming an outage does not bury a coin's own answer recorded after the round that + /// first found the outage started. func testAReConfirmedOutageKeepsANewerPerCoinAnswer() async { SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } await refresh(["ARB.USDT": [.near]]) @@ -466,7 +468,7 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(label("ARB.USDT", capable: [.near]), .near) } - /// A coin's own answer newer than the outage verdict wins over it. + /// A coin's own answer recorded after the round that first found the outage started wins over it. func testANewerPerCoinAnswerOverridesTheNearOutage() async { SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } await refresh(["ARB.USDT": [.near]]) @@ -712,6 +714,67 @@ final class SwapRouteAvailabilityTests: XCTestCase { XCTAssertEqual(store.nearVerdict(for: .sell), .up) } + /// A coin's answer stored before the round that finds the outage is hidden by it. + func testAnAnswerFromBeforeTheOutageRoundIsHidden() async { + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(store.state(of: .near, for: "AVAX.AVAX", direction: .sell), .available) + + clock += 601 + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(store.state(of: .near, for: "AVAX.AVAX", direction: .sell), .noRoute) + } + + /// A probe asked before the round that finds the outage, returning while the round is asking, + /// is ordered by when it was asked: the outage hides it. + func testAProbeAskedBeforeTheOutageRoundIsHidden() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let check = Task { @MainActor in + await store.probeNow(asset: "AVAX.AVAX", provider: .near, direction: .sell, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["AVAX.AVAX"] } + let round = Task { @MainActor in + await store.refresh(assets: ["AVAX.AVAX"], direction: .sell, capable: { _ in [.near] }, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["AVAX.AVAX", "BTC.BTC"] } + script.openGate() + _ = await check.value + await round.value + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(store.state(of: .near, for: "AVAX.AVAX", direction: .sell), .noRoute) + } + + /// A coin's own route recorded while the round that finds the outage is still asking comes after + /// that round started: the round finishing later does not hide it. + func testACoinRouteRecordedDuringTheOutageRoundStaysUsable() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + script.closeGate() + let store: SwapRouteAvailability = self.store + let probe = script.probe + let task = Task { @MainActor in + await store.refresh(assets: ["AVAX.AVAX"], direction: .sell, capable: { _ in [.near] }, probe: probe) + } + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC"] } + script.openGate() + script.closeGate() + await waitUntil { self.script.calls(to: .near) == ["BTC.BTC", "ETH.ETH"] } + + store.record(.available, provider: .near, asset: "AVAX.AVAX", direction: .sell) + clock += 1 + script.openGate() + await task.value + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(store.state(of: .near, for: "AVAX.AVAX", direction: .sell), .available) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + } + // MARK: Load func testNoMoreThanTwoProbesAreInFlight() async { diff --git a/docs/adr/0012-detect-a-near-outage-from-sentinel-coins.md b/docs/adr/0012-detect-a-near-outage-from-sentinel-coins.md index ac72230646..0503af77fc 100644 --- a/docs/adr/0012-detect-a-near-outage-from-sentinel-coins.md +++ b/docs/adr/0012-detect-a-near-outage-from-sentinel-coins.md @@ -33,7 +33,7 @@ provider-wide verdict. **Positive** - A NEAR outage costs at most three checks per direction per two minutes. -- Recovery shows up while the picker is open; a coin whose own conclusive NEAR answer is newer than the outage keeps that answer. When a sentinel routes after a "down" verdict, the other sentinels' no-routes from the outage are dropped, so their coins are asked again in the same refresh. +- Recovery shows up while the picker is open; a coin whose own conclusive NEAR answer was asked or recorded after the round that first found NEAR down started keeps that answer, also one recorded while that round was still asking (a check asked before it does not, even when it returns during the round); a round that re-confirms the outage does not move that point. When a sentinel routes after a "down" verdict, the other sentinels' no-routes from the outage are dropped, so their coins are asked again in the same refresh. **Negative** - The sentinel list is hard-coded (`SwapRouteAvailability.nearSentinels`); if NEAR stops listing these coins, rounds end inconclusive and NEAR stays in the labels from the published lists. From 6d02a225ae590af85c6dc197f9f00d6133c34426 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Tue, 10 Nov 2026 16:57:16 +0200 Subject: [PATCH 6/8] Record a provider halt the quote reports beside a route A quote to the user's address that carried a route never looked at the provider errors, so a halted provider beside the route (Maya halted while NEAR routes) was not recorded; a route from one Maya flavour still outweighs the other flavour's halt. The swap live routes summary now words two guarantees as the code keeps them: an earlier conclusive answer keeps applying after an inconclusive re-check, and the address screen re-checks a "no route" outside the picker. Review round 26 on #1297: thepastaclaw 4525313507, CodeRabbit 4524711754 and 4524711764. SDD-Published-From: 8b5e623ae43ab4ee53a336d6576f9cba18f0dc42 --- .../Models/SwapKit/SwapKitSwapProvider.swift | 29 ++++++++-------- .../SwapKitQuoteDecodingTests.swift | 33 +++++++++++++++++++ docs/features/swap-live-routes/README.md | 8 +++-- 3 files changed, 54 insertions(+), 16 deletions(-) diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index b813266a56..ddae0799eb 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -382,7 +382,9 @@ final class SwapKitSwapProvider: SwapProvider { } let requested = Set((request.providers ?? []).compactMap { RouteProvider(swapKitProvider: $0) }) - recordQuoteOutcome(response, requested: requested, asset: toAsset, direction: .sell) + Self.recordQuoteOutcome( + response, requested: requested, asset: toAsset, direction: .sell, store: routeAvailability + ) let check = Self.addressCheck(response, requested: requested) if check != .pass { @@ -973,22 +975,23 @@ final class SwapKitSwapProvider: SwapProvider { /// Feeds what a quote to the user's address said about `asset` into the live store. Only what /// cannot depend on the address is recorded: a route names the providers that carry it, and a /// provider's halt names the provider that is halted. A no-route is left to the address-free - /// re-probe in `validateAddress`. - private func recordQuoteOutcome( + /// re-probe in `validateAddress`. Internal rather than private so the tests can feed it an answer. + static func recordQuoteOutcome( _ response: SwapKitQuoteResponse, requested: Set, asset: String, - direction: SwapDirection + direction: SwapDirection, + store: SwapRouteAvailability ) { - if let routes = response.routes, !routes.isEmpty { - let carrying = Set(routes.flatMap { $0.providers }.compactMap { RouteProvider(swapKitProvider: $0) }) - for provider in carrying.intersection(requested) { - routeAvailability.record(.available, provider: provider, asset: asset, direction: direction) - } - return + let carrying = Set( + (response.routes ?? []).flatMap { $0.providers }.compactMap { RouteProvider(swapKitProvider: $0) } + ) + for provider in carrying.intersection(requested) { + store.record(.available, provider: provider, asset: asset, direction: direction) } - // Both Maya flavours answer for `.maya`: it is halted only when no flavour says otherwise. + // Both Maya flavours answer for `.maya`: it is halted only when no flavour says otherwise, + // and a route from either flavour says otherwise. var halted = Set() var notHalted = Set() for error in response.providerErrors ?? [] { @@ -1000,8 +1003,8 @@ final class SwapKitSwapProvider: SwapProvider { notHalted.insert(provider) } } - for provider in halted.subtracting(notHalted) { - routeAvailability.record(.halted, provider: provider, asset: asset, direction: direction) + for provider in halted.subtracting(notHalted).subtracting(carrying) { + store.record(.halted, provider: provider, asset: asset, direction: direction) } } diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 53110496a5..5501be72db 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -631,6 +631,39 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertFalse(SwapKitErrorCopy.isHalted(nil)) } + // MARK: SwapKitSwapProvider.recordQuoteOutcome + + /// A NEAR route beside a Maya halt: both are recorded, not only the route. + func testAQuoteRecordsAHaltBesideARoute() throws { + let store = SwapRouteAvailability() + let mixed = try decoded(#""" + {"routes":[{"routeId":"r","providers":["NEAR"],"expectedBuyAmount":"1"}], + "providerErrors":[{"provider":"MAYACHAIN_STREAMING","errorCode":"swapHalted"}]} + """#) + + SwapKitSwapProvider.recordQuoteOutcome( + mixed, requested: [.near, .maya], asset: "ETH.ETH", direction: .sell, store: store + ) + + XCTAssertEqual(store.state(of: .near, for: "ETH.ETH", direction: .sell), .available) + XCTAssertEqual(store.state(of: .maya, for: "ETH.ETH", direction: .sell), .halted) + } + + /// One Maya flavour routes while the other is halted: Maya carries it, so it stays available. + func testAMayaRouteOutweighsTheOtherMayaFlavoursHalt() throws { + let store = SwapRouteAvailability() + let mixed = try decoded(#""" + {"routes":[{"routeId":"r","providers":["MAYACHAIN"],"expectedBuyAmount":"1"}], + "providerErrors":[{"provider":"MAYACHAIN_STREAMING","errorCode":"swapHalted"}]} + """#) + + SwapKitSwapProvider.recordQuoteOutcome( + mixed, requested: [.near, .maya], asset: "ETH.ETH", direction: .sell, store: store + ) + + XCTAssertEqual(store.state(of: .maya, for: "ETH.ETH", direction: .sell), .available) + } + // MARK: Address check without a readable answer private let connectionCopy = "Address validation unavailable — please check your connection" diff --git a/docs/features/swap-live-routes/README.md b/docs/features/swap-live-routes/README.md index b51d338193..f4e10a9e83 100644 --- a/docs/features/swap-live-routes/README.md +++ b/docs/features/swap-live-routes/README.md @@ -35,9 +35,11 @@ the address screen reported every refusal as a connection problem. ## What it guarantees - A coin no provider can route right now is shown halted and cannot be picked, when the published token lists name it. -- An inconclusive answer never halts a coin; the coin keeps its published label. -- At most two checks are in flight; checks run only while the picker is open; no address leaves the - device in a check. +- An inconclusive answer is not stored and never halts a coin by itself; an earlier conclusive answer + keeps applying until a new one replaces it or it is due for a re-check. +- At most two checks are in flight; periodic checks start only while the picker is open (one already + asked may finish after it closes), and the address screen re-checks a "no route" once without the + address; no address leaves the device in a check. ## Not in scope From 093b4b6c163ed4bf36f4973db4b4b08ac68b5930 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Tue, 10 Nov 2026 18:21:33 +0200 Subject: [PATCH 7/8] Keep the newest coin list load and pass only requested routes Closes the PR #1297 review round of 2026-11-10 16:01Z: an older overlapping coin list load no longer commits its pools or starts route checks after a newer one (thread r4527231138); the address check passes only on a route a requested provider carries (r4527231147); the README states the halted, expiry and address guarantees as the code keeps them (r4527231218, r4526558156, r4526558173). Co-Authored-By: Claude Opus 5.5 SDD-Published-From: ee3e6c411eeb6bb191b121b6cabaf1c629501ae0 --- DashWallet.xcodeproj/project.pbxproj | 4 + .../Models/SwapKit/SwapKitSwapProvider.swift | 5 +- .../Swap/SelectCoin/SelectCoinViewModel.swift | 10 +- .../SelectCoinViewModelTests.swift | 107 ++++++++++++++++++ .../SwapKitQuoteDecodingTests.swift | 15 +++ docs/features/swap-live-routes/README.md | 8 +- 6 files changed, 144 insertions(+), 5 deletions(-) create mode 100644 DashWalletTests/SelectCoinViewModelTests.swift diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 64061a55b0..dcad3c857b 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1126,6 +1126,7 @@ C5A11E000000000000000003 /* SwapRouteAvailability.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E000000000000000001 /* SwapRouteAvailability.swift */; }; C5A11E0000000000000000F2 /* SwapKitFailureDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */; }; C5A11E0000000000000000F3 /* SwapKitFailureDetail.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */; }; + C5A11E0000000000000000F7 /* SelectCoinViewModelTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F6 /* SelectCoinViewModelTests.swift */; }; C5A11E0000000000000000F5 /* SwapKitFailureDetailTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */; }; AA0020012FA0000000000014 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; AA0020012FA0000000000015 /* SwapExecutionData.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020012FA0000000000013 /* SwapExecutionData.swift */; }; @@ -3275,6 +3276,7 @@ AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitSwapProvider.swift; sourceTree = ""; }; C5A11E000000000000000001 /* SwapRouteAvailability.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapRouteAvailability.swift; sourceTree = ""; }; C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitFailureDetail.swift; sourceTree = ""; }; + C5A11E0000000000000000F6 /* SelectCoinViewModelTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SelectCoinViewModelTests.swift; sourceTree = ""; }; C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapKitFailureDetailTests.swift; sourceTree = ""; }; AA0020012FA0000000000013 /* SwapExecutionData.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapExecutionData.swift; sourceTree = ""; }; AA0020022FA0000000000002 /* SwapProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapProvider.swift; sourceTree = ""; }; @@ -7403,6 +7405,7 @@ 7A11E5E70000000000000011 /* ResetWalletInfoWipeForwardingTests.swift */, CB9200012FE3000000000001 /* PassiveWalletStateUITailTests.swift */, AA0003032CA0F58E00A1B402 /* SwapAddressValidatorTests.swift */, + C5A11E0000000000000000F6 /* SelectCoinViewModelTests.swift */, C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */, 5A7E0C1D2E3F405162738496 /* VotingKeyFormatTests.swift */, 5A7E0C1D2E3F405162738498 /* VotingKeyImportTests.swift */, @@ -10727,6 +10730,7 @@ 7A11E5E70000000000000012 /* ResetWalletInfoWipeForwardingTests.swift in Sources */, CB9200022FE3000000000002 /* PassiveWalletStateUITailTests.swift in Sources */, AA0003042CA0F58E00A1B402 /* SwapAddressValidatorTests.swift in Sources */, + C5A11E0000000000000000F7 /* SelectCoinViewModelTests.swift in Sources */, C5A11E0000000000000000F5 /* SwapKitFailureDetailTests.swift in Sources */, 5A7E0C1D2E3F405162738495 /* VotingKeyFormatTests.swift in Sources */, 5A7E0C1D2E3F405162738497 /* VotingKeyImportTests.swift in Sources */, diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index ddae0799eb..65f9450411 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -293,7 +293,10 @@ final class SwapKitSwapProvider: SwapProvider { /// the quote named (`addressCheckRequest`), never empty: `sellQuoteProviders` always names NEAR /// or Maya. static func addressCheck(_ response: SwapKitQuoteResponse, requested: Set) -> AddressCheck { - if response.routes?.isEmpty == false { + // Only a route an asked provider carries counts: the swap would not use another one. + let routed = Set((response.routes ?? []).flatMap { $0.providers } + .compactMap { RouteProvider(swapKitProvider: $0) }) + if !routed.isDisjoint(with: requested) { return .pass } diff --git a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift index 9df4f46b06..9ca2f41145 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift @@ -56,6 +56,9 @@ class SelectCoinViewModel: ObservableObject { private var routeFreshnessRuns = 0 /// Identifies the latest render, so a slower older one does not publish over it. private var renderGeneration = 0 + /// Identifies the latest load: loads can overlap (the view's `.task` and a reconnect), and only + /// the latest one commits what it fetched. + private var loadGeneration = 0 /// How often the live checks are re-run while the picker is on screen. Only answers that are due /// are asked again, so most ticks send nothing. @@ -128,13 +131,15 @@ class SelectCoinViewModel: ObservableObject { func loadCoins(force: Bool = false) async { guard isOnline else { return } guard force || coins.isEmpty || errorMessage != nil else { return } + loadGeneration += 1 + let generation = loadGeneration let shouldShowLoading = coins.isEmpty || errorMessage != nil if shouldShowLoading { isLoading = true } errorMessage = nil defer { - if shouldShowLoading { + if shouldShowLoading, generation == loadGeneration { isLoading = false } } @@ -145,9 +150,11 @@ class SelectCoinViewModel: ObservableObject { // would then filter out every pool via inboundChains. let pools = try await swapProvider.fetchPools(direction: direction) let inboundAddresses = try await swapProvider.fetchInboundAddresses() + guard generation == loadGeneration else { return } loadedPools = pools loadedInboundAddresses = inboundAddresses let sorted = await render(pools: pools, inboundAddresses: inboundAddresses) + guard generation == loadGeneration else { return } let poolsByAsset = Dictionary(pools.map { ($0.asset.uppercased(), $0) }, uniquingKeysWith: { first, _ in first }) displayedPools = sorted.compactMap { poolsByAsset[$0.coin.swapAsset.uppercased()] } // A load that lands while the picker is on screen (after reconnecting, say) starts the @@ -158,6 +165,7 @@ class SelectCoinViewModel: ObservableObject { } catch { let detail = SwapKitFailureDetail.describe(error) DWLogger.log("Swap: \(type(of: swapProvider)) coin list (\(direction)) failed to load — \(detail)") + guard generation == loadGeneration else { return } errorMessage = error.localizedDescription } } diff --git a/DashWalletTests/SelectCoinViewModelTests.swift b/DashWalletTests/SelectCoinViewModelTests.swift new file mode 100644 index 0000000000..ccd8a14b15 --- /dev/null +++ b/DashWalletTests/SelectCoinViewModelTests.swift @@ -0,0 +1,107 @@ +// +// SelectCoinViewModelTests.swift +// DashWalletTests +// +// Copyright © 2026 Dash Core Group. All rights reserved. +// +// Licensed under the MIT License (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://opensource.org/licenses/MIT +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +// + +@testable import dashpay +import Combine +import XCTest + +/// Answers each pool fetch from a script; a fetch scripted as held waits until it is released. +@MainActor +private final class ScriptedPoolsProvider: SwapProvider { + var poolAnswers: [[String]] = [] + private(set) var refreshed: [[String]] = [] + private var held: CheckedContinuation? + var holdsNextFetch = false + var isHolding: Bool { held != nil } + + var displayName: String { "Scripted" } + var routeAvailabilityChanges: AnyPublisher { Empty().eraseToAnyPublisher() } + + func release() { + held?.resume() + held = nil + } + + func fetchPools() async throws -> [SwapPool] { + let assets = poolAnswers.removeFirst() + if holdsNextFetch { + holdsNextFetch = false + await withCheckedContinuation { held = $0 } + } + // A zero price shows no fiat row, which keeps the currency exchanger out of the test. + return assets.map { SwapPool(asset: $0, status: "available", assetPriceUSD: "0") } + } + + func fetchInboundAddresses() async throws -> [SwapInboundAddress] { + ["BTC", "ETH"].map { + SwapInboundAddress( + chain: $0, halted: false, address: nil, chainLpActionsPaused: nil, chainTradingPaused: nil, + dustThreshold: nil, gasRate: nil, gasRateUnits: nil, globalTradingPaused: nil, + outboundFee: nil, outboundTxSize: nil, pubKey: nil + ) + } + } + + func fetchPools(direction: SwapDirection) async throws -> [SwapPool] { try await fetchPools() } + + func refreshRouteAvailability(for pools: [SwapPool], direction: SwapDirection) { + refreshed.append(pools.map { $0.asset }) + } + + func validateAddress(destination: String, toAsset: String) async -> String? { nil } + func fetchQuote(dashSatoshis: Int64, toAsset: String, destination: String) async throws -> SwapQuoteResult { + throw SwapProviderError.unsupportedBuyOrder + } + func fetchSwapStatus(txid: String, depositAddress: String?) async throws -> SwapStatusResult { + throw SwapProviderError.unsupportedBuyOrder + } +} + +/// Online, and silent: no status event starts a load the test did not ask for. +private final class SilentOnlineStatus: NetworkStatusProviding { + var currentStatus: NetworkStatus { .online } + var isOnline: Bool { true } + var statusPublisher: AnyPublisher { Empty().eraseToAnyPublisher() } +} + +@MainActor +final class SelectCoinViewModelTests: XCTestCase { + /// Two loads overlap (the view's `.task` and a reconnect, say) and the older one ends last: the + /// rows and the live checks stay on the newer load's pools. + func testAnOlderLoadThatEndsLastDoesNotReplaceTheNewerOne() async { + let provider = ScriptedPoolsProvider() + provider.poolAnswers = [["BTC.BTC"], ["ETH.ETH"]] + provider.holdsNextFetch = true + let model = SelectCoinViewModel(swapProvider: provider, direction: .sell, networkStatus: SilentOnlineStatus()) + let checks = Task { await model.keepRouteAvailabilityFresh() } + defer { checks.cancel() } + + let older = Task { await model.loadCoins() } + while !provider.isHolding { await Task.yield() } + await model.loadCoins(force: true) + XCTAssertEqual(model.coins.map { $0.coin.swapAsset.uppercased() }, ["ETH.ETH"]) + + provider.release() + await older.value + + XCTAssertEqual(model.coins.map { $0.coin.swapAsset.uppercased() }, ["ETH.ETH"]) + XCTAssertEqual(provider.refreshed.last, ["ETH.ETH"]) + XCTAssertFalse(model.isLoading) + } +} diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 5501be72db..244d5245df 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -515,6 +515,21 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { .refused("invalidDestinationAddress")) } + /// A route only a provider the quote did not ask can carry does not pass the address: the swap + /// would not use it, so the asked provider's own answer decides. + func testAddressCheckIgnoresARouteFromAnUnrequestedProvider() throws { + let thorRoutes = try decoded(#""" + {"routes":[{"routeId":"r","providers":["THORCHAIN"],"expectedBuyAmount":"1"}], + "providerErrors":[{"provider":"NEAR","errorCode":"swapHalted"}]} + """#) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(thorRoutes, requested: [.near]), .unavailable) + let nearRoutes = try decoded(#""" + {"routes":[{"routeId":"r","providers":["NEAR"],"expectedBuyAmount":"1"}], + "providerErrors":[{"provider":"MAYACHAIN","errorCode":"swapHalted"}]} + """#) + XCTAssertEqual(SwapKitSwapProvider.addressCheck(nearRoutes, requested: [.near, .maya]), .pass) + } + // MARK: Address check after the address-free re-check (AC-05) private let addressCopy = "We couldn't set up your swap. Please check the amount and address, then try again." diff --git a/docs/features/swap-live-routes/README.md b/docs/features/swap-live-routes/README.md index f4e10a9e83..60c1a0f977 100644 --- a/docs/features/swap-live-routes/README.md +++ b/docs/features/swap-live-routes/README.md @@ -34,12 +34,14 @@ the address screen reported every refusal as a connection problem. ## What it guarantees -- A coin no provider can route right now is shown halted and cannot be picked, when the published token lists name it. +- A coin is shown halted and cannot be picked when the stored answers rule out every provider that + can carry it and the published token lists name it; a provider with no stored answer counts as usable. - An inconclusive answer is not stored and never halts a coin by itself; an earlier conclusive answer - keeps applying until a new one replaces it or it is due for a re-check. + keeps applying until a new one replaces it or it expires (30 minutes). - At most two checks are in flight; periodic checks start only while the picker is open (one already asked may finish after it closes), and the address screen re-checks a "no route" once without the - address; no address leaves the device in a check. + address. The route checks and that re-check send no address; only the address screen's own quote + to the entered address does. ## Not in scope From e5c7b9fb07fe4c3c417e14078ae93d7be6992214 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Tue, 10 Nov 2026 21:00:24 +0200 Subject: [PATCH 8/8] Let the address re-check read a newer stored answer When a quote records a route for the coin while the address screen's no-route re-check is asking, the re-check now reports that newer answer instead of its own older no-route (review: re-check ignores a newer stored answer). The README names every quote that sends the entered address (review: address claim overstated). Co-Authored-By: Claude Opus 5.5 SDD-Published-From: 04e23df4567e99102ce7691bc0c5a7b9d60e3def --- .../Models/SwapKit/SwapKitSwapProvider.swift | 12 ++++++++---- DashWalletTests/SwapKitQuoteDecodingTests.swift | 15 +++++++++++++++ docs/features/swap-live-routes/README.md | 4 ++-- 3 files changed, 25 insertions(+), 6 deletions(-) diff --git a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift index 65f9450411..f06e7ab361 100644 --- a/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift +++ b/DashWallet/Sources/Models/SwapKit/SwapKitSwapProvider.swift @@ -427,7 +427,8 @@ final class SwapKitSwapProvider: SwapProvider { /// Asks each of `noRouteProviders` (NEAR, then Maya) again through `quote` at the address /// quote's amount without the address: if a provider routes there, the address is what to fix. /// Returns each answer as read for the address (`addressReCheckState`); `store` records the - /// usual classification (`LiveRouteState.classify`). + /// usual classification (`LiveRouteState.classify`). When an answer recorded while the re-check + /// was asking is newer, the store keeps it and the re-check returns it instead. static func reCheckNoRoute( _ noRouteProviders: Set, asset: String, @@ -437,12 +438,15 @@ final class SwapKitSwapProvider: SwapProvider { var reAsked: [LiveRouteState] = [] for provider in [RouteProvider.near, .maya] where noRouteProviders.contains(provider) { var reCheck = LiveRouteState.unknown - await store.probeNow(asset: asset, provider: provider, direction: .sell) { asset, provider, _ in + var asked = LiveRouteState.unknown + let kept = await store.probeNow(asset: asset, provider: provider, direction: .sell) { asset, provider, _ in let response = await quote(addressReCheckRequest(asset: asset, provider: provider)) reCheck = addressReCheckState(response) - return response.map(LiveRouteState.classify) ?? .unknown + asked = response.map(LiveRouteState.classify) ?? .unknown + return asked } - reAsked.append(reCheck) + // A different state back means a newer answer recorded meanwhile won over this one. + reAsked.append(kept == asked ? reCheck : kept) } return reAsked } diff --git a/DashWalletTests/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 244d5245df..8be982108f 100644 --- a/DashWalletTests/SwapKitQuoteDecodingTests.swift +++ b/DashWalletTests/SwapKitQuoteDecodingTests.swift @@ -618,6 +618,21 @@ final class SwapKitQuoteBoundaryTests: XCTestCase { XCTAssertEqual(sent.first?.providers, RouteProvider.near.swapKitProviders) } + /// A quote that records a route while the re-check is asking is newer than the re-check's own + /// no-route: the store keeps the route, and the address screen reads it (the address is what + /// to fix), not the older no-route. + func testTheReCheckReadsARouteRecordedWhileItWasAsking() async { + let store = SwapRouteAvailability() + + let reAsked = await SwapKitSwapProvider.reCheckNoRoute([.near], asset: "ETH.ETH", store: store) { _ in + store.record(.available, provider: .near, asset: "ETH.ETH", direction: .sell) + return self.response(providerErrors: [self.providerError("noRoutesFound")]) + } + + XCTAssertEqual(store.state(of: .near, for: "ETH.ETH", direction: .sell), .available) + XCTAssertEqual(reAsked, [.available]) + } + func testAReCheckForAnUnknownCoinStillGivesAnAnswer() { XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.available], coin: nil), "validation_error") XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([.unknown], coin: nil)) diff --git a/docs/features/swap-live-routes/README.md b/docs/features/swap-live-routes/README.md index 60c1a0f977..2fd96b5f9d 100644 --- a/docs/features/swap-live-routes/README.md +++ b/docs/features/swap-live-routes/README.md @@ -40,8 +40,8 @@ the address screen reported every refusal as a connection problem. keeps applying until a new one replaces it or it expires (30 minutes). - At most two checks are in flight; periodic checks start only while the picker is open (one already asked may finish after it closes), and the address screen re-checks a "no route" once without the - address. The route checks and that re-check send no address; only the address screen's own quote - to the entered address does. + address. The route checks and that re-check send no address; the address screen's own quote and + the amount and confirmation quotes send the entered address. ## Not in scope