Repository Public
1<div align="center">23<img src="docs/brand/logo.svg" alt="SPWalletCore logo" width="560">45<br><br>67<img src="docs/brand/icon.png" alt="SPWalletCore icon" width="112" height="112">89# 🛡️ SPWalletCore1011**The shared Swift package of the native SP Wallet clients (iOS, iPadOS, macOS): API client and session, canonical objects and passkey approval binding, address validation, payment URIs, live quote stream, offline snapshots. No private key, no third-party dependency.**1213**Author: [Simon-Pierre Boucher](https://www.spboucher.ai)**1415[](https://wallet.spboucher.ai)161718192021222324252627282930[](https://git.spboucher.ai/sp-wallet-core/commits)31[](https://git.spboucher.ai/sp-wallet-core/commits)32[](https://git.spboucher.ai/sp-wallet-core/insights)33[](https://git.spboucher.ai/sp-wallet-core)34[](https://git.spboucher.ai/sp-wallet-core/insights)35[](https://git.spboucher.ai/sp-wallet-core)36[](https://git.spboucher.ai/sp-wallet-core/branches)37[](https://git.spboucher.ai/sp-wallet-core/tags)38[](https://git.spboucher.ai/sp-wallet-core)3940414243444546474849505152535455</div>5657---5859## Table of contents6061- [Overview](#-overview)62- [What the package provides](#-what-the-package-provides)63- [Architecture](#-architecture)64- [Stack](#-stack)65- [Repository layout](#-repository-layout)66- [Getting started](#-getting-started)67- [Configuration](#-configuration)68- [API surface](#-api-surface)69- [Canonical objects](#-canonical-objects)70- [Networks and addresses](#-networks-and-addresses)71- [Security rules](#-security-rules)72- [Testing](#-testing)73- [Throwaway stack](#-throwaway-stack)74- [Conventions](#-conventions)75- [Gotchas](#-gotchas)76- [Author](#-author)77- [License](#-license)7879---8081## 🎯 Overview8283`SPWalletCore` is the code that the native **SP Wallet** apps share. SP Wallet is a personal multichain wallet84([wallet.spboucher.ai](https://wallet.spboucher.ai)) in which the device **displays, prepares and authorizes**, and an isolated85signer on the MacLustr cluster holds the keys and signs.8687The package exists for one reason above all: a passkey approval must sign **what the owner sees**. For every object the backend88has approved by a passkey, the package ports the backend's canonical serialization byte for byte, recomputes89`SHA-256(canonical bytes)` on the device, and requires the server's WebAuthn challenge to be exactly that hash before any passkey90prompt appears. The approve calls only accept the resulting `VerifiedApproval<…>` value, which cannot be built any other way.9192It contains **no private key, no seed, and signs no transaction**.9394### SP Wallet family9596| Repository | Role | Platform |97|---|---|---|98| [sp-wallet](https://git.spboucher.ai/sp-wallet) | API, web app, isolated signer | web · [wallet.spboucher.ai](https://wallet.spboucher.ai) |99| **sp-wallet-core** (this repository) | shared Swift package `SPWalletCore` | iOS 18+ · macOS 15+ |100| [sp-wallet-ios](https://git.spboucher.ai/sp-wallet-ios) | native iPhone and iPad client (owner of this package) | iOS · iPadOS |101| [sp-wallet-macos](https://git.spboucher.ai/sp-wallet-macos) | native macOS client | macOS |102103Both apps reference the package by a local path (`../SPWalletCore`): clone this repository next to the app, under that name.104105## ✨ What the package provides106107| Area | Folder | What it does |108|---|---|---|109| Exact amounts and JSON | `Foundation/` | `BaseUnits` (base-unit integers as strings), `JSONValue`, encodings. Amounts never go through `Double` |110| Hashes and address codecs | `Crypto/` | Keccak-256, BLAKE2b, Base58, Base32, Bech32, CashAddr, checksums — implemented here, no dependency |111| HTTP client and session | `API/` | `APIClient` (actor): JSON under `/api/v1`, session cookie handled by hand, `Origin` + `X-SPW-CSRF` on every state-changing request, `Idempotency-Key` from the caller, session events |112| Authentication | `Auth/` | WebAuthn JSON types, login, sign-out, session revocation, passkey enrolment (`SPW-ENROLL-v1`) |113| Approval binding | `Signing/` | `PasskeyApprovable`, `ApprovalBinding.verify`, `VerifiedApproval`, `CanonicalWriter`, `StrictObject`, `Intent`, transfers |114| Wallet reads | `Wallet/` | networks, accounts, portfolio, charts, activity (and CSV export), address book, settings, security overview, audit journal, health |115| Addresses and payment URIs | `Blockchain/` | `AddressValidator` (23 networks), strict parser and builder of payment URIs for QR codes and pasted text |116| Offline snapshots | `Persistence/` | `OfflineStore` (actor): read-only dated snapshots and a size-capped media cache; refuses keys reserved for credentials |117| Swaps and bridges | `Domains/Swap/` | same-network swap, CCTP bridge, cross-network swap, multi-step plans, quote fingerprints, swap event stream |118| NFTs | `Domains/NFT/` | gallery, items, collections, market (read), transfers, destination allow list, UTXO locks |119| Derivatives | `Domains/Derivatives/` | market data, paper accounts, live venue approvals, collateral, GMX |120| Execution | `Domains/Execution/` | unified orders, markets, risk limits and kill switch, trading mandates, developer API keys and webhooks |121| Trading agents | `Domains/Agents/` | simulation, paper, live spot under mandate, perpetuals, withdrawals |122| Operations | `Domains/Ops/` | alert catalog and alerts, dashboard, monitor, research jobs, server-sent events, live quote websocket |123| Test support | `Sources/SPWalletTestSupport/` | `SoftwareAuthenticator`: a software WebAuthn authenticator for throwaway stacks only |124125## 🏗 Architecture126127```mermaid128flowchart TB129 subgraph Apps["Native apps"]130 iOS["sp-wallet-ios<br/>iPhone · iPad"]131 mac["sp-wallet-macos"]132 end133 subgraph Core["SPWalletCore"]134 Domains["Domains/<br/>Swap · NFT · Derivatives<br/>Execution · Agents · Ops"]135 Signing["Signing/<br/>ApprovalBinding · Intent<br/>CanonicalWriter · StrictObject"]136 Wallet["Wallet/ · Auth/"]137 API["API/<br/>APIClient (actor)<br/>SessionTokenStoring · HTTPTransport"]138 Chain["Blockchain/<br/>AddressValidator · PaymentURI"]139 Store["Persistence/<br/>OfflineStore (actor)"]140 Base["Foundation/ · Crypto/"]141 Domains --> Signing --> API142 Domains --> API143 Wallet --> API144 Signing --> Base145 Chain --> Base146 API --> Base147 end148 iOS --> Core149 mac --> Core150 API -- "HTTPS /api/v1<br/>session cookie · Origin · X-SPW-CSRF" --> Server["SP Wallet API<br/>wallet.spboucher.ai"]151 Server -- "relays object + assertion" --> Signer["Isolated signer<br/>keys · pinned passkeys"]152 TS["SPWalletTestSupport<br/>SoftwareAuthenticator"] -. "tests and DEBUG only" .-> Core153```154155The approval rule, identical for every signed operation:156157```mermaid158sequenceDiagram159 autonumber160 participant App161 participant Core as SPWalletCore162 participant API as SP Wallet API163 participant Key as Passkey164 participant Signer as Isolated signer165 App->>Core: prepare…(request, idempotency key)166 Core->>API: POST prepare167 API-->>Core: canonical object + WebAuthn options (challenge)168 Core->>Core: StrictObject — every served key must be consumed169 Core->>Core: canonicalBytes() then SHA-256170 Core->>Core: ApprovalBinding.verify — challenge == digest (32 bytes),<br/>rpId == configured relying party, userVerification == "required"171 Core->>Core: object compared with the request (ApprovalError.inconsistent on any difference)172 Core-->>App: VerifiedApproval of the object173 App->>Key: assert(options) after the owner reviewed the object174 Key-->>App: assertion175 App->>Core: approve…(VerifiedApproval, authenticator)176 Core->>API: POST approve177 API->>Signer: object + assertion178 Signer->>Signer: recomputes the same hash, verifies the assertion itself179 Signer-->>API: signed180 API-->>Core: state181```182183`ApprovalError` cases: `challengeMismatch`, `wrongRelyingParty`, `userVerificationNotRequired`, `expired`, `unsupported`,184`inconsistent`. This protects the owner against a server or a network path that would show one thing and have another signed.185It replaces none of the signer's own checks.186187## 🧱 Stack188189| Layer | Technology | Value read in the repository | Role |190|---|---|---|---|191| Manifest | Swift Package Manager | `swift-tools-version: 6.0` | package definition |192| Language | Swift | `.swiftLanguageMode(.v6)` on every target | complete concurrency checking, every public type `Sendable` |193| Platforms | iOS, macOS | `.iOS(.v18)`, `.macOS(.v15)` | deployment targets |194| Localization | — | `defaultLocalization: "fr"` | default language |195| Crypto | CryptoKit | SHA-256, P-256 (test authenticator) | digests, software passkey |196| Networking | Foundation `URLSession` behind `HTTPTransport` | scripted transport in tests | HTTP, websocket, server-sent events |197| Tests | Swift Testing (`import Testing`) | 54 suites, 321 tests | unit and live tests |198| Third-party dependencies | — | none | — |199200Products:201202| Product | Target | Use |203|---|---|---|204| `SPWalletCore` | `Sources/SPWalletCore` | everything the apps ship |205| `SPWalletTestSupport` | `Sources/SPWalletTestSupport` | software passkey and throwaway-stack setup: tests and DEBUG builds only, never referenced by release code |206207## 📁 Repository layout208209```210Package.swift 2 libraries, 2 test targets, Swift 6 language mode211Sources/SPWalletCore/ 76 files212 Foundation/ BaseUnits, Encoding, JSONValue213 Crypto/ Base32, Base58, Bech32, Blake2b, CashAddr, Checksums, Keccak256214 API/ APIClient, APIError, SessionTokenStore215 Auth/ AuthAPI, WebAuthn216 Signing/ Approval, Intent, TransfersAPI217 Wallet/ Models, WalletAPI218 Blockchain/ AddressParameters, AddressValidator, PaymentURI219 Persistence/ OfflineStore220 Domains/221 Swap/ (10 files) SwapAPI, BridgeAPI, XSwapAPI, PlanAPI, canonical, approval, models, stream222 NFT/ (5 files) NFTAPI, canonical, models, market models, transfer models223 Derivatives/ (7 files) DerivativesAPI, live API, GMX API, canonical, primitives, models224 Execution/ (14 files) orders, markets, risk, mandates, developer keys — API, canonical, models225 Agents/ (4 files) AgentsAPI, canonical, models, perpetual models226 Ops/ (12 files) alerts, dashboard, monitor, research, quote stream, server-sent events227Sources/SPWalletTestSupport/ SoftwareAuthenticator228Tests/SPWalletCoreTests/ 13 test files, Support/ (MockTransport, Vectors)229 Vectors/ canonical vectors generated by the backend's own TypeScript (+ README, generators)230 Fixtures/ 41 files: served JSON shapes, address registry and address vectors231Tests/SPWalletLiveTests/ 2 test files, run only against a throwaway stack232Scripts/dev-stack.sh throwaway local SP Wallet stack233docs/CONVENTIONS.md hard rules, layout, test conventions234docs/brand/ logo and icon of this README235```236237## 🚀 Getting started238239Add the package by local path, as both apps do (XcodeGen `project.yml`):240241```yaml242packages:243 SPWalletCore:244 path: ../SPWalletCore245```246247```bash248git clone gitsrv:srv/git/sp-wallet-core.git SPWalletCore249cd SPWalletCore250swift build251swift test # 312 unit tests; the 9 live tests are skipped without a throwaway stack252```253254A minimal read, then a transfer approval, with the public API of the package:255256```swift257import SPWalletCore258259let configuration = APIConfiguration.production(userAgent: "MyClient/1.0 (1)")260let client = APIClient(configuration: configuration, tokens: KeychainTokenStore(service: "my.bundle.id"))261262// reads263let wallet = WalletAPI(client)264let networks = try await wallet.networks()265let portfolio = try await wallet.portfolio()266267// sign in with a passkey (the app supplies a PasskeyAuthenticator)268try await AuthAPI(client).login(with: authenticator)269270// transfer: draft → verified approval → passkey → signer271let transfers = TransfersAPI(client)272let draft = try await transfers.draft(273 TransferRequest(network: "base", asset: "native", to: destination, amount: "0.001"), // decimal text in whole units274 idempotencyKey: APIClient.newIdempotencyKey())275let approval = try await transfers.requestApproval(for: draft) // throws unless challenge == SHA-256(canonical intent)276// … show approval.intent IN FULL to the owner …277let proposal = try await transfers.approve(approval, with: authenticator)278```279280A `PasskeyAuthenticator` is anything that implements:281282```swift283public protocol PasskeyAuthenticator: Sendable {284 func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion285 func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration286}287```288289The apps provide the platform implementation (Apple passkeys); tests use `SoftwareAuthenticator`.290291## ⚙️ Configuration292293The package reads no environment variable in production code. Names used by the tests and by the throwaway stack only:294295| Name | Read by | Purpose |296|---|---|---|297| `SPW_LIVE_ORIGIN` | `SPWalletLiveTests` | origin of a throwaway stack; the live tests are skipped when it is absent |298| `SPW_LIVE_DIR` | `SPWalletLiveTests` | directory of that stack (setup token, software passkey) |299| `SPW_NATIVE_PORT` | `Scripts/dev-stack.sh` | port of the stack (default 8750; signer on port + 1, local fork on port + 2) |300| `SPW_REPO` | `Scripts/dev-stack.sh` | path of the built backend checkout to run |301| `SPW_NATIVE_BASE_RPC` | `Scripts/dev-stack.sh` | upstream RPC forked by the local anvil (`up-fork`) |302| `SPW_NATIVE_WORKERS` | `Scripts/dev-stack.sh` | background workers of the API (default on) |303304`APIConfiguration` carries the origin, the relying-party id and the user agent. The cookie name follows the scheme:305`__Host-spw` behind TLS, `spw` on a plain-HTTP development stack. `APIConfiguration.production(userAgent:)` targets306`https://wallet.spboucher.ai`.307308## 🔌 API surface309310Twenty-two API groups, each a `public struct …API: Sendable` built from an `APIClient`:311312| Group | Folder | Covers |313|---|---|---|314| `AuthAPI` | `Auth/` | state, login, logout, revoke all sessions, add a passkey |315| `WalletAPI` | `Wallet/` | networks, accounts, portfolio, chart, activity, address book, settings, security overview, audit, health, emergency halt |316| `TransfersAPI` | `Signing/` | draft, proposal, status, request approval, approve, reject |317| `SwapAPI` | `Domains/Swap/` | same-network swap |318| `BridgeAPI` | `Domains/Swap/` | USDC CCTP bridge |319| `XSwapAPI` | `Domains/Swap/` | cross-network swap |320| `PlanAPI` | `Domains/Swap/` | multi-step plans |321| `NFTAPI` | `Domains/NFT/` | gallery, items, market, transfers, allow list, UTXO locks |322| `DerivativesAPI` | `Domains/Derivatives/` | market data, paper accounts |323| `DerivativesLiveAPI` | `Domains/Derivatives/` | live venue authorization, orders, leverage |324| `DerivativesCollateralAPI` | `Domains/Derivatives/` | venue deposits and withdrawals |325| `DerivativesGMXAPI` | `Domains/Derivatives/` | GMX |326| `OrdersAPI` | `Domains/Execution/` | unified orders and positions |327| `MarketsAPI` | `Domains/Execution/` | markets explorer |328| `RiskAPI` | `Domains/Execution/` | limits, kill switch, automatic stops |329| `MandatesAPI` | `Domains/Execution/` | trading mandates |330| `DeveloperAPI` | `Domains/Execution/` | API keys, webhooks |331| `AgentsAPI` | `Domains/Agents/` | trading agents |332| `AlertsAPI` | `Domains/Ops/` | alerts and their settings |333| `DashboardAPI` | `Domains/Ops/` | dashboard |334| `MonitorAPI` | `Domains/Ops/` | system state |335| `ResearchAPI` | `Domains/Ops/` | research jobs |336337Streams: `QuoteStream` (the owner's live quote websocket: sequence-checked book deltas, checksum, heartbeat watch, capped338exponential backoff with jitter, stops for good when the session ends), `SwapStream`, and a server-sent-events reader. They are339read-only market data: nothing in them can place, sign or cancel anything.340341## 🧾 Canonical objects342343Twenty-eight canonical domains are ported and checked against vectors generated by the backend's own TypeScript344(`Tests/SPWalletCoreTests/Vectors/`). Three serializations exist on the server:345346| Serialization | Bytes | Hash |347|---|---|---|348| **Framed pairs** | `UTF8(domain) ‖ 0x00`, then for each (name, value) in the order fixed by the code: `u16 BE` name length, `u32 BE` value length, name, value | `SHA-256(bytes)` |349| **Canonical JSON** | `UTF8(domain + "\n" + J(object))`, keys sorted at every depth by UTF-16 code unit, no whitespace, scalars as `JSON.stringify` writes them | `SHA-256(bytes)` |350| **Line-joined** | parts joined with `\n`, the domain first, no trailing newline | `SHA-256(bytes)` |351352`CanonicalWriter` implements the framed form; `StrictObject` reads a served object and throws on any key the code did not353consume, so an unknown field is never silently left out of what is shown.354355<details>356<summary>The 28 domains</summary>357358| Domain | Domain | Domain | Domain |359|---|---|---|---|360| `SPW-INTENT-v1` | `SPW-ENROLL-v1` | `SPW-MANDATE-v1` | `SPW-APIKEY-INTENT-v1` |361| `SPW-NFT-INTENT-v1` | `SPW-NFT-ALLOW-v1` | `SPW-UTXO-LOCKS-v1` | `SPW-SOL-TOKEN-ACCOUNT-v1` |362| `SPW-BRIDGE-MINT-v1` | `SPW-BRIDGE-MINT-SOL-v1` | `SPW-BRIDGE-RECLAIM-v1` | `SPW-ORDER-INTENT-v1` |363| `SPW-ORDER-BODY-v1` | `SPW-TRADING-MANDATE-v1` | `SPW-TRADING-MANDATE-APPROVAL-v1` | `SPW-QUOTING-SECTION-v1` |364| `SPW-RISK-INTENT-v1` | `SPW-RISK-LIMITS-INTENT-v1` | `SPW-RISK-SWITCH-INTENT-v1` | `SPW-RISK-AUTO-INTENT-v1` |365| `SPW-GMX-AUTH-v1` | `SPW-GMX-RISK-INTENT-v1` | `SPW-VENUE-AUTH-v1` | `SPW-VENUE-ORDER-v1` |366| `SPW-VENUE-LEVERAGE-v1` | `SPW-VENUE-WITHDRAW-v1` | `SPW-VENUE-MANDATE-v1` | `SPW-VENUE-QUOTING-MANDATE-v1` |367368`SPW-ORDER-INTENT-v1`, `SPW-ORDER-BODY-v1`, `SPW-TRADING-MANDATE-v1` and `SPW-QUOTING-SECTION-v1` hashes are never a WebAuthn369challenge by themselves.370371</details>372373Vector files: 28 `SPW-<DOMAIN>.json` files (100 vectors) plus per-domain files written with the domains' own tests, for374166 canonical vectors in 41 files. Each vector is `{name, domain, source, object, canonicalHex, hashHex}`; a native client must375reproduce `canonicalHex` and `hashHex` byte for byte from `object`. Vectors are **generated**, never typed by hand. The full376specification of every domain is in [`Tests/SPWalletCoreTests/Vectors/README.md`](Tests/SPWalletCoreTests/Vectors/README.md).377378## 🌐 Networks and addresses379380`AddressValidator.check(_:network:)` validates and normalizes an address for a network; `plausibleNetworks(for:among:)` lists381the networks an input could belong to; `sameEndsDifferentMiddle(_:_:)` flags look-alike addresses. Parity with the backend is382differential: 9 774 cases over the 23 networks of the fixture registry.383384| Family | Networks |385|---|---|386| EVM | Ethereum, Base, Arbitrum, Polygon, Optimism, BNB Smart Chain, Avalanche, HyperEVM |387| Bitcoin-like | Bitcoin, Litecoin, Dogecoin, Bitcoin Cash |388| Others | Solana, Stellar, XRPL, TRON, Aptos, Cosmos, Sui, NEAR, TON, Cardano, Polkadot |389390`PaymentURI` is a strict parser of what a scanned QR code or a pasted text may contain (plain address, BIP-21, EIP-681,391Solana Pay transfer request, `tron:`, `ripple:` / `xrpl:`, `stellar:` / SEP-7 pay, `cosmos:`, `ton://transfer`, `cardano:`) and392the builder of the URI shown by a Receive screen. It refuses control and invisible formatting characters, over-long input and393web or script schemes. Nothing in it touches the network and nothing is executed: the result only pre-fills a form that the394owner reviews and the backend re-validates.395396## 🔐 Security rules3973981. **No private key, no seed, no signing of transactions.** The apps display, prepare and authorize; the isolated signer signs.3992. **Passkey approvals go through `ApprovalBinding.verify`.** If an object cannot be recomputed, the approve function must not400 exist; it is documented as unavailable instead.4013. **What is approved is checked against what was asked** (network, asset, amount, destination, minimum output, leverage,402 limits…): any difference throws `ApprovalError.inconsistent`.4034. **Amounts are strings** (base units plus the server's exact display text); `BaseUnits` for arithmetic. `Double` only for prices, percentages, chart404 points and fiat estimates.4055. **Never invent data**: no default that looks like a real value, no placeholder balance, no success state inferred by the406 client. A missing balance is `nil`, not 0; an unknown state is shown verbatim.4076. **The session cookie is handled by hand**, never by a shared cookie jar, and only ever sent to the configured origin.408 `KeychainTokenStore` keeps it in the Keychain; `OfflineStore` refuses the keys reserved for credentials and is409 emptied at sign-out.4107. **Every state-changing call protected by `Idempotency-Key` takes the key from the caller**, so a retry reuses it.4118. **`SoftwareAuthenticator` is for throwaway stacks only.** It is never compiled into a release build of the apps and must412 never be enrolled on the production wallet.413414## 🧪 Testing415416```bash417swift test # unit tests418export $(Scripts/dev-stack.sh env) && swift test --filter SPWalletLiveTests # live tests against the throwaway stack419```420421| Target | Files | Tests | What it checks |422|---|---:|---:|---|423| `SPWalletCoreTests` | 13 | 312 | amounts, codecs, client contract, canonical domains against vectors, address parity, every domain's models and endpoints |424| `SPWalletLiveTests` | 2 | 9 | real server and real signer process on the throwaway stack: draft → verified intent → passkey → signer → broadcast → `finalized`, and the refusals |425426<details>427<summary>Tests per file</summary>428429| File | Tests | File | Tests |430|---|---:|---|---:|431| `SwapTests` | 45 | `FoundationTests` | 16 |432| `DerivativesTests` | 44 | `CryptoTests` | 14 |433| `ExecutionTests` | 42 | `PaymentURITests` | 14 |434| `AgentsTests` | 34 | `AddressValidatorTests` | 11 |435| `NFTTests` | 33 | `OfflineStoreTests` | 6 |436| `OpsTests` | 30 | `IntentVectorTests` | 4 |437| `QuoteStreamTests` | 19 | `LiveStackTests` (live) | 5 |438| | | `LiveTransferTests` (live) | 4 |439440</details>441442A scripted `HTTPTransport` (`Tests/SPWalletCoreTests/Support/MockTransport.swift`) checks the method, path, query, headers and443body of each endpoint. JSON fixtures copy the shape of what the backend serves; each test says where its fixture comes from.444445## 🧰 Throwaway stack446447`Scripts/dev-stack.sh` starts a local SP Wallet stack for the integration tests of the native clients: a **new random signer448keystore** (no real funds, ever), its own Postgres database, `http://localhost`.449450```bash451Scripts/dev-stack.sh up # broadcast OFF: a signed transaction never leaves the machine452Scripts/dev-stack.sh up-fork # Base served by a LOCAL anvil fork where the throwaway wallet gets 1 fake ETH; broadcast on, to that fork only453Scripts/dev-stack.sh status454Scripts/dev-stack.sh env # prints SPW_LIVE_ORIGIN=… SPW_LIVE_DIR=…455Scripts/dev-stack.sh down # stops by the PID of each port456```457458It needs a built backend checkout (`SPW_REPO`), Node.js, PostgreSQL client tools, `openssl`, and Foundry's `anvil` for459`up-fork`. Each start uses a fresh run directory; the script deletes nothing. The local fork mines a block every 2 s so that460finality can be reached. Every live-trading lock stays at its default (off).461462## 📐 Conventions463464From [`docs/CONVENTIONS.md`](docs/CONVENTIONS.md):465466- One folder per backend domain under `Domains/<Name>/`: models in `…Models.swift`, endpoints in `…API.swift` as a467 `public struct XxxAPI: Sendable { let client: APIClient; public init(_:) }`, canonical objects in `…Canonical.swift`.468- Models decode leniently on optional or absent fields (the server evolves additively) but never coerce.469- Swift 6 language mode, complete concurrency checking, zero third-party dependency, every public type `Sendable`.470- Every file starts with the header (project, File, Description, Author, Contact). Code and comments in English.471- Tests use Swift Testing; per domain `Tests/SPWalletCoreTests/<Name>Tests.swift`, fixtures in `Fixtures/<name>-*.json`,472 vectors in `Vectors/<name>-*.json`.473- This package is owned by the iOS project and shared with the macOS client: announce any breaking change of its public API474 before making it.475476## 🧯 Gotchas477478- **Sorting** in canonical objects is JavaScript's default (UTF-16 code unit, ascending, no locale). In Swift:479 `sorted { $0.utf16.lexicographicallyPrecedes($1.utf16) }`, never `localizedCompare`.480- **Canonical JSON**: `/` is not escaped (Swift's encoders write `\/` unless told otherwise); non-ASCII is raw UTF-8; an481 integer-valued double has no `.0`. Re-serialize the JSON tree that was received; do not round-trip amounts through `Double`.482- **Decimal strings** of the derivatives and trading objects are canonicalized before framing (trailing zeros and a trailing483 `.` removed, zero is `"0"`); the object served may or may not already be canonical, so always apply it.484- **`dev-stack.sh up-fork` in a pipe blocks**: redirect its output to a file instead.485- `dev-stack.sh down` stops processes by the PID that listens on the stack's ports, never by a process-name pattern.486487## 👤 Author488489<div align="center">490<img src="docs/brand/icon.png" width="64" height="64" alt=""><br>491492**Simon-Pierre Boucher** — design, development, operations<br>493[www.spboucher.ai](https://www.spboucher.ai) · [git.spboucher.ai](https://git.spboucher.ai) · contact@spboucher.ai494495</div>496497## 📄 License498499All rights reserved © 2026 Simon-Pierre Boucher.500