// Paywell browser wallet (signet test network while in test mode). Public domain. // Keys are made and used only in the browser. The backup leaves the browser only after it is locked // with the person's passkey (see app.js), so we never see the words or keys. import * as btc from '@scure/btc-signer'; import { HDKey } from '@scure/bip32'; import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english'; import qrcode from 'qrcode-generator'; const NET = btc.TEST_NETWORK; // signet uses the testnet address format (tb1...) const PATH = "m/84'/1'/0'"; const GAP = 10; export function newWords() { return generateMnemonic(wordlist, 128); } export function validWords(w) { return validateMnemonic(String(w || '').trim().toLowerCase().replace(/\s+/g, ' '), wordlist); } export function open(words) { const seed = mnemonicToSeedSync(String(words).trim().toLowerCase().replace(/\s+/g, ' ')); const acct = HDKey.fromMasterSeed(seed).derive(PATH); const key = (change, i) => acct.deriveChild(change).deriveChild(i); const addr = (change, i) => btc.p2wpkh(key(change, i).publicKey, NET); return { address: (i = 0, change = 0) => addr(change, i).address, key, addr, }; } async function get(url) { const r = await fetch(url); if (!r.ok) throw new Error('Network busy, try again.'); return r.json(); } // Look at the first addresses on both chains and collect coins and history. export async function sync(w) { const utxos = [], txs = new Map(); let nextReceive = 0, nextChange = 0; for (const change of [0, 1]) { let empty = 0; for (let i = 0; i < 40 && empty < (change ? 4 : GAP); i++) { const a = w.addr(change, i); const [u, t] = await Promise.all([get(`/api/chain/address/${a.address}/utxo`), get(`/api/chain/address/${a.address}/txs`)]); if (!t.length) { empty++; continue; } empty = 0; if (change) nextChange = i + 1; else nextReceive = i + 1; for (const x of u) utxos.push({ txid: x.txid, vout: x.vout, value: x.value, confirmed: x.status && x.status.confirmed, change, i, script: a.script }); for (const x of t) txs.set(x.txid, x); } } const mine = new Set(); for (const change of [0, 1]) for (let i = 0; i < (change ? nextChange : nextReceive) + 1; i++) mine.add(w.address(i, change)); const history = [...txs.values()].map((t) => { let delta = 0; for (const o of t.vout) if (mine.has(o.scriptpubkey_address)) delta += o.value; for (const v of t.vin) if (v.prevout && mine.has(v.prevout.scriptpubkey_address)) delta -= v.prevout.value; return { txid: t.txid, delta, time: t.status && t.status.block_time ? t.status.block_time * 1000 : null, confirmed: !!(t.status && t.status.confirmed) }; }).sort((a, b) => (b.time || 9e15) - (a.time || 9e15)); const balance = utxos.reduce((s, u) => s + u.value, 0); return { utxos, balance, history, nextReceive, nextChange }; } export function validAddress(a) { try { btc.Address(NET).decode(String(a).trim()); return true; } catch { return false; } } // Build and sign a payment. Returns { hex, fee, txid }. export function buildPayment(w, s, to, sats, feeRate) { to = String(to).trim(); if (!validAddress(to)) throw new Error('That isn’t a test-network Bitcoin address (they start with tb1).'); sats = Math.floor(sats); if (!(sats >= 330)) throw new Error('That amount is too small to send.'); const coins = [...s.utxos].sort((a, b) => b.value - a.value); const picked = []; let total = 0, fee = 0; for (const c of coins) { picked.push(c); total += c.value; fee = Math.ceil((11 + 68 * picked.length + 31 * 2) * feeRate); if (total >= sats + fee) break; } if (total < sats + fee) throw new Error('Not enough in your wallet for this payment and the network fee.'); const tx = new btc.Transaction(); for (const c of picked) tx.addInput({ txid: c.txid, index: c.vout, witnessUtxo: { script: c.script, amount: BigInt(c.value) } }); tx.addOutputAddress(to, BigInt(sats), NET); const change = total - sats - fee; if (change >= 546) tx.addOutputAddress(w.address(s.nextChange, 1), BigInt(change), NET); else fee += change; picked.forEach((c, idx) => tx.signIdx(w.key(c.change, c.i).privateKey, idx)); tx.finalize(); return { hex: tx.hex, fee, txid: tx.id }; } export function qrSvg(text) { const q = qrcode(0, 'M'); q.addData(text); q.make(); return q.createSvgTag({ cellSize: 6, margin: 2, scalable: true }); }