SPB Git

Repository Public

PlanPanel.swift 29.0 KB 420 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/DeFi/PlanPanel.swift3// Description: The any-to-any plan screen inside the DeFi hub: the form and the candidate multi-leg routes (every leg with its provider, expected and worst-case amounts, fees, gas and signer-limit requirements), then the running plan — each leg's real state, what it actually spent and received, its attempts — with the one action that is the owner's at that moment: prepare a leg, approve it by passkey on its verified intent, wait, or decide after a pause (retry, re-plan, stop).4import SwiftUI5import SPWalletCore67struct PlanPanel: View {8    let model: AppModel9    @State private var flow: PlanFlow?1011    var body: some View {12        Group {13            if let flow {14                if let e = flow.loadError { Card("Parcours multi-étapes") { Banner(.danger, "Parcours illisibles : \(e)") } }15                if let p = flow.plan { ActivePlanCard(model: model, flow: flow, plan: p) }16                else if flow.loaded {17                    PlanFormCard(model: model, flow: flow)18                    if let q = flow.quote { PlanCandidatesCard(model: model, flow: flow, quote: q) }19                }20                if !flow.recent.isEmpty, flow.plan?.isOpen != true { RecentPlansCard(plans: flow.recent) }21            } else { ProgressView() }22        }23        .task {24            if flow == nil { flow = PlanFlow(model: model) }25            await flow?.load()26        }27        .task(id: "\(flow?.plan?.id ?? "")|\(flow?.plan?.next.rawValue ?? "")|\(flow?.operation == nil)") { await flow?.follow() }28        .sheet(isPresented: Binding(get: { flow?.operation != nil }, set: { _ in })) {29            if let flow, let op = flow.operation, let p = flow.plan { PlanLegReviewSheet(model: model, flow: flow, plan: p, operation: op) }30        }31    }32}3334@MainActor enum PlanText {35    static func kind(_ k: String) -> String {36        switch k { case "swap": "Échange sur le même réseau"; case "bridge": "Pont USDC (Circle CCTP)"; case "xswap": "Échange natif inter-chaînes (THORChain)"; default: k }37    }38    static func legState(_ s: PlanLegState) -> String {39        switch s {40        case .pending: "Pas encore son tour"41        case .ready: "Prête à être préparée"42        case .proposed: "Préparée — en attente de la passkey"43        case .inFlight: "Approuvée — en vol, pas encore réglée"44        case .settled: "Réglée (montant lu sur la chaîne)"45        default: s.rawValue46        }47    }48    static func planState(_ p: PlanView) -> String {49        switch p.state {50        case .active: "En cours"51        case .paused: "En pause — une décision est attendue"52        case .done: p.isComplete ? "Terminé : toutes les étapes sont réglées" : "Terminé"53        case .stopped: "Arrêté — les fonds sont restés où ils étaient"54        default: p.state.rawValue55        }56    }57    static func pause(_ code: String) -> String {58        switch code {59        case "no_funds": "Le portefeuille ne détient plus l’actif de cette étape."60        case "floor": "Le résultat final estimé est passé sous votre plancher."61        case "refused": "L’étape a été rejetée ou son approbation a expiré."62        case "refunded": "THORChain a remboursé l’actif source : l’étape n’a pas eu lieu."63        case "leg_failed": "L’étape a échoué."64        default: "La préparation de l’étape a été refusée (\(code))."65        }66    }67    static func issue(_ i: PlanIssue) -> String {68        let need = "\(Fmt.amount(i.needDisplay, maxFraction: 8)) \(i.symbol)", have = "\(Fmt.amount(i.haveDisplay, maxFraction: 8)) \(i.symbol)", net = i.networkName ?? i.network69        let leg = i.leg.map { "Étape \($0 + 1) : " } ?? ""70        let text: String = switch i.code {71        case "insufficient_balance": "solde insuffisant sur \(net) (requis \(need), détenu \(have))"72        case "limit_missing": "le signataire n’a aucune limite définie pour \(i.symbol) sur \(net)"73        case "limit_per_transfer": "dépasse la limite par transfert du signataire sur \(net) (requis \(need), limite \(have))"74        case "limit_daily": "dépasse ce qui reste de la limite quotidienne du signataire sur \(net) (requis \(need), reste \(have))"75        case "limit_margin": "trop proche de la limite du signataire sur \(net) (requis \(need), disponible \(have))"76        case "below_minimum": "sous le minimum du protocole (minimum \(need), prévu \(have))"77        case "gas_missing": "pas assez de \(i.symbol) sur \(net) pour les frais (requis \(need), détenu \(have))"78        case "gas_unknown": "le solde de \(i.symbol) sur \(net) n’a pas pu être lu (requis \(need))"79        default: "\(i.code) sur \(net) (requis \(need), disponible \(have))"80        }81        return leg + text82    }83    static func notExecutable(_ n: PlanQuote.NotExecutable, model: AppModel) -> String {84        switch n.code {85        case "same_asset": "Départ et arrivée sont le même actif."86        case "solana_evm_bridge": "Aucun parcours exécutable entre ces deux actifs avec les capacités actuelles du serveur (liaison Solana ↔ EVM non chaînable ici)."87        case "network_without_execution": "Le portefeuille n’exécute aucun échange sur \(n.network.map { model.network($0)?.name ?? $0 } ?? "ce réseau") : aucun parcours ne peut y commencer ou y finir par un échange."88        case "no_executable_path": "Aucun enchaînement d’étapes exécutables ne relie ces deux actifs."89        default: "Aucun parcours exécutable (\(n.code))."90        }91    }92    static func fee(_ f: PlanCandidate.Fee) -> String {93        let kind: String = switch f.kind { case "network": "Réseau"; case "protocol": "Protocole"; case "provider": "Fournisseur"; case "bridge": "Pont"; case "affiliate": "Affiliation"; default: f.kind }94        return "\(kind) : \(Fmt.amount(f.display, maxFraction: 8)) \(f.symbol) (\(f.networkName ?? f.network))" + (f.usd.map { " \(SwapText.usd($0))" } ?? "") + (f.includedInOutput == true ? " — déjà déduit" : " — en sus") + (f.estimated == true ? " — estimé" : "")95    }96    static func asset(_ a: SwapAsset) -> String { "\(a.symbol) sur \(a.networkName ?? a.network)" }97}9899// MARK: - Form and candidates100101private struct PlanFormCard: View {102    let model: AppModel103    @Bindable var flow: PlanFlow104105    var body: some View {106        Card("Parcours multi-étapes — d’un actif sur un réseau à un autre actif sur un autre réseau") {107            Text("Un parcours enchaîne jusqu’à trois opérations ordinaires (échange, pont USDC, échange natif). Il ne détient jamais vos fonds : entre deux étapes, ils sont un solde ordinaire de ce portefeuille. Chaque étape exige sa propre approbation par passkey ; rien n’avance tout seul.")108                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)109            HStack(alignment: .bottom, spacing: 12) {110                VStack(alignment: .leading, spacing: 4) {111                    Text("Départ").font(.caption).foregroundStyle(.secondary)112                    SwapAssetPicker(model: model, label: "Actif de départ", assets: flow.assets, selection: $flow.fromKey, exclude: flow.toKey)113                }114                Image(systemName: "arrow.right").foregroundStyle(.secondary).padding(.bottom, 14)115                VStack(alignment: .leading, spacing: 4) {116                    Text("Arrivée").font(.caption).foregroundStyle(.secondary)117                    SwapAssetPicker(model: model, label: "Actif d’arrivée", assets: flow.assets, selection: $flow.toKey, exclude: flow.fromKey)118                }119            }120            HStack {121                TextField("Montant de départ", text: $flow.amount, prompt: Text("0.0")).textFieldStyle(.roundedBorder).frame(maxWidth: 220)122                Text(flow.from?.symbol ?? "").foregroundStyle(.secondary)123                if let f = flow.from, let b = SwapText.balance(model, of: f) {124                    Text(b.isAvailable ? "Solde : \(model.settings.hideBalances ? "••••" : Fmt.amount(b.display, maxFraction: 8))" : "Solde indisponible").font(.callout).foregroundStyle(b.isAvailable ? Color.secondary : Theme.negative)125                }126                Spacer()127            }128            HStack {129                Text("Tolérance par étape").foregroundStyle(.secondary)130                TextField("%", text: $flow.slippageText).textFieldStyle(.roundedBorder).frame(width: 64).multilineTextAlignment(.trailing)131                Text("%  (0,01 – 3 ; défaut du serveur 0,5)").foregroundStyle(.secondary)132                Spacer()133                Text("Plancher global (facultatif)").foregroundStyle(.secondary)134                TextField("aucun", text: $flow.floorText).textFieldStyle(.roundedBorder).frame(width: 130).multilineTextAlignment(.trailing)135                Text(flow.to?.symbol ?? "").foregroundStyle(.secondary)136            }137            Text("Plancher : avant chaque étape, si le résultat final estimé passe sous ce montant, le parcours se met en pause au lieu de continuer.").font(.caption).foregroundStyle(.secondary)138            if let e = flow.error { Banner(.danger, e) }139            HStack {140                if let p = flow.formProblem, !flow.amount.isEmpty { Text(p).font(.callout).foregroundStyle(Theme.warning) }141                Spacer()142                if flow.busy == .quoting { ProgressView().controlSize(.small); Text("Cotation réelle de chaque étape…").font(.callout).foregroundStyle(.secondary) }143                Button("Chercher des parcours") { Task { await flow.quotePlans() } }.buttonStyle(.borderedProminent)144                    .disabled(flow.formProblem != nil || !model.canOperate || flow.busy != nil)145            }146            Text("Chercher ne prépare rien, ne signe rien et n’enregistre rien.").font(.caption).foregroundStyle(.secondary)147        }148    }149}150151private struct PlanCandidatesCard: View {152    let model: AppModel153    let flow: PlanFlow154    let quote: PlanQuote155156    var body: some View {157        Card("Parcours possibles (\(quote.plans.count))", trailing: flow.quotedAt.map { AnyView(Text("Cotés \(Fmt.relative($0))").font(.caption).foregroundStyle(.secondary)) }) {158            if !flow.quoteIsCurrent { Banner(.warning, "Le formulaire a changé depuis cette recherche : relancez-la avant de démarrer un parcours.") }159            if let n = quote.notExecutable { Banner(.warning, PlanText.notExecutable(n, model: model)) }160            else if quote.plans.isEmpty { Banner(.warning, "Aucun parcours n’a de cotation en ce moment.") }161            ForEach(quote.plans) { c in candidate(c); Divider() }162            if !quote.skipped.isEmpty {163                Text("Formes écartées faute de cotation").font(.caption).foregroundStyle(.secondary)164                ForEach(Array(quote.skipped.enumerated()), id: \.offset) { _, s in165                    Text("• étape \(s.leg + 1) : \(s.message) [\(s.code)]").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)166                }167            }168        }169    }170171    @ViewBuilder private func candidate(_ c: PlanCandidate) -> some View {172        VStack(alignment: .leading, spacing: 8) {173            HStack(alignment: .firstTextBaseline) {174                Text("\(c.legs.count) étape\(c.legs.count > 1 ? "s" : "") · \(c.approvals) approbation\(c.approvals > 1 ? "s" : "") par passkey · \(SwapText.duration(c.seconds))").font(.headline)175                Spacer()176                if c.executable { Label("Peut démarrer", systemImage: "checkmark.seal").foregroundStyle(Theme.positive).font(.callout) }177                else { Label("Ne peut pas démarrer", systemImage: "xmark.octagon").foregroundStyle(Theme.negative).font(.callout) }178            }179            HStack(spacing: 8) {180                Text("Attendu : \(Fmt.amount(c.expectedOutDisplay, maxFraction: 8)) \(c.to.symbol)").fontWeight(.semibold).monospacedDigit()181                ProvenanceTag(p: .estimate)182                Text("Pire cas (chaque étape à son minimum garanti) : \(Fmt.amount(c.worstOutDisplay, maxFraction: 8)) \(c.to.symbol)").monospacedDigit().foregroundStyle(.secondary)183            }184            if c.expectedUsd != nil || c.extraFeesUsd != nil {185                Text("Valorisation : entrée \(SwapText.usd(c.inUsd)) · sortie attendue \(SwapText.usd(c.expectedUsd)) · pire cas \(SwapText.usd(c.worstUsd)) · frais en sus \(SwapText.usd(c.extraFeesUsd))").font(.caption).foregroundStyle(.secondary)186            }187            ForEach(Array(c.legs.enumerated()), id: \.offset) { k, l in leg(k, l) }188            if let r = c.requirements, !r.gas.isEmpty || !r.limits.isEmpty { requirements(r) }189            ForEach(Array(c.issues.enumerated()), id: \.offset) { _, i in190                Label(PlanText.issue(i), systemImage: i.blocking ? "xmark.octagon.fill" : "exclamationmark.triangle.fill").font(.callout)191                    .foregroundStyle(i.blocking ? Theme.negative : Theme.warning).fixedSize(horizontal: false, vertical: true)192            }193            HStack {194                Spacer()195                if flow.busy == .starting(c.id) { ProgressView().controlSize(.small) }196                Button("Démarrer ce parcours") { Task { await flow.start(c) } }197                    .disabled(!c.executable || !flow.quoteIsCurrent || !model.canOperate || flow.busy != nil)198                    .help("Enregistre le parcours sur le serveur. Rien n’est préparé ni signé : la première étape devient « prête ».")199            }200        }201    }202203    private func leg(_ k: Int, _ l: PlanCandidate.Leg) -> some View {204        VStack(alignment: .leading, spacing: 2) {205            Text("\(k + 1). \(PlanText.kind(l.kind)) — \(l.label ?? l.via)\(l.speed.map { " · \($0)" } ?? "")").fontWeight(.medium)206            Text("\(PlanText.asset(l.from)) → \(PlanText.asset(l.to))" + ((l.venues ?? []).isEmpty ? "" : " · via \((l.venues ?? []).joined(separator: ", "))") + " · \(SwapText.duration(l.seconds))").font(.callout).foregroundStyle(.secondary)207            Text("Entrée attendue \(Fmt.amount(l.expectedInDisplay, maxFraction: 8)) \(l.from.symbol) (pire cas \(Fmt.amount(l.worstInDisplay, maxFraction: 8))) → sortie attendue \(Fmt.amount(l.expectedOutDisplay, maxFraction: 8)) \(l.to.symbol) · minimum \(Fmt.amount(l.worstOutDisplay, maxFraction: 8)) \(l.to.symbol)")208                .font(.callout).monospacedDigit().fixedSize(horizontal: false, vertical: true)209            ForEach(Array((l.fees ?? []).enumerated()), id: \.offset) { _, f in Text(PlanText.fee(f)).font(.caption).foregroundStyle(.secondary) }210        }211        .padding(8).frame(maxWidth: .infinity, alignment: .leading).background(Color.secondary.opacity(0.06), in: RoundedRectangle(cornerRadius: 8))212    }213214    private func requirements(_ r: PlanCandidate.Requirements) -> some View {215        VStack(alignment: .leading, spacing: 2) {216            Text("Prérequis vérifiés par le serveur").font(.caption).foregroundStyle(.secondary)217            ForEach(Array(r.gas.enumerated()), id: \.offset) { _, g in218                Label("Frais sur \(g.networkName ?? g.network) : \(Fmt.amount(g.needDisplay, maxFraction: 8)) \(g.symbol) requis · détenu \(g.haveDisplay.map { Fmt.amount($0, maxFraction: 8) } ?? "illisible")", systemImage: g.ok ? "checkmark.circle" : "xmark.circle")219                    .font(.caption).foregroundStyle(g.ok ? Color.secondary : Theme.negative)220            }221            ForEach(Array(r.limits.enumerated()), id: \.offset) { _, l in222                Label("Limites du signataire, étape \(l.leg + 1) : \(Fmt.amount(l.needDisplay, maxFraction: 8)) \(l.symbol) requis · par transfert \(Fmt.amount(l.perTransferDisplay, maxFraction: 8)) · reste aujourd’hui \(Fmt.amount(l.leftTodayDisplay, maxFraction: 8))", systemImage: l.ok ? "checkmark.circle" : "xmark.circle")223                    .font(.caption).foregroundStyle(l.ok ? Color.secondary : Theme.negative)224            }225        }226    }227}228229// MARK: - The running plan230231private struct ActivePlanCard: View {232    let model: AppModel233    @Bindable var flow: PlanFlow234    let plan: PlanView235236    var body: some View {237        Card("Parcours \(PlanText.asset(plan.from)) → \(PlanText.asset(plan.to))", trailing: AnyView(HStack(spacing: 8) {238            if SwapText.isSimulatedServer(model) { ProvenanceTag(p: .simulated, text: "Serveur de test") }239            Button("Relire") { Task { await flow.refresh() } }.controlSize(.small).disabled(flow.busy != nil || model.phase != .signedIn)240        })) {241            header242            if let pz = plan.pause, plan.state == .paused {243                Banner(.warning, "Pause à l’étape \(pz.leg + 1) — \(PlanText.pause(pz.code))\nServeur : \(pz.message)")244            }245            ForEach(plan.legs) { l in PlanLegRow(model: model, plan: plan, leg: l) }246            if let e = flow.readError { Banner(.warning, "Dernière lecture du parcours en échec : \(e)") }247            if let e = flow.error { Banner(.danger, e) }248            Divider()249            actions250        }251    }252253    @ViewBuilder private var header: some View {254        HStack(spacing: 10) {255            Group {256                if plan.isComplete { Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive) }257                else if plan.state == .stopped { Image(systemName: "stop.circle.fill").foregroundStyle(.secondary) }258                else if plan.state == .paused { Image(systemName: "pause.circle.fill").foregroundStyle(Theme.warning) }259                else if plan.next == .wait { ProgressView().controlSize(.small) }260                else { Image(systemName: "hand.raised.circle.fill").foregroundStyle(Theme.accent) }261            }.font(.title2)262            VStack(alignment: .leading) {263                Text(PlanText.planState(plan)).font(.title3.weight(.semibold))264                Text("Étape \(min(plan.current + 1, max(plan.legs.count, 1))) sur \(plan.legs.count)" + (plan.replans > 0 ? " · re-planifié \(plan.replans) fois" : "")).font(.callout).foregroundStyle(.secondary)265            }266        }267        Field(label: "Montant de départ", value: "\(Fmt.amount(plan.amountInDisplay)) \(plan.from.symbol)")268        Field(label: "Prévu au démarrage", value: "attendu \(Fmt.amount(plan.plannedExpectedDisplay, maxFraction: 8)) \(plan.to.symbol) · pire cas \(Fmt.amount(plan.plannedWorstDisplay, maxFraction: 8)) \(plan.to.symbol) (information, pas une promesse)")269        if let e = plan.estimate { Field(label: "Estimation actuelle", value: "attendu \(Fmt.amount(e.expectedOutDisplay, maxFraction: 8)) · pire cas \(Fmt.amount(e.worstOutDisplay, maxFraction: 8)) \(plan.to.symbol)" + (e.at.map { " — \(Fmt.relative($0))" } ?? "")) }270        Field(label: "Plancher global", value: plan.floorDisplay.map { "\(Fmt.amount($0, maxFraction: 8)) \(plan.to.symbol)" } ?? "aucun")271        Field(label: "Tolérance par étape", value: SwapText.bps(plan.slippageBps))272        if plan.isComplete, let r = plan.receivedDisplay {273            HStack { Field(label: "Reçu à l’arrivée", value: "\(Fmt.amount(r)) \(plan.to.symbol) sur \(plan.to.networkName ?? plan.to.network)", emphasis: true); ProvenanceTag(p: .verified) }274        } else {275            Field(label: "Où sont les fonds", value: "\(Fmt.amount(plan.holding.amountDisplay)) \(plan.holding.symbol) sur \(plan.holding.networkName ?? plan.holding.network) — solde ordinaire de ce portefeuille" + (plan.next == .wait ? " (une étape est en vol : ce chiffre date d’avant son départ)" : ""))276        }277    }278279    @ViewBuilder private var actions: some View {280        let k = plan.current + 1281        switch plan.next {282        case .prepare:283            HStack {284                Text("L’étape \(k) est prête. La préparer demande une route ferme au serveur et ne signe rien ; vous approuverez ensuite sur l’écran de vérification.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)285                Spacer()286                secondary287                if flow.busy == .preparing { ProgressView().controlSize(.small) }288                Button("Préparer l’étape \(k)…") { Task { await flow.prepareLeg() } }.buttonStyle(.borderedProminent).disabled(!model.canOperate || flow.busy != nil)289            }290        case .approve:291            HStack {292                Text("Une demande d’approbation existe déjà pour l’étape \(k) mais cette app n’en détient pas le défi vérifié. La préparer de nouveau retire l’ancienne demande (jamais utilisée) et en émet une nouvelle, vérifiée avant toute signature.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)293                Spacer()294                secondary295                if flow.busy == .preparing { ProgressView().controlSize(.small) }296                Button("Préparer de nouveau l’étape \(k)…") { Task { await flow.prepareLeg() } }.buttonStyle(.borderedProminent).disabled(!model.canOperate || flow.busy != nil)297            }298        case .wait:299            HStack { ProgressView().controlSize(.small); Text("Étape \(k) en vol. La suivante ne sera proposée qu’une fois son résultat lu sur la chaîne. Un parcours ne peut pas être arrêté pendant qu’une étape est en vol.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }300        case .paused:301            VStack(alignment: .leading, spacing: 8) {302                Text("À vous de décider — aucune de ces actions ne signe quoi que ce soit :").font(.callout)303                HStack {304                    Button("Réessayer l’étape \(k)") { Task { await flow.retry(.unchanged) } }.buttonStyle(.borderedProminent)305                    if plan.floor != nil { Button("Réessayer sans plancher") { Task { await flow.retry(.remove) } } }306                    TextField("nouveau plancher", text: $flow.newFloorText).textFieldStyle(.roundedBorder).frame(width: 140)307                    Button("Réessayer avec ce plancher") { Task { await flow.retry(.set) } }.disabled(flow.newFloorText.trimmingCharacters(in: .whitespaces).isEmpty)308                    Spacer()309                    if flow.busy != nil { ProgressView().controlSize(.small) }310                }311                HStack { secondary; Spacer() }312            }.disabled(!model.canOperate || flow.busy != nil)313        case .done, .stopped:314            HStack {315                Text(plan.isComplete ? "Toutes les étapes sont réglées." : "Parcours clos. Les fonds sont un solde ordinaire du portefeuille.").font(.callout).foregroundStyle(.secondary)316                Spacer()317                Button("Nouveau parcours") { flow.dismissFinished() }318            }319        default:320            Text("Action suivante inconnue de cette version de l’app : « \(plan.next.rawValue) ». Aucune action n’est proposée.").foregroundStyle(Theme.warning)321        }322    }323324    @ViewBuilder private var secondary: some View {325        Button("Re-planifier depuis l’actif détenu") { Task { await flow.replan() } }326            .help("Remplace les étapes restantes par la meilleure route exécutable depuis l’actif actuellement détenu, vers la même arrivée.")327            .disabled(!model.canOperate || flow.busy != nil)328        Button("Arrêter ici", role: .destructive) { Task { await flow.stop() } }329            .help("Définitif. Une demande d’approbation inutilisée est retirée ; les fonds restent où ils sont.")330            .disabled(!model.canOperate || flow.busy != nil)331    }332}333334private struct PlanLegRow: View {335    let model: AppModel336    let plan: PlanView337    let leg: PlanView.Leg338339    var body: some View {340        let current = leg.index == plan.current && plan.isOpen341        VStack(alignment: .leading, spacing: 4) {342            HStack(alignment: .firstTextBaseline) {343                icon344                Text("Étape \(leg.index + 1) — \(PlanText.kind(leg.kind))\((leg.label ?? leg.via).map { " · \($0)" } ?? "")\(leg.speed.map { " · \($0)" } ?? "")").fontWeight(.semibold)345                Spacer()346                Text(PlanText.legState(leg.state)).font(.callout).foregroundStyle(leg.isSettled ? Theme.positive : current ? Theme.warning : .secondary)347            }348            Text("\(PlanText.asset(leg.from)) → \(PlanText.asset(leg.to)) · \(SwapText.duration(leg.seconds))").font(.callout).foregroundStyle(.secondary)349            Text("Prévu : entrée \(Fmt.amount(leg.planned.expectedInDisplay, maxFraction: 8)) \(leg.from.symbol) → sortie \(Fmt.amount(leg.planned.expectedOutDisplay, maxFraction: 8)) \(leg.to.symbol) (minimum \(Fmt.amount(leg.planned.worstOutDisplay, maxFraction: 8)))")350                .font(.callout).monospacedDigit().fixedSize(horizontal: false, vertical: true)351            if leg.actual.inDisplay != nil || leg.actual.outDisplay != nil {352                HStack(spacing: 6) {353                    Text("Réel : entrée \(leg.actual.inDisplay.map { Fmt.amount($0, maxFraction: 8) } ?? "—") \(leg.from.symbol) → sortie \(leg.actual.outDisplay.map { Fmt.amount($0, maxFraction: 8) } ?? "pas encore lue") \(leg.to.symbol)").font(.callout).monospacedDigit().fontWeight(.medium)354                    if leg.isSettled { ProvenanceTag(p: .verified) }355                }356            }357            ForEach(Array(leg.attempts.enumerated()), id: \.offset) { n, a in358                if a.outcome != nil || a.error != nil {359                    Text("Tentative \(n + 1) : \(outcome(a.outcome))\(a.error.map { " — \($0)" } ?? "")\(a.at.map { " · \(Fmt.date($0))" } ?? "")").font(.caption)360                        .foregroundStyle(a.outcome == "settled" ? Color.secondary : Theme.warning).fixedSize(horizontal: false, vertical: true)361                }362            }363            if let ex = leg.execution, leg.state == .proposed || leg.state == .inFlight || leg.isSettled { ExecutionTimeline(model: model, status: ex).padding(.top, 2) }364        }365        .padding(10).frame(maxWidth: .infinity, alignment: .leading)366        .background(current ? Theme.accent.opacity(0.06) : Color.secondary.opacity(0.05), in: RoundedRectangle(cornerRadius: 8))367    }368369    @ViewBuilder private var icon: some View {370        switch leg.state {371        case .settled: Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive)372        case .inFlight: Image(systemName: "paperplane.circle.fill").foregroundStyle(Theme.warning)373        case .proposed: Image(systemName: "touchid").foregroundStyle(Theme.warning)374        case .ready: Image(systemName: "circle.dotted").foregroundStyle(Theme.accent)375        default: Image(systemName: "circle").foregroundStyle(.tertiary)376        }377    }378    private func outcome(_ o: String?) -> String {379        switch o { case "settled": "réglée"; case "failed": "échouée"; case "rejected": "rejetée"; case "expired": "expirée ou retirée"; case "refunded": "remboursée"; case nil: "en cours"; case let x?: x }380    }381}382383private struct PlanLegReviewSheet: View {384    let model: AppModel385    let flow: PlanFlow386    let plan: PlanView387    let operation: ApprovableOperation388389    var body: some View {390        OperationReviewSheet(model: model, title: "Étape \(plan.current + 1) sur \(plan.legs.count) — vérifier et approuver", operation: operation, notices: notices,391                             extra: OperationReviewSheet.contextLines(model: model, operation: operation),392                             busy: flow.busy == .approving, error: flow.reviewError,393                             onReject: { Task { await flow.rejectLeg() } }, onApprove: { Task { await flow.approveLeg() } })394    }395396    private var notices: [(Banner.Kind, String)] {397        var out: [(Banner.Kind, String)] = [(.info, "Cette approbation ne couvre QUE cette étape du parcours. L’app a vérifié qu’elle correspond à l’étape affichée (même parcours, même position, mêmes actifs et réseaux), que son montant ne dépasse pas ce que le parcours détient, et que les deux extrémités sont des adresses de ce portefeuille. Une étape de parcours n’a pas de cotation de référence : le minimum garanti est celui affiché ci-dessous.")]398        if let a = OperationReviewSheet.spendApproval(operation.intent, model: model) { out.append(a) }399        if operation.intent.kind == .xswap { out.append((.info, "Le signataire isolé exige l’unanimité d’au moins trois opérateurs THORNode sur le coffre : sinon il refuse de signer (échec fermé) et le parcours se met en pause.")) }400        if operation.intent.kind == .bridge { out.append((.info, "Cette approbation couvre la destruction sur la source et la première émission sur la destination ; l’étape n’est réglée qu’une fois l’émission confirmée.")) }401        return out402    }403}404405private struct RecentPlansCard: View {406    let plans: [PlanView]407    var body: some View {408        Card("Parcours précédents") {409            ForEach(plans) { p in410                HStack {411                    Text("\(Fmt.amount(p.amountInDisplay, maxFraction: 8)) \(p.from.symbol) (\(p.from.networkName ?? p.from.network)) → \(p.to.symbol) (\(p.to.networkName ?? p.to.network))")412                    Spacer()413                    Text(p.isComplete ? "Terminé — reçu \(p.receivedDisplay.map { Fmt.amount($0, maxFraction: 8) } ?? "—") \(p.to.symbol)" : PlanText.planState(p)).foregroundStyle(p.isComplete ? Theme.positive : .secondary)414                    Text(Fmt.date(p.updatedAt ?? p.createdAt)).foregroundStyle(.secondary).monospacedDigit()415                }.font(.callout)416            }417        }418    }419}420
Files main
Menu

Theme