SPB Git

Repository Public

FuturesPolicy.swift 20.4 KB 317 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet9// File             : Features/Futures/FuturesPolicy.swift10// Description      : The API-side risk policy of a derivatives account (paper11//                    or live): shown in full as served, edited field by field,12//                    and — on a live account — the passkey approval of a change13//                    that loosens anything, of lifting the owner's halt and of14//                    re-basing after a divergence, each over the verified risk15//                    intent displayed in full. Tightening is free; stopping16//                    never needs a passkey. Global wallet limits and trading17//                    mandates live in Risque et limites / Agents.18// Module           : Features19// Repository       : https://git.spboucher.ai/sp-wallet-ios20// Created          : 2026-11-1821// Last Modified    : 2026-11-1822//23// =============================================================================24// AUTHOR & PROFESSIONAL AFFILIATION25// =============================================================================26//27// Author           : Simon-Pierre Boucher28// Position         : Professor of Finance29// Institution      : Université du Québec en Outaouais (UQO)30// Department       : Département des sciences administratives31// Organization     : SP Boucher32//33// Website          : https://spboucher.ai34// Git              : https://git.spboucher.ai35//36// =============================================================================37// OFFICIAL CONTACT DIRECTORY38// =============================================================================39//40// General          : info@spboucher.ai41// Professional     : contact@spboucher.ai42// Direct           : simon@spboucher.ai43// Research         : research@spboucher.ai44// Development      : dev@spboucher.ai45// Support          : support@spboucher.ai46// Security/Admin   : admin@spboucher.ai47// Notifications    : notifications@spboucher.ai48//49// Preferred Contact: support@spboucher.ai50//51// =============================================================================52// COPYRIGHT & INTELLECTUAL PROPERTY53// =============================================================================54//55// Copyright (c) 202656// Simon-Pierre Boucher57//58// All rights reserved where applicable.59//60// This file is governed by the applicable project license,61// copyright notices, institutional agreements and relevant law.62//63// Unless expressly authorized by the applicable license or64// rights holder, copying, redistribution, sublicensing,65// publication and commercial exploitation are not permitted.66//67// Existing third-party rights and notices remain unaffected.68//69// =============================================================================70// CONFIDENTIALITY & SECURITY71// =============================================================================72//73// Classification   : Public74// Distribution     : Public repository; use is governed by the project license75// Security Contact : admin@spboucher.ai76//77// Access to this source does not independently grant permission78// to redistribute or disclose confidential materials.79//80// Do not embed credentials, private keys, access tokens,81// certificates or confidential personal information.82//83// =============================================================================84// LICENSE & MAINTENANCE85// =============================================================================86//87// License          : None specified (no license file in this repository)88// Maintainer       : Simon-Pierre Boucher89// Technical Contact: dev@spboucher.ai90//91// =============================================================================92// END OF SP BOUCHER SOURCE HEADER93// =============================================================================9495import SwiftUI96import SPWalletCore9798/** The editable text of a policy. It starts from the policy IN FORCE (the server's values), never from suggestions. */99struct PolicyDraft: Equatable {100    var instruments: String101    var maxLeverage, maxOrderNotional, maxGrossExposure, maxPositionNotional, minFreeCollateral, minLiquidationDistanceBps, maxDailyLoss, maxTotalLoss: String102    var maxOrdersPerMinute, maxOrdersPerDay, maxDataAgeMs, maxDeviationBps, maxMarkIndexBps: String103    let mode: String104    let halt: String?105106    init(_ p: DerivRiskPolicy) {107        instruments = p.allowedInstruments.joined(separator: ", ")108        maxLeverage = p.maxLeverage; maxOrderNotional = p.maxOrderNotional; maxGrossExposure = p.maxGrossExposure; maxPositionNotional = p.maxPositionNotional109        minFreeCollateral = p.minFreeCollateral; minLiquidationDistanceBps = p.minLiquidationDistanceBps; maxDailyLoss = p.maxDailyLoss; maxTotalLoss = p.maxTotalLoss110        maxOrdersPerMinute = String(p.maxOrdersPerMinute); maxOrdersPerDay = String(p.maxOrdersPerDay); maxDataAgeMs = String(p.maxDataAgeMs)111        maxDeviationBps = p.maxDeviationBps; maxMarkIndexBps = p.maxMarkIndexBps112        mode = p.mode; halt = p.halt113    }114115    /** nil while a field is not a number the server could read. Decimals are sent in canonical form, nothing is rounded. */116    func build(decimalSeparator: String = Locale.current.decimalSeparator ?? ".") -> DerivRiskPolicy? {117        func dec(_ s: String) -> String? { if case .success(let v) = DecimalInput.parse(s, decimalSeparator: decimalSeparator) { v.description } else { nil } }118        let ids = instruments.split(whereSeparator: { $0 == "," || $0 == " " || $0 == "\n" }).map(String.init).filter { !$0.isEmpty }119        guard let lev = dec(maxLeverage), let mon = dec(maxOrderNotional), let mge = dec(maxGrossExposure), let mpn = dec(maxPositionNotional), let mfc = dec(minFreeCollateral),120              let mld = dec(minLiquidationDistanceBps), let mdl = dec(maxDailyLoss), let mtl = dec(maxTotalLoss), let dev = dec(maxDeviationBps), let mi = dec(maxMarkIndexBps),121              let opm = DecimalInput.wholeNumber(maxOrdersPerMinute), let opd = DecimalInput.wholeNumber(maxOrdersPerDay), let age = DecimalInput.wholeNumber(maxDataAgeMs) else { return nil }122        return DerivRiskPolicy(mode: mode, allowedInstruments: ids, halt: halt, maxDataAgeMs: age, maxDeviationBps: dev, maxMarkIndexBps: mi, maxLeverage: lev, maxOrderNotional: mon,123                               maxGrossExposure: mge, maxPositionNotional: mpn, minFreeCollateral: mfc, minLiquidationDistanceBps: mld, maxDailyLoss: mdl, maxTotalLoss: mtl,124                               maxOrdersPerMinute: opm, maxOrdersPerDay: opd)125    }126}127128/** Every field of a risk policy, as served. */129struct PolicyRows: View {130    let policy: DerivRiskPolicy131    var body: some View {132        FieldRow(label: String(localized: "Mode"), value: FuturesText.accountMode(policy.mode)); Divider()133        FieldRow(label: String(localized: "Instruments permis"), value: policy.allowedInstruments.isEmpty ? String(localized: "aucune liste (tous ceux de la plateforme)") : policy.allowedInstruments.joined(separator: ", "), mono: !policy.allowedInstruments.isEmpty); Divider()134        if let h = policy.halt { FieldRow(label: String(localized: "Arrêt"), value: h, tone: .danger); Divider() }135        FieldRow(label: String(localized: "Levier maximal"), value: Fx.leverage(policy.maxLeverage)); Divider()136        FieldRow(label: String(localized: "Notionnel maximal par ordre"), value: Fx.usd(policy.maxOrderNotional, exact: true)); Divider()137        FieldRow(label: String(localized: "Notionnel maximal par position"), value: Fx.usd(policy.maxPositionNotional, exact: true)); Divider()138        FieldRow(label: String(localized: "Exposition brute maximale"), value: Fx.usd(policy.maxGrossExposure, exact: true)); Divider()139        FieldRow(label: String(localized: "Collatéral libre minimal"), value: Fx.usd(policy.minFreeCollateral, exact: true)); Divider()140        FieldRow(label: String(localized: "Distance minimale à la liquidation"), value: Fx.exact(policy.minLiquidationDistanceBps) + " " + String(localized: "pb")); Divider()141        FieldRow(label: String(localized: "Perte maximale par jour · au total"), value: "\(Fx.usd(policy.maxDailyLoss, exact: true)) · \(Fx.usd(policy.maxTotalLoss, exact: true))"); Divider()142        FieldRow(label: String(localized: "Ordres par minute · par jour"), value: "\(policy.maxOrdersPerMinute) · \(policy.maxOrdersPerDay)"); Divider()143        FieldRow(label: String(localized: "Âge maximal des données · écart de prix · écart marque/indice"), value: "\(policy.maxDataAgeMs) ms · \(Fx.exact(policy.maxDeviationBps)) pb · \(Fx.exact(policy.maxMarkIndexBps)) pb")144    }145}146147/** Edits the policy of a paper account (applied at once) or of a live account (free when tighter; passkey when looser). */148struct PolicyEditorSheet: View {149    enum Target { case paper(PaperAccountID), live(LiveAccount) }150    @Environment(AppModel.self) private var model151    @Environment(\.dismiss) private var dismiss152    let fm: FuturesModel153    let target: Target154    @State var draft: PolicyDraft155    @State private var busy = false156    @State private var error: Error?157    @State private var approval: LiveRiskApproval?158159    init(fm: FuturesModel, target: Target, policy: DerivRiskPolicy) { self.fm = fm; self.target = target; _draft = State(initialValue: PolicyDraft(policy)) }160161    var body: some View {162        NavigationStack {163            ScrollView {164                VStack(alignment: .leading, spacing: Theme.Space.section) {165                    if case .live(let a) = target { ModeBand(mode: .live, network: a.network) } else { ModeBand(mode: .paper) }166                    if let a = approval, case .live(let account) = target {167                        RiskIntentReview(fm: fm, account: account, approval: a) { dismiss() }168                    } else {169                        Text(String(localized: "Valeurs en vigueur, modifiables une à une. Le serveur valide l’ensemble.")).font(.spFootnote).foregroundStyle(Theme.mute)170                        VStack(alignment: .leading, spacing: 12) {171                            VStack(alignment: .leading, spacing: 5) {172                                Text(String(localized: "Instruments permis (identifiants séparés par des virgules ; vide = aucune liste)")).font(.spFootnote).foregroundStyle(Theme.mute)173                                TextField("hyperliquid:BTC, hyperliquid:ETH", text: $draft.instruments, axis: .vertical).font(.spMono).textInputAutocapitalization(.never).autocorrectionDisabled()174                                    .padding(12).background(Theme.elev, in: RoundedRectangle(cornerRadius: Theme.Radius.small)).accessibilityIdentifier("futures.policy.instruments")175                            }176                            TypedField(label: String(localized: "Levier maximal"), text: $draft.maxLeverage, unit: "×", id: "futures.policy.maxLeverage")177                            TypedField(label: String(localized: "Notionnel maximal par ordre"), text: $draft.maxOrderNotional, unit: "$", id: "futures.policy.maxOrderNotional")178                            TypedField(label: String(localized: "Notionnel maximal par position"), text: $draft.maxPositionNotional, unit: "$", id: "futures.policy.maxPositionNotional")179                            TypedField(label: String(localized: "Exposition brute maximale"), text: $draft.maxGrossExposure, unit: "$", id: "futures.policy.maxGrossExposure")180                            TypedField(label: String(localized: "Collatéral libre minimal"), text: $draft.minFreeCollateral, unit: "$", id: "futures.policy.minFreeCollateral")181                            TypedField(label: String(localized: "Distance minimale à la liquidation"), text: $draft.minLiquidationDistanceBps, unit: String(localized: "pb"), id: "futures.policy.minLiq")182                            TypedField(label: String(localized: "Perte maximale par jour"), text: $draft.maxDailyLoss, unit: "$", id: "futures.policy.maxDailyLoss")183                            TypedField(label: String(localized: "Perte maximale au total"), text: $draft.maxTotalLoss, unit: "$", id: "futures.policy.maxTotalLoss")184                            TypedField(label: String(localized: "Ordres par minute"), text: $draft.maxOrdersPerMinute, integer: true, id: "futures.policy.opm")185                            TypedField(label: String(localized: "Ordres par jour"), text: $draft.maxOrdersPerDay, integer: true, id: "futures.policy.opd")186                            TypedField(label: String(localized: "Âge maximal des données"), text: $draft.maxDataAgeMs, unit: "ms", integer: true, id: "futures.policy.age")187                            TypedField(label: String(localized: "Écart de prix maximal"), text: $draft.maxDeviationBps, unit: String(localized: "pb"), id: "futures.policy.dev")188                            TypedField(label: String(localized: "Écart marque / indice maximal"), text: $draft.maxMarkIndexBps, unit: String(localized: "pb"), id: "futures.policy.markIndex")189                        }190                        .spCard()191                        if draft.build() == nil { Label(String(localized: "Un champ n’est pas un nombre valide."), systemImage: "exclamationmark.triangle.fill").font(.spFootnote).foregroundStyle(Theme.danger) }192                        if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.policy.error") }193                        Button { Task { await save() } } label: { BusyLabel(title: String(localized: "Enregistrer la politique"), busy: busy) }194                            .buttonStyle(.spPrimary).disabled(busy || draft.build() == nil || !model.canOperate).accessibilityIdentifier("futures.policy.save")195                        if case .live = target { Text(String(localized: "Resserrer une limite est immédiat. Tout assouplissement te sera présenté en entier puis demandera ta clé d’accès.")).font(.spFootnote).foregroundStyle(Theme.mute) }196                    }197                }198                .futuresSheetPage()199            }200            .spPage()201            .navigationTitle(String(localized: "Politique de risque du compte")).navigationBarTitleDisplayMode(.inline)202            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Annuler")) { dismiss() } } }203        }204        .interactiveDismissDisabled(approval != nil)205    }206207    private func save() async {208        guard let p = draft.build(), !busy else { return }209        busy = true; error = nil210        defer { busy = false }211        do {212            switch target {213            case .paper(let id): fm.adopt(paper: try await fm.api.setPaperPolicy(id, policy: p)); dismiss()214            case .live(let account):215                switch try await fm.liveAPI.preparePolicyChange(for: account, policy: p) {216                case .notNeeded: fm.adopt(live: try await fm.liveAPI.setPolicy(account.id, policy: p)); dismiss()217                case .approval(let a): approval = a218                }219            }220        } catch { self.error = error }221    }222}223224/** The verified risk intent, in full, then the passkey. Used for a loosened policy, lifting the owner's halt, and a re-base. */225struct RiskIntentReview: View {226    @Environment(AppModel.self) private var model227    let fm: FuturesModel228    let account: LiveAccount229    let approval: LiveRiskApproval230    let done: () -> Void231    @State private var busy = false232    @State private var error: Error?233234    private var title: String {235        switch approval.intent.kind {236        case .policy: String(localized: "Assouplir la politique de risque")237        case .resume: String(localized: "Lever l’arrêt du compte")238        case .rebase: String(localized: "Accepter les positions de la plateforme comme référence")239        }240    }241242    var body: some View {243        let i = approval.intent244        VStack(alignment: .leading, spacing: 4) {245            Text(String(localized: "Changement de risque · \(OfferedVenues.name(i.venue)) · \(FuturesAccountRef.networkBadge(i.network))")).spEyebrow()246            Text(title).font(.system(size: 26, weight: .semibold)).tracking(-0.5).fixedSize(horizontal: false, vertical: true).accessibilityIdentifier("futures.risk.title")247        }248        if !i.loosened.isEmpty { Notice(tone: .warn, title: String(localized: "Limites assouplies"), message: i.loosened.joined(separator: ", ")) }249        if let s = i.subject { Notice(tone: .warn, title: i.kind == .resume ? String(localized: "Arrêt levé par cette approbation") : String(localized: "Divergence acceptée par cette approbation"), message: s) }250        if let p = i.policy { Rows { Text(String(localized: "Politique qui sera en vigueur")).spEyebrow().padding(.bottom, 4); PolicyRows(policy: p) } }251        Rows {252            FieldRow(label: String(localized: "Compte"), value: i.accountId, mono: true); Divider()253            FieldRow(label: String(localized: "Adresse sur la plateforme"), value: i.account, mono: true, copyable: true); Divider()254            FieldRow(label: String(localized: "Autorisation"), value: i.authorizationId, mono: true); Divider()255            FieldRow(label: String(localized: "Nonce"), value: i.nonce, mono: true); Divider()256            ExpiryRow(until: i.expiry); Divider()257            FieldRow(label: String(localized: "Empreinte (défi signé par la clé d’accès)"), value: approval.approval.digest.hex, mono: true, copyable: true)258        }259        if let e = error { FuturesError(error: e) }260        Countdown(until: i.expiry) { left in261            if left <= 0 {262                Notice(tone: .warn, title: String(localized: "Fenêtre expirée"), message: String(localized: "Rien n’a été signé. Recommence."))263                Button(String(localized: "Fermer"), action: done).buttonStyle(.spSecondary)264            } else {265                Button { Task { await approve() } } label: { BusyLabel(title: String(localized: "Approuver avec la clé d’accès"), icon: "person.badge.key.fill", busy: busy) }266                    .buttonStyle(.spPrimary).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.risk.approve")267                Button(String(localized: "Ne pas approuver"), action: done).buttonStyle(.spSecondary).disabled(busy)268            }269        }270    }271272    private func approve() async {273        guard !busy else { return }274        busy = true; error = nil275        defer { busy = false }276        do { fm.adopt(live: try await fm.liveAPI.approveRiskChange(approval, with: model.env.passkeys)); done() }277        catch PasskeyError.cancelled {} catch { self.error = error }278    }279}280281/** Lifting the owner's halt or re-basing: prepared on appearance, reviewed, approved. */282struct RiskChangeSheet: View {283    enum Kind { case resume, rebase }284    @Environment(\.dismiss) private var dismiss285    let fm: FuturesModel286    let account: LiveAccount287    let kind: Kind288    @State private var approval: LiveRiskApproval?289    @State private var notNeeded = false290    @State private var error: Error?291292    var body: some View {293        NavigationStack {294            ScrollView {295                VStack(alignment: .leading, spacing: Theme.Space.section) {296                    ModeBand(mode: .live, network: account.network)297                    if let a = approval { RiskIntentReview(fm: fm, account: account, approval: a) { dismiss() } }298                    else if notNeeded { Notice(tone: .info, title: String(localized: "Rien à approuver"), message: String(localized: "Le serveur indique qu’aucune approbation n’est nécessaire (aucun arrêt du propriétaire à lever, ou aucune divergence).")) }299                    else if let e = error { FuturesError(error: e) }300                    else { ProgressView().frame(maxWidth: .infinity, minHeight: 120) }301                }302                .futuresSheetPage()303            }304            .spPage()305            .navigationTitle(kind == .resume ? String(localized: "Lever l’arrêt") : String(localized: "Re-baser")).navigationBarTitleDisplayMode(.inline)306            .toolbar { ToolbarItem(placement: .cancellationAction) { Button(String(localized: "Fermer")) { dismiss() } } }307            .task {308                do {309                    let r = kind == .resume ? try await fm.liveAPI.prepareResume(for: account) : try await fm.liveAPI.prepareRebase(for: account)310                    switch r { case .notNeeded: notNeeded = true; case .approval(let a): approval = a }311                } catch { self.error = error }312            }313        }314        .interactiveDismissDisabled(approval != nil)315    }316}317
Files main
Menu

Theme