SPB Git

Repository Public

FuturesLiveAccounts.swift 40.7 KB 576 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/Futures/FuturesLiveAccounts.swift10// Description      : LIVE venue accounts as the server serves them: the server11//                    locks (which are open, which are closed, in the server's12//                    words), the jurisdiction notice text, the accounts and13//                    their state (READ_ONLY → MANUAL_LIVE…), account creation,14//                    the venue authorization (limits ALL typed by the owner →15//                    review of the verified canonical authorization in full16//                    with the acknowledgement text and an explicit checkbox →17//                    passkey), revocation, halt and cancel-all (never a18//                    passkey), resume / re-base / policy change (passkey over19//                    the verified risk intent).20// Module           : Features21// Repository       : https://git.spboucher.ai/sp-wallet-ios22// 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 FuturesLiveAccounts: View {101    @Environment(AppModel.self) private var model102    let fm: FuturesModel103    @State private var creating = false104    @State private var authorizing = false105    @State private var editingPolicy = false106    @State private var riskChange: RiskChangeSheet.Kind?107    @State private var confirmRevoke = false108    @State private var confirmHalt = false109    @State private var busy = false110    @State private var error: Error?111    @State private var notice: String?112    @State private var showJurisdiction = false113114    var body: some View {115        VStack(alignment: .leading, spacing: Theme.Space.section) {116            if !model.canOperate { Notice(tone: .warn, title: String(localized: "Comptes réels indisponibles hors ligne"), message: String(localized: "L’état d’un compte réel n’est lu que sur le serveur. Aucune opération n’est possible."), icon: "wifi.slash") }117            locksCard118            jurisdictionCard119            accountsCard120            if let a = fm.liveAccount { accountCard(a) }121            if let a = fm.liveAccount, a.venue == "hyperliquid" { FuturesCollateralCard(fm: fm, account: a) }122            GmxStatusRow(fm: fm)123            linksCard124        }125        .sheet(isPresented: $creating) { LiveAccountCreationSheet(fm: fm).wallet(model) }126        .sheet(isPresented: $authorizing) { Group { if let a = fm.liveAccount { AuthorizationSheet(fm: fm, account: a) } }.wallet(model) }127        .sheet(isPresented: $editingPolicy) { Group { if let a = fm.liveAccount { PolicyEditorSheet(fm: fm, target: .live(a), policy: a.policy) } }.wallet(model) }128        .sheet(item: Binding(get: { riskChange.map(RiskItem.init) }, set: { riskChange = $0?.kind })) { item in Group { if let a = fm.liveAccount { RiskChangeSheet(fm: fm, account: a, kind: item.kind) } }.wallet(model) }129        .confirmationDialog(String(localized: "Révoquer l’autorisation de trading ?"), isPresented: $confirmRevoke, titleVisibility: .visible) {130            Button(String(localized: "Révoquer et annuler les ordres au carnet"), role: .destructive) { Task { await revoke(cancelOrders: true) } }131            Button(String(localized: "Révoquer sans toucher aux ordres"), role: .destructive) { Task { await revoke(cancelOrders: false) } }132            Button(String(localized: "Ne rien faire"), role: .cancel) {}133        } message: { Text(String(localized: "Le compte revient en lecture seule. Les positions restent ouvertes. Aucune clé d’accès n’est demandée pour arrêter.")) }134        .confirmationDialog(String(localized: "Arrêter les nouveaux ordres sur ce compte ?"), isPresented: $confirmHalt, titleVisibility: .visible) {135            Button(String(localized: "Arrêter les nouveaux ordres"), role: .destructive) { Task { await halt() } }136            Button(String(localized: "Ne rien faire"), role: .cancel) {}137        } message: { Text(String(localized: "Aucun ordre n’est annulé et aucune position n’est fermée par cet arrêt. Le lever demandera ta clé d’accès.")) }138    }139140    private struct RiskItem: Identifiable { let kind: RiskChangeSheet.Kind; var id: Int { kind == .resume ? 0 : 1 } }141142    // MARK: locks, as served143144    private var locksCard: some View {145        VStack(alignment: .leading, spacing: 8) {146            SectionHeader(title: String(localized: "Verrous du serveur"))147            if let c = fm.liveConfig {148                lockRow(title: String(localized: "Trading réel sur mainnet"), setting: "SPW_DERIV_LIVE_MAINNET", open: c.mainnet?.enabled ?? c.mainnetEnabled, code: c.mainnet?.code, reason: c.mainnet?.reason, id: "futures.lock.mainnet")149                Divider()150                if !c.mandateLive.available {151                    lockRow(title: String(localized: "Mandats automatiques"), setting: nil, open: false, code: c.mandateLive.code, reason: c.mandateLive.reason, id: "futures.lock.mandate")152                } else {153                    lockRow(title: String(localized: "Mandats automatiques sur mainnet"), setting: "SPW_DERIV_MANDATE_MAINNET", open: c.mandateLive.mainnet?.enabled ?? false, code: c.mandateLive.mainnet?.code, reason: c.mandateLive.mainnet?.reason, id: "futures.lock.mandate")154                }155                Divider()156                FieldRow(label: String(localized: "Réseaux servis"), value: c.venues.map { "\(OfferedVenues.name($0.venue)) : \($0.networks.map(FuturesAccountRef.networkBadge).joined(separator: ", "))" }.joined(separator: " · "))157                FieldRow(label: String(localized: "Modes de compte servis"), value: c.modes.map(FuturesText.accountMode).joined(separator: ", "))158                Text(String(localized: "Un verrou est un réglage du serveur : il ne s’ouvre pas depuis l’app. Table d’instruments épinglée le \(c.pinnedAssets.pinnedAt).")).font(.system(size: 12)).foregroundStyle(Theme.mute)159            } else if let e = fm.liveConfigError { FuturesError(error: e) { Task { await fm.loadLive() } } }160            else if model.canOperate { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }161            else { Text(String(localized: "Verrous illisibles hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }162        }163        .spCard()164    }165166    private func lockRow(title: String, setting: String?, open: Bool, code: String?, reason: String?, id: String) -> some View {167        VStack(alignment: .leading, spacing: 4) {168            HStack(alignment: .firstTextBaseline) {169                Text(title).font(.spCallout.weight(.semibold))170                Spacer()171                Pill(text: open ? String(localized: "verrou ouvert") : String(localized: "verrou serveur fermé"), tone: open ? .ok : .warn, icon: open ? "lock.open.fill" : "lock.fill")172            }173            if let setting { Text(setting).font(.system(size: 11.5, design: .monospaced)).foregroundStyle(Theme.mute) }174            if !open {175                Text((reason ?? String(localized: "Le serveur n’a pas donné de phrase pour ce verrou.")) + (code.map { " (\($0))" } ?? "")).font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)176            }177        }178        .padding(.vertical, 4)179        .accessibilityElement(children: .combine).accessibilityIdentifier(id)180    }181182    // MARK: jurisdiction text, as served183184    @ViewBuilder private var jurisdictionCard: some View {185        if let j = fm.jurisdiction {186            let ack = FuturesText.locale == "en" ? j.en : j.fr187            VStack(alignment: .leading, spacing: 8) {188                SectionHeader(title: String(localized: "Avis de juridiction"), action: (title: showJurisdiction ? String(localized: "Replier") : String(localized: "Lire en entier"), run: { showJurisdiction.toggle() }))189                Text(ack.text).font(.spFootnote).foregroundStyle(Theme.ink).lineLimit(showJurisdiction ? nil : 5).fixedSize(horizontal: false, vertical: true).textSelection(.enabled)190                    .accessibilityIdentifier("futures.jurisdiction.text")191                Text(String(localized: "Texte servi par le serveur") + (ack.version.map { " · version \($0)" } ?? "") + (ack.source.map { " · \($0)" } ?? "") + ". " + String(localized: "Information générale, pas un avis juridique."))192                    .font(.system(size: 12)).foregroundStyle(Theme.mute)193            }194            .spCard()195        }196    }197198    // MARK: accounts199200    private var accountsCard: some View {201        VStack(alignment: .leading, spacing: 8) {202            SectionHeader(title: String(localized: "Comptes réels"))203            if let all = fm.liveAccounts {204                if all.isEmpty { Text(String(localized: "Aucun compte réel. Un compte est créé en lecture seule : il ne négocie rien tant que tu ne l’autorises pas.")).font(.spCallout).foregroundStyle(Theme.mute).accessibilityIdentifier("futures.live.none") }205                ForEach(all) { a in206                    Button { Task { await fm.selectLive(a.id) } } label: {207                        HStack(spacing: 10) {208                            Image(systemName: fm.liveID == a.id ? "largecircle.fill.circle" : "circle").foregroundStyle(fm.liveID == a.id ? Theme.blue : Theme.mute)209                            VStack(alignment: .leading, spacing: 3) {210                                Text(a.label).font(.system(size: 15.5, weight: .semibold)).foregroundStyle(Theme.ink).lineLimit(1)211                                HStack(spacing: 6) {212                                    Pill(text: FuturesAccountRef.networkBadge(a.network), tone: a.isMainnet ? .danger : .warn)213                                    Pill(text: FuturesText.accountMode(a.mode.rawValue), tone: a.mode == .readOnly ? .neutral : .info)214                                    if a.halted != nil { Pill(text: String(localized: "arrêté"), tone: .danger, icon: "hand.raised.fill") }215                                }216                            }217                            Spacer()218                        }219                        .frame(minHeight: 54).contentShape(Rectangle())220                    }221                    .buttonStyle(.plain).accessibilityIdentifier("futures.live.account.\(a.network)").accessibilityAddTraits(fm.liveID == a.id ? .isSelected : [])222                }223            } else if let e = fm.liveError { FuturesError(error: e) { Task { await fm.loadLive() } } }224            else if model.canOperate { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }225            Button { creating = true } label: { Label(String(localized: "Créer un compte réel (lecture seule)"), systemImage: "plus") }226                .buttonStyle(.spSecondary).disabled(!model.canOperate || fm.liveConfig == nil).accessibilityIdentifier("futures.live.create")227        }228        .spCard()229    }230231    @ViewBuilder private func accountCard(_ a: LiveAccount) -> some View {232        VStack(alignment: .leading, spacing: 10) {233            ModeBand(mode: .live, network: a.network)234            VStack(alignment: .leading, spacing: 0) {235                FieldRow(label: String(localized: "État du compte"), value: FuturesText.accountMode(a.mode.rawValue) + " · " + (a.tradable ? String(localized: "peut ouvrir du risque") : String(localized: "ne peut pas ouvrir de risque")), tone: a.tradable ? .info : .neutral)236                    .accessibilityIdentifier("futures.live.state")237                Divider()238                FieldRow(label: String(localized: "Compte sur la plateforme (adresse de ce portefeuille)"), value: a.account, mono: true, copyable: true); Divider()239                FieldRow(label: String(localized: "Clé de trading dédiée (dans le signataire isolé)"), value: a.agentAddress, mono: true, copyable: true)240                if let h = a.halt { Divider(); FieldRow(label: String(localized: "Arrêt du propriétaire"), value: h, tone: .danger) }241                if let d = a.divergence { Divider(); FieldRow(label: String(localized: "Divergence avec la plateforme"), value: d, tone: .danger) }242                if a.isMainnet, !a.mainnetEnabled { Divider(); FieldRow(label: String(localized: "Verrou"), value: String(localized: "verrou serveur fermé : mainnet") + (fm.liveConfig?.mainnet?.reason.map { " — \($0)" } ?? ""), tone: .warn) }243            }244            if let e = fm.liveDetailError { FuturesError(error: e) { Task { await fm.loadLiveDetail() } } }245            if let s = fm.liveDetail?.venueState.state {246                HStack(alignment: .top, spacing: 10) {247                    StatTile(label: String(localized: "Valeur du compte"), value: Fx.usd(s.equity), tag: .live(a.id, network: a.network))248                    StatTile(label: String(localized: "Collatéral libre"), value: Fx.usd(s.freeCollateral))249                    StatTile(label: String(localized: "Retirable"), value: Fx.usd(s.withdrawable))250                }251            } else if let ve = fm.liveDetail?.venueState.error {252                Notice(tone: .warn, title: String(localized: "Plateforme illisible pour le moment"), message: ve)253            }254            authorizationBlock(a)255            if let m = a.mandate {256                Notice(tone: .info, title: String(localized: "Mandat automatique : \(m.phase)"), message: String(localized: "Agent \(m.agentId)") + (m.expiresAt.map { " · " + String(localized: "expire le \($0.formatted(date: .abbreviated, time: .shortened))") } ?? "") + ". " + String(localized: "Les mandats se gèrent dans Agents de trading."))257            }258            if let n = notice { Notice(tone: .info, title: n) }259            if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.live.error") }260            stopBlock(a)261            VStack(alignment: .leading, spacing: 0) {262                SectionHeader(title: String(localized: "Politique de risque du compte"), action: model.canOperate ? (title: String(localized: "Modifier"), run: { editingPolicy = true }) : nil).padding(.bottom, 6)263                PolicyRows(policy: a.policy)264            }265        }266        .spCard()267    }268269    @ViewBuilder private func authorizationBlock(_ a: LiveAccount) -> some View {270        if let z = a.authorization {271            VStack(alignment: .leading, spacing: 0) {272                HStack { Text(String(localized: "Autorisation de trading")).font(.spCallout.weight(.semibold)); Spacer(); Pill(text: z.expired ? String(localized: "expirée") : z.active ? String(localized: "active") : String(localized: "inactive"), tone: z.active && !z.expired ? .ok : .warn) }.padding(.bottom, 4)273                FieldRow(label: String(localized: "Instruments permis"), value: z.policy.allowedInstruments.joined(separator: ", "), mono: true); Divider()274                FieldRow(label: String(localized: "Levier maximal que le signataire signera"), value: "\(z.policy.maxLeverage)×"); Divider()275                FieldRow(label: String(localized: "Notionnel max. par ordre · par position · exposition brute"), value: "\(Fx.usd(z.policy.maxOrderNotional, exact: true)) · \(Fx.usd(z.policy.maxPositionNotional, exact: true)) · \(Fx.usd(z.policy.maxGrossExposure, exact: true))"); Divider()276                FieldRow(label: String(localized: "Ordres par jour · écart de prix maximal"), value: "\(z.policy.maxOrdersPerDay) · \(z.policy.maxPriceDeviationBps) pb"); Divider()277                FieldRow(label: String(localized: "Expire le"), value: z.expiresAt?.formatted(date: .abbreviated, time: .shortened) ?? "—", tone: z.expired ? .danger : nil)278            }279            Button(role: .destructive) { confirmRevoke = true } label: { Label(String(localized: "Révoquer l’autorisation"), systemImage: "xmark.shield") }280                .buttonStyle(.spSecondary).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.live.revoke")281        } else {282            Notice(tone: .neutral, title: String(localized: "Aucune autorisation de trading"), message: String(localized: "Compte en lecture seule : il ne peut rien négocier. L’autoriser fixe des limites que le signataire isolé fera respecter."))283        }284        if a.pendingAuthorization != nil {285            Notice(tone: .warn, title: String(localized: "Une autorisation est en attente côté signataire"), message: String(localized: "La réponse du signataire a peut-être été perdue. « Récupérer » adopte ce que ta clé d’accès a approuvé, ou le retire. Aucune clé d’accès n’est demandée."))286            Button(String(localized: "Récupérer l’autorisation")) { Task { await recover() } }.buttonStyle(.spSecondary).disabled(busy || !model.canOperate)287        }288        Button { authorizing = true } label: { Label(a.authorization == nil ? String(localized: "Autoriser le trading manuel…") : String(localized: "Nouvelle autorisation (remplace l’actuelle)…"), systemImage: "person.badge.key") }289            .buttonStyle(.spSecondary).disabled(!model.canOperate).accessibilityIdentifier("futures.live.authorize")290    }291292    @ViewBuilder private func stopBlock(_ a: LiveAccount) -> some View {293        HStack(spacing: 8) {294            Button(role: .destructive) { confirmHalt = true } label: { Label(String(localized: "Arrêter les nouveaux ordres"), systemImage: "hand.raised.fill").frame(maxWidth: .infinity, minHeight: 44) }295                .buttonStyle(.bordered).disabled(busy || !model.canOperate || a.halt != nil).accessibilityIdentifier("futures.live.halt")296            if a.halt != nil {297                Button { riskChange = .resume } label: { Label(String(localized: "Lever l’arrêt…"), systemImage: "play.fill").frame(maxWidth: .infinity, minHeight: 44) }298                    .buttonStyle(.bordered).disabled(!model.canOperate).accessibilityIdentifier("futures.live.resume")299            }300        }301        if a.divergence != nil {302            Button { riskChange = .rebase } label: { Label(String(localized: "Accepter les positions de la plateforme comme référence…"), systemImage: "arrow.triangle.merge") }303                .buttonStyle(.spSecondary).disabled(!model.canOperate).accessibilityIdentifier("futures.live.rebase")304        }305        Text(String(localized: "« Annuler tout » et le rapprochement avec la plateforme sont dans l’onglet Positions.")).font(.system(size: 12)).foregroundStyle(Theme.mute)306    }307308    private var linksCard: some View {309        VStack(alignment: .leading, spacing: 8) {310            Button { model.router.go(.risk) } label: { Label(String(localized: "Limites globales et mandats : Risque et limites"), systemImage: AppSection.risk.icon).frame(maxWidth: .infinity, alignment: .leading) }.buttonStyle(.bordered).accessibilityIdentifier("futures.link.risk")311            Button { model.router.go(.agents) } label: { Label(String(localized: "Stratégies automatiques : Agents de trading"), systemImage: AppSection.agents.icon).frame(maxWidth: .infinity, alignment: .leading) }.buttonStyle(.bordered).accessibilityIdentifier("futures.link.agents")312        }313    }314315    // MARK: actions without a passkey (stopping)316317    private func run(_ work: () async throws -> Void) async {318        guard !busy else { return }319        busy = true; error = nil; notice = nil320        defer { busy = false }321        do { try await work() } catch { self.error = error }322    }323324    private func revoke(cancelOrders: Bool) async {325        guard let id = fm.liveID else { return }326        await run {327            let d = try await fm.liveAPI.revokeAuthorization(id, cancelOpenOrders: cancelOrders, locale: FuturesText.locale)328            fm.adopt(live: d)329            notice = [String(localized: "Autorisation révoquée : compte en lecture seule."), d.warning, d.cancelError.map { "\($0.message) (\($0.code))" },330                      d.cancelled.map { String(localized: "Ordres annulés : \($0.accepted) sur \($0.requested).") }].compactMap { $0 }.joined(separator: " ")331        }332    }333334    private func halt() async {335        guard let id = fm.liveID else { return }336        await run {337            let d = try await fm.liveAPI.halt(id, reason: String(localized: "Arrêt demandé par le propriétaire depuis l’app iOS"))338            fm.adopt(live: d)339            notice = d.note ?? String(localized: "Nouveaux ordres arrêtés.")340        }341    }342343    private func recover() async {344        guard let id = fm.liveID else { return }345        await run {346            let d = try await fm.liveAPI.recoverAuthorization(id)347            fm.adopt(live: d)348            notice = (d.recovered ?? []).map { "\($0.what) : \($0.outcome) — \($0.detail)" }.joined(separator: " ").isEmpty ? String(localized: "Rien à récupérer.") : (d.recovered ?? []).map { "\($0.what) : \($0.outcome) — \($0.detail)" }.joined(separator: " ")349        }350    }351}352353// MARK: creation354355struct LiveAccountCreationSheet: View {356    @Environment(AppModel.self) private var model357    @Environment(\.dismiss) private var dismiss358    let fm: FuturesModel359    @State private var network: String?360    @State private var label = ""361    @State private var busy = false362    @State private var error: Error?363364    private var networks: [String] { fm.liveConfig?.venues.first { $0.venue == "hyperliquid" }?.networks ?? [] }365366    var body: some View {367        NavigationStack {368            ScrollView {369                VStack(alignment: .leading, spacing: Theme.Space.section) {370                    ModeBand(mode: .live, network: network)371                    Notice(tone: .info, title: String(localized: "Créé en lecture seule"), message: String(localized: "Le compte est l’adresse de ce portefeuille sur Hyperliquid. Il ne négocie rien tant que tu n’as pas approuvé une autorisation avec ta clé d’accès."))372                    VStack(alignment: .leading, spacing: 12) {373                        Text(String(localized: "Réseau (rien n’est présélectionné)")).font(.spFootnote).foregroundStyle(Theme.mute)374                        ForEach(networks, id: \.self) { n in375                            Button { network = n } label: {376                                HStack {377                                    Image(systemName: network == n ? "largecircle.fill.circle" : "circle").foregroundStyle(network == n ? Theme.blue : Theme.mute)378                                    VStack(alignment: .leading, spacing: 2) {379                                        Text(FuturesAccountRef.networkBadge(n)).font(.system(size: 15, weight: .bold))380                                        Text(n == "testnet" ? String(localized: "Réseau de test : jetons sans valeur.") : String(localized: "Fonds réels.") + (fm.liveConfig?.mainnet?.enabled == false ? " " + String(localized: "Verrou serveur fermé.") : "")).font(.spFootnote).foregroundStyle(Theme.mute)381                                    }382                                    Spacer()383                                }384                                .frame(minHeight: 50).contentShape(Rectangle())385                            }386                            .buttonStyle(.plain).accessibilityIdentifier("futures.live.new.network.\(n)").accessibilityAddTraits(network == n ? .isSelected : [])387                        }388                        VStack(alignment: .leading, spacing: 5) {389                            Text(String(localized: "Nom du compte")).font(.spFootnote).foregroundStyle(Theme.mute)390                            TextField(String(localized: "à saisir"), text: $label).padding(.horizontal, 12).frame(minHeight: 46)391                                .background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("futures.live.new.label")392                        }393                    }394                    .spCard()395                    if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.live.new.error") }396                    Button { Task { await create() } } label: { BusyLabel(title: String(localized: "Créer le compte en lecture seule"), busy: busy) }397                        .buttonStyle(.spPrimary).disabled(busy || network == nil || label.trimmingCharacters(in: .whitespaces).isEmpty || !model.canOperate).accessibilityIdentifier("futures.live.new.submit")398                }399                .futuresSheetPage()400            }401            .spPage()402            .navigationTitle(String(localized: "Nouveau compte réel")).navigationBarTitleDisplayMode(.inline)403            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { dismiss() }.accessibilityIdentifier("futures.live.new.cancel") } }404        }405    }406407    private func create() async {408        guard let network, !busy else { return }409        busy = true; error = nil410        defer { busy = false }411        do { fm.adopt(live: try await fm.liveAPI.createAccount(network: network, label: label.trimmingCharacters(in: .whitespaces))); dismiss() }412        catch { self.error = error }413    }414}415416// MARK: venue authorization (READ_ONLY → MANUAL_LIVE)417418struct AuthorizationSheet: View {419    @Environment(AppModel.self) private var model420    @Environment(\.dismiss) private var dismiss421    let fm: FuturesModel422    let account: LiveAccount423424    @State private var instruments: Set<String> = []425    @State private var search = ""426    @State private var maxLeverage = ""427    @State private var maxOrderNotional = ""428    @State private var maxPositionNotional = ""429    @State private var maxGrossExposure = ""430    @State private var maxOrdersPerDay = ""431    @State private var maxPriceDeviationBps = ""432    @State private var days = ""433    @State private var prepared: LiveAuthorizationPreparation?434    @State private var acknowledged = false435    @State private var approved = false436    @State private var busy = false437    @State private var error: Error?438439    private var pinned: [LivePinnedAsset] { (account.network == "testnet" ? fm.liveConfig?.pinnedAssets.testnet : fm.liveConfig?.pinnedAssets.mainnet) ?? [] }440    private var bounds: LiveConfig.Bounds? { fm.liveConfig?.bounds }441    private func dec(_ s: String) -> String? { if case .success(let v) = DecimalInput.parse(s), v.isPositive { v.description } else { nil } }442    private var policy: VenuePolicy? {443        guard !instruments.isEmpty, let lev = DecimalInput.wholeNumber(maxLeverage), let o = dec(maxOrderNotional), let p = dec(maxPositionNotional), let g = dec(maxGrossExposure),444              let n = DecimalInput.wholeNumber(maxOrdersPerDay), let b = DecimalInput.wholeNumber(maxPriceDeviationBps) else { return nil }445        return VenuePolicy(allowedInstruments: instruments.sorted(), maxLeverage: lev, maxOrderNotional: o, maxPositionNotional: p, maxGrossExposure: g, maxOrdersPerDay: n, maxPriceDeviationBps: b)446    }447    private var duration: Int? { DecimalInput.wholeNumber(days) }448449    var body: some View {450        NavigationStack {451            ScrollView {452                VStack(alignment: .leading, spacing: Theme.Space.section) {453                    ModeBand(mode: .live, network: account.network)454                    if approved { Notice(tone: .ok, title: String(localized: "Autorisation enregistrée"), message: String(localized: "État du compte selon le serveur : \(FuturesText.accountMode(fm.liveAccount?.mode.rawValue ?? ""))."))455                        Button(String(localized: "Terminer")) { dismiss() }.buttonStyle(.spSecondary)456                    } else if let p = prepared { review(p) } else { form }457                }458                .futuresSheetPage()459            }460            .spPage()461            .navigationTitle(prepared == nil ? String(localized: "Autoriser le trading manuel") : String(localized: "Vérifier et approuver")).navigationBarTitleDisplayMode(.inline)462            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(approved ? String(localized: "Fermer") : String(localized: "Annuler")) { dismiss() }.accessibilityIdentifier("futures.auth.cancel") } }463        }464        .interactiveDismissDisabled(prepared != nil && !approved)465    }466467    @ViewBuilder private var form: some View {468        Text(String(localized: "Ces limites seront appliquées par le signataire isolé à chaque ordre de ce compte. Toutes sont à saisir : rien n’est présélectionné.")).font(.spFootnote).foregroundStyle(Theme.mute)469        VStack(alignment: .leading, spacing: 10) {470            Text(String(localized: "Instruments permis (\(instruments.count) choisi(s))")).font(.spCallout.weight(.semibold))471            if !instruments.isEmpty { Text(instruments.sorted().joined(separator: ", ")).font(.spMono).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("futures.auth.chosen") }472            TextField(String(localized: "Rechercher dans la table épinglée"), text: $search).textInputAutocapitalization(.characters).autocorrectionDisabled()473                .padding(.horizontal, 12).frame(minHeight: 44).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("futures.auth.search")474            let q = search.trimmingCharacters(in: .whitespaces).uppercased()475            let rows = pinned.filter { q.isEmpty ? instruments.contains($0.instrument) : OfferedVenues.symbol(of: $0.instrument).uppercased().contains(q) }.prefix(12)476            ForEach(Array(rows), id: \.self) { a in477                Button { if instruments.contains(a.instrument) { instruments.remove(a.instrument) } else { instruments.insert(a.instrument) } } label: {478                    HStack {479                        Image(systemName: instruments.contains(a.instrument) ? "checkmark.square.fill" : "square").foregroundStyle(instruments.contains(a.instrument) ? Theme.blue : Theme.mute)480                        Text(a.instrument).font(.spMono).foregroundStyle(Theme.ink)481                        Spacer()482                        Text(String(localized: "max plateforme \(a.maxLeverage)×")).font(.system(size: 12)).foregroundStyle(Theme.mute)483                    }484                    .frame(minHeight: 40).contentShape(Rectangle())485                }486                .buttonStyle(.plain).accessibilityIdentifier("futures.auth.instrument.\(OfferedVenues.symbol(of: a.instrument))")487            }488            if q.isEmpty, instruments.isEmpty { Text(String(localized: "Cherche un symbole (BTC, ETH…) pour l’ajouter. \(pinned.count) instruments dans la table épinglée du serveur.")).font(.system(size: 12)).foregroundStyle(Theme.mute) }489        }490        .spCard()491        VStack(alignment: .leading, spacing: 12) {492            TypedField(label: String(localized: "Levier maximal que le signataire signera"), text: $maxLeverage, unit: "×", hint: bounds?.maxLeverage.map { String(localized: "Borne du serveur : \($0)×.") }, integer: true, id: "futures.auth.maxLeverage")493            TypedField(label: String(localized: "Notionnel maximal par ordre"), text: $maxOrderNotional, unit: "$", id: "futures.auth.maxOrder")494            TypedField(label: String(localized: "Notionnel maximal par position"), text: $maxPositionNotional, unit: "$", id: "futures.auth.maxPosition")495            TypedField(label: String(localized: "Exposition brute maximale"), text: $maxGrossExposure, unit: "$", id: "futures.auth.maxGross")496            TypedField(label: String(localized: "Ordres par jour"), text: $maxOrdersPerDay, hint: bounds?.maxOrdersPerDay.map { String(localized: "Borne du serveur : \($0).") }, integer: true, id: "futures.auth.ordersPerDay")497            TypedField(label: String(localized: "Écart de prix maximal par rapport à la référence"), text: $maxPriceDeviationBps, unit: String(localized: "pb"),498                       hint: (bounds?.minPriceBandBps).flatMap { lo in bounds?.maxPriceBandBps.map { String(localized: "Bornes du serveur : \(lo) à \($0) pb.") } }, integer: true, id: "futures.auth.deviation")499            TypedField(label: String(localized: "Durée de l’autorisation"), text: $days, unit: String(localized: "jours"), hint: bounds?.maxAuthorizationDays.map { String(localized: "Borne du serveur : \($0) jours.") }, integer: true, id: "futures.auth.days")500        }501        .spCard()502        if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.auth.error") }503        Button { Task { await prepare() } } label: { BusyLabel(title: String(localized: "Préparer l’autorisation"), busy: busy) }504            .buttonStyle(.spPrimary).disabled(busy || policy == nil || duration == nil || !model.canOperate).accessibilityIdentifier("futures.auth.prepare")505        Text(String(localized: "Rien n’est signé à cette étape : le serveur prépare l’autorisation, l’app la vérifie, puis tu la relis en entier.")).font(.spFootnote).foregroundStyle(Theme.mute)506    }507508    @ViewBuilder private func review(_ p: LiveAuthorizationPreparation) -> some View {509        let z = p.authorization510        VStack(alignment: .leading, spacing: 4) {511            Text(String(localized: "Autorisation de trading · \(OfferedVenues.name(z.venue)) · \(FuturesAccountRef.networkBadge(z.network))")).spEyebrow()512            Text(String(localized: "Passer ce compte en \(FuturesText.accountMode(z.mode))")).font(.system(size: 26, weight: .semibold)).tracking(-0.5).fixedSize(horizontal: false, vertical: true)513                .accessibilityIdentifier("futures.auth.review.title")514        }515        Rows {516            Text(String(localized: "Limites que le signataire fera respecter")).spEyebrow().padding(.bottom, 4)517            FieldRow(label: String(localized: "Instruments permis"), value: z.policy.allowedInstruments.joined(separator: ", "), mono: true); Divider()518            FieldRow(label: String(localized: "Levier maximal"), value: "\(z.policy.maxLeverage)×"); Divider()519            FieldRow(label: String(localized: "Notionnel maximal par ordre"), value: Fx.usd(z.policy.maxOrderNotional, exact: true)); Divider()520            FieldRow(label: String(localized: "Notionnel maximal par position"), value: Fx.usd(z.policy.maxPositionNotional, exact: true)); Divider()521            FieldRow(label: String(localized: "Exposition brute maximale"), value: Fx.usd(z.policy.maxGrossExposure, exact: true)); Divider()522            FieldRow(label: String(localized: "Ordres par jour"), value: String(z.policy.maxOrdersPerDay)); Divider()523            FieldRow(label: String(localized: "Écart de prix maximal"), value: "\(z.policy.maxPriceDeviationBps) pb")524        }525        Rows {526            FieldRow(label: String(localized: "Compte sur la plateforme (adresse de ce portefeuille)"), value: z.account, mono: true, copyable: true); Divider()527            FieldRow(label: String(localized: "Clé de trading autorisée · nom"), value: "\(z.agentAddress) · \(z.agentName)", mono: true, copyable: true); Divider()528            FieldRow(label: String(localized: "Valable du · au"), value: "\(Date(timeIntervalSince1970: TimeInterval(z.createdAt)).formatted(date: .abbreviated, time: .shortened)) · \(z.expiry.formatted(date: .abbreviated, time: .shortened))"); Divider()529            FieldRow(label: String(localized: "Identifiant · clé du signataire"), value: "\(z.authorizationId) · \(z.keyId)", mono: true); Divider()530            FieldRow(label: String(localized: "Nonce de l’action approveAgent signée par la clé du portefeuille"), value: String(z.approveNonce), mono: true); Divider()531            FieldRow(label: String(localized: "Empreinte du texte de juridiction"), value: z.ackSha256, mono: true); Divider()532            FieldRow(label: String(localized: "Empreinte de l’autorisation (défi signé par la clé d’accès)"), value: p.approval.digest.hex, mono: true, copyable: true)533        }534        if let g = p.agent {535            Rows {536                Text(String(localized: "La clé de trading dédiée, selon le serveur")).spEyebrow().padding(.bottom, 4)537                if let can = g.can, !can.isEmpty { FieldRow(label: String(localized: "Elle peut"), value: can.joined(separator: "\n")); Divider() }538                if let cannot = g.cannot, !cannot.isEmpty { FieldRow(label: String(localized: "Elle ne peut pas"), value: cannot.joined(separator: "\n")); Divider() }539                if let n = g.note { FieldRow(label: String(localized: "Note"), value: n) }540            }541        }542        if let w = p.whatIsSigned {543            Rows {544                if let m = w.byMainKey { FieldRow(label: String(localized: "Signé par la clé du portefeuille"), value: m); Divider() }545                if let k = w.byPasskey { FieldRow(label: String(localized: "Signé par ta clé d’accès"), value: k) }546            }547        }548        VStack(alignment: .leading, spacing: 8) {549            Text(String(localized: "Avis de juridiction (texte du serveur, engagé par l’autorisation)")).spEyebrow()550            Text(p.acknowledgement.text).font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true).textSelection(.enabled).accessibilityIdentifier("futures.auth.ack.text")551            CheckRow(isOn: $acknowledged, text: String(localized: "J’ai lu cet avis en entier et je décide moi-même d’activer le trading réel sur ce compte."), tone: .danger, id: "futures.auth.ack")552        }553        .spCard()554        if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.auth.error") }555        Button { Task { await approve(p) } } label: { BusyLabel(title: String(localized: "Approuver avec la clé d’accès"), icon: "person.badge.key.fill", busy: busy) }556            .buttonStyle(.spPrimary).disabled(busy || !acknowledged || !model.canOperate).accessibilityIdentifier("futures.auth.approve")557        Button(String(localized: "Ne pas approuver")) { dismiss() }.buttonStyle(.spSecondary).disabled(busy).accessibilityIdentifier("futures.auth.decline")558    }559560    private func prepare() async {561        guard let policy, let duration, !busy else { return }562        busy = true; error = nil563        defer { busy = false }564        do { prepared = try await fm.liveAPI.prepareAuthorization(for: account, policy: policy, days: duration, locale: FuturesText.locale); acknowledged = false }565        catch { self.error = error }566    }567568    private func approve(_ p: LiveAuthorizationPreparation) async {569        guard !busy else { return }570        busy = true; error = nil571        defer { busy = false }572        do { fm.adopt(live: try await fm.liveAPI.approveAuthorization(p, acknowledged: acknowledged, with: model.env.passkeys)); approved = true }573        catch PasskeyError.cancelled {} catch { self.error = error }574    }575}576
Files main
Menu

Theme