Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Swap/SwapSupport.swift3// Description: What the swap, bridge and plan screens share: French wording of the server's codes (execution steps, holds, refusals), the tracker that follows a proposal until the chain — not the client — says it is over, the asset picker fed by the server's swap graph, the review sheet of a verified operation and the unified execution timeline. Nothing here decides a success: every status is read from the proposal.4import SwiftUI5import SPWalletCore67// MARK: - Wording89@MainActor enum SwapText {10 /// The amount as the server parses it: a point as decimal separator, no grouping.11 static func normalize(_ amount: String) -> String {12 amount.trimmingCharacters(in: .whitespaces).replacingOccurrences(of: ",", with: ".").replacingOccurrences(of: "\u{202F}", with: "").replacingOccurrences(of: " ", with: "")13 }1415 static func sameId(_ a: String, _ b: String) -> Bool { a == b || (a.hasPrefix("0x") && b.hasPrefix("0x") && a.lowercased() == b.lowercased()) }1617 static func balance(_ model: AppModel, of a: SwapAsset) -> Balance? {18 model.portfolio?.value.balances.first { $0.network == a.network && sameId($0.asset, a.asset) }19 }2021 /// Base units rendered with the registry's decimals; without them the raw integer is shown as such.22 static func units(_ s: String, decimals: Int?) -> String {23 guard let decimals, let u = try? BaseUnits(s) else { return "\(s) (unités de base)" }24 return Fmt.amount(u.formatted(decimals: decimals))25 }2627 static func assetDef(_ model: AppModel, network: String, asset: String) -> AssetDef? {28 guard let n = model.network(network) else { return nil }29 return asset == "native" ? n.native : n.tokens.first { sameId($0.id, asset) }30 }3132 static func duration(_ s: Double?) -> String {33 guard let s else { return "durée non communiquée" }34 if s < 90 { return "≈ \(max(1, Int(s.rounded()))) s" }35 if s < 5400 { return "≈ \(Int((s / 60).rounded())) min" }36 return "≈ \((s / 3600).formatted(.number.precision(.fractionLength(1)))) h"37 }3839 static func bps(_ b: Double?) -> String {40 guard let b else { return "—" }41 return (b / 100).formatted(.number.precision(.fractionLength(0...2))) + " %"42 }43 static func bps(_ b: Int?) -> String { bps(b.map(Double.init)) }4445 static func usd(_ v: Double?) -> String {46 guard let v else { return "—" }47 return "≈ " + v.formatted(.currency(code: "USD").precision(.fractionLength(abs(v) < 1 && v != 0 ? 4 : 2)))48 }4950 /// Display name of a provider: the server's own name; Jupiter keeps the label its licence requires.51 static func provider(_ id: String, providers: SwapProviders?, execution: SwapExecutionInfo? = nil) -> String {52 if let s = execution?.solana, s.provider == id { return s.label }53 return providers?.providers.first { $0.id == id }?.name ?? id54 }5556 static func execState(_ s: ExecState) -> String {57 switch s {58 case .pending: "En attente"59 case .awaitingApproval: "En attente d’approbation"60 case .signing: "Signature en cours"61 case .broadcast: "Diffusée, non confirmée"62 case .confirming: "En cours de confirmation"63 case .confirmed: "Confirmée"64 case .failed: "Échouée"65 case .refunded: "Remboursée"66 case .unknown: "État inconnu"67 default: s.rawValue68 }69 }7071 static func stepKind(_ k: String) -> String {72 switch k {73 case "approval": "Autorisation de dépense (ERC-20)"74 case "send": "Envoi"75 case "swap": "Échange"76 case "burn": "Destruction (burn) sur le réseau source"77 case "attestation": "Attestation de Circle"78 case "mint": "Émission (mint) sur le réseau de destination"79 case "deposit": "Dépôt au coffre THORChain"80 case "observation": "Observation du dépôt par THORChain"81 case "outbound": "Paiement sortant vers ce portefeuille"82 case "order": "Ordre"83 default: k84 }85 }8687 static func bridgeStage(_ s: BridgeStage) -> String {88 switch s {89 case .review: "En attente d’approbation"90 case .burning: "Destruction (burn) en cours sur le réseau source"91 case .attesting: "Brûlé sur la source — attestation de Circle en attente"92 case .ready: "Attesté — émission sur la destination à lancer"93 case .minting: "Émission (mint) diffusée sur la destination, non confirmée"94 case .mintFailed: "Émission échouée — nouvelle signature requise (passkey)"95 case .done: "Reçu sur le réseau de destination"96 case .failed: "Échoué avant la destruction : rien n’a quitté le réseau source"97 default: s.rawValue98 }99 }100101 static func xswapStage(_ s: XSwapStage) -> String {102 switch s {103 case .review: "En attente d’approbation"104 case .sending: "Dépôt en cours d’envoi au coffre"105 case .sent: "Dépôt diffusé — pas encore observé par THORChain"106 case .observed: "Dépôt observé par THORChain — échange en cours"107 case .outbound: "Paiement sortant annoncé — pas encore vu par ce portefeuille"108 case .received: "Reçu sur le réseau de destination"109 case .refunded: "Remboursé par THORChain : l’échange n’a pas eu lieu"110 case .failed: "Échoué"111 default: s.rawValue112 }113 }114115 /// Why an operation is waiting. The server's own detail sentence is shown next to it, untouched.116 static func hold(_ code: String) -> String {117 switch code {118 case "destination_busy": "Une autre transaction est en vol sur le réseau de destination."119 case "destination_pending": "Une transaction précédente est encore en attente sur le réseau de destination."120 case "mint_would_fail": "L’émission échouerait maintenant sur la destination ; elle n’a pas été envoyée."121 case "fee_above_policy": "Les frais de réseau sur la destination dépassent le plafond du signataire pour l’instant."122 case "destination_gas": "Il manque de la monnaie native sur la destination pour payer l’émission."123 case "attestation_late": "Circle n’a pas encore attesté la destruction. Les fonds ne sont pas perdus : l’émission reste possible dès que l’attestation arrive."124 case "message_mismatch": "La réponse de Circle ne décrit pas le transfert approuvé ; elle n’a pas été utilisée."125 case "attestation_expired": "L’attestation rapide a expiré ; une nouvelle a été demandée à Circle."126 case "mint_reverted": "La transaction d’émission a été annulée (revert) sur la destination ; les USDC attendent toujours. Approuvez une nouvelle tentative avec la passkey."127 case "mint_replaced": "Une autre transaction a pris la place de l’émission ; les USDC attendent toujours. Approuvez une nouvelle tentative avec la passkey."128 case "mint_expired": "L’émission n’a pas été incluse à temps ; les USDC attendent toujours. Approuvez une nouvelle tentative avec la passkey."129 case "vault_churned": "Le coffre n’est plus confirmé comme actif et le dépôt n’est pas encore confirmé. Il ne peut pas être annulé ; THORChain surveille encore un coffre sortant, sans garantie."130 case "not_observed": "THORChain n’a pas encore signalé ce dépôt. Rien n’est marqué comme reçu tant que le portefeuille ne voit pas lui-même le paiement sortant."131 case "outbound_late": "THORChain a observé le dépôt mais n’a pas encore envoyé le paiement sortant."132 case "outbound_mismatch": "Le paiement sortant annoncé par THORChain ne paie pas à ce portefeuille ce qui était attendu ; il n’est pas compté comme reçu."133 case "below_minimum": "Le montant reçu est inférieur au minimum approuvé."134 case "outbound_not_seen": "THORChain annonce un paiement sortant que les sources de données du portefeuille ne voient pas encore confirmé."135 default: "En attente (\(code))."136 }137 }138139 /// Why the wallet does not execute a quoted route (`RouteCard.reasonCode` / `executability`).140 static func notExecutable(_ r: SwapRoute) -> String {141 let code = r.card?.reasonCode ?? r.executability?.code ?? r.executability?.class142 switch code {143 case "quote_only": return "Comparaison de prix seulement : ce fournisseur ne fournit qu’une cotation."144 case "opaque", "opaque_transaction": return "Comparaison seulement : la transaction de ce fournisseur est opaque, le signataire ne peut pas en vérifier le destinataire ni le minimum."145 case "not_executable": return "Comparaison seulement : ce portefeuille n’exécute pas cette route."146 case nil: return "Comparaison seulement."147 case let c?: return "Comparaison seulement (\(c))" + (r.executability?.reason.map { " — \($0)" } ?? "")148 }149 }150151 static func providerAnswer(_ a: SwapProviderAnswer) -> String {152 switch (a.status, a.code) {153 case ("no_route", _): "aucune route"154 case ("skipped", "not_configured"): "non interrogé (clé d’API non configurée sur le serveur)"155 case ("skipped", "disabled"): "non interrogé (désactivé)"156 case ("skipped", let c): "non interrogé" + (c.map { " (\($0))" } ?? "")157 case ("error", "timeout"): "délai dépassé"158 case ("error", "rate_limited"): "limite de débit atteinte"159 case ("error", "invalid_quote"): "cotation invalide, écartée"160 case ("error", let c): "erreur" + (c.map { " (\($0))" } ?? "")161 default: a.status + (a.code.map { " (\($0))" } ?? "")162 }163 }164165 static func risk(_ l: RiskLevel?) -> String {166 switch l { case .some(.low): "faible"; case .some(.medium): "moyen"; case .some(.high): "élevé"; case .some(let o): o.rawValue; case nil: "—" }167 }168169 private static let explanations: [String: String] = [170 "policy": "Refus du signataire isolé : l’opération dépasse une de ses limites (par transfert, par jour ou plafond de frais). Les limites se règlent sur la machine du signataire, pas depuis cette app.",171 "vault_unconfirmed": "Échec fermé : le coffre THORChain doit être confirmé à l’unanimité par au moins trois opérateurs THORNode indépendants. Un seul désaccord, ou moins de trois réponses, et rien n’est préparé.",172 "provider_unavailable": "Échec fermé : sans réponse des opérateurs ou du fournisseur, rien n’est préparé plutôt que d’agir à l’aveugle.",173 "chain_halted": "THORChain signale ce réseau arrêté ou en pause ; rien n’a été préparé.",174 "router_changed": "Le code du contrat sur la chaîne n’est plus celui qui a été revu ; l’opération est refusée.",175 "account_has_code": "L’adresse du portefeuille porte du code (délégation) ; l’opération est refusée.",176 "below_minimum": "Sous le minimum du protocole, un remboursement ne pourrait pas payer ses propres frais.",177 "insufficient_gas": "Ajoutez de la monnaie native sur ce réseau pour payer les frais.",178 "insufficient_funds": "Le solde lu sur la chaîne ne couvre pas le montant.",179 "token_account_missing": "Rien n’a été brûlé : ouvrez d’abord le compte de jetons USDC sur Solana, puis recommencez.",180 "fast_unavailable": "Utilisez la vitesse Standard.",181 "quote_mismatch": "La cotation affichée ne correspond plus à la demande ; les cotations sont rafraîchies.",182 "quote_not_executable": "La route affichée n’est pas exécutable par ce portefeuille.",183 "swap_not_enabled": "L’exécution d’échanges n’est pas activée sur ce réseau.",184 "xswap_not_enabled": "Cette paire n’est pas échangeable nativement par ce portefeuille.",185 "bridge_not_enabled": "Le transfert CCTP n’est pas activé entre ces réseaux.",186 "too_many_streams": "Fermez une recherche de cotations en cours ou patientez.",187 "reclaim_not_yet": "Le programme de Circle ne libère ce dépôt que cinq jours après la destruction, une fois celle-ci attestée.",188 "plan_open": "Un seul parcours peut être ouvert à la fois : terminez-le ou arrêtez-le (les fonds restent où ils sont).",189 "plan_not_startable": "Corrigez les points bloquants indiqués sur le parcours.",190 "floor_above_estimate": "Baissez le plancher ou retirez-le.",191 "rpc_degraded": "La chaîne n’a pas pu être lue de façon fiable ; rien n’a été préparé.",192 "provider_bad_answer": "La réponse du fournisseur a été refusée par les vérifications du serveur ; rien n’a été préparé.",193 ]194195 /// `model.describe` plus what the refusal means in this domain. A moved quote carries its fresh figures.196 static func describe(_ error: Error, model: AppModel) -> String {197 if let m = error as? QuoteMoved {198 return "Le prix a bougé depuis la cotation affichée : la sortie ferme serait de \(Fmt.amount(m.fresh.amountOutDisplay, maxFraction: 8)) \(m.fresh.symbol ?? ""), sous le minimum affiché (\(Fmt.amount(m.quoted.minAmountOutDisplay, maxFraction: 8))). Rien n’a été préparé ; demandez une nouvelle cotation."199 }200 if case ApprovalError.inconsistent("minimum output below the minimum displayed")? = error as? ApprovalError {201 return "Refusé par l’app : le minimum garanti de la route ferme est inférieur au minimum de la cotation affichée. Rien n’a été signé ; la demande préparée sur le serveur expire seule. Une nouvelle cotation est demandée."202 }203 let base = model.describe(error)204 if let e = error as? APIError, let more = explanations[e.code] { return "\(base)\n\(more)" }205 return base206 }207208 /// True when this server signs without relaying (test stack): every figure and button says so.209 static func isSimulatedServer(_ model: AppModel) -> Bool { model.security?.value.broadcast == false }210211 static func ownAddresses(_ model: AppModel) -> [String: String] {212 Dictionary((model.accounts?.value.accounts ?? []).map { ($0.network, $0.address) }, uniquingKeysWith: { a, _ in a })213 }214}215216// MARK: - Tracking217218/// Follows one proposal (swap, CCTP transfer, THORChain swap) by reading it. `completion` is the Core's answer to "is it done?":219/// for a cross-chain operation only the destination's confirmation counts.220@MainActor @Observable final class OperationTracker {221 let model: AppModel222 private(set) var proposal: Proposal223 private(set) var history: [(Date, String)] = []224 private(set) var readError: String?225 private var notified = false226 private var receiptReads = 0227228 init(model: AppModel, proposal: Proposal) {229 self.model = model; self.proposal = proposal230 history = [(Date(), Self.label(proposal))]231 if isSettled { notified = true }232 }233234 /// nil when the proposal's own section cannot be read: shown as unreadable, never guessed.235 var completion: OperationCompletion? { try? proposal.swapCompletion() }236237 var isSettled: Bool {238 switch completion {239 case .complete, .refunded, .failed: true240 case .notStarted, .inProgress: false241 case nil: proposal.state.isFailure || proposal.state == .notBroadcast242 }243 }244245 /// A same-network swap is final before its received amount has been read from the router's event: keep reading a little.246 private var awaitsReceipt: Bool {247 guard proposal.kind == "swap", completion == .complete, receiptReads < 10 else { return false }248 return (try? proposal.swapSection())??.received == nil249 }250251 static func label(_ p: Proposal) -> String {252 var s = ErrorText.state(p.state)253 if p.kind == "bridge", let b = try? p.bridgeSection() { s += " · " + SwapText.bridgeStage(b.stage) }254 if p.kind == "xswap", let x = try? p.xswapSection() { s += " · " + SwapText.xswapStage(x.stage) }255 return s256 }257258 func update(_ p: Proposal) {259 guard p.id == proposal.id else { return }260 let l = Self.label(p)261 if l != history.last?.1 { history.append((Date(), l)) }262 proposal = p263 if isSettled, !notified {264 notified = true265 announce()266 Task { await model.refreshAll() }267 }268 }269270 private func announce() {271 let p = proposal, what = "\(Fmt.amount(p.amountDisplay, maxFraction: 8)) \(p.symbol) · \(p.networkName ?? p.network)"272 let title: String273 switch completion {274 case .complete: title = p.kind == "bridge" ? "Transfert inter-chaînes reçu sur la destination" : p.kind == "xswap" ? "Échange inter-chaînes reçu" : "Échange finalisé"275 case .refunded: title = "Échange remboursé par THORChain"276 default: title = p.state == .notBroadcast ? "Signée, NON diffusée (serveur de test)" : "Opération : \(ErrorText.state(p.state))"277 }278 Notifier.post(title: title, body: what + (p.error.map { " — \($0)" } ?? ""), id: "op-\(p.id)")279 }280281 private var interval: Double {282 if proposal.kind == "bridge", let b = try? proposal.bridgeSection(), b.needsPasskey == true { return 20 }283 switch proposal.state {284 case .approved, .signed: return 2285 case .broadcast, .confirming, .reorged: return 4286 default: return proposal.kind == "swap" ? 3 : 8287 }288 }289290 /// Reads the proposal until the operation is settled or the calling task is cancelled (the view's `.task`).291 func follow() async {292 while !Task.isCancelled {293 if isSettled, !awaitsReceipt { return }294 try? await Task.sleep(for: .seconds(interval))295 guard !Task.isCancelled else { return }296 guard AppActivity.isActive, model.phase == .signedIn else { continue }297 if isSettled { receiptReads += 1 }298 do { update(try await TransfersAPI(model.client).proposal(proposal.id)); readError = nil }299 catch { readError = model.describe(error) }300 }301 }302}303304// MARK: - Shared views305306struct SafeLink: View {307 let title: String; let url: String?308 var body: some View {309 if let url, let u = URL(string: url), u.scheme == "https" { Link(title, destination: u).font(.callout) }310 }311}312313/// A transaction identifier: full, selectable, with its explorer link when the server gives an https one.314struct TxField: View {315 let label: String; let txid: String?; var explorer: String?; var state: String?316 var body: some View {317 if let txid {318 VStack(alignment: .leading, spacing: 2) {319 Field(label: label, value: txid + (state.map { " · \($0)" } ?? ""), mono: true)320 HStack { Spacer().frame(width: 182); SafeLink(title: "Ouvrir dans l’explorateur de blocs", url: explorer) }321 }322 }323 }324}325326/// Asset choice among the server's swap graph (never a hard-coded list): search, held assets first.327struct SwapAssetPicker: View {328 let model: AppModel329 let label: String330 let assets: [SwapAsset]331 @Binding var selection: String332 var exclude: String?333 @State private var open = false334 @State private var query = ""335336 private var chosen: SwapAsset? { assets.first { $0.key == selection } }337 private var rows: [SwapAsset] {338 let q = query.trimmingCharacters(in: .whitespaces).lowercased()339 func held(_ a: SwapAsset) -> Bool { SwapText.balance(model, of: a)?.isNonZero == true }340 return assets.filter { a in341 a.key != exclude && (q.isEmpty || a.symbol.lowercased().contains(q) || (a.name ?? "").lowercased().contains(q) || (a.networkName ?? a.network).lowercased().contains(q) || a.asset.lowercased() == q)342 }.sorted { a, b in343 let ha = held(a), hb = held(b)344 if ha != hb { return ha }345 if (a.native == true) != (b.native == true) { return a.native == true }346 return a.symbol == b.symbol ? a.network < b.network : a.symbol < b.symbol347 }348 }349350 var body: some View {351 Button { open = true } label: {352 HStack(spacing: 10) {353 if let c = chosen {354 AssetBadge(symbol: c.symbol)355 VStack(alignment: .leading, spacing: 1) {356 Text(c.symbol).fontWeight(.semibold)357 Text(c.networkName ?? c.network).font(.caption).foregroundStyle(.secondary)358 }359 } else { Text("Choisir un actif…").foregroundStyle(.secondary) }360 Spacer()361 Image(systemName: "chevron.up.chevron.down").foregroundStyle(.secondary)362 }363 .padding(10).frame(maxWidth: .infinity, alignment: .leading)364 .background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))365 .contentShape(Rectangle())366 }367 .buttonStyle(.plain)368 .accessibilityLabel("\(label) : \(chosen.map { "\($0.symbol) sur \($0.networkName ?? $0.network)" } ?? "aucun actif choisi")")369 .popover(isPresented: $open, arrowEdge: .bottom) {370 VStack(spacing: 0) {371 TextField("Rechercher (symbole, nom, réseau, contrat)", text: $query).textFieldStyle(.roundedBorder).padding(10)372 Divider()373 List(rows) { a in374 Button { selection = a.key; open = false; query = "" } label: { row(a) }.buttonStyle(.plain)375 }376 .listStyle(.plain)377 .overlay { if rows.isEmpty { Text("Aucun actif ne correspond").foregroundStyle(.secondary) } }378 }379 .frame(width: 420, height: 440)380 }381 }382383 private func row(_ a: SwapAsset) -> some View {384 let b = SwapText.balance(model, of: a)385 return HStack(spacing: 10) {386 AssetBadge(symbol: a.symbol, size: 26)387 VStack(alignment: .leading, spacing: 1) {388 Text(a.symbol).fontWeight(.medium) + Text(a.name.map { " \($0)" } ?? "").foregroundStyle(.secondary)389 Text((a.networkName ?? a.network) + (a.asset == "native" ? "" : " · \(Fmt.short(a.asset))")).font(.caption).foregroundStyle(.secondary)390 }391 Spacer()392 if let b, b.isNonZero { Text(model.settings.hideBalances ? "••••" : Fmt.amount(b.display, maxFraction: 6)).monospacedDigit().font(.callout) }393 }394 .contentShape(Rectangle())395 }396}397398/// The unified execution status of a proposal or a plan leg: one row per step, each with the server's state for it.399struct ExecutionTimeline: View {400 let model: AppModel401 let status: ExecutionStatus402403 var body: some View {404 VStack(alignment: .leading, spacing: 8) {405 Text("Étapes d’exécution").font(.caption).foregroundStyle(.secondary)406 ForEach(status.steps) { s in407 HStack(alignment: .top, spacing: 10) {408 icon(s.state).frame(width: 18)409 VStack(alignment: .leading, spacing: 2) {410 Text("\(SwapText.stepKind(s.kind)) — \(networkName(s.network))").fontWeight(.medium)411 Text(SwapText.execState(s.state) + (s.code.map { " · \(SwapText.hold($0))" } ?? "")).font(.callout).foregroundStyle(color(s.state))412 .fixedSize(horizontal: false, vertical: true)413 if let tx = s.txid { Text(tx).font(.system(.caption, design: .monospaced)).textSelection(.enabled).foregroundStyle(.secondary) }414 SafeLink(title: "Explorateur de blocs", url: s.explorer)415 }416 }417 }418 }419 }420421 private func networkName(_ id: String) -> String {422 switch id { case "circle": "Circle (hors chaîne)"; case "thorchain": "THORChain"; default: model.network(id)?.name ?? id }423 }424 private func color(_ s: ExecState) -> Color { s == .confirmed ? Theme.positive : s == .failed ? Theme.negative : s == .refunded ? Theme.warning : .secondary }425 @ViewBuilder private func icon(_ s: ExecState) -> some View {426 switch s {427 case .confirmed: Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive)428 case .failed: Image(systemName: "xmark.octagon.fill").foregroundStyle(Theme.negative)429 case .refunded: Image(systemName: "arrow.uturn.backward.circle.fill").foregroundStyle(Theme.warning)430 case .pending: Image(systemName: "circle").foregroundStyle(.tertiary)431 default: Image(systemName: "clock").foregroundStyle(Theme.warning)432 }433 }434}435436/// The headline of a tracked operation, from the Core's completion — never from the source transaction alone.437struct OperationHeadline: View {438 let proposal: Proposal439 let completion: OperationCompletion?440441 var body: some View {442 HStack(alignment: .top, spacing: 10) {443 Group {444 switch completion {445 case .complete: Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive)446 case .refunded: Image(systemName: "arrow.uturn.backward.circle.fill").foregroundStyle(Theme.warning)447 case .failed: Image(systemName: "xmark.octagon.fill").foregroundStyle(Theme.negative)448 case nil: Image(systemName: "questionmark.circle.fill").foregroundStyle(Theme.warning)449 default: ProgressView().controlSize(.small)450 }451 }.font(.title2)452 VStack(alignment: .leading, spacing: 2) {453 Text(title).font(.title3.weight(.semibold))454 Text(detail).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)455 }456 }457 }458459 private var crossChain: Bool { proposal.kind == "bridge" || proposal.kind == "xswap" }460 private var title: String {461 switch completion {462 case .complete: crossChain ? "Reçu sur le réseau de destination" : "Échange finalisé"463 case .refunded: "Remboursé — l’échange n’a pas eu lieu"464 case .failed: proposal.state == .notBroadcast ? "Signée, NON diffusée" : "Aucun succès : \(ErrorText.state(proposal.state))"465 case .inProgress: crossChain ? "En cours — pas encore reçu sur la destination" : "En cours — \(ErrorText.state(proposal.state))"466 case .notStarted: ErrorText.state(proposal.state)467 case nil: "État illisible"468 }469 }470 private var detail: String {471 switch completion {472 case .complete: crossChain ? "Le portefeuille a lui-même constaté l’arrivée des fonds sur le réseau de destination." : "La transaction d’échange est confirmée au seuil de finalité du réseau."473 case .refunded: "THORChain a renvoyé l’actif source, moins ses frais."474 case .failed: proposal.state == .notBroadcast ? "Ce serveur est en mode test : la transaction a été signée mais volontairement pas relayée. Rien n’a été envoyé." : "Vérifiez le détail ci-dessous."475 case .inProgress: crossChain ? "La transaction source (ci-dessous : « \(ErrorText.state(proposal.state)) ») n’est que la première jambe. L’opération n’est terminée que lorsque la destination est confirmée." : "Un identifiant de transaction n’est pas une confirmation."476 case .notStarted: "Rien n’est parti."477 case nil: "La section de cette opération ne peut pas être lue par cette version de l’app ; aucun état n’est déduit."478 }479 }480}481482struct StateHistory: View {483 let history: [(Date, String)]484 var body: some View {485 VStack(alignment: .leading, spacing: 4) {486 Text("Historique des états observés").font(.caption).foregroundStyle(.secondary)487 ForEach(Array(history.enumerated()), id: \.offset) { _, h in488 HStack(alignment: .firstTextBaseline) { Text(Fmt.dateSeconds(h.0)).monospacedDigit().foregroundStyle(.secondary); Text(h.1) }.font(.callout)489 }490 }491 }492}493494/// The review of a verified intent-based operation, then the explicit passkey button. Everything shown comes from the intent495/// whose hash is the challenge; `extra` adds the server's context lines, labelled as such by the caller.496struct OperationReviewSheet: View {497 let model: AppModel498 let title: String499 let operation: ApprovableOperation500 var notices: [(Banner.Kind, String)] = []501 var extra: [ReviewLine] = []502 let busy: Bool503 let error: String?504 let onReject: () -> Void505 let onApprove: () -> Void506507 var body: some View {508 let simulated = SwapText.isSimulatedServer(model)509 VStack(alignment: .leading, spacing: 0) {510 HStack {511 Text(title).font(.title2.weight(.semibold))512 Spacer()513 if simulated { ProvenanceTag(p: .simulated, text: "Serveur de test : signé, non diffusé") }514 }.padding(20)515 Divider()516 ScrollView {517 VStack(alignment: .leading, spacing: 12) {518 ForEach(Array(notices.enumerated()), id: \.offset) { _, n in Banner(n.0, n.1) }519 TransactionReview(intent: operation.intent, digest: operation.approval.digest, network: model.network(operation.intent.network),520 ownAddresses: SwapText.ownAddresses(model),521 warnings: (operation.proposal.warnings ?? []).filter { $0 != "swap_needs_approval" }, extra: extra)522 }.padding(20)523 }524 Divider()525 VStack(alignment: .leading, spacing: 8) {526 if let error { Banner(.danger, error) }527 HStack {528 Button("Rejeter", role: .destructive, action: onReject).disabled(busy)529 Spacer()530 if busy { ProgressView().controlSize(.small); Text("Passkey, puis signature isolée…").foregroundStyle(.secondary) }531 Button(action: onApprove) { Label(simulated ? "Approuver (test : ne sera pas diffusé)" : "Approuver avec la passkey", systemImage: "touchid") }532 .buttonStyle(.borderedProminent).controlSize(.large).disabled(busy || !model.canOperate)533 }534 }.padding(16)535 }536 .frame(width: 760, height: 800)537 .interactiveDismissDisabled()538 }539540 /// The exact-amount ERC-20 spend approval that precedes a swap / a burn / a router deposit, spelled out from the intent.541 static func spendApproval(_ i: Intent, model: AppModel) -> (Banner.Kind, String)? {542 let amount = "\(SwapText.units(i.amount, decimals: i.decimals)) \(i.symbol)"543 if let s = i.swap, s.approveGas != "0" {544 return (.warning, "Autorisation de dépense ERC-20 : une première transaction autorise le routeur \(s.router) à dépenser exactement \(amount) (contrat \(i.asset)) — ni plus, ni illimité. Elle est couverte par cette même approbation et consommée par l’échange (gaz maximum de l’autorisation : \(s.approveGas)).")545 }546 if let b = i.bridge, b.approveGas != "0" {547 return (.warning, "Autorisation de dépense ERC-20 : une première transaction autorise le TokenMessenger de Circle \(b.messenger) à dépenser exactement \(amount) — ni plus, ni illimité. Elle est couverte par cette même approbation (gaz maximum de l’autorisation : \(b.approveGas)).")548 }549 if let x = i.xswap, x.approveGas != "0" {550 return (.warning, "Autorisation de dépense ERC-20 : une première transaction autorise le routeur THORChain \(x.router) à dépenser exactement \(amount) — ni plus, ni illimité. Elle est couverte par cette même approbation (gaz maximum de l’autorisation : \(x.approveGas)).")551 }552 return nil553 }554555 static func simulationLine(_ simulated: Bool?, needsApproval: Bool?) -> ReviewLine {556 switch simulated {557 case true?: ReviewLine(label: "Simulation (serveur)", value: "Réussie à la préparation, contre l’état actuel de la chaîne.")558 case false?: ReviewLine(label: "Simulation (serveur)", value: needsApproval == true ? "Différée : la transaction principale sera simulée après la confirmation de l’autorisation de dépense, et ne partira pas si elle devait échouer." : "Non simulée à la préparation ; elle sera simulée contre l’état réel avant d’être relayée.", style: .warning)559 case nil: ReviewLine(label: "Simulation (serveur)", value: "Non indiquée par le serveur.", style: .warning)560 }561 }562}563564extension OperationReviewSheet {565 /// Readable versions of the intent’s own figures (decimals from the registry), then the server’s context lines, labelled as such.566 static func contextLines(model: AppModel, operation: ApprovableOperation) -> [ReviewLine] {567 let i = operation.intent, p = operation.proposal568 var out: [ReviewLine] = []569 if let s = i.swap {570 let d = SwapText.assetDef(model, network: i.network, asset: s.toAsset)571 out.append(.init(label: "Minimum reçu (lisible)", value: "\(SwapText.units(s.minOut, decimals: d?.decimals)) \(d?.symbol ?? "")", style: .strong))572 }573 if let x = i.xswap {574 let d = SwapText.assetDef(model, network: x.toNetwork, asset: x.toAsset)575 out.append(.init(label: "Minimum reçu (lisible)", value: "\(SwapText.units(x.minOut, decimals: d?.decimals)) \(d?.symbol ?? "") sur \(model.network(x.toNetwork)?.name ?? x.toNetwork)", style: .strong))576 }577 if let sec = try? p.swapSection() {578 out.append(.init(label: "Sortie attendue", value: "\(Fmt.amount(sec.expectedOutDisplay)) \(sec.toSymbol) — estimation du serveur, non garantie ; seul le minimum est signé"))579 out.append(.init(label: "Tolérance de glissement", value: SwapText.bps(sec.slippageBps) + " (demandée ; le minimum ci-dessus en découle)"))580 out.append(simulationLine(sec.simulated, needsApproval: sec.needsApproval))581 }582 if let x = try? p.xswapSection() {583 if let f = x.outboundFeeDisplay { out.append(.init(label: "Frais sortants THORChain", value: "\(Fmt.amount(f)) \(x.toSymbol) — déjà déduits du minimum")) }584 if let f = x.liquidityFeeDisplay { out.append(.init(label: "Frais de liquidité", value: "\(Fmt.amount(f)) \(x.toSymbol) — déjà déduits")) }585 out.append(.init(label: "Délai estimé", value: SwapText.duration(x.estimatedSeconds)))586 if let ops = x.operators, !ops.isEmpty { out.append(.init(label: "Coffre confirmé par", value: "\(ops.count) opérateurs (côté serveur) : \(ops.joined(separator: ", "))" + (x.vaultMembers.map { " · \($0) membres du coffre" } ?? ""))) }587 }588 if let b = try? p.bridgeSection() {589 out.append(.init(label: "Vitesse", value: BridgeText.speed(b.speed) + " — durée attendue \(SwapText.duration(b.expectedSeconds)) (information du serveur)"))590 if let g = b.destGasNeedDisplay { out.append(.init(label: "Frais d’émission prévus", value: "≈ \(Fmt.amount(g, maxFraction: 8)) \(b.destGasSymbol ?? "") sur \(b.toNetworkName ?? b.toNetwork), payés par ce portefeuille (estimation)")) }591 out.append(simulationLine(b.simulated, needsApproval: b.needsApproval))592 if let s = b.sol, s.role == "source", let d = s.depositDisplay { out.append(.init(label: "Dépôt Solana remboursable", value: "\(Fmt.amount(d, maxFraction: 9)) \(s.symbol ?? "SOL") — récupérable cinq jours après la destruction", style: .warning)) }593 if let s = b.sol, s.role == "destination", let t = s.tokenAccount { out.append(.init(label: "Compte de jetons crédité", value: t, style: .address)) }594 }595 if let fee = p.feeDisplay { out.append(.init(label: "Frais de réseau estimés", value: "\(Fmt.amount(fee)) \(p.feeSymbol ?? "") (estimation ; le plafond ci-dessus est ce qui est signé)")) }596 if i.kind != .bridge {597 if let q = try? p.quoteRecord() {598 out.append(.init(label: "Écart avec la cotation", value: "\(SwapText.bps(Double(q.deviationBps))) (cotée \(Fmt.amount(q.quotedOutDisplay)), ferme \(Fmt.amount(q.firmOutDisplay)))", style: q.deviationBps < 0 ? .warning : .normal))599 } else { out.append(.init(label: "Cotation de référence", value: "Aucune référence comparée par le serveur : fiez-vous uniquement au minimum garanti ci-dessus.", style: .warning)) }600 }601 return out602 }603}604