SPB Git

Repository Public

FuturesCollateral.swift 24.3 KB 336 lines swift

1// SP Wallet iOS2// File: Features/Futures/FuturesCollateral.swift3// Description: Collateral of a live Hyperliquid account, as served: the venue balance, the pinned deposit route and whether a4//              deposit or a withdrawal can be prepared now (with the server's reason when not). Deposit: native USDC on Arbitrum5//              to the pinned bridge — prepare → review of the verified wallet intent (`IntentReview`, with its fee ceiling) →6//              passkey → follow-up until the VENUE credits it (a confirmed Arbitrum transaction is not a credited deposit).7//              Withdrawal: to the wallet's OWN address only — review of the verified withdrawal → passkey → follow-up until the8//              wallet sees the USDC. GMX is not offered: one status row, as served.9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import SwiftUI13import SPWalletCore1415struct FuturesCollateralCard: View {16    @Environment(AppModel.self) private var model17    let fm: FuturesModel18    let account: LiveAccount19    @State private var status: CollateralStatus?20    @State private var error: Error?21    @State private var sheet: CollateralSheet.Kind?2223    var body: some View {24        VStack(alignment: .leading, spacing: 10) {25            HStack { SectionHeader(title: String(localized: "Collatéral")); Pill(text: FuturesAccountRef.networkBadge(account.network), tone: account.isMainnet ? .danger : .warn) }26            if let s = status {27                if let e = s.venueBalance.error { Notice(tone: .warn, title: String(localized: "Solde de la plateforme illisible"), message: e) }28                else {29                    HStack(alignment: .top, spacing: 10) {30                        StatTile(label: String(localized: "Valeur sur la plateforme"), value: Fx.usd(s.venueBalance.equity))31                        StatTile(label: String(localized: "Retirable"), value: Fx.usd(s.venueBalance.withdrawable))32                        if let spot = s.venueBalance.spotUsdc { StatTile(label: String(localized: "USDC au comptant"), value: Fx.usd(spot)) }33                    }34                }35                VStack(alignment: .leading, spacing: 0) {36                    if let r = s.route {37                        FieldRow(label: String(localized: "Route de dépôt épinglée"), value: "\(r.asset) · \(r.networkName) → \(OfferedVenues.name(s.venue))"); Divider()38                        FieldRow(label: String(localized: "Contrat de pont (épinglé)"), value: r.bridge, mono: true, copyable: true); Divider()39                        FieldRow(label: String(localized: "Minimum de dépôt (plancher du serveur · de la plateforme)"), value: "\(Fx.exact(r.minimum)) · \(Fx.exact(r.venueMinimum)) \(r.asset)"); Divider()40                        if let c = r.credits { FieldRow(label: String(localized: "Qui est crédité"), value: c); Divider() }41                    } else {42                        FieldRow(label: String(localized: "Route de dépôt"), value: String(localized: "aucune sur ce réseau (le serveur n’en sert pas)"), tone: .neutral); Divider()43                    }44                    FieldRow(label: String(localized: "Retrait : destination · frais de la plateforme"), value: "\(s.withdrawal.destination) · \(Fx.exact(s.withdrawal.fee)) USDC", mono: true)45                    if let w = s.wallet { Divider(); FieldRow(label: String(localized: "Portefeuille sur \(w.networkName)"), value: "\(Fx.exact(w.usdc)) USDC · \(Fx.exact(w.gas)) \(w.gasSymbol) · " + String(localized: "plafond disponible \(Fx.exact(w.limits.maxNow))")) }46                    if let we = s.walletError { Divider(); FieldRow(label: String(localized: "Portefeuille"), value: we, tone: .warn) }47                }48                availability(s.deposit, title: String(localized: "Dépôt indisponible pour le moment"), id: "futures.collateral.depositBlocked")49                availability(s.withdraw, title: String(localized: "Retrait indisponible pour le moment"), id: "futures.collateral.withdrawBlocked")50                HStack(spacing: 8) {51                    Button { sheet = .deposit } label: { Label(String(localized: "Déposer…"), systemImage: "arrow.down.to.line").frame(maxWidth: .infinity, minHeight: 44) }52                        .buttonStyle(.bordered).disabled(!s.deposit.available || !model.canOperate).accessibilityIdentifier("futures.collateral.deposit")53                    Button { sheet = .withdraw } label: { Label(String(localized: "Retirer…"), systemImage: "arrow.up.to.line").frame(maxWidth: .infinity, minHeight: 44) }54                        .buttonStyle(.bordered).disabled(!s.withdraw.available || !model.canOperate).accessibilityIdentifier("futures.collateral.withdraw")55                }56                if !s.operations.isEmpty {57                    Text(String(localized: "Opérations")).spEyebrow()58                    ForEach(s.operations.prefix(8)) { op in CollateralOperationRow(op: op); Divider() }59                }60            } else if let e = error { FuturesError(error: e) { Task { await load() } } }61            else if model.canOperate { ProgressView().frame(maxWidth: .infinity, minHeight: 60) }62            else { Text(String(localized: "Collatéral illisible hors ligne.")).font(.spCallout).foregroundStyle(Theme.mute) }63        }64        .spCard()65        .task(id: account.id) { await load() }66        .sheet(item: Binding(get: { sheet.map(SheetItem.init) }, set: { sheet = $0?.kind })) { item in67            CollateralSheet(fm: fm, account: account, kind: item.kind, status: status) { Task { await load() } }.wallet(model)68        }69    }7071    private struct SheetItem: Identifiable { let kind: CollateralSheet.Kind; var id: Int { kind == .deposit ? 0 : 1 } }7273    @ViewBuilder private func availability(_ a: CollateralStatus.Availability, title: String, id: String) -> some View {74        if let code = a.reason, !a.available {75            // the server gives a code; its own sentence for that code is in the live configuration when it has one76            let served = fm.liveConfig?.reasons?[code].map { FuturesText.locale == "en" ? $0.en : $0.fr }77            let r = DerivativesRefusal(code: code, reason: served ?? "", status: 200)78            Notice(tone: .warn, title: r.kind == .lock ? String(localized: "\(title) — verrou serveur fermé") : title,79                   message: (served.map { $0 + " " } ?? "") + "(\(code))" + ((a.bridgeFrom ?? []).isEmpty ? "" : " · " + String(localized: "USDC ailleurs : \((a.bridgeFrom ?? []).map { "\($0.name) \($0.usdc)" }.joined(separator: ", "))")), icon: r.kind == .lock ? "lock.fill" : nil)80                .accessibilityIdentifier(id)81        }82    }8384    private func load() async {85        guard model.canOperate else { return }86        do { status = try await fm.collateralAPI.status(account.id); error = nil } catch { self.error = error }87    }88}8990/** One collateral operation with the only two states that mean « done ». */91struct CollateralOperationRow: View {92    let op: CollateralOperation93    var body: some View {94        let done = op.isDone95        VStack(alignment: .leading, spacing: 3) {96            HStack {97                Text((op.kind == "deposit" ? String(localized: "Dépôt") : String(localized: "Retrait")) + " \(Fx.exact(op.amount)) \(op.asset)").font(.system(size: 14, weight: .semibold))98                Spacer()99                Pill(text: Self.label(op), tone: done ? .ok : op.final ? .danger : op.overdue == true ? .warn : .info, icon: done ? "checkmark.circle.fill" : op.final ? "xmark.circle.fill" : "clock")100            }101            if let e = op.error { Text(e).font(.system(size: 12)).foregroundStyle(Theme.danger) }102            if let t = op.createdAt { Text(t.formatted(date: .abbreviated, time: .shortened)).font(.system(size: 12)).foregroundStyle(Theme.mute) }103        }104        .padding(.vertical, 4)105    }106107    /** The server's state word, with the meaning of the ones that matter. Unknown states are shown verbatim. */108    static func label(_ op: CollateralOperation) -> String {109        switch (op.kind, op.state) {110        case ("deposit", "credited"): String(localized: "crédité par la plateforme")111        case ("withdraw", "completed"): String(localized: "reçu par le portefeuille")112        case (_, "prepared"): String(localized: "préparé, non approuvé")113        case (_, "cancelled"): String(localized: "annulé")114        case (_, "expired"): String(localized: "expiré")115        case (_, "failed"): String(localized: "échoué")116        default: op.state117        }118    }119}120121struct CollateralSheet: View {122    enum Kind { case deposit, withdraw }123    @Environment(AppModel.self) private var model124    @Environment(\.dismiss) private var dismiss125    let fm: FuturesModel126    let account: LiveAccount127    let kind: Kind128    let status: CollateralStatus?129    let changed: () -> Void130131    @State private var amountText = ""132    @State private var deposit: CollateralDepositApproval?133    @State private var withdrawal: CollateralWithdrawApproval?134    @State private var tracking: CollateralOperation?135    @State private var busy = false136    @State private var error: Error?137    @State private var confirmCancel = false138139    /** The wallet's own address on the deposit network, as the WALLET knows it (never taken from the prepared answer). */140    private var ownAddress: String? { model.account(HyperliquidCollateralPins.network)?.address }141    private var amount: String? {142        guard case .success(let v) = DecimalInput.parse(amountText), v.isPositive, v.scale <= HyperliquidCollateralPins.usdcDecimals else { return nil }143        return v.description144    }145    private var reviewing: Bool { (deposit != nil || withdrawal != nil) && tracking == nil }146147    var body: some View {148        NavigationStack {149            ScrollView {150                VStack(alignment: .leading, spacing: Theme.Space.section) {151                    ModeBand(mode: .live, network: account.network)152                    if let op = tracking { track(op) }153                    else if let d = deposit { reviewDeposit(d) }154                    else if let w = withdrawal { reviewWithdrawal(w) }155                    else { form }156                }157                .futuresSheetPage()158            }159            .spPage()160            .navigationTitle(kind == .deposit ? String(localized: "Déposer du collatéral") : String(localized: "Retirer du collatéral")).navigationBarTitleDisplayMode(.inline)161            .toolbar {162                ToolbarItem(placement: .cancellationAction) {163                    Button(tracking != nil ? String(localized: "Fermer") : String(localized: "Annuler")) { if reviewing { confirmCancel = true } else { dismiss() } }.accessibilityIdentifier("futures.collateral.close")164                }165            }166            .confirmationDialog(String(localized: "Abandonner cette opération ?"), isPresented: $confirmCancel, titleVisibility: .visible) {167                Button(String(localized: "Abandonner et fermer"), role: .destructive) { Task { await cancel() } }168                Button(String(localized: "Continuer la revue"), role: .cancel) {}169            } message: { Text(String(localized: "Rien n’a été signé. L’opération préparée sera annulée.")) }170        }171        .interactiveDismissDisabled(reviewing || busy)172    }173174    @ViewBuilder private var form: some View {175        if kind == .deposit {176            Notice(tone: .info, title: String(localized: "USDC natif d’Arbitrum vers le pont épinglé"),177                   message: String(localized: "La plateforme crédite l’adresse qui envoie : seule l’adresse de ce portefeuille peut déposer. Minimum servi : \(status?.route.map { Fx.exact($0.minimum) + " " + $0.asset } ?? "—"). Un montant sous le minimum de la plateforme serait perdu ; le serveur le refuse."))178            if ownAddress == nil { Notice(tone: .danger, title: String(localized: "Adresse Arbitrum du portefeuille inconnue"), message: String(localized: "L’app ne peut pas vérifier la source du dépôt : rien ne sera préparé.")) }179        } else {180            Notice(tone: .info, title: String(localized: "Vers l’adresse de ce portefeuille, et aucune autre"),181                   message: String(localized: "Destination : \(status?.withdrawal.destination ?? account.account). Frais de la plateforme : \(status.map { Fx.exact($0.withdrawal.fee) } ?? "—") USDC. Retirable maintenant : \(status?.withdrawal.available.map { Fx.exact($0) } ?? "—") USDC."))182        }183        VStack(alignment: .leading, spacing: 12) {184            TypedField(label: String(localized: "Montant"), text: $amountText, unit: "USDC", hint: String(localized: "Six décimales au plus. Aucun montant n’est proposé."), id: "futures.collateral.amount")185        }186        .spCard()187        if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.collateral.error") }188        Button { Task { await prepare() } } label: { BusyLabel(title: String(localized: "Préparer et vérifier"), busy: busy) }189            .buttonStyle(.spPrimary).disabled(busy || amount == nil || ownAddress == nil || !model.canOperate).accessibilityIdentifier("futures.collateral.prepare")190        Text(String(localized: "Le serveur vérifie la route, les limites et le solde. Rien n’est signé à cette étape.")).font(.spFootnote).foregroundStyle(Theme.mute)191    }192193    @ViewBuilder private func reviewDeposit(_ d: CollateralDepositApproval) -> some View {194        IntentReview(intent: d.intent, digest: d.approval.digest, extra: [195            (String(localized: "Minimum de dépôt de la plateforme (unités de base)"), d.intent.venueDeposit?.minAmount ?? "—", true),196            (String(localized: "Plafond de frais de l’intention (maxFee, unités de base)"), d.intent.maxFee, true),197        ])198        Rows {199            if let f = d.fee { FieldRow(label: String(localized: "Frais de réseau estimés · plafond"), value: "\(Fx.exact(f.estimate)) · \(Fx.exact(f.max)) \(f.symbol)"); Divider() }200            if let r = d.route { FieldRow(label: String(localized: "Délai habituel de crédit"), value: r.expectedSeconds.map { String(localized: "\($0) s") } ?? "—"); Divider() }201            if let l = d.liveness { FieldRow(label: String(localized: "Vérification du pont par le serveur"), value: (l.ok ? String(localized: "en service") : String(localized: "problème signalé")) + (l.detail.map { " — \($0)" } ?? ""), tone: l.ok ? nil : .danger); Divider() }202            FieldRow(label: String(localized: "Solde sur la plateforme avant"), value: Fx.usd(d.venueBalance?.equity, exact: true))203        }204        Notice(tone: .warn, title: String(localized: "Terminé seulement quand la plateforme crédite"), message: String(localized: "La confirmation de la transaction sur Arbitrum n’est pas le crédit du dépôt. L’app suit jusqu’à ce que le registre de la plateforme le montre."))205        approveButtons(expiry: d.intent.expiry)206    }207208    @ViewBuilder private func reviewWithdrawal(_ w: CollateralWithdrawApproval) -> some View {209        let x = w.withdrawal210        VStack(alignment: .leading, spacing: 4) {211            Text(String(localized: "Retrait · \(OfferedVenues.name(x.venue)) · \(FuturesAccountRef.networkBadge(x.network))")).spEyebrow()212            Text("\(Fx.exact(x.amount)) USDC").font(.system(size: 32, weight: .semibold)).tracking(-0.8).textSelection(.enabled).accessibilityIdentifier("futures.withdraw.amount")213        }214        Rows {215            FieldRow(label: String(localized: "Destination (adresse de ce portefeuille)"), value: x.destination, mono: true, copyable: true); Divider()216            FieldRow(label: String(localized: "Compte débité sur la plateforme"), value: x.account, mono: true, copyable: true); Divider()217            FieldRow(label: String(localized: "Frais de la plateforme"), value: "\(Fx.exact(x.fee)) USDC"); Divider()218            FieldRow(label: String(localized: "Montant attendu sur le portefeuille"), value: "\(Fx.exact(w.receive)) USDC"); Divider()219            FieldRow(label: String(localized: "Identifiant · clé du signataire"), value: "\(x.withdrawalId) · \(x.keyId)", mono: true); Divider()220            FieldRow(label: String(localized: "Horodatage de l’action de la plateforme (ms)"), value: String(x.time), mono: true); Divider()221            if let a = w.action { FieldRow(label: String(localized: "Action signée par le signataire"), value: "\(a.type) · \(a.hyperliquidChain)", mono: true); Divider() }222            ExpiryRow(until: x.expiry); Divider()223            FieldRow(label: String(localized: "Empreinte du retrait (défi signé par la clé d’accès)"), value: w.approval.digest.hex, mono: true, copyable: true)224        }225        Label(String(localized: "L’app a vérifié que la destination est l’adresse de ce portefeuille, que le montant est celui saisi et que montant − frais = montant attendu."), systemImage: "checkmark.shield.fill").font(.spFootnote).foregroundStyle(Theme.mute)226        approveButtons(expiry: x.expiry)227    }228229    @ViewBuilder private func approveButtons(expiry: Date) -> some View {230        if let e = error { FuturesError(error: e).accessibilityIdentifier("futures.collateral.error") }231        Countdown(until: expiry) { left in232            if left <= 0 {233                Notice(tone: .warn, title: String(localized: "Fenêtre expirée"), message: String(localized: "Rien n’a été signé. Recommence."))234                Button(String(localized: "Fermer")) { dismiss() }.buttonStyle(.spSecondary)235            } else {236                Button { Task { await approve() } } label: { BusyLabel(title: String(localized: "Approuver avec la clé d’accès"), icon: "person.badge.key.fill", busy: busy) }237                    .buttonStyle(.spPrimary).disabled(busy || !model.canOperate).accessibilityIdentifier("futures.collateral.approve")238            }239        }240    }241242    @ViewBuilder private func track(_ op: CollateralOperation) -> some View {243        HStack(spacing: 10) {244            if op.isDone { Image(systemName: "checkmark.circle.fill").font(.system(size: 22)).foregroundStyle(Theme.emerald) }245            else if op.final { Image(systemName: "xmark.circle.fill").font(.system(size: 22)).foregroundStyle(Theme.danger) }246            else { ProgressView() }247            Text(CollateralOperationRow.label(op)).font(.spHeadline)248        }249        .accessibilityElement(children: .combine).accessibilityIdentifier("futures.collateral.state")250        if !op.final {251            Notice(tone: .info, title: op.kind == "deposit" ? String(localized: "Pas encore crédité par la plateforme") : String(localized: "Pas encore reçu par le portefeuille"),252                   message: (op.expectedSeconds.map { String(localized: "Délai habituel : \($0) s.") + " " } ?? "") + (op.overdue == true ? String(localized: "Le délai habituel est dépassé ; l’app continue de suivre.") : String(localized: "L’app suit l’opération.")))253        }254        Rows {255            FieldRow(label: String(localized: "Montant"), value: "\(Fx.exact(op.amount)) \(op.asset)"); Divider()256            FieldRow(label: String(localized: "État servi"), value: op.state + (op.proposalState.map { " · " + String(localized: "transaction : \($0)") } ?? ""))257            if let c = op.confirmations { Divider(); FieldRow(label: String(localized: "Confirmations de la transaction"), value: String(c)) }258            if let t = op.txid { Divider(); FieldRow(label: String(localized: "Transaction"), value: t, mono: true, copyable: true) }259            if let l = op.ledger { Divider(); FieldRow(label: String(localized: "Registre de la plateforme"), value: [l.type, l.usdc.map { "\($0) USDC" }, l.hash].compactMap { $0 }.joined(separator: " · "), mono: true) }260            if let a = op.arrival { Divider(); FieldRow(label: String(localized: "Arrivée vue par le portefeuille"), value: [a.amount.map { "\($0) USDC" }, a.txid].compactMap { $0 }.joined(separator: " · "), mono: true) }261            if let e = op.error { Divider(); FieldRow(label: String(localized: "Erreur"), value: e, tone: .danger) }262        }263        if let e = op.explorer, let u = URL(string: e), u.scheme == "https" { Link(destination: u) { Label(String(localized: "Ouvrir dans l’explorateur"), systemImage: "arrow.up.right.square") }.buttonStyle(.spSecondary) }264        Button(String(localized: "Terminer")) { dismiss() }.buttonStyle(.spSecondary).accessibilityIdentifier("futures.collateral.done")265            .task(id: op.id) {266                while !Task.isCancelled, tracking?.final == false {267                    try? await Task.sleep(for: .seconds(5))268                    if let fresh = try? await fm.collateralAPI.operation(account.id, operationId: op.id) { tracking = fresh; if fresh.final { changed(); await fm.loadLiveDetail() } }269                }270            }271    }272273    private func prepare() async {274        guard let amount, let ownAddress, !busy else { return }275        busy = true; error = nil276        defer { busy = false }277        do {278            switch kind {279            case .deposit: deposit = try await fm.collateralAPI.prepareDeposit(for: account, amount: amount, ownAddress: ownAddress)280            case .withdraw: withdrawal = try await fm.collateralAPI.prepareWithdraw(for: account, amount: amount, ownAddress: ownAddress)281            }282        } catch { self.error = error }283    }284285    private func approve() async {286        guard !busy else { return }287        busy = true; error = nil288        defer { busy = false }289        let operationId = deposit?.operation.id ?? withdrawal?.operation.id290        do {291            if let d = deposit { tracking = try await fm.collateralAPI.approveDeposit(d, with: model.env.passkeys) }292            else if let w = withdrawal { tracking = try await fm.collateralAPI.approveWithdraw(w, with: model.env.passkeys) }293            changed()294        } catch PasskeyError.cancelled {295        } catch let e as APIError where e.isOffline {296            // the answer was lost after the assertion left: read the operation instead of signing again297            if let id = operationId, let op = try? await fm.collateralAPI.operation(account.id, operationId: id), op.state != "prepared" { tracking = op } else { error = e }298        } catch { self.error = error }299    }300301    private func cancel() async {302        if let id = deposit?.operation.id ?? withdrawal?.operation.id { _ = try? await fm.collateralAPI.cancel(account.id, operationId: id) }303        changed(); dismiss()304    }305}306307/** GMX v2 is not offered by this terminal (`OfferedVenues`): its state is still shown as served, so that nothing that exists is hidden. */308struct GmxStatusRow: View {309    @Environment(AppModel.self) private var model310    let fm: FuturesModel311    @State private var status: GmxStatus?312    @State private var error: Error?313314    var body: some View {315        if !OfferedVenues.offers("gmx") {316            VStack(alignment: .leading, spacing: 6) {317                HStack { Text("GMX v2").font(.spCallout.weight(.semibold)); Spacer(); Pill(text: String(localized: "non proposé dans cette app"), tone: .neutral) }318                if let s = status {319                    Text(String(localized: "Réglages du serveur : trading réel mainnet \(s.settings.liveMainnet ? "ouvert" : "fermé") · GMX \(s.settings.gmxLive ? "ouvert" : "fermé"). Négociable selon le serveur : \(s.tradable ? "oui" : "non")."))320                        .font(.spFootnote).foregroundStyle(Theme.ink).fixedSize(horizontal: false, vertical: true)321                    ForEach(s.refusals, id: \.code) { r in322                        Label((r.reason.isEmpty ? "" : r.reason + " ") + "(\(r.code))", systemImage: r.kind == .lock ? "lock.fill" : "info.circle").font(.system(size: 12.5)).foregroundStyle(Theme.mute).fixedSize(horizontal: false, vertical: true)323                    }324                    if !s.positions.isEmpty || !s.pendingOrders.isEmpty {325                        Notice(tone: .warn, title: String(localized: "Exposition existante sur GMX"), message: String(localized: "\(s.positions.count) position(s), \(s.pendingOrders.count) ordre(s) en attente, selon le serveur. Cette app n’a pas d’écran GMX : utilise l’interface web du portefeuille."))326                    }327                } else if let e = error { Text(ErrorNotice.detail(e)).font(.spFootnote).foregroundStyle(Theme.warn) }328                else { Text(model.canOperate ? String(localized: "Lecture de l’état…") : String(localized: "État illisible hors ligne.")).font(.spFootnote).foregroundStyle(Theme.mute) }329            }330            .spCard()331            .accessibilityIdentifier("futures.gmx.status")332            .task { guard model.canOperate else { return }; do { status = try await DerivativesGMXAPI(model.env.client).status(locale: FuturesText.locale) } catch { self.error = error } }333        }334    }335}336
Files main
Menu

Theme