npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bsv/wallet-toolbox

v2.18.2

Published

BRC100 conforming wallet, wallet storage and wallet signer components

Readme

BSV Wallet Toolbox

Optional durable profile state (2.18.0 source candidate)

CWIStyleWalletManager and its WalletAuthenticationManager subclass accept an optional host store through setStatePersistence. Attach it before authentication. The host awaits and verifies its own durable commits; saveSnapshot() continues to return bytes and does not itself write device storage. Existing callers that do not attach a store keep that contract. Snapshot v1/v2 and on-chain UMP formats, KDFs, BRC-100 calls, defaults and peer ranges are unchanged.

import type { WalletAuthenticationManager, WalletStatePersistence } from '@bsv/wallet-toolbox'

declare const manager: WalletAuthenticationManager
declare const durableDeviceStore: WalletStatePersistence
manager.setStatePersistence(durableDeviceStore)

The host must store both snapshot and pending-update capabilities privately, partitioned by account, network and service configuration. Never log those bytes. Fence application requests while changing profiles. Activation publishes the new profile ID and underlying wallet together after construction succeeds. Opted-in snapshot restores, profile operations and UMP updates serialize. Public wallet calls are blocked while those operations run or await recovery. A failed builder retains the previous SDK identity; a host builder with external side effects must additionally restore or withhold its own serving runtime.

A UMP update records prepared, submitting, signed and published stages. The built-in interactor signs with noSend, saves the exact signed receipt, then releases the same transaction through the wallet and the overlay. The underlying wallet must retain its staged action so sendWith can release it after restart. Custom interactors opt in with checkpointVersion: 1 and must await the signed checkpoint before any publication.

Funding and input checks run before the signing checkpoint. If planning fails, the manager can clear the prepared update. Destroying the manager clears its in-memory session. The host retains the durable checkpoint for that account.

After an interrupted update, authenticate or restore the original account, then load its retained checkpoint with loadPendingUMPUpdate before serving wallet requests. Call recoverPendingUMPUpdate to verify the exact successor or re-publish the original transaction after checking its owner, fields, unique token output and predecessor input. With Toolbox Wallet or WalletPermissionsManager and locally readable Toolbox storage, a submitting checkpoint can recover the original signed transaction using the operation ID. Recovery saves that receipt before sending it. Custom interactors can implement recoverCheckpoint to recover the same authenticated receipt from their own durable action store. An unknown signing outcome remains pending. Resume an interrupted phone-number change after recovery to finalize its existing rotation.

syncUMPToken() retains its boolean return. getUMPTokenSyncStatus() additionally distinguishes unchanged, updated, authoritative not-found and unknown results. With an attached store, refresh verifies the discovered owner where the interactor supports it, rebuilds the selected runtime and persists the result. An unavailable selected profile requires an explicit choice; it does not silently activate the default. Lookup errors preserve prior state. Applications may retain offline reads from a committed cache, but should block new UMP mutations without a verified current account. retryStatePersistence() retries a device save without publishing.

Adoption is optional and is a minor additive API change. There is no automatic schema migration: the host owns its storage and upgrade/restore tests. Before rolling back, stop new operations, reconcile pending updates with the original qualified artifact, retain their checkpoints and export a current legacy-compatible snapshot. Do not discard a checkpoint or restore a spent predecessor as current. Source merge, package publication and application release remain separate actions.

Certificate pagination

The 2.17.0 source candidate reports listCertificates totalCertificates as the size of the matching set at every offset, including full and empty later pages in IndexedDB. Non-empty final pages use the skipped rows plus the page; other pages count without a page window. User, deletion, type and certifier filters and returned certificate fields are unchanged. Upgrade the affected local storage package or remote Storage service to receive corrected totals. No API, wire or schema migration is required.

Permission-module spending authorization

Spending authorization accounts for the inputs and outputs that permission modules pass to the wallet, including token funding and change. Caller input descriptions remain attached to their outpoints when a module reorders inputs. Output descriptions follow the metadata retained by copied or reordered outputs, including outputs with identical scripts and amounts. New module entries with no caller description use the existing description fallback. Requested-output verification, exact wallet-spend checks and storage service-charge accounting remain enforced. No API, wire or stored-data migration is required.

Setup factory action batching

The 2.17.0 source candidate adds optional actionBatchMode to the Setup and SetupClient factory arguments. Select legacy when your application broadcasts its own noSend transactions and needs the existing per-action storage path:

import { SetupClient, type SetupClientWalletArgs } from '@bsv/wallet-toolbox'

declare const options: SetupClientWalletArgs
const { wallet } = await SetupClient.createWallet({ ...options, actionBatchMode: 'legacy' })

The browser client exposes the same SetupClient option. Omission keeps auto, including its existing storage-capability negotiation and fallback. When batching is available, related signed noSend actions can remain staged until a subsequent batch commit. The new option does not recover previously discarded batches or change signing, BRC-100 calls or database schemas. Existing consumers need no migration; package publication and consumer upgrades are separate steps.

Sync and recovery candidate

PR569 adds bounded wallet sync, portable recovery and durable primary handoff. Use the implementation map for current entry points and the acceptance contract for the concrete merge requirements. Historical source checkpoints and test campaign logs remain in Git history. Deployment and native TTN acceptance evidence are maintained by network-ops; a passing component test does not establish a platform or production deployment result.

Diagnosing foreground BEEF verification failures

The staging integration validates and repairs selected funding proofs before returning input BEEF to the signer. Failed canonical recovery retains the typed proof error and releases the ordinary failed allocation; it cannot return a stale proof as successful funding evidence. Remote calls remain outside the allocation transaction. Mobile SDK forwarding retains every public root export as its original external SDK object. No wire, schema or resource limit changes.

Foreground Storage processing retains its signed transaction before proof verification and submission. An error response therefore does not prove that no transaction exists or that a replacement spend is safe. Reconcile the existing action before creating another payment. With a WalletLogger enabled, failed verification now records the last root's height, expected root and accepted/declined/pending result, or the structural stage when no root was checked. Provider exceptions remain exceptions rather than invalid-proof verdicts; public error identities and all verification checks are preserved. This diagnostic distinction does not identify a historical missing-header or wrong-root cause when that provider response was never retained. Publication of these source changes and upgrading remote Storage are separate operations.

