SPB Git

Repository Public

SP-WALLET-API.md 48.5 KB 527 lines markdown

1# SP Wallet NEXT — the core wallet API contract23The contract of everything a wallet client (web, macOS, iOS) uses outside `/api/v1/trading`. It closes audit finding A14("the core wallet API has no machine-readable contract").56| File | What it is |7|---|---|8| `services/api/src/wallet-api/spec.ts` | The source: schemas, the table of operations, the enumerations, the error catalogue. Pure (zod only). |9| `docs/openapi/wallet-v1.json` | The OpenAPI 3.1 document, generated. |10| `apps/web/src/generated/wallet-api.ts` | TypeScript types for the web app, generated from the document. |11| this file | The conventions, and tables generated from the same source between `GENERATED` markers. |1213The tables below between `<!-- BEGIN GENERATED -->` markers are written by the generator: do not edit them by hand, a test14fails when they differ from what the code gives.1516## 1. How the contract is produced and kept true1718```19services/api/src/wallet-api/spec.ts ──► npx tsx scripts/gen-openapi.mts ──► docs/openapi/wallet-v1.json20                                                                        ├──► apps/web/src/generated/wallet-api.ts21                                                                        └──► the generated sections of this file22```2324`npx tsx scripts/gen-openapi.mts --check` writes nothing and exits 1 when a committed file is stale.2526The trading API registers its routes *from* its table, so its document cannot drift. The wallet routes were written before27their table and shipped native apps decode their answers, so the wallet table *describes* existing routes. Three tests28make that description binding (`services/api/test/wallet-contract.test.ts`, `wallet-api-unit.test.ts`):29301. **Answers are validated against the document.** The test boots the real server on its own database, with a real signer31   process and scripted chain reads and prices, calls every operation, and validates each answer against the response32   schema of the generated document — in *strict* mode: a member the code returns that the schema does not declare fails33   the test, as does a value of an enumeration that is not in its list. Error answers are validated against the error34   model and must carry a code the operation declares.352. **No route is undocumented.** The test enumerates the routes Fastify registered under `/api/v1` and fails when one is36   neither an operation of the table nor under a prefix of the allow-list below (families documented elsewhere).373. **Generated files are current**, and every error code thrown by the wallet's own route files is catalogued (the test38   scans the sources for `new UserError('code', …)`), as is every transfer warning a chain adapter can emit.3940Request schemas are copies of the routes' own zod schemas (those live inside modules that open a database connection when41imported). A request member added to a route without its copy here is not caught by a test today: see section 9.4243## 2. Conventions4445- **Additive.** No member is removed, renamed or retyped. Objects are open: a client ignores members it does not know.46  New routes, new members, and new values only in enumerations declared *open*.47- **Amounts are strings** of integer base units, with a display string computed by exact arithmetic next to them48  (`amount` / `amountDisplay`, `feePaid` / `feePaidDisplay`). Fiat figures are decimal strings with two decimals. Market49  prices are display numbers and never take part in an amount.50- **Estimates are flagged.** `feeEstimate` is an estimate and `feePaid` a fact; a portfolio total has `complete`; a value51  history has `estimatedMarketChange.estimate: true`; analytics buckets say how many movements are `valued` and how many52  are not; fee totals say how many transactions are `unknown`. Nothing computed from estimates is called a realised return.53- **Tolerant enumerations.** Every enumeration is a named component. `x-spw-open: true` → new values may appear: decode54  with an "unknown" fallback. `x-spw-open: false` → frozen. `state` of a proposal is frozen on purpose (shipped native55  builds decode it with a closed enum); the life cycle is read in `lifecycle`, which is open.56- **Errors** are `{ "error": code, "message": English sentence, "data"?: detail }`. Clients translate the code.57  A `bad_request` produced by input validation carries `data.fields: [{ path, code, message }]` — what is expected, never58  the value that was sent.59- **Sessions.** The owner session is a `__Host-spw` HttpOnly cookie; a mutating call also carries `Origin` and60  `X-SPW-CSRF: 1`. An API key opens nothing outside `/api/v1/trading`.61- **Lost answers.** Once an approval left the device its outcome is unknown until the server answers. A client re-reads62  the proposal; it never shows "failed", re-enables Approve or offers Cancel on a lost answer.6364### Enumerations6566<!-- BEGIN GENERATED: enums -->67| Enumeration | New values may appear | Known values |68|---|---|---|69| `ProposalState` | no (frozen) | `draft`, `pending_approval`, `approved`, `signed`, `broadcast`, `confirming`, `finalized`, `rejected`, `expired`, `failed`, `replaced`, `reorged`, `not_broadcast` |70| `Lifecycle` | **yes** — decode with a fallback | `draft`, `awaiting_confirmation`, `awaiting_signature`, `signed`, `broadcasting`, `pending`, `confirming`, `confirmed`, `failed`, `replaced`, `dropped`, `expired`, `rejected`, `not_sent` |71| `ProposalKind` | **yes** — decode with a fallback | `transfer`, `swap`, `bridge`, `xswap`, `gmx`, `nft` |72| `ActivityRowKind` | **yes** — decode with a fallback | `send`, `receive`, `swap`, `bridge`, `gmx` |73| `TransferWarning` | **yes** — decode with a fallback | `new_destination`, `address_poisoning_suspected`, `duplicate_recent`, `contract_destination`, `network_congested`, `creates_account`, `creates_token_account`, `near_creates_account`, `activates_account`, `deploys_wallet`, `destination_not_initialized`, `memo_numeric_id`, `dt_new_account`, `cd_token_outputs`, `l1_fee_unknown` |74| `ProposalErrorCode` | **yes** — decode with a fallback | `broadcast_disabled`, `approval_expired`, `expired_before_approval`, `interrupted_signing`, `not_broadcast_in_time`, `rejected_by_owner`, `signer_refused`, `signer_hash_mismatch`, `broadcast_attempt_failed`, `tx_failed`, `relay_unconfirmed`, `dropped`, `expired_onchain`, `replaced_onchain`, `swap_late`, `swap_approval_reverted`, `swap_would_revert`, `swap_would_revert_approved`, `bridge_late`, `bridge_approval_reverted`, `burn_would_revert`, `burn_would_revert_approved`, `xswap_late`, `xswap_vault_unconfirmed`, `xswap_approval_reverted`, `deposit_would_revert`, `deposit_would_revert_approved`, `sol_swap_unverified`, `sol_swap_expired`, `sol_swap_refused`, `sol_swap_would_fail`, `sol_swap_below_min`, `sol_swap_no_balances`, `sol_burn_mismatch`, `sol_burn_expired`, `sol_burn_refused`, `sol_burn_would_fail` |75| `DepositKind` | **yes** — decode with a fallback | `external`, `internal` |76| `DepositOrigin` | **yes** — decode with a fallback | `transfer`, `swap`, `bridge`, `xswap`, `gmx`, `nft`, `agent_withdrawal`, `venue_withdrawal` |77| `DepositDetection` | **yes** — decode with a fallback | `tx`, `internal_call`, `aggregate` |78| `FlowScope` | no (frozen) | `external`, `internal`, `ownAccounts` |79| `EventType` | **yes** — decode with a fallback | `transfer.state`, `transfer.relay`, `transfer.confirmations`, `deposit.seen`, `deposit.native_window`, `deposit.scan_gap`, `device.added`, `device.revoked`, `session.revoked`, `credentials.mismatch`, `credentials.reconciled`, `settings.saved`, `sessions.revoked`, `login.ok`, `owner.setup`, `addressbook.saved`, `addressbook.removed`, `settings.asset_pref`, `halt.on`, `security.contact_address_changed` |80| `AlertKind` | **yes** — decode with a fallback | `transfer.confirmed`, `transfer.failed`, `transfer.dropped`, `transfer.replaced`, `transfer.expired`, `transfer.recovered`, `swap.confirmed`, `swap.failed`, `bridge.confirmed`, `bridge.failed`, `transfer.stuck`, `deposit.received`, `plan.step_ready`, `plan.paused`, `plan.done`, `agent.order_filled`, `agent.stopped_loss`, `agent.stopped_mandate`, `agent.stopped`, `agent.mm_breaker`, `agent.mm_halted`, `agent.mm_dead_man_switch`, `agent.mm_signer_refusals`, `agent.mm_rate_budget`, `agent.mm_session_ended`, `agent.mandate_revoked`, `agent.data_stale`, `agent.signal_failures`, `agent.research_submitted`, `agent.research_failed`, `mandate.expiring`, `deriv.paper.filled`, `deriv.live.filled`, `deriv.order_rejected`, `deriv.order_unknown`, `deriv.position_opened`, `deriv.position_closed`, `deriv.margin_warning`, `deriv.paper.liquidation`, `deriv.live.liquidation`, `deriv.funding`, `deriv.loss_limit`, `deriv.halt`, `deriv.divergence`, `deriv.divergence_cleared`, `deriv.asset_table_mismatch`, `security.passkey_added`, `security.passkey_revoked`, `security.credential_mismatch`, `security.new_device`, `security.login_failed`, `security.signer_unreachable`, `security.signer_back`, `security.signer_halted`, `security.signer_unhalted`, `security.kill_switch_on`, `security.kill_switch_off`, `security.signer_refused`, `security.pin_mismatch`, `security.audit_broken`, `security.policy_changed`, `system.api_restarted`, `system.worker_failing`, `system.backup_missing`, `system.disk_low`, `system.lab_sandbox_unavailable`, `system.lab_sandbox_back`, `system.lab_sandbox_off`, `conn.down`, `conn.up`, `system.alerts_capped`, `system.test` |81| `AlertSeverity` | no (frozen) | `info`, `warning`, `critical` |82| `AlertGroup` | **yes** — decode with a fallback | `transfers`, `agents`, `derivatives`, `security`, `system` |83| `Currency` | no (frozen) | `USD`, `CAD` |84| `SearchMatch` | **yes** — decode with a fallback | `symbol`, `name`, `network`, `contract`, `label`, `address`, `note`, `txid`, `amount` |85<!-- END GENERATED: enums -->8687## 3. Routes8889<!-- BEGIN GENERATED: routes -->90| Method | Path | Tag | Session | Since | Summary |91|---|---|---|---|---|---|92| GET | `/api/v1/health/live` | Meta | public | v1 | Liveness |93| GET | `/api/v1/health/ready` | Meta | owner | v1 | Readiness: database, signer, networks, data sources |94| GET | `/api/v1/openapi.json` | Meta | owner | NEXT | This document |95| GET | `/api/v1/auth/state` | Auth | public | v1 | Is the wallet set up, and is this client signed in |96| POST | `/api/v1/auth/setup/options` | Auth | public | v1 | One-time setup: passkey creation options |97| POST | `/api/v1/auth/setup/verify` | Auth | public | v1 | One-time setup: enrol the first passkey with the signer's setup token |98| POST | `/api/v1/auth/login/options` | Auth | public | v1 | Sign-in: assertion options |99| POST | `/api/v1/auth/login/verify` | Auth | public | v1 | Sign-in: verify the assertion, open a session |100| POST | `/api/v1/auth/logout` | Auth | public | v1 | End this session |101| GET | `/api/v1/networks` | Wallet | owner | v1 | The networks of the wallet, with their verified assets and their health |102| GET | `/api/v1/assets` | Wallet | owner | v1 | The verified asset registry, flat |103| GET | `/api/v1/accounts` | Wallet | owner | v1 | The wallet's own address on every network |104| GET | `/api/v1/assets/prefs` | Wallet | owner | NEXT | Hidden and favourite assets |105| PUT | `/api/v1/assets/prefs/{network}/{asset}` | Wallet | owner | NEXT | Hide, show or favourite one asset |106| GET | `/api/v1/market/{symbol}` | Wallet | owner | v1 | Price history of one asset |107| GET | `/api/v1/portfolio` | Portfolio | owner | v1 | Balances with provenance, prices, the server-side summary and the operations in flight |108| GET | `/api/v1/portfolio/history` | Portfolio | owner | NEXT | Value of the wallet over time, with what entered and left |109| POST | `/api/v1/transfers/proposals` | Transfers | owner | v1 | Prepare a transfer: validation, fee estimate, policy pre-check, warnings |110| GET | `/api/v1/transfers/proposals/{id}` | Transfers | owner | v1 | One proposal |111| GET | `/api/v1/transfers/{id}/status` | Transfers | owner | v1 | The short status of one proposal |112| POST | `/api/v1/transfers/proposals/{id}/request-approval` | Transfers | owner | v1 | Freeze the exact transaction and get the passkey challenge |113| POST | `/api/v1/transfers/proposals/{id}/approve` | Transfers | owner | v1 | Approve with the passkey assertion over the intent hash; sign and relay |114| POST | `/api/v1/transfers/proposals/{id}/reject` | Transfers | owner | v1 | Reject a draft or a proposal awaiting approval |115| GET | `/api/v1/activity` | Activity | owner | v1 | Operations and receipts of the wallet, newest first |116| GET | `/api/v1/export/activity.csv` | Activity | owner | v1 | Every operation and receipt as CSV (text/csv) |117| GET | `/api/v1/addressbook` | AddressBook | owner | v1 | Contacts (legacy shape) |118| POST | `/api/v1/addressbook` | AddressBook | owner | v1 | Create a contact, or relabel the one that has this address |119| PATCH | `/api/v1/addressbook/{id}` | AddressBook | owner | NEXT | Edit a contact: label, note, favourite, address |120| DELETE | `/api/v1/addressbook/{id}` | AddressBook | owner | v1 | Delete a contact |121| GET | `/api/v1/contacts` | AddressBook | owner | NEXT | Contacts with note and favourite, favourites first |122| GET | `/api/v1/settings` | Settings | owner | v1 | Account settings shared by every device |123| PUT | `/api/v1/settings` | Settings | owner | v1 | Change settings (any subset) |124| GET | `/api/v1/security/overview` | Security | owner | v1 | Signer state, passkeys (both lists), sessions |125| GET | `/api/v1/security/logins` | Security | owner | NEXT | The last sign-ins |126| GET | `/api/v1/security/audit` | Security | owner | v1 | The audit hash chain, newest first |127| GET | `/api/v1/security/devices` | Security | owner | v1 | Passkeys known to the API |128| POST | `/api/v1/security/devices/options` | Security | owner | v1 | Add a passkey, step 1: creation options |129| POST | `/api/v1/security/devices/verify` | Security | owner | v1 | Add a passkey, step 2: verify the new passkey, get the request an ENROLLED passkey must approve |130| POST | `/api/v1/security/devices/confirm` | Security | owner | v1 | Add a passkey, step 3: the enrolled passkey's assertion; the signer verifies it and pins the new passkey |131| POST | `/api/v1/security/devices/revoke/options` | Security | owner | NEXT | Revoke a passkey, step 1: the request ANOTHER enrolled passkey must approve |132| POST | `/api/v1/security/devices/revoke/confirm` | Security | owner | NEXT | Revoke a passkey, step 2: the approval; the signer removes it, its sessions end |133| POST | `/api/v1/security/sessions/revoke-all` | Security | owner | v1 | Revoke every session, this one included |134| POST | `/api/v1/security/sessions/{id}/revoke` | Security | owner | NEXT | Revoke one session by its public id |135| POST | `/api/v1/security/emergency-halt` | Security | owner | v1 | Trigger the emergency halt of the signer |136| GET | `/api/v1/alerts` | Alerts | owner | v1 | In-app alerts, newest first |137| GET | `/api/v1/alerts/unread` | Alerts | owner | v1 | Unread counters |138| POST | `/api/v1/alerts/read` | Alerts | owner | v1 | Mark alerts read |139| GET | `/api/v1/alerts/stream` | Alerts | owner | v1 | Unread counters as Server-Sent Events (text/event-stream) |140| GET | `/api/v1/alerts/settings` | Alerts | owner | v1 | The owner's alert switches, quiet hours, thresholds, webhook |141| PUT | `/api/v1/alerts/settings` | Alerts | owner | v1 | Change alert settings (any subset) |142| POST | `/api/v1/alerts/webhook/secret` | Alerts | owner | v1 | Generate the webhook signing secret (shown once) |143| POST | `/api/v1/alerts/webhook/test` | Alerts | owner | v1 | Send a test call to the webhook |144| GET | `/api/v1/push/key` | Alerts | owner | v1 | VAPID public key for Web Push |145| GET | `/api/v1/push/subscriptions` | Alerts | owner | v1 | Devices subscribed to push |146| POST | `/api/v1/push/subscriptions` | Alerts | owner | v1 | Subscribe this device |147| PATCH | `/api/v1/push/subscriptions/{id}` | Alerts | owner | v1 | Rename a device, change its language |148| DELETE | `/api/v1/push/subscriptions/{id}` | Alerts | owner | v1 | Unsubscribe a device |149| POST | `/api/v1/push/test` | Alerts | owner | v1 | Send a test notification |150| GET | `/api/v1/events` | Events | owner | NEXT | Catch-up read of the wallet event log |151| GET | `/api/v1/events/stream` | Events | owner | NEXT | The wallet event log as Server-Sent Events (text/event-stream) |152| GET | `/api/v1/dashboard/status` | Dashboard | owner | v1 | Risk switches and live-limit completeness (header indicator) |153| GET | `/api/v1/dashboard/summary` | Dashboard | owner | v1 | Trading books, risk, agents, health, audit chain — each section fails on its own |154| GET | `/api/v1/dashboard/activity` | Dashboard | owner | v1 | One history of every operation: wallet, plans, orders, risk denials, audit |155| GET | `/api/v1/dashboard/activity.csv` | Dashboard | owner | v1 | The same history as CSV (text/csv) |156| GET | `/api/v1/analytics` | Analytics | owner | NEXT | What entered and left, fees paid, outcomes, counterparties — from the database only |157| GET | `/api/v1/search` | Search | owner | NEXT | Universal search: assets, contacts, transactions |15815966 operations.160<!-- END GENERATED: routes -->161162### Families documented elsewhere163164Routes under these prefixes are deliberately outside this document.165166<!-- BEGIN GENERATED: families -->167| Prefix | Documented in |168|---|---|169| `/api/v1/trading` | docs/openapi/trading-v1.json (SP Trading API) |170| `/api/v1/developer` | docs/TRADING-API-REFERENCE.md (API keys, webhooks) |171| `/api/v1/swap` | swap family |172| `/api/v1/bridge` | CCTP bridge family |173| `/api/v1/xswap` | native cross-chain swap family |174| `/api/v1/plans` | any-to-any plans |175| `/api/v1/nfts` | NFT family |176| `/api/v1/derivatives` | derivatives family |177| `/api/v1/agents` | agents family |178| `/api/v1/strategies` | agents family |179| `/api/v1/research` | research runtime |180| `/api/v1/monitor` | monitoring dashboard |181| `/api/v1/markets-hub` | markets hub |182| `/api/v1/private-markets` | private markets |183| `/api/v1/market-data` | market data engine (candles, data quality) |184| `/api/v1/utxo-locks` | UTXO locks (Bitcoin-style coins set aside; docs/adr) |185| `/api/v1/risk` | risk engine |186| `/api/v1/mandates` | trading mandates |187| `/api/v1/mm` | live market making |188| `/api/v1/stream` | quote engine websocket (docs/V11-QUOTE-ENGINE.md) |189<!-- END GENERATED: families -->190191## 4. What NEXT added to the core API192193| Route or member | What |194|---|---|195| `GET /api/v1/analytics?range=1M\|3M\|1Y\|ALL[&currency=]` | Inflows and outflows per asset and per network (count, base units, display), split external / internal / ownAccounts with the same rule as the portfolio flows; network fees paid per network with the number of transactions whose fee is unknown; counts by life-cycle outcome; biggest counterparties with their contact label. Database only. |196| `GET /api/v1/search?q=[&limit=]` | Assets (symbol, name, network, contract), contacts (label, address, note), transactions (transaction id prefix, address, exact amount). Capped groups with `truncated`. |197| `GET /api/v1/activity?network=&asset=` | Optional filter evaluated in SQL before the limit. |198| `GET /api/v1/dashboard/activity?network=&asset=` (and `.csv`) | The same filter, passed to the wallet source. |199| `contactLabel` on every row of `GET /api/v1/activity` | Address-book label of the counterparty, or null. |200| `data.fields` on `400 bad_request` | Which members were refused, and why. |201| CSV exports | Columns appended at the end of the row: `lifecycle`, `fee_paid_base_units`, `fee_paid`, `fee_symbol`, `deposit_kind`, `deposit_origin`, `contact_label` (`/export/activity.csv`); `lifecycle`, `fee_paid`, `fee_symbol`, `deposit_kind`, `deposit_origin`, `contact_label` (`/dashboard/activity.csv`). |202| Alert kinds | `transfer.dropped`, `transfer.replaced`, `transfer.expired`, `transfer.recovered` (section 7). |203204**Analytics classification.** A deposit is `external` unless the scan classified it `internal`; an internal deposit whose205origin is `agent_withdrawal` or `venue_withdrawal` is `ownAccounts`. An outgoing operation counts once it is final: a plain206transfer to another address is `external`, or `ownAccounts` when it pays one of the owner's agent vaults or funds a venue207account; swaps, bridges, native swaps, GMX order transactions and self-transfers are `internal` (nothing left the wallet).208NFT transfers move no fungible amount and are counted in the outcomes only. This is the rule of209`services/api/src/portfolio.ts` (`recordFlows`), which also records the price used for the fiat figures: the price the API210had when it saw the movement, within 30 minutes of it. A movement without such a price is counted in `unvalued` and is in211no fiat sum. Internal movements are never valued.212213**Fees.** `fees.byNetwork[].paid` sums `fee_paid` — the fee the network charged, recorded by the tracker — in the214network's native coin. `known` is the number of on-chain transactions it covers; `unknown` counts the on-chain transactions215whose fee was never recorded (every row older than NEXT), which are *not* in the sum. The fee of a separate token-approval216transaction is not recorded. Fees have no fiat value: no price is recorded with a fee.217218## 5. Errors219220Every error is `{ error, message, data? }`. Codes common to every operation: `unauthenticated` (401, session routes),221`csrf` (403, mutating routes), `bad_request` (400), `rate_limited` (429), `internal` (500).222223<!-- BEGIN GENERATED: errors -->224| Code | Status | Meaning | What the client does |225|---|---|---|---|226| `bad_address` | 400 | the destination is not a valid address of this network, or is the wallet itself | correct the address |227| `bad_amount` | 400 | the amount is not a positive decimal within the asset's precision | correct the amount |228| `bad_approval` | 422 | the approval could not be verified against the signer's list | approve again with a passkey the signer lists |229| `bad_destination` | 400 | the destination cannot receive this asset (account type, missing trust line…) | check the destination |230| `bad_memo` | 400 | the memo / destination tag is not accepted on this network | correct or remove it |231| `bad_request` | 400 | the request is not valid; `data.fields` lists the refused members when it comes from input validation | fix the request; do not retry unchanged |232| `bad_source` | 400 | the wallet's own account cannot send this asset in its present state | see the message |233| `bad_state` | 409 | the proposal is not in a state that allows this | re-read the proposal and show its real state |234| `below_rent` | 400 | the transfer would leave an account below its rent-exempt minimum | change the amount |235| `below_reserve` | 400 | the transfer would leave the account below the network reserve | change the amount |236| `challenge_expired` | 401 | the challenge expired or was already used | ask for new options and try again |237| `conflict` | 409 | the object changed concurrently | reload it, then decide again |238| `contract_destination` | 400 | the destination is a contract that cannot receive this transfer | check the destination |239| `csrf` | 403 | a mutating request without the same-origin proof (`Origin` + `X-SPW-CSRF: 1`) | send both headers; never retry from another origin |240| `duplicate_contact` | 409 | another contact already has this address | edit that contact |241| `expired` | 400, 410 | the approval window, or the pending passkey, expired | start again |242| `fee_ceiling` | 422 | the fee needed exceeds the signer's ceiling | retry later |243| `fee_too_high` | 400, 503 | the network fee is above the wallet's ceiling right now, or could not be established | retry later |244| `halted` | 423 | the emergency halt is active | nothing can be signed until the halt is lifted on the signer |245| `hash_mismatch` | 500 | the signer answered another intent hash; the transfer was marked failed | report it; nothing was sent |246| `idempotency` | 400 | the `Idempotency-Key` header is missing or malformed (16–64 letters, digits, dashes) | send one key per intended transfer |247| `idempotency_mismatch` | 409 | this Idempotency-Key was already used for a different request | use a new key |248| `insufficient_funds` | 400 | the balance does not cover the amount and the fee | lower the amount |249| `insufficient_gas` | 400 | not enough of the network's native coin to pay the fee | fund the native coin |250| `insufficient_unlocked_funds` | 400 | part of the balance is locked | lower the amount |251| `internal` | 500 | server error | retry later; a transfer approval is NOT retried blindly — re-read the proposal first |252| `invalid_cursor` | 400 | the cursor is not one a previous page returned | restart from the first page |253| `last_credential` | 409 | the last passkey on the signer cannot be revoked | add another passkey first |254| `login_failed` | 401 | authentication failed (unknown passkey or bad assertion) | try again; repeated failures raise an alert |255| `memo_required` | 400 | the destination requires a memo / tag | add it |256| `no_approver` | 409 | no other passkey can approve this revocation (none enrolled on the signer and out of its cool-down) | wait for the cool-down of the other passkey, or add one |257| `not_found` | 404 | the object does not exist | reload the list |258| `owner_only` | 403 | the route is for the owner's session, not an API key | use the session |259| `pending_tx` | 400, 409 | another transfer or swap on this network is not confirmed yet | wait for it; a dropped one no longer blocks |260| `policy` | 422 | the signer's policy refuses it (limit per transfer, per day, asset not allowed, halt) | see the message; limits are changed on the signer only |261| `protocol_changed` | 503 | the network's protocol changed since this wallet was reviewed; sending is suspended | update the wallet |262| `rate_limited` | 429 | too many requests from this address | wait a minute |263| `registration_failed` | 401 | the passkey registration could not be verified | try again |264| `rpc_degraded` | 503 | not enough data sources answered for this network; nothing was prepared | retry later |265| `rpc_disagreement` | 503 | the data sources disagree; nothing was prepared | retry later |266| `runtime_changed` | 503 | the network's runtime changed since this wallet was reviewed; sending is suspended | update the wallet |267| `self_approval` | 400 | a passkey cannot approve its own revocation | approve with another passkey |268| `setup_closed` | 403 | the one-time setup was already completed | sign in instead |269| `setup_token` | 403 | the setup token is missing | ask for the token printed by the signer |270| `signer_unreachable` | 503 | the signer cannot be reached; nothing was signed | reads still work; retry sending later |271| `simulation_failed` | 400 | the exact transaction could not be built or would fail now | see the message; nothing was signed |272| `stale_contact` | 409 | the contact changed since it was read | reload it before changing its address |273| `too_many_coins` | 400 | too many small coins are needed for this amount | send a smaller amount first |274| `too_many_streams` | 429 | too many event streams are open | close one, or fall back to polling |275| `too_many_subscriptions` | 422 | too many push devices | remove one |276| `unauthenticated` | 401 | no valid session | sign in with the passkey, then repeat the request |277| `unsupported_account` | 400 | the account type is not supported | see the message |278| `unsupported_asset` | 400, 404 | the asset is not in the verified registry of this network | pick an asset of GET /assets |279| `unsupported_funds` | 400 | the balance is of a kind this wallet does not spend | see the message |280| `unsupported_network` | 503 | the signer has no key for this network | do not offer this network |281<!-- END GENERATED: errors -->282283### Codes per operation284285*open* = a chain adapter or the signer can answer a code of its own; a signer refusal is `signer_<its code>` (422).286287<!-- BEGIN GENERATED: errors-per-route -->288| Operation | Codes beyond the common ones |289|---|---|290| POST `/api/v1/auth/setup/options` | `setup_closed` (403) |291| POST `/api/v1/auth/setup/verify` | `challenge_expired` (401), `registration_failed` (401), `setup_closed` (403), `setup_token` (403), `signer_unreachable` (503), *open* |292| POST `/api/v1/auth/login/verify` | `challenge_expired` (401), `login_failed` (401) |293| GET `/api/v1/accounts` | `signer_unreachable` (503) |294| PUT `/api/v1/assets/prefs/{network}/{asset}` | `unsupported_asset` (404) |295| GET `/api/v1/portfolio` | `signer_unreachable` (503) |296| POST `/api/v1/transfers/proposals` | `idempotency` (400), `unsupported_asset` (400), `bad_address` (400), `bad_amount` (400), `bad_memo` (400), `idempotency_mismatch` (409), `conflict` (409), `policy` (422), `signer_unreachable` (503), `bad_destination` (400), `bad_source` (400), `memo_required` (400), `contract_destination` (400), `insufficient_funds` (400), `insufficient_gas` (400), `insufficient_unlocked_funds` (400), `below_rent` (400), `below_reserve` (400), `too_many_coins` (400), `unsupported_account` (400), `unsupported_funds` (400), `fee_too_high` (400), `simulation_failed` (400), `pending_tx` (400), `pending_tx` (409), `fee_ceiling` (422), `fee_too_high` (503), `rpc_degraded` (503), `rpc_disagreement` (503), `protocol_changed` (503), `runtime_changed` (503), `unsupported_network` (503), *open* |297| GET `/api/v1/transfers/proposals/{id}` | `not_found` (404) |298| GET `/api/v1/transfers/{id}/status` | `not_found` (404) |299| POST `/api/v1/transfers/proposals/{id}/request-approval` | `not_found` (404), `bad_state` (409), `pending_tx` (409), `conflict` (409), `policy` (422), `halted` (423), `signer_unreachable` (503), `bad_destination` (400), `bad_source` (400), `memo_required` (400), `contract_destination` (400), `insufficient_funds` (400), `insufficient_gas` (400), `insufficient_unlocked_funds` (400), `below_rent` (400), `below_reserve` (400), `too_many_coins` (400), `unsupported_account` (400), `unsupported_funds` (400), `fee_too_high` (400), `simulation_failed` (400), `pending_tx` (400), `fee_ceiling` (422), `fee_too_high` (503), `rpc_degraded` (503), `rpc_disagreement` (503), `protocol_changed` (503), `runtime_changed` (503), `unsupported_network` (503), *open* |300| POST `/api/v1/transfers/proposals/{id}/approve` | `not_found` (404), `bad_state` (409), `pending_tx` (409), `conflict` (409), `expired` (410), `hash_mismatch` (500), `signer_unreachable` (503), *open* |301| POST `/api/v1/transfers/proposals/{id}/reject` | `not_found` (404), `bad_state` (409), `conflict` (409) |302| POST `/api/v1/addressbook` | `bad_address` (400) |303| PATCH `/api/v1/addressbook/{id}` | `bad_address` (400), `not_found` (404), `stale_contact` (409), `duplicate_contact` (409) |304| POST `/api/v1/security/devices/verify` | `challenge_expired` (401), `registration_failed` (401), `signer_unreachable` (503), *open* |305| POST `/api/v1/security/devices/confirm` | `expired` (400), `signer_unreachable` (503), *open* |306| POST `/api/v1/security/devices/revoke/options` | `not_found` (404), `last_credential` (409), `no_approver` (409), `signer_unreachable` (503), *open* |307| POST `/api/v1/security/devices/revoke/confirm` | `self_approval` (400), `challenge_expired` (401), `bad_approval` (422), `signer_unreachable` (503), *open* |308| POST `/api/v1/security/sessions/{id}/revoke` | `not_found` (404) |309| POST `/api/v1/security/emergency-halt` | `signer_unreachable` (503), *open* |310| GET `/api/v1/alerts/stream` | `too_many_streams` (429) |311| POST `/api/v1/push/subscriptions` | `too_many_subscriptions` (422) |312| PATCH `/api/v1/push/subscriptions/{id}` | `not_found` (404) |313| POST `/api/v1/push/test` | `not_found` (404) |314| GET `/api/v1/events/stream` | `too_many_streams` (429) |315| GET `/api/v1/dashboard/status` | `owner_only` (403) |316| GET `/api/v1/dashboard/summary` | `owner_only` (403) |317| GET `/api/v1/dashboard/activity` | `invalid_cursor` (400), `owner_only` (403) |318| GET `/api/v1/dashboard/activity.csv` | `owner_only` (403) |319<!-- END GENERATED: errors-per-route -->320321### Outcome of a proposal (`errorCode`)322323Not HTTP errors: why a stored proposal ended or is held. Source: `services/api/src/sv-texts.ts`.324325<!-- BEGIN GENERATED: outcomes -->326| `errorCode` | English sentence (`error`) |327|---|---|328| `broadcast_disabled` | signed but NOT broadcast: broadcasting is disabled on this server (SPW_BROADCAST=off); nothing was sent to the network |329| `approval_expired` | approval window expired |330| `expired_before_approval` | expired before approval |331| `interrupted_signing` | interrupted during signing; nothing was broadcast |332| `not_broadcast_in_time` | could not be broadcast in time; nothing was sent |333| `rejected_by_owner` | rejected by owner |334| `signer_refused` | the signer refused: {detail} |335| `signer_hash_mismatch` | signer hash mismatch |336| `broadcast_attempt_failed` | broadcast attempt failed: {detail} |337| `tx_failed` | the transaction failed on-chain: {detail} |338| `relay_unconfirmed` | handed to the network without an acknowledgement and not found on-chain; it stays watched and is recorded if it appears. A new transfer on this network replaces it |339| `dropped` | no longer known to the network and not confirmed; it stays watched and is recorded if it appears. A new transfer on this network replaces it |340| `expired_onchain` | its validity window closed before the network included it; nothing moved |341| `replaced_onchain` | another transaction used the same nonce or the same coins; this one can no longer be included |342| `swap_late` | the swap could not be sent in time; nothing was swapped |343| `swap_approval_reverted` | the token approval reverted; nothing was swapped |344| `swap_would_revert` | the swap would revert now ({detail}); it was not sent |345| `swap_would_revert_approved` | the swap would revert now ({detail}); it was not sent. The exact-amount approval stays in place for the next attempt |346| `bridge_late` | the transfer could not be sent in time; nothing was burned |347| `bridge_approval_reverted` | the token approval reverted; nothing was burned |348| `burn_would_revert` | the burn would revert now ({detail}); it was not sent |349| `burn_would_revert_approved` | the burn would revert now ({detail}); it was not sent. The exact-amount approval stays in place for the next attempt |350| `xswap_late` | the swap could not be sent in time; nothing was sent to the vault |351| `xswap_vault_unconfirmed` | the vault is no longer confirmed ({detail}); nothing was sent to it |352| `xswap_approval_reverted` | the token approval reverted; nothing was sent to the vault |353| `deposit_would_revert` | the deposit would revert now ({detail}); it was not sent |354| `deposit_would_revert_approved` | the deposit would revert now ({detail}); it was not sent. The exact-amount approval of the router stays in place; only this wallet can use it |355| `sol_swap_unverified` | the stored swap no longer verifies; it was not sent |356| `sol_swap_expired` | the swap expired before it could be sent (blockhash too old); nothing was swapped |357| `sol_swap_refused` | the node refused the signed swap ({detail}); it was not sent |358| `sol_swap_would_fail` | the swap would fail now ({detail}); it was not sent |359| `sol_swap_below_min` | the swap no longer delivers the approved minimum in simulation; it was not sent |360| `sol_swap_no_balances` | the node did not report the simulated balances; the swap was not sent |361| `sol_burn_mismatch` | the signer returned a transaction that is not the approved burn; it was not sent |362| `sol_burn_expired` | the transfer expired before it could be sent (blockhash too old); nothing was burned |363| `sol_burn_refused` | the node refused the signed burn ({detail}); it was not sent |364| `sol_burn_would_fail` | {detail}; it was not sent |365<!-- END GENERATED: outcomes -->366367### Warnings of a transfer review (`warnings`)368369<!-- BEGIN GENERATED: warnings -->370| Warning | Meaning | Acknowledge before approving | Emitted |371|---|---|---|---|372| `new_destination` | the wallet never sent to this address and it is not in the address book | yes | yes |373| `address_poisoning_suspected` | the address differs from a known one but starts and ends with the same characters: the classic look-alike of an address-poisoning attack | yes | yes |374| `duplicate_recent` | the same asset, amount and destination was sent, or may have been sent, in the last 24 hours | yes | yes |375| `contract_destination` | the destination is a contract (EVM) or a program-owned account (Solana), not a plain wallet: it may not be able to use what it receives | no | yes |376| `network_congested` | the network is congested: the fee is capped, so the transfer may expire without being included (nothing moves in that case) | no | yes |377| `creates_account` | the destination account does not exist yet on this network: the transfer creates it and part of the amount stays locked as its reserve | no | yes |378| `creates_token_account` | Solana: the destination has no account for this token; the transfer creates it and the sender pays its rent | no | yes |379| `near_creates_account` | NEAR: the destination account does not exist yet; the transfer creates it, which adds a fee paid by the sender | no | yes |380| `activates_account` | the address was never used on this network: activating it is charged to the sender on top of the amount (TRON) | no | yes |381| `deploys_wallet` | TON: the first outgoing transfer also deploys the wallet contract (slightly higher fee, cannot be simulated beforehand) | no | yes |382| `destination_not_initialized` | TON: no contract is deployed at the destination (a new wallet, or a wrong address); the funds are credited there and cannot bounce back | no | yes |383| `memo_numeric_id` | Stellar: the memo is digits only and is sent as a numeric id (MEMO_ID), the format exchanges expect | no | yes |384| `dt_new_account` | Polkadot Asset Hub: the destination account does not exist yet; this transfer creates it and it must always keep the existential deposit | no | yes |385| `cd_token_outputs` | Cardano: some outputs of this wallet carry native tokens or script data; they are never spent and their ADA stays locked with them | no | yes |386| `l1_fee_unknown` | OP-stack networks: the L1 data fee could not be read; the fee ESTIMATE covers the L2 part only and the chain charges the data fee on top (it is not a field the signer can bound) | no | yes |387<!-- END GENERATED: warnings -->388389A client shows a code it does not know as a generic caution. On this branch the web app has no `w_duplicate_recent` and no390`w_l1_fee_unknown` string yet (the web safety work owns them): a test lists the gap.391392## 6. Life cycle of a transfer393394`lifecycle` is the vocabulary of the three clients; `finalized` tells "in a block" from "final"; `watched` marks a dropped395or replaced transfer the worker still re-checks. `state` keeps the earlier vocabulary (a dropped transfer reads `failed`396there, with `errorCode: dropped`).397398<!-- BEGIN GENERATED: lifecycle -->399| `lifecycle` | Meaning |400|---|---|401| `draft` | prepared, nothing frozen; expires by itself |402| `awaiting_confirmation` | the exact transaction is frozen and shown; the passkey has not been given |403| `awaiting_signature` | the passkey was given; the signer call is in flight |404| `signed` | signed; no relay to the network has started |405| `broadcasting` | signed and a relay has started: from here only the chain can say that nothing was sent |406| `pending` | handed to the network, not in a block yet |407| `confirming` | in a block, not final (see `confirmations`); a reorganisation can still undo it |408| `confirmed` | FINAL. The only value a client may treat as done |409| `failed` | ended without effect, or reverted on-chain (`errorCode` says which) |410| `replaced` | another transaction used the same nonce or coins. Still re-checked for a day (`watched`): it becomes confirming / confirmed if it turns out to be in a block |411| `dropped` | no source knows it and nothing proves it dead. NOT a failure: it stays watched and is recorded if it appears; a new send on the network replaces it |412| `expired` | the approval window passed before the passkey, or the validity window of the signed transaction closed on-chain (`errorCode: expired_onchain`); nothing moved |413| `rejected` | rejected by the owner before signing |414| `not_sent` | signed and deliberately not relayed (broadcasting is disabled on this server) |415<!-- END GENERATED: lifecycle -->416417## 7. Events and alerts418419`GET /api/v1/events?after=` and `GET /api/v1/events/stream` deliver the wallet event log. An event says "look": the client420re-reads the object named by `ref`. `reset` means the position cannot be resumed.421422<!-- BEGIN GENERATED: events -->423| `type` | What happened |424|---|---|425| `transfer.state` | a proposal changed state — `data`: `{ from, to, lifecycle, network, kind, txid, confirmations, errorCode }`; `ref` = proposal id |426| `transfer.relay` | a relay of the signed transaction to the network started (its outcome is not known yet) — `data`: `{ network, lifecycle: "broadcasting", txid }` |427| `transfer.confirmations` | the confirmation count of a tracked transaction changed — `data`: `{ network, confirmations, txid }` |428| `deposit.seen` | an incoming payment was recorded — `data`: `{ network, txid, asset, amount, kind, origin?, proposal?, detection? }` |429| `deposit.native_window` | EVM native-coin scan: a balance difference was located to a block window, not to a transaction |430| `deposit.scan_gap` | a transaction of the deposit scan is no longer served by any source |431| `device.added` | a passkey was added — `data`: `{ credential, label }` |432| `device.revoked` | a passkey was revoked — `data`: `{ credential, label, signer, sessions, ip }` (`signer`: it was on the signer's list; `sessions`: sessions it had opened, ended with it) |433| `session.revoked` | one session was revoked by its public id — `data`: `{ session, current, ip }` |434| `credentials.mismatch` | the signer's passkey list and the API's differ, and still did 30 s later — `data`: `{ count, signerOnly, apiOnly }` (12-character id prefixes) |435| `credentials.reconciled` | the two passkey lists agree again |436| `settings.saved` | account settings changed — `data`: `{ changed: { locale?, currency?, hideBalances?, prices?, theme? } }`: re-read GET /settings |437| `sessions.revoked` | every session was revoked |438| `login.ok` | a sign-in succeeded — `data`: `{ credential, ip, label, device, newDevice, session }` |439| `owner.setup` | the first passkey was enrolled (one-time setup) |440| `addressbook.saved` | a contact was created or changed — `data`: `{ network, address, label }` |441| `addressbook.removed` | a contact was deleted |442| `settings.asset_pref` | an asset was hidden / shown / made favourite — `data`: `{ network, asset, hidden, favorite }` |443| `halt.on` | the emergency halt of the signer was triggered |444| `security.contact_address_changed` | a contact now points to another address — `data`: `{ id, network, label, from, to }` |445<!-- END GENERATED: events -->446447Every audit type matching `deposit.*`, `device.*`, `session(s).*`, `addressbook.*`, `settings.*`, `halt.*`, `security.*`448is mirrored into the log, so types not listed here can appear.449450**Alerts for the life-cycle outcomes.** Before NEXT only `finalized` and `failed` raised an alert. Added451(`packages/core/src/alert-catalog.ts`, `services/api/src/alerts/rules.ts`), all ON by default, with a lock-screen wording452that names the network and the kind of operation only:453454| Kind | Severity | Raised when | Says |455|---|---|---|---|456| `transfer.dropped` | warning | a proposal moves to `dropped` | not included, still watched, a new send on the network replaces it |457| `transfer.replaced` | warning | a proposal moves to `replaced` | another transaction used its nonce or coins; still re-checked |458| `transfer.expired` | warning | a plain transfer fails with `expired_onchain` | its validity window closed on-chain; nothing moved |459| `transfer.recovered` | critical | a dropped or replaced proposal moves to `confirming` or `finalized` | the transfer believed dead went through: do not send it again |460461A recovery is critical so that quiet hours and the hourly cap never hold it back: it is the one message that prevents a462second payment made by other means. The alert kind `transfer.expired` is about the on-chain validity window; the *audit*463type `transfer.expired` (approval window passed before the passkey, nothing was signed) raises no alert.464465## 8. Credentials and sessions (merged from `next-signer`)466467The operations that were marked "changing" are now described as merged; nothing is marked any more.468469- **Adding a passkey** keeps its three routes. `devices/verify` also returns `request`, the `SPW-CRED-v2` object (component470  `CredentialRequest`): `v`, `action` (`add` / `revoke`), `requestId` (single use), `keyId`, `credentialId`, `publicKey`471  (add only), `createdAt`, `expiresAt` (5 minutes at most). The challenge of `options` is the SHA-256 of its canonical472  bytes; an enrolled passkey signs it and the signer verifies the approval itself. A client that signs `options` as473  returned works unchanged.474- **Revoking a passkey**: `POST /security/devices/revoke/options` `{ credentialId }` → `{ challengeId, request, options }`,475  then `POST /security/devices/revoke/confirm` `{ challengeId, assertion }` → `{ ok, signer, sessionsRevoked }`. Refusals:476  `last_credential`, `no_approver` (409), `self_approval` (400), `bad_approval` (422), and the signer's own477  (`signer_bad_approval`, `signer_cooldown`, `signer_last_credential`, `signer_self_approval`, `signer_replay`…).478- **Sessions** have a public `id`: `POST /security/sessions/{id}/revoke` → `{ ok, current }`. `GET /security/logins` lists479  the last sign-ins (passkey, address, coarse device label, `newDevice`).480- **`security/overview`** adds `signer.recoveryExportedAt` / `recoveryVerifiedAt` / `credentialCooldownSec`,481  `devices[].credentialId` / `revocable` / `inCooldown`, `sessions[].id` / `current` / `device` / `credential`,482  `signerCredentials` (the signer's list, the source of truth), `mismatch`, `currentSessionId`.483- **Sign-in**: a passkey the signer no longer lists opens no session. When the signer does not answer, or holds no passkey484  at all, the API's own table decides.485- **Idle rule and `X-SPW-Interaction: 1`.** A session ends after 30 minutes without activity (12 hours at most). A client486  sends the header on requests caused by the user, never on timers. From the first such request on, only those refresh the487  idle timer; a session that never sent it keeps the earlier behaviour (any authenticated request refreshes it).488- **Alerts**: `security.passkey_revoked` (warning) on `device.revoked`; `security.credential_mismatch` (critical) on489  `credentials.mismatch`. **Events**: `device.revoked`, `session.revoked`, `credentials.mismatch`,490  `credentials.reconciled` (the mirror now includes `credentials.*`).491492## 9. Not covered yet493494- **Request schemas are copies.** The contract test binds answers, routes and error codes; it does not prove that a495  request schema of `spec.ts` equals the route's own. The fix is to export each route's zod schema from a pure module and496  use the same object on both sides (or to register the routes from the table, as the trading API does).497- **Free-form sections.** `swap`, `bridge`, `xswap`, `nft` and `quote` of a proposal, the `data` of the dashboard sections,498  the signer's `policy`, `rpcEndpoints` and the payload of an event are declared as open objects: they belong to families499  documented elsewhere and are not validated member by member here.500- **Shapes no test produces.** A network `health` object (the health worker is off in tests; the schema is the TypeScript501  interface), a price with a second source (`APIBRICKS_API_KEY` unset), balance rows of an unreachable network.502- **Swift models.** The Swift package is not generated from, nor checked against, this document yet.503- **The web app does not import the generated types yet** (`get<GetPortfolioResponse>('/portfolio')` is the intended use);504  wiring them is part of the web work.505506Found while writing the contract. Fixed since (additively):507508- `PUT /api/v1/settings` now writes the audit event `settings.saved` (`changed`: the keys sent and their new values), so509  the change reaches the event log and the other devices.510- A NUL character anywhere in a request, or any control character in the query string or a path parameter, is refused511  with 400 `bad_request` by one hook in front of every route (it used to reach PostgreSQL and answer 500). Body strings512  keep tabs, new lines and escape sequences: strategy sources and captured logs carry them. Behind the hook, the error513  handler maps PostgreSQL's "invalid byte sequence" class (22021, 22P05) to 400 as well, for text that does not come from514  the query, the path or the body.515- `GET /transfers/{id}/status` carries `lifecycle`, `finalized`, `watched`, `feePaid`, `feePaidDisplay`; `GET /events`516  always carries `more`.517- The document is served: `GET /api/v1/openapi.json` (owner session).518519Left as they are (answers are additive only):520521- Two operations answer two shapes: `GET /market/{symbol}` (no `currency` / `days` for an unknown symbol) and522  `security/overview.signer` (only `reachable: false` when the signer is down).523- Naming is mixed in three places and cannot change: `created_at` next to `updatedAt` on a contact, `created_at` /524  `last_seen` on a session row, `depositKind` on a receipt next to `kind`.525- In `GET /activity` a receipt's `state` is `confirming` / `finalized`, while the CSV says `confirmed` in the `state` column526  for every receipt (kept; the appended `lifecycle` column tells the two apart).527
Files main
Menu

Theme