---
title: "REST API"
description: "The ln.bot REST API: accounts, keys, wallets, invoices, payments, Lightning addresses, transactions, webhooks, event streams, L402, service status and errors."
updatedAt: "2026-10-25"
order: 12
tags: ["api", "rest", "reference", "wallets", "invoices", "payments", "addresses", "webhooks", "l402"]
---

# REST API

- **Base URL:** `https://api.ln.bot`
- **Auth:** `Authorization: Bearer uk_...` (user key) or `Bearer wk_...` (wallet key)
- **Content-Type:** `application/json` on requests with a body

Two key types:

| Key type | Prefix | Reaches |
|----------|--------|---------|
| User key | `uk_` | Every wallet on the account |
| Wallet key | `wk_` | One wallet |

`POST /v1/register` returns two user keys, a primary and a secondary. A wallet key is created per wallet, at most one each, with a user key. Most routes under `/v1/wallets/{walletId}/` take either kind of key. The wallet key routes themselves take a user key, as do creating and listing wallets and rotating user keys; event streams take a wallet key only. There are no read-only keys or scopes.

## Getting started

Three calls take you from no account to an invoice. Register first; no key is needed:

```bash
curl -X POST https://api.ln.bot/v1/register
```

```json
{
  "userId": "usr_a1b2c3d4",
  "primaryKey": "uk_...",
  "secondaryKey": "uk_...",
  "recoveryPassphrase": "orbit garden pilot smoke ..."
}
```

Store that response now: the API never returns these keys again, and the passphrase is how you [restore access](#post-v1-restore-recovery). Then create a wallet with the primary key:

```bash
curl -X POST https://api.ln.bot/v1/wallets \
  -H "Authorization: Bearer uk_..."
```

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "name": "x4k7m2",
  "address": "x4k7m2@ln.bot"
}
```

The `walletId` goes in every wallet route. Create an invoice on it:

```bash
curl -X POST https://api.ln.bot/v1/wallets/wal_c7i0hnuoxxupuwej/invoices \
  -H "Authorization: Bearer uk_..." \
  -H "Content-Type: application/json" \
  -d '{"amount": 1000, "memo": "first invoice"}'
```

The response's `bolt11` is the invoice to pay. Anyone can also pay `x4k7m2@ln.bot` without one.

## Units

Amounts are integers in bitcoin's base unit, the sat, which this site writes with ₿ as the draft [BIP 177](https://github.com/bitcoin/bips/blob/master/bip-0177.mediawiki) proposes: `"amount": 1000` is ₿1,000, or 0.00001 BTC. Amounts, fees, balances, prices and costs all use that unit. LNURL is the exception: a Lightning address's pay endpoint, `https://ln.bot/.well-known/lnurlp/<name>`, works in millisatoshis as LNURL requires, and accepts 1,000 to 1,000,000,000 msat (₿1 to ₿1,000,000) per payment.

## Errors

A failed request returns a 4xx or 5xx status. The SDKs turn the common ones into typed errors that keep the status and the raw response body (`err.status` and `err.body` in TypeScript), and use the body's `message` field as the error message when there is one.

| Status | Typical cause | TypeScript and Python |
|--------|---------------|-----------------------|
| 400 | Invalid input: a zero amount, an invalid target, not enough balance, a network fee above the cap, a generated address in a transfer, an unparseable L402 token, a malformed wallet ID | `BadRequestError` |
| 401 | Missing or invalid key | `UnauthorizedError` |
| 403 | The key can't use this resource | `ForbiddenError` |
| 404 | No such wallet, invoice, payment, address, webhook or wallet key | `NotFoundError` |
| 409 | A conflict, such as a second wallet key for one wallet | `ConflictError` |
| 429 | Too many requests to the public invoice routes, which are limited by IP | `LnBotError` |

Go has `BadRequestError` and the rest, each wrapping `*lnbot.APIError`; Rust has `LnBotError::BadRequest` and the rest; C# has `BadRequestException` and the rest. Any other status arrives as the base type with its status code: `LnBotError` in TypeScript and Python, `*lnbot.APIError` in Go, `LnBotError::Api` in Rust, `LnBotException` in C#.

## Account

### POST /v1/register

Register a new account. No authentication required.

**Response:**

```json
{
  "userId": "usr_a1b2c3d4",
  "primaryKey": "uk_...",
  "secondaryKey": "uk_...",
  "recoveryPassphrase": "orbit garden pilot smoke ..."
}
```

`primaryKey` and `secondaryKey` are user keys; either works wherever a user key does. `recoveryPassphrase` is 12 words.

> The API returns these keys and the passphrase only here. Save them now.

### GET /v1/me

Get the authenticated identity. Works with both user keys and wallet keys; with a wallet key, `walletId` is that key's wallet.

**Response:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej"
}
```

## Wallets

### POST /v1/wallets

Create a wallet. Requires a user key and takes no request body. The name is generated and the wallet gets a random Lightning address. The response has no keys: reach the wallet with the account's user key, or [create a wallet key](#post-v1-wallets-walletId-key) for it. There is no endpoint to delete a wallet.

**Response:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "name": "x4k7m2",
  "address": "x4k7m2@ln.bot"
}
```

### GET /v1/wallets

List all wallets. Requires a user key.

**Response:**

```json
[
  {
    "walletId": "wal_c7i0hnuoxxupuwej",
    "name": "x4k7m2",
    "createdAt": "2026-01-15T10:00:00Z"
  }
]
```

