Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SPWalletCore9// File : Sources/SPWalletCore/Domains/Derivatives/DerivativesCanonical.swift10// Description : Every object of the derivatives routes that the owner11// approves with a passkey, ported byte for byte from the12// backend: venue authorization, manual order, leverage13// change (packages/derivatives/src/live/canonical.ts),14// derivative mandate (live/mandate.ts), venue withdrawal15// (live/collateral.ts), GMX venue policy (live/gmx.ts), and16// the two JSON-canonical risk intents17// (services/api/src/derivatives/exec.ts, gmx-exec.ts). Each18// is parsed STRICTLY from the served object (an unknown key19// or a value the backend's schema refuses is a refusal) and20// serialized from the typed fields only. The deposit and the21// GMX order are wallet intents (`Intent`,22// Signing/Intent.swift) with a `venueDeposit` / `gmx`23// section.24// Module : SPWalletCore25// Repository : https://git.spboucher.ai/sp-wallet-core26// Created : 2026-11-1827// Last Modified : 2026-11-1828//29// =============================================================================30// AUTHOR & PROFESSIONAL AFFILIATION31// =============================================================================32//33// Author : Simon-Pierre Boucher34// Position : Professor of Finance35// Institution : Université du Québec en Outaouais (UQO)36// Department : Département des sciences administratives37// Organization : SP Boucher38//39// Website : https://spboucher.ai40// Git : https://git.spboucher.ai41//42// =============================================================================43// OFFICIAL CONTACT DIRECTORY44// =============================================================================45//46// General : info@spboucher.ai47// Professional : contact@spboucher.ai48// Direct : simon@spboucher.ai49// Research : research@spboucher.ai50// Development : dev@spboucher.ai51// Support : support@spboucher.ai52// Security/Admin : admin@spboucher.ai53// Notifications : notifications@spboucher.ai54//55// Preferred Contact: support@spboucher.ai56//57// =============================================================================58// COPYRIGHT & INTELLECTUAL PROPERTY59// =============================================================================60//61// Copyright (c) 202662// Simon-Pierre Boucher63//64// All rights reserved where applicable.65//66// This file is governed by the applicable project license,67// copyright notices, institutional agreements and relevant law.68//69// Unless expressly authorized by the applicable license or70// rights holder, copying, redistribution, sublicensing,71// publication and commercial exploitation are not permitted.72//73// Existing third-party rights and notices remain unaffected.74//75// =============================================================================76// CONFIDENTIALITY & SECURITY77// =============================================================================78//79// Classification : Public80// Distribution : Public repository; use is governed by the project license81// Security Contact : admin@spboucher.ai82//83// Access to this source does not independently grant permission84// to redistribute or disclose confidential materials.85//86// Do not embed credentials, private keys, access tokens,87// certificates or confidential personal information.88//89// =============================================================================90// LICENSE & MAINTENANCE91// =============================================================================92//93// License : None specified (no license file in this repository)94// Maintainer : Simon-Pierre Boucher95// Technical Contact: dev@spboucher.ai96//97// =============================================================================98// END OF SP BOUCHER SOURCE HEADER99// =============================================================================100101import Foundation102103enum DerivCanon {104 static func fail(_ what: String) -> ApprovalError { .unsupported(what) }105106 /** A decimal the schema calls `PosDec`: canonical grammar, positive. Returned as served; `canon` is applied when framing. */107 static func positive(_ s: String, _ path: String) throws -> String {108 guard let d = VenueDecimal(s), d.isPositive else { throw fail("\(path) is not a positive decimal") }109 return s110 }111 static func canon(_ s: String) throws -> String {112 guard let d = VenueDecimal(s) else { throw fail("not a decimal: \(s)") }113 return d.description114 }115 static func matches(_ s: String, _ pattern: String) -> Bool { s.range(of: "^(?:\(pattern))$", options: .regularExpression) != nil }116 static func require(_ s: String, _ pattern: String, _ path: String) throws -> String {117 guard matches(s, pattern) else { throw fail("\(path) is malformed") }118 return s119 }120 static let addressLower = "0x[0-9a-f]{40}"121 static let addressAny = "0x[0-9a-fA-F]{40}"122 static let uuid = "[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"123 static let hash64 = "[0-9a-f]{64}"124 static let hlInstrument = "hyperliquid:[A-Za-z0-9]{1,15}"125 static let uint = "0|[1-9][0-9]{0,77}"126127 static func network(_ s: String) throws -> String {128 guard s == "mainnet" || s == "testnet" else { throw fail("network \(s)") }129 return s130 }131 static func positiveInt(_ i: Int, _ path: String) throws -> Int {132 guard i > 0 else { throw fail("\(path) is not a positive integer") }133 return i134 }135 static func version(_ o: inout StrictObject) throws {136 guard try o.int("v") == 1 else { throw fail("\(o.path) version") }137 }138 static func strings(_ a: [JSONValue], _ path: String) throws -> [String] {139 try a.map { guard let s = $0.stringValue else { throw fail("\(path) holds a non-string") }; return s }140 }141 /** JavaScript's default `Array.prototype.sort` (UTF-16 code units). */142 static func jsSorted(_ a: [String]) -> [String] { a.sorted { $0.utf16.lexicographicallyPrecedes($1.utf16) } }143144 static func frame(_ domain: String, _ fields: [(String, String)]) -> Data {145 var w = CanonicalWriter(domain: domain)146 for (k, v) in fields { w.field(k, v) }147 return w.data148 }149}150151// MARK: SPW-VENUE-AUTH-v1152153/** The limits the isolated signer enforces on a venue account (`VenuePolicySchema`). Chosen by the owner, never defaulted here. */154public struct VenuePolicy: Sendable, Equatable, Encodable {155 /** Instrument ids (`hyperliquid:BTC`). */156 public let allowedInstruments: [String]157 /** Highest leverage SETTING the signer will sign for an instrument. */158 public let maxLeverage: Int159 public let maxOrderNotional: String160 public let maxPositionNotional: String161 public let maxGrossExposure: String162 public let maxOrdersPerDay: Int163 public let maxPriceDeviationBps: Int164165 public init(allowedInstruments: [String], maxLeverage: Int, maxOrderNotional: String, maxPositionNotional: String, maxGrossExposure: String, maxOrdersPerDay: Int, maxPriceDeviationBps: Int) {166 self.allowedInstruments = allowedInstruments; self.maxLeverage = maxLeverage; self.maxOrderNotional = maxOrderNotional; self.maxPositionNotional = maxPositionNotional167 self.maxGrossExposure = maxGrossExposure; self.maxOrdersPerDay = maxOrdersPerDay; self.maxPriceDeviationBps = maxPriceDeviationBps168 }169170 init(strict json: JSONValue?, path: String) throws {171 var p = try StrictObject(json, path: path)172 allowedInstruments = try DerivCanon.strings(try p.array("allowedInstruments"), "\(path).allowedInstruments").map { try DerivCanon.require($0, DerivCanon.hlInstrument, "\(path).allowedInstruments") }173 guard !allowedInstruments.isEmpty, allowedInstruments.count <= 256 else { throw DerivCanon.fail("\(path).allowedInstruments count") }174 maxLeverage = try DerivCanon.positiveInt(try p.int("maxLeverage"), "\(path).maxLeverage")175 maxOrderNotional = try DerivCanon.positive(try p.string("maxOrderNotional"), "\(path).maxOrderNotional")176 maxPositionNotional = try DerivCanon.positive(try p.string("maxPositionNotional"), "\(path).maxPositionNotional")177 maxGrossExposure = try DerivCanon.positive(try p.string("maxGrossExposure"), "\(path).maxGrossExposure")178 maxOrdersPerDay = try DerivCanon.positiveInt(try p.int("maxOrdersPerDay"), "\(path).maxOrdersPerDay")179 maxPriceDeviationBps = try DerivCanon.positiveInt(try p.int("maxPriceDeviationBps"), "\(path).maxPriceDeviationBps")180 try p.finish()181 }182183 /** Same limits: the same set of instruments, the same integers, decimals of the same value. */184 public func sameLimits(as o: VenuePolicy) -> Bool {185 Set(allowedInstruments) == Set(o.allowedInstruments) && allowedInstruments.count == o.allowedInstruments.count && maxLeverage == o.maxLeverage186 && VenueDecimal.same(maxOrderNotional, o.maxOrderNotional) && VenueDecimal.same(maxPositionNotional, o.maxPositionNotional)187 && VenueDecimal.same(maxGrossExposure, o.maxGrossExposure) && maxOrdersPerDay == o.maxOrdersPerDay && maxPriceDeviationBps == o.maxPriceDeviationBps188 }189}190191/** The owner turns live trading on for ONE venue account (`VenueAuthorizationSchema`, `venueAuthorizationBytes`). */192public struct VenueAuthorization: PasskeyApprovable, Equatable, Decodable {193 public let authorizationId, keyId, venue, network, account, agentAddress, agentName, mode: String194 public let policy: VenuePolicy195 /** Unix seconds. */196 public let createdAt, expiresAt: Int197 /** Nonce (unix ms) of the one `approveAgent` action this authorization lets the wallet key sign. */198 public let approveNonce: Int199 /** SHA-256 of the jurisdiction acknowledgement text that is displayed. */200 public let ackSha256: String201202 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }203204 public init(served json: JSONValue) throws {205 var o = try StrictObject(json, path: "authorization")206 try DerivCanon.version(&o)207 authorizationId = try DerivCanon.require(try o.string("authorizationId"), DerivCanon.uuid, "authorization.authorizationId")208 keyId = try o.string("keyId")209 venue = try o.string("venue")210 guard venue == "hyperliquid" else { throw DerivCanon.fail("authorization.venue \(venue)") }211 network = try DerivCanon.network(try o.string("network"))212 account = try DerivCanon.require(try o.string("account"), DerivCanon.addressLower, "authorization.account")213 agentAddress = try DerivCanon.require(try o.string("agentAddress"), DerivCanon.addressLower, "authorization.agentAddress")214 agentName = try DerivCanon.require(try o.string("agentName"), "[A-Za-z0-9_-]{1,16}", "authorization.agentName")215 mode = try o.string("mode")216 guard mode == "MANUAL_LIVE" || mode == "MANDATE_LIVE" else { throw DerivCanon.fail("authorization.mode \(mode)") }217 policy = try VenuePolicy(strict: o.raw("policy"), path: "authorization.policy")218 createdAt = try DerivCanon.positiveInt(try o.int("createdAt"), "authorization.createdAt")219 expiresAt = try DerivCanon.positiveInt(try o.int("expiresAt"), "authorization.expiresAt")220 approveNonce = try DerivCanon.positiveInt(try o.int("approveNonce"), "authorization.approveNonce")221 ackSha256 = try DerivCanon.require(try o.string("ackSha256"), DerivCanon.hash64, "authorization.ackSha256")222 try o.finish()223 }224 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "venue authorization") { try VenueAuthorization(served: $0) } }225226 public func canonicalBytes() throws -> Data {227 let p = policy228 return DerivCanon.frame("SPW-VENUE-AUTH-v1", [229 ("v", "1"), ("authorizationId", authorizationId), ("keyId", keyId), ("venue", venue), ("network", network), ("account", account),230 ("agentAddress", agentAddress), ("agentName", agentName), ("mode", mode),231 ("policy.allowedInstruments", DerivCanon.jsSorted(p.allowedInstruments).joined(separator: ",")), ("policy.maxLeverage", String(p.maxLeverage)),232 ("policy.maxOrderNotional", try DerivCanon.canon(p.maxOrderNotional)), ("policy.maxPositionNotional", try DerivCanon.canon(p.maxPositionNotional)),233 ("policy.maxGrossExposure", try DerivCanon.canon(p.maxGrossExposure)), ("policy.maxOrdersPerDay", String(p.maxOrdersPerDay)),234 ("policy.maxPriceDeviationBps", String(p.maxPriceDeviationBps)),235 ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("approveNonce", String(approveNonce)), ("ackSha256", ackSha256),236 ])237 }238}239240func decodeStrict<T>(_ decoder: Decoder, _ what: String, _ build: (JSONValue) throws -> T) throws -> T {241 let json = try JSONValue(from: decoder)242 do { return try build(json) }243 catch { throw DecodingError.dataCorrupted(.init(codingPath: decoder.codingPath, debugDescription: "\(what) refused: \(error)")) }244}245246// MARK: SPW-VENUE-ORDER-v1 / SPW-VENUE-LEVERAGE-v1247248/** ONE order exactly as the venue will receive it (`VenueOrderSchema`, `venueOrderBytes`). A market order appears as `limit` + `ioc` at its worst price. */249public struct VenueOrder: PasskeyApprovable, Equatable, Decodable {250 public let authorizationId, venue, network, account, instrument: String251 /** `buy` or `sell`. */252 public let side: String253 /** `limit`, `stop_market`, `stop_limit`, `take_profit_market`, `take_profit_limit`. */254 public let type: String255 public let size: String256 /** Limit price, or worst acceptable price. */257 public let price: String258 public let triggerPrice: String?259 public let reduceOnly: Bool260 public let tif: String261 /** The venue's client order id (128-bit hex), derived from the Idempotency-Key. */262 public let clientId: String263 /** Venue nonce and venue expiry, unix milliseconds. */264 public let nonce, expiresAt: Int265266 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }267268 public init(served json: JSONValue) throws {269 var o = try StrictObject(json, path: "order")270 try DerivCanon.version(&o)271 (authorizationId, venue, network, account, nonce, expiresAt) = try VenueOrder.head(&o, kind: "order")272 instrument = try DerivCanon.require(try o.string("instrument"), DerivCanon.hlInstrument, "order.instrument")273 side = try DerivCanon.require(try o.string("side"), "buy|sell", "order.side")274 type = try DerivCanon.require(try o.string("type"), "limit|stop_market|stop_limit|take_profit_market|take_profit_limit", "order.type")275 size = try DerivCanon.positive(try o.string("size"), "order.size")276 price = try DerivCanon.positive(try o.string("price"), "order.price")277 // nullable but REQUIRED by the schema: an absent key is not the order the backend would hash278 guard let t = o.raw("triggerPrice") else { throw DerivCanon.fail("order.triggerPrice missing") }279 if t.isNull { triggerPrice = nil } else {280 guard let s = t.stringValue else { throw DerivCanon.fail("order.triggerPrice is not a string") }281 triggerPrice = try DerivCanon.positive(s, "order.triggerPrice")282 }283 reduceOnly = try o.bool("reduceOnly")284 tif = try DerivCanon.require(try o.string("tif"), "gtc|ioc|alo", "order.tif")285 clientId = try DerivCanon.require(try o.string("clientId"), "0x[0-9a-f]{32}", "order.clientId")286 try o.finish()287 }288 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "venue order") { try VenueOrder(served: $0) } }289290 /** The fields an order and a leverage change share. */291 static func head(_ o: inout StrictObject, kind: String) throws -> (String, String, String, String, Int, Int) {292 let id = try DerivCanon.require(try o.string("authorizationId"), DerivCanon.uuid, "\(o.path).authorizationId")293 let venue = try o.string("venue")294 guard venue == "hyperliquid" else { throw DerivCanon.fail("\(o.path).venue \(venue)") }295 let network = try DerivCanon.network(try o.string("network"))296 let account = try DerivCanon.require(try o.string("account"), DerivCanon.addressLower, "\(o.path).account")297 let nonce = try DerivCanon.positiveInt(try o.int("nonce"), "\(o.path).nonce"), expiresAt = try DerivCanon.positiveInt(try o.int("expiresAt"), "\(o.path).expiresAt")298 guard try o.string("kind") == kind else { throw DerivCanon.fail("\(o.path).kind") }299 return (id, venue, network, account, nonce, expiresAt)300 }301302 public func canonicalBytes() throws -> Data {303 DerivCanon.frame("SPW-VENUE-ORDER-v1", [304 ("v", "1"), ("authorizationId", authorizationId), ("venue", venue), ("network", network), ("account", account), ("kind", "order"),305 ("instrument", instrument), ("side", side), ("type", type), ("size", try DerivCanon.canon(size)), ("price", try DerivCanon.canon(price)),306 ("triggerPrice", try triggerPrice.map(DerivCanon.canon) ?? ""), ("reduceOnly", reduceOnly ? "1" : "0"), ("tif", tif), ("clientId", clientId),307 ("nonce", String(nonce)), ("expiresAt", String(expiresAt)),308 ])309 }310}311312/** ONE leverage change of one instrument (`VenueLeverageSchema`, `venueLeverageBytes`). */313public struct VenueLeverage: PasskeyApprovable, Equatable, Decodable {314 public let authorizationId, venue, network, account, instrument: String315 public let leverage: Int316 /** `cross` or `isolated`. */317 public let marginMode: String318 public let nonce, expiresAt: Int319320 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }321322 public init(served json: JSONValue) throws {323 var o = try StrictObject(json, path: "leverage")324 try DerivCanon.version(&o)325 (authorizationId, venue, network, account, nonce, expiresAt) = try VenueOrder.head(&o, kind: "leverage")326 instrument = try DerivCanon.require(try o.string("instrument"), DerivCanon.hlInstrument, "leverage.instrument")327 leverage = try o.int("leverage")328 guard (1...1000).contains(leverage) else { throw DerivCanon.fail("leverage.leverage out of range") }329 marginMode = try DerivCanon.require(try o.string("marginMode"), "cross|isolated", "leverage.marginMode")330 try o.finish()331 }332 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "leverage change") { try VenueLeverage(served: $0) } }333334 public func canonicalBytes() throws -> Data {335 DerivCanon.frame("SPW-VENUE-LEVERAGE-v1", [336 ("v", "1"), ("authorizationId", authorizationId), ("venue", venue), ("network", network), ("account", account), ("kind", "leverage"),337 ("instrument", instrument), ("leverage", String(leverage)), ("marginMode", marginMode), ("nonce", String(nonce)), ("expiresAt", String(expiresAt)),338 ])339 }340}341342// MARK: SPW-VENUE-WITHDRAW-v1343344/** A withdrawal from the venue to the wallet's own address (`VenueWithdrawalSchema`, `venueWithdrawalBytes`). */345public struct VenueWithdrawal: PasskeyApprovable, Equatable, Decodable {346 public let withdrawalId, keyId, venue, network, account, destination: String347 /** USDC asked from the venue, and the venue's fee that was shown. */348 public let amount, fee: String349 /** `time` of the venue's withdraw3 action (unix ms). */350 public let time: Int351 /** Unix seconds. */352 public let createdAt, expiresAt: Int353354 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }355356 public init(served json: JSONValue) throws {357 var o = try StrictObject(json, path: "withdrawal")358 try DerivCanon.version(&o)359 withdrawalId = try DerivCanon.require(try o.string("withdrawalId"), DerivCanon.uuid, "withdrawal.withdrawalId")360 keyId = try o.string("keyId")361 venue = try o.string("venue")362 guard venue == "hyperliquid" else { throw DerivCanon.fail("withdrawal.venue \(venue)") }363 network = try DerivCanon.network(try o.string("network"))364 account = try DerivCanon.require(try o.string("account"), DerivCanon.addressLower, "withdrawal.account")365 destination = try DerivCanon.require(try o.string("destination"), DerivCanon.addressLower, "withdrawal.destination")366 let usd = "(0|[1-9][0-9]*)(\\.[0-9]{1,6})?"367 amount = try DerivCanon.positive(try DerivCanon.require(try o.string("amount"), usd, "withdrawal.amount"), "withdrawal.amount")368 fee = try DerivCanon.positive(try DerivCanon.require(try o.string("fee"), usd, "withdrawal.fee"), "withdrawal.fee")369 time = try DerivCanon.positiveInt(try o.int("time"), "withdrawal.time")370 createdAt = try DerivCanon.positiveInt(try o.int("createdAt"), "withdrawal.createdAt")371 expiresAt = try DerivCanon.positiveInt(try o.int("expiresAt"), "withdrawal.expiresAt")372 try o.finish()373 }374 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "venue withdrawal") { try VenueWithdrawal(served: $0) } }375376 public func canonicalBytes() throws -> Data {377 DerivCanon.frame("SPW-VENUE-WITHDRAW-v1", [378 ("v", "1"), ("withdrawalId", withdrawalId), ("keyId", keyId), ("venue", venue), ("network", network), ("account", account), ("destination", destination),379 ("amount", try DerivCanon.canon(amount)), ("fee", try DerivCanon.canon(fee)), ("time", String(time)), ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)),380 ])381 }382}383384// MARK: SPW-VENUE-MANDATE-v1385386public struct VenueMandateInstrument: Sendable, Equatable, Codable {387 public let instrument: String388 public let maxLeverage: Int389 public let maxPositionNotional: String390 public init(instrument: String, maxLeverage: Int, maxPositionNotional: String) { self.instrument = instrument; self.maxLeverage = maxLeverage; self.maxPositionNotional = maxPositionNotional }391}392393/**394 The derivative mandate (`VenueMandateSchema`, `venueMandateBytes`): after this ONE approval an automated strategy places orders395 inside these limits WITHOUT a passkey per order. It extends a venue authorization and dies with it.396 */397public struct VenueMandate: PasskeyApprovable, Equatable, Decodable {398 public let mandateId, authorizationId, keyId, venue, network, account, agentAddress, strategySha256, agentId: String399 public let instruments: [VenueMandateInstrument]400 public let maxOrderNotional, maxGrossExposure: String401 public let maxOrdersPerDay, maxOrdersPerHour: Int402 public let maxDailyTurnover, floorEquity: String403 public let maxPriceDeviationBps: Int404 /** Unix seconds. */405 public let createdAt, expiresAt: Int406 public let ackSha256: String407408 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }409410 public init(served json: JSONValue) throws {411 var o = try StrictObject(json, path: "mandate")412 try DerivCanon.version(&o)413 mandateId = try DerivCanon.require(try o.string("mandateId"), DerivCanon.uuid, "mandate.mandateId")414 authorizationId = try DerivCanon.require(try o.string("authorizationId"), DerivCanon.uuid, "mandate.authorizationId")415 keyId = try o.string("keyId")416 venue = try o.string("venue")417 guard venue == "hyperliquid" else { throw DerivCanon.fail("mandate.venue \(venue)") }418 network = try DerivCanon.network(try o.string("network"))419 account = try DerivCanon.require(try o.string("account"), DerivCanon.addressLower, "mandate.account")420 agentAddress = try DerivCanon.require(try o.string("agentAddress"), DerivCanon.addressLower, "mandate.agentAddress")421 strategySha256 = try DerivCanon.require(try o.string("strategySha256"), DerivCanon.hash64, "mandate.strategySha256")422 agentId = try DerivCanon.require(try o.string("agentId"), "[A-Za-z0-9._:-]{1,64}", "mandate.agentId")423 instruments = try o.array("instruments").enumerated().map { k, v in424 var i = try StrictObject(v, path: "mandate.instruments.\(k)")425 let x = VenueMandateInstrument(instrument: try DerivCanon.require(try i.string("instrument"), DerivCanon.hlInstrument, "mandate.instruments.\(k).instrument"),426 maxLeverage: try DerivCanon.positiveInt(try i.int("maxLeverage"), "mandate.instruments.\(k).maxLeverage"),427 maxPositionNotional: try DerivCanon.positive(try i.string("maxPositionNotional"), "mandate.instruments.\(k).maxPositionNotional"))428 try i.finish()429 return x430 }431 guard !instruments.isEmpty, instruments.count <= 8 else { throw DerivCanon.fail("mandate.instruments count") }432 maxOrderNotional = try DerivCanon.positive(try o.string("maxOrderNotional"), "mandate.maxOrderNotional")433 maxGrossExposure = try DerivCanon.positive(try o.string("maxGrossExposure"), "mandate.maxGrossExposure")434 maxOrdersPerDay = try DerivCanon.positiveInt(try o.int("maxOrdersPerDay"), "mandate.maxOrdersPerDay")435 maxOrdersPerHour = try DerivCanon.positiveInt(try o.int("maxOrdersPerHour"), "mandate.maxOrdersPerHour")436 maxDailyTurnover = try DerivCanon.positive(try o.string("maxDailyTurnover"), "mandate.maxDailyTurnover")437 floorEquity = try DerivCanon.positive(try o.string("floorEquity"), "mandate.floorEquity")438 maxPriceDeviationBps = try DerivCanon.positiveInt(try o.int("maxPriceDeviationBps"), "mandate.maxPriceDeviationBps")439 createdAt = try DerivCanon.positiveInt(try o.int("createdAt"), "mandate.createdAt")440 expiresAt = try DerivCanon.positiveInt(try o.int("expiresAt"), "mandate.expiresAt")441 ackSha256 = try DerivCanon.require(try o.string("ackSha256"), DerivCanon.hash64, "mandate.ackSha256")442 try o.finish()443 }444 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "derivative mandate") { try VenueMandate(served: $0) } }445446 public func canonicalBytes() throws -> Data {447 // the backend sorts with `<` on strings (UTF-16 code units); the sort is stable and instruments are unique448 let sorted = instruments.sorted { $0.instrument.utf16.lexicographicallyPrecedes($1.instrument.utf16) }449 return DerivCanon.frame("SPW-VENUE-MANDATE-v1", [450 ("v", "1"), ("mandateId", mandateId), ("authorizationId", authorizationId), ("keyId", keyId), ("venue", venue), ("network", network), ("account", account),451 ("agentAddress", agentAddress), ("strategySha256", strategySha256), ("agentId", agentId),452 ("instruments", try sorted.map { "\($0.instrument)|\($0.maxLeverage)|\(try DerivCanon.canon($0.maxPositionNotional))" }.joined(separator: ",")),453 ("maxOrderNotional", try DerivCanon.canon(maxOrderNotional)), ("maxGrossExposure", try DerivCanon.canon(maxGrossExposure)), ("maxOrdersPerDay", String(maxOrdersPerDay)),454 ("maxOrdersPerHour", String(maxOrdersPerHour)), ("maxDailyTurnover", try DerivCanon.canon(maxDailyTurnover)), ("floorEquity", try DerivCanon.canon(floorEquity)),455 ("maxPriceDeviationBps", String(maxPriceDeviationBps)), ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("ackSha256", ackSha256),456 ])457 }458}459460// MARK: SPW-GMX-AUTH-v1461462public struct GmxPolicy: Sendable, Equatable {463 /** GM market addresses (EIP-55). */464 public let allowedMarkets: [String]465 public let maxLeverage: Int466 public let maxOrderSizeUsd: String467 public let maxOrdersPerDay: Int468 public let maxPriceDeviationBps: Int469 /** Largest execution fee of one order, wei. Set by the server from the wallet's fee ceiling; shown, never chosen here. */470 public let maxExecutionFeeWei: String471}472473/** The GMX venue policy the owner approves once (`GmxAuthorizationSchema`, `gmxAuthorizationBytes`). The account IS the wallet's own address. */474public struct GmxAuthorization: PasskeyApprovable, Equatable, Decodable {475 public let authorizationId, keyId, venue, network, account, mode, contracts, exchangeRouter: String476 public let policy: GmxPolicy477 /** Unix seconds. */478 public let createdAt, expiresAt: Int479 public let ackSha256: String480 /** The object as served: the approve route takes it back untouched. */481 public let served: JSONValue482483 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt)) }484485 public init(served json: JSONValue) throws {486 var o = try StrictObject(json, path: "authorization")487 try DerivCanon.version(&o)488 authorizationId = try DerivCanon.require(try o.string("authorizationId"), DerivCanon.uuid, "authorization.authorizationId")489 keyId = try o.string("keyId")490 venue = try o.string("venue"); network = try o.string("network"); mode = try o.string("mode")491 guard venue == "gmx", network == "arbitrum", mode == "MANUAL_LIVE" else { throw DerivCanon.fail("authorization venue, network or mode") }492 account = try DerivCanon.require(try o.string("account"), DerivCanon.addressLower, "authorization.account")493 contracts = try o.string("contracts")494 exchangeRouter = try DerivCanon.require(try o.string("exchangeRouter"), DerivCanon.addressAny, "authorization.exchangeRouter")495 var p = try StrictObject(o.raw("policy"), path: "authorization.policy")496 let markets = try DerivCanon.strings(try p.array("allowedMarkets"), "authorization.policy.allowedMarkets").map { try DerivCanon.require($0, DerivCanon.addressAny, "authorization.policy.allowedMarkets") }497 guard !markets.isEmpty, markets.count <= 8 else { throw DerivCanon.fail("authorization.policy.allowedMarkets count") }498 policy = GmxPolicy(allowedMarkets: markets, maxLeverage: try DerivCanon.positiveInt(try p.int("maxLeverage"), "authorization.policy.maxLeverage"),499 maxOrderSizeUsd: try DerivCanon.positive(try p.string("maxOrderSizeUsd"), "authorization.policy.maxOrderSizeUsd"),500 maxOrdersPerDay: try DerivCanon.positiveInt(try p.int("maxOrdersPerDay"), "authorization.policy.maxOrdersPerDay"),501 maxPriceDeviationBps: try DerivCanon.positiveInt(try p.int("maxPriceDeviationBps"), "authorization.policy.maxPriceDeviationBps"),502 maxExecutionFeeWei: try DerivCanon.require(try p.string("maxExecutionFeeWei"), DerivCanon.uint, "authorization.policy.maxExecutionFeeWei"))503 try p.finish()504 createdAt = try DerivCanon.positiveInt(try o.int("createdAt"), "authorization.createdAt")505 expiresAt = try DerivCanon.positiveInt(try o.int("expiresAt"), "authorization.expiresAt")506 ackSha256 = try DerivCanon.require(try o.string("ackSha256"), DerivCanon.hash64, "authorization.ackSha256")507 try o.finish()508 served = json509 }510 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "GMX authorization") { try GmxAuthorization(served: $0) } }511512 public func canonicalBytes() throws -> Data {513 let p = policy514 return DerivCanon.frame("SPW-GMX-AUTH-v1", [515 ("v", "1"), ("authorizationId", authorizationId), ("keyId", keyId), ("venue", venue), ("network", network), ("account", account), ("mode", mode),516 ("contracts", contracts), ("exchangeRouter", exchangeRouter),517 ("policy.allowedMarkets", DerivCanon.jsSorted(p.allowedMarkets).joined(separator: ",")), ("policy.maxLeverage", String(p.maxLeverage)),518 ("policy.maxOrderSizeUsd", try DerivCanon.canon(p.maxOrderSizeUsd)), ("policy.maxOrdersPerDay", String(p.maxOrdersPerDay)),519 ("policy.maxPriceDeviationBps", String(p.maxPriceDeviationBps)), ("policy.maxExecutionFeeWei", p.maxExecutionFeeWei),520 ("createdAt", String(createdAt)), ("expiresAt", String(expiresAt)), ("ackSha256", ackSha256),521 ])522 }523}524525// MARK: SPW-RISK-INTENT-v1 / SPW-GMX-RISK-INTENT-v1 (domain + "\n" + sorted-key JSON)526527extension DerivRiskPolicy {528 /** Strict: exactly the sixteen fields of `RiskPolicySchema.strict()`. */529 init(strict json: JSONValue?, path: String) throws {530 var p = try StrictObject(json, path: path)531 let mode = try p.string("mode")532 let instruments = try DerivCanon.strings(try p.array("allowedInstruments"), "\(path).allowedInstruments")533 guard let h = p.raw("halt") else { throw DerivCanon.fail("\(path).halt missing") }534 guard h.isNull || h.stringValue != nil else { throw DerivCanon.fail("\(path).halt is not a string") }535 func dec(_ k: String) throws -> String {536 let s = try p.string(k)537 guard VenueDecimal(s) != nil else { throw DerivCanon.fail("\(path).\(k) is not a decimal") }538 return s539 }540 self.init(mode: mode, allowedInstruments: instruments, halt: h.stringValue, maxDataAgeMs: try p.int("maxDataAgeMs"), maxDeviationBps: try dec("maxDeviationBps"),541 maxMarkIndexBps: try dec("maxMarkIndexBps"), maxLeverage: try dec("maxLeverage"), maxOrderNotional: try dec("maxOrderNotional"), maxGrossExposure: try dec("maxGrossExposure"),542 maxPositionNotional: try dec("maxPositionNotional"), minFreeCollateral: try dec("minFreeCollateral"), minLiquidationDistanceBps: try dec("minLiquidationDistanceBps"),543 maxDailyLoss: try dec("maxDailyLoss"), maxTotalLoss: try dec("maxTotalLoss"), maxOrdersPerMinute: try p.int("maxOrdersPerMinute"), maxOrdersPerDay: try p.int("maxOrdersPerDay"))544 try p.finish()545 }546547 /** The policy as the JSON the backend hashes: strings exactly as served, the instrument list in its served order. */548 var canonicalJSON: JSONValue {549 ["mode": .string(mode), "allowedInstruments": .array(allowedInstruments.map { .string($0) }), "halt": halt.map { .string($0) } ?? .null, "maxDataAgeMs": .int(Int64(maxDataAgeMs)),550 "maxDeviationBps": .string(maxDeviationBps), "maxMarkIndexBps": .string(maxMarkIndexBps), "maxLeverage": .string(maxLeverage), "maxOrderNotional": .string(maxOrderNotional),551 "maxGrossExposure": .string(maxGrossExposure), "maxPositionNotional": .string(maxPositionNotional), "minFreeCollateral": .string(minFreeCollateral),552 "minLiquidationDistanceBps": .string(minLiquidationDistanceBps), "maxDailyLoss": .string(maxDailyLoss), "maxTotalLoss": .string(maxTotalLoss),553 "maxOrdersPerMinute": .int(Int64(maxOrdersPerMinute)), "maxOrdersPerDay": .int(Int64(maxOrdersPerDay))]554 }555}556557/** A string that is nullable but must be present (the backend hashes `null`, never an absent key). */558private func requiredNullableString(_ o: inout StrictObject, _ k: String) throws -> String? {559 guard let v = o.raw(k) else { throw DerivCanon.fail("\(o.path).\(k) missing") }560 if v.isNull { return nil }561 guard let s = v.stringValue else { throw DerivCanon.fail("\(o.path).\(k) is not a string") }562 return s563}564565/**566 A change of the API-side protections of a live account that LOOSENS something (`RiskIntent`, `riskIntentHash`): a wider policy,567 lifting the owner's halt, or accepting the venue's positions as the reference after a divergence.568 */569public struct LiveRiskIntent: PasskeyApprovable, Equatable, Decodable {570 public enum Kind: String, Sendable { case policy, resume, rebase }571 public let kind: Kind572 public let accountId, venue, network, account, authorizationId: String573 /** `policy`: the whole policy that will be in force. */574 public let policy: DerivRiskPolicy?575 /** `policy`: the fields that become looser. */576 public let loosened: [String]577 /** `resume`: the halt being lifted; `rebase`: the divergence being accepted (nil when none is flagged). */578 public let subject: String?579 public let nonce: String580 /** Unix milliseconds. */581 public let createdAt, expiresAt: Int582583 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }584585 public init(served json: JSONValue) throws {586 var o = try StrictObject(json, path: "intent")587 try DerivCanon.version(&o)588 guard let k = Kind(rawValue: try o.string("kind")) else { throw DerivCanon.fail("intent.kind") }589 kind = k590 accountId = try o.string("accountId"); venue = try o.string("venue"); network = try o.string("network"); account = try o.string("account"); authorizationId = try o.string("authorizationId")591 guard let p = o.raw("policy") else { throw DerivCanon.fail("intent.policy missing") }592 policy = p.isNull ? nil : try DerivRiskPolicy(strict: p, path: "intent.policy")593 loosened = try DerivCanon.strings(try o.array("loosened"), "intent.loosened")594 subject = try requiredNullableString(&o, "subject")595 nonce = try o.string("nonce")596 createdAt = try o.int("createdAt"); expiresAt = try o.int("expiresAt")597 try o.finish()598 guard (kind == .policy) == (policy != nil) else { throw DerivCanon.fail("intent.policy does not match its kind") }599 }600 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "risk intent") { try LiveRiskIntent(served: $0) } }601602 public func canonicalBytes() throws -> Data {603 let json: JSONValue = ["v": 1, "kind": .string(kind.rawValue), "accountId": .string(accountId), "venue": .string(venue), "network": .string(network), "account": .string(account),604 "authorizationId": .string(authorizationId), "policy": policy?.canonicalJSON ?? .null, "loosened": .array(loosened.map { .string($0) }),605 "subject": subject.map { .string($0) } ?? .null, "nonce": .string(nonce), "createdAt": .int(Int64(createdAt)), "expiresAt": .int(Int64(expiresAt))]606 return Data("SPW-RISK-INTENT-v1\n\(try StableJSON.string(json))".utf8)607 }608}609610/** The same for GMX (`GmxRiskIntent`, `gmxRiskIntentHash`): raising a loss limit, or lifting the owner's halt. */611public struct GmxRiskIntent: PasskeyApprovable, Equatable, Decodable {612 public enum Kind: String, Sendable { case limits = "gmx-limits", resume = "gmx-resume" }613 public struct Limits: Sendable, Equatable { public let maxDailyLoss, maxTotalLoss: String }614 public let kind: Kind615 public let authorizationId: String616 public let limits: Limits?617 public let loosened: [String]618 public let subject: String?619 public let nonce: String620 /** Unix milliseconds. */621 public let createdAt, expiresAt: Int622623 public var expiry: Date { Date(timeIntervalSince1970: TimeInterval(expiresAt) / 1000) }624625 public init(served json: JSONValue) throws {626 var o = try StrictObject(json, path: "intent")627 try DerivCanon.version(&o)628 guard let k = Kind(rawValue: try o.string("kind")) else { throw DerivCanon.fail("intent.kind") }629 kind = k630 authorizationId = try o.string("authorizationId")631 guard let l = o.raw("limits") else { throw DerivCanon.fail("intent.limits missing") }632 if l.isNull { limits = nil } else {633 var x = try StrictObject(l, path: "intent.limits")634 limits = Limits(maxDailyLoss: try x.string("maxDailyLoss"), maxTotalLoss: try x.string("maxTotalLoss"))635 try x.finish()636 guard VenueDecimal(limits!.maxDailyLoss) != nil, VenueDecimal(limits!.maxTotalLoss) != nil else { throw DerivCanon.fail("intent.limits are not decimals") }637 }638 loosened = try DerivCanon.strings(try o.array("loosened"), "intent.loosened")639 subject = try requiredNullableString(&o, "subject")640 nonce = try o.string("nonce")641 createdAt = try o.int("createdAt"); expiresAt = try o.int("expiresAt")642 try o.finish()643 guard (kind == .limits) == (limits != nil) else { throw DerivCanon.fail("intent.limits do not match its kind") }644 }645 public init(from decoder: Decoder) throws { self = try decodeStrict(decoder, "GMX risk intent") { try GmxRiskIntent(served: $0) } }646647 public func canonicalBytes() throws -> Data {648 let json: JSONValue = ["v": 1, "kind": .string(kind.rawValue), "authorizationId": .string(authorizationId),649 "limits": limits.map { ["maxDailyLoss": .string($0.maxDailyLoss), "maxTotalLoss": .string($0.maxTotalLoss)] } ?? .null,650 "loosened": .array(loosened.map { .string($0) }), "subject": subject.map { .string($0) } ?? .null, "nonce": .string(nonce),651 "createdAt": .int(Int64(createdAt)), "expiresAt": .int(Int64(expiresAt))]652 return Data("SPW-GMX-RISK-INTENT-v1\n\(try StableJSON.string(json))".utf8)653 }654}655656// MARK: pinned trust inputs (the same tables the isolated signer ships with)657658/** `HL_BRIDGE_PINS.mainnet` and the deposit rules of packages/derivatives/src/live/collateral.ts, pinned 2026-11-11. A deposit to anything else is refused here too. */659public enum HyperliquidCollateralPins {660 public static let network = "arbitrum"661 public static let chainRef = "42161"662 /** Bridge2 on Arbitrum One (EIP-55). */663 public static let bridge = "0x2Df1c51E09aECF9cacB7bc98cB1742757f163dF7"664 /** Native USDC on Arbitrum One. */665 public static let usdc = "0xaf88d065e77c8cC2239327C5EDb3A432268e5831"666 public static let route = "arbitrum-bridge2"667 /** The wallet's own floor in USDC base units (6 USDC): below the venue minimum of 5 the funds are lost. */668 public static let minAmountUnits = "6000000"669 public static let usdcDecimals = 6670}671