diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 50dc708..1b41c37 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -6,7 +6,7 @@ import { applyExpirations, bookFromRecords } from './addressBook.ts' import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' import ReceiveInfo from './ReceiveInfo.tsx' import { readCoverage, type Coverage } from './coverageClient.ts' -import { refreshCoins, type Coin } from './coins.ts' +import { availableRetainedCoins, refreshCoins, type Coin } from './coins.ts' import { importCoins, sendCoins, unfinishedWalletActions } from './actions.ts' import { preferCompatibleTransport } from './walletClient.ts' import { assertWalletActionFinal } from './walletActionState.ts' @@ -28,6 +28,7 @@ export default function Mountaintops() { const [message, setMessage] = useState('') const [error, setError] = useState('') const [balances, setBalances] = useState>({}) + const [checkedPayments, setCheckedPayments] = useState>({}) const [view, setView] = useState<'receive' | 'send'>('receive') const [target, setTarget] = useState('auto') const [candidate, setCandidate] = useState<{ stage: number; keyID: string; address: string } | null>(null) @@ -49,7 +50,7 @@ export default function Mountaintops() { if (operation.current) return operation.current = true; setBusy(true) if (!quiet) { setError(''); setMessage('Working… Check your wallet if prompted.') } - try { await task() } catch (e) { setError(e instanceof Error ? e.message : 'Operation unavailable. Check your wallet before retrying a payment.') } + try { await task() } catch (e) { setMessage(''); setError(e instanceof Error ? e.message : 'Operation unavailable. Check your wallet before retrying a payment.') } finally { operation.current = false; setBusy(false) } } @@ -58,7 +59,7 @@ export default function Mountaintops() { const { network } = await client.getNetwork({}) const { publicKey: identity } = await client.getPublicKey({ identityKey: true }) if (previous && (previous.identity !== identity || previous.network !== network)) { - setSession(null); setBalances({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') + setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') throw new Error('Wallet account or network changed. Connect again to load its own records.') } const store = previous?.store ?? new WalletRecords(client, identity, network) @@ -78,6 +79,22 @@ export default function Mountaintops() { return next } + const connect = () => void run(async () => { + setBalances({}); setCheckedPayments({}) + const fresh = await reload(null) + setMessage('Restoring payments from your wallet…') + let failure: unknown + for (const entry of fresh.book) { + try { + const coins = await availableRetainedCoins(client, entry, fresh.coverage) + setBalances(x => ({ ...x, [entry.keyID]: coins })) + } catch (e) { failure ??= e } + } + await reload(fresh) + if (failure) throw failure + setMessage('') + }) + // Only chain coverage is rechecked. No background address-deposit polling. useEffect(() => { if (!session) return @@ -156,15 +173,18 @@ export default function Mountaintops() { } const checkCoins = (keyID: string) => void run(async () => { const fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID)! + setCheckedPayments(x => ({ ...x, [keyID]: false })) const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) - setBalances(x => ({ ...x, [keyID]: coins })); await reload(fresh) - setMessage('Payments checked.') + setBalances(x => ({ ...x, [keyID]: coins })); setCheckedPayments(x => ({ ...x, [keyID]: true })); await reload(fresh) + setMessage('Payments checked for this address.') }) const checkAllCoins = () => void run(async () => { const fresh = await reload() for (const entry of fresh.book) { + setCheckedPayments(x => ({ ...x, [entry.keyID]: false })) const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) setBalances(x => ({ ...x, [entry.keyID]: coins })) + setCheckedPayments(x => ({ ...x, [entry.keyID]: true })) } await reload(fresh); setMessage('Payments checked.') }) @@ -174,6 +194,7 @@ export default function Mountaintops() { const entry = fresh.book.find(x => x.keyID === keyID)! const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) const submitted = await importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage) + setCheckedPayments(x => ({ ...x, [keyID]: false })) setTxid(submitted); setHistory(x => [{ txid: submitted, description: 'Import to wallet', status: 'Submitted' }, ...x]); setBalances(x => ({ ...x, [keyID]: undefined })) await reload(fresh); setMessage('Transfer submitted. Check your wallet for the final result.') }) @@ -194,6 +215,8 @@ export default function Mountaintops() { const primary = session?.book.find(x => x.keyID === session.primary) const suggestedEntry = !candidate && !pausedSearch && !searching && session?.book.filter(x => !x.retiredAt && lastCoveredStage(x.address) > (primary ? lastCoveredStage(primary.address) : -1)).sort((a, b) => lastCoveredStage(b.address) - lastCoveredStage(a.address))[0] const pendingActions = session ? unresolvedActions(session.records) : [] + const allPaymentsChecked = Boolean(session?.book.every(x => checkedPayments[x.keyID])) + const checkedCount = session?.book.filter(x => checkedPayments[x.keyID]).length ?? 0 const savedSearches = session ? [...new Map(session.records.filter(x => x.kind === 'search').map(x => [Number(x.data.stage), x.data])).values()] .filter(x => Number(x.stage) > Math.max(...session.book.map(entry => lastCoveredStage(entry.address)))) : [] const card = (entry: AddressRecord, selected = false) => { @@ -217,7 +240,7 @@ export default function Mountaintops() { {!entry.retiredAt && } {!entry.retiredAt && !selected && } - {!selected && <>
{total !== undefined ? <>{total.toLocaleString()} sats{money(total)} · available here : Payments}
+ {!selected && <>
{total !== undefined && (total > 0 || checkedPayments[entry.keyID]) ? <>{total.toLocaleString()} sats{money(total)} · available here : {total === undefined ? 'Payments not checked' : 'Not checked for new payments'}}
{Boolean(coins?.length) &&
Wallet fees apply.
}}
Address details

