# Send messages with @bsv/message-box-client

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

@bsv/message-box-client sends and receives encrypted messages and payments between identities on the BSV blockchain through a MessageBox host.

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

Use `@bsv/message-box-client` to send and receive messages and payments between identities, so two users can exchange them without being online at the same time. A MessageBox host (A server that stores each message until its recipient reads it) holds each message. At the end of this page you have run a script that sends, reads and acknowledges a message and another that sends and accepts a 100-satoshi payment, both on testnet with [BSV Desktop](https://bsvblockchain.com/docs/wallets/bsv-desktop/). For the full walkthrough, follow [Send messages between users](https://bsvblockchain.com/docs/guides/messaging/).

## Install

The latest version on npm is 2.7.0, with the status Stable. It needs Node.js 22 or newer and `@bsv/sdk`. This page was written against `@bsv/message-box-client` 2.7.0 and `@bsv/sdk` 4.0.1. The examples use top-level `await` and run with `tsx`, so use an ES module project (`npm pkg set type=module`). In your project folder, run:

```bash
npm install @bsv/message-box-client@2.7.0 @bsv/sdk@4.0.1
npm install -D tsx
```

## What the package includes

The package covers messages, payments and the permissions that control who can send them:

<BlueTable>

| Piece | What it does |
| --- | --- |
| `MessageBoxClient` | Sends a message to an identity key (The public key that identifies a user. Other users send to it), lists the messages in a box and acknowledges them. Also sends one message to up to 100 recipients with `sendMessageToRecipients`, which stores the body as plain text, and receives messages as they arrive with `listenForLiveMessages` and `sendLiveMessage` |
| `PeerPayClient` | Sends a payment between users as a message, and accepts or rejects the payments it receives |
| Box permissions, `setMessageBoxPermission` | Lets a recipient block a sender with `recipientFee: -1`, or ask a sender to pay a fee for each message |

</BlueTable>

A message goes to an identity key and waits in a box that belongs to that identity. Only the recipient reads and acknowledges it. A third identity that asks for the same box name sees nothing. The client encrypts the body of a message with the wallet, so the host stores only ciphertext. A batch sent with `sendMessageToRecipients` is the exception, because it cannot be encrypted.

## Example on testnet

The example runs on testnet with [BSV Desktop](https://bsvblockchain.com/docs/wallets/bsv-desktop/) open. It sends a message and a payment to your own identity key. A message costs nothing, and a payment spends testnet satoshis.

> BSV Desktop must be on testnet with some testnet coins. A new BSV Desktop wallet opens on Mainnet, where coins have real value, so switch it to testnet and fund it from a faucet first, as the [Quick Start](https://bsvblockchain.com/docs/get-started/quick-start-browser/) shows. The default host is a shared service, so do not send personal or sensitive data through it.

**1. Create the message script**

Create `message-box.ts`. It sends a message, reads it and acknowledges only that message, so any other message in the box stays:

```ts message-box.ts
import { MessageBoxClient } from '@bsv/message-box-client'
import { WalletClient } from '@bsv/sdk'

const wallet = new WalletClient('auto', 'localhost')
const client = new MessageBoxClient({ walletClient: wallet, networkPreset: 'testnet' })

const { publicKey: me } = await wallet.getPublicKey({ identityKey: true })

const sent = await client.sendMessage({
  recipient: me,
  messageBox: 'inbox',
  body: { text: 'Hello from my app' }
})
console.log(sent.status, sent.messageId)

const messages = await client.listMessages({ messageBox: 'inbox' })
const mine = messages.filter(m => m.messageId === sent.messageId)
console.log(mine.map(m => m.body))

await client.acknowledgeMessage({ messageIds: [sent.messageId] })
```

**2. Run it and check the output**

Run the script:

```bash
npx tsx message-box.ts
```

It prints `success` and the message ID, then the decrypted body:

```text
success 796aee760b91d405ba9458e0beb6db45a345fd0d28d8b1f2b1c6a386806843ac
[ { text: 'Hello from my app' } ]
```

Note these details about the script:

- The second argument of `WalletClient` is the originator, the name BSV Desktop shows for your app. Without it, a Node script cannot reach the wallet. The client then fails with `Identity key retrieval failed`.
- `listMessages` returns each message with `messageId`, `body`, `sender`, `createdAt` and `updatedAt`. The field names use camel case.
- `acknowledgeMessage` deletes the messages you pass from the box, so acknowledge only messages your app has handled. Acknowledging the same IDs again fails with `Failed to acknowledge messages on all hosts:`.

**3. Create the payment script**

`PeerPayClient` sends a payment as a message. Create `peerpay.ts`. It pays 100 satoshis and accepts that payment, and no other payment waiting for you:

```ts peerpay.ts
import { PeerPayClient } from '@bsv/message-box-client'
import { WalletClient } from '@bsv/sdk'

const wallet = new WalletClient('auto', 'localhost')
const { publicKey: me } = await wallet.getPublicKey({ identityKey: true })

const peerPay = new PeerPayClient({
  walletClient: wallet,
  messageBoxHost: 'https://message-box-us-1.bsvb.tech',
  originator: 'localhost'
})

await peerPay.sendPayment({ recipient: me, amount: 100 })
const incoming = await peerPay.listIncomingPayments()
const payment = incoming.find(p => p.sender === me && p.token.amount === 100)
if (!payment) throw new Error('The payment did not arrive')

const accepted = await peerPay.acceptPayment(payment)
console.log(payment.token.amount, accepted.paymentResult?.accepted)
```

**4. Run it and approve the payment**

Run the script:

```bash
npx tsx peerpay.ts
```

`sendPayment` opens a spending request in BSV Desktop for the amount plus the network fee. A blockchain transaction cannot be undone once you approve it. The script then prints the amount and the result of the acceptance:

```text
100 true
```

A recipient must be a full wallet, such as BSV Desktop or a `@bsv/wallet-toolbox` wallet. If the recipient is built on `ProtoWallet`, it cannot accept the payment and the message arrives with `paymentOutcome: 'failed'`.

## Configuration options

The options go in the `MessageBoxClient` constructor or in the call that sends:

<BlueTable>

| Option | Default | Effect |
| --- | --- | --- |
| `host` | `https://message-box-us-1.bsvb.tech` | The MessageBox host that stores the messages. It is the same for `'mainnet'` and `'testnet'`. The client uses it unless an overlay lookup finds another host for the recipient. No testnet overlay tracker works, so this is the host used on testnet |
| `networkPreset` | `'mainnet'` | The network the client uses for overlay lookups. Use `'testnet'` for the examples on this page |
| `socketOptions` | Default transport | The live methods work with the default transport in 2.7.0. Version 2.6.0 needed `{ managerOptions: { transports: ['websocket'] } }` |
| `skipEncryption` | `false` | Required by `sendMessageToRecipients`. A batch cannot be encrypted, so the call fails unless you set `skipEncryption: true`, and the host then stores the body as plain text |
| `checkPermissions` | `false` | Asks the host for the price of a message before sending. Required for a box that charges a fee |
| `maximumPayment` | None | The most the client pays for one message. The send fails before any payment when the price is higher |

</BlueTable>

## Limitations

Check these two limits before you rely on the package in an app:

- `rejectPayment` refunds the amount less 1,000 satoshis. A payment under 2,000 satoshis is acknowledged and not refunded, because the refund would be under 1,000 satoshis.
- The built-in `notifications` box charges the sender a host fee of 10 satoshis. On testnet the wallet pays the fee, but the host answers `ERR_INTERNALIZE_FAILED` and does not deliver the message. Use a box with no host fee. A box where only the recipient sets a fee works.

## Related articles

To learn more about messaging on the BSV blockchain, review these articles:

- [Send messages between users](https://bsvblockchain.com/docs/guides/messaging/)
- [Find more TypeScript packages](https://bsvblockchain.com/docs/sdk/packages/)
- [How overlays work](https://bsvblockchain.com/docs/concepts/overlays/)