### GET /v1/wallets/{walletId}

Get the wallet's name and balance. `available` is `balance` minus `onHold`, the amount held for payments in flight. With a wallet key, `GET /v1/wallets/current` returns the key's own wallet. With a wallet key, `current` works on every wallet route, so `/v1/wallets/current/invoices` lists that wallet's invoices; with a user key it returns 400.

**Response:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "name": "x4k7m2",
  "balance": 12500,
  "onHold": 0,
  "available": 12500
}
```

### PATCH /v1/wallets/{walletId}

Rename the wallet. With a wallet key, `PATCH /v1/wallets/current` does the same.

**Request body:**

```json
{
  "name": "my-agent"
}
```

**Response:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "name": "my-agent",
  "balance": 12500,
  "onHold": 0,
  "available": 12500
}
```

## Wallet keys

A wallet key (`wk_`) reaches one wallet, and each wallet has at most one. These routes take either key, so a wallet key can also rotate or revoke itself.

### POST /v1/wallets/{walletId}/key

Create the wallet's key. If it already has one, the API returns 409.

**Response:**

```json
{
  "key": "wk_...",
  "hint": "wk_...a1b2"
}
```

> The key is shown once and cannot be retrieved again.

### GET /v1/wallets/{walletId}/key

Get wallet key info (no plaintext key).

**Response:**

```json
{
  "hint": "wk_...a1b2",
  "createdAt": "2026-01-15T10:00:00Z",
  "lastUsedAt": "2026-01-16T08:00:00Z"
}
```

### DELETE /v1/wallets/{walletId}/key

Revoke the wallet key immediately.

> Returns 204 No Content on success.

### POST /v1/wallets/{walletId}/key/rotate

Rotate the wallet key. The old key stops working immediately.

**Response:**

```json
{
  "key": "wk_...",
  "hint": "wk_...c3d4"
}
```

## Invoices

### POST /v1/wallets/{walletId}/invoices

Create a BOLT11 invoice, valid for 60 minutes. `reference` is for your own tracking; `memo` is embedded in the invoice. A zero amount returns 400.

**Request body:**

```json
{
  "amount": 1000,
  "memo": "AI task payment",
  "reference": null
}
```

**Response:**

```json
{
  "number": 1,
  "status": "pending",
  "amount": 1000,
  "bolt11": "lnbc10u1pn...",
  "reference": null,
  "memo": "AI task payment",
  "preimage": null,
  "txNumber": null,
  "createdAt": "2026-01-15T10:30:00Z",
  "settledAt": null,
  "expiresAt": "2026-01-15T11:30:00Z"
}
```

### GET /v1/wallets/{walletId}/invoices

List invoices, newest first.

| Parameter | In | Type | Description |
|-----------|-----|------|-------------|
| `limit` | query | int | Max results |
| `after` | query | int | Return invoices numbered below this one (the last number on the previous page) |

**Response:**

```json
[
  {
    "number": 2,
    "status": "settled",
    "amount": 500,
    "bolt11": "lnbc5u1pn...",
    "reference": null,
    "memo": null,
    "preimage": "d4e5f6...",
    "txNumber": 3,
    "createdAt": "2026-01-15T11:00:00Z",
    "settledAt": "2026-01-15T11:02:00Z",
    "expiresAt": "2026-01-15T12:00:00Z"
  }
]
```

### GET /v1/wallets/{walletId}/invoices/{number}

Get invoice by number.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `number` | path | int | yes | Invoice number |

**Response:** Same shape as POST, with settlement data populated.

### GET /v1/wallets/{walletId}/invoices/{paymentHash}

Get invoice by payment hash.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `paymentHash` | path | string | yes | Payment hash |

> Same response as GET by number.

### GET /v1/wallets/{walletId}/invoices/{number}/events

Wait for an invoice over Server-Sent Events. Works with either key. The stream sends one event, `settled` or `expired`, with the invoice as JSON in its `data`, then closes. If the wait runs out first, the event is `timeout` and `data` is the invoice's current state. The JSON uses snake_case keys (`created_at`, `tx_number`), as [webhooks](#receiving-webhooks) do; the SDKs convert them to the field names their REST methods use.

