Paywell / website · paywell.company / open / src / wallet-src.js.txt
| 1 | // Paywell browser wallet (signet test network while in test mode). Public domain. |
| 2 | // Keys are made and used only in the browser. The backup leaves the browser only after it is locked |
| 3 | // with the person's passkey (see app.js), so we never see the words or keys. |
| 4 | import * as btc from '@scure/btc-signer'; |
| 5 | import { HDKey } from '@scure/bip32'; |
| 6 | import { generateMnemonic, mnemonicToSeedSync, validateMnemonic } from '@scure/bip39'; |
| 7 | import { wordlist } from '@scure/bip39/wordlists/english'; |
| 8 | import qrcode from 'qrcode-generator'; |
| 9 | |
| 10 | const NET = btc.TEST_NETWORK; // signet uses the testnet address format (tb1...) |
| 11 | const PATH = "m/84'/1'/0'"; |
| 12 | const GAP = 10; |
| 13 | |
| 14 | export function newWords() { return generateMnemonic(wordlist, 128); } |
| 15 | export function validWords(w) { return validateMnemonic(String(w || '').trim().toLowerCase().replace(/\s+/g, ' '), wordlist); } |
| 16 | |
| 17 | export function open(words) { |
| 18 | const seed = mnemonicToSeedSync(String(words).trim().toLowerCase().replace(/\s+/g, ' ')); |
| 19 | const acct = HDKey.fromMasterSeed(seed).derive(PATH); |
| 20 | const key = (change, i) => acct.deriveChild(change).deriveChild(i); |
| 21 | const addr = (change, i) => btc.p2wpkh(key(change, i).publicKey, NET); |
| 22 | return { |
| 23 | address: (i = 0, change = 0) => addr(change, i).address, |
| 24 | key, addr, |
| 25 | }; |
| 26 | } |
| 27 | |
| 28 | async function get(url) { const r = await fetch(url); if (!r.ok) throw new Error('Network busy, try again.'); return r.json(); } |
| 29 | |
| 30 | // Look at the first addresses on both chains and collect coins and history. |
| 31 | export async function sync(w) { |
| 32 | const utxos = [], txs = new Map(); |
| 33 | let nextReceive = 0, nextChange = 0; |
| 34 | for (const change of [0, 1]) { |
| 35 | let empty = 0; |
| 36 | for (let i = 0; i < 40 && empty < (change ? 4 : GAP); i++) { |
| 37 | const a = w.addr(change, i); |
| 38 | const [u, t] = await Promise.all([get(`/api/chain/address/${a.address}/utxo`), get(`/api/chain/address/${a.address}/txs`)]); |
| 39 | if (!t.length) { empty++; continue; } |
| 40 | empty = 0; |
| 41 | if (change) nextChange = i + 1; else nextReceive = i + 1; |
| 42 | 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 }); |
| 43 | for (const x of t) txs.set(x.txid, x); |
| 44 | } |
| 45 | } |
| 46 | const mine = new Set(); |
| 47 | for (const change of [0, 1]) for (let i = 0; i < (change ? nextChange : nextReceive) + 1; i++) mine.add(w.address(i, change)); |
| 48 | const history = [...txs.values()].map((t) => { |
| 49 | let delta = 0; |
| 50 | for (const o of t.vout) if (mine.has(o.scriptpubkey_address)) delta += o.value; |
| 51 | for (const v of t.vin) if (v.prevout && mine.has(v.prevout.scriptpubkey_address)) delta -= v.prevout.value; |
| 52 | return { txid: t.txid, delta, time: t.status && t.status.block_time ? t.status.block_time * 1000 : null, confirmed: !!(t.status && t.status.confirmed) }; |
| 53 | }).sort((a, b) => (b.time || 9e15) - (a.time || 9e15)); |
| 54 | const balance = utxos.reduce((s, u) => s + u.value, 0); |
| 55 | return { utxos, balance, history, nextReceive, nextChange }; |
| 56 | } |
| 57 | |
| 58 | export function validAddress(a) { |
| 59 | try { btc.Address(NET).decode(String(a).trim()); return true; } catch { return false; } |
| 60 | } |
| 61 | |
| 62 | // Build and sign a payment. Returns { hex, fee, txid }. |
| 63 | export function buildPayment(w, s, to, sats, feeRate) { |
| 64 | to = String(to).trim(); |
| 65 | if (!validAddress(to)) throw new Error('That isn’t a test-network Bitcoin address (they start with tb1).'); |
| 66 | sats = Math.floor(sats); |
| 67 | if (!(sats >= 330)) throw new Error('That amount is too small to send.'); |
| 68 | const coins = [...s.utxos].sort((a, b) => b.value - a.value); |
| 69 | const picked = []; let total = 0, fee = 0; |
| 70 | for (const c of coins) { |
| 71 | picked.push(c); total += c.value; |
| 72 | fee = Math.ceil((11 + 68 * picked.length + 31 * 2) * feeRate); |
| 73 | if (total >= sats + fee) break; |
| 74 | } |
| 75 | if (total < sats + fee) throw new Error('Not enough in your wallet for this payment and the network fee.'); |
| 76 | const tx = new btc.Transaction(); |
| 77 | for (const c of picked) tx.addInput({ txid: c.txid, index: c.vout, witnessUtxo: { script: c.script, amount: BigInt(c.value) } }); |
| 78 | tx.addOutputAddress(to, BigInt(sats), NET); |
| 79 | const change = total - sats - fee; |
| 80 | if (change >= 546) tx.addOutputAddress(w.address(s.nextChange, 1), BigInt(change), NET); |
| 81 | else fee += change; |
| 82 | picked.forEach((c, idx) => tx.signIdx(w.key(c.change, c.i).privateKey, idx)); |
| 83 | tx.finalize(); |
| 84 | return { hex: tx.hex, fee, txid: tx.id }; |
| 85 | } |
| 86 | |
| 87 | export function qrSvg(text) { |
| 88 | const q = qrcode(0, 'M'); q.addData(text); q.make(); |
| 89 | return q.createSvgTag({ cellSize: 6, margin: 2, scalable: true }); |
| 90 | } |