diff --git a/DashWallet.xcodeproj/project.pbxproj b/DashWallet.xcodeproj/project.pbxproj index 2174677aa4..dcad3c857b 100644 --- a/DashWallet.xcodeproj/project.pbxproj +++ b/DashWallet.xcodeproj/project.pbxproj @@ -1118,9 +1118,16 @@ 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 */; }; + 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 */; }; AA0020032FA0000000000003 /* SwapProvider.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA0020022FA0000000000002 /* SwapProvider.swift */; }; @@ -3264,8 +3271,13 @@ 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 = ""; }; + 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 = ""; }; AA0020052FA0000000000005 /* SwapBackend.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SwapBackend.swift; sourceTree = ""; }; @@ -7393,10 +7405,13 @@ 7A11E5E70000000000000011 /* ResetWalletInfoWipeForwardingTests.swift */, CB9200012FE3000000000001 /* PassiveWalletStateUITailTests.swift */, AA0003032CA0F58E00A1B402 /* SwapAddressValidatorTests.swift */, + C5A11E0000000000000000F6 /* SelectCoinViewModelTests.swift */, + C5A11E0000000000000000F4 /* SwapKitFailureDetailTests.swift */, 5A7E0C1D2E3F405162738496 /* VotingKeyFormatTests.swift */, 5A7E0C1D2E3F405162738498 /* VotingKeyImportTests.swift */, AA00F1002FF0A10000A1B402 /* ExchangeAddressLookupContextTests.swift */, AA00100D2CA0B10001A0B10D /* SwapKitQuoteDecodingTests.swift */, + C5A11E000000000000000004 /* SwapRouteAvailabilityTests.swift */, 5EAD222130A0000000A1B202 /* DashAmountFormatterTests.swift */, DA57A1010000000000000001 /* PastedAmountNormalizationTests.swift */, DA5A00000000000000000005 /* DashPayIdentityKeysTests.swift */, @@ -7671,6 +7686,8 @@ AA0010072CA0B10001A0B107 /* SwapKitModels.swift */, AA00100A2CA0B10001A0B10A /* SwapKitAPIService.swift */, AA0010112CA0B10001A0B111 /* SwapKitSwapProvider.swift */, + C5A11E000000000000000001 /* SwapRouteAvailability.swift */, + C5A11E0000000000000000F1 /* SwapKitFailureDetail.swift */, ); path = SwapKit; sourceTree = ""; @@ -10467,6 +10484,8 @@ AA0010082CA0B10001A0B108 /* SwapKitModels.swift in Sources */, 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 */, @@ -10711,10 +10730,13 @@ 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 */, 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 */, @@ -11534,6 +11556,8 @@ AA0010092CA0B10001A0B109 /* SwapKitModels.swift in Sources */, 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/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/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.. 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,24 +268,236 @@ 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` is the providers + /// the quote named (`addressCheckRequest`), never empty: `sellQuoteProviders` always names NEAR + /// or Maya. + static func addressCheck(_ response: SwapKitQuoteResponse, requested: Set) -> AddressCheck { + // 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 + } + + 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 refusal only counts for the SwapKit provider (a Maya flavour, say) that gave it: another + // 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, + let provider = RouteProvider(swapKitProvider: name), + requested.contains(provider) else { continue } + refusedBy.insert(name.uppercased()) + firstRefusal = firstRefusal ?? raw + } + + // The quote asked every usable provider at once; each one is judged on its own answer. + let states = judgedWithoutRefusals(LiveRouteState.classifyPerProvider(response, requested: requested), + errors: errors, refusedBy: refusedBy) + if states.values.contains(where: { $0.isUsable }) { + return .pass + } + 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). + /// + /// 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? { - let request = SwapKitQuoteRequest( + if !classificationBuilt { await buildClassification() } + let request = addressCheckRequest(destination: destination, toAsset: toAsset) + + let response: SwapKitQuoteResponse + do { + response = try await SwapKitAPIService.shared.quote(request) + } catch { + // 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 Self.addressCheckFailureMessage(for: error) + } + response = decoded + } + + let requested = Set((request.providers ?? []).compactMap { RouteProvider(swapKitProvider: $0) }) + Self.recordQuoteOutcome( + response, requested: requested, asset: toAsset, direction: .sell, store: routeAvailability + ) + + 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): + 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`). 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, + 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 + 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) + asked = response.map(LiveRouteState.classify) ?? .unknown + return asked + } + // A different state back means a newer answer recorded meanwhile won over this one. + reAsked.append(kept == asked ? reCheck : kept) + } + 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 — only the address format is being validated + sellAmount: Self.addressCheckAmount, slippage: SwapKitConstants.defaultSlippagePercent, sourceAddress: nil, destinationAddress: destination, - providers: nil, + providers: sellQuoteProviders(for: toAsset), affiliateFee: nil ) - do { - let response = try await SwapKitAPIService.shared.quote(request) - return response.error - } catch { - DWLogger.log("SwapKit: address validation request failed: \(error)") - return NSLocalizedString("Address validation unavailable — please check your connection", comment: "SwapKit") + } + + /// 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. + nonisolated static func addressReCheckMessage(_ reAsked: [LiveRouteState], coin: SwapCryptoCurrency?) -> String? { + if reAsked.contains(.available) { + guard let coin else { return "validation_error" } + return SwapKitErrorCopy.message(for: "validation_error", coin: coin) + } + if reAsked.contains(.unknown) { + return nil } + guard let coin else { return NSLocalizedString("No route available", comment: "SwapKit") } + return SwapKitErrorCopy.unavailableNowMessage(coin: coin) } func createBuyOrder( @@ -647,135 +881,151 @@ final class SwapKitSwapProvider: SwapProvider { return best } - // MARK: - Private: Buy Routability - - 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) - } + // MARK: - Private: Live Route Availability + + /// 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 { + Self.capableProviders( + for: asset, + direction: direction, + nearOnly: nearOnlyAssets, + mayaOnly: mayaOnlyAssets, + both: bothAssets + ) } - 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 + /// The providers the published lists say can carry `asset`. Buy routes through NEAR only, + /// so Maya never counts on Buy. + nonisolated static func capableProviders( + for asset: String, + direction: SwapDirection, + nearOnly: Set, + mayaOnly: Set, + both: Set + ) -> Set { + let key = asset.uppercased() + var providers = Set() + if nearOnly.contains(key) || both.contains(key) { + providers.insert(.near) } - - guard updatedAny else { return } - onBuyRoutabilityChanged?() - } - - private func shouldProbeBuyRoutability(for asset: String) -> Bool { - guard cachedBuyRoutability(for: asset) == nil else { return false } - return !buyRoutabilityInFlight.contains(asset) + if direction == .sell, mayaOnly.contains(key) || both.contains(key) { + providers.insert(.maya) + } + 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? { - let request = SwapKitQuoteRequest( - sellAsset: asset, - buyAsset: SwapKitConstants.dashAsset, - sellAmount: sellAmount, + /// The quote a probe sends: forced to `provider`'s SwapKit providers and carrying no address, + /// so a probe reveals nothing about the wallet. + nonisolated static func probeRequest( + asset: String, + provider: RouteProvider, + direction: SwapDirection, + amount: String + ) -> SwapKitQuoteRequest { + SwapKitQuoteRequest( + 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 ) + } + + /// 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 = Self.probeRequest(asset: asset, provider: provider, direction: direction, amount: amount) 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) + let state = Self.decodedQuoteResponse(from: error).map(LiveRouteState.classify) ?? .unknown + // Every field of a quote response is optional, so any JSON error body decodes. Only a + // conclusive answer is not a failure; a 401, a 429 or a gateway error is logged. + if state == .unknown { + let detail = SwapKitFailureDetail.describe(error) + DWLogger.log("SwapKit: route check \(asset) \(provider) \(direction) failed — \(detail)") } - return nil + return state } } - /// 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`. Internal rather than private so the tests can feed it an answer. + static func recordQuoteOutcome( + _ response: SwapKitQuoteResponse, + requested: Set, + asset: String, + direction: SwapDirection, + store: SwapRouteAvailability + ) { + 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) } - // 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, + // and a route from either 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).subtracting(carrying) { + store.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 + /// The address screen's copy for a check that got no SwapKit answer to read. A response that came + /// back but could not be read (a gateway's error page, a broken body) means the swap service + /// failed, so the user is not sent to check a connection that works; anything else never got a + /// response — no connection, a timeout, a DNS failure. + static func addressCheckFailureMessage(for error: Error) -> String { + switch error { + case HTTPClientError.statusCode, HTTPClientError.mapping, HTTPClientError.decoder: + return NSLocalizedString("The swap service isn't responding. Please try again later.", comment: "SwapKit") + default: + return NSLocalizedString("Address validation unavailable — please check your connection", comment: "SwapKit") + } } private static func decodedQuoteResponse(from error: Error) -> SwapKitQuoteResponse? { @@ -835,20 +1085,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. - private func sellQuoteProviders(for toAsset: String) -> [String]? { + /// + /// 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 @@ -1050,20 +1303,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 { + if response.routes?.isEmpty == false { + return .available + } + + let states = (response.providerErrors ?? []).map { error -> LiveRouteState in + guard let code = error.errorCode?.trimmingCharacters(in: .whitespacesAndNewlines), !code.isEmpty else { + return .unknown + } + 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. 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 { + 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 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. + 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 + /// The sequence at the start of the round that last changed the verdict to this value. A + /// coin's own answer asked or recorded after it wins over an outage, even after the outage + /// was re-confirmed — also one recorded while that round was still asking. + let sinceSequence: Int + } + + private let probeAfter: TimeInterval + private let nearDownProbeAfter: TimeInterval + private let forgetAfter: TimeInterval + 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] = [:] + /// 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 was asked or recorded after + /// the round that first found the outage started (`Verdict.sinceSequence`). + /// + /// `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, storedSequence[key, default: 0] > verdict.sinceSequence { + 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), asked: nextSequence()) + } + + // 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() } + } + forgetExpired(direction) + + 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). + /// 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) + } + + /// 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. A route after + /// a "down" verdict also drops the other sentinels' no-routes stored before this round, so + /// 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 + } + if let last = inconclusiveRoundAt[direction], now().timeIntervalSince(last) < nearDownProbeAfter { + return readableVerdict(direction)?.verdict + } + + let roundStart = sequence + // 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 + } + _ = 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 { + 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, roundStart: roundStart) + 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, roundStart: roundStart) + 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. + 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, roundStart: Int) { + let previous = readableVerdict(direction) + 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) + } + } + + /// 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 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 + } + await acquirePermit() + defer { releasePermit() } + if Task.isCancelled { + return .unknown + } + 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 readableEntry(key)?.state ?? .unknown + } + if state == .unknown { + inconclusiveAt[key] = now() + } else { + inconclusiveAt[key] = nil + store(state, for: key, asked: asked) + } + return state + } + + 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) + } + } + + // 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 + } + + 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..7505794b5f 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinView.swift @@ -17,6 +17,7 @@ // limitations under the License. // +import Combine import DashUIKit import SwiftUI @@ -46,10 +47,15 @@ struct SelectCoinView: View { init( swapProvider: SwapProvider = MayaSwapProvider(), direction: SwapDirection = .sell, + networkStatus: NetworkStatusProviding = NetworkStatusService.shared, onBack: (() -> Void)? = nil, onCoinSelected: ((SwapCryptoCurrency) -> Void)? = nil ) { - _viewModel = StateObject(wrappedValue: SelectCoinViewModel(swapProvider: swapProvider, direction: direction)) + _viewModel = StateObject(wrappedValue: SelectCoinViewModel( + swapProvider: swapProvider, + direction: direction, + networkStatus: networkStatus + )) self.onBack = onBack self.onCoinSelected = onCoinSelected } @@ -79,7 +85,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 @@ -208,7 +217,141 @@ struct SelectCoinView: View { } #if DEBUG -#Preview { - SelectCoinView(onBack: {}) +#Preview("Live labels") { + SelectCoinView( + swapProvider: SelectCoinPreviewSwapProvider(halted: []), + networkStatus: SelectCoinPreviewNetworkStatus(), + onBack: {} + ) +} + +#Preview("Halted") { + SelectCoinView( + swapProvider: SelectCoinPreviewSwapProvider(halted: [SelectCoinPreviewSwapProvider.arbUSDT, "AVAX.AVAX"]), + networkStatus: SelectCoinPreviewNetworkStatus(), + onBack: {} + ) +} + +#Preview("Loading") { + SelectCoinView( + swapProvider: SelectCoinPreviewSwapProvider(halted: [], loading: .neverAnswers), + networkStatus: SelectCoinPreviewNetworkStatus(), + onBack: {} + ) +} + +#Preview("Error") { + SelectCoinView( + swapProvider: SelectCoinPreviewSwapProvider(halted: [], loading: .fails(URLError(.timedOut))), + networkStatus: SelectCoinPreviewNetworkStatus(), + onBack: {} + ) +} + +#Preview("Offline") { + SelectCoinView( + swapProvider: SelectCoinPreviewSwapProvider(halted: []), + networkStatus: SelectCoinPreviewNetworkStatus(status: .offline), + onBack: {} + ) +} + +/// Fixed coins and live answers for the previews: no network, no SwapKit. +private final class SelectCoinPreviewSwapProvider: SwapProvider { + enum Loading { + case answers + /// Keeps the picker on its spinner. + case neverAnswers + case fails(Error) + } + + static let arbUSDT = "ARB.USDT-0XFD086BC7CD5C481DCC9C85EBE478A1C0B69FCBB9" + private static let labels: [String: RouteProvider] = [ + "BTC.BTC": .multiple, + "ETH.ETH": .multiple, + "SOL.SOL": .near, + arbUSDT: .near, + "AVAX.AVAX": .near, + ] + + private let halted: Set + private let loading: Loading + + init(halted: Set, loading: Loading = .answers) { + self.halted = halted + self.loading = loading + } + + var displayName: String { "Preview" } + var usesGenericFeeLabel: Bool { true } + var buildsSwapKitDeposit: Bool { true } + + func fetchPools() async throws -> [SwapPool] { + switch loading { + case .answers: + break + case .neverAnswers: + try await Task.sleep(nanoseconds: .max) + case .fails(let error): + throw error + } + // A zero price shows no fiat row, which keeps the currency exchanger out of the preview. + return Self.labels.keys.map { SwapPool(asset: $0, status: "available", assetPriceUSD: "0") } + } + + func fetchInboundAddresses() async throws -> [SwapInboundAddress] { + Set(Self.labels.keys.compactMap { $0.components(separatedBy: ".").first }).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 networkLabels(for pools: [SwapPool], direction: SwapDirection) async -> [String: String] { + Self.labels.filter { !halted.contains($0.key) }.mapValues { $0.shortLabel } + } + + func haltedAssets( + from inboundAddresses: [SwapInboundAddress], + pools: [SwapPool], + direction: SwapDirection + ) async -> Set { + halted + } + + func validateAddress(destination: String, toAsset: String) async -> String? { nil } + func fetchQuote(dashSatoshis: Int64, toAsset: String, destination: String) async throws -> SwapQuoteResult { + SwapQuoteResult( + error: nil, expectedAmountOut: nil, fees: nil, inboundAddress: nil, memo: nil, executionNetwork: nil + ) + } + func fetchSwapStatus(txid: String, depositAddress: String?) async throws -> SwapStatusResult { + SwapStatusResult(error: nil, isObserved: false, observedStatus: nil, outHashes: nil) + } + func createBuyOrder( + sellAsset: String, + sellAmount: String, + destination: String, + refundAddress: String + ) async throws -> BuyOrder { + throw SwapProviderError.unsupportedBuyOrder + } + func validateBuyOrder(sellAsset: String, sellAmount: String, refundAddress: String) async throws {} + func logoURL(for mayaAsset: String) -> URL? { nil } +} + +private final class SelectCoinPreviewNetworkStatus: NetworkStatusProviding { + let currentStatus: NetworkStatus + var isOnline: Bool { currentStatus == .online } + var statusPublisher: AnyPublisher { Just(currentStatus).eraseToAnyPublisher() } + + init(status: NetworkStatus = .online) { + currentStatus = status + } } #endif diff --git a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift index 1542946db1..9ca2f41145 100644 --- a/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift +++ b/DashWallet/Sources/UI/Swap/SelectCoin/SelectCoinViewModel.swift @@ -35,28 +35,49 @@ 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 + /// 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. + 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] = [] @@ -110,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 } } @@ -127,33 +150,94 @@ 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 + 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 + // checks now rather than at the next tick. + if routeFreshnessRun != 0 { + 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)") + guard generation == loadGeneration else { return } 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/DashWallet/ar.lproj/Localizable.strings b/DashWallet/ar.lproj/Localizable.strings index ec5eed7e7f..c1648df869 100644 --- a/DashWallet/ar.lproj/Localizable.strings +++ b/DashWallet/ar.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "يجب ألا يتطلب اسم المستخدم المؤقت نفسه تصويتًا."; diff --git a/DashWallet/bg.lproj/Localizable.strings b/DashWallet/bg.lproj/Localizable.strings index 5fb4394ee5..81df2a5357 100644 --- a/DashWallet/bg.lproj/Localizable.strings +++ b/DashWallet/bg.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Временното потребителско име само по себе си не бива да изисква гласуване."; diff --git a/DashWallet/ca.lproj/Localizable.strings b/DashWallet/ca.lproj/Localizable.strings index a165bdbb67..f789810857 100644 --- a/DashWallet/ca.lproj/Localizable.strings +++ b/DashWallet/ca.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "El nom d'usuari temporal no ha de requerir votació ell mateix."; diff --git a/DashWallet/cs.lproj/Localizable.strings b/DashWallet/cs.lproj/Localizable.strings index 55487d990e..087f486a50 100644 --- a/DashWallet/cs.lproj/Localizable.strings +++ b/DashWallet/cs.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Dočasné uživatelské jméno samo nesmí vyžadovat hlasování."; diff --git a/DashWallet/da.lproj/Localizable.strings b/DashWallet/da.lproj/Localizable.strings index dbb538a243..6c5394e6ea 100644 --- a/DashWallet/da.lproj/Localizable.strings +++ b/DashWallet/da.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Det midlertidige brugernavn må ikke selv kræve afstemning."; diff --git a/DashWallet/de.lproj/Localizable.strings b/DashWallet/de.lproj/Localizable.strings index a148881a73..b262d72dd3 100644 --- a/DashWallet/de.lproj/Localizable.strings +++ b/DashWallet/de.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Der temporäre Nutzername darf nicht selbst eine Abstimmung erfordern."; diff --git a/DashWallet/el.lproj/Localizable.strings b/DashWallet/el.lproj/Localizable.strings index 9e70b27028..04de395e37 100644 --- a/DashWallet/el.lproj/Localizable.strings +++ b/DashWallet/el.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Το προσωρινό όνομα χρήστη δεν πρέπει να απαιτεί το ίδιο ψηφοφορία."; diff --git a/DashWallet/en.lproj/Localizable.strings b/DashWallet/en.lproj/Localizable.strings index 50c1d1a3cc..c512f37544 100644 --- a/DashWallet/en.lproj/Localizable.strings +++ b/DashWallet/en.lproj/Localizable.strings @@ -5516,6 +5516,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "The temporary username must not itself require voting."; diff --git a/DashWallet/eo.lproj/Localizable.strings b/DashWallet/eo.lproj/Localizable.strings index 81329f5402..ee22ca308c 100644 --- a/DashWallet/eo.lproj/Localizable.strings +++ b/DashWallet/eo.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "La provizora uzantnomo mem ne devas postuli voĉdonadon."; diff --git a/DashWallet/es.lproj/Localizable.strings b/DashWallet/es.lproj/Localizable.strings index ce24e7d29e..8e70489841 100644 --- a/DashWallet/es.lproj/Localizable.strings +++ b/DashWallet/es.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "El nombre de usuario temporal no debe requerir votación él mismo."; diff --git a/DashWallet/et.lproj/Localizable.strings b/DashWallet/et.lproj/Localizable.strings index 9803b7bd0b..cfb9e24b8e 100644 --- a/DashWallet/et.lproj/Localizable.strings +++ b/DashWallet/et.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Ajutine kasutajanimi ise ei tohi nõuda hääletust."; diff --git a/DashWallet/fa.lproj/Localizable.strings b/DashWallet/fa.lproj/Localizable.strings index 55550a4aef..fa5a22e1f6 100644 --- a/DashWallet/fa.lproj/Localizable.strings +++ b/DashWallet/fa.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "نام کاربری موقت خودش نباید نیازمند رأی‌گیری باشد."; diff --git a/DashWallet/fi.lproj/Localizable.strings b/DashWallet/fi.lproj/Localizable.strings index 202a50ada5..ffd6833f8f 100644 --- a/DashWallet/fi.lproj/Localizable.strings +++ b/DashWallet/fi.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Väliaikainen käyttäjänimi ei saa itsessään vaatia äänestystä."; diff --git a/DashWallet/fil.lproj/Localizable.strings b/DashWallet/fil.lproj/Localizable.strings index 452045a6ee..084e609c5f 100644 --- a/DashWallet/fil.lproj/Localizable.strings +++ b/DashWallet/fil.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Ang pansamantalang username mismo ay hindi dapat mangailangan ng pagboto."; diff --git a/DashWallet/fr.lproj/Localizable.strings b/DashWallet/fr.lproj/Localizable.strings index c247a0cff7..29d0dfcfd3 100644 --- a/DashWallet/fr.lproj/Localizable.strings +++ b/DashWallet/fr.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Le nom d'utilisateur temporaire ne doit pas lui-même nécessiter un vote."; diff --git a/DashWallet/hr.lproj/Localizable.strings b/DashWallet/hr.lproj/Localizable.strings index b81f8c91e7..9ea043485f 100644 --- a/DashWallet/hr.lproj/Localizable.strings +++ b/DashWallet/hr.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Privremeno korisničko ime ne smije ni samo zahtijevati glasanje."; diff --git a/DashWallet/hu.lproj/Localizable.strings b/DashWallet/hu.lproj/Localizable.strings index 85a3180c37..1cebc4c923 100644 --- a/DashWallet/hu.lproj/Localizable.strings +++ b/DashWallet/hu.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Az ideiglenes felhasználónév maga nem igényelhet szavazást."; diff --git a/DashWallet/id.lproj/Localizable.strings b/DashWallet/id.lproj/Localizable.strings index 40b60f5821..26dfbc9561 100644 --- a/DashWallet/id.lproj/Localizable.strings +++ b/DashWallet/id.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Nama pengguna sementara itu sendiri tidak boleh memerlukan pemungutan suara."; diff --git a/DashWallet/it.lproj/Localizable.strings b/DashWallet/it.lproj/Localizable.strings index 11ff458c49..fb07460077 100644 --- a/DashWallet/it.lproj/Localizable.strings +++ b/DashWallet/it.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Il nome utente temporaneo non deve a sua volta richiedere una votazione."; diff --git a/DashWallet/ja.lproj/Localizable.strings b/DashWallet/ja.lproj/Localizable.strings index 87a4e6a842..89729722dc 100644 --- a/DashWallet/ja.lproj/Localizable.strings +++ b/DashWallet/ja.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "一時的なユーザー名自体が投票を必要としてはいけません。"; diff --git a/DashWallet/ko.lproj/Localizable.strings b/DashWallet/ko.lproj/Localizable.strings index c4da27c570..a05671787a 100644 --- a/DashWallet/ko.lproj/Localizable.strings +++ b/DashWallet/ko.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "임시 사용자 이름 자체가 투표를 필요로 해서는 안 됩니다."; diff --git a/DashWallet/mk.lproj/Localizable.strings b/DashWallet/mk.lproj/Localizable.strings index a68da9f177..9dfd305683 100644 --- a/DashWallet/mk.lproj/Localizable.strings +++ b/DashWallet/mk.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Привременото корисничко име само по себе не смее да бара гласање."; diff --git a/DashWallet/ms.lproj/Localizable.strings b/DashWallet/ms.lproj/Localizable.strings index 1215e22446..b106d5021f 100644 --- a/DashWallet/ms.lproj/Localizable.strings +++ b/DashWallet/ms.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Nama pengguna sementara itu sendiri tidak boleh memerlukan pengundian."; diff --git a/DashWallet/nb.lproj/Localizable.strings b/DashWallet/nb.lproj/Localizable.strings index 656ff5ec9c..febc0a4a22 100644 --- a/DashWallet/nb.lproj/Localizable.strings +++ b/DashWallet/nb.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Det midlertidige brukernavnet må ikke selv kreve avstemning."; diff --git a/DashWallet/nl.lproj/Localizable.strings b/DashWallet/nl.lproj/Localizable.strings index a73f1a827f..7638d2e1b9 100644 --- a/DashWallet/nl.lproj/Localizable.strings +++ b/DashWallet/nl.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "De tijdelijke gebruikersnaam mag zelf geen stemming vereisen."; diff --git a/DashWallet/pl.lproj/Localizable.strings b/DashWallet/pl.lproj/Localizable.strings index a29a67080f..f82271b534 100644 --- a/DashWallet/pl.lproj/Localizable.strings +++ b/DashWallet/pl.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Tymczasowa nazwa użytkownika sama nie może wymagać głosowania."; diff --git a/DashWallet/pt.lproj/Localizable.strings b/DashWallet/pt.lproj/Localizable.strings index 28c2ed884a..3fc58ea249 100644 --- a/DashWallet/pt.lproj/Localizable.strings +++ b/DashWallet/pt.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "O nome de usuário temporário não pode exigir votação por si só."; diff --git a/DashWallet/ro.lproj/Localizable.strings b/DashWallet/ro.lproj/Localizable.strings index d871477be5..a96edd37b3 100644 --- a/DashWallet/ro.lproj/Localizable.strings +++ b/DashWallet/ro.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Numele de utilizator temporar nu trebuie să necesite el însuși un vot."; diff --git a/DashWallet/ru.lproj/Localizable.strings b/DashWallet/ru.lproj/Localizable.strings index 70998c1a12..f3e8cfc365 100644 --- a/DashWallet/ru.lproj/Localizable.strings +++ b/DashWallet/ru.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Временное имя пользователя само не должно требовать голосования."; diff --git a/DashWallet/sk.lproj/Localizable.strings b/DashWallet/sk.lproj/Localizable.strings index b41cca063c..bcaee67f9b 100644 --- a/DashWallet/sk.lproj/Localizable.strings +++ b/DashWallet/sk.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Dočasné používateľské meno samo nesmie vyžadovať hlasovanie."; diff --git a/DashWallet/sl.lproj/Localizable.strings b/DashWallet/sl.lproj/Localizable.strings index c903a035c1..45e47f3974 100644 --- a/DashWallet/sl.lproj/Localizable.strings +++ b/DashWallet/sl.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Začasno uporabniško ime samo po sebi ne sme zahtevati glasovanja."; diff --git a/DashWallet/sl_SI.lproj/Localizable.strings b/DashWallet/sl_SI.lproj/Localizable.strings index 97df180742..18af12371d 100644 --- a/DashWallet/sl_SI.lproj/Localizable.strings +++ b/DashWallet/sl_SI.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Začasno uporabniško ime samo po sebi ne sme zahtevati glasovanja."; diff --git a/DashWallet/sq.lproj/Localizable.strings b/DashWallet/sq.lproj/Localizable.strings index cc2c6c35d6..5ec379c031 100644 --- a/DashWallet/sq.lproj/Localizable.strings +++ b/DashWallet/sq.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Emri i përkohshëm i përdoruesit nuk duhet të kërkojë vetë votim."; diff --git a/DashWallet/sr.lproj/Localizable.strings b/DashWallet/sr.lproj/Localizable.strings index 0674748fe7..c562ea8ca5 100644 --- a/DashWallet/sr.lproj/Localizable.strings +++ b/DashWallet/sr.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Privremeno korisničko ime ne sme ni samo da zahteva glasanje."; diff --git a/DashWallet/sv.lproj/Localizable.strings b/DashWallet/sv.lproj/Localizable.strings index 70c9c2b384..d70fb9ea85 100644 --- a/DashWallet/sv.lproj/Localizable.strings +++ b/DashWallet/sv.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Det tillfälliga användarnamnet får inte självt kräva röstning."; diff --git a/DashWallet/th.lproj/Localizable.strings b/DashWallet/th.lproj/Localizable.strings index e1a4062dbc..eb78205115 100644 --- a/DashWallet/th.lproj/Localizable.strings +++ b/DashWallet/th.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "ชื่อผู้ใช้ชั่วคราวต้องไม่เป็นชื่อที่ต้องโหวตเสียเอง"; diff --git a/DashWallet/tr.lproj/Localizable.strings b/DashWallet/tr.lproj/Localizable.strings index 567a892339..ff7f72e211 100644 --- a/DashWallet/tr.lproj/Localizable.strings +++ b/DashWallet/tr.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Geçici kullanıcı adının kendisi oylama gerektirmemelidir."; diff --git a/DashWallet/uk.lproj/Localizable.strings b/DashWallet/uk.lproj/Localizable.strings index 60351ad1b4..3f7b8ebff1 100644 --- a/DashWallet/uk.lproj/Localizable.strings +++ b/DashWallet/uk.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Тимчасове ім'я користувача саме не повинно вимагати голосування."; diff --git a/DashWallet/vi.lproj/Localizable.strings b/DashWallet/vi.lproj/Localizable.strings index 1c3c0fa1ca..faaaf2de1c 100644 --- a/DashWallet/vi.lproj/Localizable.strings +++ b/DashWallet/vi.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "Bản thân tên người dùng tạm thời không được là tên phải bỏ phiếu."; diff --git a/DashWallet/zh-Hans.lproj/Localizable.strings b/DashWallet/zh-Hans.lproj/Localizable.strings index c69efd6a99..b1d928eb90 100644 --- a/DashWallet/zh-Hans.lproj/Localizable.strings +++ b/DashWallet/zh-Hans.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "临时用户名本身不得需要投票。"; diff --git a/DashWallet/zh-Hant-TW.lproj/Localizable.strings b/DashWallet/zh-Hant-TW.lproj/Localizable.strings index e008313b73..295c5fd9e2 100644 --- a/DashWallet/zh-Hant-TW.lproj/Localizable.strings +++ b/DashWallet/zh-Hant-TW.lproj/Localizable.strings @@ -5517,6 +5517,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "臨時用戶名稱本身不得需要投票。"; diff --git a/DashWallet/zh.lproj/Localizable.strings b/DashWallet/zh.lproj/Localizable.strings index a2e8eea215..3eba2031e3 100644 --- a/DashWallet/zh.lproj/Localizable.strings +++ b/DashWallet/zh.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "临时用户名本身不得需要投票。"; diff --git a/DashWallet/zh_TW.lproj/Localizable.strings b/DashWallet/zh_TW.lproj/Localizable.strings index ad1120c68e..55e2c75237 100644 --- a/DashWallet/zh_TW.lproj/Localizable.strings +++ b/DashWallet/zh_TW.lproj/Localizable.strings @@ -5515,6 +5515,9 @@ /* Dash DEX */ "The status of your %@ swap could not be confirmed" = "The status of your %@ swap could not be confirmed"; +/* SwapKit */ +"The swap service isn't responding. Please try again later." = "The swap service isn't responding. Please try again later."; + /* Usernames */ "The temporary username must not itself require voting." = "臨時用戶名稱本身不得需要投票。"; 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/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/SwapKitQuoteDecodingTests.swift b/DashWalletTests/SwapKitQuoteDecodingTests.swift index 48cf01caf2..8be982108f 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,483 @@ 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) + /// 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) } /// 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")) + } + + /// 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 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) + } + + /// 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")) + } + + /// 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." + + /// ARB.USDT, the coin of the bug report. + private func reCheckedCoin() throws -> SwapCryptoCurrency { + try XCTUnwrap(SwapCryptoCurrency.knownCoin(for: "ARB.USDT-0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9")) + } + + /// The re-check without the address found a route: the address is what to fix. + func testAReCheckThatFindsARouteBlamesTheAddress() throws { + let coin = try reCheckedCoin() + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.available], coin: coin), addressCopy) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.noRoute, .available], coin: coin), addressCopy) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.unknown, .available], coin: coin), addressCopy, + "a route found beside an inconclusive answer still settles it") + } + + /// The re-check could not settle it: the amount screen gets to quote the coin. + func testAnInconclusiveReCheckLetsTheHolderContinue() throws { + let coin = try reCheckedCoin() + XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([.unknown], coin: coin)) + XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([.noRoute, .unknown], coin: coin)) + } + + /// The bug report: the re-check confirms no route, so the coin — not the connection — is named. + func testAConfirmedNoRouteSaysTheCoinCannotBeSwapped() throws { + let coin = try reCheckedCoin() + let message = SwapKitSwapProvider.addressReCheckMessage([.noRoute], coin: coin) + XCTAssertEqual(message, "\(coin.code) can't be swapped at the moment.") + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.noRoute, .noRoute], coin: coin), message) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.noRoute, .halted], coin: coin), message) + 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) + } + + /// 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 testProviderUpstreamFailureLeavesTheQuestionOpen() { - let upstream = response(providerErrors: [providerError("apiRequestFailed")]) - XCTAssertNil(SwapKitSwapProvider.routability(from: upstream)) + func testAReCheckForAnUnknownCoinStillGivesAnAnswer() { + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.available], coin: nil), "validation_error") + XCTAssertNil(SwapKitSwapProvider.addressReCheckMessage([.unknown], coin: nil)) + XCTAssertEqual(SwapKitSwapProvider.addressReCheckMessage([.noRoute], coin: nil), "No route available") + } + + 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 testHaltCodesAreMatchedAsAFamily() { + XCTAssertTrue(SwapKitErrorCopy.isHalted("swapHalted")) + XCTAssertTrue(SwapKitErrorCopy.isHalted("tradingHalted: ETH")) + XCTAssertFalse(SwapKitErrorCopy.isHalted("noRoutesFound")) + 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" + private let serviceCopy = "The swap service isn't responding. Please try again later." + + func testAddressCheckBlamesTheConnectionOnlyWhenNoResponseCameBack() { + let offline = HTTPClientError.moya(.underlying(URLError(.notConnectedToInternet), nil)) + XCTAssertEqual(SwapKitSwapProvider.addressCheckFailureMessage(for: offline), connectionCopy) + XCTAssertEqual(SwapKitSwapProvider.addressCheckFailureMessage(for: URLError(.timedOut)), connectionCopy) + } + + func testAddressCheckReportsTheServiceWhenItsAnswerCannotBeRead() { + let errorPage = statusError("502 Bad Gateway", statusCode: 502) + XCTAssertEqual(SwapKitSwapProvider.addressCheckFailureMessage(for: errorPage), serviceCopy) + let broken = HTTPClientError.mapping(Moya.Response(statusCode: 200, data: Data("not json".utf8))) + XCTAssertEqual(SwapKitSwapProvider.addressCheckFailureMessage(for: broken), serviceCopy) + } + + // MARK: Route check request + + /// AC-09: a route check reveals nothing about the wallet — no address, not even a placeholder. + func testARouteCheckCarriesNoAddress() throws { + for direction in [SwapDirection.sell, .buy] { + for provider in [RouteProvider.near, .maya] { + let request = SwapKitSwapProvider.probeRequest( + asset: "BTC.BTC", provider: provider, direction: direction, amount: "1" + ) + + XCTAssertNil(request.sourceAddress, "\(direction) \(provider)") + XCTAssertNil(request.destinationAddress, "\(direction) \(provider)") + let body = try XCTUnwrap(String(data: JSONEncoder().encode(request), encoding: .utf8)) + XCTAssertFalse(body.localizedCaseInsensitiveContains("address"), "\(direction) \(provider): \(body)") + } + } } } diff --git a/DashWalletTests/SwapRouteAvailabilityTests.swift b/DashWalletTests/SwapRouteAvailabilityTests.swift new file mode 100644 index 0000000000..c8bf2e0a06 --- /dev/null +++ b/DashWalletTests/SwapRouteAvailabilityTests.swift @@ -0,0 +1,815 @@ +// +// 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) + } + + /// 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", "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 { + 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 + /// 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) + } + + /// Sentinel checks skip the per-coin back-off, so an inconclusive round must hold off on its + /// own: the picker refreshes every minute, the sentinels are asked at most once per 2 minutes. + func testAnInconclusiveSentinelRoundIsNotRepeatedForTwoMinutes() async { + SwapRouteAvailability.nearSentinels.forEach { script.set(.unknown, .near, $0) } + await refresh(["AVAX.AVAX": [.near]]) + let round = ["BTC.BTC", "ETH.ETH", "SOL.SOL"] + XCTAssertEqual(script.calls(to: .near), round) + + clock += 60 + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(script.calls(to: .near), round, "a minute later the round is not sent again") + + clock += 61 + await refresh(["AVAX.AVAX": [.near]]) + XCTAssertEqual(script.calls(to: .near), round + round, "after two minutes the round runs again") + } + + 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 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 { + 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"]) + } + + /// 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 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]]) + 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 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]]) + 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) + } + + /// AC-11: Buy routes through NEAR only, so a NEAR outage on Buy halts every Buy coin, + /// also one Maya carries on Sell. + func testNearDownOnBuyHaltsEveryBuyCoinAndMayaNeverCounts() async { + let capable = { (asset: String, direction: SwapDirection) in + SwapKitSwapProvider.capableProviders( + for: asset, direction: direction, nearOnly: ["AVAX.AVAX"], mayaOnly: ["MAYA.CACAO"], both: ["ETH.USDT"] + ) + } + XCTAssertEqual(capable("ETH.USDT", .sell), both) + XCTAssertEqual(capable("ETH.USDT", .buy), [.near], "Maya never counts on Buy") + SwapRouteAvailability.nearSentinels.forEach { script.set(.noRoute, .near, $0) } + + let buyCoins = ["ETH.USDT", "AVAX.AVAX"] + await store.refresh(assets: buyCoins, direction: .buy, capable: { capable($0, .buy) }, probe: script.probe) + + XCTAssertEqual(store.nearVerdict(for: .buy), .down) + XCTAssertTrue(script.calls(to: .maya).isEmpty) + for coin in buyCoins { + XCTAssertTrue(store.usableProviders(for: coin, capable: capable(coin, .buy), direction: .buy).isEmpty, coin) + } + } + + // 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") + } + + /// 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) + } + + /// 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) + } + + /// 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) + } + + /// The same with the picker closed meanwhile: the cancelled refresh still settles the round when + /// its last sentinel returns, and the coin's newer route stays usable. + func testACoinRouteRecordedBeforeACancelledOutageRoundEndsStaysUsable() 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 + task.cancel() + script.openGate() + await task.value + + XCTAssertEqual(store.nearVerdict(for: .sell), .down) + XCTAssertEqual(label("AVAX.AVAX", capable: [.near]), .near) + } + + /// 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 { + 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") + } +} diff --git a/docs/adr/0010-probe-live-swap-routes-with-address-free-forced-quotes.md b/docs/adr/0010-probe-live-swap-routes-with-address-free-forced-quotes.md new file mode 100644 index 0000000000..83a91db961 --- /dev/null +++ b/docs/adr/0010-probe-live-swap-routes-with-address-free-forced-quotes.md @@ -0,0 +1,55 @@ +# 0010 — Probe live routes with address-free quotes forced to one provider + +- **Status:** Proposed +- **Date:** 2026-11-05 (the approach was approved by the owner on 2026-11-02 and is implemented in PR #1297) +- **Deciders:** romchornyi (author) + +## Context + +The swap coin picker labelled each coin from SwapKit's published coin lists (`/tokens?provider=`), +which say what NEAR or Maya can carry in principle, not now. On 2026-11-02 NEAR's DASH leg was down, +Maya had BTC and ETH halted, and SwapKit answered "no route" for DASH → USDT on Arbitrum through Maya +even though Maya itself quoted that pair. The picker still offered every coin. The wallet needs a +per-coin, per-direction, per-provider signal of what can be swapped right now. + +## Decision drivers + +- A Wallet holder never picks a coin that no provider can swap right now — the signal must reflect the whole path the swap will take, SwapKit's own leg included. +- A check carries no address at all. +- Check size about US$50 of the sold coin; ≤ 2 checks in flight. +- Prefer the integration the wallet already has (SwapKit through `SwapKitAPIService`) when it meets the goals: a new one adds a client, a dependency and its own failure modes. +- Only a conclusive answer may halt a coin. + +## Considered options + +1. **Route checks through SwapKit** — one quote per coin, direction and provider, forced to that provider's SwapKit names (both Maya flavours in one check), sized at about US$50, with no source or destination address; the answer is classified as available / halted / no route / unknown. +2. **Read the providers' own status directly** — Maya's node (`inbound_addresses` halt flags per chain) and a NEAR status source, bypassing SwapKit. +3. **No checks in the picker** — learn availability only from the address screen's own quote once the Wallet holder has picked a coin. + +## Decision outcome + +**Chosen:** Option 1. It asks the same service, through the same leg, that the real swap will use, +so it catches failures that live in SwapKit rather than in the provider (the ARB.USDT case above, +which option 2 would have shown as available), and it needs no new integration. Option 3 leaves the +defect in place: the Wallet holder still picks a dead coin and types an address first. + +## Consequences + +**Positive** +- One classifier (`LiveRouteState.classify`) serves Sell and Buy, the picker and the address screen. +- The answer matches what a real quote would get, SwapKit's leg included. +- No address leaves the device in a check. + +**Negative** +- Every check spends SwapKit API quota; the volume is bounded only by the load limits (two in flight, ten-minute reuse, two-minute back-off). +- The classification depends on SwapKit's error-code strings (`noRoutesFound`, `swapHalted`, the below-minimum family); a renamed code turns a conclusive answer into `unknown`, which keeps coins pickable rather than halting them. +- A bare top-level "no route" is read as conclusive only because of the check size; a Sell check without a DASH price falls back to 1 DASH, and a Buy check without a price is not sent at all. + +**Neutral** +- Moving to provider status endpoints later is possible behind the same `Probe` function type; the store and the picker would not change. + +## Links + +- Feature summary: [docs/features/swap-live-routes/README.md](../features/swap-live-routes/README.md) +- Related ADR: [0011 — Keep live route answers in one shared in-memory store with two-step ageing](0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md) +- Related ADR: [0012 — Detect a NEAR outage from sentinel coins before per-coin checks](0012-detect-a-near-outage-from-sentinel-coins.md) diff --git a/docs/adr/0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md b/docs/adr/0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md new file mode 100644 index 0000000000..c4eed7dc7e --- /dev/null +++ b/docs/adr/0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md @@ -0,0 +1,53 @@ +# 0011 — Keep live route answers in one shared in-memory store with two-step ageing + +- **Status:** Proposed +- **Date:** 2026-11-05 (implemented in PR #1297) +- **Deciders:** romchornyi (author) + +## Context + +Route checks (ADR-0010) produce one answer per direction, provider and coin. Three places read those +answers: the coin picker (labels and halted rows), the address screen (it also writes what its own +quote learned) and the quote paths (which providers a Sell quote asks). Every swap flow builds its own +`SwapKitSwapProvider` (`SwapBackend.makeProvider()`), so answers kept on the provider would die with +each picker. The repo's guardrail #4 (`CLAUDE.md`) asks every new singleton to state its reason. + +## Decision drivers + +- A conclusive answer is re-checked after 10 min and still shown until 30 min; an inconclusive one is re-asked after 2 min, not sooner. +- A coin with a conclusive answer from the last ten minutes is not checked again when the picker is reopened. +- An unknown answer never halts a coin or removes a label. +- Providers are created per flow, so state on a provider dies with each picker; prefer no new storage when memory meets the load limits, since persisting needs a SQLite migration. + +## Considered options + +1. **One app-wide in-memory store** (`SwapRouteAvailability.shared`), `@MainActor`, keyed by direction × provider × coin, with two-step ageing (due after 10 min, forgotten after 30 min) and inconclusive answers not stored (only their time, for the 2-minute back-off). Tests build their own instance. +2. **A cache on the provider instance** — answers live as long as one swap flow. +3. **A persisted cache** (UserDefaults or the app's SQLite) that survives a relaunch. + +## Decision outcome + +**Chosen:** Option 1. It is the only option that skips re-checking fresh answers across picker openings without adding +storage: option 2 re-checks every coin on every opening (coins × providers requests), and option 3 +adds serialization and a migration for answers that are forgotten after 30 minutes anyway. Keeping +unknown answers out of the store is what makes "unknown never halts" hold by construction. + +## 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, 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. + +**Negative** +- A new `static let shared`: its reason is written in the type doc, as guardrail #4 asks, but it is global state for the app's lifetime. +- After a relaunch every coin is checked again from scratch. + +**Neutral** +- The two-step ageing means a label can lag a provider's recovery by up to ten minutes (two for a NEAR outage); a quote reads only answers that are not yet due (`freshOnly`), so a stale "ruled out" never narrows a real quote. + +## Links + +- Feature summary: [docs/features/swap-live-routes/README.md](../features/swap-live-routes/README.md) +- Related ADR: [0010 — Probe live routes with address-free quotes forced to one provider](0010-probe-live-swap-routes-with-address-free-forced-quotes.md) +- Related ADR: [0012 — Detect a NEAR outage from sentinel coins before per-coin checks](0012-detect-a-near-outage-from-sentinel-coins.md) 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 new file mode 100644 index 0000000000..0503af77fc --- /dev/null +++ b/docs/adr/0012-detect-a-near-outage-from-sentinel-coins.md @@ -0,0 +1,49 @@ +# 0012 — Detect a NEAR outage from sentinel coins before per-coin checks + +- **Status:** Proposed +- **Date:** 2026-11-05 (the rule was set by the owner on 2026-11-02 and is implemented in PR #1297) +- **Deciders:** romchornyi (author) + +## Context + +NEAR can carry most of the coins in the picker, and on 2026-11-02 its DASH leg was down in both +directions: every NEAR quote answered "no route". Checking NEAR coin by coin during such an outage +would spend one request per NEAR-capable coin to learn one fact. Maya is different: its halts are per +chain, so one Maya coin says nothing about the next. + +## Decision drivers + +- During an outage ≤ 3 sentinel checks per round, at most one round per 2 min per direction, no per-coin NEAR checks; recovery re-checked on the sentinels after 2 min. +- Light on the network, quick recovery. + +## Considered options + +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. + +## Decision outcome + +**Chosen:** Option 1. It bounds an outage to at most three checks per round and gives a recovery +signal every two minutes. Option 2 breaks the load limit during exactly the outage it should handle cheaply. +Option 3 depends on which coins happen to be shown first and mixes coin-specific no-routes into a +provider-wide verdict. + +## Consequences + +**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 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. +- A NEAR outage limited to some chains is not a "down" verdict; those coins are caught by their own per-coin checks only after a sentinel routes. + +**Neutral** +- The verdict is per direction: Sell and Buy can disagree, as they did on 2026-11-02. + +## Links + +- Feature summary: [docs/features/swap-live-routes/README.md](../features/swap-live-routes/README.md) +- Related ADR: [0010 — Probe live routes with address-free quotes forced to one provider](0010-probe-live-swap-routes-with-address-free-forced-quotes.md) +- Related ADR: [0011 — Keep live route answers in one shared in-memory store with two-step ageing](0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md) diff --git a/docs/adr/README.md b/docs/adr/README.md index 1772ed23e4..fd9aa6cbb1 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -15,12 +15,15 @@ where they disagree, ADR-0001 wins. | [0006](0006-choose-the-app-connect-login-by-the-protocol-version-read-at-runtime.md) | Choose the App Connect login by the protocol version read at runtime | platform | Proposed | | | [0007](0007-call-a-payment-links-sender-back-only-when-another-app-opened-the-link.md) | Call a payment link's sender back only when another app opened the link | payments | Proposed | | | [0009](0009-answer-app-connect-request-v2-with-wallet-derived-keys-under-wallet-limits.md) | Answer App Connect request v2 with wallet-derived keys under wallet limits | platform | Proposed | | +| [0010](0010-probe-live-swap-routes-with-address-free-forced-quotes.md) | Probe live routes with address-free quotes forced to one provider | swap | Proposed | | +| [0011](0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md) | Keep live route answers in one shared in-memory store with two-step ageing | swap | Proposed | | +| [0012](0012-detect-a-near-outage-from-sentinel-coins.md) | Detect a NEAR outage from sentinel coins before per-coin checks | swap | Proposed | | | [0023](0023-remove-crowdnode-entirely-as-android-does.md) | Remove CrowdNode entirely, as Android does | ui | Proposed | | | [0024](0024-pin-shortcut-raw-values-and-refill-the-retired-slot.md) | Pin shortcut raw values and refill the retired slot | ui | Proposed | | | [0025](0025-remove-crowdnode-defaults-by-exact-key-list-on-activation.md) | Remove CrowdNode defaults by exact key list on activation | storage | Proposed | | | [0026](0026-retire-the-crowdnode-topic-by-marking-events-seen.md) | Retire the CrowdNode topic by marking its events seen | storage | Proposed | | -Areas: `spv`, `platform`, `keys`, `storage`, `coinjoin`, `payments`, `ui`, `build`, `process`. Each ADR takes one; a new +Areas: `spv`, `platform`, `keys`, `storage`, `coinjoin`, `payments`, `swap`, `ui`, `build`, `process`. Each ADR takes one; a new Area is added to this list in the PR that first needs it. ## Adding an ADR diff --git a/docs/features/swap-live-routes/README.md b/docs/features/swap-live-routes/README.md new file mode 100644 index 0000000000..2fd96b5f9d --- /dev/null +++ b/docs/features/swap-live-routes/README.md @@ -0,0 +1,50 @@ +# Live route availability in the swap coin picker + +**Owner:** romchornyi · Introduced in [#1297](https://github.com/dashpay/dashwallet-ios/pull/1297) + +## Why + +The Dash DEX coin picker labelled each coin with its provider (NEAR, Maya or Multiple) from the +providers' published coin lists. Those lists say what a provider can carry in principle, not what it +carries now. When NEAR's DASH leg went down and Maya halted BTC and ETH, the picker kept offering +every coin with the old labels. A holder who picked one and typed a valid address was told to +"check your connection", with Continue disabled: the swap aggregator had answered "no route", and +the address screen reported every refusal as a connection problem. + +## What changed + +- **Live labels.** While the picker is on screen, each coin is checked with a small quote per + provider and direction, with no address in it. Both providers route → "Multiple", one → that + provider, none → the existing halted row and toast. Buy follows the same rule; Buy routes through + NEAR only. See [ADR-0010](../../adr/0010-probe-live-swap-routes-with-address-free-forced-quotes.md). +- **One shared store.** The answers live in one in-memory store that the picker, the address screen + 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-0011](../../adr/0011-keep-live-swap-route-answers-in-one-shared-in-memory-store.md). +- **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-0012](../../adr/0012-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 + moment"; "check your connection" is shown only when no response came back; an answer the wallet + cannot read says "The swap service isn't responding. Please try again later." (the one new string). +- **Quotes follow the live state.** The amount and confirmation quotes no longer ask a provider the + store has just seen halted or without a route. + +## What it guarantees + +- 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 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; the address screen's own quote and + the amount and confirmation quotes send the entered address. + +## Not in scope + +- Providers other than NEAR and Maya. +- The Android wallet, which keeps its static labels. +- The answers are not persisted: after a relaunch every coin is checked again.