Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/DeFi/PlanFlow.swift3// Description: State machine of an any-to-any plan: quote candidate multi-leg routes (a read) → start one (stored by the server; nothing prepared or signed) → for each leg, when its turn comes: prepare it, verify it with the Core against the plan displayed, approve it with its own passkey prompt, wait until the chain settles it → next leg. After a pause the owner decides: retry, re-plan from the asset held, or stop. Nothing advances by itself and no leg is ever reported settled before the server read its output from the chain.4import Foundation5import SPWalletCore67@MainActor @Observable final class PlanFlow {8 enum Busy: Equatable { case quoting, starting(String), refreshing, preparing, approving, retrying, replanning, stopping }910 /// The server's schema default and bounds for plans (services/api/src/plan-exec.ts `Pair`): 50 bps, 1…300.11 static let slippageRange = 1...3001213 let model: AppModel14 var fromKey = ""15 var toKey = ""16 var amount = ""17 var slippageText = "0,5"18 /// Optional overall floor, in whole units of the destination asset: the plan pauses before a leg when the estimate is below it.19 var floorText = ""20 var newFloorText = ""2122 private(set) var assets: [SwapAsset] = []23 private(set) var loaded = false24 private(set) var loadError: String?25 private(set) var quote: PlanQuote?26 private(set) var quotedAt: Date?27 private(set) var plan: PlanView?28 private(set) var recent: [PlanView] = []29 private(set) var busy: Busy?30 private(set) var operation: ApprovableOperation?31 private(set) var readError: String?32 var error: String?33 var reviewError: String?34 private var announced: Set<String> = []3536 init(model: AppModel) { self.model = model }3738 private var api: PlanAPI { PlanAPI(model.client) }39 var from: SwapAsset? { assets.first { $0.key == fromKey } }40 var to: SwapAsset? { assets.first { $0.key == toKey } }41 var normalizedAmount: String { SwapText.normalize(amount) }42 var parsedAmount: BaseUnits? { guard let d = from?.decimals else { return nil }; return try? BaseUnits.parse(normalizedAmount, decimals: d) }43 var slippageBps: Int? {44 guard let v = Double(SwapText.normalize(slippageText)), v.isFinite else { return nil }45 let b = Int((v * 100).rounded())46 return Self.slippageRange.contains(b) && abs(v * 100 - Double(b)) < 1e-6 ? b : nil47 }48 private func floorValue(_ text: String) -> String?? {49 let t = SwapText.normalize(text)50 if t.isEmpty { return .some(nil) }51 guard let d = (plan?.to ?? to)?.decimals, let u = try? BaseUnits.parse(t, decimals: d), !u.isZero else { return nil }52 return .some(t)53 }5455 var formProblem: String? {56 guard let f = from, to != nil else { return "Choisissez l’actif de départ et l’actif d’arrivée." }57 if fromKey == toKey { return "Choisissez deux actifs différents." }58 if amount.trimmingCharacters(in: .whitespaces).isEmpty { return "Entrez un montant." }59 guard let a = parsedAmount, !a.isZero else { return "Montant invalide (au plus \(f.decimals) décimales)." }60 if let b = SwapText.balance(model, of: f), b.isAvailable, let u = b.units, a > u { return "Montant supérieur au solde lu sur la chaîne." }61 if slippageBps == nil { return "Tolérance invalide : entre 0,01 % et 3 %." }62 if floorValue(floorText) == nil { return "Plancher invalide." }63 return nil64 }65 private var request: PlanRequest? {66 guard formProblem == nil, let bps = slippageBps else { return nil }67 return PlanRequest(from: fromKey, to: toKey, amount: normalizedAmount, slippageBps: bps)68 }69 /// The quote on screen is for the form as it is now.70 var quoteIsCurrent: Bool {71 guard let q = quote, let a = parsedAmount else { return false }72 return q.from.key == fromKey && q.to.key == toKey && q.amountIn == a.description && q.slippageBps == slippageBps73 }7475 // MARK: loading7677 func load() async {78 guard model.phase == .signedIn else { return }79 do {80 async let a = SwapAPI(model.client).assets()81 async let open = api.list(openOnly: true, limit: 1)82 async let last = api.list(limit: 6)83 let (assets, o, l) = try await (a, open, last)84 self.assets = assets; loaded = true; loadError = nil85 recent = l.filter { !$0.isOpen }86 if plan == nil { plan = o.first }87 if let p = plan, p.isOpen { await refresh() }88 } catch { loadError = model.describe(error) }89 }9091 private func adopt(_ p: PlanView) {92 plan = p; readError = nil93 guard !p.isOpen, !announced.contains(p.id) else { return }94 announced.insert(p.id)95 if p.isComplete { Notifier.post(title: "Parcours terminé", body: "Reçu : \(p.receivedDisplay.map { Fmt.amount($0, maxFraction: 8) } ?? "—") \(p.to.symbol) sur \(p.to.networkName ?? p.to.network).", id: "plan-\(p.id)") }96 else if p.state == .stopped { Notifier.post(title: "Parcours arrêté", body: "Les fonds restent où ils sont : \(Fmt.amount(p.holding.amountDisplay, maxFraction: 8)) \(p.holding.symbol) sur \(p.holding.networkName ?? p.holding.network).", id: "plan-\(p.id)") }97 Task { await model.refreshAll() }98 }99100 /// Reading a plan makes the server look at the current leg's proposal; it creates and signs nothing.101 func refresh() async {102 guard let id = plan?.id, model.phase == .signedIn else { return }103 do { adopt(try await api.plan(id)) } catch { readError = model.describe(error) }104 }105106 /// While a leg is in flight (or an unused challenge is ageing): read the plan until the next decision is the owner's.107 func follow() async {108 while !Task.isCancelled {109 guard let p = plan, p.isOpen, p.next == .wait || (p.next == .approve && operation == nil) else { return }110 try? await Task.sleep(for: .seconds(p.next == .wait ? 5 : 20))111 guard !Task.isCancelled else { return }112 guard AppActivity.isActive, model.phase == .signedIn, busy == nil else { continue }113 await refresh()114 }115 }116117 // MARK: quote and start118119 func quotePlans() async {120 guard busy == nil, model.canOperate, let r = request else { return }121 busy = .quoting; defer { busy = nil }122 error = nil123 do { quote = try await api.quote(r); quotedAt = Date() }124 catch { quote = nil; self.error = SwapText.describe(error, model: model) }125 }126127 /// Stores the chosen shape. Nothing is prepared or signed: the first leg becomes "ready".128 func start(_ candidate: PlanCandidate) async {129 guard busy == nil, model.canOperate, quoteIsCurrent, candidate.executable, let r = request, let floor = floorValue(floorText) else { return }130 busy = .starting(candidate.id); defer { busy = nil }131 error = nil132 do { adopt(try await api.start(r, plan: candidate.id, floor: floor)); quote = nil; amount = ""; floorText = "" }133 catch {134 self.error = SwapText.describe(error, model: model)135 // a lost answer, or a plan opened elsewhere: show the plan that is really open rather than starting a second one136 if let open = try? await api.list(openOnly: true, limit: 1).first { adopt(open) }137 }138 }139140 // MARK: one leg = one verified passkey approval141142 func prepareLeg() async {143 guard busy == nil, model.canOperate, let displayed = plan, displayed.isOpen else { return }144 guard let accounts = model.accounts?.value else { error = "Les adresses du portefeuille ne sont pas synchronisées ; l’étape ne peut pas être vérifiée."; return }145 busy = .preparing; defer { busy = nil }146 error = nil; reviewError = nil147 do {148 // verified against the plan AS DISPLAYED: same plan, same position, same leg, an amount within what the plan holds149 let prep = try await api.prepareLeg(of: displayed, accounts: accounts, minimumOutput: .asPrepared)150 adopt(prep.plan)151 if let op = prep.operation?.approvable { operation = op }152 else if prep.operation != nil { await refresh() }153 } catch {154 self.error = SwapText.describe(error, model: model)155 await refresh()156 }157 }158159 func approveLeg() async {160 guard let op = operation, busy == nil else { return }161 busy = .approving; defer { busy = nil }162 reviewError = nil163 do {164 _ = try await api.approve(op, with: model.authenticator)165 operation = nil166 await refresh()167 } catch PasskeyError.cancelled {168 } catch {169 reviewError = (error as? APIError)?.isOffline == true ? "Réponse perdue pendant l’approbation. Lecture de l’état réel de l’étape…" : SwapText.describe(error, model: model)170 // never sign twice: if the proposal left "pending approval", follow the plan instead171 if let p = try? await api.proposal(op.proposal.id), p.state != .pendingApproval { operation = nil; self.error = reviewError; await refresh() }172 }173 }174175 /// Withdraws the unused challenge of this leg. The plan then records the refusal and waits for a decision.176 func rejectLeg() async {177 guard let op = operation, busy == nil else { return }178 _ = try? await api.reject(op.proposal.id)179 operation = nil; reviewError = nil180 await refresh()181 }182183 // MARK: decisions after a pause (none of them signs anything)184185 enum FloorChoice { case unchanged, remove, set }186187 func retry(_ choice: FloorChoice) async {188 guard busy == nil, model.canOperate, let id = plan?.id else { return }189 var change = PlanFloorChange.unchanged190 switch choice {191 case .unchanged: break192 case .remove: change = .remove193 case .set:194 guard let inner = floorValue(newFloorText), let v = inner else { error = "Nouveau plancher invalide."; return }195 change = .set(v)196 }197 busy = .retrying; defer { busy = nil }198 error = nil199 do { adopt(try await api.retry(id, floor: change)); newFloorText = "" } catch { self.error = SwapText.describe(error, model: model) }200 }201202 func replan() async {203 guard busy == nil, model.canOperate, let id = plan?.id else { return }204 busy = .replanning; defer { busy = nil }205 error = nil206 do { adopt(try await api.replan(id)) } catch { self.error = SwapText.describe(error, model: model) }207 }208209 func stop() async {210 guard busy == nil, model.canOperate, let id = plan?.id else { return }211 busy = .stopping; defer { busy = nil }212 error = nil213 do { adopt(try await api.stop(id)); operation = nil } catch { self.error = SwapText.describe(error, model: model) }214 }215216 /// Leave a finished plan's summary and go back to the form.217 func dismissFinished() {218 guard let p = plan, !p.isOpen else { return }219 plan = nil; error = nil; operation = nil220 Task { await load() }221 }222}223