Remote storage timeouts

StorageClient accepts optional authFetchOptions in its existing third constructor argument. This applies to the Node, browser and mobile packages. Omitting it preserves the installed SDK's defaults.

import { type WalletInterface } from '@bsv/sdk'
import { StorageClient } from '@bsv/wallet-toolbox'

declare const wallet: WalletInterface
const storage = new StorageClient(wallet, 'https://storage.example/rpc', {
  authFetchOptions: {
    requestTimeoutMs: 60_000,
    responseTimeoutMs: 60_000
  }
})

requestTimeoutMs bounds transport fetch and body consumption; responseTimeoutMs independently bounds the authenticated response waiter. Both default to 30 seconds. The response-wait option requires an SDK release containing AuthFetchOptions.responseTimeoutMs; older supported SDKs retain their existing behavior and option types. The declared SDK peer ranges remain unchanged. Other certificate/session deadlines and caller operation deadlines are independent. A local timeout does not undo a server-side financial write; reconcile its outcome before deciding whether to resubmit it.

Optional local transaction recovery

The 2.15.0 source candidate adds explicit local SQLite recovery controllers as separate deep imports. Action recovery retains one fixed-layout, two-phase noSend allocation, prepared transaction and final signed bytes. Funding recovery binds one BRC-29 payment to its acquisition and atomically retains wallet ownership, monitor work and a durable receipt. Ordinary BRC-100 calls and defaults are unchanged. The new funding capability requires SDK 3.3.0; legacy root and existing deep consumers retain the declared older SDK peer compatibility.

Install the auxiliary schemas explicitly in the active local wallet database. Reopen them after restart, and preserve a consistent whole database plus wallet keys. These journals are not included in ordinary entity backup/sync or BRC-38/39 exports. Browser, mobile, IndexedDB and remote provider wrappers do not acquire these capabilities by upgrading. During rollback, stop new operations, reconcile outstanding work and retain the original journals; deleting them loses recovery.

See local action recovery and local funding recovery for construction limits, deep imports, verification and unresolved service obligations. A local receipt does not prove settlement, a content license or protected delivery.

Internal recovery JSON ownership uses a fresh call-local context for scalar, array and record checks. It retains the same deterministic stored bytes, error identities, descriptor/prototype/cycle checks and fixed resource bounds; the refactor requires no caller or stored-format migration. It never retains ownership state or authority between calls.

Receiving already-broadcast payments

The 2.14.9 source candidate completes broadcast results even when storage already marks the request unmined or completed. This fixes first receipt without a mining proof on shared storage, and the same result path when another storage worker advances the request before the broadcast result refresh. The stored advanced state remains intact; unsuccessful provider results still reject receipt and do not credit new recipient outputs. Repeated successful receipt remains idempotent. A payment carrying its valid mining proof follows the existing proof path without rebroadcast.

SQL storage now serializes receipt ownership across independent processes through a durable user/TXID claim. The migration preserves legacy transaction and output rows, including historical duplicates, while adding the claim table. Ambiguous historical receipts still require separate reconciliation; this change prevents a new same-recipient overlap from creating another local credit. Back up and preflight the database before rollout, then upgrade all storage instances together; an older instance can bypass the new receipt claim. Pending claims recover after their database-timed lease expires. No public API or wire migration is required. Browser IndexedDB does not use the SQL receipt claim. Source versions are candidates until published through the protected release workflow; upgrading an app alone does not upgrade its remote storage server.

The 2.15.3 source candidate restores legacy AtomicBEEF normalization before the strict argument framing check. An exactly decoded envelope may contain unrelated branches from an older sender; internalization retains only its declared payment and required dependencies, then reruns the unchanged SDK validator. Truncated or trailing data, an absent subject and missing dependencies remain rejected. Normal chain proof, Script, remittance ownership and receipt checks still run. SQL receipt admission and manager forwarding use canonical bytes without changing other caller arguments. No API, wire or schema migration is required. Upgrade the wallet host and remote Storage separately; a source candidate is not a deployed release. For a previously rejected receipt, reconcile the original TXID before retrying the original import. Do not create a replacement payment or rebroadcast a mined one.

Reorg proof recovery

TaskReorg compares the latest 12 heights after each processed tip, including when ChainTracks events are unavailable. It journals pending ranges before remote work, retries unresolved heights every minute without requiring a new tip, and recovers observed gaps after monitor downtime. Each attempt reviews at most recentDepth fresh heights and recentDepth pending heights; the default is 12 and zero disables this fallback. Ranges are compacted without dropping pending work; compaction may recheck intervening heights.

The lagged TaskReviewProvenTxs audit starts at the minimum stored proof height on the built-in SQL and IndexedDB providers, leaves an empty wallet uncheckpointed, repairs older checkpoints in empty history, and retains fair bounded retries through restart and tip retreat. Custom storage providers may override getProvenTxsReviewStartHeight; its safe default starts at zero when proofs exist, so custom providers can retain a longer initial audit. Recent rolling scans and these forward cursors do not establish detection of an arbitrary historical reorg below both cursors; deeper ancestry reconciliation remains separate work.

Coordinate the upgrade of all monitor writers sharing a storage database: older versions do not understand compact retry checkpoints and may overwrite pending recovery work. The durability evidence covers one active Monitor owner with sequential restart; concurrent checkpoint writers are unqualified, and this change adds no ownership lock. Public Storage API serving topology is independent of the internal monitor worker's ownership.

No SQL schema or manual data rewrite is required. IndexedDB automatically upgrades to version 7 to add a nonunique proven_txs.height index, avoiding a proof-blob scan during audit bootstrap. Close other connections using older code before upgrading, and retain a backup of browser wallet data. Reverting to code opening an older IndexedDB version requires a compatible restore or a forward fix. Source merge does not publish a package or upgrade a running wallet.