`expired` isn't always final: an invoice paid just before it expired can turn `settled` afterwards. Before treating it as unpaid, read it again, or keep listening for `invoice.settled` on the [wallet's event stream](#get-v1-wallets-walletId-events) or a webhook.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `number` | path | int | yes | Invoice number |
| `timeout` | query | int | no | Max wait in seconds (default 60, max 300) |

> Also available as /v1/wallets/{walletId}/invoices/{paymentHash}/events. Keepalive comments every 30s.

### POST /v1/invoices/for-wallet

Create an invoice for a wallet from its ID (`wal_...`) alone, without a key. Rate limited by IP. The invoice is not saved until payment settles. A malformed wallet ID returns 400.

**Request body:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "amount": 1000,
  "reference": null,
  "comment": null
}
```

**Response:**

```json
{
  "bolt11": "lnbc10u1pn...",
  "amount": 1000,
  "expiresAt": "2026-01-15T11:30:00Z"
}
```

> No auth required.

### POST /v1/invoices/for-address

Create an invoice for the wallet that owns a Lightning address. No authentication required; rate limited by IP. ln.bot's own Lightning address endpoint calls this route: it passes the `+tag` part of `name+tag@ln.bot` as `tag`, which the invoice keeps as its reference, and the payer's note as `comment`.

**Request body:**

```json
{
  "address": "x4k7m2@ln.bot",
  "amount": 1000,
  "tag": null,
  "comment": null
}
```

**Response:**

```json
{
  "bolt11": "lnbc10u1pn...",
  "amount": 1000,
  "expiresAt": "2026-01-15T11:30:00Z"
}
```

> No auth required.

## Payments

### POST /v1/wallets/{walletId}/payments

Send a payment. `target` is a Lightning address (`user@domain`), an LNURL (`lnurl1...`) or a BOLT11 invoice. `amount` is required for addresses and LNURLs; a BOLT11 invoice uses its own amount, rounded up to a whole sat if it has a fraction of one. A retry with the same `idempotencyKey` returns the original payment instead of paying again; keys are scoped to the wallet. Not enough balance returns 400.

Transfers between ln.bot wallets are free. A payment out to Lightning pays a service fee of 0.25% (at least ₿1) and the network fee, which is the Lightning routing fee. `maxFee` caps the network fee; the service fee is separate. Leave it out: it defaults to 1% of the amount, at least ₿20, and accepts 1 up to the larger of 10,000 and 5% of the amount. The fee is quoted when the payment is created; a quote above the cap rejects the payment, and only the quote plus a small buffer (at least ₿2, never more than the cap) is held while it's in flight. [Price the payment](#get-v1-wallets-walletId-payments-resolve) first to show the fees before sending.

**Request body:**

```json
{
  "target": "alice@example.com",
  "amount": 250000,
  "maxFee": null,
  "idempotencyKey": null,
  "reference": null
}
```

**Response:**

```json
{
  "number": 1,
  "status": "settled",
  "amount": 250000,
  "maxFee": 180,
  "serviceFee": 625,
  "actualFee": 73,
  "address": "alice@example.com",
  "reference": null,
  "preimage": "e5f6a7b8...",
  "txNumber": 2,
  "failureReason": null,
  "createdAt": "2026-01-15T10:35:00Z",
  "settledAt": "2026-01-15T10:35:02Z",
  "stage": "settled",
  "statusDetail": null,
  "retryUntil": null
}
```

| Field | Meaning |
|-------|---------|
| `maxFee` | Network fee held for this payment: the quote plus the buffer. The unused part is released at settlement. |
| `actualFee` | Network fee charged, `null` until the payment settles |
| `serviceFee` | 0.25%, at least ₿1; `0` between ln.bot wallets |
| `failureReason` | Why the payment failed, `null` otherwise |
| `stage` | Where the payment is, more precisely than `status` ([payment stages](#payment-stages)) |
| `statusDetail` | A sentence to show your user as it is: what is happening while the payment is in progress, the `failureReason` once it failed, `null` once it settled |
| `retryUntil` | Only with `stage: "retrying"`: until when it is retried; `null` otherwise |

While the payment is in flight the wallet's `onHold` includes `amount + maxFee + serviceFee`. When it settles the wallet is debited `amount + actualFee + serviceFee`, the rest of the hold is released, and the receiver gets exactly `amount`.

The response can come back `pending` or `processing` while the payment is in flight. Read it again with `GET .../payments/{number}`, or [wait on its events](#get-v1-wallets-walletId-payments-number-events), until the status is `settled` or `failed`. Payments between ln.bot wallets settle within about half a second. A payment that can't be sent fails quickly, and its funds are released at once: within about half a minute if the Lightning service refuses it, or after 10 minutes of automatic retries for a temporary problem (see `retryUntil`). If its invoice expires first, it fails then. A payment stays `processing` longer only when its funds are already on the Lightning network: it settles or fails as soon as the network does, usually within seconds, sometimes a few minutes, and is never refunded while it could still be paid.

`failureReason` is one of these. Show it to the user as is.

- `Invoice expired before it could be paid.`
- `Network fee estimate exceeds the maximum fee by N sats.`
- `Invalid Lightning invoice.`
- `Lightning payment failed.`: the payment was attempted and the funds came back.
- `The Lightning service could not send this payment.`: the Lightning service refused this invoice.
- `The Lightning service is temporarily unable to send this payment. Please try again.`
- `The Lightning service is unavailable right now. Please try again.`
- `Payment expired after 24 hours`, now rare: only a payment that waited a whole day without a single send attempt.

For the two that end in "Please try again.", sending the payment again later can work.

These requests return 400 with `{ "error": "..." }` and send nothing:

| `error` | When |
|---------|------|
| `Network fee estimate (X sats) is above the default limit for this amount (Y sats). Set maxFee to allow a higher fee.` | `maxFee` left out and the quote is above the default cap |
| `Network fee estimate (X sats) exceeds maxFee (Y sats).` | The quote is above your `maxFee` |
| `MaxFee must be between 1 and N sats.` | `maxFee` out of range; `N` depends on the amount |
| `Recipient returned an invoice without an amount.` | A Lightning address or LNURL server sent a bad invoice |
| `Recipient returned an invoice for X sats, but Y sats were requested.` | The same, for the wrong amount |

### Payment stages

Every payment returned by create, get and list carries `stage` and `statusDetail`; the [status page](/status) counts the payments in progress by stage.

| `stage` | With `status` | `statusDetail` |
|---------|---------------|----------------|
| `queued` | `pending` | Waiting to be sent. |
| `retrying` | `pending` | Not sent yet; retrying for a few minutes. If it still can't be sent, it fails and the funds are released. |
| `sending` | `pending` or `processing` | Being sent. Between ln.bot wallets: Being transferred to the recipient's wallet. |
| `in_flight` | `processing` | Sent; the Lightning network is completing it, usually within seconds. |
| `confirming` | `processing` | Checking with the Lightning network whether it went out. The funds stay on hold until then. |
| `on_hold` | `processing` | Interrupted by an earlier version of the service and on hold until it is reviewed. The funds are held, not lost. |
| `settled` | `settled` | `null` |
| `failed` | `failed` | The `failureReason` |

A `retrying` payment carries `retryUntil`: if it still can't be sent by then, it fails within about a minute and the funds are released. A payment can go from `processing` back to `pending` when it is retried, so treat both as in progress. More stages may be added: for one you don't know, go by `status`. The [payment's event stream](#get-v1-wallets-walletId-payments-number-events) carries the same fields in snake_case (`stage`, `status_detail`, `retry_until`); webhooks and the wallet's event stream don't.

### GET /v1/wallets/{walletId}/payments

List payments, newest first.

| Parameter | In | Type | Description |
|-----------|-----|------|-------------|
| `limit` | query | int | Max results |
| `after` | query | int | Return payments numbered below this one (the last number on the previous page) |

**Response:**

```json
[
  {
    "number": 1,
    "status": "settled",
    "amount": 500,
    "maxFee": 0,
    "serviceFee": 0,
    "actualFee": 0,
    "address": "r7vq3np@ln.bot",
    "reference": null,
    "preimage": "e5f6a7b8...",
    "txNumber": 2,
    "failureReason": null,
    "createdAt": "2026-01-15T10:35:00Z",
    "settledAt": "2026-01-15T10:35:01Z"
  }
]
```

### GET /v1/wallets/{walletId}/payments/{number}

Get payment by number.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `number` | path | int | yes | Payment number |

> Same response shape as POST.

### GET /v1/wallets/{walletId}/payments/{paymentHash}

Get payment by payment hash.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `paymentHash` | path | string | yes | Payment hash |

> Same response shape as POST.

### GET /v1/wallets/{walletId}/payments/resolve

Inspect and price a payment without sending it: what the target accepts, the network and service fees, and the total. Nothing is sent or held.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `target` | query | string | yes | Lightning address, LNURL, or BOLT11 |
| `amount` | query | int | no | The amount to price. For a BOLT11 invoice it must equal the invoice's amount. |

**Response** for a BOLT11 invoice:

```json
{
  "type": "bolt11",
  "min": null,
  "max": null,
  "fixed": true,
  "amount": 250000,
  "internal": false,
  "networkFeeEstimate": 75,
  "serviceFee": 625,
  "maxFee": 180,
  "total": 250700,
  "maxSendable": null,
  "feeWarning": null
}
```

| Field | Meaning |
|-------|---------|
| `type` | `lightning_address`, `lnurl` or `bolt11` |
| `min`, `max` | The amounts the target accepts; `null` for a BOLT11 invoice |
| `fixed` | `true` when the target takes one amount only, such as a BOLT11 invoice with an amount |
| `amount` | The amount priced: the invoice's for BOLT11, otherwise the `amount` you passed; `null` without one |
| `internal` | `true` when the recipient is an ln.bot wallet: a free transfer |
| `networkFeeEstimate` | The network fee quote, `0` if internal; `null` without an amount or when no quote is available |
| `serviceFee` | 0.25%, at least ₿1, `0` if internal; `null` without an amount |
| `maxFee` | What would be held for the network fee with the default `maxFee`; `null` without an amount or when `feeWarning` is set |
| `total` | `amount + networkFeeEstimate + serviceFee`, using the held limit when there's no quote; `null` without an amount |
| `maxSendable` | For a Lightning address or LNURL asked without `amount`: the most this wallet can send there now, after fees. `0` if it can't cover the recipient's minimum, `null` otherwise. |
| `feeWarning` | Set when sending without `maxFee` would be rejected because the fee is unusually high. The response is still 200. |

To show the fees before paying, call it with the target, and the amount for a Lightning address or LNURL, then display `networkFeeEstimate`, `serviceFee` and `total`. To send everything, call it for a Lightning address or LNURL without `amount`, then [send the payment](#post-v1-wallets-walletId-payments) with `amount` set to `maxSendable` and no `maxFee`.

Pricing a Lightning address or LNURL fetches an invoice from the recipient's server, so it's slower than the other calls: run it once the amount is settled, not on every keystroke. An ln.bot address returns `internal: true` with `min` 1 and `max` 1,000,000,000. An unknown ln.bot address returns 400 `Recipient not found.`, and the wallet's own address returns 400 `Cannot transfer to yourself.`. An amount outside the recipient's range returns 400 with `error`, `min` and `max`.

### GET /v1/wallets/{walletId}/payments/{number}/events

Wait for a payment over Server-Sent Events. Works with either key. The stream sends one event, `settled` or `failed`, with the payment as JSON in its `data`, then closes. If the wait runs out first, the event is `timeout` and `data` is the payment's current state. The JSON uses snake_case keys (`created_at`, `tx_number`), as [webhooks](#receiving-webhooks) do; the SDKs convert them to the field names their REST methods use.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `number` | path | int | yes | Payment number |
| `timeout` | query | int | no | Max wait in seconds (default 60, max 300) |

> Also available as /v1/wallets/{walletId}/payments/{paymentHash}/events. Keepalive comments every 30s.

## Addresses

### POST /v1/wallets/{walletId}/addresses

Create a random address (`"address": null`) or claim a vanity name (`"address": "mybot"`). A vanity name costs ₿100 for five characters or more, ₿1,000 for four and ₿10,000 for three, taken from the wallet's balance. Names are 3 to 20 lowercase letters and digits.

**Request body:**

```json
{
  "address": null
}
```

**Response:**

```json
{
  "address": "j4hf8tj@ln.bot",
  "generated": true,
  "cost": 0,
  "createdAt": "2026-01-15T10:00:00Z"
}
```

### GET /v1/wallets/{walletId}/addresses

List addresses.

**Response:**

```json
[
  {
    "address": "j4hf8tj@ln.bot",
    "generated": true,
    "cost": 0,
    "createdAt": "2026-01-15T10:00:00Z"
  },
  {
    "address": "mybot@ln.bot",
    "generated": false,
    "cost": 100,
    "createdAt": "2026-01-16T08:00:00Z"
  }
]
```

### DELETE /v1/wallets/{walletId}/addresses/{address}

Delete an address. No refund for vanity addresses.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `address` | path | string | yes | The full address, such as `mybot@ln.bot` |

> Returns 204 No Content on success.

### POST /v1/wallets/{walletId}/addresses/{address}/transfer

Move an address to another wallet. Only vanity (bought) addresses can be transferred; a generated one returns 400.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `address` | path | string | yes | The full address, such as `mybot@ln.bot` |

**Request body:**

```json
{
  "targetWalletKey": "wk_..."
}
```

`targetWalletKey` is the receiving wallet's key. The SDK integration tests and the TypeScript README pass a wallet key (`wk_`); only the CLI's help text shows a user key here.

**Response:**

```json
{
  "address": "mybot@ln.bot",
  "transferredTo": "wal_x8j2knroyyqpvwfh"
}
```

## Transactions

### GET /v1/wallets/{walletId}/transactions

List transactions. Returns credit and debit transactions in reverse chronological order. Each includes the balance after it was applied.

| Parameter | In | Type | Description |
|-----------|-----|------|-------------|
| `limit` | query | int | Max results |
| `after` | query | int | Return transactions numbered below this one (the last number on the previous page) |

**Response:**

```json
[
  {
    "number": 3,
    "type": "credit",
    "amount": 500,
    "balanceAfter": 13000,
    "networkFee": 0,
    "serviceFee": 0,
    "paymentHash": "a1b2c3...",
    "preimage": "d4e5f6...",
    "reference": null,
    "note": null,
    "createdAt": "2026-01-15T11:02:00Z"
  },
  {
    "number": 2,
    "type": "debit",
    "amount": 500,
    "balanceAfter": 12500,
    "networkFee": 0,
    "serviceFee": 0,
    "paymentHash": "f6e5d4...",
    "preimage": "c3b2a1...",
    "reference": null,
    "note": null,
    "createdAt": "2026-01-15T10:35:01Z"
  }
]
```

## Webhooks

### POST /v1/wallets/{walletId}/webhooks

Create a webhook: ln.bot sends each of the wallet's events to this URL as a POST ([what a delivery looks like](#receiving-webhooks)). The URL must be HTTPS and resolve to a public address. A wallet can have up to 10 webhooks, one per URL: registering the same URL again returns 409. The signing secret is returned only once.

**Request body:**

```json
{
  "url": "https://example.com/hooks/lnbot"
}
```

**Response:**

```json
{
  "id": "e82a6e9a410c916a",
  "url": "https://example.com/hooks/lnbot",
  "secret": "15a10301168f123cba107d4c3126a53944e5cbd5ff5796af821c31f9e6545e08",
  "createdAt": "2026-01-15T10:00:00Z"
}
```

> Save the secret: it cannot be retrieved again. It is 64 hex characters, encoding the 32-byte key that signs each delivery.

### GET /v1/wallets/{walletId}/webhooks

List webhooks. Secrets are not included in the response.

**Response:**

```json
[
  {
    "id": "e82a6e9a410c916a",
    "url": "https://example.com/hooks/lnbot",
    "active": true,
    "createdAt": "2026-01-15T10:00:00Z"
  }
]
```

### DELETE /v1/wallets/{walletId}/webhooks/{id}

Delete a webhook. Pending deliveries are discarded.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `id` | path | string | yes | Webhook ID |

> Returns 204 No Content on success.

### Receiving webhooks

Each event arrives as a POST with a JSON body, the same object the [wallet's event stream](#get-v1-wallets-walletId-events) sends:

```json
{
  "event": "invoice.settled",
  "created_at": "2026-01-15T10:05:00.1234567+00:00",
  "data": {
    "number": 42,
    "status": "settled",
    "amount": 1000,
    "bolt11": "lnbc10u1pn...",
    "reference": "order-1234",
    "memo": "Coffee",
    "preimage": "9f2c...",
    "tx_number": 87,
    "created_at": "2026-01-15T10:00:00.4567890+00:00",
    "settled_at": "2026-01-15T10:05:00.1234567+00:00",
    "expires_at": "2026-01-15T11:00:00.4567890+00:00"
  }
}
```

Keys are snake_case, unlike the rest of the API. For `invoice.*` events, `data` is the invoice. For `payment.*` events it is the payment: `number`, `status`, `amount`, `max_fee`, `service_fee`, `address`, `reference` and `created_at`, and once the payment has settled or failed, `actual_fee`, `preimage`, `tx_number`, `failure_reason` and `settled_at` as well.

Two headers come with it:

| Header | Value |
|--------|-------|
| `X-Webhook-Event` | The event name, as in the body |
| `X-Webhook-Signature` | `sha256=` followed by the hex HMAC-SHA256 of the raw body, keyed with the secret's 32 bytes |

To check a delivery, decode the secret from hex, compute the HMAC over the body exactly as it arrived, before parsing it, and compare in constant time:

```typescript
import express from "express";
import { createHmac, timingSafeEqual } from "node:crypto";

