SPB Git

Repository Public

SP-WALLET-ARCHITECTURE.md 9.8 KB 139 lines markdown

1# SP Wallet NEXT — architecture23What changes with NEXT, and why. The custody model, the signer's role and the approval binding are unchanged4(`docs/adr/0001-custody.md`); this document records the decisions taken on top of them.56```7 Web (React PWA)      macOS (SwiftUI)        iOS / iPadOS (SwiftUI)8        │                   │                        │9        │        SPWalletCore (API client, canonical objects, approval binding, outcome helper)10        │        SPWalletUI   (design tokens, shared components)11        └───────────────┬───┴────────────────────────┘12                        │  HTTPS, session cookie (passkey login), CSRF header, /api/v1 (additive only)13                 BHS64 gateway (TLS, WireGuard)14                        │15        ┌───────────────▼───────────────────────────────────────────────┐16        │ API (M2M32c)                                                   │17        │  auth · wallet · portfolio · transfers · events · prefs        │18        │  swap / bridge / plans · NFT · derivatives · agents · alerts   │19        │  workers: reconcile · deposits · snapshots · alerts · prune    │20        │  Postgres 17 (state, audit chain, wallet_events)               │21        └───────┬──────────────────────────────────┬────────────────────┘22                │ HMAC over LAN (root relay)        │ public RPC / indexers, ≥ 2 independent per network23        ┌───────▼──────────┐                        ▼24        │ Signer (m6ma)    │                  Blockchains (23 networks)25        │ keys · policy    │26        │ passkey check    │27        └──────────────────┘28```2930## Decision 1 — Only the chain can say that nothing was sent3132*Problem (audit T1–T5).* A signed transfer whose relay timed out was marked failed after its window, with the words33"nothing was sent", without looking at the chain. Negative verdicts (replaced, expired) came from one endpoint's silence.34A transaction that never confirmed blocked its network for ever.3536*Decision.*371. `relay_attempted_at` is written **before** the network call. From then on a time-out, a crash or an error answer proves38   nothing. A relay error is followed by a look-up; a transaction the network has moves to `broadcast`.392. A signed row past its window is settled by the chain: tracked if present; `dropped` if every source says unknown and40   its validity cannot be proven over; `failed / not_broadcast_in_time` only when no relay ever started.413. Tracking asks every endpoint. One endpoint that has the transaction places it; absence needs all of them to answer;42   `replaced` needs the nonce consumed according to all of them. The worker applies a negative verdict only after43   3 consecutive passes over at least 60 s.444. `dropped` (EVM after 30 min unknown everywhere, Bitcoin-style after 6 h): frees the network, is not relayed again, stays45   watched. A later send cannot double-pay: on EVM it reuses the nonce; on Bitcoin-style networks the new transaction is46   forced to spend one coin of the dropped one. `replaced` stays re-checked for a day and is corrected if the transaction47   turns out to be in a block.485. Swaps, bridges and native swaps keep their "simulate, then relay" gates only until a relay has started; afterwards the49   chain is asked first (the simulation of an already-mined swap reverts and used to fail the row).506. The database enforces one transaction in flight per network (partial unique index), in addition to the route checks.5152*States.* Stored: `draft, pending_approval, approved, signed, broadcast, confirming, finalized, rejected, expired, failed,53replaced, reorged, not_broadcast, dropped`. Clients read `lifecycle` (fourteen values, `packages/core/src/state.ts`):5455| Brief | lifecycle | from |56|---|---|---|57| Draft | `draft` | draft |58| Awaiting confirmation | `awaiting_confirmation` | pending_approval (intent frozen, shown, passkey not yet given) |59| Awaiting signature | `awaiting_signature` | approved (signer call in flight) |60| Signed | `signed` | signed, no relay started |61| Broadcasting | `broadcasting` | signed, relay started |62| Pending | `pending` | broadcast |63| Confirmed | `confirming` (in a block, not final — `confirmations`) then `confirmed` (final only) | confirming, reorged · finalized |64| Failed | `failed` | failed |65| Replaced | `replaced` | replaced |66| Dropped | `dropped` | dropped |67| Expired | `expired` | expired (approval window) · failed with `expired_onchain` (validity window) |68| — | `rejected`, `not_sent` | rejected · not_broadcast |6970*Compatibility.* Shipped native builds decode `state` with closed enums. `state` therefore keeps its old vocabulary71(`dropped` is reported there as `failed`, with `errorCode: dropped` and a sentence that says it is still watched); new72fields are additive: `lifecycle`, `finalized`, `watched`, `feePaid`, `feePaidDisplay`, `relayAttemptedAt`.7374*Not covered.* GMX orders relay through their own path (`derivatives/gmx-exec.ts`); the GMX lock is off in production.75Replacing a stuck transaction on purpose (speed-up, cancel, RBF bump) needs a new signing rule: separate package, signer76review and owner approval.7778Code: `services/api/src/worker.ts` (`reconcile`, `settleLateSigned`), `transfers.ts` (`broadcastNow`, `knownToNetwork`,79`duplicateWarning`, `droppedCoins`), `chains/{evm,sol,btc}.ts` (`track`, `broadcast`). Tests: `test/lifecycle.test.ts`.8081## Decision 2 — One event log, three clients8283*Problem (audit S1).* Every client polled every screen; a transfer made on the phone appeared elsewhere after the next poll.8485*Decision.* `wallet_events` (append-only, increasing id) receives every change a client may need to hear about: transfer86transitions (`transfer.state`, `transfer.relay`, `transfer.confirmations`), deposits, device / session / address-book /87settings / halt changes (mirrored from the audit chain). `GET /api/v1/events?after=` is the catch-up, `GET88/api/v1/events/stream` the same as Server-Sent Events resumed with `Last-Event-ID`. An unresumable position is answered89`reset`. Events are facts that say "look": clients re-read the object named by `ref` through the normal read routes, so a90duplicate or late event is harmless and the server never pushes a state the chain did not give. Polling remains as the91fallback at a slow rate. Retention 30 days; the newest row is always kept.9293The stream needs a session cookie like every other route; it carries no secret and no signing material.9495Code: `services/api/src/events.ts`, `db.ts` (`walletEvent`, mirroring in `audit`). Tests: `test/events.test.ts`.9697## Decision 3 — The server computes what the three clients used to compute separately9899Portfolio total, completeness (`complete`, `missing`), 24 h change, allocation by asset and by network, value history100(snapshots, ranges 1D…ALL, net flows over the range) and balance provenance are produced once by the API. A partial total101says it is partial; a point recorded while a network was unreadable is never drawn as a low. *(Implemented on branch102`next-balances`; fields are listed in `SP-WALLET-API.md` once merged.)*103104Owner arrangements live on the server so that devices agree: hidden / favourite assets (`asset_prefs`), contacts with note105and favourite, appearance (`theme` in settings). Changing a contact's address requires the address the client believes is106current and raises `security.contact_address_changed`. Code: `services/api/src/prefs.ts`.107108## Decision 4 — Credentials and sessions have a life cycle the signer verifies109110*(Implemented on branch `next-signer`; changes to the signer are deployed only after review and the owner's approval.)*111A passkey is added or revoked through a canonical, expiring, single-use object (`SPW-CRED-v2`) signed by an existing112passkey and verified by the signer; the signer's credential list is the source of truth shown in the Security Center;113sessions have public ids and can be revoked one by one. The signer's request queue no longer reads unauthenticated bodies,114and `halt` never waits.115116## Decision 5 — One design system117118`design/tokens.json` generates the web CSS and the Swift tokens; contrast is verified at generation119(`SP-WALLET-DESIGN-SYSTEM.md`). Native apps use SwiftUI components over the same values; no web view.120121## Decision 6 — What an operation's outcome is, on every client122123Once an approval has left a device, the outcome is unknown until the server says otherwise. No client shows "failed",124re-enables Approve, resets the form or offers Cancel on a lost answer: it re-reads the operation, and when it cannot, shows125"status unknown — do not send again". The server adds a `duplicate_recent` warning when the same payment was made or may126have been made in the last 24 hours. *(Web: branch `next-web-safety`; Swift: `next` branches of the three Apple127repositories.)*128129## API rules130131- `/api/v1` is additive: no field removed, renamed or retyped; new fields and routes only. New enum values never appear132  in a field a shipped client decodes with a closed enum.133- Amounts are strings of base units plus a display string computed with exact arithmetic; never a float.134- Every figure that is an estimate, partial or stale carries the flag that says so.135- Errors are `{ error: code, message, data? }`; codes are catalogued (`sv-texts.ts` for the outcome of a stored proposal,136  `services/api/src/wallet-api/spec.ts` for the HTTP errors of every route).137- The core wallet API has a machine-readable contract: `docs/openapi/wallet-v1.json`, generated from `wallet-api/spec.ts`138  and checked against the real server by `test/wallet-contract.test.ts` — see `SP-WALLET-API.md`.139
Files main
Menu

Theme