SPB Git

Repository Public

BridgeFlow.swift 14.4 KB 267 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Bridge/BridgeFlow.swift3// Description: State machine of a USDC transfer between networks through Circle CCTP: networks the server enables → quote of both speeds → firm burn verified by the Core against the challenge → passkey → the two legs followed until the destination mint is confirmed. Also the recovery of interrupted transfers (finish, passkey-approved new mint signature, reclaim of the Solana event-account deposit) and the opening of the wallet's USDC token account on Solana — each through the Core's verified approval, or shown as unavailable when the Core cannot verify it.4import Foundation5import SPWalletCore67@MainActor @Observable final class BridgeFlow {8    enum Step: Equatable { case form, preparing, review, approving, tracking }9    enum QuotePhase: Equatable { case idle, loading, done, failed(String) }10    /// A passkey approval that is not an intent: each carries the object the Core verified against its challenge.11    enum FollowUp { case retryMint(MintRetryApproval), reclaim(DepositReclaimApproval), tokenAccount(TokenAccountApproval) }12    enum Action: String { case finish, retryMint, reclaim, tokenAccount }1314    /// One interrupted or unfinished transfer found in the activity feed.15    struct Recoverable: Identifiable {16        let item: ActivityItem17        /// nil when the server's bridge section cannot be read by this version: shown as such, never guessed.18        let section: BridgeSection?19        var id: String { item.id }20    }2122    let model: AppModel23    var fromNetwork = "" { didSet { if fromNetwork == toNetwork, let other = networks.first(where: { $0.id != fromNetwork }) { toNetwork = other.id } } }24    var toNetwork = ""25    var amount = ""26    var speed: BridgeSpeed = .standard2728    private(set) var info: BridgeExecutionInfo?29    private(set) var loadError: String?30    private(set) var quotePhase: QuotePhase = .idle31    private(set) var quote: BridgeQuote?32    private(set) var quotedAt: Date?33    private(set) var requote = 03435    private(set) var step: Step = .form36    private(set) var operation: ApprovableOperation?37    private(set) var tracker: OperationTracker?38    var error: String?39    private var idempotency: (key: String, fingerprint: String)?4041    private(set) var followUp: FollowUp?42    private(set) var followUpBusy = false43    var followUpError: String?44    private(set) var busyAction: Action?45    /// Actions the Core refused to verify (`ApprovalError.unsupported`): no way around is offered.46    private(set) var unavailable: [Action: String] = [:]47    private(set) var tokenAccountCreation: SolanaTokenAccountCreation?48    private(set) var opening: String?49    private(set) var openError: String?5051    init(model: AppModel) { self.model = model }5253    // MARK: derived5455    private var api: BridgeAPI { BridgeAPI(model.client) }56    /// The networks CCTP serves, in the server's order, limited to those the registry knows.57    var networks: [SPWalletCore.Network] { (info?.networks ?? []).compactMap { model.network($0) } }58    var normalizedAmount: String { SwapText.normalize(amount) }59    var parsedAmount: BaseUnits? { try? BaseUnits.parse(normalizedAmount, decimals: 6) } // USDC has six decimals on every CCTP network60    /// The registry id of USDC on a network — only when exactly one token carries that symbol (a symbol is not an identifier).61    func usdc(on network: String) -> AssetDef? {62        let hits = model.network(network)?.tokens.filter { $0.symbol == "USDC" } ?? []63        return hits.count == 1 ? hits[0] : nil64    }65    var sourceBalance: Balance? {66        guard let u = usdc(on: fromNetwork) else { return nil }67        return model.portfolio?.value.balances.first { $0.network == fromNetwork && SwapText.sameId($0.asset, u.id) }68    }69    var option: BridgeQuote.Option? { quote?.option(speed) }70    var tokenAccountMissing: Bool { quote?.solana?.role == "destination" && quote?.solana?.tokenAccountExists == false }7172    var formProblem: String? {73        guard let info else { return "Capacités du pont non lues." }74        guard !fromNetwork.isEmpty, !toNetwork.isEmpty else { return "Choisissez le réseau source et le réseau de destination." }75        if fromNetwork == toNetwork { return "Choisissez deux réseaux différents." }76        if !info.canBridge(from: fromNetwork, to: toNetwork) { return "Le serveur n’active pas CCTP entre ces deux réseaux." }77        if amount.trimmingCharacters(in: .whitespaces).isEmpty { return "Entrez un montant." }78        guard let a = parsedAmount, !a.isZero else { return "Montant invalide (au plus 6 décimales)." }79        if let b = sourceBalance, b.isAvailable, let u = b.units, a > u { return "Montant supérieur au solde USDC lu sur la chaîne." }80        return nil81    }8283    /// Why the selected option cannot be prepared right now; nil when it can.84    var prepareProblem: String? {85        if let p = formProblem { return p }86        guard let q = quote, quotePhase == .done else { return "En attente du devis." }87        guard let o = q.option(speed) else { return "Cette vitesse n’est pas offerte sur cette route." }88        if !o.available { return "Cette vitesse n’est pas disponible pour ce montant en ce moment." }89        if o.quote == nil { return "Le montant ne couvre pas les frais de Circle." }90        if !q.destinationGas.enough { return "Pas assez de \(q.destinationGas.symbol) sur la destination pour payer l’émission : le serveur refuse de brûler quoi que ce soit." }91        if tokenAccountMissing { return "Ouvrez d’abord le compte de jetons USDC sur Solana." }92        return nil93    }9495    var quoteKey: String { "\(fromNetwork)|\(toNetwork)|\(normalizedAmount)|\(requote)|\(model.canOperate)" }9697    /// Transfers still in transit, waiting for a decision, or whose Solana deposit has not come back, most recent first.98    var recoverable: [Recoverable] {99        (model.activity?.value ?? []).compactMap { item -> Recoverable? in100            guard item.kind == "bridge", let raw = item.bridge, !raw.isNull else { return nil }101            guard let b = try? raw.decode(BridgeSection.self) else { return item.proposalState?.isFailure == true ? nil : Recoverable(item: item, section: nil) }102            let depositOut = b.sol?.role == "source" && b.sol?.reclaimState != nil && b.sol?.isReclaimed == false && !b.isFailed103            return b.isInTransit || depositOut ? Recoverable(item: item, section: b) : nil104        }105    }106107    // MARK: loading and quote (read-only)108109    func load() async {110        guard model.phase == .signedIn else { return }111        do {112            info = try await api.execution(); loadError = nil113            if fromNetwork.isEmpty, let first = networks.first { fromNetwork = first.id }114            if toNetwork.isEmpty, let second = networks.first(where: { $0.id != fromNetwork }) { toNetwork = second.id }115        } catch { loadError = model.describe(error) }116        await model.refreshActivity()117    }118119    func refreshQuote() { requote += 1 }120    func setMax() { if let d = sourceBalance?.display { amount = d } }121    func flip() { let f = fromNetwork; fromNetwork = toNetwork; toNetwork = f }122123    func runQuote() async {124        guard step == .form else { return }125        quote = nil; quotedAt = nil126        guard model.canOperate, formProblem == nil else { quotePhase = .idle; return }127        quotePhase = .loading128        try? await Task.sleep(for: .milliseconds(500))129        if Task.isCancelled { return }130        do {131            let q = try await api.quote(from: fromNetwork, to: toNetwork, amount: normalizedAmount)132            if Task.isCancelled { return }133            guard q.from == fromNetwork, q.to == toNetwork, q.symbol == "USDC" else { throw ApprovalError.inconsistent("le devis ne correspond pas à la route demandée") }134            quote = q; quotedAt = Date(); quotePhase = .done135            if q.option(speed) == nil { speed = .standard }136        } catch is CancellationError {137        } catch { if !Task.isCancelled { quotePhase = .failed(SwapText.describe(error, model: model)) } }138    }139140    // MARK: preparation and approval of the burn141142    func prepare() async {143        guard step == .form, model.canOperate, prepareProblem == nil, let o = option, let ref = o.quote else { return }144        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 }145        error = nil; step = .preparing146        let fp = "\(fromNetwork)|\(toNetwork)|\(normalizedAmount)|\(speed.rawValue)|\(ref.fingerprint)"147        if idempotency?.fingerprint != fp { idempotency = (APIClient.newIdempotencyKey(), fp) }148        do {149            // the fee ceiling approved may not exceed the fee displayed; the asset burned must be the registry's USDC150            let prepared = try await api.prepare(BridgeRequest(fromNetwork: fromNetwork, toNetwork: toNetwork, amount: normalizedAmount, speed: speed, quote: ref),151                                                 accounts: accounts, sourceUSDC: usdc(on: fromNetwork)?.id, maxFee: o.fee, idempotencyKey: idempotency!.key)152            if let op = prepared.approvable { operation = op; step = .review }153            else { idempotency = nil; begin(tracking: prepared.proposal) }154        } catch {155            self.error = SwapText.describe(error, model: model)156            if (error as? APIError)?.isOffline != true { idempotency = nil; requote += 1 }157            step = .form158        }159    }160161    func approve() async {162        guard let op = operation, step == .review else { return }163        error = nil; step = .approving164        do {165            let p = try await api.approve(op, with: model.authenticator)166            idempotency = nil; begin(tracking: p)167        } catch PasskeyError.cancelled { step = .review }168        catch {169            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)170            if let p = try? await api.proposal(op.proposal.id), p.state != .pendingApproval { idempotency = nil; begin(tracking: p) } else { step = .review }171        }172    }173174    func reject() async {175        guard let op = operation else { return }176        _ = try? await api.reject(op.proposal.id)177        idempotency = nil; operation = nil; error = nil; step = .form; requote += 1178    }179180    private func begin(tracking p: Proposal) {181        operation = nil; unavailable = [:]; error = nil182        tracker = OperationTracker(model: model, proposal: p)183        step = .tracking184        Task { await model.refreshActivity() }185    }186187    // MARK: recovery188189    /// Open an existing transfer with its real, freshly read state.190    func open(_ r: Recoverable) async {191        guard opening == nil, step == .form || step == .tracking else { return }192        opening = r.id; defer { opening = nil }193        openError = nil194        do { begin(tracking: try await api.proposal(r.id)) }195        catch { openError = SwapText.describe(error, model: model) }196    }197198    func closeTracking() {199        tracker = nil; error = nil; unavailable = [:]; step = .form; amount = ""; quote = nil; quotePhase = .idle200        Task { await model.refreshActivity() }201    }202203    /// "Finish": the server runs the next step now. It signs nothing the burn approval did not cover.204    func finish() async {205        guard let t = tracker, busyAction == nil, model.canOperate else { return }206        busyAction = .finish; defer { busyAction = nil }207        do { t.update(try await api.finish(t.proposal.id)); error = nil }208        catch { self.error = SwapText.describe(error, model: model) }209    }210211    private func request(_ action: Action, _ make: () async throws -> FollowUp) async {212        guard busyAction == nil, followUp == nil, model.canOperate else { return }213        busyAction = action; defer { busyAction = nil }214        error = nil; followUpError = nil215        do { followUp = try await make(); unavailable[action] = nil }216        catch let e as ApprovalError {217            // the Core could not verify the object to approve: the action is unavailable, with the reason, and nothing is signed218            if case .unsupported = e { unavailable[action] = model.describe(e) } else { self.error = model.describe(e) }219        }220        catch { self.error = SwapText.describe(error, model: model) }221        if let t = tracker, let p = try? await api.proposal(t.proposal.id) { t.update(p) }222    }223224    func beginRetryMint() async {225        guard let id = tracker?.proposal.id else { return }226        let api = api227        await request(.retryMint) { .retryMint(try await api.retryMintOptions(id)) }228    }229230    func beginReclaim() async {231        guard let id = tracker?.proposal.id else { return }232        let api = api233        await request(.reclaim) { .reclaim(try await api.reclaimOptions(id)) }234    }235236    func beginTokenAccount() async {237        guard let accounts = model.accounts?.value else { error = "Les adresses du portefeuille ne sont pas synchronisées."; return }238        guard let mint = usdc(on: "solana")?.id else { unavailable[.tokenAccount] = "Le registre ne désigne pas un unique jeton USDC sur Solana : la demande ne peut pas être vérifiée."; return }239        let api = api240        await request(.tokenAccount) { .tokenAccount(try await api.solanaTokenAccountOptions(accounts: accounts, usdcMint: mint)) }241    }242243    func cancelFollowUp() { guard !followUpBusy else { return }; followUp = nil; followUpError = nil }244245    /// The passkey signs the verified challenge; the answer is never a completion (a mint sent again is not a mint received).246    func confirmFollowUp() async {247        guard let f = followUp, !followUpBusy, model.canOperate else { return }248        followUpBusy = true; defer { followUpBusy = false }249        followUpError = nil250        do {251            switch f {252            case .retryMint(let a): tracker?.update(try await api.retryMint(a, with: model.authenticator))253            case .reclaim(let a): tracker?.update(try await api.reclaim(a, with: model.authenticator))254            case .tokenAccount(let a):255                tokenAccountCreation = try await api.createSolanaTokenAccount(a, with: model.authenticator)256                requote += 1257            }258            followUp = nil259        } catch PasskeyError.cancelled {260        } catch {261            followUpError = SwapText.describe(error, model: model)262            // never sign twice on a lost answer: read what the server really did263            if let t = tracker, let p = try? await api.proposal(t.proposal.id) { t.update(p) }264        }265    }266}267
Files main
Menu

Theme