agentleFS
unicity-sphereunicity-sphere/sphere-sdk/CLAUDE.md

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

Dec 2025: 0 mentionsJan 2026: 0 mentionsFeb 2026: 0 mentionsMar 2026: 0 mentionsApr 2026: 0 mentionsMay 2026: 2 mentionsJun 2026: 2 mentionsJul 2026: 1 mentionAug 2026: 0 mentionsSep 2026: 0 mentionsOct 2026: 1 mentionNov 2026: 0 mentions
Dec 2025Jun 2026Nov 2026
Mentions a month of the unicity-sphere/sphere-sdk repository that our weekly crawl found: only 6 in all, so this is a hint, not a trend. There is no adoption data for this file yet.

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
  1. Very specific:

    Branch topology (updated 2026-07-31): all work branches from and PRs back to main — the feat/wallet-api-integration era ended when the …

    line 9
  2. Very specific:

    What 3.x is: every transaction now carries expiresAt — an exclusive request deadline in Unix seconds — and every inclusion proof carries …

    line 70
  3. Very specific:

    Read it lazily at the call site, never once at construction.

    line 358
  4. Very specific:

    The engine is mandatory for money movement: when the oracle does not supply a trust base + gateway URL (or the engine cannot be …

    line 605
  5. Very specific:

    All networks share Nostr relays (nostr-relay.testnet.unicity.network for test nets) and group relays per NETWORKS.

    line 732
  6. Very specific:

    tokenType is a CLASS, not an identity: Every token of one kind shares a type.

    line 862
  7. Very specific:

    Prefer interface over type for objects

    line 1110
  8. Very specific:

    Use readonly for immutable properties

    line 1111

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

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 — 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 + lint + build + test:run on Node 22 and 24, plus a separate test:mutation job).
  • 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 touching modules/payments-v2/ or impl/wallet-api-v2/; the code and docs/API.md are 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 null inclusionProof means "not certified YET", and the time-dependent statuses the bump added — REQUEST_EXPIRED and REFERENCE_TIME_AFTER_ROUND on verify, REQUEST_EXPIRED and SERVICE_NOT_READY on submit — each report only that THIS attempt was not admitted, never that no earlier attempt certified, so none of them is a clean reject. The STATE_ID_EXISTS aggregator lag is OVER (M7 live e2e observed 2026-06-12: the gateway answers SUCCESS for duplicate AND conflicting submits — the status carries no conflict signal; see the dated OBSERVED note in ../wallet-api/docs/sdk-changes.md E.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: expiresAt is 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 — and InclusionProofVerificationRule compares the hash BEFORE the certification data, so the disagreement surfaces as TRANSACTION_HASH_MISMATCH, i.e. as a foreign spend, which token-engine/certification-outcome.ts maps to TransferConflictError (abort + re-plan). A clock-derived deadline would therefore make every crash-resume abort an intent whose spend is already on chain. Pinned by tests/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 StoragePort and DeliveryPort (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 runs npm version itself, so package.json on a branch still reads the PREVIOUS version; never hand-edit the field. Publishing from main takes dist-tag latest, any other branch takes dev (line <next version>-dev.#). Consumers (wallet-api backend, sphere frontend) pin exact versions. The backend consumes ONLY the ./token-engine subpath (must stay browser/Nostr-free — keep token-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 carries CertificationDataVersion = 2 with a hard reject of version 1 — nothing can straddle the gateway cutover. wallet-api must bump in LOCKSTEP: both repos pin @unicitylabs/state-transition-sdk EXACTLY, 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 carries expiresAt — an exclusive request deadline in Unix seconds — and every inclusion proof carries the referenceTime of 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 in waitInclusionProof that 2.0.3 fixed (state-transition-sdk-js#140/#141) is still fixed in 3.0.1: its poll loop checks aborted before subscribing, races each poll against the signal, and cancels the in-flight request. tests/unit/token-engine/proof-deadline.test.ts is 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-sdk

Node.js:

npm install @unicitylabs/sphere-sdk ws

Complete 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

RoleClassWhere it runs
dApp (client)ConnectClientany web page / app
Wallet (host)ConnectHostSphere 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_nft needs its own nft:mint scope (Connect 2.3) — neither mint:request nor nft:transfer grants 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.setIntentAutoApprove throws for it and the host routes every mint_nft to onIntent. Params cross the wire via nftContentToWire/nftContentFromWire (connect/nft-wire.ts, inline bytes as canonical base64; shape only — value rules stay in payments.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

ComponentBrowserNode.js
Storage (keys/identity/journals)IndexedDB (IndexedDBStorageProvider)File-based JSON (FileStorageProvider)
Token custodywallet-api backend (server inventory; walletApi config required)Same
Transport (Nostr: DMs, nametags, groupchat)Native WebSocketws package (install separately)
Oracle (network config)Embedded trust base per network; API key injected via oracle.apiKeySame (+ optional trustBasePath file)
Price (CoinGecko)Optional (price config)Optional (price config)
Token RegistryRemote fetch + persistent cacheRemote fetch + file cache

Key API Methods Reference

MethodReturnsDescription
Sphere.init(options)Promise<{ sphere, created, generatedMnemonic? }>Create or load wallet (requires network and a walletApi config, or 'none')
sphere.hasPaymentsbooleanWhether 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()voidDrop 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()voidDrop 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)stringSign 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?)stringText backup (optionally password-encrypted)
sphere.on(event, handler)() => void (unsubscribe)Subscribe to events

Notes:

  • sphere.paymentsV2 is GONE (0.15.0) — sphere.payments is the only accessor. The behavioural difference consumers must handle: the alias returned null while no vertical ran, sphere.payments THROWS NOT_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 throws PAYMENTS_NOT_COMPOSED instead — permanent, not transient, and sphere.hasPayments is the try/catch-free way to ask.
  • sphere.groupChat, sphere.market are nullable getters — null unless enabled in init options. sphere.accounting / sphere.swap DO NOT EXIST (P11 flip); passing accounting:/swap: init options throws INVALID_CONFIG.

Key Events

The payments vertical emits exactly 8 events; identity/comms/groupchat events ride the same bus.

EventPayloadWhen
transfer:incomingIncomingTransfer ({ 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:updatedTransferResultOutgoing 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:updatedHistoryEntry (the just-recorded entry)History changed
payment_request:incomingPaymentRequestViewReceived 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.tsCommunications

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 the token-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.json

Subpath 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 plain StorageProvider) 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 → composePaymentsV2 builds one PaymentsFacade per active address over the wallet-api-v2 ports (WalletApiStoragePort, WalletApiDeliveryPort, WalletApiSplitCheckpointStore) and a WalletApiSession (challenge sign-in → JWT + refresh token, wake WebSocket, single-flight re-auth), and fires sweepSupersededState() once (the pv2: generation — see below). The paymentsV2Transport seam in the config injects a whole custom bundle (tests, custom hosts). Init is FAIL-CLOSED: no walletApi → INVALID_CONFIG, before any storage write. The ONE explicit escape is walletApi: 'none' (#793, NO_PAYMENTS): a wallet that is only ever a Nostr client composes nothing — no session, device, wake socket, drain, token engine or pv2g2: key, at boot or on an address switch — and payments throws PAYMENTS_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. network is still required with 'none': it configures the token registry, and init throws INVALID_CONFIG without 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 inside facade.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 to MAX_RESELECT (8) re-selections, none for a whole-token send (#625 marks the source suspectedSpent, 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) — deliveryPending on the TransferResult, landed vs pending-delivery in deliveryState, transfer:attention when undeliverable/deferred.
  • Mint: journal-first (mint journal in scoped KV), idempotent same-seed re-call converges a replay — crash-safe without a faucet.
  • Error contract (load-bearing, unchanged): CERTIFICATION_UNCONFIRMED (ProofUnconfirmedError with .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 is payments.pendingTransfers() / payments.resumeNow() (a retry button calls resumeNow(), NEVER send(): a re-issued send double-pays), plus payments.connectionStatus() for the session. An address switch stops the old facade and starts a fresh one (a stopped WalletApiSession does 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 ESLint no-restricted-imports rule blocks any other import of @unicitylabs/state-transition-sdk — everything else codes against the ITokenEngine port and sphere-domain types from token-engine/.
  • ITokenEngine operations: getIdentity, deriveIdentityAddress, tokenId, readValue, balanceOf, readMemo, readTokenData, mint, mintDataToken, transfer, split, verify, isSpent, isOwnedBy, encodeToken, decodeToken, deliveryKeys, buildNftMint, readNft (#785), and the optional dispose (worker-pool teardown).
  • The 3.x SDK surface (visible only inside token-engine/): the three create/split builders take an options object where 2.x took trailing positionals, and InclusionProofResponse.inclusionProof is InclusionProof | null where null IS "not certified yet" — isSpent and 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): expiresAt is 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_READY is instead RETRIED at the submit call site (TransientSubmitAnswer in token-engine/proof-wait.ts, sharing the one certification deadline): it is a 503 in a 200 body, and left alone a booting gateway surfaced CERTIFICATION_UNCONFIRMED. REQUEST_EXPIRED must NEVER be retried. TRANSACTION_HASH_MISMATCH remains the only conflict signal.
  • TokenBlob is { tokenId, token } and token is the SDK's own Token.toCBOR() bytes — the sphere-private CBOR envelope (token-engine/token-blob.ts, tag 39051, v/network fields) was DELETED: nothing ever read v or network, and the wallet-api wire form was the inner bytes anyway. deriveDeliveryKeys decodes those bytes directly.
  • Split checkpoints are generation 2 (token-engine/split-checkpoint.ts): CHECKPOINT_VERSION 1 → 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.
  • Sphere builds the engine from the oracle's config surface (getTrustBaseJson() / getAggregatorUrl() / getApiKey()) via createSphereTokenEngine(EngineConfig). The trust base JSON is the single source of truth for the network id (RootTrustBase.networkId, e.g. testnet2 = 4).
  • SphereToken.sdkToken is 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? } to Sphere.init (or EngineConfig) and engine.verify fans 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 and setOracleApiKey() disposes the one it replaces, but an address switch disposes NOTHING (the previous address keeps its engine until destroy), so up to poolSize × visited addresses workers can be alive. createWorker must return the VerificationWorker port type: a DOM Worker / st-sdk NodeWorker needs an as VerificationWorker cast under strict TS (their handler params are narrower). The consumer-facing entry-script contract is UNCHANGED by the 3.x bump (the SDK's IWorker/WorkerTokenVerifier declarations are diff-clean; only the main-thread side moved). See docs/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 / import reject with INVALID_CONFIG ('payments requires the v2 token engine …') and tear the half-built Sphere down, so send() / mint() are never reachable; switchToAddress() to an address whose engine cannot be built rejects the same way. The missing-engine AGGREGATOR_ERROR ('paymentsV2: token engine unavailable') is raised only by the facade's engineRef guard, after init: a money call can reject with it when its address's engine record is empty as the call starts (e.g. after a setOracleApiKey() rebuild that could not construct one). A walletApi: '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:

ProviderInterfaceImplementations
StorageStorageProviderIndexedDBStorageProvider (browser), FileStorageProvider (Node.js)
TransportTransportProviderNostrTransportProvider
OracleOracleProviderUnicityAggregatorProvider
PricePriceProviderCoinGeckoPriceProvider
Money portsStoragePort / 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 explicitly
  • getTrustBaseJson() / 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)

NetworkAggregator/GatewayStatus
testnethttps://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'
testnet2https://gateway.testnet2.unicity.networkSame config as testnet; wallet-api https://wallet-api.unicity.network
mainnethttps://gateway.mainnet.unicity.networkLive 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.payments IS the v2 facade (assets/tokens/history/send/mint/receive/ requests), and since 0.15.0 the only accessor — the paymentsV2 alias and the paymentsV2: init flag are both gone. The getter THROWS NOT_INITIALIZED where the alias returned null.
  • Removed wholesale: the legacy PaymentsModule stack, modules/accounting (invoices), modules/swap, the S1 WalletApiClient (wallet-api/ + ./wallet-api subpath), own-storage token custody (TokenStorageProvider + both platform providers + tokenStorage/tokensDir options), the S7 DeliveryProvider port, 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 :pv2 deviceId 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 typed INVALID_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-api and aggregator-go move together or not at all, with a testnet + backend reset alongside. Within 0.15.x the rail itself is unchanged: same mailbox, same raw Token.toCBOR() blobs, same predicates/trust base/memo envelope.

Send Pipeline (money-safety)

  • send() requires a recipient with a published chain pubkey (INVALID_RECIPIENT otherwise). Transfers lock to SignaturePredicate(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, or payments.resumeNow()) finishes it under the same transferId. A proven clean reject or TransferConflictError aborts (with #625 source demotion + a bounded re-plan, up to MAX_RESELECT = 8).
  • Each dist bundle (root, ./core, ./impl/nodejs, ./impl/browser) carries its own SphereError class, and isSphereError() is an instanceof check. So an error thrown by provider code (e.g. the Nostr transport's TRANSPORT_ERROR during recipient lookup) is not isSphereError() for the root bundle: read code structurally, and import isPossiblyCommittedSendOutcome / PartialSendConflictError from the same entry as Sphere.

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. A verify that 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) mailbox deliveryIds, each the content-derived sha256(tokenId ‖ stateHash), under delivery:seen in the per-address scoped KV; an id is written only after its ack succeeds, and incoming() skips every id already in the set. Second, Receive compares each yielded entry against heldStates, an in-memory Map built per composition (modules/payments-v2/compose.ts) and seeded from the server inventory listing (storagePort.listInventory()), backed by the server-side history dedupKey. 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 from tokens() — 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 a Token: that requires coinId/symbol/decimals/amount, and sentinels put untrue values in fields consumers sum. payments.tokenData(tokenId) reads the genesis payload on demand.
  • tokenType is a CLASS, not an identity. Every token of one kind shares a type; tokenId is the instance key. Resolve names with TokenRegistry.getTypeDefinition() — the registry file holds TWO id namespaces discriminated by assetKind (a fungible entry's id is a coin id, a non-fungible entry's is a token type), and the flat getDefinition() 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 === null is ambiguous — read valueEnvelope. none_* is genuinely coinless; bare_collection is 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 terminal rejectAck('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. Same TransferMachine, 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 is bare_collection — real coins this SDK cannot decode, so the move would be unaccountable.
  • sendCoinless is the NFT-scoped twin, refusing a valued source. Connect's send_nft must route there: its nft:transfer scope 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_nft intent has its OWN nft:transfer scope (2.1 → 2.2). Reusing transfer:request would silently widen every dApp that already holds it. Named nft, not token: coins are tokens too, so token:transfer beside transfer:request distinguishes nothing (and TOKEN_TRANSFER already named the removed Nostr kind 31113).
  • History records assets: [] for a coinless movement on every type. Never coinId: '' — 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 39052 NftMetadata / 39053 NftMedia / 39054 NftLink / 39055 NftSigned, codec token-engine/nft-payload.ts. payments.mintNft({ content, sign? }) mints to the wallet itself under NETWORKS[network].nftTokenType (the registry's non-fungible vessel), signed by default; payments.nft(tokenId) / nfts(tokenIds) read NftView { tokenId, content, creator, signature } behind a per-facade 256-entry LRU. creator is the key the payload CLAIMS: attribute a token to it only when signature is valid.
  • A valid signature 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 NftLink whose media type is NFT_DOCUMENT_MEDIA_TYPE (application/vnd.unicity.nft+cbor) is a document link: allowed only as a token's content (top level or NftSigned.payload), refused as image/animation_url. The linked file is exactly one NftMetadata/NftMedia item — resolve with verifyNftLinkContent, then parseNftDocument (never throws).
  • mintNft refuses a genesis payload over NFT_MAX_PAYLOAD_BYTES (1 MiB) BEFORE the journal. wallet-api's MAX_BLOB_BYTES refusal 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.readNft return null for 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 NftSigned digest is SHA-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: a valid NFT stays valid across transfers, while a payload copied onto another token, minted under another token type, or front-run to another first owner reads invalid. 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 no coinId/amount every 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 real token-engine/nft-ops.ts and 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_at first-seen-wins is only the legacy fallback for unmarked bindings and is forgeable. See docs/NAMETAG-BINDINGS.md. Runtime name resolution is Nostr-binding-only; receive is always SignaturePredicate(chainPubkey); there is no PROXY addressing anywhere.
  • The self-issued UnicityIdToken mint 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-time nametag:recovered has 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). Returns PeerInfo or null.
  • 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 emits transfer:attention recipient:network-unverified (with transferId: '') and proceeds on the session network; a resolved peer that DOES declare another network is refused with INVALID_RECIPIENT.

Token Registry (Remote + Cached)

  • TokenRegistry singleton provides token metadata (symbol, name, decimals, icons) by coin ID. No bundled data — remote URL per network (NETWORKS[network].tokenRegistryUrl; testnet/testnet2 use unicity-ids.testnet2.json) + persistent cache.
  • The facade consumes it for Asset presentation only; the money path works with coin ids.
  • A Sphere builds and OWNS its registry (#767), disposed by sphere.destroy(). The provider factories no longer call TokenRegistry.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 plain StorageProvider — 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.2 suspectedSpent / knownSpends overlays — the complete list is STORE_KEYS in modules/payments-v2/stores.ts plus the session's refresh token under refreshTokenKey(deviceId) (auth:refresh:<deviceId>, impl/wallet-api-v2/session.ts) plus the delivery port's receive seen-set under DELIVERY_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 legacy isNetworkScopedAddressKey mechanism (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, from core/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 permanent pendingTransfers() row holding its sources reserved, with no error surface. Sphere.clear() is not a mitigation (it calls storage.clear() with no prefix and takes the mnemonic with it). Under the new prefix the latch reads null, noteEpoch takes its previous === null early return, and no restore fires. Pinned by tests/unit/payments-v2/kv-generation.test.ts and a case in tests/integration/sphere-payments-v2-wiring.test.ts. A prefix must never START with a superseded one — the sweep matches by startsWith, so pv2:g2: would have deleted itself.
  • Chat/identity keys stay network-agnostic; storage providers keep their network parameter for the legacy scoped keys.

IndexedDB Databases (Browser)

DatabaseProviderPurpose
sphere-storageIndexedDBStorageProviderWallet 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/FakeWalletApi behavior pins
    • FakeGateway), port contract suites (contracts/{storage,delivery}-port.contract.ts — swappability enforced)
  • tests/aggregator/ — the real engine against a REAL aggregator-go v3, stood up by Testcontainers (npm run test:aggregator; ~1m45s cold). docker/docker-compose.yml is 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 prebuilt ghcr.io/unicitynetwork/aggregator-go image rather than building rocksdb locally. support/aggregatorStack.ts waits for consensus to CERTIFY A ROUND, not merely for health: until it has a reference time the service answers every request SERVICE_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.verify reports the aggregated FAIL (the granular status lives in the SDK's nested trace, which the test walks to name INVALID_TRUSTBASE at 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 and storage/tracked-addresses.ts, among others — the file is the list; npm run test:mutation must 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.ts locks 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_EXPIRED and SERVICE_NOT_READY end keep-open, and a booting gateway is retried through), wire-version.test.ts (a real 2.1.0-encoded token from fixtures/token-sdk-2.1.0.hex is 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_nft wire 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 whose payments getter THROWS exactly like the real one)
  • tests/unit/core/ — Sphere lifecycle, clear, nametag sync/recovery, wallet-api-protocol pins
  • tests/integration/ — Sphere payments wiring (defaults + walletApi config, incl. the superseded-pv2: sweep on composition), per-address KV bleed invariants, kv/file network isolation, wallet lifecycle
  • tests/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.testnet2
  • tests/relay/groupchat-relay.test.ts — NIP-29 relay integration (Docker + remote)

Dependencies

Core (from package.json):

  • @unicitylabs/state-transition-sdk — pinned 3.0.1 (exact; imported only via token-engine/sdk.ts)
  • @unicitylabs/nostr-js-sdk ^0.6.0 — Nostr protocol
  • @noble/hashes ^2, @noble/curves ^2, @noble/ciphers ^2 — cryptography
  • bip39, 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/nodejs imports ws when 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 interface over type for objects
  • Use readonly for immutable properties
  • Async/await over raw promises

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.