Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions website/docs/getting-started.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Built by the community, for the community. Join our working groups and help shap

### Tutorials
- **[Hands-On tutorials](/docs/tutorials/local-cardano-payment-detector.md)** - Interactive coding tutorials and workshops
- **[Wallet connect and a first payment](/docs/tutorials/cip-30-wallet-connect-mesh/)** - Connect a CIP-30 browser wallet, send test ADA on preview with Mesh, and confirm it on an explorer

### Resources
- **[Repositories](/docs/resources/repositories/)** - Essential GitHub repositories, tools, and APIs
Expand Down
326 changes: 326 additions & 0 deletions website/docs/tutorials/cip-30-wallet-connect-mesh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,326 @@
# Build a Wallet Connection and Send Your First Payment

Most Cardano front-end work now starts with a coding agent. The agent is usually good at the code and bad at one thing: knowing which generation of Mesh is current. Trained on a mix of tutorials and blog posts, it reaches for `BrowserWallet` and the `Transaction` class with complete confidence, and neither is what Mesh's docs teach today.

So this page is written the way the work actually gets done. First you hand the agent Mesh's documentation as a local file, so it stops guessing. Then you make it build a wallet connection and a first payment on **preview testnet**, and you check the handful of facts it gets wrong. Nothing here costs real funds: preview ADA comes from a faucet and is worthless.

The result is a page that lists the CIP-30 wallets in the browser, connects to one, refuses to continue if it is on the wrong network, reads the address and funds, builds an ADA payment, has the wallet sign it, submits it, and waits for confirmation.

## The Four Facts Agents Get Wrong

Everything below depends on these being right, so read them before you read the code an agent gives you:

- **`BrowserWallet` is the previous class.** The current one is `MeshCardanoBrowserWallet`, exported by `@meshsdk/wallet`. The old name still resolves from `@meshsdk/core`, which is exactly what makes the mistake hard to see: the imports compile and the method names are subtly wrong.
- **Transactions are built with `MeshTxBuilder`.** The `Transaction` class still ships in `@meshsdk/transaction`, but Mesh's docs no longer teach it, and an agent that reaches for it produces code no current page will help you debug.
- **Raw wallet calls return CBOR.** `getUtxos()` and `getBalance()` hand back hex strings; `getUtxosMesh()` and `getBalanceMesh()` hand back `UTxO[]` and `Asset[]`, which is what the builder wants.
- **`BlockfrostProvider(key)` has not changed.** It is the one thing an agent gets right while getting the rest wrong, which is how a session can look correct for twenty minutes and then fail on the first wallet call.

## Prerequisites

You'll need six things in place before the first line of code:

