Add onchain-bitcoin skill

This commit is contained in:
Alex Gleason committed 2026-05-11 10:09:05 -07:00
1 parent 46119367c8
commit 2357913037
9 files changed
+1950

No files matched your search

+415
View File
@@ -0,0 +1,415 @@
---
name: onchain-bitcoin
description: Add an onchain Bitcoin wallet derived from the user's Nostr identity. Every Nostr keypair maps deterministically to a Taproot (P2TR) address via shared secp256k1 + BIP-340 cryptography, so the same nsec receives, signs PSBTs, and broadcasts transactions through mempool.space — with no LNURL, custodian, or HD derivation. Includes balance/tx queries, send pipeline (build → sign → broadcast), capability detection across nsec / NIP-07 / NIP-46 signers, and kind 8333 onchain zaps with on-chain verification.
---
# Onchain Bitcoin Wallet
Nostr public keys (`npub` / 32-byte hex) are byte-for-byte identical to Bitcoin Taproot internal keys (BIP-340 / BIP-341): both are 32-byte x-only secp256k1 keys. This means **every Nostr identity already owns a Bitcoin address** — no key conversion, no HD derivation, no LNURL provider needed.
This skill ships a complete in-app wallet:
- Derive the user's `bc1p…` Taproot address from their pubkey
- Display balance, USD value, and transaction history
- Send Bitcoin via a PSBT pipeline that works with **all three** Nostrify signer types
- Publish and verify NIP-73 / kind 8333 "onchain zaps"
- Render NIP-73 `bitcoin:tx:` and `bitcoin:address:` identifiers in the existing `/:nip19` router
## Why It Works
| Property | Nostr | Bitcoin Taproot |
|---|---|---|
| Curve | secp256k1 | secp256k1 |
| Signature scheme | Schnorr (BIP-340) | Schnorr (BIP-340) |
| Public key format | 32-byte x-only | 32-byte x-only |
Because the formats match, a Nostr pubkey **is** a Taproot internal key (`P`). The on-chain output key is the standard BIP-341 tweak `Q = P + taggedHash("TapTweak", P) · G` with no script tree (key-path-only spend), encoded as bech32m with HRP `bc` and witness version 1 — always producing a `bc1p…` address.
`bitcoinjs-lib`'s `payments.p2tr({ internalPubkey })` performs the tweak + bech32m encoding internally.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/lib/bitcoin.ts` | `src/lib/bitcoin.ts` |
| `files/lib/bitcoin-signers.ts` | `src/lib/bitcoin-signers.ts` |
| `files/hooks/useBitcoinWallet.ts` | `src/hooks/useBitcoinWallet.ts` |
| `files/hooks/useBitcoinAddress.ts` | `src/hooks/useBitcoinAddress.ts` |
| `files/hooks/useBitcoinTx.ts` | `src/hooks/useBitcoinTx.ts` |
| `files/hooks/useBitcoinSigner.ts` | `src/hooks/useBitcoinSigner.ts` |
| `files/hooks/useOnchainZap.ts` | `src/hooks/useOnchainZap.ts` |
| `files/hooks/useOnchainZaps.ts` | `src/hooks/useOnchainZaps.ts` |
These files are framework-only. The wallet page, send dialog, and on-chain zap UI are built on top of them.
## Setup Instructions
### 1. Install Dependencies
```bash
npm install bitcoinjs-lib @bitcoinerlab/secp256k1 ecpair tiny-secp256k1
```
`buffer` is already a dependency of the template; if you removed it, also `npm install buffer`.
| Package | Role |
|---|---|
| `bitcoinjs-lib` | P2TR address derivation, PSBT construction & finalization |
| `@bitcoinerlab/secp256k1` | secp256k1 ECC backend (Schnorr, key tweaking) |
| `ecpair` | Key pair creation and BIP-341 tweaking for local nsec signing |
| `tiny-secp256k1` | Peer dep of `ecpair` (low-level ECC) |
### 2. Initialize ECC in `main.tsx`
The Buffer polyfill is already imported in mkstack's `main.tsx`. Add the ECC initialization right after it. **`bitcoin.initEccLib(ecc)` must run before any wallet code** — otherwise `payments.p2tr()` and Schnorr operations throw.
```tsx
// src/main.tsx
import { createRoot } from 'react-dom/client';
// Import polyfills first (Buffer must exist before bitcoinjs-lib is loaded)
import './lib/polyfills.ts';
// Initialize ECC for bitcoinjs-lib (Taproot / Schnorr support)
import * as bitcoin from 'bitcoinjs-lib';
import * as ecc from '@bitcoinerlab/secp256k1';
bitcoin.initEccLib(ecc);
import { ErrorBoundary } from '@/components/ErrorBoundary';
import App from './App.tsx';
import './index.css';
createRoot(document.getElementById('root')!).render(
<ErrorBoundary>
<App />
</ErrorBoundary>
);
```
`src/lib/bitcoin.ts` calls `initEccLib` again lazily inside signing/finalizing functions as a defensive measure, so test files and ad-hoc imports also work — but the early init in `main.tsx` is what the live app relies on.
### 3. Copy the Skill Files
Copy every file from `files/` into the matching directory under `src/`. The hook files import each other and `@/lib/bitcoin` / `@/lib/bitcoin-signers`, so paths must match exactly.
### 4. Wire the BTC-Capable Signers into `useCurrentUser`
The default `useCurrentUser` uses Nostrify's `NUser.from*Login` factories, which return signers without a `signPsbt` method. Replace them with the BTC-extended subclasses from this skill so the same `user.signer` instance can also sign PSBTs.
Edit `src/hooks/useCurrentUser.ts`:
```tsx
import { useNostr } from '@nostrify/react';
import { type NLoginType, NUser, useNostrLogin } from '@nostrify/react/login';
import { NSecSigner } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useCallback, useMemo } from 'react';
import { useAuthor } from './useAuthor.ts';
import { NSecSignerBtc, NBrowserSignerBtc, NConnectSignerBtc } from '@/lib/bitcoin-signers';
export function useCurrentUser() {
const { nostr } = useNostr();
const { logins } = useNostrLogin();
const loginToUser = useCallback((login: NLoginType): NUser => {
switch (login.type) {
case 'nsec': {
const sk = nip19.decode(login.data.nsec) as { type: 'nsec'; data: Uint8Array };
return new NUser(login.type, login.pubkey, new NSecSignerBtc(sk.data));
}
case 'bunker': {
const clientSk = nip19.decode(login.data.clientNsec) as { type: 'nsec'; data: Uint8Array };
const clientSigner = new NSecSigner(clientSk.data);
return new NUser(
login.type,
login.pubkey,
new NConnectSignerBtc({
relay: nostr.group(login.data.relays),
pubkey: login.data.bunkerPubkey,
signer: clientSigner,
timeout: 60_000,
}),
);
}
case 'extension':
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc());
default:
throw new Error(`Unsupported login type: ${login.type}`);
}
}, [nostr]);
const users = useMemo(() => {
const users: NUser[] = [];
for (const login of logins) {
try { users.push(loginToUser(login)); }
catch (error) { console.warn('Skipped invalid login', login.id, error); }
}
return users;
}, [logins, loginToUser]);
const user = users[0] as NUser | undefined;
const author = useAuthor(user?.pubkey);
return { user, users, ...author.data };
}
```
This is the **only** change required for the wallet to function across all three login types. If you skip it, the hooks still compile but `useBitcoinSigner` will report `'unsupported'` for every user.
## Core APIs
### Address derivation
```ts
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
nostrPubkeyToBitcoinAddress('d6889cb0…300a961d'); // 'bc1p2wsldez…'
npubToBitcoinAddress('npub1…'); // 'bc1p…'
```
Both return `''` for malformed input or off-curve pubkeys (so UIs can render an empty state without try/catch).
### `useBitcoinWallet()` — current user's wallet
```tsx
import { useBitcoinWallet } from '@/hooks/useBitcoinWallet';
import { satsToUSD, formatBTC } from '@/lib/bitcoin';
function WalletWidget() {
const { bitcoinAddress, addressData, btcPrice, transactions, isLoading } = useBitcoinWallet();
if (isLoading) return <Skeleton className="h-10 w-40" />;
if (!addressData) return null;
return (
<div>
<div>{btcPrice ? satsToUSD(addressData.totalBalance, btcPrice) : '—'}</div>
<div>{formatBTC(addressData.totalBalance)} BTC</div>
<code>{bitcoinAddress}</code>
</div>
);
}
```
Auto-refreshes every 30 s (balance + transactions) and 60 s (BTC price).
### `useBitcoinAddress(address)` / `useBitcoinTx(txid)` — NIP-73 detail pages
Use these from the `/:nip19` router (`src/pages/NIP19Page.tsx`) when an `i` tag is `bitcoin:address:bc1p…` or `bitcoin:tx:abc123…`. Both also return the BTC price for USD display.
Parse NIP-73 Bitcoin identifiers with this regex:
```ts
const txMatch = uri.match(/^bitcoin:tx:([0-9a-f]{64})$/i);
const addrMatch = uri.match(/^bitcoin:address:(.+)$/);
```
### Sending Bitcoin: the PSBT pipeline
The send flow is intentionally split into three pure functions so any signer (local key, NIP-07, NIP-46) can plug in at step 2:
```ts
import {
buildUnsignedPsbt,
finalizePsbt,
broadcastTransaction,
fetchUTXOs,
getFeeRates,
} from '@/lib/bitcoin';
import { useBitcoinSigner } from '@/hooks/useBitcoinSigner';
import { useCurrentUser } from '@/hooks/useCurrentUser';
const { user } = useCurrentUser();
const { signPsbt, canSignPsbt } = useBitcoinSigner();
if (!canSignPsbt || !signPsbt || !user) throw new Error("Login can't sign PSBTs.");
const senderAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
const [utxos, rates] = await Promise.all([fetchUTXOs(senderAddress), getFeeRates()]);
// 1. Build (no key material required — pubkey only)
const { psbtHex, fee } = buildUnsignedPsbt(
user.pubkey,
recipientAddress,
amountSats,
utxos,
rates.halfHourFee, // sat/vB
);
// 2. Sign — dispatched through the user's signer
const signedHex = await signPsbt(psbtHex);
// 3. Finalize + broadcast
const txHex = finalizePsbt(signedHex);
const txid = await broadcastTransaction(txHex);
```
Key facts about `buildUnsignedPsbt`:
- All available UTXOs are consumed as inputs (no coin selection — keep it predictable).
- Fee uses `ceil((numInputs · 57.5 + numOutputs · 43 + 10.5) · feeRate)`.
- Change is added back to the sender's own Taproot address **only** if it's ≥ 546 sats (dust limit). Below dust, change is donated to fees and the tx has 1 output instead of 2.
- Throws `Insufficient funds` if `amount + fee > total UTXO value`.
For send-max, use `maxSendable(totalBalance, numInputs, feeRate)` — it correctly subtracts a 1-output fee.
### Signer capability detection
`useBitcoinSigner()` returns one of three states for the active login:
| Login | Capability |
|---|---|
| **nsec** | Always `'supported'` — local signing with the private key. |
| **NIP-07 extension** | Probes `window.nostr.signPsbt` (re-tries every 250 ms for up to 3 s). `'supported'`, `'unsupported'`, or `'unknown'` while the extension is still injecting. |
| **NIP-46 bunker** | `'unknown'` initially (NIP-46 has no capability-discovery RPC). Flips to `'unsupported'` for the rest of the session once a `sign_psbt` call returns a "method not found"-style error — see `reportSignerUnsupported()` and `isSignerCapabilityError()`. |
The send dialog should render an "unsupported" panel (with QR-code fallback for receiving funds) whenever `capability === 'unsupported'`, and let `'unknown'` users attempt the send. `useOnchainZap`'s `onError` handler already calls `reportSignerUnsupported(user.pubkey)` automatically, so the second send attempt with the same bunker won't re-attempt.
## Onchain Zaps (kind 8333)
A Bitcoin equivalent of NIP-57 Lightning zaps. Defined in this skill — the kind number mirrors the convention `9735 = Lightning P2P port`, `8333 = Bitcoin mainnet P2P port`.
> If the project has a `NIP.md` file, **document this kind there**. If it doesn't exist, create one with the kind 8333 schema below.
### Event Structure
```json
{
"kind": 8333,
"pubkey": "<sender-pubkey>",
"content": "Great post!",
"tags": [
["i", "bitcoin:tx:<txid>"],
["p", "<recipient-pubkey>"],
["amount", "<sats>"],
["e", "<target-event-id>"],
["alt", "Bitcoin zap: 25000 sats"]
]
}
```
| Tag | Required | Notes |
|---|---|---|
| `i` | Yes | NIP-73 identifier `bitcoin:tx:<txid>` (64-char lowercase hex). |
| `p` | Yes | Recipient pubkey. |
| `amount` | Yes | Sats paid to the recipient (may be capped by verifier). |
| `e` | If zapping an event | Event being zapped. |
| `a` | If zapping an addressable event (kind 30000–39999) | `<kind>:<pubkey>:<d-tag>`. |
| `alt` | Yes | NIP-31 fallback. |
If neither `e` nor `a` is present, the zap targets the recipient's profile.
### Publishing — `useOnchainZap(target)`
Builds + signs + broadcasts the Bitcoin transaction, then publishes the kind 8333 event:
```tsx
import { useOnchainZap } from '@/hooks/useOnchainZap';
function ZapButton({ target }: { target: NostrEvent }) {
const { zap, isZapping, progress, canZap } = useOnchainZap(target);
if (!canZap) return null; // not logged in, self-zap, or PSBT-incapable signer
return (
<button
disabled={isZapping}
onClick={() => zap({ amountSats: 5000, comment: 'Great post!', feeSpeed: 'halfHour' })}
>
{isZapping ? `${progress}…` : 'Zap 5k sats'}
</button>
);
}
```
`progress` cycles through `'building' → 'signing' → 'broadcasting' → 'publishing' → 'idle'`.
### Verification — never trust the `amount` tag
The `amount` tag is self-reported. **Always verify on-chain before counting it toward zap totals.** The skill's verifier:
1. Extracts the txid from the `i` tag.
2. Fetches the transaction from mempool.space.
3. Derives the recipient's expected Taproot address from the `p` pubkey.
4. Sums tx outputs paying that address. **Change outputs to the sender are excluded automatically** — they go to a different address.
5. Caps the displayed amount at the verified amount.
6. Rejects events where verified amount = 0, where sender = recipient (self-zap), or where the txid is malformed.
Use `useOnchainZaps(target)` for a list of verified zaps targeting an event, or `useVerifiedOnchainZap(event)` for a single event:
```tsx
import { useOnchainZaps } from '@/hooks/useOnchainZaps';
function OnchainZapList({ target }: { target: NostrEvent }) {
const { zaps, totalSats, isLoading } = useOnchainZaps(target);
if (isLoading) return <Skeleton className="h-6 w-24" />;
return <div>{totalSats.toLocaleString()} sats from {zaps.length} zappers</div>;
}
```
`useOnchainZaps` queries `{ kinds: [8333], '#e': [target.id] }` (and `#a` for addressables), dedupes by txid (preferring the earliest event for any given tx), and verifies each one via mempool.space. Cached for 60 s per (txid, recipient).
### Combining with NIP-57 totals
When showing total zaps for a post, sum verified amounts from **both** kind 9735 (Lightning) and kind 8333 (onchain) — they're complementary settlement layers, not alternatives.
## Mempool.space API Cheat Sheet
All endpoints are public and unauthenticated:
| Endpoint | Used by |
|---|---|
| `GET /address/{addr}` | `fetchAddressData` — balance + tx counts |
| `GET /address/{addr}/txs` | `fetchTransactions` — recent tx history |
| `GET /address/{addr}/utxo` | `fetchUTXOs` — for building send PSBTs |
| `GET /tx/{txid}` | `fetchTxDetail` + zap verifier — full inputs/outputs |
| `GET /fee-estimates` | `getFeeRates` — sat/vB per block target |
| `POST /tx` | `broadcastTransaction` — body is raw tx hex, returns txid |
You can swap to a self-hosted Esplora instance by changing the `MEMPOOL_API` constant in `src/lib/bitcoin.ts`.
## Security Considerations
> **The same private key controls both the user's Nostr identity and the Bitcoin funds at the derived address.** This is by design, but increases the blast radius of every common Nostr-client risk.
- **localStorage nsec is now spendable Bitcoin.** The `nostr-security` skill's XSS warnings apply doubly here. Treat `dangerouslySetInnerHTML`, unsanitized URLs, and CSS injection as on-par with stealing money. Load the `nostr-security` skill before merging anything that touches user input.
- **Extensions and bunkers never see the raw key.** Only the unsigned PSBT (no secret material) is passed to the signer. The PSBT format (BIP-174) carries `witnessUtxo` values and outputs, so a properly-implemented signer can show users what they're signing before approving.
- **Mainnet only.** This skill ships mainnet derivation and uses the public mempool.space API. Testnet/signet support would require a different `network`, a different Esplora endpoint, and is out of scope for kind 8333 verification.
- **Single-key, no HD.** Every Nostr keypair maps to exactly one Bitcoin address. There's no BIP-32 path. This is fine for a wallet tied to identity, but means the user has no way to rotate the address without losing their identity.
- **Users need a backup of their nsec before receiving funds.** Surfacing this to the user (e.g. on the wallet page) is the implementing app's responsibility.
- **Self-zap rejection.** `verifyOnchainZap` already drops events where `event.pubkey === recipient pubkey`. Don't relax this check — self-zaps are trivial to fabricate.
## Testing the Wallet
For end-to-end manual testing without spending real BTC:
1. Generate two Nostr keys (`nak generate` or any client).
2. Send a small amount of mainnet BTC (e.g. 5,000 sats) to key A's derived address.
3. Log in as key A, open the wallet page, confirm balance appears within ~30 s.
4. Use the send flow to forward sats to key B's derived address.
5. Verify the transaction shows up in B's wallet and the kind 8333 event (if zapping a post) is queryable from a relay.
Mempool.space confirms unconfirmed transactions within ~10 s of broadcast and provides a `/tx/<txid>` web view for verification.
## Building UI On Top
This skill provides only the framework. To build the user-facing surfaces:
- **Wallet page** (`/wallet`) — balance + QR code (`bitcoin:<address>`) + tx list. Use `useBitcoinWallet`. Render the QR with the `qrcode` package (`npm install qrcode`).
- **Send dialog** — recipient input (accepts both raw `bc1…` addresses and `npub1…`), amount input with USD conversion, fee-speed selector, confirm/success steps. Use `useBitcoinSigner` to gate the form, `validateBitcoinAddress` for validation, `npubToBitcoinAddress` for npub recipients, and the PSBT pipeline shown above.
- **NIP-73 detail pages** — extend `NIP19Page.tsx` to dispatch `bitcoin:tx:` and `bitcoin:address:` identifiers to detail components powered by `useBitcoinTx` / `useBitcoinAddress`.
- **Onchain zap button** — drop `useOnchainZap` into the existing zap dialog as a Bitcoin tab, alongside Lightning. Show the QR-code BIP-21 fallback (`bitcoin:<address>?amount=<btc>`) when capability is `'unsupported'`.
## References
- [BIP-340: Schnorr Signatures for secp256k1](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki) — shared with NIP-01 keys
- [BIP-341: Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki) — defines the TapTweak and key-path spend
- [BIP-350: Bech32m](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki) — `bc1p…` encoding
- [BIP-174: PSBT format](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki) — what `signPsbt` operates on
- [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md) — defines secp256k1 x-only keys for Nostr
- [NIP-07](https://github.com/nostr-protocol/nips/blob/master/07.md) — `window.nostr` extension API; `signPsbt` is the optional Bitcoin extension
- [NIP-46](https://github.com/nostr-protocol/nips/blob/master/46.md) — remote signers; `sign_psbt` is the optional Bitcoin command
- [NIP-57](https://github.com/nostr-protocol/nips/blob/master/57.md) — Lightning zaps (the kind 8333 design mirrors this)
- [NIP-73](https://github.com/nostr-protocol/nips/blob/master/73.md) — external content identifiers (`bitcoin:tx:` / `bitcoin:address:`)
- [mempool.space API docs](https://mempool.space/docs/api/rest)
@@ -0,0 +1,25 @@
import { useQuery } from '@tanstack/react-query';
import { fetchAddressDetail, fetchBtcPrice } from '@/lib/bitcoin';
/**
* Fetch full address details (balance + recent txs) via the mempool.space API.
* Also fetches the current BTC/USD price for display.
*/
export function useBitcoinAddress(address: string) {
const { data: addressDetail, isLoading, error, refetch } = useQuery({
queryKey: ['bitcoin-address-detail', address],
queryFn: () => fetchAddressDetail(address),
enabled: !!address,
refetchInterval: 30_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
return { addressDetail, btcPrice, isLoading, error, refetch };
}
@@ -0,0 +1,201 @@
import { useEffect, useMemo, useState } from 'react';
import { useNostrLogin } from '@nostrify/react/login';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { type BtcSigner, hasBtcSigning } from '@/lib/bitcoin-signers';
/**
* Three possible states for Bitcoin PSBT signing capability:
*
* - `supported` — Known to work (nsec login, or extension that exposes `signPsbt`).
* - `unsupported` — Known not to work (extension without `signPsbt`, or a remote
* signer that has already rejected a `sign_psbt` request).
* - `unknown` — Cannot be determined in advance. Applies to NIP-46 bunker
* logins, since NIP-46 has no standard capability-discovery
* RPC. Treat as "attempt, then propagate the error if it
* fails" — the UI should allow the attempt but fall back to
* the unsupported state when a `sign_psbt` call rejects with
* a capability error (see `reportSignerUnsupported`).
*/
export type BitcoinSignerCapability = 'supported' | 'unsupported' | 'unknown';
/**
* Module-level registry of bunker pubkeys that have been observed to reject
* `sign_psbt`. Persists for the lifetime of the page so that the user doesn't
* see the "attempt then fail" path twice for the same bunker.
*/
const knownUnsupportedBunkers = new Set<string>();
/**
* Mark a bunker (keyed by user pubkey) as known-unsupported for PSBT signing.
* Subsequent renders of `useBitcoinSigner` will return `'unsupported'` for
* that user.
*/
export function reportSignerUnsupported(pubkey: string): void {
knownUnsupportedBunkers.add(pubkey);
// Dispatch a DOM event so hook consumers can re-render without plumbing a
// shared store through the app. Listened to by `useBitcoinSigner`.
window.dispatchEvent(new CustomEvent('bitcoin-signer-unsupported', { detail: pubkey }));
}
/**
* Clear the unsupported-bunker memo for a pubkey (or all pubkeys). Called
* when the user logs out or switches accounts, so that a re-login with a
* potentially-upgraded bunker doesn't inherit the previous rejection.
*/
export function clearSignerUnsupported(pubkey?: string): void {
if (pubkey === undefined) {
knownUnsupportedBunkers.clear();
} else {
knownUnsupportedBunkers.delete(pubkey);
}
window.dispatchEvent(new CustomEvent('bitcoin-signer-cleared', { detail: pubkey ?? '*' }));
}
/**
* Hook that exposes Bitcoin PSBT signing capability for the current login.
*
* Capability is probed eagerly for known login types so that the UI can
* replace itself with an "unsupported" state before the user attempts to
* sign anything (rather than surfacing a toast after the fact).
*
* - **nsec** → always `'supported'` (local signing).
* - **extension** → probes `window.nostr.signPsbt`. Returns `'supported'` if
* present, `'unsupported'` if absent, or `'unknown'` while
* still waiting for the extension to inject `window.nostr`.
* - **bunker** → `'unknown'` by default (NIP-46 has no capability RPC).
* Flips to `'unsupported'` for the session once a
* `sign_psbt` attempt has rejected with a capability error
* (see `reportSignerUnsupported`).
*/
export function useBitcoinSigner() {
const { user } = useCurrentUser();
const { logins } = useNostrLogin();
const loginType = logins[0]?.type;
// ── Extension: probe window.nostr.signPsbt ───────────────────
const [extensionProbe, setExtensionProbe] = useState<BitcoinSignerCapability>(() => {
if (loginType !== 'extension') return 'unknown';
const n = (globalThis as { nostr?: Record<string, unknown> }).nostr;
if (n && typeof n.signPsbt === 'function') return 'supported';
if (n) return 'unsupported';
return 'unknown';
});
useEffect(() => {
if (loginType !== 'extension') return;
// Re-probe periodically in case the extension injects `window.nostr` late.
let cancelled = false;
const probe = () => {
const n = (globalThis as { nostr?: Record<string, unknown> }).nostr;
if (!n) return false;
setExtensionProbe(typeof n.signPsbt === 'function' ? 'supported' : 'unsupported');
return true;
};
if (probe()) return;
const interval = setInterval(() => {
if (cancelled) return;
if (probe()) clearInterval(interval);
}, 250);
// Stop polling after 3 s — if the extension hasn't shown up by then it
// likely isn't going to.
const stop = setTimeout(() => clearInterval(interval), 3000);
return () => { cancelled = true; clearInterval(interval); clearTimeout(stop); };
}, [loginType]);
// ── Bunker: listen for capability-failure events ─────────────
const [bunkerUnsupported, setBunkerUnsupported] = useState(() =>
user ? knownUnsupportedBunkers.has(user.pubkey) : false,
);
// Reset memoised state whenever the active user changes (login/logout/
// account switch) so a fresh login with a potentially-upgraded signer
// isn't permanently tainted by a previous session's rejection. On full
// logout we also clear the module-level registry entirely, so logging back
// in lets the user try their bunker again.
useEffect(() => {
if (!user) {
setBunkerUnsupported(false);
knownUnsupportedBunkers.clear();
return;
}
setBunkerUnsupported(knownUnsupportedBunkers.has(user.pubkey));
}, [user?.pubkey]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (loginType !== 'bunker' || !user) return;
const onUnsupported = (e: Event) => {
const detail = (e as CustomEvent<string>).detail;
if (detail === user.pubkey) setBunkerUnsupported(true);
};
const onCleared = (e: Event) => {
const detail = (e as CustomEvent<string>).detail;
if (detail === '*' || detail === user.pubkey) setBunkerUnsupported(false);
};
window.addEventListener('bitcoin-signer-unsupported', onUnsupported);
window.addEventListener('bitcoin-signer-cleared', onCleared);
return () => {
window.removeEventListener('bitcoin-signer-unsupported', onUnsupported);
window.removeEventListener('bitcoin-signer-cleared', onCleared);
};
}, [loginType, user]);
// ── Aggregate capability ─────────────────────────────────────
const capability: BitcoinSignerCapability = useMemo(() => {
if (!user) return 'unsupported';
switch (loginType) {
case 'nsec':
// Local signing is always available for nsec logins.
return 'supported';
case 'extension':
return extensionProbe;
case 'bunker':
return bunkerUnsupported ? 'unsupported' : 'unknown';
default:
// Unknown login type: fall back to the structural check.
return hasBtcSigning(user.signer) ? 'unknown' : 'unsupported';
}
}, [user, loginType, extensionProbe, bunkerUnsupported]);
const btcSigner = useMemo((): BtcSigner | null => {
if (!user || capability === 'unsupported') return null;
if (hasBtcSigning(user.signer)) return user.signer;
return null;
}, [user, capability]);
return {
/** Detailed capability state. See {@link BitcoinSignerCapability}. */
capability,
/** True when capability is `'supported'` or `'unknown'` (attempt allowed). */
canSignPsbt: capability !== 'unsupported' && btcSigner !== null,
/**
* Sign a hex-encoded PSBT. Throws if the signer doesn't support it.
* The returned hex is a signed (but not finalized) PSBT.
*/
signPsbt: btcSigner
? (psbtHex: string) => btcSigner.signPsbt(psbtHex)
: null,
};
}
/**
* Classify a signer error as a "capability error" (the signer fundamentally
* cannot sign PSBTs) versus a transient/operational error (network blip,
* user cancellation, malformed PSBT, etc.).
*
* Used by `useOnchainZap` to decide whether a failed send should flip the
* UI into the `'unsupported'` state or just surface a normal error toast.
*/
export function isSignerCapabilityError(err: unknown): boolean {
if (!err) return false;
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
return (
msg.includes('does not support') ||
msg.includes("doesn't support") ||
msg.includes('signpsbt') ||
msg.includes('sign_psbt')
);
}
@@ -0,0 +1,25 @@
import { useQuery } from '@tanstack/react-query';
import { fetchTxDetail, fetchBtcPrice } from '@/lib/bitcoin';
/**
* Fetch full transaction details for a Bitcoin txid via the mempool.space API.
* Also fetches the current BTC/USD price for display.
*/
export function useBitcoinTx(txid: string) {
const { data: tx, isLoading, error } = useQuery({
queryKey: ['bitcoin-tx-detail', txid],
queryFn: () => fetchTxDetail(txid),
enabled: !!txid,
staleTime: 60_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
return { tx, btcPrice, isLoading, error };
}
@@ -0,0 +1,71 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { nostrPubkeyToBitcoinAddress, fetchAddressData, fetchBtcPrice, fetchTransactions } from '@/lib/bitcoin';
/**
* Hook that derives a Bitcoin Taproot address from the current user's Nostr
* pubkey and fetches the on-chain balance from the mempool.space API.
*
* Balance auto-refreshes every 30 seconds while the component is mounted.
* BTC/USD price refreshes every 60 seconds.
*/
export function useBitcoinWallet() {
const { user } = useCurrentUser();
const bitcoinAddress = useMemo(() => {
if (!user) return '';
return nostrPubkeyToBitcoinAddress(user.pubkey);
}, [user]);
const {
data: addressData,
isLoading,
error,
refetch,
} = useQuery({
queryKey: ['bitcoin-balance', bitcoinAddress],
queryFn: () => fetchAddressData(bitcoinAddress),
enabled: !!bitcoinAddress,
refetchInterval: 30_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
const {
data: transactions,
isLoading: isLoadingTxs,
} = useQuery({
queryKey: ['bitcoin-txs', bitcoinAddress],
queryFn: () => fetchTransactions(bitcoinAddress),
enabled: !!bitcoinAddress,
refetchInterval: 30_000,
});
return {
/** The derived bc1p... Taproot address. */
bitcoinAddress,
/** Balance and transaction data (undefined while loading). */
addressData,
/** Current BTC price in USD. */
btcPrice,
/** Transaction history for the address. */
transactions,
/** Whether the initial balance fetch is in progress. */
isLoading,
/** Whether transactions are still loading. */
isLoadingTxs,
/** Error from the balance query, if any. */
error,
/** Manually trigger a balance refresh. */
refetch,
/** The current user's hex pubkey (convenience). */
pubkey: user?.pubkey ?? '',
};
}
@@ -0,0 +1,217 @@
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useBitcoinSigner, isSignerCapabilityError, reportSignerUnsupported } from '@/hooks/useBitcoinSigner';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import {
nostrPubkeyToBitcoinAddress,
fetchUTXOs,
getFeeRates,
buildUnsignedPsbt,
finalizePsbt,
broadcastTransaction,
estimateFee,
} from '@/lib/bitcoin';
import type { FeeRates } from '@/lib/bitcoin';
export type OnchainFeeSpeed = 'fastest' | 'halfHour' | 'hour' | 'economy';
/**
* Resolves the fee rate for a given speed preset from a FeeRates bundle.
*/
function feeRateForSpeed(rates: FeeRates, speed: OnchainFeeSpeed): number {
switch (speed) {
case 'fastest': return rates.fastestFee;
case 'halfHour': return rates.halfHourFee;
case 'hour': return rates.hourFee;
case 'economy': return rates.economyFee;
}
}
interface OnchainZapArgs {
/** Amount to zap in satoshis. */
amountSats: number;
/** Optional comment to include in the kind 8333 event content. */
comment?: string;
/** Fee speed preset. Defaults to "halfHour". */
feeSpeed?: OnchainFeeSpeed;
}
interface OnchainZapResult {
/** The broadcast Bitcoin transaction ID. */
txid: string;
/** Amount sent in satoshis. */
amountSats: number;
/** Fee paid in satoshis. */
fee: number;
/** The published kind 8333 event. */
event: NostrEvent;
}
/**
* Hook for sending on-chain (Bitcoin L1) zaps to a Nostr event or profile.
*
* Flow:
* 1. Build, sign, and broadcast a Bitcoin transaction paying the target
* author's derived Taproot address.
* 2. Publish a kind 8333 "onchain zap" event referencing the txid, the
* target event (`e` or `a` tag), and the recipient's pubkey.
*
* Unlike NIP-57 Lightning zaps, this works for *any* Nostr user — there is
* no LNURL dependency because every pubkey has a derived Taproot address.
*/
export function useOnchainZap(
target: NostrEvent,
onSuccess?: (result: OnchainZapResult) => void,
) {
const { user } = useCurrentUser();
const { canSignPsbt, signPsbt } = useBitcoinSigner();
const { mutateAsync: publishEvent } = useNostrPublish();
const { toast } = useToast();
const queryClient = useQueryClient();
const [isZapping, setIsZapping] = useState(false);
const [progress, setProgress] = useState<'idle' | 'building' | 'signing' | 'broadcasting' | 'publishing'>('idle');
const mutation = useMutation<OnchainZapResult, Error, OnchainZapArgs>({
mutationFn: async ({ amountSats, comment = '', feeSpeed = 'halfHour' }) => {
if (!user) throw new Error('You must be logged in to zap.');
if (user.pubkey === target.pubkey) throw new Error("You can't zap yourself.");
if (!canSignPsbt || !signPsbt) {
throw new Error(
"Your login doesn't support sending Bitcoin. Log in with your secret key to send Bitcoin zaps.",
);
}
if (!Number.isFinite(amountSats) || amountSats <= 0) {
throw new Error('Invalid amount.');
}
setIsZapping(true);
setProgress('building');
const senderAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
const recipientAddress = nostrPubkeyToBitcoinAddress(target.pubkey);
if (!senderAddress || !recipientAddress) {
throw new Error('Failed to derive Bitcoin address.');
}
// Fetch UTXOs and fee rates
const [utxos, rates] = await Promise.all([
fetchUTXOs(senderAddress),
getFeeRates(),
]);
if (utxos.length === 0) {
throw new Error('Your Bitcoin wallet has no spendable funds.');
}
const feeRate = feeRateForSpeed(rates, feeSpeed);
const totalBalance = utxos.reduce((s, u) => s + u.value, 0);
const estFee = estimateFee(utxos.length, 2, feeRate);
if (amountSats + estFee > totalBalance) {
throw new Error(
`Insufficient funds. Need ~${(amountSats + estFee).toLocaleString()} sats, have ${totalBalance.toLocaleString()}.`,
);
}
// Build unsigned PSBT
const { psbtHex, fee } = buildUnsignedPsbt(
user.pubkey,
recipientAddress,
amountSats,
utxos,
feeRate,
);
// Sign
setProgress('signing');
const signedHex = await signPsbt(psbtHex);
const txHex = finalizePsbt(signedHex);
// Broadcast
setProgress('broadcasting');
const txid = await broadcastTransaction(txHex);
// Publish kind 8333 event
setProgress('publishing');
const isAddressable = target.kind >= 30000 && target.kind < 40000;
const tags: string[][] = [
['i', `bitcoin:tx:${txid}`],
['p', target.pubkey],
['amount', String(amountSats)],
];
if (isAddressable) {
const dTag = target.tags.find(([n]) => n === 'd')?.[1] ?? '';
tags.push(['a', `${target.kind}:${target.pubkey}:${dTag}`]);
}
// Always include `e` for a concrete event reference (even for addressable events)
tags.push(['e', target.id]);
tags.push(['alt', `Bitcoin zap: ${amountSats.toLocaleString()} sats`]);
const event = await publishEvent({
kind: 8333,
content: comment,
tags,
});
return { txid, amountSats, fee, event };
},
onSuccess: (result) => {
// Optimistically mark the target as zapped-by-me so any UI tracking
// user zaps updates immediately, without waiting for the relay echo.
queryClient.setQueryData(['user-zap', target.id], true);
// Invalidate caches that track zaps / balances
queryClient.invalidateQueries({ queryKey: ['onchain-zaps'] });
queryClient.invalidateQueries({ queryKey: ['event-interactions'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-utxos'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-balance'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-txs'] });
// If the caller opted into handling success themselves, skip the toast.
if (onSuccess) {
onSuccess(result);
} else {
toast({
title: 'Bitcoin zap sent!',
description: `Broadcast txid ${result.txid.slice(0, 12)}… (fee ${result.fee.toLocaleString()} sats)`,
});
}
},
onError: (err) => {
// If the signer turned out to not support PSBT signing (common for
// NIP-46 bunkers where capability can't be probed up front), mark the
// signer as unsupported for the rest of the session. The dialog UI
// watches this state and replaces itself with an "unsupported" panel
// instead of relying on this toast.
if (isSignerCapabilityError(err) && user) {
reportSignerUnsupported(user.pubkey);
return;
}
toast({
title: 'Bitcoin zap failed',
description: err.message,
variant: 'destructive',
});
},
onSettled: () => {
setIsZapping(false);
setProgress('idle');
},
});
return {
zap: mutation.mutate,
zapAsync: mutation.mutateAsync,
isZapping,
progress,
canZap: !!user && user.pubkey !== target.pubkey && canSignPsbt,
/** Whether the logged-in user has a PSBT-capable signer. */
canSignPsbt,
};
}
@@ -0,0 +1,205 @@
import { useQueries, useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { fetchTxDetail, nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
/** A single verified on-chain zap, with the amount that actually paid the recipient on-chain. */
export interface OnchainZapEntry {
/** The kind 8333 event. */
event: NostrEvent;
/** Bitcoin transaction id (lowercase hex). */
txid: string;
/** Pubkey of the sender (the 8333 event author). */
senderPubkey: string;
/** Pubkey of the recipient (from `p` tag). */
recipientPubkey: string;
/** Verified amount in sats — sum of tx outputs that pay the recipient's derived Taproot address. */
amountSats: number;
/** Sender's self-reported amount (may differ from verified). */
claimedAmountSats: number;
/** Comment from the 8333 event content. */
comment: string;
/** Unix timestamp of the 8333 event. */
createdAt: number;
/** Whether the Bitcoin tx is confirmed on-chain. */
confirmed: boolean;
}
/** Parse the txid from a kind 8333 event's `i` tag. Returns null if missing or malformed. */
export function extractOnchainZapTxid(event: NostrEvent): string | null {
const iTag = event.tags.find(([n, v]) => n === 'i' && typeof v === 'string' && v.startsWith('bitcoin:tx:'));
if (!iTag?.[1]) return null;
const txid = iTag[1].slice('bitcoin:tx:'.length).toLowerCase();
if (!/^[0-9a-f]{64}$/.test(txid)) return null;
return txid;
}
/** Parse the claimed amount (sats) from a kind 8333 event. */
export function extractOnchainZapClaimedAmount(event: NostrEvent): number {
const tag = event.tags.find(([n]) => n === 'amount');
if (!tag?.[1]) return 0;
const n = parseInt(tag[1], 10);
return Number.isFinite(n) && n > 0 ? n : 0;
}
/** Parse the recipient pubkey from a kind 8333 event (first `p` tag). */
export function extractOnchainZapRecipient(event: NostrEvent): string {
const tag = event.tags.find(([n]) => n === 'p');
return tag?.[1] ?? '';
}
/**
* Verify a kind 8333 on-chain zap event against the Bitcoin blockchain.
*
* Returns the verified amount (sum of tx outputs paying the recipient's
* derived Taproot address) and confirmation status. Returns `null` if the
* event is malformed or the transaction cannot be verified.
*
* A verified amount of 0 means the transaction exists but does not pay
* the claimed recipient — callers should discard such events.
*/
export async function verifyOnchainZap(event: NostrEvent): Promise<OnchainZapEntry | null> {
const txid = extractOnchainZapTxid(event);
const recipientPubkey = extractOnchainZapRecipient(event);
if (!txid || !recipientPubkey) return null;
// Reject self-zaps (sender == recipient). The sender already controls the
// destination address, so self-zaps are trivial to fabricate and contribute
// nothing meaningful to zap totals.
if (event.pubkey === recipientPubkey) return null;
const recipientAddress = nostrPubkeyToBitcoinAddress(recipientPubkey);
if (!recipientAddress) return null;
let detail;
try {
detail = await fetchTxDetail(txid);
} catch {
return null;
}
const amountSats = detail.outputs
.filter((o) => o.address === recipientAddress)
.reduce((sum, o) => sum + o.value, 0);
if (amountSats === 0) return null;
const claimed = extractOnchainZapClaimedAmount(event);
// If the sender is claiming more than the tx actually paid, cap it at the verified amount.
const effectiveClaim = Math.min(claimed || amountSats, amountSats);
return {
event,
txid,
senderPubkey: event.pubkey,
recipientPubkey,
amountSats: effectiveClaim,
claimedAmountSats: claimed,
comment: event.content,
createdAt: event.created_at,
confirmed: detail.confirmed,
};
}
/**
* Query all kind 8333 on-chain zaps targeting a specific event, then verify
* each one on-chain. Returns only verified entries (deduped by txid).
*/
export function useOnchainZaps(target: NostrEvent | undefined) {
const { nostr } = useNostr();
const isAddressable = target && target.kind >= 30000 && target.kind < 40000;
const dTag = isAddressable
? target.tags.find(([n]) => n === 'd')?.[1] ?? ''
: '';
const aCoord = isAddressable && target ? `${target.kind}:${target.pubkey}:${dTag}` : '';
// Step 1: fetch the raw kind 8333 events for this target
const eventsQuery = useQuery({
queryKey: ['onchain-zaps', 'events', target?.id ?? '', aCoord],
queryFn: async ({ signal }) => {
if (!target) return [] as NostrEvent[];
const timeout = AbortSignal.timeout(5000);
const combined = AbortSignal.any([signal, timeout]);
const filters: Parameters<typeof nostr.query>[0] = [
{ kinds: [8333], '#e': [target.id], limit: 100 },
];
if (aCoord) {
filters.push({ kinds: [8333], '#a': [aCoord], limit: 100 });
}
const events = await nostr.query(filters, { signal: combined });
// Dedupe by event id, then by txid (one canonical zap per tx per target).
const byId = new Map<string, NostrEvent>();
for (const e of events) byId.set(e.id, e);
const byTxid = new Map<string, NostrEvent>();
for (const e of byId.values()) {
const txid = extractOnchainZapTxid(e);
if (!txid) continue;
const existing = byTxid.get(txid);
// Prefer the earliest event for each txid (first to claim this tx).
if (!existing || e.created_at < existing.created_at) {
byTxid.set(txid, e);
}
}
return Array.from(byTxid.values());
},
enabled: !!target,
staleTime: 30_000,
});
// Step 2: verify each event on-chain (parallel, cached per txid)
const events = eventsQuery.data ?? [];
const verifications = useQueries({
queries: events.map((event) => ({
queryKey: ['onchain-zaps', 'verify', extractOnchainZapTxid(event), extractOnchainZapRecipient(event)],
queryFn: () => verifyOnchainZap(event),
staleTime: 60_000,
})),
});
const verified: OnchainZapEntry[] = verifications
.map((v) => v.data)
.filter((v): v is OnchainZapEntry => !!v);
// Sort by verified amount (largest first)
verified.sort((a, b) => b.amountSats - a.amountSats);
const totalSats = verified.reduce((s, v) => s + v.amountSats, 0);
const isLoading = eventsQuery.isLoading || verifications.some((v) => v.isLoading);
return {
zaps: verified,
totalSats,
count: verified.length,
isLoading,
};
}
/**
* Verify a single kind 8333 event against the Bitcoin blockchain and return
* the resulting `OnchainZapEntry`. Used by standalone surfaces (embedded
* cards, detail page) that need to display a verified amount without doing
* a full `#e`/`#a` fan-out.
*
* Returns `undefined` while loading, `null` if the event fails verification
* (invalid tx, wrong recipient, self-zap, etc.), or the entry.
*/
export function useVerifiedOnchainZap(event: NostrEvent | undefined): OnchainZapEntry | null | undefined {
const txid = event ? extractOnchainZapTxid(event) : null;
const recipient = event ? extractOnchainZapRecipient(event) : '';
const { data } = useQuery({
queryKey: ['onchain-zaps', 'verify', txid, recipient],
queryFn: () => verifyOnchainZap(event!),
enabled: !!event && !!txid && !!recipient,
staleTime: 60_000,
});
if (!event) return null;
return data;
}
@@ -0,0 +1,143 @@
import type { NostrSigner } from '@nostrify/types';
import { NSecSigner, NBrowserSigner, NConnectSigner } from '@nostrify/nostrify';
import type { NConnectSignerOpts } from '@nostrify/nostrify';
import { signPsbtLocal } from '@/lib/bitcoin';
// ---------------------------------------------------------------------------
// BtcSigner interface
// ---------------------------------------------------------------------------
/**
* A Nostr signer extended with Bitcoin PSBT signing capability.
*
* Implementations receive a hex-encoded unsigned PSBT, sign all Taproot
* inputs whose `tapInternalKey` matches the signer's key, and return the
* hex-encoded signed (but not finalized) PSBT.
*/
export interface BtcSigner extends NostrSigner {
signPsbt(psbtHex: string): Promise<string>;
}
/** Runtime check for whether a signer supports `signPsbt`. */
export function hasBtcSigning(signer: NostrSigner): signer is BtcSigner {
return typeof (signer as BtcSigner).signPsbt === 'function';
}
// ---------------------------------------------------------------------------
// NSecSignerBtc — local nsec signing
// ---------------------------------------------------------------------------
/**
* Extends `NSecSigner` with local Taproot PSBT signing.
*
* `NSecSigner` stores the secret key in a JS `#private` field that subclasses
* cannot access. To work around this, the constructor accepts the raw secret
* key bytes, passes them to `super()`, and keeps its own copy in a true
* runtime-private `#secretKeyBytes` field so the key is not reachable via
* property enumeration or reflection on the instance.
*/
export class NSecSignerBtc extends NSecSigner implements BtcSigner {
readonly #secretKeyBytes: Uint8Array;
constructor(secretKey: Uint8Array) {
super(secretKey);
this.#secretKeyBytes = new Uint8Array(secretKey);
}
async signPsbt(psbtHex: string): Promise<string> {
const privateKeyHex = Buffer.from(this.#secretKeyBytes).toString('hex');
return signPsbtLocal(psbtHex, privateKeyHex);
}
}
// ---------------------------------------------------------------------------
// NBrowserSignerBtc — NIP-07 extension signing
// ---------------------------------------------------------------------------
/**
* Extends `NBrowserSigner` with NIP-07 `window.nostr.signPsbt()` support.
*
* Calls the extension's `signPsbt` method if available. If the extension does
* not expose `signPsbt`, an error is thrown with a user-friendly message.
*/
export class NBrowserSignerBtc extends NBrowserSigner implements BtcSigner {
constructor(opts?: { timeout?: number }) {
super(opts);
}
async signPsbt(psbtHex: string): Promise<string> {
// `awaitNostr` is TypeScript-private but JavaScript-public at runtime.
const nostr = await (this as unknown as { awaitNostr(): Promise<Record<string, unknown>> }).awaitNostr();
if (typeof nostr.signPsbt !== 'function') {
throw new Error(
"Your browser extension doesn't support sending Bitcoin. Try a different extension, or log in with your secret key.",
);
}
const signPsbt = nostr.signPsbt as (hex: string) => Promise<string>;
return signPsbt(psbtHex);
}
}
// ---------------------------------------------------------------------------
// NConnectSignerBtc — NIP-46 remote signer
// ---------------------------------------------------------------------------
/**
* Heuristics for detecting whether a NIP-46 `sign_psbt` error reflects a
* missing-capability rejection (e.g. "method not supported", "unknown
* command") versus a transient operational failure (network, user rejection,
* malformed input). We have to match on strings because NIP-46 errors are
* plain strings without structured codes.
*/
const CAPABILITY_ERROR_PATTERNS = [
/unknown\s+(method|command)/i,
/not\s+(implemented|supported|found)/i,
/unsupported\s+method/i,
/method\s+not\s+found/i,
/invalid\s+method/i,
/no\s+such\s+method/i,
];
function looksLikeCapabilityError(msg: string): boolean {
return CAPABILITY_ERROR_PATTERNS.some((re) => re.test(msg));
}
/**
* Extends `NConnectSigner` with NIP-46 `sign_psbt` RPC support.
*
* Sends a `sign_psbt` command over the NIP-46 relay channel. The remote
* signer handles the TapTweak and Schnorr signing internally.
*
* NIP-46 returns unstructured string errors, so we use pattern matching to
* distinguish capability failures (the signer doesn't know the method) from
* operational failures (network, user rejection, bad input). Only capability
* failures are re-wrapped with the "doesn't support sending Bitcoin" message
* that flips the UI into the unsupported state; everything else propagates
* unchanged so the caller can surface the real error.
*/
export class NConnectSignerBtc extends NConnectSigner implements BtcSigner {
constructor(opts: NConnectSignerOpts) {
super(opts);
}
async signPsbt(psbtHex: string): Promise<string> {
// `cmd` is TypeScript-private but JavaScript-public at runtime.
const cmd = (this as unknown as { cmd(method: string, params: string[]): Promise<string> }).cmd;
try {
return await cmd.call(this, 'sign_psbt', [psbtHex]);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (looksLikeCapabilityError(msg)) {
throw new Error(
`Your remote signer doesn't support sending Bitcoin. Update your signer, or log in with your secret key. (${msg})`,
);
}
// Not a capability failure — propagate the original error so the user
// sees the actual reason (timeout, rejection, malformed PSBT, etc.).
throw error;
}
}
}
@@ -0,0 +1,648 @@
import * as bitcoin from 'bitcoinjs-lib';
import { toXOnly } from 'bitcoinjs-lib';
import { nip19 } from 'nostr-tools';
import * as ecc from '@bitcoinerlab/secp256k1';
import { ECPairFactory, type ECPairAPI } from 'ecpair';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Base URL for the mempool.space Esplora-compatible REST API. */
const MEMPOOL_API = 'https://mempool.space/api';
/** Standard Bitcoin dust limit in satoshis. */
const DUST_LIMIT = 546;
/** Estimated vBytes per P2TR input. */
const VBYTES_PER_INPUT = 57.5;
/** Estimated vBytes per P2TR output. */
const VBYTES_PER_OUTPUT = 43;
/** Estimated vBytes for transaction overhead (version, locktime, etc.). */
const VBYTES_OVERHEAD = 10.5;
// ---------------------------------------------------------------------------
// ECC initialisation (lazy)
// ---------------------------------------------------------------------------
let _ECPair: ECPairAPI | null = null;
function getECPair(): ECPairAPI {
if (!_ECPair) {
bitcoin.initEccLib(ecc);
_ECPair = ECPairFactory(ecc);
}
return _ECPair;
}
/**
* Strict 32-byte hex validator. Rejects anything that isn't exactly 64
* lowercase-or-uppercase hex characters.
*/
function isValidPubkeyHex(hex: string): boolean {
return typeof hex === 'string' && /^[0-9a-fA-F]{64}$/.test(hex);
}
/**
* Convert a Nostr public key (32-byte hex) to a Bitcoin Taproot (P2TR) address.
*
* Both Nostr and Bitcoin Taproot use secp256k1 with 32-byte x-only public keys
* (Schnorr / BIP-340), so the key can be used directly as a Taproot internal
* public key with no mathematical conversion.
*
* Returns an empty string if the input is malformed or not a valid x-only key
* on the secp256k1 curve.
*/
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
if (!isValidPubkeyHex(pubkeyHex)) return '';
try {
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
const { address } = bitcoin.payments.p2tr({
internalPubkey: pubkeyBuffer,
network: bitcoin.networks.bitcoin,
});
return address || '';
} catch (error) {
console.error('Error generating Bitcoin address:', error);
return '';
}
}
/**
* Convert a bech32 `npub1...` identifier to a Bitcoin Taproot (P2TR) address.
* Decodes the npub to a hex pubkey, then delegates to {@link nostrPubkeyToBitcoinAddress}.
*/
export function npubToBitcoinAddress(npub: string): string {
const decoded = nip19.decode(npub);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
return nostrPubkeyToBitcoinAddress(decoded.data);
}
// ---------------------------------------------------------------------------
// Balance / Address data (wallet page)
// ---------------------------------------------------------------------------
/** Balance data returned by the Esplora API. */
export interface AddressData {
/** Confirmed on-chain balance in satoshis. */
balance: number;
/** Unconfirmed mempool balance in satoshis. */
pendingBalance: number;
/** Sum of confirmed + pending balance. */
totalBalance: number;
/** Total satoshis ever received (confirmed). */
totalReceived: number;
/** Total satoshis ever sent (confirmed). */
totalSent: number;
/** Confirmed transaction count. */
txCount: number;
/** Pending (mempool) transaction count. */
pendingTxCount: number;
}
/**
* Fetch balance and transaction stats for a Bitcoin address from the
* mempool.space Esplora API.
*/
export async function fetchAddressData(address: string): Promise<AddressData> {
const response = await fetch(`${MEMPOOL_API}/address/${address}`);
if (!response.ok) {
throw new Error('Failed to fetch balance');
}
const data = await response.json();
const confirmedBalance = data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum;
const pendingBalance = data.mempool_stats.funded_txo_sum - data.mempool_stats.spent_txo_sum;
return {
balance: confirmedBalance,
pendingBalance,
totalBalance: confirmedBalance + pendingBalance,
totalReceived: data.chain_stats.funded_txo_sum,
totalSent: data.chain_stats.spent_txo_sum,
txCount: data.chain_stats.tx_count,
pendingTxCount: data.mempool_stats.tx_count,
};
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
/** Convert satoshis to a BTC string with up to 8 decimal places. */
export function satsToBTC(sats: number): string {
return (sats / 100_000_000).toFixed(8);
}
/**
* Convert satoshis to a BTC string with trailing zeros stripped.
* E.g. `formatBTC(100_000_000)` → `"1"`, `formatBTC(1_234_560)` → `"0.0123456"`.
*/
export function formatBTC(sats: number): string {
return satsToBTC(sats).replace(/\.?0+$/, '');
}
/** Format a satoshi amount with locale-aware thousand separators. */
export function formatSats(sats: number): string {
return sats.toLocaleString();
}
/** Fetch the current BTC price in USD from the CoinGecko API. */
export async function fetchBtcPrice(): Promise<number> {
const response = await fetch(
'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd',
);
if (!response.ok) {
throw new Error('Failed to fetch BTC price');
}
const data = await response.json();
return data.bitcoin.usd;
}
/** Convert a BTC amount to satoshis (rounded to nearest integer). */
export function btcToSats(btc: number): number {
return Math.round(btc * 100_000_000);
}
/**
* USD threshold above which Bitcoin send/zap flows should require explicit
* confirmation (two-tap). Chosen to catch meaningful dollar amounts without
* nagging on everyday $5–$25 zaps.
*/
export const LARGE_AMOUNT_USD_THRESHOLD = 100;
/**
* Whether a given satoshi amount crosses the "large amount" threshold at the
* current BTC/USD price. Returns false when `btcPrice` is unavailable, so the
* UI does not arm confirmation without a known USD value.
*/
export function isLargeAmount(sats: number, btcPrice: number | undefined): boolean {
if (!btcPrice || !Number.isFinite(btcPrice) || btcPrice <= 0) return false;
if (!Number.isFinite(sats) || sats <= 0) return false;
const usd = (sats / 100_000_000) * btcPrice;
return usd >= LARGE_AMOUNT_USD_THRESHOLD;
}
/** Convert satoshis to USD given a BTC price. */
export function satsToUSD(sats: number, btcPrice: number): string {
const btc = sats / 100_000_000;
return (btc * btcPrice).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
// ---------------------------------------------------------------------------
// Wallet-page transaction list (simplified per-address view)
// ---------------------------------------------------------------------------
/** A simplified transaction relevant to a specific address. */
export interface Transaction {
/** Transaction ID (hex). */
txid: string;
/** Net satoshi change for the address (always positive — see `type`). */
amount: number;
/** Whether this is a receive or send relative to the address. */
type: 'receive' | 'send';
/** Whether the transaction is confirmed. */
confirmed: boolean;
/** Unix timestamp of the block (undefined if unconfirmed). */
timestamp?: number;
}
/**
* Fetch transactions for a Bitcoin address from the mempool.space Esplora API.
* Returns simplified transactions with net amount relative to the address.
*/
export async function fetchTransactions(address: string): Promise<Transaction[]> {
const response = await fetch(`${MEMPOOL_API}/address/${address}/txs`);
if (!response.ok) {
throw new Error('Failed to fetch transactions');
}
const txs = await response.json();
return txs.map((tx: Record<string, unknown>) => {
const vin = tx.vin as Array<{ prevout: { scriptpubkey_address?: string; value: number } | null }>;
const vout = tx.vout as Array<{ scriptpubkey_address?: string; value: number }>;
const status = tx.status as { confirmed: boolean; block_time?: number };
// Sum sats flowing out of this address (inputs we owned)
const totalIn = vin.reduce((sum, input) => {
if (input.prevout?.scriptpubkey_address === address) {
return sum + input.prevout.value;
}
return sum;
}, 0);
// Sum sats flowing into this address (outputs we own)
const totalOut = vout.reduce((sum, output) => {
if (output.scriptpubkey_address === address) {
return sum + output.value;
}
return sum;
}, 0);
const net = totalOut - totalIn;
return {
txid: tx.txid as string,
amount: Math.abs(net),
type: net >= 0 ? 'receive' : 'send',
confirmed: status.confirmed,
timestamp: status.block_time,
} satisfies Transaction;
});
}
// ---------------------------------------------------------------------------
// Full transaction detail (NIP-73 /:nip19 bitcoin:tx:... page)
// ---------------------------------------------------------------------------
/** A single input in a full transaction. */
export interface TxInput {
txid: string;
vout: number;
address?: string;
value: number;
isCoinbase: boolean;
}
/** A single output in a full transaction. */
export interface TxOutput {
address?: string;
value: number;
scriptpubkeyType: string;
/** True if the output has been spent. */
spent: boolean;
}
/** Full transaction detail returned by the Esplora API. */
export interface TxDetail {
txid: string;
version: number;
locktime: number;
size: number;
weight: number;
fee: number;
confirmed: boolean;
blockHeight?: number;
blockHash?: string;
blockTime?: number;
inputs: TxInput[];
outputs: TxOutput[];
/** Total value of all inputs (sats). */
totalInput: number;
/** Total value of all outputs (sats). */
totalOutput: number;
}
/** Fetch full transaction details from mempool.space. */
export async function fetchTxDetail(txid: string): Promise<TxDetail> {
const response = await fetch(`${MEMPOOL_API}/tx/${txid}`);
if (!response.ok) throw new Error('Failed to fetch transaction');
const tx = await response.json();
const vin = tx.vin as Array<{
txid: string;
vout: number;
prevout: { scriptpubkey_address?: string; value: number } | null;
is_coinbase: boolean;
}>;
const vout = tx.vout as Array<{
scriptpubkey_address?: string;
value: number;
scriptpubkey_type: string;
}>;
const status = tx.status as { confirmed: boolean; block_height?: number; block_hash?: string; block_time?: number };
const inputs: TxInput[] = vin.map((input) => ({
txid: input.txid,
vout: input.vout,
address: input.prevout?.scriptpubkey_address,
value: input.prevout?.value ?? 0,
isCoinbase: input.is_coinbase,
}));
const outputs: TxOutput[] = vout.map((output) => ({
address: output.scriptpubkey_address,
value: output.value,
scriptpubkeyType: output.scriptpubkey_type,
spent: false, // Esplora /tx endpoint doesn't include spending info
}));
const totalInput = inputs.reduce((sum, i) => sum + i.value, 0);
const totalOutput = outputs.reduce((sum, o) => sum + o.value, 0);
return {
txid: tx.txid as string,
version: tx.version as number,
locktime: tx.locktime as number,
size: tx.size as number,
weight: tx.weight as number,
fee: tx.fee as number,
confirmed: status.confirmed,
blockHeight: status.block_height,
blockHash: status.block_hash,
blockTime: status.block_time,
inputs,
outputs,
totalInput,
totalOutput,
};
}
// ---------------------------------------------------------------------------
// Full address detail (NIP-73 /:nip19 bitcoin:address:... page)
// ---------------------------------------------------------------------------
/** Full address detail combining balance stats + recent transactions. */
export interface AddressDetail {
address: string;
balance: number;
pendingBalance: number;
totalBalance: number;
totalReceived: number;
totalSent: number;
txCount: number;
pendingTxCount: number;
/** Most recent transactions (up to 25). */
recentTxs: Transaction[];
}
/** Fetch full address details (balance + recent txs) from mempool.space. */
export async function fetchAddressDetail(address: string): Promise<AddressDetail> {
const [addrData, txs] = await Promise.all([
fetchAddressData(address),
fetchTransactions(address),
]);
return {
address,
...addrData,
recentTxs: txs.slice(0, 25),
};
}
// ---------------------------------------------------------------------------
// Sending: UTXOs, fee estimation, transaction construction, broadcast
// ---------------------------------------------------------------------------
/** An unspent transaction output. */
export interface UTXO {
txid: string;
vout: number;
/** Value in satoshis. */
value: number;
status: {
confirmed: boolean;
block_height?: number;
block_hash?: string;
block_time?: number;
};
}
/** Fetch UTXOs for a Bitcoin address from mempool.space. */
export async function fetchUTXOs(address: string): Promise<UTXO[]> {
const response = await fetch(`${MEMPOOL_API}/address/${address}/utxo`);
if (!response.ok) throw new Error('Failed to fetch UTXOs');
return response.json();
}
/** Fee rate estimates keyed by confirmation speed. */
export interface FeeRates {
/** ~10 min / next block (target 1). */
fastestFee: number;
/** ~30 min (target 3). */
halfHourFee: number;
/** ~1 hour (target 6). */
hourFee: number;
/** ~1 day (target 144). */
economyFee: number;
/** Minimum relay fee (target 504). */
minimumFee: number;
}
/** Fetch recommended fee rates (sat/vB) from mempool.space. */
export async function getFeeRates(): Promise<FeeRates> {
const response = await fetch(`${MEMPOOL_API}/fee-estimates`);
if (!response.ok) throw new Error('Failed to fetch fee estimates');
const data = await response.json();
return {
fastestFee: Math.ceil(data['1'] || 1),
halfHourFee: Math.ceil(data['3'] || 1),
hourFee: Math.ceil(data['6'] || 1),
economyFee: Math.ceil(data['144'] || 1),
minimumFee: Math.ceil(data['504'] || 1),
};
}
/**
* Estimate the fee for a P2TR transaction in satoshis.
*
* @param numInputs Number of Taproot inputs.
* @param numOutputs Number of outputs (recipient + optional change).
* @param feeRate Fee rate in sat/vB.
*/
export function estimateFee(numInputs: number, numOutputs: number, feeRate: number): number {
const vBytes = numInputs * VBYTES_PER_INPUT + numOutputs * VBYTES_PER_OUTPUT + VBYTES_OVERHEAD;
return Math.ceil(vBytes * feeRate);
}
/**
* Validate a Bitcoin address (mainnet). Returns `true` if the address has a
* valid format and checksum, `false` otherwise.
*/
export function validateBitcoinAddress(address: string): boolean {
try {
bitcoin.address.toOutputScript(address, bitcoin.networks.bitcoin);
return true;
} catch {
return false;
}
}
/** Broadcast a signed transaction hex to the Bitcoin network via mempool.space. Returns the txid. */
export async function broadcastTransaction(txHex: string): Promise<string> {
const response = await fetch(`${MEMPOOL_API}/tx`, {
method: 'POST',
body: txHex,
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Broadcast failed: ${body}`);
}
return response.text();
}
/**
* Compute the maximum sendable amount (in sats) after fees.
*
* @param totalBalance Total spendable sats across all UTXOs.
* @param numInputs Number of UTXOs that will be consumed.
* @param feeRate Fee rate in sat/vB.
* @returns The max amount in sats, or 0 if the balance cannot cover fees.
*/
export function maxSendable(totalBalance: number, numInputs: number, feeRate: number): number {
// When sending max there is no change output, so only 1 output.
const fee = estimateFee(numInputs, 1, feeRate);
return Math.max(0, totalBalance - fee);
}
/** Result of building an unsigned PSBT. */
export interface UnsignedPsbt {
/** Hex-encoded unsigned PSBT. */
psbtHex: string;
/** Fee in satoshis. */
fee: number;
}
/**
* Build an unsigned Taproot PSBT ready for signing.
*
* This function constructs the PSBT with all inputs and outputs but does NOT
* sign it. The returned hex can be passed to any signer (local nsec, NIP-07
* extension, or NIP-46 remote signer).
*
* @param senderPubkeyHex 32-byte hex x-only public key of the sender.
* @param toAddress Recipient Bitcoin address.
* @param amountSats Amount to send in satoshis.
* @param utxos Available UTXOs (all will be consumed).
* @param feeRate Fee rate in sat/vB.
*/
export function buildUnsignedPsbt(
senderPubkeyHex: string,
toAddress: string,
amountSats: number,
utxos: UTXO[],
feeRate: number,
): UnsignedPsbt {
const internalPubkey = Buffer.from(senderPubkeyHex, 'hex');
// Derive change address (same Taproot address as sender)
const { address: changeAddress } = bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
});
if (!changeAddress) throw new Error('Failed to derive change address');
// Build PSBT, add all UTXOs as inputs
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.bitcoin });
let totalInput = 0;
for (const utxo of utxos) {
psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
}).output!,
value: BigInt(utxo.value),
},
tapInternalKey: internalPubkey,
});
totalInput += utxo.value;
}
// Estimate fee — first assume 2 outputs (recipient + change). Change at the
// dust limit exactly is still standard, so use >= (not >) per BIP-141/P2TR
// relay policy (minimum non-dust output is 546 sats).
const change2Out = totalInput - amountSats - estimateFee(utxos.length, 2, feeRate);
const hasChange = change2Out >= DUST_LIMIT;
const numOutputs = hasChange ? 2 : 1;
const fee = estimateFee(utxos.length, numOutputs, feeRate);
const change = totalInput - amountSats - fee;
if (change < 0) {
throw new Error(
`Insufficient funds. Need ${(amountSats + fee).toLocaleString()} sats, have ${totalInput.toLocaleString()} sats.`,
);
}
// Add outputs
psbt.addOutput({ address: toAddress, value: BigInt(amountSats) });
if (hasChange) {
psbt.addOutput({ address: changeAddress, value: BigInt(change) });
}
return { psbtHex: psbt.toHex(), fee };
}
/**
* Sign a PSBT locally using a raw private key (nsec).
*
* Applies the BIP-341 TapTweak to the private key, signs all inputs whose
* `tapInternalKey` matches, and returns the signed (but not finalized) PSBT hex.
*
* @param psbtHex Hex-encoded unsigned PSBT.
* @param privateKeyHex 32-byte hex private key.
* @returns Hex-encoded signed PSBT (not finalized).
*/
export function signPsbtLocal(psbtHex: string, privateKeyHex: string): string {
bitcoin.initEccLib(ecc);
const psbt = bitcoin.Psbt.fromHex(psbtHex, { network: bitcoin.networks.bitcoin });
const keyPair = getECPair().fromPrivateKey(Buffer.from(privateKeyHex, 'hex'));
const internalPubkey = toXOnly(keyPair.publicKey);
// Tweak private key for Taproot key-path spending (BIP-341)
const tweakedSigner = keyPair.tweak(
bitcoin.crypto.taggedHash('TapTweak', internalPubkey),
);
// Per BITCOIN-SIGNING.md: inputs whose `tapInternalKey` does not match the
// signer's x-only pubkey MUST be left unchanged. This matters for future
// multi-signer PSBTs; today `buildUnsignedPsbt` only ever adds the user's
// own UTXOs, so in practice every input matches.
let signedAny = false;
for (let i = 0; i < psbt.inputCount; i++) {
const input = psbt.data.inputs[i];
const inputInternalKey = input.tapInternalKey;
if (!inputInternalKey || !Buffer.from(inputInternalKey).equals(Buffer.from(internalPubkey))) {
continue;
}
psbt.signInput(i, tweakedSigner);
signedAny = true;
}
if (!signedAny) {
throw new Error('No inputs in this PSBT are owned by the signer.');
}
return psbt.toHex();
}
/**
* Finalize a signed PSBT and extract the raw transaction hex.
*
* @param psbtHex Hex-encoded signed PSBT.
* @returns Raw transaction hex ready for broadcast.
*/
export function finalizePsbt(psbtHex: string): string {
bitcoin.initEccLib(ecc);
const psbt = bitcoin.Psbt.fromHex(psbtHex, { network: bitcoin.networks.bitcoin });
psbt.finalizeAllInputs();
return psbt.extractTransaction().toHex();
}