Backup and recovery: keep both keys and wallet data

A root key or seed alone is not a complete BRC-100 wallet backup. Users need recoverable key material and wallet records, including derivation metadata, transactions and basketed outputs. A database copy or BRC-39 file preserves data; it does not replace root-key recovery. Wallet-manager snapshots can contain keys and must be protected as secrets, but are not storage backups.

Wallet builders must provide both recovery paths, explain what their product backs up, and test restoration after device or storage-provider loss. Storage replication helps availability but does not replace versioned, independently accessible backups and a tested restore procedure.

These guides cover the recovery design. The measurements below describe specific tests and do not establish that every wallet product has complete key-and-data disaster recovery.

The unpublished 2.15 candidate captures BRC-38 source settings, wallet identity and standard table closure in one local provider read view. SQLite and IndexedDB tests cover independent writes during capture. A local MySQL 8.4.11 fixture verifies repeatable-read isolation, read-only enforcement and connection cleanup without changing session defaults. Exact proof and checkpoint reads inside these provider-owned snapshots retain the consistent view without requesting write locks; ordinary writable transactions retain their row locks. The critical wallet-read-snapshot-consistency mutation target covers the complete transaction classification and lookup methods with all six retained, portable and generated read-view suites. Generated schedules exercise direct/retained failure cleanup, cross-provider tokens, partial/exact selectors and independent writable work; ordinary lookups also preserve returned checkpoint date/boolean normalization. The original property strength and zero-uncovered/invalid/unexecuted mutation gates apply. Deployed/PXC recovery remains unqualified. Custom providers opt in with supportsReadSnapshot and readSnapshot. Use the export option requireSnapshot: true to refuse unsupported capture; old custom-provider calls retain their documented caller-quiesced fallback. Recognized optional nullable JSON fields are omitted in a detached archive copy; array entries and meaningful falsy values are preserved. The legacy helpers still materialize the full document/file, and IndexedDB writers wait during capture. Run pnpm test:snapshot-archive-crash for native SQLite process recovery and pnpm test:snapshot-archive-mysql for the disposable MySQL fixture from this package. Local MySQL qualification uses Docker Desktop and requires the pinned image already present. Required wallet CI shard 1 provisions that same immutable image on its ephemeral Linux runner, then runs both native fixtures from the same-head build before Jest. Hosted MySQL mode accepts only the local default Unix socket. The fixture uses a unique ownership label, loopback port, bounded memory/CPU/process count and temporary data volume; individual Docker calls, readiness and the child proof have deadlines. Failure or cancellation drains owned work and attempts exact-owner cleanup before reporting its outcome; unproved cleanup fails qualification. Other wallet shards do not start MySQL.

The unpublished candidate adds optional @bsv/wallet-toolbox/portable and @bsv/wallet-toolbox/portable/node streaming entries. They require explicit resource ceilings, coherent source validation and private staging. They preserve the existing archive format and materialized APIs. Private-file appends check the actual byte length before copying and own the supplied bytes before asynchronous writes, including Node Buffers and Buffer subviews. See the streaming contracts and remaining limits before integrating them. Full issue #544 production qualification remains open.

The candidate also contains internal SQL journal primitives for exact revisions, bounded metadata pages, bootstrap with a durable explicit row allowance, source-table observers, and recovery of an interrupted journal installation. Owned generations also bind explicit receipt capacity/lifetime policy; exact receipts are persisted, read and collected in bounded caller-owned transactions. Receipts prove a captured prefix and cannot reopen a lost retained view. The internal openSnapshotJournalSource controller reserves two owned native connections before its writer barrier, pins the profile and generation, persists the receipt, and publishes after receipt commit and closure verification. It requires an existing file-backed WAL database with better-sqlite3 or a static mysql2 connection; other drivers refuse before pool construction. Physical cleanup retains provider admission, and an unproved close fences further sources. If source work and transaction cleanup both fail, the ownership error retains the original source failure and each rollback cause. Run pnpm test:snapshot-journal-crash for the SQLite process-loss fixture and pnpm test:snapshot-journal-mysql for the isolated MySQL client/server-process recovery fixtures. Internal floor transactions reserve the global writer clock before current receipt locks and cannot pass a live receipt's prefix. Tombstone collection examines at most 256 primary-key rows, including live and newer records, and binds its cursor to one epoch, floor and stream. Native WAL/RC/RR checks cover twenty-four real process-loss boundaries. The internal maintainSnapshotJournal provider controller validates the complete owned generation and excludes the configured migration owner before each short floor or collection transaction. It shares source admission through cancellation, rollback and physical cleanup; failed cleanup fences further retained admission. The working candidate registers source and receiver migrations, provides bounded generation-aware delta pages and destination staging, and keeps raw source sync-state provenance separate from native checkpoints. Its explicit local SQL WalletStorageManager.reconcileJournal iterator uses fair background admission for each destination transaction, checks the current manager selection, and reports destination-persisted byte/row counters. A short source SQL primary fence is acquired in the scheduled commit and remains held through that one commit's physical cleanup. Source reads, proof preparation and observers run between commits. Lost replies re-read committed custody; cancellation reports stopped only after physical source closure. A complete window does not activate a restored primary. Fresh full scans can repair interrupted custody in the same profile after source-generation or destination-primary replacement. V2 persists the producing generation with each association, refuses old mappings as current IDs, and sweeps unobserved associations after all current rows have been applied. Creation ownership can follow a renumbered source ID only when the actual native preimage and parents still match recorded ownership. Staged archive merge and restore preserve archived managed-change policy; any later operational migration is separate from restoration. The existing aggregate restore helper retains its historical policy upgrade.

The working local SQL candidate also negotiates journal support freshly in ordinary push, pull and backup operations. Acknowledged windows can advance incrementally within the same actual source and destination generation. Primary transitions copy conflicting data outside foreground admission, then check every contributing source's current data and primary under short physical fences before selecting the destination. Cancelled operations retain durable progress and drain their source before reporting stopped. Journal provider and checkpoint types are available from the server, client and mobile entry points without importing SQL implementations into their public data contracts.

