SPB Git

Repository Public

DerivativesLiveModels.swift 35.5 KB 733 lines swift

1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Derivatives/DerivativesLiveModels.swift3// Description: Models of controlled LIVE trading (services/api/src/derivatives/exec.ts, live-routes.ts), of the collateral path4//              (collateral.ts) and of GMX v2 (gmx-exec.ts): server locks as served, venue accounts and their state machine5//              (READ_ONLY → MANUAL_LIVE, + MANDATE_LIVE), authorizations, orders, actions, fills, funding, collateral operations,6//              GMX status, positions and operations. Distinct types from the paper models on purpose.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112// MARK: configuration and locks, as served1314/** A server lock: open, or closed with its code and the server's sentence. */15public struct LiveLock: Codable, Sendable, Hashable {16    public let enabled: Bool17    public let code: String?18    public let reason: String?19}2021public struct LivePinnedAsset: Codable, Sendable, Hashable { public let instrument: String; public let maxLeverage: Int }2223/** `GET /derivatives/live/config`. Nothing here is decided by the client: the locks are the server's settings. */24public struct LiveConfig: Codable, Sendable, Hashable {25    public struct Venue: Codable, Sendable, Hashable { public let venue: String; public let networks: [String] }26    public struct MandateBounds: Codable, Sendable, Hashable { public let maxDays, maxOrdersPerHour, maxLeverageChangesPerDay, maxInstruments, windDownSeconds, orderTtlMs: Int? }27    public struct MandateLive: Codable, Sendable, Hashable {28        /** False: the signer connection offers no derivative mandate (`mandate_unavailable`). */29        public let available: Bool30        public let code: String?31        public let reason: String?32        /** Autonomous trading on mainnet: needs SPW_DERIV_LIVE_MAINNET and SPW_DERIV_MANDATE_MAINNET. */33        public let mainnet: LiveLock?34        public let bounds: MandateBounds?35    }36    public struct PinnedAssets: Codable, Sendable, Hashable { public let pinnedAt: String; public let mainnet: [LivePinnedAsset]; public let testnet: [LivePinnedAsset] }37    public struct Bounds: Codable, Sendable, Hashable { public let maxLeverage, maxOrdersPerDay, minPriceBandBps, maxPriceBandBps, maxInstruments, maxAuthorizationDays, orderApprovalTtlMs: Int? }38    public struct Reason: Codable, Sendable, Hashable { public let fr: String; public let en: String }3940    /** SPW_DERIV_LIVE_MAINNET. */41    public let mainnetEnabled: Bool42    public let locale: String?43    public let mainnet: LiveLock?44    public let venues: [Venue]45    public let modes: [String]46    public let mandateLive: MandateLive47    public let reasons: [String: Reason]?48    public let pinnedAssets: PinnedAssets49    public let bounds: Bounds50    public let ts: Date?51}5253/** The jurisdiction summary shown before live trading is enabled; the approved object commits to `sha256` of `text`. */54public struct JurisdictionAck: Codable, Sendable, Hashable {55    public let venue: String56    public let locale: String57    public let text: String58    public let sha256: String59    public let version: String?60    public let source: String?61    /** True when `sha256` really is the SHA-256 of the text that will be displayed. */62    public var textMatchesHash: Bool { DerivHash.sha256Hex(text) == sha256 }63}6465public struct JurisdictionAnswer: Codable, Sendable, Hashable { public let venue: String; public let fr: JurisdictionAck; public let en: JurisdictionAck }6667/** `POST /derivatives/live/venue-key`: the dedicated trading key the signer derives for a venue and network (an address; the key never leaves the signer). */68public struct LiveVenueKey: Codable, Sendable, Hashable {69    public let venue: String70    public let network: String71    public let address: String72    public let path: String?73    public let account: String74}7576// MARK: accounts7778/** A canonical object listed in a READ answer: kept as served, with its strict reading when this version of the app knows every field. */79public struct ServedCanonical<T: Decodable & Sendable>: Decodable, Sendable {80    public let value: T?81    public let raw: JSONValue82    public init(from decoder: Decoder) throws {83        raw = try JSONValue(from: decoder)84        value = try? raw.decode(T.self)85    }86}8788/** Mode of a venue account. `READ_ONLY` until the owner approves an authorization; `MANDATE_LIVE` is added while a mandate is active. */89public struct LiveAccountMode: RawRepresentable, Codable, Sendable, Hashable {90    public let rawValue: String91    public init(rawValue: String) { self.rawValue = rawValue }92    public static let readOnly = LiveAccountMode(rawValue: "READ_ONLY")93    public static let manualLive = LiveAccountMode(rawValue: "MANUAL_LIVE")94    public static let mandateLive = LiveAccountMode(rawValue: "MANDATE_LIVE")95}9697/** The policy of an authorization as the account lists it (lenient reading; the approved object is `VenueAuthorization`). */98public struct LiveAuthorizationPolicy: Codable, Sendable, Hashable {99    public let allowedInstruments: [String]100    public let maxLeverage: Int101    public let maxOrderNotional, maxPositionNotional, maxGrossExposure: String102    public let maxOrdersPerDay: Int103    public let maxPriceDeviationBps: Int104}105106public struct LiveAuthorizationSummary: Codable, Sendable, Hashable, Identifiable {107    public let id: String108    public let hash: String?109    public let mode: String110    public let agentName: String?111    public let policy: LiveAuthorizationPolicy112    public let createdAt: Date?113    public let expiresAt: Date?114    public let ackSha256: String?115    public let active: Bool116    public let expired: Bool117    public let revokedAt: Date?118    public let authorizedAt: Date?119}120121public struct LiveMandateSummary: Decodable, Sendable, Identifiable {122    public let id: String123    public let hash: String?124    public let authorizationId: String125    public let agentId: String126    public let strategySha256: String127    /** The mandate's limits; `value` is nil when this version of the app cannot read them strictly (they are then shown from `raw`, never approved). */128    public let limits: ServedCanonical<VenueMandate>?129    /** `active`, `wind_down`, `ended`. */130    public let phase: String131    public let active: Bool132    public let createdAt: Date?133    public let expiresAt: Date?134    public let expired: Bool?135    public let approvedAt: Date?136    public let revokedAt: Date?137    public let windDownUntil: Date?138    public let ackSha256: String?139}140141/** A venue account: the owner's own address on the venue. Real funds when `network == "mainnet"`. */142public struct LiveAccount: Decodable, Sendable, Identifiable {143    public struct Pending: Codable, Sendable, Hashable { public let authorizationId: String?; public let mandateId: String?; public let preparedAt: Date? }144    public let id: LiveAccountID145    public let venue: String146    /** `mainnet` or `testnet`. */147    public let network: String148    public let kind: String149    public let mode: LiveAccountMode150    public let label: String151    /** The venue account = the wallet's own EVM address, lower case. */152    public let account: String153    public let agentAddress: String154    public let policy: DerivRiskPolicy155    /** The owner's halt. */156    public let halt: String?157    public let divergence: String?158    /** The effective reason new orders are refused (halt or divergence), in the server's words. */159    public let halted: String?160    public let mainnetEnabled: Bool161    /** False while a lock, the mode or an expired authorization stops new risk. */162    public let tradable: Bool163    public let authorization: LiveAuthorizationSummary?164    public let pendingAuthorization: Pending?165    public let createdAt: Date?166    public let updatedAt: Date?167    public let modes: [LiveAccountMode]?168    public let mandate: LiveMandateSummary?169    public let pendingMandate: Pending?170    public var isMainnet: Bool { network != "testnet" }171}172173public struct LiveAccountsAnswer: Decodable, Sendable { public let accounts: [LiveAccount]; public let ts: Date? }174175/** The account as the venue reports it right now. `error != nil` = the venue could not be read: never show the account as empty. */176public struct LiveVenueState: Codable, Sendable, Hashable {177    /** Margin summary: equity, collateral, free collateral, margin used, maintenance margin, withdrawable. */178    public let state: DerivAccountState?179    /** Each with the liquidation price the VENUE reports. */180    public let positions: [DerivPosition]181    public let openOrders: [DerivOrder]182    public let error: String?183    public let ts: Date?184    public let source: String?185}186187/** State of a live order: `proposed → risk_checked → authorized → signed → submitted → open | partially_filled | filled | cancelled | rejected`, or `unknown`. */188public struct LiveOrderState: RawRepresentable, Codable, Sendable, Hashable {189    public let rawValue: String190    public init(rawValue: String) { self.rawValue = rawValue }191    public static let riskChecked = LiveOrderState(rawValue: "risk_checked")192    public static let unknown = LiveOrderState(rawValue: "unknown")193    /** The venue has confirmed nothing yet: never shown as done, never sent again. */194    public var isInFlight: Bool { ["authorized", "signed", "submitted", "unknown"].contains(rawValue) }195}196197public struct LiveOrder: Decodable, Sendable, Identifiable {198    /** The Idempotency-Key of the proposal. */199    public let clientId: String200    public let cloid: String?201    public let instrument: String202    public let side: String203    public let type: String204    public let size: String205    public let price: String?206    public let triggerPrice: String?207    public let reduceOnly: Bool208    public let tif: String209    public let state: LiveOrderState210    public let final: Bool211    public let venueOrderId: String?212    public let filled: String213    public let avgFillPrice: String?214    public let reason: String?215    /** `owner`, `close`, `mandate`. */216    public let origin: String?217    public let hash: String?218    public let nonce: Int?219    public let expiresAt: Date?220    /** The canonical order stored with the proposal (history: read leniently; an approval parses it strictly). */221    public let canonical: ServedCanonical<VenueOrder>?222    public let createdAt: Date?223    public let updatedAt: Date?224    public let submittedAt: Date?225    /** `venue`: the venue's own records; `local`: the wallet alone. */226    public let source: String?227    public var id: String { clientId }228}229230public struct LiveAction: Decodable, Sendable, Identifiable {231    public let id: String232    /** `leverage` or `cancel`. */233    public let kind: String234    public let state: String235    public let request: JSONValue?236    public let hash: String?237    public let nonce: Int?238    public let expiresAt: Date?239    public let error: String?240    public let createdAt: Date?241    public let updatedAt: Date?242}243244/** `GET /derivatives/live/accounts/:id` and every route that answers the account again. */245public struct LiveAccountDetail: Decodable, Sendable {246    public struct Recovered: Codable, Sendable, Hashable { public let what: String; public let id: String; public let outcome: String; public let detail: String }247    public struct CancelError: Codable, Sendable, Hashable { public let code: String; public let message: String }248    public struct WindDown: Codable, Sendable, Hashable { public let until: Date?; public let text: String?; public let openPositions: Int?; public let openOrders: Int? }249250    public let account: LiveAccount251    public let venueState: LiveVenueState252    public let orders: [LiveOrder]253    public let actions: [LiveAction]254    public let fills: [DerivFill]255    /** Funding payments of the account, from the venue. */256    public let funding: [DerivFundingPayment]257    public let riskEvents: [DerivRiskEvent]258    public let equity: [DerivEquityPoint]259    public let ts: Date?260    // extras of the routes that answer the account with more261    /** halt: what the halt does NOT do, in the server's words. */262    public let note: String?263    /** revoke / mandate revoke: the result of the cancel-all that was asked for. */264    public let cancelled: LiveCancelAll?265    public let cancelError: CancelError?266    /** revoke: orders still rest on the venue. */267    public let warning: String?268    public let venueAgent: String?269    public let recovered: [Recovered]?270    public let windDown: WindDown?271272    private enum Keys: String, CodingKey { case venueState, orders, actions, fills, funding, riskEvents, equity, ts, note, cancelled, cancelError, warning, venueAgent, recovered, windDown }273    public init(from decoder: Decoder) throws {274        account = try LiveAccount(from: decoder)275        let c = try decoder.container(keyedBy: Keys.self)276        // an answer without a venue state is an unreadable venue, never an empty account277        venueState = try c.decodeIfPresent(LiveVenueState.self, forKey: .venueState) ?? LiveVenueState(state: nil, positions: [], openOrders: [], error: "no venue state in the answer", ts: nil, source: nil)278        orders = try c.decodeIfPresent([LiveOrder].self, forKey: .orders) ?? []279        actions = try c.decodeIfPresent([LiveAction].self, forKey: .actions) ?? []280        fills = try c.decodeIfPresent([DerivFill].self, forKey: .fills) ?? []281        funding = try c.decodeIfPresent([DerivFundingPayment].self, forKey: .funding) ?? []282        riskEvents = try c.decodeIfPresent([DerivRiskEvent].self, forKey: .riskEvents) ?? []283        equity = try c.decodeIfPresent([DerivEquityPoint].self, forKey: .equity) ?? []284        ts = try c.decodeIfPresent(Date.self, forKey: .ts)285        note = try c.decodeIfPresent(String.self, forKey: .note)286        cancelled = try c.decodeIfPresent(LiveCancelAll.self, forKey: .cancelled)287        cancelError = try c.decodeIfPresent(CancelError.self, forKey: .cancelError)288        warning = try c.decodeIfPresent(String.self, forKey: .warning)289        venueAgent = try c.decodeIfPresent(String.self, forKey: .venueAgent)290        recovered = try c.decodeIfPresent([Recovered].self, forKey: .recovered)291        windDown = try c.decodeIfPresent(WindDown.self, forKey: .windDown)292    }293}294295/** `GET …/collateral` (read-only summary). The collateral operations are `CollateralStatus`. */296public struct LiveCollateralSummary: Codable, Sendable, Hashable {297    public struct How: Codable, Sendable, Hashable { public let supported: Bool; public let how: String }298    public let account: String299    public let network: String300    public let equity, collateral, freeCollateral, marginUsed, withdrawable: String?301    public let asset: String302    public let error: String?303    public let ts: Date?304    public let source: String?305    public let locale: String?306    public let deposits: How?307    public let withdrawals: How?308}309310public struct LiveCancelAll: Codable, Sendable, Hashable {311    public struct Failed: Codable, Sendable, Hashable { public let venueOrderId: String?; public let instrument: String; public let error: String }312    public let requested: Int313    public let accepted: Int314    public let failed: [Failed]315    /** What still rests on the venue afterwards; nil when it could not be read. */316    public let remaining: [DerivOrder]?317    public let source: String?318    public let ts: Date?319}320321public struct LiveReconcile: Decodable, Sendable {322    public let reconciled: Int323    public let fills: Int324    public let funding: Int325    public let divergence: String?326    public let account: LiveAccountDetail327}328329public struct LiveMandateStatus: Decodable, Sendable {330    public let modes: [LiveAccountMode]?331    public let mandate: LiveMandateSummary?332    public let pendingMandate: LiveAccount.Pending?333    /** The signer's own record of the mandate (counters of the day, phase), as served. */334    public let signer: JSONValue?335    public let ts: Date?336}337338// MARK: orders and leverage339340/** Body of a LIVE order. No leverage here: on a venue account the leverage is a venue setting changed with its own passkey-approved route. */341public struct LiveOrderRequest: Encodable, Sendable, Equatable {342    public let instrument: String343    public let side: DerivOrderSide344    public let type: DerivOrderType345    public let size: String346    /** Limit price; for a market order the worst acceptable price, or nil with `slippageBps` (the server then derives it from the book). */347    public let price: String?348    public let triggerPrice: String?349    public let reduceOnly: Bool350    public let tif: DerivTimeInForce351    public let slippageBps: Int?352353    public init(instrument: String, side: DerivOrderSide, type: DerivOrderType, size: String, price: String?, triggerPrice: String?, reduceOnly: Bool, tif: DerivTimeInForce, slippageBps: Int?) {354        self.instrument = instrument; self.side = side; self.type = type; self.size = size; self.price = price; self.triggerPrice = triggerPrice355        self.reduceOnly = reduceOnly; self.tif = tif; self.slippageBps = slippageBps356    }357    private enum Keys: String, CodingKey { case instrument, side, type, size, price, triggerPrice, reduceOnly, tif, slippageBps }358    public func encode(to encoder: Encoder) throws {359        var c = encoder.container(keyedBy: Keys.self)360        try c.encode(instrument, forKey: .instrument); try c.encode(side, forKey: .side); try c.encode(type, forKey: .type); try c.encode(size, forKey: .size)361        if let price { try c.encode(price, forKey: .price) } else { try c.encodeNil(forKey: .price) }362        if let triggerPrice { try c.encode(triggerPrice, forKey: .triggerPrice) } else { try c.encodeNil(forKey: .triggerPrice) }363        try c.encode(reduceOnly, forKey: .reduceOnly); try c.encode(tif, forKey: .tif); try c.encodeIfPresent(slippageBps, forKey: .slippageBps)364    }365}366367/** The server's estimate before a live order. It carries NO liquidation price: the venue reports one once the position exists. */368public struct LiveOrderEstimate: Codable, Sendable, Hashable {369    public let notional: String370    public let initialMargin: String371    public let fee: String372    public let feeNote: String?373    public let freeCollateralAfter: String374    /** The venue's present leverage setting for the instrument. */375    public let leverage: String?376    public let marginMode: String?377    public let price: String?378    public let mark: String?379    public let liquidationNote: String?380    public let source: String?381}382383public struct LiveOrderPreview: Codable, Sendable, Hashable {384    public struct VenueSide: Codable, Sendable, Hashable { public let state: DerivAccountState?; public let positions: [DerivPosition]?; public let source: String? }385    public let risk: DerivRiskVerdict386    public let estimate: LiveOrderEstimate?387    public let request: DerivOrderRequestEcho?388    public let venueState: VenueSide?389    public let ts: Date?390}391392public struct LiveOrderResult: Decodable, Sendable {393    public struct Venue: Codable, Sendable, Hashable { public let outcome: String; public let error: String? }394    public let order: LiveOrder395    /** approve: true when the order had already been approved, sent, refused or withdrawn (nothing was sent again). */396    public let idempotent: Bool?397    /** cancel: false when only a proposal was withdrawn. */398    public let sent: Bool?399    public let venue: Venue?400}401402public struct LiveLeverageSetting: Codable, Sendable, Hashable { public let leverage: String; public let marginMode: String }403404public struct LiveLeverageResult: Decodable, Sendable {405    public struct Venue: Codable, Sendable, Hashable { public let leverage: LiveLeverageSetting?; public let confirmed: Bool; public let source: String? }406    public let action: LiveAction407    public let idempotent: Bool408    /** What the venue reports afterwards. */409    public let venue: Venue?410}411412/** The limits of a derivative mandate as the owner chooses them. Every one is stated by the caller. */413public struct LiveMandateRequest: Encodable, Sendable, Equatable {414    public let instruments: [VenueMandateInstrument]415    public let maxOrderNotional, maxGrossExposure: String416    public let maxOrdersPerDay, maxOrdersPerHour: Int417    public let maxDailyTurnover, floorEquity: String418    public let strategySha256, agentId: String419    public let maxPriceDeviationBps: Int420    public let days: Int421    public let locale: String422    public init(instruments: [VenueMandateInstrument], maxOrderNotional: String, maxGrossExposure: String, maxOrdersPerDay: Int, maxOrdersPerHour: Int, maxDailyTurnover: String, floorEquity: String,423                strategySha256: String, agentId: String, maxPriceDeviationBps: Int, days: Int, locale: String) {424        self.instruments = instruments; self.maxOrderNotional = maxOrderNotional; self.maxGrossExposure = maxGrossExposure; self.maxOrdersPerDay = maxOrdersPerDay; self.maxOrdersPerHour = maxOrdersPerHour425        self.maxDailyTurnover = maxDailyTurnover; self.floorEquity = floorEquity; self.strategySha256 = strategySha256; self.agentId = agentId; self.maxPriceDeviationBps = maxPriceDeviationBps426        self.days = days; self.locale = locale427    }428}429430// MARK: collateral431432public struct CollateralVenueBalance: Codable, Sendable, Hashable {433    public let abstraction: String?434    public let equity, withdrawable, spotUsdc, total: String?435    public let error: String?436    public let ts: Date?437}438439/** A deposit is done only in the state `credited` (the venue's ledger shows it); a withdrawal only in `completed` (the wallet saw the USDC). */440public struct CollateralOperation: Decodable, Sendable, Identifiable {441    public struct Ledger: Codable, Sendable, Hashable { public let time: Date?; public let hash: String?; public let type: String?; public let usdc: String?; public let fee: String? }442    public struct Arrival: Codable, Sendable, Hashable { public let txid: String?; public let amount: String?; public let seenAt: Date? }443    public let id: String444    /** `deposit` or `withdraw`. */445    public let kind: String446    public let state: String447    public let final: Bool448    public let venueNetwork: String449    public let amount: String450    public let asset: String451    public let fee: String?452    public let expectedReceive: String?453    public let chainNetwork: String?454    public let chainNetworkName: String?455    public let bridge: String?456    public let txid: String?457    public let explorer: String?458    /** Hash of what the passkey signs (intent hash, or canonical withdrawal hash). */459    public let hash: String?460    public let proposalId: String?461    public let proposalState: String?462    public let confirmations: Int?463    public let createdAt: Date?464    public let expiresAt: Date?465    public let sentAt: Date?466    public let venueAt: Date?467    public let doneAt: Date?468    public let expectedSeconds: Int?469    public let overdue: Bool?470    public let check: [String]?471    public let balanceBefore: CollateralVenueBalance?472    public let balanceAfter: CollateralVenueBalance?473    public let ledger: Ledger?474    public let arrival: Arrival?475    public let error: String?476    public let attempts: Int?477    public let arrivalTracked: Bool?478    public var isDone: Bool { (kind == "deposit" && state == "credited") || (kind == "withdraw" && state == "completed") }479}480481struct CollateralOperationAnswer: Decodable, Sendable { let operation: CollateralOperation }482483public struct CollateralStatus: Decodable, Sendable {484    public struct Route: Codable, Sendable, Hashable {485        public let id, network, networkName, bridge: String486        public let bridgeExplorer: String?487        public let asset, token, venueMinimum, minimum: String488        public let expectedSeconds: Int?489        public let credits: String?490        public let venueFee: String?491        public let pinnedAt: String?492        public let codeSha256: String?493    }494    public struct Withdrawal: Codable, Sendable, Hashable { public let fee: String; public let expectedSeconds: Int?; public let destination: String; public let payoutNetworkName: String?; public let arrivalTracked: Bool?; public let available: String? }495    public struct Limits: Codable, Sendable, Hashable { public let perTransfer, perDay, spentToday, maxNow: String }496    public struct Elsewhere: Codable, Sendable, Hashable { public let network: String; public let name: String; public let usdc: String }497    public struct Wallet: Codable, Sendable, Hashable { public let address, network, networkName, usdc, gas, gasSymbol: String; public let limits: Limits; public let elsewhere: [Elsewhere]? }498    /** Whether the operation can be prepared now; when not, the server's reason code (`mainnet_disabled`, `halted`, `no_route`, `no_usdc`, `no_gas`, `limit_reached`, `usdc_elsewhere`, `wallet_unreadable`, `venue_unreadable`). */499    public struct Availability: Codable, Sendable, Hashable {500        public let available: Bool501        public let reason: String?502        public let bridgeFrom: [Elsewhere]?503        public var refusal: DerivativesRefusal? { available ? nil : DerivativesRefusal(code: reason ?? "unavailable", reason: "", status: 200) }504    }505    public let account: String506    public let accountId: LiveAccountID507    public let venue: String508    public let network: String509    public let mainnetEnabled: Bool510    public let venueBalance: CollateralVenueBalance511    /** Nil: no deposit route exists (testnet collateral is mock USDC). */512    public let route: Route?513    public let withdrawal: Withdrawal514    public let wallet: Wallet?515    public let walletError: String?516    public let deposit: Availability517    public let withdraw: Availability518    public let operations: [CollateralOperation]519    public let ts: Date?520}521522// MARK: GMX v2523524public struct GmxMarketInfo: Codable, Sendable, Hashable {525    public struct Collateral: Codable, Sendable, Hashable { public let token: String; public let symbol: String; public let decimals: Int }526    public let market: String527    public let name: String528    public let instrument: String529    public let base: String?530    public let indexDecimals: Int531    public let collateral: [Collateral]532    public let allowed: Bool533    public let mark, oracleMin, oracleMax: String?534}535536public struct GmxPositionView: Codable, Sendable, Hashable {537    public struct VenueApi: Codable, Sendable, Hashable { public let agrees: Bool?; public let detail: String? }538    public let key: String539    public let market: String540    public let marketName: String?541    public let instrument: String?542    public let side: String543    public let collateralToken: String544    public let collateralSymbol: String?545    public let sizeUsd, sizeTokens, collateral, entryPrice: String546    public let markPrice: String?547    /** Estimate at the mark, before fees. */548    public let pnlUsd: String?549    public let leverage: String?550    /** An ESTIMATE computed by the wallet's server from on-chain figures (GMX publishes none). Label it as such. */551    public let liquidationPrice: String?552    public let increasedAt: Date?553    public let source: String?554    public let venueApi: VenueApi?555}556557public struct GmxPendingOrder: Codable, Sendable, Hashable {558    public let key: String559    public let market: String560    public let marketName: String?561    public let orderType: String562    public let side: String563    public let sizeUsd, collateral, acceptablePrice, executionFeeEth: String564    public let updatedAt: Date?565    public let cancellableAt: Date?566    public let frozen: Bool567    public let opId: String?568}569570/** `created` is never "executed": success exists for `executed` (and for a mined cancel, `done`) only. */571public struct GmxOperation: Decodable, Sendable, Identifiable {572    public let id: String573    /** `increase`, `decrease`, `cancel`. */574    public let kind: String575    public let state: String576    public let final: Bool577    public let market: String?578    public let marketName: String?579    public let side: String?580    public let collateral: String?581    public let collateralSymbol: String?582    public let sizeUsd: String?583    public let acceptablePrice: String?584    public let slippageBps: Int?585    public let leverage: String?586    public let executionFeeEth: String?587    public let maxFeeEth: String?588    public let needsApproval: Bool?589    public let orderKey: String?590    public let targetOpId: String?591    /** The intent hash = what the passkey signs. */592    public let hash: String?593    public let proposalId: String?594    public let txid: String?595    public let explorer: String?596    public let approvalTxid: String?597    public let createdAt: Date?598    public let expiresAt: Date?599    public let sentAt: Date?600    public let orderCreatedAt: Date?601    public let doneAt: Date?602    public let cancellableAt: Date?603    public let overdue: Bool?604    public let estimate: JSONValue?605    public let outcome: JSONValue?606    public let error: String?607}608609struct GmxOperationAnswer: Decodable, Sendable { let operation: GmxOperation }610611public struct GmxStatus: Decodable, Sendable {612    /** The two server settings: SPW_DERIV_LIVE_MAINNET and SPW_DERIV_GMX_LIVE. */613    public struct Settings: Codable, Sendable, Hashable { public let liveMainnet: Bool; public let gmxLive: Bool }614    public struct Contract: Codable, Sendable, Hashable { public let name: String; public let address: String; public let explorer: String? }615    public struct Pins: Codable, Sendable, Hashable { public let id: String; public let reviewedAt: String?; public let ok: Bool?; public let checkedAt: Date?; public let problems: [String]?; public let contracts: [Contract] }616    public struct Account: Codable, Sendable, Hashable { public let address: String; public let explorer: String? }617    public struct Wallet: Codable, Sendable, Hashable { public let usdc, eth, weth: String; public let limits: CollateralStatus.Limits?; public let feeCeilingEth: String? }618    public struct PolicyView: Codable, Sendable, Hashable { public let allowedMarkets: [String]; public let maxLeverage: Int; public let maxOrderSizeUsd: String; public let maxOrdersPerDay: Int; public let maxPriceDeviationBps: Int; public let maxExecutionFeeWei: String? }619    public struct Today: Codable, Sendable, Hashable { public let increases: Int; public let reduces: Int }620    public struct Authorization: Codable, Sendable, Hashable, Identifiable {621        public let id: String622        /** `active`, `expired`, `revoked`, `stale` (the pinned contract set changed). */623        public let state: String624        public let policy: PolicyView625        public let createdAt: Date?626        public let expiresAt: Date?627        public let today: Today?628    }629    /** The API-side loss limits and kill switch (new risk only). */630    public struct Risk: Codable, Sendable, Hashable {631        public struct Limits: Codable, Sendable, Hashable { public let maxDailyLoss: String; public let maxTotalLoss: String }632        public let halt: String?633        public let maxDailyLoss: String634        public let maxTotalLoss: String635        public let defaults: Limits?636        public let realizedToday: String?637        public let realizedTotal: String?638        public let note: String?639    }640    public struct Facts: Codable, Sendable, Hashable { public let requestExpirationSec: Int?; public let executionGas: String?; public let twoStep: Bool? }641642    public let venue: String643    public let network: String644    public let chainId: Int645    public let settings: Settings646    public let tradable: Bool647    /** Why GMX orders cannot be prepared now (`gmx_setting_off`, `mainnet_setting_off`, `not_authorized`, `authorization_expired`, `authorization_revoked`, `contracts_changed`, `signer_halted`, `gmx_halted`, `chain_unreadable`, `wallet_unreadable`). */648    public let blockers: [String]649    /** The server's sentence for every blocker code, in the requested locale. */650    public let blockerText: [String: String]?651    public let pins: Pins652    public let account: Account?653    public let wallet: Wallet?654    public let walletError: String?655    public let authorization: Authorization?656    public let markets: [GmxMarketInfo]657    public let risk: Risk?658    public let positions: [GmxPositionView]659    public let positionsSource: String?660    public let positionsError: String?661    public let pendingOrders: [GmxPendingOrder]662    public let operations: [GmxOperation]663    public let facts: Facts?664    public let ts: Date?665666    /** Each blocker as a typed refusal with the server's own sentence. */667    public var refusals: [DerivativesRefusal] { blockers.map { DerivativesRefusal(code: $0, reason: blockerText?[$0] ?? "", status: 200) } }668    public func contract(_ name: String) -> String? { pins.contracts.first { $0.name == name }?.address }669}670671public struct GmxJurisdictionAnswer: Codable, Sendable, Hashable { public let venue: String; public let fr: JurisdictionAck; public let en: JurisdictionAck }672673/** The GMX venue policy as the owner chooses it. The execution-fee ceiling is set by the server and shown before approval. */674public struct GmxAuthorizationRequest: Encodable, Sendable, Equatable {675    public let allowedMarkets: [String]676    public let maxLeverage: Int677    public let maxOrderSizeUsd: String678    public let maxOrdersPerDay: Int679    public let maxPriceDeviationBps: Int680    public let days: Int681    public let locale: String682    public init(allowedMarkets: [String], maxLeverage: Int, maxOrderSizeUsd: String, maxOrdersPerDay: Int, maxPriceDeviationBps: Int, days: Int, locale: String) {683        self.allowedMarkets = allowedMarkets; self.maxLeverage = maxLeverage; self.maxOrderSizeUsd = maxOrderSizeUsd; self.maxOrdersPerDay = maxOrdersPerDay684        self.maxPriceDeviationBps = maxPriceDeviationBps; self.days = days; self.locale = locale685    }686}687688public enum GmxSide: String, Codable, Sendable { case long, short }689690/** A GMX market order: an increase names its collateral and EITHER a leverage or a size; a decrease names a size (nil = the whole position). */691public struct GmxOrderRequest: Encodable, Sendable, Equatable {692    public enum Action: String, Codable, Sendable { case increase, decrease }693    public let market: String694    public let side: GmxSide695    public let action: Action696    public let collateral: String?697    public let leverage: String?698    public let sizeUsd: String?699    public let slippageBps: Int700701    public static func increase(market: String, side: GmxSide, collateral: String, leverage: String, slippageBps: Int) -> GmxOrderRequest {702        GmxOrderRequest(market: market, side: side, action: .increase, collateral: collateral, leverage: leverage, sizeUsd: nil, slippageBps: slippageBps)703    }704    public static func increase(market: String, side: GmxSide, collateral: String, sizeUsd: String, slippageBps: Int) -> GmxOrderRequest {705        GmxOrderRequest(market: market, side: side, action: .increase, collateral: collateral, leverage: nil, sizeUsd: sizeUsd, slippageBps: slippageBps)706    }707    public static func decrease(market: String, side: GmxSide, sizeUsd: String?, slippageBps: Int) -> GmxOrderRequest {708        GmxOrderRequest(market: market, side: side, action: .decrease, collateral: nil, leverage: nil, sizeUsd: sizeUsd, slippageBps: slippageBps)709    }710}711712public struct GmxCloseRequest: Encodable, Sendable, Equatable {713    public let market: String714    public let side: GmxSide715    /** Above 0 and at most 1. */716    public let fraction: String717    public let slippageBps: Int718    public init(market: String, side: GmxSide, fraction: String, slippageBps: Int) { self.market = market; self.side = side; self.fraction = fraction; self.slippageBps = slippageBps }719}720721public struct GmxOrderPreview: Decodable, Sendable {722    public struct Order: Codable, Sendable, Hashable { public let market: String; public let marketName: String?; public let side: String; public let action: String; public let collateral: String?; public let sizeUsd: String; public let acceptablePrice: String; public let slippageBps: Int; public let leverage: String? }723    public let order: Order724    /** Every figure an estimate (fees, price impact, funding, an estimated liquidation price with its note). */725    public let estimate: JSONValue?726    public let risk: DerivRiskVerdict727    public let blockers: [String]728    /** What the signer's venue policy would refuse, in its words; nil when nothing. */729    public let signerWould: String?730}731732public struct GmxField: Codable, Sendable, Hashable { public let label: String; public let value: String }733
Files main
Menu

Theme