Repository Public
1// SP Wallet Core2// File: Tests/SPWalletCoreTests/DerivativesTests.swift3// Description: The derivatives domain: primitives against the backend's own outputs (Vectors/derivatives-primitives.json), every4// canonical object against the backend-generated vectors (Vectors/SPW-VENUE-*, SPW-GMX-*, SPW-RISK-INTENT-v1,5// derivatives-risk-intents.json), decoding of every response shape (Fixtures/derivatives-*.json, shapes copied from6// the TS route and view code named in the fixture generator comments and in each test), the request contract of7// every route of derivativesRoutes / liveRoutes / collateralRoutes / gmxRoutes, and the approval flows with their refusals.8//9// Author: Simon-Pierre Boucher10// Contact: contact@spboucher.ai11import Foundation12import Testing13@testable import SPWalletCore1415// MARK: support1617private enum DX {18 static let rp = "wallet.example.test"19 static let own = "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"20 static let key = "ui-3d2c0a34-8f5f-4b1e-9c56-0000000000c1"21 /** 2026-11-06T… : the instant the vectors are dated at (unix seconds 1794000000), plus ten seconds. */22 static let now = Date(timeIntervalSince1970: 1_794_000_010)23 static let paper = PaperAccountID(rawValue: "3d2c0a34-8f5f-4b1e-9c56-0000000000a1")24 static let live = LiveAccountID(rawValue: "7a1c1f0e-8f5f-4b1e-9c56-000000000710")2526 static func fixture(_ file: String, _ key: String) throws -> JSONValue {27 guard let v = try TestResources.json("derivatives-\(file).json")[key] else { throw APIError(status: 0, code: "fixture", message: "no \(key) in \(file)") }28 return v29 }30 static func text(_ v: JSONValue) -> String { String(decoding: try! APICoding.encoder().encode(v), as: UTF8.self) }31 static func vector(_ file: String, _ name: String) throws -> CanonicalVector {32 guard let v = try CanonicalVector.load("\(file).json").first(where: { $0.name == name }) else { throw APIError(status: 0, code: "vector", message: name) }33 return v34 }35 static func set(_ v: JSONValue, _ path: [String], _ new: JSONValue?) -> JSONValue {36 guard case .object(var o) = v, let k = path.first else { return new ?? .null }37 if path.count == 1 { if let new { o[k] = new } else { o[k] = nil } } else { o[k] = set(o[k] ?? .object([:]), Array(path.dropFirst()), new) }38 return .object(o)39 }40 static func options<T: PasskeyApprovable>(_ object: T, rp: String = rp) throws -> JSONValue {41 ["challenge": .string(try object.approvalDigest().base64URL), "rpId": .string(rp), "userVerification": "required", "timeout": 120000, "allowCredentials": []]42 }43 static func challenge<T: PasskeyApprovable>(_ object: T) -> String { (try? object.approvalDigest().base64URL) ?? "" }44 static func account(_ key: String = "account") throws -> LiveAccount { try fixture("live", key).decode(LiveAccountDetail.self).account }45 static func gmxStatus() throws -> GmxStatus { try fixture("gmx", "status").decode() }46 static let ackText = "Hyperliquid — conditions de la plateforme et votre juridiction (Québec, Canada)."47 static func ack(_ venue: String, locale: String = "fr") -> JSONValue {48 ["venue": .string(venue), "locale": .string(locale), "text": .string(ackText), "sha256": .string(DerivHash.sha256Hex(ackText)), "version": "2026-11-10", "source": "docs/v4/venues/jurisdiction.md"]49 }50}5152/** A passkey that signs whatever it is handed and records the challenge: the tests assert on WHAT was asked of it. */53private final class StubPasskey: PasskeyAuthenticator, @unchecked Sendable {54 private let lock = NSLock()55 private var _challenges: [String] = []56 var challenges: [String] { lock.withLock { _challenges } }57 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {58 lock.withLock { _challenges.append(options.challenge) }59 return PasskeyAssertion(credentialId: Data([1, 2, 3]), clientDataJSON: Data("{}".utf8), authenticatorData: Data([0]), signature: Data([9]), userHandle: nil)60 }61 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration { throw PasskeyError.notAvailable("stub") }62}6364// MARK: primitives6566@Suite struct DerivativesPrimitiveTests {67 let p: JSONValue68 init() throws { p = try JSONDecoder().decode(JSONValue.self, from: try TestResources.data("derivatives-primitives.json", in: "Vectors")) }6970 @Test func keccak256MatchesNobleOnEveryPaddingBoundary() throws {71 let rows = try #require(p["keccak256"]?.arrayValue)72 #expect(rows.count == 7)73 for r in rows { #expect(Keccak256.hash(Data(r["utf8"]!.stringValue!.utf8)).hex == r["hex"]!.stringValue!) }74 }75 @Test func clientOrderIdIsTheBackendsDerivation() throws {76 let rows = try #require(p["cloid"]?.arrayValue)77 #expect(rows.count >= 6)78 for r in rows { #expect(HyperliquidClientOrderID.derive(from: r["key"]!.stringValue!) == r["cloid"]!.stringValue!) }79 // a key that already is a 128-bit hex id is kept as is80 #expect(HyperliquidClientOrderID.derive(from: "0x0123456789abcdef0123456789abcdef") == "0x0123456789abcdef0123456789abcdef")81 #expect(HyperliquidClientOrderID.derive(from: "") == nil)82 #expect(HyperliquidClientOrderID.derive(from: String(repeating: "x", count: 129)) == nil)83 }84 @Test func decimalsAreCanonicalizedComparedAndMultipliedAsTheBackendDoes() throws {85 for r in try #require(p["decimalCanon"]?.arrayValue) { #expect(VenueDecimal(r["in"]!.stringValue!)?.description == r["out"]!.stringValue!) }86 for r in try #require(p["decimalCompare"]?.arrayValue) {87 let a = try #require(VenueDecimal(r["a"]!.stringValue!)), b = try #require(VenueDecimal(r["b"]!.stringValue!))88 #expect((a < b ? -1 : a > b ? 1 : 0) == r["cmp"]!.intValue!, "\(a) vs \(b)")89 }90 for r in try #require(p["gmxSizeFromLeverage"]?.arrayValue) {91 let size = try #require(VenueDecimal(r["collateral"]!.stringValue!)).multiplied(by: try #require(VenueDecimal(r["leverage"]!.stringValue!))).truncated(toDecimals: 2)92 #expect(size.description == r["sizeUsd"]!.stringValue!)93 #expect(size.units(decimals: 30) == r["sizeDeltaUsd"]!.stringValue!)94 }95 for r in try #require(p["scaleExact"]?.arrayValue) { #expect(VenueDecimal(r["in"]!.stringValue!)?.units(decimals: Int(r["decimals"]!.intValue!)) == r["out"]!.stringValue!) }96 for r in try #require(p["usdc"]?.arrayValue) {97 #expect(VenueDecimal(r["in"]!.stringValue!)?.units(decimals: 6) == r["units"]!.stringValue!)98 #expect(try BaseUnits(r["units"]!.stringValue!).formatted(decimals: 6) == r["decimal"]!.stringValue!)99 }100 }101 @Test func whatIsNotADecimalForTheBackendIsNotOneHere() {102 for bad in ["", "+1", "1e3", ".5", "1.", "01", "1,5", "1 ", "--1", "0x10", "١", String(repeating: "9", count: 61), "1." + String(repeating: "0", count: 60)] { #expect(VenueDecimal(bad) == nil, "\(bad)") }103 #expect(VenueDecimal("1.23")?.units(decimals: 1) == nil) // never rounded104 #expect(VenueDecimal("-1")?.units(decimals: 6) == nil)105 #expect(VenueDecimal.same("2500.50", "2500.5") && !VenueDecimal.same("2500.50", "2500.51") && !VenueDecimal.same("abc", "abc"))106 }107 @Test func theAcknowledgementHashIsTheHashOfTheDisplayedText() throws {108 let acks = try #require(p["acknowledgements"]).decode([JurisdictionAck].self)109 #expect(acks.count == 4 && Set(acks.map(\.venue)) == ["hyperliquid", "gmx"])110 for a in acks { #expect(a.textMatchesHash) }111 let tampered = try DX.set(try #require(p["acknowledgements"]?[0]), ["text"], "Trading on this venue is cleared for you.").decode(JurisdictionAck.self)112 #expect(!tampered.textMatchesHash)113 }114 @Test func thePinnedDepositRouteIsTheBackends() throws {115 let pin = try #require(p["pins"]?["hyperliquidMainnet"])116 #expect(pin["bridge"]?.stringValue == HyperliquidCollateralPins.bridge && pin["usdc"]?.stringValue == HyperliquidCollateralPins.usdc)117 #expect(pin["network"]?.stringValue == HyperliquidCollateralPins.network && pin["chainId"]?.intValue.map { String($0) } == HyperliquidCollateralPins.chainRef)118 #expect(VenueDecimal(try #require(p["pins"]?["depositFloorUsdc"]?.stringValue))?.units(decimals: 6) == HyperliquidCollateralPins.minAmountUnits)119 }120 @Test func stableJsonEscapesLikeJSONStringify() throws {121 #expect(StableJSON.quote("a\"b\\c\n\t\u{01}\u{1f}\u{7f}\u{2028}é😀/") == "\"a\\\"b\\\\c\\n\\t\\u0001\\u001f\u{7f}\u{2028}é😀/\"")122 #expect(try StableJSON.string(["b": 1, "a": [true, nil, "x"], "B": ["z": 0, "y": -5]]) == #"{"B":{"y":-5,"z":0},"a":[true,null,"x"],"b":1}"#)123 #expect(throws: ApprovalError.self) { try StableJSON.string(["x": .double(1.5)]) }124 }125}126127// MARK: canonical objects against the backend's vectors128129@Suite struct DerivativesCanonicalTests {130 private func run<T: PasskeyApprovable>(_ file: String, minimum: Int, _ build: (JSONValue) throws -> T) throws {131 let vectors = try CanonicalVector.load("\(file).json")132 #expect(vectors.count >= minimum, "\(file)")133 for v in vectors {134 let o = try build(v.object)135 #expect(try o.canonicalBytes().hex == v.canonicalHex, "\(file)/\(v.name) bytes")136 #expect(try o.approvalDigest().hex == v.hashHex, "\(file)/\(v.name) hash")137 }138 }139 @Test func venueAuthorization() throws { try run("SPW-VENUE-AUTH-v1", minimum: 2) { try VenueAuthorization(served: $0) } }140 @Test func venueOrder() throws { try run("SPW-VENUE-ORDER-v1", minimum: 6) { try VenueOrder(served: $0) } }141 @Test func venueLeverage() throws { try run("SPW-VENUE-LEVERAGE-v1", minimum: 2) { try VenueLeverage(served: $0) } }142 @Test func venueWithdrawal() throws { try run("SPW-VENUE-WITHDRAW-v1", minimum: 2) { try VenueWithdrawal(served: $0) } }143 @Test func derivativeMandate() throws { try run("SPW-VENUE-MANDATE-v1", minimum: 2) { try VenueMandate(served: $0) } }144 @Test func gmxAuthorization() throws { try run("SPW-GMX-AUTH-v1", minimum: 2) { try GmxAuthorization(served: $0) } }145 @Test func liveRiskIntent() throws {146 try run("SPW-RISK-INTENT-v1", minimum: 4) { try LiveRiskIntent(served: $0) }147 let mine = try CanonicalVector.load("derivatives-risk-intents.json")148 #expect(mine.count == 6)149 for v in mine where v.domain == "SPW-RISK-INTENT-v1" {150 let i = try LiveRiskIntent(served: v.object)151 #expect(try i.canonicalBytes().hex == v.canonicalHex && i.approvalDigest().hex == v.hashHex, "\(v.name)")152 }153 }154 @Test func gmxRiskIntent() throws {155 try run("SPW-GMX-RISK-INTENT-v1", minimum: 2) { try GmxRiskIntent(served: $0) }156 for v in try CanonicalVector.load("derivatives-risk-intents.json") where v.domain == "SPW-GMX-RISK-INTENT-v1" {157 let i = try GmxRiskIntent(served: v.object)158 #expect(try i.canonicalBytes().hex == v.canonicalHex && i.approvalDigest().hex == v.hashHex, "\(v.name)")159 }160 }161 @Test func theIntentsWithAVenueSectionAreTheBackends() throws {162 for name in ["venue-deposit-hyperliquid", "gmx-increase-long", "gmx-decrease-short", "gmx-cancel-with-order-key"] {163 let v = try DX.vector("SPW-INTENT-v1", name), i = try Intent(served: v.object)164 #expect(try i.canonicalBytes().hex == v.canonicalHex && i.approvalDigest().hex == v.hashHex, "\(name)")165 }166 }167168 @Test func anUnknownFieldAnywhereIsARefusal() throws {169 let cases: [(String, [String], (JSONValue) throws -> Void)] = [170 ("SPW-VENUE-AUTH-v1", ["builder"], { _ = try VenueAuthorization(served: $0) }), ("SPW-VENUE-AUTH-v1", ["policy", "maxWithdrawal"], { _ = try VenueAuthorization(served: $0) }),171 ("SPW-VENUE-ORDER-v1", ["vaultAddress"], { _ = try VenueOrder(served: $0) }), ("SPW-VENUE-LEVERAGE-v1", ["isBuy"], { _ = try VenueLeverage(served: $0) }),172 ("SPW-VENUE-WITHDRAW-v1", ["memo"], { _ = try VenueWithdrawal(served: $0) }), ("SPW-VENUE-MANDATE-v1", ["maxWithdrawal"], { _ = try VenueMandate(served: $0) }),173 ("SPW-GMX-AUTH-v1", ["referralCode"], { _ = try GmxAuthorization(served: $0) }), ("SPW-GMX-AUTH-v1", ["policy", "swapPath"], { _ = try GmxAuthorization(served: $0) }),174 ("SPW-RISK-INTENT-v1", ["extra"], { _ = try LiveRiskIntent(served: $0) }), ("SPW-RISK-INTENT-v1", ["policy", "maxWithdrawal"], { _ = try LiveRiskIntent(served: $0) }),175 ("SPW-GMX-RISK-INTENT-v1", ["extra"], { _ = try GmxRiskIntent(served: $0) }),176 ]177 for (file, path, parse) in cases {178 let object = try CanonicalVector.load("\(file).json")[0].object179 try parse(object)180 #expect(throws: ApprovalError.self, "\(file) \(path)") { try parse(DX.set(object, path, "1")) }181 }182 }183 @Test func whatTheBackendsSchemaRefusesIsRefused() throws {184 let order = try CanonicalVector.load("SPW-VENUE-ORDER-v1.json")[0].object185 for (path, value) in [(["triggerPrice"], JSONValue?.none), (["size"], "0"), (["size"], "-1"), (["price"], "1e5"), (["side"], "long"), (["type"], "market"), (["tif"], "fok"),186 (["clientId"], "0xABCDEF0123456789abcdef0123456789"), (["account"], .string(DX.own)), (["venue"], "gmx"), (["network"], "arbitrum"), (["kind"], "leverage"),187 (["v"], 2), (["nonce"], "1794000000001"), (["reduceOnly"], "false"), (["instrument"], "gmx:BTC")] as [([String], JSONValue?)] {188 #expect(throws: ApprovalError.self, "order \(path) = \(String(describing: value))") { try VenueOrder(served: DX.set(order, path, value)) }189 }190 let auth = try CanonicalVector.load("SPW-VENUE-AUTH-v1.json")[0].object191 for (path, value) in [(["mode"], "AUTO"), (["policy", "allowedInstruments"], []), (["policy", "maxLeverage"], "5"), (["policy", "maxOrderNotional"], "0"), (["ackSha256"], "C3"), (["agentName"], "has space")] as [([String], JSONValue?)] {192 #expect(throws: ApprovalError.self, "authorization \(path)") { try VenueAuthorization(served: DX.set(auth, path, value)) }193 }194 let w = try CanonicalVector.load("SPW-VENUE-WITHDRAW-v1.json")[0].object195 #expect(throws: ApprovalError.self) { try VenueWithdrawal(served: DX.set(w, ["amount"], "1.0000001")) }196 #expect(throws: ApprovalError.self) { try VenueWithdrawal(served: DX.set(w, ["destination"], .string(DX.own))) } // not lower case: not what the backend would hash197 let risk = try DX.vector("SPW-RISK-INTENT-v1", "resume-after-halt").object198 #expect(throws: ApprovalError.self) { try LiveRiskIntent(served: DX.set(risk, ["subject"], nil)) } // absent ≠ null199 #expect(throws: ApprovalError.self) { try LiveRiskIntent(served: DX.set(risk, ["kind"], "withdraw")) }200 #expect(throws: ApprovalError.self) { try LiveRiskIntent(served: DX.set(risk, ["policy"], nil)) }201 }202 @Test func everyFieldOfAnOrderChangesItsDigest() throws {203 let order = try CanonicalVector.load("SPW-VENUE-ORDER-v1.json")[0].object, base = try VenueOrder(served: order).approvalDigest()204 for (k, v) in [("size", "0.02"), ("price", "68501"), ("side", "sell"), ("reduceOnly", true), ("tif", "ioc"), ("instrument", "hyperliquid:ETH"), ("network", "testnet"), ("nonce", 1794000000002),205 ("expiresAt", 1794000090002), ("triggerPrice", "68000"), ("type", "stop_limit"), ("clientId", "0x00000000000000000000000000000002"), ("account", "0x70997970c51812dc3a010c7d01b50e0d17dc79c9"),206 ("authorizationId", "7a1c1f0e-8f5f-4b1e-9c56-000000000501")] as [(String, JSONValue)] {207 #expect(try VenueOrder(served: DX.set(order, [k], v)).approvalDigest() != base, "\(k)")208 }209 // the same value written another way is the same order210 #expect(try VenueOrder(served: DX.set(order, ["size"], "0.01")).approvalDigest() == base)211 }212}213214// MARK: decoding of every response shape215216@Suite struct DerivativesDecodingTests {217 /** Shapes: services/api/src/derivatives/routes.ts + data.ts + route.ts; packages/derivatives/src/models.ts; services/api/test/derivatives-api.test.ts, derivatives-router.test.ts. */218 @Test func marketData() throws {219 let venues: DerivVenuesAnswer = try DX.fixture("market-paper", "venues").decode()220 #expect(venues.venues.count == 2 && venues.venues[0].paper == true && venues.venues[0].capabilities?.orderTypes?.count == 6)221 #expect(venues.venues[1].restriction?.contains("exclude Canada") == true && venues.venues[1].status == "degraded" && venues.venues[1].lastOkAt == nil)222 let inst: DerivInstrumentsAnswer = try DX.fixture("market-paper", "instruments").decode()223 #expect(inst.instruments[0].id == "hyperliquid:BTC" && inst.instruments[0].maxLeverage == "40" && inst.instruments[0].tickSize == "1" && inst.instruments[0].lotSize == "0.00001")224 #expect(inst.instruments[0].minOrderSize == nil && inst.errors?.first?.venue == "gmx")225 let tickers: DerivTickersAnswer = try DX.fixture("market-paper", "tickers").decode()226 #expect(tickers.tickers[0].mark == "70000" && tickers.tickers[0].index == "69990.5" && tickers.tickers[0].funding == "0.0000125" && tickers.tickers[0].openInterest == "25000.5")227 #expect(tickers.tickers[1].index == nil && tickers.tickers[1].last == "70001" && tickers.tickers[1].nextFundingTs == Date(timeIntervalSince1970: 1_794_003_600))228 let m: DerivMarket = try DX.fixture("market-paper", "market").decode()229 #expect(m.book?.bids.first?.price == "70000" && m.book?.asks.last?.size == "3" && m.trades?.count == 1 && m.errors?["trades"] == "timeout" && m.liquidity == nil)230 let g: DerivMarket = try DX.fixture("market-paper", "marketGmx").decode()231 #expect(g.book == nil && g.liquidity?.oracleMax == "3500.5" && g.liquidity?.priceImpact?.maxFactorNegative == "0.005" && g.liquidity?.fundingRateLongPerHour == "-0.00001")232 let c: DerivCandlesAnswer = try DX.fixture("market-paper", "candles").decode()233 #expect(c.candles[0].close == "70000" && c.interval == "1h" && c.candles[0].ts == Date(timeIntervalSince1970: 1_794_000_000))234 let f: DerivFundingHistory = try DX.fixture("market-paper", "funding").decode()235 #expect(f.history.count == 2 && f.history[1].rate == "-0.000003" && f.intervalSec == 3600)236 let cmp: DerivCompareAnswer = try DX.fixture("market-paper", "compare").decode()237 #expect(cmp.rows[0].fundingVenue?.intervalSec == 3600 && cmp.rows[0].depthUsd1pct == "1500000.25" && cmp.rows[0].maxLeverage == "40")238 let w: DerivWatch = try DX.fixture("market-paper", "watch").decode()239 #expect(w.state.withdrawable == "800" && w.positions[0].liquidationPrice == "52000.5" && w.positions[0].liquidationPriceIsVenueReported && w.openOrders[0].status == "open")240 let assets: DerivRouteAssetsAnswer = try DX.fixture("market-paper", "routeAssets").decode()241 #expect(assets.assets[0].candidateVenues == 1 && assets.assets[0].venues[1].restriction == "market data only")242 let route: DerivRouteAnswer = try DX.fixture("market-paper", "route").decode()243 #expect(route.candidates[0].eligibility.executableAs == "paper" && route.candidates[0].risk?.accounts[0].code == "order_notional_exceeded" && route.candidates[0].raw["margin"]?["liquidationPrice"]?["source"]?.stringValue == "estimate")244 #expect(route.ranking?.rows[0].rank == 1 && route.ranking?.excluded?.first?.venue == "dydx" && route.source == "estimate" && route.warnings?.count == 1)245 }246 /** Shapes: services/api/src/derivatives/paper.ts view/get/preview/order/close/cancel; services/api/test/derivatives-paper.test.ts. */247 @Test func paperAccounts() throws {248 let list: PaperAccountsAnswer = try DX.fixture("market-paper", "paperAccounts").decode()249 #expect(list.accounts[0].id == DX.paper && list.accounts[0].kind == "paper" && list.accounts[0].policy.halt == nil && list.accounts[0].policy.maxOrdersPerMinute == 10)250 #expect(list.accounts[0].settings?.liquidationPrice?.hasPrefix("estimate") == true && list.accounts[0].settings?.leverageByInstrument?["hyperliquid:BTC"] == "5")251 // a paper position's liquidation price is the engine's estimate, never presented as a venue figure252 #expect(list.accounts[0].positions[0].source == "paper" && !list.accounts[0].positions[0].liquidationPriceIsVenueReported)253 let d: PaperAccountDetail = try DX.fixture("market-paper", "paperAccount").decode()254 #expect(d.account.label == "Essai" && d.orders.count == 1 && d.fills[0].fee == "0.621" && d.funding[0].amount == "-0.12" && d.riskEvents[0].code == "order_notional_exceeded" && d.equity[0].source == "paper")255 let p: PaperOrderPreview = try DX.fixture("market-paper", "paperPreview").decode()256 #expect(p.risk.ok && p.risk.refusal == nil && p.estimate?.liquidationPrice?.source == "estimate" && p.estimate?.liquidationPrice?.value == "56500.25" && p.request?.price == "70351")257 let r: PaperOrderPreview = try DX.fixture("market-paper", "paperPreviewRefused").decode()258 #expect(r.risk.refusal == DerivativesRefusal(code: "leverage_exceeded", reason: "leverage 50 is above the venue maximum 40 for hyperliquid:BTC", status: 200) && r.risk.refusal?.kind == .risk)259 let placed: PaperPlacement = try DX.fixture("market-paper", "paperPlaced").decode()260 #expect(placed.order.status == "filled" && placed.fills?.count == 1 && placed.idempotent == false)261 let closed: PaperPlacement = try DX.fixture("market-paper", "paperClosed").decode()262 #expect(closed.worstPrice == "69650" && closed.slippageBoundBps == 50 && closed.order.reduceOnly)263 }264 /** Shapes: services/api/src/derivatives/exec.ts config/summary/mandateInfo/get/collateral/revoke/recover/halt/preview/cancelAll/approveLeverage; services/api/test/derivatives-live.test.ts. */265 @Test func liveAccounts() throws {266 let cfg: LiveConfig = try DX.fixture("live", "config").decode()267 #expect(!cfg.mainnetEnabled && cfg.mainnet?.code == "mainnet_disabled" && cfg.mandateLive.available && cfg.mandateLive.mainnet?.code == "mandate_mainnet_disabled")268 #expect(cfg.pinnedAssets.mainnet[1] == LivePinnedAsset(instrument: "hyperliquid:ETH", maxLeverage: 25) && cfg.bounds.maxAuthorizationDays == 90 && cfg.bounds.orderApprovalTtlMs == 90000 && cfg.reasons?["mainnet_disabled"]?.fr.isEmpty == false)269 let j: JurisdictionAnswer = try DX.fixture("live", "jurisdiction").decode()270 #expect(j.fr.locale == "fr" && j.en.text == "TEXT")271 let k: LiveVenueKey = try DX.fixture("live", "venueKey").decode()272 #expect(k.address.hasPrefix("0x90f7") && k.account.hasPrefix("0x7099"))273 let list: LiveAccountsAnswer = try DX.fixture("live", "accounts").decode()274 #expect(list.accounts[0].id == DX.live && list.accounts[0].mode == .manualLive && list.accounts[0].isMainnet && list.accounts[0].authorization?.policy.maxLeverage == 5 && list.accounts[0].tradable)275 #expect(list.accounts[1].mode == .readOnly && list.accounts[1].authorization == nil && !list.accounts[1].tradable && list.accounts[1].modes == [.readOnly])276 let d: LiveAccountDetail = try DX.fixture("live", "account").decode()277 #expect(d.venueState.state?.maintenanceMargin == "25" && d.venueState.positions[0].liquidationPriceIsVenueReported && d.venueState.openOrders.count == 1 && d.venueState.error == nil)278 #expect(d.orders[0].canonical?.value?.clientId == "0x8f93b5713fb5623443653c9518964cca" && d.orders[0].state.rawValue == "open" && !d.orders[0].state.isInFlight && d.orders[0].source == "venue")279 // a stored object this version cannot read strictly does not hide the account: it is kept raw and has no strict value280 #expect(d.orders[1].canonical?.value == nil && d.orders[1].canonical?.raw["shape"] != nil && d.orders[1].origin == "mandate")281 #expect(d.actions[0].kind == "leverage" && d.fills[0].source == "venue" && d.funding[0].amount == "-0.12" && d.riskEvents[0].id == 7 && d.equity[0].unrealizedPnl == "20")282 let revoked: LiveAccountDetail = try DX.fixture("live", "revoked").decode()283 #expect(revoked.account.mode == .readOnly && revoked.cancelled?.accepted == 1 && revoked.cancelled?.failed[0].error == "already filled" && revoked.warning != nil && revoked.venueAgent != nil)284 #expect(try DX.fixture("live", "recovered").decode(LiveAccountDetail.self).recovered?.first?.outcome == "adopted")285 let halted: LiveAccountDetail = try DX.fixture("live", "halted").decode()286 #expect(halted.account.halt?.hasPrefix("halted by the owner") == true && halted.account.halted == halted.account.halt && halted.note?.contains("positions are still open") == true)287 let mr: LiveAccountDetail = try DX.fixture("live", "mandateRevoked").decode()288 #expect(mr.cancelError?.code == "venue_unavailable" && mr.windDown?.openPositions == 1 && mr.cancelled == nil)289 #expect(try DX.fixture("live", "mandateStatus").decode(LiveMandateStatus.self).mandate == nil)290 let c: LiveCollateralSummary = try DX.fixture("live", "collateralSummary").decode()291 #expect(c.withdrawable == "800" && c.deposits?.supported == true)292 let p: LiveOrderPreview = try DX.fixture("live", "preview").decode()293 #expect(p.risk.refusal?.code == "price_deviation" && p.risk.refusal?.reason.contains("the signer applies this rule") == true && p.estimate?.liquidationNote?.contains("venue reports") == true && p.estimate?.leverage == "5")294 #expect(try DX.fixture("live", "orderCancelled").decode(LiveOrderResult.self).venue?.outcome == "accepted")295 #expect(try DX.fixture("live", "leverageApproved").decode(LiveLeverageResult.self).venue?.confirmed == true)296 #expect(try DX.fixture("live", "reconcile").decode(LiveReconcile.self).account.orders.count == 2)297 // an answer without a venue state is an unreadable venue, never an empty account298 let noState = try DX.set(try DX.fixture("live", "account"), ["venueState"], nil).decode(LiveAccountDetail.self)299 #expect(noState.venueState.error != nil && noState.venueState.state == nil)300 }301 /** Shapes: services/api/src/derivatives/collateral.ts status/view; services/api/test/derivatives-collateral.test.ts. */302 @Test func collateral() throws {303 let s: CollateralStatus = try DX.fixture("collateral", "status").decode()304 #expect(s.route?.bridge == HyperliquidCollateralPins.bridge && s.route?.token == HyperliquidCollateralPins.usdc && s.route?.minimum == "6" && s.withdrawal.fee == "1" && s.withdrawal.destination == s.account)305 #expect(!s.deposit.available && s.deposit.refusal?.code == "usdc_elsewhere" && s.deposit.bridgeFrom?.first?.name == "Base" && s.withdraw.available && s.withdraw.refusal == nil)306 #expect(s.operations[0].isDone && s.operations[0].expectedReceive == "149.25" && s.operations[0].ledger?.usdc == "149.25")307 #expect(!s.operations[1].isDone && s.operations[1].overdue == true && s.operations[1].check?.first == "tx_success" && s.operations[1].state == "awaiting_credit")308 let t: CollateralStatus = try DX.fixture("collateral", "statusTestnet").decode()309 #expect(t.route == nil && t.deposit.refusal?.code == "no_route" && t.withdraw.refusal?.code == "venue_unreadable" && t.venueBalance.error != nil && t.venueBalance.equity == nil)310 }311 /** Shapes: services/api/src/derivatives/gmx-exec.ts status/opView/posView/orderView/preview; services/api/test/derivatives-gmx.test.ts. */312 @Test func gmx() throws {313 let s = try DX.gmxStatus()314 #expect(s.tradable && s.settings.gmxLive && s.contract("orderVault") == "0x31eF83a530Fde1B38EE9A18093A333D8Bbbc40D5" && s.authorization?.state == "active" && s.authorization?.expiresAt == Date(timeIntervalSince1970: 1_796_592_000))315 #expect(s.markets[1].indexDecimals == 18 && s.positions[0].liquidationPrice == "2400.12" && s.positions[0].source == "chain" && s.pendingOrders[0].cancellableAt == Date(timeIntervalSince1970: 1_794_000_303))316 #expect(s.operations[0].state == "created" && !s.operations[0].final && s.operations[1].outcome?["event"]?.stringValue == "OrderExecuted" && s.risk?.maxDailyLoss == "75")317 let locked: GmxStatus = try DX.fixture("gmx", "statusLocked").decode()318 #expect(!locked.tradable && locked.refusals.map(\.code) == ["gmx_setting_off", "mainnet_setting_off", "not_authorized"] && locked.refusals[0].kind == .lock && locked.refusals[0].reason.contains("SPW_DERIV_GMX_LIVE") && locked.refusals[2].kind == .authorization)319 let p: GmxOrderPreview = try DX.fixture("gmx", "preview").decode()320 #expect(p.risk.refusal?.code == "daily_loss_exceeded" && p.blockers == ["gmx_halted"] && p.signerWould?.contains("above the authorized") == true)321 }322 @Test func refusalsKeepTheServersCodeAndSentence() {323 func refusal(_ status: Int, _ code: String, _ message: String) -> DerivativesRefusal? { DerivativesRefusal(APIError(status: status, code: code, message: message)) }324 #expect(refusal(403, "mainnet_disabled", "live trading on Hyperliquid MAINNET is disabled on this server")?.kind == .lock)325 #expect(refusal(403, "mandate_mainnet_disabled", "x")?.kind == .lock && refusal(403, "gmx_disabled", "x")?.kind == .lock && refusal(503, "mandate_unavailable", "x")?.kind == .lock)326 #expect(refusal(423, "halted", "trading is halted: halted by the owner")?.kind == .halted && refusal(423, "kill_switch_active", "x")?.kind == .halted)327 #expect(refusal(403, "venue_restricted", "dYdX is served for market data only")?.kind == .jurisdiction)328 #expect(refusal(422, "order_notional_exceeded", "order notional 3000 exceeds the 2500.5 the signer will sign per order")?.reason.contains("2500.5") == true)329 #expect(refusal(422, "liquidation_too_close", "x")?.kind == .risk && refusal(422, "risk_daily_loss_exceeded", "x")?.kind == .risk && refusal(422, "risk_denied", "x")?.kind == .risk)330 #expect(refusal(422, "mode_read_only", "x")?.kind == .authorization && refusal(403, "passkey_required", "x")?.kind == .authorization)331 #expect(refusal(422, "signer_price", "x")?.kind == .signer && refusal(503, "venue_unavailable", "x")?.kind == .venue && refusal(410, "proposal_expired", "x")?.kind == .expired && refusal(409, "bad_state", "x")?.kind == .other)332 #expect(DerivativesRefusal(APIError.offline()) == nil && DerivativesRefusal(APIError(status: 401, code: "unauthenticated", message: "x")) == nil)333 }334 @Test func streamEventsAreDecodedByName() throws {335 if case .ticker(let t) = try DerivStreamEvent.parse(event: "ticker", data: Data(DX.text(try DX.fixture("market-paper", "tickers")["tickers"]![0]!).utf8)) { #expect(t.mark == "70000") } else { Issue.record("ticker") }336 if case .trades(let i, let tr) = try DerivStreamEvent.parse(event: "trades", data: Data(#"{"instrument":"hyperliquid:BTC","trades":[]}"#.utf8)) { #expect(i == "hyperliquid:BTC" && tr.isEmpty) } else { Issue.record("trades") }337 if case .order(let o) = try DerivStreamEvent.parse(event: "order", data: Data(DX.text(try DX.fixture("live", "account")["orders"]![0]!).utf8)) { #expect(o.clientId == DX.key) } else { Issue.record("order") }338 if case .unknown(let e, _) = try DerivStreamEvent.parse(event: "later", data: Data("{}".utf8)) { #expect(e == "later") } else { Issue.record("unknown") }339 }340}341342// MARK: request contract of every route343344@Suite struct DerivativesContractTests {345 private func expect(_ t: MockTransport, _ method: String, _ path: String, query: [String: String] = [:], key: String? = nil, _ note: Comment? = nil) {346 guard let r = t.last else { Issue.record("no request"); return }347 #expect(r.method == method && r.path == "/api/v1/derivatives" + path, note)348 #expect(r.query == query, note)349 #expect(r.headers["Idempotency-Key"] == key, note)350 #expect((r.headers["X-SPW-CSRF"] == "1") == (method != "GET"), note)351 }352353 /** Every route registered by `derivativesRoutes` (routes.ts): 19 JSON routes + the event stream. */354 @Test func readOnlyAndPaperRoutes() async throws {355 let (client, t, _) = MockTransport.client()356 let api = DerivativesAPI(client)357 func q(_ key: String) throws { t.enqueue(json: DX.text(try DX.fixture("market-paper", key))) }358359 try q("venues"); _ = try await api.venues(); expect(t, "GET", "/venues")360 try q("instruments"); _ = try await api.instruments(venue: "hyperliquid", locale: "fr"); expect(t, "GET", "/instruments", query: ["venue": "hyperliquid", "locale": "fr"])361 try q("instruments"); _ = try await api.instruments(); expect(t, "GET", "/instruments")362 try q("tickers"); _ = try await api.tickers(venue: "hyperliquid"); expect(t, "GET", "/tickers", query: ["venue": "hyperliquid"])363 try q("market"); _ = try await api.market(instrument: "hyperliquid:BTC"); expect(t, "GET", "/market", query: ["instrument": "hyperliquid:BTC"])364 try q("marketGmx"); _ = try await api.market(instrument: "gmx:ETH/USD [WETH-USDC]"); expect(t, "GET", "/market", query: ["instrument": "gmx:ETH/USD [WETH-USDC]"])365 try q("candles"); _ = try await api.candles(instrument: "hyperliquid:BTC", interval: .h1, limit: 200); expect(t, "GET", "/candles", query: ["instrument": "hyperliquid:BTC", "interval": "1h", "limit": "200"])366 try q("funding"); _ = try await api.fundingHistory(instrument: "hyperliquid:BTC", hours: 24); expect(t, "GET", "/funding", query: ["instrument": "hyperliquid:BTC", "hours": "24"])367 try q("compare"); _ = try await api.compare(base: "BTC", locale: "en"); expect(t, "GET", "/compare", query: ["base": "BTC", "locale": "en"])368 try q("watch"); _ = try await api.watch(account: DX.own, venue: "hyperliquid"); expect(t, "GET", "/watch", query: ["account": DX.own, "venue": "hyperliquid"])369 try q("routeAssets"); _ = try await api.routeAssets(); expect(t, "GET", "/route/assets")370 try q("route")371 _ = try await api.route(DerivRouteRequest(base: "BTC", side: "long", sizeBase: nil, notionalUsd: "1000", leverage: "3", type: "market", price: nil, reduceOnly: false, horizonHours: "24", accountIds: [DX.paper.rawValue]), locale: "fr")372 expect(t, "POST", "/route", query: ["locale": "fr"])373 #expect(t.last?.body == ["base": "BTC", "side": "long", "notionalUsd": "1000", "leverage": "3", "type": "market", "price": nil, "reduceOnly": false, "horizonHours": "24", "accountIds": [.string(DX.paper.rawValue)]])374 #expect(api.marketStream(instrument: "hyperliquid:BTC").path == "/derivatives/stream" && api.marketStream(instrument: "hyperliquid:BTC").query == ["instrument": "hyperliquid:BTC"])375376 let a = "/accounts/\(DX.paper.rawValue)"377 try q("paperAccounts"); #expect(try await api.paperAccounts().count == 1); expect(t, "GET", "/accounts")378 try q("paperAccount"); _ = try await api.createPaperAccount(PaperAccountCreation(venue: "hyperliquid", label: "Essai", collateral: "1000")); expect(t, "POST", "/accounts")379 #expect(t.last?.body == ["venue": "hyperliquid", "label": "Essai", "collateral": "1000"])380 try q("paperAccount"); let detail = try await api.paperAccount(DX.paper); expect(t, "GET", a)381 try q("paperAccount"); _ = try await api.setPaperPolicy(DX.paper, policy: detail.account.policy); expect(t, "POST", "\(a)/policy")382 // the whole policy is sent, `halt` as an explicit null (the server's schema requires the key)383 #expect(t.last?.body?.objectValue?.count == 16 && t.last?.body?["halt"] == .null && t.last?.body?["maxOrdersPerDay"] == 200 && t.last?.body?["maxLeverage"] == "3")384 let order = PaperOrderRequest(instrument: "hyperliquid:BTC", side: .buy, type: .market, size: "0.01", price: nil, triggerPrice: nil, reduceOnly: false, tif: .ioc, leverage: "5", slippageBps: 50)385 try q("paperPreview"); _ = try await api.previewPaperOrder(DX.paper, order: order); expect(t, "POST", "\(a)/orders/preview")386 try q("paperPlaced"); _ = try await api.placePaperOrder(DX.paper, order: order, idempotencyKey: "paper-key-0001"); expect(t, "POST", "\(a)/orders", key: "paper-key-0001")387 #expect(t.last?.body == ["instrument": "hyperliquid:BTC", "side": "buy", "type": "market", "size": "0.01", "price": nil, "triggerPrice": nil, "reduceOnly": false, "tif": "ioc", "leverage": "5", "slippageBps": 50])388 try q("paperCancelled"); #expect(try await api.cancelPaperOrder(DX.paper, clientId: "paper-key-0001").status == "cancelled"); expect(t, "POST", "\(a)/orders/paper-key-0001/cancel")389 try q("paperClosed"); _ = try await api.closePaperPosition(DX.paper, instrument: "hyperliquid:BTC", fraction: "0.5", slippageBps: 50, idempotencyKey: "close-key-0001"); expect(t, "POST", "\(a)/close", key: "close-key-0001")390 #expect(t.last?.body == ["instrument": "hyperliquid:BTC", "fraction": "0.5", "slippageBps": 50])391 try q("paperAccount"); _ = try await api.resetPaperAccount(DX.paper); expect(t, "POST", "\(a)/reset")392 #expect(t.requests.count == 21)393394 // a risk refusal of the paper engine is HTTP 422 with the risk code: typed, shown verbatim395 t.enqueue(status: 422, json: #"{"error":"insufficient_collateral","message":"free collateral 12 is below the initial margin 140"}"#)396 do { _ = try await api.placePaperOrder(DX.paper, order: order, idempotencyKey: "paper-key-0002"); Issue.record("expected a refusal") }397 catch { #expect(DerivativesRefusal(error) == DerivativesRefusal(code: "insufficient_collateral", reason: "free collateral 12 is below the initial margin 140", status: 422)) }398 }399400 /** Every route of `liveRoutes` (live-routes.ts) that needs no passkey; the approval routes are in DerivativesApprovalTests. */401 @Test func liveRoutesWithoutPasskey() async throws {402 let (client, t, _) = MockTransport.client()403 let api = DerivativesLiveAPI(client), a = "/live/accounts/\(DX.live.rawValue)"404 func q(_ key: String) throws { t.enqueue(json: DX.text(try DX.fixture("live", key))) }405406 try q("config"); _ = try await api.config(locale: "fr"); expect(t, "GET", "/live/config", query: ["locale": "fr"])407 try q("jurisdiction"); _ = try await api.jurisdiction(); expect(t, "GET", "/live/jurisdiction", query: ["venue": "hyperliquid"])408 try q("venueKey"); _ = try await api.venueKey(venue: "hyperliquid", network: "mainnet"); expect(t, "POST", "/live/venue-key"); #expect(t.last?.body == ["venue": "hyperliquid", "network": "mainnet"])409 try q("accounts"); #expect(try await api.accounts().count == 2); expect(t, "GET", "/live/accounts")410 try q("accountReadOnly"); _ = try await api.createAccount(network: "testnet", label: "Essai"); expect(t, "POST", "/live/accounts"); #expect(t.last?.body == ["venue": "hyperliquid", "network": "testnet", "label": "Essai"])411 try q("account"); _ = try await api.account(DX.live); expect(t, "GET", a)412 try q("collateralSummary"); _ = try await api.collateralSummary(DX.live, locale: "fr"); expect(t, "GET", "\(a)/collateral", query: ["locale": "fr"])413 try q("revoked"); _ = try await api.revokeAuthorization(DX.live, cancelOpenOrders: true, locale: "en"); expect(t, "POST", "\(a)/authorization/revoke"); #expect(t.last?.body == ["cancelOpenOrders": true, "locale": "en"])414 try q("recovered"); _ = try await api.recoverAuthorization(DX.live); expect(t, "POST", "\(a)/authorization/recover")415 let policy = try DX.account().policy416 try q("account"); _ = try await api.setPolicy(DX.live, policy: policy); expect(t, "POST", "\(a)/policy"); #expect(t.last?.body?["halt"] == .null && t.last?.body?["mode"] == "MANUAL_LIVE")417 try q("mandateStatus"); _ = try await api.mandateStatus(DX.live); expect(t, "GET", "\(a)/mandate")418 try q("mandateRevoked"); _ = try await api.revokeMandate(DX.live, cancelOpenOrders: false, locale: "fr"); expect(t, "POST", "\(a)/mandate/revoke"); #expect(t.last?.body == ["cancelOpenOrders": false, "locale": "fr"])419 let order = LiveOrderRequest(instrument: "hyperliquid:BTC", side: .buy, type: .limit, size: "0.01", price: "80000", triggerPrice: nil, reduceOnly: false, tif: .gtc, slippageBps: nil)420 try q("preview"); _ = try await api.previewOrder(DX.live, order: order); expect(t, "POST", "\(a)/orders/preview")421 // no leverage and no client id in a live order body (the server's schema refuses both)422 #expect(t.last?.body == ["instrument": "hyperliquid:BTC", "side": "buy", "type": "limit", "size": "0.01", "price": "80000", "triggerPrice": nil, "reduceOnly": false, "tif": "gtc"])423 try q("orderCancelled"); #expect(try await api.cancelOrder(DX.live, clientId: DX.key).sent == true); expect(t, "POST", "\(a)/orders/\(DX.key)/cancel")424 try q("halted"); _ = try await api.halt(DX.live, reason: "pause"); expect(t, "POST", "\(a)/halt"); #expect(t.last?.body == ["reason": "pause"])425 try q("cancelAll"); #expect(try await api.cancelAll(DX.live).requested == 2); expect(t, "POST", "\(a)/cancel-all")426 try q("reconcile"); _ = try await api.reconcile(DX.live); expect(t, "POST", "\(a)/reconcile")427 #expect(api.accountStream(DX.live) == "/derivatives\(a)/stream")428 // nothing to approve: no passkey is asked for nothing429 let account = try DX.account()430 for (path, call) in [("policy/prepare", { try await api.preparePolicyChange(for: account, policy: policy, now: DX.now) }), ("resume/prepare", { try await api.prepareResume(for: account, now: DX.now) }),431 ("rebase/prepare", { try await api.prepareRebase(for: account, now: DX.now) })] as [(String, () async throws -> LiveRiskPreparation)] {432 try q("riskNotNeeded")433 if case .approval = try await call() { Issue.record("an approval was built from an answer that asks for none") }434 expect(t, "POST", "\(a)/\(path)")435 }436 // a server lock is an error with its code and the server's sentence437 t.enqueue(status: 403, json: #"{"error":"mainnet_disabled","message":"live trading on Hyperliquid MAINNET is disabled on this server (SPW_DERIV_LIVE_MAINNET is not \"on\"): nothing was built, signed or sent. The testnet account works."}"#)438 do { _ = try await api.createAccount(network: "mainnet", label: "x"); Issue.record("expected the lock") }439 catch { #expect(DerivativesRefusal(error)?.kind == .lock && DerivativesRefusal(error)?.reason.contains("SPW_DERIV_LIVE_MAINNET") == true) }440 }441442 /** Every route of `collateralRoutes` and `gmxRoutes` that needs no passkey. */443 @Test func collateralAndGmxRoutesWithoutPasskey() async throws {444 let (client, t, _) = MockTransport.client()445 let c = DerivativesCollateralAPI(client), g = DerivativesGMXAPI(client), a = "/live/accounts/\(DX.live.rawValue)/collateral", op = "7a1c1f0e-8f5f-4b1e-9c56-000000000520"446 t.enqueue(json: DX.text(try DX.fixture("collateral", "status"))); _ = try await c.status(DX.live); expect(t, "GET", "\(a)/status")447 t.enqueue(json: DX.text(try DX.fixture("collateral", "operation"))); #expect(try await c.operation(DX.live, operationId: op).isDone); expect(t, "GET", "\(a)/operations/\(op)")448 t.enqueue(json: DX.text(try DX.fixture("collateral", "operationDeposit"))); #expect(try await c.cancel(DX.live, operationId: op).kind == "deposit"); expect(t, "POST", "\(a)/operations/\(op)/cancel")449450 func q(_ key: String) throws { t.enqueue(json: DX.text(try DX.fixture("gmx", key))) }451 let gop = "7a1c1f0e-8f5f-4b1e-9c56-000000000a01"452 try q("status"); _ = try await g.status(locale: "fr"); expect(t, "GET", "/gmx/status", query: ["locale": "fr"])453 try q("jurisdiction"); #expect(try await g.jurisdiction().venue == "gmx"); expect(t, "GET", "/gmx/jurisdiction")454 try q("statusLocked"); _ = try await g.revokeAuthorization(locale: "en"); expect(t, "POST", "/gmx/authorization/revoke", query: ["locale": "en"])455 let order = GmxOrderRequest.increase(market: "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336", side: .long, collateral: "20", leverage: "3", slippageBps: 50)456 try q("preview"); _ = try await g.previewOrder(order); expect(t, "POST", "/gmx/orders/preview")457 #expect(t.last?.body == ["market": "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336", "side": "long", "action": "increase", "collateral": "20", "leverage": "3", "slippageBps": 50])458 try q("operation"); #expect(try await g.withdraw(gop).id == gop); expect(t, "POST", "/gmx/operations/\(gop)/withdraw")459 try q("operation"); _ = try await g.operation(gop); expect(t, "GET", "/gmx/operations/\(gop)")460 try q("status"); _ = try await g.halt(reason: "pause", locale: "fr"); expect(t, "POST", "/gmx/halt", query: ["locale": "fr"]); #expect(t.last?.body == ["reason": "pause"])461 try q("status"); _ = try await g.setLimits(maxDailyLoss: "50", maxTotalLoss: "200"); expect(t, "POST", "/gmx/limits"); #expect(t.last?.body == ["maxDailyLoss": "50", "maxTotalLoss": "200"])462 let status = try DX.gmxStatus()463 t.enqueue(json: #"{"needed":false,"kind":"gmx-limits","loosened":[],"intent":null,"hash":null,"options":null,"expiresAt":null}"#)464 if case .approval = try await g.prepareLimits(maxDailyLoss: "50", maxTotalLoss: "200", status: status, now: DX.now) { Issue.record("no approval is needed") }465 expect(t, "POST", "/gmx/limits/prepare")466 t.enqueue(json: #"{"needed":false,"kind":"gmx-resume","loosened":[],"intent":null,"hash":null,"options":null,"expiresAt":null}"#)467 if case .approval = try await g.prepareResume(status: status, now: DX.now) { Issue.record("no approval is needed") }468 expect(t, "POST", "/gmx/resume/prepare")469 }470}471472// MARK: approval flows: what was asked is what is approved473474@Suite struct DerivativesApprovalTests {475 private func setup() -> (APIClient, MockTransport, StubPasskey) { let (c, t, _) = MockTransport.client(); return (c, t, StubPasskey()) }476 private func isInconsistent(_ e: Error) -> Bool { if case ApprovalError.inconsistent = e { return true } else { return false } }477 private func refuses<T: Sendable>(_ note: Comment, _ body: () async throws -> T) async {478 do { _ = try await body(); Issue.record("expected a refusal: \(note)") }479 catch { #expect(isInconsistent(error) || error is ApprovalError, note) }480 }481482 // ---- venue authorization483484 private func authorization() throws -> (JSONValue, VenuePolicy) {485 let o = DX.set(try CanonicalVector.load("SPW-VENUE-AUTH-v1.json")[0].object, ["ackSha256"], .string(DerivHash.sha256Hex(DX.ackText)))486 // the request writes the same limits another way ("2500.5" for "2500.50", another order of instruments)487 return (o, VenuePolicy(allowedInstruments: ["hyperliquid:SOL", "hyperliquid:BTC", "hyperliquid:ETH"], maxLeverage: 5, maxOrderNotional: "2500.5", maxPositionNotional: "10000.0", maxGrossExposure: "25000", maxOrdersPerDay: 200, maxPriceDeviationBps: 300))488 }489 private func authorizationAnswer(_ o: JSONValue, ack: JSONValue = DX.ack("hyperliquid"), rp: String = DX.rp) throws -> String {490 let a = try VenueAuthorization(served: o)491 return DX.text(["authorization": o, "hash": .string(try a.approvalDigest().hex), "acknowledgement": ack, "locale": "fr",492 "agent": ["address": .string(a.agentAddress), "name": "spw-live", "wireName": "spw-live valid_until 1796592000000", "validUntil": 1796592000000, "can": ["place orders"], "cannot": ["withdraw"], "note": "n"],493 "whatIsSigned": ["byMainKey": "one approveAgent action", "byPasskey": "the SHA-256 of this authorization"], "venueState": try DX.fixture("live", "account")["venueState"]!, "options": try DX.options(a, rp: rp), "ts": 1794000000000])494 }495496 @Test func enablingLiveTradingApprovesExactlyTheLimitsAsked() async throws {497 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client), account = try DX.account("accountReadOnly")498 let (o, policy) = try authorization()499 t.enqueue(json: try authorizationAnswer(o))500 let p = try await api.prepareAuthorization(for: account, policy: policy, days: 30, locale: "fr", now: DX.now)501 #expect(t.last?.path == "/api/v1/derivatives/live/accounts/\(DX.live.rawValue)/authorization/prepare" && t.last?.body?["days"] == 30 && t.last?.body?["locale"] == "fr" && t.last?.body?["policy"]?["maxLeverage"] == 5)502 #expect(t.last?.body?["agentName"] == nil)503 #expect(p.authorization.policy.maxLeverage == 5 && p.acknowledgement.text == DX.ackText && p.agent?.cannot == ["withdraw"])504 // the owner's acknowledgement is his own statement: without it nothing is asked of the passkey505 await #expect(throws: ApprovalError.self) { try await api.approveAuthorization(p, acknowledged: false, with: passkey, now: DX.now) }506 #expect(passkey.challenges.isEmpty)507 t.enqueue(json: DX.text(try DX.fixture("live", "account")))508 let d = try await api.approveAuthorization(p, acknowledged: true, with: passkey, now: DX.now)509 #expect(d.account.mode == .manualLive && passkey.challenges == [DX.challenge(p.authorization)])510 #expect(t.last?.path.hasSuffix("/authorization/approve") == true && t.last?.body?["acknowledged"] == true && t.last?.body?["assertion"]?["type"] == "public-key")511 }512 @Test func anAuthorizationThatDiffersFromTheRequestIsRefused() async throws {513 let (client, t, _) = setup(), api = DerivativesLiveAPI(client), account = try DX.account("accountReadOnly")514 let (o, policy) = try authorization()515 func attempt(_ answer: String, policy p: VenuePolicy = policy, days: Int = 30, account a: LiveAccount = account, now: Date = DX.now) async throws -> LiveAuthorizationPreparation {516 t.enqueue(json: answer); return try await api.prepareAuthorization(for: a, policy: p, days: days, locale: "fr", now: now)517 }518 await refuses("a higher leverage than asked") { try await attempt(try authorizationAnswer(DX.set(o, ["policy", "maxLeverage"], 20))) }519 await refuses("a wider order limit") { try await attempt(try authorizationAnswer(DX.set(o, ["policy", "maxOrderNotional"], "25000"))) }520 await refuses("one more instrument") { try await attempt(try authorizationAnswer(DX.set(o, ["policy", "allowedInstruments"], ["hyperliquid:ETH", "hyperliquid:BTC", "hyperliquid:SOL", "hyperliquid:DOGE"]))) }521 await refuses("a longer duration") { try await attempt(try authorizationAnswer(o), days: 7) }522 await refuses("another network") { try await attempt(try authorizationAnswer(DX.set(o, ["network"], "testnet"))) }523 await refuses("another trading key") { try await attempt(try authorizationAnswer(DX.set(o, ["agentAddress"], "0x1111111111111111111111111111111111111111"))) }524 await refuses("another account") { try await attempt(try authorizationAnswer(DX.set(o, ["account"], "0x2222222222222222222222222222222222222222"))) }525 await refuses("the mandate mode") { try await attempt(try authorizationAnswer(DX.set(o, ["mode"], "MANDATE_LIVE"))) }526 await refuses("another text than the one committed to") { try await attempt(try authorizationAnswer(o, ack: DX.set(DX.ack("hyperliquid"), ["text"], "Cleared for you."))) }527 await refuses("the acknowledgement of another venue") { try await attempt(try authorizationAnswer(o, ack: DX.ack("gmx"))) }528 await refuses("an expired authorization") { try await attempt(try authorizationAnswer(o), now: Date(timeIntervalSince1970: 1_796_592_001)) }529 // the challenge is not the hash of the authorization displayed530 let other = try VenueAuthorization(served: DX.set(o, ["policy", "maxLeverage"], 20))531 let swapped = DX.set(try JSONDecoder().decode(JSONValue.self, from: Data(try authorizationAnswer(o).utf8)), ["options"], try DX.options(other))532 await #expect(throws: ApprovalError.challengeMismatch) { try await attempt(DX.text(DX.set(swapped, ["hash"], nil))) }533 await #expect(throws: ApprovalError.wrongRelyingParty("evil.example")) { try await attempt(try authorizationAnswer(o, rp: "evil.example")) }534 // an unknown field in the object to approve fails the answer as a whole535 await #expect(throws: APIError.self) { try await attempt(try authorizationAnswer(o).replacingOccurrences(of: "\"keyId\"", with: "\"builderFee\":\"1\",\"keyId\"")) }536 }537538 // ---- orders539540 private func canonicalOrder(_ changes: [(String, JSONValue?)] = []) throws -> JSONValue {541 var o = try #require(try DX.fixture("live", "account")["orders"]?[0]?["canonical"])542 for (k, v) in changes { o = DX.set(o, [k], v) }543 return o544 }545 private func proposalAnswer(_ canonical: JSONValue, extra: [String: JSONValue] = [:]) throws -> String {546 let c = try VenueOrder(served: canonical)547 var a: [String: JSONValue] = ["order": DX.set(DX.set(try DX.fixture("live", "account")["orders"]![0]!, ["state"], "risk_checked"), ["canonical"], canonical), "canonical": canonical,548 "hash": .string(try c.approvalDigest().hex), "expiresAt": .int(Int64(c.expiresAt)), "estimate": try DX.fixture("live", "preview")["estimate"]!, "idempotent": false, "options": try DX.options(c)]549 for (k, v) in extra { a[k] = v }550 return DX.text(.object(a))551 }552 private let limit = LiveOrderRequest(instrument: "hyperliquid:BTC", side: .buy, type: .limit, size: "0.010", price: "68000.0", triggerPrice: nil, reduceOnly: false, tif: .gtc, slippageBps: nil)553554 @Test func aManualOrderIsApprovedOnlyAsTheOrderAsked() async throws {555 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()556 t.enqueue(json: try proposalAnswer(try canonicalOrder()))557 let p = try await api.proposeOrder(for: account, order: limit, idempotencyKey: DX.key, now: DX.now)558 #expect(t.last?.path == "/api/v1/derivatives/live/accounts/\(DX.live.rawValue)/orders" && t.last?.headers["Idempotency-Key"] == DX.key && t.last?.body?["size"] == "0.010")559 let approvable = try #require(p.approvable)560 #expect(approvable.order.price == "68000" && approvable.clientId == DX.key && p.estimate?.liquidationNote != nil)561 t.enqueue(json: DX.text(try DX.fixture("live", "orderApproved")))562 let r = try await api.approveOrder(approvable, with: passkey, now: DX.now)563 #expect(r.order.state.rawValue == "open" && r.idempotent == false && passkey.challenges == [DX.challenge(approvable.order)])564 #expect(t.last?.path == "/api/v1/derivatives/live/accounts/\(DX.live.rawValue)/orders/\(DX.key)/approve" && t.last?.body?.objectValue?.keys.sorted() == ["assertion"])565 // past the venue expiry (minus the server's two seconds) nothing is asked of the passkey566 await #expect(throws: ApprovalError.expired) { try await api.approveOrder(approvable, with: passkey, now: Date(timeIntervalSince1970: 1_794_000_089)) }567 #expect(passkey.challenges.count == 1)568 }569 @Test func aMarketOrderComesBackAsALimitAtItsWorstPrice() async throws {570 let (client, t, _) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()571 let market = LiveOrderRequest(instrument: "hyperliquid:BTC", side: .buy, type: .market, size: "0.01", price: nil, triggerPrice: nil, reduceOnly: false, tif: .ioc, slippageBps: 50)572 t.enqueue(json: try proposalAnswer(try canonicalOrder([("tif", "ioc"), ("price", "70351")])))573 #expect(try await api.proposeOrder(for: account, order: market, idempotencyKey: DX.key, now: DX.now).approvable?.order.price == "70351")574 #expect(t.last?.body?["slippageBps"] == 50 && t.last?.body?["price"] == .null)575 // a refused or expired proposal carries nothing to approve576 t.enqueue(json: DX.text(DX.set(try JSONDecoder().decode(JSONValue.self, from: Data(try proposalAnswer(try canonicalOrder()).utf8)), ["options"], .null)))577 #expect(try await api.proposeOrder(for: account, order: limit, idempotencyKey: DX.key, now: DX.now).approvable == nil)578 }579 @Test func anOrderThatDiffersFromTheRequestIsRefused() async throws {580 let (client, t, _) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()581 func attempt(_ changes: [(String, JSONValue?)], request: LiveOrderRequest? = nil, key: String = DX.key, account a: LiveAccount = account, now: Date = DX.now) async throws -> LiveOrderProposal {582 t.enqueue(json: try proposalAnswer(try canonicalOrder(changes))); return try await api.proposeOrder(for: a, order: request ?? limit, idempotencyKey: key, now: now)583 }584 await refuses("a larger size") { try await attempt([("size", "0.1")]) }585 await refuses("the other side") { try await attempt([("side", "sell")]) }586 await refuses("another instrument") { try await attempt([("instrument", "hyperliquid:ETH")]) }587 await refuses("another price") { try await attempt([("price", "69000")]) }588 await refuses("reduce-only flipped") { try await attempt([("reduceOnly", true)]) }589 await refuses("a trigger that was not asked") { try await attempt([("triggerPrice", "67000"), ("type", "stop_limit")]) }590 await refuses("another time in force") { try await attempt([("tif", "ioc")]) }591 await refuses("the testnet order of a mainnet account") { try await attempt([("network", "testnet")]) }592 await refuses("another authorization") { try await attempt([("authorizationId", "7a1c1f0e-8f5f-4b1e-9c56-000000000501")]) }593 await refuses("another account") { try await attempt([("account", "0x2222222222222222222222222222222222222222")]) }594 await refuses("the client order id of another key") { try await attempt([("clientId", "0x9079d48c5829dd60a71d712fcd0a6e4a")]) }595 await refuses("a window longer than two minutes") { try await attempt([("expiresAt", 1794000200001)]) }596 await refuses("an expired window") { try await attempt([], now: Date(timeIntervalSince1970: 1_794_000_091)) }597 await refuses("a limit order without a price") { try await attempt([], request: LiveOrderRequest(instrument: "hyperliquid:BTC", side: .buy, type: .limit, size: "0.01", price: nil, triggerPrice: nil, reduceOnly: false, tif: .gtc, slippageBps: nil)) }598 // the stored order of a re-used key, answered "whatever the body says", is not this request599 await refuses("the answer of another key") { try await attempt([], key: "ui-another-key-0001") }600 await refuses("a read-only account") { try await attempt([], account: try DX.account("accountReadOnly")) }601 }602 @Test func aCloseReducesThePositionShownAndNeverExceedsIt() async throws {603 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()604 let position = try #require(try DX.fixture("live", "account").decode(LiveAccountDetail.self).venueState.positions.first) // long 0.02 BTC605 func attempt(_ changes: [(String, JSONValue?)], fraction: String = "1", worst: String = "69650") async throws -> LiveOrderProposal {606 let c = try canonicalOrder([("side", "sell"), ("reduceOnly", true), ("tif", "ioc"), ("size", "0.02"), ("price", "69650")] + changes)607 t.enqueue(json: try proposalAnswer(c, extra: ["worstPrice": .string(worst), "slippageBoundBps": 50, "position": try DX.fixture("live", "account")["venueState"]!["positions"]![0]!]))608 return try await api.proposeClose(for: account, position: position, fraction: fraction, slippageBps: 50, idempotencyKey: DX.key, now: DX.now)609 }610 let p = try await attempt([])611 #expect(t.last?.path.hasSuffix("/close") == true && t.last?.body == ["instrument": "hyperliquid:BTC", "fraction": "1", "slippageBps": 50] && t.last?.headers["Idempotency-Key"] == DX.key)612 #expect(p.worstPrice == "69650" && p.slippageBoundBps == 50 && p.position?.size == "0.02")613 t.enqueue(json: DX.text(try DX.fixture("live", "orderApproved")))614 _ = try await api.approveOrder(try #require(p.approvable), with: passkey, now: DX.now)615 #expect(passkey.challenges.count == 1)616 #expect(try await attempt([("size", "0.01")], fraction: "0.5").approvable != nil)617 await refuses("a buy on a long") { try await attempt([("side", "buy")]) }618 await refuses("not reduce-only") { try await attempt([("reduceOnly", false)]) }619 await refuses("more than the position") { try await attempt([("size", "0.03")]) }620 await refuses("half when the whole was asked") { try await attempt([("size", "0.01")]) }621 await refuses("a resting order") { try await attempt([("tif", "gtc")]) }622 await refuses("another price than the worst price stated") { try await attempt([], worst: "60000") }623 }624625 // ---- leverage626627 @Test func aLeverageChangeIsApprovedOnlyAsAsked() async throws {628 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()629 let base = try DX.vector("SPW-VENUE-LEVERAGE-v1", "leverage-cross-5").object // hyperliquid:BTC, 5×, cross, mainnet, nonce …010630 func answer(_ o: JSONValue) throws -> String {631 let c = try VenueLeverage(served: o)632 let action = DX.set(DX.set(try DX.fixture("live", "account")["actions"]![0]!, ["state"], "risk_checked"), ["hash"], .string(try c.approvalDigest().hex))633 return DX.text(["action": action, "canonical": o, "hash": .string(try c.approvalDigest().hex), "current": ["leverage": "20", "marginMode": "cross"], "expiresAt": .int(Int64(c.expiresAt)), "options": try DX.options(c)])634 }635 t.enqueue(json: try answer(base))636 let l = try await api.proposeLeverage(for: account, instrument: "hyperliquid:BTC", leverage: 5, marginMode: .cross, now: DX.now)637 #expect(t.last?.path.hasSuffix("/leverage") == true && t.last?.body == ["instrument": "hyperliquid:BTC", "leverage": 5, "marginMode": "cross"])638 #expect(l.change.leverage == 5 && l.current?.leverage == "20")639 t.enqueue(json: DX.text(try DX.fixture("live", "leverageApproved")))640 #expect(try await api.approveLeverage(l, with: passkey, now: DX.now).venue?.confirmed == true)641 #expect(t.last?.path == "/api/v1/derivatives/live/accounts/\(DX.live.rawValue)/leverage/7a1c1f0e-8f5f-4b1e-9c56-000000000900/approve" && passkey.challenges == [DX.challenge(l.change)])642 for (note, change, lev, mode) in [("a higher leverage", ("leverage", JSONValue.int(20)), 5, DerivMarginMode.cross), ("another margin mode", ("marginMode", "isolated"), 5, .cross), ("another instrument", ("instrument", "hyperliquid:ETH"), 5, .cross),643 ("the leverage asked is not the one served", ("leverage", 5), 3, .cross), ("another network", ("network", "testnet"), 5, .cross)] as [(Comment, (String, JSONValue), Int, DerivMarginMode)] {644 t.enqueue(json: try answer(DX.set(base, [change.0], change.1)))645 await refuses(note) { try await api.proposeLeverage(for: account, instrument: "hyperliquid:BTC", leverage: lev, marginMode: mode, now: DX.now) }646 }647 }648649 // ---- API-side risk changes650651 @Test func liftingAHaltOrLooseningThePolicyApprovesTheIntentServed() async throws {652 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client)653 func answer(_ o: JSONValue) throws -> String {654 let i = try LiveRiskIntent(served: o)655 return DX.text(["needed": true, "kind": .string(i.kind.rawValue), "loosened": o["loosened"]!, "intent": o, "hash": .string(try i.approvalDigest().hex), "options": try DX.options(i), "expiresAt": .int(Int64(i.expiresAt))])656 }657 // resume: the halt the passkey lifts is the halt displayed658 let resume = try DX.vector("SPW-RISK-INTENT-v1", "resume-after-halt").object659 let haltText = try #require(resume["subject"]?.stringValue)660 let halted = try DX.set(DX.set(try DX.fixture("live", "account"), ["halt"], .string(haltText)), ["halted"], .string(haltText)).decode(LiveAccountDetail.self).account661 t.enqueue(json: try answer(resume))662 guard case .approval(let r) = try await api.prepareResume(for: halted, now: DX.now) else { Issue.record("an approval was expected"); return }663 t.enqueue(json: DX.text(try DX.fixture("live", "account")))664 _ = try await api.approveRiskChange(r, with: passkey, now: DX.now)665 #expect(t.last?.path.hasSuffix("/resume") == true && t.last?.body?["assertion"] != nil && passkey.challenges == [DX.challenge(r.intent)])666 t.enqueue(json: try answer(DX.set(resume, ["subject"], "another halt")))667 await refuses("another halt than the one displayed") { try await api.prepareResume(for: halted, now: DX.now) }668 t.enqueue(json: try answer(DX.set(resume, ["accountId"], "7a1c1f0e-8f5f-4b1e-9c56-000000000999")))669 await refuses("another account") { try await api.prepareResume(for: halted, now: DX.now) }670 t.enqueue(json: try answer(try DX.vector("SPW-RISK-INTENT-v1", "rebase-divergence").object))671 await refuses("a re-base served for a resume") { try await api.prepareResume(for: halted, now: DX.now) }672 t.enqueue(json: try answer(resume))673 await refuses("expired") { try await api.prepareResume(for: halted, now: Date(timeIntervalSince1970: 1_794_000_301)) }674675 // policy: the whole policy that will be in force is the one asked, field for field676 let pv = try DX.vector("SPW-RISK-INTENT-v1", "policy-loosened").object677 let policy = try DerivRiskPolicy(strict: pv["policy"], path: "policy")678 let account = try DX.account()679 t.enqueue(json: try answer(pv))680 guard case .approval(let pa) = try await api.preparePolicyChange(for: account, policy: policy, now: DX.now) else { Issue.record("an approval was expected"); return }681 #expect(t.last?.path.hasSuffix("/policy/prepare") == true && t.last?.body?.objectValue?.count == 16 && pa.intent.loosened.isEmpty == false)682 t.enqueue(json: DX.text(try DX.fixture("live", "account")))683 _ = try await api.approveRiskChange(pa, with: passkey, now: DX.now)684 #expect(t.last?.path.hasSuffix("/policy/approve") == true)685 var wider = policy; wider.maxLeverage = "3"686 t.enqueue(json: try answer(pv))687 await refuses("a policy with another leverage than the one asked") { try await api.preparePolicyChange(for: account, policy: wider, now: DX.now) }688689 // rebase690 let rb = try DX.vector("SPW-RISK-INTENT-v1", "rebase-divergence").object691 let diverged = try DX.set(try DX.fixture("live", "account"), ["divergence"], rb["subject"]!).decode(LiveAccountDetail.self).account692 t.enqueue(json: try answer(rb))693 guard case .approval(let ra) = try await api.prepareRebase(for: diverged, now: DX.now) else { Issue.record("an approval was expected"); return }694 t.enqueue(json: DX.text(try DX.fixture("live", "account")))695 _ = try await api.approveRiskChange(ra, with: passkey, now: DX.now)696 #expect(t.last?.path.hasSuffix("/rebase") == true && passkey.challenges.count == 3)697 }698699 // ---- derivative mandate700701 @Test func aMandateIsApprovedOnlyWithTheLimitsAsked() async throws {702 let (client, t, passkey) = setup(), api = DerivativesLiveAPI(client), account = try DX.account()703 let o = DX.set(try CanonicalVector.load("SPW-VENUE-MANDATE-v1.json")[0].object, ["ackSha256"], .string(DerivHash.sha256Hex(DX.ackText)))704 let m = try VenueMandate(served: o)705 let request = LiveMandateRequest(instruments: m.instruments.reversed(), maxOrderNotional: m.maxOrderNotional, maxGrossExposure: "12000", maxOrdersPerDay: m.maxOrdersPerDay, maxOrdersPerHour: m.maxOrdersPerHour,706 maxDailyTurnover: m.maxDailyTurnover, floorEquity: m.floorEquity, strategySha256: m.strategySha256, agentId: m.agentId, maxPriceDeviationBps: m.maxPriceDeviationBps,707 days: (m.expiresAt - m.createdAt) / 86_400, locale: "fr")708 func answer(_ o: JSONValue) throws -> String {709 let x = try VenueMandate(served: o)710 return DX.text(["mandate": o, "hash": .string(try x.approvalDigest().hex), "acknowledgement": DX.ack("hyperliquid"), "locale": "fr", "warning": "After this approval, orders inside these limits are placed WITHOUT asking for your passkey.",711 "enforcedBySigner": ["position limits"], "trustedBySigner": [], "notEnforced": [], "windDown": ["seconds": 86400, "text": "…"], "venueState": try DX.fixture("live", "account")["venueState"]!, "options": try DX.options(x), "ts": 1794000000000])712 }713 t.enqueue(json: try answer(o))714 let p = try await api.prepareMandate(for: account, request: request, now: DX.now)715 #expect(t.last?.path.hasSuffix("/mandate/prepare") == true && t.last?.body?["instruments"]?.arrayValue?.count == 2 && t.last?.body?["days"] != nil && p.warning?.contains("WITHOUT") == true)716 await #expect(throws: ApprovalError.self) { try await api.approveMandate(p, acknowledged: false, with: passkey, now: DX.now) }717 t.enqueue(json: DX.text(try DX.fixture("live", "account")))718 _ = try await api.approveMandate(p, acknowledged: true, with: passkey, now: DX.now)719 #expect(t.last?.path.hasSuffix("/mandate/approve") == true && t.last?.body?["acknowledged"] == true && passkey.challenges == [DX.challenge(m)])720 for (note, path, value) in [("a wider gross exposure", ["maxGrossExposure"], "120000"), ("a lower floor", ["floorEquity"], "1"), ("more orders per hour", ["maxOrdersPerHour"], 60), ("another agent", ["agentId"], "agent:other"),721 ("another strategy", ["strategySha256"], .string(String(repeating: "b2", count: 32))), ("another authorization", ["authorizationId"], "7a1c1f0e-8f5f-4b1e-9c56-000000000501"),722 ("a wider price band", ["maxPriceDeviationBps"], 2000)] as [(Comment, [String], JSONValue)] {723 t.enqueue(json: try answer(DX.set(o, path, value)))724 await refuses(note) { try await api.prepareMandate(for: account, request: request, now: DX.now) }725 }726 var inst = try #require(o["instruments"]?.arrayValue)727 inst[0] = DX.set(inst[0], ["maxLeverage"], 20)728 t.enqueue(json: try answer(DX.set(o, ["instruments"], .array(inst))))729 await refuses("a higher leverage on one instrument") { try await api.prepareMandate(for: account, request: request, now: DX.now) }730 }731732 // ---- collateral733734 @Test func aDepositGoesFromTheWalletToThePinnedBridgeForTheAmountAsked() async throws {735 let (client, t, passkey) = setup(), api = DerivativesCollateralAPI(client), account = try DX.account()736 let base = try DX.vector("SPW-INTENT-v1", "venue-deposit-hyperliquid").object // 250 USDC, Arbitrum, to Bridge2737 func answer(_ o: JSONValue) throws -> String {738 let i = try Intent(served: o)739 let op = DX.set(DX.set(DX.set(try DX.fixture("collateral", "operationDeposit")["operation"]!, ["hash"], .string(try i.approvalDigest().hex)), ["proposalId"], .string(i.proposalId)), ["state"], "pending_approval")740 return DX.text(["operation": op, "intent": o, "route": ["network": "arbitrum", "networkName": "Arbitrum One", "bridge": .string(HyperliquidCollateralPins.bridge), "minimum": "6", "venueMinimum": "5", "expectedSeconds": 60],741 "fee": ["estimate": "0.00001", "max": "0.00026", "symbol": "ETH"], "liveness": ["ok": true, "checkedAt": 1794000000000, "checked": 5, "credited": 5, "detail": "5 of the last 5 deposits credited"],742 "venueBalance": try DX.fixture("collateral", "status")["venueBalance"]!, "options": try DX.options(i)])743 }744 t.enqueue(json: try answer(base))745 let d = try await api.prepareDeposit(for: account, amount: "250", ownAddress: DX.own, now: DX.now)746 #expect(t.last?.path == "/api/v1/derivatives/live/accounts/\(DX.live.rawValue)/collateral/deposit/prepare" && t.last?.body == ["amount": "250"])747 #expect(d.intent.to == HyperliquidCollateralPins.bridge && d.intent.maxFee == "260000000000000" && d.liveness?.ok == true)748 t.enqueue(json: DX.text(try DX.fixture("collateral", "operationDeposit")))749 let op = try await api.approveDeposit(d, with: passkey, now: DX.now)750 #expect(!op.isDone && t.last?.path.hasSuffix("/collateral/deposit/\(d.operation.id)/approve") == true && passkey.challenges == [DX.challenge(d.intent)])751752 func attempt(_ o: JSONValue, amount: String = "250", own: String = DX.own, account a: LiveAccount = account) async throws -> CollateralDepositApproval {753 t.enqueue(json: try answer(o)); return try await api.prepareDeposit(for: a, amount: amount, ownAddress: own, now: DX.now)754 }755 await refuses("another amount") { try await attempt(DX.set(base, ["amount"], "2500000000")) }756 await refuses("another bridge") { try await attempt(DX.set(DX.set(base, ["to"], "0x3333333333333333333333333333333333333333"), ["venueDeposit", "bridge"], "0x3333333333333333333333333333333333333333")) }757 await refuses("a destination that is not the bridge of the section") { try await attempt(DX.set(base, ["to"], "0x3333333333333333333333333333333333333333")) }758 await refuses("another token") { try await attempt(DX.set(base, ["asset"], "0xFd086bC7CD5C481DCC9C85ebE478A1C0b69FCbb9")) }759 await refuses("another network") { try await attempt(DX.set(DX.set(base, ["network"], "base"), ["chainRef"], "8453")) }760 await refuses("a source that is not the wallet") { try await attempt(DX.set(base, ["from"], "0x4444444444444444444444444444444444444444")) }761 await refuses("an own address that is not the venue account") { try await attempt(DX.set(base, ["from"], "0x4444444444444444444444444444444444444444"), own: "0x4444444444444444444444444444444444444444") }762 await refuses("a lower minimum") { try await attempt(DX.set(base, ["venueDeposit", "minAmount"], "1")) }763 await refuses("a plain transfer") { try await attempt(DX.set(base, ["venueDeposit"], nil)) }764 await refuses("a memo") { try await attempt(DX.set(base, ["memo"], "x")) }765 await refuses("below the floor: the funds would be lost") { try await attempt(DX.set(base, ["amount"], "5000000"), amount: "5") }766 await refuses("more decimals than USDC has") { try await attempt(base, amount: "250.0000001") }767 }768 @Test func aWithdrawalOnlyGoesToTheWalletsOwnAddress() async throws {769 let (client, t, passkey) = setup(), api = DerivativesCollateralAPI(client), account = try DX.account()770 let base = try DX.vector("SPW-VENUE-WITHDRAW-v1", "withdraw-150.25").object771 func answer(_ o: JSONValue, receive: String = "149.25") throws -> String {772 let w = try VenueWithdrawal(served: o)773 let op = DX.set(DX.set(DX.set(try DX.fixture("collateral", "operation")["operation"]!, ["hash"], .string(try w.approvalDigest().hex)), ["state"], "pending_approval"), ["id"], .string(w.withdrawalId))774 return DX.text(["operation": op, "withdrawal": o, "hash": .string(try w.approvalDigest().hex), "receive": .string(receive), "venueBalance": try DX.fixture("collateral", "status")["venueBalance"]!, "options": try DX.options(w),775 "whatIsSigned": ["byMainKey": "Hyperliquid withdraw3", "byPasskey": "SHA-256 of the canonical withdrawal", "action": ["type": "withdraw3", "hyperliquidChain": "Mainnet", "signatureChainId": "0x66eee", "destination": .string(w.destination), "amount": .string(w.amount), "time": .int(Int64(w.time))]]])776 }777 t.enqueue(json: try answer(base))778 let w = try await api.prepareWithdraw(for: account, amount: "150.250", ownAddress: DX.own, now: DX.now)779 #expect(t.last?.path.hasSuffix("/collateral/withdraw/prepare") == true && t.last?.body == ["amount": "150.250"] && w.receive == "149.25" && w.action?.type == "withdraw3")780 t.enqueue(json: DX.text(try DX.fixture("collateral", "operation")))781 #expect(try await api.approveWithdraw(w, with: passkey, now: DX.now).isDone)782 #expect(t.last?.path.hasSuffix("/collateral/withdraw/\(w.withdrawal.withdrawalId)/approve") == true && passkey.challenges == [DX.challenge(w.withdrawal)])783784 func attempt(_ o: JSONValue, amount: String = "150.25", receive: String = "149.25", own: String = DX.own) async throws -> CollateralWithdrawApproval {785 t.enqueue(json: try answer(o, receive: receive)); return try await api.prepareWithdraw(for: account, amount: amount, ownAddress: own, now: DX.now)786 }787 await refuses("another destination") { try await attempt(DX.set(base, ["destination"], "0x5555555555555555555555555555555555555555")) }788 await refuses("another account and destination") { try await attempt(DX.set(DX.set(base, ["destination"], "0x5555555555555555555555555555555555555555"), ["account"], "0x5555555555555555555555555555555555555555")) }789 await refuses("another amount") { try await attempt(DX.set(base, ["amount"], "1500.25")) }790 await refuses("the testnet withdrawal of a mainnet account") { try await attempt(DX.set(base, ["network"], "testnet")) }791 await refuses("a fee that does not add up to what is shown as received") { try await attempt(DX.set(base, ["fee"], "50")) }792 await refuses("an amount received that is not amount − fee") { try await attempt(base, receive: "150.25") }793 await #expect(throws: ApprovalError.expired) { try await api.approveWithdraw(w, with: passkey, now: Date(timeIntervalSince1970: 1_794_000_121)) }794 #expect(passkey.challenges.count == 1)795 }796797 // ---- GMX798799 @Test func theGmxVenuePolicyIsApprovedOnlyAsAsked() async throws {800 let (client, t, passkey) = setup(), api = DerivativesGMXAPI(client), status = try DX.gmxStatus()801 let o = DX.set(try DX.vector("SPW-GMX-AUTH-v1", "gmx-authorization-two-markets-mixed-case-sort").object, ["ackSha256"], .string(DerivHash.sha256Hex(DX.ackText)))802 let x = try GmxAuthorization(served: o)803 let request = GmxAuthorizationRequest(allowedMarkets: x.policy.allowedMarkets.map { $0.lowercased() }, maxLeverage: 5, maxOrderSizeUsd: "500", maxOrdersPerDay: 20, maxPriceDeviationBps: 150, days: 30, locale: "fr")804 func answer(_ o: JSONValue, fee: String = "0.001") throws -> String {805 let a = try GmxAuthorization(served: o)806 return DX.text(["authorization": o, "hash": .string(try a.approvalDigest().hex), "ack": DX.ack("gmx"), "options": try DX.options(a), "maxExecutionFeeEth": .string(fee)])807 }808 t.enqueue(json: try answer(o))809 let p = try await api.prepareAuthorization(request, status: status, ownAddress: DX.own, now: DX.now)810 #expect(t.last?.path == "/api/v1/derivatives/gmx/authorization/prepare" && t.last?.body?["maxLeverage"] == 5 && t.last?.body?["days"] == 30 && p.maxExecutionFeeEth == "0.001")811 t.enqueue(json: DX.text(try DX.fixture("gmx", "status")))812 _ = try await api.approveAuthorization(p, acknowledged: true, with: passkey, locale: "fr", now: DX.now)813 // the authorization goes back exactly as served814 #expect(t.last?.path.hasSuffix("/gmx/authorization/approve") == true && t.last?.query == ["locale": "fr"] && t.last?.body?["authorization"] == o && passkey.challenges == [DX.challenge(x)])815 func attempt(_ o: JSONValue, fee: String = "0.001", own: String = DX.own) async throws -> GmxAuthorizationPreparation {816 t.enqueue(json: try answer(o, fee: fee)); return try await api.prepareAuthorization(request, status: status, ownAddress: own, now: DX.now)817 }818 await refuses("a higher leverage") { try await attempt(DX.set(o, ["policy", "maxLeverage"], 20)) }819 await refuses("a larger order size") { try await attempt(DX.set(o, ["policy", "maxOrderSizeUsd"], "5000")) }820 await refuses("another contract set") { try await attempt(DX.set(o, ["contracts"], "gmx-v2-arbitrum-2027-01-01")) }821 await refuses("another router") { try await attempt(DX.set(o, ["exchangeRouter"], "0x6666666666666666666666666666666666666666")) }822 await refuses("another account") { try await attempt(o, own: "0x4444444444444444444444444444444444444444") }823 await refuses("a fee ceiling above the hard bound") { try await attempt(DX.set(o, ["policy", "maxExecutionFeeWei"], "3000000000000000"), fee: "0.003") }824 await refuses("a fee ceiling that is not the one displayed") { try await attempt(o, fee: "0.0001") }825 await refuses("one market less") { try await attempt(DX.set(o, ["policy", "allowedMarkets"], [o["policy"]!["allowedMarkets"]![0]!])) }826 }827 @Test func aGmxOrderIsTheOrderAskedOnThePinnedContracts() async throws {828 let (client, t, passkey) = setup(), api = DerivativesGMXAPI(client), status = try DX.gmxStatus()829 let eth = "0x70d95587d40A2caf56bd97485aB3Eec10Bee6336"830 let base = try DX.vector("SPW-INTENT-v1", "gmx-increase-long").object // 20 USDC, size 60 USD, long ETH831 func answer(_ o: JSONValue, options: Bool = true) throws -> String {832 let i = try Intent(served: o)833 let op = DX.set(DX.set(DX.set(try DX.fixture("gmx", "operation")["operation"]!, ["hash"], .string(try i.approvalDigest().hex)), ["proposalId"], .string(i.proposalId)), ["state"], "pending_approval")834 return DX.text(["operation": op, "intent": o, "estimate": try DX.fixture("gmx", "preview")["estimate"]!, "fields": [["label": "action", "value": "increase"]], "fixed": [["label": "receiver", "value": .string(DX.own)]],835 "options": options ? try DX.options(i) : .null])836 }837 let byLeverage = GmxOrderRequest.increase(market: eth, side: .long, collateral: "20", leverage: "3", slippageBps: 50)838 t.enqueue(json: try answer(base))839 let p = try await api.prepareOrder(byLeverage, status: status, ownAddress: DX.own, idempotencyKey: "gmx-key-0001", now: DX.now)840 #expect(t.last?.path == "/api/v1/derivatives/gmx/orders" && t.last?.headers["Idempotency-Key"] == "gmx-key-0001" && p.fields.first?.label == "action" && p.fixed.first?.value == DX.own)841 let approvable = try #require(p.approvable)842 t.enqueue(json: DX.text(try DX.fixture("gmx", "operation")))843 let op = try await api.approve(approvable, with: passkey, now: DX.now)844 #expect(op.state == "created" && t.last?.path.hasSuffix("/gmx/operations/\(approvable.operationId)/approve") == true && passkey.challenges == [DX.challenge(approvable.intent)])845 // the same order asked by its size846 t.enqueue(json: try answer(base))847 #expect(try await api.prepareOrder(.increase(market: eth, side: .long, collateral: "20", sizeUsd: "60.00", slippageBps: 50), status: status, ownAddress: DX.own, idempotencyKey: "gmx-key-0002", now: DX.now).approvable != nil)848 // a key past approval: nothing to approve, nothing verified, nothing signable849 t.enqueue(json: try answer(base, options: false))850 #expect(try await api.prepareOrder(byLeverage, status: status, ownAddress: DX.own, idempotencyKey: "gmx-key-0001", now: DX.now).approvable == nil)851852 func attempt(_ o: JSONValue, request: GmxOrderRequest = byLeverage, status s: GmxStatus = status, own: String = DX.own) async throws -> GmxOrderPreparation {853 t.enqueue(json: try answer(o)); return try await api.prepareOrder(request, status: s, ownAddress: own, idempotencyKey: "gmx-key-0003", now: DX.now)854 }855 await refuses("a larger size than collateral × leverage") { try await attempt(DX.set(base, ["gmx", "sizeDeltaUsd"], "400000000000000000000000000000000")) }856 await refuses("a higher leverage than asked") { try await attempt(base, request: .increase(market: eth, side: .long, collateral: "20", leverage: "2", slippageBps: 50)) }857 await refuses("more collateral") { try await attempt(DX.set(base, ["amount"], "200000000")) }858 await refuses("a short when a long was asked") { try await attempt(DX.set(base, ["gmx", "isLong"], false)) }859 await refuses("another market") { try await attempt(DX.set(base, ["gmx", "market"], "0x47c031236e19d024b42f8AE6780E44A573170703")) }860 await refuses("a decrease when an increase was asked") { try await attempt(DX.set(DX.set(base, ["gmx", "action"], "decrease"), ["gmx", "orderType"], "MarketDecrease")) }861 await refuses("another order vault") { try await attempt(DX.set(base, ["gmx", "orderVault"], "0x7777777777777777777777777777777777777777")) }862 await refuses("another exchange router") { try await attempt(DX.set(DX.set(base, ["gmx", "exchangeRouter"], "0x7777777777777777777777777777777777777777"), ["to"], "0x7777777777777777777777777777777777777777")) }863 await refuses("another authorization") { try await attempt(DX.set(base, ["gmx", "authorizationId"], "7a1c1f0e-8f5f-4b1e-9c56-0000000000ab")) }864 await refuses("an execution fee above the authorized ceiling") { try await attempt(DX.set(base, ["gmx", "executionFee"], "1500000000000000")) }865 await refuses("a trigger price") { try await attempt(DX.set(base, ["gmx", "triggerPrice"], "1")) }866 await refuses("another sender") { try await attempt(base, own: "0x4444444444444444444444444444444444444444") }867 await refuses("no active authorization") { try await attempt(base, status: try DX.set(try DX.fixture("gmx", "status"), ["authorization", "state"], "expired").decode()) }868 await refuses("a plain token transfer") { try await attempt(DX.set(base, ["gmx"], nil)) }869 }870 @Test func aGmxCloseAndACancellationMoveNothingOutOfTheWallet() async throws {871 let (client, t, passkey) = setup(), api = DerivativesGMXAPI(client), status = try DX.gmxStatus()872 func answer(_ o: JSONValue) throws -> String {873 let i = try Intent(served: o)874 let op = DX.set(DX.set(DX.set(try DX.fixture("gmx", "operation")["operation"]!, ["hash"], .string(try i.approvalDigest().hex)), ["proposalId"], .string(i.proposalId)), ["kind"], "decrease")875 return DX.text(["operation": op, "intent": o, "estimate": nil, "fields": [], "fixed": [], "options": try DX.options(i)])876 }877 // decrease: the vector is a short on BTC for 125.5 USD878 let dec = try DX.vector("SPW-INTENT-v1", "gmx-decrease-short").object879 let g = try #require(try Intent(served: dec).gmx)880 let sizeUsd = try BaseUnits(g.sizeDeltaUsd).formatted(decimals: 30)881 let position: GmxPositionView = try DX.set(DX.set(DX.set(try DX.fixture("gmx", "status")["positions"]![0]!, ["market"], .string(g.market)), ["side"], g.isLong ? "long" : "short"), ["sizeUsd"], .string(sizeUsd)).decode()882 let close = GmxCloseRequest(market: g.market, side: g.isLong ? .long : .short, fraction: "1", slippageBps: 50)883 t.enqueue(json: try answer(dec))884 let p = try await api.prepareClose(close, position: position, status: status, ownAddress: DX.own, idempotencyKey: "gmx-close-0001", now: DX.now)885 #expect(t.last?.path == "/api/v1/derivatives/gmx/positions/close" && t.last?.headers["Idempotency-Key"] == "gmx-close-0001" && t.last?.body?["fraction"] == "1" && t.last?.body?["slippageBps"] == 50)886 #expect(p.approvable?.intent.amount == "0")887 t.enqueue(json: try answer(DX.set(dec, ["gmx", "isLong"], .bool(!g.isLong))))888 await refuses("the other side") { try await api.prepareClose(close, position: position, status: status, ownAddress: DX.own, idempotencyKey: "gmx-close-0002", now: DX.now) }889 t.enqueue(json: try answer(DX.set(dec, ["gmx", "sizeDeltaUsd"], "999000000000000000000000000000000")))890 await refuses("more than the position") { try await api.prepareClose(close, position: position, status: status, ownAddress: DX.own, idempotencyKey: "gmx-close-0003", now: DX.now) }891 t.enqueue(json: try answer(DX.set(dec, ["amount"], "1000000")))892 await refuses("a decrease that sends collateral") { try await api.prepareClose(close, position: position, status: status, ownAddress: DX.own, idempotencyKey: "gmx-close-0004", now: DX.now) }893 t.enqueue(json: try answer(DX.set(dec, ["gmx", "sizeDeltaUsd"], "1000000000000000000000000000000")))894 await refuses("a part when the whole was asked") { try await api.prepareClose(close, position: position, status: status, ownAddress: DX.own, idempotencyKey: "gmx-close-0005", now: DX.now) }895896 // cancel: the order key is the one of the operation the owner chose897 let cancel = try DX.vector("SPW-INTENT-v1", "gmx-cancel-with-order-key").object898 let target = try #require(status.operations.first)899 t.enqueue(json: try answer(cancel))900 let c = try await api.prepareCancel(of: target, status: status, ownAddress: DX.own, now: DX.now)901 #expect(t.last?.path == "/api/v1/derivatives/gmx/orders/\(target.id)/cancel" && c.approvable?.intent.gmx?.orderKey == target.orderKey)902 t.enqueue(json: DX.text(try DX.fixture("gmx", "operation")))903 _ = try await api.approve(try #require(c.approvable), with: passkey, now: DX.now)904 t.enqueue(json: try answer(DX.set(cancel, ["gmx", "orderKey"], .string("0x" + String(repeating: "cd", count: 32)))))905 await refuses("another order key") { try await api.prepareCancel(of: target, status: status, ownAddress: DX.own, now: DX.now) }906 t.enqueue(json: try answer(DX.set(cancel, ["amount"], "1")))907 await refuses("a cancellation that sends value") { try await api.prepareCancel(of: target, status: status, ownAddress: DX.own, now: DX.now) }908 }909 @Test func gmxRiskChangesApproveTheIntentServed() async throws {910 let (client, t, passkey) = setup(), api = DerivativesGMXAPI(client), status = try DX.gmxStatus()911 func answer(_ o: JSONValue) throws -> String {912 let i = try GmxRiskIntent(served: o)913 return DX.text(["needed": true, "kind": .string(i.kind.rawValue), "loosened": o["loosened"]!, "intent": o, "hash": .string(try i.approvalDigest().hex), "options": try DX.options(i), "expiresAt": .int(Int64(i.expiresAt))])914 }915 let limits = try DX.vector("SPW-GMX-RISK-INTENT-v1", "gmx-limits-loosened").object // 150 / 600.5916 t.enqueue(json: try answer(limits))917 guard case .approval(let l) = try await api.prepareLimits(maxDailyLoss: "150.0", maxTotalLoss: "600.50", status: status, now: DX.now) else { Issue.record("an approval was expected"); return }918 #expect(t.last?.path == "/api/v1/derivatives/gmx/limits/prepare" && t.last?.body == ["maxDailyLoss": "150.0", "maxTotalLoss": "600.50"])919 t.enqueue(json: DX.text(try DX.fixture("gmx", "status")))920 _ = try await api.approveRiskChange(l, with: passkey, locale: "fr", now: DX.now)921 #expect(t.last?.path == "/api/v1/derivatives/gmx/limits/approve" && t.last?.query == ["locale": "fr"] && passkey.challenges == [DX.challenge(l.intent)])922 t.enqueue(json: try answer(DX.set(limits, ["limits", "maxTotalLoss"], "6000")))923 await refuses("a higher loss limit than asked") { try await api.prepareLimits(maxDailyLoss: "150", maxTotalLoss: "600.5", status: status, now: DX.now) }924 t.enqueue(json: try answer(DX.set(limits, ["authorizationId"], "7a1c1f0e-8f5f-4b1e-9c56-0000000000ab")))925 await refuses("another authorization") { try await api.prepareLimits(maxDailyLoss: "150", maxTotalLoss: "600.5", status: status, now: DX.now) }926927 let resume = try DX.vector("SPW-GMX-RISK-INTENT-v1", "gmx-resume").object928 let halted: GmxStatus = try DX.set(try DX.fixture("gmx", "status"), ["risk", "halt"], resume["subject"]!).decode()929 t.enqueue(json: try answer(resume))930 guard case .approval(let r) = try await api.prepareResume(status: halted, now: DX.now) else { Issue.record("an approval was expected"); return }931 t.enqueue(json: DX.text(try DX.fixture("gmx", "status")))932 _ = try await api.approveRiskChange(r, with: passkey, now: DX.now)933 #expect(t.last?.path == "/api/v1/derivatives/gmx/resume" && passkey.challenges.count == 2)934 t.enqueue(json: try answer(resume))935 await refuses("no halt is displayed") { try await api.prepareResume(status: status, now: DX.now) }936 }937}938