The current working source also implements authenticated remote snapshot destinations, packed-IDB sources and inactive restore/publication, bounded large fields, full native composition/recovery and device backup lifecycle contracts. These additions remain functionally unqualified. The current implementation map records their entry points and qualification wiring; the candidate delivery guide records migration, compatibility and rollback requirements. Production readiness still requires complete current-system qualification, including physical quotas and the required host/device evidence.

Required wallet CI shard 1 also runs both native journal entry points from the same-head build after the existing archive fixtures. The complete journal mutation aggregate and native recovery checks are separate qualification requirements.

Both native archive entry points include interrupted auxiliary profile and numeric relation migrations through the real migrator. The numeric relation fixture terminates seven migration boundaries, repairs the abandoned migration lock and compares recovered membership with an independent source-table oracle. The MySQL entry point also observes relation writer/reader lock ordering under both supported isolation levels and checks late composite pages against 8,192 interleaved map rows per relation. It requires bounded handler reads and the auxiliary primary-key range plan. These synthetic fixture results qualify the tested engine/configuration; deployed PXC remains a separate acceptance gate.

SQL providers also expose supportsRetainedReadSnapshot / openReadSnapshot for a local view held across idle reads, with one view per provider, one read at a time, and bounded lifetime/cancellation. Await closed/close() for physical cleanup. This low-level view occupies a caller-pool connection; driver deadlines remain separate and a single-connection pool cannot serve other work until release. The durable local SQL backup integration below adds bounded pages and uses a dedicated reader to preserve foreground capacity. IndexedDB and remote RPC do not expose retained views. See the retained view contract. The SQL candidate also includes bounded archive staging for the ongoing remote snapshot implementation. This internal component does not add an authenticated export endpoint or a browser/mobile database adapter. Its metadata-only receipt directory binds every page and all thirteen table positions to the archive root before arbitrary-table reads; each payload is checked against that verified directory. The original binding JSON bytes are preserved as the hash preimage. This verifies transport integrity, not the source's honesty or portable transaction/proof semantics. An additional internal SQL request table binds retries to an immutable deadline and archive, reserves capacity before source acquisition, and retains bounded terminal receipts through cleanup. Its internal capture controller shares the provider's single owned reader slot, publishes readiness after physical cleanup, and drains cancellation/shutdown. Completed archives survive controller replacement; failed cleanup fences admission and retains its reservation. The candidate now adds a negotiated authenticated archive transport on migrated WAL/MySQL servers and both client variants, with bounded responses and durable admission/status. getSnapshotArchiveTransport(identityKey) is a low-level API; remote row reading, ordinary sync/export adoption and portable validation remain incomplete. Server or client snapshotArchives: false, or provider snapshotSync: false, disables this capability. See the transport contract. The candidate's additive source-owner table now retains request/archive capacity until the exact controller acknowledges physical source cleanup. Cross-controller cancellation fences the next page; pending cleanup reports an error and keeps its reservation. Do not mix older candidate binaries or remove the owner schema while captures remain. The reader now waits for an exact completion acknowledgement through bounded pending-cleanup polling, preserving independent failures. The additive guard migration now permits exact-owner recovery after physical source closure, using stable local SQLite WAL guard files or a same-server MySQL connection lock. Older unguarded owners remain reserved, and changed backend identities fail closed. An unproved native close also fences further snapshot sources on that provider, even after its read promise settles. Ordinary read failures remain retryable after physical cleanup succeeds. Keep the guard files and bindings intact and drain captures before downgrade. The server reader capability remains unadvertised pending complete qualification. The auxiliary profile-key migration preserves standard-table indexes and legacy OFFSET ordering while adding indexed snapshot selection for eight direct tables. Its triggers track independent writers; bounded bootstrap batches survive restart, and readers enable the index only from a complete migration in their retained view. See the migration and recovery contract. The separate numeric relation migration indexes label/tag maps while retaining both parent ownership bases, tombstones and cross-profile inconsistency checks. It preserves composite cursor and legacy OFFSET order, resumes bounded bootstrap after interruption, and bounds MySQL paging before and after statistics refresh with the auxiliary primary index and indexed source lookups. See its migration and recovery contract. The certificate-field migration adds collation-preserving composite keys and independent direct/parent ownership. Empty text keys, interrupted bootstrap and case-only renames retain their source meaning. It leaves standard indexes and legacy cursor order intact; readers require the complete migration in their pinned view. See the certificate migration and recovery contract. The global proof/request migration adds exact profile reference counts and presence guards, with resumable bootstrap and retained ordinary/archive reads. Direct and request-based proof references remain independent; removing the last reference collects its auxiliary presence guard. Standard rows, text comparisons, indexes and cursor/portable bytes remain unchanged. See the global migration and recovery contract. The additive SQLite conflict-repair migration installs metadata-bound witnesses, rebuilds all four index families in bounded resumable pages, and retires obsolete auxiliary rows without changing standard wallet data. Reader adoption follows journal publication inside the pinned view. Legacy ownership checks distinguish triggers from views even when their names coincide; foreign readers of auxiliary data refuse migration. Preserve partial state for recovery; ordinary downgrade refuses, while explicit dropAllData() retains its destructive contract. See the SQLite generation migration contract. SQLite identity and journal-observer validation read fresh bounded metadata pages for each operation. Metadata is grouped in one pass, and installed schema definitions are checked in pages of at most sixteen. Exact metadata, DDL, validation order and error identities are retained; there is no cross-operation schema cache. The existing schema and BRC-38/39 formats need no migration. Global-index validation groups fresh table and index metadata only inside its pinned SQLite transaction. Individual reads remain the fallback outside a transaction, for unsupported drivers or oversized groups; the public table validator retains its original three-argument contract. The complete sync/streaming/restore program remains in progress on #569.

Backup and sync: tested results