// The secret is hex: the HMAC key is the 32 bytes it encodes, not the text
const secret = Buffer.from(process.env.LNBOT_WEBHOOK_SECRET!, "hex");

const app = express();

// express.raw keeps the body as it arrived, which is what was signed
app.post("/hooks/lnbot", express.raw({ type: "application/json" }), (req, res) => {
  const expected = Buffer.from("sha256=" + createHmac("sha256", secret).update(req.body).digest("hex"));
  const given = Buffer.from(req.get("X-Webhook-Signature") ?? "");
  if (given.length !== expected.length || !timingSafeEqual(given, expected)) {
    return res.sendStatus(401);
  }

  const { event, data } = JSON.parse(req.body.toString("utf8"));
  if (event === "invoice.settled") console.log("invoice", data.number, "paid", data.amount);
  res.sendStatus(200);
});

app.listen(3000);
```

The same check in Python:

```python
import hashlib
import hmac
import os

# The secret is hex: the HMAC key is the 32 bytes it encodes
secret = bytes.fromhex(os.environ["LNBOT_WEBHOOK_SECRET"])

def from_lnbot(body: bytes, signature: str) -> bool:
    """body is the raw request body, before any JSON parsing."""
    expected = "sha256=" + hmac.new(secret, body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)
```

Answer with a 2xx status within 15 seconds. Any other answer, or none, is a failure, and the delivery is tried again after 10 seconds, 30 seconds, 1 minute, 5, 15 and 30 minutes, then 1, 2 and 4 hours: 10 attempts over about 8 hours. After the tenth failure the event is dropped; the invoice or payment is still in the [invoice](#get-v1-wallets-walletId-invoices) and [payment](#get-v1-wallets-walletId-payments) lists.

A retry sends the same body, and deliveries can arrive more than once or out of order, so act on each event once: `event` and `data.number` together identify it within a wallet. The signature covers only the body, so a recorded delivery would also verify if someone sent it again; acting on each event once covers that too.

A delivery doesn't say which wallet it is for. If one endpoint serves several wallets, register a different URL on each, such as `https://example.com/hooks/lnbot/wal_c7i0hnuoxxupuwej`, and keep each webhook's secret with its wallet ID.

