Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/TradingAgents/AgentVaultView.swift10// Description : The vault of a spot agent: its address and real on-chain11// balances, funding it (an ordinary wallet transfer to the12// vault address, through the same verified transfer approval13// as Send), bringing a whole balance back to the owner's own14// address (the only destination the signer signs for a15// vault), the funds the same address holds on other16// networks, and the honest tracking of each return until the17// chain confirms it.18// Module : Features19// Repository : https://git.spboucher.ai/sp-wallet-macos20// Created : 2026-11-1821// Last Modified : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author : Simon-Pierre Boucher28// Position : Professor of Finance29// Institution : Université du Québec en Outaouais (UQO)30// Department : Département des sciences administratives31// Organization : SP Boucher32//33// Website : https://spboucher.ai34// Git : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General : info@spboucher.ai41// Professional : contact@spboucher.ai42// Direct : simon@spboucher.ai43// Research : research@spboucher.ai44// Development : dev@spboucher.ai45// Support : support@spboucher.ai46// Security/Admin : admin@spboucher.ai47// Notifications : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification : Public74// Distribution : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License : None specified (no license file in this repository)88// Maintainer : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import SPWalletCore9798struct AgentVaultSection: View {99 let model: AppModel100 let d: AgentDetailStore101 @State private var fund: SendFlow?102 @State private var gas: AgentNetworks.Network?103 @State private var pendingReturn: PendingReturn?104105 struct PendingReturn: Identifiable { let id = UUID(); let asset: String; let symbol: String; let amount: String; let network: String?; let networkName: String }106107 var body: some View {108 if case .spot(let s)? = d.detail {109 let a = s.agent110 Card("Coffre de l’agent", trailing: AnyView(ProvenanceTag(p: s.vault == nil ? .unavailable : .verified))) {111 Field(label: "Adresse du coffre", value: a.vaultAddress, mono: true)112 Text(Fmt.chunked(a.vaultAddress)).font(.system(.callout, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled)113 HStack { Field(label: "Réseau", value: "\(a.networkName ?? a.network)\(a.vaultIndex.map { " · coffre n° \($0)" } ?? "")"); Button("Copier l’adresse") { copyToPasteboard(a.vaultAddress) } }114 Banner(.info, "Le coffre contient de l’argent RÉEL, quel que soit le mode de l’agent. Sa clé est chez le signataire isolé : sans mandat elle ne peut que renvoyer les fonds à votre propre adresse. N’envoyez au coffre que sur le réseau \(a.networkName ?? a.network).")115 Divider()116 if let v = s.vault {117 if v.isEmpty { Text("Le coffre ne détient rien sur ce réseau.").foregroundStyle(.secondary) }118 ForEach(v) { b in119 HStack(spacing: 10) {120 VaultBalanceRow(balance: b)121 Button("Rapatrier…") { pendingReturn = PendingReturn(asset: b.asset, symbol: b.assetSymbol, amount: b.display, network: nil, networkName: a.networkName ?? a.network) }122 .disabled(!model.canOperate || d.busy != nil || b.units?.isZero != false || a.mode == .live)123 .help(a.mode == .live ? "Révoquez d’abord le mandat : le serveur refuse un retour tant que l’agent est en réel sur ce réseau." : "Renvoie TOUT le solde de cet actif à votre propre adresse.")124 }125 }126 if let g = gas?.gas { Text("Réserve de gaz requise avant un passage en réel : \(g.reserve) \(gas?.native ?? "") (≈ \(g.perOrder) par ordre).").font(.caption).foregroundStyle(.secondary) }127 if a.mode == .live { Text("Agent en réel : un retour vers vous exige d’abord la révocation du mandat (onglet Mandat et risques).").font(.caption).foregroundStyle(Theme.warning) }128 } else { Banner(.danger, "Soldes illisibles sur la chaîne pour l’instant. Ce n’est pas un coffre vide.") }129 if let n = d.notice { Banner(.info, n) }130 if let e = d.actionError { Banner(.danger, e) }131 }132 fundCard(a)133 returnsCard134 elsewhereCard(a)135 }136 }137138 // MARK: funding — the wallet's ordinary transfer, to the vault address139140 @ViewBuilder private func fundCard(_ a: Agent) -> some View {141 Card("Alimenter le coffre") {142 if let fund {143 if fund.step == .tracking {144 TrackingCard(flow: fund)145 Text("Le dépôt n’est acquis qu’à l’état « Finalisée ». Les soldes du coffre ci-dessus sont relus sur la chaîne.").font(.caption).foregroundStyle(.secondary)146 } else {147 @Bindable var fund = fund148 let net = model.network(a.network)149 Form {150 LabeledContent("Depuis") { Text(model.address(on: a.network) ?? "adresse inconnue").font(Theme.monoSmall).textSelection(.enabled) }151 LabeledContent("Vers (coffre)") { Text(a.vaultAddress).font(Theme.monoSmall).textSelection(.enabled) }152 LabeledContent("Réseau") { Text(net?.name ?? a.network) }153 Picker("Actif", selection: $fund.asset) {154 ForEach(fundable(a, net), id: \.id) { x in Text("\(x.symbol) — \(x.role)").tag(x.id) }155 }156 LabeledContent("Solde disponible du portefeuille") {157 if let b = fund.balance, b.isAvailable { Text("\(Fmt.amount(b.display)) \(b.symbol)").monospacedDigit() } else { Text("Indisponible").foregroundStyle(Theme.negative) }158 }159 HStack { TextField("Montant", text: $fund.amount, prompt: Text("0.0")); Text(fund.assetDef?.symbol ?? "").foregroundStyle(.secondary) }160 }.formStyle(.grouped).scrollDisabled(true).disabled(fund.step != .form)161 if net == nil { Banner(.danger, "Le réseau \(a.network) n’est pas dans le registre de ce portefeuille : le dépôt ne peut pas être préparé ici.") }162 if let e = fund.error { Banner(.danger, e) }163 HStack {164 if let p = fund.formProblem, !fund.amount.isEmpty { Text(p).font(.callout).foregroundStyle(.secondary) }165 Spacer()166 if fund.step == .preparing { ProgressView().controlSize(.small); Text("Validation, simulation et calcul des frais…").font(.callout).foregroundStyle(.secondary) }167 Button("Préparer et vérifier le dépôt…") { Task { await fund.prepare() } }.buttonStyle(.borderedProminent).disabled(fund.formProblem != nil || !model.canOperate || fund.step != .form || net == nil)168 }169 Text("C’est un transfert ordinaire de votre portefeuille vers l’adresse du coffre, approuvé par votre passkey sur l’écran suivant. Déposer n’autorise aucun échange : seul un mandat le peut. Ce que vous déposez devient le budget que l’agent pourra engager s’il reçoit un mandat.").font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)170 }171 } else { ProgressView() }172 }173 .task {174 if fund == nil { let f = SendFlow(model: model); f.network = a.network; f.asset = a.holdings?.first(where: \.isCash)?.asset ?? "native"; f.to = a.vaultAddress; fund = f }175 if gas == nil { gas = try? await d.api.networks().networks.first { $0.id == a.network } }176 }177 .onChange(of: fund?.step) { old, new in178 // a new deposit always targets this vault; a finished one refreshes the balances read on-chain179 if new == .form, let f = fund { f.network = a.network; f.to = a.vaultAddress }180 if old == .approving || new == .tracking { Task { await d.refresh() } }181 }182 .onChange(of: fund?.tracked?.state) { _, s in if s?.isTerminal == true { Task { await d.refresh() } } }183 .sheet(isPresented: Binding(get: { fund?.step == .review || fund?.step == .approving }, set: { _ in })) {184 if let fund, let ap = fund.approval { FundReviewSheet(model: model, flow: fund, approval: ap, agent: a) }185 }186 }187188 private func fundable(_ a: Agent, _ net: SPWalletCore.Network?) -> [(id: String, symbol: String, role: String)] {189 var out: [(String, String, String)] = []190 for h in a.holdings ?? [] where net?.asset(h.asset) != nil { out.append((h.asset, h.assetSymbol, h.isCash ? "monnaie de règlement" : "actif négocié")) }191 if !out.contains(where: { $0.0 == "native" }), let n = net { out.append(("native", n.native.symbol, "gaz (frais de transaction du coffre)")) }192 return out193 }194195 // MARK: returns to the owner196197 @ViewBuilder private var returnsCard: some View {198 Card("Retours vers votre adresse") {199 if let r = d.returns {200 if r.broadcast == false { Banner(.warning, "Ce serveur signe mais ne diffuse pas les transactions : un retour s’y termine « signé, NON diffusé » et rien ne bouge sur la chaîne.") }201 if r.withdrawals.isEmpty { Text("Aucun retour demandé.").foregroundStyle(.secondary) }202 ForEach(r.withdrawals) { w in203 VStack(alignment: .leading, spacing: 4) {204 HStack(spacing: 8) {205 Group {206 if w.isSettled { Image(systemName: "checkmark.circle.fill").foregroundStyle(Theme.positive) }207 else if w.state == .failed || w.state == .notSent { Image(systemName: "xmark.octagon.fill").foregroundStyle(Theme.negative) }208 else if w.state.isOpen { ProgressView().controlSize(.small) }209 else { Image(systemName: "questionmark.circle").foregroundStyle(Theme.warning) }210 }211 Text("\(Fmt.amount(w.amount, maxFraction: 8)) \(w.symbol)").fontWeight(.medium).monospacedDigit()212 Text(AgentText.returnState(w.state) + (w.state == .confirmed && !w.arrived ? " — paiement vers vous NON vu dans la transaction" : w.isSettled ? " — reçu à votre adresse" : "")).foregroundStyle(w.isSettled ? Theme.positive : w.state.isOpen ? Theme.warning : Theme.negative)213 Spacer()214 Text(Fmt.date(w.createdAt)).font(.caption).foregroundStyle(.secondary)215 }216 if let n = w.network { Text("Réseau : \(model.network(n)?.name ?? n)").font(.caption).foregroundStyle(.secondary) }217 if let tx = w.txid { Text(tx).font(.system(.caption, design: .monospaced)).foregroundStyle(.secondary).textSelection(.enabled) }218 if let e = w.error { Text(e).font(.caption).foregroundStyle(Theme.negative).textSelection(.enabled) }219 if let url = AgentText.https(w.explorer) { Link("Ouvrir dans l’explorateur de blocs", destination: url).font(.caption) }220 }221 Divider()222 }223 Text("« Diffusé » n’est pas « confirmé » : un retour n’est acquis que lorsque la chaîne l’a confirmé ET que le paiement vers votre adresse y a été vu.").font(.caption).foregroundStyle(.secondary)224 } else { Unavailable(what: "Retours", error: d.error("returns")) }225 }226 .confirmationDialog("Rapatrier \(pendingReturn.map { "\(Fmt.amount($0.amount, maxFraction: 8)) \($0.symbol)" } ?? "") ?", isPresented: Binding(get: { pendingReturn != nil }, set: { if !$0 { pendingReturn = nil } }), titleVisibility: .visible, presenting: pendingReturn) { p in227 Button("Rapatrier tout le solde vers mon adresse") { Task { await d.returnToOwner(asset: p.asset, network: p.network) } }228 Button("Annuler", role: .cancel) {}229 } message: { p in230 Text("TOUT le solde de \(p.symbol) du coffre sur \(p.networkName) est envoyé à votre propre adresse de ce portefeuille (\(model.address(on: p.network ?? d.agent?.network ?? "") ?? "déterminée par le signataire")). Il n’y a ni montant ni destination à choisir : le signataire ne signe un paiement de coffre que vers son propriétaire. Aucune passkey n’est demandée. Les frais de réseau sont payés par le gaz du coffre.")231 }232 }233234 // MARK: funds on other networks235236 @ViewBuilder private func elsewhereCard(_ a: Agent) -> some View {237 Card("Fonds sur d’autres réseaux (même adresse)") {238 if let e = d.elsewhere {239 if e.holdings.isEmpty { Text("Rien n’a été trouvé à l’adresse du coffre sur les autres réseaux EVM consultés.").foregroundStyle(.secondary) }240 else {241 Banner(.warning, "Des fonds ont été envoyés à l’adresse du coffre sur un autre réseau que celui de l’agent. L’agent ne peut pas les négocier ; vous pouvez les rapatrier vers votre adresse.")242 ForEach(e.holdings) { h in243 HStack(spacing: 10) {244 AssetBadge(symbol: h.symbol, size: 26)245 VStack(alignment: .leading, spacing: 1) {246 Text("\(Fmt.amount(h.display, maxFraction: 8)) \(h.symbol) — \(h.networkName)").fontWeight(.medium)247 Text(h.gasEnough == false || !h.hasGas ? "Gaz insuffisant sur ce réseau : \(h.gasHeld ?? "0") \(h.gas) détenus\(h.gasNeed.map { ", environ \($0) requis" } ?? ""). Envoyez d’abord un peu de \(h.gas) à l’adresse du coffre sur ce réseau." : "Gaz : \(h.gasHeld ?? "?") \(h.gas)\(h.gasNeed.map { " (besoin ≈ \($0))" } ?? "")")248 .font(.caption).foregroundStyle(h.gasEnough == false || !h.hasGas ? Theme.warning : .secondary).fixedSize(horizontal: false, vertical: true)249 }250 Spacer()251 Button("Rapatrier…") { pendingReturn = PendingReturn(asset: h.asset, symbol: h.symbol, amount: h.display, network: h.network, networkName: h.networkName) }252 .disabled(!model.canOperate || d.busy != nil || (h.asset != "native" && (h.gasEnough == false || !h.hasGas)))253 }254 }255 }256 } else { Unavailable(what: "Lecture des autres réseaux", error: d.error("elsewhere")) }257 }258 }259}260261/// The review of a vault deposit: the verified transfer intent, with the destination identified as the agent's vault.262struct FundReviewSheet: View {263 let model: AppModel264 let flow: SendFlow265 let approval: TransferApproval266 let agent: Agent267268 var body: some View {269 let isVault = approval.intent.to.lowercased() == agent.vaultAddress.lowercased()270 SheetScaffold(title: "Vérifier et approuver le dépôt au coffre", width: 720, height: 780) {271 if isVault { Banner(.info, "Destination vérifiée : c’est l’adresse du coffre de l’agent « \(agent.name) ». Les fonds déposés ne reviennent que par « Rapatrier » (vers votre adresse).") }272 else { Banner(.danger, "La destination de l’intention n’est PAS l’adresse du coffre de cet agent. N’approuvez pas.") }273 TransactionReview(intent: approval.intent, digest: approval.approval.digest, network: model.network(approval.intent.network),274 ownAddresses: Dictionary((model.accounts?.value.accounts ?? []).map { ($0.network, $0.address) }, uniquingKeysWith: { a, _ in a }),275 warnings: approval.proposal.warnings ?? [],276 extra: [ReviewLine(label: "Coffre de l’agent", value: "\(agent.name) — \(agent.vaultAddress)", style: .address)]277 + (approval.proposal.feeDisplay.map { [ReviewLine(label: "Frais estimés", value: "\($0) \(approval.proposal.feeSymbol ?? "") (estimation ; le plafond ci-dessus est ce qui est signé)")] } ?? []))278 } footer: {279 if let e = flow.error { Banner(.danger, e) }280 HStack {281 Button("Rejeter", role: .destructive) { Task { await flow.reject() } }.disabled(flow.step == .approving)282 Spacer()283 if flow.step == .approving { ProgressView().controlSize(.small); Text("Passkey, puis signature isolée…").foregroundStyle(.secondary) }284 Button { Task { await flow.approve() } } label: { Label("Approuver avec la passkey", systemImage: "touchid") }285 .buttonStyle(.borderedProminent).controlSize(.large).disabled(flow.step == .approving || !isVault)286 }287 }288 .interactiveDismissDisabled()289 }290}291