Live E2E testing used a large wallet in the native desktop client, covering complete local copies, restart recovery, and repeat sync. Transfer size and oversized-record recovery were measured separately with synthetic fixtures. The latest proof-recovery follow-up has synthetic HTTP and read-only source-data validation; its live full-backup retest is pending.

| Test | Verified result | | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | | Full native desktop restores | Two complete copies; identical entity counts. Second run: 12m 50s vs 16m 30s (22.3% less time). | | Retained local backup | Completed after cancellation, a connectivity pause, and restart recovery; all 12 entity-store counts preserved on another restart. | | Local reads and repeat sync | Transaction/output reads passed; sampled transaction bytes matched; repeat sync made 0 inserts, 0 updates. | | Transfer size | 62.7% smaller encoded byte payload in a synthetic fixture. | | Oversized single record | 7 MiB restored in real browser IndexedDB, matching SHA-256; interrupted upload resumed, corrupt download rejected, repeat sync unchanged. | | Automated integration | Authenticated HTTP backup/restore, interrupted pages, lost acknowledgements, binary byte round-trips, user isolation, and legacy compatibility covered. |

Timing compares successive candidates, not a controlled comparison against upstream main. Byte verification was sampled, not database-wide. See test methods and limits for details.

SQLite migration recovery

SQLite migration handling introduced in 2.13.2 runs transactional migration DDL and the migration journal update together. The unpublished profile-index and numeric relation, certificate-field and global proof/request migrations are explicit resumable exceptions: auxiliary keys and progress commit in bounded batches before its final migration journal entry. Foreign-key enforcement is disabled before the migration transaction for table rebuilds and restored after success or failure. Failed transactional migrations can be retried after reopening the database without partial schema objects from that attempt. These resumable index migrations instead retain their verified auxiliary objects and committed progress; see its linked recovery contract before retrying an interrupted migrator. MySQL's existing transaction configuration is unchanged.

Transactional migration handling prevents partial table rebuilds. It does not automatically repair a store already left with unjournaled schema objects by an older version. Preserve the database and verified backups and reconcile the exact schema and migration journal before recovery; do not delete journal rows or wallet data blindly.

Postgres storage

StorageKnex runs on Postgres through the knex pg client. Install pg in the application and pass a Postgres knex:

import { knex as makeKnex } from 'knex'

const knex = makeKnex({ client: 'pg', connection: { host, port, user, password, database } })
const storage = new StorageKnex({ ...StorageKnex.defaultOptions(), chain: 'main', knex })

ChaintracksStorageKnex and adminStats do not support Postgres. Snapshot auxiliary migrations, including packet-label rollback, remain no-ops on Postgres; SQLite and MySQL retain their forward-recovery downgrade safeguards.

Overview

The Wallet Toolbox is the reference implementation of the BRC-100 wallet interface. It connects the BSV SDK's cryptographic primitives to real storage backends, network services, and signing flows so that application developers don't have to wire these layers together themselves.

BSV Desktop and BSV Browser are the BSV Association reference wallet applications built around this interface. Vendor distributions, including Babbage's Metanet Desktop / Metanet Explorer and Hudos Browser, can implement the same BRC-100 interface against their own product packaging and service defaults.

Local contact trust

Applications may install a ContactSource on WalletArgs to resolve identities from the user's local contacts before querying the certificate overlay. Installing that source is an explicit personal trust-policy decision: a saved contact is locally authoritative in the same sense as a self-signed certificate or locally installed trust anchor. Its default infinite trust means “the user's independent validation overrides third-party trust thresholds,” not “an external certifier proved this identity.”

The authority is scoped to the wallet user who saved the identity-key association and to that wallet's local labels and metadata. Authentication or encryption of the contact store proves that the wallet retained the user's decision; it does not independently prove the real-world identity, and the infinite-trust value must not be exported as a universal claim for other users.

Contact results retain the discovery result shape for compatibility, but default to type contact and carry empty serial, signature, and revocation-outpoint fields. Consumers must not present those fields as third-party certification. Connect ContactSource only to local, authenticated storage whose records the user has deliberately saved or validated; never populate it directly from unauthenticated network data. Pass forceRefresh: true to identity discovery when the application specifically needs to bypass local contact authority and query the overlay.

Fiat exchange-rate trust boundary

Wallet Toolbox treats exchange-rate providers and custom service adapters as untrusted financial inputs. Rates must use the supported currency codes, be finite, positive, and bounded, use USD base with an exact USD rate of 1, and carry a valid timestamp no more than five minutes in the future. Malformed or missing requested rates are never merged into the wallet cache.

The default provider transport accepts only credential-free public HTTPS, pins validated DNS answers in Node.js, rejects redirects and private/special addresses, and enforces a 15-second deadline plus a 256 KiB response limit. fiatExchangeRatesFetch is an explicitly trusted escape hatch for tests or controlled local development; production applications should retain the default transport.

ARC and Arcade provider configuration

ARC-compatible broadcaster configuration is snapshotted when the provider is constructed. API keys, callback tokens, deployment IDs, callback URLs, and custom headers therefore keep the exact reviewed values even if the caller later mutates its configuration object. Custom headers must be a plain accessor-free own-data map with valid HTTP token names and bounded string values; inherited fields and getters are rejected without being used.

The provider URL and an injected httpClient remain explicit application or operator trust decisions. Do not derive them from transaction, peer, or other untrusted input. Reconstruct the provider to rotate credentials or headers; mutating the original configuration object does not change a live provider.

Importing legacy P2PKH outputs

Setup.fundWalletFromP2PKHOutpoints and its client equivalent validate each canonical outpoint, fetched transaction ID, P2PKH ownership script, atomic signing target, and final wallet transaction before reporting success. Provider downloads are deadline-bound, redirect-free, and size-bounded; recursive BEEF construction also limits depth, graph size, aggregate source bytes, and the number of requested outpoints. If an application already has authenticated BEEF, pass it explicitly to avoid relying on public transaction-data services. Do not accept a wallet result that omits the transaction bytes needed for this binding.

What's Inside

