Repository Public
1// SP Wallet iOS2// File: Features/Swap/OperationFlow.swift3// Description: What a same-network swap, a CCTP transfer, a THORChain swap and a plan leg share once the Core has VERIFIED the4// prepared operation: the review sheet built on `IntentReview` (every row read from the intent whose hash is the5// challenge), the passkey approval, the refusal, and the hand-over to the tracker. Also the withdrawal of the6// pending proposal a refused preparation leaves on the server, so that nothing dangles.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213/** What the operation sheet opens on. */14enum OperationStart: Identifiable {15 /** A verified operation to review and approve. */16 case review(ApprovableOperation, shown: ShownMinimum? = nil)17 /** An operation that already left the review (approved earlier, or resumed from the list): follow it. */18 case tracking(proposalId: String)19 var id: String {20 switch self { case .review(let op, _): "review-" + op.proposal.id; case .tracking(let id): "track-" + id }21 }22}2324/** The guaranteed minimum the owner saw on the quote, kept so that the review can say when the firm minimum is lower. */25struct ShownMinimum: Equatable {26 let units: String27 let display: String28 let symbol: String29 /** True when the firm minimum of the intent is BELOW what the quote displayed. Unreadable figures count as lower. */30 func isAbove(intentMinimum: String) -> Bool {31 guard let shown = try? BaseUnits(units), let firm = try? BaseUnits(intentMinimum) else { return true }32 return firm < shown33 }34}3536enum OperationCleanup {37 enum Result: Equatable {38 /** The proposal(s) the refused preparation created were withdrawn. */39 case withdrawn(Int)40 /** Nothing matching is pending on the server. */41 case nothingPending42 /** The pending list could not be read or the withdrawal was refused: the owner must refuse it from Activity. */43 case failed44 }4546 /** Find the pending proposal a refused preparation created (it is not returned by the Core's error) and withdraw it. */47 @MainActor static func withdraw(_ env: AppEnvironment, kind: String, network: String, asset: String, amountUnits: String?, since: Date) async -> (result: Result, found: [Proposal]) {48 guard let pending = try? await env.wallet.portfolio().pending else { return (.failed, []) }49 let mine = SwapLogic.leftBehind(in: pending, kind: kind, network: network, asset: asset, amountUnits: amountUnits, since: since)50 guard !mine.isEmpty else { return (.nothingPending, []) }51 var done = 052 for p in mine { if (try? await env.transfers.reject(p.id)) != nil { done += 1 } }53 return (done == mine.count ? .withdrawn(done) : .failed, mine)54 }5556 static func sentence(_ r: Result) -> String {57 switch r {58 case .withdrawn: String(localized: "La proposition créée par cette préparation a été retirée : rien ne reste en attente.")59 case .nothingPending: String(localized: "Aucune proposition n’est restée en attente.")60 case .failed: String(localized: "La proposition créée n’a pas pu être retirée automatiquement : refuse-la depuis Activité, ou laisse-la expirer.")61 }62 }63}6465/** The notice of a preparation that the app refused or that the server could not make approvable. */66struct PrepareRefusalNotice: View {67 let error: Error68 var cleanup: OperationCleanup.Result?69 var body: some View {70 VStack(alignment: .leading, spacing: 10) {71 if SwapLogic.classify(error) == .serverLacksIntent {72 Notice(tone: .warn, title: SwapLogic.missingIntentTitle, message: SwapLogic.missingIntentMessage, icon: "lock.trianglebadge.exclamationmark.fill")73 .accessibilityIdentifier("op.unsupported")74 } else {75 ErrorNotice(error: error).accessibilityIdentifier("op.error")76 }77 if let cleanup { Text(OperationCleanup.sentence(cleanup)).font(.spFootnote).foregroundStyle(cleanup == .failed ? Theme.danger : Theme.mute).accessibilityIdentifier("op.cleanup") }78 }79 }80}8182@MainActor @Observable83final class OperationModel {84 enum Step: Equatable { case review, tracking }85 var step: Step86 var op: ApprovableOperation?87 var trackedId: String?88 var busy = false89 var error: Error?90 var shown: ShownMinimum?9192 init(_ start: OperationStart) {93 switch start {94 case .review(let op, let shown): self.op = op; self.shown = shown; step = .review95 case .tracking(let id): trackedId = id; step = .tracking96 }97 }9899 func approve(_ env: AppEnvironment) async {100 guard let op, !busy else { return }101 busy = true; error = nil102 defer { busy = false }103 let api = SwapAPI(env.client)104 do {105 let p = try await api.approve(op, with: env.passkeys)106 trackedId = p.id; step = .tracking107 } catch PasskeyError.cancelled {108 // dismissed: nothing signed; the proposal stays pending and can be approved or refused109 } catch let e as APIError where e.isOffline {110 // the answer was lost after the assertion left: read the real state, never sign twice111 if let p = try? await api.proposal(op.proposal.id), p.state != .pendingApproval { trackedId = p.id; step = .tracking } else { error = e }112 } catch { self.error = error }113 }114115 /** Withdraw the proposal. Returns false when the server could not be told (the proposal then expires by itself). */116 func reject(_ env: AppEnvironment) async -> Bool {117 guard let op else { return true }118 busy = true119 defer { busy = false }120 do { _ = try await SwapAPI(env.client).reject(op.proposal.id); return true } catch { self.error = error; return false }121 }122}123124/** Review → passkey → tracking, for any operation of this area. */125struct OperationSheet: View {126 @Environment(AppModel.self) private var model127 @Environment(\.dismiss) private var dismiss128 @State private var flow: OperationModel129 @State private var confirmCancel = false130131 init(start: OperationStart) { _flow = State(initialValue: OperationModel(start)) }132133 var body: some View {134 NavigationStack {135 ScrollView {136 VStack(alignment: .leading, spacing: Theme.Space.section) {137 if !model.canOperate { Notice(tone: .warn, title: String(localized: "Opération indisponible hors ligne"), message: String(localized: "Une approbation exige le serveur, le signataire isolé et ta clé d’accès.")) }138 switch flow.step {139 case .review: review140 case .tracking: tracking141 }142 }143 .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)144 .frame(maxWidth: 620).frame(maxWidth: .infinity)145 }146 .spPage()147 .navigationTitle(flow.step == .review ? String(localized: "Vérifier et approuver") : String(localized: "Suivi de l’opération")).navigationBarTitleDisplayMode(.inline)148 .toolbar {149 ToolbarItem(placement: .cancellationAction) {150 Button(flow.step == .tracking ? String(localized: "Fermer") : String(localized: "Annuler")) {151 if flow.step == .review { confirmCancel = true } else { dismiss() }152 }.accessibilityIdentifier("op.close")153 }154 }155 .confirmationDialog(String(localized: "Refuser cette opération ?"), isPresented: $confirmCancel, titleVisibility: .visible) {156 Button(String(localized: "Refuser et fermer"), role: .destructive) { Task { if await flow.reject(model.env) { dismiss() } } }157 Button(String(localized: "Continuer la revue"), role: .cancel) {}158 } message: { Text(String(localized: "Rien n’a été signé. La proposition sera marquée refusée.")) }159 }160 .interactiveDismissDisabled(flow.step == .review || flow.busy)161 }162163 @ViewBuilder private var review: some View {164 if let op = flow.op {165 IntentReview(intent: op.intent, digest: op.approval.digest, warnings: op.proposal.warnings ?? [],166 extra: SwapLogic.reviewRows(op.intent, networks: model.networks.value ?? []).map(\.tuple))167 if let shown = flow.shown, let min = op.intent.swap?.minOut ?? op.intent.xswap?.minOut, shown.isAbove(intentMinimum: min) {168 Notice(tone: .warn, title: String(localized: "Minimum garanti inférieur à celui de la cotation"),169 message: String(localized: "La cotation affichait un minimum de \(Money.exact(shown.display)) \(shown.symbol). Cette préparation ferme garantit moins : le « Minimum reçu garanti » ci-dessus est le seul chiffre que ta clé d’accès approuve. Refuse si ce n’est pas acceptable."))170 .accessibilityIdentifier("op.lowerMinimum")171 }172 ServerPreparationFacts(proposal: op.proposal)173 if let e = flow.error { ErrorNotice(error: e).accessibilityIdentifier("op.error") }174 TimelineView(.periodic(from: .now, by: 1)) { ctx in175 let expired = op.intent.expiry <= ctx.date176 VStack(spacing: 10) {177 if expired {178 Notice(tone: .warn, title: String(localized: "Fenêtre d’approbation expirée"), message: String(localized: "Refuse cette proposition puis demande une nouvelle cotation : un prix ancien n’est jamais approuvé."))179 } else {180 Button { Task { await flow.approve(model.env) } } label: { HStack { if flow.busy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Approuver avec la clé d’accès")) } }181 .buttonStyle(.spPrimary).disabled(flow.busy || !model.canOperate).accessibilityIdentifier("op.approve")182 }183 Button(String(localized: "Refuser")) { Task { if await flow.reject(model.env) { dismiss() } } }.buttonStyle(.spSecondary).disabled(flow.busy).accessibilityIdentifier("op.reject")184 }185 }186 }187 }188189 @ViewBuilder private var tracking: some View {190 if let id = flow.trackedId {191 OperationTracker(proposalId: id)192 Button(String(localized: "Fermer (le suivi continue sur le serveur)")) { dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("op.done")193 }194 }195}196197/**198 Figures of the server's preparation that are NOT part of the signed intent (estimate, simulation, expected output): shown apart199 and labelled as such, so that they are never mistaken for what the passkey guarantees.200 */201struct ServerPreparationFacts: View {202 let proposal: Proposal203 var body: some View {204 let swap = try? proposal.swapSection()205 let bridge = try? proposal.bridgeSection()206 let xswap = try? proposal.xswapSection()207 let quote = try? proposal.quoteRecord()208 VStack(alignment: .leading, spacing: 0) {209 Text(String(localized: "Indications du serveur (hors empreinte signée)")).spEyebrow().padding(.bottom, 6)210 if let s = swap {211 FieldRow(label: String(localized: "Sortie attendue (estimation)"), value: Money.exact(s.expectedOutDisplay) + " " + s.toSymbol)212 if let bps = s.slippageBps { Divider(); FieldRow(label: String(localized: "Tolérance de glissement demandée"), value: SwapLogic.slippageLabel(bps)) }213 }214 if let x = xswap {215 if let f = x.outboundFeeDisplay { Divider(); FieldRow(label: String(localized: "Frais de sortie THORChain (déjà déduits)"), value: Money.exact(f) + " " + x.toSymbol) }216 if let f = x.liquidityFeeDisplay { Divider(); FieldRow(label: String(localized: "Frais de liquidité (déjà déduits)"), value: Money.exact(f) + " " + x.toSymbol) }217 Divider(); FieldRow(label: String(localized: "Durée estimée"), value: SwapLogic.duration(x.estimatedSeconds))218 if let n = x.operators?.count { Divider(); FieldRow(label: String(localized: "Opérateurs THORNode ayant confirmé le coffre"), value: String(n)) }219 }220 if let b = bridge {221 Divider(); FieldRow(label: String(localized: "Durée estimée"), value: SwapLogic.duration(b.expectedSeconds))222 if let g = b.destGasNeedDisplay, let sym = b.destGasSymbol { Divider(); FieldRow(label: String(localized: "Frais nécessaires sur la destination (payés par ce portefeuille)"), value: Money.exact(g) + " " + sym) }223 }224 let simulated = swap?.simulated ?? bridge?.simulated ?? xswap?.simulated225 Divider()226 FieldRow(label: String(localized: "Simulation de la transaction par le serveur"),227 value: simulated == true ? String(localized: "Simulée avec succès") : simulated == false ? String(localized: "NON simulée") : String(localized: "Non indiquée"),228 tone: simulated == true ? nil : .warn)229 if let est = proposal.feeDisplay { Divider(); FieldRow(label: String(localized: "Frais de réseau estimés"), value: Money.exact(est) + " " + (proposal.feeSymbol ?? "")) }230 if let q = quote, let shown = q.quotedOutDisplay, let firm = q.firmOutDisplay {231 Divider()232 FieldRow(label: String(localized: "Cotation affichée → préparation ferme"), value: Money.exact(shown) + " → " + Money.exact(firm) + " (" + (q.deviationBps < 0 ? "−" : "+") + SwapLogic.percent(bps: Double(q.deviationBps)) + ")",233 tone: q.deviationBps < 0 ? .warn : nil)234 }235 }236 .spCard(padding: 16)237 }238}239240/** An https link to a block explorer (anything else is not offered). */241struct ExplorerLink: View {242 let url: String?243 var title = String(localized: "Ouvrir dans l’explorateur")244 var body: some View {245 if let url, let u = URL(string: url), u.scheme == "https" {246 Link(destination: u) { Label(title, systemImage: "arrow.up.right.square").font(.spCallout.weight(.semibold)).frame(minHeight: 44) }247 }248 }249}250