sphere-sdk
CLAUDE.md5.4k starsChanged 2 months agoMITView on GitHub
This file provides context for Claude Code when working with the Sphere SDK project. This repo is part of the wallet-api program (process: ../wallet-api/docs/development-workflow.md). - Branch topology (updated 2026-07-31): all work branches from and PRs back to main — the feat/wallet-api-integration era ended when the integration branches merged (releases ship from main; wallet-api#119 records this in the process doc). Every PR links a GitHub issue (Closes #N, docs-only changes exempt); squash-merge after green CI (.github/workflows/ci.yml: verify:version + typecheck + typecheck:tests…
- Reads credentials
- Installs packages
Trending
Less talk lately.thin dataabout the whole repository
Who's talking about unicity-sphere/sphere-sdk
- unicitynetwork/unicity-ids“Add bridged Sepolia USDC (USDC.e) to testnet2”GitHub · Oct 2, 2026
- unicitynetwork/webwallet“Allow webwallet to import Sphere's json”GitHub · Jul 28, 2026
- unicity-sphere/sphere-cli“fix(cli)(sphere-sdk#455): mint test tokens locally (drop HTTP faucet)”GitHub · Jun 9, 2026
- unicity-sphere/sphere“chore(vendor): bump sphere-sdk to 116b8d9 (PR #385 identity-keys cache-only)”GitHub · Jun 1, 2026
- unicitynetwork/state-transition-sdk-js“SparseMerkleTreePath.fromJSON should enforce a max step-path bit-length”GitHub · May 27, 2026
The biggest 5 of 6 mentions linking to the repository that our crawl found. Each line is their own headline.
See all 6
Talked about on GitHub (6 times).
On GitHub · 6
- Oct 2, 2026Add bridged Sepolia USDC (USDC.e) to testnet2 — unicitynetwork/unicity-ids0 reactions
- Jul 28, 2026Allow webwallet to import Sphere's json — unicitynetwork/webwallet0 reactions
- Jun 9, 2026fix(cli)(sphere-sdk#455): mint test tokens locally (drop HTTP faucet) — unicity-sphere/sphere-cli0 reactions
- Jun 1, 2026chore(vendor): bump sphere-sdk to 116b8d9 (PR #385 identity-keys cache-only) — unicity-sphere/sphere0 reactions
- May 27, 2026SparseMerkleTreePath.fromJSON should enforce a max step-path bit-length — unicitynetwork/state-transition-sdk-js0 reactions
1 more on GitHub
- May 13, 2026Publish and validate the native Sphere wallet capsule end-to-end — astrid-runtime/astrid0 reactions · 1 comment
The file
We split this CLAUDE.md into the rules it gives an agent
8 rules. About 0 are common, 0 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 9
Branch topology (updated 2026-07-31): all work branches from and PRs back to main — the feat/wallet-api-integration era ended when the …
- Very specific: line 70
What 3.x is: every transaction now carries expiresAt — an exclusive request deadline in Unix seconds — and every inclusion proof carries …
- Very specific: line 358
Read it lazily at the call site, never once at construction.
- Very specific: line 605
The engine is mandatory for money movement: when the oracle does not supply a trust base + gateway URL (or the engine cannot be …
- Very specific: line 732
All networks share Nostr relays (nostr-relay.testnet.unicity.network for test nets) and group relays per NETWORKS.
- Very specific: line 862
tokenTypeis a CLASS, not an identity: Every token of one kind shares a type. - Very specific: line 1110
Prefer interface over type for objects
- Very specific: line 1111
Use readonly for immutable properties
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md - Sphere SDK Project Context
This file provides context for Claude Code when working with the Sphere SDK project.
⚡ wallet-api program — current work (read first)
This repo is part of the wallet-api program (process: ../wallet-api/docs/development-workflow.md).
- Branch topology (updated 2026-07-31): all work branches from and PRs back to
main— thefeat/wallet-api-integrationera ended when the integration branches merged (releases ship frommain; wallet-api#119 records this in the process doc). Every PR links a GitHub issue (Closes #N, docs-only changes exempt); squash-merge after green CI (.github/workflows/ci.yml: verify:version + typecheck + typecheck:tests + lint + build + test:run on Node 22 and 24, plus a separatetest:mutationjob). - The normative spec for the program's SDK work is
../wallet-api/docs/sdk-changes.md— Part E (recoverable engine), then S1–S7 (thin wallet, ports, wallet-api providers). It was adversarially verified; build it, don't redesign it. Spec-first: contract changes land in the spec in the same PR, before code. The payments vertical (P11 flip landed) is the ONLY money path — design record + build history:docs/PAYMENTS-V2-DESIGN.md(read it for the why before touchingmodules/payments-v2/orimpl/wallet-api-v2/; the code anddocs/API.mdare normative for the current API). Migration guide for consumers:docs/MIGRATION-PAYMENTS-V2.md. - Resume is status-agnostic (sdk-changes E.2): never key engine resume off a submit status —
submit, always
getInclusionProof, match-verify (OK= mine,TRANSACTION_HASH_MISMATCH=TransferConflictError). That stays the ONLY conflict signal under 3.x: a nullinclusionProofmeans "not certified YET", and the time-dependent statuses the bump added —REQUEST_EXPIREDandREFERENCE_TIME_AFTER_ROUNDon verify,REQUEST_EXPIREDandSERVICE_NOT_READYon submit — each report only that THIS attempt was not admitted, never that no earlier attempt certified, so none of them is a clean reject. TheSTATE_ID_EXISTSaggregator lag is OVER (M7 live e2e observed 2026-06-12: the gateway answersSUCCESSfor duplicate AND conflicting submits — the status carries no conflict signal; see the dated OBSERVED note in../wallet-api/docs/sdk-changes.mdE.2); tolerant parsing shipped via state-transition-sdk-js#125 and stays. - Sphere sets no request deadline, ANYWHERE (#760): every mint / transfer / split burn /
split mint leg omits
expiresAt, so the Unicity Service assigns one from consensus time and does not record it. The reason is not determinism — a deadline persisted on the durable intent would rebuild byte-identically — it is (a) an untrusted browser clock, where one skewed wallet pinning a past deadline is a wallet-wide payment outage, and (b) unrecoverability across downtime longer than the window: every resume would rebuild an already-expired transaction and the intent would sit open forever with its sources reserved, and there is currently NO attempt budget on the certify/resume path at all. What makes the policy load-bearing rather than cosmetic:expiresAtis committed by the transaction HASH but is NOT part of the StateId, so two attempts that disagree about it address the SAME leaf with DIFFERENT hashes — andInclusionProofVerificationRulecompares the hash BEFORE the certification data, so the disagreement surfaces asTRANSACTION_HASH_MISMATCH, i.e. as a foreign spend, whichtoken-engine/certification-outcome.tsmaps toTransferConflictError(abort + re-plan). A clock-derived deadline would therefore make every crash-resume abort an intent whose spend is already on chain. Pinned bytests/unit/token-engine/expires-at.test.ts, including a 24-hour clock jump between two attempts. - Ports rule (design §10 / covenant): the money ports are
StoragePortandDeliveryPort(modules/payments-v2/ports.ts) — independent, swappable, contract-test-enforced (tests/unit/payments-v2/contracts/); the Sphere frontend is a view — no provider-specific logic outside implementations; custody (intoInventory) is a composition-time property, never a per-call flag. - Never weaken a test to make it pass; no
.skip/.only. (#487, the old pre-existing-failure tracker, is closed: it covered tests of modules that have since been deleted.) - Releases: npm versions publish via
publish.yml(workflow_dispatch, version input) — the workflow runsnpm versionitself, sopackage.jsonon a branch still reads the PREVIOUS version; never hand-edit the field. Publishing frommaintakes dist-taglatest, any other branch takesdev(line<next version>-dev.#). Consumers (wallet-api backend, sphere frontend) pin exact versions. The backend consumes ONLY the./token-enginesubpath (must stay browser/Nostr-free — keeptoken-engine/clean). - The 3.x bump was a fleet-wide flag day (#760, shipped in 0.15.0). The forcing function
is
aggregator-go, whose main already carriesCertificationDataVersion = 2with a hard reject of version 1 — nothing can straddle the gateway cutover.wallet-apimust bump in LOCKSTEP: both repos pin@unicitylabs/state-transition-sdkEXACTLY, so bumping sphere-sdk alone makes npm dedupe impossible and runs both wire realms live; they cross at../wallet-api/src/validation/verifier.ts. A testnet + wallet-api backend reset accompanied that release. - Pinned base SDK:
@unicitylabs/state-transition-sdk@3.0.1(exact pin; bump only via PR). What 3.x is: every transaction now carriesexpiresAt— an exclusive request deadline in Unix seconds — and every inclusion proof carries thereferenceTimeof the round that certified it; the sparse-Merkle leaf value became H(transactionHash, referenceTime) instead of the bare transaction hash. The Token / MintTransaction / TransferTransaction / CertificationData wire versions all moved with it: nothing written by 2.x decodes, and nothing 2.x writes is accepted by the upgraded aggregator — in either direction, no exceptions. The lost-abort hang inwaitInclusionProofthat 2.0.3 fixed (state-transition-sdk-js#140/#141) is still fixed in 3.0.1: its poll loop checksabortedbefore subscribing, races each poll against the signal, and cancels the in-flight request.tests/unit/token-engine/proof-deadline.test.tsis the guard that it keeps doing so — do not delete it on a future bump.
Quick Start (Using SDK as Dependency)
Installation
Browser:
npm install @unicitylabs/sphere-sdkNode.js:
npm install @unicitylabs/sphere-sdk wsComplete L3 Wallet Integration Example
@unicitylabs/sphere-sdk/impl/browser ships no type declarations (tsup.shared.js builds that
entry with dts: false, and package.json has no types condition for it). Under strict
TypeScript a consumer's import of it fails with TS7016 unless they add a declaration shim, for
example the one-line declare module '@unicitylabs/sphere-sdk/impl/browser'; (which types
everything from that entry as any). ./impl/nodejs and ./impl/shared/wallet-api are typed.
import { Sphere, TokenRegistry, getCoinIdBySymbol } from '@unicitylabs/sphere-sdk';
import { createBrowserProviders } from '@unicitylabs/sphere-sdk/impl/browser'; // untyped entry: see above
import { createWalletApiProviders } from '@unicitylabs/sphere-sdk/impl/shared/wallet-api';
// For Node.js: import { createNodeProviders, createWalletApiProviders } from '@unicitylabs/sphere-sdk/impl/nodejs';
// One network literal, used in all three places below. 'testnet' reaches the same
// endpoints but is a DIFFERENT string: Sphere.init throws INVALID_CONFIG when its network
// and walletApi.network differ ('testnet' vs 'testnet2' included). Sphere.init does not
// compare the base-provider literal, but that literal picks the gateway, relays and trust
// base and names the network-scoped storage keys, so keep all three the same.
const NETWORK = 'testnet2';
// 1. Create base providers. `network` is REQUIRED (throws INVALID_CONFIG otherwise).
// There is NO bundled gateway API key — inject it via oracle.apiKey.
// The testnet2 key is NOT a secret (see .env.example); a mainnet key IS.
const base = createBrowserProviders({
network: NETWORK,
oracle: { apiKey: 'sk_...' },
});
// Node.js: createNodeProviders({ network: NETWORK, oracle: { apiKey: 'sk_...' },
// dataDir: './sphere-data' }) // dataDir is optional; this is its default
// 2. Attach the wallet-api transport config — REQUIRED for money. Sphere.init
// throws INVALID_CONFIG without `walletApi`; tokens are server-custody
// (the wallet-api backend holds inventory; keys stay local). A wallet that
// never touches money passes `walletApi: 'none'` instead (#793) — see below.
const providers = createWalletApiProviders(base, {
baseUrl: 'https://wallet-api.unicity.network', // the testnet2 wallet-api
network: NETWORK,
deviceId: myDeviceId, // stable on this device across launches, different on every device
});
// 3. Init wallet (creates new OR loads existing — single entry point).
// `network` is required here too and is compared to `walletApi.network` as a
// STRING — 'testnet' vs 'testnet2' is a mismatch (INVALID_CONFIG), alias or not.
const { sphere, created, generatedMnemonic } = await Sphere.init({
...providers,
network: NETWORK, // must equal walletApi.network (checked); keep the base providers' the same
autoGenerate: true, // Generate mnemonic if no wallet exists
nametag: 'alice', // Optional: register @alice (only on create)
password: 'secret', // Optional: encrypt mnemonic (plaintext if omitted)
});
// NOTE: `accounting: true` / `swap: true` THROW INVALID_CONFIG — invoicing and
// swaps no longer exist in the SDK (P11 flip). The `paymentsV2:` flag is GONE
// (0.15.0): the vertical is the only path, so there was nothing left to switch.
if (created && generatedMnemonic) {
// Returned only by the call that created the wallet; if that call then threw, the next
// init returns created:false. Gate the backup prompt on your own 'backup confirmed' flag
// and show sphere.getMnemonic() until it is set.
console.log('SAVE THIS:', generatedMnemonic);
}
// 4. Identity is ready
const identity = sphere.identity!;
console.log('L3 address:', identity.directAddress); // DIRECT://... (primary)
console.log('Unicity ID:', identity.nametag); // alice
// 5. Balances and tokens (server-read-through; Asset keeps its legacy shape —
// unconfirmed* fields are pinned '0'/0 by the v2 presentation)
// coinId is the 64-hex coin id everywhere on the money path. Look it up in the
// registry once it has loaded (Sphere.init starts the load but does not await it);
// undefined = the symbol is not in this network's registry.
await TokenRegistry.waitForReady();
const coinIdHex = getCoinIdBySymbol('UCT');
if (!coinIdHex) throw new Error("UCT is not in this network's token registry");
const assets = await sphere.payments.assets(); // Asset[] grouped by coin
const uct = await sphere.payments.assets(coinIdHex); // filter by coin
const tokens = sphere.payments.tokens(); // individual Token[] (sync view)
const nfts = sphere.payments.coinless(); // CoinlessToken[] — DISJOINT from tokens()
const payload = await sphere.payments.tokenData(id); // an NFT's genesis bytes, or null
const view = await sphere.payments.nft(id); // NftView | null: { content, creator, signature } (#785)
const views = await sphere.payments.nfts(nfts.map((t) => t.tokenId)); // Map<tokenId, NftView>; one batched blob read
const filtered = sphere.payments.tokens({ coinId: '...' });
// 6. Send tokens (L3). Recipient must have a PUBLISHED chain pubkey
// (@nametag / DIRECT:// resolve via Nostr binding); fails loudly otherwise.
const result = await sphere.payments.send({
recipient: '@bob', // @nametag, DIRECT://..., or chain pubkey (02...)
amount: '1000000', // in smallest unit (string)
coinId: coinIdHex, // coin ID — 64-hex ONLY on the money path (see the note below)
memo: 'Payment for coffee', // optional (recipient-encrypted envelope)
});
// result: TransferResult { id, status, tokens, tokenTransfers, error?,
// deliveryPending?, deliveryState? }
// A RESOLVED send() means sent: status 'delivered' (landed in the recipient's mailbox), or
// 'confirmed' with deliveryPending: true / deliveryState 'pending-delivery' (certified; the
// mailbox deposit is retried automatically — NOT a failure). send() never resolves
// 'completed' or 'failed' (those exist only in the TransferStatus union): failures THROW.
// Six codes mean the money may already have left — isPossiblyCommittedSendOutcome(err) is true
// for exactly SEND_SYNC_PENDING, CERTIFICATION_UNCONFIRMED, CHECKPOINT_PERSIST_FAILED,
// SPLIT_CHECKPOINT_LOST, CHECKPOINT_TRUSTBASE_MISMATCH and SEND_PARTIALLY_COMPLETED. Never
// send() again for those: a retry button calls payments.resumeNow(), and
// payments.pendingTransfers() lists what is still converging.
// NOTE: coinId is the 64-hex coin id; get it from a symbol with getCoinIdBySymbol() (step 5).
// The registry is presentation only.
// 7. Receive: the facade drains the wallet-api mailbox continuously while
// started; receive() is an explicit one-shot drain (returns what landed).
const { transfers } = await sphere.payments.receive();
sphere.on('transfer:incoming', (transfer) => {
console.log(`From: ${transfer.senderNametag}, Tokens: ${transfer.tokens.length}`);
});
// 8. Self-mint fungible tokens (testnet top-up; journal-first, crash-safe)
// coinId must be even-length lowercase hex (the canonical SDK AssetId form)
const mint = await sphere.payments.mint(coinIdHex, 1000000n);
// MintResult: { success, tokenId?, error? } — one flat interface, so `success` does not narrow
// tokenId. Both mints journal BEFORE the chain op, and the convergence pass (start, heartbeat)
// replays a journaled entry under its own mintId. Never re-call for a journaled failure: a new
// call is a new mintId, so a new token. A failure that carries a tokenId is journaled; so is a
// mint() failure WITHOUT one when the engine call itself threw. Only mint()'s up-front
// coinId/amount refusal and mintNft()'s refused content (build error or the 1 MiB payload cap)
// journal nothing.
// An NFT (#785; format docs/NFT-METADATA.md): minted to this wallet, signed as creator unless
// sign: false. Same MintResult.
const nftMint = await sphere.payments.mintNft({
content: { kind: 'media', media_type: 'image/png', bytes: pngBytes },
});
// 9. Transaction history — server read-through, PAGED
const page = await sphere.payments.history({ limit: 50 });
// HistoryPage: { entries: HistoryEntry[], more, cursor }
const older = await sphere.payments.history({ before: page.cursor!, limit: 50 });
// 10. Peer resolution (Unicity ID → addresses)
const peer = await sphere.resolve('@bob');
// PeerInfo | null: { nametag?, transportPubkey, chainPubkey, directAddress, timestamp }
// 11. Multi-address
await sphere.switchToAddress(1);
await sphere.registerNametag('alice2');
const addresses = sphere.getActiveAddresses(); // TrackedAddress[]
// 12. Payment requests (wallet-api rail; encrypted memo envelope)
// create() never throws: it resolves { success, requestId?, error? } — check success.
const req = await sphere.payments.requests.create('@bob', {
coinId: coinIdHex, amount: '1000000', memo: 'Pay for order #1234', // 64-hex coin id
});
if (!req.success) console.error(req.error);
sphere.on('payment_request:incoming', (view) => {
// PaymentRequestView: { id, requestId, senderPubkey, senderNametag?, amount,
// coinId, symbol?, message?, timestamp, status } (symbol is not set here)
// Never pay from the handler itself: show the request and let the USER decide, then call
// sphere.payments.requests.pay(view.id) OR .decline(view.id). pay() rethrows send()'s errors.
});
sphere.on('payment_request:updated', ({ id, status }) => {
// Requests you RECEIVED only. status: 'pending' | 'settling' | 'paid' | 'rejected' | 'expired'
// A requester learns its own request was paid from transfer:incoming or history().
});
const open = sphere.payments.requests.list(); // PaymentRequestView[]
sphere.payments.requests.dismissProcessed(); // drop terminal entries from list()
// 13. Cleanup
await sphere.destroy();
// Node scripts that should exit: also call TokenRegistry.destroy(). Sphere.init configures the
// process-global registry too, and its hourly refresh timer keeps the event loop alive;
// sphere.destroy() disposes only the registry that Sphere owns.Connect Protocol (dApp ↔ Wallet Integration)
Typed RPC layer for dApp ↔ wallet communication. Full guide: docs/CONNECT.md
| Role | Class | Where it runs |
| dApp (client) | ConnectClient | any web page / app |
| Wallet (host) | ConnectHost | Sphere app (hosted wallet) |
Transports: PostMessageTransport (iframe/popup — the live browser path), WebSocketTransport (Node.js), and ExtensionTransport — legacy: the browser extension is discontinued and no supported wallet answers it.
Queries (14): sphere_getIdentity, sphere_getBalance, sphere_getAssets, sphere_getFiatBalance, sphere_getTokens, sphere_getHistory, sphere_resolve, sphere_subscribe, sphere_unsubscribe, sphere_disconnect, sphere_getConversations, sphere_getMessages, sphere_getDMUnreadCount, sphere_markAsRead. (The two invoice queries were removed with the P11 flip — they were experimental and never enabled in any wallet host.)
Intents (8): send, dm, payment_request, receive, sign_message, mint, send_nft, mint_nft. (The 9 invoice intents were removed with the P11 flip.)
Permission scopes (15): identity:read, balance:read, tokens:read, history:read, events:subscribe, resolve:peer, transfer:request, dm:request, dm:read, dm:manage, payment:request, sign:request, mint:request, nft:transfer, nft:mint.
mint_nftneeds its ownnft:mintscope (Connect 2.3) — neithermint:requestnornft:transfergrants it, because minting an NFT puts the user's creator signature on content the DAPP chose, which a coin top-up or an NFT-move approval never agreed to. It always asks the user:ConnectHost.setIntentAutoApprovethrows for it and the host routes everymint_nfttoonIntent. Params cross the wire vianftContentToWire/nftContentFromWire(connect/nft-wire.ts, inline bytes as canonical base64; shape only — value rules stay inpayments.mintNft).
Wire-compat adapter (connect/host/payments-compat.ts): dApps written against the pre-flip event/query contract change NOTHING. On a v2 host, sphere_getBalance/getAssets/getFiatBalance/getTokens/getHistory are served from the facade (assets()/tokens()/history() — old result shapes held), and the old subscribable event names are re-emitted from the 8 v2 events: transfer:confirmed/transfer:delivery_pending/transfer:failed ← transfer:updated; payment_request:paid|rejected|expired ← payment_request:updated; split:checkpoint-stuck/delivery:undeliverable/delivery:deferred ← transfer:attention; realtime:status/storage:degraded ← connection:status; sync:completed/sync:remote-update ← inventory:updated. (send:partial-remainder is NOT re-emitted — folded by design, no consumer existed.)
Host-side shape (0.15.0): the WIRE is unchanged — dApps see exactly what they saw before — but SphereInstance (connect/host/SphereInstance.ts) dropped its legacy payments: { getBalance/getAssets/getFiatBalance/getTokens/getHistory } object and its optional paymentsV2; it now declares readonly payments: PaymentsV2, read lazily per query branch because the real getter throws while no vertical runs and sphere_getIdentity must still answer. The ConnectHost's legacy-host fallbacks are gone (dead since the P11 flip), so sphere_getBalance and sphere_getAssets are now literally the same call and sphere_getFiatBalance is summed from assets().
Silent mode: new ConnectClient({ ..., silent: true }) — fast-check approved list without UI popup.
Wallet-pushed events (4): WALLET_EVENTS.LOCKED (wallet:locked), WALLET_EVENTS.UNLOCKED (wallet:unlocked), WALLET_EVENTS.DISCONNECTED (wallet:disconnected), WALLET_EVENTS.IDENTITY_CHANGED (identity:changed) — pushed by the host without subscription. sphere_subscribe for one of them answers success ({ subscribed: true, event }) without attaching to Sphere.on() (which would accept the name and silently never emit): pre-2.1 dApps call it fire-and-forget, and throwing there broke them (ConnectHost.handleSubscribe). Do not "fix" the host to refuse.
Graceful wallet lock (Connect 2.1): a lock is a state, not a teardown — the session survives. Host verbs: setLocked() (session preserved, push wallet:locked), updateSphere(next) (unlock, push wallet:unlocked), revokeSession() (teardown, push wallet:disconnected), setUnavailable() (Sphere gone for a non-lock reason). notifyWalletLocked() was removed, not aliased — its old meaning was the opposite of its new one. While locked a host that HOLDS a session answers four of fourteen RPC_METHODS — sphere_getIdentity (from an immutable snapshot), sphere_subscribe, sphere_unsubscribe, sphere_disconnect — and refuses the other ten plus every intent with WALLET_LOCKED (4009). That ten includes sphere_resolve and all four DM reads: messaging does NOT keep working while locked. Nothing is cached. A host that COLD-STARTS locked has no session and an empty snapshot, so the handshake itself is refused with an errorless empty response — the dApp sees no code at all, not 4009, and must treat it as "not ready yet" and wait for HOST_READY. onLockedRequest is notify-only and must never raise a credential surface — a passive badge only. See docs/CONNECT.md.
What's Included by Default
| Component | Browser | Node.js |
| Storage (keys/identity/journals) | IndexedDB (IndexedDBStorageProvider) | File-based JSON (FileStorageProvider) |
| Token custody | wallet-api backend (server inventory; walletApi config required) | Same |
| Transport (Nostr: DMs, nametags, groupchat) | Native WebSocket | ws package (install separately) |
| Oracle (network config) | Embedded trust base per network; API key injected via oracle.apiKey | Same (+ optional trustBasePath file) |
| Price (CoinGecko) | Optional (price config) | Optional (price config) |
| Token Registry | Remote fetch + persistent cache | Remote fetch + file cache |
Key API Methods Reference
| Method | Returns | Description |
Sphere.init(options) | Promise<{ sphere, created, generatedMnemonic? }> | Create or load wallet (requires network and a walletApi config, or 'none') |
sphere.hasPayments | boolean | Whether this Sphere composes money at all (#793) — fixed for its life |
Sphere.exists(storage) | Promise<boolean> | Check if wallet exists (false on any storage error; init/create/import use the strict check and reject with that error instead) |
Sphere.clear({ storage }) | Promise<void> | Delete all wallet data (the whole KV, both pv2g2:* and superseded pv2:*, + orphaned pre-flip token DBs; for IndexedDB the whole dbName, every prefix) |
Sphere.import(options) | Promise<Sphere> | Import from mnemonic/masterKey; every input is checked before storage is touched. Over a storage that already holds a wallet (or one a live Sphere uses) it rejects ALREADY_INITIALIZED unless overwrite: true, which clears that wallet first (#801) |
Sphere.importFromJSON(options) | Promise<{ success, sphere?, mnemonic?, error? }> | Import an exportToJSON() backup; same overwrite rule as import, but the refusal comes back as { success: false, error } |
Sphere.importFromLegacyFile(options) | Promise<{ success, sphere?, mnemonic?, needsPassword?, error? }> | Import a .txt / flat-JSON / bare-mnemonic backup; same overwrite rule as import (these paths reject; only a delegated exportToJSON() file returns { success: false, error }) |
listWallets(dataDir) (./impl/nodejs) | Promise<NodeWalletFile[]> | Wallet files side by side in one Node dataDir, one per walletFileName: { fileName, filePath, passwordProtected }, sorted by fileName; needs no password (#801) |
sphere.payments.assets(coinId?) | Promise<Asset[]> | Assets grouped by coin (server read-through) |
sphere.payments.tokens(filter?) | Token[] | Individual COIN tokens (sync inventory view) |
sphere.payments.coinless() | CoinlessToken[] | Coinless (NFT) holdings — disjoint from tokens() |
sphere.payments.tokenData(tokenId) | Promise<Uint8Array | null> | A token's genesis payload (fetches the blob) |
sphere.payments.nft(tokenId) | Promise<NftView | null> | A held token read as an NFT (#785); null = not a recognised NFT |
sphere.payments.nfts(tokenIds) | Promise<ReadonlyMap<string, NftView>> | Batch NFT read for list views (one blob fetch, cached); unreadable ids absent |
sphere.payments.send(request) | Promise<TransferResult> | Send L3 coin tokens (wallet-api vertical) |
sphere.payments.sendWholeToken(request) | Promise<TransferResult> | Move ONE named token whole — coinless or valued, never split |
sphere.payments.sendCoinless(request) | Promise<TransferResult> | NFT-scoped twin: refuses a valued source (Connect send_nft) |
sphere.payments.mint(coinIdHex, amount) | Promise<MintResult> | Self-mint via engine (journal-first, no faucet) |
sphere.payments.mintNft({ content, sign? }) | Promise<MintResult> | Mint an NFT to this wallet, signed as creator by default (journal-first) |
sphere.payments.receive() | Promise<{ transfers }> | Explicit one-shot mailbox drain |
sphere.payments.history(page?) | Promise<HistoryPage> | Paged history ({ before?, limit? }) |
sphere.payments.pendingTransfers() | Promise<PendingTransfer[]> | What is still converging (open intents, owed deliveries, partial-send shortfalls) — for the UI |
sphere.payments.resumeNow() | Promise<void> | Run a convergence pass now — the ONLY retry verb (never re-send()) |
sphere.payments.connectionStatus() | 'connected' | 'degraded' | 'offline' | Current wallet-api session status (connection:status is the change event) |
sphere.payments.prewarmSend(request) | Promise<void> | Read a pending send's source blobs while the confirm screen is up (reserves nothing) |
sphere.payments.discardPrewarm() | void | Drop the prewarmed reads |
sphere.payments.requests.create(to, terms) | Promise<{ success, requestId?, error? }> | Send a payment request (never throws; check success) |
sphere.payments.requests.list() | PaymentRequestView[] | Current views of requests you RECEIVED |
sphere.payments.requests.pay(id) | Promise<TransferResult> | Pay an incoming request (rethrows send() errors; a possibly-committed failure links the request and leaves it settling, except when the link write fails: then pay() rejects with the storage error, the link lives only in memory, and the request can be payable again after a restart) |
sphere.payments.requests.decline(id) | Promise<void> | Decline (server 403/409 propagate) |
sphere.payments.requests.dismissProcessed() | void | Drop terminal entries from list() |
sphere.resolve(identifier) | Promise<PeerInfo | null> | Resolve @nametag/address/pubkey |
sphere.communications.resolvePeerNametag(pubkey) | Promise<string | undefined> | Resolve peer Unicity ID via transport |
sphere.registerNametag(name) | Promise<void> | Register Unicity ID (Nostr binding; nothing is minted) |
sphere.signMessage(message) | string | Sign with wallet key (secp256k1 ECDSA) |
sphere.switchToAddress(index, options?) | Promise<void> | Switch HD address |
sphere.getActiveAddresses() | TrackedAddress[] | Non-hidden tracked addresses |
sphere.setOracleApiKey(key) | Promise<void> | Rebuild the engine with a new gateway key |
sphere.exportToTxt(options?) | string | Text backup (optionally password-encrypted) |
sphere.on(event, handler) | () => void (unsubscribe) | Subscribe to events |
Notes:
sphere.paymentsV2is GONE (0.15.0) —sphere.paymentsis the only accessor. The behavioural difference consumers must handle: the alias returnednullwhile no vertical ran,sphere.paymentsTHROWSNOT_INITIALIZED(init in flight, mid address-switch, destroyed). Read it lazily at the call site, never once at construction. Under the #793 messaging-only composition it throwsPAYMENTS_NOT_COMPOSEDinstead — permanent, not transient, andsphere.hasPaymentsis the try/catch-free way to ask.sphere.groupChat,sphere.marketare nullable getters —nullunless enabled in init options.sphere.accounting/sphere.swapDO NOT EXIST (P11 flip); passingaccounting:/swap:init options throwsINVALID_CONFIG.
Key Events
The payments vertical emits exactly 8 events; identity/comms/groupchat events ride the same bus.
| Event | Payload | When |
transfer:incoming | IncomingTransfer ({ senderPubkey, senderNametag?, tokens, coinless?, memo?, receivedAt }) | Tokens landed from the wallet-api mailbox (verified before entering balance). A coinless arrival is named in coinless, NOT in tokens — read both. An arrival whose mint reason no plugin here can verify yet is not in this event: it is parked (unacked on the server, recorded in the scoped KV, the cursor moves past it), rechecked on a doubling schedule, announced once with transfer:attention code receive:unverifiable, and listed by payments.parkedArrivals() |
transfer:updated | TransferResult | Outgoing transfer changed status (read status / deliveryPending) |
transfer:attention | { transferId, code, detail? } | A transfer needs operator attention (stuck checkpoint, undeliverable, deferred) |
inventory:updated | {} | Inventory changed (send/receive/mint/resync) |
history:updated | HistoryEntry (the just-recorded entry) | History changed |
payment_request:incoming | PaymentRequestView | Received payment request |
payment_request:updated | { id, status } | Request moved (settling/paid/rejected/expired) |
connection:status | { status: 'connected' | 'degraded' | 'offline' } | Wallet-api session/wake-socket health |
identity:changed | { directAddress?, chainPubkey, nametag?, addressIndex } | Address switch |
nametag:registered | { nametag, addressIndex } | Unicity ID registered |
nametag:recovered | { nametag } | Unicity ID recovered from Nostr. The init-time recovery (create/load/import) emits BEFORE the call returns, so a listener added afterwards never sees it — read sphere.identity?.nametag; later recoveries (after switchToAddress) do reach listeners |
address:activated | { address: TrackedAddress } | New address tracked |
message:dm / message:broadcast / groupchat:* | see types/index.ts | Communications |
The pre-flip event names (transfer:confirmed, sync:*, invoice:*, swap:*, …) are GONE from
the public event map — dApps on the Connect wire still receive the old names via the ConnectHost
compat adapter, but direct sphere.on() consumers must use the v2 names.
See QUICKSTART-BROWSER.md and QUICKSTART-NODEJS.md for detailed guides.
Project Overview
Sphere SDK (@unicitylabs/sphere-sdk) is a modular TypeScript SDK for Unicity wallet operations supporting:
- L3 (Unicity state transition network) - Token transfers via the v3 state-transition SDK (pinned
3.0.1), consumed exclusively through thetoken-engine/port. Wallets are L3-only. - Money custody: wallet-api backend (server inventory + mailbox delivery). Nostr carries DMs, group chat and nametag bindings ONLY — no asset or payment-request traffic.
Version: see package.json (the 0.17.x line). The state-transition-sdk 3.x bump shipped as 0.15.0, a breaking release (no cross-major wire interop in either direction). package.json on a branch still reads the previous version: publish.yml sets the field at publish time from its version input. Releases ship from main under the npm latest tag; -dev.# builds are published from a branch and land under dev. Per-release notes: CHANGELOG (versioned sections start at 0.14.11; older entries are pooled under [0.14.10] and earlier)
License: MIT
Target: Node.js >= 22.0.0, Browser (ESM/CJS)
CLI: moved out to its own repository, unicity-sphere/sphere-cli, which is not published to npm yet (npm install -g @unicity-sphere/cli fails with a 404; npm run cli prints this pointer and exits with an error)
Directory Structure
sphere-sdk/
├── core/ # Core wallet and crypto utilities
│ ├── Sphere.ts # Main wallet class - entry point
│ ├── payments-v2-wiring.ts # Composition: walletApi config → facade (resolvePaymentsV2Composition)
│ ├── wallet-api-protocol.ts # Cross-repo contract strings (auth challenge, intent signing)
│ ├── address.ts # DIRECT:// address parsing/validation
│ ├── crypto.ts # BIP39/BIP32, secp256k1, hashing, message signing
│ ├── encryption.ts # Wallet/seed encryption, CryptoJS AES-256-CBC: encryptSimple (OpenSSL
│ │ # passphrase mode, MD5 EVP_BytesToKey, 1 iteration) stores the seed
│ │ # when a password is set (plaintext without one) and backs
│ │ # exportToJSON; encrypt()/decrypt() use PBKDF2-SHA256 (100k)
│ ├── field-encryption.ts / delivery-envelope.ts # pv2 field crypto + S6 memo envelope (XChaCha20-Poly1305)
│ ├── errors.ts # SphereError + SphereErrorCode
│ ├── logger.ts # Centralized logger singleton
│ ├── currency.ts # Amount formatting/conversion
│ ├── discover.ts # HD address scanning/discovery
│ ├── network-health.ts # checkNetworkHealth()
│ └── utils.ts # Base58, patterns, UUID, helpers
│
├── token-engine/ # ⭐ Anti-corruption layer over the v3 state-transition SDK
│ ├── engine.ts # ITokenEngine port (frozen contract) + EngineConfig
│ ├── types.ts # Sphere-domain types: SphereToken, TokenBlob, Mint/Transfer/SplitParams
│ ├── factory.ts # createSphereTokenEngine(config)
│ ├── SphereTokenEngine.ts # The real adapter (engine implementation)
│ ├── SpherePaymentData.ts # Value envelope codec (coins inside SDK tokens, CBOR tag 39050)
│ ├── proof-wait.ts # Bounded proof wait + transient policy (TransientSubmitAnswer)
│ ├── certification-outcome.ts # conflict vs possibly-committed classification
│ ├── split-checkpoint.ts # Durable burn checkpoint (CHECKPOINT_VERSION 2)
│ ├── blob-keys.ts # deriveDeliveryKeys() over raw Token.toCBOR() bytes
│ ├── identity.ts # deriveDirectAddress() — vendored v1-identical DIRECT:// derivation
│ ├── network.ts # SphereNetwork ↔ SDK NetworkId mapping
│ └── sdk.ts # ⚠️ THE ONLY file allowed to import @unicitylabs/state-transition-sdk
│
├── types/ # TypeScript type definitions
│ └── index.ts # Main types (Identity, Token, Asset, Transfer, events, etc.)
│
├── modules/ # Feature modules
│ ├── payments-v2/ # ⭐ The payments vertical (docs/PAYMENTS-V2-DESIGN.md)
│ │ ├── api.ts # PaymentsV2 facade surface + the 8 events (§4)
│ │ ├── PaymentsFacade.ts # Facade: lifecycle, send/mint/receive orchestration
│ │ ├── ports.ts # StoragePort / DeliveryPort (contract-test-enforced)
│ │ ├── stores.ts # pv2g2:{network}:{pubkey}: scoped KV — §6 durable state
│ │ ├── restore.ts # §5.1 epoch-change reseed (see the KV generation note below)
│ │ ├── machine/ # TransferMachine + resume (E.2/E.4) + intent journal
│ │ ├── select/ # CoinSelector, Reservations ledger, op queue
│ │ ├── receive/ # Mailbox drain, claim, verified-before-balance
│ │ ├── requests/ # Payment requests (streams + settling journal)
│ │ ├── history/ # Server read-through paged history
│ │ ├── inventory/ # InventoryView + Asset presentation (legacy shape held)
│ │ └── compose.ts / async.ts / index.ts
│ ├── groupchat/ # NIP-29 group chat (relay-based)
│ ├── market/ # Market intents
│ └── communications/ # DMs and broadcasts
│
├── impl/ # Platform-specific implementations
│ ├── browser/ # IndexedDB storage, browser oracle/transport, connect
│ ├── nodejs/ # FileStorage (+ listWallets), Node oracle/transport, connect
│ ├── shared/ # Config resolvers, network checks, trust-base loaders
│ │ └── wallet-api/ # createWalletApiProviders → { walletApi: WalletApiTransportConfig }
│ └── wallet-api-v2/ # Wallet-api wire: session (auth+wake WS), client, http,
│ # storage/mailbox/checkpoints port implementations
│
├── transport/ # P2P messaging abstraction (NostrTransportProvider)
├── storage/ # StorageProvider port (keys/identity/journals) + HistoryRecord
├── oracle/ # Network-config provider for the token engine
├── price/ # Token market prices (CoinGeckoPriceProvider)
├── registry/ # Token metadata registry (remote fetch + cache): the process-global
│ # instance + one registry owned by each Sphere (#767)
├── serialization/ # Text wallet backup format (.txt) parsing/writing
├── connect/ # Sphere Connect protocol (client/, host/ incl. payments-compat)
├── assets/ # Embedded trust bases per network (trustbase.ts)
│
├── tests/ # Vitest: unit/ (incl. payments-v2 + contracts), integration/,
│ # e2e/ (live staging), relay/, mutation/ (probes.json)
├── docs/ # API, INTEGRATION, CONNECT, QUICKSTART-*, NFT-METADATA, VERIFICATION-WORKERS,
│ # MIGRATION-PAYMENTS-V2, MIGRATION-TOKEN-REGISTRY, PAYMENTS-V2-DESIGN (design record), ...
├── index.ts # Main SDK entry point
├── constants.ts # Global constants, NETWORKS, storage keys
└── package.jsonSubpath exports: . (root), ./core, ./token-engine, ./payments-v2 (the facade module),
./impl/wallet-api-v2, ./impl/shared/wallet-api, ./impl/browser, ./impl/nodejs,
./connect, ./connect/browser, ./connect/nodejs. Every entry ships type declarations
EXCEPT ./impl/browser (dts: false in tsup.shared.js; its exports map has no types), so a
strict-TypeScript consumer of it needs a declare module shim. The ./wallet-api subpath (old S1
client) is GONE.
Architecture
Payments vertical (the only money path)
docs/PAYMENTS-V2-DESIGN.md is the design record (the why; the code and docs/API.md are
normative for the current API, and its §5 layout and progress rows are historical). The short
version:
- Server is the record. Token inventory, blobs, transfer intents, mailbox, history and
payment requests live in the wallet-api backend. The client holds keys, a per-address scoped
KV (
pv2g2:{network}:{chainPubkey}:*in the plainStorageProvider) with the refresh token, cursors and journals — nothing else. There is no client token store to sync (sphere.sync()is gone). - Composition:
Sphere.init({ walletApi })→resolvePaymentsV2Composition→composePaymentsV2builds onePaymentsFacadeper active address over the wallet-api-v2 ports (WalletApiStoragePort,WalletApiDeliveryPort,WalletApiSplitCheckpointStore) and aWalletApiSession(challenge sign-in → JWT + refresh token, wake WebSocket, single-flight re-auth), and firessweepSupersededState()once (thepv2:generation — see below). ThepaymentsV2Transportseam in the config injects a whole custom bundle (tests, custom hosts). Init is FAIL-CLOSED: nowalletApi→INVALID_CONFIG, before any storage write. The ONE explicit escape iswalletApi: 'none'(#793,NO_PAYMENTS): a wallet that is only ever a Nostr client composes nothing — no session, device, wake socket, drain, token engine orpv2g2:key, at boot or on an address switch — andpaymentsthrowsPAYMENTS_NOT_COMPOSED.'none'shares the field with the config so both cannot be said; OMITTING the field still refuses, because "I forgot" must not read as "I meant it", and a near-miss ('None') is refused by name.networkis still required with'none': it configures the token registry, and init throwsINVALID_CONFIGwithout it (configureTokenRegistry). - Send:
TransferMachine— durable intent on the server first (putIntent), then engine ops (transfer/split), per-op progress checkpoints (field-encrypted, signed), mailbox deposit, signed complete (completeSignMessage— the server's seedGate verifies it). Resume is THE SAME machine replaying the SAME transferId — runs insidefacade.start()(off critical path), never re-issues a spend. A possibly-committed outcome keeps the intent OPEN (never a fresh send); a clean conflict with a demoted source triggers a bounded re-plan — up toMAX_RESELECT(8) re-selections, none for a whole-token send (#625 marks the sourcesuspectedSpent, excluded from selection, recoverable by resync). - Receive: continuous mailbox drain while started + explicit
receive(). Every incoming token is engine-verified and ownership-checked BEFORE entering the balance; dedup by (tokenId, stateHash) — genesis id alone would refuse a token legitimately re-acquired at a later state; store-before-ack (a crash between store and claim re-claims, never loses). - Delivery journal (#621): a certified-but-undelivered blob is journaled in the scoped KV
and replayed with a poison budget (#517) —
deliveryPendingon the TransferResult,landedvspending-deliveryindeliveryState,transfer:attentionwhen undeliverable/deferred. - Mint: journal-first (
mintjournal in scoped KV), idempotent same-seed re-call converges a replay — crash-safe without a faucet. - Error contract (load-bearing, unchanged):
CERTIFICATION_UNCONFIRMED(ProofUnconfirmedErrorwith.cause),SEND_SYNC_PENDING, the checkpoint trio,SEND_PARTIALLY_COMPLETED,isPossiblyCommittedSendOutcome()— callers keep PENDING_COMMIT handling exactly as before; never re-issue a send after a possibly-committed reject. - Lifecycle:
facade.start()/stop()are Sphere-internal (init/destroy/address switch). The public convergence surface ispayments.pendingTransfers()/payments.resumeNow()(a retry button callsresumeNow(), NEVERsend(): a re-issued send double-pays), pluspayments.connectionStatus()for the session. An address switch stops the old facade and starts a fresh one (a stoppedWalletApiSessiondoes not restart).
Token Engine (v3) — the only chain-op path
The canonical package name resolves to the v3 SDK, pinned 3.0.1 (exact). The whole 3.x wire
break is absorbed here: ITokenEngine did not change shape for the bump, and the only
sphere-domain type that moved is TokenBlob (two never-read fields dropped — below).
- The SDK is imported in exactly ONE file:
token-engine/sdk.ts. An ESLintno-restricted-importsrule blocks any other import of@unicitylabs/state-transition-sdk— everything else codes against theITokenEngineport and sphere-domain types fromtoken-engine/. ITokenEngineoperations:getIdentity,deriveIdentityAddress,tokenId,readValue,balanceOf,readMemo,readTokenData,mint,mintDataToken,transfer,split,verify,isSpent,isOwnedBy,encodeToken,decodeToken,deliveryKeys,buildNftMint,readNft(#785), and the optionaldispose(worker-pool teardown).- The 3.x SDK surface (visible only inside
token-engine/): the threecreate/splitbuilders take an options object where 2.x took trailing positionals, andInclusionProofResponse.inclusionProofisInclusionProof | nullwhere null IS "not certified yet" —isSpentand the split pre-flight read the response, never a field inside the proof. Exact signatures are in the types; the CHANGELOG 0.15.0 entry lists the status-enum moves. - No request deadline is set on anything (see the program bullet above for WHY it is
money-critical):
expiresAtis omitted on every mint, transfer, split burn and split mint leg. - Submit-status classification did NOT change.
CLEAN_REJECT_STATUSES— the proven "nothing certified" set that permits an abort — still excludes both 3.x additions.SERVICE_NOT_READYis instead RETRIED at the submit call site (TransientSubmitAnswerintoken-engine/proof-wait.ts, sharing the one certification deadline): it is a 503 in a 200 body, and left alone a booting gateway surfacedCERTIFICATION_UNCONFIRMED.REQUEST_EXPIREDmust NEVER be retried.TRANSACTION_HASH_MISMATCHremains the only conflict signal. TokenBlobis{ tokenId, token }andtokenis the SDK's ownToken.toCBOR()bytes — the sphere-private CBOR envelope (token-engine/token-blob.ts, tag 39051,v/networkfields) was DELETED: nothing ever readvornetwork, and the wallet-api wire form was the inner bytes anyway.deriveDeliveryKeysdecodes those bytes directly.- Split checkpoints are generation 2 (
token-engine/split-checkpoint.ts):CHECKPOINT_VERSION1 → 2,CHECKPOINT_SDK_VERSION→@unicitylabs/state-transition-sdk@3.0.1. Every stored 2.x checkpoint is unreadable; the version check now names that cause instead of letting the byte-comparison blame "derivation drift" and send the reader hunting a realization bug. Spherebuilds the engine from the oracle's config surface (getTrustBaseJson()/getAggregatorUrl()/getApiKey()) viacreateSphereTokenEngine(EngineConfig). The trust base JSON is the single source of truth for the network id (RootTrustBase.networkId, e.g. testnet2 = 4).SphereToken.sdkTokenis an OPAQUE handle — callers store it and hand it back to the engine, never call methods on it.- Verification is sequential by default; parallel is opt-in (since 2.0.2). Pass
verification: { createWorker, poolSize? }toSphere.init(orEngineConfig) andengine.verifyfans per-transfer work out to a worker pool. The entry script is the CONSUMER's (only their bundler can emit a worker) and its predicate verifier must match the engine's or the verdict silently diverges. Workers spawn lazily. Each address builds its own engine (so its own pool) on first use;sphere.destroy()disposes every address's engine andsetOracleApiKey()disposes the one it replaces, but an address switch disposes NOTHING (the previous address keeps its engine until destroy), so up topoolSize× visited addresses workers can be alive.createWorkermust return theVerificationWorkerport type: a DOMWorker/ st-sdkNodeWorkerneeds anas VerificationWorkercast under strict TS (their handler params are narrower). The consumer-facing entry-script contract is UNCHANGED by the 3.x bump (the SDK'sIWorker/WorkerTokenVerifierdeclarations are diff-clean; only the main-thread side moved). Seedocs/VERIFICATION-WORKERS.md. - The engine is mandatory for money movement: when the oracle does not supply a trust base +
gateway URL (or the engine cannot be constructed),
Sphere.init/create/load/importreject withINVALID_CONFIG('payments requires the v2 token engine …') and tear the half-built Sphere down, sosend()/mint()are never reachable;switchToAddress()to an address whose engine cannot be built rejects the same way. The missing-engineAGGREGATOR_ERROR('paymentsV2: token engine unavailable') is raised only by the facade'sengineRefguard, after init: a money call can reject with it when its address's engine record is empty as the call starts (e.g. after asetOracleApiKey()rebuild that could not construct one). AwalletApi: 'none'wallet builds no engine and starts no payments vertical.
Single Identity Model
A single secp256k1 key pair backs the L3 identity:
mnemonic → master key → BIP32 derivation → identity
↓
┌─────────────────────┴─────────────────────┐
│ chainPubkey: 33-byte compressed pubkey │
│ directAddress: DIRECT://... (L3) │
│ transportPubkey: derived for Nostr │
└─────────────────────────────────────────────┘The DIRECT:// address is derived by token-engine/identity.ts
(deriveDirectAddress) — a vendored, byte-identical reproduction of the v1
derivation. It MUST stay stable: external systems (Quest XP) key user identity
on it.
Key Types
interface Identity {
chainPubkey: string; // 33-byte compressed secp256k1 (for L3)
directAddress?: string; // L3 DIRECT address
ipnsName?: string; // legacy derived id; retained for backup-format stability
nametag?: string; // Unicity ID (@username)
}
interface FullIdentity extends Identity {
privateKey: string; // secp256k1 private key (hex)
}
interface SendRequest { // sphere.payments.send()
recipient: string; // @nametag, DIRECT://..., chain pubkey
amount: string; // Amount in smallest unit
coinId: string; // Coin ID — even-length lowercase hex
memo?: string; // Optional message (recipient-encrypted envelope)
}
interface TransferResult {
readonly id: string;
status: 'pending' | 'submitted' | 'confirmed' | 'delivered' | 'completed' | 'failed';
// ^ the TransferStatus union. A resolved send() is only 'delivered' or 'confirmed'
// (+ deliveryPending); 'failed' appears only on transfer:updated for a clean failure.
readonly tokens: Token[];
readonly tokenTransfers: TokenTransferDetail[]; // { sourceTokenId, method: 'direct'|'split' }
error?: string;
deliveryPending?: boolean; // certified, mailbox deposit still owed
deliveryState?: 'landed' | 'pending-delivery';
}
// token-engine sphere-domain types
interface TokenBlob {
tokenId: string; // genesis-stable 64-hex id (same across all states)
token: Uint8Array; // the SDK's own Token.toCBOR() bytes — no sphere envelope
}
// A holding that names NO coin (wallet-api#140) — an NFT. Deliberately NOT a Token:
// that type requires coinId/symbol/decimals/amount, and sentinels would put untrue
// values in fields consumers sum. Disjoint from tokens(); joins no balance.
interface CoinlessToken {
tokenId: string; // the INSTANCE key
tokenType?: string; // the token's CLASS, lowercase hex — see the caveat below
name?: string; // resolved from the wallet's OWN registry when recognised
iconUrl?: string;
stateHash: string;
transferring: boolean;
suspectedSpent?: boolean;
createdAt: number;
updatedAt: number;
}
interface SphereToken {
sdkToken: Token; // OPAQUE SDK handle — never touch outside token-engine/
blob: TokenBlob; // serializable form
value: SphereValue | null; // decoded { assets: [{ coinId, amount: bigint }] }
// #778: WHY value is null. 'none_*' = genuinely coinless; 'bare_collection' =
// coins in the bridged dialect this SDK does not decode, so zero means "cannot
// read", NOT "has none". A corrupt envelope throws instead of reaching this.
valueEnvelope: 'sphere' | 'bare_collection' | 'none_tag' | 'none_other' | 'none_absent';
tokenType: string; // genesis TokenType hex — the CLASS, never the instance
}Asset keeps its full legacy shape for UI compatibility — the v2 presentation pins
unconfirmedAmount: '0' / unconfirmedTokenCount: 0 (nothing is ever unconfirmed in server
custody) and still populates transferringAmount/transferringTokenCount for in-flight sends.
Provider Pattern
Abstract interfaces for platform independence:
| Provider | Interface | Implementations |
| Storage | StorageProvider | IndexedDBStorageProvider (browser), FileStorageProvider (Node.js) |
| Transport | TransportProvider | NostrTransportProvider |
| Oracle | OracleProvider | UnicityAggregatorProvider |
| Price | PriceProvider | CoinGeckoPriceProvider |
| Money ports | StoragePort / DeliveryPort (modules/payments-v2/ports.ts) | WalletApiStoragePort, WalletApiDeliveryPort (impl/wallet-api-v2/) |
There is NO TokenStorageProvider — token custody is the wallet-api backend. The walletApi
member of the provider bundle is a plain transport CONFIG (WalletApiTransportConfig), not a
provider object.
Oracle is a thin network-config provider. Its surface:
initialize(trustBaseJson?)— loads trust base via the platform loader unless passed explicitlygetTrustBaseJson()/getAggregatorUrl()/getApiKey()— REQUIRED members; the engine is built from exactly these three
Custom OracleProvider implementations MUST provide the three config accessors.
Network Configuration (constants.ts → NETWORKS)
| Network | Aggregator/Gateway | Status |
testnet | https://gateway.testnet2.unicity.network | ⭐ Same endpoints as testnet2 (the current gateway, trust-base networkId 4, testnet2 token registry) — but a DIFFERENT string: Sphere.init compares network with walletApi.network literally, so never mix 'testnet' and 'testnet2'; the testnet2 wallet-api signs in only as 'testnet2' |
testnet2 | https://gateway.testnet2.unicity.network | Same config as testnet; wallet-api https://wallet-api.unicity.network |
mainnet | https://gateway.mainnet.unicity.network | Live v3 gateway; embedded trust base, networkId 1 (pinned in EXPECTED_NETWORK_ID); own unicity-ids.mainnet.json registry (currently only the non-fungible base type, no fungible coins). Live wallet-api at https://wallet-api.mainnet.unicity.network (use 'mainnet' in all three places and a SECRET gateway key); shares testnet's Nostr relay until one is stood up |
All networks share Nostr relays (nostr-relay.testnet.unicity.network for test
nets) and group relays per NETWORKS.
assertNetworkConsistency() (impl/shared/network.ts) refuses provably-broken
networks at provider creation (null or networkId-mismatched trust base).
API key: there is NO bundled default. Consumers inject oracle.apiKey
(plumbed through createBrowserProviders/createNodeProviders →
UnicityAggregatorProvider → engine). The testnet2 key is non-secret and
pre-filled in .env.example; a mainnet key is a secret.
Common Commands
# Build (ESM + CJS via tsup, multiple entry points)
npm run build
# Test (watch mode)
npm test
# Test (single run)
npm run test:run
# Mutation probes (tests/mutation/probes.json lists what they cover; all must be KILLED)
npm run test:mutation
# E2E against a REAL aggregator-go (Testcontainers; needs Docker)
npm run test:aggregator
# E2E tests (live testnet2/staging; needs .env — see .env.example)
npm run test:e2e
# Relay integration tests (Docker testcontainers, or RELAY_URL=...)
npm run test:relay
# Lint
npm run lint
# Type check (+ tests project)
npm run typecheck
npm run typecheck:tests⚠️ Windows note: the tsup DTS build is known to segfault on Windows + Node 22.x. This is a local toolchain trap, NOT a real break — CI (Linux) is authoritative for build success.
Key Concepts
P11 flip (what changed — see docs/MIGRATION-PAYMENTS-V2.md)
sphere.paymentsIS the v2 facade (assets/tokens/history/send/mint/receive/requests), and since 0.15.0 the only accessor — thepaymentsV2alias and thepaymentsV2:init flag are both gone. The getter THROWSNOT_INITIALIZEDwhere the alias returnednull.- Removed wholesale: the legacy
PaymentsModulestack,modules/accounting(invoices),modules/swap, the S1WalletApiClient(wallet-api/+./wallet-apisubpath), own-storage token custody (TokenStorageProvider+ both platform providers +tokenStorage/tokensDiroptions), the S7DeliveryProviderport, the Nostr asset/payment-request rail (kinds 31113/31115/31116), TXF types/serializer,validation/,sphere.sync(),startWalletApiSession/resumeOpenIntents/walletApiSessionStatus, the old event names, and the Connect invoice surface (2 queries, 9 intents, 2 scopes). - Kept deliberately:
Sphere.importFromLegacyFile/detectLegacyFileType/isLegacyFileEncrypted+exportToTxt(live onboarding/backup path);Asset.unconfirmed*fields (pinned 0); the:pv2deviceId suffix (deployed refresh-token rows are keyed<deviceId>:pv2);core/wallet-api-protocol.ts(cross-repo contract strings). - The ONE sanctioned refusal fossil, still kept:
accounting:/swap:init options throw typedINVALID_CONFIG, because a silent ignore would hide that invoices/swaps no longer exist. - Interop, as of the 3.x bump: there is none across the major. Pre-0.15 clients (including
the pre-flip ≤0.13 module clients that used to transact freely with the vertical over the same
mailbox rail) speak the 2.x wire: nothing they wrote decodes here, and once the gateway cuts
over nothing they write gets certified at all. That is what makes it a flag day — sphere-sdk,
wallet-apiandaggregator-gomove together or not at all, with a testnet + backend reset alongside. Within 0.15.x the rail itself is unchanged: same mailbox, same rawToken.toCBOR()blobs, same predicates/trust base/memo envelope.
Send Pipeline (money-safety)
send()requires a recipient with a published chain pubkey (INVALID_RECIPIENTotherwise). Transfers lock toSignaturePredicate(recipient chainPubkey).- Concurrency: reservations ledger + op queue (
modules/payments-v2/select/) — concurrent sends queue for sources instead of failing; open intents keep their sources reserved until resume adopts them. - Durable-intent-first: the server records the intent BEFORE any chain op; every op posts a signed, field-encrypted progress checkpoint; the mailbox deposit and the signed complete close it. A crash at ANY stage resumes the SAME transferId — never a second spend (E.2/E.4, #631, #676, #690).
- Never re-issue
send()after a possibly-committed outcome (isPossiblyCommittedSendOutcome()is true for exactly six codes:SEND_SYNC_PENDING,CERTIFICATION_UNCONFIRMED,CHECKPOINT_PERSIST_FAILED,SPLIT_CHECKPOINT_LOST,CHECKPOINT_TRUSTBASE_MISMATCH,SEND_PARTIALLY_COMPLETED): the intent stays OPEN and the convergence pass (facade.start(), the heartbeat, orpayments.resumeNow()) finishes it under the same transferId. A proven clean reject orTransferConflictErroraborts (with #625 source demotion + a bounded re-plan, up toMAX_RESELECT= 8). - Each dist bundle (root,
./core,./impl/nodejs,./impl/browser) carries its ownSphereErrorclass, andisSphereError()is aninstanceofcheck. So an error thrown by provider code (e.g. the Nostr transport'sTRANSPORT_ERRORduring recipient lookup) is notisSphereError()for the root bundle: readcodestructurally, and importisPossiblyCommittedSendOutcome/PartialSendConflictErrorfrom the same entry asSphere.
Receive & Verification
- Incoming tokens arrive as FINISHED SDK tokens via the wallet-api mailbox (continuous drain
while started;
receive()for an explicit one-shot). - Verified before entering the balance:
engine.verify(full trust-base proof check) +engine.isOwnedBy(token, own chainPubkey); a failed check is a terminal mailbox reject (reason'invalid'/'not-owned') and is not logged. Only an undecodable blob is also warn-logged. Averifythat throws (infra) is not a reject: the entry stays unacked and re-lists on the next drain. Dedup by (tokenId, stateHash) — keyed on the genesis id alone, a token sent away and legitimately received back (A→B→A) would be dropped as a duplicate. Dedup has two layers. First,WalletApiDeliveryPort(impl/wallet-api-v2/mailbox.ts) keeps a durable seen-set of settled (claimed or rejected) mailboxdeliveryIds, each the content-derivedsha256(tokenId ‖ stateHash), underdelivery:seenin the per-address scoped KV; an id is written only after its ack succeeds, andincoming()skips every id already in the set. Second, Receive compares each yielded entry againstheldStates, an in-memoryMapbuilt per composition (modules/payments-v2/compose.ts) and seeded from the server inventory listing (storagePort.listInventory()), backed by the server-side historydedupKey. Store-before-ack: the token is stored before the mailbox claim is acknowledged, so a crash re-claims instead of losing.
Minting
payments.mint(coinIdHex, amount: bigint)= engine self-mint (standalone SDK mint to the wallet's own pubkey, no faucet). Journal-first: the mint journal entry is durable before the chain op; a replay converges by idempotent same-seed re-call. Lets a fresh wallet top up on testnet2.
Coinless tokens (#777/#778/#780/#781, wallet-api#140/#141/#147/#151)
- A token whose genesis data is not a value envelope names no coin. The word is coinless,
never "non-fungible": in Unicity every token is non-fungible by construction (each is a unique
object keyed by
tokenId), so that term names every token and distinguishes none. - Surfaced by
payments.coinless(), disjoint fromtokens()— an active entry is in exactly one, so no coin consumer changes and an NFT joins no balance and no selector pool. It is not aToken: that requirescoinId/symbol/decimals/amount, and sentinels put untrue values in fields consumers sum.payments.tokenData(tokenId)reads the genesis payload on demand. tokenTypeis a CLASS, not an identity. Every token of one kind shares a type;tokenIdis the instance key. Resolve names withTokenRegistry.getTypeDefinition()— the registry file holds TWO id namespaces discriminated byassetKind(afungibleentry's id is a coin id, anon-fungibleentry's is a token type), and the flatgetDefinition()map cannot tell them apart. An unrecognised type is legitimate — never reject or hide a token for it. Do NOT build a "group by type" UI for valued tokens:mint()and split outputs derive a type per operation.value === nullis ambiguous — readvalueEnvelope.none_*is genuinely coinless;bare_collectionis the bridged dialect this SDK does not decode, so zero there means "cannot read", not "has none". Conflating them either hides real coins or invents a phantom NFT.- A corrupt value envelope throws rather than reading as valueless (#778). The classifier's
throw set must stay a SUBSET of wallet-api's §8.2 422 set: everything arriving over the mailbox
already passed §8.2, and
Receive.screen()turns a decode throw into a terminalrejectAck('invalid'), so throwing where wallet-api accepts LOSES the token. - Transfer is
sendWholeToken({recipient, tokenId, memo?})— ONE named token, coinless or valued, never split, so a valued token's coins travel with it. A coin spend SELECTS sources for an amount and may queue; a whole spend reserves the one it was NAMED and never queues. SameTransferMachine, one money path. A proven conflict is TERMINAL: #625's re-plan needs an alternative source and a named token has none. The one refusal isbare_collection— real coins this SDK cannot decode, so the move would be unaccountable. sendCoinlessis the NFT-scoped twin, refusing a valued source. Connect'ssend_nftmust route there: itsnft:transferscope does NOT authorise coin transfers, so routing it at the general verb would let a dApp holding only that scope move coins.- The durable intent is discriminated by a REQUIRED
kind('coin' | 'whole'); an ABSENT kind reads as'coin', the only shape written before #777, and an EXPLICIT unknown one is refused.'coinless'is 0.17.0's spelling of'whole'and is still ACCEPTED on read — the payload is durable SERVER state, so a 0.17.0 client may have left one open and this client must resume it;isWholeIntent()is the only discriminator, never a=== 'whole'comparison. A whole intent names EXACTLY one source and can never carry a split — re-checked on resume, because a second leg would let a '0' remainder complete the intent and report success for a leg that never landed. - Connect: the
send_nftintent has its OWNnft:transferscope (2.1 → 2.2). Reusingtransfer:requestwould silently widen every dApp that already holds it. Named nft, not token: coins are tokens too, sotoken:transferbesidetransfer:requestdistinguishes nothing (andTOKEN_TRANSFERalready named the removed Nostr kind 31113). - History records
assets: []for a coinless movement on every type. NevercoinId: ''— wallet-api keeps refusing that so there is only one wire spelling of "no coin". - The coinless verdict is DERIVED from wallet-api's §8.2 step-6 boundary. Moving that boundary needs the client verdict re-derived, not merely re-tested (recorded in wallet-api's §8.2 too).
- NFT metadata (#785) is a payload format on top of coinless tokens — normative spec
docs/NFT-METADATA.md, CBOR tags 39052NftMetadata/ 39053NftMedia/ 39054NftLink/ 39055NftSigned, codectoken-engine/nft-payload.ts.payments.mintNft({ content, sign? })mints to the wallet itself underNETWORKS[network].nftTokenType(the registry'snon-fungiblevessel), signed by default;payments.nft(tokenId)/nfts(tokenIds)readNftView { tokenId, content, creator, signature }behind a per-facade 256-entry LRU.creatoris the key the payload CLAIMS: attribute a token to it only whensignatureisvalid. - A
validsignature is attribution, not authorization: which key signed this item for this token — never that the signer is recognised or that a collection authorized the issue (that is the mint reason, under the type's issuance policy).NftMetadata.collection_id(1–64 bytes, hex in the API) is likewise a CLAIM: never present it as verified membership. The format defines no supply cap. - An
NftLinkwhose media type isNFT_DOCUMENT_MEDIA_TYPE(application/vnd.unicity.nft+cbor) is a document link: allowed only as a token's content (top level orNftSigned.payload), refused asimage/animation_url. The linked file is exactly oneNftMetadata/NftMediaitem — resolve withverifyNftLinkContent, thenparseNftDocument(never throws). mintNftrefuses a genesis payload overNFT_MAX_PAYLOAD_BYTES(1 MiB) BEFORE the journal. wallet-api'sMAX_BLOB_BYTESrefusal lands only at upload, after certification, so a larger payload would leave a certified token that no replay can ever store.- NFT recognition is display-only and never throws:
parseNftPayload/engine.readNftreturnnullfor anything unrecognised, and nothing on the receive or mirror path calls them. Keep it that way — a throw where a token can be refused LOSES a token wallet-api accepted, the same reason the classifier's throw set is bounded above. - An
NftSigneddigest isSHA-256(CBOR[h'UNICITY_NFT_SIGNED', 1, α, h(recipient predicate), h(token id), h(token type), h(payload)]), the yellowpaper genesis-commitment layout. The recipient is the GENESIS one, never the current owner: avalidNFT stays valid across transfers, while a payload copied onto another token, minted under another token type, or front-run to another first owner readsinvalid. Verification recovers the key, so the recovery byte is bound and high-s is refused. The digest is a cross-SDK byte vector — hash the payload bytes as received, never a re-encoding. - The NFT mint has its own journal (
STORE_KEYS.nftMintJournal), never the coin one: an older client would retry an entry with nocoinId/amountevery pass. It journals the planned BYTES (payload, salt, token type) before the chain op, so replay re-submits exactly the first attempt — no re-signing, no deterministic-engine requirement — and a minted id other than the plan's is never finalised. The fake engine plans and verifies through the realtoken-engine/nft-ops.tsand keeps each token's first owner and genesis token type, so it judges signatures exactly as the real engine does.
Unicity IDs (nametags)
- Human-readable aliases (e.g.,
@alice) for receiving payments. - Registration = publishing the Nostr identity binding (name ↔ chainPubkey). The binding
carries the UNIP-01 marker
["L", "unicity:nametag"](nostr-js-sdk 0.6.0): a UNIP-01 relay enforces single ownership by receive order, and resolution prefers the marked binding (ambiguous →null);created_atfirst-seen-wins is only the legacy fallback for unmarked bindings and is forgeable. Seedocs/NAMETAG-BINDINGS.md. Runtime name resolution is Nostr-binding-only; receive is alwaysSignaturePredicate(chainPubkey); there is no PROXY addressing anywhere. - The self-issued
UnicityIdTokenmint was REMOVED with the 2.0.0 SDK bump (upstream deleted the unicity-id primitive, state-transition-sdk-js#132) — registration is Nostr-binding-only. - Recovered from Nostr during create/load/import (before the call returns — read
sphere.identity?.nametag, the init-timenametag:recoveredhas no listener yet); each HD address can have its own.
Peer Resolution
sphere.resolve(identifier)— unified lookup via transport.- Accepts:
@nametag,DIRECT://..., chain pubkey (02/03), transport pubkey (64-hex). ReturnsPeerInfoornull. - Identity binding event published on init/load — wallet discoverable without a Unicity ID.
- The payments vertical rides the same resolution for
send()/requests.create()recipients. A bare 66-hex chain pubkey is taken as being on the session network. A@nametag/DIRECT://binding declares no network (#734), so every such send emitstransfer:attentionrecipient:network-unverified(withtransferId: '') and proceeds on the session network; a resolved peer that DOES declare another network is refused withINVALID_RECIPIENT.
Token Registry (Remote + Cached)
TokenRegistrysingleton provides token metadata (symbol, name, decimals, icons) by coin ID. No bundled data — remote URL per network (NETWORKS[network].tokenRegistryUrl; testnet/testnet2 useunicity-ids.testnet2.json) + persistent cache.- The facade consumes it for Asset presentation only; the money path works with coin ids.
- A
Spherebuilds and OWNS its registry (#767), disposed bysphere.destroy(). The provider factories no longer callTokenRegistry.configure()— in the published package they are separate tsup bundles with separate singleton copies, so that call wrote to an object no consumer could read.
Durable client state (the complete inventory — design §6)
- Everything the client persists for money lives in the per-(network, address) scoped KV:
pv2g2:{network}:{chainPubkey}:*inside the plainStorageProvider— refresh token, sync cursors, receive seen-set, intent backstop, split-checkpoint cache, delivery journal (#621), mint journal, NFT mint journal (#785), #690 shortfalls, request settling journal, the epoch latch and the §5.2suspectedSpent/knownSpendsoverlays — the complete list isSTORE_KEYSinmodules/payments-v2/stores.tsplus the session's refresh token underrefreshTokenKey(deviceId)(auth:refresh:<deviceId>,impl/wallet-api-v2/session.ts) plus the delivery port's receive seen-set underDELIVERY_SEEN_KEY(delivery:seen,impl/wallet-api-v2/mailbox.ts: settled mailbox entry ids, written only after the ack succeeds). One writer per store. Being self-prefixed with the network, it never rides the legacyisNetworkScopedAddressKeymechanism (which still guards the remaining chat/identity keys in the platform storage providers). - The
pv2:→pv2g2:rename IS the 3.x local migration (modules/payments-v2/stores.ts;sweepSupersededState()clears the old prefix once per composition, fromcore/payments-v2-wiring.ts). Not hygiene — money-critical: the sync-epoch latch lives in that KV, so after a backend reset a SURVIVING latch makes the session see a CHANGED epoch and run the restore protocol (modules/payments-v2/restore.ts), which re-PUTs every locally-open intent into the freshly wiped backend. Those intents reference tokens that no longer exist, so they can never complete — and the server now calls them open, so nothing can drop them: a permanentpendingTransfers()row holding its sources reserved, with no error surface.Sphere.clear()is not a mitigation (it callsstorage.clear()with no prefix and takes the mnemonic with it). Under the new prefix the latch readsnull,noteEpochtakes itsprevious === nullearly return, and no restore fires. Pinned bytests/unit/payments-v2/kv-generation.test.tsand a case intests/integration/sphere-payments-v2-wiring.test.ts. A prefix must never START with a superseded one — the sweep matches bystartsWith, sopv2:g2:would have deleted itself. - Chat/identity keys stay network-agnostic; storage providers keep their
networkparameter for the legacy scoped keys.
IndexedDB Databases (Browser)
| Database | Provider | Purpose |
sphere-storage | IndexedDBStorageProvider | Wallet keys, per-address data, pv2g2:* scoped KV |
Sphere.clear({ storage }) empties it (the object store, not deleteDatabase; both KV
generations and every key prefix in that dbName go with it) and sweeps orphaned pre-flip
sphere-token-storage-* databases. IndexedDBStorageProvider.backingStoreId is therefore the
database, not the prefix: two wallets sharing one dbName share one fate.
Testing
Framework: Vitest
Run: npm run test:run (unit/integration), npm run test:mutation (probes must be KILLED),
npm run test:e2e (live staging/testnet2, needs .env), npm run test:relay,
npm run test:aggregator (a REAL aggregator-go, stood up by Testcontainers — needs Docker,
no manual setup and no local build)
Know what each layer can and cannot prove. Everything else that exercises the chain runs
against TestAggregatorClient, which orchestrates the SDK's OWN smt / CertificationData /
verification rule — so it proves this client is self-consistent, never that the client and the
SERVICE agree. tests/integration/sphere-payments-v2-* prove less about the wire still: they
swap a fake engine in via setEngine, so they pin facade orchestration and would pass with the
CBOR wrong. Only tests/aggregator/ closes that gap.
Key test areas:
tests/unit/payments-v2/— the vertical: TransferMachine send/resume, receive drain, requests, mint journal, history, facade assembly, inventory presentation, the KV generation rename (kv-generation.test.ts), adversarial fakes (fakes/FakeWalletApibehavior pins- FakeGateway), port contract suites
(
contracts/{storage,delivery}-port.contract.ts— swappability enforced)
- FakeGateway), port contract suites
(
tests/aggregator/— the real engine against a REAL aggregator-go v3, stood up by Testcontainers (npm run test:aggregator; ~1m45s cold).docker/docker-compose.ymlis copied from state-transition-sdk-js, which the Java SDK mirrors too — keep the three in step, or "passes against a real aggregator" means something different in each repo. It pins a prebuiltghcr.io/unicitynetwork/aggregator-goimage rather than building rocksdb locally.support/aggregatorStack.tswaits for consensus to CERTIFY A ROUND, not merely for health: until it has a reference time the service answers every requestSERVICE_NOT_READY. Mint / transfer / split / same-transferId resume, each verified against the service's own generated trust base.verify()passing is the assertion no fake can make: the leaf value this client computes —H(transactionHash, referenceTime)since 3.x — reproduces the leaf the Go service inserted. Guard against it going vacuous: with a well-formed but WRONG root key the SAME certified token must be refused —engine.verifyreports the aggregatedFAIL(the granular status lives in the SDK's nested trace, which the test walks to nameINVALID_TRUSTBASEat the quorum-signature rule). The compose stack runs a SINGLE bft-root node, so this exercises "wrong key", not a real quorum — mainnet's 4-node/threshold-3 shape is still unexercised anywhere in the repo.tests/mutation/probes.json— mutation probes over the money path and its neighbours:modules/payments-v2/*,token-engine/(engine, factory, proof wait, NFT payload, value envelope),impl/wallet-api-v2/*,core/(Sphere lifecycle, wiring), the Nostr transport, the token registry, the storage providers andstorage/tracked-addresses.ts, among others — the file is the list;npm run test:mutationmust report every one KILLED (a probe count belongs in the file, not here — it has gone stale twice)tests/unit/token-engine/— engine contract, factory, FakeTokenEngine, identity golden test (identity.test.tslocks the DIRECT:// derivation),expires-at.test.ts(no deadline on any submitted request nor on the token itself; two transactions differing ONLY in the deadline share a StateId but not a transaction hash; a 24-hour clock jump between two attempts still rebuilds byte-identical bytes;REQUEST_EXPIREDandSERVICE_NOT_READYend keep-open, and a booting gateway is retried through),wire-version.test.ts(a real 2.1.0-encoded token fromfixtures/token-sdk-2.1.0.hexis refused with an error naming the version — that fixture is uncapturable once the pin moves again),proof-deadline.test.ts(the abort guard)tests/unit/connect/— protocol surface guard (14/8/15 counts),mint_nftwire helpers (nft-wire.test.ts) and its never-auto-approved guard, lock semantics, payments-compat adapter conformance (old wire names/payloads from the v2 facade, against a mock Sphere whosepaymentsgetter THROWS exactly like the real one)tests/unit/core/— Sphere lifecycle, clear, nametag sync/recovery, wallet-api-protocol pinstests/integration/— Sphere payments wiring (defaults + walletApi config, incl. the superseded-pv2:sweep on composition), per-address KV bleed invariants, kv/file network isolation, wallet lifecycletests/e2e/— live staging:payments-v2-vertical.staging(money matrix incl. splits + crash-resume),sphere-paymentsv2-wiring.staging(the REAL Sphere composition),wallet-api-v2-session.staging,token-engine.testnet2tests/relay/groupchat-relay.test.ts— NIP-29 relay integration (Docker + remote)
Dependencies
Core (from package.json):
@unicitylabs/state-transition-sdk— pinned3.0.1(exact; imported only viatoken-engine/sdk.ts)@unicitylabs/nostr-js-sdk^0.6.0— Nostr protocol@noble/hashes^2,@noble/curves^2,@noble/ciphers^2— cryptographybip39,crypto-js,canonicalize,buffer
Optional/peer (Node WebSocket):
ws>=8.0.0— Node.js WebSocket (peer,peerDependenciesMeta.optional). Optional in metadata only:@unicitylabs/sphere-sdk/impl/nodejsimportswswhen the module loads (impl/nodejs/transport/index.ts), on every Node version, so Node consumers must install it.
File Size Reference
Largest source files (September 2026, for context; sizes drift):
core/Sphere.ts— wallet lifecycle (~4,450 lines)transport/NostrTransportProvider.ts— Nostr transport (~2,100)modules/groupchat/GroupChatModule.ts— NIP-29 group chat (~1,850)transport/MultiAddressTransportMux.ts— per-address transport mux (~1,800)connect/host/ConnectHost.ts— Connect wallet host (~1,400)
The money path's core files are smaller: modules/payments-v2/PaymentsFacade.ts (~790),
modules/payments-v2/machine/TransferMachine.ts (~660), impl/wallet-api-v2/session.ts (~450).
Code Style
- TypeScript strict mode
- ESLint with TypeScript rules (+ the token-engine SDK import boundary)
- ESM modules (with CJS build output)
- Prefer
interfaceovertypefor objects - Use
readonlyfor immutable properties - Async/await over raw promises
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

