// BIP84 (native segwit, p2wpkh) HD wallet core. // // Derivation: m / 84' / coin' / 0' / chain / index // chain 0 = receive (external) addresses // chain 1 = change (internal) addresses // // All signing uses witnessUtxo only (script + amount). That is all segwit needs, // which is what makes offline signing easy: we never have to fetch full previous // transactions, only the (txid, vout, value, address) of each UTXO. import { HDKey } from '@scure/bip32'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; import { hex, base64urlnopad, base32nopad, base58check } from '@scure/base'; import { sha256 } from '@noble/hashes/sha256'; import { scrypt } from '@noble/hashes/scrypt'; import { randomBytes } from '@noble/hashes/utils'; import { xchacha20poly1305 } from '@noble/ciphers/chacha.js'; import { utf8ToBytes, bytesToUtf8 } from '@noble/ciphers/utils.js'; import * as btc from '@scure/btc-signer'; import { p2wpkh } from '@scure/btc-signer/payment'; import { concatBytes } from '@scure/btc-signer/utils.js'; import { Api, pool, getBackend, explorerWeb, electrumCandidates } from './api.js'; import { ElectrumApi } from './electrum.js'; import { schnorr } from '@noble/curves/secp256k1'; // Resolve a same-origin '/path' WebSocket URL to an absolute ws(s):// URL against // the page. The regtest backends are proxied through the dev server as relative // paths (e.g. '/electrum') so the app works from a phone over the LAN/Tailscale; // absolute URLs (real deployments, tests) pass through untouched. export function absWsUrl(u) { if (u && u[0] === '/' && typeof location !== 'undefined') { return (location.protocol === 'https:' ? 'wss://' : 'ws://') + location.host + u; } return u; } // No look-ahead: stop scanning a chain at the first unused address. This wallet // only ever exposes ONE unused address at a time (freshReceive = first unused; // there is no "generate another address" button), so used addresses stay // contiguous and there is never a gap to look past. Keeps scans tiny. const GAP_LIMIT = 1; // Extra pause after finding a used address, before querying the next index — // keeps us gentle on the explorers' rate limits when a wallet has activity. const USED_HIT_DELAY_MS = 500; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); // Silent-payment catch-up dust limit (sats): the indexer drops tweaks for txs // whose taproot outputs are all below this, cutting the candidate math on a big // scan. 0 = receive everything (default, so no small payment is ever missed). export const NETS = { mainnet: { net: btc.NETWORK, coin: 0 }, testnet: { net: btc.TEST_NETWORK, coin: 1 }, // signet + mutinynet share testnet's address format / version bytes / coin // type (`tb` HRP); only the chain + servers differ. signet: { net: btc.TEST_NETWORK, coin: 1 }, mutinynet: { net: btc.TEST_NETWORK, coin: 1 }, // Regtest shares testnet's version bytes / coin type; only the bech32 HRP // differs (`bcrt`). @scure/btc-signer derives addresses + validates from this. regtest: { net: { ...btc.TEST_NETWORK, bech32: 'bcrt' }, coin: 1 }, }; export function newMnemonic(strengthBits = 128) { return generateMnemonic(wordlist, strengthBits); } // The base localStorage cache key for a wallet identity (xpub, xprv, or // seed-id) — mirrors Wallet#_cacheKey, so app code can target a specific // account's cached state (e.g. to wipe it on log-out). export function cacheKeyFor(id) { return 'btc-wallet-cache:' + hex.encode(sha256(new TextEncoder().encode(id))).slice(0, 32); } // Account-level xpub for a seed/key without constructing a Wallet — used to // verify an entered recovery phrase matches a watch-only account before // upgrading it to spendable. export function accountXpubFor({ mnemonic, passphrase = '', xprv } = {}, netName = 'mainnet') { const { coin } = NETS[netName]; let acct; if (xprv) { const node = HDKey.fromExtendedKey(xprv); acct = node.depth === 0 ? node.derive(`m/84'/${coin}'/0'`) : node; } else { acct = HDKey.fromMasterSeed(mnemonicToSeedSync(mnemonic, passphrase)).derive(`m/84'/${coin}'/0'`); } return acct.publicExtendedKey; } export function isValidMnemonic(m) { try { return validateMnemonic(m.trim().replace(/\s+/g, ' '), wordlist); } catch { return false; } } export class Wallet { constructor() { this.mnemonic = ''; this.passphrase = ''; this.netName = 'mainnet'; // Feature-registered providers of coin ids to exclude from spending and // the spendable balance (e.g. coins reserved behind unclaimed gift links). this._coinLocks = []; // Further optional-feature registries (see the seams section below): extra // balance buckets, extra spendable inputs, send-address preparers, input // signers, history rows, scan/realtime/load hooks, cache extensions. this._balanceExtras = []; this._inputProviders = []; this._sendPreparers = []; this._inputSigners = []; this._historyProviders = []; this._scanHooks = []; this._realtimeHooks = []; this._loadHooks = []; this._cacheExtensions = []; this._cacheSavedHooks = []; this.api = new Api('mainnet'); this.offline = false; // Scanned chains: arrays of { chain, index, address, used } this.receive = []; this.change = []; this.addrMap = new Map(); // address -> { chain, index } this.utxos = []; // { txid, vout, value, address, chain, index, confirmed } this.txs = []; // aggregated history this.feeRates = null; this.confirmed = 0; this.pending = 0; this.scanning = false; this.loaded = false; // true once a scan/snapshot has populated balances once this.historyLoading = false; // history is still being fetched in the background this._refreshing = false; // a scan/refresh is in flight this.nextReceiveIndex = 0; this.nextChangeIndex = 0; this._account = null; this._accountKey = ''; this._addrCache = new Map(); // Realtime (mempool.space WebSocket) this.live = false; this._ws = null; this._wsWant = false; this._wsRetry = null; this._refresh
<svg
class="mx-auto h-6 w-6 animate-spin text-white"
xmlns="http://www.w3.org/2000/svg"
fill="none"
viewBox="0 0 24 24"
>
<circle
class="opacity-25"
cx="12"
cy="12"
r="10"
stroke="currentColor"
stroke-width="4"
/>
<path
class="opacity-75"
fill="currentColor"
d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
/>
</svg>