SPB Git

Repository Public

SwapModel.swift 9.8 KB 193 lines swift

1// SP Wallet iOS2// File: Features/Swap/SwapModel.swift3// Description: State of the same-network swap screen: what the server serves (assets, providers, where it executes), the pair,4//              the amount, the tolerance the owner chose, the live quote stream and the route the owner picked, then the5//              preparation of THAT route with its quote reference. A quote never prepares anything; a preparation the Core6//              refuses is withdrawn; a price that moved is shown with both sets of figures and a new quote is offered.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import Observation12import SPWalletCore1314@MainActor @Observable15final class SwapModel {16    enum Phase: Equatable { case idle, loading, done, failed }1718    // what the server serves19    var assets: [SwapAsset] = []20    var providers: SwapProviders?21    var execution: SwapExecutionInfo?22    var catalogLoaded = false23    var catalogError: Error?2425    // the form26    var network: String?27    var from: SwapAsset?28    var to: SwapAsset?29    var amount = ""30    /** nil until the owner picks one: no tolerance is preselected. */31    var slippageBps: Int?32    /** Bumped by "new quote": restarts the stream for the same inputs. */33    var generation = 03435    // the current search36    var phase: Phase = .idle37    var quoteError: Error?38    var routes: [SwapRoute] = []39    var answers: [SwapProviderAnswer] = []40    var best: [String: String] = [:]41    var reachable: Bool?42    var pairExecutors: [String] = []43    /** The owner's pick among the routes of the CURRENT search; cleared whenever the search restarts. */44    var selectedRouteId: String?4546    // preparation47    var busy = false48    var error: Error?49    var cleanup: OperationCleanup.Result?50    var moved: QuoteMoved?51    /** Figures of a preparation the app refused (firm minimum below the minimum displayed), read before it was withdrawn. */52    var refused: (shownMin: String, firmMin: String, firmOut: String, symbol: String)?53    /** Learned from a real preparation the owner asked for (never probed): this server does not return the canonical object. */54    var serverLacksIntent = false55    var start: OperationStart?56    private var idempotency: (key: String, request: SwapRequest)?5758    // MARK: catalog5960    func load(_ env: AppEnvironment) async {61        let api = SwapAPI(env.client)62        do {63            async let a = api.assets(), p = api.providers(), e = api.execution()64            (assets, providers, execution) = try await (a, p, e)65            catalogLoaded = true; catalogError = nil66        } catch { catalogError = error }67    }6869    /** Networks with at least two assets in the swap graph, in the order served. */70    var networks: [(id: String, name: String)] {71        var seen: [String: Int] = [:], order: [(String, String)] = []72        for a in assets { if seen[a.network] == nil { order.append((a.network, a.networkName ?? a.network)) }; seen[a.network, default: 0] += 1 }73        return order.filter { (seen[$0.0] ?? 0) >= 2 }.map { (id: $0.0, name: $0.1) }74    }75    /** Every network of the swap graph (cross-network tools: a network with a single asset is a valid end). */76    var allNetworks: [(id: String, name: String)] {77        var seen = Set<String>(), order: [(id: String, name: String)] = []78        for a in assets where !seen.contains(a.network) { seen.insert(a.network); order.append((id: a.network, name: a.networkName ?? a.network)) }79        return order80    }81    func assets(on network: String) -> [SwapAsset] { assets.filter { $0.network == network } }82    /** The provider that executes a same-network swap there, as /swap/execution states it. nil = quotes only. */83    func executor(on network: String) -> String? { execution?.executor(on: network) }8485    func pick(network id: String) {86        guard id != network else { return }87        network = id; from = nil; to = nil; amount = ""88    }89    func pick(from a: SwapAsset) { from = a; if to?.key == a.key { to = nil }; amount = "" }90    func pick(to a: SwapAsset) { to = a; if from?.key == a.key { from = nil; amount = "" } }91    func flip() { (from, to) = (to, from); amount = "" }9293    // MARK: quotes9495    /** The amount as the quote stream needs it (not compared with the balance: consulting prices is always allowed). */96    var quoteAmount: String? { from.flatMap { SwapLogic.checkAmount(amount, decimals: $0.decimals, balance: nil).text } }9798    var quoteRequest: SwapQuoteRequest? {99        guard let from, let to, let slippageBps, let text = quoteAmount else { return nil }100        return SwapQuoteRequest(from: from.key, to: to.key, amount: text, slippageBps: slippageBps)101    }102103    /** Identity of the current search: any change restarts the stream and forgets the previous routes and pick. */104    var quoteSignature: String { "\(from?.key ?? "")|\(to?.key ?? "")|\(quoteAmount ?? "")|\(slippageBps ?? 0)|\(generation)" }105106    /** A new search forgets everything of the previous one — its routes, and the owner's pick among them. */107    func resetSearch() {108        routes = []; answers = []; best = [:]; reachable = nil; pairExecutors = []; selectedRouteId = nil; quoteError = nil109        moved = nil; refused = nil; error = nil; cleanup = nil110    }111112    func runQuotes(_ env: AppEnvironment, online: Bool) async {113        resetSearch()114        guard let req = quoteRequest, online else { phase = .idle; return }115        phase = .loading116        try? await Task.sleep(for: .milliseconds(450)) // a short pause in typing117        if Task.isCancelled { return }118        do {119            for try await e in SwapAPI(env.client).quoteStream(req) {120                if Task.isCancelled { return }121                switch e {122                case .start(let s): reachable = s.reachable; pairExecutors = s.executors123                case .route(let r): routes.removeAll { $0.id == r.id }; routes.append(r)124                case .provider(let a): answers.append(a)125                case .done(let d): routes = d.routes; best = d.best; reachable = d.reachable; pairExecutors = d.executors; answers = d.providers; phase = .done126                case .failed(let code, let message): quoteError = APIError(status: 200, code: code, message: message); phase = .failed127                case .unknown: break128                }129            }130            if Task.isCancelled { return }131            if phase == .loading { quoteError = APIError(status: 200, code: "stream_ended", message: String(localized: "Le flux de cotations s’est terminé avant le classement final.")); phase = .failed }132        } catch is CancellationError {133        } catch { if !Task.isCancelled { quoteError = error; phase = .failed } }134    }135136    var ordered: [SwapRoute] { SwapLogic.ordered(routes) }137    var selected: SwapRoute? { SwapLogic.selection(selectedRouteId, in: routes) }138139    /** The owner picks a route. Only a route that can be prepared now is selectable; selecting prepares nothing. */140    func select(_ r: SwapRoute, now: Date = Date()) {141        guard SwapLogic.preparability(r, now: now).reference != nil else { return }142        selectedRouteId = r.id143    }144145    func requote() { generation += 1 }146147    // MARK: preparation148149    private func key(for r: SwapRequest) -> String {150        if let i = idempotency, i.request == r { return i.key }151        let k = APIClient.newIdempotencyKey()152        idempotency = (k, r)153        return k154    }155156    func request(now: Date = Date()) -> SwapRequest? {157        guard let from, let to, let slippageBps, let text = quoteAmount, let r = selected, let ref = SwapLogic.preparability(r, now: now).reference else { return nil }158        return SwapRequest(network: from.network, fromAsset: from.asset, toAsset: to.asset, amount: text, slippageBps: slippageBps, quote: ref)159    }160161    /**162     Prepare the route the owner picked, with its reference. By default the firm minimum must not be below the minimum displayed.163     `acceptingFirmMinimum` is the owner's EXPLICIT choice after such a refusal: the firm minimum is then accepted as prepared, and164     the review states that it is lower than the quote's (the server still refuses when the firm expected output is below it).165     */166    func prepare(_ env: AppEnvironment, accounts: Accounts?, acceptingFirmMinimum: Bool = false) async {167        guard !busy, !serverLacksIntent, let accounts, let r = request(), let from, let route = selected else { return }168        busy = true; error = nil; cleanup = nil; moved = nil; refused = nil169        defer { busy = false }170        let started = Date()171        do {172            let prepared = try await SwapAPI(env.client).prepare(r, accounts: accounts, minimumOutput: .asPrepared, idempotencyKey: key(for: r))173            idempotency = nil174            let shown = ShownMinimum(units: route.minAmountOut, display: route.minAmountOutDisplay, symbol: to?.symbol ?? "")175            start = prepared.approvable.map { .review($0, shown: shown) } ?? .tracking(proposalId: prepared.proposal.id)176        } catch {177            let kind = SwapLogic.classify(error)178            if kind != .offline { idempotency = nil } // answered, even by a refusal: the next attempt is a new request179            if let m = error as? QuoteMoved { moved = m; selectedRouteId = nil; return }180            self.error = error181            if kind == .serverLacksIntent { serverLacksIntent = true }182            if SwapLogic.leavesPendingProposal(error) {183                let units = SwapLogic.checkAmount(r.amount, decimals: from.decimals, balance: nil).units?.description184                let c = await OperationCleanup.withdraw(env, kind: "swap", network: r.network, asset: r.fromAsset, amountUnits: units, since: started)185                cleanup = c.result186                if kind == .refusedByApp, let s = c.found.compactMap({ try? $0.swapSection() }).first {187                    refused = (route.minAmountOutDisplay, s.minOutDisplay, s.expectedOutDisplay, s.toSymbol)188                }189            }190        }191    }192}193
Files main
Menu

Theme