Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Wallet for macOS9// File : Features/Futures/FuturesApprovalSheet.swift10// Description : The review sheet shown before every passkey approval of11// the live derivatives path. It renders the fields OF THE12// VERIFIED OBJECT — the venue authorization, the venue13// order, the leverage change, the collateral deposit intent,14// the venue withdrawal or the risk intent whose SHA-256 the15// Core proved to be the WebAuthn challenge — never the16// server's summary of it, followed by the binding proof. The17// server's estimates are shown apart and labelled as18// estimates. Nothing is approved without the explicit19// button; closing the sheet withdraws the pending proposal.20// Module : Features21// Repository : https://git.spboucher.ai/sp-wallet-macos22// Created : 2026-11-1823// Last Modified : 2026-11-1824//25// =============================================================================26// AUTHOR & PROFESSIONAL AFFILIATION27// =============================================================================28//29// Author : Simon-Pierre Boucher30// Position : Professor of Finance31// Institution : Université du Québec en Outaouais (UQO)32// Department : Département des sciences administratives33// Organization : SP Boucher34//35// Website : https://spboucher.ai36// Git : https://git.spboucher.ai37//38// =============================================================================39// OFFICIAL CONTACT DIRECTORY40// =============================================================================41//42// General : info@spboucher.ai43// Professional : contact@spboucher.ai44// Direct : simon@spboucher.ai45// Research : research@spboucher.ai46// Development : dev@spboucher.ai47// Support : support@spboucher.ai48// Security/Admin : admin@spboucher.ai49// Notifications : notifications@spboucher.ai50//51// Preferred Contact: support@spboucher.ai52//53// =============================================================================54// COPYRIGHT & INTELLECTUAL PROPERTY55// =============================================================================56//57// Copyright (c) 202658// Simon-Pierre Boucher59//60// All rights reserved where applicable.61//62// This file is governed by the applicable project license,63// copyright notices, institutional agreements and relevant law.64//65// Unless expressly authorized by the applicable license or66// rights holder, copying, redistribution, sublicensing,67// publication and commercial exploitation are not permitted.68//69// Existing third-party rights and notices remain unaffected.70//71// =============================================================================72// CONFIDENTIALITY & SECURITY73// =============================================================================74//75// Classification : Public76// Distribution : Public repository; use is governed by the project license77// Security Contact : admin@spboucher.ai78//79// Access to this source does not independently grant permission80// to redistribute or disclose confidential materials.81//82// Do not embed credentials, private keys, access tokens,83// certificates or confidential personal information.84//85// =============================================================================86// LICENSE & MAINTENANCE87// =============================================================================88//89// License : None specified (no license file in this repository)90// Maintainer : Simon-Pierre Boucher91// Technical Contact: dev@spboucher.ai92//93// =============================================================================94// END OF SP BOUCHER SOURCE HEADER95// =============================================================================9697import SwiftUI98import SPWalletCore99100struct FutApprovalSheet: View {101 let model: AppModel102 let store: FuturesStore103 @Bindable var ops: FutLiveOps104 let sheet: FutLiveOps.Sheet105106 private var mode: FutMode { store.mode }107108 var body: some View {109 VStack(alignment: .leading, spacing: 0) {110 FutSheetHeader(title: title, mode: mode)111 Divider()112 ScrollView { VStack(alignment: .leading, spacing: 14) { content }.padding(20) }113 Divider()114 VStack(alignment: .leading, spacing: 8) {115 if let e = ops.sheetError { Banner(.danger, e) }116 if !model.canOperate { Banner(.warning, "Session ou portefeuille indisponible : l’approbation est désactivée.") }117 HStack {118 Button(closeTitle, role: .destructive) { Task { await ops.dismiss() } }.disabled(ops.approving)119 Spacer()120 if ops.approving { ProgressView().controlSize(.small); Text("Passkey, puis signataire isolé…").foregroundStyle(.secondary) }121 Button { Task { await ops.approve() } } label: { Label(approveTitle, systemImage: "touchid") }122 .buttonStyle(.borderedProminent).tint(mode.color).controlSize(.large)123 .disabled(ops.approving || !model.canOperate || needsAcknowledgement)124 }125 }.padding(16)126 }127 .frame(width: 740, height: 780)128 .interactiveDismissDisabled()129 }130131 private var needsAcknowledgement: Bool { if case .authorization = sheet { return !ops.acknowledged }; return false }132133 private var title: String {134 switch sheet {135 case .authorization: "Autoriser la clé de négociation"136 case .order(_, _, let close): close ? "Vérifier et approuver la clôture" : "Vérifier et approuver l’ordre"137 case .leverage: "Vérifier et approuver le changement de levier"138 case .deposit: "Vérifier et approuver le dépôt de collatéral"139 case .withdraw: "Vérifier et approuver le retrait de collatéral"140 case .risk(let r): r.intent.kind == .resume ? "Lever l’arrêt du compte" : r.intent.kind == .rebase ? "Accepter les positions de la plateforme" : "Assouplir les limites du compte"141 }142 }143 private var closeTitle: String {144 switch sheet {145 case .order: "Retirer la proposition"146 case .deposit, .withdraw: "Annuler l’opération"147 default: "Fermer sans approuver"148 }149 }150 private var approveTitle: String { "Approuver avec la passkey (\(mode.badge))" }151152 @ViewBuilder private var content: some View {153 switch sheet {154 case .authorization(let p): authorization(p)155 case .order(let p, let a, let close): order(p, a, close: close)156 case .leverage(let l): leverage(l)157 case .deposit(let d): deposit(d)158 case .withdraw(let w): withdraw(w)159 case .risk(let r): risk(r)160 }161 }162163 private static func date(seconds: Int) -> String { Fmt.dateSeconds(Date(timeIntervalSince1970: TimeInterval(seconds))) }164 private static func date(ms: Int) -> String { Fmt.dateSeconds(Date(timeIntervalSince1970: TimeInterval(ms) / 1000)) }165166 // MARK: venue authorization167168 @ViewBuilder private func authorization(_ p: LiveAuthorizationPreparation) -> some View {169 let x = p.authorization, pol = x.policy170 Banner(.warning, "Après cette approbation, la clé de négociation dédiée peut placer sur ce compte les ordres que vous approuverez un à un, dans les limites ci-dessous. Ces limites sont appliquées par le signataire isolé.")171 ReviewLines(lines: [172 .init(label: "Type d’opération", value: "Autorisation de négociation sur un compte de plateforme", style: .strong),173 .init(label: "Plateforme / réseau", value: "\(x.venue) · \(x.network)", style: .strong),174 .init(label: "Compte (votre adresse)", value: x.account, style: .address),175 .init(label: "Clé de négociation autorisée", value: x.agentAddress, style: .address),176 .init(label: "Nom de la clé", value: x.agentName),177 .init(label: "Mode accordé", value: x.mode),178 .init(label: "Instruments permis", value: pol.allowedInstruments.sorted().joined(separator: ", "), style: .strong),179 .init(label: "Levier maximal", value: "\(pol.maxLeverage)×", style: .strong),180 .init(label: "Notionnel max par ordre", value: "\(FutNum.exact(pol.maxOrderNotional)) $"),181 .init(label: "Notionnel max par position", value: "\(FutNum.exact(pol.maxPositionNotional)) $"),182 .init(label: "Exposition brute maximale", value: "\(FutNum.exact(pol.maxGrossExposure)) $"),183 .init(label: "Ordres par jour", value: String(pol.maxOrdersPerDay)),184 .init(label: "Écart de prix toléré", value: "\(pol.maxPriceDeviationBps) points de base"),185 .init(label: "Valide du", value: Self.date(seconds: x.createdAt)),186 .init(label: "Expire le", value: Self.date(seconds: x.expiresAt), style: .strong),187 .init(label: "Nonce de l’approbation", value: String(x.approveNonce)),188 .init(label: "Empreinte de l’avis lu", value: x.ackSha256),189 .init(label: "Identifiant", value: x.authorizationId),190 .init(label: "Clé du portefeuille", value: x.keyId),191 ])192 if let a = p.agent {193 if let can = a.can, !can.isEmpty { listBlock("Ce que la clé de négociation peut faire (selon le serveur)", can, color: Theme.warning) }194 if let cannot = a.cannot, !cannot.isEmpty { listBlock("Ce qu’elle ne peut pas faire", cannot, color: Theme.positive) }195 if let n = a.note { Text(n).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) }196 }197 if let w = p.whatIsSigned {198 if let m = w.byMainKey { Field(label: "Signé par la clé du portefeuille", value: m) }199 if let k = w.byPasskey { Field(label: "Signé par votre passkey", value: k) }200 }201 if let e = p.venueState?.error { Banner(.warning, "État du compte illisible sur la plateforme au moment de la préparation : \(e)") }202 VStack(alignment: .leading, spacing: 8) {203 Text("Avis de juridiction (\(p.acknowledgement.venue), \(p.acknowledgement.locale))").font(.headline)204 Text(p.acknowledgement.text).font(.callout).textSelection(.enabled).fixedSize(horizontal: false, vertical: true)205 Toggle("J’ai lu cet avis et je confirme que je peux utiliser cette plateforme. L’autorisation s’engage sur l’empreinte de ce texte.", isOn: $ops.acknowledged).toggleStyle(.checkbox)206 }.padding(10).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))207 BindingProof(digest: p.approval.digest, expiry: nil)208 }209210 private func listBlock(_ title: String, _ items: [String], color: Color) -> some View {211 VStack(alignment: .leading, spacing: 4) {212 Text(title).font(.callout.weight(.medium))213 ForEach(items, id: \.self) { Label($0, systemImage: "circle.fill").labelStyle(.titleAndIcon).font(.callout).foregroundStyle(.primary).symbolRenderingMode(.monochrome).imageScale(.small).tint(color) }214 }215 }216217 // MARK: venue order218219 @ViewBuilder private func order(_ p: LiveOrderProposal, _ a: LiveOrderApproval, close: Bool) -> some View {220 let o = a.order221 if p.idempotent { Banner(.info, "Cette proposition existait déjà pour la même clé : c’est elle qui est affichée, rien n’a été créé une seconde fois.") }222 ReviewLines(lines: [223 .init(label: "Type d’opération", value: close ? "Clôture en réduction seule sur la plateforme" : "Ordre sur la plateforme", style: .strong),224 .init(label: "Plateforme / réseau", value: "\(o.venue) · \(o.network)", style: .strong),225 .init(label: "Compte", value: o.account, style: .address),226 .init(label: "Instrument", value: o.instrument, style: .strong),227 .init(label: "Sens", value: o.side == "buy" ? "ACHAT (buy)" : "VENTE (sell)", style: .strong),228 .init(label: "Taille", value: FutNum.exact(o.size), style: .strong),229 .init(label: "Type envoyé", value: "\(o.type) · \(o.tif)" + (o.type == "limit" && o.tif == "ioc" ? " — un ordre au marché est envoyé comme limite immédiate au pire prix ci-dessous" : "")),230 .init(label: o.tif == "ioc" ? "Pire prix accepté" : "Prix limite", value: FutNum.exact(o.price), style: .strong),231 .init(label: "Prix de déclenchement", value: o.triggerPrice.map { FutNum.exact($0) } ?? "aucun"),232 .init(label: "Réduction seule", value: o.reduceOnly ? "oui — ne peut qu’alléger la position" : "non — peut ouvrir ou augmenter une position", style: o.reduceOnly ? .normal : .warning),233 .init(label: "Identifiant d’ordre (plateforme)", value: o.clientId),234 .init(label: "Autorisation utilisée", value: o.authorizationId),235 .init(label: "Nonce / expiration", value: "\(o.nonce) · expire à \(Self.date(ms: o.expiresAt))"),236 ])237 if let e = p.estimate {238 VStack(alignment: .leading, spacing: 8) {239 HStack { Text("Estimations du serveur").font(.headline); ProvenanceTag(p: .estimate) }240 Field(label: "Exposition notionnelle", value: FutNum.usd(e.notional))241 Field(label: "Levier (plateforme)", value: (e.leverage.map { "\(FutNum.exact($0))×" } ?? "non lu") + (e.marginMode.map { " · marge \($0)" } ?? ""))242 Field(label: "Marge requise", value: FutNum.usd(e.initialMargin))243 Field(label: "Frais", value: FutNum.usd(e.fee) + (e.feeNote.map { " — \($0)" } ?? ""))244 Field(label: "Collatéral libre après", value: FutNum.usd(e.freeCollateralAfter))245 Field(label: "Prix de liquidation", value: e.liquidationNote ?? "aucune estimation avant l’ordre : la plateforme le publie une fois la position ouverte")246 }.padding(10).background(Color.secondary.opacity(0.08), in: RoundedRectangle(cornerRadius: 8))247 }248 if close, let pos = p.position {249 Field(label: "Position visée", value: "\(pos.side.uppercased()) \(FutNum.exact(pos.size)) \(pos.instrument) (entrée \(FutNum.exact(pos.entryPrice)))")250 if let b = p.slippageBoundBps { Field(label: "Borne de glissement", value: "\(b) points de base") }251 }252 Text(o.reduceOnly ? "Un ordre exécuté sur la plateforme est définitif. La perte latente de la partie clôturée devient réalisée."253 : "Un ordre exécuté sur la plateforme est définitif. Une position à effet de levier peut être liquidée : la marge, et en marge croisée tout le collatéral du compte, peuvent être perdus.")254 .font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)255 BindingProof(digest: a.approval.digest, expiry: o.expiry)256 }257258 // MARK: leverage259260 @ViewBuilder private func leverage(_ l: LiveLeverageApproval) -> some View {261 let c = l.change262 ReviewLines(lines: [263 .init(label: "Type d’opération", value: "Changement du réglage de levier sur la plateforme", style: .strong),264 .init(label: "Plateforme / réseau", value: "\(c.venue) · \(c.network)", style: .strong),265 .init(label: "Compte", value: c.account, style: .address),266 .init(label: "Instrument", value: c.instrument, style: .strong),267 .init(label: "Nouveau levier", value: "\(c.leverage)×", style: .strong),268 .init(label: "Mode de marge", value: c.marginMode == "cross" ? "croisée (cross) — tout le collatéral du compte garantit la position" : "isolée (isolated)", style: .strong),269 .init(label: "Réglage actuel de la plateforme", value: l.current.map { "\($0.leverage)× (\($0.marginMode))" } ?? "illisible"),270 .init(label: "Autorisation utilisée", value: c.authorizationId),271 .init(label: "Nonce / expiration", value: "\(c.nonce) · expire à \(Self.date(ms: c.expiresAt))"),272 ])273 if let cur = l.current.flatMap({ Int($0.leverage) }), c.leverage > cur {274 Banner(.warning, "Le levier augmente : le prix de liquidation d’une position ouverte sur cet instrument se rapproche du prix actuel.")275 }276 BindingProof(digest: l.approval.digest, expiry: c.expiry)277 }278279 // MARK: collateral280281 private func depositExtra(_ d: CollateralDepositApproval) -> [ReviewLine] {282 var extra: [ReviewLine] = []283 if let r = d.route {284 extra.append(.init(label: "Route (selon le serveur)", value: "\(r.networkName ?? r.network) → pont \(r.bridge)" + (r.expectedSeconds.map { " · crédit attendu en ≈ \($0) s" } ?? "")))285 if let m = r.venueMinimum { extra.append(.init(label: "Minimum de la plateforme", value: "\(m) USDC — en dessous, les fonds sont perdus", style: .warning)) }286 }287 if let f = d.fee { extra.append(.init(label: "Frais de réseau estimés", value: "\(f.estimate) \(f.symbol) (plafond signé : \(f.max) \(f.symbol))")) }288 if let l = d.liveness { extra.append(.init(label: "Contrôle du pont", value: (l.ok ? "dépôts récents crédités" : "NON CONFIRMÉ") + (l.detail.map { " — \($0)" } ?? "") + (l.checkedAt.map { " · vérifié \(Fmt.relative($0))" } ?? ""), style: l.ok ? .normal : .warning)) }289 if let b = d.venueBalance { extra.append(.init(label: "Solde actuel sur la plateforme", value: b.error.map { "illisible : \($0)" } ?? "\(b.total ?? b.equity ?? "—") USDC")) }290 return extra291 }292293 @ViewBuilder private func deposit(_ d: CollateralDepositApproval) -> some View {294 Banner(.warning, "La plateforme crédite l’adresse EXPÉDITRICE : ce dépôt part de l’adresse de ce portefeuille vers le pont épinglé. Il n’est terminé que lorsque la plateforme l’a crédité.")295 TransactionReview(intent: d.intent, digest: d.approval.digest, network: model.network(d.intent.network),296 ownAddresses: Dictionary((model.accounts?.value.accounts ?? []).map { ($0.network, $0.address) }, uniquingKeysWith: { a, _ in a }), warnings: [], extra: depositExtra(d))297 }298299 @ViewBuilder private func withdraw(_ w: CollateralWithdrawApproval) -> some View {300 let x = w.withdrawal301 ReviewLines(lines: [302 .init(label: "Type d’opération", value: "Retrait de collatéral de la plateforme vers ce portefeuille", style: .strong),303 .init(label: "Plateforme / réseau", value: "\(x.venue) · \(x.network)", style: .strong),304 .init(label: "Compte débité", value: x.account, style: .address),305 .init(label: "Destination (votre adresse)", value: x.destination, style: .address),306 .init(label: "Montant demandé", value: "\(FutNum.exact(x.amount)) USDC", style: .strong),307 .init(label: "Frais de la plateforme", value: "\(FutNum.exact(x.fee)) USDC"),308 .init(label: "Vous recevez", value: "\(FutNum.exact(w.receive)) USDC (montant − frais, recalculé par l’app)", style: .strong),309 .init(label: "Horodatage de l’action", value: Self.date(ms: x.time)),310 .init(label: "Expire le", value: Self.date(seconds: x.expiresAt)),311 .init(label: "Identifiant", value: x.withdrawalId),312 .init(label: "Clé du portefeuille", value: x.keyId),313 ] + (w.action.map { [ReviewLine(label: "Action signée pour la plateforme", value: "\($0.type) sur \($0.hyperliquidChain) → \($0.destination), \($0.amount) USDC")] } ?? [])314 + (w.venueBalance.map { [ReviewLine(label: "Solde actuel sur la plateforme", value: $0.error.map { "illisible : \($0)" } ?? "retirable \($0.withdrawable ?? "—") USDC")] } ?? []))315 Text("Le retrait n’est terminé que lorsque ce portefeuille a vu les USDC arriver. Retirer du collatéral rapproche le prix de liquidation des positions ouvertes.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)316 BindingProof(digest: w.approval.digest, expiry: x.expiry)317 }318319 // MARK: risk intent of the account320321 @ViewBuilder private func risk(_ r: LiveRiskApproval) -> some View {322 let i = r.intent323 Banner(.warning, i.kind == .resume ? "Lever l’arrêt redonne au compte la possibilité de prendre du nouveau risque."324 : i.kind == .rebase ? "Vous acceptez les positions actuelles de la plateforme comme référence après une divergence."325 : "Ce changement ASSOUPLIT les protections du compte.")326 ReviewLines(lines: [327 .init(label: "Type d’opération", value: i.kind == .resume ? "Levée de l’arrêt du compte" : i.kind == .rebase ? "Acceptation des positions (re-base)" : "Nouvelle politique de risque du compte", style: .strong),328 .init(label: "Plateforme / réseau", value: "\(i.venue) · \(i.network)", style: .strong),329 .init(label: "Compte", value: i.account, style: .address),330 .init(label: "Identifiant du compte", value: i.accountId),331 .init(label: "Autorisation", value: i.authorizationId),332 .init(label: i.kind == .resume ? "Arrêt levé" : "Divergence acceptée", value: i.subject ?? "aucun"),333 .init(label: "Champs assouplis", value: i.loosened.isEmpty ? "aucun" : i.loosened.joined(separator: ", "), style: i.loosened.isEmpty ? .normal : .warning),334 .init(label: "Nonce", value: i.nonce),335 ] + (i.policy.map(Self.policyLines) ?? []))336 BindingProof(digest: r.approval.digest, expiry: i.expiry)337 }338339 static func policyLines(_ p: DerivRiskPolicy) -> [ReviewLine] {340 [341 .init(label: "Politique — mode", value: p.mode),342 .init(label: "Instruments permis", value: p.allowedInstruments.isEmpty ? "aucun" : p.allowedInstruments.joined(separator: ", ")),343 .init(label: "Arrêt", value: p.halt ?? "aucun"),344 .init(label: "Levier maximal", value: "\(p.maxLeverage)×"),345 .init(label: "Notionnel max par ordre", value: p.maxOrderNotional),346 .init(label: "Notionnel max par position", value: p.maxPositionNotional),347 .init(label: "Exposition brute max", value: p.maxGrossExposure),348 .init(label: "Collatéral libre minimal", value: p.minFreeCollateral),349 .init(label: "Distance min. à la liquidation", value: "\(p.minLiquidationDistanceBps) pb"),350 .init(label: "Perte quotidienne max", value: p.maxDailyLoss),351 .init(label: "Perte totale max", value: p.maxTotalLoss),352 .init(label: "Ordres par minute / jour", value: "\(p.maxOrdersPerMinute) / \(p.maxOrdersPerDay)"),353 .init(label: "Âge max des données", value: "\(p.maxDataAgeMs) ms"),354 .init(label: "Écart de prix max", value: "\(p.maxDeviationBps) pb"),355 .init(label: "Écart mark / indice max", value: "\(p.maxMarkIndexBps) pb"),356 ]357 }358}359