🛡️ SPWalletCore
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.
Author: Simon-Pierre Boucher
Table of contents
- Overview
- What the package provides
- Architecture
- Stack
- Repository layout
- Getting started
- Configuration
- API surface
- Canonical objects
- Networks and addresses
- Security rules
- Testing
- Throwaway stack
- Conventions
- Gotchas
- Author
- License
🎯 Overview
SPWalletCore is the code that the native SP Wallet apps share. SP Wallet is a personal multichain wallet
(wallet.spboucher.ai) in which the device displays, prepares and authorizes, and an isolated
signer on the MacLustr cluster holds the keys and signs.
The package exists for one reason above all: a passkey approval must sign what the owner sees. For every object the backend
has approved by a passkey, the package ports the backend's canonical serialization byte for byte, recomputes
SHA-256(canonical bytes) on the device, and requires the server's WebAuthn challenge to be exactly that hash before any passkey
prompt appears. The approve calls only accept the resulting VerifiedApproval<…> value, which cannot be built any other way.
It contains no private key, no seed, and signs no transaction.
SP Wallet family
| Repository | Role | Platform |
|---|---|---|
| sp-wallet | API, web app, isolated signer | web · wallet.spboucher.ai |
| sp-wallet-core (this repository) | shared Swift package SPWalletCore |
iOS 18+ · macOS 15+ |
| sp-wallet-ios | native iPhone and iPad client (owner of this package) | iOS · iPadOS |
| sp-wallet-macos | native macOS client | macOS |
Both apps reference the package by a local path (../SPWalletCore): clone this repository next to the app, under that name.
✨ What the package provides
| Area | Folder | What it does |
|---|---|---|
| Exact amounts and JSON | Foundation/ |
BaseUnits (base-unit integers as strings), JSONValue, encodings. Amounts never go through Double |
| Hashes and address codecs | Crypto/ |
Keccak-256, BLAKE2b, Base58, Base32, Bech32, CashAddr, checksums — implemented here, no dependency |
| 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 |
| Authentication | Auth/ |
WebAuthn JSON types, login, sign-out, session revocation, passkey enrolment (SPW-ENROLL-v1) |
| Approval binding | Signing/ |
PasskeyApprovable, ApprovalBinding.verify, VerifiedApproval, CanonicalWriter, StrictObject, Intent, transfers |
| Wallet reads | Wallet/ |
networks, accounts, portfolio, charts, activity (and CSV export), address book, settings, security overview, audit journal, health |
| Addresses and payment URIs | Blockchain/ |
AddressValidator (23 networks), strict parser and builder of payment URIs for QR codes and pasted text |
| Offline snapshots | Persistence/ |
OfflineStore (actor): read-only dated snapshots and a size-capped media cache; refuses keys reserved for credentials |
| Swaps and bridges | Domains/Swap/ |
same-network swap, CCTP bridge, cross-network swap, multi-step plans, quote fingerprints, swap event stream |
| NFTs | Domains/NFT/ |
gallery, items, collections, market (read), transfers, destination allow list, UTXO locks |
| Derivatives | Domains/Derivatives/ |
market data, paper accounts, live venue approvals, collateral, GMX |
| Execution | Domains/Execution/ |
unified orders, markets, risk limits and kill switch, trading mandates, developer API keys and webhooks |
| Trading agents | Domains/Agents/ |
simulation, paper, live spot under mandate, perpetuals, withdrawals |
| Operations | Domains/Ops/ |
alert catalog and alerts, dashboard, monitor, research jobs, server-sent events, live quote websocket |
| Test support | Sources/SPWalletTestSupport/ |
SoftwareAuthenticator: a software WebAuthn authenticator for throwaway stacks only |
🏗 Architecture
flowchart TB
subgraph Apps["Native apps"]
iOS["sp-wallet-ios<br/>iPhone · iPad"]
mac["sp-wallet-macos"]
end
subgraph Core["SPWalletCore"]
Domains["Domains/<br/>Swap · NFT · Derivatives<br/>Execution · Agents · Ops"]
Signing["Signing/<br/>ApprovalBinding · Intent<br/>CanonicalWriter · StrictObject"]
Wallet["Wallet/ · Auth/"]
API["API/<br/>APIClient (actor)<br/>SessionTokenStoring · HTTPTransport"]
Chain["Blockchain/<br/>AddressValidator · PaymentURI"]
Store["Persistence/<br/>OfflineStore (actor)"]
Base["Foundation/ · Crypto/"]
Domains --> Signing --> API
Domains --> API
Wallet --> API
Signing --> Base
Chain --> Base
API --> Base
end
iOS --> Core
mac --> Core
API -- "HTTPS /api/v1<br/>session cookie · Origin · X-SPW-CSRF" --> Server["SP Wallet API<br/>wallet.spboucher.ai"]
Server -- "relays object + assertion" --> Signer["Isolated signer<br/>keys · pinned passkeys"]
TS["SPWalletTestSupport<br/>SoftwareAuthenticator"] -. "tests and DEBUG only" .-> Core
The approval rule, identical for every signed operation:
sequenceDiagram autonumber participant App participant Core as SPWalletCore participant API as SP Wallet API participant Key as Passkey participant Signer as Isolated signer App->>Core: prepare…(request, idempotency key) Core->>API: POST prepare API-->>Core: canonical object + WebAuthn options (challenge) Core->>Core: StrictObject — every served key must be consumed Core->>Core: canonicalBytes() then SHA-256 Core->>Core: ApprovalBinding.verify — challenge == digest (32 bytes),<br/>rpId == configured relying party, userVerification == "required" Core->>Core: object compared with the request (ApprovalError.inconsistent on any difference) Core-->>App: VerifiedApproval of the object App->>Key: assert(options) after the owner reviewed the object Key-->>App: assertion App->>Core: approve…(VerifiedApproval, authenticator) Core->>API: POST approve API->>Signer: object + assertion Signer->>Signer: recomputes the same hash, verifies the assertion itself Signer-->>API: signed API-->>Core: state
ApprovalError cases: challengeMismatch, wrongRelyingParty, userVerificationNotRequired, expired, unsupported,
inconsistent. This protects the owner against a server or a network path that would show one thing and have another signed.
It replaces none of the signer's own checks.
🧱 Stack
| Layer | Technology | Value read in the repository | Role |
|---|---|---|---|
| Manifest | Swift Package Manager | swift-tools-version: 6.0 |
package definition |
| Language | Swift | .swiftLanguageMode(.v6) on every target |
complete concurrency checking, every public type Sendable |
| Platforms | iOS, macOS | .iOS(.v18), .macOS(.v15) |
deployment targets |
| Localization | — | defaultLocalization: "fr" |
default language |
| Crypto | CryptoKit | SHA-256, P-256 (test authenticator) | digests, software passkey |
| Networking | Foundation URLSession behind HTTPTransport |
scripted transport in tests | HTTP, websocket, server-sent events |
| Tests | Swift Testing (import Testing) |
54 suites, 321 tests | unit and live tests |
| Third-party dependencies | — | none | — |
Products:
| Product | Target | Use |
|---|---|---|
SPWalletCore |
Sources/SPWalletCore |
everything the apps ship |
SPWalletTestSupport |
Sources/SPWalletTestSupport |
software passkey and throwaway-stack setup: tests and DEBUG builds only, never referenced by release code |
📁 Repository layout
Package.swift 2 libraries, 2 test targets, Swift 6 language mode
Sources/SPWalletCore/ 76 files
Foundation/ BaseUnits, Encoding, JSONValue
Crypto/ Base32, Base58, Bech32, Blake2b, CashAddr, Checksums, Keccak256
API/ APIClient, APIError, SessionTokenStore
Auth/ AuthAPI, WebAuthn
Signing/ Approval, Intent, TransfersAPI
Wallet/ Models, WalletAPI
Blockchain/ AddressParameters, AddressValidator, PaymentURI
Persistence/ OfflineStore
Domains/
Swap/ (10 files) SwapAPI, BridgeAPI, XSwapAPI, PlanAPI, canonical, approval, models, stream
NFT/ (5 files) NFTAPI, canonical, models, market models, transfer models
Derivatives/ (7 files) DerivativesAPI, live API, GMX API, canonical, primitives, models
Execution/ (14 files) orders, markets, risk, mandates, developer keys — API, canonical, models
Agents/ (4 files) AgentsAPI, canonical, models, perpetual models
Ops/ (12 files) alerts, dashboard, monitor, research, quote stream, server-sent events
Sources/SPWalletTestSupport/ SoftwareAuthenticator
Tests/SPWalletCoreTests/ 13 test files, Support/ (MockTransport, Vectors)
Vectors/ canonical vectors generated by the backend's own TypeScript (+ README, generators)
Fixtures/ 41 files: served JSON shapes, address registry and address vectors
Tests/SPWalletLiveTests/ 2 test files, run only against a throwaway stack
Scripts/dev-stack.sh throwaway local SP Wallet stack
docs/CONVENTIONS.md hard rules, layout, test conventions
docs/brand/ logo and icon of this README🚀 Getting started
Add the package by local path, as both apps do (XcodeGen project.yml):
packages:
SPWalletCore:
path: ../SPWalletCoregit clone gitsrv:srv/git/sp-wallet-core.git SPWalletCore
cd SPWalletCore
swift build
swift test # 312 unit tests; the 9 live tests are skipped without a throwaway stackA minimal read, then a transfer approval, with the public API of the package:
import SPWalletCore
let configuration = APIConfiguration.production(userAgent: "MyClient/1.0 (1)")
let client = APIClient(configuration: configuration, tokens: KeychainTokenStore(service: "my.bundle.id"))
// reads
let wallet = WalletAPI(client)
let networks = try await wallet.networks()
let portfolio = try await wallet.portfolio()
// sign in with a passkey (the app supplies a PasskeyAuthenticator)
try await AuthAPI(client).login(with: authenticator)
// transfer: draft → verified approval → passkey → signer
let transfers = TransfersAPI(client)
let draft = try await transfers.draft(
TransferRequest(network: "base", asset: "native", to: destination, amount: "0.001"), // decimal text in whole units
idempotencyKey: APIClient.newIdempotencyKey())
let approval = try await transfers.requestApproval(for: draft) // throws unless challenge == SHA-256(canonical intent)
// … show approval.intent IN FULL to the owner …
let proposal = try await transfers.approve(approval, with: authenticator)A PasskeyAuthenticator is anything that implements:
public protocol PasskeyAuthenticator: Sendable {
func assert(_ options: PasskeyRequestOptions, rpId: String) async throws -> PasskeyAssertion
func register(_ options: PasskeyCreationOptions, rpId: String) async throws -> PasskeyRegistration
}The apps provide the platform implementation (Apple passkeys); tests use SoftwareAuthenticator.
⚙️ Configuration
The package reads no environment variable in production code. Names used by the tests and by the throwaway stack only:
| Name | Read by | Purpose |
|---|---|---|
SPW_LIVE_ORIGIN |
SPWalletLiveTests |
origin of a throwaway stack; the live tests are skipped when it is absent |
SPW_LIVE_DIR |
SPWalletLiveTests |
directory of that stack (setup token, software passkey) |
SPW_NATIVE_PORT |
Scripts/dev-stack.sh |
port of the stack (default 8750; signer on port + 1, local fork on port + 2) |
SPW_REPO |
Scripts/dev-stack.sh |
path of the built backend checkout to run |
SPW_NATIVE_BASE_RPC |
Scripts/dev-stack.sh |
upstream RPC forked by the local anvil (up-fork) |
SPW_NATIVE_WORKERS |
Scripts/dev-stack.sh |
background workers of the API (default on) |
APIConfiguration carries the origin, the relying-party id and the user agent. The cookie name follows the scheme:
__Host-spw behind TLS, spw on a plain-HTTP development stack. APIConfiguration.production(userAgent:) targets
https://wallet.spboucher.ai.
🔌 API surface
Twenty-two API groups, each a public struct …API: Sendable built from an APIClient:
| Group | Folder | Covers |
|---|---|---|
AuthAPI |
Auth/ |
state, login, logout, revoke all sessions, add a passkey |
WalletAPI |
Wallet/ |
networks, accounts, portfolio, chart, activity, address book, settings, security overview, audit, health, emergency halt |
TransfersAPI |
Signing/ |
draft, proposal, status, request approval, approve, reject |
SwapAPI |
Domains/Swap/ |
same-network swap |
BridgeAPI |
Domains/Swap/ |
USDC CCTP bridge |
XSwapAPI |
Domains/Swap/ |
cross-network swap |
PlanAPI |
Domains/Swap/ |
multi-step plans |
NFTAPI |
Domains/NFT/ |
gallery, items, market, transfers, allow list, UTXO locks |
DerivativesAPI |
Domains/Derivatives/ |
market data, paper accounts |
DerivativesLiveAPI |
Domains/Derivatives/ |
live venue authorization, orders, leverage |
DerivativesCollateralAPI |
Domains/Derivatives/ |
venue deposits and withdrawals |
DerivativesGMXAPI |
Domains/Derivatives/ |
GMX |
OrdersAPI |
Domains/Execution/ |
unified orders and positions |
MarketsAPI |
Domains/Execution/ |
markets explorer |
RiskAPI |
Domains/Execution/ |
limits, kill switch, automatic stops |
MandatesAPI |
Domains/Execution/ |
trading mandates |
DeveloperAPI |
Domains/Execution/ |
API keys, webhooks |
AgentsAPI |
Domains/Agents/ |
trading agents |
AlertsAPI |
Domains/Ops/ |
alerts and their settings |
DashboardAPI |
Domains/Ops/ |
dashboard |
MonitorAPI |
Domains/Ops/ |
system state |
ResearchAPI |
Domains/Ops/ |
research jobs |
Streams: QuoteStream (the owner's live quote websocket: sequence-checked book deltas, checksum, heartbeat watch, capped
exponential backoff with jitter, stops for good when the session ends), SwapStream, and a server-sent-events reader. They are
read-only market data: nothing in them can place, sign or cancel anything.
🧾 Canonical objects
Twenty-eight canonical domains are ported and checked against vectors generated by the backend's own TypeScript
(Tests/SPWalletCoreTests/Vectors/). Three serializations exist on the server:
| Serialization | Bytes | Hash |
|---|---|---|
| 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) |
| 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) |
| Line-joined | parts joined with \n, the domain first, no trailing newline |
SHA-256(bytes) |
CanonicalWriter implements the framed form; StrictObject reads a served object and throws on any key the code did not
consume, so an unknown field is never silently left out of what is shown.
The 28 domains
| Domain | Domain | Domain | Domain |
|---|---|---|---|
SPW-INTENT-v1 |
SPW-ENROLL-v1 |
SPW-MANDATE-v1 |
SPW-APIKEY-INTENT-v1 |
SPW-NFT-INTENT-v1 |
SPW-NFT-ALLOW-v1 |
SPW-UTXO-LOCKS-v1 |
SPW-SOL-TOKEN-ACCOUNT-v1 |
SPW-BRIDGE-MINT-v1 |
SPW-BRIDGE-MINT-SOL-v1 |
SPW-BRIDGE-RECLAIM-v1 |
SPW-ORDER-INTENT-v1 |
SPW-ORDER-BODY-v1 |
SPW-TRADING-MANDATE-v1 |
SPW-TRADING-MANDATE-APPROVAL-v1 |
SPW-QUOTING-SECTION-v1 |
SPW-RISK-INTENT-v1 |
SPW-RISK-LIMITS-INTENT-v1 |
SPW-RISK-SWITCH-INTENT-v1 |
SPW-RISK-AUTO-INTENT-v1 |
SPW-GMX-AUTH-v1 |
SPW-GMX-RISK-INTENT-v1 |
SPW-VENUE-AUTH-v1 |
SPW-VENUE-ORDER-v1 |
SPW-VENUE-LEVERAGE-v1 |
SPW-VENUE-WITHDRAW-v1 |
SPW-VENUE-MANDATE-v1 |
SPW-VENUE-QUOTING-MANDATE-v1 |
SPW-ORDER-INTENT-v1, SPW-ORDER-BODY-v1, SPW-TRADING-MANDATE-v1 and SPW-QUOTING-SECTION-v1 hashes are never a WebAuthn
challenge by themselves.
Vector files: 28 SPW-<DOMAIN>.json files (100 vectors) plus per-domain files written with the domains' own tests, for
166 canonical vectors in 41 files. Each vector is {name, domain, source, object, canonicalHex, hashHex}; a native client must
reproduce canonicalHex and hashHex byte for byte from object. Vectors are generated, never typed by hand. The full
specification of every domain is in Tests/SPWalletCoreTests/Vectors/README.md.
🌐 Networks and addresses
AddressValidator.check(_:network:) validates and normalizes an address for a network; plausibleNetworks(for:among:) lists
the networks an input could belong to; sameEndsDifferentMiddle(_:_:) flags look-alike addresses. Parity with the backend is
differential: 9 774 cases over the 23 networks of the fixture registry.
| Family | Networks |
|---|---|
| EVM | Ethereum, Base, Arbitrum, Polygon, Optimism, BNB Smart Chain, Avalanche, HyperEVM |
| Bitcoin-like | Bitcoin, Litecoin, Dogecoin, Bitcoin Cash |
| Others | Solana, Stellar, XRPL, TRON, Aptos, Cosmos, Sui, NEAR, TON, Cardano, Polkadot |
PaymentURI is a strict parser of what a scanned QR code or a pasted text may contain (plain address, BIP-21, EIP-681,
Solana Pay transfer request, tron:, ripple: / xrpl:, stellar: / SEP-7 pay, cosmos:, ton://transfer, cardano:) and
the builder of the URI shown by a Receive screen. It refuses control and invisible formatting characters, over-long input and
web or script schemes. Nothing in it touches the network and nothing is executed: the result only pre-fills a form that the
owner reviews and the backend re-validates.
🔐 Security rules
- No private key, no seed, no signing of transactions. The apps display, prepare and authorize; the isolated signer signs.
- Passkey approvals go through
ApprovalBinding.verify. If an object cannot be recomputed, the approve function must not exist; it is documented as unavailable instead. - What is approved is checked against what was asked (network, asset, amount, destination, minimum output, leverage,
limits…): any difference throws
ApprovalError.inconsistent. - Amounts are strings (base units plus the server's exact display text);
BaseUnitsfor arithmetic.Doubleonly for prices, percentages, chart points and fiat estimates. - Never invent data: no default that looks like a real value, no placeholder balance, no success state inferred by the
client. A missing balance is
nil, not 0; an unknown state is shown verbatim. - The session cookie is handled by hand, never by a shared cookie jar, and only ever sent to the configured origin.
KeychainTokenStorekeeps it in the Keychain;OfflineStorerefuses the keys reserved for credentials and is emptied at sign-out. - Every state-changing call protected by
Idempotency-Keytakes the key from the caller, so a retry reuses it. SoftwareAuthenticatoris for throwaway stacks only. It is never compiled into a release build of the apps and must never be enrolled on the production wallet.
🧪 Testing
swift test # unit tests
export $(Scripts/dev-stack.sh env) && swift test --filter SPWalletLiveTests # live tests against the throwaway stack| Target | Files | Tests | What it checks |
|---|---|---|---|
SPWalletCoreTests |
13 | 312 | amounts, codecs, client contract, canonical domains against vectors, address parity, every domain's models and endpoints |
SPWalletLiveTests |
2 | 9 | real server and real signer process on the throwaway stack: draft → verified intent → passkey → signer → broadcast → finalized, and the refusals |
Tests per file
| File | Tests | File | Tests |
|---|---|---|---|
SwapTests |
45 | FoundationTests |
16 |
DerivativesTests |
44 | CryptoTests |
14 |
ExecutionTests |
42 | PaymentURITests |
14 |
AgentsTests |
34 | AddressValidatorTests |
11 |
NFTTests |
33 | OfflineStoreTests |
6 |
OpsTests |
30 | IntentVectorTests |
4 |
QuoteStreamTests |
19 | LiveStackTests (live) |
5 |
LiveTransferTests (live) |
4 |
A scripted HTTPTransport (Tests/SPWalletCoreTests/Support/MockTransport.swift) checks the method, path, query, headers and
body of each endpoint. JSON fixtures copy the shape of what the backend serves; each test says where its fixture comes from.
🧰 Throwaway stack
Scripts/dev-stack.sh starts a local SP Wallet stack for the integration tests of the native clients: a new random signer
keystore (no real funds, ever), its own Postgres database, http://localhost.
Scripts/dev-stack.sh up # broadcast OFF: a signed transaction never leaves the machine
Scripts/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 only
Scripts/dev-stack.sh status
Scripts/dev-stack.sh env # prints SPW_LIVE_ORIGIN=… SPW_LIVE_DIR=…
Scripts/dev-stack.sh down # stops by the PID of each portIt needs a built backend checkout (SPW_REPO), Node.js, PostgreSQL client tools, openssl, and Foundry's anvil for
up-fork. Each start uses a fresh run directory; the script deletes nothing. The local fork mines a block every 2 s so that
finality can be reached. Every live-trading lock stays at its default (off).
📐 Conventions
From docs/CONVENTIONS.md:
- One folder per backend domain under
Domains/<Name>/: models in…Models.swift, endpoints in…API.swiftas apublic struct XxxAPI: Sendable { let client: APIClient; public init(_:) }, canonical objects in…Canonical.swift. - Models decode leniently on optional or absent fields (the server evolves additively) but never coerce.
- Swift 6 language mode, complete concurrency checking, zero third-party dependency, every public type
Sendable. - Every file starts with the header (project, File, Description, Author, Contact). Code and comments in English.
- Tests use Swift Testing; per domain
Tests/SPWalletCoreTests/<Name>Tests.swift, fixtures inFixtures/<name>-*.json, vectors inVectors/<name>-*.json. - This package is owned by the iOS project and shared with the macOS client: announce any breaking change of its public API before making it.
🧯 Gotchas
- Sorting in canonical objects is JavaScript's default (UTF-16 code unit, ascending, no locale). In Swift:
sorted { $0.utf16.lexicographicallyPrecedes($1.utf16) }, neverlocalizedCompare. - Canonical JSON:
/is not escaped (Swift's encoders write\/unless told otherwise); non-ASCII is raw UTF-8; an integer-valued double has no.0. Re-serialize the JSON tree that was received; do not round-trip amounts throughDouble. - Decimal strings of the derivatives and trading objects are canonicalized before framing (trailing zeros and a trailing
.removed, zero is"0"); the object served may or may not already be canonical, so always apply it. dev-stack.sh up-forkin a pipe blocks: redirect its output to a file instead.dev-stack.sh downstops processes by the PID that listens on the stack's ports, never by a process-name pattern.
👤 Author
Simon-Pierre Boucher — design, development, operations
www.spboucher.ai · git.spboucher.ai · contact@spboucher.ai
📄 License
All rights reserved © 2026 Simon-Pierre Boucher.