Repository Public
1// SP Wallet Core2// File: Tests/SPWalletCoreTests/ExecutionTests.swift3// Description: The Execution domain: canonical bytes of every passkey-approved object against vectors generated by the backend's4// own TypeScript (Vectors/SPW-*.json of the lead, Vectors/execution-*.json of /tmp/spw-vectors-exec.mts), strict5// reading, the binding of each prepare answer to its request, the request contract of every endpoint, the decoding6// of every answer shape, and the secrecy of one-time secrets.7// Fixtures (Fixtures/execution-*.json) copy the shapes of: services/api/src/orders/index.ts `executionRoutes` and8// risk/service.ts `limits`/`exposure`/`decisions` (execution-risk.json); trading-api/spec.ts `OrderRow`, `R.*` and9// orders/service.ts `view` (execution-orders.json); apps/web/src/markets.ts, privateMarkets.ts and market/routes.ts10// (execution-markets.json); trading-api/keys.ts `keyView`, developer-routes.ts, apps/web/src/developer.ts11// (execution-developer.json). execution-mandate-approval-sheet.json is GENERATED by the vector script from the12// backend's `compileToVenueMandate`, hashes and challenges, in the shape of mandates/service.ts `prepareApproval`.13//14// Author: Simon-Pierre Boucher15// Contact: contact@spboucher.ai16import Foundation17import Testing18@testable import SPWalletCore1920// MARK: support2122private final class StubAuthenticator: PasskeyAuthenticator, @unchecked Sendable {23 private let lock = NSLock()24 private var _challenges: [String] = []25 var challenges: [String] { lock.withLock { _challenges } }26 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {27 lock.withLock { _challenges.append(options.challenge) }28 return PasskeyAssertion(credentialId: Data("cred-1".utf8), clientDataJSON: Data(options.challenge.utf8), authenticatorData: Data([1]), signature: Data([2]), userHandle: nil)29 }30 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration { throw PasskeyError.cancelled }31}3233private let rp = "wallet.example.test"34private func text(_ v: JSONValue) -> String { String(decoding: try! APICoding.encoder().encode(v), as: UTF8.self) }35private func options(hashHex: String, rpId: String = rp, uv: String = "required") -> JSONValue {36 ["challenge": .string(Data(hex: hashHex)!.base64URL), "rpId": .string(rpId), "timeout": 120000, "userVerification": .string(uv), "allowCredentials": [["id": "Y3JlZC0x", "type": "public-key"]]]37}38private func with(_ v: JSONValue, _ path: [String], _ new: JSONValue?) -> JSONValue {39 guard case .object(var o) = v, let k = path.first else { return new ?? .null }40 if path.count == 1 { o[k] = new } else { o[k] = with(o[k] ?? .object([:]), Array(path.dropFirst()), new) }41 return .object(o)42}43private func vector(_ file: String, _ name: String) throws -> CanonicalVector { try #require(try CanonicalVector.load(file).first { $0.name == name }) }44private func isUnsupported(_ e: Error) -> Bool { if case ApprovalError.unsupported = e { return true }; return false }45private func isInconsistent(_ e: Error) -> Bool { if case ApprovalError.inconsistent = e { return true }; return false }46/** inside every stamped vector's window (createdAt 1794000000000, expiresAt 1794000300000) */47private let nowInWindow = Date(timeIntervalSince1970: 1_794_000_100)4849// MARK: canonical bytes5051@Suite struct ExecutionCanonicalTests {52 private func assertAll<O>(_ files: [String], minimum: Int, _ make: (JSONValue) throws -> O, _ bytes: (O) throws -> Data) throws {53 var n = 054 for f in files {55 for v in try CanonicalVector.load(f) {56 let o = try make(v.object)57 let b = try bytes(o)58 #expect(b.hex == v.canonicalHex, "\(f) \(v.name): canonical bytes")59 #expect(Data(SHA256Digest.hash(b)).hex == v.hashHex, "\(f) \(v.name): hash")60 n += 161 }62 }63 #expect(n >= minimum)64 }6566 @Test func riskLimitsIntentMatchesTheBackend() throws {67 try assertAll(["SPW-RISK-LIMITS-INTENT-v1.json", "execution-risk-limits-intent.json"], minimum: 5, { try RiskLimitsIntent(served: $0) }, { try $0.canonicalBytes() })68 }69 @Test func riskSwitchIntentMatchesTheBackend() throws {70 try assertAll(["SPW-RISK-SWITCH-INTENT-v1.json", "execution-risk-switch-intent.json"], minimum: 7, { try RiskSwitchReleaseIntent(served: $0) }, { try $0.canonicalBytes() })71 }72 @Test func autoKillIntentMatchesTheBackend() throws {73 try assertAll(["SPW-RISK-AUTO-INTENT-v1.json", "execution-risk-auto-intent.json"], minimum: 4, { try AutoKillIntent(served: $0) }, { try $0.canonicalBytes() })74 }75 @Test func tradingMandateMatchesTheBackend() throws {76 try assertAll(["SPW-TRADING-MANDATE-v1.json", "execution-trading-mandate.json"], minimum: 6, { try TradingMandate(served: $0) }, { try $0.canonicalBytes() })77 }78 @Test func compiledVenueMandateMatchesTheBackend() throws {79 try assertAll(["SPW-VENUE-MANDATE-v1.json", "execution-venue-mandate.json"], minimum: 4, { try CompiledVenueMandate(served: $0) }, { try $0.canonicalBytes() })80 }81 @Test func mandateApprovalIntentMatchesTheBackend() throws {82 try assertAll(["SPW-TRADING-MANDATE-APPROVAL-v1.json", "execution-mandate-approval-intent.json"], minimum: 4, { try MandateApprovalIntent(served: $0) }, { try $0.canonicalBytes() })83 }84 @Test func apiKeyIntentMatchesTheBackend() throws {85 try assertAll(["SPW-APIKEY-INTENT-v1.json", "execution-apikey-intent.json"], minimum: 14, { try APIKeyIntent(served: $0) }, { try $0.canonicalBytes() })86 }87 @Test func canonicalOrderMatchesTheBackend() throws {88 try assertAll(["SPW-ORDER-INTENT-v1.json"], minimum: 3, { try $0.decode(CanonicalOrder.self) }, { try $0.canonicalBytes() })89 }90 /** The serialization itself, on every JSON-canonical vector of the repository (also the domains other modules own). */91 @Test func stableJSONReproducesEveryJSONCanonicalVector() throws {92 var n = 093 for f in ["SPW-RISK-INTENT-v1.json", "SPW-GMX-RISK-INTENT-v1.json", "SPW-RISK-LIMITS-INTENT-v1.json", "SPW-RISK-SWITCH-INTENT-v1.json", "SPW-RISK-AUTO-INTENT-v1.json", "SPW-TRADING-MANDATE-APPROVAL-v1.json", "SPW-APIKEY-INTENT-v1.json",94 "execution-risk-limits-intent.json", "execution-risk-switch-intent.json", "execution-risk-auto-intent.json", "execution-mandate-approval-intent.json", "execution-apikey-intent.json"] {95 for v in try CanonicalVector.load(f) { #expect(try ExecutionStableJSON.bytes(domain: v.domain, v.object).hex == v.canonicalHex, "\(f) \(v.name)"); n += 1 }96 }97 #expect(n >= 40)98 }99 @Test func numbersPrintAsECMAScriptPrintsThem() throws {100 for (d, s) in [(1500.5, "1500.5"), (0.1, "0.1"), (1e-7, "1e-7"), (1.5e-7, "1.5e-7"), (0.000001, "0.000001"), (99999999.99, "99999999.99"), (123456.789, "123456.789"), (100000000.0, "100000000"),101 (1e21, "1e+21"), (1.25e21, "1.25e+21"), (123456789012345680000.0, "123456789012345680000"), (5e-324, "5e-324"), (-2.5, "-2.5"), (0.0, "0"), (-0.0, "0"), (4.35, "4.35"), (0.30000000000000004, "0.30000000000000004")] {102 #expect(try ExecutionStableJSON.number(d) == s)103 }104 #expect(throws: ApprovalError.self) { try ExecutionStableJSON.number(.infinity) }105 #expect(throws: ApprovalError.self) { try ExecutionStableJSON.encode(.int(9_007_199_254_740_993)) }106 #expect(try ExecutionStableJSON.encode(["b": [1, "é/\u{2028}\u{1}\"\\", nil, true], "a": ["z": .double(1.5), "Z": -3]]) == "{\"a\":{\"Z\":-3,\"z\":1.5},\"b\":[1,\"é/\u{2028}\\u0001\\\"\\\\\",null,true]}")107 }108 @Test func decimalsAreCanonicalAndExact() throws {109 #expect(try ExecutionDecimal.canon("5000.00") == "5000"); #expect(try ExecutionDecimal.canon("0.50") == "0.5"); #expect(try ExecutionDecimal.canon("-0.0") == "0"); #expect(try ExecutionDecimal.canon("-1.20") == "-1.2")110 for bad in ["", ".5", "1.", "01", "1e3", "+1", "1,5", " 1", String(repeating: "9", count: 61)] { #expect(throws: ApprovalError.self) { try ExecutionDecimal.canon(bad) } }111 #expect(try ExecutionDecimal.multiply("5000.50", by: 3) == "15001.5"); #expect(try ExecutionDecimal.multiply("0.000001", by: 500) == "0.0005"); #expect(try ExecutionDecimal.multiply("2000.00", by: 120) == "240000")112 #expect(ExecutionDecimal.equal("2000.00", "2000")); #expect(!ExecutionDecimal.equal("2000.01", "2000"))113 #expect(ExecutionDecimal.greater("10", "9.99") == true); #expect(ExecutionDecimal.greater("1.5", "1.50") == false); #expect(ExecutionDecimal.greater("0.2", "0.19") == true)114 #expect(ExecutionDecimal.isPositive("0.0001")); #expect(!ExecutionDecimal.isPositive("0.000")); #expect(!ExecutionDecimal.isNonNegative("-1"))115 }116117 // MARK: strictness118119 @Test func anUnknownOrMistypedFieldIsARefusalNotAnOmission() throws {120 let limits = try vector("execution-risk-limits-intent.json", "limits-live-every-field").object121 #expect(try RiskLimitsIntent(served: limits).limits.maxDailyLoss == "500")122 for bad in [with(limits, ["drain"], "1"), with(limits, ["limits", "maxWithdrawal"], "9"), with(limits, ["limits", "maxPositionNotional", "extra"], "1"), with(limits, ["limits", "maxDailyLoss"], 500),123 with(limits, ["limits", "maxOrdersPerDay"], "500"), with(limits, ["limits", "maxOrdersPerDay"], .double(500.5)), with(limits, ["limits", "maxDailyLoss"], "-1"), with(limits, ["limits", "maxDailyLoss"], nil as JSONValue?).objectValue.map { _ in with(limits, ["limits", "maxDailyLoss"], .null) }!,124 with(limits, ["nonce"], nil), with(limits, ["kind"], "auto"), with(limits, ["v"], 2), with(limits, ["mode"], "prod")] {125 #expect { try RiskLimitsIntent(served: bad) } throws: { isUnsupported($0) }126 }127 let sw = try vector("execution-risk-switch-intent.json", "release-read-only-nulls").object128 #expect { try RiskSwitchReleaseIntent(served: with(sw, ["reason"], nil)) } throws: { isUnsupported($0) } // a nullable member is always present129 #expect { try RiskSwitchReleaseIntent(served: with(sw, ["kind"], "halt")) } throws: { isUnsupported($0) }130 #expect { try RiskSwitchReleaseIntent(served: with(sw, ["scope"], "all")) } throws: { isUnsupported($0) }131 let auto = try vector("execution-risk-auto-intent.json", "auto-all-off").object132 #expect { try AutoKillIntent(served: with(auto, ["auto", "liquidation"], false)) } throws: { isUnsupported($0) }133 #expect { try AutoKillIntent(served: with(auto, ["auto", "drawdown"], 0)) } throws: { isUnsupported($0) }134 let key = try vector("execution-apikey-intent.json", "create-read-only-defaults").object135 for bad in [with(key, ["key", "admin"], true), with(key, ["key", "limits", "maxOrderNotionalUsd"], "5"), with(key, ["key", "mandateId"], nil), with(key, ["keyId"], "spk_0123456789ab"), with(key, ["action"], "delete"), with(key, ["key", "id"], "spk_XYZ")] {136 #expect { try APIKeyIntent(served: bad) } throws: { isUnsupported($0) }137 }138 let rotate = try vector("execution-apikey-intent.json", "rotate").object139 #expect { try APIKeyIntent(served: with(rotate, ["changes"], ["scopes": ["orders:execute"]])) } throws: { isUnsupported($0) }140 }141142 @Test func aMandateWithAnythingUnknownOrAmbiguousIsRefused() throws {143 let m = try vector("execution-trading-mandate.json", "live-agent-perp-all-stop-conditions").object144 _ = try TradingMandate(served: m)145 for bad in [with(m, ["withdraw"], true), with(m, ["maxCapitalUsd"], 5000), with(m, ["maxCapitalUsd"], "0"), with(m, ["maxLeverage"], "3x"), with(m, ["strategySha256"], nil), with(m, ["instruments"], ["hyperliquid:BTC,hyperliquid:DOGE"]),146 with(m, ["instruments"], []), with(m, ["accounts"], [["kind": "venue_account", "venue": "hyperliquid", "network": "mainnet", "account": "0xabc,venue_account|gmx|mainnet|0xdef"]]),147 with(m, ["accounts"], [["kind": "venue_account", "venue": "hyperliquid", "network": "mainnet", "account": "0xabc", "vaultIndex": 1]]), with(m, ["accounts"], [["kind": "treasury", "network": "mainnet"]]),148 with(m, ["stopConditions"], [["kind": "loss_gte", "usd": "10", "bps": 5]]), with(m, ["stopConditions"], [["kind": "never"]]), with(m, ["frequency", "perSecond"], 1), with(m, ["mode"], "prod"),149 with(m, ["principal", "kind"], "owner"), with(m, ["notAfter"], 0), with(m, ["marketKinds"], ["options"]), with(m, ["v"], 2)] {150 #expect { try TradingMandate(served: bad) } throws: { isUnsupported($0) }151 }152 let c = try vector("execution-venue-mandate.json", "compiled-from-live-agent-perp-all-stop-conditions").object153 for bad in [with(c, ["maxWithdrawal"], "1"), with(c, ["venue"], "gmx"), with(c, ["account"], "0xABC"), with(c, ["maxOrdersPerHour"], 61), with(c, ["instruments"], [["instrument": "hyperliquid:BTC", "maxLeverage": 3, "maxPositionNotional": "8000", "isolated": true]]),154 with(c, ["instruments"], [["instrument": "gmx:BTC", "maxLeverage": 3, "maxPositionNotional": "8000"]]), with(c, ["floorEquity"], "0")] {155 #expect { try CompiledVenueMandate(served: bad) } throws: { isUnsupported($0) }156 }157 }158159 @Test func everyLimitOfAMandateChangesItsHash() throws {160 let m = try vector("execution-trading-mandate.json", "live-agent-perp-all-stop-conditions").object161 let base = try TradingMandate(served: m).hashHex()162 for (path, v): ([String], JSONValue) in [(["maxCapitalUsd"], "5000.51"), (["maxOrderNotionalUsd"], "2000.01"), (["maxPositionNotionalUsd"], "8001"), (["maxLeverage"], "4"), (["maxDailyLossUsd"], "250.51"), (["floorEquityUsd"], "2499"),163 (["notAfter"], 1795209601), (["instruments"], ["hyperliquid:ETH", "hyperliquid:BTC", "hyperliquid:SOL"]), (["venues"], ["hyperliquid", "gmx"]), (["maxSlippageBps"], 151), (["maxFeeUsd"], "5.01"),164 (["frequency", "perDay"], 121), (["orderTypes"], ["market"]), (["mode"], "paper"), (["principal", "id"], "9f8e7d6c-5b4a-4c3d-8e2f-000000000202"), (["stopConditions"], []), (["label"], "x")] {165 #expect(try TradingMandate(served: with(m, path, v)).hashHex() != base, "field \(path)")166 }167 // order of a list and trailing zeros of a decimal are NOT part of the identity (the backend sorts and canonicalizes)168 #expect(try TradingMandate(served: with(with(m, ["instruments"], ["hyperliquid:BTC", "hyperliquid:ETH"]), ["maxCapitalUsd"], "5000.5")).hashHex() == base)169 }170171 @Test func theStateMachineHasTwelveStatesAndFourTerminalOnes() throws {172 // packages/trading/src/orders/state.ts ORDER_STATES / TERMINAL_STATES / AT_VENUE_STATES173 let names = ["CREATED", "VALIDATED", "AWAITING_APPROVAL", "APPROVED", "SUBMITTING", "SUBMITTED", "PARTIALLY_FILLED", "FILLED", "CANCELLED", "REJECTED", "FAILED", "UNKNOWN"]174 #expect(OrderState.all.map(\.rawValue) == names)175 #expect(names.map(OrderState.init(rawValue:)) == OrderState.all)176 #expect(OrderState.all.filter(\.isTerminal).map(\.rawValue) == ["FILLED", "CANCELLED", "REJECTED", "FAILED"])177 #expect(OrderState.all.filter(\.isSuccess) == [.filled])178 #expect(OrderState.all.filter(\.isFailure) == [.rejected, .failed])179 #expect(OrderState.all.filter(\.isAtVenue).map(\.rawValue) == ["SUBMITTING", "SUBMITTED", "PARTIALLY_FILLED", "UNKNOWN"])180 #expect(!OrderState.unknown.isTerminal && !OrderState.unknown.isFailure && OrderState.unknown.isBeingVerified)181 let future = OrderState(rawValue: "SETTLING_ON_CHAIN")182 #expect(future == .unrecognized("SETTLING_ON_CHAIN") && future.rawValue == "SETTLING_ON_CHAIN" && !future.isTerminal && !future.isSuccess && !future.isFailure && future.isBeingVerified)183 #expect(!OrderState.partiallyFilled.isSuccess && !OrderState.submitted.isSuccess && !OrderState.cancelled.isSuccess)184 }185}186187/** SHA-256 through the package's own path (`approvalDigest`), so the tests need no second implementation. */188private enum SHA256Digest {189 struct Raw: PasskeyApprovable { let data: Data; func canonicalBytes() throws -> Data { data } }190 static func hash(_ d: Data) -> Data { try! Raw(data: d).approvalDigest() }191}192193// MARK: risk194195@Suite struct ExecutionRiskTests {196 private func prepared(_ v: CanonicalVector, extra: [String: JSONValue] = [:], intent: JSONValue? = nil, hash: String? = nil, opts: JSONValue? = nil) -> String {197 var o: [String: JSONValue] = ["needed": true, "intent": intent ?? v.object, "hash": .string(hash ?? v.hashHex), "options": opts ?? options(hashHex: v.hashHex), "expiresAt": v.object["expiresAt"] ?? .null]198 for (k, x) in extra { o[k] = x }199 return text(.object(o))200 }201202 @Test func stateDecodesEveryShape() async throws {203 let (client, t, _) = MockTransport.client()204 t.enqueue(json: text(try TestResources.json("execution-risk.json")["state"]!))205 let s = try await RiskAPI(client).state()206 let r = try #require(t.last)207 #expect(r.method == "GET" && r.path == "/api/v1/risk/state" && r.headers["X-SPW-CSRF"] == nil)208 #expect(s.switches.killSwitch.on && s.switches.killSwitch.by?.label == "owner:owner" && s.switches.killSwitch.reason == "arrêt d'urgence" && !s.switches.readOnly.on && s.switches.readOnly.at == nil)209 #expect(s.auto == AutoKillSettings(totalLoss: true, drawdown: true, dailyLoss: false))210 #expect(s.limits.paper.missing.isEmpty && s.limits.paper.defaults.maxPriceAgeMs?.per["coingecko"] == 900000 && s.limits.paper.defaults.maxPositionNotional?.fallback == "20000000")211 let live = s.limits.live212 #expect(live.stored.maxDailyLoss == "500" && live.stored.maxOrderNotional == nil && live.storedUnknownFields == ["futureLimit"])213 #expect(live.effectiveOwner?.maxOrderNotional == "5000" && live.seed?.notSeeded == ["maxDailyNotional", "maxNetExposure"] && live.seed?.sources.first?.from == "policy.maxOrderNotional (minimum)")214 #expect(live.missing == ["maxDailyNotional", "maxNetExposure"] && live.ownerOrdersRefused == true && live.automationOrdersRefused == true)215 #expect(s.exposure.paper.isReadable && s.exposure.paper.equity == "10000" && s.exposure.paper.positions?.first?.liquidationDistanceBps == "3166.66" && s.exposure.paper.collateral?.first?.shareBps == "10000")216 #expect(!s.exposure.live.isReadable && s.exposure.live.error == "live accounts: signer unreachable" && s.exposure.live.equity == nil) // an unreadable book has NO figure, not zeros217 #expect(s.exposure.liveTestnet.leverage == nil)218 let d = try #require(s.decisions.first)219 #expect(d.denied && !d.preview && d.principal.label == "api_key:spk_0123456789ab" && d.failing == [RiskCheckFailure(id: "order_notional", observed: "6850", limit: "5000", detail: "order notional 6850 is above the limit 5000"),220 RiskCheckFailure(id: "kill_switch", observed: "on", limit: nil, detail: "the kill switch is on (arrêt d'urgence)")])221 #expect(s.decisions[1].preview && !s.decisions[1].denied && s.decisions[1].instrument == nil)222 #expect(s.locks.map(\.id) == ["deriv_live_mainnet", "trading_api_execution"] && s.locks.allSatisfy { !$0.on } && s.locks[1].why?.contains("SPW_TRADING_API_EXECUTION") == true)223 }224225 @Test func readsSendTheirQueries() async throws {226 let (client, t, _) = MockTransport.client()227 let fx = try TestResources.json("execution-risk.json")["state"]!228 t.enqueue(json: text(["decisions": fx["decisions"]!]))229 #expect(try await RiskAPI(client).decisions(limit: 900).count == 2)230 #expect(t.last?.path == "/api/v1/risk/decisions" && t.last?.query == ["limit": "200"])231 t.enqueue(json: text(fx["exposure"]!["live"]!))232 #expect(try await RiskAPI(client).exposure(book: .liveMainnet).error != nil)233 #expect(t.last?.path == "/api/v1/risk/exposure" && t.last?.query == ["book": "live-mainnet"])234 t.enqueue(json: text(fx["limits"]!["live"]!))235 #expect(try await RiskAPI(client).limits(mode: .live).mode == .live)236 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/risk/limits/live")237 }238239 @Test func engagingNeedsNoPasskeyAndIsNeverAssumed() async throws {240 let (client, t, _) = MockTransport.client()241 let on: JSONValue = ["killSwitch": ["on": true, "at": 1794000000000, "by": ["kind": "owner", "id": "owner"], "reason": "stop"], "readOnly": ["on": false, "at": nil, "by": nil, "reason": nil]]242 t.enqueue(json: text(on))243 #expect(try await RiskAPI(client).engageKillSwitch(reason: " stop ").killSwitch.on)244 let r = try #require(t.last)245 #expect(r.method == "POST" && r.path == "/api/v1/risk/kill-switch" && r.body == ["reason": "stop"] && r.headers["X-SPW-CSRF"] == "1" && r.body?["assertion"] == nil)246 t.enqueue(json: text(with(on, ["killSwitch", "on"], false)))247 await #expect(throws: APIError.self) { _ = try await RiskAPI(client).engageKillSwitch(reason: "x") } // the answer does not show it ON248 t.enqueue(json: text(with(on, ["readOnly", "on"], true)))249 #expect(try await RiskAPI(client).engageReadOnly(reason: "").readOnly.on)250 #expect(t.last?.path == "/api/v1/risk/read-only" && t.last?.body == ["reason": ""])251 }252253 @Test func releasingTheKillSwitchIsBoundToTheEngagementShown() async throws {254 let v = try vector("execution-risk-switch-intent.json", "release-kill-switch-owner")255 let shown: RiskSwitch = try JSONValue.object(["on": true, "at": 1793999940000, "by": ["kind": "owner", "id": "owner"], "reason": v.object["reason"]!]).decode()256 let (client, t, _) = MockTransport.client(), api = RiskAPI(client), auth = StubAuthenticator()257 t.enqueue(json: prepared(v, extra: ["kind": "kill_switch"]))258 guard case .approval(let a) = try await api.prepareRelease(.killSwitch, displayed: shown, now: nowInWindow) else { Issue.record("expected an approval"); return }259 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/risk/kill-switch/release/prepare")260 #expect(a.approval.digest.hex == v.hashHex && a.intent.engagedBy == "owner:owner")261 t.enqueue(json: text(["killSwitch": ["on": false, "at": nil, "by": nil, "reason": nil], "readOnly": ["on": false, "at": nil, "by": nil, "reason": nil]]))262 #expect(try await api.release(a, with: auth, now: nowInWindow).killSwitch.on == false)263 #expect(t.last?.path == "/api/v1/risk/kill-switch/release" && t.last?.body?["assertion"]?["id"]?.stringValue == Data("cred-1".utf8).base64URL)264 #expect(auth.challenges == [Data(hex: v.hashHex)!.base64URL])265 await #expect(throws: ApprovalError.expired) { _ = try await api.release(a, with: auth, now: Date(timeIntervalSince1970: 1_794_000_300)) }266267 // refusals, each BEFORE the passkey is asked268 func refused(_ json: String, kind: RiskSwitchKind = .killSwitch, displayed: RiskSwitch = shown, now: Date = nowInWindow, _ check: (Error) -> Bool, _ c: Comment) async {269 t.enqueue(json: json)270 do { _ = try await api.prepareRelease(kind, displayed: displayed, now: now); Issue.record("expected a refusal: \(c)") } catch { #expect(check(error), c) }271 }272 let other: RiskSwitch = try JSONValue.object(["on": true, "at": 1793999940001, "by": ["kind": "owner", "id": "owner"], "reason": v.object["reason"]!]).decode()273 await refused(prepared(v, extra: ["kind": "kill_switch"]), displayed: other, isInconsistent, "re-engaged since")274 let byKey: RiskSwitch = try JSONValue.object(["on": true, "at": 1793999940000, "by": ["kind": "api_key", "id": "spk_0123456789ab"], "reason": v.object["reason"]!]).decode()275 await refused(prepared(v, extra: ["kind": "kill_switch"]), displayed: byKey, isInconsistent, "another actor")276 await refused(prepared(v, extra: ["kind": "kill_switch"]), kind: .readOnly, isInconsistent, "the intent releases the other switch")277 var bad = Data(hex: v.hashHex)!; bad[31] ^= 1278 await refused(prepared(v, extra: ["kind": "kill_switch"], opts: options(hashHex: bad.hex)), { $0 as? ApprovalError == .challengeMismatch }, "a challenge that is not the hash of the intent")279 await refused(prepared(v, extra: ["kind": "kill_switch"], opts: options(hashHex: v.hashHex, rpId: "evil.example")), { $0 as? ApprovalError == .wrongRelyingParty("evil.example") }, "another relying party")280 await refused(prepared(v, extra: ["kind": "kill_switch"], opts: options(hashHex: v.hashHex, uv: "preferred")), { $0 as? ApprovalError == .userVerificationNotRequired }, "no user verification")281 await refused(prepared(v, extra: ["kind": "kill_switch"], hash: bad.hex), isInconsistent, "a stated hash that is not the intent's")282 await refused(prepared(v, extra: ["kind": "kill_switch"]), now: Date(timeIntervalSince1970: 1_794_000_300), { $0 as? ApprovalError == .expired }, "expired")283 await refused(prepared(v, extra: ["kind": "kill_switch"], intent: with(v.object, ["scope"], "everything")), isUnsupported, "an unknown field")284 await refused(prepared(v, extra: ["kind": "kill_switch", "expiresAt": 1794009999999]), isInconsistent, "another window")285 #expect(auth.challenges.count == 1)286287 t.enqueue(json: #"{"needed":false,"kind":"read_only","intent":null,"hash":null,"options":null,"expiresAt":null}"#)288 guard case .notEngaged = try await api.prepareRelease(.readOnly, displayed: shown) else { Issue.record("expected notEngaged"); return }289 #expect(t.last?.path == "/api/v1/risk/read-only/release/prepare")290 let ro = try vector("execution-risk-switch-intent.json", "release-read-only-nulls")291 let roShown: RiskSwitch = try JSONValue.object(["on": true, "at": nil, "by": nil, "reason": nil]).decode()292 t.enqueue(json: prepared(ro, extra: ["kind": "read_only"]))293 guard case .approval(let b) = try await api.prepareRelease(.readOnly, displayed: roShown, now: nowInWindow) else { Issue.record("expected an approval"); return }294 t.enqueue(json: text(["killSwitch": ["on": false, "at": nil, "by": nil, "reason": nil], "readOnly": ["on": false, "at": nil, "by": nil, "reason": nil]]))295 _ = try await api.release(b, with: auth, now: nowInWindow)296 #expect(t.last?.path == "/api/v1/risk/read-only/release")297 }298299 @Test func looseningLimitsIsBoundToEveryValueRequested() async throws {300 let v = try vector("execution-risk-limits-intent.json", "limits-live-every-field")301 let asked: EngineRiskLimits = try v.object["limits"]!.decode()302 let (client, t, _) = MockTransport.client(), api = RiskAPI(client), auth = StubAuthenticator()303 t.enqueue(json: prepared(v, extra: ["loosened": v.object["loosened"]!]))304 guard case .approval(let a) = try await api.prepareLimits(mode: .live, limits: asked, now: nowInWindow) else { Issue.record("expected an approval"); return }305 let r = try #require(t.last)306 #expect(r.method == "POST" && r.path == "/api/v1/risk/limits/live/prepare" && r.body == ["limits": v.object["limits"]!]) // the body is the limit set, value for value307 #expect(a.loosened == ["allowedInstruments", "maxDailyLoss", "maxGrossExposure", "maxPositionNotional"] && a.limits == asked && a.approval.digest.hex == v.hashHex)308 t.enqueue(json: text(try TestResources.json("execution-risk.json")["state"]!["limits"]!["live"]!))309 _ = try await api.approveLimits(a, with: auth, now: nowInWindow)310 #expect(t.last?.path == "/api/v1/risk/limits/live/approve" && t.last?.body?["assertion"] != nil && auth.challenges == [Data(hex: v.hashHex)!.base64URL])311312 // the server prepares ANOTHER set than the one asked: each single value is caught313 for (path, value): ([String], JSONValue) in [(["maxDailyLoss"], "5000"), (["maxPositionNotional", "per", "hyperliquid:BTC"], "200000"), (["allowedInstruments"], ["hyperliquid:ETH", "hyperliquid:BTC", "gmx:BTC/USD [BTC-USDC]", "hyperliquid:DOGE"]),314 (["maxOrderLeverage"], "50"), (["maxPriceAgeMs", "default"], 99999), (["minLiquidity", "multiple"], "1"), (["maxOrdersPerDay"], 501)] {315 var other = asked316 let mutated: EngineRiskLimits = try with(v.object["limits"]!, path, value).decode()317 other = mutated318 t.enqueue(json: prepared(v, extra: ["loosened": v.object["loosened"]!]))319 do { _ = try await api.prepareLimits(mode: .live, limits: other, now: nowInWindow); Issue.record("expected a refusal for \(path)") } catch { #expect(isInconsistent(error), "\(path)") }320 }321 t.enqueue(json: prepared(v, extra: ["loosened": v.object["loosened"]!]))322 do { _ = try await api.prepareLimits(mode: .paper, limits: asked, now: nowInWindow); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) }323 t.enqueue(json: prepared(v, extra: ["loosened": ["maxDailyLoss"]]))324 do { _ = try await api.prepareLimits(mode: .live, limits: asked, now: nowInWindow); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) }325 #expect(auth.challenges.count == 1)326327 t.enqueue(json: #"{"needed":false,"loosened":[],"intent":null,"hash":null,"options":null,"expiresAt":null}"#)328 guard case .passkeyNotNeeded = try await api.prepareLimits(mode: .live, limits: asked) else { Issue.record("expected passkeyNotNeeded"); return }329330 // tightening: the session alone; a loosening sent there is the server's 403, kept verbatim331 t.enqueue(status: 403, json: #"{"error":"passkey_required","message":"this change loosens maxDailyLoss: it needs the owner's passkey (prepare it, then approve). Tightening needs none."}"#)332 do { _ = try await api.setLimits(mode: .live, limits: asked); Issue.record("expected 403") } catch let e as APIError { #expect(e.status == 403 && e.code == "passkey_required" && e.message.contains("maxDailyLoss")) }333 #expect(t.last?.path == "/api/v1/risk/limits/live" && t.last?.body?["assertion"] == nil)334 var invalid = asked; invalid.maxDailyLoss = "1e3"335 let before = t.requests.count336 await #expect(throws: ApprovalError.self) { _ = try await api.setLimits(mode: .live, limits: invalid) }337 #expect(t.requests.count == before) // a malformed limit never leaves the device338 }339340 @Test func switchingAnAutomaticStopOffNeedsThePasskey() async throws {341 let v = try vector("execution-risk-auto-intent.json", "auto-total-loss-off")342 let asked = AutoKillSettings(totalLoss: false, drawdown: true, dailyLoss: false)343 let (client, t, _) = MockTransport.client(), api = RiskAPI(client), auth = StubAuthenticator()344 t.enqueue(json: prepared(v, extra: ["loosened": ["totalLoss"]]))345 guard case .approval(let a) = try await api.prepareAutoKill(asked, now: nowInWindow) else { Issue.record("expected an approval"); return }346 #expect(t.last?.path == "/api/v1/risk/auto/prepare" && t.last?.body == ["auto": ["totalLoss": false, "drawdown": true, "dailyLoss": false]] && a.loosened == ["totalLoss"])347 t.enqueue(json: #"{"auto":{"totalLoss":false,"drawdown":true,"dailyLoss":false}}"#)348 #expect(try await api.approveAutoKill(a, with: auth, now: nowInWindow) == asked)349 #expect(t.last?.path == "/api/v1/risk/auto" && t.last?.body?["auto"] == ["totalLoss": false, "drawdown": true, "dailyLoss": false] && t.last?.body?["assertion"] != nil)350 t.enqueue(json: prepared(v, extra: ["loosened": ["totalLoss"]]))351 do { _ = try await api.prepareAutoKill(AutoKillSettings(totalLoss: false, drawdown: false, dailyLoss: false), now: nowInWindow); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) }352 t.enqueue(json: #"{"auto":{"totalLoss":true,"drawdown":true,"dailyLoss":true}}"#)353 #expect(try await api.setAutoKill(AutoKillSettings(totalLoss: true, drawdown: true, dailyLoss: true)).dailyLoss)354 #expect(t.last?.body == ["auto": ["totalLoss": true, "drawdown": true, "dailyLoss": true]])355 }356357 @Test func refusalsAreTypedAndVerbatim() async throws {358 let fx = try TestResources.json("execution-risk.json")359 let (client, t, _) = MockTransport.client()360 t.enqueue(status: 422, json: text(fx["riskDeniedError"]!))361 let req = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.1"), price: "68500", reduceOnly: false, tif: "gtc")362 do { _ = try await OrdersAPI(client).place(req, idempotencyKey: "ui-order-0001-abcdef"); Issue.record("expected a refusal") }363 catch let e as APIError {364 let r = try #require(ExecutionRefusal(e))365 #expect(r.stage == .risk && r.code == "risk_denied" && r.status == 422 && r.message == "order_notional: order notional 6850 is above the limit 5000" && r.decisionId == 812)366 #expect(r.failed == ["order_notional", "future_check"])367 #expect(r.checks == [RiskCheckFailure(id: "order_notional", observed: "6850", limit: "5000", detail: "order notional 6850 is above the limit 5000"),368 RiskCheckFailure(id: "future_check", observed: nil, limit: nil, detail: "a check this version does not know")])369 #expect(r.order?.status == .rejected && r.order?.reasonCode == "RISK_DENIED" && r.order?.rejectCode == "risk_denied" && r.order?.isFinal == true)370 }371 let m = try #require(ExecutionRefusal(APIError(status: 403, code: "mandate_denied", message: fx["mandateDeniedError"]!["message"]!.stringValue!, data: fx["mandateDeniedError"]!["data"])))372 #expect(m.stage == .mandate && m.reasons == ["ORDER_NOTIONAL_EXCEEDED", "LEVERAGE_EXCEEDED"] && m.checks.isEmpty && m.order == nil)373 let k = try #require(ExecutionRefusal(APIError(status: 423, code: "kill_switch_active", message: "the kill switch is on (x): no new risk; cancels and reduce-only exits still pass")))374 #expect(k.stage == .risk && k.message.hasPrefix("the kill switch is on"))375 #expect(ExecutionRefusal(APIError(status: 400, code: "invalid_order", message: "bad")) == nil)376 #expect(ExecutionRefusal(APIError.offline()) == nil)377 }378}379380// MARK: mandates381382@Suite struct ExecutionMandateTests {383 static let accountId = "6e0f8a44-1b7c-4f1e-9d55-0000000000b1"384 static func sheet() throws -> JSONValue { try TestResources.json("execution-mandate-approval-sheet.json") }385 /** the creation request the generated live mandate corresponds to */386 static func request(budget: String = "5000.50", perOrder: String = "2000", leverage: String = "3", days: Int = 14, instruments: [String] = ["hyperliquid:ETH", "hyperliquid:BTC"], dailyLoss: String = "250.5", floor: String = "2500") -> MandateCreateRequest {387 MandateCreateRequest(principal: MandatePrincipal(kind: "agent", id: "9f8e7d6c-5b4a-4c3d-8e2f-000000000201"), mode: .live, accountIds: [accountId], venues: nil, allowedInstruments: instruments, marketKinds: ["perp"],388 orderTypes: ["market", "limit", "stop", "take_profit"], budgetCapUsd: budget, perOrderCapUsd: perOrder, positionCapUsd: "8000", maxLeverage: leverage, dailyLossLimitUsd: dailyLoss, floorEquityUsd: floor, expiresInDays: days,389 frequency: .init(perMinute: 5, perHour: 30, perDay: 120), maxSlippageBps: 150, maxFeeUsd: "5",390 stopConditions: [.init(kind: "signer_unreachable_gte", ms: 120000), .init(kind: "loss_gte", usd: "1000.0"), .init(kind: "drawdown_gte", bps: 1500), .init(kind: "data_stale_gte", ms: 30000), .init(kind: "consecutive_rejects_gte", count: 5)],391 strategySha256: String(repeating: "a1", count: 32), label: " Tendance BTC/ETH — été ", locale: "fr")392 }393 static func record(state: String = "created", phase: String = "not_approved", mandate: JSONValue? = nil) throws -> JSONValue {394 let s = try sheet()395 return ["id": s["mandateId"]!, "kind": "directional", "quoting": nil, "principal": s["mandate"]!["principal"]!, "mode": "live", "state": .string(state), "phase": .string(phase), "hash": s["hash"]!, "mandate": mandate ?? s["mandate"]!,396 "label": s["mandate"]!["label"]!, "enforcement": s["enforcement"]!, "derived": s["derived"]!, "signer": nil, "stop": nil, "revocation": nil, "approval": nil, "integrity": nil,397 "usage": ["ordersAccepted": 0, "ordersRejected": 0, "consecutiveRejects": 0, "notionalTotal": "0", "peakEquity": nil, "startEquity": nil, "lastOrderAt": nil, "ordersLastMinute": 0, "ordersLastHour": 0, "ordersToday": 0, "openOrders": 0],398 "createdAt": 1794000000000, "approvedAt": nil, "revokedAt": nil, "notBefore": 1794000000000, "notAfter": 1795209600000]399 }400 static let now = Date(timeIntervalSince1970: 1_794_000_100)401402 @Test func theGeneratedSheetIsConsistentWithItsVectors() throws {403 // the fixture was built by the backend's compileToVenueMandate from the first trading-mandate vector: same objects, same hashes404 let s = try Self.sheet()405 #expect(s["mandate"] == (try vector("execution-trading-mandate.json", "live-agent-perp-all-stop-conditions").object))406 #expect(s["hash"]?.stringValue == (try vector("execution-trading-mandate.json", "live-agent-perp-all-stop-conditions").hashHex))407 #expect(s["signer"]?["hash"]?.stringValue == (try vector("execution-venue-mandate.json", "compiled-from-live-agent-perp-all-stop-conditions").hashHex))408 #expect(s["binding"]?["hash"]?.stringValue == (try vector("execution-mandate-approval-intent.json", "approval-directional").hashHex))409 #expect(s["enforcement"]?.arrayValue?.contains { $0["enforcedBy"]?.stringValue == "api_only" } == true)410 }411412 @Test func listAndDetailShowOnlyLimitsThatHashToTheRecord() async throws {413 let (client, t, _) = MockTransport.client(), api = MandatesAPI(client)414 let tampered = with(try Self.sheet()["mandate"]!, ["maxCapitalUsd"], "999999")415 let unknown = with(try Self.sheet()["mandate"]!, ["maxWithdrawalUsd"], "1")416 t.enqueue(json: text(["mandates": [try Self.record(state: "active", phase: "active"), try Self.record(mandate: tampered), try Self.record(mandate: unknown)]]))417 let l = try await api.list()418 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/mandates")419 let m = try #require(l[0].mandate)420 #expect(l[0].isActive && m.maxCapitalUsd == "5000.50" && m.maxOrderNotionalUsd == "2000.00" && m.maxLeverage == "3" && m.maxDailyLossUsd == "250.50" && m.floorEquityUsd == "2500.0" && m.instruments == ["hyperliquid:ETH", "hyperliquid:BTC"] && m.notAfter == 1795209600)421 #expect(l[0].enforcement.contains { $0.field == "maxDailyLossUsd" } && l[0].usage?.openOrders == 0 && !l[0].isQuoting)422 #expect(l[1].mandate == nil && l[1].mandateProblem?.contains("hash") == true && !l[1].isActive) // limits that do not hash to the record are not shown as its limits423 #expect(l[2].mandate == nil && l[2].mandateProblem != nil)424 t.enqueue(json: text(["mandate": try Self.record()]))425 #expect(try await api.mandate("4b9d1c2e-3f40-4a5b-8c6d-000000000101").state == "created")426 #expect(t.last?.path == "/api/v1/mandates/4b9d1c2e-3f40-4a5b-8c6d-000000000101")427 }428429 @Test func creationStatesEveryLimitAndChecksTheAnswer() async throws {430 let (client, t, _) = MockTransport.client(), api = MandatesAPI(client)431 t.enqueue(json: text(["mandate": try Self.record()]))432 let m = try await api.create(Self.request())433 #expect(m.state == "created")434 let r = try #require(t.last), b = try #require(r.body)435 #expect(r.method == "POST" && r.path == "/api/v1/mandates" && r.headers["X-SPW-CSRF"] == "1")436 #expect(b["maxCapitalUsd"] == "5000.50" && b["maxOrderNotionalUsd"] == "2000" && b["maxPositionNotionalUsd"] == "8000" && b["maxLeverage"] == "3" && b["maxDailyLossUsd"] == "250.5" && b["floorEquityUsd"] == "2500")437 #expect(b["instruments"] == ["hyperliquid:ETH", "hyperliquid:BTC"] && b["days"] == 14 && b["accountIds"] == [.string(Self.accountId)] && b["mode"] == "live" && b["principal"] == ["kind": "agent", "id": "9f8e7d6c-5b4a-4c3d-8e2f-000000000201"])438 #expect(b["frequency"] == ["perMinute": 5, "perHour": 30, "perDay": 120] && b["maxSlippageBps"] == 150 && b["maxFeeUsd"] == "5" && b["stopConditions"]?.arrayValue?.count == 5 && b["venues"] == nil && b["quoting"] == nil && b["locale"] == "fr")439 for bad in [Self.request(budget: "6000"), Self.request(perOrder: "2000.01"), Self.request(leverage: "4"), Self.request(days: 30), Self.request(instruments: ["hyperliquid:ETH"]), Self.request(dailyLoss: "300"), Self.request(floor: "100")] {440 t.enqueue(json: text(["mandate": try Self.record()]))441 do { _ = try await api.create(bad); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) }442 }443 let before = t.requests.count444 await #expect(throws: APIError.self) { _ = try await api.create(Self.request(budget: "0")) }445 await #expect(throws: APIError.self) { _ = try await api.create(Self.request(leverage: "")) }446 await #expect(throws: APIError.self) { _ = try await api.create(Self.request(days: 0)) }447 await #expect(throws: APIError.self) { _ = try await api.create(Self.request(instruments: [])) }448 #expect(t.requests.count == before)449 }450451 @Test func aLiveApprovalVerifiesBothChallengesAndTheCompilation() async throws {452 let (client, t, _) = MockTransport.client(), api = MandatesAPI(client), auth = StubAuthenticator()453 let s = try Self.sheet(), id = s["mandateId"]!.stringValue!454 t.enqueue(json: text(s))455 let sheet = try await api.prepareApproval(id: id, expecting: .request(Self.request()), locale: "fr", now: Self.now)456 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/mandates/\(id)/approve/prepare" && t.last?.body == ["locale": "fr"])457 let live = try #require(sheet.live)458 #expect(live.signer.digest.hex == s["signer"]!["hash"]!.stringValue && live.binding.digest.hex == s["binding"]!["hash"]!.stringValue && live.signer.digest != live.binding.digest)459 #expect(live.signer.object.maxGrossExposure == "15001.5" && live.signer.object.maxDailyTurnover == "240000" && live.signer.object.instruments.allSatisfy { $0.maxLeverage == 3 } && live.acknowledgement.sha256 == live.signer.object.ackSha256)460 #expect(sheet.mandate.maxCapitalUsd == "5000.50" && sheet.enforcement.count == 25 && sheet.enforcement.first { $0.field == "maxDailyLossUsd" }?.enforcedBy == "api_only" && live.accountId == Self.accountId)461 // the same sheet against the mandate displayed from its record462 let displayed = try TradingMandate(served: s["mandate"])463 t.enqueue(json: text(s))464 _ = try await api.prepareApproval(id: id, expecting: .displayed(displayed), locale: "en", now: Self.now)465466 await #expect { _ = try await api.approve(sheet, acknowledgementConfirmed: false, with: auth, now: Self.now) } throws: { isInconsistent($0) }467 #expect(auth.challenges.isEmpty)468 t.enqueue(json: text(["mandate": try Self.record(state: "active", phase: "active")]))469 #expect(try await api.approve(sheet, acknowledgementConfirmed: true, with: auth, now: Self.now).isActive)470 let b = try #require(t.last?.body)471 #expect(t.last?.path == "/api/v1/mandates/\(id)/approve" && b["acknowledged"] == true && b["assertion"] != nil && b["bindingAssertion"] != nil)472 #expect(auth.challenges == [live.signer.options.challenge, live.binding.options.challenge])473 #expect(b["assertion"]?["response"]?["clientDataJSON"]?.stringValue == Data(live.signer.options.challenge.utf8).base64URL && b["bindingAssertion"]?["response"]?["clientDataJSON"]?.stringValue == Data(live.binding.options.challenge.utf8).base64URL)474 await #expect(throws: ApprovalError.expired) { _ = try await api.approve(sheet, acknowledgementConfirmed: true, with: auth, now: Date(timeIntervalSince1970: 1_794_000_300)) }475 }476477 @Test func anySheetThatDoesNotLineUpIsRefusedBeforeThePasskey() async throws {478 let s = try Self.sheet(), id = s["mandateId"]!.stringValue!479 func refused(_ sheet: JSONValue, expecting: MandateExpectation = .request(Self.request()), now: Date = Self.now, _ check: (Error) -> Bool, _ c: Comment) {480 do { _ = try MandatesAPI.verify(sheet: sheet, id: id, expecting: expecting, rpId: rp, now: now); Issue.record("expected a refusal: \(c)") } catch { #expect(check(error), "\(c): \(error)") }481 }482 _ = try MandatesAPI.verify(sheet: s, id: id, expecting: .request(Self.request()), rpId: rp, now: Self.now)483 // the mandate484 refused(with(s, ["mandate", "maxCapitalUsd"], "50000"), isInconsistent, "a mandate that does not hash to the stated hash")485 refused(with(s, ["mandate", "maxWithdrawalUsd"], "1"), isUnsupported, "an unknown field in the mandate")486 refused(with(s, ["hash"], .string(String(repeating: "0", count: 64))), isInconsistent, "another stated hash")487 for r in [Self.request(budget: "5000"), Self.request(perOrder: "1999"), Self.request(leverage: "2"), Self.request(days: 15), Self.request(instruments: ["hyperliquid:BTC", "hyperliquid:ETH", "hyperliquid:SOL"]), Self.request(dailyLoss: "250"), Self.request(floor: "2500.01")] {488 refused(s, expecting: .request(r), isInconsistent, "a mandate that is not the request")489 }490 refused(s, expecting: .displayed(try TradingMandate(served: try vector("execution-trading-mandate.json", "paper-api-key-wildcard-null-strategy").object)), isInconsistent, "another mandate than the one displayed")491 refused(s, now: Date(timeIntervalSince1970: 1_795_209_600), { $0 as? ApprovalError == .expired }, "a mandate past its expiry")492 refused(with(s, ["passkey"], false), isInconsistent, "a live mandate presented as needing no passkey")493 refused(with(s, ["principalDescriptor"], "spw-principal-v1|api_key|spk_0123456789ab"), isInconsistent, "a descriptor for an agent")494 // the signer mandate495 refused(with(s, ["signer", "mandate", "maxOrderNotional"], "200000"), isInconsistent, "a signer mandate wider than the mandate")496 refused(with(s, ["signer", "mandate", "drain"], true), isUnsupported, "an unknown field in the signer mandate")497 refused(with(s, ["signer", "hash"], .string(String(repeating: "1", count: 64))), isInconsistent, "another stated signer hash")498 refused(with(s, ["signer", "options"], options(hashHex: s["binding"]!["hash"]!.stringValue!)), { $0 as? ApprovalError == .challengeMismatch }, "challenge 1 is not the signer mandate's hash")499 refused(with(s, ["signer", "options"], options(hashHex: s["signer"]!["hash"]!.stringValue!, rpId: "evil.example")), { $0 as? ApprovalError == .wrongRelyingParty("evil.example") }, "another relying party")500 refused(with(s, ["signer", "acknowledgement", "sha256"], .string(String(repeating: "d", count: 64))), isInconsistent, "another acknowledgement than the one in the signer mandate")501 refused(with(s, ["signer", "accountId"], "6e0f8a44-1b7c-4f1e-9d55-00000000ffff"), isInconsistent, "a venue account that was not requested")502 // the binding intent503 refused(with(s, ["binding", "options"], options(hashHex: s["signer"]!["hash"]!.stringValue!)), { $0 as? ApprovalError == .challengeMismatch }, "challenge 2 is not the intent's hash")504 refused(with(s, ["binding", "intent", "tradingMandateHash"], .string(String(repeating: "2", count: 64))), isInconsistent, "an intent naming another mandate hash")505 refused(with(s, ["binding", "intent", "signer", "mandateHash"], .string(String(repeating: "3", count: 64))), isInconsistent, "an intent naming another signer mandate")506 refused(with(s, ["binding", "intent", "principal"], "agent:someone-else"), isInconsistent, "an intent naming another principal")507 refused(with(s, ["binding", "intent", "scope"], "all"), isUnsupported, "an unknown field in the intent")508 refused(with(s, ["binding"], nil), isUnsupported, "no binding")509 refused(s, now: Date(timeIntervalSince1970: 1_794_000_300), { $0 as? ApprovalError == .expired }, "the binding window has passed")510 // quoting mandates are not approved from this module511 refused(with(s, ["kind"], "quoting"), isUnsupported, "a quoting mandate")512 refused(with(s, ["signer", "shape"], "SPW-VENUE-QUOTING-MANDATE-v1"), isUnsupported, "a quoting signer shape")513 refused(with(with(s, ["binding", "intent"], try vector("execution-mandate-approval-intent.json", "approval-quoting-with-section-hash").object), ["binding", "hash"], .string(try vector("execution-mandate-approval-intent.json", "approval-quoting-with-section-hash").hashHex)), { isInconsistent($0) || isUnsupported($0) }, "a quoting intent")514 }515516 @Test func theSignerMandateMustBeWhatTheMandateCompilesTo() throws {517 let s = try Self.sheet()518 let compiled = try CompiledVenueMandate(served: s["signer"]!["mandate"])519 try MandatesAPI.check(compiled: compiled, against: try TradingMandate(served: s["mandate"]))520 // packages/trading compileToVenueMandate: each rule, broken on the mandate side (the compiled object is the backend's own)521 for (path, v, what): ([String], JSONValue, Comment) in [(["maxLeverage"], "2", "max leverage"), (["maxOrderNotionalUsd"], "1999", "per-order cap"), (["maxPositionNotionalUsd"], "7999", "position cap"), (["maxCapitalUsd"], "5000", "budget cap × leverage"),522 (["floorEquityUsd"], "2400", "loss limit"), (["notAfter"], 1795209599, "expiry"), (["frequency", "perDay"], 119, "orders per day"), (["frequency", "perHour"], 29, "orders per hour"),523 (["maxSlippageBps"], 149, "price band"), (["instruments"], ["hyperliquid:ETH"], "allowed markets"), (["instruments"], ["hyperliquid:ETH", "hyperliquid:BTC", "hyperliquid:SOL"], "allowed markets"),524 (["principal", "id"], "agent-other", "principal"), (["strategySha256"], .string(String(repeating: "b2", count: 32)), "strategy"), (["mandateId"], "4b9d1c2e-3f40-4a5b-8c6d-0000000001ff", "mandate id"),525 (["maxLeverage"], "2.5", "integer leverage"), (["mode"], "paper", "paper"),526 (["accounts"], [["kind": "venue_account", "venue": "hyperliquid", "network": "mainnet", "account": "0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc"]], "venue account")] {527 let m = try TradingMandate(served: with(s["mandate"]!, path, v))528 do { try MandatesAPI.check(compiled: compiled, against: m); Issue.record("expected a refusal: \(what)") } catch { #expect(isInconsistent(error), what) }529 }530 }531532 @Test func aPaperMandateNeedsNoPasskeyAndAnAPIKeyMandateNamesItsDescriptor() async throws {533 let v = try vector("execution-trading-mandate.json", "paper-api-key-wildcard-null-strategy")534 let id = v.object["mandateId"]!.stringValue!535 // paper sheet (mandates/service.ts prepareApproval, `passkey: false`); `strategySha256` null is the vector's — the service itself stores the descriptor hash536 let paper: JSONValue = ["mandateId": .string(id), "mandate": v.object, "hash": .string(v.hashHex), "mode": "paper", "enforcement": [["field": "maxCapitalUsd", "enforcedBy": "api_only", "signerField": nil, "note": "paper: nothing is signed; every field is enforced by the API on the simulated account"]],537 "derived": [], "principalDescriptor": "spw-principal-v1|api_key|spk_0123456789ab", "passkey": false, "signer": nil, "note": "a paper mandate needs no signer and no passkey: nothing is signed in paper mode"]538 let displayed = try TradingMandate(served: v.object)539 let (client, t, _) = MockTransport.client(), api = MandatesAPI(client), auth = StubAuthenticator()540 t.enqueue(json: text(paper))541 let sheet = try await api.prepareApproval(id: id, expecting: .displayed(displayed), locale: "en", now: Self.now)542 #expect(sheet.live == nil && sheet.principalDescriptor == "spw-principal-v1|api_key|spk_0123456789ab" && sheet.mandate.instruments.contains("hyperliquid:*"))543 t.enqueue(json: text(["mandate": with(with(try Self.record(state: "active", phase: "pending", mandate: v.object), ["id"], .string(id)), ["hash"], .string(v.hashHex))]))544 _ = try await api.approve(sheet, acknowledgementConfirmed: false, with: auth, now: Self.now)545 #expect(t.last?.path == "/api/v1/mandates/\(id)/approve" && t.last?.body == [:] && auth.challenges.isEmpty)546 #expect { try MandatesAPI.verify(sheet: with(paper, ["passkey"], true), id: id, expecting: .displayed(displayed), rpId: rp, now: Self.now) } throws: { isInconsistent($0) }547 #expect { try MandatesAPI.verify(sheet: with(paper, ["principalDescriptor"], nil), id: id, expecting: .displayed(displayed), rpId: rp, now: Self.now) } throws: { isInconsistent($0) }548 #expect(TradingMandate.principalDescriptorSha256(kind: "api_key", id: "spk_0123456789ab") == SHA256Digest.hash(Data("spw-principal-v1|api_key|spk_0123456789ab".utf8)).hex)549 }550551 @Test func revocationAndRecovery() async throws {552 let (client, t, _) = MockTransport.client(), api = MandatesAPI(client)553 t.enqueue(json: text(["mandate": try Self.record(state: "revoked", phase: "wind_down"), "cancelled": 2, "signerRevoked": false, "signerError": "signer unreachable"]))554 let r = try await api.revoke(id: "4b9d1c2e-3f40-4a5b-8c6d-000000000101", cancelOpenOrders: true, detail: "fin de test")555 #expect(t.last?.path == "/api/v1/mandates/4b9d1c2e-3f40-4a5b-8c6d-000000000101/revoke" && t.last?.body == ["cancelOpenOrders": true, "detail": "fin de test"] && t.last?.body?["assertion"] == nil)556 #expect(r.cancelled == 2 && r.signerRevoked == false && r.signerError == "signer unreachable" && r.mandate.phase == "wind_down" && !r.mandate.isActive)557 t.enqueue(json: #"{"adopted":["a"],"revoked":[],"pending":["b"]}"#)558 #expect(try await api.recoverQuoting().pending == ["b"])559 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/mandates/recover-quoting")560 }561}562563// MARK: orders564565@Suite struct ExecutionOrdersTests {566 static func fx(_ k: String) throws -> JSONValue { try #require(try TestResources.json("execution-orders.json")[k]) }567 static let request = OrderRequest(mode: .live, accountId: "6e0f8a44-1b7c-4f1e-9d55-0000000000b1", instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.01"), price: "68500", reduceOnly: false, tif: "gtc")568569 @Test func listAndDetail() async throws {570 let (client, t, _) = MockTransport.client(), api = OrdersAPI(client)571 t.enqueue(json: text(try Self.fx("page")))572 let p = try await api.orders(OrderFilter(mode: .live, venue: "hyperliquid", open: true, limit: 9999, cursor: "abc_-9"))573 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/trading/orders" && t.last?.query == ["mode": "live", "venue": "hyperliquid", "open": "true", "limit": "500", "cursor": "abc_-9"])574 #expect(p.nextCursor == "MTc5Mzk5NzAwMDAwMHwwYzhm" && p.orders.count == 3)575 #expect(p.orders[0].status == .partiallyFilled && p.orders[0].isOpen && !p.orders[0].status.isSuccess && p.orders[0].filled == "0.004" && p.orders[0].principal?.label == "owner:owner" && p.orders[0].reasonCode == "VENUE_FILL")576 #expect(p.orders[1].status == .unknown && p.orders[1].isOpen && p.orders[1].instrument == nil && p.orders[1].size == nil)577 #expect(p.orders[2].status == .unrecognized("SETTLING_ON_CHAIN") && p.orders[2].isOpen && !p.orders[2].isFinal)578 t.enqueue(json: text(try Self.fx("page")))579 _ = try await api.orders()580 #expect(t.last?.query == ["limit": "100"])581 t.enqueue(json: text(try Self.fx("detail")))582 let d = try await api.order("agent:7/x")583 #expect(t.last?.path == "/api/v1/trading/orders/agent:7%2Fx" || t.last?.path == "/api/v1/trading/orders/agent:7/x")584 #expect(d.order.isFinal && d.order.status.isSuccess && d.fills.first?.closedPnl == "-12.4" && d.history?.map(\.to) == [.validated, .approved, .submitting, .filled] && d.history?.last?.reason == "VENUE_FILLED" && d.history?[1].detail == "paper: nothing is signed")585 // a state and a `final` flag that disagree: never treated as final586 let odd: UnifiedOrder = try with(try Self.fx("detail")["order"]!, ["final"], false).decode()587 #expect(!odd.isFinal)588 t.enqueue(json: text(try Self.fx("positions")))589 let pos = try await api.positions(mode: .live)590 #expect(t.last?.path == "/api/v1/trading/positions" && t.last?.query == ["mode": "live"] && pos.errors == [SourceError(source: "gmx", message: "rpc timeout")] && pos.positions.first?.id.contains(":") == true)591 t.enqueue(json: text(try Self.fx("risk")))592 let r = try await api.riskOverview()593 #expect(t.last?.path == "/api/v1/trading/risk" && r.signer.signerHalted == false && r.engine.readOnly.on && r.engine.readOnly.by?.label == "system:supervisor" && !r.engine.killSwitch.on && r.capabilityLocks.first?.on == false)594 }595596 private func preview(order: JSONValue, hash: String) throws -> JSONValue { with(with(try Self.fx("previewRest"), ["order"], order), ["hash"], .string(hash)) }597598 @Test func aPreviewIsTheOrderItsHashNames() async throws {599 let v = try #require(try CanonicalVector.load("SPW-ORDER-INTENT-v1.json").first) // hyperliquid:BTC limit buy 0.0100 @ 68500.0, live, owner600 let (client, t, _) = MockTransport.client(), api = OrdersAPI(client)601 t.enqueue(json: text(try preview(order: v.object, hash: v.hashHex)))602 let p = try await api.preview(Self.request, idempotencyKey: "ui-preview-0001-abcdef")603 let r = try #require(t.last), b = try #require(r.body)604 #expect(r.method == "POST" && r.path == "/api/v1/trading/orders/preview" && r.headers["Idempotency-Key"] == "ui-preview-0001-abcdef")605 #expect(b == ["mode": "live", "accountId": "6e0f8a44-1b7c-4f1e-9d55-0000000000b1", "instrument": "hyperliquid:BTC", "side": "buy", "type": "limit", "size": "0.01", "price": "68500", "reduceOnly": false, "tif": "gtc"])606 #expect(!p.wouldExecute && p.refusals.map(\.stage) == ["lock", "risk"] && p.refusals[0].code == "execution_disabled" && p.approval.by == "owner_passkey" && p.approval.required)607 #expect(p.risk.failures == [RiskCheckFailure(id: "order_notional", observed: "685", limit: "500", detail: "order notional 685 is above the limit 500")] && p.risk.checks.count == 3 && p.mandate == nil && p.account.equity == "1200")608 #expect(try p.order.hashHex() == v.hashHex)609610 func refused(_ answer: JSONValue, req: OrderRequest = Self.request, _ c: Comment) async {611 t.enqueue(json: text(answer))612 do { _ = try await api.preview(req, idempotencyKey: "ui-preview-0001-abcdef"); Issue.record("expected a refusal: \(c)") } catch { #expect(isInconsistent(error), c) }613 }614 await refused(try preview(order: with(v.object, ["size"], "1"), hash: v.hashHex), "the order shown is not the order hashed")615 await refused(try preview(order: v.object, hash: String(repeating: "0", count: 64)), "another hash")616 let sell = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:BTC", side: "sell", type: "limit", quantity: .size("0.01"), price: "68500", reduceOnly: false, tif: "gtc")617 await refused(try preview(order: v.object, hash: v.hashHex), req: sell, "another side")618 let bigger = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.1"), price: "68500", reduceOnly: false, tif: "gtc")619 await refused(try preview(order: v.object, hash: v.hashHex), req: bigger, "another size")620 let cheaper = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.01"), price: "68000", reduceOnly: false, tif: "gtc")621 await refused(try preview(order: v.object, hash: v.hashHex), req: cheaper, "another price")622 let eth = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:ETH", side: "buy", type: "limit", quantity: .size("0.01"), price: "68500", reduceOnly: false, tif: "gtc")623 await refused(try preview(order: v.object, hash: v.hashHex), req: eth, "another instrument")624 let paper = OrderRequest(mode: .paper, accountId: nil, instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.01"), price: "68500", reduceOnly: false, tif: "gtc")625 await refused(try preview(order: v.object, hash: v.hashHex), req: paper, "another mode")626 let reduce = OrderRequest(mode: .live, accountId: nil, instrument: "hyperliquid:BTC", side: "buy", type: "limit", quantity: .size("0.01"), price: "68500", reduceOnly: true, tif: "gtc")627 await refused(try preview(order: v.object, hash: v.hashHex), req: reduce, "reduce-only")628 await refused(with(try preview(order: v.object, hash: v.hashHex), ["wouldExecute"], true), "would execute, with refusals")629 #expect(OrdersAPI.canonicalType("stop_market") == "stop" && OrdersAPI.canonicalType("stop_limit") == "stop" && OrdersAPI.canonicalType("take_profit_limit") == "take_profit" && OrdersAPI.canonicalType("market") == "market")630 }631632 @Test func placingCarriesTheKeyAndNeverMeansFilled() async throws {633 let (client, t, _) = MockTransport.client(), api = OrdersAPI(client)634 t.enqueue(json: text(try Self.fx("placed")))635 let key = APIClient.newIdempotencyKey()636 let p = try await api.place(Self.request, idempotencyKey: key)637 let r = try #require(t.last)638 #expect(r.method == "POST" && r.path == "/api/v1/trading/orders" && r.headers["Idempotency-Key"] == key && r.headers["X-SPW-CSRF"] == "1" && r.headers["Authorization"] == nil && r.body?["size"] == "0.01" && r.body?["notional"] == nil)639 #expect(p.order.status == .awaitingApproval && p.order.status.awaitsOwner && !p.order.status.isSuccess && p.order.isOpen && p.idempotent == false)640 #expect(p.approval?.approve?.path.hasSuffix("/orders/0x0123/approve") == true && p.approval?.by == "owner_passkey" && p.approval?.expiresAt == 1794000120000)641 t.enqueue(json: text(with(try Self.fx("placed"), ["order", "side"], "sell")))642 do { _ = try await api.place(Self.request, idempotencyKey: key); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) }643 let n = OrderRequest(mode: .paper, accountId: nil, instrument: "spot:ETH", side: "buy", type: "market", quantity: .notional("250"), reduceOnly: false, tif: "ioc", slippageBps: 50)644 #expect(try JSONValue.from(n) == ["mode": "paper", "instrument": "spot:ETH", "side": "buy", "type": "market", "notional": "250", "reduceOnly": false, "tif": "ioc", "slippageBps": 50])645646 t.enqueue(json: text(try Self.fx("cancelled")))647 let c = try await api.cancel(orderId: "0c8f4c9e-1f7b-4a64-8a26-000000000005", idempotencyKey: "ui-cancel-0001-abcdef")648 #expect(t.last?.method == "DELETE" && t.last?.path == "/api/v1/trading/orders/0c8f4c9e-1f7b-4a64-8a26-000000000005" && t.last?.headers["Idempotency-Key"] == "ui-cancel-0001-abcdef" && t.last?.headers["X-SPW-CSRF"] == "1")649 #expect(c.order.status == .cancelled && !c.sent && c.changed && c.order.isFinal && !c.order.status.isSuccess)650651 t.enqueue(json: text(try Self.fx("placed")))652 _ = try await api.closePosition(id: "live:hyperliquid:acct:hyperliquid:BTC", slippageBps: 40, idempotencyKey: "ui-close-0001-abcdef")653 #expect(t.last?.method == "POST" && t.last?.body == ["slippageBps": 40] && t.last?.headers["Idempotency-Key"] == "ui-close-0001-abcdef" && t.last?.path.hasSuffix("/close") == true && t.last?.path.hasPrefix("/api/v1/trading/positions/live:hyperliquid:acct") == true)654 t.enqueue(json: text(try Self.fx("placed")))655 _ = try await api.reducePosition(id: "p1", fraction: "0.25", idempotencyKey: "ui-reduce-0001-abcdef")656 #expect(t.last?.path == "/api/v1/trading/positions/p1/reduce" && t.last?.body == ["fraction": "0.25"])657 let before = t.requests.count658 for bad in ["0", "1.5", "-0.1", "abc", "0.0"] { await #expect(throws: APIError.self) { _ = try await api.reducePosition(id: "p1", fraction: bad, idempotencyKey: "ui-reduce-0001-abcdef") } }659 #expect(t.requests.count == before)660 }661662 @Test func commandsAndDefaults() async throws {663 let (client, t, _) = MockTransport.client(), api = OrdersAPI(client)664 t.enqueue(json: text(try Self.fx("commandControl")))665 let a = try await api.command(text: "CANCEL ALL", mode: .paper, dryRun: true, idempotencyKey: "ui-cmd-0001-abcdefgh")666 #expect(t.last?.path == "/api/v1/trading/commands" && t.last?.body == ["text": "CANCEL ALL", "mode": "paper", "dryRun": true] && t.last?.headers["Idempotency-Key"] == "ui-cmd-0001-abcdefgh")667 #expect(a.kind == "control" && a.executed == false && a.raw["orders"]?.arrayValue?.count == 1 && a.placedOrder == nil)668 let v = try #require(try CanonicalVector.load("SPW-ORDER-INTENT-v1.json").first)669 t.enqueue(json: text(["kind": "order", "command": "LONG", "mode": "live", "dryRun": true, "executed": false, "order": v.object, "hash": .string(v.hashHex), "attached": []]))670 let dry = try await api.command(text: "LONG BTC-PERP 500 x2", mode: .live, accountId: "6e0f8a44-1b7c-4f1e-9d55-0000000000b1", dryRun: true, idempotencyKey: "ui-cmd-0002-abcdefgh")671 #expect(try dry.canonicalOrder?.hashHex() == dry.hash && t.last?.body?["accountId"] == "6e0f8a44-1b7c-4f1e-9d55-0000000000b1")672 t.enqueue(json: text(["kind": "order", "command": "LONG", "mode": "live", "dryRun": false, "executed": true, "order": try Self.fx("placed")["order"]!, "canonical": v.object, "hash": .string(v.hashHex), "idempotent": false, "approval": nil, "attached": []]))673 do { _ = try await api.command(text: "LONG BTC-PERP 500 x2", mode: .live, dryRun: true, idempotencyKey: "ui-cmd-0003-abcdefgh"); Issue.record("expected a refusal") } catch { #expect(isInconsistent(error)) } // a dry run answered as executed674 t.enqueue(json: #"{"defaults":{"spotNetwork":"base","perpNetworkByVenue":{"hyperliquid":"mainnet"},"maxSlippageBps":50}}"#)675 let d = try await api.commandDefaults()676 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/developer/command-defaults" && d.spotNetwork == "base" && d.maxSlippageBps == 50 && d.perpLeverage == nil)677 t.enqueue(json: #"{"defaults":{"spotNetwork":"base","perpNetworkByVenue":{"hyperliquid":"mainnet"},"maxSlippageBps":50}}"#)678 _ = try await api.setCommandDefaults(d)679 #expect(t.last?.method == "PUT" && t.last?.body == ["defaults": ["spotNetwork": "base", "perpNetworkByVenue": ["hyperliquid": "mainnet"], "maxSlippageBps": 50]])680 }681}682683// MARK: markets684685@Suite struct ExecutionMarketsTests {686 static func fx(_ k: String) throws -> JSONValue { try #require(try TestResources.json("execution-markets.json")[k]) }687688 @Test func theExplorerKeepsSourceTimestampAndStaleness() async throws {689 let (client, t, _) = MockTransport.client(), api = MarketsAPI(client)690 t.enqueue(json: text(try Self.fx("hubList")))691 let l = try await api.list(HubQuery(kind: "perp", venue: "hyperliquid", category: "crypto", search: " btc ", tradable: true, sort: .openInterest, descending: false, limit: 5000, offset: 10))692 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/markets-hub" && t.last?.query == ["kind": "perp", "venue": "hyperliquid", "category": "crypto", "q": "btc", "tradable": "yes", "sort": "openInterest", "dir": "asc", "limit": "500", "offset": "10"])693 let btc = l.rows[0], eth = l.rows[1]694 #expect(btc.price == "68620.5" && btc.priceKind == "mark" && btc.source == "hyperliquid" && btc.sourceTs == 1793999999000 && !btc.stale && btc.funding?.annualised == "0.1095" && btc.tradable)695 #expect(eth.price == nil && eth.stale && eth.sourceTs == nil && !eth.tradable && eth.tradableReason == "no price" && eth.source == "market-data" && eth.networks?.first?.network == "base") // no price is nil, never 0696 #expect(l.errors == [SourceError(source: "gmx", message: "rpc timeout")] && l.venues[1].status == "error" && l.counts?.stale == 1 && l.cache?.ttlMs == 5000)697 t.enqueue(json: text(try Self.fx("hubList")))698 _ = try await api.list()699 #expect(t.last?.query == ["sort": "volume", "dir": "desc", "limit": "50", "offset": "0"])700 t.enqueue(json: text(try Self.fx("underlyings")))701 #expect(try await api.underlyings().map(\.comparable) == [true, false])702 #expect(t.last?.path == "/api/v1/markets-hub/underlyings")703 t.enqueue(json: text(try Self.fx("underlying")))704 _ = try await api.underlying("BTC")705 #expect(t.last?.path == "/api/v1/markets-hub/underlyings/BTC")706 }707708 @Test func theComparatorIsAnEstimateWithItsReasons() async throws {709 let (client, t, _) = MockTransport.client(), api = MarketsAPI(client)710 t.enqueue(json: text(try Self.fx("compare")))711 let c = try await api.compare(CompareQuery(underlying: "BTC", side: "long", notional: "1000", leverage: "2", horizonHours: "24"))712 #expect(t.last?.path == "/api/v1/markets-hub/compare" && t.last?.query == ["underlying": "BTC", "side": "long", "notional": "1000", "leverage": "2", "horizonHours": "24"])713 let hl = c.rows[0], gmx = c.rows[1]714 #expect(hl.fees?.source == "venue fee schedule" && hl.fees?.asOf == "2026-11-01" && hl.price?.mark == "68620.5" && hl.depth?.first?.askComplete == false)715 #expect(hl.cost?.entryFeeUsd?.value == "0.45" && hl.cost?.exitSlippageUsd?.value == nil && hl.cost?.exitSlippageUsd?.reason == "exit depth unknown" && hl.cost?.totalCostUsd?.value == nil && hl.cost?.missing == ["exitSlippageUsd"]) // no partial total716 #expect(gmx.cost == nil && gmx.error == "rpc timeout" && gmx.stale && !gmx.tradable && gmx.price?.mark == nil)717 #expect(c.discrepancies.first?.netEdgeEstimateBps == nil && c.discrepancies.first?.actionableFromWallet == false && c.discrepancies.first?.risks.first?.code == "execution" && c.texts.disclaimer == "An estimate, not an offer." && c.warnings == ["gmx could not be read"])718 t.enqueue(json: text(with(try Self.fx("compare"), ["underlying"], "ETH")))719 await #expect { _ = try await api.compare(CompareQuery(underlying: "BTC", side: "long", notional: "1000", leverage: "2", horizonHours: "24", liquidity: "maker", minNetEdgeBps: "5")) } throws: { isInconsistent($0) }720 #expect(t.last?.query["liquidity"] == "maker" && t.last?.query["minNetEdgeBps"] == "5")721 }722723 @Test func privateMarketsAreDisplayOnlyWithSourcedValuations() async throws {724 let (client, t, _) = MockTransport.client(), api = MarketsAPI(client)725 let market = try Self.fx("privateMarket"), env = try Self.fx("privateEnvelope")726 let unreviewed = with(with(with(market, ["valuation"], try Self.fx("privateUnreviewed")["valuation"]!), ["review"], try Self.fx("privateUnreviewed")["review"]!), ["status"], "delisted")727 t.enqueue(json: text(with(env, ["markets"], [market, unreviewed])))728 let l = try await api.privateMarkets(delisted: true, size: "2.5", side: "short")729 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/private-markets" && t.last?.query == ["delisted": "true", "size": "2.5", "side": "short"])730 let m = l.markets[0], u = l.markets[1]731 #expect(!m.tradable && m.notTradable?.code == "builder_dex_read_only" && l.notice.tradable == false && l.notice.text == "These contracts cannot be traded from this wallet.")732 #expect(m.valuation.syntheticPrice.value == "412.5" && m.valuation.syntheticPrice.source == "hyperliquid" && m.valuation.syntheticPrice.ts == 1793999999000 && m.valuation.syntheticPrice.priceKind == "mark")733 #expect(m.valuation.impliedValuation.isDerived && m.valuation.impliedValuation.formula == "price × 1e9" && m.valuation.impliedValuation.formulaId == "valuation_billions" && m.valuation.impliedValuation.formulaSource?.quote == "1 unit = USD 1 billion of valuation")734 #expect(m.valuation.notionalExposure.hypothetical == true && m.valuation.contractMarketValue.formula == "open interest × price" && m.valuation.lastPrivateValuation?.kind == "tender" && m.valuation.lastPrivateValuation?.confidence == "medium" && m.valuation.caveats.first?.code == "synthetic")735 #expect(m.market.mid?.value == nil && m.market.mid?.stale == true && m.market.funding?.intervalSec == 3600 && m.contract.unit.kind == "valuation_usd_billions")736 // expiry of the contract sheet737 #expect(m.review.isReviewed && m.review.validUntil == "2026-12-01" && m.review.isExpired(at: Date(timeIntervalSince1970: 1_794_000_000)) == false && m.review.isExpired(at: Date(timeIntervalSince1970: 1_800_000_000)) == true)738 #expect(!u.review.isReviewed && u.review.isExpired(at: Date(timeIntervalSince1970: 1_794_000_000)) == true && u.review.reasons == ["sheet expired"])739 #expect(!u.valuation.impliedValuation.isDerived && u.valuation.impliedValuation.value == nil && u.valuation.impliedValuation.reasonCode == "not_reviewed" && u.valuation.contractMarketValue.formula == nil && u.valuation.premiumDiscount.premiumBps == nil && u.valuation.syntheticPrice.priceKind == "frozen mark")740 #expect(l.excluded?.first?.reason == "no reviewed sheet" && l.companies.first?.divergence?.first?.spreadBps == "0" && l.venuesWithoutAdapter?.first?.venue == "other")741 t.enqueue(json: text(with(env, ["markets"], [])))742 _ = try await api.privateMarkets()743 #expect(t.last?.query == [:])744745 let detail: JSONValue = ["market": market, "book": ["bids": [["412", "3"]], "asks": [], "ts": 1793999999000, "stale": false, "source": "hyperliquid"], "candles": ["error": "no candles"], "references": [market["valuation"]!["lastPrivateValuation"]!],746 "company": env["companies"]![0]!, "sameCompany": [["id": "hyperliquid:xyz:SPACEX", "platform": "XYZ", "price": ["value": "101", "source": "hyperliquid", "ts": 1, "stale": true], "unit": ["kind": "usd_per_share", "label": "USD per share"], "review": "under_review"]],747 "notice": env["notice"]!, "position": ["side": "long", "size": "1"], "ts": 1794000000000]748 t.enqueue(json: text(detail))749 let d = try await api.privateMarket(id: "hyperliquid:vntl:SPACEX", size: "1", side: "long", interval: "1d", limit: 900)750 #expect(t.last?.path == "/api/v1/private-markets/hyperliquid:vntl:SPACEX" && t.last?.query == ["size": "1", "side": "long", "interval": "1d", "limit": "500"])751 #expect(d.sameCompany?.first?.review == "under_review" && d.references.count == 1 && d.candles?["error"] == "no candles" && d.market.id == "hyperliquid:vntl:SPACEX")752 t.enqueue(json: text(detail))753 await #expect { _ = try await api.privateMarket(id: "hyperliquid:vntl:OPENAI") } throws: { isInconsistent($0) }754 let company: JSONValue = ["company": ["slug": "spacex", "name": "SpaceX", "note": nil], "contracts": [market], "delisted": [unreviewed], "references": [], "lastPrivateValuation": nil, "divergence": [], "merged": nil,755 "mergedReason": "contracts of different venues are different instruments: no average, no blended price, no cross-fill", "venues": env["venues"]!, "notice": env["notice"]!, "position": ["side": "long", "size": "1"], "ts": 1794000000000, "source": "venue"]756 t.enqueue(json: text(company))757 let c = try await api.privateCompany(slug: "spacex")758 #expect(t.last?.path == "/api/v1/private-markets/companies/spacex" && c.contracts.count == 1 && c.delisted.first?.status == "delisted" && c.mergedReason?.contains("no average") == true)759 }760761 @Test func marketData() async throws {762 let (client, t, _) = MockTransport.client(), api = MarketsAPI(client)763 t.enqueue(json: text(try Self.fx("candles")))764 let c = try await api.candles(symbol: "BTC", interval: "1h", limit: 99999, until: 1793999999000)765 #expect(t.last?.path == "/api/v1/market-data/candles" && t.last?.query == ["symbol": "BTC", "interval": "1h", "limit": "5000", "until": "1793999999000"])766 #expect(c.bars.first?["source"] == "binance" && c.bars.first?["close"] == "68620" && c.rule.contains("never a blend") && c.priority == ["binance", "coinbase"])767 t.enqueue(json: text(try Self.fx("candles")))768 await #expect { _ = try await api.candles(symbol: "ETH", interval: "1h") } throws: { isInconsistent($0) }769 t.enqueue(json: text(try Self.fx("marketDataStatus")))770 let s = try await api.marketDataStatus()771 #expect(t.last?.path == "/api/v1/market-data/status" && s.quality.first?.fresh == true && s.quality.first?.status == "ok" && s.symbols == ["BTC", "ETH"])772 }773}774775// MARK: developer776777@Suite struct ExecutionDeveloperTests {778 static func fx(_ k: String) throws -> JSONValue { try #require(try TestResources.json("execution-developer.json")[k]) }779 static let statedExpiry = 1_795_000_000_000780 static let now = Date(timeIntervalSince1970: 1_794_999_000)781 static func prepared(_ v: CanonicalVector, intent: JSONValue? = nil, sha: String? = nil, opts: JSONValue? = nil, expiresAt: Int = statedExpiry) -> String {782 text(["intentId": (intent ?? v.object)["intentId"]!, "intent": intent ?? v.object, "sha256": .string(sha ?? v.hashHex), "expiresAt": .int(Int64(expiresAt)), "options": opts ?? options(hashHex: v.hashHex)])783 }784 static let request = APIKeyCreateRequest(name: " bot-1 ", scopes: ["positions:manage", "orders:read", "orders:execute", "orders:prepare", "orders:cancel", "orders:read"], expiresInDays: 30,785 limits: APIKeyLimits(maxOrderNotionalUsd: 1500.5, maxDailyNotionalUsd: 100000000),786 restrictions: APIKeyRestrictions(networks: ["mainnet"], venues: ["hyperliquid"], instruments: ["hyperliquid:ETH", "hyperliquid:BTC"], ipAllow: ["2001:db8::1", "203.0.113.0/24"]),787 rateLimitPerMin: 600, mandateId: "4b9d1c2e-3f40-4a5b-8c6d-000000000101")788 static func issuedKey(_ k: JSONValue, expiresAt: Int) -> JSONValue {789 ["id": k["id"]!, "name": k["name"]!, "status": "active", "scopes": k["scopes"]!, "limits": k["limits"]!, "restrictions": k["restrictions"]!, "rateLimitPerMin": k["rateLimitPerMin"]!, "mandateId": k["mandateId"]!, "inertScopes": [], "rotatedFrom": nil,790 "createdAt": 1794918896789, "expiresAt": .int(Int64(expiresAt)), "revokedAt": nil, "revokedReason": nil, "lastUsedAt": nil, "lastUsedIp": nil]791 }792 static let token = "spw_live_spk_a1b2c3d4e5f6_AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"793794 @Test func listsDecode() async throws {795 let (client, t, _) = MockTransport.client(), api = DeveloperAPI(client)796 t.enqueue(json: text(try Self.fx("keys")))797 let l = try await api.keys()798 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1/developer/keys")799 #expect(l.keys.first?.isActive == true && l.keys.first?.limits.maxOrderNotionalUsd.value == nil && l.keys.first?.limits.maxDailyNotionalUsd.value == 2500.5 && l.keys.first?.restrictions.venues == ["hyperliquid"] && l.keys.first?.mandateId == nil)800 #expect(l.scopes.last?.execution == true && l.bounds.maxKeys == 50 && l.execution?.liveEnabled == false)801 t.enqueue(json: text(try Self.fx("usage")))802 let u = try await api.usage(keyId: "spk_0123456789ab", limit: 5000)803 #expect(t.last?.path == "/api/v1/developer/usage" && t.last?.query == ["key": "spk_0123456789ab", "limit": "500"] && u.perKey.first?.p95Ms == 31 && u.items.first?.route == "/api/v1/trading/orders")804 t.enqueue(json: text(try Self.fx("status")))805 let s = try await api.status()806 #expect(t.last?.path == "/api/v1/developer/status" && s.services.last?.ok == false && s.services.last?.lastOkAt == 1793999000000 && s.capabilities?.first?.id == "deriv_live_mainnet" && s.api.implemented == 48)807 }808809 @Test func creatingAKeyIsBoundToEveryPermissionRequested() async throws {810 let v = try vector("execution-apikey-intent.json", "create-trading-fractional-limits-restrictions-mandate")811 let (client, t, _) = MockTransport.client(), api = DeveloperAPI(client), auth = StubAuthenticator()812 t.enqueue(json: Self.prepared(v))813 let a = try await api.prepareCreate(Self.request, now: Self.now)814 let r = try #require(t.last), b = try #require(r.body)815 #expect(r.method == "POST" && r.path == "/api/v1/developer/keys/prepare" && b["expiresInDays"] == 30 && b["limits"] == ["maxOrderNotionalUsd": .double(1500.5), "maxDailyNotionalUsd": 100000000] && b["mandateId"] == "4b9d1c2e-3f40-4a5b-8c6d-000000000101" && b["rateLimitPerMin"] == 600)816 #expect(a.approval.digest.hex == v.hashHex && a.intent.key?.scopes == ["orders:cancel", "orders:execute", "orders:prepare", "orders:read", "positions:manage"] && a.intent.key?.id == "spk_a1b2c3d4e5f6")817818 func refused(_ json: String, req r: APIKeyCreateRequest = Self.request, now: Date = Self.now, _ check: (Error) -> Bool, _ c: Comment) async {819 t.enqueue(json: json)820 do { _ = try await api.prepareCreate(r, now: now); Issue.record("expected a refusal: \(c)") } catch { #expect(check(error), "\(c): \(error)") }821 }822 func req(scopes: [String] = Self.request.scopes, days: Int = 30, limits: APIKeyLimits = Self.request.limits, restrictions: APIKeyRestrictions = Self.request.restrictions, rate: Int = 600, mandate: String? = "4b9d1c2e-3f40-4a5b-8c6d-000000000101") -> APIKeyCreateRequest {823 APIKeyCreateRequest(name: "bot-1", scopes: scopes, expiresInDays: days, limits: limits, restrictions: restrictions, rateLimitPerMin: rate, mandateId: mandate)824 }825 await refused(Self.prepared(v), req: req(scopes: ["orders:read"]), isInconsistent, "the intent grants scopes that were not requested")826 await refused(Self.prepared(v), req: req(days: 7), isInconsistent, "another expiry")827 await refused(Self.prepared(v), req: req(limits: APIKeyLimits(maxOrderNotionalUsd: 1500, maxDailyNotionalUsd: 100000000)), isInconsistent, "another per-order limit")828 await refused(Self.prepared(v), req: req(limits: APIKeyLimits(maxOrderNotionalUsd: 1500.5, maxDailyNotionalUsd: nil)), isInconsistent, "a daily limit where none was… or none where one was requested")829 await refused(Self.prepared(v), req: req(restrictions: APIKeyRestrictions(networks: ["mainnet"], venues: ["hyperliquid"], instruments: ["hyperliquid:BTC"], ipAllow: ["2001:db8::1", "203.0.113.0/24"])), isInconsistent, "wider instruments")830 await refused(Self.prepared(v), req: req(restrictions: APIKeyRestrictions(networks: ["mainnet"], venues: ["hyperliquid"], instruments: ["hyperliquid:ETH", "hyperliquid:BTC"], ipAllow: ["203.0.113.0/24"])), isInconsistent, "another address list")831 await refused(Self.prepared(v), req: req(rate: 120), isInconsistent, "another rate")832 await refused(Self.prepared(v), req: req(mandate: nil), isInconsistent, "a mandate binding that was not requested")833 await refused(Self.prepared(try vector("execution-apikey-intent.json", "rotate")), isInconsistent, "a rotation answered to a creation")834 await refused(Self.prepared(v, sha: String(repeating: "0", count: 64)), isInconsistent, "another stated hash")835 var badHash = Data(hex: v.hashHex)!; badHash[0] ^= 0x80836 await refused(Self.prepared(v, opts: options(hashHex: badHash.hex)), { $0 as? ApprovalError == .challengeMismatch }, "a challenge that is not the hash")837 await refused(Self.prepared(v, intent: with(v.object, ["key", "superuser"], true)), isUnsupported, "an unknown field")838 await refused(Self.prepared(v), now: Date(timeIntervalSince1970: 1_795_000_000), { $0 as? ApprovalError == .expired }, "expired")839 // an intent prepared for another origin (the vectors are for wallet.example.test; this client is another wallet)840 let otherClient = APIClient(configuration: APIConfiguration(origin: URL(string: "https://other.example.test")!, rpId: rp, userAgent: "t"), tokens: InMemoryTokenStore("x"), transport: t)841 t.enqueue(json: Self.prepared(v))842 await #expect { _ = try await DeveloperAPI(otherClient).prepareCreate(Self.request, now: Self.now) } throws: { isInconsistent($0) }843 #expect(auth.challenges.isEmpty)844845 // step 2: the secret is in this answer only846 let expires = 1797597296789 // 2026-12-18T12:34:56.789Z847 t.enqueue(json: text(["key": Self.issuedKey(v.object["key"]!, expiresAt: expires), "secret": .string(Self.token)]))848 let issued = try await api.create(a, with: auth, now: Self.now)849 #expect(t.last?.path == "/api/v1/developer/keys" && t.last?.body?["intentId"] == v.object["intentId"] && t.last?.body?["assertion"] != nil && auth.challenges == [Data(hex: v.hashHex)!.base64URL])850 #expect(issued.discrepancies.isEmpty && issued.key.id == "spk_a1b2c3d4e5f6" && issued.secret.reveal() == Self.token)851 // …and it does not leak through any textual path852 var dumped = ""853 dump(issued, to: &dumped); dump(issued.secret, to: &dumped)854 for s in ["\(issued)", "\(issued.secret)", String(describing: issued.secret), String(reflecting: issued.secret), String(reflecting: issued), dumped, "\(Mirror(reflecting: issued.secret).children.map { "\($0)" })", "\([issued.secret])", "\(Optional(issued.secret) as Any)"] {855 #expect(!s.contains("AAAA") && !s.contains("spw_live_"), "leaked in: \(s)")856 }857 #expect("\(issued.secret)" == "<redacted>")858 // a created key that is NOT what was approved is reported, with its secret still returned (it exists and must be revoked)859 t.enqueue(json: text(["key": with(Self.issuedKey(v.object["key"]!, expiresAt: expires + 86_400_000), ["scopes"], ["orders:execute", "wallet:read"]), "secret": .string(Self.token)]))860 let odd = try await api.create(a, with: auth, now: Self.now)861 #expect(odd.discrepancies == ["scopes", "expiresAt"] && odd.secret.reveal() == Self.token)862 await #expect(throws: ApprovalError.expired) { _ = try await api.create(a, with: auth, now: Date(timeIntervalSince1970: 1_795_000_000)) }863 }864865 @Test func rotationUpdateNarrowingAndRevocation() async throws {866 let (client, t, _) = MockTransport.client(), api = DeveloperAPI(client), auth = StubAuthenticator()867 let rv = try vector("execution-apikey-intent.json", "rotate")868 t.enqueue(json: Self.prepared(rv))869 let ra = try await api.prepareRotate(id: "spk_0123456789ab", now: Self.now)870 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/rotate/prepare" && ra.intent.newKeyId == "spk_ba9876543210")871 t.enqueue(json: Self.prepared(rv))872 await #expect { _ = try await api.prepareRotate(id: "spk_ffffffffffff", now: Self.now) } throws: { isInconsistent($0) }873 let newKey = with(with(try Self.fx("keys")["keys"]![0]!, ["id"], "spk_ba9876543210"), ["rotatedFrom"], "spk_0123456789ab")874 t.enqueue(json: text(["key": newKey, "secret": "spw_live_spk_ba9876543210_BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB", "revoked": "spk_0123456789ab", "mandate": ["carried": false, "mandateId": "m", "code": "mandate_principal_mismatch"]]))875 let rot = try await api.rotate(ra, with: auth, now: Self.now)876 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/rotate" && t.last?.body?["intentId"] == rv.object["intentId"] && rot.revoked == "spk_0123456789ab" && rot.mandate?["carried"] == false && rot.discrepancies.isEmpty && !"\(rot)".contains("BBBB"))877878 let uv = try vector("execution-apikey-intent.json", "update-widening-scopes-limits-expiry")879 let changes = APIKeyChanges(scopes: ["orders:read", "markets:read", "orders:prepare", "orders:read"], expiresAt: "2027-03-01T00:00:00.000Z", limits: APIKeyLimits(maxOrderNotionalUsd: 2500, maxDailyNotionalUsd: nil), rateLimitPerMin: 240)880 t.enqueue(json: Self.prepared(uv))881 let ua = try await api.prepareUpdate(id: "spk_0123456789ab", changes: changes, now: Self.now)882 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/update/prepare" && t.last?.body?["changes"]?["limits"] == ["maxOrderNotionalUsd": 2500, "maxDailyNotionalUsd": nil] && t.last?.body?["changes"]?["mandateId"] == nil)883 #expect(ua.intent.widening == ["scopes", "expiresAt", "limits", "rateLimitPerMin"])884 t.enqueue(json: Self.prepared(uv))885 await #expect { _ = try await api.prepareUpdate(id: "spk_0123456789ab", changes: APIKeyChanges(scopes: ["markets:read"]), now: Self.now) } throws: { isInconsistent($0) }886 t.enqueue(json: text(["key": try Self.fx("keys")["keys"]![0]!]))887 _ = try await api.update(ua, with: auth, now: Self.now)888 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/update" && t.last?.body?["intentId"] == uv.object["intentId"] && t.last?.body?["assertion"] != nil && t.last?.body?["changes"] == nil)889890 // binding a mandate / unbinding it: three distinct states of one member891 let bind = try vector("execution-apikey-intent.json", "update-bind-mandate")892 t.enqueue(json: Self.prepared(bind))893 _ = try await api.prepareUpdate(id: "spk_a1b2c3d4e5f6", changes: APIKeyChanges(mandate: .bind("4b9d1c2e-3f40-4a5b-8c6d-000000000101")), now: Self.now)894 #expect(t.last?.body == ["changes": ["mandateId": "4b9d1c2e-3f40-4a5b-8c6d-000000000101"]])895 t.enqueue(json: Self.prepared(bind))896 await #expect { _ = try await api.prepareUpdate(id: "spk_a1b2c3d4e5f6", changes: APIKeyChanges(mandate: .unbind), now: Self.now) } throws: { isInconsistent($0) }897 let unbind = try vector("execution-apikey-intent.json", "update-unbind-mandate-rename-restrictions")898 t.enqueue(json: Self.prepared(unbind))899 let un = try await api.prepareUpdate(id: "spk_a1b2c3d4e5f6", changes: APIKeyChanges(name: " bot-1 (étroit) ", restrictions: APIKeyRestrictions(networks: [], venues: ["hyperliquid", "gmx", "gmx"], instruments: [], ipAllow: []), mandate: .unbind), now: Self.now)900 #expect(un.intent.changes?.mandate == .unbind && un.intent.widening == ["restrictions.venues"] && t.last?.body?["changes"]?["mandateId"] == .null)901902 t.enqueue(json: text(["key": try Self.fx("keys")["keys"]![0]!]))903 _ = try await api.narrow(id: "spk_0123456789ab", changes: APIKeyChanges(rateLimitPerMin: 30))904 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/update" && t.last?.body == ["changes": ["rateLimitPerMin": 30]])905 t.enqueue(status: 403, json: #"{"error":"passkey_required","message":"this change widens the key (scopes): it needs a passkey approval"}"#)906 do { _ = try await api.narrow(id: "spk_0123456789ab", changes: APIKeyChanges(scopes: ["orders:execute"])); Issue.record("expected 403") } catch let e as APIError { #expect(e.code == "passkey_required") }907 t.enqueue(json: text(["key": with(with(try Self.fx("keys")["keys"]![0]!, ["status"], "revoked"), ["revokedReason"], "leaked")]))908 let rk = try await api.revoke(id: "spk_0123456789ab", reason: " leaked ")909 #expect(t.last?.path == "/api/v1/developer/keys/spk_0123456789ab/revoke" && t.last?.body == ["reason": "leaked"] && !rk.isActive && rk.revokedReason == "leaked")910 }911912 @Test func webhooks() async throws {913 let (client, t, _) = MockTransport.client(), api = DeveloperAPI(client)914 let hook = try Self.fx("webhooks")["webhooks"]![0]!915 t.enqueue(json: text(try Self.fx("webhooks")))916 let l = try await api.webhooks()917 #expect(t.last?.path == "/api/v1/developer/webhooks" && l.webhooks.first?.hasSecret == true && l.deliveries.first?.state == "failed" && l.retry?.backoffSec == [5, 30, 120, 600] && l.events.first?.event == "order.updated")918 t.enqueue(json: text(["deliveries": try Self.fx("webhooks")["deliveries"]!]))919 _ = try await api.deliveries(webhookId: "wh_0123456789ab", limit: 999)920 #expect(t.last?.path == "/api/v1/developer/webhooks/deliveries" && t.last?.query == ["webhook": "wh_0123456789ab", "limit": "200"])921 t.enqueue(json: text(["webhook": hook, "secret": "whsec_CCCCCCCCCCCCCCCC"]))922 let c = try await api.createWebhook(url: "https://hooks.example.test/spw", events: ["order.updated"], label: "ops")923 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/developer/webhooks" && t.last?.body == ["url": "https://hooks.example.test/spw", "events": ["order.updated"], "label": "ops"])924 #expect(c.secret.reveal() == "whsec_CCCCCCCCCCCCCCCC" && !"\(c)".contains("CCCC") && !String(reflecting: c).contains("CCCC"))925 t.enqueue(json: text(["webhook": hook]))926 _ = try await api.updateWebhook(id: "wh_0123456789ab", enabled: false, idempotencyKey: "ui-hook-0001-abcdefg")927 #expect(t.last?.path == "/api/v1/developer/webhooks/wh_0123456789ab" && t.last?.body == ["enabled": false] && t.last?.headers["Idempotency-Key"] == "ui-hook-0001-abcdefg")928 t.enqueue(json: text(["webhook": hook, "secret": "whsec_DDDDDDDDDDDDDDDD"]))929 #expect(try await api.rotateWebhookSecret(id: "wh_0123456789ab").secret.reveal() == "whsec_DDDDDDDDDDDDDDDD")930 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/developer/webhooks/wh_0123456789ab/secret")931 t.enqueue(json: #"{"ok":true}"#)932 try await api.deleteWebhook(id: "wh_0123456789ab")933 #expect(t.last?.method == "DELETE" && t.last?.path == "/api/v1/developer/webhooks/wh_0123456789ab")934 }935}936