| Module | Description | | ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------ | | Wallet | Full BRC-100 wallet — action creation, signing, certificate management, identity discovery, output tracking | | Storage | Pluggable persistence with three backends: SQLite/MySQL (via Knex), IndexedDB (browser/mobile), and remote (client/server over HTTP) | | Services | Network layer — ARC transaction broadcasting, chain tracking (Chaintracks), merkle proof verification, UTXO lookups via WhatsOnChain | | Monitor | Background daemon that watches pending transactions, rebroadcasts failures, handles chain reorganizations, and manages proof acquisition | | Signer | WalletSigner bridges any BRC-100 wallet to the SDK's Transaction signing interface | | Key Management | PrivilegedKeyManager for secure key storage with Shamir secret sharing and obfuscation; protocol-based key derivation per BRC-42/43 | | Permissions | WalletPermissionsManager for fine-grained per-app, per-protocol permission control with grouped approval flows | | MockChain | In-memory blockchain for testing — mock mining, UTXO tracking, and merkle proof generation without a network | | Entropy | EntropyCollector gathers mouse/touch entropy for high-quality randomness in browser environments |

Durable permission grants queue their internal token transaction for delayed broadcast, so permission approval does not inherit network-broadcast latency. The funding planner prefers settled change and uses queued permission ancestry only as a last resort, keeping the application path fast without hiding funds.

Permission-token basket membership and tags are discovery hints, not authority. Before using a stored token, the manager binds it to its exact BEEF outpoint and one-satoshi output, verifies the canonical PushDrop field signature and locally derived locking key, strictly decodes every signed grant field, and rechecks the requested filters against that signed content. Unsigned, foreign-wallet, substituted, malformed, or mislabeled rows grant no permission. Token issuance, renewal, coalescing, and revocation also bind every requested input and output to the final wallet transaction; a partial-action reference never authorizes a different transaction. When the underlying Wallet Toolbox signer adds a storage service charge, its exact wallet-funded amount is carried locally into the spending check so the charge is visible and counted in authorization. This metadata is deliberately not a BRC-100 wire extension. Since 2.14.1, it lives in a shared local WeakMap rather than on the public result object, preserving exact accounting across separately loaded bundles while allowing strict binary result validation. Upgrade the wallet host and permission manager together. If an older host reports a result-serialization failure, check its transaction history before retrying: the wallet may already have created or completed the action.

Permission modules may transform calls with onRequest and onResponse, or own a P-scheme's semantics with the optional handleRequest(request, next) hook. A semantic handler can return the normal BRC-100 result directly; if it needs the underlying wallet operation, next is guarded so it can be invoked at most once. Existing transformation-only modules remain compatible. The standalone @bsv/ecpm-permission-module demonstrates this extension by implementing p ecpm point multiplication through getPublicKey, without a new BRC-100 method or wire message.

Immediate actions prefer completed, then unproven, then sending change. A pathological settled plan is compared with pending alternatives by exact serialized BEEF plus transaction bytes; queued ancestry is used only when it is necessary or smaller. Pending change is never withheld, so queued work cannot strand the balance behind a large reserved input.

sendWith transaction IDs form one atomic broadcast set: the wallet never silently slices that set into separately submitted groups. A set is limited to 1,000 unique transactions, including a transaction created or signed by the current call. Oversized or noncanonical requests are rejected before storage commit. The background monitor bounds both discovery and re-expansion of older queued batches; an oversized legacy batch is skipped as a whole and reported for operator recovery rather than partially broadcast.

Setup.makeEnv() returns a development .env template containing newly generated private keys but never prints it. Callers must deliberately write the returned text to a protected local file and must not route it through ordinary application, CI, or shared terminal logs.

Packages

The toolbox publishes three npm packages from this repo:

Sync performance and recovery

Sync pages start at 64 records and adapt after successful commits toward a five-second marginal-work budget. A bounded history separates fixed read and commit overhead from per-record work, so slow fixed latency does not collapse large copies to one record per request. A two-record probe permits recovery from the single-record floor. Proof-bearing pages cap growth at 128 records; metadata pages can grow to 1,000, while provider byte/item ceilings still apply. These are work estimates, not deadlines: an individual proof or unavailable dependency can still take longer. The server checks at most eight proofs concurrently and waits for all started checks to settle on failure before rejecting the page. Every proof still passes transaction, Merkle path, active-root and active-header validation before a merge. An authenticated HTTP regression covers 250 synthetic proofs and confirms that an invalid follow-up page cannot change the committed checkpoint. Stale proofs can be reconciled through another provider, but only after the replacement passes the same transaction, membership and active-chain checks. Transaction bytes, wallet references and source cursor timestamps are preserved. Corrected destination proofs receive a fresh local timestamp for incremental replication. Unverifiable replacements stop the page with a recovery message; no record is silently skipped.

A read-only deployment-host sample of 250 proofs took 42.6 seconds with sequential validation and 5.58 seconds with bounded concurrency, with the same 250 root and 250 header checks. This measures validation only, not full-copy throughput. Timeouts remain possible during dependency outages; writes are never blindly replayed, and resumed sync rereads durable destination progress.

Adaptive snapshot paging isolates observations by table, separates fixed page latency from marginal row cost, and uses the actual committed payload charge to forecast the next request. A known next table starts at the original 64-row budget; repeated observations of the same table retain their history. A newly expensive page immediately shrinks the next work budget even when recent pages have equal row counts; sustained recovery remains smoothed to avoid request-size oscillation. Caller row and byte limits remain authoritative, and an oversized individual row still refuses without advancing the checkpoint. These forecasts do not establish a WAL, allocation or memory bound. This change needs no wire or schema migration. Full #544 qualification and production performance evidence remain required.

The adaptive page controller and optional validated-proof lookup add a small client bundle cost. The artifact measurements and limits include the combined upstream security fixes. These are explicit feature costs; the RPC validation coordinator remains excluded from browser/mobile bundles.

