Sphere SDK
A modular TypeScript SDK for Unicity wallet operations (Unicity state transition network).
Features
- Wallet Management - BIP39/BIP32 key derivation; optional password encryption (PBKDF2)
- Payments - Engine-certified token transfers, delivered via the wallet-api mailbox (
DeliveryProviderport); concurrent-send safety (SpendQueue); self-healing coin selection - Invoicing / Accounting (experimental — not production-ready, not enabled in the Sphere wallet) - On-chain invoice lifecycle with payment attribution, auto-return, privacy-preserving hashed invoice IDs; invoices travel as v2 data-token blobs (hex strings) —
createInvoice()returns the blob,importInvoice()accepts it - Token Swaps - P2P atomic swaps via escrow with DM-based negotiation protocol
- Payment Requests - Request payments with async response tracking
- Market (Intents) - Signed intent bulletin board with semantic search and live feed
- Group Chat - NIP-29 relay-based group messaging with moderation
- Messaging (Nostr) - NIP-17 DMs + NIP-29 group chat and nametag publishing — messaging only; not the v2 payment rail
- Multi-Address - HD address derivation (BIP32/BIP44)
- Token Validation - Engine-based token verification (trust base + spent check via the v2 gateway)
- Connect Protocol - dApp ↔ wallet communication via
ConnectClient/ConnectHost(browser extension + popup) - CLI - Comprehensive command-line interface with shell auto-completion
Installation
npm install @unicitylabs/sphere-sdkQuick Start Guides
Choose your platform:
| Platform | Guide | Required | Optional |
|---|---|---|---|
| Browser | QUICKSTART-BROWSER.md | SDK only | IndexedDB storage |
| Node.js | QUICKSTART-NODEJS.md | SDK + ws |
File storage |
| CLI | @unicity-sphere/cli | Separate package | - |
| dApp integration | CONNECT.md | SDK only | Sphere extension |
CLI (Command Line Interface)
The CLI has moved to a dedicated package: @unicity-sphere/cli.
npm install -g @unicity-sphere/cli
sphere --helpSee docs/QUICKSTART-CLI.md for the full command reference.
Quick Start
v2 setup is two provider layers, not one.
createBrowserProviders/createNodeProvidersbuild only the base (storage + transport + oracle). You must then add the wallet-api rails withcreateWalletApiProviders— that is what gives the wallet its delivery (mailbox) and token-storage ports. Skipping it does not error; you silently get a wallet that cannot send or receive v2 transfers. This single step is what trips most integrators up.
import { Sphere } from '@unicitylabs/sphere-sdk';
import { createBrowserProviders } from '@unicitylabs/sphere-sdk/impl/browser';
import { createWalletApiProviders } from '@unicitylabs/sphere-sdk/impl/shared/wallet-api';
// 1. Base providers: storage + transport + oracle. `network` is REQUIRED here (no default).
// The testnet2 gateway key is PUBLIC (not a secret); it is required at runtime for send/mint.
const base = createBrowserProviders({
network: 'testnet', // alias of testnet2 (networkId 4)
oracle: { apiKey: 'sk_ddc3cfcc001e4a28ac3fad7407f99590' }, // public testnet2 key
});
// 2. Add the v2 wallet-api rails: mailbox delivery + server token storage + client.
// Returns { ...base, delivery, walletApi, tokenStorage }. THIS is the step v1 docs omitted.
const providers = createWalletApiProviders(base, {
baseUrl: 'https://wallet-api.unicity.network', // your wallet-api deployment (testnet2)
network: 'testnet2',
deviceId: 'my-stable-device-id', // persist this to avoid re-auth each launch
});
// 3. Init the wallet (auto-creates one if none exists).
const { sphere, created, generatedMnemonic } = await Sphere.init({
...providers,
autoGenerate: true,
});
if (created && generatedMnemonic) {
console.log('SAVE THIS RECOVERY PHRASE:', generatedMnemonic);
}
// 4. Send — engine-driven, certified on-chain. The recipient needs a published identity
// (chain pubkey), e.g. a registered Unicity ID; otherwise send fails with INVALID_RECIPIENT.
const result = await sphere.payments.send({
recipient: '@alice',
amount: '1000000', // decimal STRING — never a JS number
coinId: 'UCT', // a symbol auto-resolves to its hex coinId
memo: 'hello',
});
console.log(result.status); // 'completed'
// result.deliveryPending === true is NORMAL, not a failure: the token is certified on-chain but
// the recipient's mailbox delivery was deferred and will land on retry (see "Send result" below).
// 5. Receive — incoming transfers arrive automatically via the delivery port (background poll +
// wake). To drain explicitly (e.g. a CLI/batch app), call receive():
const { transfers } = await sphere.payments.receive(undefined, (t) => {
console.log('received', t.amount, t.coinId);
});
console.log(await sphere.payments.getAssets());What just happened (the provider model)
A v2 wallet is composed from swappable ports, layered in two steps:
| Layer | Built by | Ports it supplies |
|---|---|---|
| Base | createBrowserProviders / createNodeProviders |
storage (wallet state), transport (Nostr — messaging/nametags only), oracle (gateway/trust base) |
| wallet-api rails | createWalletApiProviders(base, …) |
delivery (mailbox), walletApi (REST client), tokenStorage (server inventory) |
- Delivery is a port, not Nostr. In v2, transfers are certified on-chain by the token engine and the finished token is delivered through the wallet-api mailbox (
WalletApiMailboxProvider). Nostr carries messaging/nametags — it does not move payments. - Custody.
createWalletApiProvidersuses server custody ('inventory'): the wallet-api holds your token inventory. For own-custody (your app keeps token storage, wallet-api is delivery-only), swap increateOwnStorageWalletApiProviders(custody'external'). networkplacement. Required oncreateBrowserProviders/createNodeProviders(throwsINVALID_CONFIGif absent); optional/informational onSphere.init.
For manual/advanced provider wiring, see Custom Providers Configuration. For the deeper integration guide, see docs/INTEGRATION.md.
Send result (TransferResult)
send() resolves with a TransferResult:
| Field | Meaning |
|---|---|
status |
'completed' on success. ('pending' | 'submitted' | 'confirmed' | 'delivered' | 'failed' also exist for in-flight/terminal states.) |
deliveryPending |
true when the spend is certified on-chain but the recipient's mailbox delivery was deferred (a full inbox / transient outage). This is success, not failure — the token is finalized and the finished blob is journaled and re-delivered automatically. |
deliveryState |
'landed' (delivered) or 'pending-delivery' (deferred, as above). |
Treat status === 'completed' as sent. Use deliveryPending only to show a "delivery pending" hint — never as an error. A stale-but-spent source is self-healed (the next live coin is selected automatically).
Handling send() rejections — CERTIFICATION_UNCONFIRMED is NOT re-sendable (money-safety)
send() throws for genuine failures (INVALID_RECIPIENT, insufficient balance, a TransferConflictError lost race) and for one indeterminate case you must handle specially: a ProofUnconfirmedError (code: 'CERTIFICATION_UNCONFIRMED', mayHaveCertified: true). It means the spend may already be on-chain but the proof fetch was inconclusive — the SDK keeps the intent open and completes it later under the same transferId.
⚠️ Never re-issuesend()onCERTIFICATION_UNCONFIRMED. A freshsend()mints a newtransferIdon a different source, so the original resumes and the retry sends → the recipient is double-paid. Treat it as "sent, pending confirmation."- Recovery is
resumeOpenIntents()— it replays the open intent under the sametransferId(recovers the proof + delivery, or records the spend if a rival tx won; never a second spend). It runs automatically at session start (Sphere.init/Sphere.load/ re-sign-in). A long-running bot that doesn't re-init should callsphere.payments.resumeOpenIntents()on startup and periodically — it returns{ resumed, conflicted, failed }.
import { isSphereError } from '@unicitylabs/sphere-sdk';
try {
const result = await sphere.payments.send({ recipient: '@bob', amount, coinId });
// result.status === 'completed' (or result.deliveryPending === true) → sent
} catch (err) {
if (isSphereError(err) && err.code === 'CERTIFICATION_UNCONFIRMED') {
// Possibly already sent on-chain — DO NOT re-send. Resume finishes it
// (auto at next sign-in, or: await sphere.payments.resumeOpenIntents()).
} else {
// genuine failure — safe to surface to the user / retry
}
}
transferModeonTransferRequestis deprecated — accepted for backwards-compat but ignored (v2 has a single engine-driven path).
Network Configuration
The SDK ships network presets that configure all services automatically. network is required — there is no default:
| Network | Aggregator (gateway) | Nostr Relay |
|---|---|---|
testnet |
gateway.testnet2.unicity.network (v2) | nostr-relay.testnet.unicity.network |
testnet2 |
alias of testnet (same configuration) |
nostr-relay.testnet.unicity.network |
mainnet |
aggregator.unicity.network (v1-era) | relay.unicity.network (+ public relays) |
dev |
dev-aggregator.dyndns.org (v1-era) | nostr-relay.testnet.unicity.network |
v1 → v2 cutover:
testnetnow points at testnet2, the v2 state-transition gateway network (network id 4, taken from the trust base; own testnet2 token registry). The oldgoggregator-testtestnet spoke the removed v1 protocol and is gone.mainnetanddevstill point at v1-era aggregators — wallet operations that move money (send,mintFungibleToken, invoices) fail loudly (AGGREGATOR_ERROR) on those networks until their gateways are cut over to the v2 protocol. The only supported transfer wire payload is the finished v2 token blob — incoming v1-era payloads are dropped with an explicit error log, so peers must run a >= 0.8 wallet to send to this wallet.
// Use testnet for all services
const providers = createBrowserProviders({ network: 'testnet' });
// Override specific services while using network preset
const providers = createBrowserProviders({
network: 'testnet',
oracle: { url: 'https://custom-gateway.example.com' }, // custom v2 gateway
});API Key
The SDK bundles no default API key. Pass the gateway key via oracle: { apiKey } — without it, gateway requests are unauthenticated and money movement on testnet2 fails.
const providers = createBrowserProviders({
network: 'testnet',
oracle: { apiKey: 'sk_...' },
});The testnet2 key is not a secret — it is published in .env.example and safe to keep in docs and client code. A mainnet key, by contrast, IS a secret: keep it in your deploy environment only.
Testnet2 endpoints (the values we build with)
The testnet preset wires most of these automatically — you only pass network, oracle.apiKey, and the wallet-api baseUrl. The full set, for reference and manual wiring:
| What | Value |
|---|---|
| Network | testnet (alias testnet2), networkId 4 |
| Aggregator / gateway (token engine) | https://gateway.testnet2.unicity.network |
| Aggregator API key (public — not a secret) | sk_ddc3cfcc001e4a28ac3fad7407f99590 |
| wallet-api (delivery + token storage) | https://wallet-api.unicity.network |
| Nostr relay (messaging / nametags) | wss://nostr-relay.testnet.unicity.network |
| Group-chat relay (NIP-29) | wss://sphere-relay.unicity.network |
| Token registry | https://raw.githubusercontent.com/unicitynetwork/unicity-ids/refs/heads/main/unicity-ids.testnet2.json |
The aggregator key above is the testnet2 key only and is safe in client code; a mainnet key is a real secret. mainnet/dev still point at v1-era aggregators and cannot serve the v2 engine yet (AGGREGATOR_ERROR).
Price Provider (Optional)
Enable fiat price display by adding a price config. Currently supports CoinGecko API (free and pro tiers).
// With CoinGecko (free tier, no API key)
const providers = createBrowserProviders({
network: 'testnet',
price: { platform: 'coingecko' },
});
// With CoinGecko Pro
const providers = createBrowserProviders({
network: 'testnet',
price: { platform: 'coingecko', apiKey: 'CG-xxx' },
});
const { sphere } = await Sphere.init({ ...providers, autoGenerate: true });
// Total portfolio value in USD
const totalUsd = await sphere.payments.getFiatBalance();
// 1523.45
// Assets with price data
const assets = await sphere.payments.getAssets();
// [{ coinId, symbol, totalAmount, priceUsd: 97500, fiatValueUsd: 975.00, change24h: 2.3, ... }]Without price config, getFiatBalance() returns null and price fields in getAssets() are null. All other functionality works normally. (getBalance() is the synchronous per-coin balance accessor — it returns Asset[] without price data.)
You can also set the price provider after initialization:
import { createPriceProvider } from '@unicitylabs/sphere-sdk';
sphere.setPriceProvider(createPriceProvider({
platform: 'coingecko',
apiKey: 'CG-xxx',
}));Test Tokens on Testnet (Self-Mint)
There is no faucet. On testnet you top up your wallet by self-minting fungible tokens via the v2 token engine — mintFungibleToken(coinIdHex, amount) mints a finished token directly to this wallet:
import { getCoinIdBySymbol } from '@unicitylabs/sphere-sdk';
// Resolve the coin's hex id from the token registry (or pass a hex coinId directly)
const coinId = getCoinIdBySymbol('UCT');
const result = await sphere.payments.mintFungibleToken(coinId!, 1000n);
if (result.success) {
console.log('Minted token:', result.tokenId);
} else {
console.error('Mint failed:', result.error);
}Note: Minting requires a working v2 oracle config (trust base + gateway URL + API key) — it fails with an error result otherwise. See API Key above.
Multi-Address Support
The SDK supports HD (Hierarchical Deterministic) wallets with multiple addresses:
// Get current address index
const currentIndex = sphere.getCurrentAddressIndex(); // 0
// Switch to a different address
await sphere.switchToAddress(1);
console.log(sphere.identity?.directAddress); // DIRECT://... (address at index 1)
// Register nametag for this address (independent per address)
await sphere.registerNametag('bob');
// Switch back to first address
await sphere.switchToAddress(0);
// Get nametag for specific address
const bobNametag = sphere.getNametagForAddress(1); // 'bob'
// Get all address nametags
const allNametags = sphere.getAllAddressNametags();
// Map { 0 => 'alice', 1 => 'bob' }
// Derive address without switching (for display/receiving)
const addr2 = sphere.deriveAddress(2);
console.log(addr2.address, addr2.publicKey);Identity Properties
Important: The DIRECT address is the primary address for the Unicity network.
interface Identity {
chainPubkey: string; // 33-byte compressed secp256k1 public key
directAddress?: string; // DIRECT address (DIRECT://...) - PRIMARY ADDRESS
ipnsName?: string; // IPNS name for token sync
nametag?: string; // Registered nametag (@username)
}
// Access identity - use directAddress as primary
console.log(sphere.identity?.directAddress); // DIRECT://0000be36... (PRIMARY)
console.log(sphere.identity?.nametag); // alice (human-readable)
console.log(sphere.identity?.chainPubkey); // 02abc123... (33-byte compressed)Address Change Event
// Listen for address switches
sphere.on('identity:changed', (event) => {
console.log('Switched to address index:', event.data.addressIndex);
console.log('L3 address:', event.data.directAddress);
console.log('Chain pubkey:', event.data.chainPubkey);
console.log('Nametag:', event.data.nametag);
});
// Listen for nametag recovery (when importing wallet)
sphere.on('nametag:recovered', (event) => {
console.log('Recovered nametag from Nostr:', event.data.nametag);
});Payment Requests
Request payments from others with response tracking:
// Send payment request
const result = await sphere.payments.sendPaymentRequest('@bob', {
amount: '1000000',
coinId: 'UCT',
message: 'Payment for order #1234',
});
// Wait for response (with 2 minute timeout)
if (result.success) {
const response = await sphere.payments.waitForPaymentResponse(result.requestId!, 120000);
if (response.responseType === 'paid') {
console.log('Payment received! Transfer:', response.transferId);
}
}
// Or subscribe to responses
sphere.payments.onPaymentRequestResponse((response) => {
console.log(`Response: ${response.responseType}`);
});
// Handle incoming payment requests
sphere.payments.onPaymentRequest((request) => {
console.log(`${request.senderNametag} requests ${request.amount} ${request.symbol}`);
// Accept and pay
await sphere.payments.payPaymentRequest(request.id);
// Or reject
await sphere.payments.rejectPaymentRequest(request.id);
});Group Chat (NIP-29)
Relay-based group messaging using the NIP-29 protocol. The module embeds its own Nostr connection separate from the wallet transport.
Enabling Group Chat
// Enable with network defaults (wss://sphere-relay.unicity.network)
const { sphere } = await Sphere.init({
...providers,
autoGenerate: true,
groupChat: true,
});
// Enable with custom relay
const { sphere } = await Sphere.init({
...providers,
autoGenerate: true,
groupChat: { relays: ['wss://my-nip29-relay.com'] },
});
// Access the module
const gc = sphere.groupChat!;Connection
// Connect to the NIP-29 relay
await gc.connect();
console.log('Connected:', gc.getConnectionStatus());
// Check if current user is a relay admin
const isRelayAdmin = await gc.isCurrentUserRelayAdmin();Groups
import { GroupVisibility } from '@unicitylabs/sphere-sdk';
// Create a public group
const group = await gc.createGroup({
name: 'General',
description: 'Public discussion',
});
// Create a private group
const privateGroup = await gc.createGroup({
name: 'Team',
visibility: GroupVisibility.PRIVATE,
});
// Create a write-restricted group (only admins/writers can post)
const announcements = await gc.createGroup({
name: 'Announcements',
writeRestricted: true,
});
// Discover and join
const available = await gc.fetchAvailableGroups(); // public groups on relay
await gc.joinGroup(group.id);
// Join private group with invite
await gc.joinGroup(privateGroup.id, inviteCode);
// List joined groups
const groups = gc.getGroups();
// Leave or delete
await gc.leaveGroup(group.id);
await gc.deleteGroup(group.id); // admin onlyMessaging
// Send a message
const msg = await gc.sendMessage(group.id, 'Hello!');
// Reply to a message
await gc.sendMessage(group.id, 'Agreed', { replyToId: msg.id });
// Fetch messages from relay
const messages = await gc.fetchMessages(group.id, { limit: 50 });
// Get locally cached messages
const cached = gc.getMessages(group.id);
// Listen for new messages in real-time
const unsubscribe = gc.onMessage((message) => {
console.log(`[${message.groupId}] ${message.senderPubkey}: ${message.content}`);
});Members & Moderation
// Get members
const members = gc.getMembers(group.id);
// Check roles
gc.isCurrentUserAdmin(group.id); // boolean
gc.isCurrentUserModerator(group.id); // boolean
await gc.canModerateGroup(group.id); // includes relay admin check
gc.canWriteToGroup(group.id); // false if write-restricted and not admin/moderator
// Moderate (requires admin/moderator role)
await gc.kickUser(group.id, userPubkey, 'reason');
await gc.deleteMessage(group.id, messageId);Invites (Private Groups)
// Create invite code (admin only)
const invite = await gc.createInvite(group.id);
// Share invite code, recipient joins with:
await gc.joinGroup(group.id, invite);Unread Counts
const total = gc.getTotalUnreadCount();
gc.markGroupAsRead(group.id);Key Types
interface GroupData {
id: string;
relayUrl: string;
name: string;
description?: string;
visibility: GroupVisibility; // 'PUBLIC' | 'PRIVATE'
writeRestricted?: boolean; // Only admins and moderators can post
memberCount?: number;
unreadCount?: number;
lastMessageTime?: number;
lastMessageText?: string;
}
interface GroupMessageData {
id?: string;
groupId: string;
content: string;
timestamp: number;
senderPubkey: string;
senderNametag?: string;
replyToId?: string;
}
interface GroupMemberData {
pubkey: string;
groupId: string;
role: GroupRole; // 'ADMIN' | 'MODERATOR' | 'MEMBER'
nametag?: string;
joinedAt: number;
}Direct Messages (NIP-17)
End-to-end encrypted DMs via NIP-17 gift wrap, accessed through sphere.communications:
// Send a DM (by nametag or pubkey)
await sphere.communications.sendDM('@alice', 'Hello!');
// Listen for incoming DMs
sphere.communications.onDirectMessage((msg) => {
console.log(`From ${msg.senderNametag ?? msg.senderPubkey}: ${msg.content}`);
});DM History on Connect
By default, the SDK resumes from the last processed DM timestamp (persisted in storage). On first connect, it starts from "now" — no historical replay.
Use dmSince to control how far back to fetch DMs on first connect:
const { sphere } = await Sphere.init({
...providers,
autoGenerate: true,
dmSince: Math.floor(Date.now() / 1000) - 86400, // last 24 hours
});Once the SDK processes DMs, the timestamp is persisted and dmSince is ignored on subsequent connects.
Ephemeral Mode (No Caching)
For anonymous agents or LLM bots that don't need message history, disable DM caching:
const { sphere } = await Sphere.init({
...providers,
communications: { cacheMessages: false },
});
// Stream-only: receive, process, forget
sphere.communications.onDirectMessage((msg) => {
processAndReply(msg);
});
// sendDM still works — message is sent but not stored locally
await sphere.communications.sendDM('@alice', 'response');When cacheMessages is false:
onDirectMessage()handlers andmessage:dmevents fire normally- Messages are never stored in memory or persisted to storage
getConversation()/getConversations()return empty results- Deduplication is skipped (duplicate relay deliveries may trigger duplicate events)