SPB Git

Repository Public

README.md 34.3 KB 359 lines markdown

1# Native test vectors — canonical bytes and passkey challenges23Machine-generated by `scripts/native-vectors.mts` (`npx tsx scripts/native-vectors.mts` from the repository root) with the4**real** TypeScript canonical functions of this repository, at commit `52e513b` + worktree `native-clients`. A native client5(Swift) must reproduce `canonicalHex` and `hashHex` byte for byte from `object`.67Each `SPW-<DOMAIN>.json` is a JSON array of89```json10{ "name": "...", "domain": "SPW-…-v1", "source": "<TS path> <exported function>", "object": { … }, "canonicalHex": "…", "hashHex": "…" }11```1213- `object` — the object as JSON, as the API serves it (it went through `JSON.parse(JSON.stringify(…))`).14- `canonicalHex` — hex of the canonical bytes. Present in **every** vector of this set.15- `hashHex` — hex of `SHA-256(canonical bytes)`. The WebAuthn challenge is these 32 bytes (base64url, no padding, in16  `options.challenge`). Exception: `SPW-ORDER-INTENT-v1`, `SPW-ORDER-BODY-v1`, `SPW-TRADING-MANDATE-v1` and17  `SPW-QUOTING-SECTION-v1` hashes are never a challenge by themselves (§4).1819The generator is deterministic (fixed UUIDs and timestamps, no clock, no randomness, no network, no database query): two runs20give identical files. It asserts for every vector that `sha256(canonicalHex) == hashHex` where `hashHex` comes from the real21hash function, and that the bytes start with the domain string.2223## 0. Where `canonicalHex` comes from2425| Case | Domains | How |26|---|---|---|27| The real function returns the bytes | INTENT, NFT-INTENT, NFT-ALLOW, UTXO-LOCKS, MANDATE, VENUE-AUTH, VENUE-ORDER, VENUE-LEVERAGE, VENUE-WITHDRAW, VENUE-MANDATE, VENUE-QUOTING-MANDATE, GMX-AUTH, TRADING-MANDATE, QUOTING-SECTION, ORDER-INTENT, BRIDGE-MINT, BRIDGE-MINT-SOL, BRIDGE-RECLAIM | bytes of the real function, hash of the real function (for the three BRIDGE-* domains the real code has only a bytes function; callers take `sha256` of it — `services/api/src/bridge.ts:278`, signer `signer.ts:307`) |28| The real function returns only the hash | SOL-TOKEN-ACCOUNT (`solTokenAccountHash`), ORDER-BODY (`orderBodyHashHex`) | bytes rebuilt with the real exported framing `canonicalEncode` (`packages/derivatives/src/live/canonical.ts:26/240`) — for ORDER-BODY from the real `canonicalOrderFields` minus its last three pairs; for SOL-TOKEN-ACCOUNT from the field list of §2.14 — then **asserted** to hash to the value of the real function |29| JSON-canonical, hash only | RISK-INTENT, GMX-RISK-INTENT, RISK-LIMITS-INTENT, RISK-SWITCH-INTENT, RISK-AUTO-INTENT, TRADING-MANDATE-APPROVAL (`canonicalIntentHash`, whose `stableJson` is not exported) | bytes = `domain + "\n" +` the exported `canonicalJson` of `services/api/src/trading-api/key-model.ts:30`, **asserted** to hash to the value of the real `canonicalIntentHash` / `riskIntentHash` / `gmxRiskIntentHash` |30| JSON-canonical, real pieces | APIKEY-INTENT | real `canonicalJson` + real `intentChallenge` |31| Unexported function | ENROLL (`services/api/src/auth.ts:16`, not exported) | hash from the signer's exported copy `services/isolated-signer/src/signer.ts:598`; bytes = the same string, asserted against it |3233Since SHA-256 equality is asserted, a rebuilt `canonicalHex` is exactly the byte string the real function hashed.3435**Not generated: none.** Every domain of the request could be produced by a real function. The API modules import without a36database (dummy `SPW_ORIGIN`, `SPW_RP_ID`, `DATABASE_URL`, `SPW_SIGNER_SECRET`; `postgres()` is lazy and nothing is queried).3738Domain strings found in the source and deliberately **not** covered, because no passkey signs them: `SPW-AUDIT-v1`39(`packages/core/src/audit.ts:16`, audit chain) and `SPW-CLIENT-ORDER-ID-v1` (`packages/trading/src/orders/idempotency.ts:17`).4041## 1. The three serializations4243### 1.1 Framed (name, value) pairs — "F"4445Used by 21 domains. One implementation, copied in several files (`intent.ts:160-171`, `nft-intent.ts:78`, `mandate.ts:47-49`,46`canonical.ts:26`, `collateral.ts:156`, `gmx.ts:468`, `cctp-sol-tx.ts:165`); all byte-identical in behaviour.4748```49bytes = UTF8(domain) || 0x00 || for each (name, value) in the FIXED order of the code:50          u16 big-endian (byte length of UTF8(name)) || u32 big-endian (byte length of UTF8(value)) || UTF8(name) || UTF8(value)51hash  = SHA-256(bytes)52```5354- The separator after the domain is **one zero byte**. No terminator at the end. Lengths are **byte** lengths of the UTF-855  encoding (vectors with `é`, `—`, `«»`, `°` are included), header = 2 + 4 bytes, both **big-endian**, name length first.56- Field order is fixed by the code, **never** by JSON key order.57- Value stringification (every value is a string before framing):58  - **string**: as is (no trimming, no case change; EIP-55 addresses keep their case).59  - **integer number** (`v`, `decimals`, timestamps, nonces, counts…): decimal digits, no sign, no leading zero, no exponent60    (`String(n)` of a safe integer). `v` is always `"1"`.61  - **boolean**: `"1"` / `"0"`.62  - **base-unit amounts** (`amount`, `maxFee`, gas values…): already decimal strings in the object; framed as is.63  - **decimal string** `canon(x)` (prices, sizes, USD amounts of the derivatives/trading objects — marked *canon* below): remove64    trailing zeros of the fraction, then remove a trailing `.`; a zero value is `"0"`. The integer part is untouched; never an65    exponent. `"2500.50"→"2500.5"`, `"25000.000"→"25000"`, `"68500.0"→"68500"`, `"0.00"→"0"`, `"0.0000123400"→"0.00001234"`.66    (`packages/derivatives/src/decimal.ts:34-73`, `D.str(D.from(x))`.) The object served by the API may or may not already be67    canonical: always apply it.68  - **null** (where the schema allows it): the **empty string** `""` — the pair is still present.69  - **absent optional field**: per domain, either the pair is **absent**, or (only `gmx.orderKey`) present with `""`. Stated per70    domain below.71  - **lists**: per domain — either expanded (`*.count` + indexed names, order kept), or sorted and joined with `,`.72  - **maps**: expanded to one pair per key, keys sorted.73- **Sorting** is JavaScript's default: by UTF-16 code unit, ascending, no locale. For ASCII this is plain byte order:74  digits < upper case < `_` < lower case; `.` < digits. (Vector `synthetic-x-map-key-sort-order`: `A, B, a.1, a1, aB, a_1, ab, b`.)75  In Swift: `sorted { $0.utf16.lexicographicallyPrecedes($1.utf16) }`, never `localizedCompare`.7677### 1.2 Canonical JSON — "J"7879```80bytes = UTF8(domain + "\n" + J(object))          hash = SHA-256(bytes)81```8283`J` = JSON with **object keys sorted at every depth** (same UTF-16 code-unit order), **no whitespace**, arrays in their own84order, and every scalar written as JavaScript's `JSON.stringify` writes it:8586- strings: `"` → `\"`, `\` → `\\`, U+0008 `\b`, U+0009 `\t`, U+000A `\n`, U+000C `\f`, U+000D `\r`, any other code unit below87  U+0020 → `\u00xx` (4 hex digits, **lower case**); everything else **raw UTF-8**: `/` is NOT escaped (Swift's `JSONEncoder`88  /`JSONSerialization` write `\/` unless `.withoutEscapingSlashes`), U+007F raw, non-ASCII raw (not `\uXXXX`), emoji raw;89- `null`, `true`, `false`;90- numbers: integers as plain digits. Non-integers occur in ONE place (`SPW-APIKEY-INTENT-v1` `limits.*NotionalUsd`): the91  shortest round-trip form of ECMAScript (`2500.5`, `0.1`, `100000000`) — an integer-valued double has **no** `.0`.92- a key whose value is `undefined` does not exist in JSON; the object you receive has no such key. (Difference between the93  two server implementations, not visible on the wire: `stableJson` of `exec.ts:151` would write an explicit `undefined`94  member as `null`, `canonicalJson` of `key-model.ts:30` drops it. No such member is produced by the code read.)9596Vectors `release-kill-switch-engaged-by-owner` and `…-control-chars` exercise the escaping rules.9798Advice: re-serialize the JSON tree you received (keep integers as integers; do not round-trip amounts through `Double`).99100### 1.3 Line-joined — "L"101102```103bytes = UTF8(parts joined with "\n")  (the domain is the first part; no trailing newline)      hash = SHA-256(bytes)104```105106## 2. Signer-verified objects107108"Signer" = the isolated signer recomputes the same hash from the object it is sent and verifies the WebAuthn assertion over109it; the API only relays. `P` = prepare route (issues `options.challenge`), `A` = approve route. All routes are `POST`.110111### 2.1 `SPW-INTENT-v1` — F — `packages/core/src/intent.ts:145` `canonicalBytes`, `:174` `intentHash` (field list `:109-142`)112113Order: `v, proposalId, keyId, network, chainRef, asset, symbol, decimals, amount, from, to, maxFee, createdAt, expiresAt,114policyVersion`, then each section **only if present in the object**, in this order:1151161. `evm.nonce, evm.gasLimit, evm.maxFeePerGas, evm.maxPriorityFeePerGas`1172. `btc.inputs.count`, then per input k = 0… in array order `btc.inputs.k.txid, btc.inputs.k.vout, btc.inputs.k.value`, then `btc.change, btc.fee`1183. `sol.recentBlockhash, sol.lastValidBlockHeight, sol.createAta` (bool), `sol.computeUnitLimit, sol.computeUnitPrice`1194. `swap.provider, swap.toAsset, swap.minOut, swap.router, swap.dataHash, swap.approveGas`1205. `bridge.provider, bridge.toNetwork, bridge.toDomain, bridge.maxFee, bridge.minFinalityThreshold, bridge.messenger, bridge.transmitter, bridge.approveGas`, then `bridge.recipient` **only if present**1216. `xswap.provider, xswap.toNetwork, xswap.toAsset, xswap.minOut, xswap.limit, xswap.memo, xswap.vault, xswap.vaultPubKey, xswap.router` (may be `""` for a UTXO source — pair present), `xswap.expiry, xswap.approveGas`1227. `venueDeposit.venue, venueDeposit.venueNetwork, venueDeposit.route, venueDeposit.bridge, venueDeposit.minAmount`1238. `gmx.venue, gmx.action, gmx.authorizationId, gmx.exchangeRouter, gmx.router, gmx.orderVault, gmx.market, gmx.indexToken, gmx.collateralToken, gmx.orderType, gmx.isLong` (bool), `gmx.sizeDeltaUsd, gmx.acceptablePrice, gmx.triggerPrice, gmx.executionFee, gmx.approveGas, gmx.orderKey` — **`gmx.orderKey` is always framed: `""` when absent**1249. `memo` **only if present** (an empty memo `""` is present: vector `transfer-cosmos-empty-memo`) — note: after every section, before `x`12510. `x.<key>` for each key of `x` in sorted order (plugin families: xrpl, cosmos, stellar, tron, aptos, sui, near, ton, cardano, polkadot, bch)126127No decimal canonicalization here: every amount is a base-unit integer string, framed as is. The function also validates128(strict schema; chain section must match the network family; exclusions between sections) — a client only needs the bytes.129130Routes (all approved through `A = /api/v1/transfers/proposals/:id/approve {assertion}` unless said):131132| Kind | P | Canonical object in the P response |133|---|---|---|134| transfer | `/api/v1/transfers/proposals/:id/request-approval` (`transfers.ts:181-222`) | **`intent`** (`{ proposal, intent, options }`); hash also at `proposal.intentHash` |135| swap (KyberSwap `swap-exec.ts:159`, Jupiter `swap-exec-sol.ts:275`) | `/api/v1/swap/proposals` | **NOT returned** — `{ proposal, options }` |136| bridge (EVM source `bridge.ts:250`, Solana source `bridge-sol.ts:270`) | `/api/v1/bridge/proposals` | **NOT returned** — `{ proposal, options }` |137| xswap (`xswap.ts:267`) | `/api/v1/xswap/proposals` | **NOT returned** — `{ proposal, options }` |138| idempotent replay of the three above (`prepare-common.ts:54`) | same routes, same `Idempotency-Key` | **NOT returned** — `{ proposal, options, replayed: true }` |139| venueDeposit (`derivatives/collateral.ts:343`) | `/api/v1/derivatives/live/accounts/:id/collateral/deposit/prepare`; A = `…/collateral/deposit/:opId/approve` | **`intent`**, `options` (no hash field) |140| gmx (`derivatives/gmx-exec.ts:567`) | `/api/v1/derivatives/gmx/orders`, `…/gmx/positions/close`, `…/gmx/orders/:opId/cancel`; A = `/api/v1/derivatives/gmx/operations/:opId/approve` | **`intent`**, `options` (no hash field) |141142For the "NOT returned" rows the proposal view (`transfers.ts:39` `view`) carries `intentHash` but not the intent, and lacks143`keyId`, `chainRef`, `createdAt`, `policyVersion`, the `evm`/`sol`/`btc` section, `swap.dataHash/router/approveGas`,144`bridge.toDomain/messenger/transmitter`, `xswap.memo/vault/expiry`: **the client cannot rebuild the intent**; it can only compare145`options.challenge` with `proposal.intentHash`, which proves nothing about what is signed.146Verified by: signer (`services/isolated-signer/src/signer.ts:441` `sign` → `intentHash`).147148### 2.2 `SPW-NFT-INTENT-v1` — F — `packages/core/src/nft-intent.ts:95` `nftCanonicalBytes`, `:114` `nftIntentHash`149150Order: `v, kind, proposalId, keyId, network, chainRef, standard, asset, quantity, program, from, to, maxFee, createdAt, expiresAt,151policyVersion, nftPolicyVersion`; then `tokenId` only if present (**after** `nftPolicyVersion`, not next to `asset`); then if152`evm`: `evm.nonce, evm.gasLimit, evm.maxFeePerGas, evm.maxPriorityFeePerGas`; if `sol`: `sol.recentBlockhash,153sol.lastValidBlockHeight, sol.computeUnitLimit, sol.computeUnitPrice`, then each only if present, in this order:154`sol.tokenProgram, sol.createAta` (bool), `sol.ruleSet, sol.collection`. Note `sol.createAta` is optional here and sits in a155different position than in `SPW-INTENT-v1`.156P `/api/v1/nfts/transfer/prepare` → **`intent`**, `options`, hash at `proposal.intentHash`; A `/api/v1/nfts/transfer/:id/approve`.157Verified by: signer (`services/isolated-signer/src/nft.ts:54`).158159### 2.3 `SPW-NFT-ALLOW-v1` — F — `nft-intent.ts:162` `nftAllowBytes`, `:167` `nftAllowHash`160161Order: `v, kind, requestId, keyId, network, action, address, createdAt, expiresAt, policyVersion`.162P `/api/v1/nfts/allow/prepare` → **`intent`**, `options` (no hash field); A `/api/v1/nfts/allow/approve {intent, assertion}` (the163client sends the intent back). Signer: `nft.ts:157`.164165### 2.4 `SPW-UTXO-LOCKS-v1` — F — `nft-intent.ts:135` `utxoLockBytes`, `:144` `utxoLockHash`166167Order: `v, kind, requestId, keyId, network, action, reason, outpoints.count`, per outpoint k in **array order (not sorted)**168`outpoints.k.txid, outpoints.k.vout`, then `createdAt, expiresAt, policyVersion`.169P `/api/v1/utxo-locks/prepare` → **`intent`**, `hash`, `options`; A `/api/v1/utxo-locks/approve {intent, assertion}`. Signer: `nft.ts:131`.170171### 2.5 `SPW-MANDATE-v1` (spot agent vault mandate) — F — `packages/core/src/mandate.ts:41` `mandateBytes`, `:52` `mandateHash`172173Order: `v, mandateId, keyId, vaultIndex, vault, network, provider, assets` (= asset ids **sorted, joined with `,`**), then174`maxOrder.<assetId>` for each key of `maxOrder` sorted, then `maxDaily.<assetId>` for each key of `maxDaily` sorted, then175`maxOrdersPerDay, maxSlippageBps, createdAt, expiresAt, strategySha256, label`. Asset ids keep their case (`0x8335…` sorts176before `native`). The key sets of the two maps may be smaller than `assets`.177P `/api/v1/agents/:id/mandate/prepare` → **`mandate`**, `hash`, `options` (`agents/mandate-write.ts:47-50`); A178`/api/v1/agents/:id/mandate/approve`. Signer: `signer.ts:141`.179180### 2.6 `SPW-VENUE-AUTH-v1` — F — `packages/derivatives/src/live/canonical.ts:87` `venueAuthorizationBytes`, `:98`181182Order: `v, authorizationId, keyId, venue, network, account, agentAddress, agentName, mode, policy.allowedInstruments` (sorted,183`,`-joined), `policy.maxLeverage, policy.maxOrderNotional` (*canon*), `policy.maxPositionNotional` (*canon*),184`policy.maxGrossExposure` (*canon*), `policy.maxOrdersPerDay, policy.maxPriceDeviationBps, createdAt, expiresAt, approveNonce, ackSha256`.185P `/api/v1/derivatives/live/accounts/:id/authorization/prepare` → **`authorization`**, `hash`, `options`; A186`…/authorization/approve {assertion, acknowledged: true}`. Signer: `venue.ts:62`.187188### 2.7 `SPW-VENUE-ORDER-v1` — F — `canonical.ts:150` `venueOrderBytes`, `:159`189190Order: `v, authorizationId, venue, network, account, kind, instrument, side, type, size` (*canon*), `price` (*canon*),191`triggerPrice` (**`""` when null**, else *canon*), `reduceOnly` (bool), `tif, clientId, nonce, expiresAt` — `nonce`/`expiresAt`192are unix **milliseconds** and come last although they are declared first in the schema.193P `/api/v1/derivatives/live/accounts/:id/orders` and `…/accounts/:id/close` → **`canonical`** (also `order.canonical`), `hash`,194`options` (null when not approvable); A `…/orders/:clientId/approve`. Signer: `venue.ts:205`.195196### 2.8 `SPW-VENUE-LEVERAGE-v1` — F — `canonical.ts:170` `venueLeverageBytes`, `:177`197198Order: `v, authorizationId, venue, network, account, kind, instrument, leverage, marginMode, nonce, expiresAt`.199P `/api/v1/derivatives/live/accounts/:id/leverage` → **`canonical`**, `hash`, `options`; A `…/leverage/:actionId/approve`. Signer: `venue.ts:221`.200201### 2.9 `SPW-VENUE-WITHDRAW-v1` — F — `packages/derivatives/src/live/collateral.ts:150` `venueWithdrawalBytes`, `:168`202203Order: `v, withdrawalId, keyId, venue, network, account, destination, amount` (*canon*), `fee` (*canon*), `time` (ms),204`createdAt, expiresAt` (seconds).205P `/api/v1/derivatives/live/accounts/:id/collateral/withdraw/prepare` → **`withdrawal`**, `hash`, `options`; A206`…/collateral/withdraw/:opId/approve`. Signer: `venue-collateral.ts:53`.207208### 2.10 `SPW-VENUE-MANDATE-v1` (derivative mandate) — F — `packages/derivatives/src/live/mandate.ts:71` `venueMandateBytes`, `:82`209210Order: `v, mandateId, authorizationId, keyId, venue, network, account, agentAddress, strategySha256, agentId, instruments,211maxOrderNotional` (*canon*), `maxGrossExposure` (*canon*), `maxOrdersPerDay, maxOrdersPerHour, maxDailyTurnover` (*canon*),212`floorEquity` (*canon*), `maxPriceDeviationBps, createdAt, expiresAt, ackSha256`.213`instruments` = ONE value: the entries **sorted by `instrument`**, each written `instrument|maxLeverage|canon(maxPositionNotional)`, joined with `,`.214P, three ways: (a) `/api/v1/derivatives/live/accounts/:id/mandate/prepare` → **`mandate`**, `hash`, `options`; (b)215`/api/v1/mandates/:id/approve/prepare` → **`signer.mandate`**, `signer.hash`, `signer.options`; (c)216`/api/v1/agents/:id/perp/live/prepare` → **`mandate`**, `hash`, `options`. A: (a) `…/mandate/approve {assertion, acknowledged}`;217(b) `/api/v1/mandates/:id/approve {assertion, bindingAssertion, acknowledged}`; (c) `/api/v1/agents/:id/perp/live/approve`.218Signer: `venue-mandate.ts:59`.219220### 2.11 `SPW-VENUE-QUOTING-MANDATE-v1` — F — `packages/derivatives/src/live/quoting.ts:93` `venueQuotingMandateBytes`, `:106`221222Order: `v, mandateId, authorizationId, keyId, venue, network, account, agentAddress, strategySha256, agentId, instruments,223maxRestingTotal, maxGrossExposure` (*canon*), `minHalfSpreadBps, maxDistanceBps, maxReduceDeviationBps, floorEquity` (*canon*),224`rate.burstActions, rate.actionsPerMinute, rate.ordersPerHour, rate.ordersPerDay, rate.dailyTurnover` (*canon*),225`deadManSeconds, createdAt, expiresAt, ackSha256`.226`instruments` = entries sorted by `instrument`, each227`instrument|maxLeverage|canon(maxQuoteNotional)|maxRestingPerSide|canon(maxRestingNotionalPerSide)|canon(maxInventoryNotional)`, joined with `,`.228P `/api/v1/mandates/:id/approve/prepare` (quoting branch, `mandates/service.ts:372-379`) → **`signer.mandate`**, `signer.hash`229(also `hashes.signerMandate`), `signer.options`; A `/api/v1/mandates/:id/approve` (`assertion`). Signer: `venue-quoting.ts:81`.230231### 2.12 `SPW-GMX-AUTH-v1` — F — `packages/derivatives/src/live/gmx.ts:460` `gmxAuthorizationBytes`, `:474`232233Order: `v, authorizationId, keyId, venue, network, account, mode, contracts, exchangeRouter, policy.allowedMarkets` (sorted,234`,`-joined — **case-sensitive sort of EIP-55 addresses**: upper-case hex letters sort before lower-case), `policy.maxLeverage,235policy.maxOrderSizeUsd` (*canon*), `policy.maxOrdersPerDay, policy.maxPriceDeviationBps, policy.maxExecutionFeeWei, createdAt, expiresAt, ackSha256`.236P `/api/v1/derivatives/gmx/authorization/prepare` → **`authorization`**, `hash`, `options`; A237`…/gmx/authorization/approve {authorization, assertion}` (the client sends it back). Signer: `venue-gmx.ts:40`.238239### 2.13 CCTP second legs — L240241| Domain | Function | Parts, joined with `\n` |242|---|---|---|243| `SPW-BRIDGE-MINT-v1` | `packages/core/src/cctp.ts:284` `cctpMintRetryBytes(proposalId, messageHash, gas)` | domain, `proposalId`, `messageHash`, `gas.nonce`, `gas.gasLimit`, `gas.maxFeePerGas`, `gas.maxPriorityFeePerGas` |244| `SPW-BRIDGE-MINT-SOL-v1` | `packages/core/src/cctp-sol-tx.ts:141` `cctpSolMintRetryBytes(proposalId, messageHash, sol)` | domain, `proposalId`, `messageHash`, `sol.recentBlockhash`, `sol.lastValidBlockHeight`, `sol.computeUnitLimit`, `sol.computeUnitPrice` |245| `SPW-BRIDGE-RECLAIM-v1` | `cctp-sol-tx.ts:144` `cctpSolReclaimBytes(proposalId, eventAccount, messageHash, sol)` | domain, `proposalId`, `eventAccount`, `messageHash`, then the same four `sol` values |246247`messageHash` is the string the server holds (`0x` + 64 hex, as returned by `cctpMessageHash`). The vector `object` is248`{ proposalId, messageHash, gas | sol [, eventAccount] }` — the arguments by name; it is **not** an object any route serves.249250- MINT / MINT-SOL: P `/api/v1/bridge/proposals/:id/retry-mint/options` → `{ proposal, options }`: **NOT returned** (neither251  `messageHash` nor the gas / budget; only `proposal.id`). A `/api/v1/bridge/proposals/:id/retry-mint`. Signer: `signer.ts:307` / `:340`.252- RECLAIM: P `/api/v1/bridge/proposals/:id/reclaim/options` → `{ proposal, options, deposit, networkFee }`: **NOT returned**253  (`proposal.bridge.sol.eventAccount` is there; `messageHash` and the budget are not). A `…/reclaim`. Signer: `signer.ts:377`.254255### 2.14 `SPW-SOL-TOKEN-ACCOUNT-v1` — F — `packages/core/src/cctp-sol-tx.ts:160` `solTokenAccountHash` (hash only)256257Order: `v, requestId, keyId, network, chainRef, owner, mint, tokenAccount, maxFee, createdAt, expiresAt, policyVersion,258sol.recentBlockhash, sol.lastValidBlockHeight, sol.computeUnitLimit, sol.computeUnitPrice`.259P `/api/v1/bridge/solana/token-account/options` (`bridge-sol.ts:514-541`) → `{ requestId, owner, tokenAccount, rent, rentDisplay,260networkFee, networkFeeDisplay, symbol, expiresAt, options }`: **NOT returned** (missing `keyId`, `chainRef`, `mint`, `maxFee`261= networkFee + the fixed rent bound, `createdAt` = `expiresAt − 50`, `policyVersion`, the whole `sol` section). A262`/api/v1/bridge/solana/token-account {requestId, assertion}`. Signer: `signer.ts:393`.263264### 2.15 `SPW-ENROLL-v1` — L — `services/api/src/auth.ts:16` `enrollChallenge` (not exported); signer copy `services/isolated-signer/src/signer.ts:598`265266`SHA-256("SPW-ENROLL-v1\n" + credentialId + "\n" + publicKey)` — `credentialId` = the WebAuthn credential id (base64url, no267padding), `publicKey` = base64url (no padding) of the credential public key bytes as `@simplewebauthn/server` returns them at268registration (COSE key; `auth.ts:83`). The vector `object` is `{ credentialId, publicKey }` (argument names, not a served object).269P `/api/v1/security/devices/verify` → `{ pendingId, options }`: **partly returned** — `pendingId` is the credential id, the270`publicKey` string is not served; the new device holds its own public key from its registration response (that those bytes are271the same COSE encoding was not verified here). A `/api/v1/security/devices/confirm {pendingId, assertion}`. Signer:272`signer.ts:122` → `:598`.273274## 3. API-only objects (the signer never sees them) — J275276Verified by the API alone against its own credentials table (`auth.ts:44` `verifyOwnerAssertion`; API keys:277`verifyAuthenticationResponse` in `trading-api/keys.ts:126-134`). They guard against a stolen session; nothing is signed on278their strength. All are `domain + "\n" + J(intent)`; hash function `services/api/src/derivatives/exec.ts:154`279`canonicalIntentHash` (`stableJson` `:151`) except API keys. Every intent built by `risk/passkey.ts:27` `prepareIntent` is the280body **plus** `nonce` (UUID), `createdAt`, `expiresAt` (unix **ms**, TTL 300 000).281282| Domain | Built at | Intent members (before sorting) | P → A | P response |283|---|---|---|---|---|284| `SPW-RISK-INTENT-v1` | `exec.ts:155` `riskIntentHash`, `:579-600` `prepareRisk` | `v, kind ('policy'\|'resume'\|'rebase'), accountId, venue, network, account, authorizationId, policy (object\|null), loosened[], subject (string\|null), nonce, createdAt, expiresAt` | `/api/v1/derivatives/live/accounts/:id/policy/prepare`, `…/resume/prepare`, `…/rebase/prepare` → `…/policy/approve`, `…/resume`, `…/rebase` | `{ needed, kind, loosened, **intent**, hash, options, expiresAt }` (all null when `needed: false`) |285| `SPW-GMX-RISK-INTENT-v1` | `derivatives/gmx-exec.ts:118` `gmxRiskIntentHash` | `v, kind ('gmx-limits'\|'gmx-resume'), authorizationId, limits ({maxDailyLoss, maxTotalLoss}\|null), loosened[], subject, nonce, createdAt, expiresAt` | `/api/v1/derivatives/gmx/limits/prepare`, `…/gmx/resume/prepare` → `…/gmx/limits/approve`, `…/gmx/resume` | **`intent`**, `hash`, `options` |286| `SPW-RISK-SWITCH-INTENT-v1` | `risk/service.ts:174` | `v, kind ('kill_switch'\|'read_only'), engagedAt (ms\|null), engagedBy ("<kind>:<id>"\|null), reason (string\|null)` + stamp | `/api/v1/risk/kill-switch/release/prepare`, `/api/v1/risk/read-only/release/prepare` → `…/release` | `{ needed, kind, **intent**, hash, options, expiresAt }` |287| `SPW-RISK-LIMITS-INTENT-v1` | `risk/service.ts:244` | `v, kind: 'limits', mode ('paper'\|'live'), limits (RiskLimits, `packages/trading/src/risk/engine.ts:81`; absent members are absent), loosened[]` + stamp | `/api/v1/risk/limits/:mode/prepare` → `/api/v1/risk/limits/:mode/approve` | `{ needed, loosened, **intent**, hash, options, expiresAt }` |288| `SPW-RISK-AUTO-INTENT-v1` | `risk/service.ts:271` | `v, kind: 'auto', auto ({totalLoss, drawdown, dailyLoss} booleans), loosened[]` + stamp | `/api/v1/risk/auto/prepare` → `/api/v1/risk/auto {auto, assertion}` | same shape |289| `SPW-TRADING-MANDATE-APPROVAL-v1` | `mandates/service.ts:71`, `:351` (directional), `:374` (quoting) | `v, kind: 'trading_mandate_approval', mandateId, tradingMandateHash, principal ("<kind>:<id>"), mode: 'live', signer {shape, mandateHash}, [quotingSectionHash — quoting only, otherwise the key is absent]` + stamp | `/api/v1/mandates/:id/approve/prepare` (also surfaced as `binding` by `/api/v1/agents/:id/perp/live/prepare`) → `/api/v1/mandates/:id/approve`, field **`bindingAssertion`** | **`binding.intent`**, `binding.hash`, `binding.options`, `binding.domain`, `binding.expiresAt` |290| `SPW-APIKEY-INTENT-v1` | `trading-api/key-model.ts:30` `canonicalJson`, `:38` `intentChallenge`; `trading-api/keys.ts:76` `storeIntent` | `v, action, intentId, origin, preparedAt (ISO string)` + create: `key {id, name, scopes[], expiresAt (ISO), limits {maxOrderNotionalUsd, maxDailyNotionalUsd: number\|null}, restrictions {networks[], venues[], instruments[], ipAllow[]}, rateLimitPerMin, mandateId\|null}`; rotate: `keyId, newKeyId`; update: `keyId, changes{…}, widening[]` | `/api/v1/developer/keys/prepare`, `…/keys/:id/rotate/prepare`, `…/keys/:id/update/prepare` → `/api/v1/developer/keys`, `…/keys/:id/rotate`, `…/keys/:id/update` `{intentId, assertion}` | `{ intentId, **intent**, sha256, expiresAt, options }` — the hash field is **`sha256`**, not `hash` |291292A live trading-mandate approval is **two** passkey ceremonies in one request: `assertion` over the signer shape293(§2.10 / §2.11, verified by the signer) and `bindingAssertion` over the approval intent (API only). The binding assertion is294stored and verified again on each load (`risk/passkey.ts:62`).295296## 4. Hashes that are embedded, never a challenge by themselves — F297298| Domain | Function | Order | Where it goes |299|---|---|---|---|300| `SPW-TRADING-MANDATE-v1` | `packages/trading/src/mandate/trading-mandate.ts:97` `tradingMandateBytes`, `:111` | `v, mandateId, principal.kind, principal.id, accounts, venues, networks, instruments, marketKinds, orderTypes` (each of these six: **sorted, `,`-joined**), `maxCapitalUsd, maxOrderNotionalUsd, maxPositionNotionalUsd, maxLeverage, maxDailyLossUsd, floorEquityUsd` (all *canon*), `createdAt, notBefore, notAfter, frequency.perMinute, frequency.perHour, frequency.perDay, maxSlippageBps, maxFeeUsd` (*canon*), `stopConditions` (sorted, `,`-joined), `mode, strategySha256` (`""` when null), `label` | `tradingMandateHash` of the approval intent (§3) and of the quoting section. Served as `mandate` + `hash` by `/api/v1/mandates/:id/approve/prepare`, as `tradingMandate.mandate` / `.hash` by the perp live prepare |301| `SPW-QUOTING-SECTION-v1` | `packages/trading/src/mandate/quoting-mandate.ts:233` `quotingSectionBytes`, `:245` | `v, mandateId, tradingMandateHash, terms.levelsPerSide, terms.minHalfSpreadBps, terms.maxDistanceBps, terms.burstActions, terms.actionsPerMinute, terms.quotesPerHour, terms.quotesPerDay, terms.dailyTurnoverUsd` (*canon*), `terms.deadManSeconds, engine.policy, engine.configSha256, engine.quoteSizeUsd, engine.softInventoryUsd, engine.hardInventoryUsd` (*canon* ×3), `engine.maxSessionMinutes, engine.hours` (`"<start>-<end>"`, `""` when null), `engine.maxSessionLossUsd` (*canon*), `engine.stopBeforeExpiryS, engine.breakers` (keys sorted, `code=action`, `,`-joined; `""` when empty), `engine.flattenOnStop` (bool) | `quotingSectionHash` of the approval intent. Served as `quoting.section` / `quoting.hash` (also `hashes.quotingSection`) |302| `SPW-ORDER-INTENT-v1` | `packages/trading/src/orders/canonical.ts:119` `canonicalOrderBytes`, `:120`; fields `:105-118` | `v, venue, network, instrument, marketKind, side, type, size, notional, limitPrice, triggerPrice` (each *canon*, `""` when null), `reduceOnly` (bool), `tif, maxSlippageBps, maxFeeUsd` (*canon*), `leverage` (*canon* / `""`), `marginMode` (`""` when null), `mode, principal.kind, principal.id, mandateId` (`""` when null), `clientOrderId, createdAt, expiresAt` (ms) | order identity (`orderHash`); returned as `{order, hash}` by order previews. No `generateAuthenticationOptions` site uses it: a live Hyperliquid order is approved over `SPW-VENUE-ORDER-v1` |303| `SPW-ORDER-BODY-v1` | `orders/canonical.ts:129` `orderBodyHashHex` (hash only) | the same list **without the last three** (`clientOrderId, createdAt, expiresAt`), under the other domain | idempotency comparison only |304305Element formats of the sorted lists of a trading mandate: account = `vault|<network>|<vaultIndex>|<address>` or306`venue_account|<venue>|<network>|<account>`; stop condition = `loss_gte|canon(usd)`, `drawdown_gte|<bps>`,307`consecutive_rejects_gte|<count>`, `data_stale_gte|<ms>`, `signer_unreachable_gte|<ms>` (`trading-mandate.ts:92-93`). The308lists are sorted **after** formatting.309310## 5. One domain string, several meanings — read this before grepping311312- **`SPW-INTENT-v1`** is serialized in exactly ONE place: `packages/core/src/intent.ts:105/160`. Its occurrence in313  `packages/core/src/nft-intent.ts:7` is a comment ("the transfer intent … is not touched"). NFT objects have their own314  domains and their own field lists; only the framing is shared.315- **`SPW-MANDATE-v1`** is serialized in exactly ONE place: `packages/core/src/mandate.ts:47` (the spot vault mandate). Every316  other occurrence is a *label*, not a serialization: `packages/trading/src/mandate/trading-mandate.ts:6` (comment), `:333`,317  `:336`, `:460`, `:504`, `:624` (the value of a `shape` tag / a table of signer shapes), `services/api/src/agents/mandate-write.ts:3`318  and `agents/runtime-routes.ts:54` (comment / shape tag).319- **`SPW-VENUE-MANDATE-v1`**: one serialization (`derivatives/src/live/mandate.ts:73`); elsewhere a `shape` tag — including320  the string value `signer.shape` INSIDE the `SPW-TRADING-MANDATE-APPROVAL-v1` intent, where it is hashed as data.321- **`SPW-VENUE-QUOTING-MANDATE-v1`**, **`SPW-TRADING-MANDATE-v1`**, **`SPW-QUOTING-SECTION-v1`**: one serialization each;322  the other occurrences are constants, shape tags, comments or SQL comments (`services/api/src/db.ts`).323- **`SPW-ORDER-INTENT-v1`** also appears in `services/api/src/trading-api/spec.ts:166` and the generated SDK324  (`packages/trading-sdk/src/generated/openapi.ts:102`) as documentation text.325- **`SPW-ENROLL-v1`**: two independent copies of the same one-liner (API `auth.ts:16`, signer `signer.ts:598`).326- **Two JSON canonicalizers** share the "J" format: `stableJson` (`exec.ts:151`, private) and `canonicalJson`327  (`key-model.ts:30`; a third private copy in `agent-runtime/model.ts:192`, a client copy in `packages/trading-sdk/src/util.ts:10`).328  They agree on every value that can travel as JSON.329- Seconds vs milliseconds: intents, NFT objects, mandates, authorizations use unix **seconds** for `createdAt`/`expiresAt`;330  `SPW-VENUE-ORDER/LEVERAGE` `nonce`/`expiresAt`, `approveNonce`, `VenueWithdrawal.time`, canonical orders and every "J"331  intent stamp use **milliseconds**. Irrelevant for the bytes (digits either way), relevant for display.332333## 6. Routes that do NOT return the full canonical object to the client3343351. `POST /api/v1/swap/proposals` (KyberSwap and Jupiter) — `SPW-INTENT-v1`3362. `POST /api/v1/bridge/proposals` (EVM source and Solana source) — `SPW-INTENT-v1`3373. `POST /api/v1/xswap/proposals` — `SPW-INTENT-v1`3384. any idempotent replay of 1–3 (`prepare-common.ts` `challengeFor`: `{ proposal, options, replayed }`)3395. `POST /api/v1/bridge/proposals/:id/retry-mint/options` — `SPW-BRIDGE-MINT-v1` and `SPW-BRIDGE-MINT-SOL-v1`3406. `POST /api/v1/bridge/proposals/:id/reclaim/options` — `SPW-BRIDGE-RECLAIM-v1`3417. `POST /api/v1/bridge/solana/token-account/options` — `SPW-SOL-TOKEN-ACCOUNT-v1`3428. `POST /api/v1/security/devices/verify` — `SPW-ENROLL-v1` (credential id returned as `pendingId`, `publicKey` not)343344On these routes a native client cannot recompute the challenge; it signs what the server (and then the signer) says. Every345other prepare route of §2–§3 returns the complete object.346347## 7. How this document was checked348349- **Run**: the generator twice → identical files (SHA-256 of all 28 files compared); both output directories identical.350- **Run**: an independent Python recomputation written from the prose of this file (not from the TypeScript) reproduces351  `canonicalHex` and `hashHex` of 52 vectors: all 22 `SPW-INTENT-v1`, both `SPW-VENUE-AUTH-v1`, all 3352  `SPW-TRADING-MANDATE-v1`, all 20 "J" vectors (7 domains), `SPW-BRIDGE-RECLAIM-v1`, both `SPW-BRIDGE-MINT-v1`, both `SPW-ENROLL-v1`.353- **Read, not run**: the route table (paths, response field names, which component verifies). It was established by reading354  `services/api/src` and `services/isolated-signer/src`; no server was started. Not read: the exact shape of355  `GET /api/v1/mandates/:id` and the routes that call the order previews.356- The vectors are schema-valid examples, not transactions: addresses, hashes and block hashes are placeholders (the357  canonical functions validate shape, not chain state). `synthetic-x-map-key-sort-order` is a sort-order probe that no358  plugin would produce; the three BRIDGE-* and the ENROLL `object`s are argument lists, not served objects.359
Files main
Menu

Theme