Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/DeFi/DeFiView.swift3// Description: The DeFi hub, honest about what this wallet's backend integrates: DEX swap aggregation, Circle CCTP bridging, THORChain native swaps and multi-leg plans — and nothing else (no lending, staking, liquidity provision or dApp connection). The "connected protocols" table is built only from the server's own provider and capability endpoints: for each provider what it does, where, whether this wallet EXECUTES through it or only compares its quotes, and whether it needs a key the server has.4import SwiftUI5import SPWalletCore67/// One answer of a capability endpoint: fresh, or the last one kept on this Mac with its date, or unavailable with the reason.8struct HubAnswer<T: Codable & Sendable>: Sendable {9 var value: T?10 var at: Date?11 var cached = false12 var error: String?13}1415@MainActor @Observable final class DeFiHub {16 let model: AppModel17 private(set) var providers = HubAnswer<SwapProviders>()18 private(set) var swap = HubAnswer<SwapExecutionInfo>()19 private(set) var bridge = HubAnswer<BridgeExecutionInfo>()20 private(set) var xswap = HubAnswer<XSwapExecutionInfo>()21 private(set) var plans = HubAnswer<PlanCapabilities>()22 private(set) var stats = HubAnswer<SwapStats>()23 private(set) var loading = false24 private(set) var loadedOnce = false2526 init(model: AppModel) { self.model = model }2728 private func fetch<T: Codable & Sendable>(_ key: String, _ call: @Sendable () async throws -> T) async -> HubAnswer<T> {29 if model.phase == .signedIn {30 do {31 let v = try await call()32 await SnapshotStore.shared.save(v, as: "defi.\(key)")33 return HubAnswer(value: v, at: Date(), cached: false, error: nil)34 } catch {35 let old: Snapshot<T>? = await SnapshotStore.shared.load("defi.\(key)")36 return HubAnswer(value: old?.value, at: old?.savedAt, cached: old != nil, error: model.describe(error))37 }38 }39 let old: Snapshot<T>? = await SnapshotStore.shared.load("defi.\(key)")40 return HubAnswer(value: old?.value, at: old?.savedAt, cached: old != nil, error: old == nil ? "Jamais synchronisé sur ce Mac." : nil)41 }4243 func load() async {44 guard !loading else { return }45 loading = true; defer { loading = false; loadedOnce = true }46 let c = model.client47 async let a = fetch("providers") { try await SwapAPI(c).providers() }48 async let b = fetch("swap-execution") { try await SwapAPI(c).execution() }49 async let d = fetch("bridge-execution") { try await BridgeAPI(c).execution() }50 async let e = fetch("xswap-execution") { try await XSwapAPI(c).execution() }51 async let f = fetch("plan-capabilities") { try await PlanAPI(c).capabilities() }52 async let g = fetch("swap-stats") { try await SwapAPI(c).stats() }53 (providers, swap, bridge, xswap, plans, stats) = await (a, b, d, e, f, g)54 }5556 struct Row: Identifiable {57 let id: String58 let name: String59 let does: String60 let networks: String61 let executes: Bool62 let execution: String63 let key: String64 let health: String65 let healthy: Bool66 let stats: String67 }6869 private func names(_ ids: [String]) -> String { ids.map { model.network($0)?.name ?? $0 }.joined(separator: ", ") }7071 /// One row per provider the server lists. "Executes" is the server's statement (`executors`), scoped by its execution endpoints.72 var rows: [Row] {73 guard let p = providers.value else { return [] }74 return p.providers.map { info in75 let cap = info.capabilities76 let does = (cap?.kinds ?? []).map { k -> String in77 switch k { case "swap": "Agrégation d’échanges (DEX)"; case "bridge": "Pont inter-chaînes"; case "native_swap": "Échange natif inter-chaînes"; default: k }78 }.joined(separator: " + ")79 let executes = p.isExecutor(info.id)80 let st = stats.value?.providers.first { $0.provider == info.id }81 let key: String = switch (cap?.needsKey, cap?.configured) {82 case (true?, true?): "Clé requise — configurée"83 case (true?, _): "Clé requise — NON configurée : jamais interrogé"84 case (false?, _): "Aucune clé requise"85 default: "Non indiqué"86 }87 let breaker: String = switch info.state { case "closed"?: "opérationnel"; case "open"?: "coupé (trop d’échecs)"; case "half_open"?: "en reprise"; case let s?: s; case nil: "état non indiqué" }88 return Row(id: info.id, name: SwapText.provider(info.id, providers: p, execution: swap.value),89 does: does.isEmpty ? "Non indiqué" : does,90 networks: cap.map { "\($0.networks.count) : \(names($0.networks))" + ($0.crossChain ? " (inter-chaînes)" : "") } ?? "Non indiqué",91 executes: executes, execution: executes ? scope(info.id) : "Cotation seulement — sert à comparer les prix",92 key: key, health: info.enabled ? breaker : "désactivé sur le serveur", healthy: info.enabled && info.state != "open",93 stats: st.map { "\($0.calls ?? 0) appels · \($0.ok ?? 0) réussis · \($0.quotes ?? 0) cotations" + ($0.p50.map { " · médiane \(Int($0)) ms" } ?? "") } ?? "—")94 }95 }9697 /// Where an executor really executes, from the matching execution endpoint; unknown when that endpoint could not be read.98 private func scope(_ id: String) -> String {99 if let s = swap.value {100 if s.provider == id { return s.enabled ? "Exécutable : échanges sur \(names(s.networks))" : "Exécuteur désactivé par le serveur" }101 if let sol = s.solana, sol.provider == id { return s.enabled ? "Exécutable : échanges sur \(names(sol.networks))" : "Exécuteur désactivé par le serveur" }102 }103 if let b = bridge.value, b.provider == id { return b.enabled ? "Exécutable : \(b.asset) entre \(names(b.networks))" : "Exécuteur désactivé par le serveur" }104 if let x = xswap.value, x.provider == id { return x.enabled ? "Exécutable : \(x.assets.count) actifs natifs (voir ci-dessous)" : "Exécuteur désactivé par le serveur" }105 return "Exécuteur déclaré par le serveur — périmètre illisible pour l’instant"106 }107}108109struct DeFiView: View {110 let model: AppModel111 let nav: Navigator112 @State private var hub: DeFiHub?113114 var body: some View {115 Page("DeFi", subtitle: "Ce que ce portefeuille sait réellement faire en finance décentralisée — d’après les capacités déclarées par son serveur, rien de plus.") {116 Banner(.info, "Ici, « DeFi » signifie : agrégation d’échanges sur DEX, pont USDC par Circle CCTP, échanges natifs inter-chaînes par THORChain, et parcours en plusieurs étapes qui les enchaînent. Aucun protocole de prêt, de staking ou de fourniture de liquidité n’est intégré.")117 if !model.canOperate { Banner(.warning, "Session ou portefeuille indisponible : les capacités affichées peuvent être les dernières synchronisées, et aucune opération n’est possible.") }118 if SwapText.isSimulatedServer(model) { Banner(.warning, "SERVEUR DE TEST : les transactions sont signées mais ne sont PAS diffusées.") }119 if let hub {120 ProtocolsCard(model: model, hub: hub)121 CapabilitiesCard(model: model, hub: hub, nav: nav)122 } else { ProgressView() }123 PlanPanel(model: model)124 unavailable125 }126 .task {127 if hub == nil { hub = DeFiHub(model: model) }128 await hub?.load()129 }130 }131132 private var unavailable: some View {133 Card("Ce qui n’est PAS disponible") {134 ForEach([135 ("Prêt et emprunt", "Aucune intégration de protocole de prêt (Aave, Compound, Morpho…). Aucun rendement n’est proposé ni affiché."),136 ("Staking et staking liquide", "Aucune délégation, aucun jeton de staking liquide. Le portefeuille ne met rien en jeu."),137 ("Fourniture de liquidité", "Aucun dépôt dans des pools (Uniswap, Curve…) : le portefeuille échange à travers les DEX, il ne leur fournit pas de liquidité."),138 ("Connexion à des dApps", "Pas de WalletConnect ni de navigateur de dApps : le signataire ne signe que des opérations qu’il reconstruit et vérifie lui-même, jamais une transaction arbitraire présentée par un site."),139 ], id: \.0) { item in140 HStack(alignment: .top, spacing: 10) {141 Image(systemName: "minus.circle").foregroundStyle(.secondary)142 VStack(alignment: .leading, spacing: 1) { Text(item.0).fontWeight(.medium); Text(item.1).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }143 }144 }145 HStack {146 Text("Les dérivés (contrats à terme perpétuels) ont leur propre écran.").font(.callout).foregroundStyle(.secondary)147 Button("Ouvrir « Contrats à terme »") { nav.section = .futures }.buttonStyle(.link)148 }149 }150 }151}152153// MARK: - Connected protocols154155private struct ProtocolsCard: View {156 let model: AppModel157 let hub: DeFiHub158159 var body: some View {160 let rows = hub.rows161 Card("Protocoles connectés", trailing: AnyView(HStack(spacing: 8) {162 if hub.loading { ProgressView().controlSize(.small) }163 if let at = hub.providers.at { ProvenanceTag(p: hub.providers.cached ? .stale : .verified, text: hub.providers.cached ? "Liste du \(Fmt.date(at))" : "Lu sur le serveur \(Fmt.relative(at))") }164 Button("Relire") { Task { await hub.load() } }.controlSize(.small).disabled(hub.loading)165 })) {166 if let e = hub.providers.error { Banner(hub.providers.value == nil ? .danger : .warning, "Liste des fournisseurs : \(e)") }167 if let p = hub.providers.value {168 if !p.executionEnabled { Banner(.danger, "Le serveur déclare l’exécution des échanges désactivée : tous les fournisseurs ci-dessous ne servent qu’à comparer.") }169 Text("« Exécutable » = ce portefeuille prépare, vérifie et signe lui-même l’opération à travers ce protocole (contrat revu, champs vérifiés par le signataire). Tous les autres fournisseurs ne font que coter : leurs prix servent de comparaison et ne peuvent pas être exécutés d’ici.")170 .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)171 Table(rows) {172 TableColumn("Protocole") { r in Text(r.name).fontWeight(.medium) }.width(min: 110, ideal: 140)173 TableColumn("Fonction") { r in Text(r.does) }.width(min: 150, ideal: 190)174 TableColumn("Exécution par ce portefeuille") { r in175 Label(r.execution, systemImage: r.executes ? "checkmark.seal.fill" : "eye").foregroundStyle(r.executes ? Theme.positive : .secondary).help(r.execution)176 }.width(min: 230, ideal: 320)177 TableColumn("Clé d’API") { r in Text(r.key).foregroundStyle(r.key.contains("NON") ? Theme.warning : .primary) }.width(min: 140, ideal: 190)178 TableColumn("État") { r in Text(r.health).foregroundStyle(r.healthy ? Color.primary : Theme.warning) }.width(min: 100, ideal: 130)179 TableColumn("7 derniers jours") { r in Text(r.stats).foregroundStyle(.secondary).monospacedDigit().help(r.stats) }.width(min: 160, ideal: 240)180 }181 .frame(height: CGFloat(max(rows.count, 1)) * 28 + 36)182 VStack(alignment: .leading, spacing: 4) {183 Text("Réseaux couverts par fournisseur").font(.caption).foregroundStyle(.secondary)184 ForEach(rows) { r in Text("\(r.name) — \(r.networks)").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) }185 }186 if !p.needsKey.isEmpty { Text("Présents dans le code du serveur mais jamais interrogés faute de clé d’API : \(p.needsKey.joined(separator: ", ")).").font(.callout).foregroundStyle(Theme.warning) }187 if let e = hub.stats.error { Text("Statistiques indisponibles : \(e)").font(.caption).foregroundStyle(.secondary) }188 } else if hub.loadedOnce {189 EmptyState(symbol: "xmark.octagon", title: "Liste des protocoles indisponible", detail: "Le serveur n’a pas répondu et aucune copie n’existe sur ce Mac. Rien n’est supposé.")190 } else { ProgressView() }191 }192 }193}194195// MARK: - What is executable, endpoint by endpoint196197private struct CapabilitiesCard: View {198 let model: AppModel199 let hub: DeFiHub200 let nav: Navigator201202 private func names(_ ids: [String]) -> String { ids.isEmpty ? "aucun" : ids.map { model.network($0)?.name ?? $0 }.joined(separator: ", ") }203204 var body: some View {205 Card("Ce que ce portefeuille exécute lui-même") {206 section("Échanges sur un même réseau", hub.swap, link: ("Ouvrir « Échanger »", .swap)) { s in207 Field(label: "État", value: s.enabled ? "Activé" : "Désactivé par le serveur", emphasis: true)208 Field(label: "\(SwapText.provider(s.provider, providers: hub.providers.value)) (EVM)", value: names(s.networks))209 if let r = s.router { Field(label: "Routeur revu", value: r, mono: true) }210 if let sol = s.solana {211 Field(label: sol.label, value: names(sol.networks))212 if let p = sol.program { Field(label: "Programme Solana", value: p, mono: true) }213 }214 }215 Divider()216 section("Pont USDC — Circle CCTP", hub.bridge, link: ("Ouvrir « Pont inter-chaînes »", .bridge)) { b in217 Field(label: "État", value: b.enabled ? "Activé" : "Désactivé par le serveur", emphasis: true)218 Field(label: "Actif", value: b.asset)219 Field(label: "Réseaux", value: names(b.networks))220 if let m = b.messenger { Field(label: "TokenMessenger", value: m, mono: true) }221 if let t = b.transmitter { Field(label: "MessageTransmitter", value: t, mono: true) }222 }223 Divider()224 section("Échanges natifs inter-chaînes — THORChain", hub.xswap, link: ("Ouvrir « Échanger »", .swap)) { x in225 Field(label: "État", value: x.enabled ? "Activé" : "Désactivé par le serveur", emphasis: true)226 Field(label: "Actifs", value: x.assets.map { "\($0.symbol) sur \(model.network($0.network)?.name ?? $0.network)\($0.source ? "" : " (destination seulement)")" }.joined(separator: " · "))227 Field(label: "Sécurité du coffre", value: "Unanimité d’au moins \(x.minOperators.map(String.init) ?? "—") opérateurs THORNode indépendants ; sinon rien n’est préparé ni signé (échec fermé)." + ((x.operators ?? []).isEmpty ? "" : "\nOpérateurs : \((x.operators ?? []).map { $0.host ?? $0.id }.joined(separator: ", "))"))228 if let r = x.routers, !r.isEmpty { Field(label: "Routeurs revus", value: r.keys.sorted().map { "\(model.network($0)?.name ?? $0) : \(r[$0] ?? "")" }.joined(separator: "\n"), mono: true) }229 }230 Divider()231 section("Parcours multi-étapes", hub.plans, link: nil) { c in232 Field(label: "Étapes au maximum", value: String(c.maxLegs))233 Field(label: "Actif intermédiaire", value: c.hub)234 Field(label: "Échanges chaînables", value: c.swap.keys.sorted().map { "\(model.network($0)?.name ?? $0) (\(SwapText.provider(c.swap[$0] ?? "", providers: hub.providers.value, execution: hub.swap.value)))" }.joined(separator: ", "))235 Field(label: "Pont CCTP entre", value: names(c.cctp))236 Field(label: "THORChain", value: c.thorchain.map { "\($0.symbol) (\($0.networkName ?? $0.network))\($0.source == true ? "" : " — destination seulement")" }.joined(separator: " · "))237 }238 }239 }240241 @ViewBuilder private func section<T: Codable & Sendable, Content: View>(_ title: String, _ answer: HubAnswer<T>, link: (String, Section)?, @ViewBuilder content: (T) -> Content) -> some View {242 HStack {243 Text(title).font(.headline)244 if answer.cached, let at = answer.at { ProvenanceTag(p: .stale, text: "Copie du \(Fmt.date(at))") }245 Spacer()246 if let link { Button(link.0) { nav.section = link.1 }.buttonStyle(.link) }247 }248 if let v = answer.value {249 if let e = answer.error { Text("Lecture en échec (\(e)) — dernière copie affichée.").font(.caption).foregroundStyle(Theme.warning) }250 content(v)251 } else if let e = answer.error {252 HStack { ProvenanceTag(p: .unavailable); Text(e).font(.callout).foregroundStyle(.secondary) }253 } else { ProgressView().controlSize(.small) }254 }255}256