Repository Public
1// SP Wallet Core2// File: Sources/SPWalletCore/Domains/Agents/AgentsAPI.swift3// Description: Endpoints of the trading agents (/api/v1/agents, /api/v1/strategies, /api/v1/mm): creation with every limit stated,4// mode-scoped reads that refuse an answer of another mode, the vault and its return to the owner, the strategy library5// and backtests, start / pause / stop (never a passkey), and going live — the mandate is parsed strictly, compared6// with what the owner entered, bound to the passkey challenge by `ApprovalBinding.verify`, and only then approved.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation1112// MARK: requests1314/** A spot agent: one vault on one network. Every limit is required; `risk.mandateDays` is the validity of the mandate it may later be given. */15public struct SpotAgentCreateRequest: Encodable, Sendable, Equatable {16 public let name: String17 public let mission: String18 /** One of the networks of `AgentsAPI.networks()`. */19 public let network: String20 /** Market symbols (BTC, ETH, LINK…), 1 to 12. */21 public let universe: [String]22 /** The registry asset to hold for a symbol (`native` or a token address) when the owner chose one. */23 public let assets: [String: String]24 /** `USDC` or `USDT`. */25 public let cash: String26 /** `1h` or `1d`. */27 public let interval: String28 /** Decimal text, USDC. */29 public let capitalUsdc: String30 public let risk: SpotAgentRisk31 public init(name: String, mission: String, network: String, universe: [String], assets: [String: String], cash: String, interval: String, capitalUsdc: String, risk: SpotAgentRisk) {32 self.name = name; self.mission = mission; self.network = network; self.universe = universe; self.assets = assets; self.cash = cash; self.interval = interval; self.capitalUsdc = capitalUsdc; self.risk = risk33 }34}3536/** A perp agent: created in SIMULATION on a paper account of the venue (no vault, no mandate, nothing asked of the signer). */37public struct PerpAgentCreateRequest: Encodable, Sendable, Equatable {38 public let kind = "perp"39 public let name: String40 public let mission: String41 /** Instrument symbols of the venue (1 to 8). */42 public let instruments: [String]43 public let interval: String44 /** Simulated collateral, decimal text (at least 50). */45 public let capitalUsdc: String46 public let risk: PerpAgentRisk47 public init(name: String, mission: String, instruments: [String], interval: String, capitalUsdc: String, risk: PerpAgentRisk) {48 self.name = name; self.mission = mission; self.instruments = instruments; self.interval = interval; self.capitalUsdc = capitalUsdc; self.risk = risk49 }50}5152/** An agent from one of the built-in templates. The template's proposed capital and limits are shown to the owner and sent back explicitly. */53public struct TemplateAgentCreateRequest: Encodable, Sendable, Equatable {54 public let template: String55 public let name: String56 public let mission: String57 public let strategyPath: String?58 public let universe: [String]?59 public let venues: [String]?60 public let capitalUsdc: String61 public let risk: [String: JSONValue]62 public let config: [String: JSONValue]?63 public init(template: String, name: String, mission: String, strategyPath: String? = nil, universe: [String]? = nil, venues: [String]? = nil, capitalUsdc: String, risk: [String: JSONValue], config: [String: JSONValue]? = nil) {64 self.template = template; self.name = name; self.mission = mission; self.strategyPath = strategyPath; self.universe = universe; self.venues = venues; self.capitalUsdc = capitalUsdc; self.risk = risk; self.config = config65 }66}6768/** The owner's changes of state of the historical route (`POST /agents/:id/mode`). None of them adds authority; none needs a passkey. */69public enum AgentModeCommand: String, Sendable, CaseIterable { case paper = "PAPER", paused = "PAUSED", stopped = "STOPPED", research = "RESEARCH" }7071/** An acknowledgement of the market-making go-live checklist. The texts are the ones the server served (`evidence(locale:)`). */72public enum MarketMakingAcknowledgement: Sendable {73 /** The lab study and the simulation are negative: `displayed` is the evidence that was on screen. */74 case evidence(displayed: MarketMakingEvidence)75 case jurisdiction(displayed: MarketMakingEvidence)76 /** The owner attests that he ran the testnet step himself. */77 case testnet(note: String?)78 var step: String { switch self { case .evidence: "evidence"; case .jurisdiction: "jurisdiction"; case .testnet: "testnet" } }79}8081// MARK: going live — what the owner entered, and the verified approvals8283/**84 What the mandate of a spot agent must say, from what the owner entered and reviewed: the vault, the network, the assets, the two USD85 caps, the order count, the validity and the strategy. `AgentsAPI.check` compares a served mandate with it field by field.86 The engine's loss limit (`maxLossPct`) is NOT in a spot mandate: the signer cannot enforce it, the engine stops the agent.87 */88public struct SpotMandateExpectation: Sendable, Equatable {89 public struct Asset: Sendable, Equatable {90 public let id: String91 public let symbol: String92 public let decimals: Int93 public let isCash: Bool94 public init(id: String, symbol: String, decimals: Int, isCash: Bool) { self.id = id; self.symbol = symbol; self.decimals = decimals; self.isCash = isCash }95 }96 public let vault: String97 public let vaultIndex: Int98 public let network: String99 /** The cash leg and one registry asset per market symbol. */100 public let assets: [Asset]101 public let maxOrderUsd: USDLimit102 public let maxDailyUsd: USDLimit103 public let maxOrdersPerDay: Int104 public let slippageBps: Int105 public let mandateDays: Int106 public let strategySha256: String107 public let agentName: String108109 public init(vault: String, vaultIndex: Int, network: String, assets: [Asset], maxOrderUsd: USDLimit, maxDailyUsd: USDLimit, maxOrdersPerDay: Int, slippageBps: Int, mandateDays: Int, strategySha256: String, agentName: String) {110 self.vault = vault; self.vaultIndex = vaultIndex; self.network = network; self.assets = assets; self.maxOrderUsd = maxOrderUsd; self.maxDailyUsd = maxDailyUsd111 self.maxOrdersPerDay = maxOrdersPerDay; self.slippageBps = slippageBps; self.mandateDays = mandateDays; self.strategySha256 = strategySha256; self.agentName = agentName112 }113114 /** From the agent the owner is looking at and the wallet's registry of its network (decimals of each asset). */115 public init(detail d: SpotAgentDetail, network n: Network) throws {116 let a = d.agent117 guard a.resolvedKind == .spot, n.id == a.network else { throw ApprovalError.inconsistent("network") }118 guard let risk = a.spotRisk else { throw ApprovalError.unsupported("the agent's limits cannot be read exactly") }119 guard let index = a.vaultIndex, a.hasVault else { throw ApprovalError.unsupported("the agent has no vault") }120 guard let holdings = a.holdings, holdings.count >= 2 else { throw ApprovalError.unsupported("the agent's assets are not in the registry") }121 guard let v = d.approvedVersion else { throw ApprovalError.unsupported("no approved strategy version") }122 let assets = try holdings.map { h -> Asset in123 guard let def = n.asset(h.asset) else { throw ApprovalError.unsupported("asset \(h.asset) is not in the registry of \(n.id)") }124 return Asset(id: h.asset, symbol: h.assetSymbol, decimals: def.decimals, isCash: h.isCash)125 }126 self.init(vault: a.vaultAddress, vaultIndex: index, network: a.network, assets: assets, maxOrderUsd: risk.maxOrderUsd, maxDailyUsd: risk.maxDailyUsd, maxOrdersPerDay: risk.maxOrdersPerDay,127 slippageBps: risk.slippageBps, mandateDays: risk.mandateDays, strategySha256: v.sha256, agentName: a.name)128 }129}130131/** One asset of a spot mandate with its caps as exact decimal text, computed by the client from the canonical object (never the server's display). */132public struct SpotMandateLine: Sendable, Equatable, Identifiable {133 public let asset: String134 public let symbol: String135 public let decimals: Int136 public let isCash: Bool137 /** Nil: the asset can be bought but not sold under the mandate. */138 public let maxOrder: String?139 public let maxDaily: String?140 public var id: String { asset }141}142143/** A spot mandate ready for the passkey: parsed strictly, equal to what was entered, bound to the challenge. */144public struct SpotMandateApproval: Sendable {145 public struct GasReserve: Codable, Sendable, Equatable { public let required: String; public let held: String; public let symbol: String }146 public let agentId: String147 public let approval: VerifiedApproval<AgentSpotMandate>148 public let lines: [SpotMandateLine]149 public let networkName: String?150 /** The native coin the vault holds against what live trading needs (the server refuses the preparation below it). */151 public let gasReserve: GasReserve?152 public var mandate: AgentSpotMandate { approval.object }153}154155/** What the derivative mandate of a perp agent must say, from the agent's own limits, the venue account chosen and the proposal reviewed. */156public struct PerpLiveExpectation: Sendable, Equatable {157 public let agentId: String158 /** The venue account (id of the wallet's record) and its address and network. */159 public let accountId: String160 public let account: String161 public let network: String162 /** `hyperliquid:<symbol>` for each instrument of the agent. */163 public let instruments: [String]164 /** The owner's leverage limit: no instrument of the mandate may be above it. */165 public let maxLeverage: Int166 /** Validity asked for, days. Mandatory: the server's "longest possible" default is never used. */167 public let days: Int168 public let strategySha256: String169 /** Ceilings of the proposal the owner reviewed (canonical decimals, USDC). */170 public let maxPositionNotional: String171 public let maxOrderNotional: String172 public let maxGrossExposure: String173 public let maxOrdersPerDay: Int174 public let maxOrdersPerHour: Int175 /** Loss limit: the account value below which only cancels and reduce-only orders are signed. The mandate may not go below it. */176 public let floorEquity: String177178 public init(agentId: String, accountId: String, account: String, network: String, instruments: [String], maxLeverage: Int, days: Int, strategySha256: String,179 maxPositionNotional: String, maxOrderNotional: String, maxGrossExposure: String, maxOrdersPerDay: Int, maxOrdersPerHour: Int, floorEquity: String) throws {180 self.agentId = agentId; self.accountId = accountId; self.account = account.lowercased(); self.network = network; self.instruments = instruments; self.maxLeverage = maxLeverage; self.days = days181 self.strategySha256 = strategySha256; self.maxOrdersPerDay = maxOrdersPerDay; self.maxOrdersPerHour = maxOrdersPerHour182 self.maxPositionNotional = try AgentsCanon.positive(maxPositionNotional, "maxPositionNotional"); self.maxOrderNotional = try AgentsCanon.positive(maxOrderNotional, "maxOrderNotional")183 self.maxGrossExposure = try AgentsCanon.positive(maxGrossExposure, "maxGrossExposure"); self.floorEquity = try AgentsCanon.positive(floorEquity, "floorEquity")184 }185186 /** From the agent and the checklist the owner reviewed (`perpLiveReadiness(…, account:, days:)` of the same account and days). */187 public init(agent a: Agent, readiness r: PerpLiveReadiness, days: Int) throws {188 guard a.resolvedKind == .perp, r.agentId == a.id else { throw ApprovalError.inconsistent("agent") }189 guard let risk = a.perpRisk else { throw ApprovalError.unsupported("the agent's limits cannot be read") }190 guard r.next == "mandate", let p = r.proposal, let acct = r.account, let sha = r.steps.strategy.sha256 else { throw ApprovalError.unsupported("the agent is not ready for a mandate (\(r.next))") }191 guard p.body.agentId == a.id, p.days == days, p.body.days == days, p.body.strategySha256 == sha else { throw ApprovalError.inconsistent("proposal") }192 guard let position = p.body.instruments.map(\.maxPositionNotional).first, p.body.instruments.allSatisfy({ $0.maxPositionNotional == position && $0.maxLeverage <= risk.maxLeverage }) else { throw ApprovalError.inconsistent("proposal instruments") }193 try self.init(agentId: a.id, accountId: acct.id, account: acct.account, network: acct.network, instruments: a.universe.map { "hyperliquid:\($0)" }, maxLeverage: risk.maxLeverage, days: days, strategySha256: sha,194 maxPositionNotional: position, maxOrderNotional: p.body.maxOrderNotional, maxGrossExposure: p.body.maxGrossExposure, maxOrdersPerDay: p.body.maxOrdersPerDay, maxOrdersPerHour: p.body.maxOrdersPerHour, floorEquity: p.body.floorEquity)195 }196}197198/**199 A perp agent's live mandate ready for its TWO passkey prompts: `signer` is the derivative mandate the isolated signer stores and200 enforces; `binding` is the API's intent that names the full trading mandate hash and that derivative mandate. Both challenges were201 recomputed from the fields below.202 */203public struct PerpLiveApproval: Sendable {204 public struct Acknowledgement: Codable, Sendable, Equatable { public let text: String; public let sha256: String?; public let version: String?; public let source: String? }205 public let agentId: String206 public let accountId: String207 public let signer: VerifiedApproval<AgentVenueMandate>208 public let binding: VerifiedApproval<AgentMandateApprovalIntent>209 /** The trading mandate (API-enforced fields included: daily loss, stop conditions, fee cap), whose recomputed hash the binding names. */210 public let tradingMandate: AgentTradingMandate211 /** The jurisdiction text the owner must have read: its SHA-256 is `mandate.ackSha256`. */212 public let acknowledgement: Acknowledgement213 public let warning: String?214 public let enforcedBySigner: JSONValue?215 public let trustedBySigner: JSONValue?216 public let notEnforced: JSONValue?217 public let windDown: JSONValue?218 /** Field by field: what the signer enforces and what only the API enforces. */219 public let enforcement: JSONValue?220 public let proposal: PerpLiveProposal?221 public var mandate: AgentVenueMandate { signer.object }222}223224// MARK: API225226public struct AgentsAPI: Sendable {227 let client: APIClient228 public init(_ client: APIClient) { self.client = client }229230 private func seg(_ s: String) -> String { APIClient.segment(s) }231 private static func mismatch(_ what: String, got: AgentMode, wanted: AgentMode) -> APIError {232 APIError(status: 200, code: "mode_mismatch", message: "the server answered \(what) of mode \(got.rawValue) when \(wanted.rawValue) was asked: refused, never shown under another mode")233 }234 private static func queryMode(_ m: AgentMode) throws -> String {235 guard let q = m.query else { throw APIError(status: 0, code: "bad_request", message: "mode must be research, paper or live") }236 return q237 }238239 // MARK: catalogue, list, creation240241 /** What an agent can trade, network by network, with the gas reserve live trading needs there. */242 public func networks() async throws -> AgentNetworks { try await client.get("/agents/networks") }243244 public func list() async throws -> [Agent] {245 struct Answer: Decodable, Sendable { let agents: [Agent] }246 return try await client.get("/agents", as: Answer.self).agents247 }248249 /** Creates the agent and its vault (address derived by the signer). Nothing can be traded live until a mandate is approved. */250 public func create(_ r: SpotAgentCreateRequest) async throws -> Agent { try await client.post("/agents", body: r) }251 public func create(_ r: PerpAgentCreateRequest) async throws -> Agent { try await client.post("/agents", body: r) }252253 public func templates() async throws -> AgentTemplates { try await client.get("/agents/templates") }254 public func create(_ r: TemplateAgentCreateRequest) async throws -> TemplateAgentCreated { try await client.post("/agents/from-template", body: r) }255256 public func detail(_ id: String) async throws -> AgentDetail { try await client.get("/agents/\(seg(id))") }257 public func overview(_ id: String) async throws -> AgentOverview { try await client.get("/agents/\(seg(id))/overview") }258259 public func configVersions(_ id: String) async throws -> [AgentConfigVersion] {260 struct Answer: Decodable, Sendable { let versions: [AgentConfigVersion] }261 return try await client.get("/agents/\(seg(id))/config-versions", as: Answer.self).versions262 }263264 /** Replaces the configuration and / or limits of a stream or supervisor agent (it must be paused or stopped). */265 public func updateConfig(_ id: String, config: [String: JSONValue]? = nil, risk: [String: JSONValue]? = nil) async throws -> RuntimeConfigUpdated {266 struct Body: Encodable, Sendable { let config: [String: JSONValue]?; let risk: [String: JSONValue]? }267 return try await client.post("/agents/\(seg(id))/config", body: Body(config: config, risk: risk))268 }269270 /** The fields the owner would approve for this agent to go live. Read-only: nothing is prepared at the signer. */271 public func mandateDraft(_ id: String, locale: String) async throws -> MandateDraft { try await client.get("/agents/\(seg(id))/mandate-draft", query: ["locale": locale]) }272273 // MARK: mode-scoped reads — one answer never carries two modes, and an answer of another mode is refused274275 private func page(_ mode: AgentMode, _ limit: Int?, _ before: Date?) throws -> [String: String?] {276 ["mode": try Self.queryMode(mode), "limit": limit.map { String(min(max($0, 1), 500)) }, "before": before.map { String(Int64(($0.timeIntervalSince1970 * 1000).rounded())) }]277 }278279 public func signals(_ id: String, mode: AgentMode, limit: Int? = nil, before: Date? = nil) async throws -> ModeScoped<[AgentSignal]> {280 struct Answer: Decodable, Sendable { let mode: AgentMode; let signals: [AgentSignal] }281 let a: Answer = try await client.get("/agents/\(seg(id))/signals", query: try page(mode, limit, before))282 guard a.mode == mode, a.signals.allSatisfy({ $0.mode == mode }) else { throw Self.mismatch("signals", got: a.signals.first { $0.mode != mode }?.mode ?? a.mode, wanted: mode) }283 return ModeScoped(mode: mode, value: a.signals)284 }285286 public func journal(_ id: String, mode: AgentMode, limit: Int? = nil, before: Date? = nil) async throws -> ModeScoped<[AgentJournalEntry]> {287 struct Answer: Decodable, Sendable { let mode: AgentMode; let entries: [AgentJournalEntry] }288 let a: Answer = try await client.get("/agents/\(seg(id))/journal", query: try page(mode, limit, before))289 guard a.mode == mode, a.entries.allSatisfy({ $0.mode == mode }) else { throw Self.mismatch("journal entries", got: a.entries.first { $0.mode != mode }?.mode ?? a.mode, wanted: mode) }290 return ModeScoped(mode: mode, value: a.entries)291 }292293 public func orders(_ id: String, mode: AgentMode, limit: Int? = nil, before: Date? = nil, openOnly: Bool = false) async throws -> ModeScoped<[AgentOrder]> {294 struct Answer: Decodable, Sendable { let mode: AgentMode; let orders: [AgentOrder] }295 var q = try page(mode, limit, before)296 if openOnly { q["open"] = "true" }297 let a: Answer = try await client.get("/agents/\(seg(id))/orders", query: q)298 guard a.mode == mode, a.orders.allSatisfy({ $0.mode == mode }) else { throw Self.mismatch("orders", got: a.orders.first { $0.mode != mode }?.mode ?? a.mode, wanted: mode) }299 return ModeScoped(mode: mode, value: a.orders)300 }301302 /** Performance of ONE mode. `research` answers no figure: backtests are read as `SimulationFigures` on the strategy versions. */303 public func performance(_ id: String, mode: AgentMode) async throws -> AgentPerformance {304 let p: AgentPerformance = try await client.get("/agents/\(seg(id))/performance", query: ["mode": try Self.queryMode(mode)])305 guard p.mode == mode else { throw Self.mismatch("performance", got: p.mode, wanted: mode) }306 return p307 }308309 public func timeline(_ id: String, mode: AgentMode, limit: Int? = nil, before: Date? = nil) async throws -> ModeScoped<[AgentTimelineItem]> {310 struct Answer: Decodable, Sendable { let mode: AgentMode; let items: [AgentTimelineItem] }311 let a: Answer = try await client.get("/agents/\(seg(id))/timeline", query: try page(mode, limit, before))312 guard a.mode == mode else { throw Self.mismatch("timeline", got: a.mode, wanted: mode) }313 return ModeScoped(mode: mode, value: a.items)314 }315316 // MARK: life cycle — stopping never needs a passkey317318 /**319 Start in a mode. `live` succeeds only when a mandate approved by the owner is in force at the signer; otherwise the server answers320 409 `mandate_required` (this call can never create or approve one).321 */322 public func start(_ id: String, mode: AgentMode) async throws -> AgentSummary {323 struct Body: Encodable, Sendable { let mode: String }324 return try await client.post("/agents/\(seg(id))/start", body: Body(mode: try Self.queryMode(mode)))325 }326327 /** No new exposure. A live SPOT agent's mandate is revoked at the signer at once (resuming needs a new one); a live perp agent keeps its positions and its mandate. */328 public func pause(_ id: String) async throws -> AgentSummary { try await client.post("/agents/\(seg(id))/pause") }329330 /** Resume in the mode the agent was paused in. Answers 409 `mandate_required` when that mode was live and the mandate is gone. */331 public func resume(_ id: String) async throws -> AgentSummary { try await client.post("/agents/\(seg(id))/resume") }332333 /**334 Always allowed, no passkey. Stops the agent and removes its authority: a live spot agent's mandate is revoked at the signer, a335 live perp agent's mandate is revoked and its positions closed with reduce-only orders (`windDown` in the answer; the agent stays336 `STOPPING` meanwhile), a market-making agent's quoting mandate is revoked.337 */338 public func stop(_ id: String) async throws -> AgentSummary { try await client.post("/agents/\(seg(id))/stop") }339340 /** The historical state route (spot and paper perp agents). `paused` and `stopped` are always accepted; `paper` needs an approved strategy version. */341 public func setMode(_ id: String, _ command: AgentModeCommand) async throws -> Agent {342 struct Body: Encodable, Sendable { let mode: String }343 return try await client.post("/agents/\(seg(id))/mode", body: Body(mode: command.rawValue))344 }345346 /** Revoke the spot mandate at the signer and stop the agent. No passkey: revoking only removes authority. */347 public func revokeMandate(_ id: String) async throws -> Agent { try await client.post("/agents/\(seg(id))/revoke") }348349 /**350 Engage THE kill switch (the risk engine's — there is no other): no agent, key or mandate can add risk until it is released. It is351 released only with the owner's passkey in the Risk screen; there is no release here.352 */353 public func engageKillSwitch(reason: String = "engaged by the owner from the agents panel") async throws -> AgentKillSwitchState {354 struct Body: Encodable, Sendable { let reason: String }355 let r = reason.trimmingCharacters(in: .whitespacesAndNewlines)356 // the server wants 3 to 200 characters; a reason that would be refused must never stand between the owner and the switch357 return try await client.post("/agents/kill-switch/engage", body: Body(reason: r.count < 3 ? "engaged by the owner" : String(r.prefix(200))))358 }359360 /** Workers, leases, queue and the kill switch's state. */361 public func runtimeStatus() async throws -> AgentRuntimeStatus { try await client.get("/agents/runtime/status") }362 public func killSwitch() async throws -> AgentKillSwitchState { try await runtimeStatus().killSwitch }363364 // MARK: strategies and backtests365366 public func strategyLibrary() async throws -> [LibraryStrategy] {367 struct Answer: Decodable, Sendable { let strategies: [LibraryStrategy] }368 return try await client.get("/strategies", as: Answer.self).strategies369 }370 public func perpStrategyLibrary() async throws -> [LibraryStrategy] {371 struct Answer: Decodable, Sendable { let kind: String; let strategies: [LibraryStrategy] }372 let a: Answer = try await client.get("/strategies", query: ["kind": "perp"])373 guard a.kind == "perp" else { throw APIError(status: 200, code: "decoding", message: "the perp library was asked; the server answered \(a.kind)") }374 return a.strategies375 }376377 /** Pin a library version to the agent and start its backtest. Writes no code and approves nothing. */378 public func registerStrategy(_ id: String, path: String) async throws -> StrategyRegistration {379 struct Body: Encodable, Sendable { let path: String }380 return try await client.post("/agents/\(seg(id))/strategies", body: Body(path: path))381 }382 public func registerStrategy(_ id: String, _ s: LibraryStrategy) async throws -> StrategyRegistration { try await registerStrategy(id, path: s.registrationPath) }383384 /**385 The owner approves a backtested version: the agent may run it on paper, and a later mandate pins its hash. The server asks no386 passkey here (it gives no authority over funds); it refuses a version without a report or whose look-ahead check did not pass.387 */388 public func approveStrategyVersion(agentId: String, versionId: String) async throws -> Agent {389 try await client.post("/agents/\(seg(agentId))/strategies/\(seg(versionId))/approve")390 }391392 /** Asynchronous: the answer is a job to poll with `job(_:)`. Its result is a backtest report — a simulation. */393 public func requestBacktest(_ id: String, versionId: String? = nil, hours: Int? = nil) async throws -> BacktestRequestResult {394 struct Body: Encodable, Sendable { let versionId: String?; let hours: Int? }395 return try await client.post("/agents/\(seg(id))/backtest", body: Body(versionId: versionId, hours: hours))396 }397 public func job(_ jobId: String) async throws -> AgentJob {398 struct Answer: Decodable, Sendable { let job: AgentJob }399 return try await client.get("/agents/jobs/\(seg(jobId))", as: Answer.self).job400 }401402 // MARK: vault403404 /** What the vault's address holds on the other EVM networks. */405 public func fundsElsewhere(_ id: String) async throws -> FundsElsewhere { try await client.get("/agents/\(seg(id))/elsewhere") }406407 /**408 Bring the WHOLE balance of one asset of the vault back to the owner's own address. There is no destination and no amount to give:409 the server takes the owner's address from the signer, and the signer signs a vault payment to that address only. On the agent's410 own network the mandate must be revoked first (409 otherwise). `idempotencyKey` (8–64 of [A-Za-z0-9_-]) travels in the body; a411 retry with the same key, or a second request while one is open, answers the same operation with `duplicate`.412 */413 public func returnToOwner(_ id: String, asset: String, network: String? = nil, idempotencyKey: String) async throws -> VaultReturn {414 struct Body: Encodable, Sendable { let asset: String; let network: String?; let idempotencyKey: String }415 return try await client.post("/agents/\(seg(id))/withdraw", body: Body(asset: asset, network: network, idempotencyKey: idempotencyKey))416 }417 public func vaultReturns(_ id: String) async throws -> VaultReturns { try await client.get("/agents/\(seg(id))/withdrawals") }418 public func vaultReturn(_ id: String, returnId: String) async throws -> VaultReturn { try await client.get("/agents/\(seg(id))/withdrawals/\(seg(returnId))") }419420 // MARK: spot mandate — prepare (verified) → passkey → signer421422 /**423 Ask the server to build the mandate from the agent's limits, then VERIFY locally: strict parsing, the mandate says what424 `expectation` says, the challenge is the hash of the mandate, the server's display equals the client's own formatting.425 */426 public func prepareSpotMandate(agentId: String, expecting e: SpotMandateExpectation, now: Date = Date()) async throws -> SpotMandateApproval {427 struct Limit: Decodable, Sendable { let maxOrder: String?; let maxDaily: String? }428 struct Answer: Decodable, Sendable { let mandate: JSONValue; let hash: String; let limits: [Limit]?; let options: PasskeyRequestOptions; let network: String; let networkName: String?; let gasReserve: SpotMandateApproval.GasReserve? }429 let a: Answer = try await client.post("/agents/\(seg(agentId))/mandate/prepare")430 let m = try AgentSpotMandate(served: a.mandate)431 let lines = try Self.check(mandate: m, against: e, now: now)432 guard a.network == e.network else { throw ApprovalError.inconsistent("network") }433 guard a.hash == (try m.approvalDigest()).hex else { throw ApprovalError.challengeMismatch }434 if let shown = a.limits {435 guard shown.count == lines.count, zip(shown, lines).allSatisfy({ $0.maxOrder == $1.maxOrder && $0.maxDaily == $1.maxDaily }) else { throw ApprovalError.inconsistent("displayed limits") }436 }437 return SpotMandateApproval(agentId: agentId, approval: try ApprovalBinding.verify(m, options: a.options, rpId: client.configuration.rpId), lines: lines, networkName: a.networkName, gasReserve: a.gasReserve)438 }439440 /**441 The mandate must be the one the owner's limits describe. Compared as exact strings and integers.442 The cash leg's caps are the USD limits themselves, exactly. The caps of the other assets are the same USD limits converted by443 the server at the prices of the preparation: they cannot be recomputed here and are returned as exact text to be DISPLAYED.444 */445 public static func check(mandate m: AgentSpotMandate, against e: SpotMandateExpectation, now: Date) throws -> [SpotMandateLine] {446 let t = Int(now.timeIntervalSince1970)447 guard m.vault == e.vault, m.vaultIndex == e.vaultIndex else { throw ApprovalError.inconsistent("vault") }448 guard m.network == e.network else { throw ApprovalError.inconsistent("network") }449 guard m.provider == "kyberswap" else { throw ApprovalError.inconsistent("provider") }450 guard Set(m.assets) == Set(e.assets.map(\.id)), m.assets.count == e.assets.count else { throw ApprovalError.inconsistent("assets") }451 guard e.assets.filter(\.isCash).count == 1 else { throw ApprovalError.inconsistent("cash leg") }452 var lines: [SpotMandateLine] = []453 for a in e.assets {454 // the server caps every asset of the agent; an asset left without a cap, or a cap for something else, is not what was entered455 guard let order = m.maxOrder[a.id], let daily = m.maxDaily[a.id], let o = try? BaseUnits(order), let d = try? BaseUnits(daily) else { throw ApprovalError.inconsistent("per-order and daily caps of \(a.symbol)") }456 if a.isCash {457 guard let wantOrder = try? e.maxOrderUsd.baseUnits(decimals: a.decimals), let wantDaily = try? e.maxDailyUsd.baseUnits(decimals: a.decimals) else { throw ApprovalError.unsupported("the USD limits cannot be expressed in \(a.symbol)") }458 guard o == wantOrder else { throw ApprovalError.inconsistent("per-order cap") }459 guard d == wantDaily else { throw ApprovalError.inconsistent("daily volume cap") }460 } else {461 guard !o.isZero, !d.isZero else { throw ApprovalError.inconsistent("caps of \(a.symbol)") }462 }463 lines.append(SpotMandateLine(asset: a.id, symbol: a.symbol, decimals: a.decimals, isCash: a.isCash, maxOrder: o.formatted(decimals: a.decimals), maxDaily: d.formatted(decimals: a.decimals)))464 }465 guard m.maxOrdersPerDay == e.maxOrdersPerDay else { throw ApprovalError.inconsistent("orders per day") }466 guard m.maxSlippageBps == min(500, max(150, e.slippageBps + 80)) else { throw ApprovalError.inconsistent("slippage guard") }467 guard e.mandateDays >= 1, m.expiresAt - m.createdAt == e.mandateDays * 86_400 else { throw ApprovalError.inconsistent("expiry") }468 guard m.createdAt <= t + 120, m.createdAt >= t - 600 else { throw ApprovalError.inconsistent("creation time") }469 guard m.expiresAt > t else { throw ApprovalError.expired }470 guard m.strategySha256 == e.strategySha256 else { throw ApprovalError.inconsistent("strategy") }471 guard Array(m.label.utf16) == Array(e.agentName.utf16.prefix(60)) else { throw ApprovalError.inconsistent("label") }472 return lines473 }474475 /**476 Ask the passkey to sign the verified challenge and hand the assertion to the server, which forwards it to the isolated signer:477 only the signer judges it and stores the limits. On success the agent is LIVE.478 */479 public func approveSpotMandate(_ a: SpotMandateApproval, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> Agent {480 guard a.mandate.expiry > now else { throw ApprovalError.expired }481 let assertion = try await authenticator.assert(a.approval.options, rpId: client.configuration.rpId)482 return try await submitSpotMandate(assertion: assertion, for: a)483 }484 /** Second half of `approveSpotMandate`, separate so that a lost answer is followed by a read of the agent instead of a second signature. */485 public func submitSpotMandate(assertion: PasskeyAssertion, for a: SpotMandateApproval) async throws -> Agent {486 struct Body: Encodable, Sendable { let assertion: PasskeyAssertion }487 return try await client.post("/agents/\(seg(a.agentId))/mandate/approve", body: Body(assertion: assertion))488 }489490 // MARK: perp agents491492 public func perpVenues() async throws -> PerpVenues { try await client.get("/agents/perp/venues") }493494 /** Replace the limits of a perp agent in SIMULATION (refused while it is on a venue account: its limits are then its mandate's). */495 public func setPerpRisk(_ id: String, risk: PerpAgentRisk, liftHalt: Bool) async throws -> Agent {496 struct Body: Encodable, Sendable { let risk: PerpAgentRisk; let liftHalt: Bool }497 return try await client.post("/agents/\(seg(id))/perp/risk", body: Body(risk: risk, liftHalt: liftHalt))498 }499500 /** Close every position of the PAPER account with reduce-only orders (always possible there). A live agent is closed by `stopPerpLive`. */501 public func flattenPerpPaper(_ id: String) async throws -> PerpFlattenResult { try await client.post("/agents/\(seg(id))/perp/flatten") }502503 /** The go-live checklist and the mandate that would be proposed for `account` over `days`. Read-only. */504 public func perpLiveReadiness(_ id: String, account: String? = nil, locale: String, days: Int? = nil) async throws -> PerpLiveReadiness {505 try await client.get("/agents/\(seg(id))/perp/live", query: ["account": account, "locale": locale, "days": days.map(String.init)])506 }507508 /**509 Create the live trading mandate from the agent's limits WITHOUT approving it (state `created`: it authorises nothing). The owner510 approves it in the Risk screen with the passkey, then starts the agent live. No passkey is involved in this call.511 */512 public func createPerpLiveMandate(_ id: String, accountId: String, days: Int, locale: String) async throws -> PerpLiveMandateCreated {513 struct Body: Encodable, Sendable { let accountId: String; let days: Int; let locale: String }514 return try await client.post("/agents/\(seg(id))/perp/live/mandate", body: Body(accountId: accountId, days: days, locale: locale))515 }516517 /**518 Create the trading mandate and prepare its approval, then VERIFY locally: the derivative mandate is parsed strictly and is no519 wider than `expectation`; its hash is the first challenge; the trading mandate re-hashes to the hash the binding intent names;520 the intent names this derivative mandate and its hash is the second challenge; the acknowledgement text hashes to `ackSha256`.521 */522 public func preparePerpLive(expecting e: PerpLiveExpectation, locale: String, now: Date = Date()) async throws -> PerpLiveApproval {523 struct Body: Encodable, Sendable { let accountId: String; let days: Int; let locale: String }524 struct Binding: Decodable, Sendable { let domain: String; let intent: JSONValue; let hash: String; let options: PasskeyRequestOptions }525 struct Trading: Decodable, Sendable { let id: String; let hash: String; let mandate: JSONValue; let enforcement: JSONValue? }526 struct Answer: Decodable, Sendable {527 let mandate: JSONValue; let hash: String; let options: PasskeyRequestOptions; let acknowledgement: PerpLiveApproval.Acknowledgement?; let warning: String?528 let enforcedBySigner: JSONValue?; let trustedBySigner: JSONValue?; let notEnforced: JSONValue?; let windDown: JSONValue?; let proposal: PerpLiveProposal?529 let binding: Binding?; let tradingMandate: Trading?530 }531 let a: Answer = try await client.post("/agents/\(seg(e.agentId))/perp/live/prepare", body: Body(accountId: e.accountId, days: e.days, locale: locale))532 guard let b = a.binding, let tm = a.tradingMandate, let ack = a.acknowledgement else { throw ApprovalError.unsupported("the server did not return the trading mandate, its approval intent and the acknowledgement: nothing is approved blind") }533 let m = try AgentVenueMandate(served: a.mandate), t = try AgentTradingMandate(served: tm.mandate), intent = try AgentMandateApprovalIntent(served: b.intent)534 let rp = client.configuration.rpId535 try Self.check(mandate: m, against: e, now: now)536 let venueHash = (try m.approvalDigest()).hex537 guard a.hash == venueHash else { throw ApprovalError.challengeMismatch }538 guard SHA256Digest.hash(Data(ack.text.utf8)).hex == m.ackSha256, ack.sha256 == nil || ack.sha256 == m.ackSha256 else { throw ApprovalError.inconsistent("acknowledgement") }539 try Self.check(tradingMandate: t, servedId: tm.id, servedHash: tm.hash, mandate: m, against: e)540 try Self.check(binding: intent, domain: b.domain, servedHash: b.hash, tradingMandate: t, venueHash: venueHash, agentId: e.agentId, now: now)541 return PerpLiveApproval(agentId: e.agentId, accountId: e.accountId, signer: try ApprovalBinding.verify(m, options: a.options, rpId: rp), binding: try ApprovalBinding.verify(intent, options: b.options, rpId: rp),542 tradingMandate: t, acknowledgement: ack, warning: a.warning, enforcedBySigner: a.enforcedBySigner, trustedBySigner: a.trustedBySigner, notEnforced: a.notEnforced, windDown: a.windDown,543 enforcement: tm.enforcement, proposal: a.proposal)544 }545546 /**547 The derivative mandate must be for this agent, this venue account and these instruments, and NO WIDER than what was reviewed:548 leverage, position, order, gross exposure and order rates at or below, the floor on the account value at or above, the validity549 at most the days asked. `maxDailyTurnover` is compiled by the server as order limit × orders per day: it has no counterpart in550 what the owner entered and is to be displayed as it is.551 */552 public static func check(mandate m: AgentVenueMandate, against e: PerpLiveExpectation, now: Date) throws {553 let t = Int(now.timeIntervalSince1970)554 func atMost(_ a: String, _ b: String) -> Bool { !AgentsCanon.less(b, a) }555 guard m.agentId == e.agentId else { throw ApprovalError.inconsistent("agent") }556 guard m.account == e.account, m.venue == "hyperliquid" else { throw ApprovalError.inconsistent("venue account") }557 guard m.network == e.network else { throw ApprovalError.inconsistent("network") }558 guard Set(m.instruments.map(\.instrument)) == Set(e.instruments), m.instruments.count == e.instruments.count else { throw ApprovalError.inconsistent("instruments") }559 guard m.instruments.allSatisfy({ $0.maxLeverage <= e.maxLeverage }) else { throw ApprovalError.inconsistent("leverage cap") }560 guard m.instruments.allSatisfy({ atMost($0.maxPositionNotional, e.maxPositionNotional) }) else { throw ApprovalError.inconsistent("position cap") }561 guard atMost(m.maxOrderNotional, e.maxOrderNotional) else { throw ApprovalError.inconsistent("per-order cap") }562 guard atMost(m.maxGrossExposure, e.maxGrossExposure) else { throw ApprovalError.inconsistent("gross exposure cap") }563 guard m.maxOrdersPerDay <= e.maxOrdersPerDay, m.maxOrdersPerHour <= e.maxOrdersPerHour else { throw ApprovalError.inconsistent("orders per day") }564 guard atMost(e.floorEquity, m.floorEquity) else { throw ApprovalError.inconsistent("loss limit") }565 guard e.days >= 1, m.expiresAt - m.createdAt <= e.days * 86_400 else { throw ApprovalError.inconsistent("expiry") }566 guard m.createdAt <= t + 120, m.createdAt >= t - 600 else { throw ApprovalError.inconsistent("creation time") }567 guard m.expiresAt > t else { throw ApprovalError.expired }568 guard m.strategySha256 == e.strategySha256 else { throw ApprovalError.inconsistent("strategy") }569 }570571 /** The trading mandate must re-hash to the hash served, be the live mandate of this agent on this account, and agree with the derivative mandate compiled from it. */572 static func check(tradingMandate t: AgentTradingMandate, servedId: String, servedHash: String, mandate m: AgentVenueMandate, against e: PerpLiveExpectation) throws {573 guard t.hashHex() == servedHash else { throw ApprovalError.challengeMismatch }574 guard t.mandateId == servedId, t.mandateId == m.mandateId else { throw ApprovalError.inconsistent("mandate id") }575 guard t.mode == "live" else { throw ApprovalError.inconsistent("mode") }576 guard t.principalKind == "agent", t.principalId == e.agentId else { throw ApprovalError.inconsistent("agent") }577 guard t.accounts.count == 1, case .venueAccount("hyperliquid", e.network, let acct) = t.accounts[0], acct.lowercased() == e.account else { throw ApprovalError.inconsistent("venue account") }578 guard t.venues == ["hyperliquid"], t.networks == [e.network] else { throw ApprovalError.inconsistent("network") }579 guard Set(t.instruments) == Set(e.instruments), t.instruments.count == e.instruments.count else { throw ApprovalError.inconsistent("instruments") }580 guard t.marketKinds == ["perp"] else { throw ApprovalError.inconsistent("market kinds") }581 guard !AgentsCanon.less(String(e.maxLeverage), t.maxLeverage) else { throw ApprovalError.inconsistent("leverage cap") }582 guard t.maxOrderNotionalUsd == m.maxOrderNotional, t.maxPositionNotionalUsd == m.instruments[0].maxPositionNotional, t.floorEquityUsd == m.floorEquity else { throw ApprovalError.inconsistent("limits of the two mandates") }583 guard t.perDay == m.maxOrdersPerDay, t.perHour == m.maxOrdersPerHour, t.notAfter == m.expiresAt, t.createdAt == m.createdAt else { throw ApprovalError.inconsistent("rates and expiry of the two mandates") }584 guard t.strategySha256 == e.strategySha256 else { throw ApprovalError.inconsistent("strategy") }585 }586587 static func check(binding i: AgentMandateApprovalIntent, domain: String, servedHash: String, tradingMandate t: AgentTradingMandate, venueHash: String, agentId: String, now: Date) throws {588 guard domain == AgentMandateApprovalIntent.domain, servedHash == (try i.approvalDigest()).hex else { throw ApprovalError.challengeMismatch }589 guard i.mandateId == t.mandateId, i.tradingMandateHash == t.hashHex() else { throw ApprovalError.inconsistent("trading mandate") }590 guard i.principal == "agent:\(agentId)" else { throw ApprovalError.inconsistent("agent") }591 guard i.signerShape == AgentVenueMandate.domain, i.signerMandateHash == venueHash, i.quotingSectionHash == nil else { throw ApprovalError.inconsistent("signer mandate") }592 guard i.expiry > now else { throw ApprovalError.expired }593 }594595 /**596 Two passkey prompts — the signer's, then the API's — and the approval. `acknowledged` must be true: the owner read597 `approval.acknowledgement.text`. On success the agent is LIVE on that venue account.598 */599 public func approvePerpLive(_ a: PerpLiveApproval, acknowledged: Bool, with authenticator: PasskeyAuthenticator, now: Date = Date()) async throws -> PerpAgentDetail {600 guard acknowledged else { throw ApprovalError.inconsistent("the jurisdiction acknowledgement was not given") }601 guard a.mandate.expiry > now, a.binding.object.expiry > now else { throw ApprovalError.expired }602 let rp = client.configuration.rpId603 let assertion = try await authenticator.assert(a.signer.options, rpId: rp)604 let bindingAssertion = try await authenticator.assert(a.binding.options, rpId: rp)605 return try await submitPerpLive(assertion: assertion, bindingAssertion: bindingAssertion, for: a)606 }607 public func submitPerpLive(assertion: PasskeyAssertion, bindingAssertion: PasskeyAssertion, for a: PerpLiveApproval) async throws -> PerpAgentDetail {608 struct Body: Encodable, Sendable { let accountId: String; let assertion: PasskeyAssertion; let bindingAssertion: PasskeyAssertion; let acknowledged: Bool }609 return try await client.post("/agents/\(seg(a.agentId))/perp/live/approve", body: Body(accountId: a.accountId, assertion: assertion, bindingAssertion: bindingAssertion, acknowledged: true))610 }611612 /** No new exposure; positions are KEPT on the venue account and the mandate stays active. No passkey. */613 public func pausePerpLive(_ id: String) async throws -> PerpAgentDetail { try await client.post("/agents/\(seg(id))/perp/live/pause") }614 /** Refused when the mandate is no longer active at the signer. No passkey: resuming adds no authority. */615 public func resumePerpLive(_ id: String) async throws -> PerpAgentDetail { try await client.post("/agents/\(seg(id))/perp/live/resume") }616 /** Revoke the mandate and close the positions with reduce-only orders (`windDown` in the answer). Always allowed, no passkey. */617 public func stopPerpLive(_ id: String) async throws -> PerpAgentDetail { try await client.post("/agents/\(seg(id))/perp/live/stop") }618619 // MARK: market making (/api/v1/mm — the owner's session only)620621 private static func mmMode(_ m: AgentMode) throws -> String {622 guard m == .paper || m == .live else { throw APIError(status: 0, code: "bad_request", message: "a quoting session is paper or live") }623 return m.rawValue624 }625626 public func marketMakingEvidence(locale: String) async throws -> MarketMakingEvidence { try await client.get("/mm/evidence", query: ["locale": locale]) }627 public func marketMakingBounds() async throws -> MarketMakingBounds { try await client.get("/mm/bounds") }628629 /** The session now, the past sessions OF THAT MODE, the mandate and the go-live checklist. */630 public func marketMaking(_ id: String, mode: AgentMode) async throws -> MarketMakingView {631 let v: MarketMakingView = try await client.get("/mm/agents/\(seg(id))", query: ["mode": try Self.mmMode(mode)])632 if let other = ([v.session].compactMap { $0 } + v.sessions).first(where: { $0.mode != mode }) { throw Self.mismatch("a session", got: other.mode, wanted: mode) }633 return v634 }635636 public func marketMakingFills(_ id: String, mode: AgentMode, limit: Int? = nil, session: String? = nil) async throws -> ModeScoped<[MarketMakingFill]> {637 struct Answer: Decodable, Sendable { let mode: AgentMode; let simulated: Bool; let fills: [MarketMakingFill] }638 let a: Answer = try await client.get("/mm/agents/\(seg(id))/fills", query: ["mode": try Self.mmMode(mode), "limit": limit.map { String(min(max($0, 1), 500)) }, "session": session])639 guard a.mode == mode, a.simulated == (mode == .paper) else { throw Self.mismatch("fills", got: a.mode, wanted: mode) }640 return ModeScoped(mode: mode, value: a.fills)641 }642643 public func marketMakingPerformance(_ id: String, mode: AgentMode) async throws -> MarketMakingPerformance {644 let p: MarketMakingPerformance = try await client.get("/mm/agents/\(seg(id))/performance", query: ["mode": try Self.mmMode(mode)])645 guard p.mode == mode else { throw Self.mismatch("performance", got: p.mode, wanted: mode) }646 return p647 }648649 private func command(_ id: String, _ c: String) async throws -> MarketMakingCommandResult {650 struct Body: Encodable, Sendable { let command: String }651 return try await client.post("/mm/agents/\(seg(id))/command", body: Body(command: c))652 }653 /** Withdraw every resting quote now. Works under every lock and halt; no passkey. */654 public func pullQuotes(_ id: String) async throws -> MarketMakingCommandResult { try await command(id, "pull") }655 /** Withdraw the quotes and close the inventory with reduce-only orders. Works under every lock and halt; no passkey. */656 public func flattenInventory(_ id: String) async throws -> MarketMakingCommandResult { try await command(id, "flatten") }657 /** Quote again after a pull (only while a session is running; it adds no authority: the mandate and the breakers still decide). */658 public func resumeQuoting(_ id: String) async throws -> MarketMakingCommandResult { try await command(id, "resume") }659660 /** Record one acknowledgement of the go-live checklist. The server identifies the text by the hash of what it served in `locale`. */661 public func acknowledgeGoLive(_ id: String, _ ack: MarketMakingAcknowledgement, locale: String) async throws -> MarketMakingGoLive {662 struct Body: Encodable, Sendable { let step: String; let locale: String; let acknowledged: Bool; let note: String? }663 struct Answer: Decodable, Sendable { let goLive: MarketMakingGoLive }664 var note: String?665 switch ack {666 case .evidence(let d): guard !d.statement.isEmpty, d.sha256.count == 64 else { throw ApprovalError.inconsistent("the evidence was not displayed") }667 case .jurisdiction(let d): guard SHA256Digest.hash(Data(d.jurisdiction.text.utf8)).hex == d.jurisdiction.sha256 else { throw ApprovalError.inconsistent("the jurisdiction text does not match its hash") }668 case .testnet(let n): note = n.flatMap { $0.isEmpty ? nil : String($0.prefix(500)) }669 }670 return try await client.post("/mm/agents/\(seg(id))/golive/ack", body: Body(step: ack.step, locale: locale, acknowledged: true, note: note), as: Answer.self).goLive671 }672673 /** Reconcile a lost approval answer and signer-side orphans of quoting mandates. */674 public func recoverMarketMaking() async throws -> MarketMakingRecovery { try await client.post("/mm/recover") }675}676