SPB Git

Repository Public

AgentLiveFlows.swift 42.0 KB 572 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/TradingAgents/AgentLiveFlows.swift10// Description      : Going live. SPOT: the owner types every limit (empty11//                    fields, nothing pre-selected, expiry mandatory), the Core12//                    asks the server for the mandate and verifies it against13//                    what was typed and against the passkey challenge, the14//                    VERIFIED mandate is shown in full (vault, network, each15//                    asset's caps in exact units, what the signer enforces and16//                    what only the engine enforces, digest), then the passkey17//                    approves it. PERP: the server's checklist as served, both18//                    objects and the acknowledgement text exactly as served19//                    with an explicit tick, then the TWO passkey prompts. A20//                    lock or a refusal of the server is shown verbatim and ends21//                    the flow. Nothing here can weaken a check or skip the22//                    review.23// Module           : Features24// Repository       : https://git.spboucher.ai/sp-wallet-ios25// Created          : 2026-11-1826// Last Modified    : 2026-11-1827//28// =============================================================================29// AUTHOR & PROFESSIONAL AFFILIATION30// =============================================================================31//32// Author           : Simon-Pierre Boucher33// Position         : Professor of Finance34// Institution      : Université du Québec en Outaouais (UQO)35// Department       : Département des sciences administratives36// Organization     : SP Boucher37//38// Website          : https://spboucher.ai39// Git              : https://git.spboucher.ai40//41// =============================================================================42// OFFICIAL CONTACT DIRECTORY43// =============================================================================44//45// General          : info@spboucher.ai46// Professional     : contact@spboucher.ai47// Direct           : simon@spboucher.ai48// Research         : research@spboucher.ai49// Development      : dev@spboucher.ai50// Support          : support@spboucher.ai51// Security/Admin   : admin@spboucher.ai52// Notifications    : notifications@spboucher.ai53//54// Preferred Contact: support@spboucher.ai55//56// =============================================================================57// COPYRIGHT & INTELLECTUAL PROPERTY58// =============================================================================59//60// Copyright (c) 202661// Simon-Pierre Boucher62//63// All rights reserved where applicable.64//65// This file is governed by the applicable project license,66// copyright notices, institutional agreements and relevant law.67//68// Unless expressly authorized by the applicable license or69// rights holder, copying, redistribution, sublicensing,70// publication and commercial exploitation are not permitted.71//72// Existing third-party rights and notices remain unaffected.73//74// =============================================================================75// CONFIDENTIALITY & SECURITY76// =============================================================================77//78// Classification   : Public79// Distribution     : Public repository; use is governed by the project license80// Security Contact : admin@spboucher.ai81//82// Access to this source does not independently grant permission83// to redistribute or disclose confidential materials.84//85// Do not embed credentials, private keys, access tokens,86// certificates or confidential personal information.87//88// =============================================================================89// LICENSE & MAINTENANCE90// =============================================================================91//92// License          : None specified (no license file in this repository)93// Maintainer       : Simon-Pierre Boucher94// Technical Contact: dev@spboucher.ai95//96// =============================================================================97// END OF SP BOUCHER SOURCE HEADER98// =============================================================================99100import SwiftUI101import SPWalletCore102103// MARK: spot104105@MainActor @Observable106final class SpotLiveModel {107    enum Step: Equatable { case form, review, status }108    var step: Step = .form109    var form = SpotLiveForm()110    var busy = false111    var error: Error?112    var approval: SpotMandateApproval?113    var result: Agent?114    /** The mandate as the signer reports it after the approval (read back, never assumed). */115    var signerStatus: SpotMandateStatus?116117    func prepare(_ env: AppEnvironment, detail: SpotAgentDetail, network: Network?) async {118        guard !busy else { return }119        busy = true; error = nil120        defer { busy = false }121        do {122            guard let network else { throw ApprovalError.unsupported("the network of the vault is not in the wallet's registry") }123            let expectation = try form.expectation(detail: detail, network: network)124            approval = try await AgentsAPI(env.client).prepareSpotMandate(agentId: detail.agent.id, expecting: expectation)125            step = .review126        } catch { self.error = error }127    }128129    func approve(_ env: AppEnvironment) async {130        guard let a = approval, !busy else { return }131        busy = true; error = nil132        defer { busy = false }133        let api = AgentsAPI(env.client)134        do {135            result = try await api.approveSpotMandate(a, with: env.passkeys)136            await readBack(api, id: a.agentId)137            step = .status138        } catch PasskeyError.cancelled {139            // dismissed: nothing was signed; the prepared mandate authorises nothing140        } catch let e as APIError where e.isOffline {141            // the answer was lost after the assertion left: read the agent instead of signing again142            await readBack(api, id: a.agentId)143            if let r = result, r.mode == .live { step = .status } else { error = e }144        } catch { self.error = error }145    }146147    private func readBack(_ api: AgentsAPI, id: String) async {148        if case .spot(let d)? = try? await api.detail(id) { result = d.agent; signerStatus = d.mandateStatus }149    }150151    func backToForm() { approval = nil; error = nil; step = .form }152}153154struct SpotLiveFlow: View {155    @Environment(AppModel.self) private var model156    @Environment(\.dismiss) private var dismiss157    let detail: SpotAgentDetail158    let done: () -> Void159    @State private var live = SpotLiveModel()160    @State private var confirmCancel = false161162    private var agent: Agent { detail.agent }163    private var network: Network? { model.network(agent.network) }164165    var body: some View {166        NavigationStack {167            ScrollView {168                VStack(alignment: .leading, spacing: Theme.Space.section) {169                    AgentModeBand(mode: .live, detail: String(localized: "argent réel"))170                    if !model.canOperate { Notice(tone: .warn, title: String(localized: "Indisponible hors ligne"), message: String(localized: "Approuver un mandat exige le serveur, le signataire isolé et ta clé d’accès.")) }171                    switch live.step {172                    case .form: form173                    case .review: review174                    case .status: status175                    }176                }177                .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)178                .frame(maxWidth: 640).frame(maxWidth: .infinity)179            }180            .scrollDismissesKeyboard(.immediately)181            .spPage()182            .navigationTitle(live.step == .form ? String(localized: "Passer en réel") : live.step == .review ? String(localized: "Vérifier et approuver le mandat") : String(localized: "État du mandat"))183            .navigationBarTitleDisplayMode(.inline)184            .toolbar {185                ToolbarItem(placement: .cancellationAction) {186                    Button(live.step == .status ? String(localized: "Fermer") : String(localized: "Annuler")) { if live.step == .review { confirmCancel = true } else { done(); dismiss() } }187                        .accessibilityIdentifier("live.close")188                }189            }190            .confirmationDialog(String(localized: "Abandonner ce mandat ?"), isPresented: $confirmCancel, titleVisibility: .visible) {191                Button(String(localized: "Abandonner et fermer"), role: .destructive) { done(); dismiss() }192                Button(String(localized: "Continuer la revue"), role: .cancel) {}193            } message: { Text(String(localized: "Rien n’a été signé. Un mandat préparé mais non approuvé n’autorise rien.")) }194        }195        .interactiveDismissDisabled(live.step == .review || live.busy)196    }197198    // MARK: form — every limit typed199200    private func field(_ f: SpotLiveForm.Field) -> String? { live.form.problem(f, agent: agent) }201202    @ViewBuilder private var form: some View {203        @Bindable var live = live204        Notice(tone: .warn, title: String(localized: "Tu vas autoriser des ordres réels"), message: String(localized: "Sous ce mandat, le signataire isolé signera des échanges avec les fonds du coffre, sans te redemander, jusqu’à l’expiration ou la révocation. Saisis toi-même chaque limite : rien n’est prérempli."))205        if detail.approvedVersion == nil {206            Notice(tone: .danger, title: String(localized: "Aucune version de stratégie approuvée"), message: String(localized: "Approuve d’abord une version dans « Simulation » : le mandat épingle son empreinte.")).accessibilityIdentifier("live.spot.nostrategy")207        }208        VStack(alignment: .leading, spacing: 14) {209            Text(String(localized: "Limites du mandat")).font(.spHeadline)210            Text(String(localized: "Les limites d’un agent spot sont fixées à sa création ; le mandat est construit à partir d’elles. Saisis-les de nouveau : l’app refusera tout mandat qui ne dit pas exactement ce que tu as saisi.")).font(.spFootnote).foregroundStyle(Theme.mute)211            LimitField(label: String(localized: "Budget maximal confié à l’agent"), text: $live.form.budget, unit: "USD", hint: String(localized: "Imposé par le moteur, pas par le signataire."), problem: field(.budget), id: "live.spot.budget")212            LimitField(label: String(localized: "Plafond par ordre"), text: $live.form.maxOrder, unit: "USD", problem: field(.maxOrder), id: "live.spot.maxOrder")213            LimitField(label: String(localized: "Plafond de volume par jour"), text: $live.form.maxDaily, unit: "USD", problem: field(.maxDaily), id: "live.spot.maxDaily")214            LimitField(label: String(localized: "Nombre d’ordres par jour"), text: $live.form.ordersPerDay, problem: field(.ordersPerDay), integer: true, id: "live.spot.ordersPerDay")215            LimitField(label: String(localized: "Limite de perte"), text: $live.form.lossPct, unit: "%", hint: String(localized: "Imposée par le moteur seulement : le signataire ne peut pas la garantir, et un écart de prix peut la dépasser."), problem: field(.lossPct), id: "live.spot.lossPct")216            LimitField(label: String(localized: "Durée du mandat (expiration obligatoire)"), text: $live.form.days, unit: String(localized: "jours"), hint: String(localized: "Le mandat cesse d’autoriser quoi que ce soit à cette échéance."), problem: field(.days), integer: true, id: "live.spot.days")217        }.spCard()218        VStack(alignment: .leading, spacing: 8) {219            Text(String(localized: "Actifs autorisés")).font(.spHeadline)220            Text(String(localized: "Coche chaque actif que le signataire pourra échanger pour cet agent.")).font(.spFootnote).foregroundStyle(Theme.mute)221            ForEach(agent.holdings ?? [], id: \.asset) { h in222                AgentCheckRow(title: "\(h.assetSymbol) — \(h.name)" + (h.isCash ? " · " + String(localized: "réserve") : " · " + String(localized: "marché \(h.symbol)")),223                         subtitle: h.asset == "native" ? String(localized: "monnaie native du réseau") : h.asset, on: live.form.assets.contains(h.asset), id: "live.spot.asset.\(h.assetSymbol)") {224                    if live.form.assets.contains(h.asset) { live.form.assets.remove(h.asset) } else { live.form.assets.insert(h.asset) }225                }226            }227            if let p = field(.assets) { Label(p, systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger).fixedSize(horizontal: false, vertical: true) }228        }.spCard()229        VStack(alignment: .leading, spacing: 0) {230            Text(String(localized: "Non saisi — repris de l’agent et relu à l’étape suivante")).font(.spCallout.weight(.semibold)).padding(.bottom, 4)231            FieldRow(label: String(localized: "Coffre de l’agent sur \(network?.name ?? agent.network)"), value: agent.vaultAddress, mono: true, copyable: true)232            if let v = detail.approvedVersion { Divider(); FieldRow(label: String(localized: "Stratégie épinglée : \(v.name) v\(v.version)"), value: v.sha256, mono: true) }233            if let r = agent.spotRisk { Divider(); FieldRow(label: String(localized: "Garde de glissement du mandat"), value: String(localized: "\(r.mandateSlippageBps) pb (glissement de l’agent \(r.slippageBps) pb + 80, borné entre 150 et 500)")) }234        }.spCard()235        if let e = live.error { ErrorNotice(error: e).accessibilityIdentifier("live.error") }236        let missing = live.form.missing237        if !missing.isEmpty { Text(String(localized: "Il reste \(missing.count) élément(s) à saisir.")).font(.spFootnote).foregroundStyle(Theme.mute).accessibilityIdentifier("live.spot.missing") }238        Button { Task { await live.prepare(model.env, detail: detail, network: network) } } label: { HStack { if live.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer le mandat et le vérifier")) } }239            .buttonStyle(.spPrimary).disabled(!model.canOperate || live.busy || !live.form.isComplete(agent: agent) || detail.approvedVersion == nil)240            .accessibilityIdentifier("live.spot.prepare")241        Text(String(localized: "Rien n’est signé à cette étape. Le serveur construit le mandat ; l’app le compare à ta saisie et à l’empreinte que ta clé d’accès signera.")).font(.spFootnote).foregroundStyle(Theme.mute)242    }243244    // MARK: review — the verified mandate, in full245246    @ViewBuilder private var review: some View {247        if let a = live.approval {248            let m = a.mandate249            VStack(alignment: .leading, spacing: 0) {250                Text(String(localized: "Mandat vérifié")).spEyebrow().padding(.bottom, 4)251                FieldRow(label: String(localized: "Coffre (le seul compte que ce mandat engage)"), value: m.vault, mono: true, copyable: true).accessibilityIdentifier("live.review.vault")252                Divider(); FieldRow(label: String(localized: "Indice du coffre chez le signataire"), value: String(m.vaultIndex))253                Divider(); FieldRow(label: String(localized: "Réseau"), value: (a.networkName ?? network?.name ?? m.network) + " (\(m.network))")254                Divider(); FieldRow(label: String(localized: "Fournisseur d’échange (le seul autorisé)"), value: m.provider)255                Divider(); FieldRow(label: String(localized: "Libellé"), value: m.label)256                Divider(); FieldRow(label: String(localized: "Identifiant du mandat"), value: m.mandateId, mono: true)257                Divider(); FieldRow(label: String(localized: "Clé du signataire"), value: m.keyId, mono: true)258            }.spCard(padding: 16)259            VStack(alignment: .leading, spacing: 0) {260                Text(String(localized: "Actifs et plafonds, en unités exactes")).spEyebrow().padding(.bottom, 4)261                ForEach(Array(a.lines.enumerated()), id: \.element.id) { i, l in262                    if i > 0 { Divider() }263                    VStack(alignment: .leading, spacing: 2) {264                        FieldRow(label: l.symbol + (l.isCash ? " · " + String(localized: "réserve") : ""), value: l.asset == "native" ? String(localized: "monnaie native du réseau") : l.asset, mono: l.asset != "native", copyable: l.asset != "native")265                        FieldRow(label: String(localized: "Plafond par ordre"), value: l.maxOrder.map { Money.exact($0) + " " + l.symbol } ?? String(localized: "aucune vente autorisée"))266                        FieldRow(label: String(localized: "Plafond par jour"), value: l.maxDaily.map { Money.exact($0) + " " + l.symbol } ?? String(localized: "aucune vente autorisée"))267                        Text(l.isCash ? String(localized: "Égal à tes limites saisies, vérifié à l’unité près.") : String(localized: "Converti par le serveur à ses prix, vérifié par empreinte, non recalculable ici."))268                            .font(.spFootnote).foregroundStyle(l.isCash ? Theme.emerald : Theme.warn).padding(.bottom, 6)269                    }270                    .accessibilityElement(children: .combine).accessibilityIdentifier("live.review.line.\(l.symbol)")271                }272            }.spCard(padding: 16)273            VStack(alignment: .leading, spacing: 0) {274                FieldRow(label: String(localized: "Ordres par jour, au plus"), value: String(m.maxOrdersPerDay))275                Divider(); FieldRow(label: String(localized: "Règle de glissement : tout échange au-delà est refusé par le signataire"), value: String(localized: "\(m.maxSlippageBps) pb"))276                Divider(); FieldRow(label: String(localized: "Créé le"), value: AgentFmt.date(Date(timeIntervalSince1970: TimeInterval(m.createdAt))))277                Divider(); FieldRow(label: String(localized: "Expire le"), value: AgentFmt.date(m.expiry)).accessibilityIdentifier("live.review.expiry")278                Divider(); FieldRow(label: String(localized: "Empreinte de la stratégie épinglée"), value: m.strategySha256, mono: true, copyable: true)279                if let g = a.gasReserve { Divider(); FieldRow(label: String(localized: "Réserve pour les frais de réseau : exigée · détenue par le coffre"), value: "\(Money.exact(g.required)) · \(Money.exact(g.held)) \(g.symbol)") }280            }.spCard(padding: 16)281            VStack(alignment: .leading, spacing: 8) {282                Label(String(localized: "Imposé par le signataire isolé"), systemImage: "lock.shield.fill").font(.spCallout.weight(.semibold)).foregroundStyle(Theme.emerald)283                Text(String(localized: "Ce coffre seulement, ce réseau, ce fournisseur, ces actifs, les plafonds par ordre et par jour ci-dessus, le nombre d’ordres par jour, la règle de glissement et l’expiration. Un ordre hors de ces limites n’est pas signé.")).font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)284                Label(String(localized: "Imposé par le moteur seulement"), systemImage: "exclamationmark.triangle.fill").font(.spCallout.weight(.semibold)).foregroundStyle(Theme.warn)285                Text(String(localized: "La limite de perte (\(live.form.lossPct) %), le budget (\(live.form.budget) USD) et l’exposition maximale ne sont PAS dans le mandat : le signataire ne peut pas les imposer. Le moteur arrête l’agent quand la perte est atteinte ; un écart de prix peut la dépasser."))286                    .font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("live.review.engine")287            }.spCard(padding: 16)288            VStack(alignment: .leading, spacing: 0) {289                FieldRow(label: String(localized: "Empreinte du mandat (défi signé par la clé d’accès)"), value: a.approval.digest.hex, mono: true, copyable: true).accessibilityIdentifier("live.review.digest")290            }.spCard(padding: 16)291            Label(String(localized: "L’app a recalculé cette empreinte à partir des champs affichés, vérifié qu’elle est le défi demandé à ta clé d’accès et que le mandat dit ce que tu as saisi. Le signataire isolé la revérifie avant d’enregistrer le mandat."), systemImage: "checkmark.shield.fill")292                .font(.spFootnote).foregroundStyle(Theme.mute)293            if let e = live.error { ErrorNotice(error: e).accessibilityIdentifier("live.error") }294            Button { Task { await live.approve(model.env) } } label: { HStack { if live.busy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Approuver le mandat avec la clé d’accès")) } }295                .buttonStyle(.spPrimary).disabled(live.busy || !model.canOperate).accessibilityIdentifier("live.spot.approve")296            Button(String(localized: "Revenir à la saisie")) { live.backToForm() }.buttonStyle(.spSecondary).disabled(live.busy).accessibilityIdentifier("live.spot.back")297        }298    }299300    @ViewBuilder private var status: some View {301        if let r = live.result {302            VStack(alignment: .leading, spacing: 10) {303                Text(String(localized: "Réponse du serveur")).spEyebrow()304                HStack(spacing: 8) { ModeBadgeView(badge: AgentModeBadge.of(r)).accessibilityIdentifier("live.status.badge"); StateLabelView(state: r.state) }305                if r.mode != .live { Notice(tone: .warn, title: String(localized: "L’agent n’est PAS en réel"), message: String(localized: "Le serveur n’a pas confirmé le passage en réel. État rapporté : \(r.state).")) }306            }.spCard()307            AgentCard(title: String(localized: "Mandat chez le signataire")) {308                if let s = live.signerStatus {309                    FieldRow(label: String(localized: "État rapporté par le signataire"), value: s.revoked ? String(localized: "Révoqué") : s.expired ? String(localized: "Expiré") : s.active ? String(localized: "Actif") : String(localized: "Inactif"), tone: s.active ? .ok : .warn)310                        .accessibilityIdentifier("live.status.signer")311                    FieldRow(label: String(localized: "Expiration"), value: AgentFmt.date(s.expiry))312                } else { Text(String(localized: "Le signataire n’a pas rapporté de mandat pour cet agent : rien n’est supposé.")).font(.spCallout).foregroundStyle(Theme.warn) }313            }314            Text(String(localized: "Pour arrêter : « Arrêter » en bas de la page de l’agent, ou « Révoquer le mandat » dans l’espace Réel. Aucune clé d’accès n’est demandée pour arrêter.")).font(.spFootnote).foregroundStyle(Theme.mute)315        }316        Button(String(localized: "Terminer")) { done(); dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("live.done")317    }318}319320// MARK: perp321322@MainActor @Observable323final class PerpLiveModel {324    enum Step: Equatable { case checklist, review, status }325    var step: Step = .checklist326    var form = PerpLiveForm()327    var readiness: PerpLiveReadiness?328    /** The account and the days the checklist on screen was computed for. */329    var readinessFor: (account: String, days: Int)?330    var busy = false331    var error: Error?332    var approval: PerpLiveApproval?333    var acknowledged = false334    var result: PerpAgentDetail?335336    func loadAccounts(_ env: AppEnvironment, id: String) async {337        do { readiness = try await AgentsAPI(env.client).perpLiveReadiness(id, locale: "fr"); readinessFor = nil; error = nil } catch { self.error = error }338    }339340    /** The checklist for the account the owner chose over the validity he typed. */341    func check(_ env: AppEnvironment, id: String) async {342        guard let account = form.accountId, let days = form.typedDays, !busy else { return }343        busy = true; error = nil344        defer { busy = false }345        do {346            let r = try await AgentsAPI(env.client).perpLiveReadiness(id, account: account, locale: "fr", days: days)347            guard r.accountId == account else { throw ApprovalError.inconsistent("the checklist is for another venue account") }348            readiness = r; readinessFor = (account, days)349        } catch { self.error = error }350    }351352    func prepare(_ env: AppEnvironment, agent: Agent) async {353        guard let r = readiness, let f = readinessFor, f.account == form.accountId, f.days == form.typedDays, !busy else { return }354        busy = true; error = nil355        defer { busy = false }356        do {357            let expectation = try PerpLiveExpectation(agent: agent, readiness: r, days: f.days)358            guard LimitInput.int(form.maxLeverage) == expectation.maxLeverage else { throw ApprovalError.inconsistent("the leverage entered is not the agent's leverage limit") }359            approval = try await AgentsAPI(env.client).preparePerpLive(expecting: expectation, locale: "fr")360            acknowledged = false361            step = .review362        } catch { self.error = error }363    }364365    func approve(_ env: AppEnvironment) async {366        guard let a = approval, acknowledged, !busy else { return }367        busy = true; error = nil368        defer { busy = false }369        let api = AgentsAPI(env.client)370        do {371            result = try await api.approvePerpLive(a, acknowledged: acknowledged, with: env.passkeys)372            step = .status373        } catch PasskeyError.cancelled {374            // one of the two prompts was dismissed: nothing was submitted; both prompts are asked again on the next try375        } catch let e as APIError where e.isOffline {376            if case .perp(let d)? = try? await api.detail(a.agentId), d.agent.mode == .live { result = d; step = .status } else { error = e }377        } catch { self.error = error }378    }379}380381struct PerpLiveFlow: View {382    @Environment(AppModel.self) private var model383    @Environment(\.dismiss) private var dismiss384    let detail: PerpAgentDetail385    let done: () -> Void386    @State private var live = PerpLiveModel()387    @State private var confirmCancel = false388389    private var agent: Agent { detail.agent }390    private var maxDays: Int? { live.readiness?.steps.account.authorization?.maxMandateDays ?? live.readiness?.proposal?.maxDays }391392    var body: some View {393        NavigationStack {394            ScrollView {395                VStack(alignment: .leading, spacing: Theme.Space.section) {396                    AgentModeBand(mode: .live, detail: networkWord(live.approval?.mandate.network ?? live.readiness?.account?.network))397                    if !model.canOperate { Notice(tone: .warn, title: String(localized: "Indisponible hors ligne"), message: String(localized: "Approuver un mandat exige le serveur, le signataire isolé et ta clé d’accès.")) }398                    switch live.step {399                    case .checklist: checklist400                    case .review: review401                    case .status: status402                    }403                }404                .padding(.horizontal, Theme.Space.gutter).padding(.vertical, 12)405                .frame(maxWidth: 640).frame(maxWidth: .infinity)406            }407            .scrollDismissesKeyboard(.immediately)408            .spPage()409            .navigationTitle(live.step == .checklist ? String(localized: "Passer en réel (contrats)") : live.step == .review ? String(localized: "Vérifier et approuver") : String(localized: "État"))410            .navigationBarTitleDisplayMode(.inline)411            .toolbar {412                ToolbarItem(placement: .cancellationAction) {413                    Button(live.step == .status ? String(localized: "Fermer") : String(localized: "Annuler")) { if live.step == .review { confirmCancel = true } else { done(); dismiss() } }.accessibilityIdentifier("live.close")414                }415            }416            .confirmationDialog(String(localized: "Abandonner ce mandat ?"), isPresented: $confirmCancel, titleVisibility: .visible) {417                Button(String(localized: "Abandonner et fermer"), role: .destructive) { done(); dismiss() }418                Button(String(localized: "Continuer la revue"), role: .cancel) {}419            } message: { Text(String(localized: "Rien n’a été signé. Un mandat créé mais non approuvé n’autorise rien ; il se retire dans « Risque et limites ».")) }420            .task { if live.readiness == nil, model.canOperate { await live.loadAccounts(model.env, id: agent.id) } }421        }422        .interactiveDismissDisabled(live.step == .review || live.busy)423    }424425    private func networkWord(_ n: String?) -> String? {426        switch n { case "mainnet"?: String(localized: "MAINNET · argent réel"); case "testnet"?: String(localized: "TESTNET · argent de test"); case let n?: n; case nil: nil }427    }428429    private func stepRow(_ title: String, ok: Bool, reason: String?, code: String?) -> some View {430        HStack(alignment: .top, spacing: 10) {431            Image(systemName: ok ? "checkmark.circle.fill" : "xmark.circle.fill").foregroundStyle(ok ? Theme.emerald : Theme.danger).font(.system(size: 18)).padding(.top, 1)432            VStack(alignment: .leading, spacing: 2) {433                Text(title + " : " + (ok ? String(localized: "fait") : String(localized: "à faire"))).font(.spBody.weight(.medium)).foregroundStyle(Theme.ink)434                if let reason, !reason.isEmpty { Text(reason + (code.map { " (\($0))" } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true) }435            }436            Spacer(minLength: 0)437        }.padding(.vertical, 6).accessibilityElement(children: .combine)438    }439440    // MARK: checklist441442    @ViewBuilder private var checklist: some View {443        @Bindable var live = live444        if let r = live.readiness {445            if let lock = r.steps.mandate.lock {446                Notice(tone: .danger, title: String(localized: "Verrou du serveur : passage en réel impossible"), message: "\(lock.reason) (\(lock.code))").accessibilityIdentifier("live.perp.lock")447            }448            VStack(alignment: .leading, spacing: 8) {449                Text(String(localized: "Compte de la plateforme")).font(.spHeadline)450                if r.accounts.isEmpty {451                    Text(String(localized: "Aucun compte Hyperliquid n’est rattaché à ce portefeuille. Autorise et alimente un compte dans « Contrats à terme », puis reviens ici.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("live.perp.noaccount")452                }453                ForEach(r.accounts) { acct in454                    AgentCheckRow(title: (acct.label ?? acct.id) + " · " + (networkWord(acct.network) ?? acct.network),455                             subtitle: acct.account + (acct.equity.map { "\n" + String(localized: "valeur : \($0) USDC") } ?? "") + (acct.usedBy.map { "\n" + String(localized: "utilisé par l’agent \($0.name)") } ?? "") + (acct.error.map { "\n" + $0 } ?? ""),456                             on: live.form.accountId == acct.id, id: "live.perp.account.\(acct.network)") { live.form.accountId = live.form.accountId == acct.id ? nil : acct.id; live.readinessFor = nil }457                }458                LimitField(label: String(localized: "Durée du mandat (expiration obligatoire)"), text: $live.form.days, unit: String(localized: "jours"), hint: maxDays.map { String(localized: "Au plus \($0) jours sur ce serveur.") }, problem: live.form.daysProblem(maxDays: maxDays), integer: true, id: "live.perp.days")459                Button { Task { await live.check(model.env, id: agent.id) } } label: { HStack { if live.busy { ProgressView() }; Text(String(localized: "Lire la liste de contrôle pour ce compte")) } }460                    .buttonStyle(.spSecondary).disabled(!model.canOperate || live.busy || !live.form.canAskReadiness(maxDays: maxDays)).accessibilityIdentifier("live.perp.check")461            }.spCard()462            VStack(alignment: .leading, spacing: 0) {463                Text(String(localized: "Liste de contrôle du serveur") + (live.readinessFor == nil ? " · " + String(localized: "avant le choix du compte") : "")).font(.spHeadline).padding(.bottom, 4)464                stepRow(String(localized: "Stratégie approuvée"), ok: r.steps.strategy.ok, reason: r.steps.strategy.reason ?? r.steps.strategy.name.map { "\($0) v\(r.steps.strategy.version ?? "?")" }, code: nil)465                Divider()466                stepRow(String(localized: "Compte autorisé"), ok: r.steps.account.ok, reason: [r.steps.account.reason, r.steps.account.instrumentsMissing.flatMap { $0.isEmpty ? nil : String(localized: "contrats non autorisés : \($0.joined(separator: ", "))") }].compactMap { $0 }.joined(separator: " · "), code: r.steps.account.code)467                Divider()468                stepRow(String(localized: "Compte alimenté"), ok: r.steps.funded.ok, reason: [r.steps.funded.reason, r.steps.funded.equity.map { String(localized: "valeur \($0) USDC") }, r.steps.funded.minEquity.map { String(localized: "minimum \($0) USDC") }].compactMap { $0 }.joined(separator: " · "), code: r.steps.funded.code)469                Divider()470                stepRow(String(localized: "Mandat"), ok: r.steps.mandate.ok, reason: r.steps.mandate.phase.map { String(localized: "phase : \($0)") }, code: r.steps.mandate.lock?.code)471                Divider()472                FieldRow(label: String(localized: "Prochaine étape selon le serveur"), value: r.next).accessibilityIdentifier("live.perp.next")473            }.spCard()474            if live.readinessFor != nil, r.next == "mandate", let p = r.proposal {475                VStack(alignment: .leading, spacing: 0) {476                    Text(String(localized: "Mandat proposé par le serveur")).font(.spHeadline).padding(.bottom, 4)477                    FieldRow(label: String(localized: "Valeur du compte (référence des limites)"), value: Money.exact(p.capital) + " USDC")478                    ForEach(p.body.instruments, id: \.instrument) { i in Divider(); FieldRow(label: i.instrument, value: String(localized: "levier ≤ \(i.maxLeverage)× · position ≤ \(Money.exact(i.maxPositionNotional)) USDC")) }479                    Divider(); FieldRow(label: String(localized: "Plafond par ordre"), value: Money.exact(p.body.maxOrderNotional) + " USDC")480                    Divider(); FieldRow(label: String(localized: "Exposition brute maximale"), value: Money.exact(p.body.maxGrossExposure) + " USDC")481                    Divider(); FieldRow(label: String(localized: "Volume par jour, au plus"), value: Money.exact(p.body.maxDailyTurnover) + " USDC")482                    Divider(); FieldRow(label: String(localized: "Limite de perte : valeur plancher du compte"), value: Money.exact(p.body.floorEquity) + " USDC")483                    Divider(); FieldRow(label: String(localized: "Ordres par jour · par heure"), value: "\(p.body.maxOrdersPerDay) · \(p.body.maxOrdersPerHour)")484                    Divider(); FieldRow(label: String(localized: "Durée"), value: String(localized: "\(p.body.days) jours"))485                    ForEach(p.derived, id: \.field) { d in Divider(); FieldRow(label: String(localized: "\(d.field) — calculé depuis \(d.from)"), value: d.value) }486                    ForEach(p.notes, id: \.self) { n in Notice(tone: .info, title: n) }487                }.spCard()488                VStack(alignment: .leading, spacing: 10) {489                    LimitField(label: String(localized: "Levier maximal que tu autorises"), text: $live.form.maxLeverage, unit: "×", problem: live.form.leverageProblem(agent: agent), integer: true, id: "live.perp.leverage")490                }.spCard()491            }492            if let e = live.error { ErrorNotice(error: e).accessibilityIdentifier("live.error") }493            Button { Task { await live.prepare(model.env, agent: agent) } } label: { HStack { if live.busy { ProgressView().tint(Theme.onPrimary) }; Text(String(localized: "Préparer le mandat et le vérifier")) } }494                .buttonStyle(.spPrimary)495                .disabled(!model.canOperate || live.busy || r.steps.mandate.lock != nil || r.next != "mandate" || live.readinessFor == nil || !live.form.isComplete(agent: agent, maxDays: maxDays))496                .accessibilityIdentifier("live.perp.prepare")497            Text(String(localized: "Le bouton reste inactif tant que la liste de contrôle du serveur n’est pas complète pour le compte choisi, et tant que la durée et le levier ne sont pas saisis.")).font(.spFootnote).foregroundStyle(Theme.mute)498        } else if let e = live.error { ErrorNotice(error: e).accessibilityIdentifier("live.error") }499        else { ProgressView().frame(maxWidth: .infinity, minHeight: 160) }500    }501502    // MARK: review — both objects, the acknowledgement, the two prompts503504    private func fields(_ title: String, _ rows: [(String, String)], id: String) -> some View {505        VStack(alignment: .leading, spacing: 0) {506            Text(title).spEyebrow().padding(.bottom, 4)507            ForEach(Array(rows.enumerated()), id: \.offset) { i, r in508                if i > 0 { Divider() }509                FieldRow(label: r.0, value: r.1, mono: r.1.count > 24, copyable: r.1.count > 24)510            }511        }.spCard(padding: 16).accessibilityIdentifier(id)512    }513514    @ViewBuilder private var review: some View {515        @Bindable var live = live516        if let a = live.approval {517            let m = a.mandate518            if let w = a.warning { Notice(tone: .warn, title: String(localized: "Avertissement du serveur"), message: w) }519            VStack(alignment: .leading, spacing: 0) {520                Text(String(localized: "Résumé")).spEyebrow().padding(.bottom, 4)521                FieldRow(label: String(localized: "Compte de la plateforme"), value: m.account, mono: true, copyable: true)522                Divider(); FieldRow(label: String(localized: "Réseau"), value: networkWord(m.network) ?? m.network, tone: m.isMainnet ? .danger : .warn)523                ForEach(m.instruments, id: \.instrument) { i in Divider(); FieldRow(label: i.instrument, value: String(localized: "levier ≤ \(i.maxLeverage)× · position ≤ \(Money.exact(i.maxPositionNotional)) USDC")) }524                Divider(); FieldRow(label: String(localized: "Expire le"), value: AgentFmt.date(m.expiry))525                Divider(); FieldRow(label: String(localized: "Fin de la période de clôture après expiration ou arrêt"), value: AgentFmt.date(m.windDownEnd))526            }.spCard(padding: 16)527            fields(String(localized: "Objet 1/2 — mandat du signataire (tous les champs signés)"), m.fields(), id: "live.perp.object1")528            fields(String(localized: "Objet 2/2 — mandat de négociation complet (limites imposées par l’API comprises)"), a.tradingMandate.fields(), id: "live.perp.object2")529            VStack(alignment: .leading, spacing: 0) {530                Text(String(localized: "Intention d’approbation de l’API (lie les deux objets)")).spEyebrow().padding(.bottom, 4)531                JSONFields(value: a.binding.object.served)532            }.spCard(padding: 16)533            VStack(alignment: .leading, spacing: 8) {534                ServerDetail(title: String(localized: "Imposé par le signataire isolé"), value: a.enforcedBySigner)535                ServerDetail(title: String(localized: "Cru sur parole par le signataire"), value: a.trustedBySigner)536                ServerDetail(title: String(localized: "NON imposé"), value: a.notEnforced)537                ServerDetail(title: String(localized: "Champ par champ : signataire ou API"), value: a.enforcement)538                ServerDetail(title: String(localized: "Période de clôture"), value: a.windDown)539            }.spCard(padding: 16)540            VStack(alignment: .leading, spacing: 10) {541                Text(String(localized: "Texte à reconnaître, tel que servi")).spEyebrow()542                Text(a.acknowledgement.text).font(.spBody).foregroundStyle(Theme.ink).textSelection(.enabled).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("live.perp.ack.text")543                if let v = a.acknowledgement.version { Text(String(localized: "Version \(v)") + (a.acknowledgement.source.map { " · " + $0 } ?? "")).font(.spFootnote).foregroundStyle(Theme.mute) }544                FieldRow(label: String(localized: "Empreinte de ce texte, inscrite dans le mandat"), value: m.ackSha256, mono: true)545                AgentCheckRow(title: String(localized: "J’ai lu ce texte et je le reconnais."), on: live.acknowledged, id: "live.perp.ack") { live.acknowledged.toggle() }546            }.spCard(padding: 16)547            VStack(alignment: .leading, spacing: 8) {548                Text(String(localized: "Deux demandes de clé d’accès vont se suivre")).font(.spHeadline)549                FieldRow(label: String(localized: "1/2 — signataire : le mandat que le signataire isolé enregistre et impose"), value: a.signer.digest.hex, mono: true, copyable: true)550                FieldRow(label: String(localized: "2/2 — API : l’intention qui nomme le mandat de négociation complet et ce mandat du signataire"), value: a.binding.digest.hex, mono: true, copyable: true)551                Text(String(localized: "L’app a recalculé les deux empreintes à partir des champs affichés. Si tu annules l’une des deux demandes, rien n’est soumis.")).font(.spFootnote).foregroundStyle(Theme.mute)552            }.spCard(padding: 16)553            if let e = live.error { ErrorNotice(error: e).accessibilityIdentifier("live.error") }554            Button { Task { await live.approve(model.env) } } label: { HStack { if live.busy { ProgressView().tint(Theme.onPrimary) } else { Image(systemName: "person.badge.key.fill") }; Text(String(localized: "Approuver (2 demandes de clé d’accès)")) } }555                .buttonStyle(.spPrimary).disabled(live.busy || !live.acknowledged || !model.canOperate).accessibilityIdentifier("live.perp.approve")556        }557    }558559    @ViewBuilder private var status: some View {560        if let d = live.result {561            VStack(alignment: .leading, spacing: 10) {562                Text(String(localized: "Réponse du serveur")).spEyebrow()563                HStack(spacing: 8) { ModeBadgeView(badge: AgentModeBadge.of(d.agent)); StateLabelView(state: d.agent.state) }564                if d.agent.mode != .live { Notice(tone: .warn, title: String(localized: "L’agent n’est PAS en réel"), message: String(localized: "État rapporté : \(d.agent.state).")) }565                Text(d.execution.note).font(.spFootnote).foregroundStyle(Theme.mute)566            }.spCard()567            AgentCard(title: String(localized: "Mandat réel")) { PerpLiveBlockView(detail: d) }568        }569        Button(String(localized: "Terminer")) { done(); dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("live.done")570    }571}572
Files main
Menu

Theme