The transfer extension is included in the published 2.13.2 graph. Older 2.12.0 providers have no record-transfer methods. Check exact build provenance and authenticated runtime capabilities, not a version label alone. An oversized record on a legacy source cannot be rescued by upgrading only its destination; upgrade the source before retrying. Records exceeding the negotiated 64 MiB frame limit fail safely without being skipped or advancing their checkpoint.

Large individual records can use the negotiated bounded transfer protocol, with durable staging, integrity verification and checkpoint replay protection. Its authenticated HTTP/SQLite/IndexedDB regression exercises a 7 MiB binary record, an interrupted upload across client/server restart, a lost part acknowledgement, corrupted download rejection and a verified restore followed by an unchanged resync. The current frame limit is 64 MiB; legacy providers must be upgraded to use it. It also passes with a one-second delay on every authenticated transport send; that models added latency, not a measured bandwidth limit or a real mobile network. These synthetic regressions are separate from the large-wallet timing evidence above.

Wallet storage replication applies each received page and its durable sync checkpoint in one provider transaction. IndexedDB and Knex therefore avoid per-record transaction startup, and a failed page rolls back without advancing the checkpoint. Sources fill each bounded page with adaptive, size-aware reads, and Knex storage adds user-scoped proof lookup indexes. Clients may set includeTotals on a sync-chunk request to receive optional source record totals for exact progress reporting. Older providers ignore the hint, and totals are not counted unless requested. New clients also send the writer-local sync-state identifier selected during provider registration. New providers use it to disambiguate legacy duplicate checkpoints, while either side remains compatible with older protocol peers. When a provider rejects a sync page because its serialized RPC response exceeds the service ceiling, remote clients retry the read-only request with a smaller chunk budget and remember the working limit for the rest of the session.

Output synchronization requires a local mapping for every non-null source basket ID. A missing mapping rejects the page so its transaction and checkpoint can roll back; retry after transferring the missing basket. Newer source updates apply basket changes, including explicit removal. Same-time or older updates preserve local relinquishment. Previously unbasketed records require a verified newer source update to repair; no heuristic rewrites existing wallet state.

StorageKnex.getRawTxOfKnownValidTransaction() can read a cold store while the caller holds a transaction, including SQLite's single-connection pool. Settings are read through that transaction without entering the shared cache or starting prepared-BEEF background work; ordinary makeAvailable() remains the explicit store-wide startup operation. An absent optional inputBEEF does not prevent returning stored raw transaction bytes.

IndexedDB schema version 6 adds a non-unique transaction-ID/user index. Sync identity lookups, commissions, and relation maps use selective indexes or exact keys instead of scanning the growing wallet for each row. Proof batch checks resolve requested transaction IDs through the existing index, preserving primary-key ordering, pagination, and proof-validation rules. Existing bytes and legacy duplicate transaction IDs are preserved. Databases upgrade automatically; older clients that open schema version 5 cannot reopen an upgraded database, so keep a compatible client when retaining a local backup.

Updated servers advertise syncCheckpointVersion: 1 in runtime settings. Compatible clients fetch a compact checkpoint once, then use the checkpoint returned by each committed page. The complete ID mapping remains durable on the writer and is no longer downloaded before every page. Older providers use the existing full-state path; authentication, gateway, and malformed checkpoint errors remain failures rather than compatibility fallbacks. A retry starts from the writer's durable checkpoint. includeNextCheckpoint is optional, and legacy requests retain their existing response shape.

When a reader negotiates binary JSON, large schema-defined sync byte fields are encoded as base64 instead of decimal number arrays. Legacy readers retain the existing arrays; unrelated numeric fields are never reinterpreted as bytes. Clients with binaryRequests: true use the same compact representation for sync uploads after the server negotiates binary request support. The default request setting is unchanged. Binary JSON parsing preserves the existing marker and escaping rules while avoiding a JavaScript reviver callback for every scalar byte. The SDK also prevents certificate work or session recovery from dispatching another request after the caller's authentication deadline has expired. This does not cancel a write already received by a server or automatically replay failed writes.

Run the authenticated candidate-provider sync benchmark with:

pnpm bench:storage-sync

Set WALLET_TOOLBOX_BENCH_MYSQL=true, MYSQL_CONNECTION, and optionally WALLET_TOOLBOX_BENCH_MYSQL_DATABASE to exercise the same fixture through a MySQL-backed provider. The benchmark reports HTTP p50/p95 latency and the source-query limits used to fill a 250-record page; it is observational rather than a cross-machine latency SLA. It also compares the old reviver with the current parser on identical synthetic data and measures checkpoint size. On one local Node 24 run, a 1 MiB numeric-array fixture (3.74 MB of JSON) measured 501.2 ms versus 10.1 ms median parsing time across nine alternating samples. A synthetic 50,000-entry mapping occupied 678,850 bytes; its compact checkpoint occupied 432 bytes. These are CPU and payload measurements, not a claim of the same end-to-end network speedup. Encoding the synthetic byte field through the negotiated sync codec reduced its JSON payload from 3,743,771 to 1,398,163 bytes (62.7%).

Retained integration tests cover authenticated HTTP backup and complete restore into a fresh IndexedDB store, multipage progression, no-change resync, interruption/resume, user isolation, malformed checkpoints, and legacy-provider fallback. Live deployment results must be reported separately with the tested revision and scope; a partial page sample is not a full restore verification.

A native desktop integration run against candidate runtime a88d18abf14b75a3227016bfd947d5a08b3ee236 completed a full remote-to-local copy in 769.5 seconds, compared with 990.3 seconds for the preceding candidate run with identical entity counts. Remote reads took 619.2 seconds, local writes 146.0 seconds, and measurement 4.1 seconds. Proof-page writes fell from 75.7 to 9.8 seconds after indexed preflight lookup. These are sequential observations, not a controlled full-wallet comparison against upstream main. The all-state 100 ms timer probe reported p95 delay of 908 ms; foreground focus was not recorded, so this does not establish foreground UI latency. Separate 90-second native foreground probes during a retained backup measured p95 delays of 5 ms for transactions, 8 ms for outputs, 10 ms for heavier output pages, and 5 ms for proof requests. Their maxima were 60, 51, 298, and 62 ms respectively; these samples are not a whole-copy latency guarantee. The retained-backup test also verified cancellation at a page boundary and automatic checkpoint recovery after a full native app restart. Development testing required refreshing Vite's cached linked dependencies to load the candidate schema consistently. See PR486 for final integration completion and release evidence. Personal deployment and wallet details are retained privately, outside this repository.

