> ## Documentation Index
> Fetch the complete documentation index at: https://docs.kaleidoswap.com/llms.txt
> Use this file to discover all available pages before exploring further.

# DApp Connectivity

> Connect the KaleidoSwap Extension to trusted DApps with the WebLN, WebBTC, RGB, and Nostr (NIP-07) providers, plus Nostr Wallet Connect, covering approval flow, permissions, and methods

## Overview

The KaleidoSwap Extension injects standard wallet providers into browser pages so DApps can interact with wallet capabilities after user approval. It follows the same provider conventions as other browser wallets (e.g., Alby), so most existing WebLN, WebBTC, and Nostr apps work without any KaleidoSwap-specific integration.

The extension injects:

* **`window.webln`** — [WebLN](https://www.webln.dev/) provider for Lightning (invoices, payments, message signing, keysend, LNURL).
* **`window.webbtc`** — WebBTC provider for on-chain Bitcoin (addresses, PSBT signing, BIP-322 message signing, broadcasting).
* **`window.nostr`** — full [NIP-07](https://github.com/nostr-protocol/nips/blob/master/07.md) provider for Nostr event signing and encryption.
* **`window.bitcoin`** — a Bitcoin Wallet Standard provider (Unisat/OKX/Leather-style) that some DApps probe for on-chain accounts.
* **`window.rgb`** — a KaleidoSwap-specific provider for RGB assets: issue, receive, send and track assets, and, with a Lightning node, pay and receive them over Lightning.

### How It Works

1. The KaleidoSwap Extension's **content script** is injected into web pages
2. The content script loads an **injected script** that adds `window.webln`, `window.webbtc`, `window.nostr`, `window.bitcoin`, and `window.rgb`
3. DApps call methods on those providers
4. Requests are routed to the KaleidoSwap Extension **background service worker**
5. Sensitive operations trigger a confirmation or permission prompt

### Provider Ready Events

The injected script dispatches ready events (both with and without the colon, for SDK parity) once the providers are installed:

* `webln:ready` / `weblnReady`
* `webbtc:ready` / `webbtcReady`
* `nostr:ready`
* `bitcoin:ready`
* `rgb:ready`

### Error Codes

Every provider rejects with an `Error` that carries a `code` property, so a DApp can tell a user's "no" from a wallet fault:

| Code | Meaning |
| - | - |
| `USER_REJECTED` | The user declined the connection or the confirmation prompt |
| `NOT_ENABLED` | The provider was called before `enable()` resolved for this origin |
| `METHOD_NOT_SUPPORTED` | The connected wallet cannot serve this method (for example RGB over Lightning on a node-less RGB wallet) |
| `INVALID_PARAMS` | Malformed arguments, e.g. a bad `assetId` or an any-amount invoice to `payLnInvoice` (`window.rgb`) |
| `ASSET_NOT_FOUND` | The wallet does not know this asset; omit `assetId` in `blindReceive` to accept any asset (`window.rgb`) |
| `POPUP_CLOSED` | The approval window was closed, or could not open, before the user answered. Not a refusal: the DApp may ask again |
| `REQUEST_INTERRUPTED` | The wallet restarted in the background before answering. The request may or may not have completed: check its outcome (for example the payment status) before repeating anything that moves funds |
| `NO_AVAILABLE_UTXOS` | No free colorable UTXO for a blinded receive; call `createUtxos()` or use `witnessReceive()` (`window.rgb`) |
| `UNSAFE_PSBT` | The PSBT would spend an input holding RGB assets, so it is refused before any prompt (`window.rgb`) |
| `INTERNAL_ERROR` | Anything else, with the wallet's message in `error.message` |

`window.rgb` only uses the codes defined by the WebRGB spec, so on that provider `POPUP_CLOSED` and `REQUEST_INTERRUPTED` arrive as `INTERNAL_ERROR`.

## WebLN Provider

`window.webln` follows the WebLN spec and can be used to:

* Request node information
* Create Lightning invoices
* Send Lightning payments
* Sign and verify messages
* Send keysend payments
* Handle LNURL requests
* Read balance details

### Supported Methods

| Method | Description |
| - | - |
| `enable()` | Connect the DApp and request approval for the origin |
| `getInfo()` | Get node information and supported methods |
| `sendPayment(paymentRequest)` | Pay a BOLT-11 invoice |
| `makeInvoice(args)` | Create a Lightning invoice |
| `signMessage(message)` | Sign a message with the node key |
| `verifyMessage(signature, message)` | Verify a signed message |
| `keysend(args)` | Send a spontaneous (keysend) payment |
| `lnurl(input)` | Handle an LNURL request |
| `getBalance()` | Get wallet balance details |
| `request(method, params)` | Low-level passthrough request |

### Example Usage

```javascript theme={null}
window.addEventListener('webln:ready', async () => {
  await window.webln.enable();

  const info = await window.webln.getInfo();

  const { paymentRequest } = await window.webln.makeInvoice({
    amount: 1000,
    defaultMemo: 'Coffee'
  });

  const { preimage } = await window.webln.sendPayment('lnbc...');
});
```

## WebBTC Provider

`window.webbtc` is an on-chain Bitcoin provider that can:

* Return a receive address
* Sign and finalize PSBTs
* Sign messages (BIP-322)
* Broadcast raw transactions
* Send on-chain payments

### Supported Methods

| Method | Description |
| - | - |
| `enable()` | Connect the DApp and request approval for the origin |
| `getInfo()` | Get node/network information and supported methods |
| `getAddress(opts?)` | Get an on-chain receive address. Pass `{ protocol: "LIQUID" }` (or another account) to get that account's address. Requires a connected site |
| `signPsbt(psbtHex)` | Sign wallet-owned inputs in a PSBT |
| `finalizePsbt(psbtHex)` | Finalize a signed PSBT into broadcastable hex |
| `broadcastTransaction(txHex)` | Broadcast a raw, signed transaction |
| `signMessage(message, address?)` | Sign a message (BIP-322) |
| `sendPayment(paymentRequest)` | Pay a BIP-21 or BOLT-11 request |
| `sendTransaction(address, amount)` | Send an on-chain payment |

> [!NOTE]
>
> Some DApps probe `window.bitcoin` (a Bitcoin Wallet Standard provider) instead of, or alongside, `window.webbtc`. It exposes `connect()`, `requestAccounts()`, `getAccounts()`, `getPublicKey()`, `signMessage()`, `signPsbt()`, `pushPsbt()`, `sendBitcoin()`, and `disconnect()` over the same wallet keys.

### PSBT Confirmations

Approving `signPsbt`, `finalizePsbt`, or `pushPsbt` is never blind-signing: the confirmation prompt decodes the PSBT and shows the destinations, amounts, and network fee before you approve. If the amounts cannot be decoded from the PSBT, the prompt shows an explicit warning instead.

![PSBT signing confirmation decoding the transaction total, each output with its destination and amount, and the network fee](https://mintcdn.com/kaleidoswap/jZkXeFEXDE4-8PkF/assets/images/extension/32-psbt-confirm.png?fit=max\&auto=format\&n=jZkXeFEXDE4-8PkF\&q=85\&s=9d7f4cc1fd920c2f281001f5acc29372)

## RGB Provider

`window.rgb` exposes the wallet's RGB runtime to DApps — the node-less RGB wallet or a connected RGB Lightning node, whichever the wallet is configured with — so an app can issue, receive, send and track RGB assets without running its own RGB backend. Every funds-touching call confirms in the extension popup, and the connect prompt lets the user restrict an origin to specific capabilities (minting is gated by its own `issueAsset` capability).

> [!NOTE]
>
> `window.rgb` ships from extension 0.3.0 on. It is not present in 0.2.0 builds; feature-detect it with the `rgb:ready` event rather than assuming it exists. The WebRGB 0.4 methods (`witnessReceive`, `createUtxos`, `cancelReceive`, `getBtcBalance`, `refresh`, `getAssetMetadata`, `signPsbt`, `signMessage`) ship from extension 0.4.0; check `getInfo().methods` before calling them.

### TypeScript Support

The [`@kaleidorg/webrgb`](https://github.com/kaleidoswap/webrgb) package ships the `window.rgb` declarations, provider discovery, an in-memory mock wallet and a conformance suite. [`SPEC.md`](https://github.com/kaleidoswap/webrgb/blob/main/SPEC.md) in that repository is the interface contract this provider implements.

```bash theme={null}
npm install @kaleidorg/webrgb
```

```typescript theme={null}
import { requestProvider, isProviderError, supports } from "@kaleidorg/webrgb";

// Resolves window.rgb, or waits for the wallet if the page ran first.
const rgb = await requestProvider({ enable: true });

const info = await rgb.getInfo();
if (supports(info, "makeLnInvoice")) {
  // the wallet's RGB runtime is a Lightning node
}
```

A rejection crosses a `postMessage` boundary on its way out of the wallet, so what a page catches is a plain `Error` carrying `code` — test it with `isProviderError(err)`, never `instanceof`.

`listAssets()` and `listTransfers()` always resolve to arrays from 0.3.0 on; `toAssetArray()` / `toTransferArray()` in the package tolerate wallets that wrap them.

### Building without the extension

`@kaleidorg/webrgb/mock` is an in-memory provider that enforces the same rules a real one does — `NOT_ENABLED` before `enable()`, `METHOD_NOT_SUPPORTED` for anything absent from `getInfo().methods`, a confirmation step you can make refuse — so a DApp can be built and tested with no wallet installed.

```typescript theme={null}
import { installMockProvider } from "@kaleidorg/webrgb/mock";

const { provider, uninstall } = installMockProvider({ protocol: "RGB_LN" });
```

The [playground](https://kaleidoswap.github.io/webrgb/) drives every method against the extension or against that mock, with a live log of calls, results and error codes. `@kaleidorg/webrgb/conformance` checks a wallet against the spec using read-only calls only, so it raises no confirmation.

### Discovery

`window.rgb` is a single slot and only one wallet can own it, so the extension also announces itself, EIP-6963 style. It dispatches `rgb:announceProvider` on load and in answer to any `rgb:requestProvider` a page dispatches, carrying `{ info: { uuid, name, rdns }, provider }` — its `rdns` is `com.kaleidoswap.extension`.

```typescript theme={null}
import { listProviders } from "@kaleidorg/webrgb";

// Every installed RGB wallet that answers, deduplicated by rdns.
for (const { info, provider } of await listProviders()) {
  console.log(info.name, info.rdns);
}
```

Discovery is additive: reading `window.rgb` directly still works, and `requestProvider()` settles on whichever arrives first.

### Supported Methods

| Method | Description |
| - | - |
| `enable()` | Connect the DApp; shares the origin approval with the other providers |
| `getInfo()` | `{ ready, network, protocol, methods }` — `ready` is `false` when no RGB wallet is connected |
| `getAddress()` | Bitcoin address of the RGB wallet, used to anchor RGB state |
| `blindReceive(args)` | Blinded-UTXO receive invoice (optional `assetId`: omit it for an invoice that accepts any asset; optional `amount`, `durationSeconds`, `minConfirmations`, never below 3) |
| `witnessReceive(args)` | Witness receive invoice: the sender funds a new output to this wallet, so it works without a free colorable UTXO (same arguments as `blindReceive`) |
| `createUtxos(args?)` | Create colorable UTXOs from the RGB wallet's bitcoin (optional `num`, `size`, `feeRate`); spends BTC, so it always confirms in the popup |
| `cancelReceive(recipientId)` | Cancel an unpaid receive this wallet created and release the UTXO it reserved; confirms in the popup; `{ cancelled }` |
| `getBtcBalance()` | Bitcoin held by the RGB wallet, split into vanilla and colored `{ settled, future, spendable }`, plus `freeColorableUtxos` |
| `refresh(assetId?)` | Sync and advance pending transfers; `{ refreshed }` |
| `getAssetMetadata(assetId)` | The asset's RGB metadata as the wallet knows it |
| `signPsbt(psbt, { finalize? })` | Sign the wallet-owned inputs of a base64 PSBT after a confirmation that shows each input; an input holding RGB assets rejects with `UNSAFE_PSBT`; `{ psbt, signedInputs }` |
| `signMessage(message)` | Sign a message with the wallet's message key (LND `signmessage` format) after confirmation, so a backend can authenticate the wallet; `{ signature }` |
| `issueAsset(args)` | Issue a new asset (`schema: "nia"`, `ticker`, `name`, `amounts`, `precision`); listed in `methods` only when the wallet can mint |
| `listAssets()` | Assets held by the wallet |
| `getAssetBalance(assetId)` | `{ assetId, balance }` for one asset |
| `sendAsset(args)` | Send against a receiver's RGB invoice (`{ invoice }`) or explicitly (`assetId`, `amount`, `recipientId`) |
| `listTransfers(assetId?)` | Transfer history, optionally filtered by asset |
| `getTransferStatus(id, assetId?)` | One transfer by index, recipient id or txid |
| `decodeRgbInvoice(invoice)` | What an invoice asks for — asset, amount, recipient — before sending against it. Read-only, so it raises no confirmation; `amount` is `null` for an any-amount invoice |
| `makeLnInvoice(args)` | BOLT-11 invoice carrying an asset (`assetId`, optional `assetAmount`, `amountSats`, `description`, `expirySeconds`); RGB Lightning wallets only |
| `payLnInvoice(args)` | Pay a BOLT-11 invoice that carries an asset (`{ invoice }`); RGB Lightning wallets only |
| `on(event, listener)` / `off(event, listener)` | Subscribe to `transferReceived` and `transferSettled` |

### Example Usage

```javascript theme={null}
window.addEventListener("rgb:ready", async () => {
  await window.rgb.enable();

  const info = await window.rgb.getInfo();
  // { ready: true, network: "signet", protocol: "RGB_L1" | "RGB_LN", methods: [...] }

  const { invoice } = await window.rgb.blindReceive({
    assetId: "rgb:…",
    amount: 1, // omit for an any-amount invoice
  });

  // Preferred: send against the receiver's RGB invoice
  await window.rgb.sendAsset({ invoice: "rgb:…/…utxob:…" });
});
```

### RGB over Lightning

When the wallet's RGB runtime is a Lightning node, `getInfo().protocol` is `"RGB_LN"` and `methods` also lists `makeLnInvoice` and `payLnInvoice`. On a node-less RGB wallet both reject with `METHOD_NOT_SUPPORTED`.

```javascript theme={null}
// Receive: a BOLT-11 invoice that carries the asset. `amountSats` is the
// Bitcoin the HTLC carries; the node enforces a floor and the wallet
// raises the figure to it, which is what the confirmation shows.
const { invoice, paymentHash } = await window.rgb.makeLnInvoice({
  assetId: "rgb:…",
  assetAmount: 5, // omit for an any-amount invoice
  description: "tickets",
});

// Pay: the invoice must carry an asset with an explicit amount. Plain
// Bitcoin invoices are refused — use window.webln.sendPayment() for those.
const { preimage, assetId, assetAmount } = await window.rgb.payLnInvoice({ invoice: "lnbc…" });
```

Both calls confirm in the popup with the asset, its units and the sats the HTLC carries. Spending allowances do not apply to asset payments: every `payLnInvoice` prompts.

### Events

```javascript theme={null}
window.rgb.on("transferReceived", (t) => { /* new incoming transfer seen */ });
window.rgb.on("transferSettled", (t) => { /* a known transfer reached Settled */ });
```

The payload is `{ assetId, transferId, status, kind, amount, recipientId, txid }`. Events are pushed by a background poll that runs about once a minute while a subscribed origin has an open tab, so there is no need to poll `listTransfers()` in a loop — but do not expect sub-minute latency.

## Nostr Provider (NIP-07)

The KaleidoSwap Extension injects a full **NIP-07** provider at `window.nostr`, so Nostr web apps can request the wallet's public key, sign events, and encrypt or decrypt direct messages. The Nostr identity is derived from the wallet recovery phrase (or an imported identity, when set).

### Supported Methods

| Method | Description |
| - | - |
| `getPublicKey()` | Return the wallet's Nostr public key (hex) |
| `signEvent(event)` | Sign a Nostr event |
| `getRelays()` | Return the configured relays |
| `signSchnorr(sigHash)` | Sign a 32-byte hash with the Nostr key |
| `hashAndSignSchnorr(message)` | Hash a message and sign the hash with the Nostr key |
| `nip04.encrypt(pubkey, plaintext)` / `nip04.decrypt(pubkey, ciphertext)` | NIP-04 encryption |
| `nip44.encrypt(pubkey, plaintext)` / `nip44.decrypt(pubkey, ciphertext)` | NIP-44 encryption |

### Example Usage

```javascript theme={null}
window.addEventListener('nostr:ready', async () => {
  const pubkey = await window.nostr.getPublicKey();

  const signed = await window.nostr.signEvent({
    kind: 1,
    content: 'Hello from KaleidoSwap',
    tags: [],
    created_at: Math.floor(Date.now() / 1000)
  });
});
```

Connecting a site for Nostr asks how much to approve up front. **Ask every time** (the default) confirms each request; **Sign-in only** auto-approves relay sign-in (NIP-42, kind 22242) and still asks for posts, deletions and everything else. A site connected only for WebLN or WebBTC must ask again before it can use your Nostr identity, and reading your public key or relays needs the site's Nostr permission.

If you deny a site's connection, `window.nostr` stops prompting for the rest of that page, and the wallet remembers the denial for that site for 10 minutes. A prompt that is closed or left unanswered only backs off briefly; it is not recorded as a denial.

## Nostr Connect (NIP-46)

Beyond in-page NIP-07 signing, the extension can act as a **remote signer** for Nostr apps that support [NIP-46](https://github.com/nostr-protocol/nips/blob/master/46.md) (nsecBunker). From **Settings > Nostr > Nostr Connect**, generate a `bunker://` connection string and paste it into the client app; signing requests then travel over Nostr relays and are approved in the extension. Active NIP-46 sessions appear in Connected Apps, where they can be reviewed and revoked.

![Nostr Connect remote signing screen with a listening status, the generated bunker connection string, and a revoke action](https://mintcdn.com/kaleidoswap/jZkXeFEXDE4-8PkF/assets/images/extension/34-nostr-connect-bunker.png?fit=max\&auto=format\&n=jZkXeFEXDE4-8PkF\&q=85\&s=8a21faf90bbdc298211274405b42dc70)

## Nostr Wallet Connect (NWC)

The extension can also expose the wallet to external apps over **Nostr Wallet Connect**: pair an app by scanning the pairing QR code, then control what it can do with **amount-aware budgets**. Zap payments (NIP-57) made through NWC are validated and correlated with wallet activity.

### For Developers

NWC is the integration path for anything that is not a web page in the same browser — mobile apps, desktop clients, bots and backends. The extension acts as the [NIP-47](https://github.com/nostr-protocol/nips/blob/master/47.md) **wallet service**; any NIP-47 client library works against it, so nothing KaleidoSwap-specific is required. The pairing string generated in **Settings > Nostr > Wallet Connect** has the standard shape:

```text theme={null}
nostr+walletconnect://<wallet-pubkey>?relay=<wss-relay-url>&secret=<client-secret>
```

The service announces NIP-47 version `1.0` with `nip04` and `nip44_v2` encryption and supports these methods:

| Method | Notes |
| - | - |
| `get_info` | Node alias, network, supported methods and encryptions |
| `get_balance` | Spendable Lightning balance |
| `make_invoice` | Create a BOLT-11 invoice |
| `pay_invoice` | Pay a BOLT-11 invoice; prompts unless the request fits the client's budget |
| `multi_pay_invoice` | Pay several invoices in one request, each judged against the budget |
| `lookup_invoice` | Look up an invoice by payment hash or BOLT-11 |
| `list_transactions` | Recent incoming and outgoing payments |
| `sign_message` | Sign a message with the node key |
| `pay_keysend` | Advertised only when the active Lightning backend supports keysend |

Each paired client gets its own spending budget, visible and revocable under **Settings > Connected Apps**. A payment within budget settles without a prompt; anything over it opens the same confirmation window the in-page providers use.

## Permission Prompts and Connected Apps

When a connected site makes a sensitive request, the KaleidoSwap Extension asks the user to approve or deny the action. The connect prompt lists the capabilities the site asks for (create invoices, send Lightning payments, sign messages, sign PSBTs, send Bitcoin, issue RGB assets, Nostr), and the site gets exactly the ones the user leaves on; an approval without a capability list grants nothing. Every prompt names the site that asks.

* **More requests need approval:** LNURL-auth, LNURL-withdraw and LNURL-channel go through the site's permissions and the unlock gate like any other request, and reading node info or addresses needs approval. A site cannot switch the wallet's active account.
* **Site payments are checked first:** Lightning invoices are fully decoded (checksum, network, expiry) and validated before any spending allowance is reserved, and refused when they are for another network than the paying wallet. The allowance is refunded only when the payment certainly did not go out.
* **Arkade:** sites cannot start a Lightning payment (WebLN, LNURL, WebBTC) from an Arkade account, because Arkade pays Lightning through an Intents swap whose solver fee and delayed proof of payment a site confirmation does not show. Pay from the wallet's Send screen instead.
* **Prompts are robust:** an approval window survives the wallet restarting in the background, a window closed without an answer is reported as `POPUP_CLOSED` rather than a refusal, and a locked wallet can be unlocked from the prompt with a passkey.
* **Other wallets keep working:** the injected providers are read-only but configurable, so the extension never replaces another wallet's `window.webln`, `webbtc`, `bitcoin`, `rgb` or `nostr`.

![Connection approval prompt showing the requesting site origin, the access it asks for, and the Nostr choice between Ask every time (default) and Sign-in only, with Deny and Allow actions](https://mintcdn.com/kaleidoswap/OYrIAX44Hz-HKeUZ/assets/images/extension/31-dapp-approval-prompt.png?fit=max\&auto=format\&n=OYrIAX44Hz-HKeUZ\&q=85\&s=84b960d0b27c25574cbecad26a3d2b93)

**Settings > Connected Apps** lists every site and app connected to the wallet, including NIP-46 (bunker) clients, showing which capabilities each one has been granted. You can revoke individual capabilities or disconnect a site entirely at any time.

![Connected Apps screen listing connected apps, Nostr Wallet Connect sessions, and a field to block a site](https://mintcdn.com/kaleidoswap/jZkXeFEXDE4-8PkF/assets/images/extension/33-connected-sites.png?fit=max\&auto=format\&n=jZkXeFEXDE4-8PkF\&q=85\&s=db50ff3e6bf135e58a238b70c0913a8c)

> [!WARNING]
>
> Always review what a DApp is requesting before approving. Only approve payments, invoices, asset sends, and signing requests from sites you trust.

## Nostr Identity

The KaleidoSwap Extension derives a Nostr identity from the wallet recovery phrase (or an imported identity) and exposes it both to web pages through `window.nostr` and in the extension settings.

### Nostr Key Management

Your Nostr keypair is managed in **Settings > Nostr > Nostr Identity**:

* View your public key (`npub`)
* View/copy the session private key when the wallet is unlocked
* Import a key, or revert an imported key to the identity derived from your recovery phrase

By default the identity is derived from the recovery phrase (NIP-06). If you already have a Nostr identity, you can import your own key (`nsec1…` or 64-character hex) during onboarding or later from **Settings > Nostr > Nostr Identity**; it is stored encrypted and used everywhere the derived identity would be.

## Browser Approval Flow

The KaleidoSwap Extension keeps DApp approvals user-driven:

1. A trusted site requests a connection, payment, invoice, asset, or signing action
2. The KaleidoSwap Extension routes the request through the content script and background service worker
3. The user reviews the details and approves or rejects the action

This keeps wallet-side actions explicit while still allowing DApps to use the KaleidoSwap Extension as a browser provider.

## Security Considerations

| Practice | Description |
| - | - |
| **Verify the site** | Check the URL before approving wallet connections |
| **Review requests** | Read invoice, asset, and signing details before approving |
| **Lock when done** | Lock the KaleidoSwap Extension when you are finished using DApps |
| **Limit exposure** | Only connect to trusted sites |

***

> [card] [Access the Beta](https://kaleidoswap.com/products/extension/beta)
>
> Request access to the KaleidoSwap Extension closed beta.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.