SPB Git

Repository Public

CrossSwap.swift 27.4 KB 401 lines swift

1// SP Wallet iOS2// File: Features/Bridge/CrossSwap.swift3// Description: "Échange entre réseaux": one asset on one network for another asset on another network. Shows what the server4//              serves as capabilities, the live routes of the pair (who executes, who only quotes), the native THORChain swap5//              when the server states it executes the pair, and the multi-step plans with every leg, requirement and issue.6//              A quote starts nothing; starting a plan stores it and signs nothing; each step has its own passkey later.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213@MainActor @Observable14final class CrossModel {15    var xinfo: XSwapExecutionInfo?16    var caps: PlanCapabilities?17    var capsError: Error?1819    var planQuote: PlanQuote?20    var planError: Error?21    var planQuoting = false22    /** Optional overall floor of a plan, decimal text in the destination asset; empty = none. */23    var floor = ""2425    var busy = false26    var error: Error?27    var cleanup: OperationCleanup.Result?28    var moved: QuoteMoved?29    var serverLacksIntent = false30    var start: OperationStart?31    var confirmPlan: PlanCandidate?32    private var idempotency: (key: String, request: XSwapRequest)?3334    func load(_ env: AppEnvironment) async {35        do {36            async let x = XSwapAPI(env.client).execution(), c = PlanAPI(env.client).capabilities()37            (xinfo, caps) = try await (x, c)38            capsError = nil39        } catch { capsError = error }40    }4142    func runPlanQuote(_ env: AppEnvironment, request: PlanRequest?) async {43        planQuote = nil; planError = nil44        guard let request else { planQuoting = false; return }45        try? await Task.sleep(for: .milliseconds(600))46        if Task.isCancelled { return }47        planQuoting = true48        defer { planQuoting = false }49        do { let q = try await PlanAPI(env.client).quote(request); if !Task.isCancelled { planQuote = q } }50        catch { if !Task.isCancelled { planError = error } }51    }5253    private func key(for r: XSwapRequest) -> String {54        if let i = idempotency, i.request == r { return i.key }55        let k = APIClient.newIdempotencyKey()56        idempotency = (k, r)57        return k58    }5960    static func xswapRequest(_ swap: SwapModel, now: Date = Date()) -> XSwapRequest? {61        guard let from = swap.from, let to = swap.to, from.network != to.network, let bps = swap.slippageBps, let text = swap.quoteAmount,62              let r = swap.selected, r.statedExecutor == "thorchain", let ref = SwapLogic.preparability(r, now: now).reference else { return nil }63        return XSwapRequest(fromNetwork: from.network, fromAsset: from.asset, toNetwork: to.network, toAsset: to.asset, amount: text, slippageBps: bps, quote: ref)64    }6566    /** Prepare the THORChain route the owner picked; the firm minimum must not be below the minimum displayed. */67    func prepareXSwap(_ env: AppEnvironment, swap: SwapModel, accounts: Accounts?) async {68        guard !busy, !serverLacksIntent, let accounts, let r = Self.xswapRequest(swap), let from = swap.from else { return }69        busy = true; error = nil; cleanup = nil; moved = nil70        defer { busy = false }71        let started = Date()72        do {73            let prepared = try await XSwapAPI(env.client).prepare(r, accounts: accounts, minimumOutput: .asPrepared, idempotencyKey: key(for: r))74            idempotency = nil75            start = prepared.approvable.map { .review($0) } ?? .tracking(proposalId: prepared.proposal.id)76        } catch {77            let kind = SwapLogic.classify(error)78            if kind != .offline { idempotency = nil }79            if let m = error as? QuoteMoved { moved = m; swap.selectedRouteId = nil; return }80            self.error = error81            if kind == .serverLacksIntent { serverLacksIntent = true }82            if SwapLogic.leavesPendingProposal(error) {83                // THORChain credits eight decimals: the amount the server stored may be coarser than what was typed, so it is not compared84                cleanup = await OperationCleanup.withdraw(env, kind: "xswap", network: r.fromNetwork, asset: r.fromAsset, amountUnits: from.decimals > 8 ? nil : SwapLogic.checkAmount(r.amount, decimals: from.decimals, balance: nil).units?.description, since: started).result85                swap.selectedRouteId = nil86            }87        }88    }8990    enum FloorCheck: Equatable { case none, invalid, ok(String) }91    func floorCheck(decimals: Int) -> FloorCheck {92        switch SwapLogic.checkAmount(floor, decimals: decimals, balance: nil) {93        case .empty: .none94        case .ok(_, let text): .ok(text)95        default: .invalid96        }97    }9899    /** Store the plan the owner chose. Nothing is prepared, nothing is signed: its first step becomes "ready". */100    func startPlan(_ env: AppEnvironment, request: PlanRequest, candidate: PlanCandidate, floor: String?) async -> PlanView? {101        guard !busy else { return nil }102        busy = true; error = nil; cleanup = nil103        defer { busy = false }104        do { return try await PlanAPI(env.client).start(request, plan: candidate.id, floor: floor) } catch { self.error = error; return nil }105    }106}107108struct CrossSwapView: View {109    @Environment(AppModel.self) private var model110    let regular: Bool111    let openPlan: (String) -> Void112    @State private var swap = SwapModel()113    @State private var cross = CrossModel()114115    var body: some View {116        @Bindable var cross = cross117        Group {118            if let e = swap.catalogError, !swap.catalogLoaded { ErrorNotice(error: e) { Task { await swap.load(model.env) } } }119            else if !swap.catalogLoaded { if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) } }120            else if regular {121                HStack(alignment: .top, spacing: 20) {122                    VStack(alignment: .leading, spacing: Theme.Space.section) { form; prepareBlock; capabilities }.frame(maxWidth: 440)123                    VStack(alignment: .leading, spacing: Theme.Space.section) { routes; plans }.frame(maxWidth: .infinity)124                }125            } else { form; routes; prepareBlock; plans; capabilities }126        }127        .task(id: model.canOperate) {128            guard model.canOperate else { return }129            if !swap.catalogLoaded { await swap.load(model.env) }130            if cross.caps == nil { await cross.load(model.env) }131        }132        .task(id: swap.quoteSignature + (model.canOperate ? "+" : "-")) { await swap.runQuotes(model.env, online: model.canOperate && isCrossNetwork) }133        .task(id: swap.quoteSignature + (model.canOperate ? "p+" : "p-")) { await cross.runPlanQuote(model.env, request: model.canOperate ? planRequest : nil) }134        .sheet(item: $cross.start, onDismiss: { swap.requote(); Task { await model.refreshAll() } }) { OperationSheet(start: $0).wallet(model) }135        .confirmationDialog(String(localized: "Démarrer ce plan ?"), isPresented: Binding(get: { cross.confirmPlan != nil }, set: { if !$0 { cross.confirmPlan = nil } }), titleVisibility: .visible) {136            Button(String(localized: "Démarrer le plan (rien n’est signé)")) {137                guard let c = cross.confirmPlan, let req = planRequest, let to = swap.to else { return }138                let floor: String? = if case .ok(let f) = cross.floorCheck(decimals: to.decimals) { f } else { nil }139                Task { if let p = await cross.startPlan(model.env, request: req, candidate: c, floor: floor) { openPlan(p.id) } }140            }141            Button(String(localized: "Annuler"), role: .cancel) {}142        } message: { Text(String(localized: "Le serveur enregistre le plan ; sa première étape devient « prête ». Chaque étape sera préparée à ta demande et approuvée par sa propre clé d’accès. Un seul plan peut être ouvert à la fois.")) }143    }144145    private var isCrossNetwork: Bool { guard let f = swap.from, let t = swap.to else { return false }; return f.network != t.network }146    private var planRequest: PlanRequest? {147        guard isCrossNetwork, let f = swap.from, let t = swap.to, let bps = swap.slippageBps, let text = swap.quoteAmount else { return nil }148        return PlanRequest(from: f.key, to: t.key, amount: text, slippageBps: bps)149    }150    private var balance: Balance? {151        guard let f = swap.from else { return nil }152        return model.portfolio.value?.balances.first { $0.network == f.network && SwapLogic.sameAssetId($0.asset, f.asset) }153    }154    private var amountCheck: SwapLogic.AmountCheck {155        guard let f = swap.from else { return .empty }156        return SwapLogic.checkAmount(swap.amount, decimals: f.decimals, balance: balance?.units)157    }158159    // MARK: form160161    @ViewBuilder private var form: some View {162        @Bindable var swap = swap163        VStack(alignment: .leading, spacing: 12) {164            assetMenu(String(localized: "Tu donnes"), swap.from, id: "cross.from") { swap.pick(from: $0) }165            HStack {166                Rectangle().fill(Theme.hairline).frame(height: 0.5)167                Button { swap.flip() } label: { Image(systemName: "arrow.up.arrow.down").font(.system(size: 15, weight: .semibold)).frame(width: 44, height: 44).background(Theme.elev, in: Circle()) }168                    .foregroundStyle(Theme.ink).accessibilityLabel(String(localized: "Inverser")).accessibilityIdentifier("cross.flip")169                Rectangle().fill(Theme.hairline).frame(height: 0.5)170            }171            assetMenu(String(localized: "Tu reçois"), swap.to, id: "cross.to") { swap.pick(to: $0) }172            if let f = swap.from, let t = swap.to {173                if f.network == t.network {174                    Notice(tone: .info, title: String(localized: "Même réseau"), message: String(localized: "Pour deux actifs du même réseau, utilise la section Échanger.")).accessibilityIdentifier("cross.sameNetwork")175                } else if let x = cross.xinfo {176                    if x.canSwap(from: f.ref, to: t.ref) { Pill(text: String(localized: "Échange natif THORChain servi pour cette paire"), tone: .ok, icon: "checkmark.seal.fill") }177                    else { Pill(text: String(localized: "Pas d’échange natif direct pour cette paire : voir les plans"), tone: .neutral, icon: "list.number") }178                }179            }180        }181        .spCard().disabled(!model.canOperate)182183        if let f = swap.from {184            VStack(alignment: .leading, spacing: 10) {185                Text(String(localized: "Montant donné")).font(.spHeadline)186                HStack {187                    TextField("0", text: $swap.amount).keyboardType(.decimalPad).font(.system(size: 30, weight: .semibold)).monospacedDigit().accessibilityIdentifier("cross.amount")188                    Text(f.symbol).font(.spHeadline).foregroundStyle(Theme.mute)189                }190                HStack {191                    Text(String(localized: "Disponible")).font(.spFootnote).foregroundStyle(Theme.mute)192                    Spacer()193                    if let d = balance?.display { Masked(text: Money.exact(d) + " " + f.symbol).font(.spFootnote.weight(.semibold)).monospacedDigit() }194                    else { Text(String(localized: "solde indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }195                }196                if let p = amountCheck.problem { Label(p, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(amountCheck == .aboveBalance ? Theme.warn : Theme.danger) }197                if f.decimals > 8 { Text(String(localized: "THORChain ne crédite que huit décimales : le serveur n’envoie rien de plus fin.")).font(.spFootnote).foregroundStyle(Theme.mute) }198                Divider()199                HStack {200                    Text(String(localized: "Tolérance de glissement (par étape)")).font(.spCallout.weight(.semibold))201                    Spacer()202                    Text(swap.slippageBps.map { SwapLogic.slippageLabel($0) } ?? String(localized: "à choisir")).font(.spCallout.weight(.semibold)).foregroundStyle(swap.slippageBps == nil ? Theme.warn : Theme.ink)203                }204                HStack(spacing: 8) {205                    ForEach(SwapLogic.crossSlippagePresets, id: \.self) { bps in206                        Button { swap.slippageBps = bps } label: {207                            Text(SwapLogic.slippageLabel(bps)).font(.spCallout.weight(.semibold)).frame(maxWidth: .infinity, minHeight: 44)208                                .foregroundStyle(swap.slippageBps == bps ? Theme.onPrimary : Theme.ink)209                                .background(swap.slippageBps == bps ? Theme.primary : Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small))210                        }211                        .buttonStyle(.plain).accessibilityIdentifier("cross.slippage.\(bps)").accessibilityAddTraits(swap.slippageBps == bps ? .isSelected : [])212                    }213                }214            }215            .spCard().disabled(!model.canOperate)216        }217    }218219    private func assetMenu(_ title: String, _ current: SwapAsset?, id: String, pick: @escaping (SwapAsset) -> Void) -> some View {220        VStack(alignment: .leading, spacing: 6) {221            Text(title).spEyebrow()222            Menu {223                ForEach(swap.allNetworks, id: \.id) { n in224                    Menu(n.name) { ForEach(swap.assets(on: n.id)) { a in Button(a.symbol + " — " + (a.name ?? a.asset)) { pick(a) } } }225                }226            } label: {227                HStack(spacing: 12) {228                    if let a = current { AssetIcon(symbol: a.symbol, network: a.network, size: 36) } else { Circle().fill(Theme.elev).frame(width: 36, height: 36) }229                    VStack(alignment: .leading, spacing: 1) {230                        Text(current?.symbol ?? String(localized: "Choisir un actif")).font(.spHeadline).foregroundStyle(Theme.ink)231                        if let a = current { Text(String(localized: "sur \(a.networkName ?? a.network)")).font(.spFootnote).foregroundStyle(Theme.mute) }232                    }233                    Spacer()234                    Image(systemName: "chevron.up.chevron.down").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.mute)235                }.frame(minHeight: 48).contentShape(Rectangle())236            }237            .accessibilityIdentifier(id)238        }239    }240241    // MARK: direct routes242243    @ViewBuilder private var routes: some View {244        if isCrossNetwork {245            VStack(alignment: .leading, spacing: 12) {246                HStack {247                    Text(String(localized: "Routes directes")).font(.spHeadline)248                    if swap.phase == .loading { ProgressView().padding(.leading, 4) }249                    Spacer()250                    if swap.quoteRequest != nil { Button { swap.requote() } label: { Label(String(localized: "Actualiser"), systemImage: "arrow.clockwise") }.font(.spCallout.weight(.semibold)).disabled(!model.canOperate).accessibilityIdentifier("cross.refresh") }251                }252                if swap.quoteRequest == nil {253                    Text(String(localized: "Saisis un montant et choisis une tolérance pour voir les cotations.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("cross.quotes.waiting")254                } else {255                    if let e = swap.quoteError { ErrorNotice(error: e) { swap.requote() }.accessibilityIdentifier("cross.quotes.error") }256                    if swap.phase == .done, swap.routes.isEmpty { EmptyState(icon: "arrow.triangle.swap", title: String(localized: "Aucune route directe"), message: String(localized: "Aucun fournisseur n’a coté cette paire pour ce montant.")).accessibilityIdentifier("cross.quotes.empty") }257                    TimelineView(.periodic(from: .now, by: 5)) { ctx in258                        let ordered = swap.ordered259                        let highlight = SwapLogic.bestPreparable(ordered, executor: "thorchain", now: ctx.date)260                        VStack(spacing: 10) {261                            ForEach(Array(ordered.enumerated()), id: \.element.id) { k, r in262                                RouteCardView(route: r, index: k, toSymbol: swap.to?.symbol ?? "", providers: swap.providers, now: ctx.date,263                                              selected: swap.selectedRouteId == r.id, highlighted: highlight?.id == r.id, serverBest: swap.best["best_price"] == r.id,264                                              select: { if r.statedExecutor == "thorchain" { swap.select(r) } })265                            }266                        }267                    }268                    Text(String(localized: "Seule une route que le serveur déclare exécutable par THORChain peut être préparée ici ; les autres sont des comparaisons.")).font(.spFootnote).foregroundStyle(Theme.mute)269                }270            }271            .spCard()272        }273    }274275    @ViewBuilder private var prepareBlock: some View {276        if isCrossNetwork {277            if let m = cross.moved {278                Notice(tone: .warn, title: String(localized: "Le prix a bougé : rien n’a été préparé"),279                       message: String(localized: "Minimum affiché : \(Money.exact(m.quoted.minAmountOutDisplay)). Maintenant : attendu \(Money.exact(m.fresh.amountOutDisplay)), minimum \(Money.exact(m.fresh.minAmountOutDisplay)) \(m.fresh.symbol ?? ""). Demande une nouvelle cotation."))280                    .accessibilityIdentifier("cross.quoteMoved")281                Button { swap.requote() } label: { Label(String(localized: "Demander une nouvelle cotation"), systemImage: "arrow.clockwise") }.buttonStyle(.spSecondary)282            }283            if let e = cross.error { PrepareRefusalNotice(error: e, cleanup: cross.cleanup) }284            else if cross.serverLacksIntent { Notice(tone: .warn, title: SwapLogic.missingIntentTitle, message: SwapLogic.missingIntentMessage).accessibilityIdentifier("op.unsupported") }285            if swap.routes.contains(where: { $0.statedExecutor == "thorchain" }) {286                Button { Task { await cross.prepareXSwap(model.env, swap: swap, accounts: model.accounts.value) } } label: { HStack { if cross.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer l’échange natif")) } }287                    .buttonStyle(.spPrimary)288                    .disabled(!model.canOperate || cross.busy || cross.serverLacksIntent || amountCheck.units == nil || CrossModel.xswapRequest(swap) == nil || model.accounts.value == nil)289                    .accessibilityIdentifier("cross.prepare")290                Text(String(localized: "Choisis d’abord la route THORChain. Le serveur confirme le coffre auprès de plusieurs opérateurs et prépare un seul envoi vers ce coffre, avec un mémo qui livre à ta propre adresse. Rien n’est signé à cette étape."))291                    .font(.spFootnote).foregroundStyle(Theme.mute)292            }293        }294    }295296    // MARK: plans297298    @ViewBuilder private var plans: some View {299        if isCrossNetwork {300            VStack(alignment: .leading, spacing: 12) {301                HStack { Text(String(localized: "Plans en plusieurs étapes")).font(.spHeadline); if cross.planQuoting { ProgressView().padding(.leading, 4) } }302                if planRequest == nil { Text(String(localized: "Saisis un montant et choisis une tolérance pour voir les plans.")).font(.spCallout).foregroundStyle(Theme.mute) }303                if let e = cross.planError { ErrorNotice(error: e).accessibilityIdentifier("cross.plans.error") }304                if let q = cross.planQuote {305                    if let ne = q.notExecutable {306                        Notice(tone: .info, title: String(localized: "Aucun plan exécutable pour cette paire"), message: notExecutable(ne)).accessibilityIdentifier("cross.plans.none")307                    } else if q.plans.isEmpty {308                        EmptyState(icon: "list.number", title: String(localized: "Aucun plan coté pour le moment")).accessibilityIdentifier("cross.plans.none")309                    }310                    if !q.plans.isEmpty, let to = swap.to {311                        @Bindable var cross = cross312                        VStack(alignment: .leading, spacing: 6) {313                            Text(String(localized: "Plancher global (facultatif), en \(to.symbol)")).font(.spFootnote).foregroundStyle(Theme.mute)314                            TextField(String(localized: "aucun"), text: $cross.floor).keyboardType(.decimalPad).padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("cross.floor")315                            if cross.floorCheck(decimals: to.decimals) == .invalid { Label(String(localized: "Plancher invalide."), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger) }316                            Text(String(localized: "Le plan se met en pause avant une étape si l’estimation finale passe sous ce plancher.")).font(.spFootnote).foregroundStyle(Theme.mute)317                        }318                    }319                    ForEach(q.plans) { c in planCard(c) }320                    ForEach(Array(q.skipped.enumerated()), id: \.offset) { _, s in321                        Text(String(localized: "Forme non cotée (étape \(s.leg + 1)) : \(s.message) (\(s.code))")).font(.spFootnote).foregroundStyle(Theme.mute)322                    }323                }324            }325            .spCard()326        }327    }328329    private func notExecutable(_ n: PlanQuote.NotExecutable) -> String {330        switch n.code {331        case "same_asset": String(localized: "Les deux actifs sont identiques.")332        case "solana_evm_bridge": String(localized: "Ce trajet demanderait un transfert Solana ↔ EVM que les plans ne chaînent pas.")333        case "network_without_execution": String(localized: "Le portefeuille n’exécute aucun échange sur \(n.network ?? "ce réseau").")334        case "no_executable_path": String(localized: "Aucun enchaînement d’étapes exécutables ne relie ces deux actifs.")335        default: n.code336        }337    }338339    private func planCard(_ c: PlanCandidate) -> some View {340        VStack(alignment: .leading, spacing: 8) {341            FlowPills() {342                Pill(text: String(localized: "\(c.legs.count) étapes · \(c.approvals) approbations"), tone: .info, icon: "person.badge.key.fill")343                if c.executable { Pill(text: String(localized: "Démarrable"), tone: .ok, icon: "checkmark.seal.fill") } else { Pill(text: String(localized: "Bloqué"), tone: .danger, icon: "xmark.octagon.fill") }344                if let s = c.seconds { Pill(text: SwapLogic.duration(s), tone: .neutral, icon: "clock") }345            }346            Text(String(localized: "Attendu : \(Money.exact(c.expectedOutDisplay)) \(c.to.symbol)")).font(.system(size: 18, weight: .semibold)).monospacedDigit().foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)347            Text(String(localized: "Pire cas (chaque étape à son minimum garanti) : \(Money.exact(c.worstOutDisplay)) \(c.to.symbol)")).font(.spFootnote.weight(.medium)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)348            ForEach(Array(c.legs.enumerated()), id: \.offset) { k, leg in349                VStack(alignment: .leading, spacing: 2) {350                    Text("\(k + 1). " + PlanText.legTitle(kind: leg.kind, via: leg.label ?? leg.via, from: leg.from, to: leg.to)).font(.spFootnote.weight(.semibold)).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)351                    Text(String(localized: "attendu \(Money.brief(leg.expectedOutDisplay)), pire cas \(Money.brief(leg.worstOutDisplay)) \(leg.to.symbol) · \(SwapLogic.duration(leg.seconds))")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)352                    if let fees = leg.fees, !fees.isEmpty {353                        Text(String(localized: "frais : ") + fees.map { Money.brief($0.display, maxFraction: 8) + " " + $0.symbol + ($0.includedInOutput == true ? " " + String(localized: "(déduits)") : "") }.joined(separator: " + ")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)354                    }355                }356            }357            ForEach(Array((c.requirements?.gas ?? []).enumerated()), id: \.offset) { _, g in358                Label(String(localized: "Frais sur \(g.networkName ?? g.network) : besoin de \(Money.brief(g.needDisplay)) \(g.symbol), détenu \(g.haveDisplay.map { Money.brief($0) } ?? String(localized: "illisible"))"), systemImage: g.ok ? "checkmark.circle.fill" : "exclamationmark.triangle.fill")359                    .font(.spFootnote).foregroundStyle(g.ok ? Theme.mute : Theme.warn).fixedSize(horizontal: false, vertical: true)360            }361            ForEach(Array(c.issues.enumerated()), id: \.offset) { _, i in362                Label(String(localized: "\(i.code) — \(i.networkName ?? i.network) : besoin de \(i.needDisplay ?? i.need) \(i.symbol), disponible \(i.haveDisplay ?? i.have)"), systemImage: i.blocking ? "xmark.octagon.fill" : "exclamationmark.triangle.fill")363                    .font(.spFootnote).foregroundStyle(i.blocking ? Theme.danger : Theme.warn).fixedSize(horizontal: false, vertical: true)364            }365            Button(String(localized: "Démarrer ce plan…")) { cross.confirmPlan = c }366                .buttonStyle(.spSecondary).disabled(!c.executable || !model.canOperate || cross.busy || cross.floorCheck(decimals: c.to.decimals) == .invalid || amountCheck.units == nil)367                .accessibilityIdentifier("cross.plan.start")368        }369        .padding(14).frame(maxWidth: .infinity, alignment: .leading)370        .background(Theme.bg, in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))371        .overlay(RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous).strokeBorder(Theme.hairline, lineWidth: 0.5))372    }373374    // MARK: capabilities375376    @ViewBuilder private var capabilities: some View {377        if let e = cross.capsError { ErrorNotice(error: e) { Task { await cross.load(model.env) } } }378        if cross.xinfo != nil || cross.caps != nil {379            VStack(alignment: .leading, spacing: 8) {380                Text(String(localized: "Ce que le serveur sert")).font(.spHeadline)381                if let x = cross.xinfo {382                    Text(x.enabled ? String(localized: "Échange natif THORChain : activé") : String(localized: "Échange natif THORChain : désactivé")).font(.spCallout.weight(.semibold)).foregroundStyle(x.enabled ? Theme.ink : Theme.warn)383                    if let m = x.minOperators { Text(String(localized: "Coffre confirmé par au moins \(m) opérateurs THORNode avant toute préparation.")).font(.spFootnote).foregroundStyle(Theme.mute) }384                    FlowPills() {385                        ForEach(Array(x.assets.enumerated()), id: \.offset) { _, a in386                            Pill(text: a.symbol + " · " + (model.network(a.network)?.name ?? a.network) + (a.source ? "" : " · " + String(localized: "destination seulement")), tone: a.source ? .ok : .neutral)387                        }388                    }389                }390                if let c = cross.caps {391                    Divider()392                    Text(String(localized: "Plans : \(c.maxLegs) étapes au plus, actif intermédiaire \(c.hub)")).font(.spCallout.weight(.semibold))393                    Text(String(localized: "Échange exécuté sur : \(c.swap.keys.sorted().map { model.network($0)?.name ?? $0 }.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute)394                    Text(String(localized: "CCTP entre : \(c.cctp.map { model.network($0)?.name ?? $0 }.joined(separator: ", "))")).font(.spFootnote).foregroundStyle(Theme.mute)395                }396            }397            .spCard().accessibilityIdentifier("cross.capabilities")398        }399    }400}401
Files main
Menu

Theme