Repository Public
1// SP Wallet iOS2// File: Features/Bridge/PlanViews.swift3// Description: A multi-step plan (any asset to any asset): its legs with what was planned and what really happened, where the4// funds are now, and the owner's decisions. NOTHING advances by itself: each leg is prepared on request, verified,5// and approved with its own passkey; after a pause the owner retries, re-plans or stops. A plan is "terminé" only6// when every leg settled; a stopped plan is not a success.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213enum PlanText {14 static func next(_ n: PlanNextAction) -> String {15 switch n {16 case .prepare: String(localized: "Étape prête : à préparer")17 case .approve: String(localized: "Étape préparée : en attente de ta clé d’accès")18 case .wait: String(localized: "Étape en cours sur le réseau")19 case .paused: String(localized: "En pause : une décision est attendue")20 case .done: String(localized: "Terminé : toutes les étapes sont réglées")21 case .stopped: String(localized: "Arrêté avant la fin")22 default: n.rawValue23 }24 }25 static func leg(_ s: PlanLegState) -> (String, Tone, String) {26 switch s {27 case .pending: (String(localized: "pas encore son tour"), .neutral, "circle")28 case .ready: (String(localized: "prête à préparer"), .warn, "hand.point.up.left.fill")29 case .proposed: (String(localized: "préparée, attend la clé d’accès"), .warn, "person.badge.key.fill")30 case .inFlight: (String(localized: "en cours, pas encore réglée"), .info, "clock.arrow.2.circlepath")31 case .settled: (String(localized: "réglée (lue sur la chaîne)"), .ok, "checkmark.circle.fill")32 default: (s.rawValue, .neutral, "questionmark.circle")33 }34 }35 static func kind(_ k: String) -> String {36 switch k {37 case "swap": String(localized: "Échange")38 case "bridge": String(localized: "Transfert USDC (CCTP)")39 case "xswap": String(localized: "Échange natif (THORChain)")40 default: k41 }42 }43 static func legTitle(kind k: String, via: String?, from: SwapAsset, to: SwapAsset) -> String {44 let a = from.symbol + " (" + (from.networkName ?? from.network) + ")", b = to.symbol + " (" + (to.networkName ?? to.network) + ")"45 return kind(k) + (via.map { " · " + $0 } ?? "") + " : " + a + " → " + b46 }47}4849@MainActor @Observable50final class PlanModel {51 var plan: PlanView?52 var loadError: Error?53 var busy = false54 var error: Error?55 var cleanup: OperationCleanup.Result?56 var serverLacksIntent = false57 var legStart: OperationStart?5859 func refresh(_ env: AppEnvironment, id: String) async {60 do { plan = try await PlanAPI(env.client).plan(id); loadError = nil } catch { if plan == nil { loadError = error } }61 }6263 /** Prepare the current leg ON REQUEST and verify it against the plan as displayed. Nothing is signed here. */64 func prepareLeg(_ env: AppEnvironment, accounts: Accounts?) async {65 guard !busy, !serverLacksIntent, let displayed = plan, let accounts else { return }66 busy = true; error = nil; cleanup = nil67 defer { busy = false }68 let api = PlanAPI(env.client)69 do {70 let r = try await api.prepareLeg(of: displayed, accounts: accounts, minimumOutput: .asPrepared)71 plan = r.plan72 if let op = r.operation { legStart = op.approvable.map { .review($0) } ?? .tracking(proposalId: op.proposal.id) }73 } catch {74 self.error = error75 if SwapLogic.classify(error) == .serverLacksIntent { serverLacksIntent = true }76 // whatever the server did, show the plan as it is now — and withdraw a proposal the app refused to approve77 if let fresh = try? await api.plan(displayed.id) {78 plan = fresh79 if SwapLogic.leavesPendingProposal(error), let p = fresh.proposal, p.state == .pendingApproval {80 cleanup = (try? await api.reject(p.id)) != nil ? .withdrawn(1) : .failed81 if let again = try? await api.plan(displayed.id) { plan = again }82 } else if SwapLogic.leavesPendingProposal(error) { cleanup = .nothingPending }83 }84 }85 }8687 func run(_ env: AppEnvironment, _ action: @escaping @MainActor (PlanAPI, String) async throws -> PlanView) async {88 guard !busy, let id = plan?.id else { return }89 busy = true; error = nil; cleanup = nil90 defer { busy = false }91 do { plan = try await action(PlanAPI(env.client), id) } catch { self.error = error }92 }93}9495struct PlanSheet: View {96 @Environment(AppModel.self) private var model97 @Environment(\.dismiss) private var dismiss98 let planId: String99 @State private var pm = PlanModel()100 @State private var confirmStop = false101102 var body: some View {103 @Bindable var pm = pm104 NavigationStack {105 ScrollView {106 VStack(alignment: .leading, spacing: Theme.Space.section) {107 if !model.canOperate { Notice(tone: .warn, title: String(localized: "Plan en lecture seule hors ligne")) }108 if let p = pm.plan { content(p) }109 else if let e = pm.loadError { ErrorNotice(error: e) { Task { await pm.refresh(model.env, id: planId) } } }110 else { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) }111 }112 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)113 .frame(maxWidth: 620).frame(maxWidth: .infinity)114 }115 .spPage()116 .navigationTitle(String(localized: "Plan en plusieurs étapes")).navigationBarTitleDisplayMode(.inline)117 .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Fermer")) { dismiss() }.accessibilityIdentifier("plan.close") } }118 .task(id: planId) {119 while !Task.isCancelled {120 if pm.legStart == nil, !pm.busy { await pm.refresh(model.env, id: planId) }121 if let p = pm.plan, !p.isOpen { break }122 try? await Task.sleep(for: .seconds(5))123 }124 }125 .sheet(item: $pm.legStart, onDismiss: { Task { await pm.refresh(model.env, id: planId) } }) { OperationSheet(start: $0).wallet(model) }126 .confirmationDialog(String(localized: "Arrêter ce plan ?"), isPresented: $confirmStop, titleVisibility: .visible) {127 Button(String(localized: "Arrêter le plan"), role: .destructive) { Task { await pm.run(model.env) { try await $0.stop($1) } } }128 Button(String(localized: "Continuer"), role: .cancel) {}129 } message: { Text(String(localized: "Définitif. Les fonds restent où ils sont, comme un solde ordinaire. Une demande d’approbation non utilisée est retirée.")) }130 }131 }132133 @ViewBuilder private func content(_ p: PlanView) -> some View {134 VStack(alignment: .leading, spacing: 6) {135 Text(String(localized: "\(Money.exact(p.amountInDisplay)) \(p.from.symbol) → \(p.to.symbol)")).font(.system(size: 26, weight: .semibold)).tracking(-0.4).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)136 HStack(spacing: 8) {137 Image(systemName: p.isComplete ? "checkmark.circle.fill" : p.state == .stopped ? "stop.circle.fill" : p.state == .paused ? "pause.circle.fill" : "clock.arrow.2.circlepath")138 .foregroundStyle(p.isComplete ? Theme.emerald : p.state == .stopped || p.state == .paused ? Theme.warn : Theme.blue)139 Text(PlanText.next(p.next)).font(.spHeadline).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)140 }141 .accessibilityElement(children: .combine).accessibilityIdentifier("plan.next")142 Text(String(localized: "Étape \(min(p.current + 1, p.steps)) sur \(p.steps) · une approbation par étape · rien n’avance sans toi")).font(.spFootnote).foregroundStyle(Theme.mute)143 }144145 VStack(alignment: .leading, spacing: 0) {146 FieldRow(label: String(localized: "Où sont les fonds du plan maintenant (ton adresse, solde ordinaire)"), value: Money.exact(p.holding.amountDisplay) + " " + p.holding.symbol + " · " + (p.holding.networkName ?? p.holding.network))147 Divider(); FieldRow(label: String(localized: "Prévu au départ — attendu / pire cas"), value: Money.exact(p.plannedExpectedDisplay) + " / " + Money.exact(p.plannedWorstDisplay) + " " + p.to.symbol)148 if let e = p.estimate { Divider(); FieldRow(label: String(localized: "Estimation actuelle — attendu / pire cas"), value: Money.exact(e.expectedOutDisplay) + " / " + Money.exact(e.worstOutDisplay) + " " + p.to.symbol) }149 if let f = p.floorDisplay { Divider(); FieldRow(label: String(localized: "Ton plancher global"), value: Money.exact(f) + " " + p.to.symbol) }150 if let s = p.slippageBps { Divider(); FieldRow(label: String(localized: "Tolérance par étape"), value: SwapLogic.slippageLabel(s)) }151 Divider()152 if let r = p.receivedDisplay, p.isComplete {153 FieldRow(label: String(localized: "Reçu au final (lu sur la chaîne)"), value: Money.exact(r) + " " + p.to.symbol, tone: .ok).accessibilityIdentifier("plan.received")154 } else {155 FieldRow(label: String(localized: "Reçu au final"), value: p.state == .stopped ? String(localized: "Rien : le plan a été arrêté avant la dernière étape") : String(localized: "Pas encore : la dernière étape n’est pas réglée"), tone: .neutral)156 }157 }.spCard(padding: 16)158159 if let pause = p.pause {160 Notice(tone: .warn, title: String(localized: "Plan en pause à l’étape \(pause.leg + 1) (\(pause.code))"), message: pause.message).accessibilityIdentifier("plan.pause")161 }162163 VStack(alignment: .leading, spacing: 0) {164 Text(String(localized: "Étapes")).spEyebrow().padding(.bottom, 6)165 ForEach(p.legs) { leg in166 if leg.index > 0 { Divider() }167 legRow(leg, current: leg.index == p.current && p.isOpen)168 }169 }.spCard(padding: 16)170171 if let e = pm.error { PrepareRefusalNotice(error: e, cleanup: pm.cleanup) }172 else if pm.serverLacksIntent { Notice(tone: .warn, title: SwapLogic.missingIntentTitle, message: SwapLogic.missingIntentMessage).accessibilityIdentifier("op.unsupported") }173174 actions(p)175176 if p.next == .wait, let id = p.currentLeg?.proposalId {177 Text(String(localized: "Suivi de l’étape en cours")).font(.spHeadline)178 OperationTracker(proposalId: id)179 }180 }181182 private func legRow(_ leg: PlanView.Leg, current: Bool) -> some View {183 let (text, tone, symbol) = PlanText.leg(leg.state)184 return VStack(alignment: .leading, spacing: 4) {185 HStack(alignment: .firstTextBaseline, spacing: 8) {186 Image(systemName: symbol).foregroundStyle(tone.color).font(.system(size: 14, weight: .semibold))187 Text("\(leg.index + 1). " + PlanText.legTitle(kind: leg.kind, via: leg.label ?? leg.via, from: leg.from, to: leg.to)).font(.spBody.weight(current ? .semibold : .medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)188 }189 Text(text).font(.spFootnote.weight(.semibold)).foregroundStyle(tone.color)190 Text(String(localized: "Prévu : \(Money.brief(leg.planned.expectedInDisplay)) \(leg.from.symbol) → attendu \(Money.brief(leg.planned.expectedOutDisplay)), pire cas \(Money.brief(leg.planned.worstOutDisplay)) \(leg.to.symbol)")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)191 if leg.actual.inDisplay != nil || leg.actual.outDisplay != nil {192 Text(String(localized: "Réel : \(leg.actual.inDisplay.map { Money.exact($0) + " " + leg.from.symbol } ?? "—") → \(leg.actual.outDisplay.map { Money.exact($0) + " " + leg.to.symbol } ?? String(localized: "pas encore lu"))")).font(.spFootnote.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)193 }194 ForEach(Array(leg.attempts.enumerated()), id: \.offset) { _, a in195 if let o = a.outcome, o != "settled" {196 Text(String(localized: "Tentative : \(o)") + (a.error.map { " — " + $0 } ?? "") + (a.errorCode.map { " (\($0))" } ?? "")).font(.spFootnote).foregroundStyle(o == "refunded" ? Theme.warn : Theme.danger).fixedSize(horizontal: false, vertical: true)197 }198 }199 }200 .padding(.vertical, 8)201 }202203 @ViewBuilder private func actions(_ p: PlanView) -> some View {204 let can = model.canOperate && !pm.busy205 if p.next == .prepare || p.next == .approve {206 if p.next == .approve {207 Text(String(localized: "Une demande d’approbation existe déjà pour cette étape mais cette session ne l’a pas vérifiée. La préparer de nouveau retire l’ancienne et en vérifie une fraîche.")).font(.spFootnote).foregroundStyle(Theme.mute)208 }209 Button { Task { await pm.prepareLeg(model.env, accounts: model.accounts.value) } } label: { HStack { if pm.busy { ProgressView().tint(Theme.onPrimary) }; Text(p.current == 0 ? String(localized: "Préparer la première étape") : String(localized: "Préparer l’étape suivante")) } }210 .buttonStyle(.spPrimary).disabled(!can || pm.serverLacksIntent || model.accounts.value == nil).accessibilityIdentifier("plan.prepareLeg")211 Text(String(localized: "La préparation ne signe rien. Tu vérifieras ensuite l’opération exacte de cette étape (son propre minimum) avant de l’approuver avec ta clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute)212 }213 if p.state == .paused {214 Button(String(localized: "Réessayer la même étape")) { Task { await pm.run(model.env) { try await $0.retry($1) } } }.buttonStyle(.spSecondary).disabled(!can).accessibilityIdentifier("plan.retry")215 Button(String(localized: "Replanifier depuis l’actif détenu")) { Task { await pm.run(model.env) { try await $0.replan($1) } } }.buttonStyle(.spSecondary).disabled(!can).accessibilityIdentifier("plan.replan")216 Text(String(localized: "Réessayer et replanifier ne signent rien : l’étape redevient simplement « prête »." )).font(.spFootnote).foregroundStyle(Theme.mute)217 }218 if p.isOpen {219 Button(String(localized: "Arrêter le plan ici")) { confirmStop = true }.buttonStyle(.spSecondary).disabled(!can).accessibilityIdentifier("plan.stop")220 if p.next == .wait { Text(String(localized: "Une étape déjà diffusée ne peut pas être rappelée : le serveur refuse l’arrêt tant qu’elle n’est pas réglée ou échouée, et le dit.")).font(.spFootnote).foregroundStyle(Theme.mute) }221 }222 }223}224