SPB Git

Repository Public

SwapView.swift 28.5 KB 412 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Swap/SwapView.swift3// Description: Swapping: the pair, the amount and the tolerance; the live comparison of every provider's quote with the one route this wallet can really execute put forward (the others are labelled comparison-only, with the reason); the review of the verified intent (router, calldata fingerprint, guaranteed minimum, exact-amount spend approval, simulation); the passkey; then the honest tracking — approval transaction, swap transaction, and the received amount only once it was read from the chain. Native cross-chain pairs (THORChain) use the same screen and say so.4import SwiftUI5import SPWalletCore67struct SwapView: View {8    let model: AppModel9    @State private var flow: SwapFlow?1011    var body: some View {12        Page("Échanger", subtitle: "Les cotations comparent plusieurs fournisseurs ; seule la route exécutable par ce portefeuille peut être préparée, puis approuvée par passkey.") {13            if let flow {14                if !model.canOperate { Banner(.warning, "Échange impossible pour l’instant : session ou portefeuille indisponible. Aucune cotation n’est demandée hors connexion.") }15                if SwapText.isSimulatedServer(model) { Banner(.warning, "SERVEUR DE TEST : les transactions sont signées mais ne sont PAS diffusées. Aucun échange réel n’aura lieu depuis ce serveur.") }16                if model.portfolio?.value.halted == true { Banner(.danger, "Arrêt d’urgence actif : le signataire ne signe plus rien.") }17                if let e = flow.loadError { Banner(.danger, "Capacités d’échange illisibles : \(e)") }18                if flow.step == .tracking, let t = flow.tracker {19                    SwapTrackingCard(model: model, flow: flow, tracker: t)20                } else if flow.loaded {21                    SwapFormCard(model: model, flow: flow)22                    SwapQuoteSection(model: model, flow: flow)23                } else if flow.loadError == nil { ProgressView("Lecture des actifs et des fournisseurs…") }24            } else { ProgressView() }25        }26        .task {27            if flow == nil { flow = SwapFlow(model: model) }28            if flow?.loaded != true { await flow?.load() }29        }30        .task(id: flow?.quoteKey) { await flow?.runQuotes() }31        .task(id: flow?.tracker?.proposal.id) { await flow?.tracker?.follow() }32        .sheet(isPresented: Binding(get: { flow?.step == .review || flow?.step == .approving }, set: { _ in })) {33            if let flow, let op = flow.operation { SwapReviewSheet(model: model, flow: flow, operation: op) }34        }35    }36}3738// MARK: - Form3940private struct SwapFormCard: View {41    let model: AppModel42    @Bindable var flow: SwapFlow4344    var body: some View {45        Card("Paire et montant") {46            HStack(alignment: .bottom, spacing: 12) {47                VStack(alignment: .leading, spacing: 4) {48                    Text("Vous vendez").font(.caption).foregroundStyle(.secondary)49                    SwapAssetPicker(model: model, label: "Actif vendu", assets: flow.assets, selection: $flow.fromKey, exclude: flow.toKey)50                }51                Button { flow.flip() } label: { Image(systemName: "arrow.left.arrow.right") }.help("Inverser la paire").padding(.bottom, 10)52                    .accessibilityLabel("Inverser la paire")53                VStack(alignment: .leading, spacing: 4) {54                    Text("Vous achetez").font(.caption).foregroundStyle(.secondary)55                    SwapAssetPicker(model: model, label: "Actif acheté", assets: flow.assets, selection: $flow.toKey, exclude: flow.fromKey)56                }57            }58            .disabled(flow.step != .form)59            if let f = flow.from, let t = flow.to { pairFacts(f, t) }60            HStack {61                TextField("Montant vendu", text: $flow.amount, prompt: Text("0.0")).textFieldStyle(.roundedBorder).frame(maxWidth: 260)62                Text(flow.from?.symbol ?? "").foregroundStyle(.secondary)63                Button("Max") { flow.setMax() }.disabled(flow.balance?.isAvailable != true)64                    .help(flow.from?.asset == "native" ? "Solde entier : les frais de réseau devront en être déduits, le serveur refusera sinon." : "Solde entier de cet actif")65                Spacer()66                balanceText67            }68            .disabled(flow.step != .form)69            if let a = flow.parsedAmount, !a.isZero, let f = flow.from, let p = model.price(f.symbol) {70                HStack(spacing: 6) {71                    Text(Fmt.fiat(a.approximate(decimals: f.decimals) * p.value(in: model.currency), model.currency)).foregroundStyle(.secondary).font(.callout)72                    ProvenanceTag(p: p.stale ? .stale : .estimate)73                }74            }75            slippage76            if let p = flow.formProblem, !flow.amount.isEmpty { Text(p).font(.callout).foregroundStyle(Theme.warning) }77        }78    }7980    @ViewBuilder private var balanceText: some View {81        if flow.from == nil { EmptyView() }82        else if let b = flow.balance, b.isAvailable { Text("Solde : \(model.settings.hideBalances ? "••••" : Fmt.amount(b.display)) \(b.symbol)").monospacedDigit().foregroundStyle(.secondary) }83        else if flow.balance != nil { Text("Solde indisponible (lecture de chaîne en échec)").foregroundStyle(Theme.negative) }84        else { Text("Solde : —").foregroundStyle(.secondary) }85    }8687    @ViewBuilder private func pairFacts(_ f: SwapAsset, _ t: SwapAsset) -> some View {88        VStack(alignment: .leading, spacing: 4) {89            Text(f.network == t.network ? "Réseau : \(f.networkName ?? f.network)" : "Réseaux : \(f.networkName ?? f.network) → \(t.networkName ?? t.network)").font(.callout)90            if f.asset != "native" { Text("Contrat vendu : \(f.asset)").font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) }91            if t.asset != "native" { Text("Contrat acheté : \(t.asset)").font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) }92        }93        let hint = flow.capabilityHint94        if flow.isBridgePair {95            Banner(.info, "USDC → USDC entre deux réseaux est un transfert Circle CCTP : il se prépare dans « Pont inter-chaînes » (barre latérale), avec ses deux vitesses et leurs frais. Les cotations ci-dessous ne servent qu’à comparer.")96        } else if flow.isNativeCrossChain {97            Banner(.info, "Échange inter-chaînes natif par THORChain : un dépôt de l’actif vendu vers le coffre THORChain, puis un paiement sortant vers l’adresse de ce portefeuille sur \(t.networkName ?? t.network). Irréversible une fois le dépôt envoyé. Le coffre doit être confirmé à l’unanimité par au moins \(flow.xswapInfo?.minOperators.map(String.init) ?? "3") opérateurs THORNode : sinon rien n’est préparé (échec fermé)." + (f.decimals > 8 ? " THORChain ne crédite que 8 décimales : le montant est tronqué à 8 décimales par le serveur." : ""))98        } else if hint.isEmpty, f.key != t.key {99            Banner(.warning, f.network == t.network100                   ? "Ce portefeuille n’exécute pas d’échange sur \(f.networkName ?? f.network) : les cotations de cette paire sont des comparaisons seulement."101                   : "Aucune exécution directe pour cette paire inter-réseaux. Un parcours en plusieurs étapes est peut-être possible : voir « DeFi » → Parcours multi-étapes.")102        }103    }104105    private var slippage: some View {106        VStack(alignment: .leading, spacing: 4) {107            HStack {108                Text("Tolérance de glissement").foregroundStyle(.secondary)109                ForEach(SwapFlow.slippagePresets, id: \.self) { b in110                    Button(SwapText.bps(b)) { flow.setSlippage(bps: b) }.buttonStyle(.bordered).controlSize(.small)111                        .tint(flow.slippageBps == b ? Theme.accent : nil)112                }113                TextField("%", text: $flow.slippageText).textFieldStyle(.roundedBorder).frame(width: 64).multilineTextAlignment(.trailing)114                    .accessibilityLabel("Tolérance de glissement en pourcentage")115                Text("%").foregroundStyle(.secondary)116            }117            .disabled(flow.step != .form)118            Text("Le minimum reçu garanti est calculé avec cette tolérance ; sous ce minimum, la transaction échoue plutôt que de s’exécuter. Valeur par défaut du serveur : \(SwapText.bps(flow.isNativeCrossChain ? SwapFlow.defaultNativeSlippageBps : SwapFlow.defaultSlippageBps)) ; le serveur refuse toute valeur hors de 0,01 % – 3 %.")119                .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)120            if let b = flow.slippageBps, b > 100 { Text("Tolérance élevée : vous acceptez de recevoir jusqu’à \(SwapText.bps(b)) de moins que la cotation.").font(.caption).foregroundStyle(Theme.warning) }121        }122    }123}124125// MARK: - Quotes126127private struct SwapQuoteSection: View {128    let model: AppModel129    @Bindable var flow: SwapFlow130    @State private var selection: SwapRoute.ID?131132    var body: some View {133        switch flow.quotePhase {134        case .idle:135            if flow.from != nil, flow.to != nil, flow.formProblem == nil, !model.canOperate { EmptyView() }136            else { Card { EmptyState(symbol: "arrow.left.arrow.right", title: "Entrez une paire et un montant", detail: "Les cotations sont une lecture : rien n’est préparé ni signé tant que vous n’avez pas demandé la préparation puis approuvé avec la passkey.") } }137        case .failed(let message):138            Card("Cotations") {139                Banner(.danger, message)140                HStack { Spacer(); Button("Réessayer") { flow.refreshQuotes() } }141            }142        case .loading, .done:143            executableCard144            if !flow.routes.isEmpty { comparisonCard }145            if !flow.answers.isEmpty { answersCard }146        }147    }148149    // The route the action executes — never the top-ranked quote of a comparison-only provider.150    @ViewBuilder private var executableCard: some View {151        Card("Route exécutable par ce portefeuille", trailing: AnyView(HStack(spacing: 8) {152            if flow.quotePhase == .loading { ProgressView().controlSize(.small); Text("Cotations en cours…").font(.caption).foregroundStyle(.secondary) }153            else if let at = flow.quotedAt { Text("Cotée \(Fmt.relative(at))").font(.caption).foregroundStyle(.secondary) }154            Button("Rafraîchir") { flow.refreshQuotes() }.controlSize(.small).disabled(flow.step != .form)155        })) {156            if let r = flow.executableRoute {157                TimelineView(.periodic(from: .now, by: 5)) { ctx in158                    let expired = flow.isExpired(r, now: ctx.date)159                    VStack(alignment: .leading, spacing: 10) {160                        hero(r)161                        RouteDetail(model: model, flow: flow, route: r)162                        if expired { Banner(.warning, "Cette cotation a expiré. Rafraîchissez avant de préparer.") }163                        if flow.isBridgePair { EmptyView() } else {164                            HStack {165                                Spacer()166                                if flow.step == .preparing { ProgressView().controlSize(.small); Text("Route ferme, simulation, limites du signataire…").font(.callout).foregroundStyle(.secondary) }167                                Button(SwapText.isSimulatedServer(model) ? "Préparer et vérifier (serveur de test)…" : "Préparer et vérifier…") { Task { await flow.prepare() } }168                                    .buttonStyle(.borderedProminent).controlSize(.large)169                                    .disabled(flow.formProblem != nil || !model.canOperate || flow.step != .form || expired)170                            }171                            Text("Préparer ne signe rien : le serveur demande une route ferme, vérifie le routeur et les données d’appel, simule, contrôle les limites du signataire, puis l’app vérifie que le défi de la passkey est l’empreinte de l’opération affichée. L’échange n’a lieu qu’après votre approbation sur l’écran suivant.")172                                .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)173                        }174                    }175                }176            } else if flow.quotePhase == .loading {177                Text("En attente de la réponse de l’exécuteur…").foregroundStyle(.secondary)178            } else {179                noExecutable180            }181            if let e = flow.error { Banner(.danger, e) }182        }183    }184185    @ViewBuilder private var noExecutable: some View {186        let executors = (flow.pairExecutors ?? []).filter { $0 != "cctp" }187        if flow.reachable == false {188            Banner(.warning, "Aucun fournisseur activé n’annonce cette paire.")189        } else if executors.isEmpty {190            Banner(.warning, flow.isBridgePair ? "Cette paire se traite dans « Pont inter-chaînes »." : "Le serveur n’indique aucun exécuteur pour cette paire : rien ici ne peut être exécuté par ce portefeuille. Les routes ci-dessous sont des comparaisons de prix seulement.")191        } else {192            Banner(.warning, "L’exécuteur de cette paire (\(executors.map { SwapText.provider($0, providers: flow.providers, execution: flow.execution) }.joined(separator: ", "))) n’a renvoyé aucune route pour l’instant. Rien ne peut être préparé ; réessayez.")193        }194    }195196    private func hero(_ r: SwapRoute) -> some View {197        let toSym = flow.to?.symbol ?? r.path.last?.symbol ?? ""198        return VStack(alignment: .leading, spacing: 4) {199            HStack(alignment: .firstTextBaseline, spacing: 8) {200                Text("\(Fmt.amount(r.amountOutDisplay, maxFraction: 8)) \(toSym)").font(.system(size: 30, weight: .semibold, design: .rounded)).monospacedDigit().textSelection(.enabled)201                ProvenanceTag(p: .estimate, text: "Estimation de la cotation")202                if SwapText.isSimulatedServer(model) { ProvenanceTag(p: .simulated, text: "Serveur de test") }203            }204            Text("Minimum reçu si la cotation est tenue : \(Fmt.amount(r.minAmountOutDisplay, maxFraction: 8)) \(toSym) — le minimum réellement garanti est celui de l’opération préparée, affiché avant l’approbation.")205                .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)206        }207    }208209    private var comparisonCard: some View {210        let rows = flow.sortedRoutes211        let chosen = rows.first { $0.id == selection }212        return Card("Comparaison des cotations (\(rows.count))") {213            Text("Beaucoup de fournisseurs ne sont interrogés que pour comparer les prix. Seules les lignes « Exécutable » peuvent être préparées par ce portefeuille ; c’est le serveur qui le déclare, à partir de ses contrats revus.")214                .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)215            Table(rows, selection: $selection) {216                TableColumn("Fournisseur") { r in Text(r.providers.map { SwapText.provider($0, providers: flow.providers, execution: flow.execution) }.joined(separator: " + ")) }.width(min: 120, ideal: 160)217                TableColumn("Reçu estimé") { r in Text(Fmt.amount(r.amountOutDisplay, maxFraction: 8)).monospacedDigit() }.width(min: 110, ideal: 140)218                TableColumn("Minimum") { r in Text(Fmt.amount(r.minAmountOutDisplay, maxFraction: 8)).monospacedDigit().foregroundStyle(.secondary) }.width(min: 110, ideal: 140)219                TableColumn("Impact prix") { r in Text(SwapText.bps(r.priceImpactBps)).monospacedDigit() }.width(76)220                TableColumn("Délai") { r in Text(SwapText.duration(r.estimatedSeconds)) }.width(min: 70, ideal: 90)221                TableColumn("Risque") { r in Text(SwapText.risk(r.risk?.level)).foregroundStyle(r.risk?.level == .high ? Theme.negative : r.risk?.level == .medium ? Theme.warning : .secondary) }.width(60)222                TableColumn("Exécution") { r in223                    if r.statedExecutor != nil { Label("Exécutable", systemImage: "checkmark.seal.fill").foregroundStyle(Theme.positive) }224                    else { Text("Comparaison seulement").foregroundStyle(.secondary) }225                }.width(min: 150, ideal: 170)226            }227            .frame(height: CGFloat(min(rows.count, 10)) * 28 + 36)228            if let r = chosen {229                Divider()230                Text("Détail de la cotation sélectionnée").font(.headline)231                if r.statedExecutor == nil { Banner(.info, SwapText.notExecutable(r)) }232                RouteDetail(model: model, flow: flow, route: r)233            } else { Text("Sélectionnez une ligne pour voir sa route, ses frais et ses contrats.").font(.caption).foregroundStyle(.secondary) }234        }235    }236237    private var answersCard: some View {238        Card("Réponses des fournisseurs") {239            ForEach(Array(flow.answers.enumerated()), id: \.offset) { _, a in240                HStack {241                    Text(SwapText.provider(a.provider, providers: flow.providers, execution: flow.execution)).frame(width: 190, alignment: .leading)242                    Text(SwapText.providerAnswer(a)).foregroundStyle(.secondary)243                    Spacer()244                    if let ms = a.ms { Text("\(Int(ms)) ms").monospacedDigit().foregroundStyle(.tertiary) }245                }.font(.callout)246            }247            if let n = flow.providers?.needsKey, !n.isEmpty {248                Text("Non interrogés faute de clé d’API sur le serveur : \(n.map { SwapText.provider($0, providers: flow.providers) }.joined(separator: ", ")).").font(.caption).foregroundStyle(.secondary)249            }250        }251    }252}253254/// Everything a quoted route says: price, impact, tolerance, route steps and venues, contracts, fees, time, risk.255private struct RouteDetail: View {256    let model: AppModel257    let flow: SwapFlow258    let route: SwapRoute259260    var body: some View {261        let r = route262        VStack(alignment: .leading, spacing: 7) {263            Field(label: "Fournisseur", value: r.providers.map { SwapText.provider($0, providers: flow.providers, execution: flow.execution) }.joined(separator: " + ")264                  + (r.statedExecutor != nil ? "  — exécuté par ce portefeuille" : "  — comparaison seulement"))265            if let p = indicativePrice { Field(label: "Prix indicatif", value: p) }266            Field(label: "Impact de prix estimé", value: r.priceImpactBps.map { SwapText.bps($0) } ?? "non communiqué par le fournisseur")267            Field(label: "Tolérance de la cotation", value: SwapText.bps(r.card?.toleranceBps))268            Field(label: "Minimum reçu (cotation)", value: "\(Fmt.amount(r.minAmountOutDisplay)) \(r.path.last?.symbol ?? "")")269            Field(label: "Délai estimé", value: SwapText.duration(r.estimatedSeconds))270            if let steps = r.steps, !steps.isEmpty { Field(label: "Route", value: steps.enumerated().map { stepText($0.offset, $0.element) }.joined(separator: "\n")) }271            let contracts = (r.steps ?? []).flatMap { $0.contracts ?? [] }272            if !contracts.isEmpty { Field(label: "Contrats", value: contracts.map { "\($0.role) · \(model.network($0.network)?.name ?? $0.network)\n\($0.address)" }.joined(separator: "\n"), mono: true) }273            Field(label: "Frais", value: feesText)274            if let v = r.valuation {275                Field(label: "Valorisation (USD)", value: "entrée \(SwapText.usd(v.inUsd)) · sortie \(SwapText.usd(v.outUsd)) · frais en sus \(SwapText.usd(v.extraFeesUsd))" + ((v.unpricedFees ?? 0) > 0 ? " · certains frais sans prix ne sont pas comptés" : ""))276            }277            if let risk = r.risk {278                Field(label: "Risque", value: SwapText.risk(risk.level) + (risk.flags.isEmpty ? "" : " — " + risk.flags.map { $0.code + ($0.detail.map { " (\($0))" } ?? "") }.joined(separator: " ; ")))279            }280            if let a = r.atomic { Field(label: "Atomicité", value: a ? "Une seule transaction : tout ou rien." : "Plusieurs étapes : pas atomique.") }281            if r.statedExecutor != nil, let e = r.executability?.reason { Field(label: "Vérification", value: e) }282            if let exp = r.expiresAt ?? r.card?.expiresAt { Field(label: "Validité de la cotation", value: "jusqu’à \(Fmt.dateSeconds(Date(timeIntervalSince1970: Double(exp) / 1000)))") }283        }284    }285286    /// Output per unit of input, from the quote's own figures: an estimate, labelled as such.287    private var indicativePrice: String? {288        guard let f = route.path.first, let t = route.path.last, let ain = route.amountIn ?? route.card?.amountIn,289              let i = try? BaseUnits(ain), let o = try? BaseUnits(route.amountOut), !i.isZero else { return nil }290        let p = o.approximate(decimals: t.decimals) / i.approximate(decimals: f.decimals)291        guard p.isFinite, p > 0 else { return nil }292        return "≈ \(p.formatted(.number.precision(.significantDigits(1...8)))) \(t.symbol) pour 1 \(f.symbol) (estimation, frais inclus dans la sortie)"293    }294295    private func stepText(_ k: Int, _ s: SwapRoute.Step) -> String {296        let nets = s.from.network == s.to.network ? (s.from.networkName ?? s.from.network) : "\(s.from.networkName ?? s.from.network) → \(s.to.networkName ?? s.to.network)"297        let venues = (s.via ?? []).isEmpty ? "" : " — via \((s.via ?? []).joined(separator: ", "))"298        return "\(k + 1). \(s.kind) · \(SwapText.provider(s.provider, providers: flow.providers, execution: flow.execution)) · \(s.from.symbol) → \(s.to.symbol) · \(nets)\(venues)"299    }300301    private var feesText: String {302        let fees = route.fees ?? []303        guard !fees.isEmpty else { return "Aucune ligne de frais communiquée par le fournisseur (les frais de réseau fermes sont affichés à la préparation)." }304        return fees.map { f in305            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 }306            let amount = f.display.map { "\(Fmt.amount($0, maxFraction: 8)) \(f.symbol ?? "")" } ?? "montant non communiqué"307            return "\(kind) : \(amount)" + (f.usd.map { " (\(SwapText.usd($0)))" } ?? "") + (f.includedInOutput == true ? " — déjà déduit de la sortie" : " — en sus") + (f.estimated == true ? " — estimé" : "")308        }.joined(separator: "\n")309    }310}311312// MARK: - Review313314private struct SwapReviewSheet: View {315    let model: AppModel316    let flow: SwapFlow317    let operation: ApprovableOperation318319    var body: some View {320        OperationReviewSheet(model: model, title: operation.intent.kind == .xswap ? "Vérifier et approuver l’échange inter-chaînes" : "Vérifier et approuver l’échange",321                             operation: operation, notices: notices, extra: extra, busy: flow.step == .approving, error: flow.error,322                             onReject: { Task { await flow.reject() } }, onApprove: { Task { await flow.approve() } })323    }324325    private var notices: [(Banner.Kind, String)] {326        var out: [(Banner.Kind, String)] = []327        if let a = OperationReviewSheet.spendApproval(operation.intent, model: model) { out.append(a) }328        if operation.intent.kind == .xswap {329            out.append((.info, "Le signataire isolé redemande lui-même à ses opérateurs THORNode si le coffre ci-dessous est authentique : sans unanimité d’au moins trois opérateurs, il refuse de signer (échec fermé) et rien ne part."))330        }331        return out332    }333334    private var extra: [ReviewLine] { OperationReviewSheet.contextLines(model: model, operation: operation) }335}336337// MARK: - Tracking338339private struct SwapTrackingCard: View {340    let model: AppModel341    let flow: SwapFlow342    let tracker: OperationTracker343344    var body: some View {345        let p = tracker.proposal346        Card(p.kind == "xswap" ? "Suivi de l’échange inter-chaînes" : "Suivi de l’échange", trailing: SwapText.isSimulatedServer(model) ? AnyView(ProvenanceTag(p: .simulated, text: "Serveur de test")) : nil) {347            OperationHeadline(proposal: p, completion: tracker.completion)348            Field(label: "Vendu", value: "\(Fmt.amount(p.amountDisplay)) \(p.symbol) · \(p.networkName ?? p.network)")349            if let s = try? p.swapSection() { swapFacts(p, s) }350            else if p.swap != nil { Banner(.warning, "La section d’échange de cette opération est illisible par cette version de l’app.") }351            if p.kind == "xswap" {352                if let x = try? p.xswapSection() { xswapFacts(p, x) }353                else { Banner(.warning, "La section inter-chaînes de cette opération est illisible par cette version de l’app.") }354            }355            if let e = p.error { Banner(p.state.isFailure || p.state == .notBroadcast ? .danger : .warning, e) }356            if let e = tracker.readError { Banner(.warning, "Dernière lecture de l’état en échec : \(e)") }357            if let e = flow.error { Banner(.danger, e) }358            if let ex = try? p.executionStatus() { Divider(); ExecutionTimeline(model: model, status: ex) }359            Divider()360            StateHistory(history: tracker.history)361            HStack {362                if p.kind == "xswap", !tracker.isSettled {363                    Button("Vérifier maintenant") { Task { await flow.refreshNow() } }.disabled(flow.refreshing || !model.canOperate)364                        .help("Demande au serveur de regarder tout de suite l’état côté THORChain. Ne signe rien.")365                }366                Spacer()367                Button(tracker.isSettled ? "Nouvel échange" : "Nouvel échange (le suivi continue dans Activité)") { flow.reset() }368            }369        }370    }371372    @ViewBuilder private func swapFacts(_ p: Proposal, _ s: SwapSection) -> some View {373        Field(label: "Fournisseur", value: SwapText.provider(s.provider, providers: flow.providers, execution: flow.execution))374        Field(label: "Sortie attendue", value: "\(Fmt.amount(s.expectedOutDisplay)) \(s.toSymbol) (estimation)")375        Field(label: "Minimum garanti", value: "\(Fmt.amount(s.minOutDisplay)) \(s.toSymbol)")376        if p.kind == "swap" {377            if let r = s.receivedDisplay {378                HStack { Field(label: "Reçu", value: "\(Fmt.amount(r)) \(s.toSymbol)", emphasis: true); ProvenanceTag(p: .verified) }379            } else {380                Field(label: "Reçu", value: p.state == .finalized ? "Lecture du montant sur la chaîne en cours…" : "— (connu seulement une fois l’échange finalisé et lu sur la chaîne)")381            }382        }383        if s.needsApproval == true || s.approvalTxid != nil {384            TxField(label: "Autorisation ERC-20", txid: s.approvalTxid ?? "(pas encore diffusée)", state: approvalState(s.approvalState))385        }386        TxField(label: p.kind == "xswap" ? "Dépôt (source)" : "Transaction d’échange", txid: p.txid, explorer: p.explorer, state: ErrorText.state(p.state))387        if let c = p.confirmations, p.txid != nil { Field(label: "Confirmations", value: String(c)) }388    }389390    private func approvalState(_ s: String?) -> String {391        switch s { case "pending": "en attente"; case "sent": "diffusée, non confirmée"; case "confirmed": "confirmée"; case nil: "aucune"; case let o?: o }392    }393394    @ViewBuilder private func xswapFacts(_ p: Proposal, _ x: XSwapSection) -> some View {395        Field(label: "Étape", value: SwapText.xswapStage(x.stage), emphasis: true)396        Field(label: "Destination", value: "\(x.toSymbol) sur \(x.toNetworkName ?? x.toNetwork)")397        if let h = x.hold { Banner(x.isComplete ? .danger : .warning, SwapText.hold(h) + (x.holdDetail.map { "\nServeur : \($0)" } ?? "")) }398        if x.refundPlanned == true, !x.isRefunded { Banner(.warning, "THORChain annonce un remboursement de l’actif source.") }399        Field(label: "Coffre THORChain", value: x.vault, mono: true)400        Field(label: "Mémo", value: x.memo, mono: true)401        TxField(label: x.outKind == "refund" ? "Remboursement" : "Paiement sortant", txid: x.outTxid, explorer: x.outExplorer)402        if let r = x.receivedDisplay {403            HStack { Field(label: "Reçu", value: "\(Fmt.amount(r)) \(x.toSymbol)", emphasis: true); if x.isComplete { ProvenanceTag(p: .verified) } }404            if x.receivedBelowMinimum { Banner(.danger, "Reçu, mais moins que le minimum approuvé (\(Fmt.amount(x.minOutDisplay)) \(x.toSymbol)).") }405        } else if !x.isRefunded {406            Field(label: "Reçu", value: "— (connu seulement quand ce portefeuille voit lui-même le paiement sortant)")407        }408        if let r = x.refundedDisplay { Field(label: "Remboursé", value: "\(Fmt.amount(r)) \(p.symbol)", emphasis: true) }409        Field(label: "Délai estimé", value: SwapText.duration(x.estimatedSeconds))410    }411}412
Files main
Menu

Theme