SPB Git

Repository Public

SwapTests.swift 97.7 KB 1,125 lines swift

1// SP Wallet Core2// File: Tests/SPWalletCoreTests/SwapTests.swift3// Description: Swap domain — swaps, CCTP bridges, THORChain swaps, any-to-any plans. Canonical bytes against the backend's vectors,4//              decoding of every response shape, the request contract of every endpoint, the quote stream, and the verification5//              that precedes every passkey (intent against request, challenge binding, absent intent, quote_moved).6//7//              Where the fixtures come from (all written by /tmp/spw-vectors-swap.mts, run with the backend's own TypeScript):8//              - Fixtures/swap-proposal-views.json, swap-pending-execution.json: the REAL `view()` of services/api/src/transfers.ts9//                (bridgeView, solBridgeView), `xswapView` of xswap-state.ts and `executionOf` / `pendingExecution` of exec-status.ts,10//                run on hand-built proposal rows; swap-proposal-intents.json: the intents stored on those rows.11//              - Fixtures/swap-quote-moved.json, swap-quote-record.json: the REAL `checkQuoteRef` of prepare-common.ts.12//              - Fixtures/swap-discovery.json, swap-bridge-quote.json, swap-plans.json: shapes copied field by field from swap.ts13//                (viewRoute, summary, the SSE writer), card.ts, bridge.ts (/bridge/quote), bridge-sol.ts, xswap.ts, plan-exec.ts14//                (planView, docView) — closures that need the HTTP stack — with fingerprints from the real `quoteFingerprint` /15//                `cctpQuoteRef` and embedded proposals / execution statuses from the real `view()` / `executionOf()`.16//              - Vectors/swap-quote-fingerprint.json, swap-asset-keys.json, swap-cctp-quote-ref.json: the real `quoteFingerprint`,17//                `assetKey`, `cctpQuoteRef`. Intent and bridge-approval vectors are the shared Vectors/SPW-*.json.18//19// Author: Simon-Pierre Boucher20// Contact: contact@spboucher.ai21import Foundation22import Testing23@testable import SPWalletCore2425// MARK: - support2627private enum Fx {28    static let evm = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8", sol = "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU", btc = "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"29    static let usdcBase = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", usdcEth = "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", usdcSol = "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"30    static let rp = "wallet.example.test"31    /** Inside the approval window of every fixture intent (createdAt 1795000000). */32    static let now = Date(timeIntervalSince1970: 1_795_000_010)3334    static func view(_ name: String) throws -> JSONValue { try #require(try TestResources.json("swap-proposal-views.json")["views"]?[name], "view \(name)") }35    static func intent(_ name: String) throws -> JSONValue { try #require(try TestResources.json("swap-proposal-intents.json")["intents"]?[name], "intent \(name)") }36    static func proposal(_ name: String) throws -> Proposal { try view(name).decode() }3738    static func accounts(_ extra: [String: String] = [:]) throws -> Accounts {39        var m = ["base": evm, "ethereum": evm, "arbitrum": evm, "solana": sol, "bitcoin": btc]40        for (k, v) in extra { m[k] = v }41        let list = m.sorted { $0.key < $1.key }.map { JSONValue.object(["network": .string($0.key), "name": .string($0.key), "family": "x", "address": .string($0.value), "explorer": ""]) }42        return try JSONValue.object(["keyId": "spw-0123456789abcdef", "signerReachable": true, "accounts": .array(list)]).decode()43    }44    static func text(_ v: JSONValue) -> String { String(decoding: try! JSONEncoder().encode(v), as: UTF8.self) }45    static func options(_ digest: Data, rp: String = rp) -> JSONValue { ["challenge": .string(digest.base64URL), "rpId": .string(rp), "userVerification": "required", "timeout": 70000] }4647    /** `{ proposal, intent, options }` as the `native-clients` backend answers; the challenge is the hash of the intent GIVEN. */48    static func answer(_ name: String, intent: JSONValue? = nil, view: JSONValue? = nil, withIntent: Bool = true, extra: [String: JSONValue] = [:]) throws -> String {49        let i = try intent ?? Fx.intent(name)50        let digest = try Intent(served: i).approvalDigest()51        var o: [String: JSONValue] = ["proposal": try view ?? rehashed(Fx.view(name), digest), "options": options(digest)]52        if withIntent { o["intent"] = i }53        for (k, v) in extra { o[k] = v }54        return text(.object(o))55    }56    /** A server that lies consistently: the proposal's fingerprint follows the (tampered) intent. */57    static func rehashed(_ view: JSONValue, _ digest: Data) -> JSONValue { set(view, ["intentHash"], .string(digest.hex)) }5859    static func set(_ v: JSONValue, _ path: [String], _ new: JSONValue?) -> JSONValue {60        guard let k = path.first, case .object(var o) = v else { return new ?? .null }61        if path.count == 1 { if let new { o[k] = new } else { o[k] = nil } } else { o[k] = set(o[k] ?? .object([:]), Array(path.dropFirst()), new) }62        return .object(o)63    }64}6566private final class StubAuthenticator: PasskeyAuthenticator, @unchecked Sendable {67    private let lock = NSLock()68    private var _challenges: [String] = []69    var challenges: [String] { lock.withLock { _challenges } }70    func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {71        lock.withLock { _challenges.append(options.challenge) }72        return PasskeyAssertion(credentialId: Data([1, 2, 3]), clientDataJSON: Data("{}".utf8), authenticatorData: Data([4]), signature: Data([5]), userHandle: nil)73    }74    func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration { throw PasskeyError.notAvailable("stub") }75}7677private struct ScriptedStream: EventStreamTransport {78    let status: Int79    let chunks: [Data]80    let recorder: Recorder81    final class Recorder: @unchecked Sendable { private let lock = NSLock(); private var r: URLRequest?; var request: URLRequest? { get { lock.withLock { r } } set { lock.withLock { r = newValue } } } }82    init(status: Int = 200, chunks: [Data]) { self.status = status; self.chunks = chunks; recorder = Recorder() }83    func open(_ request: URLRequest) async throws -> (HTTPURLResponse, AsyncThrowingStream<Data, Error>) {84        recorder.request = request85        let http = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: ["content-type": "text/event-stream"])!86        return (http, AsyncThrowingStream { c in for d in chunks { c.yield(d) }; c.finish() })87    }88}8990private func expectInconsistent(_ fragment: String, sourceLocation: SourceLocation = #_sourceLocation, _ body: () async throws -> Void) async {91    do { try await body(); Issue.record("expected ApprovalError.inconsistent(…\(fragment)…)", sourceLocation: sourceLocation) }92    catch ApprovalError.inconsistent(let why) { #expect(why.contains(fragment), "inconsistent(\(why))", sourceLocation: sourceLocation) }93    catch { Issue.record("expected ApprovalError.inconsistent, got \(error)", sourceLocation: sourceLocation) }94}9596// MARK: - canonical bytes9798@Suite struct SwapCanonicalTests {99    @Test func swapBridgeAndXSwapIntentsReproduceTheBackendBytes() throws {100        let vectors = try CanonicalVector.load("SPW-INTENT-v1.json").filter { ["swap", "bridge", "xswap"].contains(String($0.name.split(separator: "-")[0])) }101        #expect(vectors.count >= 7)102        var kinds = Set<Intent.Kind>()103        for v in vectors {104            let i = try Intent(served: v.object)105            kinds.insert(i.kind)106            #expect(try i.canonicalBytes().hex == v.canonicalHex, "canonical bytes of \(v.name)")107            #expect(try i.approvalDigest().hex == v.hashHex, "hash of \(v.name)")108        }109        #expect(kinds == [.swap, .bridge, .xswap])110    }111112    /** `proposal.intentHash` of each fixture was computed by the backend's `intentHash` on the stored intent. */113    @Test func theFixtureIntentsHashToWhatTheBackendStoredOnTheirProposals() throws {114        let intents = try #require(try TestResources.json("swap-proposal-intents.json")["intents"]?.objectValue)115        #expect(intents.count == 9)116        for (name, json) in intents {117            #expect(try Intent(served: json).approvalDigest().hex == Fx.view(name)["intentHash"]?.stringValue, "\(name)")118        }119    }120121    @Test func mintRetryReclaimAndTokenAccountReproduceTheBackendBytes() throws {122        var seen = 0123        for file in ["SPW-BRIDGE-MINT-v1.json", "SPW-BRIDGE-MINT-SOL-v1.json"] {124            for v in try CanonicalVector.load(file) {125                let o = try BridgeMintRetry(served: v.object)126                #expect(try o.canonicalBytes().hex == v.canonicalHex && o.approvalDigest().hex == v.hashHex, "\(v.name)")127                if case .evm = o.parameters { #expect(v.domain == "SPW-BRIDGE-MINT-v1") } else { #expect(v.domain == "SPW-BRIDGE-MINT-SOL-v1") }128                seen += 1129            }130        }131        for v in try CanonicalVector.load("SPW-BRIDGE-RECLAIM-v1.json") {132            let o = try BridgeDepositReclaim(served: v.object)133            #expect(try o.canonicalBytes().hex == v.canonicalHex && o.approvalDigest().hex == v.hashHex, "\(v.name)"); seen += 1134        }135        for v in try CanonicalVector.load("SPW-SOL-TOKEN-ACCOUNT-v1.json") {136            let o = try SolanaTokenAccountRequest(served: v.object)137            #expect(try o.canonicalBytes().hex == v.canonicalHex && o.approvalDigest().hex == v.hashHex, "\(v.name)"); seen += 1138        }139        #expect(seen >= 4)140    }141142    @Test func anUnknownOrAmbiguousFieldOfABridgeApprovalIsARefusal() throws {143        let mint = try #require(try CanonicalVector.load("SPW-BRIDGE-MINT-v1.json").first).object144        #expect(throws: ApprovalError.self) { try BridgeMintRetry(served: Fx.set(mint, ["destinationCaller"], "0x00")) }145        #expect(throws: ApprovalError.self) { try BridgeMintRetry(served: Fx.set(mint, ["gas", "data"], "0xdead")) }146        #expect(throws: ApprovalError.self) { try BridgeMintRetry(served: Fx.set(mint, ["sol"], mint["gas"])) } // both gas and sol147        #expect(throws: ApprovalError.self) { try BridgeMintRetry(served: Fx.set(mint, ["gas"], nil)) }148        // a line break would let one field pass for two in the line-joined serialization149        #expect(throws: ApprovalError.self) { try BridgeMintRetry(served: Fx.set(mint, ["messageHash"], "0xaa\n7")) }150        let reclaim = try #require(try CanonicalVector.load("SPW-BRIDGE-RECLAIM-v1.json").first).object151        #expect(throws: ApprovalError.self) { try BridgeDepositReclaim(served: Fx.set(reclaim, ["payee"], "x")) }152        #expect(throws: ApprovalError.self) { try BridgeDepositReclaim(served: Fx.set(reclaim, ["eventAccount"], "a\nb")).canonicalBytes() }153        let ata = try #require(try CanonicalVector.load("SPW-SOL-TOKEN-ACCOUNT-v1.json").first).object154        #expect(throws: ApprovalError.self) { try SolanaTokenAccountRequest(served: Fx.set(ata, ["authority"], "x")) }155        #expect(throws: ApprovalError.self) { try SolanaTokenAccountRequest(served: Fx.set(ata, ["v"], 2)) }156        let base = try SolanaTokenAccountRequest(served: ata).approvalDigest()157        for (k, v) in [("owner", JSONValue.string(Fx.btc)), ("mint", "x"), ("tokenAccount", "y"), ("maxFee", "2100001"), ("expiresAt", 1794000046)] {158            #expect(try SolanaTokenAccountRequest(served: Fx.set(ata, [k], v)).approvalDigest() != base, "field \(k)")159        }160    }161162    @Test func quoteFingerprintIsTheBackends() throws {163        let vectors = try CanonicalVector.load("swap-quote-fingerprint.json")164        #expect(vectors.count == 5)165        for v in vectors {166            let o = v.object167            let f = QuoteFacts(provider: try #require(o["provider"]?.stringValue), fromKey: try #require(o["fromKey"]?.stringValue), toKey: try #require(o["toKey"]?.stringValue),168                               amountIn: try #require(o["amountIn"]?.stringValue), slippageBps: Int(try #require(o["slippageBps"]?.intValue)),169                               amountOut: try #require(o["amountOut"]?.stringValue), minAmountOut: try #require(o["minAmountOut"]?.stringValue))170            #expect(Data(f.canonicalText.utf8).hex == v.canonicalHex, "joined text of \(v.name)")171            #expect(f.fingerprint == String(v.hashHex.prefix(32)), "fingerprint of \(v.name)")172            #expect(f.fingerprint.count == 32)173        }174        // served `fingerprint` field of the vector file = what the API serves175        let raw = try JSONDecoder().decode([JSONValue].self, from: try TestResources.data("swap-quote-fingerprint.json", in: "Vectors"))176        #expect(raw[0]["fingerprint"]?.stringValue == String(vectors[0].hashHex.prefix(32)))177    }178179    @Test func assetKeysLowercaseEvmAddressesOnly() throws {180        let raw = try JSONDecoder().decode([JSONValue].self, from: try TestResources.data("swap-asset-keys.json", in: "Vectors"))181        #expect(raw.count == 7)182        for v in raw {183            let o = try #require(v["object"])184            let ref = AssetRef(network: try #require(o["network"]?.stringValue), asset: try #require(o["asset"]?.stringValue))185            #expect(ref.key(family: try #require(o["family"]?.stringValue)) == v["key"]?.stringValue)186        }187        #expect(AssetRef.sameAssetId(Fx.usdcBase, Fx.usdcBase.lowercased()))188        #expect(!AssetRef.sameAssetId(Fx.usdcSol, Fx.usdcSol.lowercased())) // a Solana mint is case-sensitive189        #expect(!AssetRef.sameAssetId("native", Fx.usdcBase))190    }191192    @Test func cctpOptionReferencesAreTheFingerprintOfTheirOwnFigures() throws {193        let raw = try JSONDecoder().decode([JSONValue].self, from: try TestResources.data("swap-cctp-quote-ref.json", in: "Vectors"))194        #expect(raw.count == 4)195        for v in raw {196            let o = try #require(v["object"]), ref: QuoteRef = try #require(v["ref"]).decode()197            let f = QuoteFacts(provider: "cctp", fromKey: try #require(o["fromKey"]?.stringValue), toKey: try #require(o["toKey"]?.stringValue),198                               amountIn: try #require(o["amount"]?.stringValue), slippageBps: 0, amountOut: ref.amountOut, minAmountOut: ref.minAmountOut)199            #expect(f.fingerprint == ref.fingerprint && ref.isWellFormed && ref.amountOut == ref.minAmountOut)200        }201    }202203    @Test func exactProductsAndSolanaFees() throws {204        #expect(DecimalDigits.multiply("250000", "30000000000") == "7500000000000000")205        #expect(DecimalDigits.multiply("0", "123") == "0")206        #expect(DecimalDigits.multiply("115792089237316195423570985008687907853269984665640564039457584007913129639935", "2") == "231584178474632390847141970017375815706539969331281128078915168015826259279870")207        #expect(EVMGasParameters(nonce: 1, gasLimit: "240000", maxFeePerGas: "200000000", maxPriorityFeePerGas: "1").maxNetworkFee == "48000000000000")208        // priorityOf of bridge-sol.ts: ⌈limit × price ÷ 10⁶⌉209        let b = SolanaBudget(recentBlockhash: "x", lastValidBlockHeight: 1, computeUnitLimit: 60000, computeUnitPrice: "10000")210        #expect(b.priorityFee?.description == "600" && b.singleSignerNetworkFee?.description == "5600")211        #expect(SolanaBudget(recentBlockhash: "x", lastValidBlockHeight: 1, computeUnitLimit: 40001, computeUnitPrice: "5").priorityFee?.description == "1")212        #expect(SolanaBudget(recentBlockhash: "x", lastValidBlockHeight: 1, computeUnitLimit: 40000, computeUnitPrice: "0").singleSignerNetworkFee?.description == "5000")213    }214}215216// MARK: - decoding217218@Suite struct SwapDecodingTests {219    @Test func discoveryShapes() throws {220        let d = try TestResources.json("swap-discovery.json")221        struct Assets: Decodable { let assets: [SwapAsset] }222        let assets = try #require(d["assets"]).decode(Assets.self).assets223        #expect(assets.count == 4 && assets[0].native == true && assets[1].key == "base:" + Fx.usdcBase.lowercased() && assets[1].asset == Fx.usdcBase)224225        let p: SwapProviders = try #require(d["providers"]).decode()226        #expect(p.executionEnabled && p.executors == ["kyberswap", "jupiter", "cctp", "thorchain"] && p.needsKey == ["zerox", "oneinch"])227        #expect(p.isExecutor("kyberswap") && !p.isExecutor("lifi")) // lifi quotes; it never executes here228        #expect(p.providers[1].p50 == nil && p.providers[1].state == "half_open" && p.providers[1].lastError == "timeout")229        #expect(p.providers[2].capabilities?.needsKey == true && p.providers[2].capabilities?.configured == false)230231        let s: SwapStats = try #require(d["stats"]).decode()232        #expect(s.window == "7d" && s.providers[0].quotes == 117)233234        let e: SwapExecutionInfo = try #require(d["swapExecution"]).decode()235        #expect(e.executor(on: "base") == "kyberswap" && e.executor(on: "solana") == "jupiter" && e.executor(on: "bitcoin") == nil)236        #expect(e.solana?.label == "Jupiter (Metis)" && e.solana?.lastDeploySlot == 462802085)237238        let b: BridgeExecutionInfo = try #require(d["bridgeExecution"]).decode()239        #expect(b.canBridge(from: "base", to: "solana") && !b.canBridge(from: "base", to: "base") && !b.canBridge(from: "base", to: "bsc"))240241        let x: XSwapExecutionInfo = try #require(d["xswapExecution"]).decode()242        #expect(x.minOperators == 3 && x.routers?["ethereum"] != nil)243        #expect(x.canSwap(from: AssetRef(network: "ethereum", asset: Fx.usdcEth.lowercased()), to: AssetRef(network: "bitcoin", asset: "native")))244        #expect(x.canSwap(from: AssetRef(network: "bitcoin", asset: "native"), to: AssetRef(network: "dogecoin", asset: "native")))245        #expect(!x.canSwap(from: AssetRef(network: "dogecoin", asset: "native"), to: AssetRef(network: "bitcoin", asset: "native"))) // destination only246        #expect(!x.canSwap(from: AssetRef(network: "ethereum", asset: "native"), to: AssetRef(network: "ethereum", asset: Fx.usdcEth)))247248        let c: PlanCapabilities = try #require(d["planCapabilities"]).decode()249        #expect(c.maxLegs == 3 && c.hub == "USDC" && c.swap["solana"] == "jupiter" && c.thorchain[1].source == false)250    }251252    @Test func routesCardsAndTheQuoteReference() throws {253        let s: SwapSearch = try #require(try TestResources.json("swap-discovery.json")["search"]).decode()254        #expect(s.reachable && s.executors == ["kyberswap"] && s.best["best_price"] == "kyberswap:6c1f" && s.providers.count == 4)255        let kyber = s.routes[0], lifi = s.routes[1]256        #expect(kyber.executable && kyber.statedExecutor == "kyberswap" && kyber.executability?.class == "verified")257        #expect(kyber.amountOut == "25000000" && kyber.minAmountOutDisplay == "24.875" && kyber.refundable == nil && kyber.estimatedSeconds == nil)258        #expect(kyber.card?.toleranceBps == 50 && kyber.card?.networkFee?.items.first?.display == "0.000021" && kyber.card?.protocolFee == nil && kyber.card?.etaSeconds == nil)259        #expect(kyber.fingerprintIsConsistent)260        let ref = try #require(kyber.quoteReference)261        #expect(ref == QuoteRef(id: "kyberswap:6c1f", provider: "kyberswap", fingerprint: try #require(kyber.fingerprint), amountOut: "25000000", minAmountOut: "24875000", quotedAt: 1795000000123))262263        // a comparison-only route: better price, never a reference, never an executor264        #expect(!lifi.executable && lifi.statedExecutor == nil && lifi.quoteReference == nil && lifi.card?.reasonCode == "opaque_calldata")265        #expect(lifi.risk?.level == .medium && lifi.risk?.flags.map(\.code) == ["opaque_transaction", "not_executable"])266        #expect(lifi.fingerprintIsConsistent) // consistent, and still not sent: the wallet does not execute it267268        // a route whose figures do not hash to the served fingerprint gives no reference269        let tampered: SwapRoute = try Fx.set(try #require(try TestResources.json("swap-discovery.json")["search"]?["routes"]?[0]), ["minAmountOut"], "24000000").decode()270        #expect(!tampered.fingerprintIsConsistent && tampered.quoteReference == nil)271        // a CCTP route of the stream is never referenced (it is prepared from /bridge/quote)272        var cctp = try #require(try TestResources.json("swap-discovery.json")["search"]?["routes"]?[0])273        cctp = Fx.set(Fx.set(cctp, ["executor"], "cctp"), ["exec"], ["via": "cctp", "speed": "fast"])274        #expect(try cctp.decode(SwapRoute.self).quoteReference == nil)275    }276277    @Test func sameNetworkSwapViews() throws {278        let review = try Fx.proposal("swap-kyber-review")279        let s = try #require(try review.swapSection())280        #expect(review.kind == "swap" && s.provider == "kyberswap" && s.minOut == "24875000" && s.minOutDisplay == "24.875" && s.received == nil && s.approvalState == nil)281        let q = try #require(try review.quoteRecord())282        #expect(q.deviationBps == -4 && q.quotedOutDisplay == "25" && q.firmOutDisplay == "24.99" && q.firmMinOut == "24865050")283        let e = try #require(try review.executionStatus())284        #expect(e.state == .awaitingApproval && !e.isComplete && e.currentStep?.kind == "swap")285        #expect(try review.swapCompletion() == .notStarted)286287        let approving = try Fx.proposal("swap-kyber-approval-sent")288        #expect(try approving.swapSection()?.approvalState == "sent" && approving.swapSection()?.needsApproval == true)289        let steps = try #require(try approving.executionStatus()).steps290        #expect(steps.map(\.id) == ["approval", "swap"] && steps[0].state == .broadcast && steps[1].state == .pending)291        #expect(try approving.swapCompletion() == .inProgress)292293        let final = try Fx.proposal("swap-kyber-finalized")294        #expect(try final.swapSection()?.received == "24991234" && final.swapSection()?.receivedDisplay == "24.991234")295        #expect(try final.swapCompletion() == .complete && final.executionStatus()?.isComplete == true)296297        let failed = try Fx.proposal("swap-kyber-failed-would-revert")298        #expect(failed.errorCode == "swap_would_revert" && failed.errorParams?["detail"]?.stringValue == "Return amount is not enough")299        #expect(try failed.swapCompletion() == .failed && failed.executionStatus()?.state == .failed)300301        let jup = try #require(try Fx.proposal("swap-jupiter-review").swapSection())302        #expect(jup.provider == "jupiter" && jup.detail?["label"]?.stringValue == "Jupiter (Metis)" && jup.detail?["createsAccount"]?.boolValue == true && jup.detail?["rentDisplay"]?.stringValue == "0.00203928")303    }304305    /** Every phase of bridge.ts `BridgePhase` × the proposal states that matter: complete ONLY when the mint is recorded. */306    @Test func aBridgeIsCompleteOnlyWhenTheDestinationIsConfirmed() throws {307        let cases: [(String, BridgeStage, BridgePhase, OperationCompletion)] = [308            ("bridge-review", .review, .burn, .notStarted), ("bridge-burning", .burning, .burn, .inProgress),309            ("bridge-attesting", .attesting, .attesting, .inProgress), ("bridge-attesting-late-hold", .attesting, .attesting, .inProgress),310            ("bridge-ready-destination-gas-hold", .ready, .ready, .inProgress), ("bridge-minting", .minting, .mintSent, .inProgress),311            ("bridge-mint-failed-needs-passkey", .mintFailed, .mintFailed, .inProgress), ("bridge-done", .done, .done, .complete),312            ("bridge-done-minted-by-other", .done, .done, .complete), ("bridge-burn-failed", .failed, .burn, .failed),313            ("bridge-sol-source-burn-sent", .burning, .burn, .inProgress), ("bridge-sol-destination-ready", .ready, .ready, .inProgress),314        ]315        for (name, stage, phase, completion) in cases {316            let p = try Fx.proposal(name), b = try #require(try p.bridgeSection(), "\(name)")317            #expect(b.stage == stage && b.phase == phase, "\(name)")318            #expect(try p.swapCompletion() == completion, "\(name)")319            #expect(b.isComplete == (completion == .complete), "\(name)")320            #expect(try p.executionStatus()?.isComplete == (completion == .complete), "\(name)")321        }322        // the burn is FINAL on its chain and the transfer is not complete: the proposal state alone would say "success"323        let late = try Fx.proposal("bridge-attesting-late-hold"), lateB = try #require(try late.bridgeSection())324        #expect(late.state == .finalized && late.state.isSuccess && !lateB.isComplete && lateB.isInTransit)325        #expect(lateB.hold == "attestation_late" && lateB.holdCode == "hold_attestation_late" && lateB.received == nil && lateB.canFinish == true)326327        let gas = try #require(try Fx.proposal("bridge-ready-destination-gas-hold").bridgeSection())328        #expect(gas.hold == "destination_gas" && gas.holdParams?["need"]?.stringValue == "0.000048" && gas.attested == true)329        let failedMint = try #require(try Fx.proposal("bridge-mint-failed-needs-passkey").bridgeSection())330        #expect(failedMint.needsPasskey == true && failedMint.mintTxid != nil && !failedMint.isComplete && !failedMint.isFailed)331        let done = try #require(try Fx.proposal("bridge-done").bridgeSection())332        #expect(done.received == "49995000" && done.receivedDisplay == "49.995" && done.feeExecutedDisplay == "0.005" && done.mintedBy == "wallet" && done.canFinish == false)333        let other = try #require(try Fx.proposal("bridge-done-minted-by-other").bridgeSection())334        #expect(other.isComplete && other.mintedBy == "other" && other.mintTxid == nil && other.speed == .fast && other.cctpMaxFee == "6500")335        let review = try #require(try Fx.proposal("bridge-review").bridgeSection())336        #expect(review.cctpMaxFee == "0" && review.minReceiveDisplay == "50" && review.needsApproval == true && review.sol == nil && review.speed == .standard)337        // a phase added by a newer server is kept verbatim and is never "complete" (bridgeView's own fallback would call it `done`)338        let unknown: BridgeSection = try Fx.set(Fx.set(try Fx.view("bridge-minting"), ["bridge", "phase"], "mint_queued"), ["bridge", "stage"], "done")["bridge"]!.decode()339        #expect(unknown.phase.rawValue == "mint_queued" && !unknown.isComplete)340    }341342    @Test func solanaEventAccountReclaimStates() throws {343        let cases: [(String, ReclaimState, Bool, Bool)] = [344            ("bridge-sol-source-review", .pending, false, false), ("bridge-sol-source-burn-sent", .pending, false, false),345            ("bridge-sol-source-done-reclaim-locked", .locked, false, false), ("bridge-sol-source-reclaim-available", .available, true, false),346            ("bridge-sol-source-reclaim-sent", .sent, false, false), ("bridge-sol-source-reclaim-failed", .failed, true, false),347            ("bridge-sol-source-reclaim-done", .done, false, true),348        ]349        for (name, state, canReclaim, reclaimed) in cases {350            let s = try #require(try Fx.proposal(name).bridgeSection()?.sol, "\(name)")351            #expect(s.role == "source" && s.reclaimState == state && s.canReclaim == canReclaim && s.isReclaimed == reclaimed, "\(name)")352        }353        let review = try #require(try Fx.proposal("bridge-sol-source-review").bridgeSection()?.sol)354        #expect(review.deposit == "3883680" && review.depositDisplay == "0.00388368" && review.eventAccount == nil && review.reclaimEstimated == true && review.reclaimableAt != nil)355        let locked = try #require(try Fx.proposal("bridge-sol-source-done-reclaim-locked").bridgeSection()?.sol)356        #expect(locked.reclaimEstimated == false && locked.reclaimableAt == Date(timeIntervalSince1970: 1_795_000_020 + 5 * 86400) && locked.eventAccount == "GokivDYuQXPZCWRkwMhdH2h91KpDQXBEmpgBgs55bnpH")357        let failed = try #require(try Fx.proposal("bridge-sol-source-reclaim-failed").bridgeSection()?.sol)358        #expect(failed.reclaimError?.contains("the deposit is still there") == true)359        let done = try #require(try Fx.proposal("bridge-sol-source-reclaim-done").bridgeSection()?.sol)360        #expect(done.reclaimedDisplay == "0.00387808" && done.reclaimTxid != nil && done.reclaimExplorer != nil)361        // the transfer itself was complete long before the deposit came back362        #expect(try Fx.proposal("bridge-sol-source-done-reclaim-locked").swapCompletion() == .complete)363        let dest = try #require(try Fx.proposal("bridge-sol-destination-ready").bridgeSection()?.sol)364        #expect(dest.role == "destination" && dest.reclaimState == nil && !dest.canReclaim && dest.recipient == Fx.sol && dest.tokenAccount != nil && dest.nonceRentDisplay == "0.00095352")365    }366367    /** Every phase of xswap-state.ts `XswapPhase`: complete ONLY when the wallet saw the outbound; a refund is not a success. */368    @Test func aNativeSwapIsCompleteOnlyWhenTheOutboundWasSeen() throws {369        let cases: [(String, XSwapStage, XSwapPhase, OperationCompletion)] = [370            ("xswap-review", .review, .sending, .notStarted), ("xswap-sending", .sending, .sending, .inProgress), ("xswap-sent", .sent, .sent, .inProgress),371            ("xswap-sent-vault-churned-hold", .sent, .sent, .inProgress), ("xswap-observed-refund-planned", .observed, .observed, .inProgress),372            ("xswap-outbound", .outbound, .outbound, .inProgress), ("xswap-received", .received, .received, .complete),373            ("xswap-received-below-minimum-hold", .received, .received, .complete), ("xswap-refunded", .refunded, .refunded, .refunded),374            ("xswap-source-failed", .failed, .sending, .failed),375        ]376        for (name, stage, phase, completion) in cases {377            let p = try Fx.proposal(name), x = try #require(try p.xswapSection(), "\(name)")378            #expect(x.stage == stage && x.phase == phase, "\(name)")379            #expect(try p.swapCompletion() == completion, "\(name)")380            #expect(x.isComplete == (completion == .complete) && x.isRefunded == (completion == .refunded), "\(name)")381        }382        let observed = try Fx.proposal("xswap-observed-refund-planned"), o = try #require(try observed.xswapSection())383        #expect(observed.state == .finalized && !o.isComplete && o.refundPlanned == true && o.done == false) // source final, nothing received384        let received = try #require(try Fx.proposal("xswap-received").xswapSection())385        #expect(received.receivedDisplay == "0.00054801" && received.outKind == "out" && received.done == true && !received.receivedBelowMinimum && received.outExplorer != nil)386        let below = try #require(try Fx.proposal("xswap-received-below-minimum-hold").xswapSection())387        #expect(below.isComplete && below.receivedBelowMinimum && below.hold == "below_minimum")388        let refunded = try Fx.proposal("xswap-refunded"), r = try #require(try refunded.xswapSection())389        #expect(r.done == true && !r.isComplete && r.refundedDisplay == "0.0197" && r.outKind == "refund" && r.receivedDisplay == nil)390        #expect(try refunded.executionStatus()?.state == .refunded && refunded.executionStatus()?.isComplete == false)391        let review = try #require(try Fx.proposal("xswap-review").xswapSection())392        #expect(review.vault == "0x718f6C9df785BC4e323086De024CA822efbE8aB9" && review.memo.hasPrefix("=:b:") && review.operators?.count == 3 && review.evidenceMultiple == 406150 && review.minOutDisplay == "0.00054436")393        let churn = try #require(try Fx.proposal("xswap-sent-vault-churned-hold").xswapSection())394        #expect(churn.hold == "vault_churned" && churn.holdCode == "hold_vault_churned")395        let btc = try #require(try Fx.proposal("xswap-btc-review").xswapSection())396        #expect(btc.router == nil && btc.toNetwork == "ethereum")397        // a transfer is not a swap398        #expect(throws: ApprovalError.self) { try Fx.set(try Fx.view("xswap-review"), ["kind"], "transfer").decode(Proposal.self).swapCompletion() }399    }400401    @Test func executionStatusOfALegWithoutProposal() throws {402        let d = try TestResources.json("swap-pending-execution.json")403        let pending: ExecutionStatus = try #require(d["pending"]).decode(), settled: ExecutionStatus = try #require(d["settled"]).decode()404        #expect(pending.kind == "bridge" && pending.state == .pending && pending.steps.map(\.kind) == ["burn"] && !pending.isComplete && pending.updatedAt == nil)405        #expect(settled.state == .confirmed && settled.isComplete && settled.steps[0].kind == "deposit")406        let bridge = try #require(try Fx.proposal("bridge-minting").executionStatus())407        #expect(bridge.steps.map(\.id) == ["burn", "attestation", "mint"] && bridge.steps[1].network == "circle" && bridge.currentStep?.id == "mint" && bridge.steps[2].state == .broadcast)408        let x = try #require(try Fx.proposal("xswap-outbound").executionStatus())409        #expect(x.steps.map(\.id) == ["deposit", "observation", "outbound"] && x.steps[2].state == .confirming && x.steps[1].network == "thorchain")410    }411412    @Test func quoteMovedAndQuoteRecord() throws {413        let f = try TestResources.json("swap-quote-moved.json")414        let body = try #require(f["body"])415        let e = APIError(status: 409, code: "quote_moved", message: try #require(body["message"]?.stringValue), data: body["data"], body: body)416        let m = try #require(QuoteMoved(e))417        #expect(m.quoted.minAmountOut == "24875000" && m.quoted.minAmountOutDisplay == "24.875" && m.fresh.amountOut == "24800000" && m.fresh.amountOutDisplay == "24.8")418        #expect(m.fresh.symbol == "USDC" && m.fresh.fingerprint?.count == 32 && m.deviationBps == -80 && m.slippageBps == 50 && m.message.contains("Nothing was prepared"))419        #expect(QuoteMoved(APIError(status: 409, code: "pending_tx", message: "x", data: body["data"])) == nil)420        #expect(QuoteMoved(APIError(status: 409, code: "quote_moved", message: "x")) == nil) // no figures: stays a plain APIError421        let r: QuoteRecord = try #require(try TestResources.json("swap-quote-record.json")["record"]).decode()422        #expect(r.deviationBps == -4 && r.firmOut == "24990000" && r.quotedOutDisplay == nil)423    }424425    @Test func bridgeQuotes() throws {426        let d = try TestResources.json("swap-bridge-quote.json")427        let evm: BridgeQuote = try #require(d["evm"]).decode()428        #expect(evm.options.map(\.speed) == [.standard, .fast] && evm.option(.fast)?.fee == "6500" && evm.option(.fast)?.minReceiveDisplay == "49.9935" && evm.destinationGas.enough && evm.solana == nil)429        #expect(evm.option(.standard)?.quote?.id == "cctp-standard-base-arbitrum-50000000" && evm.option(.standard)?.quote?.isWellFormed == true)430        let from: BridgeQuote = try #require(d["fromSolana"]).decode()431        #expect(from.solana?.role == "source" && from.solana?.deposit == "3883680" && from.solana?.reclaimAfterSeconds == 432000 && !from.destinationGas.enough)432        let to: BridgeQuote = try #require(d["toSolana"]).decode()433        #expect(to.options.count == 1 && to.option(.fast) == nil && to.solana?.tokenAccountExists == false && to.solana?.recipient == Fx.sol)434        let ta: SolanaTokenAccountStatus = try #require(d["tokenAccount"]).decode()435        #expect(!ta.exists && ta.rent == "2039280")436    }437438    @Test func plans() throws {439        let d = try TestResources.json("swap-plans.json")440        let q: PlanQuote = try #require(d["quote"]).decode()441        let c = try #require(q.plans.first)442        #expect(q.notExecutable == nil && c.executable && c.approvals == 3 && c.legs.map(\.kind) == ["swap", "bridge", "xswap"] && c.legs.map(\.via) == ["kyberswap", "cctp", "thorchain"])443        #expect(c.worstOut == "21052" && c.worstOutDisplay == "0.00021052" && c.requirements?.gas[1].haveDisplay == nil && c.issues[0].code == "gas_unknown" && c.issues[0].blocking == false && c.issues[0].leg == nil)444        #expect(q.skipped[0].leg == 1 && q.skipped[0].code == "no_route")445        let none: PlanQuote = try #require(d["quoteNotExecutable"]).decode()446        #expect(none.plans.isEmpty && none.notExecutable?.code == "network_without_execution" && none.notExecutable?.network == "dogecoin")447448        let ready: PlanView = try #require(d["ready"]).decode()449        #expect(ready.state == .active && ready.next == .prepare && ready.isOpen && !ready.isComplete && ready.currentLeg?.state == .ready && ready.legs[1].state == .pending)450        #expect(ready.holding.amount == "10000000000000000" && ready.floor == "21000" && ready.proposal == nil && ready.receivedDisplay == nil && ready.legs[0].execution?.state == .pending)451452        let prepared: PlanView = try #require(d["prepared"]?["plan"]).decode()453        #expect(prepared.next == .approve && prepared.currentLeg?.state == .proposed && prepared.currentLeg?.proposalId == prepared.proposal?.id && prepared.legs[0].attempts[0].outcome == nil)454        #expect(prepared.legs[0].execution?.state == .awaitingApproval)455456        let paused: PlanView = try #require(d["pausedOnFloor"]?["plan"]).decode()457        #expect(paused.state == .paused && paused.next == .paused && paused.pause?.code == "floor" && paused.pause?.params?["floor"]?.stringValue == "0.00021" && paused.pause?.at != nil && paused.isOpen)458459        let done: PlanView = try #require(d["done"]).decode()460        #expect(done.state == .done && done.isComplete && !done.isOpen && done.receivedDisplay == "24.991234" && done.legs[0].isSettled && done.legs[0].actual.outDisplay == "24.991234")461        // "done" without every leg settled is not complete462        let odd: PlanView = try Fx.set(try #require(d["ready"]), ["state"], "done").decode()463        #expect(!odd.isComplete)464    }465}466467// MARK: - request contract468469@Suite struct SwapRequestContractTests {470    private func expectGet(_ t: MockTransport, _ path: String, query: [String: String] = [:], sourceLocation: SourceLocation = #_sourceLocation) {471        let r = t.last472        #expect(r?.method == "GET" && r?.path == "/api/v1" + path && r?.query == query && r?.headers["Idempotency-Key"] == nil && r?.headers["X-SPW-CSRF"] == nil, sourceLocation: sourceLocation)473    }474    private func expectPost(_ t: MockTransport, _ path: String, body: JSONValue, idempotencyKey: String? = nil, sourceLocation: SourceLocation = #_sourceLocation) {475        let r = t.last476        #expect(r?.method == "POST" && r?.path == "/api/v1" + path && r?.query == [:], sourceLocation: sourceLocation)477        #expect(r?.body == body, "body \(String(describing: r?.body))", sourceLocation: sourceLocation)478        #expect(r?.headers["Idempotency-Key"] == idempotencyKey && r?.headers["X-SPW-CSRF"] == "1" && r?.headers["Origin"] == "https://wallet.example.test", sourceLocation: sourceLocation)479    }480481    @Test func discoveryReads() async throws {482        let (client, t, _) = MockTransport.client()483        let d = try TestResources.json("swap-discovery.json")484        let api = SwapAPI(client)485        t.enqueue(json: Fx.text(try #require(d["assets"]))); #expect(try await api.assets().count == 4); expectGet(t, "/swap/assets")486        t.enqueue(json: Fx.text(try #require(d["providers"]))); _ = try await api.providers(); expectGet(t, "/swap/providers")487        t.enqueue(json: Fx.text(try #require(d["stats"]))); _ = try await api.stats(); expectGet(t, "/swap/stats")488        t.enqueue(json: Fx.text(try #require(d["swapExecution"]))); _ = try await api.execution(); expectGet(t, "/swap/execution")489        t.enqueue(json: Fx.text(try #require(d["bridgeExecution"]))); _ = try await BridgeAPI(client).execution(); expectGet(t, "/bridge/execution")490        t.enqueue(json: Fx.text(try #require(d["xswapExecution"]))); _ = try await XSwapAPI(client).execution(); expectGet(t, "/xswap/execution")491        t.enqueue(json: Fx.text(try #require(d["planCapabilities"]))); _ = try await PlanAPI(client).capabilities(); expectGet(t, "/plans/capabilities")492493        t.enqueue(json: Fx.text(try #require(d["search"])))494        let s = try await api.quote(SwapQuoteRequest(from: "base:native", to: "base:" + Fx.usdcBase.lowercased(), amount: "0.01"))495        #expect(s.routes.count == 2)496        expectPost(t, "/swap/quote", body: ["from": "base:native", "to": .string("base:" + Fx.usdcBase.lowercased()), "amount": "0.01", "slippageBps": 50])497    }498499    @Test func bridgeRoutes() async throws {500        let (client, t, _) = MockTransport.client()501        let api = BridgeAPI(client), d = try TestResources.json("swap-bridge-quote.json")502        t.enqueue(json: Fx.text(try #require(d["evm"])))503        _ = try await api.quote(from: "base", to: "arbitrum", amount: "50")504        expectGet(t, "/bridge/quote", query: ["from": "base", "to": "arbitrum", "amount": "50"])505        t.enqueue(json: Fx.text(try #require(d["tokenAccount"]))); _ = try await api.solanaTokenAccount(); expectGet(t, "/bridge/solana/token-account")506507        let id = "5b2d3c4e-1a2b-4c3d-8e4f-000000000004"508        t.enqueue(json: Fx.text(try Fx.view("bridge-minting")))509        #expect(try await api.finish(id).bridgeSection()?.stage == .minting)510        expectPost(t, "/bridge/proposals/\(id)/finish", body: [:])511        t.enqueue(json: Fx.text(try Fx.view("xswap-outbound")))512        #expect(try await XSwapAPI(client).refresh("5b2d3c4e-1a2b-4c3d-8e4f-000000000008").xswapSection()?.stage == .outbound)513        expectPost(t, "/xswap/proposals/5b2d3c4e-1a2b-4c3d-8e4f-000000000008/refresh", body: [:])514515        // the shared follow-up of a proposal: status and rejection are the transfers routes516        t.enqueue(json: Fx.text(try Fx.view("bridge-attesting"))); _ = try await api.proposal(id); expectGet(t, "/transfers/proposals/\(id)")517        t.enqueue(json: #"{"id":"\#(id)","state":"confirming","kind":"bridge","execution":{"kind":"bridge","state":"confirming","steps":[],"updatedAt":null}}"#)518        #expect(try await api.status(id).executionStatus()?.isComplete == false); expectGet(t, "/transfers/\(id)/status")519        t.enqueue(json: Fx.text(Fx.set(try Fx.view("bridge-review"), ["state"], "rejected"))); #expect(try await api.reject(id).state == .rejected)520        expectPost(t, "/transfers/proposals/\(id)/reject", body: [:])521    }522523    @Test func planRoutes() async throws {524        let (client, t, _) = MockTransport.client()525        let api = PlanAPI(client), d = try TestResources.json("swap-plans.json")526        let r = PlanRequest(from: "base:native", to: "bitcoin:native", amount: "0.01")527        t.enqueue(json: Fx.text(try #require(d["quote"])))528        let q = try await api.quote(r)529        expectPost(t, "/plans/quote", body: ["from": "base:native", "to": "bitcoin:native", "amount": "0.01", "slippageBps": 50])530531        let shape = q.plans[0].id, id = "9d1e2f30-4a5b-4c6d-8e7f-000000000001"532        t.enqueue(json: Fx.text(try #require(d["ready"])))533        #expect(try await api.start(r, plan: shape, floor: "0.00021").next == .prepare)534        expectPost(t, "/plans", body: ["from": "base:native", "to": "bitcoin:native", "amount": "0.01", "slippageBps": 50, "plan": .string(shape), "floor": "0.00021"])535        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.start(r, plan: shape)536        #expect(t.last?.body?["floor"] == nil && t.last?.headers["Idempotency-Key"] == nil)537538        t.enqueue(json: Fx.text(["plans": [try #require(d["ready"])]])); #expect(try await api.list(openOnly: true, limit: 500).count == 1)539        expectGet(t, "/plans", query: ["open": "1", "limit": "50"])540        t.enqueue(json: #"{"plans":[]}"#); _ = try await api.list(); expectGet(t, "/plans", query: ["limit": "10"])541        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.plan(id); expectGet(t, "/plans/\(id)")542543        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.retry(id); expectPost(t, "/plans/\(id)/retry", body: [:])544        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.retry(id, floor: .remove); expectPost(t, "/plans/\(id)/retry", body: ["floor": nil])545        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.retry(id, floor: .set("0.0002")); expectPost(t, "/plans/\(id)/retry", body: ["floor": "0.0002"])546        t.enqueue(json: Fx.text(Fx.set(try #require(d["ready"]), ["state"], "stopped"))); #expect(try await api.stop(id).state == .stopped)547        expectPost(t, "/plans/\(id)/stop", body: [:])548        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.replan(id); expectPost(t, "/plans/\(id)/replan", body: [:])549        t.enqueue(json: Fx.text(try #require(d["ready"]))); _ = try await api.replan(id, plan: shape); expectPost(t, "/plans/\(id)/replan", body: ["plan": .string(shape)])550    }551552    @Test func preparationsCarryTheCallersIdempotencyKeyAndTheQuoteReference() async throws {553        let (client, t, _) = MockTransport.client()554        let accounts = try Fx.accounts(), key = APIClient.newIdempotencyKey()555        let search: SwapSearch = try #require(try TestResources.json("swap-discovery.json")["search"]).decode()556        let ref = try #require(search.routes[0].quoteReference)557        let refJSON = try JSONValue.from(ref)558559        t.enqueue(json: try Fx.answer("swap-kyber-review"))560        _ = try await SwapAPI(client).prepare(SwapRequest(network: "base", fromAsset: "native", toAsset: Fx.usdcBase, amount: "0.01", quote: ref), accounts: accounts, idempotencyKey: key, now: Fx.now)561        expectPost(t, "/swap/proposals", body: ["network": "base", "fromAsset": "native", "toAsset": .string(Fx.usdcBase), "amount": "0.01", "slippageBps": 50, "quote": refJSON], idempotencyKey: key)562        #expect(refJSON.objectValue?.keys.sorted() == ["amountOut", "fingerprint", "id", "minAmountOut", "provider", "quotedAt"]) // the server's schema is strict563564        t.enqueue(json: try Fx.answer("swap-kyber-review"))565        _ = try await SwapAPI(client).prepare(SwapRequest(network: "base", fromAsset: "native", toAsset: Fx.usdcBase, amount: "0.01", slippageBps: 30), accounts: accounts, idempotencyKey: key, now: Fx.now)566        expectPost(t, "/swap/proposals", body: ["network": "base", "fromAsset": "native", "toAsset": .string(Fx.usdcBase), "amount": "0.01", "slippageBps": 30], idempotencyKey: key) // no `quote` key at all567568        t.enqueue(json: try Fx.answer("bridge-review"))569        _ = try await BridgeAPI(client).prepare(BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "50"), accounts: accounts, idempotencyKey: key, now: Fx.now)570        expectPost(t, "/bridge/proposals", body: ["fromNetwork": "base", "toNetwork": "arbitrum", "amount": "50", "speed": "standard"], idempotencyKey: key)571572        t.enqueue(json: try Fx.answer("xswap-review"))573        _ = try await XSwapAPI(client).prepare(XSwapRequest(fromNetwork: "ethereum", fromAsset: "native", toNetwork: "bitcoin", toAsset: "native", amount: "0.02"), accounts: accounts, idempotencyKey: key, now: Fx.now)574        expectPost(t, "/xswap/proposals", body: ["fromNetwork": "ethereum", "fromAsset": "native", "toNetwork": "bitcoin", "toAsset": "native", "amount": "0.02", "slippageBps": 100], idempotencyKey: key)575    }576}577578// MARK: - the quote stream579580@Suite struct SwapStreamTests {581    @Test func theParserHandlesAnyChunkingCommentsRetryAndCRLF() throws {582        let wire = "event: start\nretry: 3000\ndata: {\"a\":1}\n\n: keep-alive\n\nevent: route\r\ndata: {\"b\":\r\ndata: 2}\r\n\r\ndata: bare\n\nevent: empty\n\nevent: last\ndata:no-space\n\n"583        let expected = [SwapSSEvent(name: "start", data: "{\"a\":1}", retry: 3000), SwapSSEvent(name: "route", data: "{\"b\":\n2}"), SwapSSEvent(name: "message", data: "bare"), SwapSSEvent(name: "last", data: "no-space")]584        for size in [1, 2, 3, 7, 64, wire.utf8.count] {585            var p = SwapSSEParser(), out: [SwapSSEvent] = []586            let bytes = Array(wire.utf8)587            for start in stride(from: 0, to: bytes.count, by: size) { out += try p.feed(bytes[start..<min(start + size, bytes.count)]) }588            #expect(out == expected, "chunks of \(size)")589        }590        var p = SwapSSEParser()591        #expect(try p.feed(Array("event: done\ndata: {}".utf8)).isEmpty) // an unterminated block is not an event592    }593594    @Test func theStreamDeliversTypedEventsInOrderAndEndsAfterDone() async throws {595        let (client, _, _) = MockTransport.client()596        let wire = Array(try #require(try TestResources.json("swap-discovery.json")["stream"]?.stringValue).utf8)597        let chunks = stride(from: 0, to: wire.count, by: 1000).map { Data(wire[$0..<min($0 + 1000, wire.count)]) } + [Data("event: route\ndata: {}\n\n".utf8)] // anything after `done` is not read598        let transport = ScriptedStream(chunks: chunks)599        var events: [SwapQuoteEvent] = []600        for try await e in SwapAPI(client).quoteStream(SwapQuoteRequest(from: "base:native", to: "base:0xabc", amount: "0.01", slippageBps: 75), transport: transport) { events.append(e) }601        #expect(events.count == 6)602        guard case .start(let s) = events[0], case .provider(let p0) = events[1], case .route(let r1) = events[2], case .provider(let p1) = events[3], case .route(let r2) = events[4], case .done(let done) = events[5] else { Issue.record("unexpected order \(events.map { String(describing: $0).prefix(12) })"); return }603        #expect(s.executors == ["kyberswap"] && s.amountIn == "10000000000000000" && s.slippageBps == 50)604        #expect(p0.code == "not_configured" && p1.status == "error" && p1.code == "timeout")605        #expect(r1.statedExecutor == "kyberswap" && r1.quoteReference != nil && r2.statedExecutor == nil)606        #expect(done.routes.count == 2 && done.routes[0] == r1)607608        let req = try #require(transport.recorder.request), url = try #require(req.url)609        let c = try #require(URLComponents(url: url, resolvingAgainstBaseURL: false))610        #expect(req.httpMethod == "GET" && c.path == "/api/v1/swap/quote/stream" && c.host == "wallet.example.test")611        #expect(Dictionary(uniqueKeysWithValues: (c.queryItems ?? []).map { ($0.name, $0.value ?? "") }) == ["from": "base:native", "to": "base:0xabc", "amount": "0.01", "slippageBps": "75"])612        #expect(req.value(forHTTPHeaderField: "Cookie") == "__Host-spw=test-session-token" && req.value(forHTTPHeaderField: "Accept") == "text/event-stream")613        #expect(req.value(forHTTPHeaderField: "X-SPW-CSRF") == nil && req.httpShouldHandleCookies == false)614    }615616    @Test func aFailedSearchARefusalAndAnUnreadableEvent() async throws {617        let (client, _, _) = MockTransport.client()618        let api = SwapAPI(client), r = SwapQuoteRequest(from: "a:native", to: "b:native", amount: "1")619        var events: [SwapQuoteEvent] = []620        let failed = Data(try #require(try TestResources.json("swap-discovery.json")["streamFailed"]?.stringValue).utf8)621        for try await e in api.quoteStream(r, transport: ScriptedStream(chunks: [failed])) { events.append(e) }622        #expect(events.count == 2 && events.last == .failed(code: "internal", message: "the search could not be completed"))623624        // 429 before the stream opens: the server's own error, as for a JSON call625        do { for try await _ in api.quoteStream(r, transport: ScriptedStream(status: 429, chunks: [Data(#"{"error":"too_many_streams","message":"too many quote searches are running at once; close one or wait a moment"}"#.utf8)])) {}; Issue.record("expected an error") }626        catch let e as APIError { #expect(e.status == 429 && e.code == "too_many_streams") }627628        // a route that cannot be decoded ends the stream with an error: it is never skipped silently629        do { for try await _ in api.quoteStream(r, transport: ScriptedStream(chunks: [Data("event: route\ndata: {\"id\":1}\n\n".utf8)])) {}; Issue.record("expected an error") }630        catch let e as APIError { #expect(e.code == "decoding") }631632        // an event added by a newer server is delivered untouched633        events = []634        for try await e in api.quoteStream(r, transport: ScriptedStream(chunks: [Data("event: hint\ndata: {\"k\":true}\n\n".utf8)])) { events.append(e) }635        #expect(events == [.unknown(name: "hint", data: ["k": true])])636    }637}638639// MARK: - verification before the passkey640641@Suite struct SwapApprovalTests {642    private func swapRequest(amount: String = "0.01", toAsset: String = Fx.usdcBase, quote: QuoteRef? = nil) -> SwapRequest {643        SwapRequest(network: "base", fromAsset: "native", toAsset: toAsset, amount: amount, quote: quote)644    }645    private func kyberQuote(minAmountOut: String = "24875000") -> QuoteRef {646        QuoteRef(id: "kyberswap:6c1f", provider: "kyberswap", fingerprint: String(repeating: "a", count: 32), amountOut: "25000000", minAmountOut: minAmountOut, quotedAt: 1795000000123)647    }648    private func prepareSwap(_ json: String, _ r: SwapRequest? = nil, rule: MinimumOutputRule = .notBelowQuote, accounts: Accounts? = nil, status: Int = 200, now: Date = Fx.now) async throws -> PreparedOperation {649        let (client, t, _) = MockTransport.client()650        t.enqueue(status: status, json: json)651        return try await SwapAPI(client).prepare(r ?? swapRequest(), accounts: try accounts ?? Fx.accounts(), minimumOutput: rule, idempotencyKey: "idem-0123456789abcdef", now: now)652    }653654    @Test func aVerifiedSwapIsApprovedOnTheTransfersRouteWithItsOwnChallenge() async throws {655        let (client, t, _) = MockTransport.client()656        t.enqueue(json: try Fx.answer("swap-kyber-review"))657        let prepared = try await SwapAPI(client).prepare(swapRequest(quote: kyberQuote()), accounts: try Fx.accounts(), idempotencyKey: "idem-0123456789abcdef", now: Fx.now)658        let op = try #require(prepared.approvable)659        #expect(!prepared.replayed && op.intent.kind == .swap && op.intent.swap?.minOut == "24875000" && op.intent.to == op.intent.from)660        #expect(op.approval.digest.hex == prepared.proposal.intentHash)661662        let auth = StubAuthenticator()663        t.enqueue(json: Fx.text(Fx.set(try Fx.view("swap-kyber-review"), ["state"], "broadcast")))664        let after = try await SwapAPI(client).approve(op, with: auth, now: Fx.now)665        #expect(try after.state == .broadcast && after.swapCompletion() == .inProgress) // broadcast is not done666        let r = try #require(t.last)667        #expect(r.method == "POST" && r.path == "/api/v1/transfers/proposals/\(prepared.proposal.id)/approve" && r.body?["assertion"]?["type"]?.stringValue == "public-key")668        #expect(auth.challenges == [op.approval.digest.base64URL])669        // past the window nothing is asked of the passkey670        await #expect(throws: ApprovalError.expired) { _ = try await SwapAPI(client).approve(op, with: auth, now: Date(timeIntervalSince1970: 1_795_000_076)) }671        #expect(auth.challenges.count == 1)672    }673674    /** Production today (branch v11): `{ proposal, options }` without the intent. Nothing is approvable. */675    @Test func withoutTheIntentNothingIsApprovable() async throws {676        let unsupported = ApprovalError.unsupported("the server did not return the object to approve")677        await #expect(throws: unsupported) { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", withIntent: false)) }678        await #expect(throws: unsupported) { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", withIntent: false, extra: ["intent": nil])) }679        let (client, t, _) = MockTransport.client()680        t.enqueue(json: try Fx.answer("bridge-review", withIntent: false))681        await #expect(throws: unsupported) { _ = try await BridgeAPI(client).prepare(BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "50"), accounts: try Fx.accounts(), idempotencyKey: "idem-0123456789abcdef", now: Fx.now) }682        // the proposal the server created is withdrawn at once: nothing the owner will not approve stays pending683        #expect(t.last?.method == "POST" && t.last?.path.hasPrefix("/api/v1/transfers/proposals/") == true && t.last?.path.hasSuffix("/reject") == true)684        t.enqueue(json: try Fx.answer("xswap-review", withIntent: false, extra: ["replayed": true]))685        await #expect(throws: unsupported) { _ = try await XSwapAPI(client).prepare(XSwapRequest(fromNetwork: "ethereum", fromAsset: "native", toNetwork: "bitcoin", toAsset: "native", amount: "0.02"), accounts: try Fx.accounts(), idempotencyKey: "idem-0123456789abcdef", now: Fx.now) }686    }687688    @Test func theChallengeMustBeTheHashOfTheIntentForThisRelyingParty() async throws {689        let intent = try Fx.intent("swap-kyber-review"), digest = try Intent(served: intent).approvalDigest()690        var other = digest; other[31] ^= 1691        func answer(_ options: JSONValue) throws -> String { Fx.text(["proposal": try Fx.view("swap-kyber-review"), "intent": intent, "options": options]) }692        await #expect(throws: ApprovalError.challengeMismatch) { _ = try await prepareSwap(try answer(Fx.options(other))) }693        await #expect(throws: ApprovalError.wrongRelyingParty("evil.example")) { _ = try await prepareSwap(try answer(Fx.options(digest, rp: "evil.example"))) }694        await #expect(throws: ApprovalError.userVerificationNotRequired) { _ = try await prepareSwap(try answer(Fx.set(Fx.options(digest), ["userVerification"], "preferred"))) }695        // an intent with a field this version does not know is refused, not hashed "as is"696        await #expect(throws: ApprovalError.self) { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", intent: Fx.set(intent, ["swap", "feeReceiver"], "0x01"), view: Fx.view("swap-kyber-review"))) }697        #expect(try await prepareSwap(try answer(Fx.options(digest))).approvable != nil)698    }699700    @Test func aSwapThatIsNotTheOneRequestedIsRefused() async throws {701        let intent = try Fx.intent("swap-kyber-review"), view = try Fx.view("swap-kyber-review")702        // the request differs from what the server prepared703        await expectInconsistent("amount") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(amount: "0.011")) }704        await expectInconsistent("destination asset") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(toAsset: "0x4200000000000000000000000000000000000006")) }705        await expectInconsistent("network") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), SwapRequest(network: "arbitrum", fromAsset: "native", toAsset: Fx.usdcBase, amount: "0.01")) }706        await expectInconsistent("asset") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), SwapRequest(network: "base", fromAsset: Fx.usdcBase, toAsset: "native", amount: "0.01")) }707        await expectInconsistent("provider") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(quote: QuoteRef(id: "x", provider: "jupiter", fingerprint: String(repeating: "a", count: 32), amountOut: "1", minAmountOut: "1", quotedAt: 1))) }708        await expectInconsistent("a swap was requested") { _ = try await prepareSwap(try Fx.answer("bridge-review")) }709        await expectInconsistent("not the wallet's address") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), accounts: try Fx.accounts(["base": "0x1111111111111111111111111111111111111111"])) }710        await expectInconsistent("no known address") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), accounts: try JSONValue.object(["keyId": "k", "signerReachable": true, "accounts": []]).decode()) }711712        // the intent differs from the proposal displayed (the proposal still looks like the request)713        func tampered(_ path: [String], _ v: JSONValue?, view v2: JSONValue? = nil) throws -> String { try Fx.answer("swap-kyber-review", intent: Fx.set(intent, path, v), view: v2) }714        await expectInconsistent("amount") { _ = try await prepareSwap(try tampered(["amount"], "20000000000000000")) }715        await expectInconsistent("network") { _ = try await prepareSwap(try tampered(["network"], "arbitrum")) }716        await expectInconsistent("asset") { _ = try await prepareSwap(try tampered(["asset"], .string(Fx.usdcBase))) }717        await expectInconsistent("destination") { _ = try await prepareSwap(try tampered(["to"], "0x2222222222222222222222222222222222222222")) }718        await expectInconsistent("proposal id") { _ = try await prepareSwap(try tampered(["proposalId"], "5b2d3c4e-1a2b-4c3d-8e4f-0000000000ff")) }719        await expectInconsistent("destination asset") { _ = try await prepareSwap(try tampered(["swap", "toAsset"], "0x4200000000000000000000000000000000000006")) }720        await expectInconsistent("not the intent's") { _ = try await prepareSwap(try tampered(["swap", "minOut"], "1")) } // the review sheet would show 24.875721        await expectInconsistent("not the intent's") { _ = try await prepareSwap(try tampered(["swap", "provider"], "jupiter")) }722        await expectInconsistent("memo") { _ = try await prepareSwap(try tampered(["memo"], "x")) }723        // a swap whose output goes elsewhere: `to` ≠ `from`, proposal lying along724        let elsewhere = "0x2222222222222222222222222222222222222222"725        let i2 = Fx.set(intent, ["to"], .string(elsewhere))726        await expectInconsistent("deliver to the wallet itself") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", intent: i2, view: Fx.rehashed(Fx.set(view, ["to"], .string(elsewhere)), try Intent(served: i2).approvalDigest()))) }727        // a bridge intent under a swap proposal728        await expectInconsistent("the intent is a") { _ = try await prepareSwap(try tampered(["swap"], nil)) }729        // the proposal's fingerprint must be the intent's730        await expectInconsistent("fingerprint") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", view: Fx.set(view, ["intentHash"], .string(String(repeating: "0", count: 64))))) }731        // a challenge for a proposal that is not waiting for one732        await expectInconsistent("challenge was issued") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", view: Fx.set(view, ["state"], "approved"))) }733        await #expect(throws: ApprovalError.expired) { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), now: Date(timeIntervalSince1970: 1_795_000_075)) }734    }735736    @Test func theMinimumOutputAgainstWhatWasDisplayed() async throws {737        // the firm minimum (24.875) is below the minimum of the quote displayed (24.9): refused by default…738        await expectInconsistent("minimum output below the minimum displayed") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(quote: kyberQuote(minAmountOut: "24900000"))) }739        // …accepted when the screen commits to showing the intent's own minimum, or when it equals / exceeds the floor740        #expect(try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(quote: kyberQuote(minAmountOut: "24900000")), rule: .asPrepared).approvable?.intent.swap?.minOut == "24875000")741        #expect(try await prepareSwap(try Fx.answer("swap-kyber-review"), swapRequest(quote: kyberQuote(minAmountOut: "24875000"))).approvable != nil)742        #expect(try await prepareSwap(try Fx.answer("swap-kyber-review"), rule: .atLeast("24875000")).approvable != nil)743        await expectInconsistent("minimum output below") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review"), rule: .atLeast("24875001")) }744        // a zero minimum is never approvable, whatever the rule745        let i0 = Fx.set(try Fx.intent("swap-kyber-review"), ["swap", "minOut"], "0")746        let v0 = Fx.rehashed(Fx.set(try Fx.view("swap-kyber-review"), ["swap", "minOut"], "0"), try Intent(served: i0).approvalDigest())747        await expectInconsistent("minimum output is zero") { _ = try await prepareSwap(try Fx.answer("swap-kyber-review", intent: i0, view: v0), rule: .asPrepared) }748    }749750    @Test func quoteMovedIsATypedRefusalAndOtherErrorsStayTheServers() async throws {751        let f = try TestResources.json("swap-quote-moved.json")752        do { _ = try await prepareSwap(Fx.text(try #require(f["body"])), swapRequest(quote: kyberQuote()), status: 409); Issue.record("expected QuoteMoved") }753        catch let m as QuoteMoved { #expect(m.fresh.amountOutDisplay == "24.8" && m.quoted.minAmountOutDisplay == "24.875" && m.deviationBps == -80) }754        do { _ = try await prepareSwap(#"{"error":"pending_tx","message":"a previous transfer or swap on this network is not confirmed yet"}"#, status: 409); Issue.record("expected APIError") }755        catch let e as APIError { #expect(e.code == "pending_tx" && e.status == 409) }756        do { _ = try await prepareSwap(#"{"error":"idempotency_mismatch","message":"this Idempotency-Key was already used for a different request; use a new key"}"#, status: 409); Issue.record("expected APIError") }757        catch let e as APIError { #expect(e.code == "idempotency_mismatch") }758    }759760    @Test func anIdempotentReplay() async throws {761        // still approvable: the same proposal, its challenge again, the intent with it762        let again = try await prepareSwap(try Fx.answer("swap-kyber-review", extra: ["replayed": true]))763        #expect(again.replayed && again.approvable != nil)764        // already on its way: no challenge, no intent — the proposal is returned to be followed, nothing to approve765        let gone = try await prepareSwap(Fx.text(["proposal": Fx.set(try Fx.view("swap-kyber-review"), ["state"], "broadcast"), "intent": nil, "options": nil, "replayed": true]))766        #expect(gone.replayed && gone.approvable == nil && gone.proposal.state == .broadcast)767        // a replay is still checked against the request768        await expectInconsistent("amount") { _ = try await prepareSwap(Fx.text(["proposal": try Fx.view("swap-kyber-review"), "intent": nil, "options": nil, "replayed": true]), swapRequest(amount: "5")) }769        // a first answer without a challenge is not a preparation770        await #expect(throws: ApprovalError.self) { _ = try await prepareSwap(Fx.text(["proposal": try Fx.view("swap-kyber-review")])) }771    }772773    @Test func jupiterOnSolana() async throws {774        let (client, t, _) = MockTransport.client()775        t.enqueue(json: try Fx.answer("swap-jupiter-review"))776        let op = try #require(try await SwapAPI(client).prepare(SwapRequest(network: "solana", fromAsset: "native", toAsset: Fx.usdcSol, amount: "0.5", slippageBps: 100), accounts: try Fx.accounts(), idempotencyKey: "idem-0123456789abcdef", now: Fx.now).approvable)777        #expect(op.intent.swap?.provider == "jupiter" && op.intent.sol?.createAta == true && op.intent.from == Fx.sol)778        // a Solana mint is case-sensitive: the lower-cased mint is another asset779        t.enqueue(json: try Fx.answer("swap-jupiter-review"))780        await expectInconsistent("destination asset") { _ = try await SwapAPI(client).prepare(SwapRequest(network: "solana", fromAsset: "native", toAsset: Fx.usdcSol.lowercased(), amount: "0.5"), accounts: try Fx.accounts(), idempotencyKey: "idem-0123456789abcdef", now: Fx.now) }781    }782783    @Test func requestedAmountsInBaseUnits() throws {784        #expect(try SwapVerification.requestedUnits("0.01", decimals: 18, kind: .swap) == "10000000000000000")785        // THORChain credits eight decimals: nothing finer is sent (xswap.ts)786        #expect(try SwapVerification.requestedUnits("0.020000001234", decimals: 18, kind: .xswap) == "20000000000000000")787        #expect(try SwapVerification.requestedUnits("0.02000000999", decimals: 18, kind: .xswap) == "20000000000000000")788        #expect(try SwapVerification.requestedUnits("0.02000001", decimals: 18, kind: .xswap) == "20000010000000000")789        #expect(try SwapVerification.requestedUnits("0.0000000001", decimals: 18, kind: .xswap) == "0")790        #expect(try SwapVerification.requestedUnits("0.0006", decimals: 8, kind: .xswap) == "60000")791        #expect(try SwapVerification.requestedUnits("0.020000001234", decimals: 18, kind: .swap) == "20000001234000000")792        #expect(throws: ApprovalError.self) { try SwapVerification.requestedUnits("1.0000001", decimals: 6, kind: .bridge) }793    }794}795796@Suite struct BridgeApprovalTests {797    private let key = "idem-0123456789abcdef"798    private func prepare(_ json: String, _ r: BridgeRequest, accounts: Accounts? = nil, sourceUSDC: String? = nil, maxFee: String? = nil) async throws -> PreparedOperation {799        let (client, t, _) = MockTransport.client()800        t.enqueue(json: json)801        return try await BridgeAPI(client).prepare(r, accounts: try accounts ?? Fx.accounts(), sourceUSDC: sourceUSDC, maxFee: maxFee, idempotencyKey: key, now: Fx.now)802    }803    private let standard = BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "50")804    private func fastQuote() throws -> QuoteRef {805        let raw = try JSONDecoder().decode([JSONValue].self, from: try TestResources.data("swap-cctp-quote-ref.json", in: "Vectors"))806        return try #require(raw.first { $0["name"]?.stringValue == "cctp-fast-base-ethereum" }?["ref"]).decode()807    }808809    @Test func evmToEvm() async throws {810        let op = try #require(try await prepare(try Fx.answer("bridge-review"), standard, sourceUSDC: Fx.usdcBase.lowercased()).approvable)811        #expect(op.intent.kind == .bridge && op.intent.bridge?.toNetwork == "arbitrum" && op.intent.bridge?.maxFee == "0" && op.intent.bridge?.recipient == nil && op.intent.to == op.intent.from)812813        let fast = BridgeRequest(fromNetwork: "base", toNetwork: "ethereum", amount: "50", speed: .fast, quote: try fastQuote())814        #expect(try await prepare(try Fx.answer("bridge-fast-review"), fast).approvable?.intent.bridge?.maxFee == "6500") // exactly the fee of the option displayed815        #expect(try await prepare(try Fx.answer("bridge-fast-review"), fast, maxFee: "6500").approvable != nil)816        await expectInconsistent("CCTP fee above the fee displayed") { _ = try await prepare(try Fx.answer("bridge-fast-review"), fast, maxFee: "6499") }817        // the fee ceiling grew between the quote and the intent, the proposal lying along818        let i = Fx.set(try Fx.intent("bridge-fast-review"), ["bridge", "maxFee"], "9000")819        let v = Fx.rehashed(Fx.set(try Fx.view("bridge-fast-review"), ["bridge", "cctpMaxFee"], "9000"), try Intent(served: i).approvalDigest())820        await expectInconsistent("CCTP fee above the fee displayed") { _ = try await prepare(try Fx.answer("bridge-fast-review", intent: i, view: v), fast) }821        // the review sheet would show another fee than the intent carries822        await expectInconsistent("not the intent's") { _ = try await prepare(try Fx.answer("bridge-fast-review", intent: i), fast, maxFee: "9000") }823    }824825    @Test func aBridgeThatIsNotTheOneRequestedIsRefused() async throws {826        let intent = try Fx.intent("bridge-review")827        func tampered(_ path: [String], _ v: JSONValue?) throws -> String { try Fx.answer("bridge-review", intent: Fx.set(intent, path, v)) }828        await expectInconsistent("destination network") { _ = try await prepare(try Fx.answer("bridge-review"), BridgeRequest(fromNetwork: "base", toNetwork: "ethereum", amount: "50")) }829        await expectInconsistent("amount") { _ = try await prepare(try Fx.answer("bridge-review"), BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "49.99")) }830        await expectInconsistent("network") { _ = try await prepare(try Fx.answer("bridge-review"), BridgeRequest(fromNetwork: "ethereum", toNetwork: "arbitrum", amount: "50")) }831        await expectInconsistent("speed") { _ = try await prepare(try Fx.answer("bridge-review"), BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "50", speed: .fast)) }832        await expectInconsistent("asset") { _ = try await prepare(try Fx.answer("bridge-review"), standard, sourceUSDC: Fx.usdcEth) }833        await expectInconsistent("destination network") { _ = try await prepare(try tampered(["bridge", "toNetwork"], "ethereum"), standard) }834        await expectInconsistent("finality threshold") { _ = try await prepare(try tampered(["bridge", "minFinalityThreshold"], 1000), standard) }835        await expectInconsistent("recipient is not the wallet's address") { _ = try await prepare(try tampered(["bridge", "recipient"], "0x2222222222222222222222222222222222222222"), standard) }836        await expectInconsistent("the intent is a") { _ = try await prepare(try tampered(["bridge"], nil), standard) }837        await expectInconsistent("no known address on arbitrum") { _ = try await prepare(try Fx.answer("bridge-review"), standard, accounts: try JSONValue.object(["keyId": "k", "signerReachable": true, "accounts": [["network": "base", "name": "Base", "family": "evm", "address": .string(Fx.evm), "explorer": ""]]]).decode()) }838        // a token that merely calls itself USDC, with other decimals839        await expectInconsistent("asset") { _ = try await prepare(try Fx.answer("bridge-review", view: Fx.set(try Fx.view("bridge-review"), ["decimals"], 18)), standard) }840        // the quote reference must be a CCTP one that fits the amount841        await expectInconsistent("quote reference") { _ = try await prepare(try Fx.answer("bridge-review"), BridgeRequest(fromNetwork: "base", toNetwork: "arbitrum", amount: "50", quote: QuoteRef(id: "x", provider: "kyberswap", fingerprint: String(repeating: "a", count: 32), amountOut: "1", minAmountOut: "1", quotedAt: 1))) }842    }843844    @Test func solanaEndsNameTheWalletsOwnAddressOnTheOtherSide() async throws {845        let toSol = BridgeRequest(fromNetwork: "ethereum", toNetwork: "solana", amount: "50")846        #expect(try await prepare(try Fx.answer("bridge-to-solana-review"), toSol).approvable?.intent.bridge?.recipient == Fx.sol)847        await expectInconsistent("recipient is not the wallet's address") { _ = try await prepare(try Fx.answer("bridge-to-solana-review"), toSol, accounts: try Fx.accounts(["solana": "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"])) }848        // without the named recipient a Solana destination would be the EVM address849        await expectInconsistent("recipient is not the wallet's address") { _ = try await prepare(try Fx.answer("bridge-to-solana-review", intent: Fx.set(try Fx.intent("bridge-to-solana-review"), ["bridge", "recipient"], nil)), toSol) }850851        let fromSol = BridgeRequest(fromNetwork: "solana", toNetwork: "base", amount: "50", speed: .fast)852        let op = try #require(try await prepare(try Fx.answer("bridge-sol-source-review"), fromSol, sourceUSDC: Fx.usdcSol, maxFee: "6500").approvable)853        #expect(try op.intent.bridge?.recipient == Fx.evm && op.intent.sol != nil && op.intent.from == Fx.sol && op.proposal.bridgeSection()?.sol?.deposit == "3883680")854        await expectInconsistent("recipient is not the wallet's address") { _ = try await prepare(try Fx.answer("bridge-sol-source-review"), fromSol, accounts: try Fx.accounts(["base": "0x2222222222222222222222222222222222222222"])) }855    }856857    // MARK: follow-up approvals (retry-mint, reclaim, token account)858859    private let mintId = "5b2d3c4e-1a2b-4c3d-8e4f-000000000004", solId = "5b2d3c4e-1a2b-4c3d-8e4f-000000000007"860    private let hash = "0x" + String(repeating: "44", count: 32), eventAccount = "GokivDYuQXPZCWRkwMhdH2h91KpDQXBEmpgBgs55bnpH"861    private let budget: JSONValue = ["recentBlockhash": "EkSnNWid2cvwEVnVx9aBqawnmiCNiDgp3gUdkDPTKN1N", "lastValidBlockHeight": 312345678, "computeUnitLimit": 60000, "computeUnitPrice": "10000"]862863    @Test func mintRetry() async throws {864        let (client, t, _) = MockTransport.client()865        let api = BridgeAPI(client), view = try Fx.view("bridge-mint-failed-needs-passkey")866        let approval: JSONValue = ["proposalId": .string(mintId), "messageHash": .string(hash), "gas": ["nonce": 9, "gasLimit": "240000", "maxFeePerGas": "200000000", "maxPriorityFeePerGas": "1000000"]]867        let digest = try BridgeMintRetry(served: approval).approvalDigest()868869        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(digest), "approval": approval]))870        let a = try await api.retryMintOptions(mintId)871        #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/bridge/proposals/\(mintId)/retry-mint/options" && t.last?.body == [:] && t.last?.headers["Idempotency-Key"] == nil)872        guard case .evm(let gas) = a.object.parameters else { Issue.record("expected EVM parameters"); return }873        #expect(gas.maxNetworkFee == "48000000000000" && a.object.messageHash == hash)874875        let auth = StubAuthenticator()876        t.enqueue(json: Fx.text(try Fx.view("bridge-minting")))877        let after = try await api.retryMint(a, with: auth)878        #expect(try after.bridgeSection()?.stage == .minting && after.swapCompletion() == .inProgress)879        #expect(t.last?.path == "/api/v1/bridge/proposals/\(mintId)/retry-mint" && t.last?.body?["assertion"]?["id"] != nil && auth.challenges == [digest.base64URL])880881        // production today: no `approval` → nothing is signed882        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(digest)]))883        await #expect(throws: ApprovalError.unsupported("the server did not return the object to approve")) { _ = try await api.retryMintOptions(mintId) }884        // the object is for another transfer / the challenge is not its hash / the transfer needs no new signature885        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(digest), "approval": Fx.set(approval, ["proposalId"], "5b2d3c4e-1a2b-4c3d-8e4f-0000000000aa")]))886        await expectInconsistent("another transfer") { _ = try await api.retryMintOptions(mintId) }887        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(digest), "approval": Fx.set(approval, ["gas", "maxFeePerGas"], "900000000000")]))888        await #expect(throws: ApprovalError.challengeMismatch) { _ = try await api.retryMintOptions(mintId) }889        t.enqueue(json: Fx.text(["proposal": try Fx.view("bridge-minting"), "options": Fx.options(digest), "approval": approval]))890        await expectInconsistent("does not need a new mint signature") { _ = try await api.retryMintOptions(mintId) }891        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(digest), "approval": approval]))892        await expectInconsistent("proposal id") { _ = try await api.retryMintOptions("5b2d3c4e-1a2b-4c3d-8e4f-0000000000aa") }893        // a Solana destination carries a budget instead of gas894        let solApproval: JSONValue = ["proposalId": .string(mintId), "messageHash": .string(hash), "sol": budget]895        t.enqueue(json: Fx.text(["proposal": view, "options": Fx.options(try BridgeMintRetry(served: solApproval).approvalDigest()), "approval": solApproval]))896        guard case .solana(let b) = try await api.retryMintOptions(mintId).object.parameters else { Issue.record("expected a Solana budget"); return }897        #expect(b.singleSignerNetworkFee?.description == "5600")898    }899900    @Test func eventAccountReclaim() async throws {901        let (client, t, _) = MockTransport.client()902        let api = BridgeAPI(client), view = try Fx.view("bridge-sol-source-reclaim-available")903        let approval: JSONValue = ["proposalId": .string(solId), "eventAccount": .string(eventAccount), "messageHash": .string(hash), "sol": budget]904        let digest = try BridgeDepositReclaim(served: approval).approvalDigest()905        func answer(_ approval: JSONValue?, fee: String = "5600", deposit: String = "3883680", view v: JSONValue? = nil) -> String {906            var o: [String: JSONValue] = ["proposal": v ?? view, "options": Fx.options(digest), "deposit": .string(deposit), "networkFee": .string(fee)]907            if let approval { o["approval"] = approval }908            return Fx.text(.object(o))909        }910        t.enqueue(json: answer(approval))911        let a = try await api.reclaimOptions(solId)912        #expect(t.last?.path == "/api/v1/bridge/proposals/\(solId)/reclaim/options" && a.deposit == "3883680" && a.networkFee == "5600" && a.object.eventAccount == eventAccount)913914        let auth = StubAuthenticator()915        t.enqueue(json: Fx.text(try Fx.view("bridge-sol-source-reclaim-sent")))916        let after = try await api.reclaim(a, with: auth)917        #expect(try after.bridgeSection()?.sol?.reclaimState == .sent && after.bridgeSection()?.sol?.isReclaimed == false) // sent is not reclaimed918        #expect(t.last?.path == "/api/v1/bridge/proposals/\(solId)/reclaim" && auth.challenges == [digest.base64URL])919920        t.enqueue(json: answer(nil))921        await #expect(throws: ApprovalError.unsupported("the server did not return the object to approve")) { _ = try await api.reclaimOptions(solId) }922        t.enqueue(json: answer(Fx.set(approval, ["eventAccount"], "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin")))923        await expectInconsistent("event account") { _ = try await api.reclaimOptions(solId) }924        t.enqueue(json: answer(approval, fee: "5000")) // the fee displayed is not the fee of the budget signed925        await expectInconsistent("network fee") { _ = try await api.reclaimOptions(solId) }926        t.enqueue(json: answer(approval, deposit: "5000"))927        await expectInconsistent("deposit") { _ = try await api.reclaimOptions(solId) }928        t.enqueue(json: answer(Fx.set(approval, ["sol", "computeUnitPrice"], "10001"), fee: "5601"))929        await #expect(throws: ApprovalError.challengeMismatch) { _ = try await api.reclaimOptions(solId) }930        t.enqueue(json: answer(approval, view: try Fx.view("bridge-sol-destination-ready")))931        await expectInconsistent("proposal id") { _ = try await api.reclaimOptions(solId) }932        t.enqueue(json: answer(approval, view: Fx.set(try Fx.view("bridge-done"), ["id"], .string(solId)))) // an EVM burn has no deposit933        await expectInconsistent("no deposit to reclaim") { _ = try await api.reclaimOptions(solId) }934        // before the five-day window the server refuses; that is its error, untouched935        t.enqueue(status: 409, json: #"{"error":"reclaim_not_yet","message":"the program releases this deposit five days after the burn: on 2026-11-23 15:00 UTC"}"#)936        do { _ = try await api.reclaimOptions(solId); Issue.record("expected APIError") } catch let e as APIError { #expect(e.code == "reclaim_not_yet") }937    }938939    @Test func solanaTokenAccountCreation() async throws {940        let (client, t, _) = MockTransport.client()941        let api = BridgeAPI(client), ata = "C4PRXFV6Gf5mytVZb6RoeLsG8CjcFWzR2EJ3dvwPTUJH", requestId = "7a1c1f0e-8f5f-4b1e-9c56-000000000631"942        let request: JSONValue = ["v": 1, "requestId": .string(requestId), "keyId": "spw-0123456789abcdef", "network": "solana", "chainRef": "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdpKuc147dw2N9d",943                                  "owner": .string(Fx.sol), "mint": .string(Fx.usdcSol), "tokenAccount": .string(ata), "maxFee": "2044480", "createdAt": 1795000000, "expiresAt": 1795000050, "policyVersion": 7,944                                  "sol": ["recentBlockhash": "EkSnNWid2cvwEVnVx9aBqawnmiCNiDgp3gUdkDPTKN1N", "lastValidBlockHeight": 312345678, "computeUnitLimit": 40000, "computeUnitPrice": "5000"]]945        func answer(_ request: JSONValue?, _ patch: [String: JSONValue] = [:]) throws -> String {946            var o: [String: JSONValue] = ["requestId": .string(requestId), "owner": .string(Fx.sol), "tokenAccount": .string(ata), "rent": "2039280", "rentDisplay": "0.00203928", "networkFee": "5200", "networkFeeDisplay": "0.0000052",947                                          "symbol": "SOL", "expiresAt": 1795000050]948            if let request { o["request"] = request; o["options"] = Fx.options(try SolanaTokenAccountRequest(served: request).approvalDigest()) }949            else { o["options"] = Fx.options(Data(repeating: 7, count: 32)) }950            for (k, v) in patch { o[k] = v }951            return Fx.text(.object(o))952        }953        func options(_ json: String, accounts: Accounts? = nil, mint: String = Fx.usdcSol, now: Date = Fx.now) async throws -> TokenAccountApproval {954            t.enqueue(json: json)955            return try await api.solanaTokenAccountOptions(accounts: try accounts ?? Fx.accounts(), usdcMint: mint, now: now)956        }957        let a = try await options(try answer(request))958        #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/bridge/solana/token-account/options" && t.last?.body == [:])959        #expect(a.request.tokenAccount == ata && a.request.maxFee == "2044480" && a.rent == "2039280" && a.networkFee == "5200")960961        let auth = StubAuthenticator()962        t.enqueue(json: Fx.text(try #require(try TestResources.json("swap-bridge-quote.json")["tokenAccountCreated"])))963        let created = try await api.createSolanaTokenAccount(a, with: auth, now: Fx.now)964        #expect(created.sent && created.tokenAccount == ata)965        #expect(t.last?.path == "/api/v1/bridge/solana/token-account" && t.last?.body?["requestId"]?.stringValue == requestId && t.last?.body?["assertion"] != nil && auth.challenges == [a.approval.digest.base64URL])966        await #expect(throws: ApprovalError.expired) { _ = try await api.createSolanaTokenAccount(a, with: auth, now: Date(timeIntervalSince1970: 1_795_000_051)) }967968        await #expect(throws: ApprovalError.unsupported("the server did not return the object to approve")) { _ = try await options(try answer(nil)) }969        await expectInconsistent("owner") { _ = try await options(try answer(Fx.set(request, ["owner"], "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"))) }970        await expectInconsistent("owner") { _ = try await options(try answer(request), accounts: try Fx.accounts(["solana": "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin"])) }971        await expectInconsistent("mint") { _ = try await options(try answer(Fx.set(request, ["mint"], "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"))) }972        await expectInconsistent("mint") { _ = try await options(try answer(request), mint: "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB") }973        await expectInconsistent("token account") { _ = try await options(try answer(Fx.set(request, ["tokenAccount"], .string(Fx.sol)))) }974        await expectInconsistent("request id") { _ = try await options(try answer(Fx.set(request, ["requestId"], "7a1c1f0e-8f5f-4b1e-9c56-0000000006ff"))) }975        await expectInconsistent("network") { _ = try await options(try answer(Fx.set(request, ["network"], "solana-devnet"))) }976        await expectInconsistent("expiry") { _ = try await options(try answer(Fx.set(request, ["expiresAt"], 1795009999))) }977        await expectInconsistent("network fee") { _ = try await options(try answer(request, ["networkFee": "5000"])) }978        await expectInconsistent("fee ceiling does not cover") { _ = try await options(try answer(Fx.set(request, ["maxFee"], "2044479"))) }979        await #expect(throws: ApprovalError.expired) { _ = try await options(try answer(request), now: Date(timeIntervalSince1970: 1_795_000_050)) }980        await #expect(throws: ApprovalError.challengeMismatch) { _ = try await options(try answer(request, ["options": Fx.options(Data(repeating: 7, count: 32))])) }981    }982}983984@Suite struct XSwapApprovalTests {985    private func prepare(_ json: String, _ r: XSwapRequest, rule: MinimumOutputRule = .notBelowQuote, accounts: Accounts? = nil, now: Date = Fx.now) async throws -> PreparedOperation {986        let (client, t, _) = MockTransport.client()987        t.enqueue(json: json)988        return try await XSwapAPI(client).prepare(r, accounts: try accounts ?? Fx.accounts(), minimumOutput: rule, idempotencyKey: "idem-0123456789abcdef", now: now)989    }990    private func ethToBtc(amount: String = "0.02", quote: QuoteRef? = nil) -> XSwapRequest { XSwapRequest(fromNetwork: "ethereum", fromAsset: "native", toNetwork: "bitcoin", toAsset: "native", amount: amount, quote: quote) }991    private func quote(min: String) -> QuoteRef { QuoteRef(id: "thorchain:1", provider: "thorchain", fingerprint: String(repeating: "b", count: 32), amountOut: "54986", minAmountOut: min, quotedAt: 1795000000123) }992993    @Test func everySourceFamily() async throws {994        let op = try #require(try await prepare(try Fx.answer("xswap-review"), ethToBtc(quote: quote(min: "54436"))).approvable)995        #expect(op.intent.kind == .xswap && op.intent.to == op.intent.xswap?.vault && op.intent.xswap?.memo == "=:b:\(Fx.btc):54436" && op.intent.xswap?.minOut == "54436")996        // the request amount beyond eight decimals is the truncated amount the server sends997        #expect(try await prepare(try Fx.answer("xswap-review"), ethToBtc(amount: "0.020000001234")).approvable != nil)998        // an ERC-20 source (checksum case does not matter), with its exact-amount approval999        let erc20 = XSwapRequest(fromNetwork: "ethereum", fromAsset: Fx.usdcEth.lowercased(), toNetwork: "bitcoin", toAsset: "native", amount: "250")1000        #expect(try await prepare(try Fx.answer("xswap-erc20-review"), erc20).approvable?.intent.xswap?.approveGas == "70000")1001        // a Bitcoin source: the destination of the memo is the wallet's EVM address1002        let btc = XSwapRequest(fromNetwork: "bitcoin", fromAsset: "native", toNetwork: "ethereum", toAsset: "native", amount: "0.0006")1003        let b = try #require(try await prepare(try Fx.answer("xswap-btc-review"), btc).approvable)1004        #expect(b.intent.btc?.inputs.count == 2 && b.intent.xswap?.router == "" && b.intent.xswap?.memo.contains(Fx.evm) == true)1005    }10061007    @Test func aNativeSwapThatIsNotTheOneRequestedIsRefused() async throws {1008        let intent = try Fx.intent("xswap-review"), view = try Fx.view("xswap-review")1009        func tampered(_ path: [String], _ v: JSONValue?, viewPatch: [([String], JSONValue)] = []) throws -> String {1010            let i = Fx.set(intent, path, v)1011            var w = view1012            for (p, x) in viewPatch { w = Fx.set(w, p, x) }1013            return try Fx.answer("xswap-review", intent: i, view: viewPatch.isEmpty ? JSONValue?.none : Fx.rehashed(w, try Intent(served: i).approvalDigest()))1014        }1015        await expectInconsistent("destination network") { _ = try await prepare(try Fx.answer("xswap-review"), XSwapRequest(fromNetwork: "ethereum", fromAsset: "native", toNetwork: "litecoin", toAsset: "native", amount: "0.02")) }1016        await expectInconsistent("destination asset") { _ = try await prepare(try Fx.answer("xswap-erc20-review"), XSwapRequest(fromNetwork: "ethereum", fromAsset: Fx.usdcEth, toNetwork: "bitcoin", toAsset: "0xdAC17F958D2ee523a2206206994597C13D831ec7", amount: "250")) }1017        await expectInconsistent("amount") { _ = try await prepare(try Fx.answer("xswap-review"), ethToBtc(amount: "0.03")) }1018        await expectInconsistent("provider") { _ = try await prepare(try Fx.answer("xswap-review"), ethToBtc(quote: QuoteRef(id: "m", provider: "maya", fingerprint: String(repeating: "b", count: 32), amountOut: "1", minAmountOut: "1", quotedAt: 1))) }1019        await expectInconsistent("minimum output below the minimum displayed") { _ = try await prepare(try Fx.answer("xswap-review"), ethToBtc(quote: quote(min: "54437"))) }1020        #expect(try await prepare(try Fx.answer("xswap-review"), ethToBtc(quote: quote(min: "54437")), rule: .asPrepared).approvable != nil)10211022        // the memo delivers elsewhere, the proposal lying along: caught against the wallet's own Bitcoin address1023        let thief = "bc1qar0srrr7xfkvy5l643lydnw9re59gtzzwf5mdq", memo = "=:b:\(thief):54436"1024        await expectInconsistent("memo does not deliver to the wallet's address") { _ = try await prepare(try tampered(["xswap", "memo"], .string(memo), viewPatch: [(["xswap", "memo"], .string(memo))]), ethToBtc()) }1025        await expectInconsistent("memo does not deliver to the wallet's address") { _ = try await prepare(try Fx.answer("xswap-review"), ethToBtc(), accounts: try Fx.accounts(["bitcoin": thief])) }1026        // a lower limit in the memo than the one approved; an affiliate suffix; the vault not being the payee1027        let low = "=:b:\(Fx.btc):1"1028        await expectInconsistent("memo limit") { _ = try await prepare(try tampered(["xswap", "memo"], .string(low), viewPatch: [(["xswap", "memo"], .string(low))]), ethToBtc()) }1029        let affiliate = "=:b:\(Fx.btc):54436:t:30"1030        await expectInconsistent("not a plain swap memo") { _ = try await prepare(try tampered(["xswap", "memo"], .string(affiliate), viewPatch: [(["xswap", "memo"], .string(affiliate))]), ethToBtc()) }1031        await expectInconsistent("does not pay the vault") { _ = try await prepare(try tampered(["xswap", "vault"], "0x2222222222222222222222222222222222222222"), ethToBtc()) }1032        // the review sheet shows the vault and the minimum: they must be the intent's1033        let otherVault = "0x3333333333333333333333333333333333333333"1034        let i3 = Fx.set(Fx.set(intent, ["to"], .string(otherVault)), ["xswap", "vault"], .string(otherVault))1035        let v3 = Fx.rehashed(Fx.set(view, ["to"], .string(otherVault)), try Intent(served: i3).approvalDigest()) // `xswap.vault` of the sheet still shows the old vault1036        await expectInconsistent("not the intent's") { _ = try await prepare(try Fx.answer("xswap-review", intent: i3, view: v3), ethToBtc()) }1037        await expectInconsistent("minimum is not the intent's") { _ = try await prepare(try tampered(["xswap", "minOut"], "1"), ethToBtc()) }1038        await expectInconsistent("destination network") { _ = try await prepare(try tampered(["xswap", "toNetwork"], "litecoin"), ethToBtc()) }1039        await expectInconsistent("the intent is a") { _ = try await prepare(try tampered(["xswap"], nil), ethToBtc()) }1040        // the vault's validity window is over (the intent's own window is checked first)1041        await #expect(throws: ApprovalError.expired) { _ = try await prepare(try tampered(["xswap", "expiry"], 1795000005), ethToBtc()) }1042    }1043}10441045@Suite struct PlanApprovalTests {1046    private let planId = "9d1e2f30-4a5b-4c6d-8e7f-000000000001"1047    private func fixtures() throws -> (ready: PlanView, prepared: JSONValue, paused: JSONValue) {1048        let d = try TestResources.json("swap-plans.json")1049        return (try #require(d["ready"]).decode(), try #require(d["prepared"]), try #require(d["pausedOnFloor"]))1050    }1051    /** The prepare answer of the fixture with a challenge = the hash of its intent. */1052    private func answer(_ prepared: JSONValue, intent: JSONValue?? = .none, patch: [([String], JSONValue?)] = []) throws -> String {1053        var a = prepared1054        let i: JSONValue? = { if case .some(let v) = intent { return v } else { return prepared["intent"] } }()1055        a = Fx.set(a, ["intent"], i)1056        a = Fx.set(a, ["options"], Fx.options(try Intent(served: try #require(prepared["intent"])).approvalDigest()))1057        if let i, !i.isNull { a = Fx.set(a, ["options"], Fx.options(try Intent(served: i).approvalDigest())) }1058        for (p, v) in patch { a = Fx.set(a, p, v) }1059        return Fx.text(a)1060    }1061    private func prepare(_ json: String, displayed: PlanView, rule: MinimumOutputRule = .asPrepared) async throws -> (PlanLegPreparation, MockTransport) {1062        let (client, t, _) = MockTransport.client()1063        t.enqueue(json: json)1064        return (try await PlanAPI(client).prepareLeg(of: displayed, accounts: try Fx.accounts(), minimumOutput: rule, now: Fx.now), t)1065    }10661067    @Test func aLegIsPreparedVerifiedAndApprovedLikeAnyOtherProposal() async throws {1068        let f = try fixtures()1069        let (p, t) = try await prepare(try answer(f.prepared), displayed: f.ready)1070        #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/plans/\(planId)/prepare" && t.last?.body == [:] && t.last?.headers["Idempotency-Key"] == nil)1071        let op = try #require(p.operation?.approvable)1072        #expect(p.plan.next == .approve && p.plan.currentLeg?.state == .proposed && op.proposal.id == p.plan.currentLeg?.proposalId)1073        #expect(op.intent.kind == .swap && op.intent.amount == "10000000000000000" && op.intent.swap?.toAsset == Fx.usdcBase)1074        // nothing was approved and nothing advanced: the plan still waits for the passkey of THIS leg1075        #expect(t.requests.count == 1 && p.plan.legs[1].state == .pending)10761077        let (client, t2, _) = MockTransport.client(), auth = StubAuthenticator()1078        t2.enqueue(json: Fx.text(Fx.set(try Fx.view("swap-kyber-review"), ["state"], "broadcast")))1079        _ = try await PlanAPI(client).approve(op, with: auth, now: Fx.now)1080        #expect(t2.last?.path == "/api/v1/transfers/proposals/\(op.proposal.id)/approve" && auth.challenges == [op.approval.digest.base64URL])1081    }10821083    @Test func aPausedPlanPreparesNothing() async throws {1084        let f = try fixtures()1085        let (p, _) = try await prepare(Fx.text(f.paused), displayed: f.ready)1086        #expect(p.operation == nil && p.plan.state == .paused && p.plan.pause?.code == "floor")1087        // a challenge without a proposal is refused1088        await expectInconsistent("challenge without a proposal") { _ = try await prepare(Fx.text(Fx.set(f.paused, ["options"], Fx.options(Data(repeating: 1, count: 32)))), displayed: f.ready) }1089    }10901091    @Test func productionWithoutTheIntentAndEveryMismatchWithThePlanDisplayed() async throws {1092        let f = try fixtures()1093        await #expect(throws: ApprovalError.unsupported("the server did not return the object to approve")) { _ = try await prepare(try answer(f.prepared, intent: .some(nil)), displayed: f.ready) }1094        await #expect(throws: ApprovalError.unsupported("the server did not return the object to approve")) { _ = try await prepare(try answer(f.prepared, intent: .some(.null)), displayed: f.ready) }10951096        await expectInconsistent("plan id") { _ = try await prepare(try answer(f.prepared, patch: [(["plan", "id"], "9d1e2f30-4a5b-4c6d-8e7f-0000000000ff")]), displayed: f.ready) }1097        await expectInconsistent("the plan moved") { _ = try await prepare(try answer(f.prepared, patch: [(["plan", "current"], 1)]), displayed: f.ready) }1098        await expectInconsistent("the plan moved") { _ = try await prepare(try answer(f.prepared, patch: [(["plan", "replans"], 1)]), displayed: f.ready) }1099        await expectInconsistent("not the plan's current step") { _ = try await prepare(try answer(f.prepared, patch: [(["proposal", "id"], "5b2d3c4e-1a2b-4c3d-8e4f-0000000000ff")]), displayed: f.ready) }11001101        // the leg displayed was another one (another destination asset; another provider)1102        let d = try TestResources.json("swap-plans.json"), ready = try #require(d["ready"])1103        func displayed(_ patch: (JSONValue) -> JSONValue) throws -> PlanView {1104            guard case .array(var legs)? = ready["legs"] else { throw ApprovalError.unsupported("fixture") }1105            legs[0] = patch(legs[0])1106            return try Fx.set(ready, ["legs"], .array(legs)).decode()1107        }1108        await expectInconsistent("not the one displayed") { _ = try await prepare(try answer(f.prepared), displayed: try displayed { Fx.set($0, ["to", "key"], "base:native-other") }) }1109        await expectInconsistent("not the one displayed") { _ = try await prepare(try answer(f.prepared), displayed: try displayed { Fx.set($0, ["via"], "jupiter") }) }1110        // the plan held less than the leg spends1111        await expectInconsistent("above what the plan holds") { _ = try await prepare(try answer(f.prepared), displayed: try Fx.set(ready, ["holding", "amount"], "9999999999999999").decode()) }1112        // the plan holds another asset than the leg's source1113        await expectInconsistent("does not hold this step's source asset") { _ = try await prepare(try answer(f.prepared), displayed: try Fx.set(ready, ["holding", "asset"], .string(Fx.usdcBase)).decode()) }1114        // the intent swaps to another asset than the leg displayed1115        let i = Fx.set(try #require(f.prepared["intent"]), ["swap", "toAsset"], "0x4200000000000000000000000000000000000006")1116        let digest = try Intent(served: i).approvalDigest()1117        await expectInconsistent("destination asset") { _ = try await prepare(try answer(f.prepared, intent: .some(i), patch: [(["proposal", "intentHash"], .string(digest.hex))]), displayed: f.ready) }1118        // a leg may be given an explicit floor1119        await expectInconsistent("minimum output below") { _ = try await prepare(try answer(f.prepared), displayed: f.ready, rule: .atLeast("24875001")) }1120        // a leg sized BELOW what the plan holds (balance lower than the holding) is the server's rule and is accepted1121        let more = try Fx.set(ready, ["holding", "amount"], "20000000000000000").decode(PlanView.self)1122        #expect(try await prepare(try answer(f.prepared), displayed: more).0.operation?.approvable != nil)1123    }1124}1125
Files main
Menu

Theme