SPB Git

Repository Public

SwapFlow.swift 13.5 KB 248 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Swap/SwapFlow.swift3// Description: State machine of a swap: pair and amount → live quotes from every provider (price discovery only: nothing is prepared or signed) → the ONE route this wallet can execute, as the server states it → firm preparation verified by the Core against the challenge → passkey → tracking until the chain says what was received. Same-network swaps (KyberSwap, Jupiter) and native cross-chain swaps (THORChain) share the flow; the executor is always the server's statement, never a guess.4import Foundation5import SPWalletCore67@MainActor @Observable final class SwapFlow {8    enum Step: Equatable { case form, preparing, review, approving, tracking }9    enum QuotePhase: Equatable { case idle, loading, done, failed(String) }1011    /// The server's own schema defaults and bounds (services/api/src/swap-exec.ts and xswap.ts `Create`): 50 bps for a12    /// same-network swap, 100 bps for a THORChain swap, 1…300 bps accepted at preparation. No endpoint serves them.13    static let defaultSlippageBps = 5014    static let defaultNativeSlippageBps = 10015    static let slippageRange = 1...30016    static let slippagePresets = [10, 30, 50, 100, 200, 300]1718    let model: AppModel19    var fromKey = "" { didSet { if fromKey != oldValue { pairChanged() } } }20    var toKey = "" { didSet { if toKey != oldValue { pairChanged() } } }21    var amount = ""22    /// Tolerance as typed, in percent ("0,5").23    var slippageText = "0,5" { didSet { if slippageText != oldValue { slippageTouched = true } } }24    private var slippageTouched = false2526    private(set) var assets: [SwapAsset] = []27    private(set) var providers: SwapProviders?28    private(set) var execution: SwapExecutionInfo?29    private(set) var xswapInfo: XSwapExecutionInfo?30    private(set) var bridgeInfo: BridgeExecutionInfo?31    private(set) var loadError: String?32    private(set) var loaded = false3334    private(set) var quotePhase: QuotePhase = .idle35    private(set) var routes: [SwapRoute] = []36    private(set) var best: [String: String] = [:]37    private(set) var answers: [SwapProviderAnswer] = []38    /// The executors the SERVER states for this pair (pinned tables); nil until a search started.39    private(set) var pairExecutors: [String]?40    private(set) var reachable: Bool?41    private(set) var quotedAt: Date?42    private(set) var requote = 04344    private(set) var step: Step = .form45    private(set) var operation: ApprovableOperation?46    private(set) var tracker: OperationTracker?47    private(set) var refreshing = false48    var error: String?49    private var idempotency: (key: String, fingerprint: String)?5051    init(model: AppModel) { self.model = model }5253    // MARK: derived5455    var from: SwapAsset? { assets.first { $0.key == fromKey } }56    var to: SwapAsset? { assets.first { $0.key == toKey } }57    var normalizedAmount: String { SwapText.normalize(amount) }58    var parsedAmount: BaseUnits? { guard let d = from?.decimals else { return nil }; return try? BaseUnits.parse(normalizedAmount, decimals: d) }59    var balance: Balance? { from.flatMap { SwapText.balance(model, of: $0) } }60    var slippageBps: Int? {61        guard let v = Double(SwapText.normalize(slippageText)), v.isFinite else { return nil }62        let b = Int((v * 100).rounded())63        return Self.slippageRange.contains(b) && abs(v * 100 - Double(b)) < 1e-6 ? b : nil64    }65    var crossNetwork: Bool { guard let f = from, let t = to else { return false }; return f.network != t.network }6667    /// What the server's capability lists say about the pair before any quote is asked.68    var capabilityHint: [String] {69        guard let f = from, let t = to, f.key != t.key else { return [] }70        if let e = pairExecutors { return e }71        var out: [String] = []72        if f.network == t.network { if let p = execution?.executor(on: f.network) { out.append(p) } }73        else {74            if f.symbol == "USDC", t.symbol == "USDC", bridgeInfo?.canBridge(from: f.network, to: t.network) == true { out.append("cctp") }75            if xswapInfo?.canSwap(from: f.ref, to: t.ref) == true { out.append("thorchain") }76        }77        return out78    }79    var isNativeCrossChain: Bool { capabilityHint.contains("thorchain") }80    /// USDC ↔ USDC between two CCTP networks is a bridge: prepared on its own screen, with its own speeds and fees.81    var isBridgePair: Bool { capabilityHint.contains("cctp") && !capabilityHint.contains("thorchain") }8283    var sortedRoutes: [SwapRoute] {84        let top = best["best_price"]85        func min(_ r: SwapRoute) -> BaseUnits { (try? BaseUnits(r.minAmountOut)) ?? .zero }86        return routes.sorted { a, b in87            if (a.id == top) != (b.id == top) { return a.id == top }88            return min(a) > min(b)89        }90    }91    /// The route the action executes: the first one the server marks executable by this wallet (CCTP routes belong to the bridge screen).92    var executableRoute: SwapRoute? { sortedRoutes.first { r in r.statedExecutor != nil && r.statedExecutor != "cctp" } }9394    func isExpired(_ r: SwapRoute, now: Date = Date()) -> Bool {95        guard let ms = r.expiresAt ?? r.card?.expiresAt else { return false }96        return now.timeIntervalSince1970 * 1000 >= Double(ms)97    }9899    var formProblem: String? {100        guard let f = from, let t = to else { return "Choisissez l’actif vendu et l’actif acheté." }101        if f.key == t.key { return "Choisissez deux actifs différents." }102        if amount.trimmingCharacters(in: .whitespaces).isEmpty { return "Entrez un montant." }103        guard let a = parsedAmount, !a.isZero else { return "Montant invalide (au plus \(f.decimals) décimales)." }104        if let b = balance, b.isAvailable, let u = b.units, a > u { return "Montant supérieur au solde lu sur la chaîne." }105        if slippageBps == nil { return "Tolérance de glissement invalide : entre 0,01 % et 3 %." }106        return nil107    }108109    /// Identity of the quote search: the view restarts the stream when it changes and closes it when it disappears.110    var quoteKey: String { "\(fromKey)|\(toKey)|\(normalizedAmount)|\(slippageBps ?? -1)|\(requote)|\(model.canOperate)" }111112    // MARK: loading113114    func load() async {115        guard model.phase == .signedIn else { return }116        let swap = SwapAPI(model.client)117        do {118            async let a = swap.assets()119            async let p = swap.providers()120            async let e = swap.execution()121            (assets, providers, execution) = try await (a, p, e)122            loadError = nil; loaded = true123        } catch { loadError = model.describe(error) }124        // the two cross-chain capability lists only refine hints: their absence disables nothing by itself125        xswapInfo = try? await XSwapAPI(model.client).execution()126        bridgeInfo = try? await BridgeAPI(model.client).execution()127    }128129    private func pairChanged() {130        guard !slippageTouched || slippageBps == nil else { return }131        // the server's default tolerance for the kind of swap this pair is132        slippageText = isNativeCrossChain ? "1" : "0,5"133        slippageTouched = false134    }135136    func setSlippage(bps: Int) { slippageText = (Double(bps) / 100).formatted(.number.precision(.fractionLength(0...2))) }137    func setMax() { if let d = balance?.display { amount = d } }138    func flip() { let f = fromKey; fromKey = toKey; toKey = f; amount = "" }139    func refreshQuotes() { requote += 1 }140141    // MARK: quotes (read-only)142143    private func clearQuotes() { routes = []; best = [:]; answers = []; pairExecutors = nil; reachable = nil; quotedAt = nil }144145    /// One server-sent stream per (pair, amount, tolerance). Asking for quotes prepares nothing and signs nothing.146    func runQuotes() async {147        guard step == .form else { return }148        clearQuotes()149        guard model.canOperate, let f = from, let t = to, f.key != t.key, let a = parsedAmount, !a.isZero, let bps = slippageBps else { quotePhase = .idle; return }150        quotePhase = .loading151        try? await Task.sleep(for: .milliseconds(600)) // a pause in typing152        if Task.isCancelled { return }153        let request = SwapQuoteRequest(from: f.key, to: t.key, amount: normalizedAmount, slippageBps: bps)154        do {155            for try await event in SwapAPI(model.client).quoteStream(request) {156                switch event {157                case .start(let s): pairExecutors = s.executors; reachable = s.reachable158                case .route(let r): routes.removeAll { $0.id == r.id }; routes.append(r)159                case .provider(let p): answers.append(p)160                case .done(let s):161                    routes = s.routes; best = s.best; answers = s.providers; pairExecutors = s.executors; reachable = s.reachable162                    quotedAt = Date(); quotePhase = .done163                case .failed(let code, let message): quotePhase = .failed(SwapText.describe(APIError(status: 200, code: code, message: message), model: model))164                case .unknown: break165                }166            }167            if Task.isCancelled { return }168            if quotePhase == .loading { quotePhase = .failed("La recherche de cotations s’est interrompue avant son résultat final.") }169        } catch is CancellationError {170        } catch { if !Task.isCancelled { quotePhase = .failed(SwapText.describe(error, model: model)) } }171    }172173    // MARK: preparation and approval174175    func prepare() async {176        guard step == .form, model.canOperate, formProblem == nil, let f = from, let t = to, let bps = slippageBps,177              let route = executableRoute, let via = route.statedExecutor, !isExpired(route) else { return }178        guard let accounts = model.accounts?.value else { error = "Les adresses du portefeuille ne sont pas synchronisées ; l’opération ne peut pas être vérifiée."; return }179        error = nil; step = .preparing180        // the reference of the route displayed travels with the request: the server refuses when its firm route is below the minimum shown181        let ref = route.quoteReference182        let rule: MinimumOutputRule = ref == nil ? .asPrepared : .notBelowQuote183        let fp = "\(via)|\(f.key)|\(t.key)|\(normalizedAmount)|\(bps)|\(ref?.fingerprint ?? "-")"184        if idempotency?.fingerprint != fp { idempotency = (APIClient.newIdempotencyKey(), fp) }185        let key = idempotency!.key186        do {187            let prepared: PreparedOperation188            if via == "thorchain" {189                prepared = try await XSwapAPI(model.client).prepare(XSwapRequest(fromNetwork: f.network, fromAsset: f.asset, toNetwork: t.network, toAsset: t.asset, amount: normalizedAmount, slippageBps: bps, quote: ref),190                                                                    accounts: accounts, minimumOutput: rule, idempotencyKey: key)191            } else {192                guard f.network == t.network else { throw ApprovalError.inconsistent("un échange \(via) ne change pas de réseau") }193                prepared = try await SwapAPI(model.client).prepare(SwapRequest(network: f.network, fromAsset: f.asset, toAsset: t.asset, amount: normalizedAmount, slippageBps: bps, quote: ref),194                                                                   accounts: accounts, minimumOutput: rule, idempotencyKey: key)195            }196            if let op = prepared.approvable { operation = op; step = .review }197            else { idempotency = nil; begin(tracking: prepared.proposal) } // replay of a proposal that is no longer waiting for an approval198        } catch {199            self.error = SwapText.describe(error, model: model)200            // answered, even by a refusal: the next attempt is a new request. A lost answer keeps its key, so the retry finds the same proposal.201            if (error as? APIError)?.isOffline != true { idempotency = nil; requote += 1 }202            step = .form203        }204    }205206    func approve() async {207        guard let op = operation, step == .review else { return }208        error = nil; step = .approving209        let api = SwapAPI(model.client)210        do {211            let p = try await api.approve(op, with: model.authenticator)212            idempotency = nil; begin(tracking: p)213        } catch PasskeyError.cancelled { step = .review }214        catch {215            // never sign twice: read what the server really did with this proposal216            self.error = (error as? APIError)?.isOffline == true ? "Réponse perdue pendant l’approbation. Lecture de l’état réel de l’opération…" : SwapText.describe(error, model: model)217            if let p = try? await api.proposal(op.proposal.id), p.state != .pendingApproval { idempotency = nil; begin(tracking: p) } else { step = .review }218        }219    }220221    func reject() async {222        guard let op = operation else { return }223        _ = try? await SwapAPI(model.client).reject(op.proposal.id)224        idempotency = nil; operation = nil; error = nil; step = .form225        requote += 1226    }227228    private func begin(tracking p: Proposal) {229        operation = nil230        tracker = OperationTracker(model: model, proposal: p)231        step = .tracking232        Task { await model.refreshActivity() }233    }234235    /// THORChain: look now instead of waiting for the server's worker. Signs nothing.236    func refreshNow() async {237        guard let t = tracker, t.proposal.kind == "xswap", !refreshing, model.canOperate else { return }238        refreshing = true; defer { refreshing = false }239        do { t.update(try await XSwapAPI(model.client).refresh(t.proposal.id)); error = nil }240        catch { self.error = SwapText.describe(error, model: model) }241    }242243    func reset() {244        tracker = nil; operation = nil; error = nil; amount = ""; idempotency = nil; step = .form245        clearQuotes(); quotePhase = .idle246    }247}248
Files main
Menu

Theme