SPB Git

Repository Public

PerpAgentViews.swift 16.5 KB 200 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/TradingAgents/PerpAgentViews.swift3// Description: A perp agent: its simulated (paper) derivatives account, and the road to real execution exactly as the server exposes it — the go-live checklist (strategy, venue account, funding, mandate), the proposed mandate, the server locks, then the verified two-prompt passkey approval. When a lock is closed or the server cannot run a mandate, the live controls are absent and the server's reason is shown.4import SwiftUI5import SPWalletCore67struct PerpAgentSection: View {8    let model: AppModel9    let d: AgentDetailStore10    let store: AgentsStore11    @State private var flow: PerpGoLiveFlow?12    @State private var confirmFlatten = false13    @State private var confirmStop = false1415    var body: some View {16        if case .perp(let p)? = d.detail {17            paper(p)18            live(p)19        }20    }2122    // MARK: paper account2324    @ViewBuilder private func paper(_ p: PerpAgentDetail) -> some View {25        let kind = ModeKind(.paper)26        Card("Compte de simulation", trailing: AnyView(ModeTag(kind: kind))) {27            if let acct = p.account {28                VStack(alignment: .leading, spacing: 8) {29                    Text("Le moteur papier exécute contre le carnet réel de la plateforme, mais rien n’atteint la plateforme : positions, ordres, exécutions et financement ci-dessous sont SIMULÉS.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)30                    if let h = acct.halt { Banner(.warning, "Disjoncteur du compte simulé : \(h)") }31                    Field(label: "Collatéral initial simulé", value: acct.initialCollateral.map { "\(Fmt.amount($0)) USDC" } ?? "—")32                    JSONFacts(value: acct.state, depth: 1, empty: "État du compte simulé indisponible.")33                    if let t = acct.totals, !t.isNull { Text("Totaux").font(.caption.weight(.semibold)); JSONFacts(value: t, depth: 2) }34                    DisclosureGroup("Positions simulées (\(acct.positions.count))") { JSONList(items: acct.positions, empty: "Aucune position.").padding(.top, 6) }35                    DisclosureGroup("Ordres ouverts simulés (\(acct.openOrders.count))") { JSONList(items: acct.openOrders, empty: "Aucun ordre ouvert.").padding(.top, 6) }36                    DisclosureGroup("Dernières exécutions simulées (\(acct.fills.count))") { JSONList(items: acct.fills, limit: 30, empty: "Aucune exécution.").padding(.top, 6) }37                    DisclosureGroup("Financement simulé (\(acct.funding.count))") { JSONList(items: acct.funding, limit: 30, empty: "Aucun paiement de financement.").padding(.top, 6) }38                    DisclosureGroup("Événements de risque (\(acct.riskEvents.count))") { JSONList(items: acct.riskEvents, limit: 30, empty: "Aucun événement.").padding(.top, 6) }39                    HStack {40                        Spacer()41                        ModeButton(title: "Fermer toutes les positions", kind: kind, systemImage: "arrow.down.to.line", role: .destructive) { confirmFlatten = true }42                            .disabled(!model.canOperate || d.busy != nil || acct.positions.isEmpty || p.agent.mode == .live)43                    }44                }.modeFramed(kind)45            } else { Text("Cet agent n’a pas de compte de simulation.").foregroundStyle(.secondary) }46            if let n = d.notice { Banner(.info, n) }47            if let e = d.actionError { Banner(.danger, e) }48        }49        .confirmationDialog("Fermer toutes les positions du compte PAPIER ?", isPresented: $confirmFlatten, titleVisibility: .visible) {50            Button("Fermer · PAPIER", role: .destructive) { Task { await d.flattenPaper() } }51            Button("Annuler", role: .cancel) {}52        } message: { Text("Des ordres réducteurs simulés ferment les positions du compte de simulation. Rien n’est envoyé à la plateforme.") }53    }5455    // MARK: live5657    @ViewBuilder private func live(_ p: PerpAgentDetail) -> some View {58        let a = p.agent, l = p.live59        let kind = ModeKind(.live, liveNetwork: l?.network ?? a.liveNetwork)60        Card("Exécution réelle sous mandat", trailing: AnyView(Group { if a.mode == .live { ModeTag(kind: kind) } })) {61            if let l, !l.available {62                Label("Ce serveur ne peut pas exécuter de mandat de dérivés\(l.reason.map { " : \($0)" } ?? ".")", systemImage: "lock.fill").foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)63            } else if a.mode == .live, let l {64                VStack(alignment: .leading, spacing: 6) {65                    Field(label: "Réseau de la plateforme", value: l.network == "mainnet" ? "mainnet — ARGENT RÉEL" : "\(l.network ?? "—") — argent fictif", emphasis: true)66                    Field(label: "Mandat", value: l.mandateId ?? "—", mono: true)67                    Field(label: "En réel depuis", value: Fmt.date(l.since) + (l.paused ? " · EN PAUSE (positions conservées)" : ""))68                    if let c = l.capital { Field(label: "Capital de référence", value: "\(Fmt.amount(c)) USDC") }69                    Text("Compte de la plateforme (lu sur la plateforme)").font(.caption.weight(.semibold)); JSONFacts(value: l.account, depth: 2, empty: "Compte non lu.")70                    Text("Mandat et compteurs rapportés par le signataire").font(.caption.weight(.semibold)); JSONFacts(value: l.signer, depth: 3, empty: "Le signataire n’a rien rapporté.")71                }.modeFramed(kind)72                Divider()73                HStack(alignment: .top, spacing: 12) {74                    VStack(alignment: .leading, spacing: 2) {75                        Text("Arrêt et révocation").font(.headline)76                        Text("Sans passkey : le mandat est révoqué au signataire et les positions sont fermées avec des ordres réducteurs, au prix du marché (résultat non garanti). La pause, elle, conserve les positions et le mandat.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)77                    }78                    Spacer()79                    VStack(alignment: .trailing, spacing: 8) {80                        Button(role: .destructive) { confirmStop = true } label: { Label("Arrêter et révoquer le mandat", systemImage: "xmark.shield.fill").fontWeight(.semibold) }.buttonStyle(.borderedProminent).tint(Theme.negative).controlSize(.large)81                        if l.paused { ModeButton(title: "Reprendre", kind: kind, systemImage: "play.fill") { Task { await d.resume() } } }82                        else { ModeButton(title: "Mettre en pause", kind: kind, systemImage: "pause.fill") { Task { await d.pause() } } }83                    }.disabled(!model.canOperate || d.busy != nil)84                }85            } else if let flow {86                readiness(flow, a)87            } else { ProgressView() }88        }89        .task(id: a.mode) { if flow == nil { flow = PerpGoLiveFlow(model: model, agentId: a.id) }; if a.mode != .live, l?.available != false { await flow?.load() } }90        .confirmationDialog("Arrêter l’agent et révoquer son mandat ?", isPresented: $confirmStop, titleVisibility: .visible) {91            Button("Arrêter et révoquer · \(kind.short)", role: .destructive) { Task { await d.stop(); await store.refresh() } }92            Button("Annuler", role: .cancel) {}93        } message: { Text("Le mandat est révoqué au signataire. Les positions sont fermées avec des ordres réducteurs ; l’agent reste « arrêt en cours » jusqu’à la fin. Pendant 24 heures, seuls des annulations et des ordres réducteurs peuvent encore être signés.") }94        .sheet(isPresented: Binding(get: { flow?.step == .review || flow?.step == .approving }, set: { _ in })) {95            if let flow, let ap = flow.approval { PerpLiveSheet(model: model, flow: flow, approval: ap) }96        }97        .onChange(of: flow?.step) { _, s in if s == .done { Task { await d.refresh(); await store.refresh() } } }98    }99100    /// The server locks that close the live path for the chosen venue account; empty = none known to be closed.101    private func closedLocks(_ r: PerpLiveReadiness) -> [(String, String?)] {102        var out: [(String, String?)] = []103        if let l = r.steps.mandate.lock { out.append((l.code, l.reason)) }104        var ids = ["trading_api_execution"]105        if r.account?.network == "mainnet" { ids += ["deriv_live_mainnet", "deriv_mandate_mainnet"] }106        for id in ids { if let l = store.lock(id), !l.on { out.append((l.id, l.why)) } }107        return out108    }109110    @ViewBuilder private func readiness(_ flow: PerpGoLiveFlow, _ a: Agent) -> some View {111        @Bindable var flow = flow112        if let r = flow.readiness {113            let s = r.steps, locks = closedLocks(r)114            VStack(alignment: .leading, spacing: 8) {115                step(s.strategy.ok, "1 · Stratégie approuvée", s.strategy.ok ? "\(s.strategy.name ?? "") \(s.strategy.version ?? "")" : s.strategy.reason)116                step(s.account.ok, "2 · Compte de la plateforme autorisé", s.account.ok ? r.account.map { "\($0.label ?? $0.id) · \($0.network) · \($0.account)" } : s.account.reason ?? s.account.code)117                step(s.funded.ok, "3 · Compte approvisionné", s.funded.ok ? s.funded.equity.map { "valeur du compte : \(Fmt.amount($0)) USDC" } : (s.funded.reason ?? s.funded.code).map { "\($0)\(s.funded.minEquity.map { " (minimum \($0) USDC)" } ?? "")" })118                step(s.mandate.ok, "4 · Mandat approuvé avec la passkey", s.mandate.ok ? "mandat \(s.mandate.mandateId ?? "") — \(s.mandate.phase ?? "")" : s.mandate.phase.map { "phase : \($0)" })119            }120            if let missing = s.account.instrumentsMissing, !missing.isEmpty { Banner(.warning, "Instruments absents de l’autorisation du compte : \(missing.joined(separator: ", ")).") }121            if !r.accounts.isEmpty {122                Form {123                    Picker("Compte de la plateforme", selection: $flow.accountId) {124                        ForEach(r.accounts) { acct in125                            Text("\(acct.label ?? acct.id) — \(acct.network == "mainnet" ? "mainnet (argent réel)" : acct.network)\(acct.equity.map { " · \($0) USDC" } ?? "")\(acct.usedBy.map { " · utilisé par \($0.name)" } ?? "")").tag(acct.id)126                        }127                    }128                    TextField("Validité du mandat (jours, 1 à \(r.proposal?.maxDays ?? s.account.authorization?.maxMandateDays ?? AgentVenueMandate.maxDays))", text: $flow.daysText, prompt: Text("à indiquer"))129                }.formStyle(.grouped).scrollDisabled(true)130                    .onChange(of: flow.accountId) { Task { await flow.load() } }131                    .onChange(of: flow.days) { Task { await flow.load() } }132            } else {133                Text("Aucun compte de plateforme n’existe dans ce portefeuille. Un compte se crée, s’autorise (passkey) et s’approvisionne dans la section Contrats à terme.").font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)134            }135            if let acct = r.account, let e = acct.error { Banner(.warning, "Compte illisible : \(e)") }136            if let pr = r.proposal { proposal(pr, r) }137            if !locks.isEmpty {138                Divider()139                Text("Passage en réel fermé par le serveur").font(.callout.weight(.semibold))140                ForEach(Array(locks.enumerated()), id: \.offset) { _, l in LockRow(name: l.0, open: false, reason: l.1) }141                Text("Tant qu’un de ces verrous est fermé, aucune commande de mandat réel n’est proposée ici.").font(.caption).foregroundStyle(.secondary)142            } else {143                Text(guidance(r.next)).font(.callout).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)144                if let e = flow.error { Banner(.danger, e) }145                if flow.step == .done { Banner(.ok, "Mandat approuvé. État de l’agent selon le serveur : \(flow.result.map { AgentText.phase($0.agent.state) } ?? "—").") }146                if r.next == "mandate", r.proposal != nil {147                    let kind = ModeKind(.live, liveNetwork: r.account?.network)148                    HStack {149                        if flow.days == nil { Text("Indiquez la validité du mandat en jours : aucune durée par défaut n’est appliquée.").font(.callout).foregroundStyle(Theme.warning) }150                        Spacer()151                        if flow.step == .preparing { ProgressView().controlSize(.small); Text("Construction et vérification du mandat…").foregroundStyle(.secondary) }152                        ModeButton(title: "Préparer le mandat à approuver…", kind: kind, systemImage: "touchid", prominent: true) { Task { await flow.prepare(agent: a) } }153                            .disabled(!model.canOperate || flow.days == nil || (flow.step != .idle && flow.step != .done) || store.killSwitch?.engaged == true)154                    }155                    if store.killSwitch?.engaged == true { Text("Arrêt d’urgence engagé : aucun mandat n’est préparé.").font(.caption).foregroundStyle(Theme.negative) }156                }157            }158            HStack { Spacer(); if flow.loading { ProgressView().controlSize(.small) }; Button("Relire la liste de contrôle") { Task { await flow.load() } } }159        } else if let e = flow.readinessError { Banner(.danger, "Liste de contrôle indisponible : \(e)"); Button("Réessayer") { Task { await flow.load() } } }160        else { ProgressView() }161    }162163    private func guidance(_ next: String) -> String {164        switch next {165        case "strategy": "Prochaine étape : approuver une version de stratégie testée (onglet Stratégie)."166        case "account": "Prochaine étape : un compte de la plateforme autorisé pour les instruments de l’agent (section Contrats à terme)."167        case "fund": "Prochaine étape : approvisionner le compte de la plateforme (section Contrats à terme)."168        case "mandate": "Tout est prêt pour le mandat. Préparer ne signe rien : vous verrez le mandat complet, vérifié par cette app, avant d’approuver avec votre passkey."169        case "live": "Un mandat est en vigueur : l’agent se démarre en réel depuis « Cycle de vie », en haut de la page."170        case "locked": "Le serveur a fermé cette voie."171        default: "Étape suivante selon le serveur : \(next)."172        }173    }174175    private func step(_ ok: Bool, _ title: String, _ detail: String?) -> some View {176        HStack(alignment: .top, spacing: 8) {177            Image(systemName: ok ? "checkmark.circle.fill" : "circle").foregroundStyle(ok ? Theme.positive : .secondary)178            VStack(alignment: .leading, spacing: 1) { Text(title).fontWeight(.medium); if let detail, !detail.isEmpty { Text(detail).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true).textSelection(.enabled) } }179        }180    }181182    @ViewBuilder private func proposal(_ pr: PerpLiveProposal, _ r: PerpLiveReadiness) -> some View {183        let kind = ModeKind(.live, liveNetwork: r.account?.network), b = pr.body184        VStack(alignment: .leading, spacing: 5) {185            HStack { Text("Mandat que le serveur proposerait (aperçu — rien n’est préparé)").font(.callout.weight(.semibold)); ModeTag(kind: kind, compact: true) }186            Field(label: "Valeur du compte (référence)", value: "\(Fmt.amount(pr.capital)) USDC")187            Field(label: "Validité", value: "\(pr.days) jour(s) (maximum \(pr.maxDays))")188            Field(label: "Instruments", value: b.instruments.map { "\($0.instrument) — levier ≤ ×\($0.maxLeverage), position ≤ \(Fmt.amount($0.maxPositionNotional)) USDC" }.joined(separator: "\n"))189            Field(label: "Notionnel par ordre", value: "≤ \(Fmt.amount(b.maxOrderNotional)) USDC")190            Field(label: "Exposition brute", value: "≤ \(Fmt.amount(b.maxGrossExposure)) USDC")191            Field(label: "Volume quotidien", value: "≤ \(Fmt.amount(b.maxDailyTurnover)) USDC")192            Field(label: "Plancher de valeur du compte", value: "\(Fmt.amount(b.floorEquity)) USDC (limite de perte appliquée par le signataire)")193            Field(label: "Ordres", value: "≤ \(b.maxOrdersPerHour) par heure · ≤ \(b.maxOrdersPerDay) par jour")194            ForEach(pr.derived, id: \.field) { x in Text("\(x.field) = \(x.value) — \(x.from)").font(.caption).foregroundStyle(.secondary).textSelection(.enabled) }195            ForEach(pr.notes, id: \.self) { n in Label(n, systemImage: "arrow.down.right").font(.caption).foregroundStyle(Theme.warning) }196        }197        .padding(10).frame(maxWidth: .infinity, alignment: .leading).modeFramed(kind).background(kind.color.opacity(0.05), in: RoundedRectangle(cornerRadius: 8))198    }199}200
Files main
Menu

Theme