SPB Git

Repository Public

DerivativesLiveAPI.swift 41.4 KB 542 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Derivatives/DerivativesLiveAPI.swift3// Description: Controlled LIVE trading on a venue account (Hyperliquid) and its collateral — every route of `liveRoutes` and4//              `collateralRoutes` (services/api/src/derivatives/live-routes.ts, collateral-routes.ts). Each passkey approval is5//              prepare → strict parse of the canonical object → comparison with what was asked → `ApprovalBinding.verify` →6//              passkey → approve. The approve functions only take the verified types built here. Stopping (cancel, cancel-all,7//              halt, revoke) never needs a passkey; nothing here defaults a leverage, a limit or a slippage bound.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation1213// MARK: what a preparation returns1415public struct LiveAuthorizationPreparation: Sendable {16    public struct Agent: Codable, Sendable, Hashable { public let address: String; public let name: String; public let wireName: String?; public let validUntil: Date?; public let can: [String]?; public let cannot: [String]?; public let note: String? }17    public struct WhatIsSigned: Codable, Sendable, Hashable { public let byMainKey: String?; public let byPasskey: String? }18    public let accountId: LiveAccountID19    public let approval: VerifiedApproval<VenueAuthorization>20    /** The text to DISPLAY before the passkey is asked; the authorization commits to its hash. */21    public let acknowledgement: JurisdictionAck22    /** The dedicated trading key: what it can and cannot do, in the server's words. */23    public let agent: Agent?24    public let whatIsSigned: WhatIsSigned?25    public let venueState: LiveVenueState?26    public var authorization: VenueAuthorization { approval.object }27}2829public struct LiveMandatePreparation: Sendable {30    public struct WindDown: Codable, Sendable, Hashable { public let seconds: Int?; public let text: String? }31    public let accountId: LiveAccountID32    public let approval: VerifiedApproval<VenueMandate>33    public let acknowledgement: JurisdictionAck34    /** "After this approval, orders inside these limits are placed WITHOUT asking for your passkey." — the server's sentence, to display. */35    public let warning: String?36    public let enforcedBySigner: [String]?37    public let trustedBySigner: [String]?38    public let notEnforced: [String]?39    public let windDown: WindDown?40    public let venueState: LiveVenueState?41    public var mandate: VenueMandate { approval.object }42}4344/** A verified order, ready for the passkey. Built only by `proposeOrder` / `proposeClose`. */45public struct LiveOrderApproval: Sendable {46    public let accountId: LiveAccountID47    /** The Idempotency-Key of the proposal. */48    public let clientId: String49    public let approval: VerifiedApproval<VenueOrder>50    public var order: VenueOrder { approval.object }51}5253public struct LiveOrderProposal: Sendable {54    public let order: LiveOrder55    public let estimate: LiveOrderEstimate?56    /** True when the key had already been used: the STORED order was answered (and checked against this request like any other). */57    public let idempotent: Bool58    /** Nil when there is nothing (left) to approve: refused, expired, already approved. */59    public let approvable: LiveOrderApproval?60    /** Close only. */61    public let worstPrice: String?62    public let slippageBoundBps: Int?63    public let position: DerivPosition?64}6566public struct LiveLeverageApproval: Sendable {67    public let accountId: LiveAccountID68    public let action: LiveAction69    public let approval: VerifiedApproval<VenueLeverage>70    /** The venue's present setting; nil when it could not be read. */71    public let current: LiveLeverageSetting?72    public var change: VenueLeverage { approval.object }73}7475public struct LiveRiskApproval: Sendable {76    public let accountId: LiveAccountID77    public let approval: VerifiedApproval<LiveRiskIntent>78    public var intent: LiveRiskIntent { approval.object }79}8081public enum LiveRiskPreparation: Sendable {82    /** Nothing loosens (use `setPolicy`), or there is no owner halt to lift: no passkey is asked for nothing. */83    case notNeeded84    case approval(LiveRiskApproval)85}8687public struct DerivativesLiveAPI: Sendable {88    let client: APIClient89    public init(_ client: APIClient) { self.client = client }9091    private static let base = "/derivatives/live"92    private func acct(_ id: LiveAccountID) -> String { "\(Self.base)/accounts/\(APIClient.segment(id.rawValue))" }93    private var rpId: String { client.configuration.rpId }9495    // MARK: configuration, locks, jurisdiction9697    /** The server locks (mainnet, mandates), the pinned asset table with each instrument's venue maximum leverage, the bounds. */98    public func config(locale: String? = nil) async throws -> LiveConfig { try await client.get("\(Self.base)/config", query: ["locale": locale]) }99100    /** The jurisdiction summary of Hyperliquid in both languages. General information, not a legal clearance. */101    public func jurisdiction() async throws -> JurisdictionAnswer { try await client.get("\(Self.base)/jurisdiction", query: ["venue": "hyperliquid"]) }102103    public func venueKey(venue: String, network: String) async throws -> LiveVenueKey {104        struct Body: Encodable, Sendable { let venue: String; let network: String }105        return try await client.post("\(Self.base)/venue-key", body: Body(venue: venue, network: network))106    }107108    // MARK: accounts109110    public func accounts() async throws -> [LiveAccount] { try await client.get("\(Self.base)/accounts", as: LiveAccountsAnswer.self).accounts }111112    /** One account per venue and network, created READ_ONLY (it trades nothing). A mainnet account is refused while the server keeps mainnet closed. */113    public func createAccount(network: String, label: String) async throws -> LiveAccountDetail {114        struct Body: Encodable, Sendable { let venue: String; let network: String; let label: String }115        return try await client.post("\(Self.base)/accounts", body: Body(venue: "hyperliquid", network: network, label: label))116    }117118    /** The account, the venue's own state (margin summary, positions with the venue's liquidation prices, open orders), orders, fills, funding, risk events. */119    public func account(_ id: LiveAccountID) async throws -> LiveAccountDetail { try await client.get(acct(id)) }120121    public func collateralSummary(_ id: LiveAccountID, locale: String? = nil) async throws -> LiveCollateralSummary { try await client.get("\(acct(id))/collateral", query: ["locale": locale]) }122123    /** Path of the account's server-sent events (`status`, `account`, `order`, `action`, `risk`), below /api/v1. See `DerivativesAPI.marketStream`. */124    public func accountStream(_ id: LiveAccountID) -> String { "\(acct(id))/stream" }125126    /** One reconciliation pass with the venue now. */127    public func reconcile(_ id: LiveAccountID) async throws -> LiveReconcile { try await client.post("\(acct(id))/reconcile") }128129    // MARK: venue authorization (READ_ONLY → MANUAL_LIVE)130131    /**132     Step 1 of enabling live trading. The authorization the server prepared must carry exactly the limits asked for, for this133     account, network and trading key, for `days` days, and commit to the hash of the acknowledgement text that will be displayed.134     */135    public func prepareAuthorization(for account: LiveAccount, policy: VenuePolicy, days: Int, locale: String, agentName: String? = nil, now: Date = Date()) async throws -> LiveAuthorizationPreparation {136        struct Body: Encodable, Sendable { let policy: VenuePolicy; let days: Int; let locale: String; let agentName: String? }137        struct Answer: Decodable, Sendable {138            let authorization: VenueAuthorization; let hash: String?; let acknowledgement: JurisdictionAck; let agent: LiveAuthorizationPreparation.Agent?139            let whatIsSigned: LiveAuthorizationPreparation.WhatIsSigned?; let venueState: LiveVenueState?; let options: PasskeyRequestOptions140        }141        let a: Answer = try await client.post("\(acct(account.id))/authorization/prepare", body: Body(policy: policy, days: days, locale: locale, agentName: agentName))142        try Self.check(authorization: a.authorization, account: account, policy: policy, days: days, agentName: agentName ?? a.agent?.name, now: now)143        try DerivApproval.requireAck(a.acknowledgement, sha: a.authorization.ackSha256, venue: "hyperliquid", locale: locale)144        try DerivApproval.requireHash(a.hash, of: a.authorization)145        return LiveAuthorizationPreparation(accountId: account.id, approval: try ApprovalBinding.verify(a.authorization, options: a.options, rpId: rpId), acknowledgement: a.acknowledgement,146                                            agent: a.agent, whatIsSigned: a.whatIsSigned, venueState: a.venueState)147    }148149    public static func check(authorization x: VenueAuthorization, account: LiveAccount, policy: VenuePolicy, days: Int, agentName: String?, now: Date) throws {150        guard x.venue == account.venue else { throw DerivApproval.no("venue") }151        guard x.network == account.network else { throw DerivApproval.no("network") }152        guard x.account == account.account else { throw DerivApproval.no("account") }153        guard x.agentAddress == account.agentAddress.lowercased(), x.agentAddress != x.account else { throw DerivApproval.no("trading key") }154        guard x.mode == "MANUAL_LIVE" else { throw DerivApproval.no("mode") }155        guard x.policy.sameLimits(as: policy) else { throw DerivApproval.no("limits") }156        guard x.expiresAt - x.createdAt == days * 86_400 else { throw DerivApproval.no("duration") }157        if let agentName { guard x.agentName == agentName else { throw DerivApproval.no("trading key name") } }158        guard x.expiry > now else { throw ApprovalError.expired }159    }160161    /**162     Step 2. `acknowledged` is the owner's own statement that the jurisdiction summary was displayed and read: the caller sets it163     from the screen, it is never assumed. The isolated signer judges the passkey, stores the limits and signs the venue approval.164     */165    public func approveAuthorization(_ p: LiveAuthorizationPreparation, acknowledged: Bool, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> LiveAccountDetail {166        guard acknowledged else { throw ApprovalError.inconsistent("the jurisdiction summary was not acknowledged") }167        guard p.authorization.expiry > now else { throw ApprovalError.expired }168        let assertion = try await DerivApproval.assertion(p.approval.options, client, authenticator)169        return try await client.post("\(acct(p.accountId))/authorization/approve", body: AcknowledgedAssertionBody(assertion: assertion, acknowledged: true))170    }171172    /** Back to READ_ONLY — no passkey. `cancelOpenOrders`: also withdraw every order resting on the venue first. Positions stay open. */173    public func revokeAuthorization(_ id: LiveAccountID, cancelOpenOrders: Bool, locale: String) async throws -> LiveAccountDetail {174        struct Body: Encodable, Sendable { let cancelOpenOrders: Bool; let locale: String }175        return try await client.post("\(acct(id))/authorization/revoke", body: Body(cancelOpenOrders: cancelOpenOrders, locale: locale))176    }177178    /** After a lost answer of the signer: adopts the authorization the passkey approved, or revokes it. No passkey: it only takes or removes. */179    public func recoverAuthorization(_ id: LiveAccountID) async throws -> LiveAccountDetail { try await client.post("\(acct(id))/authorization/recover") }180181    // MARK: API-side risk policy, halt, re-base182183    /** Tightening is free. A change that loosens anything is refused with `passkey_required`: use `preparePolicyChange`. */184    public func setPolicy(_ id: LiveAccountID, policy: DerivRiskPolicy) async throws -> LiveAccountDetail { try await client.post("\(acct(id))/policy", body: policy) }185186    public func preparePolicyChange(for account: LiveAccount, policy: DerivRiskPolicy, now: Date = Date()) async throws -> LiveRiskPreparation {187        try await prepareRisk(account, .policy, path: "policy/prepare", body: policy, policy: policy, now: now)188    }189    /** Lifting the OWNER's halt (the passkey signs the halt being lifted). A divergence is not lifted here. */190    public func prepareResume(for account: LiveAccount, now: Date = Date()) async throws -> LiveRiskPreparation {191        try await prepareRisk(account, .resume, path: "resume/prepare", body: nil, policy: nil, now: now)192    }193    /** Accepting the venue's present positions as the reference after a divergence. */194    public func prepareRebase(for account: LiveAccount, now: Date = Date()) async throws -> LiveRiskPreparation {195        try await prepareRisk(account, .rebase, path: "rebase/prepare", body: nil, policy: nil, now: now)196    }197198    private func prepareRisk(_ account: LiveAccount, _ kind: LiveRiskIntent.Kind, path: String, body: DerivRiskPolicy?, policy: DerivRiskPolicy?, now: Date) async throws -> LiveRiskPreparation {199        struct Answer: Decodable, Sendable { let needed: Bool; let intent: LiveRiskIntent?; let hash: String?; let options: PasskeyRequestOptions? }200        let a: Answer = try await client.post("\(acct(account.id))/\(path)", body: body)201        guard a.needed else { return .notNeeded }202        guard let intent = a.intent, let options = a.options else { throw ApprovalError.unsupported("the server asked for an approval without the object to approve") }203        try Self.check(risk: intent, kind: kind, account: account, policy: policy, now: now)204        try DerivApproval.requireHash(a.hash, of: intent)205        return .approval(LiveRiskApproval(accountId: account.id, approval: try ApprovalBinding.verify(intent, options: options, rpId: rpId)))206    }207208    public static func check(risk i: LiveRiskIntent, kind: LiveRiskIntent.Kind, account: LiveAccount, policy: DerivRiskPolicy?, now: Date) throws {209        guard i.kind == kind else { throw DerivApproval.no("kind of change") }210        guard i.accountId == account.id.rawValue, i.venue == account.venue, i.network == account.network, i.account == account.account else { throw DerivApproval.no("account") }211        guard let auth = account.authorization, i.authorizationId == auth.id else { throw DerivApproval.no("authorization") }212        switch kind {213        case .policy: guard let policy, i.policy == policy else { throw DerivApproval.no("policy") }214        case .resume: guard i.subject == account.halt, i.subject != nil else { throw DerivApproval.no("halt") }215        case .rebase: guard i.subject == account.divergence else { throw DerivApproval.no("divergence") }216        }217        guard i.expiry > now else { throw ApprovalError.expired }218    }219220    /** Applies a prepared risk change: the loosened policy, the lifting of the halt, or the re-base — whichever was prepared and verified. */221    public func approveRiskChange(_ r: LiveRiskApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> LiveAccountDetail {222        guard r.intent.expiry > now else { throw ApprovalError.expired }223        let assertion = try await DerivApproval.assertion(r.approval.options, client, authenticator)224        let path: String225        switch r.intent.kind { case .policy: path = "policy/approve"; case .resume: path = "resume"; case .rebase: path = "rebase" }226        return try await client.post("\(acct(r.accountId))/\(path)", body: DerivAssertionBody(assertion: assertion))227    }228229    /** Stops NEW orders on this account — no passkey. It cancels nothing and closes nothing (`note` says so). */230    public func halt(_ id: LiveAccountID, reason: String) async throws -> LiveAccountDetail {231        struct Body: Encodable, Sendable { let reason: String }232        return try await client.post("\(acct(id))/halt", body: Body(reason: reason))233    }234235    // MARK: derivative mandate (MANDATE_LIVE)236237    public func mandateStatus(_ id: LiveAccountID) async throws -> LiveMandateStatus { try await client.get("\(acct(id))/mandate") }238239    /** Step 1 of letting an automated strategy trade without a passkey per order, inside limits the signer enforces. */240    public func prepareMandate(for account: LiveAccount, request: LiveMandateRequest, now: Date = Date()) async throws -> LiveMandatePreparation {241        struct Answer: Decodable, Sendable {242            let mandate: VenueMandate; let hash: String?; let acknowledgement: JurisdictionAck; let warning: String?; let enforcedBySigner: [String]?; let trustedBySigner: [String]?243            let notEnforced: [String]?; let windDown: LiveMandatePreparation.WindDown?; let venueState: LiveVenueState?; let options: PasskeyRequestOptions244        }245        let a: Answer = try await client.post("\(acct(account.id))/mandate/prepare", body: request)246        try Self.check(mandate: a.mandate, account: account, request: request, now: now)247        try DerivApproval.requireAck(a.acknowledgement, sha: a.mandate.ackSha256, venue: "hyperliquid", locale: request.locale)248        try DerivApproval.requireHash(a.hash, of: a.mandate)249        return LiveMandatePreparation(accountId: account.id, approval: try ApprovalBinding.verify(a.mandate, options: a.options, rpId: rpId), acknowledgement: a.acknowledgement, warning: a.warning,250                                      enforcedBySigner: a.enforcedBySigner, trustedBySigner: a.trustedBySigner, notEnforced: a.notEnforced, windDown: a.windDown, venueState: a.venueState)251    }252253    public static func check(mandate m: VenueMandate, account: LiveAccount, request r: LiveMandateRequest, now: Date) throws {254        guard m.venue == account.venue, m.network == account.network, m.account == account.account, m.agentAddress == account.agentAddress.lowercased() else { throw DerivApproval.no("account") }255        guard let auth = account.authorization, m.authorizationId == auth.id else { throw DerivApproval.no("authorization") }256        guard m.strategySha256 == r.strategySha256, m.agentId == r.agentId else { throw DerivApproval.no("strategy or agent") }257        guard m.instruments.count == r.instruments.count, Set(m.instruments.map(\.instrument)).count == m.instruments.count else { throw DerivApproval.no("instruments") }258        for want in r.instruments {259            guard let got = m.instruments.first(where: { $0.instrument == want.instrument }), got.maxLeverage == want.maxLeverage,260                  VenueDecimal.same(got.maxPositionNotional, want.maxPositionNotional) else { throw DerivApproval.no("limits of \(want.instrument)") }261        }262        guard VenueDecimal.same(m.maxOrderNotional, r.maxOrderNotional), VenueDecimal.same(m.maxGrossExposure, r.maxGrossExposure), VenueDecimal.same(m.maxDailyTurnover, r.maxDailyTurnover),263              VenueDecimal.same(m.floorEquity, r.floorEquity), m.maxOrdersPerDay == r.maxOrdersPerDay, m.maxOrdersPerHour == r.maxOrdersPerHour,264              m.maxPriceDeviationBps == r.maxPriceDeviationBps else { throw DerivApproval.no("limits") }265        guard m.expiresAt - m.createdAt == r.days * 86_400 else { throw DerivApproval.no("duration") }266        guard m.expiry > now else { throw ApprovalError.expired }267    }268269    public func approveMandate(_ p: LiveMandatePreparation, acknowledged: Bool, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> LiveAccountDetail {270        guard acknowledged else { throw ApprovalError.inconsistent("the jurisdiction summary was not acknowledged") }271        guard p.mandate.expiry > now else { throw ApprovalError.expired }272        let assertion = try await DerivApproval.assertion(p.approval.options, client, authenticator)273        return try await client.post("\(acct(p.accountId))/mandate/approve", body: AcknowledgedAssertionBody(assertion: assertion, acknowledged: true))274    }275276    /** Stops the mandate — no passkey. Positions are NOT closed (`windDown` says what still happens). */277    public func revokeMandate(_ id: LiveAccountID, cancelOpenOrders: Bool, locale: String) async throws -> LiveAccountDetail {278        struct Body: Encodable, Sendable { let cancelOpenOrders: Bool; let locale: String }279        return try await client.post("\(acct(id))/mandate/revoke", body: Body(cancelOpenOrders: cancelOpenOrders, locale: locale))280    }281282    // MARK: orders283284    /** The risk engine on the venue's REAL account state, and an estimate; nothing is stored. A lock or a read-only account is an error with its code. */285    public func previewOrder(_ id: LiveAccountID, order: LiveOrderRequest) async throws -> LiveOrderPreview { try await client.post("\(acct(id))/orders/preview", body: order) }286287    private struct ProposalAnswer: Decodable, Sendable {288        let order: LiveOrder; let canonical: VenueOrder?; let hash: String?; let estimate: LiveOrderEstimate?; let idempotent: Bool?; let options: PasskeyRequestOptions?289        let worstPrice: String?; let slippageBoundBps: Int?; let position: DerivPosition?290    }291292    /**293     Propose ONE order. `idempotencyKey` is the order's client id; the venue's own client order id is derived from it, so a retry294     can never place a second order. The canonical order (what the passkey signs) is compared with the request field by field —295     which is also what keeps the stored order of a re-used key from being approved by mistake.296     */297    public func proposeOrder(for account: LiveAccount, order: LiveOrderRequest, idempotencyKey: String, now: Date = Date()) async throws -> LiveOrderProposal {298        let a: ProposalAnswer = try await client.post("\(acct(account.id))/orders", body: order, idempotencyKey: idempotencyKey)299        return try proposal(a, account: account, key: idempotencyKey, now: now) { try Self.check(order: $0, request: order) }300    }301302    /**303     Propose a reduce-only market order on `fraction` (0 < f ≤ 1) of the VENUE's position, bounded at `slippageBps` from the book.304     `position` is the position the owner is looking at: the canonical order must reduce it and never exceed it.305     */306    public func proposeClose(for account: LiveAccount, position: DerivPosition, fraction: String, slippageBps: Int, idempotencyKey: String, now: Date = Date()) async throws -> LiveOrderProposal {307        struct Body: Encodable, Sendable { let instrument: String; let fraction: String; let slippageBps: Int }308        let a: ProposalAnswer = try await client.post("\(acct(account.id))/close", body: Body(instrument: position.instrument, fraction: fraction, slippageBps: slippageBps), idempotencyKey: idempotencyKey)309        return try proposal(a, account: account, key: idempotencyKey, now: now) { c in310            try Self.check(close: c, position: position, fraction: fraction)311            if let w = a.worstPrice { guard VenueDecimal.same(c.price, w) else { throw DerivApproval.no("worst price") } }312        }313    }314315    private func proposal(_ a: ProposalAnswer, account: LiveAccount, key: String, now: Date, check: (VenueOrder) throws -> Void) throws -> LiveOrderProposal {316        guard a.order.clientId == key else { throw DerivApproval.no("order key") }317        var approvable: LiveOrderApproval?318        if let options = a.options {319            guard let c = a.canonical else { throw ApprovalError.unsupported("the server asked for an approval without the order to approve") }320            try check(c)321            try Self.check(order: c, account: account, key: key, now: now)322            try DerivApproval.requireHash(a.hash, of: c)323            approvable = LiveOrderApproval(accountId: account.id, clientId: key, approval: try ApprovalBinding.verify(c, options: options, rpId: rpId))324        }325        return LiveOrderProposal(order: a.order, estimate: a.estimate, idempotent: a.idempotent ?? false, approvable: approvable, worstPrice: a.worstPrice, slippageBoundBps: a.slippageBoundBps, position: a.position)326    }327328    /** Is the canonical order the order that was asked for? A market order comes back as a limit IOC at its worst price: that is expected. */329    public static func check(order c: VenueOrder, request r: LiveOrderRequest) throws {330        guard c.instrument == r.instrument else { throw DerivApproval.no("instrument") }331        guard c.side == r.side.rawValue else { throw DerivApproval.no("side") }332        guard VenueDecimal.same(c.size, r.size) else { throw DerivApproval.no("size") }333        guard c.reduceOnly == r.reduceOnly else { throw DerivApproval.no("reduce-only") }334        let market = r.type == .market335        guard c.type == (market ? "limit" : r.type.rawValue) else { throw DerivApproval.no("order type") }336        guard c.tif == (market ? "ioc" : r.tif.rawValue) else { throw DerivApproval.no("time in force") }337        switch (c.triggerPrice, r.triggerPrice) {338        case (nil, nil): break339        case let (a?, b?): guard VenueDecimal.same(a, b) else { throw DerivApproval.no("trigger price") }340        default: throw DerivApproval.no("trigger price")341        }342        if let p = r.price { guard VenueDecimal.same(c.price, p) else { throw DerivApproval.no("price") } }343        else { guard market, r.slippageBps != nil else { throw DerivApproval.no("price") } }344    }345346    /** The same for a close: reduce-only, immediate, the side that reduces the position, at most the position's size (the whole of it for a fraction of 1). */347    public static func check(close c: VenueOrder, position: DerivPosition, fraction: String) throws {348        guard c.instrument == position.instrument else { throw DerivApproval.no("instrument") }349        guard c.side == (position.side == "long" ? "sell" : "buy"), position.side == "long" || position.side == "short" else { throw DerivApproval.no("side") }350        guard c.reduceOnly else { throw DerivApproval.no("reduce-only") }351        guard c.type == "limit", c.tif == "ioc", c.triggerPrice == nil else { throw DerivApproval.no("order type") }352        guard let s = VenueDecimal(c.size), let p = VenueDecimal(position.size), let f = VenueDecimal(fraction), s.isPositive, s <= p else { throw DerivApproval.no("size") }353        if f == VenueDecimal("1") { guard s == p else { throw DerivApproval.no("size") } }354    }355356    /** The order is for THIS account under its present authorization, carries the client order id of THIS key, and its window is open and short. */357    public static func check(order c: VenueOrder, account: LiveAccount, key: String, now: Date) throws {358        guard c.venue == account.venue, c.network == account.network, c.account == account.account else { throw DerivApproval.no("account") }359        guard let auth = account.authorization, c.authorizationId == auth.id else { throw DerivApproval.no("authorization") }360        guard let cloid = HyperliquidClientOrderID.derive(from: key), c.clientId == cloid else { throw DerivApproval.no("client order id") }361        guard c.expiresAt > c.nonce, c.expiresAt - c.nonce <= 120_000 else { throw DerivApproval.no("validity window") }362        guard c.expiry > now else { throw ApprovalError.expired }363    }364365    /** Passkey → signer → venue → reconciliation. The answered order is the venue's word, or `unknown` when it gave none: never assumed. */366    public func approveOrder(_ o: LiveOrderApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> LiveOrderResult {367        // the server stops 2 s before the venue expiry368        guard o.order.expiry.timeIntervalSince(now) > 2 else { throw ApprovalError.expired }369        return try await submit(assertion: try await DerivApproval.assertion(o.approval.options, client, authenticator), for: o)370    }371372    /** Second half of `approveOrder`, for an approval whose answer was lost: the server sends an order once however many times it is approved. */373    public func submit(assertion: PasskeyAssertion, for o: LiveOrderApproval) async throws -> LiveOrderResult {374        try await client.post("\(acct(o.accountId))/orders/\(APIClient.segment(o.clientId))/approve", body: DerivAssertionBody(assertion: assertion))375    }376377    /** No passkey. Before approval it only withdraws the proposal (`sent == false`); after, the venue is asked. */378    public func cancelOrder(_ id: LiveAccountID, clientId: String) async throws -> LiveOrderResult { try await client.post("\(acct(id))/orders/\(APIClient.segment(clientId))/cancel") }379380    /** Cancels every order resting on the venue account (the venue's own list) — no passkey. It closes no position. */381    public func cancelAll(_ id: LiveAccountID) async throws -> LiveCancelAll { try await client.post("\(acct(id))/cancel-all") }382383    // MARK: leverage384385    /** Propose the leverage SETTING of one instrument on the venue. Every parameter is the caller's: nothing is defaulted. */386    public func proposeLeverage(for account: LiveAccount, instrument: String, leverage: Int, marginMode: DerivMarginMode, now: Date = Date()) async throws -> LiveLeverageApproval {387        struct Body: Encodable, Sendable { let instrument: String; let leverage: Int; let marginMode: DerivMarginMode }388        struct Answer: Decodable, Sendable { let action: LiveAction; let canonical: VenueLeverage; let hash: String?; let current: LiveLeverageSetting?; let options: PasskeyRequestOptions }389        let a: Answer = try await client.post("\(acct(account.id))/leverage", body: Body(instrument: instrument, leverage: leverage, marginMode: marginMode))390        try Self.check(leverage: a.canonical, account: account, instrument: instrument, leverage: leverage, marginMode: marginMode, now: now)391        try DerivApproval.requireHash(a.hash, of: a.canonical)392        if let h = a.action.hash { try DerivApproval.requireHash(h, of: a.canonical) }393        return LiveLeverageApproval(accountId: account.id, action: a.action, approval: try ApprovalBinding.verify(a.canonical, options: a.options, rpId: rpId), current: a.current)394    }395396    public static func check(leverage c: VenueLeverage, account: LiveAccount, instrument: String, leverage: Int, marginMode: DerivMarginMode, now: Date) throws {397        guard c.venue == account.venue, c.network == account.network, c.account == account.account else { throw DerivApproval.no("account") }398        guard let auth = account.authorization, c.authorizationId == auth.id else { throw DerivApproval.no("authorization") }399        guard c.instrument == instrument else { throw DerivApproval.no("instrument") }400        guard c.leverage == leverage else { throw DerivApproval.no("leverage") }401        guard c.marginMode == marginMode.rawValue else { throw DerivApproval.no("margin mode") }402        guard c.expiresAt > c.nonce, c.expiresAt - c.nonce <= 120_000 else { throw DerivApproval.no("validity window") }403        guard c.expiry > now else { throw ApprovalError.expired }404    }405406    /** `venue.confirmed` says whether the venue now reports the setting; it is the venue's answer, not an assumption. */407    public func approveLeverage(_ l: LiveLeverageApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> LiveLeverageResult {408        guard l.change.expiry.timeIntervalSince(now) > 2 else { throw ApprovalError.expired }409        let assertion = try await DerivApproval.assertion(l.approval.options, client, authenticator)410        return try await client.post("\(acct(l.accountId))/leverage/\(APIClient.segment(l.action.id))/approve", body: DerivAssertionBody(assertion: assertion))411    }412}413414// MARK: collateral415416public struct CollateralDepositApproval: Sendable {417    public struct RouteFacts: Codable, Sendable, Hashable { public let network: String; public let networkName: String?; public let bridge: String; public let minimum: String?; public let venueMinimum: String?; public let expectedSeconds: Int? }418    public struct Fee: Codable, Sendable, Hashable { public let estimate: String; public let max: String; public let symbol: String }419    public struct Liveness: Codable, Sendable, Hashable { public let ok: Bool; public let checkedAt: Date?; public let checked: Int?; public let credited: Int?; public let detail: String? }420    public let accountId: LiveAccountID421    public let operation: CollateralOperation422    /** The wallet intent with its `venueDeposit` section: what the passkey signs. Its `maxFee` is the fee ceiling to display. */423    public let approval: VerifiedApproval<Intent>424    public let route: RouteFacts?425    public let fee: Fee?426    public let liveness: Liveness?427    public let venueBalance: CollateralVenueBalance?428    public var intent: Intent { approval.object }429}430431public struct CollateralWithdrawApproval: Sendable {432    public struct Action: Codable, Sendable, Hashable { public let type: String; public let hyperliquidChain: String; public let destination: String; public let amount: String; public let time: Int }433    public let accountId: LiveAccountID434    public let operation: CollateralOperation435    public let approval: VerifiedApproval<VenueWithdrawal>436    /** What should arrive on the wallet: the amount minus the venue's fee, as the server states it (and as recomputed here). */437    public let receive: String438    /** The one venue action the signer will build from the canonical withdrawal, as described by the server. */439    public let action: Action?440    public let venueBalance: CollateralVenueBalance?441    public var withdrawal: VenueWithdrawal { approval.object }442}443444public struct DerivativesCollateralAPI: Sendable {445    let client: APIClient446    public init(_ client: APIClient) { self.client = client }447448    private func base(_ id: LiveAccountID) -> String { "/derivatives/live/accounts/\(APIClient.segment(id.rawValue))/collateral" }449    private struct AmountBody: Encodable, Sendable { let amount: String }450451    /** Venue balance, the pinned route and its facts, the wallet side, whether a deposit / a withdrawal can be prepared now (with the reason code when not), the operations. */452    public func status(_ id: LiveAccountID) async throws -> CollateralStatus { try await client.get("\(base(id))/status") }453454    public func operation(_ id: LiveAccountID, operationId: String) async throws -> CollateralOperation {455        try await client.get("\(base(id))/operations/\(APIClient.segment(operationId))", as: CollateralOperationAnswer.self).operation456    }457458    /** Before the passkey only. */459    public func cancel(_ id: LiveAccountID, operationId: String) async throws -> CollateralOperation {460        try await client.post("\(base(id))/operations/\(APIClient.segment(operationId))/cancel", as: CollateralOperationAnswer.self).operation461    }462463    /**464     Prepare a deposit of `amount` USDC (decimal text, at most 6 decimals) from the wallet's own address to the venue's pinned bridge.465     - Parameter ownAddress: the wallet's own EVM address as the app knows it from the wallet (never taken from this answer).466     */467    public func prepareDeposit(for account: LiveAccount, amount: String, ownAddress: String, now: Date = Date()) async throws -> CollateralDepositApproval {468        struct Answer: Decodable, Sendable {469            let operation: CollateralOperation; let intent: Intent; let route: CollateralDepositApproval.RouteFacts?; let fee: CollateralDepositApproval.Fee?470            let liveness: CollateralDepositApproval.Liveness?; let venueBalance: CollateralVenueBalance?; let options: PasskeyRequestOptions471        }472        let a: Answer = try await client.post("\(base(account.id))/deposit/prepare", body: AmountBody(amount: amount))473        try Self.check(deposit: a.intent, amount: amount, account: account, ownAddress: ownAddress, now: now)474        guard a.operation.kind == "deposit", a.operation.venueNetwork == account.network else { throw DerivApproval.no("operation") }475        if let p = a.operation.proposalId { guard p == a.intent.proposalId else { throw DerivApproval.no("operation") } }476        try DerivApproval.requireHash(a.operation.hash, of: a.intent)477        return CollateralDepositApproval(accountId: account.id, operation: a.operation, approval: try ApprovalBinding.verify(a.intent, options: a.options, rpId: client.configuration.rpId),478                                         route: a.route, fee: a.fee, liveness: a.liveness, venueBalance: a.venueBalance)479    }480481    /**482     Everything a venue deposit must be (`checkVenueDepositIntent` of the backend, against the same pinned table): native USDC on483     Arbitrum One, from the wallet's own address — the venue credits the SENDER — to the pinned bridge, at least the 6 USDC floor,484     exactly the amount asked, no memo, nothing else riding along.485     */486    public static func check(deposit i: Intent, amount: String, account: LiveAccount, ownAddress: String, now: Date) throws {487        guard i.kind == .venueDeposit, let d = i.venueDeposit, i.evm != nil, i.memo == nil else { throw DerivApproval.no("not a venue deposit") }488        guard d.venue == "hyperliquid", account.venue == "hyperliquid", d.venueNetwork == account.network, d.venueNetwork == "mainnet" else { throw DerivApproval.no("venue network") }489        guard d.route == HyperliquidCollateralPins.route, i.network == HyperliquidCollateralPins.network, i.chainRef == HyperliquidCollateralPins.chainRef else { throw DerivApproval.no("deposit network") }490        guard i.asset == HyperliquidCollateralPins.usdc, i.symbol == "USDC", i.decimals == HyperliquidCollateralPins.usdcDecimals else { throw DerivApproval.no("asset") }491        guard d.bridge == HyperliquidCollateralPins.bridge, i.to == HyperliquidCollateralPins.bridge else { throw DerivApproval.no("destination is not the pinned bridge") }492        guard DerivApproval.sameAddress(i.from, ownAddress), DerivApproval.sameAddress(ownAddress, account.account) else { throw DerivApproval.no("source is not the wallet's own address") }493        guard d.minAmount == HyperliquidCollateralPins.minAmountUnits else { throw DerivApproval.no("minimum") }494        guard let want = VenueDecimal(amount)?.units(decimals: HyperliquidCollateralPins.usdcDecimals), i.amount == want else { throw DerivApproval.no("amount") }495        guard let floor = try? BaseUnits(d.minAmount), i.amountUnits >= floor else { throw DerivApproval.no("amount below the minimum") }496        guard i.expiry > now else { throw ApprovalError.expired }497    }498499    /** The passkey assertion over the intent hash is the approval; only the signer judges it. Done only when the operation reaches `credited`. */500    public func approveDeposit(_ d: CollateralDepositApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> CollateralOperation {501        guard d.intent.expiry > now else { throw ApprovalError.expired }502        let assertion = try await DerivApproval.assertion(d.approval.options, client, authenticator)503        return try await client.post("\(base(d.accountId))/deposit/\(APIClient.segment(d.operation.id))/approve", body: DerivAssertionBody(assertion: assertion), as: CollateralOperationAnswer.self).operation504    }505506    /** Prepare a withdrawal of `amount` USDC from the venue. The only destination that exists is the wallet's own address. */507    public func prepareWithdraw(for account: LiveAccount, amount: String, ownAddress: String, now: Date = Date()) async throws -> CollateralWithdrawApproval {508        struct WhatIsSigned: Decodable, Sendable { let action: CollateralWithdrawApproval.Action? }509        struct Answer: Decodable, Sendable {510            let operation: CollateralOperation; let withdrawal: VenueWithdrawal; let hash: String?; let whatIsSigned: WhatIsSigned?; let receive: String511            let venueBalance: CollateralVenueBalance?; let options: PasskeyRequestOptions512        }513        let a: Answer = try await client.post("\(base(account.id))/withdraw/prepare", body: AmountBody(amount: amount))514        try Self.check(withdrawal: a.withdrawal, amount: amount, receive: a.receive, account: account, ownAddress: ownAddress, now: now)515        guard a.operation.kind == "withdraw", a.operation.id == a.withdrawal.withdrawalId, a.operation.venueNetwork == account.network else { throw DerivApproval.no("operation") }516        if let x = a.whatIsSigned?.action {517            guard x.type == "withdraw3", x.destination == a.withdrawal.destination, VenueDecimal.same(x.amount, a.withdrawal.amount), x.time == a.withdrawal.time else { throw DerivApproval.no("venue action") }518        }519        try DerivApproval.requireHash(a.hash, of: a.withdrawal)520        try DerivApproval.requireHash(a.operation.hash, of: a.withdrawal)521        return CollateralWithdrawApproval(accountId: account.id, operation: a.operation, approval: try ApprovalBinding.verify(a.withdrawal, options: a.options, rpId: client.configuration.rpId),522                                          receive: a.receive, action: a.whatIsSigned?.action, venueBalance: a.venueBalance)523    }524525    public static func check(withdrawal w: VenueWithdrawal, amount: String, receive: String, account: LiveAccount, ownAddress: String, now: Date) throws {526        guard w.venue == account.venue, w.network == account.network, w.account == account.account else { throw DerivApproval.no("account") }527        guard w.destination == ownAddress.lowercased(), w.destination == w.account else { throw DerivApproval.no("destination is not the wallet's own address") }528        guard VenueDecimal.same(w.amount, amount) else { throw DerivApproval.no("amount") }529        // what arrives = amount − fee, exactly (USDC has 6 decimals)530        guard let a = VenueDecimal(w.amount)?.units(decimals: 6), let f = VenueDecimal(w.fee)?.units(decimals: 6), let au = try? BaseUnits(a), let fu = try? BaseUnits(f),531              let net = try? au.subtracting(fu), !net.isZero, VenueDecimal.same(net.formatted(decimals: 6), receive) else { throw DerivApproval.no("fee or amount received") }532        guard w.expiry > now else { throw ApprovalError.expired }533    }534535    /** Done only when the operation reaches `completed` (the wallet saw the USDC arrive). */536    public func approveWithdraw(_ w: CollateralWithdrawApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> CollateralOperation {537        guard w.withdrawal.expiry > now else { throw ApprovalError.expired }538        let assertion = try await DerivApproval.assertion(w.approval.options, client, authenticator)539        return try await client.post("\(base(w.accountId))/withdraw/\(APIClient.segment(w.operation.id))/approve", body: DerivAssertionBody(assertion: assertion), as: CollateralOperationAnswer.self).operation540    }541}542
Files main
Menu

Theme