Repository Public
1// SP Wallet iOS2// File: Features/Bridge/CCTPBridge.swift3// Description: USDC between networks through Circle CCTP: source and destination among the networks the server serves as4// enabled, exact amount, the two speeds with their fee and duration AS SERVED, the gas the destination needs, the5// Solana prerequisites (the wallet's USDC token account, created with a passkey over a verified request), then the6// preparation of the burn with the reference and the fee ceiling of the option displayed.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import SwiftUI11import SPWalletCore1213@MainActor @Observable14final class CCTPModel {15 var info: BridgeExecutionInfo?16 var infoError: Error?17 var from: String?18 var to: String?19 var amount = ""20 /** nil until the owner picks one. */21 var speed: BridgeSpeed?22 var generation = 02324 var quote: BridgeQuote?25 var quoteAt: Date?26 var quoteError: Error?27 var quoting = false2829 var busy = false30 var error: Error?31 var cleanup: OperationCleanup.Result?32 var serverLacksIntent = false33 var start: OperationStart?34 private var idempotency: (key: String, request: BridgeRequest)?3536 // Solana token account37 var ataApproval: TokenAccountApproval?38 var ataCreation: SolanaTokenAccountCreation?39 var ataError: Error?40 var ataBusy = false4142 func load(_ env: AppEnvironment) async {43 do { info = try await BridgeAPI(env.client).execution(); infoError = nil } catch { infoError = error }44 }4546 /** USDC has six decimals on every CCTP network. */47 static let decimals = 648 var amountText: String? { SwapLogic.checkAmount(amount, decimals: Self.decimals, balance: nil).text }49 var signature: String { "\(from ?? "")|\(to ?? "")|\(amountText ?? "")|\(generation)" }5051 func pick(from id: String) { from = id; if to == id { to = nil }; speed = nil }52 func pick(to id: String) { to = id; if from == id { from = nil }; speed = nil }53 func flip() { (from, to) = (to, from) }5455 /** Reads the quote, then again every 20 s while the screen shows it. Reading prepares nothing. */56 func runQuotes(_ env: AppEnvironment, online: Bool) async {57 quote = nil; quoteAt = nil; quoteError = nil; error = nil; cleanup = nil; ataApproval = nil; ataCreation = nil; ataError = nil58 guard online, let from, let to, let text = amountText, info?.canBridge(from: from, to: to) == true else { quoting = false; return }59 try? await Task.sleep(for: .milliseconds(450))60 while !Task.isCancelled {61 quoting = true62 do {63 let q = try await BridgeAPI(env.client).quote(from: from, to: to, amount: text)64 if Task.isCancelled { return }65 quote = q; quoteAt = Date(); quoteError = nil66 } catch { if Task.isCancelled { return }; quoteError = error; quote = nil }67 quoting = false68 try? await Task.sleep(for: .seconds(20))69 }70 }7172 var option: BridgeQuote.Option? { speed.flatMap { quote?.option($0) } }7374 func request() -> BridgeRequest? {75 guard let from, let to, let text = amountText, let speed, let o = option, o.available, let ref = o.quote else { return nil }76 return BridgeRequest(fromNetwork: from, toNetwork: to, amount: text, speed: speed, quote: ref)77 }7879 private func key(for r: BridgeRequest) -> String {80 if let i = idempotency, i.request == r { return i.key }81 let k = APIClient.newIdempotencyKey()82 idempotency = (k, r)83 return k84 }8586 func prepare(_ env: AppEnvironment, accounts: Accounts?, sourceUSDC: String?) async {87 guard !busy, !serverLacksIntent, let accounts, let sourceUSDC, let r = request(), let o = option else { return }88 busy = true; error = nil; cleanup = nil89 defer { busy = false }90 let started = Date()91 do {92 // the fee ceiling approved must not exceed the fee of the option displayed93 let prepared = try await BridgeAPI(env.client).prepare(r, accounts: accounts, sourceUSDC: sourceUSDC, maxFee: o.fee, idempotencyKey: key(for: r))94 idempotency = nil95 start = prepared.approvable.map { .review($0) } ?? .tracking(proposalId: prepared.proposal.id)96 } catch {97 let kind = SwapLogic.classify(error)98 if kind != .offline { idempotency = nil }99 self.error = error100 if kind == .serverLacksIntent { serverLacksIntent = true }101 if kind == .quoteMoved { generation += 1 }102 if SwapLogic.leavesPendingProposal(error) {103 let units = SwapLogic.checkAmount(r.amount, decimals: Self.decimals, balance: nil).units?.description104 cleanup = await OperationCleanup.withdraw(env, kind: "bridge", network: r.fromNetwork, asset: sourceUSDC, amountUnits: units, since: started).result105 }106 }107 }108109 // MARK: Solana token account (must exist before anything is burned toward Solana)110111 func askTokenAccount(_ env: AppEnvironment, accounts: Accounts?, usdcMint: String?) async {112 guard !ataBusy, let accounts, let usdcMint else { return }113 ataBusy = true; ataError = nil114 defer { ataBusy = false }115 do { ataApproval = try await BridgeAPI(env.client).solanaTokenAccountOptions(accounts: accounts, usdcMint: usdcMint) } catch { ataError = error }116 }117118 func createTokenAccount(_ env: AppEnvironment) async {119 guard !ataBusy, let a = ataApproval else { return }120 ataBusy = true; ataError = nil121 defer { ataBusy = false }122 do { ataCreation = try await BridgeAPI(env.client).createSolanaTokenAccount(a, with: env.passkeys); ataApproval = nil }123 catch PasskeyError.cancelled { /* nothing signed */ }124 catch { ataError = error }125 }126}127128struct CCTPBridgeView: View {129 @Environment(AppModel.self) private var model130 let regular: Bool131 @State private var cctp = CCTPModel()132133 var body: some View {134 @Bindable var cctp = cctp135 Group {136 if let e = cctp.infoError, cctp.info == nil { ErrorNotice(error: e) { Task { await cctp.load(model.env) } } }137 else if let info = cctp.info {138 if !info.enabled { Notice(tone: .warn, title: String(localized: "Transferts CCTP désactivés sur ce serveur")) }139 else if regular {140 HStack(alignment: .top, spacing: 20) {141 VStack(alignment: .leading, spacing: Theme.Space.section) { form(info); prepareBlock }.frame(maxWidth: 440)142 VStack(alignment: .leading, spacing: Theme.Space.section) { details }.frame(maxWidth: .infinity)143 }144 } else { form(info); details; prepareBlock }145 } else if model.canOperate { ProgressView().frame(maxWidth: .infinity).padding(.vertical, 30) }146 }147 .task(id: model.canOperate) { if model.canOperate, cctp.info == nil { await cctp.load(model.env) } }148 .task(id: cctp.signature + (model.canOperate ? "+" : "-") + (cctp.info == nil ? "?" : "!")) { await cctp.runQuotes(model.env, online: model.canOperate) }149 .sheet(item: $cctp.start, onDismiss: { cctp.generation += 1; Task { await model.refreshAll() } }) { OperationSheet(start: $0).wallet(model) }150 }151152 private func name(_ id: String) -> String { model.network(id)?.name ?? id }153 private func usdc(_ network: String?) -> AssetDef? { network.flatMap { model.network($0) }?.tokens.first { $0.symbol == "USDC" } }154 private var balance: Balance? {155 guard let f = cctp.from else { return nil }156 return model.portfolio.value?.balances.first { $0.network == f && $0.symbol == "USDC" && $0.asset != "native" }157 }158 private var amountCheck: SwapLogic.AmountCheck { SwapLogic.checkAmount(cctp.amount, decimals: CCTPModel.decimals, balance: balance?.units) }159160 // MARK: form161162 @ViewBuilder private func form(_ info: BridgeExecutionInfo) -> some View {163 @Bindable var cctp = cctp164 VStack(alignment: .leading, spacing: 12) {165 networkMenu(String(localized: "Depuis"), cctp.from, id: "cctp.from", options: info.networks) { cctp.pick(from: $0) }166 HStack {167 Rectangle().fill(Theme.hairline).frame(height: 0.5)168 Button { cctp.flip() } label: { Image(systemName: "arrow.up.arrow.down").font(.system(size: 15, weight: .semibold)).frame(width: 44, height: 44).background(Theme.elev, in: Circle()) }169 .foregroundStyle(Theme.ink).accessibilityLabel(String(localized: "Inverser")).accessibilityIdentifier("cctp.flip")170 Rectangle().fill(Theme.hairline).frame(height: 0.5)171 }172 networkMenu(String(localized: "Vers"), cctp.to, id: "cctp.to", options: info.networks.filter { $0 != cctp.from }) { cctp.pick(to: $0) }173 Text(String(localized: "Seuls les réseaux que le serveur sert pour CCTP sont proposés. Les USDC arrivent à ta propre adresse sur le réseau de destination."))174 .font(.spFootnote).foregroundStyle(Theme.mute)175 }176 .spCard().disabled(!model.canOperate)177178 if cctp.from != nil {179 VStack(alignment: .leading, spacing: 10) {180 Text(String(localized: "Montant")).font(.spHeadline)181 HStack {182 TextField("0", text: $cctp.amount).keyboardType(.decimalPad).font(.system(size: 30, weight: .semibold)).monospacedDigit().accessibilityIdentifier("cctp.amount")183 Text("USDC").font(.spHeadline).foregroundStyle(Theme.mute)184 }185 HStack {186 Text(String(localized: "Disponible")).font(.spFootnote).foregroundStyle(Theme.mute)187 Spacer()188 if let d = balance?.display {189 Masked(text: Money.exact(d) + " USDC").font(.spFootnote.weight(.semibold)).monospacedDigit()190 Button(String(localized: "Tout")) { cctp.amount = d }.font(.spFootnote.weight(.semibold)).buttonStyle(.bordered).accessibilityIdentifier("cctp.max")191 } else { Text(String(localized: "solde indisponible")).font(.spFootnote).foregroundStyle(Theme.warn) }192 }193 if let p = amountCheck.problem { Label(p, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(amountCheck == .aboveBalance ? Theme.warn : Theme.danger).accessibilityIdentifier("cctp.amountProblem") }194 Text(String(localized: "Les frais du pont sont prélevés sur le montant ; les frais de réseau se paient en monnaie native de chaque réseau.")).font(.spFootnote).foregroundStyle(Theme.mute)195 }196 .spCard().disabled(!model.canOperate)197 }198 }199200 private func networkMenu(_ title: String, _ current: String?, id: String, options: [String], pick: @escaping (String) -> Void) -> some View {201 VStack(alignment: .leading, spacing: 6) {202 Text(title).spEyebrow()203 Menu {204 ForEach(options, id: \.self) { n in Button(name(n)) { pick(n) } }205 } label: {206 HStack(spacing: 12) {207 if let c = current { NetworkIcon(network: c, size: 34) } else { Circle().fill(Theme.elev).frame(width: 34, height: 34) }208 Text(current.map(name) ?? String(localized: "Choisir un réseau")).font(.spHeadline).foregroundStyle(Theme.ink)209 Spacer()210 Image(systemName: "chevron.up.chevron.down").font(.system(size: 13, weight: .semibold)).foregroundStyle(Theme.mute)211 }.frame(minHeight: 48).contentShape(Rectangle())212 }213 .accessibilityIdentifier(id)214 }215 }216217 // MARK: quote details218219 @ViewBuilder private var details: some View {220 if cctp.from != nil, cctp.to != nil {221 VStack(alignment: .leading, spacing: 12) {222 HStack {223 Text(String(localized: "Vitesse et frais")).font(.spHeadline)224 if cctp.quoting { ProgressView().padding(.leading, 4) }225 Spacer()226 if let at = cctp.quoteAt { TimelineView(.periodic(from: .now, by: 5)) { ctx in Text(String(localized: "lu il y a \(max(0, Int(ctx.date.timeIntervalSince(at)))) s")).font(.system(size: 12)).foregroundStyle(Theme.mute) } }227 }228 if cctp.amountText == nil { Text(String(localized: "Saisis un montant pour voir les frais et les durées.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("cctp.quote.waiting") }229 if let e = cctp.quoteError { ErrorNotice(error: e) { cctp.generation += 1 }.accessibilityIdentifier("cctp.quote.error") }230 if let q = cctp.quote {231 ForEach(q.options, id: \.speed) { o in speedCard(o) }232 Text(String(localized: "Frais et durées tels que servis par le serveur (plafond de Circle). Aucune vitesse n’est choisie à ta place.")).font(.spFootnote).foregroundStyle(Theme.mute)233 }234 }235 .spCard()236 if let q = cctp.quote {237 gasCard(q)238 if let s = q.solana { solanaCard(s) }239 }240 }241 }242243 private func speedCard(_ o: BridgeQuote.Option) -> some View {244 let selected = cctp.speed == o.speed245 let title = o.speed == .fast ? String(localized: "Rapide") : o.speed == .standard ? String(localized: "Standard") : o.speed.rawValue246 return Button { if o.available { cctp.speed = o.speed } } label: {247 VStack(alignment: .leading, spacing: 6) {248 HStack {249 Image(systemName: selected ? "checkmark.circle.fill" : "circle").foregroundStyle(selected ? Theme.primary : Theme.mute)250 Text(title).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink)251 Spacer()252 if !o.available { Pill(text: String(localized: "Indisponible maintenant"), tone: .warn, icon: "exclamationmark.triangle.fill") }253 }254 row(String(localized: "Frais du pont, plafond"), Money.exact(o.feeDisplay) + " USDC")255 row(String(localized: "Minimum reçu"), Money.exact(o.minReceiveDisplay) + " USDC")256 row(String(localized: "Durée attendue"), SwapLogic.duration(o.seconds))257 }258 .padding(14).frame(maxWidth: .infinity, alignment: .leading)259 .background(Theme.bg, in: RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous))260 .overlay(RoundedRectangle(cornerRadius: Theme.Radius.control, style: .continuous).strokeBorder(selected ? Theme.primary : Theme.hairline, lineWidth: selected ? 2 : 0.5))261 .opacity(o.available ? 1 : 0.6)262 }263 .buttonStyle(.plain).disabled(!o.available || !model.canOperate)264 .accessibilityIdentifier("cctp.speed.\(o.speed.rawValue)").accessibilityAddTraits(selected ? .isSelected : [])265 }266267 private func row(_ label: String, _ value: String) -> some View {268 HStack(alignment: .firstTextBaseline) {269 Text(label).font(.spFootnote).foregroundStyle(Theme.mute)270 Spacer(minLength: 8)271 Text(value).font(.spFootnote.weight(.medium)).monospacedDigit().foregroundStyle(Theme.ink).multilineTextAlignment(.trailing).fixedSize(horizontal: false, vertical: true)272 }273 }274275 private func gasCard(_ q: BridgeQuote) -> some View {276 let g = q.destinationGas277 return VStack(alignment: .leading, spacing: 8) {278 if g.enough {279 Notice(tone: .info, title: String(localized: "Frais sur \(q.toName ?? name(q.to)) : couverts"),280 message: String(localized: "L’émission sur la destination coûte environ \(Money.exact(g.needDisplay)) \(g.symbol) ; ce portefeuille y détient \(Money.exact(g.balanceDisplay)) \(g.symbol)."))281 } else {282 Notice(tone: .danger, title: String(localized: "Pas assez de \(g.symbol) sur \(q.toName ?? name(q.to)) pour recevoir"),283 message: String(localized: "L’émission sur la destination exige \(Money.exact(g.needDisplay)) \(g.symbol) ; ce portefeuille n’y détient que \(Money.exact(g.balanceDisplay)) \(g.symbol). Le serveur refuse de brûler tant que ce n’est pas couvert."))284 .accessibilityIdentifier("cctp.gasMissing")285 }286 }287 }288289 @ViewBuilder private func solanaCard(_ s: BridgeQuote.Solana) -> some View {290 VStack(alignment: .leading, spacing: 10) {291 Text(String(localized: "Particularités Solana")).font(.spHeadline)292 if s.role == "source" {293 if let d = s.depositDisplay { FieldRow(label: String(localized: "Dépôt remboursable du compte d’événement"), value: Money.exact(d) + " " + (s.symbol ?? "SOL")) }294 if let sec = s.reclaimAfterSeconds { FieldRow(label: String(localized: "Récupérable après"), value: SwapLogic.duration(Double(sec))) }295 if let f = s.networkFeeDisplay { FieldRow(label: String(localized: "Frais de réseau Solana"), value: Money.exact(f) + " " + (s.symbol ?? "SOL")) }296 Text(String(localized: "Le brûlage sur Solana bloque ce dépôt ; il se récupère plus tard depuis le suivi du transfert, avec ta clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute)297 } else {298 if let r = s.recipient { FieldRow(label: String(localized: "Adresse Solana du portefeuille"), value: r, mono: true, copyable: true) }299 if let t = s.tokenAccount { FieldRow(label: String(localized: "Compte de jetons USDC"), value: t, mono: true, copyable: true) }300 if s.tokenAccountExists == false { tokenAccountFlow(s) }301 else if s.tokenAccountExists == true { Label(String(localized: "Le compte de jetons USDC existe."), systemImage: "checkmark.circle.fill").font(.spFootnote).foregroundStyle(Theme.emerald) }302 else { Text(String(localized: "Existence du compte de jetons : non indiquée par le serveur.")).font(.spFootnote).foregroundStyle(Theme.warn) }303 }304 }305 .spCard()306 }307308 @ViewBuilder private func tokenAccountFlow(_ s: BridgeQuote.Solana) -> some View {309 Notice(tone: .warn, title: String(localized: "Compte de jetons USDC à créer d’abord"),310 message: String(localized: "Sans lui, les USDC ne peuvent pas être émis sur Solana : rien n’est brûlé tant qu’il n’existe pas. Sa création est une petite transaction approuvée par ta clé d’accès.") + (s.tokenAccountRentDisplay.map { " " + String(localized: "Loyer : \(Money.exact($0)) SOL.") } ?? ""))311 .accessibilityIdentifier("cctp.ataMissing")312 if let c = cctp.ataCreation {313 Notice(tone: c.sent ? .info : .warn, title: c.sent ? String(localized: "Création envoyée, pas encore confirmée") : String(localized: "Signée mais NON envoyée (diffusion désactivée sur ce serveur)"),314 message: String(localized: "Le formulaire relit l’état du compte toutes les 20 s."))315 FieldRow(label: String(localized: "Transaction de création"), value: c.txid, mono: true, copyable: true)316 ExplorerLink(url: c.explorer)317 } else if let a = cctp.ataApproval {318 VStack(alignment: .leading, spacing: 0) {319 FieldRow(label: String(localized: "Propriétaire (ce portefeuille)"), value: a.request.owner, mono: true)320 Divider(); FieldRow(label: String(localized: "Jeton (mint USDC)"), value: a.request.mint, mono: true)321 Divider(); FieldRow(label: String(localized: "Compte créé"), value: a.request.tokenAccount, mono: true)322 Divider(); FieldRow(label: String(localized: "Loyer"), value: lamports(a.rent, a.rentDisplay))323 Divider(); FieldRow(label: String(localized: "Frais de réseau"), value: lamports(a.networkFee, a.networkFeeDisplay))324 Divider(); FieldRow(label: String(localized: "Plafond total approuvé"), value: lamports(a.request.maxFee, nil))325 Divider(); FieldRow(label: String(localized: "Empreinte approuvée par la clé d’accès"), value: a.approval.digest.hex, mono: true, copyable: true)326 }.spCard(padding: 16)327 Button { Task { await cctp.createTokenAccount(model.env) } } label: { HStack { if cctp.ataBusy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Créer le compte avec la clé d’accès")) } }328 .buttonStyle(.spSecondary).disabled(cctp.ataBusy || !model.canOperate).accessibilityIdentifier("cctp.ata.confirm")329 } else {330 Button { Task { await cctp.askTokenAccount(model.env, accounts: model.accounts.value, usdcMint: usdc("solana")?.id) } } label: { HStack { if cctp.ataBusy { ProgressView() }; Text(String(localized: "Préparer la création du compte")) } }331 .buttonStyle(.spSecondary).disabled(cctp.ataBusy || !model.canOperate || usdc("solana") == nil).accessibilityIdentifier("cctp.ata.prepare")332 }333 if let e = cctp.ataError { PrepareRefusalNotice(error: e) }334 }335336 private func lamports(_ units: String, _ display: String?) -> String {337 let sol = model.network("solana")?.native338 if let display { return Money.exact(display) + " " + (sol?.symbol ?? "SOL") }339 guard let sol, let u = try? BaseUnits(units) else { return units + " " + String(localized: "(unités de base)") }340 return Money.exact(u.formatted(decimals: sol.decimals)) + " " + sol.symbol341 }342343 // MARK: prepare344345 private var blockedReason: String? {346 guard let q = cctp.quote else { return nil }347 if !q.destinationGas.enough { return String(localized: "Frais de destination non couverts.") }348 if q.solana?.role == "destination", q.solana?.tokenAccountExists != true { return String(localized: "Le compte de jetons USDC sur Solana doit exister d’abord.") }349 if usdc(cctp.from) == nil { return String(localized: "USDC est absent du registre de l’app pour le réseau source : la préparation ne peut pas être vérifiée.") }350 if cctp.speed == nil { return String(localized: "Choisis une vitesse.") }351 if let o = cctp.option, o.quote == nil { return String(localized: "Le montant ne couvre pas les frais de cette vitesse.") }352 return nil353 }354 private var canPrepare: Bool {355 model.canOperate && !cctp.busy && !cctp.serverLacksIntent && amountCheck.units != nil && cctp.request() != nil && blockedReason == nil && model.accounts.value != nil356 }357358 @ViewBuilder private var prepareBlock: some View {359 if cctp.from != nil, cctp.to != nil {360 if let e = cctp.error { PrepareRefusalNotice(error: e, cleanup: cctp.cleanup) }361 else if cctp.serverLacksIntent { Notice(tone: .warn, title: SwapLogic.missingIntentTitle, message: SwapLogic.missingIntentMessage).accessibilityIdentifier("op.unsupported") }362 Button { Task { await cctp.prepare(model.env, accounts: model.accounts.value, sourceUSDC: usdc(cctp.from)?.id) } } label: { HStack { if cctp.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer et vérifier")) } }363 .buttonStyle(.spPrimary).disabled(!canPrepare).accessibilityIdentifier("cctp.prepare")364 Text(blockedReason ?? String(localized: "Le serveur prépare le brûlage et vérifie les limites ; l’app vérifie ensuite la destination, le plafond de frais et le défi. Rien n’est signé à cette étape. L’approbation du brûlage couvre aussi la première émission sur la destination."))365 .font(.spFootnote).foregroundStyle(blockedReason == nil ? Theme.mute : Theme.warn).accessibilityIdentifier("cctp.prepareHint")366 }367 }368}369