SPB Git

Repository Public

TransactionReview.swift 11.7 KB 180 lines swift

1// SP Wallet iOS2// File: Components/TransactionReview.swift3// Description: The review of what the passkey is about to approve. Every figure shown here is read from the INTENT whose hash is4//              the challenge (already verified by SPWalletCore) — not from the request, not from the proposal summary. Nothing is5//              truncated, folded away or animated; the sheet cannot be swiped away by accident.6//7// Author: Simon-Pierre Boucher8// Contact: contact@spboucher.ai9import SwiftUI10import SPWalletCore1112struct IntentReview: View {13    @Environment(AppModel.self) private var model14    let intent: Intent15    let digest: Data16    var warnings: [String] = []17    /** Extra rows a specialised flow adds (swap minimum, bridge destination…), already derived from the same intent. */18    var extra: [(String, String, Bool)] = []1920    private var network: Network? { model.network(intent.network) }21    private var feeDecimals: Int? { network?.native.decimals }22    private var feeSymbol: String { network?.native.symbol ?? "" }2324    var body: some View {25        VStack(alignment: .leading, spacing: 14) {26            VStack(alignment: .leading, spacing: 4) {27                Text(kindTitle).spEyebrow()28                Text(Money.exact(intent.amountUnits.formatted(decimals: intent.decimals)) + " " + intent.symbol)29                    .font(.system(size: 32, weight: .semibold)).tracking(-0.8).foregroundStyle(Theme.ink)30                    .fixedSize(horizontal: false, vertical: true).textSelection(.enabled)31                    .accessibilityIdentifier("review.amount")32            }33            ForEach(warnings, id: \.self) { w in Notice(tone: Self.warningTone(w), title: Self.warningTitle(w), message: Self.warningMessage(w)) }34            VStack(alignment: .leading, spacing: 0) {35                FieldRow(label: String(localized: "Réseau"), value: (network?.name ?? intent.network) + " (\(intent.chainRef))")36                Divider()37                FieldRow(label: String(localized: "Actif"), value: intent.asset == "native" ? "\(intent.symbol) — " + String(localized: "monnaie native") : intent.symbol)38                if intent.asset != "native" { FieldRow(label: String(localized: "Contrat du jeton"), value: intent.asset, mono: true, copyable: true) }39                Divider()40                FieldRow(label: String(localized: "De (ce portefeuille)"), value: intent.from, mono: true, copyable: true)41                Divider()42                FieldRow(label: destinationLabel, value: intent.to, mono: true, copyable: true).accessibilityIdentifier("review.to")43                if let memo = intent.memo { Divider(); FieldRow(label: String(localized: "Mémo / tag de destination"), value: memo, mono: true) }44                Divider()45                FieldRow(label: String(localized: "Frais de réseau, plafond"), value: feeText)46                if let total = totalText { Divider(); FieldRow(label: String(localized: "Total maximal débité"), value: total) }47                ForEach(Array(extra.enumerated()), id: \.offset) { _, row in Divider(); FieldRow(label: row.0, value: row.1, mono: row.2, copyable: row.2) }48                ForEach(Array(kindRows.enumerated()), id: \.offset) { _, row in Divider(); FieldRow(label: row.0, value: row.1, mono: row.2, copyable: row.2) }49            }50            .spCard(padding: 16)51            VStack(alignment: .leading, spacing: 0) {52                TimelineView(.periodic(from: .now, by: 1)) { ctx in53                    let left = Int(intent.expiry.timeIntervalSince(ctx.date))54                    FieldRow(label: String(localized: "Fenêtre d’approbation"), value: left > 0 ? String(localized: "expire dans \(left) s") : String(localized: "expirée"), tone: left > 15 ? nil : .danger)55                }56                Divider()57                FieldRow(label: String(localized: "Empreinte de l’intention (défi signé par la clé d’accès)"), value: digest.hex, mono: true, copyable: true)58                Divider()59                FieldRow(label: String(localized: "Clé du signataire · version de politique"), value: "\(intent.keyId) · v\(intent.policyVersion)", mono: true)60            }61            .spCard(padding: 16)62            Label(String(localized: "L’app a recalculé cette empreinte à partir des champs affichés et vérifié qu’elle est le défi demandé à ta clé d’accès. Le signataire isolé la revérifie avant de signer."),63                  systemImage: "checkmark.shield.fill")64                .font(.spFootnote).foregroundStyle(Theme.mute)65        }66    }6768    private var kindTitle: String {69        switch intent.kind {70        case .transfer: String(localized: "Envoi")71        case .swap: String(localized: "Échange")72        case .bridge: String(localized: "Transfert entre réseaux")73        case .xswap: String(localized: "Échange natif entre réseaux")74        case .venueDeposit: String(localized: "Dépôt sur une plateforme")75        case .gmx: String(localized: "Ordre GMX")76        }77    }78    private var destinationLabel: String {79        switch intent.kind {80        case .transfer: String(localized: "Destinataire")81        case .swap: String(localized: "Livré à (ce portefeuille)")82        case .bridge: String(localized: "Livré à (ce portefeuille)")83        case .xswap: String(localized: "Coffre du protocole (entrée de l’échange)")84        case .venueDeposit: String(localized: "Contrat de dépôt de la plateforme")85        case .gmx: String(localized: "Contrat appelé (ExchangeRouter)")86        }87    }88    private var feeText: String {89        guard let d = feeDecimals else { return intent.maxFee + " " + String(localized: "(unités de base)") }90        return Money.exact(intent.maxFeeUnits.formatted(decimals: d)) + " " + feeSymbol91    }92    private var totalText: String? {93        guard intent.kind == .transfer, intent.asset == "native", let d = feeDecimals, d == intent.decimals else { return nil }94        return Money.exact((intent.amountUnits + intent.maxFeeUnits).formatted(decimals: d)) + " " + intent.symbol95    }96    /** Kind-specific fields of the intent, shown raw when no specialised flow formats them: nothing signed is hidden. */97    private var kindRows: [(String, String, Bool)] {98        var r: [(String, String, Bool)] = []99        if let s = intent.swap {100            r += [(String(localized: "Fournisseur"), s.provider, false), (String(localized: "Actif reçu (contrat)"), s.toAsset, true),101                  (String(localized: "Minimum reçu (unités de base)"), s.minOut, true), (String(localized: "Routeur appelé"), s.router, true),102                  (String(localized: "Empreinte des données d’appel"), s.dataHash, true)]103        }104        if let b = intent.bridge {105            r += [(String(localized: "Fournisseur"), b.provider, false), (String(localized: "Réseau de destination"), model.network(b.toNetwork)?.name ?? b.toNetwork, false),106                  (String(localized: "Frais du pont, plafond (unités de base)"), b.maxFee, true), (String(localized: "Contrat de pont"), b.messenger, true)]107            if let rcp = b.recipient { r.append((String(localized: "Adresse de destination (ce portefeuille)"), rcp, true)) }108        }109        if let x = intent.xswap {110            r += [(String(localized: "Fournisseur"), x.provider, false), (String(localized: "Réseau de destination"), model.network(x.toNetwork)?.name ?? x.toNetwork, false),111                  (String(localized: "Actif reçu"), x.toAsset, true), (String(localized: "Minimum reçu (unités de base)"), x.minOut, true), (String(localized: "Mémo du protocole"), x.memo, true)]112        }113        if let d = intent.venueDeposit { r += [(String(localized: "Plateforme"), "\(d.venue) · \(d.venueNetwork)", false), (String(localized: "Route"), d.route, false)] }114        if let g = intent.gmx {115            r += [(String(localized: "Action"), "\(g.action) · \(g.orderType) · \(g.isLong ? "long" : "short")", false), (String(localized: "Marché"), g.market, true),116                  (String(localized: "Taille (USD, 30 décimales)"), g.sizeDeltaUsd, true), (String(localized: "Prix acceptable"), g.acceptablePrice, true),117                  (String(localized: "Frais d’exécution (wei)"), g.executionFee, true)]118        }119        return r120    }121122    static func warningTone(_ w: String) -> Tone { w == "address_poisoning_suspected" ? .danger : .warn }123    static func warningTitle(_ w: String) -> String {124        switch w {125        case "new_destination": String(localized: "Nouvelle destination")126        case "address_poisoning_suspected": String(localized: "Adresse suspecte : ressemble à une adresse connue")127        default: w.replacingOccurrences(of: "_", with: " ").capitalized128        }129    }130    static func warningMessage(_ w: String) -> String? {131        switch w {132        case "new_destination": String(localized: "Ce portefeuille n’a jamais envoyé à cette adresse. Vérifie-la caractère par caractère : un envoi est irréversible.")133        case "address_poisoning_suspected": String(localized: "Elle a le même début et la même fin qu’une adresse déjà utilisée, mais un milieu différent. C’est la signature d’une attaque par empoisonnement d’adresse.")134        default: nil135        }136    }137}138139/** Live follow-up of a proposal after approval: every intermediate state is shown; only `finalized` is a success. */140struct ProposalTracker: View {141    @Environment(AppModel.self) private var model142    let proposalId: String143    @State private var status: ProposalStatus?144    @State private var error: Error?145146    var body: some View {147        VStack(alignment: .leading, spacing: 14) {148            if let s = status {149                HStack(spacing: 10) {150                    if s.state.isInFlight { ProgressView() } else { Image(systemName: s.state.symbol).font(.system(size: 22)).foregroundStyle(s.state.tone.color) }151                    Text(s.state.label).font(.spHeadline).foregroundStyle(Theme.ink)152                }153                .accessibilityIdentifier("tracker.state")154                if s.state == .broadcast || s.state == .confirming {155                    Notice(tone: .info, title: String(localized: "Pas encore confirmée par le réseau"), message: String(localized: "Une transaction diffusée peut encore échouer ou être remplacée. L’app suit les confirmations."))156                }157                if s.state == .notBroadcast {158                    Notice(tone: .warn, title: String(localized: "Signée mais non diffusée"), message: String(localized: "Ce serveur a la diffusion désactivée : rien n’a quitté le serveur et rien ne sera confirmé."))159                }160                VStack(alignment: .leading, spacing: 0) {161                    if let c = s.confirmations { FieldRow(label: String(localized: "Confirmations"), value: String(c)) ; Divider() }162                    if let t = s.txid { FieldRow(label: String(localized: "Identifiant de transaction"), value: t, mono: true, copyable: true) }163                    if let e = s.error { Divider(); FieldRow(label: String(localized: "Erreur"), value: e + (s.errorCode.map { " (\($0))" } ?? ""), tone: .danger) }164                }165                .spCard(padding: 16)166                if let e = s.explorer, let u = URL(string: e), u.scheme == "https" {167                    Link(destination: u) { Label(String(localized: "Ouvrir dans l’explorateur"), systemImage: "arrow.up.right.square") }.buttonStyle(.spSecondary)168                }169            } else if let error { ErrorNotice(error: error) } else { ProgressView().frame(maxWidth: .infinity) }170        }171        .task(id: proposalId) {172            while !Task.isCancelled {173                do { status = try await model.env.transfers.status(proposalId); error = nil } catch let e { if status == nil { error = e } }174                if status?.state.isTerminal == true { await model.refreshAll(); break }175                try? await Task.sleep(for: .seconds(4))176            }177        }178    }179}180
Files main
Menu

Theme