listOutputs reports totalOutputs as the full matching result count on every page for both Knex and IndexedDB storage, including short final pages and pages requested at or past the end of the result set.

Resumable pulls and foreground access

WalletStorageManager.syncFromReaderResumable(identityKey, reader, options) adds per-page progress and cancellation without changing the existing sync method signatures. The result reports completed or cancelled, page and row counts, the last acknowledged checkpoint, and the selected execution mode.

The new resumable API defaults to a 256 KiB rough page target, with an explicit ceiling up to 10 MB. Existing sync methods retain their previous defaults.

const cancellation = new AbortController()
const result = await storage.syncFromReaderResumable(identityKey, reader, {
  signal: cancellation.signal,
  maxItems: 128,
  maxRoughSize: 262144,
  onProgress: progress => console.log(progress.state, progress.pages)
})
// A later invocation loads durable destination progress, including any page
// whose acknowledgement was lost. Do not replay a saved request manually.

Local SQLite/MySQL and IndexedDB destinations advertise storageAccess.version 1 with atomic sync checkpoints. Their paged pull reads and prepares one source page outside manager write ownership, then queues its atomic data/checkpoint commit. Network-backed proof checks finish before that queue is acquired; the commit rejects changed proof records. Payloads are detached during preparation, and a prepared page can only be consumed once. Foreground operations can run between pages and during source/proof I/O. Supported reads share up to eight slots; writers remain exclusive. A waiting background page gets a turn within eight foreground grants or after one second of waiting at the next release. This bounds queue preference, not the duration of a provider operation.

Cancellation before a commit discards that page. Cancellation during a commit waits for its acknowledgement, reports the committed checkpoint, then stops. Source I/O also settles before the stopped result: custom providers must supply their own I/O deadlines. Failures propagate without blind write replay; restart loads the durable checkpoint. Changing the selected primary fences an older session before its next write. Concurrent copies of the same source cannot both commit the same checkpoint. Progress observers receive independent checkpoint copies and run outside page ownership in paged mode.

Missing capabilities, remote destinations, self-copies and primary reconciliation retain exclusive execution. Supported ordinary local SQL copies use the durable snapshot path described below. The legacy atomic-page capability probe retains its serialized fallback; snapshot validation and I/O failures reject. Page ceilings are rough encoded size hints; the existing negotiated per-record transfer bounds still apply to large records. One page is in flight, and progress does not accumulate wallet records or per-record logs. Legacy source pagination retains the existing eventual replication contract. Supported local SQL sources use one coherent retained view; the destination remains a merged replica. Remote snapshot handles and streaming portable archives require their separate consistency and format contracts. The existing timestamp boundary is inclusive: an unchanged copy can reread rows sharing the final timestamp, including an entire same-timestamp import. Those rows are not rewritten. This protects late same-time arrivals; a coherent source revision/snapshot is needed to eliminate that boundary traffic safely. Smaller maxRoughSize values (for example 262144) reduce transient authenticated HTTP memory and event-loop work for constrained devices, at the cost of more pages.

Every live sync checks declared network chains before registering a destination user or checkpoint. A missing or unrecognized chain is not inferred. Thrown and returned provider errors take precedence over done, counters and checkpoint hints; unfinished pages without durable progress stop instead of spinning. WERR_NETWORK_CHAIN and ProcessSyncChunkResult.error remain compatible.

Canonical proof recovery during actions

When services are configured, selected-change BEEF is checked before returning to the signer, including embedded ancestry and prepared artifacts. The actual send/monitor path checks its rebuilt bundle as well. Valid graphs avoid extra proof-record reads and copies; checks run with at most eight operations in flight. Stale roots trigger bounded canonical lookups. Replacement transaction bytes, Merkle membership, root and active header must agree before use.

SQLite/MySQL and IndexedDB persist verified corrections with a compare-and-set against the original proof, and invalidate prepared artifacts in the same transaction. A concurrent repair is never overwritten. Custom providers may implement compareAndSetProvenTxProof; the default repairs only the outgoing graph. Failed recovery retains the source records, stops before broadcast, and returns WERR_INVALID_MERKLE_ROOT with its txid, root and height across JSON-RPC. Failed construction releases its funding reservation through the existing failed-action cleanup; it does not mark the input spent without evidence.

Standalone storage construction without configured services retains its offline contract; its caller must validate before signing or broadcasting. This change does not audit historical block-hash metadata or repair every stored proof: BEEF root validity and an operator's historical-store audit remain distinct.

Profile update failures

CWIStyleWalletManager.addProfile and deleteProfile commit the local profile list when the replacement UMP token is published. A factor-decryption or publication failure preserves the previous list, so a failed creation can be retried with the same name. Concurrent creations reserve names without regard to case until each attempt settles. A failed deletion of the active profile attempts to restore that profile and preserves the original update error if restoration also fails.

Restoring the active wallet can fail after publication has succeeded. In that case, the token and profile list already contain the change, and the default profile may remain active. Inspect listProfiles() before retrying and switch to an available profile as needed. This bookkeeping fix does not correct the underlying factor-decryption error; diagnose that error separately.

UMP account continuity and phone changes

Argon2id password derivation uses a proven-ready host backend when one is registered with registerArgon2idBackend. This lets React Native applications perform the memory-hard operation asynchronously in native code. Browser and Node runtimes prefer hash-wasm; when WebAssembly is unavailable, Wallet Toolbox falls back to an asynchronously yielding JavaScript implementation with the same parameters and output. Existing UMP v3 tokens remain interoperable and do not need migration; users do not need to enable a device or browser setting. A selected host backend is authoritative, so a derivation error or malformed output is surface