SPB Git

Repository Public

FuturesLiveOps.swift 22.6 KB 460 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Wallet for macOS9// File             : Features/Futures/FuturesLiveOps.swift10// Description      : Every operation on a LIVE venue account (testnet or11//                    mainnet): creating the account, authorizing and revoking12//                    the trading key, proposing an order or a reduce-only13//                    close, leverage changes, collateral deposit and14//                    withdrawal, the account's halt and its lifting. Each one15//                    that grants authority or moves funds is prepared by the16//                    server, verified by the Core against its WebAuthn17//                    challenge, shown in a review sheet, and only then approved18//                    with the passkey. Stopping (cancel, cancel-all, halt,19//                    revoke) needs no passkey. The client never infers an20//                    outcome: what is displayed afterwards is the order, action21//                    or operation as the server answers it.22// Module           : Features23// Repository       : https://git.spboucher.ai/sp-wallet-macos24// Created          : 2026-11-1825// Last Modified    : 2026-11-1826//27// =============================================================================28// AUTHOR & PROFESSIONAL AFFILIATION29// =============================================================================30//31// Author           : Simon-Pierre Boucher32// Position         : Professor of Finance33// Institution      : Université du Québec en Outaouais (UQO)34// Department       : Département des sciences administratives35// Organization     : SP Boucher36//37// Website          : https://spboucher.ai38// Git              : https://git.spboucher.ai39//40// =============================================================================41// OFFICIAL CONTACT DIRECTORY42// =============================================================================43//44// General          : info@spboucher.ai45// Professional     : contact@spboucher.ai46// Direct           : simon@spboucher.ai47// Research         : research@spboucher.ai48// Development      : dev@spboucher.ai49// Support          : support@spboucher.ai50// Security/Admin   : admin@spboucher.ai51// Notifications    : notifications@spboucher.ai52//53// Preferred Contact: support@spboucher.ai54//55// =============================================================================56// COPYRIGHT & INTELLECTUAL PROPERTY57// =============================================================================58//59// Copyright (c) 202660// Simon-Pierre Boucher61//62// All rights reserved where applicable.63//64// This file is governed by the applicable project license,65// copyright notices, institutional agreements and relevant law.66//67// Unless expressly authorized by the applicable license or68// rights holder, copying, redistribution, sublicensing,69// publication and commercial exploitation are not permitted.70//71// Existing third-party rights and notices remain unaffected.72//73// =============================================================================74// CONFIDENTIALITY & SECURITY75// =============================================================================76//77// Classification   : Public78// Distribution     : Public repository; use is governed by the project license79// Security Contact : admin@spboucher.ai80//81// Access to this source does not independently grant permission82// to redistribute or disclose confidential materials.83//84// Do not embed credentials, private keys, access tokens,85// certificates or confidential personal information.86//87// =============================================================================88// LICENSE & MAINTENANCE89// =============================================================================90//91// License          : None specified (no license file in this repository)92// Maintainer       : Simon-Pierre Boucher93// Technical Contact: dev@spboucher.ai94//95// =============================================================================96// END OF SP BOUCHER SOURCE HEADER97// =============================================================================9899import Foundation100import SPWalletCore101102@MainActor @Observable final class FutLiveOps {103    /// What is waiting for the owner's review and passkey. Each case carries only objects the Core verified.104    enum Sheet: Identifiable {105        case authorization(LiveAuthorizationPreparation)106        case order(LiveOrderProposal, LiveOrderApproval, close: Bool)107        case leverage(LiveLeverageApproval)108        case deposit(CollateralDepositApproval)109        case withdraw(CollateralWithdrawApproval)110        case risk(LiveRiskApproval)111        var id: String {112            switch self {113            case .authorization(let p): "auth-\(p.authorization.authorizationId)"114            case .order(_, let a, _): "order-\(a.clientId)"115            case .leverage(let l): "lev-\(l.action.id)"116            case .deposit(let d): "dep-\(d.operation.id)"117            case .withdraw(let w): "wd-\(w.operation.id)"118            case .risk(let r): "risk-\(r.intent.nonce)"119            }120        }121    }122123    let model: AppModel124    let store: FuturesStore125126    var sheet: Sheet?127    /// The owner's own tick under the jurisdiction text of the authorization sheet.128    var acknowledged = false129    private(set) var busy: String?130    private(set) var approving = false131    var error: String?132    var sheetError: String?133    /// The server's last answer to a stop / maintenance action, in words.134    var notice: String?135136    /// The last order that went through a proposal: as the server reports it, refreshed until it is final.137    private(set) var trackedOrder: LiveOrder?138    private(set) var trackedOrderVenue: LiveOrderResult.Venue?139    private(set) var leverageResult: LiveLeverageResult?140    private(set) var collateral = FutLoaded<CollateralStatus>()141    private(set) var trackedOperation: CollateralOperation?142143    @ObservationIgnored private var orderKey: (key: String, fingerprint: String)?144    @ObservationIgnored private var closeKey: (key: String, fingerprint: String)?145    @ObservationIgnored private var orderTask: Task<Void, Never>?146    @ObservationIgnored private var operationTask: Task<Void, Never>?147148    init(model: AppModel, store: FuturesStore) { self.model = model; self.store = store }149150    private var live: DerivativesLiveAPI { store.live }151    var isBusy: Bool { busy != nil || approving }152    var busyText: String? { busy }153154    private func run(_ what: String, _ body: () async throws -> Void) async {155        guard model.canOperate, !isBusy else { return }156        busy = what; error = nil; notice = nil157        defer { busy = nil }158        do { try await body() }159        catch PasskeyError.cancelled {}160        catch { self.error = model.describe(error) }161    }162163    private func account() throws -> LiveAccount {164        guard let a = store.liveAccount else { throw APIError(status: 404, code: "no_account", message: "Aucun compte de plateforme dans ce mode.") }165        return a166    }167168    // MARK: account, authorization169170    func createAccount(network: String, label: String) async {171        await run("Création du compte…") {172            let d = try await live.createAccount(network: network, label: label)173            await store.loadAccounts(); store.adopt(d)174            notice = "Compte créé en lecture seule : il ne négocie rien tant que vous n’avez pas autorisé la clé de négociation."175        }176    }177178    func prepareAuthorization(policy: VenuePolicy, days: Int) async {179        await run("Préparation de l’autorisation…") {180            let p = try await live.prepareAuthorization(for: try account(), policy: policy, days: days, locale: store.locale)181            acknowledged = false; sheetError = nil182            sheet = .authorization(p)183        }184    }185186    func revoke(cancelOpenOrders: Bool) async {187        await run("Révocation…") {188            let d = try await live.revokeAuthorization(try account().id, cancelOpenOrders: cancelOpenOrders, locale: store.locale)189            store.adopt(d); await store.loadAccounts()190            var parts = ["Autorisation révoquée : le compte est en lecture seule. Les positions restent ouvertes."]191            if let c = d.cancelled { parts.append(Self.text(c)) }192            if let e = d.cancelError { parts.append("Annulation des ordres en échec : \(e.message) [\(e.code)]") }193            if let w = d.warning { parts.append(w) }194            notice = parts.joined(separator: " ")195        }196    }197198    /// After a lost answer of the signer during an authorization: the server adopts or removes what the passkey approved. No passkey.199    func recover() async {200        await run("Récupération…") {201            let d = try await live.recoverAuthorization(try account().id)202            store.adopt(d); await store.loadAccounts()203            notice = d.recovered.map { r in r.isEmpty ? "Rien à récupérer." : r.map { "\($0.what) \($0.id) : \($0.outcome) — \($0.detail)" }.joined(separator: " ; ") } ?? "Récupération terminée ; état du compte relu."204        }205    }206207    func reconcile() async {208        await run("Rapprochement avec la plateforme…") {209            let r = try await live.reconcile(try account().id)210            store.adopt(r.account)211            notice = "Rapprochement : \(r.reconciled) ordre(s), \(r.fills) exécution(s), \(r.funding) paiement(s) de financement." + (r.divergence.map { " Divergence : \($0)" } ?? "")212        }213    }214215    // MARK: orders216217    func propose(_ request: LiveOrderRequest) async {218        await run("Proposition de l’ordre…") {219            let a = try account()220            let fp = "\(a.id)|\(request.instrument)|\(request.side.rawValue)|\(request.type.rawValue)|\(request.size)|\(request.price ?? "")|\(request.reduceOnly)|\(request.tif.rawValue)|\(request.slippageBps.map(String.init) ?? "")"221            if orderKey?.fingerprint != fp { orderKey = (APIClient.newIdempotencyKey(), fp) }222            let p = try await live.proposeOrder(for: a, order: request, idempotencyKey: orderKey!.key)223            present(p, close: false)224        }225    }226227    func proposeClose(_ position: DerivPosition, fraction: String, slippageBps: Int) async {228        await run("Proposition de la clôture…") {229            let a = try account()230            let fp = "\(a.id)|\(position.instrument)|\(position.side)|\(position.size)|\(fraction)|\(slippageBps)"231            if closeKey?.fingerprint != fp { closeKey = (APIClient.newIdempotencyKey(), fp) }232            let p = try await live.proposeClose(for: a, position: position, fraction: fraction, slippageBps: slippageBps, idempotencyKey: closeKey!.key)233            present(p, close: true)234        }235    }236237    private func present(_ p: LiveOrderProposal, close: Bool) {238        sheetError = nil239        if let approvable = p.approvable { sheet = .order(p, approvable, close: close) }240        else {241            // nothing (left) to approve: the stored order says why — refused by the risk engine, expired, or already handled242            orderKey = nil; closeKey = nil243            follow(p.order, venue: nil)244        }245    }246247    func cancel(orderClientId: String) async {248        await run("Annulation…") {249            let r = try await live.cancelOrder(try account().id, clientId: orderClientId)250            notice = r.sent == false ? "Proposition retirée : rien n’avait été envoyé à la plateforme." : "Annulation demandée à la plateforme — état de l’ordre : \(FutOrderStatePill.text(r.order.state.rawValue))." + (r.venue?.error.map { " \($0)" } ?? "")251            if trackedOrder?.clientId == r.order.clientId { trackedOrder = r.order }252            await store.refreshAccount()253        }254    }255256    func cancelAll() async {257        await run("Annulation de tous les ordres…") {258            let r = try await live.cancelAll(try account().id)259            notice = Self.text(r)260            await store.refreshAccount()261        }262    }263264    static func text(_ c: LiveCancelAll) -> String {265        var s = "Annulation groupée : \(c.requested) demandé(s), \(c.accepted) accepté(s) par la plateforme"266        if !c.failed.isEmpty { s += ", \(c.failed.count) en échec (\(c.failed.map { "\($0.instrument) : \($0.error)" }.joined(separator: " ; ")))" }267        s += c.remaining.map { ". Ordres encore au carnet : \($0.count)." } ?? ". Ordres restants : lecture impossible."268        return s269    }270271    private func follow(_ order: LiveOrder, venue: LiveOrderResult.Venue?) {272        trackedOrder = order; trackedOrderVenue = venue273        orderTask?.cancel()274        Task { await store.refreshAccount() }275        guard !order.final else { announce(order); return }276        orderTask = Task { [weak self] in277            for _ in 0..<60 {278                try? await Task.sleep(for: .seconds(3))279                guard let self, !Task.isCancelled, let cur = self.trackedOrder, cur.clientId == order.clientId else { return }280                await self.store.refreshAccount()281                guard let fresh = self.store.currentLiveDetail?.orders.first(where: { $0.clientId == cur.clientId }) else { continue }282                self.trackedOrder = fresh283                if fresh.final { self.announce(fresh); return }284            }285        }286    }287288    private func announce(_ o: LiveOrder) {289        Notifier.post(title: "Ordre \(o.instrument) : \(FutOrderStatePill.text(o.state.rawValue))", body: "\(o.side == "buy" ? "Achat" : "Vente") \(o.size)" + (o.reason.map { " — \($0)" } ?? ""), id: "deriv-\(o.clientId)")290    }291292    func clearTrackedOrder() { orderTask?.cancel(); trackedOrder = nil; trackedOrderVenue = nil }293294    // MARK: leverage, halt, risk295296    func proposeLeverage(instrument: String, leverage: Int, marginMode: DerivMarginMode) async {297        await run("Préparation du changement de levier…") {298            let l = try await live.proposeLeverage(for: try account(), instrument: instrument, leverage: leverage, marginMode: marginMode)299            sheetError = nil; leverageResult = nil300            sheet = .leverage(l)301        }302    }303304    func halt(reason: String) async {305        await run("Arrêt des nouveaux ordres…") {306            let d = try await live.halt(try account().id, reason: reason)307            store.adopt(d); await store.loadAccounts()308            notice = "Arrêt engagé sur ce compte." + (d.note.map { " \($0)" } ?? "")309        }310    }311312    func prepareResume() async { await prepareRisk("Préparation de la levée de l’arrêt…") { try await self.live.prepareResume(for: $0) } }313    func prepareRebase() async { await prepareRisk("Préparation de l’acceptation des positions…") { try await self.live.prepareRebase(for: $0) } }314315    private func prepareRisk(_ what: String, _ call: (LiveAccount) async throws -> LiveRiskPreparation) async {316        await run(what) {317            switch try await call(try account()) {318            case .notNeeded: notice = "Rien à approuver : il n’y a aucun arrêt ou aucune divergence à lever sur ce compte."; await store.refreshAccount()319            case .approval(let r): sheetError = nil; sheet = .risk(r)320            }321        }322    }323324    // MARK: collateral325326    func loadCollateral() async {327        guard let a = store.liveAccount else { return }328        collateral.loading = true329        do { collateral.set(try await store.collateral.status(a.id)) } catch { collateral.fail(model.describe(error)) }330    }331    func resetCollateral() { collateral = FutLoaded(); trackedOperation = nil; operationTask?.cancel() }332333    private func ownAddress() throws -> String {334        guard let a = model.address(on: HyperliquidCollateralPins.network) else { throw APIError(status: 0, code: "no_address", message: "L’adresse Arbitrum de ce portefeuille est inconnue de l’app : impossible de vérifier l’opération.") }335        return a336    }337338    func prepareDeposit(amount: String) async {339        await run("Préparation du dépôt…") {340            let d = try await store.collateral.prepareDeposit(for: try account(), amount: amount, ownAddress: try ownAddress())341            sheetError = nil; sheet = .deposit(d)342        }343    }344345    func prepareWithdraw(amount: String) async {346        await run("Préparation du retrait…") {347            let w = try await store.collateral.prepareWithdraw(for: try account(), amount: amount, ownAddress: try ownAddress())348            sheetError = nil; sheet = .withdraw(w)349        }350    }351352    func cancelOperation(_ id: String) async {353        await run("Annulation de l’opération…") {354            let op = try await store.collateral.cancel(try account().id, operationId: id)355            notice = "Opération \(op.kind == "deposit" ? "de dépôt" : "de retrait") : \(op.state). Rien n’a été signé."356            await loadCollateral()357        }358    }359360    private func follow(_ op: CollateralOperation, account: LiveAccountID) {361        trackedOperation = op362        operationTask?.cancel()363        guard !op.final else { return }364        operationTask = Task { [weak self] in365            while !Task.isCancelled {366                try? await Task.sleep(for: .seconds(6))367                guard let self, !Task.isCancelled, let cur = self.trackedOperation, cur.id == op.id else { return }368                guard AppActivity.isActive, let fresh = try? await self.store.collateral.operation(account, operationId: cur.id) else { continue }369                self.trackedOperation = fresh370                if fresh.final {371                    Notifier.post(title: fresh.isDone ? (fresh.kind == "deposit" ? "Dépôt crédité par la plateforme" : "Retrait reçu par le portefeuille") : "Opération de collatéral : \(fresh.state)",372                                  body: "\(fresh.amount) \(fresh.asset)" + (fresh.error.map { " — \($0)" } ?? ""), id: "coll-\(fresh.id)")373                    await self.loadCollateral(); await self.model.refreshAll(); await self.store.refreshAccount()374                    return375                }376            }377        }378    }379380    // MARK: the passkey step381382    /// Approves what the open sheet shows — and nothing else: each branch hands the Core the verified object the sheet rendered.383    func approve() async {384        guard let sheet, model.canOperate, !approving else { return }385        approving = true; sheetError = nil386        defer { approving = false }387        do {388            switch sheet {389            case .authorization(let p):390                let d = try await live.approveAuthorization(p, acknowledged: acknowledged, with: model.authenticator)391                store.adopt(d); await store.loadAccounts()392                notice = "Autorisation enregistrée par le signataire. Mode du compte : \(d.account.mode.rawValue)."393                self.sheet = nil394            case .order(_, let a, _):395                let r = try await live.approveOrder(a, with: model.authenticator)396                orderKey = nil; closeKey = nil397                self.sheet = nil398                follow(r.order, venue: r.venue)399            case .leverage(let l):400                let r = try await live.approveLeverage(l, with: model.authenticator)401                leverageResult = r402                notice = r.venue?.confirmed == true403                    ? "Levier confirmé par la plateforme : \(r.venue?.leverage.map { "\($0.leverage)× (\($0.marginMode))" } ?? "valeur non relue")."404                    : "Changement de levier envoyé — état : \(r.action.state). La plateforme ne confirme pas encore le nouveau réglage" + (r.action.error.map { " : \($0)" } ?? ".")405                self.sheet = nil406                await store.refreshAccount()407            case .deposit(let d):408                let op = try await store.collateral.approveDeposit(d, with: model.authenticator)409                self.sheet = nil410                follow(op, account: d.accountId); await loadCollateral()411            case .withdraw(let w):412                let op = try await store.collateral.approveWithdraw(w, with: model.authenticator)413                self.sheet = nil414                follow(op, account: w.accountId); await loadCollateral()415            case .risk(let r):416                let d = try await live.approveRiskChange(r, with: model.authenticator)417                store.adopt(d); await store.loadAccounts()418                notice = "Changement appliqué par le serveur. " + (d.account.halted.map { "Le compte reste arrêté : \($0)" } ?? "Aucun arrêt actif sur ce compte.")419                self.sheet = nil420            }421        } catch PasskeyError.cancelled {422            // the owner dismissed the passkey prompt: the sheet stays, nothing was signed423        } catch {424            sheetError = model.describe(error)425            await afterFailedApproval(sheet)426        }427    }428429    /// The answer of an approval may be lost after the server acted on it: read the real state instead of asking for a second signature.430    private func afterFailedApproval(_ s: Sheet) async {431        switch s {432        case .order(_, let a, _):433            guard let d = try? await live.account(a.accountId), let o = d.orders.first(where: { $0.clientId == a.clientId }) else { return }434            store.adopt(d)435            if o.state != .riskChecked && o.state.rawValue != "proposed" { orderKey = nil; closeKey = nil; sheet = nil; error = sheetError; follow(o, venue: nil) }436        case .deposit(let d):437            if let op = try? await store.collateral.operation(d.accountId, operationId: d.operation.id), op.state != d.operation.state { sheet = nil; error = sheetError; follow(op, account: d.accountId) }438        case .withdraw(let w):439            if let op = try? await store.collateral.operation(w.accountId, operationId: w.operation.id), op.state != w.operation.state { sheet = nil; error = sheetError; follow(op, account: w.accountId) }440        case .authorization, .leverage, .risk:441            await store.refreshAccount()442        }443    }444445    /// Closing a sheet without approving: a stored proposal or operation is withdrawn on the server so that nothing stays pending.446    func dismiss() async {447        guard let s = sheet, !approving else { return }448        sheet = nil; sheetError = nil449        switch s {450        case .order(_, let a, _):451            orderKey = nil; closeKey = nil452            if let r = try? await live.cancelOrder(a.accountId, clientId: a.clientId) { notice = r.sent == false ? "Proposition retirée : rien n’a été signé ni envoyé." : nil }453            await store.refreshAccount()454        case .deposit(let d): _ = try? await store.collateral.cancel(d.accountId, operationId: d.operation.id); await loadCollateral()455        case .withdraw(let w): _ = try? await store.collateral.cancel(w.accountId, operationId: w.operation.id); await loadCollateral()456        case .authorization, .leverage, .risk: break457        }458    }459}460
Files main
Menu

Theme