{coverageLabel(entry.address, entry.network, session!.coverage.anchorMtp, entry.retiredAt)}

{entry.retiredAt &&

Expired at block {entry.retiredAt.height.toLocaleString()}. New-deposit lookups have stopped permanently.

}

Key ID {entry.keyID} · address rules satisfied through stage {level}. Payment transaction rules also apply.

{coins &&

Funding transactions: {coins.filter(x => x.fundingCoverage === 'covered').length} covered at confirmation, {coins.filter(x => x.fundingCoverage === 'outside coverage').length} outside coverage, {coins.filter(x => x.fundingCoverage === 'unconfirmed').length} unconfirmed. These labels do not change ownership.

}
@@ -225,7 +248,7 @@ export default function Mountaintops() { return

Mountaintops

Public BSV payments.

- {!session ?

Your BSV, ready to receive.

Connect your wallet to find your addresses and payments.

Use the same BRC-100 wallet on any device.

: <> + {!session ?

Your BSV, ready to receive.

Connect your wallet to find your addresses and payments.

Use the same BRC-100 wallet on any device.

: <> {pendingActions.length > 0 &&

Check your wallet before continuing

A previous payment has no final result yet. Do not send it again.

{pendingActions.map(action =>
Payment details

{String(action.state)} {action.txid ? `· ${String(action.txid)}` : ''}

- {session.book.every(x => balances[x.keyID] !== undefined) ?

All addresses checked this session.

:

Check here for payments to current and earlier addresses.

} +

Payments to your addresses

+

{allPaymentsChecked ? 'All addresses checked this session.' : checkedCount ? `${checkedCount} of ${session.book.length} addresses checked for new payments.` : session.book.every(x => balances[x.keyID] !== undefined) ? 'Payments restored from your wallet. Refresh to check for new ones.' : 'Some payments still need checking. Refresh to check all addresses.'}

{session.book.filter(x => balances[x.keyID]?.length).map(entry =>
{balances[entry.keyID]!.reduce((sum, coin) => sum + coin.satoshis, 0).toLocaleString()} sats{entry.keyID === '1' ? 'Original address' : `Address …${entry.address.slice(-6)}`}{entry.retiredAt ? ' · earlier payments' : ''}
)} {session.book.some(x => balances[x.keyID]?.length) &&

Wallet fees apply when moving coins.

} - {session.book.every(x => balances[x.keyID] !== undefined && balances[x.keyID]?.length === 0) &&

No available payments found.

} + {allPaymentsChecked && session.book.every(x => balances[x.keyID]?.length === 0) &&

No available payments found.

}

A longer-lasting address

{suggestedEntry ? 'Already saved. Free to switch.' : 'Free to find. Wallet fees apply to save it.'}

{searching ? : }
{suggestedEntry &&

{expirationEstimate(lastCoveredStage(suggestedEntry.address), calendar)}

Estimated · stage {lastCoveredStage(suggestedEntry.address)}
} diff --git a/frontend/src/coins.ts b/frontend/src/coins.ts index 42030d0..180935a 100644 --- a/frontend/src/coins.ts +++ b/frontend/src/coins.ts @@ -217,6 +217,14 @@ export async function refreshCoins(wallet: WalletInterface, store: WalletRecords catch { progress('Coin evidence is retained in your wallet. Saving historical-check completion needs wallet funds; the bounded check may repeat until it is saved. Import remains available.') } } } + return availableRetainedCoins(wallet, entry, coverage, retained) +} + +// Reconnecting restores known funds from the wallet without address discovery, +// historical bootstrap receipts, or a fee-bearing record. Keep the same source, +// spend-state and canonical-proof checks used by an explicit payment refresh. +export async function availableRetainedCoins(wallet: WalletInterface, entry: AddressRecord, coverage: Coverage, retained?: Awaited>): Promise { + retained ??= await retainedCoins(wallet, entry) const unique = new Map() for (const coin of retained.coins) { // Revalidate known evidence even for wallet rows omitted from current WoC diff --git a/frontend/test/coinRecords.test.mjs b/frontend/test/coinRecords.test.mjs index 5d4d02a..2f3619e 100644 --- a/frontend/test/coinRecords.test.mjs +++ b/frontend/test/coinRecords.test.mjs @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { MerklePath, P2PKH, PublicKey, Transaction } from '@bsv/sdk' -import { COIN_BASKET, refreshCoins, retainedCoins } from '../src/coins.ts' +import { availableRetainedCoins, COIN_BASKET, refreshCoins, retainedCoins } from '../src/coins.ts' import { FixtureWallet } from './fixtureWallet.mjs' test('tagless wallet receipts remain recoverable and are scoped to each address', async () => { @@ -28,7 +28,10 @@ test('tagless wallet receipts remain recoverable and are scoped to each address' await assert.rejects(retainedCoins(wallet, entries[0]), /pagination is incomplete/) }) -test('active refresh reuses acknowledged evidence and still checks actual spend status and canonical roots', async () => { +for (const mode of ['discovery', 'restore-active', 'restore-expired', 'restore-unknown']) test(mode === 'discovery' + ? 'active refresh reuses acknowledged evidence and checks spend status and canonical roots' + : mode === 'restore-unknown' ? 'unknown spend state during reconnect is an error, never a zero balance' + : `${mode} recovers wallet funds on a fresh instance without address lookups or paid records`, async () => { const wallet = new FixtureWallet() const keyID = '1' const pub = await wallet.getPublicKey({ protocolID: [1, 'mountaintops'], keyID, counterparty: 'anyone', forSelf: true }) @@ -40,17 +43,29 @@ test('active refresh reuses acknowledged evidence and still checks actual spend const coin = { txid, vout: 0, satoshis: 10000, keyID, address, height } wallet.state.outputs.set(`${txid}.0`, { basket: COIN_BASKET, tags: [], satoshis: 10000, spendable: true, customInstructions: JSON.stringify({ v: 1, network: 'mainnet', ...coin }) }) wallet.internalizeAction = async () => { throw new Error('Must not reinsert acknowledged evidence') } + wallet.createAction = async () => { throw new Error('Recovery must not create a transaction') } const previous = globalThis.fetch, calls = [] globalThis.fetch = async url => { calls.push(String(url)) - if (String(url).includes('/unspent/all')) return Response.json({ address, result: [{ tx_hash: txid, tx_pos: 0, value: 10000, height, isSpentInMempoolTx: false }] }) - if (String(url).endsWith('/spent')) return new Response('', { status: 404 }) + if (mode === 'discovery' && String(url).includes('/unspent/all')) return Response.json({ address, result: [{ tx_hash: txid, tx_pos: 0, value: 10000, height, isSpentInMempoolTx: false }] }) + if (String(url).endsWith('/spent')) return new Response('', { status: mode === 'restore-unknown' ? 400 : 404 }) if (String(url).endsWith(`/block/${height}/header`)) return Response.json({ merkleroot: txid }) throw new Error('Unexpected proof download: ' + url) } try { - const coins = await refreshCoins(wallet, {}, { keyID, address, network: 'mainnet', targetStage: 0, retiredAt: null }, { stage: 0, height: 972777, activations: [] }, () => {}) + const entry = { keyID, address, network: 'mainnet', targetStage: 0, retiredAt: mode === 'restore-expired' ? { height: 1000002, hash: 'f'.repeat(64), mtp: 123, lastReceiveHeight: 1000001 } : null } + const coverage = { stage: 0, height: 972777, activations: [] } + const fresh = new FixtureWallet(wallet.state) + fresh.createAction = wallet.createAction; fresh.internalizeAction = wallet.internalizeAction + if (mode === 'restore-unknown') { + await assert.rejects(availableRetainedCoins(fresh, entry, coverage), /Spend status unknown/) + assert.equal(calls.length, 1) + return + } + const coins = mode === 'discovery' ? await refreshCoins(fresh, {}, entry, coverage, () => {}) : await availableRetainedCoins(fresh, entry, coverage) assert.equal(coins.length, 1) - assert.equal(calls.length, 3) + assert.equal(coins[0].satoshis, 10000) + assert.equal(calls.length, mode === 'discovery' ? 3 : 2) + if (mode !== 'discovery') assert.equal(calls.some(url => url.includes('/address/')), false) } finally { globalThis.fetch = previous } }) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index c5cf2a6..7595c49 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -2,7 +2,11 @@ import { FixtureWallet } from './fixtureWallet.mjs' import { firstMatch } from '../src/derivation.ts' import { WalletRecords } from '../src/walletRecords.ts' +import { MerklePath, P2PKH, PublicKey, Transaction } from '@bsv/sdk' +import { COIN_BASKET } from '../src/coins.ts' const wallet = new FixtureWallet() +const paymentRoots = new Map() +let savedAddress window.CWI = wallet const counter = document.createElement('output'); counter.id = 'fixture-actions'; counter.style.cssText = 'display:block;text-align:center;padding:8px'; counter.textContent = 'Isolated fixture · 0 wallet transactions'; document.body.prepend(counter) const create = wallet.createAction.bind(wallet) @@ -10,6 +14,8 @@ wallet.createAction = async args => { counter.textContent = `Isolated fixture · ${++actions} wallet transactions`; return create(args) } window.fetch = async (input) => { const url = String(input) + const headerHeight = Number(url.match(/\/block\/(\d+)\/header$/)?.[1]) + if (paymentRoots.has(headerHeight)) return Response.json({ merkleroot: paymentRoots.get(headerHeight) }) if (url.endsWith('/spent')) return new Response('', { status: 404 }) if (url.includes('/block/height/972777')) return Response.json({ height: 972777, hash: 'a'.repeat(64), previousblockhash: 'b'.repeat(64), mediantime: Date.parse('2026-10-29T12:00:00Z') / 1000 }) if (url.includes('/chain/info')) return Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) @@ -20,6 +26,7 @@ const identity = (await wallet.getPublicKey({ identityKey: true })).publicKey const found = firstMatch(identity, 8, 'mainnet', 10000n) if (!found) throw new Error('Fixture address missing') + savedAddress = found await new WalletRecords(wallet, identity, 'mainnet').append('address', { keyID: found.keyID, address: found.address, targetStage: 8, useForReceiving: true }) } if (new URL(location.href).searchParams.has('expired')) { @@ -27,5 +34,17 @@ const store = new WalletRecords(wallet, identity, 'mainnet') await store.append('retirement', { keyID: '1', boundary: { height: 1000002, hash: 'f'.repeat(64), mtp: 1920000000, lastReceiveHeight: 1000001 } }) } +if (new URL(location.href).searchParams.has('payments')) { + for (const [index, keyID] of ['1', savedAddress?.keyID].filter(Boolean).entries()) { + const pub = await wallet.getPublicKey({ protocolID: [1, 'mountaintops'], keyID, counterparty: 'anyone', forSelf: true }) + const address = PublicKey.fromString(pub.publicKey).toAddress() + const tx = new Transaction(1, [], [{ satoshis: index ? 10000 : 10002, lockingScript: new P2PKH().lock(address) }]) + const txid = tx.id('hex'), height = 971998 + index + tx.merklePath = MerklePath.fromCoinbaseTxidAndHeight(txid, height) + paymentRoots.set(height, txid); wallet.state.transactions.set(txid, tx) + const coin = { txid, vout: 0, satoshis: index ? 10000 : 10002, keyID, address, height } + wallet.state.outputs.set(`${txid}.0`, { basket: COIN_BASKET, tags: [], satoshis: coin.satoshis, spendable: true, customInstructions: JSON.stringify({ v: 1, network: 'mainnet', ...coin }) }) + } +} await import('../src/main.tsx')