- **Node.js 20 or later**, and npm.
- **A coding agent with file access in your editor**: Claude Code, Cursor, or Copilot in VS Code. The page works without one, but Step 1 is what stops the agent inventing API names.
- **A CIP-30 browser wallet**: Eternl, Lace, Nami, Flint or Gero. Install the extension before you start, because the page can only see wallets that already exist in the browser.
- **A preview testnet account in that wallet.** Create a fresh account and switch the wallet's network to **Preview**, not Mainnet.
- **Test ADA** from the [Cardano testnet faucet](https://docs.cardano.org/cardano-testnets/tools/faucet). Pick **Preview**, paste one of your wallet's `addr_test1…` addresses, and request funds. It arrives in a minute or two.
- **A Blockfrost preview project key** from [blockfrost.io](https://blockfrost.io/). The free tier is enough. Create the project with network **Preview**, because a mainnet key will fail against preview addresses.

:::warning

Every address in this tutorial starts with `addr_test1`. If your wallet shows an `addr1…` address, you are on mainnet and the transaction will be rejected at submit. That is the single most common source of confusion here.

:::

## Step 1: Give Your Agent the Mesh Docs

The agent cannot know which Mesh version is current, so hand it the documentation before it writes a line. Mesh publishes its whole doc set as one file for exactly this, and a local copy beats a link: the agent can grep it, cite it, and read it without a network call.

```bash
mkdir -p docs
curl -o docs/mesh-llms.txt https://meshjs.dev/llms-full.txt
```

That file is every Mesh guide, API page and example in one markdown document, about 1.3 MB, regenerated by Mesh and served with no key or account. Keep it out of version control with a line in `.gitignore`, because it is a snapshot of somebody else's docs:

```
docs/mesh-llms.txt
```

Then make the instruction stick. Give the agent one line at the start of a session, and put the same line in `AGENTS.md` (or `CLAUDE.md` in a Claude Code project) so it survives the next one:

> Before you write any Mesh code, read `docs/mesh-llms.txt` and cite the page for every API you use. If an API is not in that file, say so instead of guessing.

For anything the file does not settle, every Mesh page has a markdown twin: append `.md` to its URL and paste it in. `https://meshjs.dev/apis/wallets/browserwallet.md` is the page for the class this tutorial uses.

### Prove the Docs Are In Play

Before building anything, ask the agent a question whose answer changed between versions:

> Which package exports `MeshCardanoBrowserWallet`, and what does `enable()` do when the user declines?

An agent reading the docs names `@meshsdk/wallet` and says the promise rejects. An agent working from memory answers `@meshsdk/react` and that `enable()` returns `null`. If you get the second answer, fix the documentation access before you write any code, or every snippet below will be wrong in the same quiet way.

## Step 2: Scaffold the Project

The fastest route is the Mesh CLI, which sets up Next.js with Mesh installed:

```bash
npx meshjs mesh-preview-payment
cd mesh-preview-payment
```

If you already have a React or Next.js app, install the two packages instead. `@meshsdk/wallet` holds the CIP-30 wallet wrapper, and `@meshsdk/core` holds the transaction builder and the providers:

```bash
npm install @meshsdk/core @meshsdk/wallet
```

## Step 3: Wire the Provider

Only one of the three actors in this flow touches the network. The provider answers questions about the chain, and it needs a Blockfrost project key in `.env.local`:

```
NEXT_PUBLIC_BLOCKFROST_KEY=preview…
```

`NEXT_PUBLIC_` means the key is visible in the browser. That is acceptable for a preview project key and unacceptable for anything else; the Blockfrost docs are explicit that a project key is not a secret once it is in front-end code.

```tsx
import { BlockfrostProvider } from '@meshsdk/core';

const provider = new BlockfrostProvider(process.env.NEXT_PUBLIC_BLOCKFROST_KEY!);
```

**Prompt:** "Create the Blockfrost provider from the key in `.env.local`, and tell me which Mesh calls actually go to it."

**Reject it if:** the agent claims the wallet calls need the provider. Discovery, connection and signing are the wallet's own API; only building and confirming reach the chain.

## Step 4: Connect the Wallet

### The Building Blocks

The browser exposes CIP-30 wallets under `window.cardano`. Mesh wraps them:

```tsx
import { MeshCardanoBrowserWallet } from '@meshsdk/wallet';
```

### What Is Installed

```tsx
const installed = MeshCardanoBrowserWallet.getInstalledWallets();
// [{ id: 'eternl', name: 'Eternl', icon: 'data:image/png;base64,…', version: '…' }]
```

Each entry carries the `id` to pass to `enable()`, a display `name`, a base64 `icon` for an `<img>` source, and the extension's `version`.

This returns nothing until the extension is installed **and the page has been reloaded**. Extensions inject themselves at page load, so a page that was open when you installed the wallet keeps showing an empty list.

### Asking for Permission

```tsx
const wallet = await MeshCardanoBrowserWallet.enable('eternl');
```

`enable()` rejects if the user declines. Show that as a message and let them try again; do not retry in a loop, because each attempt reopens the wallet popup.

### Guarding the Network

```tsx
const networkId = await wallet.getNetworkId(); // 0 = testnet, 1 = mainnet

if (networkId !== 0) {
throw new Error('Switch the wallet to Preview testnet before continuing.');
}
```

The network belongs to the account inside the wallet, not to your app, so this is the check that catches the reader who followed every step and left the wallet on mainnet. Doing it first turns a rejected transaction into a sentence.

**Prompt:** "List the installed CIP-30 wallets, let me pick one, connect to it, and refuse to continue unless the wallet's network id is 0."

**Reject it if:** it hardcodes a wallet id instead of using the ids from `getInstalledWallets()`, it checks `networkId === 1` rather than `!== 0`, or it connects inside `useEffect` on mount. The popup has to follow a click.

## Step 5: Address, UTxOs and Amounts

### The Change Address

A wallet can own many addresses. The one to build against is the change address, where the unspent remainder goes:

```tsx
const changeAddress = await wallet.getChangeAddressBech32();
```

### UTxOs, Not a Balance

Cardano has no account balance. Funds live in unspent transaction outputs, and a wallet is the collection its addresses can spend:

```tsx
const utxos = await wallet.getUtxosMesh();
// [{ input: { txHash, outputIndex }, output: { address, amount: [{ unit: 'lovelace', quantity }] } }]
```

### Why Every Amount Is a String

```tsx
const balance = await wallet.getBalanceMesh();
const lovelace = balance.find((a) => a.unit === 'lovelace')?.quantity ?? '0';
console.log(`${Number(lovelace) / 1_000_000} tADA`);
```

One ADA is `1_000_000` lovelace, and every quantity in the Mesh API is a **string**, because some tokens have 19 decimal places and JavaScript integers cannot hold them. Convert only for display.

**Prompt:** "Show my change address, my UTxO count and my total in tADA, and use the `*Mesh` wallet methods for the structured values."

**Reject it if:** it calls `getUtxos()` or `getBalance()` and then parses CBOR by hand, or it turns a quantity into a number before dividing.

## Step 6: Build the Payment

A transaction body says which UTxOs go in, which outputs come out, and where the change goes. Mesh selects the inputs, calculates the fee, and returns the remainder to your address:

```tsx
import { MeshTxBuilder } from '@meshsdk/core';

const unsignedTx = await new MeshTxBuilder({ fetcher: provider })
.txOut('addr_test1vq…', [{ unit: 'lovelace', quantity: String(5_000_000) }])
.changeAddress(await wallet.getChangeAddressBech32())
.selectUtxosFrom(await wallet.getUtxosMesh())
.complete();
```

`txOut` takes the recipient and an asset list in the same `unit`/`quantity` shape the wallet reported. `complete()` is the first call that reads the chain, so it is also the first one that can fail on your key rather than your code: a `Blockfrost error: 403` means the key is wrong, or belongs to another network. The result is an unsigned transaction in CBOR hex, a proposal until the wallet signs it.

**Prompt:** "Build a 5 tADA payment to the address I paste, with the change back to me, using `MeshTxBuilder` and the UTxOs from the wallet."

**Reject it if:** it constructs the CBOR itself, uses the `Transaction` class, or hardcodes the UTxO list. `selectUtxosFrom` exists so the builder can pick.

## Step 7: Sign, Submit, Confirm

```tsx
const signedTx = await wallet.signTx(unsignedTx, false); // false = single signature
const txHash = await wallet.submitTx(signedTx);
```

The second argument to `signTx` is `partialSign`, and it matters only when more than one party has to sign. Submit through the provider (`provider.submitTx`) instead when a key your server holds signed the transaction.

A hash is not a receipt, so wait for the chain:

```tsx
provider.onTxConfirmed(txHash, () => console.log('Confirmed'));
```

Or paste the hash into the search box at [preview.cexplorer.io](https://preview.cexplorer.io/) and read the inputs, outputs and fee there.

**Prompt:** "Sign the transaction with the wallet, submit it, then keep polling until it confirms and show me the hash."

**Reject it if:** it treats a returned hash as success, or it logs the signed CBOR to the console.

## The Whole Page

Everything above in one component, with the error handling the prompts ask for. Read it as the spec your agent should have arrived at:

```tsx
'use client';

import { useState } from 'react';
import { MeshCardanoBrowserWallet } from '@meshsdk/wallet';
import { BlockfrostProvider, MeshTxBuilder } from '@meshsdk/core';

const provider = new BlockfrostProvider(process.env.NEXT_PUBLIC_BLOCKFROST_KEY!);

export default function Payment() {
const [status, setStatus] = useState<string>('Not connected');
const [pending, setPending] = useState(false);

async function pay() {
setPending(true);

try {
setStatus('Connecting…');
const wallet = await MeshCardanoBrowserWallet.enable('eternl');

if ((await wallet.getNetworkId()) !== 0) {
setStatus('Wrong network: switch the wallet to Preview.');
return;
}

setStatus('Building…');
const unsignedTx = await new MeshTxBuilder({ fetcher: provider })
.txOut('addr_test1vq…', [{ unit: 'lovelace', quantity: '5000000' }])
.changeAddress(await wallet.getChangeAddressBech32())
.selectUtxosFrom(await wallet.getUtxosMesh())
.complete();

setStatus('Waiting for the wallet to sign…');
const signedTx = await wallet.signTx(unsignedTx, false);
const txHash = await wallet.submitTx(signedTx);

setStatus(`Submitted ${txHash}, waiting for confirmation…`);
provider.onTxConfirmed(txHash, () => setStatus(`Confirmed ${txHash}`));
} catch (error) {
setStatus(`Failed: ${error instanceof Error ? error.message : String(error)}`);
} finally {
setPending(false);
}
}

return (
<div>
<button onClick={pay} disabled={pending}>
Send 5 tADA
</button>
<p>{status}</p>
</div>
);
}
```

## Run It

```bash
npm run dev
```

Then:

1. Open [http://localhost:3000](http://localhost:3000).
2. Click the button, pick your preview wallet in the popup, and approve.
3. Watch the status line move through connecting, building and signing.
4. Approve the transaction in the wallet.
5. Paste the hash into [preview.cexplorer.io](https://preview.cexplorer.io/) and check the recipient and the amount.

Expected: the status line ends at `Confirmed <txHash>`, and the explorer shows a fee taken from your balance and 5 tADA at the recipient.

## Troubleshooting

**The agent wrote `BrowserWallet`, the `Transaction` class, or `.getUtxos()`.** It is answering from training data. Redo Step 1, then ask again with the specific page linked, and check the package on every import it produces.

**"No wallets found" / the list is empty.** The extension is installed but the page loaded before it. Reload. If it is still empty, the wallet is disabled for this site, or it is not a CIP-30 wallet.

**Wrong network.** `addr1…` instead of `addr_test1…` means the wallet is on mainnet. Switch the network in the wallet, then reload.

**`Blockfrost error: 403` or "project not found".** The key is invalid, or it was created for a different network than the addresses you are using.

**"Not enough funds" / the fee cannot be covered.** Test ADA has not arrived yet, or you are sending more than the wallet holds. Leave at least ~2 tADA for fees and the minimum ADA per output.

**"UTxOs are not available" right after a transaction.** The wallet has not refreshed. Wait a few seconds and call `getUtxosMesh()` again before rebuilding.

**Missing collateral.** Collateral is required only for transactions that run Plutus scripts, and a plain ADA payment is not one. If you later add a smart contract call, get it with `wallet.getCollateralMesh()` and pass it to the builder.

**"User rejected the request".** The wallet popup was dismissed. Show it as a message and let the user retry.

## Summary

You wired a coding agent to Mesh's documentation, then used it to build a page where a browser wallet connects, the app checks which network the wallet is on, reads the address and UTxOs, builds a 5 tADA payment with `MeshTxBuilder`, asks the wallet to sign, submits, and waits for confirmation.

The pattern underneath is the one every Cardano dApp reuses: keys stay in the wallet, your app describes the change it wants, and a provider supplies the chain data. The new part is the division of labour. The agent writes most of the lines, and your job moves to the four facts it cannot know: which class is current, which call returns objects instead of CBOR, and whether the wallet it connected to is on the network you think it is.

## Where to Go Next

- [Browser Wallet API (Mesh)](https://meshjs.dev/apis/wallets/browserwallet): every CIP-30 method Mesh wraps, including `signData` for proving ownership.
- [Mesh transaction builder](https://meshjs.dev/apis/txbuilder): minting, multi-asset payments, metadata, TTL and script interactions.
- [Blockfrost provider](https://meshjs.dev/providers/blockfrost): the rest of the chain-data API, and `onTxConfirmed`.
- [CIP-30](https://cips.cardano.org/cip/CIP-30): the standard behind the connect flow, worth reading once.
- [Getting started](/docs/getting-started/): the rest of the Developer Experience track, including the session archive.

Once this works on preview, the same code runs on mainnet by switching the network and the provider key. Do that only after you have handled the two things preview lets you skip: showing the user the fee before they sign, and treating any address you did not personally type as untrusted input.