Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Components/TransactionReview.swift3// Description: The review of an operation before the passkey prompt. It renders ONLY the fields of the canonical intent whose SHA-256 the app has verified to be the WebAuthn challenge — not the server's summary of it — so what is displayed is what the passkey signs and what the isolated signer will rebuild. Nothing is abbreviated: full addresses, exact base-unit amounts, fee ceiling, expiry.4import SwiftUI5import SPWalletCore67/// One line of a review: label, exact value, and whether it deserves emphasis or a warning colour.8struct ReviewLine: Identifiable {9 enum Style { case normal, strong, address, warning }10 let id = UUID()11 let label: String; let value: String; var style: Style = .normal12}1314enum IntentReview {15 static func kindTitle(_ k: Intent.Kind) -> String {16 switch k {17 case .transfer: "Transfert"18 case .swap: "Échange (swap) — sortie livrée à ce portefeuille"19 case .bridge: "Transfert inter-chaînes (Circle CCTP) — de ce portefeuille à lui-même"20 case .xswap: "Échange inter-chaînes natif (THORChain)"21 case .venueDeposit: "Dépôt de collatéral sur une plateforme de dérivés"22 case .gmx: "Ordre GMX v2"23 }24 }2526 /// Every value-bearing field of the intent, in reading order. `network` supplies names and the fee coin; unknown → raw identifiers.27 static func lines(_ i: Intent, network n: SPWalletCore.Network?, ownAddresses: [String: String]) -> [ReviewLine] {28 var out: [ReviewLine] = []29 let feeSym = n?.native.symbol ?? "(monnaie native)", feeDec = n?.native.decimals30 func units(_ s: String, _ dec: Int?) -> String { guard let dec, let u = try? BaseUnits(s) else { return s + " (unités de base)" }; return Fmt.amount(u.formatted(decimals: dec)) }31 out.append(.init(label: "Type d’opération", value: kindTitle(i.kind), style: .strong))32 out.append(.init(label: "Réseau", value: "\(n?.name ?? i.network) (\(i.network), \(i.chainRef))"))33 out.append(.init(label: "Actif", value: i.asset == "native" ? "\(i.symbol) (monnaie native)" : "\(i.symbol) — contrat \(i.asset)"))34 out.append(.init(label: "Montant", value: "\(units(i.amount, i.decimals)) \(i.symbol)", style: .strong))35 out.append(.init(label: "Montant exact", value: "\(i.amount) unités de base (\(i.decimals) décimales)"))36 out.append(.init(label: "Depuis", value: i.from, style: .address))37 let self_ = i.to == i.from || ownAddresses.values.contains(i.to)38 out.append(.init(label: i.kind == .transfer ? "Destinataire" : "Destination de la transaction", value: i.to, style: .address))39 if i.kind == .transfer, self_ { out.append(.init(label: "", value: "La destination est une adresse de ce portefeuille.")) }40 if let m = i.memo { out.append(.init(label: "Mémo / étiquette", value: m.isEmpty ? "(vide)" : m)) }41 // native-coin transfer: the fee comes on top of the amount, in the same coin42 if i.kind == .gmx { out.append(.init(label: "Plafond frais + exécution", value: "\(units(i.maxFee, feeDec)) \(feeSym)")) }43 else { out.append(.init(label: "Frais de réseau maximum", value: "\(units(i.maxFee, feeDec)) \(feeSym)")) }44 if i.asset == "native", i.kind == .transfer, let a = try? BaseUnits(i.amount), let f = try? BaseUnits(i.maxFee) {45 out.append(.init(label: "Total maximum débité", value: "\(Fmt.amount((a + f).formatted(decimals: i.decimals))) \(i.symbol)", style: .strong))46 } else if i.kind == .transfer {47 out.append(.init(label: "Total maximum débité", value: "\(units(i.amount, i.decimals)) \(i.symbol) + \(units(i.maxFee, feeDec)) \(feeSym) de frais", style: .strong))48 }49 if let s = i.swap {50 out.append(.init(label: "Fournisseur", value: s.provider))51 out.append(.init(label: "Actif reçu", value: s.toAsset == "native" ? "monnaie native" : "contrat \(s.toAsset)"))52 out.append(.init(label: "Minimum reçu garanti", value: "\(s.minOut) unités de base de l’actif reçu", style: .strong))53 out.append(.init(label: "Contrat appelé (routeur)", value: s.router, style: .address))54 out.append(.init(label: "Empreinte des données d’appel", value: s.dataHash))55 if s.approveGas != "0" { out.append(.init(label: "Autorisation de dépense", value: "Une approbation ERC-20 du montant exact au routeur précède l’échange (gaz \(s.approveGas)).", style: .warning)) }56 }57 if let b = i.bridge {58 out.append(.init(label: "Réseau de destination", value: "\(b.toNetwork) (domaine CCTP \(b.toDomain))", style: .strong))59 out.append(.init(label: "Bénéficiaire", value: b.recipient ?? i.from, style: .address))60 out.append(.init(label: "Frais Circle maximum", value: "\(units(b.maxFee, i.decimals)) \(i.symbol)"))61 if let a = try? BaseUnits(i.amount), let f = try? BaseUnits(b.maxFee), let m = try? a.subtracting(f) { out.append(.init(label: "Minimum reçu", value: "\(Fmt.amount(m.formatted(decimals: i.decimals))) \(i.symbol)", style: .strong)) }62 out.append(.init(label: "Seuil de finalité", value: String(b.minFinalityThreshold)))63 out.append(.init(label: "Contrats appelés", value: "TokenMessenger \(b.messenger)\nMessageTransmitter \(b.transmitter)", style: .address))64 if b.approveGas != "0" { out.append(.init(label: "Autorisation de dépense", value: "Une approbation du montant exact au TokenMessenger précède le transfert.", style: .warning)) }65 }66 if let x = i.xswap {67 out.append(.init(label: "Fournisseur", value: x.provider))68 out.append(.init(label: "Vous recevez sur", value: "\(x.toNetwork) — actif \(x.toAsset)", style: .strong))69 out.append(.init(label: "Minimum reçu", value: "\(x.minOut) unités de base", style: .strong))70 out.append(.init(label: "Coffre THORChain (destination)", value: x.vault, style: .address))71 out.append(.init(label: "Mémo THORChain", value: x.memo))72 if !x.router.isEmpty { out.append(.init(label: "Contrat appelé (routeur)", value: x.router, style: .address)) }73 out.append(.init(label: "Échéance du dépôt", value: Fmt.dateSeconds(Date(timeIntervalSince1970: TimeInterval(x.expiry)))))74 out.append(.init(label: "Risque", value: "Un échange natif inter-chaînes est irréversible une fois le dépôt envoyé ; en cas d’échec côté THORChain, un remboursement peut être émis moins les frais.", style: .warning))75 }76 if let v = i.venueDeposit {77 out.append(.init(label: "Plateforme", value: "\(v.venue) (\(v.venueNetwork)), route \(v.route)", style: .strong))78 out.append(.init(label: "Contrat du pont", value: v.bridge, style: .address))79 out.append(.init(label: "Minimum accepté", value: "\(units(v.minAmount, i.decimals)) \(i.symbol)"))80 }81 if let g = i.gmx {82 out.append(.init(label: "Action", value: "\(g.action) · \(g.orderType) · \(g.isLong ? "LONG" : "SHORT")", style: .strong))83 out.append(.init(label: "Taille (USD, 30 déc.)", value: g.sizeDeltaUsd))84 out.append(.init(label: "Prix acceptable", value: g.acceptablePrice))85 out.append(.init(label: "Frais d’exécution", value: "\(units(g.executionFee, feeDec)) \(feeSym)"))86 out.append(.init(label: "Marché", value: g.market, style: .address))87 out.append(.init(label: "Contrat appelé", value: g.exchangeRouter, style: .address))88 if let k = g.orderKey { out.append(.init(label: "Ordre visé", value: k)) }89 }90 if let e = i.evm { out.append(.init(label: "Paramètres EVM", value: "nonce \(e.nonce) · gaz \(e.gasLimit) · max \(e.maxFeePerGas) wei/gaz · priorité \(e.maxPriorityFeePerGas)")) }91 if let b = i.btc {92 out.append(.init(label: "Entrées dépensées", value: b.inputs.map { "\($0.txid):\($0.vout) — \($0.value)" }.joined(separator: "\n")))93 out.append(.init(label: "Monnaie rendue / frais", value: "\(b.change) / \(b.fee) (unités de base)"))94 }95 if let s = i.sol { out.append(.init(label: "Paramètres Solana", value: "valide jusqu’au bloc \(s.lastValidBlockHeight) · \(s.computeUnitLimit) CU à \(s.computeUnitPrice) µlamports" + (s.createAta ? " · crée le compte de jetons du destinataire" : ""))) }96 if let x = i.x, !x.isEmpty { out.append(.init(label: "Paramètres de chaîne", value: x.keys.sorted().map { "\($0) = \(x[$0]!.count > 90 ? String(x[$0]!.prefix(90)) + "…(\(x[$0]!.count) car.)" : x[$0]!)" }.joined(separator: "\n"))) }97 out.append(.init(label: "Clé du portefeuille", value: i.keyId))98 out.append(.init(label: "Politique du signataire", value: "version \(i.policyVersion)"))99 return out100 }101}102103/// The verified-binding footer shared by every approval sheet.104struct BindingProof: View {105 let digest: Data106 let expiry: Date?107 var body: some View {108 VStack(alignment: .leading, spacing: 6) {109 Label("Défi vérifié par cette app", systemImage: "checkmark.seal.fill").foregroundStyle(Theme.positive).font(.callout.weight(.medium))110 Text("Le défi que votre passkey va signer est exactement l’empreinte SHA-256 de l’opération ci-dessus, recalculée sur ce Mac. Le signataire isolé reconstruit la transaction à partir de ces mêmes champs et refuse toute différence.")111 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)112 Text(digest.map { String(format: "%02x", $0) }.joined()).font(.system(.caption, design: .monospaced)).textSelection(.enabled).foregroundStyle(.secondary)113 if let expiry {114 TimelineView(.periodic(from: .now, by: 1)) { ctx in115 let left = Int(expiry.timeIntervalSince(ctx.date))116 Text(left > 0 ? "Fenêtre d’approbation : \(left) s" : "Fenêtre d’approbation expirée").font(.caption.weight(.medium)).foregroundStyle(left > 15 ? Color.secondary : Theme.negative).monospacedDigit()117 }118 }119 }120 .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Theme.positive.opacity(0.07), in: RoundedRectangle(cornerRadius: 8))121 }122}123124struct ReviewLines: View {125 let lines: [ReviewLine]126 var body: some View {127 VStack(alignment: .leading, spacing: 9) {128 ForEach(lines) { l in129 HStack(alignment: .firstTextBaseline, spacing: 12) {130 Text(l.label).foregroundStyle(.secondary).frame(width: 190, alignment: .leading)131 Group {132 switch l.style {133 case .address: Text(l.value).font(Theme.monoSmall)134 case .strong: Text(l.value).fontWeight(.semibold)135 case .warning: Label(l.value, systemImage: "exclamationmark.triangle.fill").foregroundStyle(Theme.warning)136 case .normal: Text(l.value)137 }138 }.textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).fixedSize(horizontal: false, vertical: true)139 }140 }141 }142 }143}144145/// The complete review of an intent-based operation (transfer, swap, bridge, cross-chain swap, venue deposit, GMX order).146struct TransactionReview: View {147 let intent: Intent148 let digest: Data149 let network: SPWalletCore.Network?150 let ownAddresses: [String: String]151 var warnings: [String] = []152 var extra: [ReviewLine] = []153154 var body: some View {155 VStack(alignment: .leading, spacing: 14) {156 ForEach(warnings, id: \.self) { w in Banner(w == "address_poisoning_suspected" ? .danger : .warning, ErrorText.warning(w)) }157 ReviewLines(lines: IntentReview.lines(intent, network: network, ownAddresses: ownAddresses) + extra)158 if intent.kind == .transfer {159 VStack(alignment: .leading, spacing: 4) {160 Text("Adresse du destinataire, par groupes de 4 caractères").font(.caption).foregroundStyle(.secondary)161 Text(Fmt.chunked(intent.to)).font(.system(.title3, design: .monospaced)).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)162 }163 .padding(10).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))164 }165 Text("Une transaction diffusée sur une blockchain est irréversible. Une adresse erronée ou un mauvais réseau signifie la perte des fonds.").font(.callout).foregroundStyle(.secondary)166 BindingProof(digest: digest, expiry: intent.expiry)167 }168 }169}170