# Build a wallet with wallet-toolbox

> For the complete documentation index, see [llms.txt](https://bsvblockchain.com/docs/llms.txt).

Set up a BRC-100 wallet with the Setup helpers of @bsv/wallet-toolbox, run its Monitor and choose where it stores its records.

import BlueTable from '/snippets/BlueTable.jsx';
import ToolboxSetupFlow from '/snippets/ToolboxSetupFlow.jsx';

Start a BRC-100 (BSV Request for Comments 100, the standard interface between apps and wallets) wallet on `@bsv/wallet-toolbox` with its `Setup` helpers, then decide where the wallet keeps its records. At the end, you have a testnet wallet in Node.js with SQLite storage and a running Monitor, plus the calls that open a wallet with the same keys on remote storage or in a browser.

## Before you begin

You need Node.js 22 or newer. The example runs on testnet with a new wallet that holds no coins, so it needs no funding. This page was written against `@bsv/wallet-toolbox` 2.15.1 and `@bsv/wallet-toolbox-client` 2.15.1, with `@bsv/sdk` 4.0.1.

## How it works

The `Setup` class turns the keys in a `.env` file into a complete wallet:

<ToolboxSetupFlow />

How Setup builds a wallet, in four steps: .env holds testnet and Mainnet keys and placeholder API keys, written once by Setup.makeEnv(). Setup.getEnv('test') reads the testnet keys and sets the chain to testnet. Setup.createWalletSQLite builds the key deriver, the storage, the services and the Monitor, then the wallet. setup is the object your code uses: the wallet and every part behind it.

The `setup` object it returns gives you each part by name:

<BlueTable>

| Field | What you use it for |
| --- | --- |
| `wallet` | The BRC-100 wallet. Your code and the apps call its methods, such as `createAction` and `listOutputs` |
| `storage` | The `WalletStorageManager`, which holds the active store and its backups and can switch between them |
| `activeStorage` | The `StorageKnex` provider that writes to the SQLite file |
| `services` | The `Services` the wallet uses on testnet to broadcast, track the chain and look up proofs |
| `monitor` | The Monitor (The toolbox component that broadcasts queued transactions, gathers proofs and repairs wallet state in the background). `Setup` creates it but does not start it |
| `identityKey`, `keyDeriver`, `rootKey` | The keys from `.env`. `identityKey` is the public key that apps see |
| `chain`, `userId` | `test` for testnet, and the ID of the wallet's user record in the store |

</BlueTable>

## Create a testnet wallet

The first step is to create a Node.js project folder with the toolbox, the keys and a wallet that opens on SQLite:

**1. Install the toolbox**

In an empty folder, install `@bsv/wallet-toolbox`:

```bash
npm init -y
npm install @bsv/wallet-toolbox
```

The toolbox installs `@bsv/sdk`, Knex and SQLite with it, so the wallet needs no database server.

**2. Keep the keys out of git**

Add `.gitignore` to the project folder, so the keys and the wallet files never reach a repository:

```text .gitignore
.env
*.sqlite
node_modules
```

**3. Generate the keys**

> The `.env` file holds the private keys of the wallet. Keep it private, never print it, paste it into code or commit it, and use this wallet only on testnet. The file also holds Mainnet keys that this page does not use. Anyone with this file can spend the coins of the wallet.

`Setup.makeEnv()` generates the keys. Save this script as `create-env.mjs` in the same folder, to write them to `.env`:

```javascript create-env.mjs
import { existsSync, writeFileSync } from 'node:fs'
import { Setup } from '@bsv/wallet-toolbox'

if (existsSync('.env')) {
  console.log('.env already exists, nothing was written.')
} else {
  writeFileSync('.env', Setup.makeEnv(), { mode: 0o600 })
  console.log('Wrote the test wallet keys to .env.')
}
```

Run it once with `node create-env.mjs`:

```text
Wrote the test wallet keys to .env.
```

- `.env` holds two testnet keys, two Mainnet keys and placeholder API keys. The wallet on this page uses the first testnet key.
- `{ mode: 0o600 }` lets only your user account read and write `.env` on Linux and macOS.
- The script never prints the keys, and it does not replace an existing `.env`.

**4. Open the wallet**

Create `wallet.mjs`, a module that the other scripts import to open the wallet:

```javascript wallet.mjs
import { Setup } from '@bsv/wallet-toolbox'

process.loadEnvFile('.env')
const env = Setup.getEnv('test')

export const setup = await Setup.createWalletSQLite({
  env,
  filePath: './wallet.sqlite',
  databaseName: 'mywallet'
})
```

- `Setup.getEnv('test')` reads the testnet keys and puts the wallet on testnet. `test` is the name the toolbox uses for testnet.
- `Setup.createWalletSQLite` creates `wallet.sqlite` on the first run and sets up its tables. `databaseName` becomes the name of this store.

**5. Check the wallet**

Write `check.mjs`, which asks the wallet for its identity key, its network and its outputs:

```javascript check.mjs
import { setup } from './wallet.mjs'

const { wallet } = setup

const { publicKey } = await wallet.getPublicKey({ identityKey: true })
console.log('Identity key:', publicKey)

const { network } = await wallet.getNetwork({})
console.log('Network:', network)

const outputs = await wallet.listOutputs({ basket: 'default' })
console.log('Outputs:', outputs)

await wallet.destroy()
```

Run it with `node check.mjs`:

```text
Identity key: 023d8dae...591b10
Network: testnet
Outputs: { totalOutputs: 0, outputs: [] }
```

- `default` is the basket (A named group of outputs the wallet tracks) that holds the coins the wallet spends from. It is empty because the wallet is new.
- `destroy()` closes the storage, so the script can end.

The wallet now answers BRC-100 calls on testnet and keeps its records in `wallet.sqlite`. To give a wallet like this its first coins, follow [Fund the server wallet from BSV Desktop](https://bsvblockchain.com/docs/get-started/quick-start-server/#fund-the-server-wallet-from-bsv-desktop). It uses its own `server-wallet.mjs` module in place of `wallet.mjs`.

## Start the Monitor

With the wallet open, start its Monitor, which finishes the work that wallet methods leave for later, such as delayed broadcasts and Merkle proofs (The proof that a transaction is in a block, checked against the block header). By default, `createAction` leaves the broadcast to the Monitor, so a wallet that sends transactions needs the Monitor running. A script that ends right away needs it too, unless it sends with `acceptDelayedBroadcast: false`.

Create `monitor.mjs`, which starts the Monitor and stops it cleanly on Ctrl+C:

```javascript monitor.mjs
import { setup } from './wallet.mjs'

const { wallet, monitor } = setup

const running = monitor.startTasks()
console.log('Monitor running. Press Ctrl+C to stop.')

process.once('SIGINT', async () => {
  monitor.stopTasks()
  await running
  await wallet.destroy()
  console.log('Monitor stopped.')
})
```

- `startTasks()` runs the Monitor tasks on an interval until `stopTasks()` is called.
- Stop the Monitor before `destroy()`, so no task writes to a closed store.

Run it with `node monitor.mjs`, and press Ctrl+C when you want it to stop:

```text
Monitor running. Press Ctrl+C to stop.
Monitor stopped.
```

With the Monitor running, the wallet broadcasts its queued transactions and collects their proofs on its own. [How the toolbox tracks UTXOs](https://bsvblockchain.com/docs/wallet-dev/wallet-toolbox/utxo-lifecycle/#what-the-monitor-settles-in-the-background) lists what each Monitor task does.

## Choose the storage

Each `Setup` call opens a wallet with the same keys on a different store, with its own records. Pick the store by where the wallet runs:

**SQLite or MySQL**

For a wallet in Node.js, such as a server wallet or a desktop app. The records stay in a database you run, through Knex.

`wallet.mjs` above already uses SQLite:

```javascript
const setup = await Setup.createWalletSQLite({ env, filePath: './wallet.sqlite', databaseName: 'mywallet' })
```

For MySQL, call `Setup.createWalletMySQL({ env, databaseName })` instead. It reads the connection from `MYSQL_CONNECTION` in `.env`, a JSON string with the host, port, user and password, and the schema named by `databaseName` must already exist. Both calls go through `Setup.createWalletKnex`, which accepts any Knex instance in its `knex` argument.

**Remote storage**

For a wallet that keeps its records on a storage server and reaches it over HTTPS with `StorageClient`.

Save this as `remote-wallet.mjs` in the same project:

```javascript remote-wallet.mjs
import { Setup } from '@bsv/wallet-toolbox'

process.loadEnvFile('.env')
const env = Setup.getEnv('test')

const setup = await Setup.createWalletClient({
  env,
  endpointUrl: 'https://go-wallet-testnet-us-1.bsvblockchain.tech'
})

for (const store of setup.storage.getStores()) {
  console.log(store.storageClass, store.endpointURL)
}

await setup.wallet.destroy()
```

Run it with `node remote-wallet.mjs`:

```text
StorageClient https://go-wallet-testnet-us-1.bsvblockchain.tech
```

- `endpointUrl` here is a public testnet storage server, for trying remote storage. It must run on the same network as the wallet. Without `endpointUrl`, the call uses `https://staging-storage.babbage.systems` on testnet.
- Production wallets run their own storage server, as [Run a wallet backend](https://bsvblockchain.com/docs/wallet-dev/infrastructure/) describes.
- The records live on the server, and the keys stay in `.env` on your machine.

**IndexedDB**

For a wallet that runs in a browser and keeps its records on the user's device.

Install the browser package in your web app:

```bash
npm install @bsv/wallet-toolbox-client
```

Then open the wallet with `SetupClient.createWalletIdb`:

```javascript wallet.js
import { SetupClient } from '@bsv/wallet-toolbox-client'

export async function openWallet (rootKeyHex) {
  return await SetupClient.createWalletIdb({
    chain: 'test',
    rootKeyHex,
    databaseName: 'mywallet'
  })
}
```

Open it in the browser and run the checks of `check.mjs` on the wallet it returns. In Chrome on testnet, with a new key, they print:

```text
Identity key: 038524fd...50ba47
Network: testnet
Outputs: { totalOutputs: 0, outputs: [] }
```

- A browser has no `.env`, so `rootKeyHex` comes from the key management of your wallet, such as a key the user unlocks. Never ship a key in the app bundle.
- `databaseName` becomes the name of this store, as with SQLite. The records go to an IndexedDB database on the device named `wallet-toolbox-testnet`.

Whichever store you pick, the wallet methods stay the same. Some `setup` fields change with the store: `createWalletClient` returns `endpointUrl` and no `activeStorage` or `userId`, and the `activeStorage` of `createWalletIdb` is a `StorageIdb`.

The wallet needs its records to recover its outputs, since the keys in `.env` alone cannot rebuild them, so keep a backup store next to the active one. [Plug in your own storage](https://bsvblockchain.com/docs/wallet-dev/wallet-toolbox/storage-adapter/) shows how to add one.

## Next steps

With a working wallet, continue with how it handles its coins and its storage:

- [How the toolbox tracks UTXOs](https://bsvblockchain.com/docs/wallet-dev/wallet-toolbox/utxo-lifecycle/)
- [Plug in your own storage](https://bsvblockchain.com/docs/wallet-dev/wallet-toolbox/storage-adapter/)