Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet9// File : Features/Swap/SwapLogic.swift10// Description : The decisions of the swap, bridge and cross-network11// screens that must never drift from what is executed — pure12// functions, tested without a server: amount validation, the13// explicit slippage choice, the order of the compared routes14// and which one may be prepared, quote age, what a15// preparation error means (price moved, server without the16// canonical object, refusal), the proposal left behind by a17// refused preparation, and the human rows of a review18// derived FROM THE VERIFIED INTENT.19// Module : Features20// Repository : https://git.spboucher.ai/sp-wallet-ios21// Created : 2026-11-1822// Last Modified : 2026-11-1823//24// =============================================================================25// AUTHOR & PROFESSIONAL AFFILIATION26// =============================================================================27//28// Author : Simon-Pierre Boucher29// Position : Professor of Finance30// Institution : Université du Québec en Outaouais (UQO)31// Department : Département des sciences administratives32// Organization : SP Boucher33//34// Website : https://spboucher.ai35// Git : https://git.spboucher.ai36//37// =============================================================================38// OFFICIAL CONTACT DIRECTORY39// =============================================================================40//41// General : info@spboucher.ai42// Professional : contact@spboucher.ai43// Direct : simon@spboucher.ai44// Research : research@spboucher.ai45// Development : dev@spboucher.ai46// Support : support@spboucher.ai47// Security/Admin : admin@spboucher.ai48// Notifications : notifications@spboucher.ai49//50// Preferred Contact: support@spboucher.ai51//52// =============================================================================53// COPYRIGHT & INTELLECTUAL PROPERTY54// =============================================================================55//56// Copyright (c) 202657// Simon-Pierre Boucher58//59// All rights reserved where applicable.60//61// This file is governed by the applicable project license,62// copyright notices, institutional agreements and relevant law.63//64// Unless expressly authorized by the applicable license or65// rights holder, copying, redistribution, sublicensing,66// publication and commercial exploitation are not permitted.67//68// Existing third-party rights and notices remain unaffected.69//70// =============================================================================71// CONFIDENTIALITY & SECURITY72// =============================================================================73//74// Classification : Public75// Distribution : Public repository; use is governed by the project license76// Security Contact : admin@spboucher.ai77//78// Access to this source does not independently grant permission79// to redistribute or disclose confidential materials.80//81// Do not embed credentials, private keys, access tokens,82// certificates or confidential personal information.83//84// =============================================================================85// LICENSE & MAINTENANCE86// =============================================================================87//88// License : None specified (no license file in this repository)89// Maintainer : Simon-Pierre Boucher90// Technical Contact: dev@spboucher.ai91//92// =============================================================================93// END OF SP BOUCHER SOURCE HEADER94// =============================================================================9596import Foundation97import SPWalletCore9899enum SwapLogic {100 // MARK: slippage (always chosen by the owner, never preselected)101102 /** Tolerances offered for a same-network swap, basis points (the web client offers the same three). */103 static let swapSlippagePresets = [30, 50, 100]104 /** Tolerances offered for a native cross-network swap or a plan (the server accepts 1…300). */105 static let crossSlippagePresets = [50, 100, 300]106107 static func slippageLabel(_ bps: Int, locale: Locale = .current) -> String {108 (Double(bps) / 100).formatted(.number.precision(.fractionLength(0...2)).locale(locale)) + " %"109 }110111 // MARK: amounts112113 enum AmountCheck: Equatable {114 case empty115 case invalid116 case tooManyDecimals(Int)117 case zero118 case aboveBalance119 /** `text` is the canonical decimal text sent to the server (exact, "." separator, no rounding). */120 case ok(units: BaseUnits, text: String)121122 var text: String? { if case .ok(_, let t) = self { t } else { nil } }123 var units: BaseUnits? { if case .ok(let u, _) = self { u } else { nil } }124 var problem: String? {125 switch self {126 case .empty, .ok: nil127 case .invalid: String(localized: "Montant invalide.")128 case .tooManyDecimals(let d): String(localized: "Trop de décimales pour cet actif (\(d) au plus).")129 case .zero: String(localized: "Le montant doit être supérieur à zéro.")130 case .aboveBalance: String(localized: "Montant supérieur au solde disponible.")131 }132 }133 }134135 /** Exact reading of what was typed. `balance == nil` means the balance is unknown: the amount is then not compared with it. */136 static func checkAmount(_ typed: String, decimals: Int, balance: BaseUnits?) -> AmountCheck {137 let t = typed.trimmingCharacters(in: .whitespaces)138 guard !t.isEmpty else { return .empty }139 let units: BaseUnits140 do { units = try BaseUnits.parse(t, decimals: decimals) }141 catch { return error == .tooManyDecimals ? .tooManyDecimals(decimals) : .invalid }142 if units.isZero { return .zero }143 if let balance, units > balance { return .aboveBalance }144 return .ok(units: units, text: units.formatted(decimals: decimals))145 }146147 // MARK: quotes148149 /** Without an expiry from the server, a quote older than this is treated as expired by the app. */150 static let maxAgeWithoutExpiry: TimeInterval = 60151152 enum Freshness: Equatable {153 case fresh(seconds: Int)154 case expired(seconds: Int)155 var isExpired: Bool { if case .expired = self { true } else { false } }156 }157158 /** Age of a quote from the server's own timestamps (Unix milliseconds). nil = the server gave no timestamp. */159 static func freshness(quotedAt: Int?, expiresAt: Int?, now: Date) -> Freshness? {160 guard let quotedAt else { return nil }161 let nowMs = now.timeIntervalSince1970 * 1000162 let age = max(0, Int((nowMs - Double(quotedAt)) / 1000))163 if let expiresAt { return nowMs >= Double(expiresAt) ? .expired(seconds: age) : .fresh(seconds: age) }164 return Double(age) >= maxAgeWithoutExpiry ? .expired(seconds: age) : .fresh(seconds: age)165 }166167 static func freshness(of r: SwapRoute, now: Date) -> Freshness? {168 freshness(quotedAt: r.quotedAt ?? r.card?.quotedAt, expiresAt: r.expiresAt ?? r.card?.expiresAt, now: now)169 }170171 static func ageLabel(_ f: Freshness?) -> String {172 switch f {173 case nil: String(localized: "âge non indiqué")174 case .fresh(let s): s < 90 ? String(localized: "cotée il y a \(s) s") : String(localized: "cotée il y a \(s / 60) min")175 case .expired: String(localized: "cotation expirée")176 }177 }178179 /**180 Display order: the routes the wallet can execute first, then by expected output (exact integer comparison — every route of181 one search delivers the same asset). The order never selects anything.182 */183 static func ordered(_ routes: [SwapRoute]) -> [SwapRoute] {184 func out(_ r: SwapRoute) -> BaseUnits { (try? BaseUnits(r.amountOut)) ?? .zero }185 return routes.sorted { a, b in186 if a.executable != b.executable { return a.executable }187 let (x, y) = (out(a), out(b))188 return x != y ? x > y : a.id < b.id189 }190 }191192 enum Preparability: Equatable {193 case ready(QuoteRef)194 /** The wallet does not execute this route: comparison only. */195 case comparisonOnly(code: String?)196 case expired197 /** Executable, but the served fingerprint does not match the served figures: nothing to refer to, nothing is prepared. */198 case unverifiableQuote199 var reference: QuoteRef? { if case .ready(let q) = self { q } else { nil } }200 }201202 static let useCCTPTool = "use_cctp_tool"203204 static func preparability(_ r: SwapRoute, now: Date) -> Preparability {205 guard r.executable, let executor = r.statedExecutor else { return .comparisonOnly(code: r.executability?.code ?? r.card?.reasonCode) }206 // a CCTP route of the stream is quoted with the swap tolerance, not as the option that is executed: it is prepared from207 // the USDC tool with the reference of its own /bridge/quote option, never from here208 if executor == "cctp" { return .comparisonOnly(code: useCCTPTool) }209 guard let f = freshness(of: r, now: now) else { return .unverifiableQuote }210 if f.isExpired { return .expired }211 guard let q = r.quoteReference else { return .unverifiableQuote }212 return .ready(q)213 }214215 /** The route to HIGHLIGHT (never to select or execute): the first one, in display order, that could be prepared now. */216 static func bestPreparable(_ ordered: [SwapRoute], executor: String? = nil, now: Date) -> SwapRoute? {217 ordered.first { (executor == nil || $0.statedExecutor == executor) && preparability($0, now: now).reference != nil }218 }219220 /** The route the owner picked, only while it is still among the routes of the CURRENT search. */221 static func selection(_ id: String?, in routes: [SwapRoute]) -> SwapRoute? { id.flatMap { id in routes.first { $0.id == id } } }222223 // MARK: preparation outcome224225 enum PrepareFailure: Equatable {226 /** The server answered without the canonical object: the Core refuses to bind a passkey to something it cannot recompute. */227 case serverLacksIntent228 /** The Core refused what the server prepared (it differs from the request, or cannot be verified). */229 case refusedByApp230 /** `409 quote_moved`: nothing was prepared. */231 case quoteMoved232 /** The server refused (limits, pending transaction, no route…): nothing was prepared. */233 case refusedByServer234 case offline235 case other236 }237238 /** The exact text of `ApprovalError.unsupported` when a preparation answer carries no intent (SwapApproval.swift, `notReturned`). */239 static let missingIntentReason = "the server did not return the object to approve"240241 static func classify(_ error: Error) -> PrepareFailure {242 if error is QuoteMoved { return .quoteMoved }243 if let a = error as? ApprovalError {244 if case .unsupported(let why) = a, why == missingIntentReason { return .serverLacksIntent }245 return .refusedByApp246 }247 if let e = error as? APIError { return e.isOffline ? .offline : e.code == "quote_moved" ? .quoteMoved : .refusedByServer }248 return .other249 }250251 /**252 True when the error was raised AFTER the server created a pending proposal (every verification refusal of the Core): that253 proposal will never be approved by this app and must be withdrawn so that nothing dangles.254 */255 static func leavesPendingProposal(_ error: Error) -> Bool { error is ApprovalError }256257 static let missingIntentTitle = String(localized: "Approbation indisponible sur ce serveur")258 static let missingIntentMessage = String(localized: "Ce serveur n’a pas fourni l’objet à vérifier pour cette opération (version antérieure du serveur) ; l’app refuse d’approuver à l’aveugle. Rien n’a été signé.")259260 static func sameAssetId(_ a: String, _ b: String) -> Bool {261 a == b || (a.hasPrefix("0x") && b.hasPrefix("0x") && a.lowercased() == b.lowercased())262 }263264 /**265 The pending proposal(s) a refused preparation left on the server: same kind, network, asset and amount, still waiting for an266 approval, created around the request. Used only to withdraw them.267 */268 static func leftBehind(in pending: [Proposal], kind: String, network: String, asset: String, amountUnits: String?, since: Date, tolerance: TimeInterval = 120) -> [Proposal] {269 pending.filter { p in270 guard p.kind == kind, p.state == .pendingApproval, p.network == network, sameAssetId(p.asset, asset) else { return false }271 if let amountUnits, p.amount != amountUnits { return false }272 guard let created = p.createdAt else { return false }273 return created >= since.addingTimeInterval(-tolerance)274 }275 }276277 // MARK: completion (a broadcast is never a success)278279 struct Outcome: Equatable {280 let completion: OperationCompletion?281 /** Set when the proposal's own section could not be read: shown as such, never replaced by a guess. */282 let unreadable: Bool283 var isComplete: Bool { completion == .complete }284 /** Nothing more will happen by itself (complete, refunded or failed). */285 var isSettled: Bool { completion == .complete || completion == .refunded || completion == .failed }286 }287288 static func outcome(of p: Proposal) -> Outcome {289 do { return Outcome(completion: try p.swapCompletion(), unreadable: false) } catch { return Outcome(completion: nil, unreadable: true) }290 }291292 static func label(_ c: OperationCompletion?, kind: String?) -> (text: String, tone: Tone, symbol: String) {293 switch c {294 case .complete?:295 switch kind {296 case "bridge": (String(localized: "Terminé : USDC reçus sur le réseau de destination"), .ok, "checkmark.circle.fill")297 case "xswap": (String(localized: "Terminé : sortie reçue sur le réseau de destination"), .ok, "checkmark.circle.fill")298 default: (String(localized: "Échange confirmé par le réseau"), .ok, "checkmark.circle.fill")299 }300 case .refunded?: (String(localized: "Remboursé : l’échange n’a pas eu lieu"), .warn, "arrow.uturn.backward.circle.fill")301 case .failed?: (String(localized: "Échoué ou abandonné"), .danger, "xmark.octagon.fill")302 case .inProgress?: (String(localized: "En cours — pas encore terminé"), .info, "clock.arrow.2.circlepath")303 case .notStarted?: (String(localized: "Pas encore approuvé"), .neutral, "circle.dashed")304 case nil: (String(localized: "État illisible"), .warn, "questionmark.circle")305 }306 }307308 // MARK: review rows, derived from the verified intent309310 struct ReviewRow: Equatable {311 let label: String312 let value: String313 var mono = false314 var tuple: (String, String, Bool) { (label, value, mono) }315 }316317 static func assetDef(_ id: String, in network: Network?) -> AssetDef? {318 guard let network else { return nil }319 return id == "native" ? network.native : network.tokens.first { sameAssetId($0.id, id) }320 }321322 private static func amount(_ units: String, _ def: AssetDef?) -> String? {323 guard let def, let u = try? BaseUnits(units) else { return nil }324 return Money.exact(u.formatted(decimals: def.decimals)) + " " + def.symbol325 }326327 private static func approvalRow(approveGas: String, intent i: Intent, spender: String) -> ReviewRow {328 let needs = approveGas != "0"329 let exact = Money.exact(i.amountUnits.formatted(decimals: i.decimals)) + " " + i.symbol330 return ReviewRow(label: String(localized: "Transaction d’approbation du jeton avant l’opération"),331 value: needs ? String(localized: "Oui : une première transaction autorise \(spender) à prélever exactement \(exact), pas davantage. Elle est couverte par cette même approbation.")332 : String(localized: "Non : aucune autorisation de jeton n’est émise."))333 }334335 /** Same-network swap: what is received (symbol from the registry), the exact guaranteed minimum, the approval pre-transaction. */336 static func swapRows(_ i: Intent, network: Network?) -> [ReviewRow] {337 guard let s = i.swap else { return [] }338 let def = assetDef(s.toAsset, in: network)339 return [340 ReviewRow(label: String(localized: "Actif reçu"), value: def.map { "\($0.symbol) — \($0.name)" } ?? String(localized: "Absent du registre de l’app : vérifie le contrat indiqué plus bas")),341 ReviewRow(label: String(localized: "Minimum reçu garanti"), value: amount(s.minOut, def) ?? String(localized: "Non formatable (actif inconnu) : voir les unités de base plus bas")),342 approvalRow(approveGas: s.approveGas, intent: i, spender: String(localized: "au routeur")),343 ]344 }345346 /** CCTP transfer: destination network and own address there, Circle's fee ceiling, the minimum received (amount − ceiling), speed. */347 static func bridgeRows(_ i: Intent, networks: [Network]) -> [ReviewRow] {348 guard let b = i.bridge else { return [] }349 let to = networks.first { $0.id == b.toNetwork }350 let fee = (try? BaseUnits(b.maxFee)) ?? .zero351 var rows = [352 ReviewRow(label: String(localized: "Réseau de destination"), value: to?.name ?? b.toNetwork),353 ReviewRow(label: String(localized: "Livré à ton adresse sur \(to?.name ?? b.toNetwork)"), value: b.recipient ?? i.to, mono: true),354 ReviewRow(label: String(localized: "Frais du pont (Circle), plafond"), value: Money.exact(fee.formatted(decimals: i.decimals)) + " " + i.symbol),355 ]356 if let min = try? i.amountUnits.subtracting(fee) {357 rows.append(ReviewRow(label: String(localized: "Minimum reçu sur la destination"), value: Money.exact(min.formatted(decimals: i.decimals)) + " " + i.symbol))358 }359 let speed: String = switch b.minFinalityThreshold {360 case 1000: String(localized: "Rapide (seuil de finalité 1000)")361 case 2000: String(localized: "Standard (seuil de finalité 2000)")362 default: String(localized: "Seuil de finalité \(b.minFinalityThreshold)")363 }364 rows.append(ReviewRow(label: String(localized: "Vitesse"), value: speed))365 rows.append(approvalRow(approveGas: b.approveGas, intent: i, spender: String(localized: "au contrat de pont")))366 return rows367 }368369 /** THORChain swap: vault, memo and expiry are in the raw rows of `IntentReview`; here the human reading of what arrives. */370 static func xswapRows(_ i: Intent, networks: [Network]) -> [ReviewRow] {371 guard let x = i.xswap else { return [] }372 let to = networks.first { $0.id == x.toNetwork }373 let def = assetDef(x.toAsset, in: to)374 var rows = [375 ReviewRow(label: String(localized: "Actif reçu"), value: def.map { "\($0.symbol) — \($0.name) (\(to?.name ?? x.toNetwork))" } ?? String(localized: "Absent du registre de l’app : vérifie l’identifiant indiqué plus bas")),376 ReviewRow(label: String(localized: "Minimum reçu garanti"), value: amount(x.minOut, def) ?? String(localized: "Non formatable (actif inconnu) : voir les unités de base plus bas")),377 ReviewRow(label: String(localized: "Coffre THORChain (clé publique)"), value: x.vaultPubKey, mono: true),378 ReviewRow(label: String(localized: "Limite inscrite dans le mémo (unités THORChain, 8 décimales)"), value: x.limit, mono: true),379 ReviewRow(label: String(localized: "Le coffre n’est plus valable après"), value: Date(timeIntervalSince1970: TimeInterval(x.expiry)).formatted(date: .abbreviated, time: .standard)),380 ]381 if !x.router.isEmpty { rows.append(ReviewRow(label: String(localized: "Routeur THORChain appelé"), value: x.router, mono: true)) }382 rows.append(approvalRow(approveGas: x.approveGas, intent: i, spender: String(localized: "au routeur THORChain")))383 return rows384 }385386 static func reviewRows(_ i: Intent, networks: [Network]) -> [ReviewRow] {387 switch i.kind {388 case .swap: swapRows(i, network: networks.first { $0.id == i.network })389 case .bridge: bridgeRows(i, networks: networks)390 case .xswap: xswapRows(i, networks: networks)391 default: []392 }393 }394395 // MARK: small formatters396397 static func duration(_ seconds: Double?) -> String {398 guard let s = seconds else { return String(localized: "durée non indiquée") }399 if s < 90 { return "\(max(1, Int(s.rounded()))) s" }400 if s < 5400 { return "\(Int((s / 60).rounded())) min" }401 return (s / 3600).formatted(.number.precision(.fractionLength(1))) + " h"402 }403404 static func percent(bps: Double) -> String { (abs(bps) / 100).formatted(.number.precision(.fractionLength(2))) + " %" }405406 /** Display name of a provider id from /swap/providers; Jupiter's licence requires its "Metis" label wherever its route is shown. */407 static func providerName(_ id: String, in providers: SwapProviders?) -> String {408 providers?.providers.first { $0.id == id }?.name ?? (id == "jupiter" ? "Jupiter (Metis)" : id)409 }410}411