Repository Public
1// SP Wallet Core2// File: Tests/SPWalletCoreTests/AgentsTests.swift3// Description: The Agents domain: the five canonical objects against the backend's own bytes, strict parsing, the mandate compared4// with what the owner entered, decoding of every response shape, the request contract of every endpoint, the three5// modes kept apart, and the stop paths that never ask for a passkey.6// Fixtures: Fixtures/agents-responses.json (one section per shape, written from the TypeScript named in its `_sources`),7// agents-spot-mandate-prepare.json, agents-perp-live-prepare.json, agents-withdrawals.json, agents-job.json and8// Vectors/agents-mandates.json are GENERATED by the backend's code (/tmp/spw-vectors-agents.mts, see each `_source`).9//10// Author: Simon-Pierre Boucher11// Contact: contact@spboucher.ai12import Foundation13import Testing14@testable import SPWalletCore1516private enum Fx {17 static let responses: JSONValue = try! TestResources.json("agents-responses.json")18 static let spotPrepare: JSONValue = try! TestResources.json("agents-spot-mandate-prepare.json")19 static let perpPrepare: JSONValue = try! TestResources.json("agents-perp-live-prepare.json")20 static func text(_ v: JSONValue) -> String { String(decoding: try! APICoding.encoder().encode(v), as: UTF8.self) }21 static func section(_ k: String) -> JSONValue { responses[k]! }22 static func json(_ k: String) -> String { text(section(k)) }23 static func decode<T: Decodable>(_ k: String, as t: T.Type = T.self) throws -> T { try section(k).decode(T.self) }24 /** A copy of a JSON object with one member replaced (`nil` removes it), at a dotted path. */25 static func with(_ v: JSONValue, _ path: String, _ new: JSONValue?) -> JSONValue {26 let parts = path.split(separator: ".", maxSplits: 1).map(String.init)27 switch v {28 case .object(var o):29 if parts.count == 1 { o[parts[0]] = new } else { o[parts[0]] = with(o[parts[0]] ?? .object([:]), parts[1], new) }30 return .object(o)31 case .array(var a):32 let i = Int(parts[0])!33 if parts.count == 1 { a[i] = new ?? .null } else { a[i] = with(a[i], parts[1], new) }34 return .array(a)35 default: return v36 }37 }38 static let now = Date(timeIntervalSince1970: 1_794_000_010)39 static let spotId = "5b1d6c1e-2f43-4a53-8f0a-0000000a1000"40 static var perpId: String { perpPrepare["_context"]!["agentId"]!.stringValue! }41 static var accountId: String { perpPrepare["_context"]!["accountId"]!.stringValue! }42 static func challenge(of o: some PasskeyApprovable) -> JSONValue { .string(try! o.approvalDigest().base64URL) }43}4445/** Signs nothing: records the challenges it was asked to sign and answers a well-formed assertion. */46private final class RecordingAuthenticator: PasskeyAuthenticator, @unchecked Sendable {47 private let lock = NSLock()48 private var _challenges: [String] = []49 var challenges: [String] { lock.withLock { _challenges } }50 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion {51 lock.withLock { _challenges.append(options.challenge) }52 return PasskeyAssertion(credentialId: Data("cred".utf8), clientDataJSON: Data(#"{"challenge":"\#(options.challenge)"}"#.utf8), authenticatorData: Data([1]), signature: Data([2]), userHandle: nil)53 }54 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration { throw PasskeyError.notAvailable("test") }55}5657// MARK: canonical objects5859@Suite struct AgentsCanonicalTests {60 static let rp = "wallet.spboucher.ai"61 private func bound(_ o: some PasskeyApprovable, _ v: CanonicalVector) throws {62 #expect(try o.canonicalBytes().hex == v.canonicalHex, "canonical bytes of \(v.name)")63 #expect(try o.approvalDigest().hex == v.hashHex, "hash of \(v.name)")64 _ = try ApprovalBinding.verify(o, options: PasskeyRequestOptions(challenge: Data(hex: v.hashHex)!.base64URL, rpId: Self.rp), rpId: Self.rp)65 }66 /** The lead's vectors of the domain and the domain's own (generated from routes.ts `mandateFor`, `compileToVenueMandate`, bounds of each schema). */67 private func vectors(_ domain: String) throws -> [CanonicalVector] {68 try CanonicalVector.load("\(domain).json") + CanonicalVector.load("agents-mandates.json").filter { $0.domain == domain }69 }7071 @Test func spotMandateReproducesTheBackendBytes() throws {72 let vs = try vectors("SPW-MANDATE-v1")73 #expect(vs.count >= 5)74 for v in vs { try bound(try AgentSpotMandate(served: v.object), v) }75 #expect(vs.contains { $0.name == "agents-spot-built-by-mandateFor" })76 }77 @Test func derivativeMandateReproducesTheBackendBytes() throws {78 let vs = try vectors("SPW-VENUE-MANDATE-v1")79 #expect(vs.count >= 4)80 for v in vs { try bound(try AgentVenueMandate(served: v.object), v) }81 }82 @Test func quotingMandateReproducesTheBackendBytes() throws {83 let vs = try vectors("SPW-VENUE-QUOTING-MANDATE-v1")84 #expect(vs.count >= 4)85 for v in vs { try bound(try AgentQuotingMandate(served: v.object), v) }86 }87 @Test func tradingMandateReproducesTheBackendBytesAndHash() throws {88 let vs = try vectors("SPW-TRADING-MANDATE-v1")89 #expect(vs.count >= 5)90 for v in vs {91 let t = try AgentTradingMandate(served: v.object)92 #expect(t.canonicalBytes().hex == v.canonicalHex, "canonical bytes of \(v.name)")93 #expect(t.hashHex() == v.hashHex, "hash of \(v.name)")94 }95 }96 @Test func approvalIntentReproducesTheBackendBytes() throws {97 let vs = try vectors("SPW-TRADING-MANDATE-APPROVAL-v1")98 #expect(vs.count >= 4)99 for v in vs { try bound(try AgentMandateApprovalIntent(served: v.object), v) }100 #expect(vs.contains { (try? AgentMandateApprovalIntent(served: $0.object))?.quotingSectionHash != nil })101 }102103 @Test func decimalsAreCanonicalizedLikeTheBackend() throws {104 #expect(try AgentsCanon.decimal("1.50", "x") == "1.5")105 #expect(try AgentsCanon.decimal("8000.000", "x") == "8000")106 #expect(try AgentsCanon.decimal("0.0", "x") == "0")107 #expect(try AgentsCanon.decimal("-0", "x") == "0")108 #expect(try AgentsCanon.decimal("-2.10", "x") == "-2.1")109 for bad in ["01.5", "1.", ".5", "1e3", "+1", "1,5", "", " 1", String(repeating: "9", count: 61)] {110 #expect(throws: ApprovalError.self, "\(bad)") { try AgentsCanon.decimal(bad, "x") }111 }112 #expect(throws: ApprovalError.self) { try AgentsCanon.positive("0.00", "x") }113 #expect(throws: ApprovalError.self) { try AgentsCanon.positive("-1", "x") }114 #expect(AgentsCanon.less("999.99", "1000") && AgentsCanon.less("1000.1", "1000.12") && !AgentsCanon.less("1000.12", "1000.12") && !AgentsCanon.less("20", "9.5") && AgentsCanon.less("0.5", "0.51"))115 }116117 @Test func stableJSONWritesWhatJSONStringifyWrites() throws {118 let v: JSONValue = ["b": [1, "a/b", nil, true], "a": ["é\"\\\n\u{01}": "x"], "A": -3]119 #expect(try AgentsCanon.stableJSON(v, "x") == #"{"A":-3,"a":{"é\"\\\n\u0001":"x"},"b":[1,"a/b",null,true]}"#)120 #expect(throws: ApprovalError.self) { try AgentsCanon.stableJSON(["x": .double(1.5)], "x") }121 }122123 @Test func anUnknownFieldIsARefusalInEveryObject() throws {124 let all = try CanonicalVector.load("agents-mandates.json")125 func first(_ d: String) -> JSONValue { all.first { $0.domain == d }!.object }126 let spot = first("SPW-MANDATE-v1"), venue = first("SPW-VENUE-MANDATE-v1"), quoting = first("SPW-VENUE-QUOTING-MANDATE-v1"), trading = first("SPW-TRADING-MANDATE-v1"), intent = first("SPW-TRADING-MANDATE-APPROVAL-v1")127 #expect(throws: ApprovalError.self) { try AgentSpotMandate(served: Fx.with(spot, "recipient", "0x0000000000000000000000000000000000000001")) }128 #expect(throws: ApprovalError.self) { try AgentVenueMandate(served: Fx.with(venue, "withdrawTo", "0x1")) }129 #expect(throws: ApprovalError.self) { try AgentVenueMandate(served: Fx.with(venue, "instruments.0.unlimited", true)) }130 #expect(throws: ApprovalError.self) { try AgentQuotingMandate(served: Fx.with(quoting, "rate.extra", 1)) }131 #expect(throws: ApprovalError.self) { try AgentTradingMandate(served: Fx.with(trading, "accounts.0.note", "x")) }132 #expect(throws: ApprovalError.self) { try AgentTradingMandate(served: Fx.with(trading, "stopConditions.0.kind", "never")) }133 #expect(throws: ApprovalError.self) { try AgentMandateApprovalIntent(served: Fx.with(intent, "signer.extra", "x")) }134 // a missing field is a refusal too: there is no default limit135 for k in ["maxOrder", "maxDaily", "maxOrdersPerDay", "maxSlippageBps", "expiresAt", "assets", "vault", "strategySha256"] { #expect(throws: ApprovalError.self, "\(k)") { try AgentSpotMandate(served: Fx.with(spot, k, nil)) } }136 for k in ["instruments", "maxOrderNotional", "maxGrossExposure", "maxOrdersPerDay", "maxOrdersPerHour", "maxDailyTurnover", "floorEquity", "expiresAt", "ackSha256"] { #expect(throws: ApprovalError.self, "\(k)") { try AgentVenueMandate(served: Fx.with(venue, k, nil)) } }137 }138139 @Test func whatTheBackendSchemaRefusesIsRefused() throws {140 let all = try CanonicalVector.load("agents-mandates.json")141 let spot = all.first { $0.name == "agents-spot-cash-and-native" }!.object, venue = all.first { $0.domain == "SPW-VENUE-MANDATE-v1" }!.object142 let bad: [(String, JSONValue)] = [("provider", "uniswap"), ("vaultIndex", 0), ("v", 2), ("maxOrdersPerDay", 501), ("maxSlippageBps", 501), ("maxOrder.native", "01"), ("maxOrder.0x0000000000000000000000000000000000000009", "1"),143 ("maxOrder.native", "99999999999999999999"), ("expiresAt", .int(1_794_000_000 + 91 * 86_400)), ("label", ""), ("strategySha256", "C3"), ("vaultIndex", "3")]144 for (k, v) in bad { #expect(throws: ApprovalError.self, "\(k)") { try AgentSpotMandate(served: Fx.with(spot, k, v)) } }145 let badVenue: [(String, JSONValue)] = [("venue", "dydx"), ("network", "devnet"), ("account", "0x70997970C51812dc3A010C7d01b50e0d17dc79C8"), ("instruments.0.maxLeverage", 21), ("instruments.0.maxPositionNotional", "0"),146 ("maxOrderNotional", "-5"), ("maxOrderNotional", 1000), ("maxOrdersPerHour", 61), ("expiresAt", .int(1_794_000_000 + 31 * 86_400)), ("instruments.1", Fx.with(venue, "x", nil)["instruments"]![0]!)]147 for (k, v) in badVenue { #expect(throws: ApprovalError.self, "\(k)") { try AgentVenueMandate(served: Fx.with(venue, k, v)) } }148 }149150 @Test func changingAnyLimitChangesTheDigest() throws {151 let all = try CanonicalVector.load("agents-mandates.json")152 let spot = all.first { $0.name == "agents-spot-cash-and-native" }!.object, base = try AgentSpotMandate(served: spot).approvalDigest()153 for (k, v) in [("maxOrder.native", JSONValue.string("7142857100000001")), ("maxDaily.native", "28571428500000001"), ("maxOrdersPerDay", 13), ("maxSlippageBps", 151), ("expiresAt", 1_796_592_001), ("vault", "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A66"),154 ("network", "arbitrum"), ("vaultIndex", 4), ("strategySha256", .string(String(repeating: "d4", count: 32))), ("label", "Trend ETH ")] {155 #expect(try AgentSpotMandate(served: Fx.with(spot, k, v)).approvalDigest() != base, "field \(k)")156 }157 let venue = all.first { $0.domain == "SPW-VENUE-MANDATE-v1" }!.object, vbase = try AgentVenueMandate(served: venue).approvalDigest()158 for (k, v) in [("instruments.0.maxLeverage", JSONValue.int(2)), ("instruments.0.maxPositionNotional", "1000.13"), ("maxOrderNotional", "1000.13"), ("maxGrossExposure", "1500.19"), ("maxOrdersPerDay", 97), ("maxDailyTurnover", "96011.53"),159 ("floorEquity", "900.1"), ("expiresAt", 1_795_209_601), ("network", "mainnet"), ("agentId", "another-agent")] {160 #expect(try AgentVenueMandate(served: Fx.with(venue, k, v)).approvalDigest() != vbase, "field \(k)")161 }162 // a trailing zero is the same number and the same bytes: `canon`163 #expect(try AgentVenueMandate(served: Fx.with(venue, "floorEquity", "900.110")).approvalDigest() == vbase)164 }165}166167// MARK: going live: the mandate against what the owner entered168169@Suite struct AgentsMandateFlowTests {170 private func spotExpectation() throws -> SpotMandateExpectation {171 guard case .spot(let d) = try Fx.decode("spotDetail", as: AgentDetail.self) else { throw ApprovalError.unsupported("fixture") }172 return try SpotMandateExpectation(detail: d, network: try Fx.section("wallet")["network"]!.decode(Network.self))173 }174 private func prepareSpot(_ answer: JSONValue, expecting e: SpotMandateExpectation? = nil) async throws -> (SpotMandateApproval, MockTransport, APIClient) {175 let (client, t, _) = MockTransport.client()176 t.enqueue(json: Fx.text(answer))177 let a = try await AgentsAPI(client).prepareSpotMandate(agentId: Fx.spotId, expecting: try e ?? spotExpectation(), now: Fx.now)178 return (a, t, client)179 }180181 @Test func theExpectationIsReadFromTheAgentTheOwnerSees() throws {182 let e = try spotExpectation()183 #expect(e.maxOrderUsd.text == "25.5" && e.maxDailyUsd.text == "100" && e.maxOrdersPerDay == 12 && e.mandateDays == 30 && e.slippageBps == 50 && e.vaultIndex == 3 && e.network == "base")184 #expect(e.assets.map(\.decimals) == [6, 18] && e.assets.map(\.isCash) == [true, false])185 #expect(e.strategySha256 == String(repeating: "c3", count: 32))186 }187188 @Test func aSpotMandateThatSaysWhatWasEnteredVerifies() async throws {189 let (a, t, client) = try await prepareSpot(Fx.spotPrepare)190 let r = try #require(t.last)191 #expect(r.method == "POST" && r.path == "/api/v1/agents/\(Fx.spotId)/mandate/prepare" && r.body == JSONValue.object([:]))192 #expect(a.mandate.maxOrdersPerDay == 12 && a.mandate.maxSlippageBps == 150 && a.mandate.provider == "kyberswap")193 // the cash caps are the USD limits exactly; the other caps are shown in asset units computed from the canonical object194 #expect(a.lines.map(\.maxOrder) == ["25.5", "0.00728571"] && a.lines.map(\.maxDaily) == ["100", "0.02857143"])195 #expect(a.gasReserve?.symbol == "ETH" && a.networkName == "Base")196197 let auth = RecordingAuthenticator()198 t.enqueue(json: Fx.json("spotLive"))199 let live = try await AgentsAPI(client).approveSpotMandate(a, with: auth, now: Fx.now)200 #expect(live.mode == .live && live.tradesRealMoney && live.mandate?.maxOrdersPerDay == 12)201 #expect(auth.challenges == [try a.mandate.approvalDigest().base64URL])202 let p = try #require(t.last)203 #expect(p.method == "POST" && p.path == "/api/v1/agents/\(Fx.spotId)/mandate/approve" && p.body?["assertion"]?["response"]?["signature"] != nil && p.body?.objectValue?.count == 1)204 }205206 @Test func aSpotMandateThatDiffersFromWhatWasEnteredIsRefused() async throws {207 let usdc = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"208 let cases: [(String, JSONValue, String)] = [209 ("mandate.maxOrder.\(usdc)", "25500001", "per-order cap"), ("mandate.maxDaily.\(usdc)", "100000001", "daily volume cap"), ("mandate.maxOrdersPerDay", 13, "orders per day"),210 ("mandate.maxSlippageBps", 500, "slippage guard"), ("mandate.expiresAt", .int(1_794_000_000 + 31 * 86_400), "expiry"), ("mandate.vault", "0x15d34AAf54267DB7D7c367839AAf71A00a2C6A66", "vault"),211 ("mandate.vaultIndex", 4, "vault"), ("mandate.network", "arbitrum", "network"), ("mandate.strategySha256", .string(String(repeating: "d4", count: 32)), "strategy"), ("mandate.label", "Something else", "label"),212 ("mandate.createdAt", 1_793_990_000, "expiry"), ("network", "arbitrum", "network"), ("limits.0.maxOrder", "25", "displayed limits"),213 ]214 for (path, value, what) in cases {215 await #expect(throws: ApprovalError.inconsistent(what), "\(path)") { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, path, value)) }216 }217 // an asset the owner never chose, or a missing cap218 let extra = Fx.with(Fx.with(Fx.with(Fx.spotPrepare, "mandate.assets", [.string(usdc), "native", "0x4200000000000000000000000000000000000006"]), "mandate.maxOrder.0x4200000000000000000000000000000000000006", "1"), "mandate.maxDaily.0x4200000000000000000000000000000000000006", "1")219 await #expect(throws: ApprovalError.inconsistent("assets")) { _ = try await prepareSpot(extra) }220 let noCap = Fx.with(Fx.with(Fx.spotPrepare, "mandate.maxOrder.native", nil), "mandate.maxDaily.native", nil)221 await #expect(throws: ApprovalError.inconsistent("per-order and daily caps of ETH")) { _ = try await prepareSpot(noCap) }222 // the owner's own limits changed since: the same mandate no longer matches223 var e = try spotExpectation()224 e = SpotMandateExpectation(vault: e.vault, vaultIndex: e.vaultIndex, network: e.network, assets: e.assets, maxOrderUsd: try USDLimit("25"), maxDailyUsd: e.maxDailyUsd, maxOrdersPerDay: e.maxOrdersPerDay, slippageBps: e.slippageBps,225 mandateDays: e.mandateDays, strategySha256: e.strategySha256, agentName: e.agentName)226 await #expect(throws: ApprovalError.inconsistent("per-order cap")) { _ = try await prepareSpot(Fx.spotPrepare, expecting: e) }227 }228229 @Test func aSpotMandateIsRefusedOnUnknownFieldChallengeMismatchOrExpiry() async throws {230 await #expect(throws: ApprovalError.self) { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, "mandate.sweepTo", "0x0000000000000000000000000000000000000001")) }231 var other = Data(base64URL: Fx.spotPrepare["options"]!["challenge"]!.stringValue!)!; other[5] ^= 0x40232 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, "options.challenge", .string(other.base64URL))) }233 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, "hash", .string(String(repeating: "0", count: 64)))) }234 await #expect(throws: ApprovalError.wrongRelyingParty("evil.example")) { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, "options.rpId", "evil.example")) }235 await #expect(throws: ApprovalError.userVerificationNotRequired) { _ = try await prepareSpot(Fx.with(Fx.spotPrepare, "options.userVerification", "discouraged")) }236 // prepared, then left on screen past the mandate's own expiry: the passkey is never asked237 let (a, t, client) = try await prepareSpot(Fx.spotPrepare)238 let auth = RecordingAuthenticator(), n = t.requests.count239 await #expect(throws: ApprovalError.expired) { _ = try await AgentsAPI(client).approveSpotMandate(a, with: auth, now: Date(timeIntervalSince1970: 1_796_592_000)) }240 #expect(auth.challenges.isEmpty && t.requests.count == n)241 }242243 private func perpExpectation(days: Int = 14) throws -> PerpLiveExpectation {244 try PerpLiveExpectation(agent: try Fx.decode("list", as: AgentListFixture.self).agents[1], readiness: try Fx.decode("readiness"), days: days)245 }246 struct AgentListFixture: Decodable { let agents: [Agent] }247 private func preparePerp(_ answer: JSONValue, expecting e: PerpLiveExpectation? = nil) async throws -> (PerpLiveApproval, MockTransport, APIClient) {248 let (client, t, _) = MockTransport.client()249 t.enqueue(json: Fx.text(answer))250 let a = try await AgentsAPI(client).preparePerpLive(expecting: try e ?? perpExpectation(), locale: "en", now: Fx.now)251 return (a, t, client)252 }253254 @Test func aPerpMandateNoWiderThanWhatWasReviewedVerifiesAndTakesTwoPasskeyPrompts() async throws {255 let e = try perpExpectation()256 #expect(e.maxLeverage == 2 && e.instruments == ["hyperliquid:ETH", "hyperliquid:BTC"] && e.network == "testnet" && e.floorEquity == "900.11" && e.days == 14)257 let (a, t, client) = try await preparePerp(Fx.perpPrepare)258 let r = try #require(t.last)259 #expect(r.method == "POST" && r.path == "/api/v1/agents/\(Fx.perpId)/perp/live/prepare")260 #expect(r.body == JSONValue.object(["accountId": .string(Fx.accountId), "days": 14, "locale": "en"]))261 #expect(a.mandate.maxLeverage == 1 && !a.mandate.isMainnet && a.mandate.floorEquity == "900.11" && a.tradingMandate.maxDailyLossUsd == "30.01")262 let venueHash = try a.mandate.approvalDigest().hex263 #expect(a.tradingMandate.stopConditions.contains(.lossAtLeast(usd: "100.01")) && a.binding.object.signerMandateHash == venueHash)264265 let auth = RecordingAuthenticator()266 await #expect(throws: ApprovalError.self) { _ = try await AgentsAPI(client).approvePerpLive(a, acknowledged: false, with: auth, now: Fx.now) }267 #expect(auth.challenges.isEmpty)268 var live = Fx.with(Fx.with(Fx.with(Fx.section("perpDetail"), "mode", "LIVE"), "state", "LIVE"), "liveNetwork", "testnet")269 for k in ["signals.0.mode", "equity.0.mode", "log.0.mode"] { live = Fx.with(live, k, "LIVE") }270 live = Fx.with(live, "execution", ["kind": "live", "network": "testnet", "note": "Orders are REAL orders on the Hyperliquid testnet account (test network: the money is not real)"])271 t.enqueue(json: Fx.text(live))272 let d = try await AgentsAPI(client).approvePerpLive(a, acknowledged: true, with: auth, now: Fx.now)273 #expect(d.agent.mode == .live && !d.agent.tradesRealMoney && d.signals.mode == .live && d.execution.mode == .live)274 #expect(auth.challenges == [try a.mandate.approvalDigest().base64URL, try a.binding.object.approvalDigest().base64URL])275 let p = try #require(t.last)276 #expect(p.path == "/api/v1/agents/\(Fx.perpId)/perp/live/approve" && p.body?["accountId"]?.stringValue == Fx.accountId && p.body?["acknowledged"] == true)277 #expect(p.body?["assertion"]?["response"]?["clientDataJSON"] != p.body?["bindingAssertion"]?["response"]?["clientDataJSON"] && p.body?.objectValue?.count == 4)278 }279280 /** Re-binds a tampered prepare answer end to end (hashes, intent, challenges) the way a lying server would: only the comparison with what was entered can catch it. */281 private func rebound(_ answer: JSONValue) throws -> JSONValue {282 var a = answer283 let m = try AgentVenueMandate(served: a["mandate"]!), venueHash = try m.approvalDigest().hex284 a = Fx.with(Fx.with(a, "hash", .string(venueHash)), "options.challenge", Fx.challenge(of: m))285 let t = try AgentTradingMandate(served: a["tradingMandate"]!["mandate"]!)286 a = Fx.with(Fx.with(Fx.with(a, "tradingMandate.hash", .string(t.hashHex())), "binding.intent.tradingMandateHash", .string(t.hashHex())), "binding.intent.signer.mandateHash", .string(venueHash))287 let i = try AgentMandateApprovalIntent(served: a["binding"]!["intent"]!)288 return Fx.with(Fx.with(a, "binding.hash", .string(try i.approvalDigest().hex)), "binding.options.challenge", Fx.challenge(of: i))289 }290291 @Test func aPerpMandateWiderThanWhatWasReviewedIsRefusedEvenWhenEveryHashAgrees() async throws {292 let cases: [(String, JSONValue, String)] = [293 ("mandate.instruments.0.maxLeverage", 3, "leverage cap"), ("mandate.instruments.1.maxPositionNotional", "1000.13", "position cap"), ("mandate.maxOrderNotional", "1000.13", "per-order cap"),294 ("mandate.maxGrossExposure", "1500.19", "gross exposure cap"), ("mandate.maxOrdersPerDay", 97, "orders per day"), ("mandate.maxOrdersPerHour", 5, "orders per day"), ("mandate.floorEquity", "900.1", "loss limit"),295 ("mandate.expiresAt", .int(1_794_000_000 + 15 * 86_400), "expiry"), ("mandate.agentId", "5b1d6c1e-2f43-4a53-8f0a-0000000a3001", "agent"), ("mandate.account", "0x3c44cdddb6a900fa2b585dd299e03d12fa4293bc", "venue account"),296 ("mandate.network", "mainnet", "network"), ("mandate.strategySha256", .string(String(repeating: "d4", count: 32)), "strategy"), ("mandate.instruments.0.instrument", "hyperliquid:SOL", "instruments"),297 ]298 for (path, value, what) in cases {299 let tampered = try rebound(Fx.with(Fx.perpPrepare, path, value))300 await #expect(throws: ApprovalError.inconsistent(what), "\(path)") { _ = try await preparePerp(tampered) }301 }302 // the trading mandate behind an honest derivative mandate: another agent, paper instead of live, an extra instrument, looser API-side limits than the signer's303 let trading: [(String, JSONValue, String)] = [("tradingMandate.mandate.principal.id", "another-agent", "agent"), ("tradingMandate.mandate.mode", "paper", "mode"), ("tradingMandate.mandate.maxLeverage", "3", "leverage cap"),304 ("tradingMandate.mandate.maxOrderNotionalUsd", "5000", "limits of the two mandates"), ("tradingMandate.mandate.notAfter", 1_795_209_601, "rates and expiry of the two mandates"),305 ("tradingMandate.mandate.instruments", ["hyperliquid:ETH", "hyperliquid:BTC", "hyperliquid:SOL"], "instruments"), ("tradingMandate.mandate.marketKinds", ["perp", "spot"], "market kinds")]306 for (path, value, what) in trading {307 let tampered = try rebound(Fx.with(Fx.perpPrepare, path, value))308 await #expect(throws: ApprovalError.inconsistent(what), "\(path)") { _ = try await preparePerp(tampered) }309 }310 // the owner asked for 7 days and the proposal reviewed says 14: nothing is even sent311 #expect(throws: ApprovalError.inconsistent("proposal")) { _ = try perpExpectation(days: 7) }312 }313314 @Test func aPerpApprovalIsRefusedWhenAHashAChallengeOrTheAcknowledgementDoesNotBind() async throws {315 // a trading mandate changed without its hash: the second passkey prompt would commit to something else than what is displayed316 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "tradingMandate.mandate.maxDailyLossUsd", "3000")) }317 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "mandate.maxDailyTurnover", "960115.2")) }318 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "binding.intent.nonce", "7a1c1f0e-8f5f-4b1e-9c56-0000000a0721")) }319 var other = Data(base64URL: Fx.perpPrepare["binding"]!["options"]!["challenge"]!.stringValue!)!; other[0] ^= 1320 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "binding.options.challenge", .string(other.base64URL))) }321 await #expect(throws: ApprovalError.challengeMismatch) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "binding.domain", "SPW-RISK-INTENT-v1")) }322 // the intent names another signer mandate (its own hash and challenge recomputed): caught by the comparison323 let i = try AgentMandateApprovalIntent(served: Fx.with(Fx.perpPrepare["binding"]!["intent"]!, "signer.mandateHash", .string(String(repeating: "ab", count: 32))))324 let swapped = Fx.with(Fx.with(Fx.with(Fx.perpPrepare, "binding.intent", i.served), "binding.hash", .string(try i.approvalDigest().hex)), "binding.options.challenge", Fx.challenge(of: i))325 await #expect(throws: ApprovalError.inconsistent("signer mandate")) { _ = try await preparePerp(swapped) }326 await #expect(throws: ApprovalError.inconsistent("acknowledgement")) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "acknowledgement.text", "I agree.")) }327 // an answer without the trading mandate, its intent or the acknowledgement is never approved blind; an unknown field is a refusal328 for k in ["binding", "tradingMandate", "acknowledgement"] { await #expect(throws: ApprovalError.self, "\(k)") { _ = try await preparePerp(Fx.with(Fx.perpPrepare, k, nil)) } }329 await #expect(throws: ApprovalError.self) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "mandate.withdrawTo", "0x1")) }330 await #expect(throws: ApprovalError.self) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "binding.intent.also", "x")) }331 await #expect(throws: ApprovalError.wrongRelyingParty("evil.example")) { _ = try await preparePerp(Fx.with(Fx.perpPrepare, "binding.options.rpId", "evil.example")) }332 // the binding intent's own window (5 minutes) has passed333 let (a, _, client) = try await preparePerp(Fx.perpPrepare)334 let auth = RecordingAuthenticator()335 await #expect(throws: ApprovalError.expired) { _ = try await AgentsAPI(client).approvePerpLive(a, acknowledged: true, with: auth, now: Date(timeIntervalSince1970: 1_794_000_301)) }336 #expect(auth.challenges.isEmpty)337 }338339 @Test func aMandateRequestStatesEveryLimit() throws {340 // there is no initializer with a default budget, leverage or validity; what is sent is exactly what was entered, as JSON numbers341 let risk = SpotAgentRisk(maxExposurePct: 50, maxLossPct: 5, maxOrderUsd: try USDLimit("25.50"), maxDailyUsd: try USDLimit("100"), maxOrdersPerDay: 12, mandateDays: 30, slippageBps: 50)342 let body = try JSONValue.from(SpotAgentCreateRequest(name: "Trend ETH", mission: "", network: "base", universe: ["ETH"], assets: [:], cash: "USDC", interval: "1h", capitalUsdc: "250", risk: risk))343 #expect(body["risk"]?.objectValue?.keys.sorted() == ["mandateDays", "maxDailyUsd", "maxExposurePct", "maxLossPct", "maxOrderUsd", "maxOrdersPerDay", "slippageBps"])344 #expect(body["risk"]?["maxOrderUsd"] == .double(25.5) && body["risk"]?["maxDailyUsd"] == .int(100) && body["risk"]?["mandateDays"] == .int(30))345 #expect(risk.mandateSlippageBps == 150)346 let perp = try JSONValue.from(PerpAgentCreateRequest(name: "Momentum", mission: "", instruments: ["ETH", "BTC"], interval: "1h", capitalUsdc: "1000",347 risk: PerpAgentRisk(maxLeverage: 2, maxGrossExposureX: 1.5, maxPositionX: 1, maxDailyLossPct: 3, maxTotalLossPct: 10, slippageBps: 30, minTradePct: 2)))348 #expect(perp["kind"] == "perp" && perp["risk"]?.objectValue?.count == 7 && perp["risk"]?["maxLeverage"] == .int(2))349 for bad in ["", "1e3", "-5", "25.1234567", "12345678", "1,5", " 25"] { #expect(throws: AmountError.invalid, "\(bad)") { try USDLimit(bad) } }350 #expect(try USDLimit("025.500").text == "25.5" && USDLimit("0.5").text == "0.5" && USDLimit("7").baseUnits(decimals: 6).description == "7000000")351 // a stored limit that cannot be compared exactly is refused when read, never rounded352 #expect(throws: (any Error).self) { try JSONValue.double(25.12345678).decode(USDLimit.self) }353 #expect(try JSONValue.double(25.5).decode(USDLimit.self).text == "25.5" && JSONValue.int(100).decode(USDLimit.self).text == "100")354 }355}356357// MARK: decoding of every response shape358359@Suite struct AgentsDecodingTests {360 @Test func listAndCreation() throws {361 struct L: Decodable { let agents: [Agent] }362 let l = try Fx.decode("list", as: L.self).agents363 #expect(l.map(\.resolvedKind) == [.spot, .perp, .stream] && l.map(\.mode) == [.paper, .paper, .research])364 #expect(l[0].hasVault && l[0].spotRisk?.maxOrderUsd.text == "25.5" && l[0].perpRisk == nil && l[0].holdings?.first?.isCash == true && l[0].vaultIndex == 3)365 #expect(!l[1].hasVault && l[1].perpRisk?.maxLeverage == 2 && l[1].instruments == ["hyperliquid:ETH", "hyperliquid:BTC"] && l[1].simulation == true && !l[1].tradesRealMoney)366 #expect(l[2].spotRisk == nil && l[2].family == "market_making")367 let c = try Fx.decode("created", as: Agent.self)368 #expect(c.warnings?.first?.code == "paper_only" && c.strategyVersionId == nil)369 let live = try Fx.decode("spotLive", as: Agent.self)370 #expect(live.mode == .live && live.tradesRealMoney && live.mandate?.isExpired(at: Fx.now) == false && live.mandate?.isExpired(at: Date(timeIntervalSince1970: 1_796_592_000)) == true)371 }372373 @Test func spotDetailKeepsTheVaultThePaperBookAndTheBacktestApart() throws {374 guard case .spot(let d) = try Fx.decode("spotDetail", as: AgentDetail.self) else { Issue.record("spot expected"); return }375 #expect(d.vault?.map(\.role) == ["cash", "asset"] && d.vault?[0].units?.description == "249500000" && d.vault?[1].usd == nil)376 #expect(d.paper?.mode == .paper && d.paper?.positions.first?.units == "0.0351" && d.paper?.cashUsd == 127.2)377 #expect(d.orders.mode == .paper && d.orders.value.first?.amountIn?.text == "25000000" && d.orders.value.first?.state == "filled" && d.equity.mode == .paper && d.equity.value.first?.equityUsd.value == 250.05)378 let v = try #require(d.approvedVersion)379 #expect(v.sha256 == String(repeating: "c3", count: 32) && v.simulation.mode == .research && v.simulation.label == "backtest" && v.simulation.metrics?["test"]?["sharpe"]?.doubleValue == 0.8 && v.perpSummary == nil)380 #expect(d.log.map(\.mode) == [.paper, .research] && d.mandateStatus == nil)381 // a vault that could not be read is nil, never empty382 guard case .spot(let unread) = try Fx.with(Fx.section("spotDetail"), "vault", nil).decode(AgentDetail.self) else { return }383 #expect(unread.vault == nil)384 }385386 @Test func perpDetailAndReportSummary() throws {387 guard case .perp(let d) = try Fx.decode("perpDetail", as: AgentDetail.self) else { Issue.record("perp expected"); return }388 #expect(d.account?.mode == .paper && d.account?.positions.count == 1 && d.account?.halt == nil && d.signals.mode == .paper && d.execution.mode == .paper && d.live?.active == false)389 let s = try #require(d.versions.first?.perpSummary)390 #expect(s.mode == .research && s.liquidations?["test"] == 1 && s.problem == nil && s.buyAndHoldIsSpot == false && s.schemaVersion == 3)391 #expect(d.versions.first?.meta?["kind"] == "perp" && d.windDown == nil)392 // perp-routes.ts perpDetail → derivatives paper `accountView`: `account.state` is the account snapshot OBJECT (seen on a live stack, 2026-11-18), not a text393 let snapshot: JSONValue = ["venue": "hyperliquid", "account": "paper:1a6e3c2a", "equity": "1000", "collateral": "1000", "freeCollateral": "1000", "marginUsed": "0", "source": "paper"]394 guard case .perp(let real) = try Fx.with(Fx.section("perpDetail"), "account", Fx.with(Fx.section("perpDetail")["account"]!, "state", snapshot)).decode(AgentDetail.self) else { Issue.record("perp expected"); return }395 #expect(real.account?.state?["equity"]?.stringValue == "1000" && real.account?.state?["source"]?.stringValue == "paper" && d.account?.state?.stringValue == "active")396 guard case .runtime(let a) = try Fx.section("list")["agents"]![2]!.decode(AgentDetail.self) else { Issue.record("runtime expected"); return }397 #expect(a.resolvedKind == .stream)398 // stop: the same shape with the wind-down399 let stopped = Fx.with(Fx.with(Fx.section("perpDetail"), "windDown", ["until": 1_794_086_400_000, "text": "24 h", "openPositions": 1, "openOrders": 0]), "result", "closing")400 let p = try stopped.decode(PerpAgentDetail.self)401 #expect(p.windDown?.openPositions == 1 && p.windDown?.until == Date(timeIntervalSince1970: 1_794_086_400) && p.result == "closing")402 }403404 @Test func catalogueVaultAndStrategies() throws {405 let n = try Fx.decode("networks", as: AgentNetworks.self)406 #expect(n.networks[0].gas?.reserve == "0.0004" && n.networks[1].gas == nil && n.maxLiveSymbols == 11 && n.networks[0].symbols[0].live && n.networks[0].symbols[0].data?["1d"] == .some(nil))407 let e = try Fx.decode("elsewhere", as: FundsElsewhere.self)408 #expect(e.holdings[0].gasEnough == nil && !e.holdings[0].hasGas && e.holdings[0].display == "12.5")409 struct S: Decodable { let strategies: [LibraryStrategy] }410 let s = try Fx.decode("strategies", as: S.self).strategies[0], p = try Fx.decode("perpStrategies", as: S.self).strategies[0]411 #expect(s.registrationPath == "ma_trend/1" && s.generic == true && p.meta.maxLeverage == 2 && p.spotLegs == false)412 #expect(try Fx.decode("registration", as: StrategyRegistration.self).status == "backtesting")413 }414415 /** agents-withdrawals.json and agents-job.json: generated by withdrawals.ts `view()` and queue.ts `jobView()`. */416 @Test func vaultReturnsSayExactlyHowFarTheyWent() throws {417 let r = try TestResources.json("agents-withdrawals.json").decode(VaultReturns.self)418 #expect(r.broadcast == false && r.withdrawals.map(\.state) == [.confirmed, .broadcast, .notSent, .failed, .requested])419 #expect(r.withdrawals.map(\.ok) == [true, true, false, false, false] && r.withdrawals.map(\.isSettled) == [true, false, false, false, false])420 #expect(r.withdrawals[1].duplicate == true && r.withdrawals[0].amount == "249.5" && r.withdrawals[2].error?.contains("nothing was sent") == true && r.withdrawals[4].txid == nil)421 #expect(try JSONValue.string("swept").decode(VaultReturnState.self) == .unknown)422 let j = try TestResources.json("agents-job.json").decode(BacktestRequestResult.self)423 #expect(j.label == "backtest" && j.job.status == .failed && j.job.deadLettered == true && j.job.status.isFinished && j.job.finishedAt != nil)424 }425426 @Test func panelOverviewTemplatesAndStatus() throws {427 let o = try Fx.decode("overview", as: AgentOverview.self)428 #expect(o.summary.state == .active && o.summary.phase == "PAPER_TRADING" && o.summary.mode == .paper && o.summary.kind == .perp && o.summary.strategy?.kind == "python" && o.summary.live.capable)429 #expect(o.backtests.label == "backtest" && o.backtests.versions[0].approvedBy == "owner" && o.backtests.versions[0].simulation.lookaheadCheck == "pass" && o.backtests.versions[0].hasReport == true)430 #expect(o.worker?.lease?.active == true && o.jobs[0].status == .failed && !o.killSwitch.engaged && o.killSwitch.release?.passkey == true && o.familyModes?.modes == [.research, .paper, .live])431 let stopped = try Fx.decode("stopped", as: AgentSummary.self)432 #expect(stopped.isWindingDown && stopped.state == .active && stopped.windDown?["openPositions"] == 1)433 let t = try Fx.decode("templates", as: AgentTemplates.self)434 let v = try #require(t.templates[0].labVerdicts)435 #expect(v[0].mode == .research && v[0].label == "backtest" && v[0].significant == false && v[0].splits?["test"]??.stop?.code == "max_total_loss" && v[0].splits?["validation"] == .some(nil) && !v[1].available && v[1].reason != nil)436 #expect(t.families["funding_arb"]?.modes == [.research, .paper] && t.templates[0].installed[0].liveCapable && t.templates[0].defaults.risk["maxLeverage"] == 2)437 #expect(try Fx.decode("fromTemplate", as: TemplateAgentCreated.self).agent.mode == .research)438 #expect(try Fx.decode("configUpdated", as: RuntimeConfigUpdated.self).configVersion == 4)439 struct C: Decodable { let versions: [AgentConfigVersion] }440 #expect(try Fx.decode("configVersions", as: C.self).versions[0].actor == "owner")441 let d = try Fx.decode("mandateDraft", as: MandateDraft.self)442 #expect(d.shape == "SPW-MANDATE-v1" && d.kind == "spot" && d.fields?["engineLossLimitPct"] == 5 && d.available)443 let s = try Fx.decode("runtimeStatus", as: AgentRuntimeStatus.self)444 #expect(s.killSwitch.engaged && s.killSwitch.by == "owner:owner" && s.leases[0].active && s.queue.dead24h == 1 && s.loops[0].failures == 0 && s.workers.inProcess)445 }446447 @Test func perpVenuesReadinessAndMarketMaking() throws {448 let v = try Fx.decode("perpVenues", as: PerpVenues.self)449 #expect(v.riskDefaults.maxLeverage == 2 && v.venues[0].instruments[1].eligible == false && v.minCapital == "50")450 let r = try Fx.decode("readiness", as: PerpLiveReadiness.self)451 #expect(r.next == "mandate" && r.account?.network == "testnet" && r.proposal?.body.maxOrdersPerHour == 4 && r.steps.account.authorization?.maxMandateDays == 30 && r.steps.mandate.lock == nil)452 #expect(try Fx.decode("liveMandateCreated", as: PerpLiveMandateCreated.self).state == "created")453 #expect(try Fx.decode("flatten", as: PerpFlattenResult.self).mode == .paper)454 let m = try Fx.decode("mmView", as: MarketMakingView.self)455 #expect(m.session?.mode == .paper && m.session?.simulated == true && m.session?.status?.switch?.armed == true && m.session?.pnl?.totalUsd == "-0.42" && m.agentMode == .paper)456 #expect(m.goLive.nextStep?.id == "evidence" && !m.goLive.ready && m.mandate == nil)457 let live = try Fx.decode("mmViewLiveSessionInPaperRead", as: MarketMakingView.self)458 #expect(live.sessions[0].mode == .live && !live.sessions[0].simulated && live.mandate?.signer?["shape"] == "SPW-VENUE-QUOTING-MANDATE-v1")459 let ev = try Fx.decode("mmEvidence", as: MarketMakingEvidence.self)460 #expect(SHA256Digest.hash(Data(ev.jurisdiction.text.utf8)).hex == ev.jurisdiction.sha256)461 let b = try Fx.decode("mmBounds", as: MarketMakingBounds.self)462 #expect(b.locks.mainnet.lock?.setting == "SPW_DERIV_LIVE_MAINNET" && b.locks.testnet.lock == nil && b.breakers[0].alwaysStops)463 #expect(try Fx.decode("mmCommandNothing", as: MarketMakingCommandResult.self).taken == "nothing")464 #expect(try Fx.decode("mmRecover", as: MarketMakingRecovery.self).revoked.count == 1)465 }466}467468// MARK: the three modes469470@Suite struct AgentsModeTests {471 @Test func bothVocabulariesDecodeAndAnUnknownModeIsNeitherLiveNorSimulation() throws {472 #expect(try JSONValue.array(["research", "RESEARCH", "paper", "PAPER", "live", "LIVE", "shadow", ""]).decode([AgentMode].self) == [.research, .research, .paper, .paper, .live, .live, .unknown, .unknown])473 #expect(AgentMode.live.isLive && !AgentMode.live.isSimulation && AgentMode.paper.isSimulation && AgentMode.research.isSimulation && !AgentMode.unknown.isLive && !AgentMode.unknown.isSimulation)474 }475476 @Test func aFigureCarriesItsModeAndAPaperAnswerIsNeverAcceptedForLive() async throws {477 let (client, t, _) = MockTransport.client()478 let api = AgentsAPI(client)479 t.enqueue(json: Fx.json("performancePaper"))480 let p = try await api.performance(Fx.perpId, mode: .paper)481 #expect(t.last?.query == ["mode": "paper"] && p.netPnlUsd == ModedFigure(mode: .paper, value: 12, reason: nil) && p.netPnlUsd.isSimulated && p.equityCurve.mode == .paper && p.equityCurve.value.count == 2)482 #expect(p.sharpe.value == nil && p.sharpe.reason == "fewer than 30 points" && p.label.hasPrefix("PAPER"))483 t.enqueue(json: Fx.json("performanceLive"))484 #expect(try await api.performance(Fx.perpId, mode: .live).netPnlUsd.isSimulated == false)485 // live asked, paper answered (and the reverse): refused, whatever the numbers say486 t.enqueue(json: Fx.json("performancePaper"))487 do { _ = try await api.performance(Fx.perpId, mode: .live); Issue.record("expected a refusal") } catch let e as APIError { #expect(e.code == "mode_mismatch") }488 t.enqueue(json: Fx.json("performanceLive"))489 do { _ = try await api.performance(Fx.perpId, mode: .paper); Issue.record("expected a refusal") } catch let e as APIError { #expect(e.code == "mode_mismatch") }490 t.enqueue(json: Fx.json("performanceResearch"))491 let r = try await api.performance(Fx.perpId, mode: .research)492 #expect(r.netPnlUsd.value == nil && r.equityCurve.value.isEmpty && r.label.hasPrefix("RESEARCH"))493 // an unknown mode cannot even be asked for494 let n = t.requests.count495 await #expect(throws: APIError.self) { _ = try await api.performance(Fx.perpId, mode: .unknown) }496 #expect(t.requests.count == n)497 }498499 @Test func aListNeverMixesModes() async throws {500 let (client, t, _) = MockTransport.client()501 let api = AgentsAPI(client)502 t.enqueue(json: Fx.json("orders"))503 let o = try await api.orders(Fx.perpId, mode: .paper, limit: 900, before: Date(timeIntervalSince1970: 1_794_000_000), openOnly: true)504 #expect(t.last?.query == ["mode": "paper", "limit": "500", "before": "1794000000000", "open": "true"] && o.mode == .paper && o.value[0].state == "FILLED" && o.value[0].history?.first?.to == "SUBMITTED")505 t.enqueue(json: Fx.json("ordersLiveInPaperEnvelope"))506 do { _ = try await api.orders(Fx.perpId, mode: .paper); Issue.record("expected a refusal") } catch let e as APIError { #expect(e.code == "mode_mismatch") }507 t.enqueue(json: Fx.json("orders"))508 do { _ = try await api.orders(Fx.perpId, mode: .live); Issue.record("expected a refusal") } catch let e as APIError { #expect(e.code == "mode_mismatch") }509 for (section, call) in [("signals", "signals"), ("journal", "journal"), ("timeline", "timeline")] {510 t.enqueue(json: Fx.json(section)); t.enqueue(json: Fx.json(section))511 switch call {512 case "signals": #expect(try await api.signals(Fx.perpId, mode: .paper).value[0].decision == "trade"); await #expect(throws: APIError.self) { _ = try await api.signals(Fx.perpId, mode: .live) }513 case "journal": #expect(try await api.journal(Fx.perpId, mode: .paper).value[0].code == "started_paper"); await #expect(throws: APIError.self) { _ = try await api.journal(Fx.perpId, mode: .live) }514 default: #expect(try await api.timeline(Fx.perpId, mode: .paper).value[0].type == "signal"); await #expect(throws: APIError.self) { _ = try await api.timeline(Fx.perpId, mode: .live) }515 }516 #expect(t.last?.path == "/api/v1/agents/\(Fx.perpId)/\(call)")517 }518 }519520 @Test func aDetailWhoseRecordsMixModesDoesNotDecode() throws {521 // a live order in the list of an agent that is on paper, a paper point on the curve of a live agent522 #expect(throws: (any Error).self) { try Fx.with(Fx.section("spotDetail"), "orders.0.mode", "LIVE").decode(AgentDetail.self) }523 #expect(throws: (any Error).self) { try Fx.with(Fx.section("spotDetail"), "equity.0.mode", "LIVE").decode(AgentDetail.self) }524 #expect(throws: (any Error).self) { try Fx.with(Fx.with(Fx.section("spotDetail"), "mode", "LIVE"), "state", "LIVE").decode(AgentDetail.self) }525 #expect(throws: (any Error).self) { try Fx.with(Fx.section("perpDetail"), "signals.0.mode", "LIVE").decode(AgentDetail.self) }526 #expect(throws: (any Error).self) { try Fx.with(Fx.section("perpDetail"), "equity.0.mode", "LIVE").decode(AgentDetail.self) }527 // a market-making session that calls itself both live and simulated528 #expect(throws: (any Error).self) { try Fx.with(Fx.section("mmView"), "session.simulated", false).decode(MarketMakingView.self) }529 #expect(throws: (any Error).self) { try Fx.with(Fx.section("mmView"), "session.mode", "live").decode(MarketMakingView.self) }530 }531532 @Test func marketMakingReadsNameOneMode() async throws {533 let (client, t, _) = MockTransport.client()534 let api = AgentsAPI(client), id = "5b1d6c1e-2f43-4a53-8f0a-0000000a7000"535 t.enqueue(json: Fx.json("mmView"))536 #expect(try await api.marketMaking(id, mode: .paper).sessions.count == 1)537 #expect(t.last?.path == "/api/v1/mm/agents/\(id)" && t.last?.query == ["mode": "paper"])538 t.enqueue(json: Fx.json("mmViewLiveSessionInPaperRead"))539 do { _ = try await api.marketMaking(id, mode: .paper); Issue.record("expected a refusal") } catch let e as APIError { #expect(e.code == "mode_mismatch") }540 t.enqueue(json: Fx.json("mmFills"))541 let f = try await api.marketMakingFills(id, mode: .paper, limit: 50, session: "6a0c1d2e-5a3b-4c44-9d0a-0000000a9000")542 #expect(f.mode == .paper && f.value[0].markoutsBps?.s1 == "-0.8" && f.value[0].markoutsBps?.s10 == nil && t.last?.query == ["mode": "paper", "limit": "50", "session": "6a0c1d2e-5a3b-4c44-9d0a-0000000a9000"])543 t.enqueue(json: Fx.json("mmFills"))544 await #expect(throws: APIError.self) { _ = try await api.marketMakingFills(id, mode: .live) }545 t.enqueue(json: Fx.text(Fx.with(Fx.section("mmFills"), "simulated", false)))546 await #expect(throws: APIError.self) { _ = try await api.marketMakingFills(id, mode: .paper) }547 t.enqueue(json: Fx.json("mmPerformance"))548 #expect(try await api.marketMakingPerformance(id, mode: .paper).attribution.totalUsd == "-0.42")549 t.enqueue(json: Fx.json("mmPerformance"))550 await #expect(throws: APIError.self) { _ = try await api.marketMakingPerformance(id, mode: .live) }551 let n = t.requests.count552 await #expect(throws: APIError.self) { _ = try await api.marketMaking(id, mode: .research) }553 #expect(t.requests.count == n)554 }555}556557// MARK: request contract of every endpoint558559@Suite struct AgentsRequestTests {560 private let id = Fx.spotId, mm = "5b1d6c1e-2f43-4a53-8f0a-0000000a7000"561562 @Test func reads() async throws {563 let (client, t, _) = MockTransport.client()564 let api = AgentsAPI(client)565 func expectGet(_ path: String, _ query: [String: String] = [:], sourceLocation: SourceLocation = #_sourceLocation) {566 #expect(t.last?.method == "GET" && t.last?.path == "/api/v1" + path && t.last?.query == query && t.last?.headers["X-SPW-CSRF"] == nil, sourceLocation: sourceLocation)567 }568 t.enqueue(json: Fx.json("networks")); _ = try await api.networks(); expectGet("/agents/networks")569 t.enqueue(json: Fx.json("list")); #expect(try await api.list().count == 3); expectGet("/agents")570 t.enqueue(json: Fx.json("templates")); _ = try await api.templates(); expectGet("/agents/templates")571 t.enqueue(json: Fx.json("spotDetail")); _ = try await api.detail(id); expectGet("/agents/\(id)")572 t.enqueue(json: Fx.json("overview")); _ = try await api.overview(id); expectGet("/agents/\(id)/overview")573 t.enqueue(json: Fx.json("configVersions")); #expect(try await api.configVersions(id).count == 1); expectGet("/agents/\(id)/config-versions")574 t.enqueue(json: Fx.json("mandateDraft")); _ = try await api.mandateDraft(id, locale: "fr"); expectGet("/agents/\(id)/mandate-draft", ["locale": "fr"])575 t.enqueue(json: Fx.json("runtimeStatus")); _ = try await api.runtimeStatus(); expectGet("/agents/runtime/status")576 t.enqueue(json: Fx.json("runtimeStatus")); #expect(try await api.killSwitch().engaged); expectGet("/agents/runtime/status")577 t.enqueue(json: Fx.json("strategies")); #expect(try await api.strategyLibrary().count == 1); expectGet("/strategies")578 t.enqueue(json: Fx.json("perpStrategies")); #expect(try await api.perpStrategyLibrary().count == 1); expectGet("/strategies", ["kind": "perp"])579 t.enqueue(json: Fx.json("strategies")); await #expect(throws: (any Error).self) { _ = try await api.perpStrategyLibrary() }580 t.enqueue(json: #"{"job":\#(Fx.text(try TestResources.json("agents-job.json")["job"]!))}"#); _ = try await api.job("8e0c1d2e-5a3b-4c44-9d0a-0000000a6000"); expectGet("/agents/jobs/8e0c1d2e-5a3b-4c44-9d0a-0000000a6000")581 t.enqueue(json: Fx.json("elsewhere")); _ = try await api.fundsElsewhere(id); expectGet("/agents/\(id)/elsewhere")582 let returns = try TestResources.json("agents-withdrawals.json")583 t.enqueue(json: Fx.text(returns)); _ = try await api.vaultReturns(id); expectGet("/agents/\(id)/withdrawals")584 t.enqueue(json: Fx.text(returns["withdrawals"]![0]!)); _ = try await api.vaultReturn(id, returnId: "3f0c1d2e-5a3b-4c44-9d0a-0000000a5000"); expectGet("/agents/\(id)/withdrawals/3f0c1d2e-5a3b-4c44-9d0a-0000000a5000")585 t.enqueue(json: Fx.json("perpVenues")); _ = try await api.perpVenues(); expectGet("/agents/perp/venues")586 t.enqueue(json: Fx.json("readiness")); _ = try await api.perpLiveReadiness(id, account: Fx.accountId, locale: "en", days: 14); expectGet("/agents/\(id)/perp/live", ["account": Fx.accountId, "locale": "en", "days": "14"])587 t.enqueue(json: Fx.json("readiness")); _ = try await api.perpLiveReadiness(id, locale: "fr"); expectGet("/agents/\(id)/perp/live", ["locale": "fr"])588 t.enqueue(json: Fx.json("mmEvidence")); _ = try await api.marketMakingEvidence(locale: "fr"); expectGet("/mm/evidence", ["locale": "fr"])589 t.enqueue(json: Fx.json("mmBounds")); _ = try await api.marketMakingBounds(); expectGet("/mm/bounds")590 }591592 @Test func writes() async throws {593 let (client, t, _) = MockTransport.client()594 let api = AgentsAPI(client)595 func expectPost(_ path: String, _ body: JSONValue, sourceLocation: SourceLocation = #_sourceLocation) {596 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1" + path && t.last?.body == body, sourceLocation: sourceLocation)597 #expect(t.last?.headers["X-SPW-CSRF"] == "1" && t.last?.headers["Origin"] == "https://wallet.example.test", sourceLocation: sourceLocation)598 }599 let risk = SpotAgentRisk(maxExposurePct: 50, maxLossPct: 5, maxOrderUsd: try USDLimit("25.5"), maxDailyUsd: try USDLimit("100"), maxOrdersPerDay: 12, mandateDays: 30, slippageBps: 50)600 t.enqueue(json: Fx.json("created"))601 _ = try await api.create(SpotAgentCreateRequest(name: "Trend ETH", mission: "m", network: "base", universe: ["ETH"], assets: ["ETH": "native"], cash: "USDC", interval: "1h", capitalUsdc: "250", risk: risk))602 expectPost("/agents", ["name": "Trend ETH", "mission": "m", "network": "base", "universe": ["ETH"], "assets": ["ETH": "native"], "cash": "USDC", "interval": "1h", "capitalUsdc": "250",603 "risk": ["maxExposurePct": 50, "maxLossPct": 5, "maxOrderUsd": .double(25.5), "maxDailyUsd": 100, "maxOrdersPerDay": 12, "mandateDays": 30, "slippageBps": 50]])604 let prisk = PerpAgentRisk(maxLeverage: 2, maxGrossExposureX: 1.5, maxPositionX: 1, maxDailyLossPct: 3, maxTotalLossPct: 10, slippageBps: 30, minTradePct: 2)605 let priskJSON: JSONValue = ["maxLeverage": 2, "maxGrossExposureX": .double(1.5), "maxPositionX": 1, "maxDailyLossPct": 3, "maxTotalLossPct": 10, "slippageBps": 30, "minTradePct": 2]606 t.enqueue(json: Fx.text(Fx.section("list")["agents"]![1]!))607 _ = try await api.create(PerpAgentCreateRequest(name: "Momentum", mission: "", instruments: ["ETH", "BTC"], interval: "1h", capitalUsdc: "1000", risk: prisk))608 expectPost("/agents", ["kind": "perp", "name": "Momentum", "mission": "", "instruments": ["ETH", "BTC"], "interval": "1h", "capitalUsdc": "1000", "risk": priskJSON])609 t.enqueue(json: Fx.json("fromTemplate"))610 _ = try await api.create(TemplateAgentCreateRequest(template: "momentum", name: "Momentum", mission: "", strategyPath: "momentum_xs_perp/2", capitalUsdc: "1000", risk: ["maxLeverage": 2]))611 expectPost("/agents/from-template", ["template": "momentum", "name": "Momentum", "mission": "", "strategyPath": "momentum_xs_perp/2", "capitalUsdc": "1000", "risk": ["maxLeverage": 2]])612 t.enqueue(json: Fx.json("configUpdated")); _ = try await api.updateConfig(mm, config: ["quoteSizeUsd": "25"]); expectPost("/agents/\(mm)/config", ["config": ["quoteSizeUsd": "25"]])613 t.enqueue(json: Fx.json("registration")); _ = try await api.registerStrategy(id, try Fx.section("strategies")["strategies"]![0]!.decode(LibraryStrategy.self)); expectPost("/agents/\(id)/strategies", ["path": "ma_trend/1"])614 t.enqueue(json: Fx.json("created")); _ = try await api.approveStrategyVersion(agentId: id, versionId: "9c2f6f5e-0a51-4f3b-9a56-0000000a2000"); expectPost("/agents/\(id)/strategies/9c2f6f5e-0a51-4f3b-9a56-0000000a2000/approve", [:])615 let job = Fx.text(try TestResources.json("agents-job.json"))616 t.enqueue(json: job); _ = try await api.requestBacktest(id); expectPost("/agents/\(id)/backtest", [:])617 t.enqueue(json: job); _ = try await api.requestBacktest(id, versionId: "9c2f6f5e-0a51-4f3b-9a56-0000000a2000", hours: 24); expectPost("/agents/\(id)/backtest", ["versionId": "9c2f6f5e-0a51-4f3b-9a56-0000000a2000", "hours": 24])618 t.enqueue(json: Fx.json("summary")); _ = try await api.start(id, mode: .paper); expectPost("/agents/\(id)/start", ["mode": "paper"])619 t.enqueue(json: Fx.json("summary")); _ = try await api.resume(id); expectPost("/agents/\(id)/resume", [:])620 t.enqueue(json: Fx.text(Fx.section("list")["agents"]![1]!)); _ = try await api.setPerpRisk(Fx.perpId, risk: prisk, liftHalt: false); expectPost("/agents/\(Fx.perpId)/perp/risk", ["risk": priskJSON, "liftHalt": false])621 t.enqueue(json: Fx.json("liveMandateCreated")); _ = try await api.createPerpLiveMandate(Fx.perpId, accountId: Fx.accountId, days: 14, locale: "fr")622 expectPost("/agents/\(Fx.perpId)/perp/live/mandate", ["accountId": .string(Fx.accountId), "days": 14, "locale": "fr"])623 t.enqueue(json: Fx.json("perpDetail")); _ = try await api.resumePerpLive(Fx.perpId); expectPost("/agents/\(Fx.perpId)/perp/live/resume", [:])624 t.enqueue(json: Fx.json("mmCommand")); _ = try await api.resumeQuoting(mm); expectPost("/mm/agents/\(mm)/command", ["command": "resume"])625 let ev = try Fx.decode("mmEvidence", as: MarketMakingEvidence.self)626 t.enqueue(json: Fx.json("mmAck")); _ = try await api.acknowledgeGoLive(mm, .evidence(displayed: ev), locale: "fr"); expectPost("/mm/agents/\(mm)/golive/ack", ["step": "evidence", "locale": "fr", "acknowledged": true])627 t.enqueue(json: Fx.json("mmAck")); _ = try await api.acknowledgeGoLive(mm, .jurisdiction(displayed: ev), locale: "en"); expectPost("/mm/agents/\(mm)/golive/ack", ["step": "jurisdiction", "locale": "en", "acknowledged": true])628 t.enqueue(json: Fx.json("mmAck")); _ = try await api.acknowledgeGoLive(mm, .testnet(note: "ran it on 2026-11-06"), locale: "en"); expectPost("/mm/agents/\(mm)/golive/ack", ["step": "testnet", "locale": "en", "acknowledged": true, "note": "ran it on 2026-11-06"])629 // a jurisdiction text that is not the one its hash names is not acknowledged630 let n = t.requests.count, forged = try Fx.with(Fx.section("mmEvidence"), "jurisdiction.text", "ok").decode(MarketMakingEvidence.self)631 await #expect(throws: ApprovalError.self) { _ = try await api.acknowledgeGoLive(mm, .jurisdiction(displayed: forged), locale: "en") }632 #expect(t.requests.count == n)633 t.enqueue(json: Fx.json("mmRecover")); _ = try await api.recoverMarketMaking(); expectPost("/mm/recover", [:])634 // start live without a mandate: the server's refusal is surfaced as it is; nothing here can create or approve one635 t.enqueue(status: 409, json: #"{"error":"mandate_required","message":"LIVE needs a mandate approved by the owner with the passkey"}"#)636 do { _ = try await api.start(id, mode: .live); Issue.record("expected mandate_required") } catch let e as APIError { #expect(e.code == "mandate_required" && t.last?.body == ["mode": "live"]) }637 }638639 /** Verified in the backend: none of these routes reads an assertion (runtime-routes.ts, routes.ts, perp-routes.ts, mm/routes.ts). */640 @Test func everyStopPathIsOneCallWithoutPasskey() async throws {641 let (client, t, _) = MockTransport.client()642 let api = AgentsAPI(client)643 func expectStop(_ path: String, _ body: JSONValue = [:], sourceLocation: SourceLocation = #_sourceLocation) {644 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1" + path && t.last?.body == body, sourceLocation: sourceLocation)645 #expect(Fx.text(t.last?.body ?? .null).contains("assertion") == false, sourceLocation: sourceLocation)646 }647 t.enqueue(json: Fx.json("stopped")); let s = try await api.stop(id); expectStop("/agents/\(id)/stop"); #expect(s.isWindingDown)648 t.enqueue(json: Fx.json("summary")); _ = try await api.pause(id); expectStop("/agents/\(id)/pause")649 t.enqueue(json: Fx.json("created")); _ = try await api.revokeMandate(id); expectStop("/agents/\(id)/revoke")650 t.enqueue(json: Fx.json("created")); _ = try await api.setMode(id, .stopped); expectStop("/agents/\(id)/mode", ["mode": "STOPPED"])651 t.enqueue(json: Fx.json("created")); _ = try await api.setMode(id, .paused); expectStop("/agents/\(id)/mode", ["mode": "PAUSED"])652 t.enqueue(json: Fx.json("perpDetail")); _ = try await api.pausePerpLive(Fx.perpId); expectStop("/agents/\(Fx.perpId)/perp/live/pause")653 t.enqueue(json: Fx.json("perpDetail")); _ = try await api.stopPerpLive(Fx.perpId); expectStop("/agents/\(Fx.perpId)/perp/live/stop")654 t.enqueue(json: Fx.json("flatten")); _ = try await api.flattenPerpPaper(Fx.perpId); expectStop("/agents/\(Fx.perpId)/perp/flatten")655 t.enqueue(json: Fx.json("mmCommand")); #expect(try await api.pullQuotes(mm).taken == "queued"); expectStop("/mm/agents/\(mm)/command", ["command": "pull"])656 t.enqueue(json: Fx.json("mmCommandNothing")); _ = try await api.flattenInventory(mm); expectStop("/mm/agents/\(mm)/command", ["command": "flatten"])657 // the kill switch: a reason is never an obstacle (the server wants 3 to 200 characters)658 t.enqueue(json: Fx.json("killSwitchEngaged")); #expect(try await api.engageKillSwitch().engaged); expectStop("/agents/kill-switch/engage", ["reason": "engaged by the owner from the agents panel"])659 t.enqueue(json: Fx.json("killSwitchEngaged")); _ = try await api.engageKillSwitch(reason: " "); expectStop("/agents/kill-switch/engage", ["reason": "engaged by the owner"])660 t.enqueue(json: Fx.json("killSwitchEngaged")); _ = try await api.engageKillSwitch(reason: String(repeating: "x", count: 300)); #expect(t.last?.body?["reason"]?.stringValue?.count == 200)661 }662663 @Test func aVaultReturnNamesNoDestinationAndNoAmount() async throws {664 let (client, t, _) = MockTransport.client()665 let api = AgentsAPI(client), usdc = "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"666 let returns = try TestResources.json("agents-withdrawals.json")["withdrawals"]!667 t.enqueue(json: Fx.text(returns[1]!))668 let r = try await api.returnToOwner(id, asset: usdc, idempotencyKey: "wd-0000000a5000")669 // the body is exactly the server's strict schema: the asset, optionally the network, the key — the signer pays the owner's own address only670 #expect(t.last?.method == "POST" && t.last?.path == "/api/v1/agents/\(id)/withdraw" && t.last?.body == ["asset": .string(usdc), "idempotencyKey": "wd-0000000a5000"])671 #expect(r.duplicate == true && r.ok && !r.isSettled && r.state.isOpen)672 t.enqueue(json: Fx.text(returns[2]!))673 let off = try await api.returnToOwner(id, asset: "native", network: "arbitrum", idempotencyKey: "wd-0000000a5001")674 #expect(t.last?.body == ["asset": "native", "network": "arbitrum", "idempotencyKey": "wd-0000000a5001"] && !off.ok && off.state == .notSent && off.state.isTerminal)675 t.enqueue(status: 409, json: #"{"error":"bad_state","message":"revoke the mandate before withdrawing"}"#)676 do { _ = try await api.returnToOwner(id, asset: usdc, idempotencyKey: "wd-0000000a5002"); Issue.record("expected bad_state") } catch let e as APIError { #expect(e.code == "bad_state") }677 }678}679