Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Bridge/BridgeView.swift3// Description: The cross-network USDC bridge (Circle CCTP): source and destination among the networks the server enables, both speeds with their fee ceiling and expected time, the review of the verified burn, then the two legs — burn on the source, Circle's attestation, mint on the destination — each with its own transaction id. A transfer is shown as received ONLY when the destination mint is confirmed. Interrupted transfers are listed on load with their real phase and the actions the server offers.4import SwiftUI5import SPWalletCore67struct BridgeView: View {8 let model: AppModel9 @State private var flow: BridgeFlow?1011 var body: some View {12 Page("Pont inter-chaînes", subtitle: "USDC d’un réseau à l’autre par Circle CCTP : destruction sur la source, attestation de Circle, émission sur la destination — toujours de ce portefeuille à lui-même.") {13 if let flow {14 if !model.canOperate { Banner(.warning, "Transfert impossible pour l’instant : session ou portefeuille indisponible.") }15 if SwapText.isSimulatedServer(model) { Banner(.warning, "SERVEUR DE TEST : les transactions sont signées mais ne sont PAS diffusées. Aucun transfert 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 du pont illisibles : \(e)") }18 if let info = flow.info, !info.enabled { Banner(.warning, "Le serveur indique que le pont CCTP est désactivé.") }19 if flow.step == .tracking, let t = flow.tracker {20 BridgeTrackingCard(model: model, flow: flow, tracker: t)21 } else {22 BridgeRecoveryCard(model: model, flow: flow)23 if flow.info != nil {24 BridgeFormCard(model: model, flow: flow)25 BridgeQuoteCard(model: model, flow: flow)26 } else if flow.loadError == nil { ProgressView("Lecture des réseaux du pont…") }27 }28 } else { ProgressView() }29 }30 .task {31 if flow == nil { flow = BridgeFlow(model: model) }32 if flow?.info == nil { await flow?.load() }33 }34 .task(id: flow?.quoteKey) { await flow?.runQuote() }35 .task(id: flow?.tracker?.proposal.id) { await flow?.tracker?.follow() }36 .sheet(isPresented: Binding(get: { flow?.step == .review || flow?.step == .approving }, set: { _ in })) {37 if let flow, let op = flow.operation { BridgeReviewSheet(model: model, flow: flow, operation: op) }38 }39 .sheet(isPresented: Binding(get: { flow?.followUp != nil }, set: { _ in })) {40 if let flow, let f = flow.followUp { BridgeFollowUpSheet(model: model, flow: flow, followUp: f) }41 }42 }43}4445// MARK: - Recovery4647private struct BridgeRecoveryCard: View {48 let model: AppModel49 let flow: BridgeFlow5051 var body: some View {52 let rows = flow.recoverable53 if !rows.isEmpty {54 Card("Transferts en cours ou à reprendre (\(rows.count))", trailing: model.activity.map { AnyView(ProvenanceTag(p: $0.fromCache ? .stale : .verified, text: $0.fromCache ? "Activité du \(Fmt.date($0.fetchedAt))" : "Activité lue \(Fmt.relative($0.fetchedAt))")) }) {55 Text("Un transfert brûlé mais pas encore émis n’est pas perdu : les USDC restent réclamables sur la destination. Ouvrez-le pour voir sa phase réelle et les actions offertes par le serveur.")56 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)57 ForEach(rows.prefix(25)) { r in58 HStack(spacing: 12) {59 VStack(alignment: .leading, spacing: 2) {60 Text("\(Fmt.amount(r.item.amountDisplay, maxFraction: 6)) \(r.item.symbol) · \(r.item.networkName ?? r.item.network) → \(r.section.map { $0.toNetworkName ?? $0.toNetwork } ?? "?")").fontWeight(.medium)61 Text(status(r)).font(.callout).foregroundStyle(statusColor(r)).fixedSize(horizontal: false, vertical: true)62 Text(Fmt.date(r.item.at)).font(.caption).foregroundStyle(.secondary)63 }64 Spacer()65 if flow.opening == r.id { ProgressView().controlSize(.small) }66 Button("Ouvrir") { Task { await flow.open(r) } }.disabled(flow.opening != nil || model.phase != .signedIn)67 }68 .padding(.vertical, 3)69 Divider()70 }71 if rows.count > 25 { Text("\(rows.count - 25) autres dans « Activité ».").font(.caption).foregroundStyle(.secondary) }72 if let e = flow.openError { Banner(.danger, e) }73 }74 }75 }7677 private func status(_ r: BridgeFlow.Recoverable) -> String {78 guard let b = r.section else { return "État illisible par cette version de l’app" }79 if b.isComplete, let s = b.sol?.reclaimState { return "Reçu sur la destination · dépôt Solana : \(BridgeText.reclaim(s))" }80 var s = SwapText.bridgeStage(b.stage)81 if b.needsPasskey == true { s += " — action requise" }82 else if let h = b.hold { s += " — en attente (\(h))" }83 return s84 }85 private func statusColor(_ r: BridgeFlow.Recoverable) -> Color {86 guard let b = r.section else { return Theme.warning }87 return b.needsPasskey == true || b.hold != nil ? Theme.warning : .secondary88 }89}9091@MainActor enum BridgeText {92 static func reclaim(_ s: ReclaimState) -> String {93 switch s {94 case .pending: "la destruction n’est pas encore minée"95 case .locked: "verrouillé (fenêtre de cinq jours du programme)"96 case .available: "récupérable maintenant"97 case .sent: "récupération diffusée, non confirmée"98 case .done: "récupéré"99 case .failed: "dernière tentative échouée — le dépôt est toujours là"100 default: s.rawValue101 }102 }103 static func speed(_ s: BridgeSpeed?) -> String {104 switch s { case .some(.standard): "Standard"; case .some(.fast): "Rapide (Fast Transfer)"; case .some(let o): o.rawValue; case nil: "—" }105 }106}107108// MARK: - Form and quote109110private struct BridgeFormCard: View {111 let model: AppModel112 @Bindable var flow: BridgeFlow113114 var body: some View {115 Card("Transfert") {116 Form {117 NetworkPicker(networks: flow.networks, selection: $flow.fromNetwork, label: "Réseau source")118 NetworkPicker(networks: flow.networks.filter { $0.id != flow.fromNetwork }, selection: $flow.toNetwork, label: "Réseau de destination")119 LabeledContent("Actif") {120 VStack(alignment: .trailing, spacing: 1) {121 Text("\(flow.info?.asset ?? "USDC") (émis par Circle) — seul actif de ce pont")122 if let u = flow.usdc(on: flow.fromNetwork) { Text(u.id).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) }123 }124 }125 LabeledContent("Solde USDC sur la source") {126 if let b = flow.sourceBalance, b.isAvailable { Text(model.settings.hideBalances ? "••••" : "\(Fmt.amount(b.display)) \(b.symbol)").monospacedDigit() }127 else if flow.sourceBalance != nil { Text("Indisponible (lecture de chaîne en échec)").foregroundStyle(Theme.negative) }128 else { Text("—") }129 }130 HStack {131 TextField("Montant", text: $flow.amount, prompt: Text("0.0"))132 Text("USDC").foregroundStyle(.secondary)133 Button("Max") { flow.setMax() }.disabled(flow.sourceBalance?.isAvailable != true)134 }135 LabeledContent("Destinataire") {136 Text(model.address(on: flow.toNetwork) ?? "adresse de ce portefeuille sur la destination").font(Theme.monoSmall).textSelection(.enabled)137 }138 }139 .formStyle(.grouped).scrollDisabled(true).disabled(flow.step != .form)140 HStack {141 Button { flow.flip() } label: { Label("Inverser les réseaux", systemImage: "arrow.up.arrow.down") }.disabled(flow.step != .form)142 Spacer()143 if let p = flow.formProblem, !flow.amount.isEmpty { Text(p).font(.callout).foregroundStyle(Theme.warning) }144 }145 Text("Le destinataire est toujours l’adresse de ce portefeuille sur le réseau de destination : le serveur et l’app refusent tout autre bénéficiaire.").font(.caption).foregroundStyle(.secondary)146 }147 }148}149150private struct BridgeQuoteCard: View {151 let model: AppModel152 @Bindable var flow: BridgeFlow153154 var body: some View {155 switch flow.quotePhase {156 case .idle: EmptyView()157 case .loading: Card("Devis") { HStack { ProgressView().controlSize(.small); Text("Lecture des frais de Circle et des frais de réseau…").foregroundStyle(.secondary) } }158 case .failed(let m):159 Card("Devis") { Banner(.danger, m); HStack { Spacer(); Button("Réessayer") { flow.refreshQuote() } } }160 case .done:161 if let q = flow.quote { quoteCard(q) }162 }163 }164165 @ViewBuilder private func quoteCard(_ q: BridgeQuote) -> some View {166 Card("Devis — \(q.fromName ?? q.from) → \(q.toName ?? q.to)", trailing: AnyView(HStack(spacing: 8) {167 if let at = flow.quotedAt { Text("Lu \(Fmt.relative(at))").font(.caption).foregroundStyle(.secondary) }168 Button("Rafraîchir") { flow.refreshQuote() }.controlSize(.small).disabled(flow.step != .form)169 })) {170 Text("Route : destruction (burn) des USDC sur \(q.fromName ?? q.from) → attestation par Circle → émission (mint) sur \(q.toName ?? q.to). Une seule approbation par passkey couvre la destruction et la première émission.")171 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)172 ForEach(q.options, id: \.speed) { o in optionRow(o) }173 Divider()174 Field(label: "Frais d’émission (destination)", value: "≈ \(Fmt.amount(q.destinationGas.needDisplay, maxFraction: 8)) \(q.destinationGas.symbol) requis · le portefeuille détient \(Fmt.amount(q.destinationGas.balanceDisplay, maxFraction: 8)) \(q.destinationGas.symbol)")175 if !q.destinationGas.enough { Banner(.danger, "Pas assez de \(q.destinationGas.symbol) sur \(q.toName ?? q.to) pour payer l’émission. Le serveur refuse de brûler quoi que ce soit tant que la destination ne peut pas recevoir.") }176 if let s = q.solana { solana(s, q) }177 if let e = flow.error { Banner(.danger, e) }178 HStack {179 if let p = flow.prepareProblem, flow.formProblem == nil { Text(p).font(.callout).foregroundStyle(Theme.warning).fixedSize(horizontal: false, vertical: true) }180 Spacer()181 if flow.step == .preparing { ProgressView().controlSize(.small); Text("Contrats, frais, simulation, limites du signataire…").font(.callout).foregroundStyle(.secondary) }182 Button(SwapText.isSimulatedServer(model) ? "Préparer et vérifier (serveur de test)…" : "Préparer et vérifier…") { Task { await flow.prepare() } }183 .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.prepareProblem != nil || !model.canOperate || flow.step != .form)184 }185 Text("Préparer ne signe rien et ne brûle rien : le serveur vérifie le code des contrats de Circle, simule la destruction et contrôle les limites du signataire ; l’app vérifie ensuite que le défi de la passkey est l’empreinte du transfert affiché.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)186 }187 }188189 private func optionRow(_ o: BridgeQuote.Option) -> some View {190 let selected = flow.speed == o.speed191 return Button { flow.speed = o.speed } label: {192 HStack(alignment: .top, spacing: 10) {193 Image(systemName: selected ? "largecircle.fill.circle" : "circle").foregroundStyle(selected ? Theme.accent : .secondary)194 VStack(alignment: .leading, spacing: 3) {195 HStack { Text(BridgeText.speed(o.speed)).fontWeight(.semibold); if !o.available { ProvenanceTag(p: .unavailable, text: "Indisponible maintenant") } }196 Text("Frais Circle (plafond) : \(Fmt.amount(o.feeDisplay)) USDC · Minimum reçu : \(Fmt.amount(o.minReceiveDisplay)) USDC · Durée attendue : \(SwapText.duration(o.seconds))").font(.callout).monospacedDigit()197 .fixedSize(horizontal: false, vertical: true)198 if !o.available { Text(o.quote == nil ? "Le montant ne couvre pas ces frais." : "Circle n’offre pas cette vitesse pour ce montant en ce moment (frais ou allocation Fast).").font(.caption).foregroundStyle(Theme.warning) }199 }200 Spacer()201 }202 .padding(10).background(selected ? Theme.accent.opacity(0.08) : Color.clear, in: RoundedRectangle(cornerRadius: 8))203 .overlay(RoundedRectangle(cornerRadius: 8).strokeBorder(selected ? Theme.accent.opacity(0.5) : Theme.stroke.opacity(0.5)))204 .contentShape(Rectangle())205 }206 .buttonStyle(.plain).disabled(flow.step != .form)207 .accessibilityLabel("Vitesse \(BridgeText.speed(o.speed))\(selected ? ", sélectionnée" : "")")208 }209210 @ViewBuilder private func solana(_ s: BridgeQuote.Solana, _ q: BridgeQuote) -> some View {211 Divider()212 if s.role == "source" {213 Field(label: "Dépôt Solana (remboursable)", value: "\(Fmt.amount(s.depositDisplay, maxFraction: 9)) \(s.symbol ?? "SOL") — loyer du compte d’événement créé par la destruction ; récupérable après \(s.reclaimAfterSeconds.map { "\($0 / 86400) jours" } ?? "le délai du programme"), par une transaction approuvée par passkey.")214 if let f = s.networkFeeDisplay { Field(label: "Frais de réseau Solana", value: "≈ \(Fmt.amount(f, maxFraction: 9)) \(s.symbol ?? "SOL")") }215 } else {216 if let r = s.recipient { Field(label: "Bénéficiaire (Solana)", value: r, mono: true) }217 if let t = s.tokenAccount { Field(label: "Compte de jetons USDC", value: t + (s.tokenAccountExists == true ? " — existe" : s.tokenAccountExists == false ? " — N’EXISTE PAS ENCORE" : ""), mono: true) }218 if let r = s.nonceRentDisplay { Field(label: "Loyer du compte de nonce", value: "\(Fmt.amount(r, maxFraction: 9)) \(s.symbol ?? "SOL") (payé par l’émission)") }219 if s.tokenAccountExists == false { tokenAccount(s) }220 }221 }222223 @ViewBuilder private func tokenAccount(_ s: BridgeQuote.Solana) -> some View {224 Banner(.warning, "Le compte de jetons USDC de ce portefeuille n’existe pas encore sur Solana. La destruction le nomme et ne peut pas être redirigée : il doit être ouvert AVANT (petite transaction approuvée par passkey, dépôt de loyer ≈ \(Fmt.amount(s.tokenAccountRentDisplay, maxFraction: 9)) \(s.symbol ?? "SOL")).")225 if let why = flow.unavailable[.tokenAccount] { Banner(.danger, "Ouverture indisponible : \(why)") }226 if let c = flow.tokenAccountCreation {227 Banner(c.sent ? .info : .warning, c.sent ? "Transaction d’ouverture diffusée (non confirmée) : \(c.txid). Rafraîchissez le devis dans quelques secondes pour constater l’existence du compte." : "Serveur de test : la transaction d’ouverture a été signée mais PAS diffusée. Le compte n’a pas été créé.")228 SafeLink(title: "Ouvrir dans l’explorateur de blocs", url: c.explorer)229 }230 HStack {231 Spacer()232 if flow.busyAction == .tokenAccount { ProgressView().controlSize(.small) }233 Button("Ouvrir le compte de jetons USDC…") { Task { await flow.beginTokenAccount() } }234 .disabled(!model.canOperate || flow.busyAction != nil || flow.unavailable[.tokenAccount] != nil)235 }236 }237}238239// MARK: - Review of the burn240241private struct BridgeReviewSheet: View {242 let model: AppModel243 let flow: BridgeFlow244 let operation: ApprovableOperation245246 var body: some View {247 OperationReviewSheet(model: model, title: "Vérifier et approuver le transfert inter-chaînes", operation: operation, notices: notices, extra: extra,248 busy: flow.step == .approving, error: flow.error,249 onReject: { Task { await flow.reject() } }, onApprove: { Task { await flow.approve() } })250 }251252 private var notices: [(Banner.Kind, String)] {253 var out: [(Banner.Kind, String)] = [(.info, "Cette approbation couvre la destruction des USDC sur la source ET la première émission sur la destination. Après la destruction, le transfert ne peut plus être annulé ; il n’est terminé que lorsque l’émission est confirmée sur la destination.")]254 if let a = OperationReviewSheet.spendApproval(operation.intent, model: model) { out.append(a) }255 return out256 }257258 private var extra: [ReviewLine] { OperationReviewSheet.contextLines(model: model, operation: operation) }259}260261// MARK: - Follow-up approvals (objects that are not intents)262263private struct BridgeFollowUpSheet: View {264 let model: AppModel265 let flow: BridgeFlow266 let followUp: BridgeFlow.FollowUp267268 var body: some View {269 let simulated = SwapText.isSimulatedServer(model)270 VStack(alignment: .leading, spacing: 0) {271 HStack {272 Text(title).font(.title2.weight(.semibold))273 Spacer()274 if simulated { ProvenanceTag(p: .simulated, text: "Serveur de test : signé, non diffusé") }275 }.padding(20)276 Divider()277 ScrollView {278 VStack(alignment: .leading, spacing: 14) {279 Banner(.info, explanation)280 ReviewLines(lines: lines)281 BindingProof(digest: digest, expiry: expiry)282 }.padding(20)283 }284 Divider()285 VStack(alignment: .leading, spacing: 8) {286 if let e = flow.followUpError { Banner(.danger, e) }287 HStack {288 Button("Annuler") { flow.cancelFollowUp() }.disabled(flow.followUpBusy)289 Spacer()290 if flow.followUpBusy { ProgressView().controlSize(.small); Text("Passkey, puis signature isolée…").foregroundStyle(.secondary) }291 Button { Task { await flow.confirmFollowUp() } } label: { Label(simulated ? "Approuver (test : ne sera pas diffusé)" : "Approuver avec la passkey", systemImage: "touchid") }292 .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.followUpBusy || !model.canOperate)293 }294 }.padding(16)295 }296 .frame(width: 720, height: 640)297 .interactiveDismissDisabled()298 }299300 private var title: String {301 switch followUp {302 case .retryMint: "Signer de nouveau l’émission (mint)"303 case .reclaim: "Récupérer le dépôt du compte d’événement Solana"304 case .tokenAccount: "Ouvrir le compte de jetons USDC sur Solana"305 }306 }307 private var explanation: String {308 switch followUp {309 case .retryMint: "La première émission a échoué, a été remplacée ou a expiré. Les USDC brûlés attendent toujours : cette approbation signe une nouvelle transaction d’émission pour le même message attesté par Circle, avec les paramètres de frais ci-dessous. Une émission renvoyée n’est pas une émission reçue."310 case .reclaim: "La destruction faite sur Solana a créé un compte d’événement dont le loyer vous revient cinq jours plus tard. Cette approbation signe la transaction qui ferme ce compte et rend le dépôt à ce portefeuille."311 case .tokenAccount: "Cette approbation signe une transaction Solana qui ouvre le compte de jetons USDC de ce portefeuille (dépôt de loyer). Elle ne déplace aucun USDC."312 }313 }314 private var digest: Data {315 switch followUp { case .retryMint(let a): a.approval.digest; case .reclaim(let a): a.approval.digest; case .tokenAccount(let a): a.approval.digest }316 }317 private var expiry: Date? { if case .tokenAccount(let a) = followUp { a.request.expiry } else { nil } }318319 private func budget(_ b: SolanaBudget) -> [ReviewLine] {320 let sol = model.network("solana")?.native321 return [322 .init(label: "Blockhash récent", value: b.recentBlockhash, style: .address),323 .init(label: "Valide jusqu’au bloc", value: String(b.lastValidBlockHeight)),324 .init(label: "Budget de calcul", value: "\(b.computeUnitLimit) CU à \(b.computeUnitPrice) µlamports/CU"),325 .init(label: "Frais de réseau", value: b.singleSignerNetworkFee.map { "\(SwapText.units($0.description, decimals: sol?.decimals)) \(sol?.symbol ?? "SOL")" } ?? "non calculable", style: .strong),326 ]327 }328329 /// Only fields of the object whose hash is the challenge, plus served figures the Core checked against it.330 private var lines: [ReviewLine] {331 let sol = model.network("solana")?.native332 switch followUp {333 case .retryMint(let a):334 let o = a.object335 let dest = (try? a.proposal.bridgeSection())?.toNetwork336 var out: [ReviewLine] = [337 .init(label: "Opération", value: "Nouvelle signature de l’émission CCTP", style: .strong),338 .init(label: "Transfert", value: o.proposalId),339 .init(label: "Message attesté (empreinte)", value: o.messageHash, style: .address),340 .init(label: "Réseau de destination", value: dest.map { model.network($0)?.name ?? $0 } ?? "—"),341 .init(label: "Montant du transfert", value: "\(Fmt.amount(a.proposal.amountDisplay)) \(a.proposal.symbol) (inchangé : fixé par le message attesté)"),342 ]343 switch o.parameters {344 case .evm(let g):345 let native = dest.flatMap { model.network($0)?.native }346 out.append(.init(label: "Paramètres EVM", value: "nonce \(g.nonce) · gaz \(g.gasLimit) · max \(g.maxFeePerGas) wei/gaz · priorité \(g.maxPriorityFeePerGas)"))347 out.append(.init(label: "Frais de réseau maximum", value: "\(SwapText.units(g.maxNetworkFee, decimals: native?.decimals)) \(native?.symbol ?? "")", style: .strong))348 case .solana(let b): out += budget(b)349 }350 return out351 case .reclaim(let a):352 let o = a.object353 return [354 .init(label: "Opération", value: "Fermeture du compte d’événement CCTP et retour du dépôt", style: .strong),355 .init(label: "Transfert", value: o.proposalId),356 .init(label: "Compte d’événement", value: o.eventAccount, style: .address),357 .init(label: "Message attesté (empreinte)", value: o.messageHash, style: .address),358 .init(label: "Dépôt rendu", value: "\(SwapText.units(a.deposit, decimals: sol?.decimals)) \(sol?.symbol ?? "SOL") (lu sur la chaîne par le serveur)", style: .strong),359 .init(label: "Bénéficiaire", value: model.address(on: "solana") ?? "adresse Solana de ce portefeuille", style: .address),360 ] + budget(o.budget)361 case .tokenAccount(let a):362 let q = a.request363 return [364 .init(label: "Opération", value: "Création du compte de jetons USDC (compte associé)", style: .strong),365 .init(label: "Réseau", value: "\(model.network(q.network)?.name ?? q.network) (\(q.network), \(q.chainRef))"),366 .init(label: "Propriétaire", value: q.owner, style: .address),367 .init(label: "Jeton (mint USDC)", value: q.mint, style: .address),368 .init(label: "Compte de jetons créé", value: q.tokenAccount, style: .address),369 .init(label: "Dépôt de loyer", value: "\(SwapText.units(a.rent, decimals: sol?.decimals)) \(sol?.symbol ?? "SOL")"),370 .init(label: "Plafond total (loyer + frais)", value: "\(SwapText.units(q.maxFee, decimals: sol?.decimals)) \(sol?.symbol ?? "SOL")", style: .strong),371 ] + budget(q.budget) + [372 .init(label: "Clé du portefeuille", value: q.keyId),373 .init(label: "Politique du signataire", value: "version \(q.policyVersion)"),374 .init(label: "Demande", value: q.requestId),375 ]376 }377 }378}379380// MARK: - Tracking: the two legs381382private struct BridgeTrackingCard: View {383 let model: AppModel384 let flow: BridgeFlow385 let tracker: OperationTracker386387 var body: some View {388 let p = tracker.proposal389 Card("Suivi du transfert inter-chaînes", trailing: SwapText.isSimulatedServer(model) ? AnyView(ProvenanceTag(p: .simulated, text: "Serveur de test")) : nil) {390 OperationHeadline(proposal: p, completion: tracker.completion)391 if let b = try? p.bridgeSection() { content(p, b) }392 else { Banner(.warning, "La section « pont » de cette opération est illisible par cette version de l’app : aucun état n’est déduit et aucune action n’est proposée.") }393 if let e = p.error { Banner(p.state.isFailure || p.state == .notBroadcast ? .danger : .warning, e) }394 if let e = tracker.readError { Banner(.warning, "Dernière lecture de l’état en échec : \(e)") }395 if let e = flow.error { Banner(.danger, e) }396 if let ex = try? p.executionStatus() { Divider(); ExecutionTimeline(model: model, status: ex) }397 Divider()398 StateHistory(history: tracker.history)399 HStack { Spacer(); Button(tracker.isSettled ? "Fermer" : "Fermer (le transfert reste listé ici et dans Activité)") { flow.closeTracking() } }400 }401 }402403 @ViewBuilder private func content(_ p: Proposal, _ b: BridgeSection) -> some View {404 Field(label: "Étape", value: SwapText.bridgeStage(b.stage), emphasis: true)405 Field(label: "Route", value: "\(p.networkName ?? p.network) → \(b.toNetworkName ?? b.toNetwork) · Circle CCTP · \(BridgeText.speed(b.speed)) (\(SwapText.duration(b.expectedSeconds)))")406 Field(label: "Montant brûlé", value: "\(Fmt.amount(p.amountDisplay)) \(p.symbol)")407 Field(label: "Frais Circle", value: "plafond approuvé \(Fmt.amount(b.cctpMaxFeeDisplay)) \(p.symbol)" + (b.feeExecutedDisplay.map { " · prélevés \(Fmt.amount($0)) \(p.symbol)" } ?? " · montant prélevé pas encore connu"))408 Field(label: "Minimum reçu", value: "\(Fmt.amount(b.minReceiveDisplay)) \(p.symbol)")409 if let r = b.receivedDisplay, b.isComplete {410 HStack { Field(label: "Reçu sur la destination", value: "\(Fmt.amount(r)) \(p.symbol)", emphasis: true); ProvenanceTag(p: .verified) }411 } else {412 Field(label: "Reçu sur la destination", value: "— (pas encore : l’émission n’est pas confirmée)")413 }414 if let h = b.hold { Banner(.warning, SwapText.hold(h) + (b.holdDetail.map { "\nServeur : \($0)" } ?? "")) }415416 Divider()417 Text("Jambe 1 — destruction sur \(p.networkName ?? p.network)").font(.headline)418 if b.needsApproval == true || b.approvalTxid != nil {419 TxField(label: "Autorisation ERC-20", txid: b.approvalTxid ?? "(pas encore diffusée)", state: b.approvalState.map { $0 == "confirmed" ? "confirmée" : $0 == "sent" ? "diffusée, non confirmée" : "en attente" })420 }421 if p.txid != nil { TxField(label: "Transaction de destruction", txid: p.txid, explorer: p.explorer, state: ErrorText.state(p.state)) }422 else { Field(label: "Transaction de destruction", value: "— (\(ErrorText.state(p.state)))") }423 if let c = p.confirmations, p.txid != nil { Field(label: "Confirmations", value: String(c)) }424425 Text("Attestation de Circle").font(.headline)426 Field(label: "État", value: (b.attested == true ? "Reçue et conforme au transfert approuvé" : "Pas encore reçue") + (b.irisStatus.map { " · Circle : \($0)" } ?? "") + (b.delayReason.map { " · \($0)" } ?? ""))427428 Text("Jambe 2 — émission sur \(b.toNetworkName ?? b.toNetwork)").font(.headline)429 if let m = b.mintTxid {430 TxField(label: "Transaction d’émission", txid: m, explorer: b.mintExplorer, state: b.isComplete ? "confirmée" : b.stage == .mintFailed ? "échouée" : "diffusée, non confirmée")431 if b.mintedBy == "other" { Field(label: "Émise par", value: "un tiers (l’émission est ouverte à tous) — les USDC sont bien arrivés à ce portefeuille") }432 } else { Field(label: "Transaction d’émission", value: "— (aucune pour l’instant)") }433434 actions(b)435 if let s = b.sol { Divider(); solana(s) }436 }437438 @ViewBuilder private func actions(_ b: BridgeSection) -> some View {439 if b.needsPasskey == true {440 Banner(.warning, "L’émission doit être signée de nouveau : cela exige votre passkey sur un objet que l’app vérifie (transfert, message attesté, paramètres de frais).")441 if let why = flow.unavailable[.retryMint] { Banner(.danger, "Nouvelle signature indisponible : \(why)") }442 HStack {443 Spacer()444 if flow.busyAction == .retryMint { ProgressView().controlSize(.small) }445 Button("Préparer une nouvelle signature de l’émission…") { Task { await flow.beginRetryMint() } }446 .buttonStyle(.borderedProminent).disabled(!model.canOperate || flow.busyAction != nil || flow.unavailable[.retryMint] != nil)447 }448 } else if b.canFinish == true {449 HStack {450 Text("« Terminer » demande au serveur d’exécuter l’étape suivante maintenant au lieu d’attendre son passage périodique. Aucune nouvelle signature : rien n’est signé au-delà de ce que l’approbation de la destruction couvrait.")451 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)452 Spacer()453 if flow.busyAction == .finish { ProgressView().controlSize(.small) }454 Button("Terminer maintenant") { Task { await flow.finish() } }.disabled(!model.canOperate || flow.busyAction != nil)455 }456 }457 }458459 @ViewBuilder private func solana(_ s: SolanaBridgeSection) -> some View {460 Text("Côté Solana").font(.headline)461 if s.role == "destination" {462 if let r = s.recipient { Field(label: "Bénéficiaire", value: r, mono: true) }463 if let t = s.tokenAccount { Field(label: "Compte de jetons crédité", value: t, mono: true) }464 } else {465 if let e = s.eventAccount { Field(label: "Compte d’événement", value: e, mono: true) }466 if let d = s.depositDisplay { Field(label: "Dépôt remboursable", value: "\(Fmt.amount(d, maxFraction: 9)) \(s.symbol ?? "SOL")") }467 if let st = s.reclaimState {468 Field(label: "Récupération du dépôt", value: BridgeText.reclaim(st), emphasis: true)469 if let at = s.reclaimableAt, !s.isReclaimed { Field(label: "Récupérable à partir du", value: Fmt.date(at) + (s.reclaimEstimated == true ? " (estimation : la destruction n’est pas encore minée ou le compte pas encore lu)" : "")) }470 if let e = s.reclaimError { Banner(.warning, "Dernière tentative : \(e)") }471 TxField(label: "Transaction de récupération", txid: s.reclaimTxid, explorer: s.reclaimExplorer, state: s.isReclaimed ? "confirmée" : "diffusée, non confirmée")472 if let r = s.reclaimedDisplay, s.isReclaimed { Field(label: "Récupéré", value: "\(Fmt.amount(r, maxFraction: 9)) \(s.symbol ?? "SOL")") }473 if let why = flow.unavailable[.reclaim] { Banner(.danger, "Récupération indisponible : \(why)") }474 if s.canReclaim {475 HStack {476 Spacer()477 if flow.busyAction == .reclaim { ProgressView().controlSize(.small) }478 Button("Récupérer le dépôt…") { Task { await flow.beginReclaim() } }479 .buttonStyle(.borderedProminent).disabled(!model.canOperate || flow.busyAction != nil || flow.unavailable[.reclaim] != nil)480 }481 } else if st == .locked || st == .pending {482 Text("La récupération sera offerte ici une fois la fenêtre de cinq jours écoulée et la destruction attestée ; elle demandera votre passkey.").font(.caption).foregroundStyle(.secondary)483 }484 }485 }486 }487}488