# Store data and files

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

Put data in a transaction output on the BSV blockchain through the user's wallet and read it back with the TypeScript SDK.

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

**Data outputs** let a transaction on the BSV blockchain carry data next to the coins it moves, which fits a small public record that needs a timestamp and cannot be changed later, such as a note, a hash or a receipt. In this guide you write a short note to an output, read it back and find it on the testnet explorer, in a standalone Node script you can copy into an existing app.

## Before you begin

You need a funded testnet wallet in [BSV Desktop](https://desktop.bsvb.tech/). [Send a payment from a web app](https://bsvblockchain.com/docs/get-started/quick-start-browser/) shows how to set one up.

The code runs with [Node.js](https://nodejs.org/) in an empty project folder. In that folder, run these commands to create an ES module project and install the SDK and `tsx`, a tool that runs TypeScript files without a build step:

```bash
npm init -y
npm pkg set type=module
npm install @bsv/sdk
npm install -D tsx
```

> The network comes from the wallet, not from the code. These examples use a testnet wallet. To use mainnet, read [Move your app to mainnet](https://bsvblockchain.com/docs/guides/go-to-mainnet/).

## How it works

Your script asks BSV Desktop to write the data and to list it back. The wallet builds, signs and broadcasts the transaction, so your code never touches the keys:

<StoreDataFlow />

## Store data with the wallet

Both sections below use only `@bsv/sdk`.

### Write data to a transaction output

Follow these steps to write a short text to a transaction output.

**1. Connect to the wallet**

Create a file in your project folder, for example `store-note.ts`, and connect to BSV Desktop with `WalletClient`:

```ts
import { WalletClient } from '@bsv/sdk'

const wallet = new WalletClient('auto', 'localhost')
```

The second argument of `WalletClient` is the originator, the name BSV Desktop shows for your app.

**2. Build the data output**

Build the locking script (The part of a transaction output that sets the condition to spend it) that holds your text, in the same file and after the connection:

```ts
import { LockingScript, OP, Utils } from '@bsv/sdk'

const data = Utils.toArray('hello from my app', 'utf8')
const pushOp = (n: number) =>
  n <= 75 ? n : n <= 0xff ? OP.OP_PUSHDATA1 : n <= 0xffff ? OP.OP_PUSHDATA2 : OP.OP_PUSHDATA4

const lockingScript = new LockingScript([
  { op: OP.OP_FALSE },
  { op: OP.OP_RETURN },
  { op: pushOp(data.length), data }
])
```

A data output starts with `OP_FALSE OP_RETURN`, which makes it unspendable, followed by the bytes you choose. The SDK has no template for it, so the script is built from the two opcodes and one data push. `pushOp` picks the opcode that announces the push by the length of the data: up to 75 bytes the length itself is the opcode, and longer data uses `OP_PUSHDATA1`, `OP_PUSHDATA2` or `OP_PUSHDATA4`.

**3. Create the transaction**

Ask the wallet to create a transaction with that script and log the id it returns:

```ts
const { txid } = await wallet.createAction({
  description: 'Store a note on-chain',
  outputs: [{
    lockingScript: lockingScript.toHex(),
    satoshis: 0,
    outputDescription: 'Stored note',
    basket: 'notes',
    tags: ['note']
  }],
  options: { acceptDelayedBroadcast: false }
})

console.log(txid)
```

The output holds no coins, so the cost is the network fee, which grows with the size of the transaction and uses the rate set in BSV Desktop under **Settings**, **Advanced settings**, **Transaction fees**. The `basket` and `tags` let you list the output later, and `acceptDelayedBroadcast: false` makes the wallet broadcast the transaction before the call returns.

**4. Run the script**

In the terminal, in your project folder, run the file while BSV Desktop is open and unlocked:

```bash
npx tsx store-note.ts
```

**5. Authorize the request in BSV Desktop**

BSV Desktop opens a **Spending Request** with the name of your app, the `description` you passed and the network fee. The call returns after you click **Authorize**. The user reads the `description` and the `outputDescription`, so write them for the user.

After you authorize, the terminal prints the `txid`, for example:

```text
ed5ca9804da9c2cb5d2bf3541727cb65348abc7197a61ed6965c3b404ac323de
```

> Anything in the output is public, and anyone with the transaction ID can read it. Do not put personal data or secrets in it.

### Read the data back

Once the transaction is broadcast, read the output from the wallet and from the network:

**1. List the output from the wallet**

Add this code below the rest of `store-note.ts` and run the file again, which also writes a new note:

```ts
const { outputs } = await wallet.listOutputs({
  basket: 'notes',
  tags: ['note'],
  include: 'locking scripts'
})

const readData = (hex: string): number[] => {
  const bytes = Utils.toArray(hex, 'hex')
  if (bytes[0] !== OP.OP_FALSE || bytes[1] !== OP.OP_RETURN) throw new Error('Not a data output')
  const reader = new Utils.Reader(bytes.slice(2))
  const op = reader.readUInt8()
  const length = op <= 75 ? op
    : op === OP.OP_PUSHDATA1 ? reader.readUInt8()
    : op === OP.OP_PUSHDATA2 ? reader.readUInt16LE()
    : reader.readUInt32LE()
  return reader.read(length)
}

for (const output of outputs) {
  console.log(Utils.toUTF8(readData(output.lockingScript!)))
}
```

`readData` reverses the script: it checks that the script starts with `OP_FALSE OP_RETURN`, reads the push opcode and the length, and returns the data bytes, which `Utils.toUTF8` turns back into text.

The terminal prints one line for each output in the basket, so a second run adds a second line:

```text
hello from my app
```

**2. Check the transaction on an explorer**

Open the transaction in a testnet explorer such as [WhatsOnChain](https://test.whatsonchain.com/), by its transaction ID. Output 0 has a value of 0 and the same script. An explorer can cut a large script short, and the WhatsOnChain API returns only its first 50,000 bytes.

## Store data with `@bsv/simple`

If your app already uses `@bsv/simple` in a browser, its wallet writes the same output in one call:

```ts
import { createWallet } from '@bsv/simple/browser'

const wallet = await createWallet()

const text = await wallet.inscribeText('hello from my app', { basket: 'notes' })
const json = await wallet.inscribeJSON({ note: 'hello' }, { basket: 'notes' })

console.log(text.txid, json.txid)
```

`createWallet` connects to BSV Desktop with its own originator, and you authorize each call there. The output is the same script, so the helper above reads it when you list the `notes` basket without the `tags` filter.

## Adapt the example to your app

To use this in a real app, apply these two points:

- Encrypt the data before you write it when it should stay private.
- Use one `basket` for each kind of data your app stores, and `tags` to filter inside it, so a read returns only what you expect.

## Troubleshooting

**Node script cannot reach the wallet**

The `@bsv/sdk` package throws `No wallet available over any communication substrate` in your script's terminal, not in BSV Desktop. A Node script cannot reach BSV Desktop without an originator. Pass one as the second argument, for example `new WalletClient('auto', 'localhost')`, and keep BSV Desktop open and unlocked.

**BSV Desktop keeps the call waiting**

The script prints nothing and does not exit because BSV Desktop waits for you to click **Authorize** on the **Spending Request**. Bring the app to the front.

**Output reader rejects a stored output**

Your `readData` helper throws `Not a data output` when it reads an output that does not start with `OP_FALSE OP_RETURN`, which happens when the basket also holds other outputs. Filter the list with `tags`, or use a basket only for data outputs.

## Related articles

To learn more about data and transactions on the BSV blockchain, review these articles:

- [Permissions and outputs](https://bsvblockchain.com/docs/guides/wallet-aware-apps/)
- [Send messages between users](https://bsvblockchain.com/docs/guides/messaging/)
- [Transactions](https://bsvblockchain.com/docs/concepts/transactions/)
- [Script](https://bsvblockchain.com/docs/concepts/script/)