SPB Git

Repository Public

SendView.swift 12.1 KB 195 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Send/SendView.swift3// Description: Sending crypto: form with live address validation (same rules as the backend), the review sheet of the verified intent, the passkey approval, then the honest tracking of the transaction until the chain finalizes it.4import SwiftUI5import SPWalletCore67struct SendView: View {8    let model: AppModel9    @Bindable var nav: Navigator10    @State private var flow: SendFlow?1112    var body: some View {13        Page("Envoyer", subtitle: "Chaque envoi est autorisé par votre passkey sur l’intention exacte, puis signé par le signataire isolé.") {14            if let flow {15                if !model.canOperate { Banner(.warning, "Envoi impossible pour l’instant : session ou portefeuille indisponible.") }16                switch flow.step {17                case .tracking: TrackingCard(flow: flow)18                default: SendForm(model: model, flow: flow)19                }20            } else { ProgressView() }21        }22        .task {23            if flow == nil { flow = SendFlow(model: model) }24            applyPreset()25        }26        .onChange(of: nav.sendPreset) { applyPreset() }27        .sheet(isPresented: Binding(get: { flow?.step == .review || flow?.step == .approving }, set: { _ in })) {28            if let flow, let a = flow.approval { ReviewSheet(model: model, flow: flow, approval: a) }29        }30    }31    private func applyPreset() {32        guard let flow, flow.step == .form else { return }33        if let p = nav.sendPreset { flow.network = p.network; flow.asset = p.asset; nav.sendPreset = nil }34        else if flow.network.isEmpty, let first = model.networks?.value.first { flow.network = first.id; flow.asset = "native" }35    }36}3738private struct SendForm: View {39    let model: AppModel40    @Bindable var flow: SendFlow4142    var body: some View {43        Card {44            Form {45                NetworkPicker(networks: model.networks?.value ?? [], selection: $flow.network)46                    .onChange(of: flow.network) { if flow.net?.asset(flow.asset) == nil { flow.asset = "native" } }47                AssetPicker(network: flow.net, selection: $flow.asset, balances: model.portfolio?.value.balances ?? [])48                if let a = flow.assetDef, !a.isNative { LabeledContent("Contrat") { Text(a.id).font(Theme.monoSmall).textSelection(.enabled) } }49                LabeledContent("Solde disponible") {50                    if let b = flow.balance, b.isAvailable { Text("\(Fmt.amount(b.display)) \(b.symbol)").monospacedDigit() }51                    else { Text("Indisponible (lecture de chaîne en échec)").foregroundStyle(Theme.negative) }52                }53                if let h = flow.net?.health, h.ok == false { LabeledContent("État RPC") { Text(h.readable == false ? "Chaîne illisible pour l’instant" : "Dégradé").foregroundStyle(Theme.warning) } }54                TextField("Destinataire", text: $flow.to, prompt: Text("Adresse sur \(flow.net?.name ?? "ce réseau")"), axis: .vertical).font(Theme.monoSmall).lineLimit(1...3)55                addressFeedback56                if !model.addressBook.filter({ $0.network == flow.network }).isEmpty {57                    Picker("Carnet d’adresses", selection: Binding(get: { "" }, set: { if !$0.isEmpty { flow.to = $0 } })) {58                        Text("Choisir…").tag("")59                        ForEach(model.addressBook.filter { $0.network == flow.network }) { e in Text("\(e.label) — \(Fmt.short(e.address))").tag(e.address) }60                    }61                }62                HStack {63                    TextField("Montant", text: $flow.amount, prompt: Text("0.0"))64                    Text(flow.assetDef?.symbol ?? "").foregroundStyle(.secondary)65                    Button("Max") { flow.setMax() }.disabled(flow.balance?.isAvailable != true).help(flow.assetDef?.isNative == true ? "Solde entier : les frais de réseau devront être déduits, le serveur refusera sinon." : "Solde entier de cet actif")66                }67                if let a = flow.parsedAmount, !a.isZero, let p = model.price(flow.assetDef?.symbol ?? ""), let d = flow.assetDef?.decimals {68                    LabeledContent("Valeur") { Text(Fmt.fiat(a.approximate(decimals: d) * p.value(in: model.currency), model.currency)).foregroundStyle(.secondary) }69                }70                if let m = flow.net?.memo { TextField(m == "uint32" ? "Étiquette de destination (entier)" : "Mémo", text: $flow.memo) }71                TextField("Note personnelle (non envoyée sur la chaîne)", text: $flow.note)72            }73            .formStyle(.grouped).scrollDisabled(true).disabled(flow.step != .form)74            if let e = flow.error { Banner(.danger, e) }75            HStack {76                if let p = flow.formProblem, !flow.to.isEmpty || !flow.amount.isEmpty { Text(p).foregroundStyle(.secondary).font(.callout) }77                Spacer()78                if flow.step == .preparing { ProgressView().controlSize(.small); Text("Validation, simulation et calcul des frais…").font(.callout).foregroundStyle(.secondary) }79                Button("Préparer et vérifier…") { Task { await flow.prepare() } }.buttonStyle(.borderedProminent).controlSize(.large)80                    .disabled(flow.formProblem != nil || !model.canOperate || flow.step != .form)81            }82            Text("Préparer ne signe rien et n’envoie rien : le serveur valide l’adresse, simule la transaction, calcule les frais et vérifie les limites du signataire. L’envoi n’a lieu qu’après votre approbation par passkey sur l’écran suivant.").font(.caption).foregroundStyle(.secondary)83        }84    }8586    @ViewBuilder private var addressFeedback: some View {87        switch flow.addressCheck {88        case .valid(let n):89            LabeledContent("") { Label(flow.isOwnAddress ? "C’est l’adresse de ce portefeuille" : n == flow.to.trimmingCharacters(in: .whitespaces) ? "Adresse valide pour ce réseau" : "Valide — forme normalisée : \(n)", systemImage: flow.isOwnAddress ? "xmark.circle" : "checkmark.circle").foregroundStyle(flow.isOwnAddress ? Theme.negative : Theme.positive).font(.callout) }90        case .invalid(let r):91            LabeledContent("") {92                VStack(alignment: .leading) {93                    Label(SendFlow.text(r), systemImage: "xmark.circle").foregroundStyle(Theme.negative).font(.callout)94                    if !flow.otherNetworks.isEmpty { Text("Cette adresse est valide sur : \(flow.otherNetworks.map(\.name).joined(separator: ", ")). Vérifiez le réseau choisi.").font(.caption).foregroundStyle(Theme.warning) }95                }96            }97        case .unverifiable: LabeledContent("") { Label("Format non vérifiable par cette version de l’app : le serveur validera l’adresse.", systemImage: "questionmark.circle").foregroundStyle(Theme.warning).font(.callout) }98        case nil: EmptyView()99        }100    }101}102103private struct ReviewSheet: View {104    let model: AppModel105    let flow: SendFlow106    let approval: TransferApproval107108    var body: some View {109        VStack(alignment: .leading, spacing: 0) {110            Text("Vérifier et approuver l’envoi").font(.title2.weight(.semibold)).padding(20)111            Divider()112            ScrollView {113                TransactionReview(intent: approval.intent, digest: approval.approval.digest, network: model.network(approval.intent.network),114                                  ownAddresses: Dictionary(uniqueKeysWithValues: (model.accounts?.value.accounts ?? []).map { ($0.network, $0.address) }),115                                  warnings: approval.proposal.warnings ?? [],116                                  extra: approval.proposal.feeDisplay.map { [ReviewLine(label: "Frais estimés", value: "\($0) \(approval.proposal.feeSymbol ?? "") (estimation ; le plafond ci-dessus est ce qui est signé)")] } ?? [])117                    .padding(20)118            }119            Divider()120            VStack(alignment: .leading, spacing: 8) {121                if let e = flow.error { Banner(.danger, e) }122                HStack {123                    Button("Rejeter", role: .destructive) { Task { await flow.reject() } }.disabled(flow.step == .approving)124                    Spacer()125                    if flow.step == .approving { ProgressView().controlSize(.small); Text("Passkey, puis signature isolée…").foregroundStyle(.secondary) }126                    Button { Task { await flow.approve() } } label: { Label("Approuver avec la passkey", systemImage: "touchid") }127                        .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.step == .approving)128                }129            }.padding(16)130        }131        .frame(width: 720, height: 760)132        .interactiveDismissDisabled()133    }134}135136/// After approval: every state change as it happened. Success is announced only at `finalized`.137struct TrackingCard: View {138    let flow: SendFlow139    var body: some View {140        if let p = flow.tracked {141            Card("Suivi de la transaction") {142                ProposalStatusView(proposal: p)143                Divider()144                VStack(alignment: .leading, spacing: 4) {145                    Text("Historique des états").font(.caption).foregroundStyle(.secondary)146                    ForEach(Array(flow.history.enumerated()), id: \.offset) { _, h in147                        HStack { Text(Fmt.dateSeconds(h.0)).monospacedDigit().foregroundStyle(.secondary); Text(ErrorText.state(h.1)) }.font(.callout)148                    }149                }150                HStack { Spacer(); Button(p.state.isTerminal ? "Nouvel envoi" : "Nouvel envoi (le suivi continue dans Activité)") { flow.reset() } }151            }152        }153    }154}155156/// The state of one proposal, with the exact vocabulary: signed ≠ broadcast ≠ confirming ≠ finalized.157struct ProposalStatusView: View {158    let proposal: Proposal159    var body: some View {160        let p = proposal161        VStack(alignment: .leading, spacing: 10) {162            HStack(spacing: 10) {163                Group {164                    if p.state.isSuccess { Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive) }165                    else if p.state.isFailure || p.state == .notBroadcast { Image(systemName: "xmark.octagon.fill").foregroundStyle(Theme.negative) }166                    else { ProgressView().controlSize(.small) }167                }.font(.title2)168                VStack(alignment: .leading) {169                    Text(ErrorText.state(p.state)).font(.title3.weight(.semibold))170                    Text(explanation(p.state)).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)171                }172            }173            Field(label: "Montant", value: "\(Fmt.amount(p.amountDisplay)) \(p.symbol) · \(p.networkName ?? p.network)")174            if let to = p.to { Field(label: "Destinataire", value: to, mono: true) }175            if let tx = p.txid { Field(label: "Identifiant de transaction", value: tx, mono: true) }176            if let c = p.confirmations, p.txid != nil { Field(label: "Confirmations", value: String(c)) }177            if let e = p.error { Banner(p.state.isFailure || p.state == .notBroadcast ? .danger : .warning, e) }178            if let ex = p.explorer, let url = URL(string: ex), url.scheme == "https" { Link("Ouvrir dans l’explorateur de blocs", destination: url) }179        }180    }181    private func explanation(_ s: ProposalState) -> String {182        switch s {183        case .approved: "Approbation transmise au signataire isolé."184        case .signed: "Transaction signée ; pas encore relayée au réseau."185        case .broadcast: "Relayée au réseau. Un identifiant de transaction n’est pas une confirmation : elle peut encore être abandonnée ou remplacée."186        case .confirming: "Incluse dans un bloc ; en attente du nombre de confirmations requis."187        case .finalized: "Confirmée par la chaîne au seuil de finalité du réseau."188        case .reorged: "Le bloc qui la contenait a été réorganisé ; la confirmation est à refaire."189        case .notBroadcast: "Le serveur est en mode test : la transaction a été signée mais volontairement pas relayée. Rien n’a été envoyé."190        case .failed, .rejected, .expired, .replaced: "Aucun succès. Vérifiez le détail ci-dessous."191        default: ""192        }193    }194}195
Files main
Menu

Theme