Source:
docs/api-jsdoc (working tree)
Top-level SDK for RAILGUN Reloaded. Creates and persists wallets, syncs chain data, aggregates balances and builds transactions.
For the ./node entry, install the native SQLite driver:
npm add @railgun-reloaded/wallet-sdk better-sqlite3
For the ./browser entry, install the SQLite WASM driver:
npm add @railgun-reloaded/wallet-sdk @sqlite.org/sqlite-wasm
See the browser integration fixture for the browser check.
import { randomBytes } from 'node:crypto'
import { Mnemonic, RailgunClient } from '@railgun-reloaded/wallet-sdk/node'
const client = await RailgunClient.create()
const mnemonic = Mnemonic.generate()
const encryptionKey = new Uint8Array(randomBytes(32))
const info = await client.createWallet({
mnemonic,
encryptionKey,
name: 'primary'
})
console.log(info)
// { walletId: '...', name: 'primary', createdAt: Date }
const ctx = await client.loadWallet(info.walletId, encryptionKey)
console.log({
railgunAddress: ctx.railgunAddress, // '0zk1...'
masterPublicKey: ctx.masterPublicKey, // Uint8Array(32)
viewingPublicKey: ctx.viewingPublicKey // Uint8Array(32)
})
await client.close()
Chains 137 and 8453 have a default indexer. For any other chain, pass a
dataSource. For Sepolia, use createDataSource with the Sepolia squid URL.
RailgunClient initializes the underlying cryptography libraries (ed25519,
circomlib, EdDSA) automatically on the first call to loadWallet, decrypt,
or sync. The init is cached, so subsequent calls and additional
RailgunClient instances in the same process share the same one-time setup.
createWallet does not trigger init — it only runs BIP39 validation, ID
derivation, and AES-GCM blob encryption.
To pay the init cost up front — for example at app startup, before serving
any UI that depends on wallet ops — call initialize() explicitly:
const client = await RailgunClient.create()
await client.initialize()
The same effect is available as a stand-alone function for callers that
don't have a client at hand (e.g. direct deriveWalletKeys usage):
import { initializeCrypto } from '@railgun-reloaded/wallet-sdk'
await initializeCrypto()
RailgunClient exposes typed in-process events. balance:update fires after
decrypt() or sync() changes a wallet's notes and cached balances have been
recalculated. Its payload is a fresh full balance snapshot; applications should
calculate any UI delta they need from their own previous snapshot.
Successful no-op decrypt and sync runs do not emit balance:update. Subscribe
to sync:complete when the application needs completion notifications even
when balances did not change.
const stopBalanceUpdates = client.on(
'balance:update',
({ walletId, chainId, balances, notesAdded, notesSpent }) => {
console.log({ walletId, chainId, balances, notesAdded, notesSpent })
},
{ walletId: info.walletId, chainId: 11155111 }
)
const stopSyncCompletion = client.on(
'sync:complete',
({ phase, walletId, chainId }) => {
console.log({ phase, walletId, chainId })
},
{ walletId: info.walletId, chainId: 11155111 }
)
// Remove subscriptions when this view or process no longer needs them.
stopBalanceUpdates()
stopSyncCompletion()
A fresh wallet can bootstrap its canonical historical prefix (deployment block →
endHeight) from an immutable snapshot instead of replaying it through Subsquid.
You assemble the SourceAggregator (and bring snapshot's decodeArtifact); the
SDK owns the protocol — staging snapshot blocks as untrusted state, checking
their commitment trees against the contract, promoting chain.db atomically, and recovering
interrupted attempts. Subsquid then continues from endHeight + 1.
import {
bootstrapSnapshotAtomically,
CommitmentTreeMismatchError,
RailgunEngine
} from '@railgun-reloaded/wallet-sdk/node'
import { SnapshotProvider, SourceAggregator, SubsquidProvider } from '@railgun-reloaded/scanner'
import { decodeArtifact } from '@railgun-reloaded/snapshot'
import { createPublicClient, http } from 'viem'
const publicClient = createPublicClient({ transport: http(archiveRpcURL) })
// Stage + check the commitment trees at endHeight + promote atomically.
// chain ID, RAILGUN version, and deployment start height come from NETWORK_CONFIG.
// The caller owns the data source. The bootstrap does not destroy it.
// A data source must serve one scan at a time.
const dataSource = new SourceAggregator([
new SnapshotProvider({ ipfsHash: cid, gateways, decodeArtifact }),
new SubsquidProvider(subsquidURL)
])
try {
const result = await bootstrapSnapshotAtomically({
chainId: 11155111,
cid,
endHeight, // from the snapshot manifest
dataSource,
publicClient
})
// result.status === 'promoted' | 'skipped'
} catch (error) {
// The snapshot differs from the contract: reject this snapshot.
// error.failures lists every difference. Other errors (RPC, fetch) can be retried.
if (!(error instanceof CommitmentTreeMismatchError)) throw error
} finally {
dataSource.destroy()
}
// Continue from the persisted cursor (endHeight + 1).
const engine = new RailgunEngine({ chainId: 11155111 })
const tailSource = new SourceAggregator([new SubsquidProvider(subsquidURL)])
try {
await engine.scan({ dataSource: tailSource })
} finally {
tailSource.destroy()
}
A chain DB already holding trusted sync state (lastBlockHeight > 0) is left
untouched (status: 'skipped'). The trusted cursor is never advanced before
validation and atomic promotion succeed, so any fetch, integrity, validation, or
promotion failure leaves no trusted state and falls back to a full Subsquid scan.
Interrupted attempts are cleaned up on the next run — no manual chain.db
deletion.
The bootstrap reads treeNumber, nextLeafIndex, merkleRoot and
rootHistory from the RAILGUN proxy at exactly endHeight. Every closed tree
root must be in rootHistory. The latest tree must match nextLeafIndex and
merkleRoot. The RPC must serve state at that block, so an old block needs an
archive node. The bootstrap throws a plain Error when the RPC serves a
different chain.
Both clients have buildUnshield and unshield. The recipient is a public
0x address, not a 0zk address. An unshield pays an ERC20 token. With
ephemeralSigner, it pays the native coin: see BuildUnshieldParams.
buildUnshield(params, chainId) selects notes, proves the transaction, and
returns the unsigned transact call. It does not sign or send. Use it to
sign with your own tooling.unshield(params, chainId) calls buildUnshield, sends the call with
params.signer, waits for the receipt, and returns its Unshield events.
There is no approval step.The client does not include a proving library. For Mopro, use the default
import from @railgun-reloaded/mopro-wasm and first call
await mopro.initialize(). Pass createGroth16ForEngine(mopro) from
@railgun-reloaded/prover as the prover option to RailgunClient.create().
Without a prover, buildUnshield throws ProverNotConfiguredError.
You also supply the circuit artifacts:
params.loadArtifact(variant) returns the artifact for the variant that the
note selection needs, for example from @railgun-reloaded/ipfs-artifact-fetcher.
The client spends only the notes that getBalances puts in the Spendable
bucket. On a PPOI network, each list in the network PPOI config must tag a
note Valid. The client reads the stored tags. It makes no PPOI node call.
Run scan() or sync() first in the same client:
the proof needs the local note commitment tree.
const result = await client.unshield({
walletId,
encryptionKey,
tokenAddress,
amount: 1_000_000n,
recipient: '0x...',
loadArtifact: (variant) => fetchArtifact(variant),
publicClient,
signer
}, 11155111)
refreshPoiStatus(walletId, chainId) refreshes persisted PPOI for received
notes, nonzero sent outputs, and wallet-owned unshields.
getTransactionHistory() reads these results without node requests.
Each entry has a poiStatus: Valid, ProofSubmitted, Missing, Unknown,
Blocked, or NotRequired. Missing output coverage or required-list results
cannot produce Valid. The existing spendState describes received notes.
InvalidMnemonicError — BIP39 validation failed.InvalidEncryptionKeyError — key is not 32 bytes, or decryption auth failed.WalletAlreadyExistsError — (mnemonic, index) collision. .walletId points to the existing wallet.WalletNotFoundError — loadWallet called with unknown id.InvalidUnshieldRecipientError — the unshield recipient is not a public 0x address.InvalidUnshieldAmountError — the unshield amount is zero or negative.InvalidUnshieldTokenError — the unshield token is not a 0x address. .tokenAddress holds the rejected value.SignerAccountError — the unshield or transfer signer holds no account.SignerChainError — the unshield or transfer signer is on another chain. .expectedChainId and .actualChainId hold both chain IDs.ProverNotConfiguredError — buildUnshield called on a client with no prover.NoSpendableNotesError — no note of the token is in the Spendable balance bucket of the network.SolverError (from @railgun-reloaded/utxo-manager) — the eligible notes sum to less than the amount plus the broadcaster fee, or the first transaction cannot pay the whole broadcaster fee.UnknownMerkleRootError — the contract never had the local merkle root. Rescan, or check the RPC node.CommitmentPositionError — a scanned commitment position does not continue the local tree. The local chain store does not match the data source. Rescan from the deployment block. .treeNumber, .expectedPosition, .position and .blockNumber hold the tree, the next local position, the received position and its block.UnshieldEventMissingError — the confirmed unshield receipt has no Unshield event.