## User keys

### POST /v1/keys/{slot}/rotate

Rotate a user key. Generates a new secret for the slot (0 = primary, 1 = secondary). The old key is immediately invalidated.

| Parameter | In | Type | Required | Description |
|-----------|-----|------|----------|-------------|
| `slot` | path | int | yes | 0 = primary, 1 = secondary |

**Response:**

```json
{
  "key": "uk_newrotated...",
  "name": "primary"
}
```

> The new key is returned once and cannot be retrieved again.

## Events

### GET /v1/wallets/{walletId}/events

A Server-Sent Events stream of everything that happens on the wallet. Works with either key.

```bash
curl -N https://api.ln.bot/v1/wallets/wal_c7i0hnuoxxupuwej/events \
  -H "Authorization: Bearer wk_..."
```

Events: `invoice.created`, `invoice.settled`, `payment.created`, `payment.settled`, `payment.failed`. Each arrives as a `data:` line holding a JSON object with `event`, `created_at` and `data` (the invoice or the payment), the same object, with the same snake_case keys, that a [webhook delivers](#receiving-webhooks). Keepalive comments every 30s.

In `payment.*` events, `max_fee` is the network fee held, `actual_fee` the network fee charged, and `failure_reason` one of the [reasons a payment fails](#post-v1-wallets-walletId-payments). An invoice paid just before it expired still sends `invoice.settled`.

## L402

### POST /v1/wallets/{walletId}/l402/challenges

Create an L402 challenge: a Lightning invoice and a macaroon. Returns the `WWW-Authenticate` value to send with an HTTP 402. `caveats` is an array of up to 10 `key=value` strings that go into the macaroon; `expirySeconds` adds an expiry caveat.

**Request body:**

```json
{
  "amount": 100,
  "description": "API access",
  "expirySeconds": 3600,
  "caveats": ["tier=pro"]
}
```

**Response:**

```json
{
  "macaroon": "AgELbG4uYm90...",
  "invoice": "lnbc1u1pn...",
  "paymentHash": "a1b2c3d4...",
  "expiresAt": "2026-01-15T11:30:00Z",
  "wwwAuthenticate": "L402 macaroon=\"...\", invoice=\"lnbc...\""
}
```

### POST /v1/wallets/{walletId}/l402/verify

Verify an L402 token: the macaroon's signature, the preimage (proof that the invoice was paid) and the caveats, such as expiry. Verification is stateless, with no database lookup, so a valid token keeps verifying until it expires, however many times it is presented. If each payment should buy one request, the paywall has to remember spent tokens; the 1.1 [L402 middleware](/docs/sdks#l402-libraries) does. A token that can't be parsed returns 400 rather than `"valid": false`.

**Request body:**

```json
{
  "authorization": "L402 AgELbG4uYm90...:a1b2c3d4..."
}
```

**Response:**

```json
{
  "valid": true,
  "paymentHash": "a1b2c3d4...",
  "caveats": ["expiry=1737000000"],
  "error": null
}
```

### POST /v1/wallets/{walletId}/l402/pay

Pay an L402 challenge from this wallet. Parses the `WWW-Authenticate` header, pays the invoice it contains and returns a ready-to-use `Authorization` header. With `wait` (the default), it waits up to `timeout` seconds (1 to 120, default 60) for settlement; if the payment hasn't settled by then, `authorization` is `null` and `status` says where it is. It pays whatever the invoice asks, so check the price first if that matters: the TypeScript and C# clients read it from the invoice. `maxFee` caps the network fee, with the same default and limits as [payments](#post-v1-wallets-walletId-payments); leave it out. `fee` in the response is the network fee charged.

**Request body:**

```json
{
  "wwwAuthenticate": "L402 macaroon=\"...\", invoice=\"lnbc...\"",
  "maxFee": null,
  "reference": null,
  "wait": true,
  "timeout": 60
}
```

**Response:**

```json
{
  "authorization": "L402 AgELbG4uYm90...:e5f6a7b8...",
  "paymentHash": "a1b2c3d4...",
  "preimage": "e5f6a7b8...",
  "amount": 100,
  "fee": 0,
  "paymentNumber": 5,
  "status": "settled"
}
```

## Backup and restore

### POST /v1/backup/recovery

Generate a new 12-word recovery passphrase, with a user key. The previous passphrase stops working.

**Response:**

```json
{
  "passphrase": "copper rival tunnel fiscal ..."
}
```

### POST /v1/restore/recovery

Get back into an account with its recovery passphrase. No authentication required. Restoring rotates the account's API keys: the response carries the new ones, and the old ones stop working.

**Request body:**

```json
{
  "passphrase": "orbit garden pilot smoke ..."
}
```

**Response:**

```json
{
  "walletId": "wal_c7i0hnuoxxupuwej",
  "name": "x4k7m2",
  "primaryKey": "uk_...",
  "secondaryKey": "uk_..."
}
```

### Passkeys

A WebAuthn passkey is the other way back in. These routes run in a browser, as the terminal on the [ln.bot home page](https://ln.bot) does: each `begin` returns a `sessionId` and the options to pass to `navigator.credentials.create()` (backup) or `navigator.credentials.get()` (restore), and `complete` takes the `sessionId` with the authenticator's response.

| Route | Auth | Does |
|-------|------|------|
| `POST /v1/backup/passkey/begin` | User key | Start registering a passkey |
| `POST /v1/backup/passkey/complete` | User key | Finish it, with the `attestation` |
| `POST /v1/restore/passkey/begin` | None | Start restoring |
| `POST /v1/restore/passkey/complete` | None | Finish, with the `assertion`; returns the same fields as the recovery route |

## Service status

Whether ln.bot is working, measured about once a minute. Both routes are public: no key is needed (sending one does no harm), any origin may call them, and they share the API's limit for public routes, 10 requests a minute per IP; over it they answer 429. The [status page](/status) is drawn from them.

### GET /v1/status

Right now. Refreshed every minute, with `Cache-Control: public, max-age=15`.

```bash
curl -s https://api.ln.bot/v1/status
```

**Response:**

```json
{
  "status": "degraded",
  "updatedAt": "2026-10-25T14:33:53.06+00:00",
  "notice": { "level": "warning", "message": "Sends are slower than usual.", "since": "2026-10-25T14:20:00+00:00", "until": null },
  "components": {
    "sending": {
      "status": "degraded",
      "inProgress": 3,
      "byStage": { "in_flight": 2, "retrying": 1 },
      "longestWaitSeconds": 412,
      "sentLastHour": 57,
      "failedLastHour": 4,
      "serviceFailuresLastHour": 0,
      "medianSeconds": 2.4,
      "p95Seconds": 9.1
    },
    "receiving": { "status": "operational", "creditedLastHour": 120, "creditBacklog": 0 },
    "node": { "status": "operational", "latencyMs": 310 },
    "webhooks": { "status": "operational", "backlog": 2 }
  }
}
```

| Field | Meaning |
|-------|---------|
| `status` | `operational`, `degraded`, `outage` or `unknown`. `unknown` means nothing was measured for 5 minutes, and the numbers are as old as `updatedAt`. |
| `updatedAt` | When it was measured; null if never |
| `notice` | A message from the operators, or null. `level` is `info` (no effect on the status), `warning` (the status is at least `degraded`) or `outage`; `message` is up to 500 characters, to show as it is |
| `components.*.status` | The same four values for `sending` (payments out), `receiving` (payments in), `node` (the Lightning node the service runs on) and `webhooks` (deliveries) |
| `sending.inProgress`, `sending.byStage` | Payments being sent now, and how many are at each [stage](#payment-stages): `queued`, `retrying`, `sending`, `in_flight`, `confirming` or `on_hold`. Stages with none are left out. |
| `sending.longestWaitSeconds` | How long the oldest of those has waited; null when none |
| `sending.sentLastHour`, `sending.failedLastHour` | Sent, and failed for any reason, in the last hour |
| `sending.serviceFailuresLastHour` | Of those failures, the ones the service caused; the rest were the invoice's or the route's |
| `sending.medianSeconds`, `sending.p95Seconds` | Request to settlement, median and 95th percentile; null when nothing was sent |
| `receiving.creditedLastHour`, `receiving.creditBacklog` | Incoming payments credited in the last hour, and waiting to be credited now |
| `node.latencyMs` | How long the node took to answer; null when it didn't |
| `webhooks.backlog` | Deliveries waiting to go out |

A part is `degraded` when sending has a payment that has waited over 5 minutes or 3 or more failures in the last hour that the service caused, when receiving can't credit payments or they pile up, when the node takes over 5 s to answer, or when webhook deliveries pile up. If the node doesn't answer at all, `node`, `sending` and `receiving` are all `outage`.

### GET /v1/status/history

The same, over time, for charts. `range` is `24h` (the default), `7d`, `30d` or `90d`; anything else returns 400. Responses carry `Cache-Control: public, max-age=60`.

| `range` | One bucket per |
|---------|----------------|
| `24h` | 5 minutes |
| `7d` | hour |
| `30d` | 6 hours |
| `90d` | day |

Buckets are aligned to UTC, so days start at 00:00 UTC, and the last one is still filling.

```bash
curl -s "https://api.ln.bot/v1/status/history?range=24h"
```

**Response** (cut to one bucket):

```json
{
  "range": "24h",
  "bucketSeconds": 300,
  "from": "2026-10-24T14:35:00+00:00",
  "to": "2026-10-25T14:35:12+00:00",
  "summary": {
    "samples": 1438,
    "uptime": {
      "overall": { "operational": 99.722, "degraded": 0.278, "outage": 0 },
      "sending": { "operational": 99.722, "degraded": 0.278, "outage": 0 },
      "receiving": { "operational": 100, "degraded": 0, "outage": 0 },
      "node": { "operational": 100, "degraded": 0, "outage": 0 },
      "webhooks": { "operational": 100, "degraded": 0, "outage": 0 }
    },
    "sent": 1312,
    "failed": 21,
    "serviceFailures": 2,
    "credited": 2875,
    "medianSeconds": 2.3,
    "p95Seconds": 8.6,
    "settleTimes": [
      { "upToSeconds": 1, "count": 40 },
      { "upToSeconds": 2, "count": 610 },
      { "upToSeconds": 3, "count": 380 },
      { "upToSeconds": 5, "count": 160 },
      { "upToSeconds": 10, "count": 80 },
      { "upToSeconds": 20, "count": 25 },
      { "upToSeconds": 30, "count": 9 },
      { "upToSeconds": 60, "count": 5 },
      { "upToSeconds": 120, "count": 2 },
      { "upToSeconds": 300, "count": 1 },
      { "upToSeconds": 600, "count": 0 },
      { "upToSeconds": null, "count": 0 }
    ],
    "avgLatencyMs": 296,
    "maxLatencyMs": 2140
  },
  "buckets": [
    {
      "at": "2026-10-24T14:35:00+00:00",
      "samples": 5,
      "overall": { "degraded": 0, "outage": 0 },
      "sending": { "degraded": 0, "outage": 0, "sent": 4, "failed": 0, "serviceFailures": 0, "medianSeconds": 2.1, "p95Seconds": 3.4, "maxInProgress": 1, "maxWaitSeconds": 3 },
      "receiving": { "degraded": 0, "outage": 0, "credited": 9, "maxBacklog": 0 },
      "node": { "degraded": 0, "outage": 0, "avgLatencyMs": 288, "maxLatencyMs": 340 },
      "webhooks": { "degraded": 0, "outage": 0, "maxBacklog": 1 }
    }
  ],
  "notices": [
    { "level": "warning", "message": "Sends are slower than usual.", "since": "2026-10-25T09:10:00+00:00", "until": "2026-10-25T09:40:00+00:00" }
  ]
}
```

- `samples` is how many measurements a bucket holds, about one a minute. `0` means it wasn't measured: treat it as no data, never as up or down.
- `degraded` and `outage` count the bucket's measurements that found that part, or ln.bot as a whole (`overall`), in that state; the rest found it operational. A bucket's uptime is `(samples - degraded - outage) / samples`.
- `sent`, `failed`, `serviceFailures` and `credited` count what happened during the bucket. `maxInProgress`, `maxWaitSeconds`, `maxBacklog` and `maxLatencyMs` are the highest seen in it, `avgLatencyMs` the average.
- `medianSeconds` and `p95Seconds` are approximate, computed from the `settleTimes` histogram, and null when nothing was sent. Its bounds are 1, 2, 3, 5, 10, 20, 30, 60, 120, 300 and 600 seconds; the last entry (`upToSeconds: null`) holds anything slower.
- `summary` covers the whole range. Its `uptime` is the percent of measured time in each state, null when nothing was measured.
- `notices` lists the operators' notices that were up during the range, oldest first, with `until` null while one is still up.
