From 12d4edec9483d69c6feb5804f08a2892ee697526 Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Wed, 11 Nov 2026 15:41:24 -0800 Subject: [PATCH 01/13] Distinguish submitted payments from unknown wallet outcomes --- README.md | 20 +++++++++ frontend/package-lock.json | 48 +++++++++++++++++++++ frontend/package.json | 4 +- frontend/src/App.tsx | 15 ++++--- frontend/src/walletActionState.ts | 23 ++++++++-- frontend/test/actions.test.mjs | 2 +- frontend/test/browser/payment-status.mjs | 55 ++++++++++++++++++++++++ frontend/test/paymentStatus.test.mjs | 31 +++++++++++++ frontend/test/permissions.test.mjs | 4 +- frontend/test/ui.html | 6 +++ 10 files changed, 195 insertions(+), 13 deletions(-) create mode 100644 frontend/test/browser/payment-status.mjs create mode 100644 frontend/test/paymentStatus.test.mjs diff --git a/README.md b/README.md index fba9120..8758f91 100644 --- a/README.md +++ b/README.md @@ -67,3 +67,23 @@ After publishing addresses, rollback must preserve this wallet record format, ex New actions use fixed labels and native TXIDs, avoiding a new label permission for every request. Older UUID-labelled actions remain recoverable by reading the common app label and matching their TXID or legacy label in returned metadata. No transaction UI history is persisted. The header and favicon use the same authored `/mountaintops.svg`. Wallet/PWA icons and the touch icon are PNG renders of that source at 192 and 512 pixels. Keep all variants in sync when changing the logo. The unused legacy Vite file remains only for cached old HTML during compatible releases; the current app and manifest never reference it. + +## November 11 payment-status candidate + +The local review candidate distinguishes a submitted `unproven` payment waiting +for a mined proof from an unknown sending outcome. **Refresh payment status** +reads wallet history and shows the last check time without signing, rebroadcasting +or saving a record. Prepared unsent actions retain their separate cancel action. +All existing pending-payment guards, fixed labels, device-independent recovery, +receiving expiration and coin/input checks remain. No schema migration or live +release is included; operator merge and release review remain pending. + +Validation from `frontend/`: `npm test`, `npm run lint`, `npm run build`, and +`npm run test:browser`. Browser checks at 1440, 390 and 320 pixels cover delayed +proof, repeated refresh, blocked resend, completion, reconnect and unknown +outcomes using synthetic wallet state. They assert zero wallet transactions and +block external requests. `PAYMENT_STATUS_EVIDENCE` optionally saves synthetic +screenshots. The status API supplies no submission timestamp, so the UI reports +the observed check time rather than inventing elapsed submission time. Release +must retain the immutable asset bridge and existing CARS availability rules; +rollback is the prior compatible frontend, never deletion of wallet records. diff --git a/frontend/package-lock.json b/frontend/package-lock.json index 672d2ac..93e9001 100644 --- a/frontend/package-lock.json +++ b/frontend/package-lock.json @@ -24,6 +24,7 @@ "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.16", "globals": "^15.14.0", + "playwright": "1.61.1", "typescript": "5.8.3", "typescript-eslint": "^8.18.2", "vite": "^6.0.5" @@ -2694,6 +2695,53 @@ "url": "https://github.com/sponsors/jonschlinkert" } }, + "node_modules/playwright": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.1.tgz", + "integrity": "sha512-DWnY5o3YbLWK4GovuAVwpqL+1VwGNdUGrRr++8j8PtQQzvAVZUIMjKQ90fY689sEJZJBbZVw1rXaOKSTitkzPQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.61.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.61.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.1.tgz", + "integrity": "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/playwright/node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, "node_modules/postcss": { "version": "8.5.31", "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.31.tgz", diff --git a/frontend/package.json b/frontend/package.json index 0857e4a..dfe66e0 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,8 @@ "build": "tsc -b && vite build", "lint": "eslint .", "test": "node --test --experimental-strip-types test/*.test.mjs", - "preview": "vite preview" + "preview": "vite preview", + "test:browser": "node test/browser/payment-status.mjs" }, "dependencies": { "@bsv/sdk": "4.0.0", @@ -28,6 +29,7 @@ "eslint-plugin-react-hooks": "^5.0.0", "eslint-plugin-react-refresh": "^0.4.16", "globals": "^15.14.0", + "playwright": "1.61.1", "typescript": "5.8.3", "typescript-eslint": "^8.18.2", "vite": "^6.0.5" diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 1b41c37..efd44c4 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,7 +9,7 @@ import { readCoverage, type Coverage } from './coverageClient.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' +import { walletActionStatus, walletStatusMessage } from './walletActionState.ts' import './style.css' const client = new WalletClient('auto') @@ -27,6 +27,7 @@ export default function Mountaintops() { const [busy, setBusy] = useState(false) const [message, setMessage] = useState('') const [error, setError] = useState('') + const [statusCheckedAt, setStatusCheckedAt] = useState(null) const [balances, setBalances] = useState>({}) const [checkedPayments, setCheckedPayments] = useState>({}) const [view, setView] = useState<'receive' | 'send'>('receive') @@ -76,6 +77,7 @@ export default function Mountaintops() { records = [...records, ...await unfinishedWalletActions(client, network)] const next = { identity, network, store, records, book, coverage, primary: receivingBlocked ? null : receivingKeyID(book, coverage.stage, previous?.primary), receivingBlocked } setSession(next) + setStatusCheckedAt(Date.now()) return next } @@ -250,16 +252,19 @@ export default function Mountaintops() {

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.

: <> - {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)}` : ''}

)}
} + })}>{action.state === 'prepared' ? 'Cancel unsent payment' : 'Refresh payment status'})}} {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} {(message || error) &&
{message && !searching &&

{message}

}{error &&

{error}

}
} diff --git a/frontend/src/walletActionState.ts b/frontend/src/walletActionState.ts index 107f8c4..05f0f4f 100644 --- a/frontend/src/walletActionState.ts +++ b/frontend/src/walletActionState.ts @@ -13,12 +13,27 @@ async function walletActions(wallet: WalletInterface) { } } -export async function assertWalletActionFinal(wallet: WalletInterface, action: Record): Promise { - // Read legacy UUID labels from results without requesting that dynamic scope. +export async function walletActionStatus(wallet: WalletInterface, action: Record): Promise<'completed' | 'failed' | 'unproven' | 'unknown'> { + // Read legacy UUID labels without requesting that dynamic permission scope. const actions = (await walletActions(wallet)).filter(x => action.txid ? x.txid === action.txid : typeof action.id === 'string' && x.labels?.includes(`mountaintops request ${action.id}`)) - if (!actions.length || actions.some(x => !['completed', 'failed'].includes(x.status))) throw new Error('Your wallet has no final result yet. Do not retry this payment.') + const statuses = new Set(actions.map(x => x.status)) + if (statuses.size !== 1) return 'unknown' + const status = actions[0]?.status + return status === 'completed' || status === 'failed' || status === 'unproven' ? status : 'unknown' +} + +export function walletStatusMessage(status: Awaited>): string { + if (status === 'completed') return 'Payment confirmed by your wallet.' + if (status === 'failed') return 'Your wallet reports this payment failed. Review wallet activity before starting another payment.' + if (status === 'unproven') return 'Submitted; waiting for confirmation. Your wallet has not returned a mined proof yet. Do not send this payment again.' + return 'The payment outcome is not known. Check wallet activity before continuing. Do not send it again.' +} + +export async function assertWalletActionFinal(wallet: WalletInterface, action: Record): Promise { + const status = await walletActionStatus(wallet, action) + if (status !== 'completed' && status !== 'failed') throw new Error(walletStatusMessage(status)) } export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { @@ -28,7 +43,7 @@ export async function unfinishedWalletActions(wallet: WalletInterface, network: if (action.status === 'unproven' && action.labels?.includes(RECORD_LABEL)) continue const id = action.labels?.find(x => x.startsWith('mountaintops request '))?.slice(21) ?? action.txid const canAbort = action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) - pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) + pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : action.status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) } return pending } diff --git a/frontend/test/actions.test.mjs b/frontend/test/actions.test.mjs index fb7ca25..de6e02c 100644 --- a/frontend/test/actions.test.mjs +++ b/frontend/test/actions.test.mjs @@ -129,7 +129,7 @@ test('fresh-device recovery blocks another payment while a submission is sending wallet.state.actions.push({ txid: 'a'.repeat(64), status, labels: ['mountaintops actions v1', 'mountaintops request uncertain'], description: 'Awaiting wallet outcome' }) const pending = await unfinishedWalletActions(new FixtureWallet(wallet.state), 'mainnet') assert.equal(pending.length, 1) - assert.equal(pending[0].data.state, 'needs wallet review') + assert.equal(pending[0].data.state, status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review') await assert.rejects(sendCoins(wallet, { network: 'mainnet' }, new PrivateKey(43).toPublicKey().toAddress(), '0.00000001', { stage: 0 }, () => {}), /unfinished wallet action/) } }) diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs new file mode 100644 index 0000000..871211a --- /dev/null +++ b/frontend/test/browser/payment-status.mjs @@ -0,0 +1,55 @@ +import assert from 'node:assert/strict' +import path from 'node:path' +import { mkdir } from 'node:fs/promises' +import { createServer } from 'vite' +import { chromium } from 'playwright' +const root = path.resolve(import.meta.dirname, '../..') +const evidence = process.env.PAYMENT_STATUS_EVIDENCE +if (evidence) await mkdir(evidence, { recursive: true }) +const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 } }) +await server.listen() +const origin = `http://127.0.0.1:${server.httpServer.address().port}` +const browser = await chromium.launch({ headless: true }) +try { + for (const width of [1440, 390, 320]) { + const context = await browser.newContext({ viewport: { width, height: 1000 }, serviceWorkers: 'block' }) + const page = await context.newPage(), errors = [], unexpected = [] + page.on('pageerror', error => errors.push(error.message)) + await context.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue() + unexpected.push(route.request().url()); return route.abort() + }) + try { + await page.goto(origin + '/test/ui.html?pending=unproven') + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() + const status = page.getByRole('region', { name: 'Wallet payment status' }) + await status.getByRole('heading', { name: 'Submitted; waiting for confirmation', exact: true }).waitFor() + await status.getByText('Last checked', { exact: false }).waitFor() + for (let i = 0; i < 2; i++) { + await status.getByRole('button', { name: 'Refresh payment status' }).click() + await page.getByText('Submitted; waiting for confirmation. Your wallet has not returned a mined proof yet. Do not send this payment again.', { exact: true }).last().waitFor() + } + assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') + await page.getByRole('button', { name: 'Send', exact: true }).click() + await page.getByLabel('To', { exact: true }).fill('1BoatSLRHtKNngkdXEeobR76b53LETtpyT') + await page.getByLabel('Amount in BSV').fill('0.00000001') + assert.equal(await page.getByRole('button', { name: 'Send BSV', exact: true }).isDisabled(), true) + if (evidence) await page.screenshot({ path: path.join(evidence, `pending-${width}.png`), fullPage: true }) + await page.evaluate(() => window.fixtureSetStatus('completed')) + await status.getByRole('button', { name: 'Refresh payment status' }).click() + await page.getByText('Payment confirmed by your wallet.', { exact: true }).waitFor() + assert.equal(await status.count(), 0) + assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + // A fresh connection must show an unknown sending outcome differently. + await page.goto(origin + '/test/ui.html?pending=sending') + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() + await status.getByRole('heading', { name: 'Check your wallet before continuing', exact: true }).waitFor() + await status.getByRole('button', { name: 'Refresh payment status' }).click() + await page.getByText('The payment outcome is not known.', { exact: false }).last().waitFor() + assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') + assert.deepEqual(errors, []); assert.deepEqual(unexpected, []) + console.log(`PASS ${width}px: pending proof, repeated refresh, completion and unknown outcome; zero wallet transactions or external requests`) + } finally { await context.close() } + } +} finally { await browser.close(); await server.close() } diff --git a/frontend/test/paymentStatus.test.mjs b/frontend/test/paymentStatus.test.mjs new file mode 100644 index 0000000..9261b82 --- /dev/null +++ b/frontend/test/paymentStatus.test.mjs @@ -0,0 +1,31 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { walletActionStatus, walletStatusMessage, unfinishedWalletActions, assertWalletActionFinal } from '../src/walletActionState.ts' + +const txid = 'a'.repeat(64) +test('refresh and reconnect distinguish submitted/unproven from unknown without another financial call', async () => { + let status = 'unproven', reads = 0 + const wallet = { listActions: async () => { reads++; return { totalActions: 1, actions: [{ txid, status, labels: ['mountaintops actions v1'] }] } } } + for (let i = 0; i < 3; i++) { + assert.equal((await unfinishedWalletActions(wallet, 'mainnet'))[0].data.state, 'awaiting confirmation') + assert.equal(await walletActionStatus(wallet, { txid }), 'unproven') + assert.match(walletStatusMessage('unproven'), /Submitted; waiting for confirmation/) + await assert.rejects(assertWalletActionFinal(wallet, { txid }), /Do not send this payment again/) + } + status = 'completed' + assert.equal(await walletActionStatus(wallet, { txid }), 'completed') + await assertWalletActionFinal(wallet, { txid }) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) + status = 'failed' + assert.equal(await walletActionStatus(wallet, { txid }), 'failed') + assert.match(walletStatusMessage('failed'), /reports this payment failed/) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) + assert.ok(reads > 10) +}) +test('missing, conflicting, sending and unfamiliar outcomes never claim submission or completion', async () => { + for (const actions of [[], [{ txid, status: 'sending' }], [{ txid, status: 'future-state' }], [{ txid, status: 'completed' }, { txid, status: 'unproven' }]]) { + const wallet = { listActions: async () => ({ totalActions: actions.length, actions }) } + assert.equal(await walletActionStatus(wallet, { txid }), 'unknown') + await assert.rejects(assertWalletActionFinal(wallet, { txid }), /outcome is not known/) + } +}) diff --git a/frontend/test/permissions.test.mjs b/frontend/test/permissions.test.mjs index ed00b5b..81e86c9 100644 --- a/frontend/test/permissions.test.mjs +++ b/frontend/test/permissions.test.mjs @@ -127,7 +127,7 @@ test('legacy and new pending actions resolve using one fixed label across pages' await assertWalletActionFinal(wallet, { id: 'old-request' }) await assertWalletActionFinal(wallet, { txid: actions[100].txid }) actions[100].status = 'unproven' - await assert.rejects(assertWalletActionFinal(wallet, { id: 'old-request' }), /no final result/) - await assert.rejects(assertWalletActionFinal(wallet, { txid: 'f'.repeat(64) }), /no final result/) + await assert.rejects(assertWalletActionFinal(wallet, { id: 'old-request' }), /Submitted; waiting for confirmation/) + await assert.rejects(assertWalletActionFinal(wallet, { txid: 'f'.repeat(64) }), /outcome is not known/) await assert.rejects(unfinishedWalletActions({ listActions: async () => ({ totalActions: 200, actions: [] }) }, 'mainnet'), /incomplete/) }) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 7595c49..9fae183 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -46,5 +46,11 @@ wallet.state.outputs.set(`${txid}.0`, { basket: COIN_BASKET, tags: [], satoshis: coin.satoshis, spendable: true, customInstructions: JSON.stringify({ v: 1, network: 'mainnet', ...coin }) }) } } +const pendingStatus = new URL(location.href).searchParams.get('pending') +if (pendingStatus) { + const pending = { txid: 'a'.repeat(64), status: pendingStatus, satoshis: 0, isOutgoing: true, version: 1, lockTime: 0, labels: ['mountaintops actions v1'], description: 'Synthetic payment waiting for wallet status' } + wallet.state.actions.push(pending) + window.fixtureSetStatus = status => { pending.status = status } +} await import('../src/main.tsx') From 4a23f921f99704f9d7db92cbae62dc7f5171dbbb Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Wed, 11 Nov 2026 19:50:44 -0800 Subject: [PATCH 02/13] Keep payment refresh read-only and retain uncertain action guards --- .github/workflows/ci.yml | 2 + README.md | 10 +++ frontend/src/App.tsx | 35 ++++++---- frontend/src/walletActionState.ts | 85 +++++++++++++++++++----- frontend/test/browser/payment-status.mjs | 24 +++++++ frontend/test/paymentStatus.test.mjs | 59 ++++++++++++++++ frontend/test/ui.html | 13 ++++ 7 files changed, 201 insertions(+), 27 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c7e2d2..41ec070 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,4 +22,6 @@ jobs: - run: npm run test - run: npm run lint - run: npm run build + - run: npx playwright install --with-deps chromium + - run: npm run test:browser - run: npm audit --omit=dev --audit-level=moderate diff --git a/README.md b/README.md index 8758f91..c403171 100644 --- a/README.md +++ b/README.md @@ -87,3 +87,13 @@ screenshots. The status API supplies no submission timestamp, so the UI reports the observed check time rather than inventing elapsed submission time. Release must retain the immutable asset bridge and existing CARS availability rules; rollback is the prior compatible frontend, never deletion of wallet records. + +The second validation pass gives payment status its own read path using only +`getPublicKey`, `getNetwork` and `listActions`; it never calls the general reload, +coverage scanner, recovery store or expiration persistence. Conflicting and +unfamiliar statuses block admission, and a previously observed unresolved action +missing from a later response remains blocked in that session. Legacy final +records are resolved only in memory; the existing record-only unproven exception +is retained. A stale cancel button cannot abort an action now reported submitted. +The browser regression deliberately refuses recovery/chain reads during status +refresh; CI installs Chromium and runs this regression as well as unit checks. diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index efd44c4..d341b33 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,9 +7,9 @@ import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveU import ReceiveInfo from './ReceiveInfo.tsx' import { readCoverage, type Coverage } from './coverageClient.ts' import { availableRetainedCoins, refreshCoins, type Coin } from './coins.ts' -import { importCoins, sendCoins, unfinishedWalletActions } from './actions.ts' +import { importCoins, sendCoins } from './actions.ts' import { preferCompatibleTransport } from './walletClient.ts' -import { walletActionStatus, walletStatusMessage } from './walletActionState.ts' +import { paymentActionRecords, refreshPaymentStatus, WalletAccountChangedError, walletStatusMessage } from './walletActionState.ts' import './style.css' const client = new WalletClient('auto') @@ -55,12 +55,16 @@ export default function Mountaintops() { finally { operation.current = false; setBusy(false) } } + const clearWalletSession = () => { + setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') + } + const reload = async (previous: Session | null = current.current): Promise => { await preferCompatibleTransport(client) const { network } = await client.getNetwork({}) const { publicKey: identity } = await client.getPublicKey({ identityKey: true }) if (previous && (previous.identity !== identity || previous.network !== network)) { - setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') + clearWalletSession() throw new Error('Wallet account or network changed. Connect again to load its own records.') } const store = previous?.store ?? new WalletRecords(client, identity, network) @@ -74,7 +78,7 @@ export default function Mountaintops() { const receivingBlocked = await applyExpirations(book, coverage, store) records = await store.load() if (!receivingBlocked) book = bookFromRecords(identity, network, records) - records = [...records, ...await unfinishedWalletActions(client, network)] + records = await paymentActionRecords(client, network, [...records, ...(previous?.records.filter(record => record.kind === 'action' && record.clock === 0) ?? [])]) const next = { identity, network, store, records, book, coverage, primary: receivingBlocked ? null : receivingKeyID(book, coverage.stage, previous?.primary), receivingBlocked } setSession(next) setStatusCheckedAt(Date.now()) @@ -255,14 +259,21 @@ export default function Mountaintops() { {pendingActions.length > 0 &&

{pendingActions.every(action => action.state === 'awaiting confirmation') ? 'Submitted; waiting for confirmation' : 'Check your wallet before continuing'}

Do not send these payments again. Confirmation may take time after submission.

{statusCheckedAt &&

Last checked {new Date(statusCheckedAt).toLocaleTimeString()}.

}{pendingActions.map(action =>

{action.state === 'awaiting confirmation' ? walletStatusMessage('unproven') : action.state === 'prepared' ? 'This payment is prepared but has not been submitted.' : walletStatusMessage('unknown')}

Payment details

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

)}
} {session.receivingBlocked &&

{session.receivingBlocked}

} diff --git a/frontend/src/walletActionState.ts b/frontend/src/walletActionState.ts index 05f0f4f..ac51e70 100644 --- a/frontend/src/walletActionState.ts +++ b/frontend/src/walletActionState.ts @@ -1,4 +1,4 @@ -import type { WalletInterface } from '@bsv/sdk' +import type { WalletAction, WalletInterface } from '@bsv/sdk' import type { RecoveryRecord, WalletRecords } from './walletRecords.ts' import { ACTION_LABEL, RECORD_LABEL } from './walletScopes.ts' @@ -13,17 +13,23 @@ async function walletActions(wallet: WalletInterface) { } } -export async function walletActionStatus(wallet: WalletInterface, action: Record): Promise<'completed' | 'failed' | 'unproven' | 'unknown'> { - // Read legacy UUID labels without requesting that dynamic permission scope. - const actions = (await walletActions(wallet)).filter(x => action.txid - ? x.txid === action.txid - : typeof action.id === 'string' && x.labels?.includes(`mountaintops request ${action.id}`)) - const statuses = new Set(actions.map(x => x.status)) +function matches(action: Record, row: WalletAction): boolean { + return typeof action.txid === 'string' && action.txid !== '' ? row.txid === action.txid + : typeof action.id === 'string' && Boolean(row.labels?.includes(`mountaintops request ${action.id}`)) +} + +function statusFromActions(actions: WalletAction[], action: Record): 'completed' | 'failed' | 'unproven' | 'unknown' { + const matching = actions.filter(row => matches(action, row)) + const statuses = new Set(matching.map(row => row.status)) if (statuses.size !== 1) return 'unknown' - const status = actions[0]?.status + const status = matching[0]?.status return status === 'completed' || status === 'failed' || status === 'unproven' ? status : 'unknown' } +export async function walletActionStatus(wallet: WalletInterface, action: Record): Promise<'completed' | 'failed' | 'unproven' | 'unknown'> { + return statusFromActions(await walletActions(wallet), action) +} + export function walletStatusMessage(status: Awaited>): string { if (status === 'completed') return 'Payment confirmed by your wallet.' if (status === 'failed') return 'Your wallet reports this payment failed. Review wallet activity before starting another payment.' @@ -36,15 +42,64 @@ export async function assertWalletActionFinal(wallet: WalletInterface, action: R if (status !== 'completed' && status !== 'failed') throw new Error(walletStatusMessage(status)) } -export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { +function pendingFromActions(actions: WalletAction[], network: WalletRecords['network']): RecoveryRecord[] { + const groups = new Map() + actions.forEach((action, index) => { + const key = action.txid || action.labels?.find(label => label.startsWith('mountaintops request ')) || `unidentified ${index}` + groups.set(key, [...(groups.get(key) ?? []), action]) + }) const pending: RecoveryRecord[] = [] - for (const action of await walletActions(wallet)) { - if (!['unsigned', 'nosend', 'nonfinal', 'unprocessed', 'sending', 'unproven'].includes(action.status)) continue - if (action.status === 'unproven' && action.labels?.includes(RECORD_LABEL)) continue - const id = action.labels?.find(x => x.startsWith('mountaintops request '))?.slice(21) ?? action.txid - const canAbort = action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) - pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : action.status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) + for (const [key, group] of groups) { + const action = group[0], statuses = new Set(group.map(row => row.status)) + const consistent = statuses.size === 1 + if (consistent && (action.status === 'completed' || action.status === 'failed')) continue + if (consistent && action.status === 'unproven' && group.every(row => row.labels?.includes(RECORD_LABEL))) continue + const id = action.labels?.find(label => label.startsWith('mountaintops request '))?.slice(21) ?? (action.txid || key) + const canAbort = consistent && action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) + pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : consistent && action.status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) } return pending } +function reconcileActionRecords(actions: WalletAction[], network: WalletRecords['network'], records: RecoveryRecord[]): RecoveryRecord[] { + const native = pendingFromActions(actions, network) + const carried: RecoveryRecord[] = [] + const resolved = new Set(['submitted', 'canceled', 'reviewed in wallet']) + for (const record of records) { + if (record.kind !== 'action') { carried.push(record); continue } + if (resolved.has(String(record.data.state))) { if (record.clock > 0) carried.push(record); continue } + const status = statusFromActions(actions, record.data) + const matching = actions.filter(row => matches(record.data, row)) + const recordOnly = status === 'unproven' && matching.every(row => row.labels?.includes(RECORD_LABEL)) + if (recordOnly || status === 'completed' || status === 'failed') { + // Resolve a legacy record only in memory; refresh never writes a token. + if (record.clock > 0) carried.push({ ...record, data: { ...record.data, state: 'reviewed in wallet' } }) + continue + } + if (native.some(item => item.data.id === record.data.id || (record.data.txid && item.data.txid === record.data.txid))) continue + // A previously observed action disappearing from history is not proof that + // it failed. Keep the resend guard until the wallet supplies a final result. + native.push({ ...record, data: { ...record.data, state: status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: null } }) + } + return [...carried, ...native] +} + +export async function paymentActionRecords(wallet: WalletInterface, network: WalletRecords['network'], records: RecoveryRecord[]): Promise { + return reconcileActionRecords(await walletActions(wallet), network, records) +} + +export class WalletAccountChangedError extends Error { + constructor() { super('Wallet account or network changed. Connect again to load its own records.') } +} + +/** Only identity, network and action-history reads; never reload recovery state. */ +export async function refreshPaymentStatus(wallet: WalletInterface, identity: string, network: WalletRecords['network'], records: RecoveryRecord[], action: Record) { + const [key, currentNetwork] = await Promise.all([wallet.getPublicKey({ identityKey: true }), wallet.getNetwork({})]) + if (key.publicKey !== identity || currentNetwork.network !== network) throw new WalletAccountChangedError() + const actions = await walletActions(wallet) + return { status: statusFromActions(actions, action), records: reconcileActionRecords(actions, network, records) } +} + +export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { + return pendingFromActions(await walletActions(wallet), network) +} diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs index 871211a..c371119 100644 --- a/frontend/test/browser/payment-status.mjs +++ b/frontend/test/browser/payment-status.mjs @@ -25,8 +25,12 @@ try { const status = page.getByRole('region', { name: 'Wallet payment status' }) await status.getByRole('heading', { name: 'Submitted; waiting for confirmation', exact: true }).waitFor() await status.getByText('Last checked', { exact: false }).waitFor() + await page.evaluate(() => window.fixtureBlockRecoveryReads()) for (let i = 0; i < 2; i++) { await status.getByRole('button', { name: 'Refresh payment status' }).click() + await status.getByRole('button', { name: 'Refresh payment status' }).waitFor({ state: 'visible' }) + await page.waitForFunction(() => !document.querySelector('[aria-label="Wallet payment status"] button').disabled) + assert.equal(await page.getByRole('alert').count(), 0, 'status refresh must not access recovery records or chain coverage') await page.getByText('Submitted; waiting for confirmation. Your wallet has not returned a mined proof yet. Do not send this payment again.', { exact: true }).last().waitFor() } assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') @@ -48,6 +52,26 @@ try { await status.getByRole('button', { name: 'Refresh payment status' }).click() await page.getByText('The payment outcome is not known.', { exact: false }).last().waitFor() assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') + await page.evaluate(() => { window.fixtureSetStatus('completed'); window.fixtureAddConflict() }) + await status.getByRole('button', { name: 'Refresh payment status' }).click() + await status.getByText('The payment outcome is not known.', { exact: false }).waitFor() + assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') + // A stale cancel button must not cancel a payment submitted elsewhere. + await page.goto(origin + '/test/ui.html?pending=nosend') + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() + await status.getByRole('button', { name: 'Cancel unsent payment' }).waitFor() + await page.evaluate(() => { window.fixtureBlockRecoveryReads(); window.fixtureSetStatus('unproven') }) + await status.getByRole('button', { name: 'Cancel unsent payment' }).click() + await status.getByRole('heading', { name: 'Submitted; waiting for confirmation', exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 0) + // A still-unsent preparation retains its normal explicit cancellation. + await page.evaluate(() => window.fixtureSetStatus('nosend')) + await status.getByRole('button', { name: 'Refresh payment status' }).click() + await status.getByRole('button', { name: 'Cancel unsent payment' }).click() + await page.getByText('Unsent payment canceled.', { exact: true }).waitFor() + assert.equal(await status.count(), 0) + assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 1) + assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') assert.deepEqual(errors, []); assert.deepEqual(unexpected, []) console.log(`PASS ${width}px: pending proof, repeated refresh, completion and unknown outcome; zero wallet transactions or external requests`) } finally { await context.close() } diff --git a/frontend/test/paymentStatus.test.mjs b/frontend/test/paymentStatus.test.mjs index 9261b82..b7f8a87 100644 --- a/frontend/test/paymentStatus.test.mjs +++ b/frontend/test/paymentStatus.test.mjs @@ -29,3 +29,62 @@ test('missing, conflicting, sending and unfamiliar outcomes never claim submissi await assert.rejects(assertWalletActionFinal(wallet, { txid }), /outcome is not known/) } }) + +test('unfamiliar and conflicting terminal wallet rows keep payment admission blocked', async () => { + for (const actions of [[{ txid, status: 'future-state' }], [{ txid, status: 'completed' }, { txid, status: 'failed' }]]) { + const wallet = { listActions: async () => ({ totalActions: actions.length, actions }) } + assert.equal((await unfinishedWalletActions(wallet, 'mainnet')).length, 1) + } +}) + +test('dedicated refresh uses only identity/network/history reads and keeps missing or conflicting observations blocked', async () => { + const { refreshPaymentStatus } = await import('../src/walletActionState.ts') + const identity = 'synthetic-wallet-identity' + let rows = [{ txid, status: 'unproven', labels: ['mountaintops actions v1'] }] + const methods = [] + const wallet = new Proxy({ + getPublicKey: async () => { methods.push('getPublicKey'); return { publicKey: identity } }, + getNetwork: async () => { methods.push('getNetwork'); return { network: 'mainnet' } }, + listActions: async () => { methods.push('listActions'); return { totalActions: rows.length, actions: rows } } + }, { get(target, key) { if (!(key in target)) throw Error(`Unexpected wallet method: ${String(key)}`); return target[key] } }) + let records = await unfinishedWalletActions(wallet, 'mainnet') + let result = await refreshPaymentStatus(wallet, identity, 'mainnet', records, { txid }) + assert.equal(result.status, 'unproven'); assert.equal(result.records.length, 1) + rows = [] + result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) + assert.equal(result.status, 'unknown'); assert.equal(result.records[0].data.state, 'needs wallet review') + rows = [{ txid, status: 'completed' }, { txid, status: 'failed' }] + result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) + assert.equal(result.status, 'unknown'); assert.equal(result.records.length, 1) + rows = [{ txid, status: 'completed' }] + result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) + assert.equal(result.status, 'completed'); assert.deepEqual(result.records, []) + assert.ok(methods.every(method => ['getPublicKey', 'getNetwork', 'listActions'].includes(method))) + await assert.rejects(refreshPaymentStatus(wallet, 'different-wallet', 'mainnet', records, { txid }), /account or network changed/) + await assert.rejects(refreshPaymentStatus(wallet, identity, 'testnet', records, { txid }), /account or network changed/) +}) + +test('status reconciliation retains the existing unproven record-only exception and resolves legacy records only in memory', async () => { + const { paymentActionRecords } = await import('../src/walletActionState.ts') + const prior = [{ v: 1, network: 'mainnet', kind: 'action', clock: 0, data: { id: txid, txid, state: 'needs wallet review' } }] + const recordRows = [{ txid, status: 'unproven', labels: ['mountaintops actions v1', 'mountaintops records v1'] }] + // The exact exported record scope, rather than an extra permission label. + const { RECORD_LABEL } = await import('../src/walletScopes.ts') + recordRows[0].labels[1] = RECORD_LABEL + const wallet = { listActions: async () => ({ totalActions: 1, actions: recordRows }) } + assert.deepEqual(await paymentActionRecords(wallet, 'mainnet', prior), []) + recordRows[0] = { txid, status: 'completed', labels: ['mountaintops actions v1'] } + const legacy = [{ ...prior[0], clock: 1, serial: 'synthetic.0' }] + const reconciled = await paymentActionRecords(wallet, 'mainnet', legacy) + assert.equal(reconciled[0].data.state, 'reviewed in wallet') + assert.equal(legacy[0].data.state, 'needs wallet review') +}) + +test('a failed history refresh cannot mutate or discard the previously observed guard', async () => { + const { refreshPaymentStatus } = await import('../src/walletActionState.ts') + const records = [{ v: 1, network: 'mainnet', kind: 'action', clock: 0, data: { id: txid, txid, state: 'awaiting confirmation' } }] + const before = structuredClone(records) + const wallet = { getPublicKey: async () => ({ publicKey: 'synthetic' }), getNetwork: async () => ({ network: 'mainnet' }), listActions: async () => { throw Error('Read unavailable') } } + await assert.rejects(refreshPaymentStatus(wallet, 'synthetic', 'mainnet', records, { txid }), /Read unavailable/) + assert.deepEqual(records, before) +}) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 9fae183..56f08cd 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -50,7 +50,20 @@ if (pendingStatus) { const pending = { txid: 'a'.repeat(64), status: pendingStatus, satoshis: 0, isOutgoing: true, version: 1, lockTime: 0, labels: ['mountaintops actions v1'], description: 'Synthetic payment waiting for wallet status' } wallet.state.actions.push(pending) + const abort = wallet.abortAction.bind(wallet) + let aborts = 0 + window.fixtureAbortCalls = () => aborts + wallet.abortAction = async args => { + aborts++ + if (args.reference === pending.txid && pending.status === 'nosend') { pending.status = 'failed'; return { aborted: true } } + return abort(args) + } window.fixtureSetStatus = status => { pending.status = status } + window.fixtureAddConflict = () => { wallet.state.actions.push({ ...pending, status: 'failed' }) } + window.fixtureBlockRecoveryReads = () => { + wallet.listOutputs = async () => { throw new Error('Status refresh accessed wallet records') } + window.fetch = async () => { throw new Error('Status refresh accessed chain coverage') } + } } await import('../src/main.tsx') From e75a726e19ebecc83d5133fe59ea03bcf8e1407f Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Wed, 11 Nov 2026 20:51:43 -0800 Subject: [PATCH 03/13] Present sent payments with clear compact status cards --- frontend/src/App.tsx | 28 ++++++++++++--------- frontend/src/PaymentStatus.tsx | 31 ++++++++++++++++++++++++ frontend/src/style.css | 25 +++++++++++++++++++ frontend/test/browser/payment-status.mjs | 26 ++++++++++++++------ 4 files changed, 92 insertions(+), 18 deletions(-) create mode 100644 frontend/src/PaymentStatus.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index d341b33..a28f463 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -5,6 +5,7 @@ import { WalletRecords, type RecoveryRecord } from './walletRecords.ts' import { applyExpirations, bookFromRecords } from './addressBook.ts' import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' import ReceiveInfo from './ReceiveInfo.tsx' +import PaymentStatus from './PaymentStatus.tsx' import { readCoverage, type Coverage } from './coverageClient.ts' import { availableRetainedCoins, refreshCoins, type Coin } from './coins.ts' import { importCoins, sendCoins } from './actions.ts' @@ -202,7 +203,8 @@ export default function Mountaintops() { 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.') + const next = await reload(fresh) + setMessage(unresolvedActions(next.records).length ? '' : 'Transfer submitted.') }) const send = () => void run(async () => { const fresh = await reload() @@ -212,8 +214,9 @@ export default function Mountaintops() { if (own) assertReceivable(own, fresh.coverage.stage) const submitted = await sendCoins(client, fresh.store, recipient, amount, fresh.coverage, setMessage) setTxid(submitted); setHistory(x => [{ txid: submitted, description: `Send ${amount} BSV`, status: 'Submitted' }, ...x]) - setRecipient(''); setAmount(''); await reload(fresh) - setMessage('Payment submitted. Check your wallet for the final result.') + setRecipient(''); setAmount('') + const next = await reload(fresh) + setMessage(unresolvedActions(next.records).length ? '' : 'Payment sent.') }) const disabled = busy || searching @@ -221,6 +224,9 @@ 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 paymentHold = pendingActions.length ? pendingActions.every(action => action.state === 'awaiting confirmation') + ? 'New transfers are paused until your outgoing payment confirms.' + : 'Check the payment above before starting another transfer.' : '' 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()] @@ -247,7 +253,7 @@ export default function Mountaintops() { {!entry.retiredAt && !selected && } {!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.
}} + {Boolean(coins?.length) && <>
Wallet fees apply.
{paymentHold &&

{paymentHold}

}}}
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.

}
} @@ -256,9 +262,8 @@ export default function Mountaintops() {

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.

: <> - {pendingActions.length > 0 &&

{pendingActions.every(action => action.state === 'awaiting confirmation') ? 'Submitted; waiting for confirmation' : 'Check your wallet before continuing'}

Do not send these payments again. Confirmation may take time after submission.

{statusCheckedAt &&

Last checked {new Date(statusCheckedAt).toLocaleTimeString()}.

}{pendingActions.map(action =>
-

{action.state === 'awaiting confirmation' ? walletStatusMessage('unproven') : action.state === 'prepared' ? 'This payment is prepared but has not been submitted.' : walletStatusMessage('unknown')}

-
Payment details

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

)}
} + }, true)} /> {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} {(message || error) &&
{message && !searching &&

{message}

}{error &&

{error}

}
} @@ -283,7 +288,8 @@ export default function Mountaintops() { {primary ? card(primary, true) :

Choose a receiving address

Find a new address or choose an active one below. Earlier payments remain yours.

}

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.filter(x => balances[x.keyID]?.length).map(entry =>
Received{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' : ''}
)} + {paymentHold && session.book.some(x => balances[x.keyID]?.length) &&

{paymentHold}

} {session.book.some(x => balances[x.keyID]?.length) &&

Wallet fees apply when moving coins.

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

No available payments found.

}
@@ -298,7 +304,7 @@ export default function Mountaintops() {
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))}

An address can expire. Your coins are still yours.

- :

Send BSV

Public payment · wallet fees apply

Expired addresses are blocked. Confirm the result in your wallet before retrying.

{txid &&

Submitted: {txid}

}
} + :

Send BSV

Public payment · wallet fees apply

{paymentHold || 'Wallet approval is required. Expired receiving addresses are blocked.'}

{txid && !pendingActions.some(action => action.txid === txid) &&

Submitted: {txid}

}
}
Activity this session {history.length}

Clears when you leave. Your wallet keeps its own payment records.

{!history.length &&

No payments yet.

}{history.map(x =>

{x.description} · {x.status}
{x.txid}

)}
} {!session && error &&

{error}

} diff --git a/frontend/src/PaymentStatus.tsx b/frontend/src/PaymentStatus.tsx new file mode 100644 index 0000000..d92f09a --- /dev/null +++ b/frontend/src/PaymentStatus.tsx @@ -0,0 +1,31 @@ +type Props = { + actions: Record[] + checkedAt: number | null + disabled: boolean + busy: boolean + onReview: (action: Record) => void +} + +export default function PaymentStatus({ actions, checkedAt, disabled, busy, onReview }: Props) { + return actions.map(action => { + const sent = action.state === 'awaiting confirmation' + const prepared = action.state === 'prepared' + return
+
+ +
+

{sent ? 'Payment sent' : prepared ? 'Payment not sent' : 'Check payment status'}

+

{sent ? 'Waiting for confirmation.' : prepared ? 'A prepared payment is waiting in your wallet.' : 'Your wallet has not reported a clear result.'}

+
+ +
+ {!sent &&

{prepared ? 'Cancel it before starting another payment.' : 'Check wallet activity before trying again.'}

} +
+ Payment details + {sent &&

Your payment has been submitted. Do not send the same payment again.

} + {action.txid ?

{String(action.txid)}

:

No transaction ID was returned.

} + {checkedAt &&

Last checked .

} +
+
+ }) +} diff --git a/frontend/src/style.css b/frontend/src/style.css index 19aa588..7128daf 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -2,4 +2,29 @@ .payments-panel{padding:24px 28px;border-top:1px solid #344b55}.payments-panel .section-heading{align-items:center}.payment-row{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-top:18px}.payment-row>div{display:flex;flex-direction:column;gap:4px}.payment-row strong{font-size:1.4rem}.payment-row button{flex-shrink:0}@media(max-width:520px){.payments-panel{padding:22px 18px}.payments-panel .section-heading{flex-direction:row;gap:8px}.payments-panel .section-heading h3{font-size:.9rem}.payments-panel .section-heading button{width:auto;font-size:.8rem}.payment-row{gap:10px}.payment-row button{font-size:.8rem}.payment-row strong{font-size:1.2rem}} +.payment-status{padding:20px 24px;box-shadow:none} +.payment-status.sent{background:#16332df7;border-color:#416e5d} +.payment-status.needs-review{border-color:#b58b59} +.payment-status-heading{display:flex;align-items:center;gap:12px} +.payment-status-mark{display:grid;place-items:center;width:32px;height:32px;flex-shrink:0;border-radius:50%;background:#31454f;color:#d4e5e7;font-size:1.1rem;font-weight:700} +.sent .payment-status-mark{background:#285444;color:#bce9d2} +.needs-review .payment-status-mark{background:#60482c;color:#ffe0b1} +.payment-status-copy{min-width:0;flex:1} +.payment-status h2{font-size:1.05rem;letter-spacing:-.01em;margin:0 0 3px} +.payment-status-copy p{font-size:.82rem;color:#b7d0cb;margin:0;line-height:1.45} +.payment-status-heading button{flex-shrink:0;font-size:.8rem;padding:8px 12px} +.payment-status-guidance{font-size:.82rem;color:#c9d5d7;margin:12px 0 0} +.payment-status-details{font-size:.78rem;color:#aac3bd;margin-top:12px} +.payment-status-details summary{font-weight:400} +.payment-status-details p{font-size:.82rem} +.payment-status-details .transaction{margin-bottom:8px} +.received-label{font-size:.75rem;font-weight:600;color:#b3e2cd} +.payment-hold{margin-bottom:0} +@media(max-width:520px){ + .payment-status{padding:18px} + .payment-status-heading{flex-wrap:wrap;gap:10px} + .payment-status-copy{flex-basis:calc(100% - 42px)} + .payment-status-heading button{margin-left:42px} +} + .lifetime-meta{display:flex;align-items:center;gap:12px;color:#a9c1c8;font-size:.8rem;margin:5px 0 8px}.text-button{background:none;border:0;color:#b8e3d7;text-decoration:underline;text-underline-offset:3px;padding:4px 0;font-size:.8rem;font-weight:500}.text-button:hover:not(:disabled){background:none;color:#fff}.coverage{font-weight:600}.receive-info{width:min(640px,calc(100% - 32px));max-height:85dvh;overflow:auto;background:#142630;color:#edf3f5;border:1px solid #58717b;border-radius:16px;padding:28px;box-shadow:0 24px 90px #0008}.receive-info::backdrop{background:#07141dcc;backdrop-filter:blur(3px)}.modal-heading{display:flex;align-items:flex-start;gap:18px;justify-content:space-between}.modal-heading h2{font-size:1.35rem}.modal-heading button{flex-shrink:0}.receive-info p{font-size:.9rem}.receive-info details{margin:20px 0;font-size:.9rem}.stage-summary{background:#203e46;border-radius:10px;padding:16px;margin:18px 0}.stage-summary p{margin:6px 0}.schedule-scroll{max-height:300px;overflow:auto;border:1px solid #40535a;border-radius:8px;margin:16px 0}table{width:100%;border-collapse:collapse;font-size:.78rem;text-align:left}caption{padding:12px;text-align:left;color:#a9c1c8}th,td{padding:9px;border-bottom:1px solid #344b55}th{background:#203e46;position:sticky;top:0}.receive-info>a{font-size:.9rem}@media(max-width:520px){.receive-info{padding:20px}.modal-heading{gap:10px}.modal-heading h2{font-size:1.1rem}.modal-heading button{padding:8px 10px}.receive-info p{font-size:.85rem}th,td{padding:8px 6px}} diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs index c371119..2abff2a 100644 --- a/frontend/test/browser/payment-status.mjs +++ b/frontend/test/browser/payment-status.mjs @@ -20,18 +20,28 @@ try { unexpected.push(route.request().url()); return route.abort() }) try { - await page.goto(origin + '/test/ui.html?pending=unproven') + await page.goto(origin + '/test/ui.html?pending=unproven&payments') await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() + await page.waitForFunction(() => document.querySelector('main').getAttribute('aria-busy') === 'false') const status = page.getByRole('region', { name: 'Wallet payment status' }) - await status.getByRole('heading', { name: 'Submitted; waiting for confirmation', exact: true }).waitFor() + await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() + await status.getByText('Waiting for confirmation.', { exact: true }).waitFor() + assert.equal(await status.getAttribute('class'), 'payment-status sent') + await page.getByText('Received', { exact: true }).waitFor() + await page.getByText('10,002 sats', { exact: true }).waitFor() + await page.getByText('New transfers are paused until your outgoing payment confirms.', { exact: true }).waitFor() + await status.getByText('Payment details', { exact: true }).click() await status.getByText('Last checked', { exact: false }).waitFor() + await status.getByText('Payment details', { exact: true }).click() + if (evidence) await page.screenshot({ path: path.join(evidence, `received-${width}.png`), fullPage: true }) await page.evaluate(() => window.fixtureBlockRecoveryReads()) for (let i = 0; i < 2; i++) { await status.getByRole('button', { name: 'Refresh payment status' }).click() await status.getByRole('button', { name: 'Refresh payment status' }).waitFor({ state: 'visible' }) await page.waitForFunction(() => !document.querySelector('[aria-label="Wallet payment status"] button').disabled) assert.equal(await page.getByRole('alert').count(), 0, 'status refresh must not access recovery records or chain coverage') - await page.getByText('Submitted; waiting for confirmation. Your wallet has not returned a mined proof yet. Do not send this payment again.', { exact: true }).last().waitFor() + await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() + assert.equal(await page.locator('.feedback').count(), 0, 'a successful status refresh must not add a duplicate notice') } assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') await page.getByRole('button', { name: 'Send', exact: true }).click() @@ -48,13 +58,15 @@ try { // A fresh connection must show an unknown sending outcome differently. await page.goto(origin + '/test/ui.html?pending=sending') await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() - await status.getByRole('heading', { name: 'Check your wallet before continuing', exact: true }).waitFor() + await status.getByRole('heading', { name: 'Check payment status', exact: true }).waitFor() await status.getByRole('button', { name: 'Refresh payment status' }).click() - await page.getByText('The payment outcome is not known.', { exact: false }).last().waitFor() + await status.getByText('Your wallet has not reported a clear result.', { exact: true }).waitFor() + assert.equal(await page.locator('.feedback').count(), 0) + if (evidence) await page.screenshot({ path: path.join(evidence, `unknown-${width}.png`), fullPage: true }) assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') await page.evaluate(() => { window.fixtureSetStatus('completed'); window.fixtureAddConflict() }) await status.getByRole('button', { name: 'Refresh payment status' }).click() - await status.getByText('The payment outcome is not known.', { exact: false }).waitFor() + await status.getByText('Your wallet has not reported a clear result.', { exact: true }).waitFor() assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') // A stale cancel button must not cancel a payment submitted elsewhere. await page.goto(origin + '/test/ui.html?pending=nosend') @@ -62,7 +74,7 @@ try { await status.getByRole('button', { name: 'Cancel unsent payment' }).waitFor() await page.evaluate(() => { window.fixtureBlockRecoveryReads(); window.fixtureSetStatus('unproven') }) await status.getByRole('button', { name: 'Cancel unsent payment' }).click() - await status.getByRole('heading', { name: 'Submitted; waiting for confirmation', exact: true }).waitFor() + await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 0) // A still-unsent preparation retains its normal explicit cancellation. await page.evaluate(() => window.fixtureSetStatus('nosend')) From 65943236541879e78aaa86c0181394a86a4e389a Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Wed, 11 Nov 2026 20:54:25 -0800 Subject: [PATCH 04/13] Keep receiving essentials visible and collapse secondary guidance --- frontend/src/App.tsx | 24 ++++++++++-------------- frontend/src/style.css | 8 ++++++++ frontend/test/browser/payment-status.mjs | 2 +- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index a28f463..597695b 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -225,8 +225,8 @@ export default function Mountaintops() { 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 paymentHold = pendingActions.length ? pendingActions.every(action => action.state === 'awaiting confirmation') - ? 'New transfers are paused until your outgoing payment confirms.' - : 'Check the payment above before starting another transfer.' : '' + ? 'Transfers resume after confirmation.' + : 'Check payment status to continue.' : '' 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()] @@ -239,13 +239,11 @@ export default function Mountaintops() { const longest = Math.max(...session!.book.filter(x => !x.retiredAt).map(x => lastCoveredStage(x.address))) const level = lastCoveredStage(entry.address) const name = selected ? 'Your receiving address' : entry.keyID === '1' ? 'Original address' : 'Saved address' - const expiration = entry.retiredAt ? 'Expired — do not send here' : pendingExpiry ? 'Expiration pending — stop sharing' : entry.network !== 'mainnet' ? 'No testnet expiration schedule' : expirationEstimate(level, calendar) + const expiration = entry.retiredAt ? 'Expired — do not send here' : pendingExpiry ? 'Expiration pending — stop sharing' : entry.network !== 'mainnet' ? 'No testnet expiration schedule' : expirationEstimate(level, calendar).replace(/^Not earlier than /, 'Estimated expiry: ') return

{name}

{entry.retiredAt ? 'Expired' : pendingExpiry ? 'Expiring' : 'Active'}
{entry.address} -

{expiration}

- {entry.network === 'mainnet' &&
{!entry.retiredAt && !pendingExpiry && level < 27 ? 'Estimated · ' : ''}Stage {level}
} - {!entry.retiredAt && !pendingExpiry && entry.network === 'mainnet' && longest > 0 &&

{level === longest ? 'Longest coverage of your saved addresses.' : 'Expires earlier than your longest-lasting saved address.'}

} +

{expiration}

{entry.network === 'mainnet' && }
{entry.retiredAt &&

Receiving is disabled. You can still move earlier payments to your wallet.

} {pendingExpiry &&

Stop sharing this address. The chain-time notice ends {new Date(pending.deadline * 1000).toISOString().replace('.000Z', ' UTC')}; expiration begins in the following accepted block.

}
@@ -254,7 +252,7 @@ export default function Mountaintops() {
{!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.
{paymentHold &&

{paymentHold}

}}} -
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.

}
+
Address details

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

{!entry.retiredAt && !pendingExpiry && entry.network === 'mainnet' && longest > 0 &&

{level === longest ? 'Longest coverage of your saved addresses.' : 'Expires earlier than your longest-lasting saved address.'}

}{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.

}
} @@ -286,14 +284,13 @@ export default function Mountaintops() { {(message || error) &&
{message && !searching &&

{message}

}{error &&

{error}

}
} {view === 'receive' ?
{primary ? card(primary, true) :

Choose a receiving address

Find a new address or choose an active one below. Earlier payments remain yours.

} -

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 =>
Received{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' : ''}
)} +

Your payments

+ {checkedCount > 0 && !allPaymentsChecked ?

{checkedCount} of {session.book.length} addresses checked for new payments.

: session.book.some(x => balances[x.keyID] === undefined) &&

Some payments still need checking.

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

{paymentHold}

} - {session.book.some(x => balances[x.keyID]?.length) &&

Wallet fees apply when moving coins.

} {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 ? 'Use a longer-lasting address' : 'Find a longer-lasting address'}

{suggestedEntry ? 'Already saved. Free to switch.' : 'Searching is free. Saving an address has wallet fees.'}

{searching ? : }
{suggestedEntry &&

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

Estimated · stage {lastCoveredStage(suggestedEntry.address)}
} {searching &&

{message}

} {candidate &&

New address found

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

Estimated · Stage {lastCoveredStage(candidate.address)}

Save once to recover this address on any device.

Wallet fees apply to save. Switching saved addresses is free.
} @@ -301,9 +298,8 @@ export default function Mountaintops() { {pausedSearch && <>

Wallet fees apply. Otherwise you can repeat this search on another device for free.

} {!searching && savedSearches.map(search =>

Saved in your wallet · next key ID {String(search.next)}

)}
-
+
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))}
-

An address can expire. Your coins are still yours.

:

Send BSV

Public payment · wallet fees apply

{paymentHold || 'Wallet approval is required. Expired receiving addresses are blocked.'}

{txid && !pendingActions.some(action => action.txid === txid) &&

Submitted: {txid}

}
}
Activity this session {history.length}

Clears when you leave. Your wallet keeps its own payment records.

{!history.length &&

No payments yet.

}{history.map(x =>

{x.description} · {x.status}
{x.txid}

)}
} diff --git a/frontend/src/style.css b/frontend/src/style.css index 7128daf..1430c61 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -20,11 +20,19 @@ .payment-status-details .transaction{margin-bottom:8px} .received-label{font-size:.75rem;font-weight:600;color:#b3e2cd} .payment-hold{margin-bottom:0} +.expiry-summary{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:12px 0} +.expiry-summary p{margin:0} +.payment-row>.payment-actions{align-items:flex-end;gap:6px} +.payment-actions .small{font-size:.73rem} +.address-search{border-top:1px solid #344b55} +.address-search>summary{padding:22px 28px;color:#c6d8dd;font-size:.88rem} +.address-search>.mining{border-top:0;padding-top:0} @media(max-width:520px){ .payment-status{padding:18px} .payment-status-heading{flex-wrap:wrap;gap:10px} .payment-status-copy{flex-basis:calc(100% - 42px)} .payment-status-heading button{margin-left:42px} + .address-search>summary{padding:20px 18px} } .lifetime-meta{display:flex;align-items:center;gap:12px;color:#a9c1c8;font-size:.8rem;margin:5px 0 8px}.text-button{background:none;border:0;color:#b8e3d7;text-decoration:underline;text-underline-offset:3px;padding:4px 0;font-size:.8rem;font-weight:500}.text-button:hover:not(:disabled){background:none;color:#fff}.coverage{font-weight:600}.receive-info{width:min(640px,calc(100% - 32px));max-height:85dvh;overflow:auto;background:#142630;color:#edf3f5;border:1px solid #58717b;border-radius:16px;padding:28px;box-shadow:0 24px 90px #0008}.receive-info::backdrop{background:#07141dcc;backdrop-filter:blur(3px)}.modal-heading{display:flex;align-items:flex-start;gap:18px;justify-content:space-between}.modal-heading h2{font-size:1.35rem}.modal-heading button{flex-shrink:0}.receive-info p{font-size:.9rem}.receive-info details{margin:20px 0;font-size:.9rem}.stage-summary{background:#203e46;border-radius:10px;padding:16px;margin:18px 0}.stage-summary p{margin:6px 0}.schedule-scroll{max-height:300px;overflow:auto;border:1px solid #40535a;border-radius:8px;margin:16px 0}table{width:100%;border-collapse:collapse;font-size:.78rem;text-align:left}caption{padding:12px;text-align:left;color:#a9c1c8}th,td{padding:9px;border-bottom:1px solid #344b55}th{background:#203e46;position:sticky;top:0}.receive-info>a{font-size:.9rem}@media(max-width:520px){.receive-info{padding:20px}.modal-heading{gap:10px}.modal-heading h2{font-size:1.1rem}.modal-heading button{padding:8px 10px}.receive-info p{font-size:.85rem}th,td{padding:8px 6px}} diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs index 2abff2a..6f71ef8 100644 --- a/frontend/test/browser/payment-status.mjs +++ b/frontend/test/browser/payment-status.mjs @@ -29,7 +29,7 @@ try { assert.equal(await status.getAttribute('class'), 'payment-status sent') await page.getByText('Received', { exact: true }).waitFor() await page.getByText('10,002 sats', { exact: true }).waitFor() - await page.getByText('New transfers are paused until your outgoing payment confirms.', { exact: true }).waitFor() + await page.getByText('Transfers resume after confirmation.', { exact: true }).waitFor() await status.getByText('Payment details', { exact: true }).click() await status.getByText('Last checked', { exact: false }).waitFor() await status.getByText('Payment details', { exact: true }).click() From 58ff6408911a5c0af9c90b719d6b5102f86d011f Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 08:16:54 -0800 Subject: [PATCH 05/13] Allow native wallet reads of local permission manifests --- frontend/test/localManifest.test.mjs | 21 +++++++++++++++++++++ frontend/vite.config.ts | 8 ++++++++ 2 files changed, 29 insertions(+) create mode 100644 frontend/test/localManifest.test.mjs diff --git a/frontend/test/localManifest.test.mjs b/frontend/test/localManifest.test.mjs new file mode 100644 index 0000000..2be19b9 --- /dev/null +++ b/frontend/test/localManifest.test.mjs @@ -0,0 +1,21 @@ +import assert from 'node:assert/strict' +import { fileURLToPath } from 'node:url' +import test from 'node:test' +import { createServer } from 'vite' + +test('native wallet origin can read the complete local manifest without opening CORS to unrelated sites', async () => { + const server = await createServer({ root: fileURLToPath(new URL('..', import.meta.url)), server: { host: '127.0.0.1', port: 0 } }) + await server.listen() + try { + const url = `http://127.0.0.1:${server.httpServer.address().port}/manifest.json` + const response = await fetch(url, { headers: { Origin: 'tauri://localhost' } }) + assert.equal(response.status, 200) + assert.equal(response.headers.get('access-control-allow-origin'), 'tauri://localhost') + const manifest = await response.json() + assert.equal(manifest.metanet.schemaVersion, 1) + assert.equal(manifest.metanet.groupPermissions.protocolPermissions.length, 6) + assert.equal(manifest.metanet.groupPermissions.basketAccess.length, 2) + const unrelated = await fetch(url, { headers: { Origin: 'https://unrelated.example' } }) + assert.equal(unrelated.headers.get('access-control-allow-origin'), null) + } finally { await server.close() } +}) diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 913f14b..88b4abd 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -1,9 +1,17 @@ import { defineConfig } from 'vite' import react from '@vitejs/plugin-react' +// The native wallet fetches a localhost app's public permission manifest from +// its webview. Keep loopback development origins and allow that exact origin. +const localWalletCors = { + origin: ['tauri://localhost', /^https?:\/\/(?:(?:[^:]+\.)?localhost|127\.0\.0\.1|\[::1\])(?::\d+)?$/] +} + // https://vite.dev/config/ export default defineConfig({ plugins: [react()], + server: { cors: localWalletCors }, + preview: { cors: localWalletCors }, build: { outDir: 'build' } From ec483a78d693b62e68ce29693ec7078b67736cd7 Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:06:42 -0800 Subject: [PATCH 06/13] Finish payments on wallet acceptance with clear review and receipts --- frontend/src/App.tsx | 91 +++++++++--- frontend/src/PaymentReceipt.tsx | 17 +++ frontend/src/PaymentReview.tsx | 17 +++ frontend/src/PaymentStatus.tsx | 16 +- frontend/src/actions.ts | 27 ++-- frontend/src/paymentAmount.ts | 23 +++ frontend/src/style.css | 25 +++- frontend/src/walletActionState.ts | 44 +++--- frontend/test/actions.test.mjs | 71 ++++++++- frontend/test/browser/payment-status.mjs | 177 +++++++++++++++-------- frontend/test/fixtureWallet.mjs | 2 + frontend/test/paymentAmount.test.mjs | 17 +++ frontend/test/paymentStatus.test.mjs | 105 ++++++-------- frontend/test/permissions.test.mjs | 14 +- frontend/test/ui.html | 22 ++- 15 files changed, 468 insertions(+), 200 deletions(-) create mode 100644 frontend/src/PaymentReceipt.tsx create mode 100644 frontend/src/PaymentReview.tsx create mode 100644 frontend/src/paymentAmount.ts create mode 100644 frontend/test/paymentAmount.test.mjs diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 597695b..09882f6 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,20 +2,23 @@ import { useEffect, useRef, useState } from 'react' import { PublicKey, WalletClient } from '@bsv/sdk' import { addressMatches, assertReceivable, coverageLabel, lastCoveredStage, stages, type AddressRecord, type Network } from '../../shared/brc234.ts' import { WalletRecords, type RecoveryRecord } from './walletRecords.ts' -import { applyExpirations, bookFromRecords } from './addressBook.ts' +import { applyExpirations, bookFromRecords, validateAddress } from './addressBook.ts' import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' import ReceiveInfo from './ReceiveInfo.tsx' import PaymentStatus from './PaymentStatus.tsx' +import PaymentReceipt, { type PaymentReceiptData } from './PaymentReceipt.tsx' +import PaymentReview, { type PaymentDraft } from './PaymentReview.tsx' +import { bsvAmount, parseAmount, type AmountUnit } from './paymentAmount.ts' import { readCoverage, type Coverage } from './coverageClient.ts' import { availableRetainedCoins, refreshCoins, type Coin } from './coins.ts' -import { importCoins, sendCoins } from './actions.ts' +import { importCoins, sendCoins, PaymentOutcomeUnknownError } from './actions.ts' import { preferCompatibleTransport } from './walletClient.ts' import { paymentActionRecords, refreshPaymentStatus, WalletAccountChangedError, walletStatusMessage } from './walletActionState.ts' import './style.css' const client = new WalletClient('auto') type Session = { identity: string; network: Network; store: WalletRecords; book: AddressRecord[]; records: RecoveryRecord[]; coverage: Coverage; primary: string | null; receivingBlocked: string | null } -const money = (satoshis: number) => `${Math.floor(satoshis / 100_000_000)}.${String(satoshis % 100_000_000).padStart(8, '0')} BSV` +const money = (satoshis: number) => `${bsvAmount(satoshis)} BSV` function unresolvedActions(records: RecoveryRecord[]) { const actions = new Map>() @@ -37,8 +40,10 @@ export default function Mountaintops() { const [pausedSearch, setPausedSearch] = useState<{ stage: number; next: string } | null>(null) const [recipient, setRecipient] = useState('') const [amount, setAmount] = useState('') - const [txid, setTxid] = useState('') - const [history, setHistory] = useState<{ txid: string; description: string; status: string }[]>([]) + const [unit, setUnit] = useState('sats') + const [review, setReview] = useState(null) + const [receipt, setReceipt] = useState(null) + const [history, setHistory] = useState([]) const [searching, setSearching] = useState(false) const [info, setInfo] = useState<{ stage: number; expired: boolean } | null>(null) const worker = useRef(null) @@ -57,7 +62,7 @@ export default function Mountaintops() { } const clearWalletSession = () => { - setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') + setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setReceipt(null); setReview(null); setRecipient(''); setAmount('') } const reload = async (previous: Session | null = current.current): Promise => { @@ -66,7 +71,7 @@ export default function Mountaintops() { const { publicKey: identity } = await client.getPublicKey({ identityKey: true }) if (previous && (previous.identity !== identity || previous.network !== network)) { clearWalletSession() - throw new Error('Wallet account or network changed. Connect again to load its own records.') + throw new WalletAccountChangedError() } const store = previous?.store ?? new WalletRecords(client, identity, network) let records = await store.load() @@ -195,28 +200,49 @@ export default function Mountaintops() { } await reload(fresh); setMessage('Payments checked.') }) + const finishPayment = async (fresh: Session, task: () => Promise, details: Omit, onAccepted: () => void) => { + let submitted: string + try { submitted = await task() } catch (error) { + if (!(error instanceof PaymentOutcomeUnknownError)) throw error + const guard: RecoveryRecord = { v: 1, kind: 'action', clock: 0, network: fresh.network, data: { id: error.txid, txid: error.txid, state: 'needs wallet review', reference: null } } + setSession(previous => previous && previous.identity === fresh.identity && previous.network === fresh.network ? { ...previous, records: [...previous.records.filter(record => record.kind !== 'action' || record.data.txid !== error.txid), guard] } : previous) + setReceipt(null); setReview(null); setRecipient(''); setAmount(''); setError(''); setMessage('') + return + } + const payment = { ...details, txid: submitted } + setReceipt(payment); setHistory(items => [payment, ...items]); setReview(null); setRecipient(''); setAmount(''); setMessage('') + onAccepted() + // The wallet acknowledged this transaction. Do not turn a later chain or + // metadata read into a payment failure, or wait for the wallet's mined proof. + } + const importMoney = (keyID: string) => void run(async () => { const fresh = await reload() if (unresolvedActions(fresh.records).length) throw new Error('Review the unfinished wallet action before another payment.') 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 })) - const next = await reload(fresh) - setMessage(unresolvedActions(next.records).length ? '' : 'Transfer submitted.') + await finishPayment(fresh, () => importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage), { kind: 'move' }, () => { + setBalances(values => ({ ...values, [keyID]: (values[keyID] ?? []).filter(coin => !coins.some(spent => spent.txid === coin.txid && spent.vout === coin.vout)) })) + }) }) + const reviewPayment = () => { + if (!session || disabled || unresolvedActions(session.records).length) return + try { + const destination = recipient.trim() + validateAddress(destination, session.network) + const satoshis = parseAmount(amount, unit) + setReview({ recipient: destination, satoshis }); setReceipt(null); setError(''); setMessage('') + } catch (error) { setError(error instanceof Error ? error.message : 'Check the recipient and amount.'); setMessage('') } + } const send = () => void run(async () => { + if (!review) throw new Error('Review the recipient and amount before sending.') + const intent = review const fresh = await reload() if (unresolvedActions(fresh.records).length) throw new Error('Review the unfinished wallet action before another payment.') if (fresh.receivingBlocked) throw new Error(fresh.receivingBlocked) - const own = fresh.book.find(x => x.address === recipient) + const own = fresh.book.find(x => x.address === intent.recipient) if (own) assertReceivable(own, fresh.coverage.stage) - const submitted = await sendCoins(client, fresh.store, recipient, amount, fresh.coverage, setMessage) - setTxid(submitted); setHistory(x => [{ txid: submitted, description: `Send ${amount} BSV`, status: 'Submitted' }, ...x]) - setRecipient(''); setAmount('') - const next = await reload(fresh) - setMessage(unresolvedActions(next.records).length ? '' : 'Payment sent.') + await finishPayment(fresh, () => sendCoins(client, fresh.store, intent.recipient, bsvAmount(intent.satoshis), fresh.coverage, setMessage), { ...intent, kind: 'send' }, () => {}) }) const disabled = busy || searching @@ -224,9 +250,7 @@ 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 paymentHold = pendingActions.length ? pendingActions.every(action => action.state === 'awaiting confirmation') - ? 'Transfers resume after confirmation.' - : 'Check payment status to continue.' : '' + const paymentHold = pendingActions.length ? 'Check your wallet to continue.' : '' 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()] @@ -273,12 +297,16 @@ export default function Mountaintops() { result = await refreshPaymentStatus(client, session.identity, session.network, result.records, action) } setSession({ ...session, records: result.records }); setStatusCheckedAt(Date.now()) - setMessage(canceled ? 'Unsent payment canceled.' : unresolvedActions(result.records).length ? '' : walletStatusMessage(result.status)) + if (!canceled && result.status === 'accepted' && typeof action.txid === 'string') { + setReceipt({ txid: action.txid, kind: 'recovered' }); setReview(null) + } + setMessage(canceled ? 'Unsent payment canceled.' : unresolvedActions(result.records).length || result.status === 'accepted' ? '' : walletStatusMessage(result.status)) } catch (error) { if (error instanceof WalletAccountChangedError) clearWalletSession() throw error } }, true)} /> + {receipt && { setReceipt(null); setView('receive') }} onAnother={() => { setReceipt(null); setReview(null); setView('send') }} />} {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} {(message || error) &&
{message && !searching &&

{message}

}{error &&

{error}

}
} @@ -300,8 +328,23 @@ export default function Mountaintops() {
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))}
- :

Send BSV

Public payment · wallet fees apply

{paymentHold || 'Wallet approval is required. Expired receiving addresses are blocked.'}

{txid && !pendingActions.some(action => action.txid === txid) &&

Submitted: {txid}

}
} -
Activity this session {history.length}

Clears when you leave. Your wallet keeps its own payment records.

{!history.length &&

No payments yet.

}{history.map(x =>

{x.description} · {x.status}
{x.txid}

)}
+ : receipt ? null : review ? 0} onBack={() => setReview(null)} onSend={send} /> :
+

Send BSV

+
{ event.preventDefault(); reviewPayment() }}> + + +
setAmount(e.target.value)} placeholder="0" inputMode={unit === 'sats' ? 'numeric' : 'decimal'} maxLength={32} />
+ + {paymentHold &&

{paymentHold}

} +
+
} + {history.length > 0 &&
Recent activity {history.length}

This session only. Your wallet keeps the payment records.

{history.map(payment =>
{payment.kind === 'move' ? 'Moved to wallet' : 'Sent'}{payment.satoshis !== undefined ? ` · ${payment.satoshis.toLocaleString()} sats` : ''}{payment.recipient &&

To {payment.recipient}

}

{payment.txid}

)}
} } {!session && error &&

{error}

}
Expiration, fees & recovery

When does my address expire?

Each address shows a month-and-year estimate and the stage it meets. Choose More info for the schedule. Before block 1,000,000 arrives, estimates can move earlier or later. Low transaction volume can delay expiration.

When an address expires, stop using it everywhere. Mountaintops disables receiving and stops looking for new deposits. Earlier coins remain yours and can still be moved to your wallet.

Can I recover on another device?

Connect the same BRC-100 wallet account. Your saved addresses and coin evidence come from the wallet, without browser data or files from this device. Keep your wallet account and its recovery service available.

What costs money?

Searching and pausing are free. Saving a new address also makes it your receiving address in one encrypted 1-satoshi wallet record. Switching saved addresses is free for this session; reconnecting opens the longest-lasting eligible saved address. Saving search progress also needs a wallet record. Network and wallet service fees may apply to records. Moving or sending coins also incurs wallet fees.

Does a longer-lasting address cover every payment?

No. Funding TXID rules also apply, and from stage 13 the transaction must use version 1. Mountaintops prepares eligible transactions within a bounded work budget. External senders may create payments outside those rules. Eligibility never changes who owns the coins.

Technical status{session &&

{session.network} · checked through block {session.coverage.height.toLocaleString()} · stage {session.coverage.stage}

}

Client-only. Encrypted PushDrop recovery records use your BRC-100 wallet’s baskets. WhatsOnChain supplies chain data and historical recovery; unavailable or incomplete data cannot establish a balance.

diff --git a/frontend/src/PaymentReceipt.tsx b/frontend/src/PaymentReceipt.tsx new file mode 100644 index 0000000..bf1f849 --- /dev/null +++ b/frontend/src/PaymentReceipt.tsx @@ -0,0 +1,17 @@ +import { useEffect, useRef } from 'react' +import { bsvAmount } from './paymentAmount.ts' + +export type PaymentReceiptData = { txid: string; kind: 'send' | 'move' | 'recovered'; satoshis?: number; recipient?: string } + +export default function PaymentReceipt({ payment, onDone, onAnother }: { payment: PaymentReceiptData; onDone: () => void; onAnother: () => void }) { + const heading = useRef(null) + useEffect(() => { heading.current?.focus() }, [payment.txid]) + return
+ +

{payment.kind === 'move' ? 'Moved to your wallet' : payment.kind === 'send' ? 'Payment sent' : 'Payment accepted'}

+

{payment.satoshis !== undefined ? <>{payment.satoshis.toLocaleString()} sats : 'All done'}

+ {payment.recipient &&
To{payment.recipient}
} +
{payment.kind === 'send' && }
+
Transaction details{payment.satoshis !== undefined &&

{bsvAmount(payment.satoshis)} BSV to the recipient. Wallet fees are additional.

}

{payment.txid}

+
+} diff --git a/frontend/src/PaymentReview.tsx b/frontend/src/PaymentReview.tsx new file mode 100644 index 0000000..8fc7647 --- /dev/null +++ b/frontend/src/PaymentReview.tsx @@ -0,0 +1,17 @@ +import { useEffect, useRef } from 'react' +import { bsvAmount } from './paymentAmount.ts' + +export type PaymentDraft = { recipient: string; satoshis: number } + +export default function PaymentReview({ payment, busy, onBack, onSend }: { payment: PaymentDraft; busy: boolean; onBack: () => void; onSend: () => void }) { + const heading = useRef(null) + useEffect(() => { heading.current?.focus() }, []) + return
+

Review payment

+

{payment.satoshis.toLocaleString()} sats

+

{bsvAmount(payment.satoshis)} BSV

+
To{payment.recipient}
+

Wallet and network fees are additional.

+
+
+} diff --git a/frontend/src/PaymentStatus.tsx b/frontend/src/PaymentStatus.tsx index d92f09a..37133e0 100644 --- a/frontend/src/PaymentStatus.tsx +++ b/frontend/src/PaymentStatus.tsx @@ -8,21 +8,19 @@ type Props = { export default function PaymentStatus({ actions, checkedAt, disabled, busy, onReview }: Props) { return actions.map(action => { - const sent = action.state === 'awaiting confirmation' const prepared = action.state === 'prepared' - return
+ return
- +
-

{sent ? 'Payment sent' : prepared ? 'Payment not sent' : 'Check payment status'}

-

{sent ? 'Waiting for confirmation.' : prepared ? 'A prepared payment is waiting in your wallet.' : 'Your wallet has not reported a clear result.'}

+

{prepared ? 'Unfinished payment' : 'Check your wallet'}

+

{prepared ? 'This payment has not been sent.' : 'Your wallet has not reported a clear result.'}

- +
- {!sent &&

{prepared ? 'Cancel it before starting another payment.' : 'Check wallet activity before trying again.'}

} +

{prepared ? 'Cancel it to start a new payment.' : 'Check this attempt before sending the same payment again.'}

- Payment details - {sent &&

Your payment has been submitted. Do not send the same payment again.

} + Details {action.txid ?

{String(action.txid)}

:

No transaction ID was returned.

} {checkedAt &&

Last checked .

}
diff --git a/frontend/src/actions.ts b/frontend/src/actions.ts index 3234ea9..03cdd78 100644 --- a/frontend/src/actions.ts +++ b/frontend/src/actions.ts @@ -8,14 +8,16 @@ import type { WalletRecords } from './walletRecords.ts' import { assertInputsUnspent } from './inputChecks.ts' import { unfinishedWalletActions } from './walletActionState.ts' import { ACTION_LABEL } from './walletScopes.ts' +import { parseSatoshis } from './paymentAmount.ts' export { unfinishedWalletActions } from './walletActionState.ts' +export { parseSatoshis } from './paymentAmount.ts' -export function parseSatoshis(bsv: string): number { - if (!/^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$/.test(bsv)) throw new Error('Enter a positive BSV amount with at most 8 decimal places.') - const [whole, fraction = ''] = bsv.split('.') - const satoshis = BigInt(whole) * 100_000_000n + BigInt(fraction.padEnd(8, '0')) - if (satoshis <= 0n || satoshis > 2_100_000_000_000_000n) throw new Error('Amount is outside the valid BSV range.') - return Number(satoshis) +export class PaymentOutcomeUnknownError extends Error { + readonly txid: string + constructor(txid: string) { + super('Check your wallet before sending this payment again.') + this.txid = txid + } } type Progress = (message: string) => void @@ -43,7 +45,7 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor const started = performance.now() let nonce = 0 while (performance.now() - started < 30_000) { - progress(`Preparing an eligible transaction (attempt ${nonce + 1}). Your wallet may request permission; payment fees apply to the submitted payment.`) + progress('Preparing your payment…') // A two-step action is unsigned until signAction. Request ordinary // preparation here: noSend preparation can trigger wallet batch funding // that adds migration inputs even when an import already covers its fees. @@ -56,7 +58,7 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor for (const output of args.outputs ?? []) { if (tx.outputs.filter(x => x.lockingScript.toHex() === output.lockingScript && BigInt(x.satoshis ?? -1) === BigInt(output.satoshis)).length !== 1) throw new Error('Wallet did not preserve the requested recipient and amount') } - progress('Checking the wallet’s coins before signing…') + progress('Checking your payment…') await assertInputsUnspent(tx, store.network) const spends: SignActionArgs['spends'] = {} for (const coin of coins) { @@ -66,6 +68,7 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor const script = await new Importer().unlock(wallet, coin.keyID).sign(tx, index) spends[index] = { unlockingScript: script.toHex() } } + progress('Finishing with your wallet…') const signed = await wallet.signAction({ reference, spends, options: { noSend: true, returnTXIDOnly: false } }) if (!signed.tx || !signed.txid) throw new Error('Wallet omitted signed transaction evidence') const final = Transaction.fromAtomicBEEF(signed.tx) @@ -97,12 +100,12 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor if (fresh.state?.pending && !addressMatches(recipient, fresh.state.pending.target)) throw new Error('This address expires at the pending transition. Use a longer-coverage destination.') } // Permission dialogs and concurrent apps can change the spend state. - progress('Checking the wallet’s coins before submission…') + progress('Sending payment…') await assertInputsUnspent(final, store.network) submissionStarted = true const result = await wallet.createAction({ description: 'Submit eligible Mountaintops payment', options: { sendWith: [signedTxid], acceptDelayedBroadcast: false, returnTXIDOnly: false } }) - const status = result.sendWithResults?.find(x => x.txid === signedTxid)?.status - if (!status || status === 'failed') throw new Error('Wallet reported a submission failure; inspect its transaction status before another payment.') + const acknowledgments = result.sendWithResults?.filter(item => item.txid === signedTxid) ?? [] + if (acknowledgments.length !== 1 || !['sending', 'unproven'].includes(acknowledgments[0].status)) throw new Error('Wallet did not acknowledge acceptance of this exact payment.') return signedTxid } throw new Error('No eligible transaction found within the 30-second work budget. Nothing was submitted.') @@ -115,7 +118,7 @@ export async function eligibleAction(wallet: WalletInterface, store: WalletRecor throw new Error('Wallet action cleanup is unresolved. Open the wallet transaction history before preparing another payment.') } } - if (submissionStarted) throw new Error(`Submission outcome is uncertain${signedTxid ? ` for ${signedTxid}` : ''}. The wallet may retry automatically. Do not send again; check wallet history.`) + if (submissionStarted) throw new PaymentOutcomeUnknownError(signedTxid!) throw error } } diff --git a/frontend/src/paymentAmount.ts b/frontend/src/paymentAmount.ts new file mode 100644 index 0000000..3b19fea --- /dev/null +++ b/frontend/src/paymentAmount.ts @@ -0,0 +1,23 @@ +export type AmountUnit = 'sats' | 'BSV' +const MAX_SATOSHIS = 2_100_000_000_000_000n + +export function parseSatoshis(bsv: string): number { + if (!/^(0|[1-9][0-9]*)(\.[0-9]{1,8})?$/.test(bsv)) throw new Error('Enter a positive BSV amount with at most 8 decimal places.') + const [whole, fraction = ''] = bsv.split('.') + const satoshis = BigInt(whole) * 100_000_000n + BigInt(fraction.padEnd(8, '0')) + if (satoshis <= 0n || satoshis > MAX_SATOSHIS) throw new Error('Amount is outside the valid BSV range.') + return Number(satoshis) +} + +export function parseAmount(value: string, unit: AmountUnit): number { + if (unit === 'BSV') return parseSatoshis(value) + if (!/^[1-9][0-9]*$/.test(value)) throw new Error('Enter a whole number of satoshis greater than zero.') + const amount = BigInt(value) + if (amount > MAX_SATOSHIS) throw new Error('Amount is outside the valid BSV range.') + return Number(amount) +} + +export function bsvAmount(satoshis: number): string { + if (!Number.isSafeInteger(satoshis) || satoshis < 0 || BigInt(satoshis) > MAX_SATOSHIS) throw new Error('Invalid satoshi amount.') + return `${Math.floor(satoshis / 100_000_000)}.${String(satoshis % 100_000_000).padStart(8, '0')}` +} diff --git a/frontend/src/style.css b/frontend/src/style.css index 1430c61..2406f86 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -3,11 +3,9 @@ .payments-panel{padding:24px 28px;border-top:1px solid #344b55}.payments-panel .section-heading{align-items:center}.payment-row{display:flex;align-items:center;justify-content:space-between;gap:16px;margin-top:18px}.payment-row>div{display:flex;flex-direction:column;gap:4px}.payment-row strong{font-size:1.4rem}.payment-row button{flex-shrink:0}@media(max-width:520px){.payments-panel{padding:22px 18px}.payments-panel .section-heading{flex-direction:row;gap:8px}.payments-panel .section-heading h3{font-size:.9rem}.payments-panel .section-heading button{width:auto;font-size:.8rem}.payment-row{gap:10px}.payment-row button{font-size:.8rem}.payment-row strong{font-size:1.2rem}} .payment-status{padding:20px 24px;box-shadow:none} -.payment-status.sent{background:#16332df7;border-color:#416e5d} .payment-status.needs-review{border-color:#b58b59} .payment-status-heading{display:flex;align-items:center;gap:12px} .payment-status-mark{display:grid;place-items:center;width:32px;height:32px;flex-shrink:0;border-radius:50%;background:#31454f;color:#d4e5e7;font-size:1.1rem;font-weight:700} -.sent .payment-status-mark{background:#285444;color:#bce9d2} .needs-review .payment-status-mark{background:#60482c;color:#ffe0b1} .payment-status-copy{min-width:0;flex:1} .payment-status h2{font-size:1.05rem;letter-spacing:-.01em;margin:0 0 3px} @@ -27,12 +25,35 @@ .address-search{border-top:1px solid #344b55} .address-search>summary{padding:22px 28px;color:#c6d8dd;font-size:.88rem} .address-search>.mining{border-top:0;padding-top:0} +.eyebrow{font-size:.82rem;font-weight:600;color:#b4d7cd;letter-spacing:.02em;margin:0 0 12px} +.payment-receipt{text-align:center;border-color:#416e5d;background:linear-gradient(160deg,#193b33,#142b32);padding:36px 28px} +.receipt-mark{display:grid;place-items:center;width:52px;height:52px;margin:0 auto 18px;background:#2a5947;border-radius:50%;color:#c4f0dc;font-size:1.7rem} +.payment-receipt h2,.send-review h2{font-size:2.6rem;letter-spacing:-.045em;margin:0} +.payment-receipt h2 span,.send-review h2 span{font-size:1.15rem;color:#b5cbc7;font-weight:500;letter-spacing:0} +.receipt-recipient,.review-recipient{display:flex;flex-direction:column;gap:8px;margin:24px 0} +.receipt-recipient code,.review-recipient code{font-size:.88rem;overflow-wrap:anywhere;line-height:1.6} +.receipt-actions,.review-actions{display:flex;gap:10px;margin-top:28px} +.receipt-actions{justify-content:center} +.receipt-actions button{min-width:125px} +.payment-receipt .technical{text-align:left;border-top:1px solid #35554e;padding-top:18px;margin-top:28px} +.review-recipient{border-top:1px solid #344b55;padding-top:22px} +.review-actions .accent{flex:1} +.review-fees{margin-top:24px} +.amount-entry{display:flex;gap:10px;margin:-12px 0 24px} +.amount-entry input{min-width:0;font-size:1.45rem;letter-spacing:-.025em} +.amount-entry select{width:100px;flex-shrink:0} +.send-panel form>button{width:100%} +.activity-payment{margin-top:14px;padding-top:14px;border-top:1px solid #344b55} @media(max-width:520px){ .payment-status{padding:18px} .payment-status-heading{flex-wrap:wrap;gap:10px} .payment-status-copy{flex-basis:calc(100% - 42px)} .payment-status-heading button{margin-left:42px} .address-search>summary{padding:20px 18px} + .payment-receipt{padding:28px 20px} + .payment-receipt h2,.send-review h2{font-size:2.2rem} + .receipt-actions{flex-wrap:wrap} + .receipt-actions button{flex:1;min-width:100px} } .lifetime-meta{display:flex;align-items:center;gap:12px;color:#a9c1c8;font-size:.8rem;margin:5px 0 8px}.text-button{background:none;border:0;color:#b8e3d7;text-decoration:underline;text-underline-offset:3px;padding:4px 0;font-size:.8rem;font-weight:500}.text-button:hover:not(:disabled){background:none;color:#fff}.coverage{font-weight:600}.receive-info{width:min(640px,calc(100% - 32px));max-height:85dvh;overflow:auto;background:#142630;color:#edf3f5;border:1px solid #58717b;border-radius:16px;padding:28px;box-shadow:0 24px 90px #0008}.receive-info::backdrop{background:#07141dcc;backdrop-filter:blur(3px)}.modal-heading{display:flex;align-items:flex-start;gap:18px;justify-content:space-between}.modal-heading h2{font-size:1.35rem}.modal-heading button{flex-shrink:0}.receive-info p{font-size:.9rem}.receive-info details{margin:20px 0;font-size:.9rem}.stage-summary{background:#203e46;border-radius:10px;padding:16px;margin:18px 0}.stage-summary p{margin:6px 0}.schedule-scroll{max-height:300px;overflow:auto;border:1px solid #40535a;border-radius:8px;margin:16px 0}table{width:100%;border-collapse:collapse;font-size:.78rem;text-align:left}caption{padding:12px;text-align:left;color:#a9c1c8}th,td{padding:9px;border-bottom:1px solid #344b55}th{background:#203e46;position:sticky;top:0}.receive-info>a{font-size:.9rem}@media(max-width:520px){.receive-info{padding:20px}.modal-heading{gap:10px}.modal-heading h2{font-size:1.1rem}.modal-heading button{padding:8px 10px}.receive-info p{font-size:.85rem}th,td{padding:8px 6px}} diff --git a/frontend/src/walletActionState.ts b/frontend/src/walletActionState.ts index ac51e70..416a597 100644 --- a/frontend/src/walletActionState.ts +++ b/frontend/src/walletActionState.ts @@ -1,6 +1,11 @@ import type { WalletAction, WalletInterface } from '@bsv/sdk' import type { RecoveryRecord, WalletRecords } from './walletRecords.ts' -import { ACTION_LABEL, RECORD_LABEL } from './walletScopes.ts' +import { ACTION_LABEL } from './walletScopes.ts' + +// These states acknowledge that the wallet owns the transaction lifecycle. +// Mining, proof collection and broadcast retries belong to that wallet. +const acceptedStatuses = new Set(['sending', 'unproven', 'completed']) +export type PaymentOutcome = 'accepted' | 'failed' | 'unknown' async function walletActions(wallet: WalletInterface) { const actions = [] @@ -18,28 +23,30 @@ function matches(action: Record, row: WalletAction): boolean { : typeof action.id === 'string' && Boolean(row.labels?.includes(`mountaintops request ${action.id}`)) } -function statusFromActions(actions: WalletAction[], action: Record): 'completed' | 'failed' | 'unproven' | 'unknown' { - const matching = actions.filter(row => matches(action, row)) - const statuses = new Set(matching.map(row => row.status)) - if (statuses.size !== 1) return 'unknown' - const status = matching[0]?.status - return status === 'completed' || status === 'failed' || status === 'unproven' ? status : 'unknown' +function outcomeFromRows(rows: WalletAction[]): PaymentOutcome { + if (!rows.length) return 'unknown' + if (rows.every(row => acceptedStatuses.has(row.status))) return 'accepted' + if (rows.every(row => row.status === 'failed')) return 'failed' + return 'unknown' +} + +function statusFromActions(actions: WalletAction[], action: Record): PaymentOutcome { + return outcomeFromRows(actions.filter(row => matches(action, row))) } -export async function walletActionStatus(wallet: WalletInterface, action: Record): Promise<'completed' | 'failed' | 'unproven' | 'unknown'> { +export async function walletActionStatus(wallet: WalletInterface, action: Record): Promise { return statusFromActions(await walletActions(wallet), action) } export function walletStatusMessage(status: Awaited>): string { - if (status === 'completed') return 'Payment confirmed by your wallet.' + if (status === 'accepted') return 'Your wallet accepted this payment.' if (status === 'failed') return 'Your wallet reports this payment failed. Review wallet activity before starting another payment.' - if (status === 'unproven') return 'Submitted; waiting for confirmation. Your wallet has not returned a mined proof yet. Do not send this payment again.' return 'The payment outcome is not known. Check wallet activity before continuing. Do not send it again.' } -export async function assertWalletActionFinal(wallet: WalletInterface, action: Record): Promise { +export async function assertWalletActionResolved(wallet: WalletInterface, action: Record): Promise { const status = await walletActionStatus(wallet, action) - if (status !== 'completed' && status !== 'failed') throw new Error(walletStatusMessage(status)) + if (status === 'unknown') throw new Error(walletStatusMessage(status)) } function pendingFromActions(actions: WalletAction[], network: WalletRecords['network']): RecoveryRecord[] { @@ -52,11 +59,10 @@ function pendingFromActions(actions: WalletAction[], network: WalletRecords['net for (const [key, group] of groups) { const action = group[0], statuses = new Set(group.map(row => row.status)) const consistent = statuses.size === 1 - if (consistent && (action.status === 'completed' || action.status === 'failed')) continue - if (consistent && action.status === 'unproven' && group.every(row => row.labels?.includes(RECORD_LABEL))) continue + if (outcomeFromRows(group) !== 'unknown') continue const id = action.labels?.find(label => label.startsWith('mountaintops request '))?.slice(21) ?? (action.txid || key) const canAbort = consistent && action.status === 'nosend' && /^[a-f0-9]{64}$/.test(action.txid) - pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : consistent && action.status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) + pending.push({ v: 1, network, kind: 'action', clock: 0, data: { id, state: canAbort ? 'prepared' : 'needs wallet review', reference: canAbort ? action.txid : null, txid: action.txid } }) } return pending } @@ -69,17 +75,15 @@ function reconcileActionRecords(actions: WalletAction[], network: WalletRecords[ if (record.kind !== 'action') { carried.push(record); continue } if (resolved.has(String(record.data.state))) { if (record.clock > 0) carried.push(record); continue } const status = statusFromActions(actions, record.data) - const matching = actions.filter(row => matches(record.data, row)) - const recordOnly = status === 'unproven' && matching.every(row => row.labels?.includes(RECORD_LABEL)) - if (recordOnly || status === 'completed' || status === 'failed') { + if (status === 'accepted' || status === 'failed') { // Resolve a legacy record only in memory; refresh never writes a token. if (record.clock > 0) carried.push({ ...record, data: { ...record.data, state: 'reviewed in wallet' } }) continue } if (native.some(item => item.data.id === record.data.id || (record.data.txid && item.data.txid === record.data.txid))) continue // A previously observed action disappearing from history is not proof that - // it failed. Keep the resend guard until the wallet supplies a final result. - native.push({ ...record, data: { ...record.data, state: status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review', reference: null } }) + // it failed. Keep the guard until the wallet acknowledges its outcome. + native.push({ ...record, data: { ...record.data, state: 'needs wallet review', reference: null } }) } return [...carried, ...native] } diff --git a/frontend/test/actions.test.mjs b/frontend/test/actions.test.mjs index de6e02c..21b2d2c 100644 --- a/frontend/test/actions.test.mjs +++ b/frontend/test/actions.test.mjs @@ -1,7 +1,7 @@ import test from 'node:test' import assert from 'node:assert/strict' import { P2PKH, PrivateKey, Transaction, Spend } from '@bsv/sdk' -import { assertSameTemplate, importCoins, sendCoins, unfinishedWalletActions } from '../src/actions.ts' +import { assertSameTemplate, importCoins, sendCoins, unfinishedWalletActions, PaymentOutcomeUnknownError } from '../src/actions.ts' import Importer from '../src/Importer.ts' import { FixtureWallet } from './fixtureWallet.mjs' @@ -59,6 +59,69 @@ test('unsigned preparation and withheld signing precede one explicit sendWith', } finally { globalThis.fetch = previous } }) +test('two deliberate payments can spend valid wallet change before either payment is mined', async () => { + const previous = globalThis.fetch + globalThis.fetch = async url => String(url).endsWith('/spent') ? new Response('', { status: 404 }) : Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) + const wallet = new FixtureWallet(), store = { network: 'mainnet', load: async () => [] } + const submissions = [], create = wallet.createAction.bind(wallet) + wallet.createAction = async args => { if (args.options?.sendWith) submissions.push(...args.options.sendWith); return create(args) } + try { + const first = await sendCoins(wallet, store, new PrivateKey(43).toPublicKey().toAddress(), '0.00001000', { stage: 0, state: null }, () => {}) + const second = await sendCoins(wallet, store, new PrivateKey(44).toPublicKey().toAddress(), '0.00000500', { stage: 0, state: null }, () => {}) + assert.notEqual(first, second) + assert.deepEqual(submissions, [first, second]) + assert.ok(wallet.state.actions.every(action => action.status === 'unproven')) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) + const next = wallet.state.transactions.get(second) + assert.equal(next.inputs[0].sourceTXID, first) + assert.equal(next.inputs[0].sourceOutputIndex, 1, 'the next payment spends owned change, not the external recipient output') + for (const txid of submissions) { + const tx = wallet.state.transactions.get(txid), input = tx.inputs[0], source = input.sourceTransaction.outputs[input.sourceOutputIndex] + const spend = new Spend({ sourceTXID: input.sourceTXID, sourceOutputIndex: input.sourceOutputIndex, sourceSatoshis: source.satoshis, lockingScript: source.lockingScript, transactionVersion: tx.version, otherInputs: [], inputIndex: 0, inputSequence: input.sequence, unlockingScript: input.unlockingScript, outputs: tx.outputs, lockTime: tx.lockTime }) + assert.equal(spend.validate(), true) + } + } finally { globalThis.fetch = previous } +}) + +test('a lost submission reply carries its exact TXID and never retries or aborts a released payment', async () => { + const previous = globalThis.fetch + globalThis.fetch = async url => String(url).endsWith('/spent') ? new Response('', { status: 404 }) : Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) + const wallet = new FixtureWallet(), create = wallet.createAction.bind(wallet) + let submitted, calls = 0, aborts = 0 + wallet.createAction = async args => { + const result = await create(args) + if (args.options?.sendWith) { calls++; submitted = args.options.sendWith[0]; throw new Error('Synthetic reply lost after acceptance') } + return result + } + wallet.abortAction = async () => { aborts++; return { aborted: true } } + try { + await assert.rejects(sendCoins(wallet, { network: 'mainnet', load: async () => [] }, new PrivateKey(43).toPublicKey().toAddress(), '0.00001000', { stage: 0, state: null }, () => {}), error => error instanceof PaymentOutcomeUnknownError && error.txid === submitted) + assert.equal(calls, 1); assert.equal(aborts, 0) + assert.equal(wallet.state.actions.at(-1).status, 'unproven') + } finally { globalThis.fetch = previous } +}) + +test('missing, mismatched, failed and contradictory submission acknowledgments cannot become a success', async () => { + const previous = globalThis.fetch + globalThis.fetch = async url => String(url).endsWith('/spent') ? new Response('', { status: 404 }) : Response.json({ blocks: 972777, bestblockhash: 'a'.repeat(64) }) + try { + for (const mode of ['missing', 'mismatched', 'failed', 'contradictory']) { + const wallet = new FixtureWallet(), create = wallet.createAction.bind(wallet) + let submissions = 0, aborts = 0, submitted + wallet.createAction = async args => { + const result = await create(args) + if (!args.options?.sendWith) return result + submissions++; submitted = args.options.sendWith[0] + const accepted = { txid: submitted, status: 'unproven' } + return { ...result, sendWithResults: mode === 'missing' ? [] : mode === 'mismatched' ? [{ ...accepted, txid: 'f'.repeat(64) }] : mode === 'failed' ? [{ ...accepted, status: 'failed' }] : [accepted, { ...accepted, status: 'failed' }] } + } + wallet.abortAction = async () => { aborts++; return { aborted: true } } + await assert.rejects(sendCoins(wallet, { network: 'mainnet', load: async () => [] }, new PrivateKey(43).toPublicKey().toAddress(), '0.00001000', { stage: 0, state: null }, () => {}), error => error instanceof PaymentOutcomeUnknownError && error.txid === submitted, mode) + assert.equal(submissions, 1, mode); assert.equal(aborts, 0, mode) + } + } finally { globalThis.fetch = previous } +}) + for (const staleMigrationCoin of [false, true]) test(staleMigrationCoin ? 'a self-funded import avoids optional batch migration of an already-spent wallet coin' @@ -123,13 +186,13 @@ test('a fresh wallet instance finds a signed unsubmitted action without browser }) -test('fresh-device recovery blocks another payment while a submission is sending or unproven', async () => { - for (const status of ['sending', 'unproven']) { +test('fresh-device recovery blocks only unsent or unresolved wallet actions', async () => { + for (const status of ['unsigned', 'nosend', 'unprocessed', 'nonfinal', 'future-state']) { const wallet = new FixtureWallet() wallet.state.actions.push({ txid: 'a'.repeat(64), status, labels: ['mountaintops actions v1', 'mountaintops request uncertain'], description: 'Awaiting wallet outcome' }) const pending = await unfinishedWalletActions(new FixtureWallet(wallet.state), 'mainnet') assert.equal(pending.length, 1) - assert.equal(pending[0].data.state, status === 'unproven' ? 'awaiting confirmation' : 'needs wallet review') + assert.equal(pending[0].data.state, status === 'nosend' ? 'prepared' : 'needs wallet review') await assert.rejects(sendCoins(wallet, { network: 'mainnet' }, new PrivateKey(43).toPublicKey().toAddress(), '0.00000001', { stage: 0 }, () => {}), /unfinished wallet action/) } }) diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs index 6f71ef8..7377dcc 100644 --- a/frontend/test/browser/payment-status.mjs +++ b/frontend/test/browser/payment-status.mjs @@ -3,6 +3,7 @@ import path from 'node:path' import { mkdir } from 'node:fs/promises' import { createServer } from 'vite' import { chromium } from 'playwright' + const root = path.resolve(import.meta.dirname, '../..') const evidence = process.env.PAYMENT_STATUS_EVIDENCE if (evidence) await mkdir(evidence, { recursive: true }) @@ -10,6 +11,8 @@ const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 } await server.listen() const origin = `http://127.0.0.1:${server.httpServer.address().port}` const browser = await chromium.launch({ headless: true }) +const destination = '1BoatSLRHtKNngkdXEeobR76b53LETtpyT' + try { for (const width of [1440, 390, 320]) { const context = await browser.newContext({ viewport: { width, height: 1000 }, serviceWorkers: 'block' }) @@ -19,73 +22,123 @@ try { if (new URL(route.request().url()).origin === origin) return route.continue() unexpected.push(route.request().url()); return route.abort() }) - try { - await page.goto(origin + '/test/ui.html?pending=unproven&payments') + const idle = () => page.waitForFunction(() => document.querySelector('main').getAttribute('aria-busy') === 'false') + const connect = async query => { + await page.goto(`${origin}/test/ui.html?${query}`) await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() - await page.waitForFunction(() => document.querySelector('main').getAttribute('aria-busy') === 'false') - const status = page.getByRole('region', { name: 'Wallet payment status' }) - await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() - await status.getByText('Waiting for confirmation.', { exact: true }).waitFor() - assert.equal(await status.getAttribute('class'), 'payment-status sent') - await page.getByText('Received', { exact: true }).waitFor() - await page.getByText('10,002 sats', { exact: true }).waitFor() - await page.getByText('Transfers resume after confirmation.', { exact: true }).waitFor() - await status.getByText('Payment details', { exact: true }).click() - await status.getByText('Last checked', { exact: false }).waitFor() - await status.getByText('Payment details', { exact: true }).click() - if (evidence) await page.screenshot({ path: path.join(evidence, `received-${width}.png`), fullPage: true }) + await idle() + } + const draft = async amount => { + await page.getByRole('button', { name: 'Send', exact: true }).click() + await page.getByLabel('To', { exact: true }).fill(destination) + await page.getByLabel('Amount', { exact: true }).fill(amount) + await page.getByRole('button', { name: 'Review payment', exact: true }).click() + await page.getByRole('region', { name: 'Review payment' }).waitFor() + } + const receipt = page.getByRole('status', { name: 'Payment receipt' }) + const unresolved = page.getByRole('region', { name: 'Wallet payment status' }) + const shot = async name => { if (evidence) await page.screenshot({ path: path.join(evidence, `${name}-${width}.png`), fullPage: true }) } + try { + // Existing accepted unmined funds are usable, without status polling. + await connect('pending=unproven&payments') + assert.equal(await unresolved.count(), 0) + assert.equal(await page.getByRole('button', { name: 'Move to wallet' }).isEnabled(), true) + assert.doesNotMatch(await page.locator('body').innerText(), /waiting for confirmation|resume after confirmation/i) + await shot('receive') + await page.getByRole('button', { name: 'Send', exact: true }).click() + await page.getByLabel('To', { exact: true }).fill(destination) + await page.getByLabel('Amount', { exact: true }).fill('1000') + await page.getByLabel('Amount unit').selectOption('BSV') + assert.equal(await page.getByLabel('Amount', { exact: true }).inputValue(), '0.00001000') + await page.getByLabel('Amount unit').selectOption('sats') + assert.equal(await page.getByLabel('Amount', { exact: true }).inputValue(), '1000') + await page.getByRole('button', { name: 'Review payment', exact: true }).click() + await page.getByRole('region', { name: 'Review payment' }).waitFor() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) + await shot('review') + await page.getByRole('button', { name: 'Back', exact: true }).click() + assert.equal(await page.getByLabel('Amount', { exact: true }).inputValue(), '1000') + await page.getByRole('button', { name: 'Review payment', exact: true }).click() + // Two immediate clicks still authorize one submission only. + await page.evaluate(() => { + const button = [...document.querySelectorAll('button')].find(item => item.textContent === 'Send payment') + button.click(); button.click() + }) + await receipt.getByText('Payment sent', { exact: true }).waitFor() + await idle() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + assert.equal(await unresolved.count(), 0) + assert.equal(await page.getByRole('region', { name: 'Review payment' }).count(), 0) + await shot('sent') + // A distinct subsequent payment does not wait for either payment to mine. + await receipt.getByRole('button', { name: 'Send another' }).click() + assert.equal(await page.getByLabel('To', { exact: true }).inputValue(), '') + await draft('500') + await page.getByRole('button', { name: 'Send payment', exact: true }).click() + await receipt.getByText('Payment sent', { exact: true }).waitFor(); await idle() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 2) + await receipt.getByRole('button', { name: 'Done', exact: true }).click() + assert.equal(await page.getByRole('button', { name: 'Move to wallet' }).isEnabled(), true) + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + + // Truly unresolved outcomes are distinct; checking cannot create a payment. + await connect('pending=unprocessed&payments') + await unresolved.getByRole('heading', { name: 'Check your wallet' }).waitFor() + assert.equal(await page.getByRole('button', { name: 'Move to wallet' }).isDisabled(), true) await page.evaluate(() => window.fixtureBlockRecoveryReads()) for (let i = 0; i < 2; i++) { - await status.getByRole('button', { name: 'Refresh payment status' }).click() - await status.getByRole('button', { name: 'Refresh payment status' }).waitFor({ state: 'visible' }) - await page.waitForFunction(() => !document.querySelector('[aria-label="Wallet payment status"] button').disabled) - assert.equal(await page.getByRole('alert').count(), 0, 'status refresh must not access recovery records or chain coverage') - await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() - assert.equal(await page.locator('.feedback').count(), 0, 'a successful status refresh must not add a duplicate notice') + await unresolved.getByRole('button', { name: 'Check payment in wallet' }).click(); await idle() + assert.equal(await page.getByRole('alert').count(), 0) + } + await shot('unknown') + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) + await page.evaluate(() => window.fixtureSetStatus('unproven')) + await unresolved.getByRole('button', { name: 'Check payment in wallet' }).click(); await idle() + assert.equal(await unresolved.count(), 0) + await receipt.getByText('Payment accepted', { exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) + + if (width === 1440) { + // Cancel is checked against fresh wallet history, never a stale button. + await connect('pending=nosend') + await page.evaluate(() => { window.fixtureBlockRecoveryReads(); window.fixtureSetStatus('unproven') }) + await unresolved.getByRole('button', { name: 'Cancel unsent payment' }).click(); await idle() + assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 0) + assert.equal(await unresolved.count(), 0) + await connect('pending=nosend') + await page.evaluate(() => window.fixtureBlockRecoveryReads()) + await unresolved.getByRole('button', { name: 'Cancel unsent payment' }).click(); await idle() + assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 1) + assert.equal(await unresolved.count(), 0) + + for (const mode of ['missing', 'accepted-lost', 'failed']) { + await connect(`submit=${mode}`); await draft('1000') + await page.getByRole('button', { name: 'Send payment', exact: true }).click(); await idle() + await unresolved.getByRole('heading', { name: 'Check your wallet' }).waitFor() + assert.equal(await receipt.count(), 0) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + await unresolved.getByRole('button', { name: 'Check payment in wallet' }).click(); await idle() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + if (mode === 'missing') assert.equal(await unresolved.count(), 1) + else if (mode === 'accepted-lost') { assert.equal(await unresolved.count(), 0); await receipt.getByText('Payment accepted', { exact: true }).waitFor() } + else { assert.equal(await receipt.count(), 0); await page.getByText('Your wallet reports this payment failed.', { exact: false }).waitFor() } + } + // Post-acceptance metadata problems cannot erase success or cause retry. + await connect('block-after-accept'); await draft('1000') + await page.getByRole('button', { name: 'Send payment', exact: true }).click(); await idle() + await receipt.getByText('Payment sent', { exact: true }).waitFor() + assert.equal(await page.getByRole('alert').count(), 0) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + + await connect(''); await draft('1000') + await page.evaluate(() => window.fixtureSetNetwork('testnet')) + await page.getByRole('button', { name: 'Send payment', exact: true }).click(); await idle() + await page.getByRole('button', { name: 'Connect wallet', exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) + assert.equal(await receipt.count(), 0) } - assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') - await page.getByRole('button', { name: 'Send', exact: true }).click() - await page.getByLabel('To', { exact: true }).fill('1BoatSLRHtKNngkdXEeobR76b53LETtpyT') - await page.getByLabel('Amount in BSV').fill('0.00000001') - assert.equal(await page.getByRole('button', { name: 'Send BSV', exact: true }).isDisabled(), true) - if (evidence) await page.screenshot({ path: path.join(evidence, `pending-${width}.png`), fullPage: true }) - await page.evaluate(() => window.fixtureSetStatus('completed')) - await status.getByRole('button', { name: 'Refresh payment status' }).click() - await page.getByText('Payment confirmed by your wallet.', { exact: true }).waitFor() - assert.equal(await status.count(), 0) - assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') - assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) - // A fresh connection must show an unknown sending outcome differently. - await page.goto(origin + '/test/ui.html?pending=sending') - await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() - await status.getByRole('heading', { name: 'Check payment status', exact: true }).waitFor() - await status.getByRole('button', { name: 'Refresh payment status' }).click() - await status.getByText('Your wallet has not reported a clear result.', { exact: true }).waitFor() - assert.equal(await page.locator('.feedback').count(), 0) - if (evidence) await page.screenshot({ path: path.join(evidence, `unknown-${width}.png`), fullPage: true }) - assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') - await page.evaluate(() => { window.fixtureSetStatus('completed'); window.fixtureAddConflict() }) - await status.getByRole('button', { name: 'Refresh payment status' }).click() - await status.getByText('Your wallet has not reported a clear result.', { exact: true }).waitFor() - assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') - // A stale cancel button must not cancel a payment submitted elsewhere. - await page.goto(origin + '/test/ui.html?pending=nosend') - await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() - await status.getByRole('button', { name: 'Cancel unsent payment' }).waitFor() - await page.evaluate(() => { window.fixtureBlockRecoveryReads(); window.fixtureSetStatus('unproven') }) - await status.getByRole('button', { name: 'Cancel unsent payment' }).click() - await status.getByRole('heading', { name: 'Payment sent', exact: true }).waitFor() - assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 0) - // A still-unsent preparation retains its normal explicit cancellation. - await page.evaluate(() => window.fixtureSetStatus('nosend')) - await status.getByRole('button', { name: 'Refresh payment status' }).click() - await status.getByRole('button', { name: 'Cancel unsent payment' }).click() - await page.getByText('Unsent payment canceled.', { exact: true }).waitFor() - assert.equal(await status.count(), 0) - assert.equal(await page.evaluate(() => window.fixtureAbortCalls()), 1) - assert.equal(await page.locator('#fixture-actions').innerText(), 'Isolated fixture · 0 wallet transactions') assert.deepEqual(errors, []); assert.deepEqual(unexpected, []) - console.log(`PASS ${width}px: pending proof, repeated refresh, completion and unknown outcome; zero wallet transactions or external requests`) + console.log(`PASS ${width}px: wallet acceptance, amount review, single submission, subsequent payment, unresolved recovery; no external requests`) } finally { await context.close() } } } finally { await browser.close(); await server.close() } diff --git a/frontend/test/fixtureWallet.mjs b/frontend/test/fixtureWallet.mjs index fe126b5..d15f05b 100644 --- a/frontend/test/fixtureWallet.mjs +++ b/frontend/test/fixtureWallet.mjs @@ -62,6 +62,8 @@ export class FixtureWallet extends ProtoWallet { this.state.transactions.set(txid, tx) tx.outputs.forEach((out, index) => { const original = args.outputs?.[index] + // External recipient outputs do not become this wallet's funding coins. + if (!original?.basket && out.lockingScript.toHex() !== new P2PKH().lock(this.key.toPublicKey().toAddress()).toHex()) return this.state.outputs.set(`${txid}.${index}`, { basket: original?.basket ?? 'default', tags: original?.tags ?? [], satoshis: out.satoshis, customInstructions: original?.customInstructions, spendable: true }) }) this.state.actions.push({ txid, satoshis: -2, isOutgoing: true, version: tx.version, lockTime: tx.lockTime, status: options?.noSend ? 'nosend' : 'unproven', labels: args.labels ?? [], description: args.description }) diff --git a/frontend/test/paymentAmount.test.mjs b/frontend/test/paymentAmount.test.mjs new file mode 100644 index 0000000..6ec0299 --- /dev/null +++ b/frontend/test/paymentAmount.test.mjs @@ -0,0 +1,17 @@ +import test from 'node:test' +import assert from 'node:assert/strict' +import { parseAmount, bsvAmount } from '../src/paymentAmount.ts' + +test('sats and BSV preserve the exact recipient amount through unit changes', () => { + for (const sats of [1, 1000, 100000001, 2100000000000000]) { + assert.equal(parseAmount(String(sats), 'sats'), sats) + assert.equal(parseAmount(bsvAmount(sats), 'BSV'), sats) + } +}) + +test('invalid, fractional satoshi and out-of-range values never reach review', () => { + for (const value of ['0', '-1', '1.2', '1e3', ' 1', '9007199254740993']) assert.throws(() => parseAmount(value, 'sats')) + for (const value of ['0', '0.000000001', '-1', '1e3', '21000000.00000001']) assert.throws(() => parseAmount(value, 'BSV')) + assert.throws(() => bsvAmount(1.1)) + assert.throws(() => bsvAmount(Number.MAX_SAFE_INTEGER)) +}) diff --git a/frontend/test/paymentStatus.test.mjs b/frontend/test/paymentStatus.test.mjs index b7f8a87..b319a78 100644 --- a/frontend/test/paymentStatus.test.mjs +++ b/frontend/test/paymentStatus.test.mjs @@ -1,89 +1,78 @@ import assert from 'node:assert/strict' import test from 'node:test' -import { walletActionStatus, walletStatusMessage, unfinishedWalletActions, assertWalletActionFinal } from '../src/walletActionState.ts' +import { walletActionStatus, walletStatusMessage, unfinishedWalletActions, assertWalletActionResolved, refreshPaymentStatus, paymentActionRecords } from '../src/walletActionState.ts' const txid = 'a'.repeat(64) -test('refresh and reconnect distinguish submitted/unproven from unknown without another financial call', async () => { - let status = 'unproven', reads = 0 - const wallet = { listActions: async () => { reads++; return { totalActions: 1, actions: [{ txid, status, labels: ['mountaintops actions v1'] }] } } } - for (let i = 0; i < 3; i++) { - assert.equal((await unfinishedWalletActions(wallet, 'mainnet'))[0].data.state, 'awaiting confirmation') - assert.equal(await walletActionStatus(wallet, { txid }), 'unproven') - assert.match(walletStatusMessage('unproven'), /Submitted; waiting for confirmation/) - await assert.rejects(assertWalletActionFinal(wallet, { txid }), /Do not send this payment again/) +const row = status => ({ txid, status, labels: ['mountaintops actions v1'] }) +const guard = () => ({ v: 1, network: 'mainnet', kind: 'action', clock: 0, data: { id: txid, txid, state: 'needs wallet review' } }) + +test('wallet acceptance releases the app without waiting for mining, including after reconnect', async () => { + for (const status of ['sending', 'unproven', 'completed']) { + const wallet = { listActions: async () => ({ totalActions: 1, actions: [row(status)] }) } + assert.equal(await walletActionStatus(wallet, { txid }), 'accepted') + await assertWalletActionResolved(wallet, { txid }) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) + assert.deepEqual(await paymentActionRecords(wallet, 'mainnet', [guard()]), []) } - status = 'completed' - assert.equal(await walletActionStatus(wallet, { txid }), 'completed') - await assertWalletActionFinal(wallet, { txid }) - assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) - status = 'failed' - assert.equal(await walletActionStatus(wallet, { txid }), 'failed') - assert.match(walletStatusMessage('failed'), /reports this payment failed/) + assert.equal(walletStatusMessage('accepted'), 'Your wallet accepted this payment.') +}) + +test('compatible accepted lifecycle observations are not conflicting payment outcomes', async () => { + const actions = ['sending', 'unproven', 'completed'].map(row) + const wallet = { listActions: async () => ({ totalActions: actions.length, actions }) } + assert.equal(await walletActionStatus(wallet, { txid }), 'accepted') assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) - assert.ok(reads > 10) }) -test('missing, conflicting, sending and unfamiliar outcomes never claim submission or completion', async () => { - for (const actions of [[], [{ txid, status: 'sending' }], [{ txid, status: 'future-state' }], [{ txid, status: 'completed' }, { txid, status: 'unproven' }]]) { + +test('missing, unfamiliar and contradictory outcomes stay guarded', async () => { + for (const actions of [[], [row('future-state')], [row('unsigned')], [row('completed'), row('failed')], [row('unproven'), row('nosend')]]) { const wallet = { listActions: async () => ({ totalActions: actions.length, actions }) } assert.equal(await walletActionStatus(wallet, { txid }), 'unknown') - await assert.rejects(assertWalletActionFinal(wallet, { txid }), /outcome is not known/) + await assert.rejects(assertWalletActionResolved(wallet, { txid }), /outcome is not known/) + const records = await paymentActionRecords(wallet, 'mainnet', [guard()]) + assert.equal(records.length, 1) + assert.equal(records[0].data.state, 'needs wallet review') } }) -test('unfamiliar and conflicting terminal wallet rows keep payment admission blocked', async () => { - for (const actions of [[{ txid, status: 'future-state' }], [{ txid, status: 'completed' }, { txid, status: 'failed' }]]) { - const wallet = { listActions: async () => ({ totalActions: actions.length, actions }) } - assert.equal((await unfinishedWalletActions(wallet, 'mainnet')).length, 1) - } +test('failed is a known wallet outcome, never a success receipt or automatic retry', async () => { + const wallet = { listActions: async () => ({ totalActions: 1, actions: [row('failed')] }) } + assert.equal(await walletActionStatus(wallet, { txid }), 'failed') + assert.match(walletStatusMessage('failed'), /reports this payment failed/) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) }) -test('dedicated refresh uses only identity/network/history reads and keeps missing or conflicting observations blocked', async () => { - const { refreshPaymentStatus } = await import('../src/walletActionState.ts') - const identity = 'synthetic-wallet-identity' - let rows = [{ txid, status: 'unproven', labels: ['mountaintops actions v1'] }] - const methods = [] +test('checking an unresolved attempt uses only identity/network/history reads', async () => { + const identity = 'synthetic-wallet-identity', methods = [] + let rows = [row('unprocessed')] const wallet = new Proxy({ getPublicKey: async () => { methods.push('getPublicKey'); return { publicKey: identity } }, getNetwork: async () => { methods.push('getNetwork'); return { network: 'mainnet' } }, listActions: async () => { methods.push('listActions'); return { totalActions: rows.length, actions: rows } } }, { get(target, key) { if (!(key in target)) throw Error(`Unexpected wallet method: ${String(key)}`); return target[key] } }) - let records = await unfinishedWalletActions(wallet, 'mainnet') - let result = await refreshPaymentStatus(wallet, identity, 'mainnet', records, { txid }) - assert.equal(result.status, 'unproven'); assert.equal(result.records.length, 1) + let result = await refreshPaymentStatus(wallet, identity, 'mainnet', [guard()], { txid }) + assert.equal(result.status, 'unknown'); assert.equal(result.records.length, 1) rows = [] result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) - assert.equal(result.status, 'unknown'); assert.equal(result.records[0].data.state, 'needs wallet review') - rows = [{ txid, status: 'completed' }, { txid, status: 'failed' }] - result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) assert.equal(result.status, 'unknown'); assert.equal(result.records.length, 1) - rows = [{ txid, status: 'completed' }] + rows = [row('unproven')] result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) - assert.equal(result.status, 'completed'); assert.deepEqual(result.records, []) + assert.equal(result.status, 'accepted'); assert.deepEqual(result.records, []) assert.ok(methods.every(method => ['getPublicKey', 'getNetwork', 'listActions'].includes(method))) - await assert.rejects(refreshPaymentStatus(wallet, 'different-wallet', 'mainnet', records, { txid }), /account or network changed/) - await assert.rejects(refreshPaymentStatus(wallet, identity, 'testnet', records, { txid }), /account or network changed/) + await assert.rejects(refreshPaymentStatus(wallet, 'different-wallet', 'mainnet', [guard()], { txid }), /account or network changed/) + await assert.rejects(refreshPaymentStatus(wallet, identity, 'testnet', [guard()], { txid }), /account or network changed/) }) -test('status reconciliation retains the existing unproven record-only exception and resolves legacy records only in memory', async () => { - const { paymentActionRecords } = await import('../src/walletActionState.ts') - const prior = [{ v: 1, network: 'mainnet', kind: 'action', clock: 0, data: { id: txid, txid, state: 'needs wallet review' } }] - const recordRows = [{ txid, status: 'unproven', labels: ['mountaintops actions v1', 'mountaintops records v1'] }] - // The exact exported record scope, rather than an extra permission label. - const { RECORD_LABEL } = await import('../src/walletScopes.ts') - recordRows[0].labels[1] = RECORD_LABEL - const wallet = { listActions: async () => ({ totalActions: 1, actions: recordRows }) } - assert.deepEqual(await paymentActionRecords(wallet, 'mainnet', prior), []) - recordRows[0] = { txid, status: 'completed', labels: ['mountaintops actions v1'] } - const legacy = [{ ...prior[0], clock: 1, serial: 'synthetic.0' }] - const reconciled = await paymentActionRecords(wallet, 'mainnet', legacy) - assert.equal(reconciled[0].data.state, 'reviewed in wallet') - assert.equal(legacy[0].data.state, 'needs wallet review') +test('legacy action records resolve in memory after wallet acceptance without a paid record', async () => { + const original = { ...guard(), clock: 1, serial: 'synthetic.0' } + const wallet = { listActions: async () => ({ totalActions: 1, actions: [row('unproven')] }) } + const result = await paymentActionRecords(wallet, 'mainnet', [original]) + assert.equal(result[0].data.state, 'reviewed in wallet') + assert.equal(original.data.state, 'needs wallet review') }) -test('a failed history refresh cannot mutate or discard the previously observed guard', async () => { - const { refreshPaymentStatus } = await import('../src/walletActionState.ts') - const records = [{ v: 1, network: 'mainnet', kind: 'action', clock: 0, data: { id: txid, txid, state: 'awaiting confirmation' } }] - const before = structuredClone(records) +test('a failed history read preserves the unresolved attempt', async () => { + const records = [guard()], before = structuredClone(records) const wallet = { getPublicKey: async () => ({ publicKey: 'synthetic' }), getNetwork: async () => ({ network: 'mainnet' }), listActions: async () => { throw Error('Read unavailable') } } await assert.rejects(refreshPaymentStatus(wallet, 'synthetic', 'mainnet', records, { txid }), /Read unavailable/) assert.deepEqual(records, before) diff --git a/frontend/test/permissions.test.mjs b/frontend/test/permissions.test.mjs index 81e86c9..5af2dde 100644 --- a/frontend/test/permissions.test.mjs +++ b/frontend/test/permissions.test.mjs @@ -6,7 +6,7 @@ import { WalletPermissionsManager } from '@bsv/wallet-toolbox-client' import { FixtureWallet } from './fixtureWallet.mjs' import { WalletRecords } from '../src/walletRecords.ts' import { sendCoins } from '../src/actions.ts' -import { assertWalletActionFinal, unfinishedWalletActions } from '../src/walletActionState.ts' +import { assertWalletActionResolved, unfinishedWalletActions } from '../src/walletActionState.ts' import { ACTION_LABEL, RECORD_LABEL, RECEIPT_LABEL } from '../src/walletScopes.ts' import { publicDeriver } from '../src/derivation.ts' @@ -71,8 +71,8 @@ test('real SDK encrypted save, fresh recovery, derivation and payment use only d assert.equal((await restored.load()).length, 1) await wallet.listOutputs({ basket: 'mountaintops receipts v1' }) const txid = await sendCoins(wallet, store, new PrivateKey(43).toPublicKey().toAddress(), '0.00001000', { stage: 0, state: null }, () => {}) - const pending = await unfinishedWalletActions(wallet, 'mainnet') - assert.equal(pending[0].data.id, txid) + assert.deepEqual(await unfinishedWalletActions(wallet, 'mainnet'), []) + await assertWalletActionResolved(wallet, { txid }) assert.deepEqual(raw.state.actions.at(-1).labels, [ACTION_LABEL]) assert.deepEqual(raw.state.actions[0].labels, [ACTION_LABEL, RECORD_LABEL]) } finally { globalThis.fetch = previous } @@ -124,10 +124,10 @@ test('legacy and new pending actions resolve using one fixed label across pages' assert.deepEqual(args.labels, [ACTION_LABEL]) return { totalActions: actions.length, actions: actions.slice(args.offset, args.offset + args.limit) } } } - await assertWalletActionFinal(wallet, { id: 'old-request' }) - await assertWalletActionFinal(wallet, { txid: actions[100].txid }) + await assertWalletActionResolved(wallet, { id: 'old-request' }) + await assertWalletActionResolved(wallet, { txid: actions[100].txid }) actions[100].status = 'unproven' - await assert.rejects(assertWalletActionFinal(wallet, { id: 'old-request' }), /Submitted; waiting for confirmation/) - await assert.rejects(assertWalletActionFinal(wallet, { txid: 'f'.repeat(64) }), /outcome is not known/) + await assertWalletActionResolved(wallet, { id: 'old-request' }) + await assert.rejects(assertWalletActionResolved(wallet, { txid: 'f'.repeat(64) }), /outcome is not known/) await assert.rejects(unfinishedWalletActions({ listActions: async () => ({ totalActions: 200, actions: [] }) }, 'mainnet'), /incomplete/) }) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 56f08cd..6a0b478 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -8,10 +8,28 @@ 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 counter = document.createElement('output'); counter.id = 'fixture-actions'; counter.style.cssText = 'display:block;text-align:center;padding:8px'; counter.textContent = 'Isolated demo · no real funds · 0 simulated actions'; document.body.prepend(counter) const create = wallet.createAction.bind(wallet) let actions = 0 -wallet.createAction = async args => { counter.textContent = `Isolated fixture · ${++actions} wallet transactions`; return create(args) } +let submissions = 0 +window.fixtureSubmissionCount = () => submissions +window.fixtureSetNetwork = network => { wallet.getNetwork = async () => ({ network }) } +wallet.createAction = async args => { + counter.textContent = `Isolated demo · no real funds · ${++actions} simulated actions` + const result = await create(args) + if (args.options?.sendWith) { + submissions++ + const mode = new URL(location.href).searchParams.get('submit') + if (mode === 'missing') { wallet.state.actions.length = 0; throw new Error('Synthetic unknown submission') } + if (mode === 'accepted-lost') throw new Error('Synthetic reply lost after wallet acceptance') + if (mode === 'failed') { wallet.state.actions.at(-1).status = 'failed'; return { sendWithResults: args.options.sendWith.map(txid => ({ txid, status: 'failed' })) } } + if (new URL(location.href).searchParams.has('block-after-accept')) { + wallet.listOutputs = async () => { throw new Error('Accepted payment triggered an unnecessary recovery read') } + window.fetch = async () => { throw new Error('Accepted payment triggered an unnecessary chain read') } + } + } + return result +} window.fetch = async (input) => { const url = String(input) const headerHeight = Number(url.match(/\/block\/(\d+)\/header$/)?.[1]) From e8063e881dca6ceb153426b3bc30afeff56ee921 Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:12:52 -0800 Subject: [PATCH 07/13] Simplify received-payment progress wording --- frontend/src/coins.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frontend/src/coins.ts b/frontend/src/coins.ts index 180935a..90d6a33 100644 --- a/frontend/src/coins.ts +++ b/frontend/src/coins.ts @@ -202,7 +202,7 @@ export async function refreshCoins(wallet: WalletInterface, store: WalletRecords const alreadyRetained = new Set(retained.coins.map(coin => `${coin.txid}.${coin.vout}`)) const newCoins = found.filter(coin => !alreadyRetained.has(`${coin.txid}.${coin.vout}`)) if (newCoins.length) { - progress('Saving new deposit evidence in your wallet for device-independent recovery…') + progress('Updating your payments…') await retainCoins(wallet, entry, newCoins) retained = await retainedCoins(wallet, entry) } From 1c3e323af148c14d78f611085e3ba4a7d76cc22a Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:16:05 -0800 Subject: [PATCH 08/13] Animate payment progress through wallet acceptance --- frontend/src/App.tsx | 17 ++++++++++---- frontend/src/PaymentProgress.tsx | 15 ++++++++++++ frontend/src/PaymentReview.tsx | 7 +++--- frontend/src/style.css | 12 ++++++++++ frontend/test/browser/payment-status.mjs | 30 ++++++++++++++++++++++++ frontend/test/ui.html | 6 +++++ 6 files changed, 79 insertions(+), 8 deletions(-) create mode 100644 frontend/src/PaymentProgress.tsx diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 09882f6..b58eccd 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -7,6 +7,7 @@ import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveU import ReceiveInfo from './ReceiveInfo.tsx' import PaymentStatus from './PaymentStatus.tsx' import PaymentReceipt, { type PaymentReceiptData } from './PaymentReceipt.tsx' +import PaymentProgress from './PaymentProgress.tsx' import PaymentReview, { type PaymentDraft } from './PaymentReview.tsx' import { bsvAmount, parseAmount, type AmountUnit } from './paymentAmount.ts' import { readCoverage, type Coverage } from './coverageClient.ts' @@ -43,6 +44,7 @@ export default function Mountaintops() { const [unit, setUnit] = useState('sats') const [review, setReview] = useState(null) const [receipt, setReceipt] = useState(null) + const [paymentInFlight, setPaymentInFlight] = useState<'send' | 'move' | null>(null) const [history, setHistory] = useState([]) const [searching, setSearching] = useState(false) const [info, setInfo] = useState<{ stage: number; expired: boolean } | null>(null) @@ -60,6 +62,10 @@ export default function Mountaintops() { 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) } } + const runPayment = (kind: 'send' | 'move', task: () => Promise) => run(async () => { + setPaymentInFlight(kind); setReceipt(null) + try { await task() } finally { setPaymentInFlight(null) } + }) const clearWalletSession = () => { setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setReceipt(null); setReview(null); setRecipient(''); setAmount('') @@ -216,7 +222,7 @@ export default function Mountaintops() { // metadata read into a payment failure, or wait for the wallet's mined proof. } - const importMoney = (keyID: string) => void run(async () => { + const importMoney = (keyID: string) => void runPayment('move', async () => { const fresh = await reload() if (unresolvedActions(fresh.records).length) throw new Error('Review the unfinished wallet action before another payment.') const entry = fresh.book.find(x => x.keyID === keyID)! @@ -234,7 +240,7 @@ export default function Mountaintops() { setReview({ recipient: destination, satoshis }); setReceipt(null); setError(''); setMessage('') } catch (error) { setError(error instanceof Error ? error.message : 'Check the recipient and amount.'); setMessage('') } } - const send = () => void run(async () => { + const send = () => void runPayment('send', async () => { if (!review) throw new Error('Review the recipient and amount before sending.') const intent = review const fresh = await reload() @@ -283,7 +289,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.

: <> - + void run(async () => { setError(''); setMessage('') try { @@ -307,9 +313,10 @@ export default function Mountaintops() { } }, true)} /> {receipt && { setReceipt(null); setView('receive') }} onAnother={() => { setReceipt(null); setReview(null); setView('send') }} />} + {paymentInFlight === 'move' &&
} {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} - {(message || error) &&
{message && !searching &&

{message}

}{error &&

{error}

}
} + {((message && !paymentInFlight) || error) &&
{message && !searching && !paymentInFlight &&

{message}

}{error &&

{error}

}
} {view === 'receive' ?
{primary ? card(primary, true) :

Choose a receiving address

Find a new address or choose an active one below. Earlier payments remain yours.

}

Your payments

@@ -328,7 +335,7 @@ export default function Mountaintops() {
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))}
-
: receipt ? null : review ? 0} onBack={() => setReview(null)} onSend={send} /> :
+
: receipt ? null : review ? 0} sending={paymentInFlight === 'send'} phase={message} onBack={() => setReview(null)} onSend={send} /> :

Send BSV

{ event.preventDefault(); reviewPayment() }}> diff --git a/frontend/src/PaymentProgress.tsx b/frontend/src/PaymentProgress.tsx new file mode 100644 index 0000000..7376d51 --- /dev/null +++ b/frontend/src/PaymentProgress.tsx @@ -0,0 +1,15 @@ +type Props = { message: string; moving?: boolean } + +export default function PaymentProgress({ message, moving = false }: Props) { + const phase = message === 'Finishing with your wallet…' ? 'Review the request in your wallet.' + : message === 'Sending payment…' ? 'Submitting to your wallet…' + : ['Checking your payment…', 'Updating your payments…'].includes(message) ? message + : 'Preparing your payment…' + return
+ +

{moving ? 'Moving to your wallet' : 'Sending your payment'}

{phase}

Approve in your wallet if prompted.

+
+} diff --git a/frontend/src/PaymentReview.tsx b/frontend/src/PaymentReview.tsx index 8fc7647..a07bd6d 100644 --- a/frontend/src/PaymentReview.tsx +++ b/frontend/src/PaymentReview.tsx @@ -1,17 +1,18 @@ import { useEffect, useRef } from 'react' import { bsvAmount } from './paymentAmount.ts' +import PaymentProgress from './PaymentProgress.tsx' export type PaymentDraft = { recipient: string; satoshis: number } -export default function PaymentReview({ payment, busy, onBack, onSend }: { payment: PaymentDraft; busy: boolean; onBack: () => void; onSend: () => void }) { +export default function PaymentReview({ payment, busy, sending, phase, onBack, onSend }: { payment: PaymentDraft; busy: boolean; sending: boolean; phase: string; onBack: () => void; onSend: () => void }) { const heading = useRef(null) useEffect(() => { heading.current?.focus() }, []) return
-

Review payment

+ {sending ? :

Review payment

}

{payment.satoshis.toLocaleString()} sats

{bsvAmount(payment.satoshis)} BSV

To{payment.recipient}

Wallet and network fees are additional.

-
+
} diff --git a/frontend/src/style.css b/frontend/src/style.css index 2406f86..f8977dc 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -39,6 +39,18 @@ .review-recipient{border-top:1px solid #344b55;padding-top:22px} .review-actions .accent{flex:1} .review-fees{margin-top:24px} +.payment-progress{display:flex;align-items:center;gap:18px;padding-bottom:24px;margin-bottom:24px;border-bottom:1px solid #35554e;text-align:left} +.payment-motion{position:relative;display:grid;place-items:center;flex:0 0 64px;width:64px;height:64px;color:#bce9d7;background:#22463e;border-radius:50%} +.payment-motion svg{width:34px;height:34px;animation:payment-flight 2.4s ease-in-out infinite} +.payment-orbit{position:absolute;inset:0;border:2px solid #aee1cf26;border-top-color:#bce9d7;border-right-color:#bce9d7; border-radius:50%;animation:payment-orbit 1.8s linear infinite} +.payment-progress p{margin:0;line-height:1.5} +.progress-title{font-size:.95rem;font-weight:650;color:#e4f2ed} +.payment-progress .progress-phase{font-size:.82rem;color:#b8d6cd;margin-top:3px} +.payment-progress .progress-hint{font-size:.75rem;color:#a9c1c8;margin-top:6px} +.moving-payment .payment-progress{border:0;padding:0;margin:0} +@keyframes payment-orbit{to{transform:rotate(360deg)}} +@keyframes payment-flight{0%,100%{transform:translate(-1px,1px)}50%{transform:translate(2px,-2px)}} +@media(prefers-reduced-motion:reduce){.payment-orbit,.payment-motion svg{animation:none}} .amount-entry{display:flex;gap:10px;margin:-12px 0 24px} .amount-entry input{min-width:0;font-size:1.45rem;letter-spacing:-.025em} .amount-entry select{width:100px;flex-shrink:0} diff --git a/frontend/test/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs index 7377dcc..5d927bd 100644 --- a/frontend/test/browser/payment-status.mjs +++ b/frontend/test/browser/payment-status.mjs @@ -81,6 +81,26 @@ try { assert.equal(await page.getByRole('button', { name: 'Move to wallet' }).isEnabled(), true) assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + // Progress stays visible through a wallet wait, with no invented percentage. + await connect('hold-submit'); await draft('1000') + await page.getByRole('button', { name: 'Send payment', exact: true }).click() + const progress = page.getByRole('status', { name: 'Payment progress' }) + await progress.getByText('Submitting to your wallet…', { exact: true }).waitFor() + assert.equal(await page.getByRole('button', { name: 'Sending…', exact: true }).isDisabled(), true) + assert.equal(await page.getByRole('region', { name: 'Review payment' }).getByText(destination, { exact: true }).isVisible(), true) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) + assert.equal(await page.locator('.payment-orbit').evaluate(element => getComputedStyle(element).animationName), 'payment-orbit') + await shot('sending') + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + await page.emulateMedia({ reducedMotion: 'reduce' }) + assert.equal(await page.locator('.payment-orbit').evaluate(element => getComputedStyle(element).animationName), 'none') + assert.equal(await page.locator('.payment-motion svg').evaluate(element => getComputedStyle(element).animationName), 'none') + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await page.getByRole('button', { name: 'Complete simulated payment', exact: true }).click() + await receipt.getByText('Payment sent', { exact: true }).waitFor(); await idle() + assert.equal(await progress.count(), 0) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + // Truly unresolved outcomes are distinct; checking cannot create a payment. await connect('pending=unprocessed&payments') await unresolved.getByRole('heading', { name: 'Check your wallet' }).waitFor() @@ -99,6 +119,16 @@ try { assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 0) if (width === 1440) { + await connect('payments&hold-submit') + await page.getByRole('button', { name: 'Move to wallet', exact: true }).click() + await page.getByRole('status', { name: 'Payment progress' }).getByText('Submitting to your wallet…', { exact: true }).waitFor() + await page.getByText('Moving to your wallet', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Complete simulated payment', exact: true }).click() + await receipt.getByText('Moved to your wallet', { exact: true }).waitFor(); await idle() + assert.equal(await page.getByRole('status', { name: 'Payment progress' }).count(), 0) + assert.equal(await page.getByRole('button', { name: 'Move to wallet', exact: true }).count(), 0) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), 1) + // Cancel is checked against fresh wallet history, never a stale button. await connect('pending=nosend') await page.evaluate(() => { window.fixtureBlockRecoveryReads(); window.fixtureSetStatus('unproven') }) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 6a0b478..adf4fae 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -16,6 +16,12 @@ window.fixtureSetNetwork = network => { wallet.getNetwork = async () => ({ network }) } wallet.createAction = async args => { counter.textContent = `Isolated demo · no real funds · ${++actions} simulated actions` + if (args.options?.sendWith && new URL(location.href).searchParams.has('hold-submit')) { + await new Promise(resolve => { + const finish = document.createElement('button'); finish.textContent = 'Complete simulated payment' + finish.onclick = () => { finish.remove(); resolve() }; counter.append(finish) + }) + } const result = await create(args) if (args.options?.sendWith) { submissions++ From 9651f008f934c45b4003349d54353e1423356512 Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:25:39 -0800 Subject: [PATCH 09/13] Copy receiving addresses directly without losing clipboard focus --- frontend/package.json | 3 +- frontend/src/App.tsx | 41 ++++++++++++-- frontend/src/receiveUX.ts | 14 ++++- frontend/src/style.css | 1 + frontend/test/browser/copy-address.mjs | 74 ++++++++++++++++++++++++++ frontend/test/receiveUX.test.mjs | 21 +++++++- frontend/test/ui.html | 5 ++ 7 files changed, 153 insertions(+), 6 deletions(-) create mode 100644 frontend/test/browser/copy-address.mjs diff --git a/frontend/package.json b/frontend/package.json index dfe66e0..a88b411 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,7 +10,8 @@ "lint": "eslint .", "test": "node --test --experimental-strip-types test/*.test.mjs", "preview": "vite preview", - "test:browser": "node test/browser/payment-status.mjs" + "test:browser": "node test/browser/copy-address.mjs && node test/browser/payment-status.mjs", + "test:browser:copy": "node test/browser/copy-address.mjs" }, "dependencies": { "@bsv/sdk": "4.0.0", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index b58eccd..cfd25d3 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -3,7 +3,7 @@ import { PublicKey, WalletClient } from '@bsv/sdk' import { addressMatches, assertReceivable, coverageLabel, lastCoveredStage, stages, type AddressRecord, type Network } from '../../shared/brc234.ts' import { WalletRecords, type RecoveryRecord } from './walletRecords.ts' import { applyExpirations, bookFromRecords, validateAddress } from './addressBook.ts' -import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' +import { AddressCheckRequiredError, assertCopyableAddress, calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' import ReceiveInfo from './ReceiveInfo.tsx' import PaymentStatus from './PaymentStatus.tsx' import PaymentReceipt, { type PaymentReceiptData } from './PaymentReceipt.tsx' @@ -45,6 +45,8 @@ export default function Mountaintops() { const [review, setReview] = useState(null) const [receipt, setReceipt] = useState(null) const [paymentInFlight, setPaymentInFlight] = useState<'send' | 'move' | null>(null) + const [copiedAddress, setCopiedAddress] = useState(null) + const [manualCopyAddress, setManualCopyAddress] = useState(null) const [history, setHistory] = useState([]) const [searching, setSearching] = useState(false) const [info, setInfo] = useState<{ stage: number; expired: boolean } | null>(null) @@ -55,6 +57,11 @@ export default function Mountaintops() { current.current = session useEffect(() => () => { worker.current?.terminate() }, []) + useEffect(() => { + if (!copiedAddress) return + const timer = setTimeout(() => setCopiedAddress(null), 2000) + return () => clearTimeout(timer) + }, [copiedAddress]) const run = async (task: () => Promise, quiet = false) => { if (operation.current) return operation.current = true; setBusy(true) @@ -68,6 +75,7 @@ export default function Mountaintops() { }) const clearWalletSession = () => { + setCopiedAddress(null); setManualCopyAddress(null) setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setReceipt(null); setReview(null); setRecipient(''); setAmount('') } @@ -189,6 +197,31 @@ export default function Mountaintops() { setSession({ ...fresh, primary: keyID }); setError(''); setMessage('Receiving address changed. Switching is free.') } catch (e) { setError(e instanceof Error ? e.message : 'Address unavailable') } } + const copyAddress = (displayed: AddressRecord) => { + const fresh = current.current + if (!fresh) return + const entry = fresh.book.find(item => item.keyID === displayed.keyID && item.address === displayed.address) + try { + if (!entry) throw new Error('Address changed. Choose the current receiving address.') + assertCopyableAddress(entry, fresh.coverage, fresh.receivingBlocked) + } catch (error) { + if (error instanceof AddressCheckRequiredError && !operation.current) { + void run(async () => { await reload(); setMessage('Address checked. Click Copy address to copy it.') }) + } else { setMessage(''); setError(error instanceof AddressCheckRequiredError ? 'Address status is updating. Copy it when the check finishes.' : error instanceof Error ? error.message : 'Address unavailable.') } + return + } + const manualCopy = () => { + setCopiedAddress(null); setManualCopyAddress(entry.address) + const node = document.getElementById(`address-${entry.keyID}`) + if (node) { const range = document.createRange(); range.selectNodeContents(node); const selection = window.getSelection(); selection?.removeAllRanges(); selection?.addRange(range) } + } + setError(''); setMessage(''); setManualCopyAddress(null) + try { + // Start the clipboard write directly in the click, before any await/RPC. + if (!navigator.clipboard?.writeText) { manualCopy(); return } + void navigator.clipboard.writeText(entry.address).then(() => setCopiedAddress(entry.address), manualCopy) + } catch { manualCopy() } + } 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 })) @@ -272,14 +305,16 @@ export default function Mountaintops() { const expiration = entry.retiredAt ? 'Expired — do not send here' : pendingExpiry ? 'Expiration pending — stop sharing' : entry.network !== 'mainnet' ? 'No testnet expiration schedule' : expirationEstimate(level, calendar).replace(/^Not earlier than /, 'Estimated expiry: ') return

{name}

{entry.retiredAt ? 'Expired' : pendingExpiry ? 'Expiring' : 'Active'}
- {entry.address} + {entry.address}

{expiration}

{entry.network === 'mainnet' && }
{entry.retiredAt &&

Receiving is disabled. You can still move earlier payments to your wallet.

} {pendingExpiry &&

Stop sharing this address. The chain-time notice ends {new Date(pending.deadline * 1000).toISOString().replace('.000Z', ' UTC')}; expiration begins in the following accepted block.

}
- {!entry.retiredAt && } + {!entry.retiredAt && } {!entry.retiredAt && !selected && }
+ {copiedAddress === entry.address && Address copied.} + {manualCopyAddress === entry.address &&

Automatic copy is unavailable. Select the address above and use your browser’s Copy command.

} {!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.
{paymentHold &&

{paymentHold}

}}}
Address details

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

{!entry.retiredAt && !pendingExpiry && entry.network === 'mainnet' && longest > 0 &&

{level === longest ? 'Longest coverage of your saved addresses.' : 'Expires earlier than your longest-lasting saved address.'}

}{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.

}
diff --git a/frontend/src/receiveUX.ts b/frontend/src/receiveUX.ts index 2fb0aa3..0d40b7f 100644 --- a/frontend/src/receiveUX.ts +++ b/frontend/src/receiveUX.ts @@ -1,7 +1,19 @@ -import { ANCHOR_HEIGHT, NOTICE_SECONDS, assertReceivable, eligibilityTime, lastCoveredStage, type AddressRecord } from '../../shared/brc234.ts' +import { ANCHOR_HEIGHT, NOTICE_SECONDS, addressMatches, assertReceivable, eligibilityTime, lastCoveredStage, type AddressRecord } from '../../shared/brc234.ts' import type { Coverage } from './coverageClient.ts' const BLOCK_SECONDS = 600 +export class AddressCheckRequiredError extends Error {} + +// Copy uses the already validated snapshot, without awaiting wallet calls and +// losing the click's focused clipboard context. Stale snapshots need a separate +// refresh and a new explicit copy click; never copy later in the background. +export function assertCopyableAddress(entry: AddressRecord, coverage: Coverage, receivingBlocked: string | null, now = Date.now()): void { + if (receivingBlocked) throw new Error(receivingBlocked) + if (entry.network !== coverage.network) throw new Error('Wallet network changed. Reconnect before copying an address.') + assertReceivable(entry, coverage.stage) + if (entry.network === 'mainnet' && coverage.state?.pending && !addressMatches(entry.address, coverage.state.pending.target)) throw new Error('This address is expiring. Choose a longer-lasting address.') + if (!Number.isFinite(coverage.checkedAt) || now < coverage.checkedAt || now - coverage.checkedAt > 90_000) throw new AddressCheckRequiredError('Address status needs a fresh check.') +} export type CalendarEstimate = { anchor: number; projectedAnchor: boolean } // Presentation only. Estimated dates/heights must never activate a stage, diff --git a/frontend/src/style.css b/frontend/src/style.css index f8977dc..74521ce 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -17,6 +17,7 @@ .payment-status-details p{font-size:.82rem} .payment-status-details .transaction{margin-bottom:8px} .received-label{font-size:.75rem;font-weight:600;color:#b3e2cd} +.copy-feedback{display:block;margin-top:9px;color:#b3e2cd} .payment-hold{margin-bottom:0} .expiry-summary{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:12px 0} .expiry-summary p{margin:0} diff --git a/frontend/test/browser/copy-address.mjs b/frontend/test/browser/copy-address.mjs new file mode 100644 index 0000000..670199a --- /dev/null +++ b/frontend/test/browser/copy-address.mjs @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict' +import path from 'node:path' +import { mkdir } from 'node:fs/promises' +import { createServer } from 'vite' +import { chromium } from 'playwright' + +const root = path.resolve(import.meta.dirname, '../..') +const evidence = process.env.COPY_ADDRESS_EVIDENCE +if (evidence) await mkdir(evidence, { recursive: true }) +const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 } }) +await server.listen() +const origin = `http://127.0.0.1:${server.httpServer.address().port}` +const browser = await chromium.launch({ headless: true }) +try { + for (const width of [1440, 390, 320]) { + const context = await browser.newContext({ viewport: { width, height: 1000 }, permissions: ['clipboard-read', 'clipboard-write'], serviceWorkers: 'block' }) + const page = await context.newPage(), errors = [], external = [] + page.on('pageerror', error => errors.push(error.message)) + await context.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue() + external.push(route.request().url()); return route.abort() + }) + await page.addInitScript(() => { + const write = navigator.clipboard.writeText.bind(navigator.clipboard) + window.copyCalls = [] + Object.defineProperty(navigator.clipboard, 'writeText', { value: text => { + window.copyCalls.push({ text, active: navigator.userActivation.isActive, focused: document.hasFocus() }) + return new URL(location.href).searchParams.has('deny-copy') ? Promise.reject(new DOMException('Document is not focused.', 'NotAllowedError')) : write(text) + } }) + }) + const idle = () => page.waitForFunction(() => document.querySelector('main')?.getAttribute('aria-busy') === 'false') + const connect = async query => { + await page.goto(`${origin}/test/ui.html?${query}`); await page.bringToFront() + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click(); await idle() + } + try { + await connect('') + const address = await page.locator('.selected .address').innerText() + await page.evaluate(() => window.fixtureBlockCopyReads()) + await page.getByRole('button', { name: 'Copy address', exact: true }).click() + await page.getByText('Address copied.', { exact: true }).waitFor() + assert.deepEqual(await page.evaluate(() => window.copyCalls), [{ text: address, active: true, focused: true }]) + assert.equal(await page.evaluate(() => navigator.clipboard.readText()), address) + assert.equal(await page.getByRole('button', { name: 'Copy address', exact: true }).innerText(), 'Copied!') + assert.equal(await page.getByRole('alert').count(), 0) + if (evidence) await page.screenshot({ path: path.join(evidence, `copied-${width}.png`), fullPage: true }) + + await connect('deny-copy') + await page.evaluate(() => window.fixtureBlockCopyReads()) + await page.getByRole('button', { name: 'Copy address', exact: true }).click() + await page.getByText('Automatic copy is unavailable.', { exact: false }).waitFor() + assert.equal(await page.evaluate(() => window.getSelection().toString()), address) + assert.equal(await page.getByText('Address copied.', { exact: true }).count(), 0) + assert.equal(await page.getByRole('alert').count(), 0) + if (evidence) await page.screenshot({ path: path.join(evidence, `manual-copy-${width}.png`), fullPage: true }) + + if (width === 1440) { + await connect('') + await page.clock.setFixedTime(new Date(Date.now() + 120000)) + await page.getByRole('button', { name: 'Copy address', exact: true }).click(); await idle() + await page.getByText('Address checked. Click Copy address to copy it.', { exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.copyCalls.length), 0, 'stale refresh never writes the clipboard after the click') + await page.getByRole('button', { name: 'Copy address', exact: true }).click() + await page.getByText('Address copied.', { exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.copyCalls.length), 1) + await page.clock.setFixedTime(new Date()) + await connect('expired') + assert.equal(await page.getByRole('button', { name: 'Copy address', exact: true }).count(), 0) + } + assert.deepEqual(errors, []); assert.deepEqual(external, []) + console.log(`PASS ${width}px: focused direct clipboard copy with blocked RPCs, manual fallback; no external requests`) + } finally { await context.close() } + } +} finally { await browser.close(); await server.close() } diff --git a/frontend/test/receiveUX.test.mjs b/frontend/test/receiveUX.test.mjs index 31edcf7..2131518 100644 --- a/frontend/test/receiveUX.test.mjs +++ b/frontend/test/receiveUX.test.mjs @@ -1,12 +1,31 @@ import assert from 'node:assert/strict' import test from 'node:test' import { ANCHOR_HEIGHT, NOTICE_SECONDS, eligibilityTime, assertReceivable } from '../../shared/brc234.ts' -import { calendarEstimate, stageEstimate, expirationEstimate, monthYear, receivingKeyID } from '../src/receiveUX.ts' +import { AddressCheckRequiredError, assertCopyableAddress, calendarEstimate, stageEstimate, expirationEstimate, monthYear, receivingKeyID } from '../src/receiveUX.ts' import { readCoverage } from '../src/coverageClient.ts' const anchor = Date.parse('2030-08-31T12:34:56Z') / 1000 const coverage = { network: 'mainnet', height: ANCHOR_HEIGHT - 144, anchorMtp: null, tipMtp: anchor - 86400 } +test('copy uses a bounded fresh eligibility snapshot and requires a new click after stale or invalid time', () => { + const entry = { keyID: '1', address: '1Ktest', network: 'mainnet', retiredAt: null } + const snapshot = { ...coverage, stage: 0, checkedAt: 100000, state: null } + assert.doesNotThrow(() => assertCopyableAddress(entry, snapshot, null, 100000)) + assert.doesNotThrow(() => assertCopyableAddress(entry, snapshot, null, 190000)) + for (const now of [190001, 99999]) assert.throws(() => assertCopyableAddress(entry, snapshot, null, now), AddressCheckRequiredError) + assert.throws(() => assertCopyableAddress(entry, { ...snapshot, checkedAt: NaN }, null, 100000), AddressCheckRequiredError) +}) + +test('copy never bypasses retirement, active/pending exclusion, blocked receiving or the network boundary', () => { + const entry = { keyID: '1', address: '1Ktest', network: 'mainnet', retiredAt: null } + const snapshot = { ...coverage, stage: 0, checkedAt: 100000, state: null } + assert.throws(() => assertCopyableAddress({ ...entry, retiredAt: { height: 1000002 } }, snapshot, null, 100000), /Expired/) + assert.throws(() => assertCopyableAddress(entry, { ...snapshot, stage: 1 }, null, 100000), /Expired/) + assert.throws(() => assertCopyableAddress(entry, { ...snapshot, state: { pending: { target: 1 } } }, null, 100000), /expiring/) + assert.throws(() => assertCopyableAddress(entry, snapshot, 'Receiving blocked', 100000), /Receiving blocked/) + assert.throws(() => assertCopyableAddress(entry, { ...snapshot, network: 'testnet' }, null, 100000), /network changed/) +}) + test('pre-anchor estimates project from validated chain time, including the notice round and following block', () => { const calendar = calendarEstimate(coverage) assert.deepEqual(calendar, { anchor, projectedAnchor: true }) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index adf4fae..587d965 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -14,6 +14,11 @@ let submissions = 0 window.fixtureSubmissionCount = () => submissions window.fixtureSetNetwork = network => { wallet.getNetwork = async () => ({ network }) } +window.fixtureBlockCopyReads = () => { + const blocked = async () => { throw new Error('Copy triggered a wallet or chain read') } + wallet.getPublicKey = wallet.getNetwork = wallet.listOutputs = wallet.listActions = blocked + window.fetch = blocked +} wallet.createAction = async args => { counter.textContent = `Isolated demo · no real funds · ${++actions} simulated actions` if (args.options?.sendWith && new URL(location.href).searchParams.has('hold-submit')) { From 766016c8a42d959392d21f64222813b72663ae21 Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:44:59 -0800 Subject: [PATCH 10/13] Show animated progress while refreshing payments and addresses --- frontend/package.json | 5 +- frontend/src/App.tsx | 34 +++++--- frontend/src/RefreshProgress.tsx | 13 +++ frontend/src/style.css | 10 +++ frontend/test/browser/refresh-payments.mjs | 94 ++++++++++++++++++++++ frontend/test/ui.html | 17 ++++ 6 files changed, 159 insertions(+), 14 deletions(-) create mode 100644 frontend/src/RefreshProgress.tsx create mode 100644 frontend/test/browser/refresh-payments.mjs diff --git a/frontend/package.json b/frontend/package.json index a88b411..4f26b29 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,8 +10,9 @@ "lint": "eslint .", "test": "node --test --experimental-strip-types test/*.test.mjs", "preview": "vite preview", - "test:browser": "node test/browser/copy-address.mjs && node test/browser/payment-status.mjs", - "test:browser:copy": "node test/browser/copy-address.mjs" + "test:browser": "node test/browser/copy-address.mjs && node test/browser/refresh-payments.mjs && node test/browser/payment-status.mjs", + "test:browser:copy": "node test/browser/copy-address.mjs", + "test:browser:refresh": "node test/browser/refresh-payments.mjs" }, "dependencies": { "@bsv/sdk": "4.0.0", diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index cfd25d3..8339ca0 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -8,6 +8,7 @@ import ReceiveInfo from './ReceiveInfo.tsx' import PaymentStatus from './PaymentStatus.tsx' import PaymentReceipt, { type PaymentReceiptData } from './PaymentReceipt.tsx' import PaymentProgress from './PaymentProgress.tsx' +import RefreshProgress, { RefreshButton, type RefreshState } from './RefreshProgress.tsx' import PaymentReview, { type PaymentDraft } from './PaymentReview.tsx' import { bsvAmount, parseAmount, type AmountUnit } from './paymentAmount.ts' import { readCoverage, type Coverage } from './coverageClient.ts' @@ -45,6 +46,7 @@ export default function Mountaintops() { const [review, setReview] = useState(null) const [receipt, setReceipt] = useState(null) const [paymentInFlight, setPaymentInFlight] = useState<'send' | 'move' | null>(null) + const [refreshing, setRefreshing] = useState(null) const [copiedAddress, setCopiedAddress] = useState(null) const [manualCopyAddress, setManualCopyAddress] = useState(null) const [history, setHistory] = useState([]) @@ -73,6 +75,11 @@ export default function Mountaintops() { setPaymentInFlight(kind); setReceipt(null) try { await task() } finally { setPaymentInFlight(null) } }) + const runRefresh = (kind: RefreshState['kind'], keyID: string | undefined, task: () => Promise) => run(async () => { + setRefreshing({ kind, keyID, detail: 'Checking your wallet…' }) + try { await task() } finally { setRefreshing(null) } + }) + const refreshDetail = (detail: string) => setRefreshing(previous => previous ? { ...previous, detail } : null) const clearWalletSession = () => { setCopiedAddress(null); setManualCopyAddress(null) @@ -206,7 +213,7 @@ export default function Mountaintops() { assertCopyableAddress(entry, fresh.coverage, fresh.receivingBlocked) } catch (error) { if (error instanceof AddressCheckRequiredError && !operation.current) { - void run(async () => { await reload(); setMessage('Address checked. Click Copy address to copy it.') }) + void runRefresh('addresses', undefined, async () => { await reload(); setMessage('Address checked. Click Copy address to copy it.') }) } else { setMessage(''); setError(error instanceof AddressCheckRequiredError ? 'Address status is updating. Copy it when the check finishes.' : error instanceof Error ? error.message : 'Address unavailable.') } return } @@ -222,22 +229,24 @@ export default function Mountaintops() { void navigator.clipboard.writeText(entry.address).then(() => setCopiedAddress(entry.address), manualCopy) } catch { manualCopy() } } - const checkCoins = (keyID: string) => void run(async () => { + const checkCoins = (keyID: string) => void runRefresh('single', keyID, async () => { const fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID)! setCheckedPayments(x => ({ ...x, [keyID]: false })) + refreshDetail('Checking this address for new payments…') const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) - setBalances(x => ({ ...x, [keyID]: coins })); setCheckedPayments(x => ({ ...x, [keyID]: true })); await reload(fresh) + setBalances(x => ({ ...x, [keyID]: coins })); setCheckedPayments(x => ({ ...x, [keyID]: true })); refreshDetail('Finishing refresh…'); await reload(fresh) setMessage('Payments checked for this address.') }) - const checkAllCoins = () => void run(async () => { + const checkAllCoins = () => void runRefresh('payments', undefined, async () => { const fresh = await reload() - for (const entry of fresh.book) { + for (const [index, entry] of fresh.book.entries()) { + refreshDetail(`${index} of ${fresh.book.length} addresses checked`) 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.') + refreshDetail('Finishing refresh…'); await reload(fresh); setMessage('Payments checked.') }) const finishPayment = async (fresh: Session, task: () => Promise, details: Omit, onAccepted: () => void) => { let submitted: string @@ -315,7 +324,7 @@ export default function Mountaintops() { {copiedAddress === entry.address && Address copied.} {manualCopyAddress === entry.address &&

Automatic copy is unavailable. Select the address above and use your browser’s Copy command.

} - {!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'}}
+ {!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'}}
checkCoins(entry.keyID)} label={entry.retiredAt ? 'Check earlier payments' : total === undefined ? 'Check for payments' : 'Refresh'} />
{Boolean(coins?.length) && <>
Wallet fees apply.
{paymentHold &&

{paymentHold}

}}}
Address details

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

{!entry.retiredAt && !pendingExpiry && entry.network === 'mainnet' && longest > 0 &&

{level === longest ? 'Longest coverage of your saved addresses.' : 'Expires earlier than your longest-lasting saved address.'}

}{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.

}
@@ -349,16 +358,17 @@ export default function Mountaintops() { }, true)} /> {receipt && { setReceipt(null); setView('receive') }} onAnother={() => { setReceipt(null); setReview(null); setView('send') }} />} {paymentInFlight === 'move' &&
} + {refreshing && } {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} - {((message && !paymentInFlight) || error) &&
{message && !searching && !paymentInFlight &&

{message}

}{error &&

{error}

}
} + {((message && !paymentInFlight && !refreshing) || error) &&
{message && !searching && !paymentInFlight && !refreshing &&

{message}

}{error &&

{error}

}
} {view === 'receive' ?
{primary ? card(primary, true) :

Choose a receiving address

Find a new address or choose an active one below. Earlier payments remain yours.

} -

Your payments

- {checkedCount > 0 && !allPaymentsChecked ?

{checkedCount} of {session.book.length} addresses checked for new payments.

: session.book.some(x => balances[x.keyID] === undefined) &&

Some payments still need checking.

} +

Your payments

+ {!refreshing && (checkedCount > 0 && !allPaymentsChecked ?

{checkedCount} of {session.book.length} addresses checked for new payments.

: session.book.some(x => balances[x.keyID] === undefined) &&

Some payments still need checking.

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

{paymentHold}

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

No available payments found.

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

No available payments found.

}
{suggestedEntry ? 'Use a longer-lasting address' : 'Find a longer-lasting address'}

{suggestedEntry ? 'Already saved. Free to switch.' : 'Searching is free. Saving an address has wallet fees.'}

{searching ? : }
{suggestedEntry &&

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

Estimated · stage {lastCoveredStage(suggestedEntry.address)}
} @@ -369,7 +379,7 @@ export default function Mountaintops() { {!searching && savedSearches.map(search =>

Saved in your wallet · next key ID {String(search.next)}

)}
-
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))}
+
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))} void runRefresh('addresses', undefined, async () => { await reload(); setMessage('Addresses and expiration checked.') })} />
: receipt ? null : review ? 0} sending={paymentInFlight === 'send'} phase={message} onBack={() => setReview(null)} onSend={send} /> :

Send BSV

{ event.preventDefault(); reviewPayment() }}> diff --git a/frontend/src/RefreshProgress.tsx b/frontend/src/RefreshProgress.tsx new file mode 100644 index 0000000..94dbe38 --- /dev/null +++ b/frontend/src/RefreshProgress.tsx @@ -0,0 +1,13 @@ +export type RefreshState = { kind: 'payments' | 'single' | 'addresses'; keyID?: string; detail: string } + +export function RefreshIcon({ spinning = false }: { spinning?: boolean }) { + return +} + +export function RefreshButton({ active, disabled, label, ariaLabel, onClick }: { active: boolean; disabled: boolean; label: string; ariaLabel?: string; onClick: () => void }) { + return +} + +export default function RefreshProgress({ progress }: { progress: RefreshState }) { + return

{progress.kind === 'addresses' ? 'Checking your addresses' : 'Checking for payments'}

{progress.detail}

+} diff --git a/frontend/src/style.css b/frontend/src/style.css index 74521ce..6f0920c 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -18,6 +18,16 @@ .payment-status-details .transaction{margin-bottom:8px} .received-label{font-size:.75rem;font-weight:600;color:#b3e2cd} .copy-feedback{display:block;margin-top:9px;color:#b3e2cd} +.refresh-icon{display:block;width:18px;height:18px;flex-shrink:0} +.refresh-icon.is-spinning{animation:payment-orbit 1.3s linear infinite} +.refresh-button{display:inline-flex;align-items:center;justify-content:center;gap:8px} +.refresh-button[aria-busy=true]:disabled{opacity:1;background:#23453f;border-color:#77b5a1;color:#d5efe5;cursor:progress} +.refresh-progress{display:flex;align-items:center;gap:14px;padding:18px 22px;border-color:#416e5d;box-shadow:none} +.refresh-mark{display:grid;place-items:center;width:44px;height:44px;flex:0 0 44px;border-radius:50%;background:#22463e;color:#bce9d7} +.refresh-mark .refresh-icon{width:24px;height:24px} +.refresh-progress p{margin:0;line-height:1.5} +.refresh-progress .progress-phase{font-size:.82rem;color:#b8d6cd;margin-top:3px} +@media(prefers-reduced-motion:reduce){.refresh-icon.is-spinning{animation:none}} .payment-hold{margin-bottom:0} .expiry-summary{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:12px 0} .expiry-summary p{margin:0} diff --git a/frontend/test/browser/refresh-payments.mjs b/frontend/test/browser/refresh-payments.mjs new file mode 100644 index 0000000..eb7a364 --- /dev/null +++ b/frontend/test/browser/refresh-payments.mjs @@ -0,0 +1,94 @@ +import assert from 'node:assert/strict' +import path from 'node:path' +import { mkdir } from 'node:fs/promises' +import { createServer } from 'vite' +import { chromium } from 'playwright' + +const root = path.resolve(import.meta.dirname, '../..') +const evidence = process.env.REFRESH_EVIDENCE +if (evidence) await mkdir(evidence, { recursive: true }) +const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 } }) +await server.listen() +const origin = `http://127.0.0.1:${server.httpServer.address().port}` +const browser = await chromium.launch({ headless: true }) +try { + for (const width of [1440, 390, 320]) { + const context = await browser.newContext({ viewport: { width, height: 1000 }, permissions: ['clipboard-write'], serviceWorkers: 'block' }) + const page = await context.newPage(), errors = [], external = [] + page.on('pageerror', error => errors.push(error.message)) + await context.route('**/*', route => { + if (new URL(route.request().url()).origin === origin) return route.continue() + external.push(route.request().url()); return route.abort() + }) + const idle = () => page.waitForFunction(() => document.querySelector('main')?.getAttribute('aria-busy') === 'false') + let baselineSubmissions = 0 + const connect = async extra => { + await page.goto(`${origin}/test/ui.html?saved&payments&hold-refresh&${extra}`); await page.bringToFront() + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click(); await idle() + baselineSubmissions = await page.evaluate(() => window.fixtureSubmissionCount()) + } + const progress = page.getByRole('status', { name: 'Refresh progress' }) + const refresh = page.getByRole('button', { name: 'Refresh payments', exact: true }) + const amounts = () => page.locator('.payments-panel .payment-row strong').allTextContents() + try { + await connect('') + const before = await amounts() + await page.evaluate(() => { const button = document.querySelector('[aria-label="Refresh payments"]'); button.click(); button.click() }) + await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).waitFor() + await progress.getByText('0 of 2 addresses checked', { exact: true }).waitFor() + assert.equal(await refresh.innerText(), 'Refreshing…') + assert.equal(await refresh.getAttribute('aria-busy'), 'true') + assert.equal(await refresh.evaluate(element => getComputedStyle(element).opacity), '1') + assert.equal(await progress.locator('svg').evaluate(element => getComputedStyle(element).animationName), 'payment-orbit') + assert.deepEqual(await amounts(), before, 'refresh keeps existing balances visible') + assert.equal(await page.evaluate(() => window.fixtureRefreshReads()), 1, 'two clicks still start one refresh') + await page.getByRole('button', { name: 'Copy address', exact: true }).first().click() + await page.getByText('Address copied.', { exact: true }).waitFor() + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + if (evidence) await page.screenshot({ path: path.join(evidence, `refreshing-${width}.png`), fullPage: true }) + await page.emulateMedia({ reducedMotion: 'reduce' }) + assert.equal(await progress.locator('svg').evaluate(element => getComputedStyle(element).animationName), 'none') + await page.emulateMedia({ reducedMotion: 'no-preference' }) + await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).click(); await idle() + assert.equal(await progress.count(), 0) + assert.equal(await refresh.innerText(), 'Refresh') + assert.equal(await refresh.isEnabled(), true) + assert.equal(await page.evaluate(() => window.fixtureRefreshReads()), 2) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), baselineSubmissions) + await page.getByText('Payments checked.', { exact: true }).waitFor() + + await connect('refresh-error') + const retained = await amounts() + await refresh.click(); await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).waitFor() + await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).click(); await idle() + assert.equal(await progress.count(), 0) + assert.equal(await refresh.isEnabled(), true) + assert.deepEqual(await amounts(), retained, 'failed refresh cannot erase restored funds') + assert.equal(await page.getByRole('alert').count(), 1) + assert.equal(await page.getByText('Payments checked.', { exact: true }).count(), 0) + assert.equal(await page.evaluate(() => window.fixtureSubmissionCount()), baselineSubmissions) + + if (width === 1440) { + await connect('') + await page.locator('.address-list > summary').click() + const single = page.locator('.address-list .address-card').getByRole('button', { name: 'Refresh', exact: true }) + await single.click(); await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).waitFor() + await progress.getByText('Checking this address for new payments…', { exact: true }).waitFor() + assert.equal(await single.innerText(), 'Refreshing…') + await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).click(); await idle() + assert.equal(await progress.count(), 0) + assert.equal(await page.evaluate(() => window.fixtureRefreshReads()), 1) + await page.evaluate(() => window.fixtureHoldNextRefresh('addresses')) + const addresses = page.getByRole('button', { name: 'Refresh addresses', exact: true }) + await addresses.click(); await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).waitFor() + await progress.getByText('Checking your addresses', { exact: true }).waitFor() + assert.equal(await addresses.innerText(), 'Refreshing…') + await page.getByRole('button', { name: 'Complete simulated refresh', exact: true }).click(); await idle() + assert.equal(await progress.count(), 0) + assert.equal(await addresses.isEnabled(), true) + } + assert.deepEqual(errors, []); assert.deepEqual(external, []) + console.log(`PASS ${width}px: visible refresh progress, preserved balances/copy, reduced motion, success/failure cleanup; no external requests`) + } finally { await context.close() } + } +} finally { await browser.close(); await server.close() } diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 587d965..ba3e06a 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -41,8 +41,25 @@ } return result } +let holdRefresh = new URL(location.href).searchParams.has('hold-refresh') ? 'payments' : null +let refreshReads = 0 +window.fixtureRefreshReads = () => refreshReads +window.fixtureHoldNextRefresh = kind => { holdRefresh = kind } +const pauseRefresh = async kind => { + if (holdRefresh !== kind) return + holdRefresh = null + await new Promise(resolve => { + const finish = document.createElement('button'); finish.textContent = 'Complete simulated refresh' + finish.onclick = () => { finish.remove(); resolve() }; counter.append(finish) + }) +} window.fetch = async (input) => { const url = String(input) + if (url.includes('/unspent/all')) { + refreshReads++; await pauseRefresh('payments') + if (new URL(location.href).searchParams.has('refresh-error')) return new Response('', { status: 400 }) + } + if (url.includes('/chain/info')) await pauseRefresh('addresses') 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 }) From 6c314a673bb803064e27e633c2340e7fdf0c639c Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:56:45 -0800 Subject: [PATCH 11/13] Give every asynchronous wallet action consistent activity feedback --- .github/workflows/ci.yml | 21 +++++ frontend/package.json | 3 +- frontend/src/ActionFeedback.tsx | 11 +++ frontend/src/App.tsx | 72 +++++++++------- frontend/src/PaymentReview.tsx | 3 +- frontend/src/PaymentStatus.tsx | 7 +- frontend/src/RefreshProgress.tsx | 3 +- frontend/src/style.css | 11 ++- frontend/test/browser/all-actions.mjs | 116 ++++++++++++++++++++++++++ frontend/test/ui.html | 44 ++++++++++ 10 files changed, 251 insertions(+), 40 deletions(-) create mode 100644 frontend/src/ActionFeedback.tsx create mode 100644 frontend/test/browser/all-actions.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 41ec070..9d2ffd1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -25,3 +25,24 @@ jobs: - run: npx playwright install --with-deps chromium - run: npm run test:browser - run: npm audit --omit=dev --audit-level=moderate + qualification-image: + needs: client + runs-on: ubuntu-latest + env: + SOURCE_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha || github.sha }} + - name: Build committed Linux qualification image + run: | + docker build --platform linux/amd64 --build-arg SOURCE_REVISION="$SOURCE_SHA" -f ops/canary.Dockerfile -t "mountaintops-qualification:$SOURCE_SHA" . + docker image inspect "mountaintops-qualification:$SOURCE_SHA" --format '{{.Id}} {{.Architecture}} {{index .Config.Labels "org.opencontainers.image.revision"}}' > qualification-image.txt + docker save "mountaintops-qualification:$SOURCE_SHA" | gzip > qualification-image.tar.gz + sha256sum qualification-image.tar.gz > qualification-image.sha256 + - uses: actions/upload-artifact@v4 + with: + name: mountaintops-qualification-${{ github.event.pull_request.head.sha || github.sha }} + path: qualification-image.* + retention-days: 1 + compression-level: 0 diff --git a/frontend/package.json b/frontend/package.json index 4f26b29..704c0dd 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -10,7 +10,8 @@ "lint": "eslint .", "test": "node --test --experimental-strip-types test/*.test.mjs", "preview": "vite preview", - "test:browser": "node test/browser/copy-address.mjs && node test/browser/refresh-payments.mjs && node test/browser/payment-status.mjs", + "test:browser": "node test/browser/all-actions.mjs && node test/browser/copy-address.mjs && node test/browser/refresh-payments.mjs && node test/browser/payment-status.mjs", + "test:browser:actions": "node test/browser/all-actions.mjs", "test:browser:copy": "node test/browser/copy-address.mjs", "test:browser:refresh": "node test/browser/refresh-payments.mjs" }, diff --git a/frontend/src/ActionFeedback.tsx b/frontend/src/ActionFeedback.tsx new file mode 100644 index 0000000..72feb1f --- /dev/null +++ b/frontend/src/ActionFeedback.tsx @@ -0,0 +1,11 @@ +import type { ReactNode } from 'react' + +export type Activity = { id: string; title: string; detail: string } + +export function ActionButton({ active, disabled = false, label, activeLabel, ariaLabel, variant = 'secondary', icon, onClick }: { active: boolean; disabled?: boolean; label: string; activeLabel: string; ariaLabel?: string; variant?: string; icon?: ReactNode; onClick: () => void }) { + return +} + +export default function ActionFeedback({ activity }: { activity: Activity }) { + return

{activity.title}

{activity.detail}

+} diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 8339ca0..6ec0c96 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -9,6 +9,7 @@ import PaymentStatus from './PaymentStatus.tsx' import PaymentReceipt, { type PaymentReceiptData } from './PaymentReceipt.tsx' import PaymentProgress from './PaymentProgress.tsx' import RefreshProgress, { RefreshButton, type RefreshState } from './RefreshProgress.tsx' +import ActionFeedback, { ActionButton, type Activity } from './ActionFeedback.tsx' import PaymentReview, { type PaymentDraft } from './PaymentReview.tsx' import { bsvAmount, parseAmount, type AmountUnit } from './paymentAmount.ts' import { readCoverage, type Coverage } from './coverageClient.ts' @@ -47,6 +48,9 @@ export default function Mountaintops() { const [receipt, setReceipt] = useState(null) const [paymentInFlight, setPaymentInFlight] = useState<'send' | 'move' | null>(null) const [refreshing, setRefreshing] = useState(null) + const [activity, setActivity] = useState(null) + const [movingKeyID, setMovingKeyID] = useState(null) + const [copyingAddress, setCopyingAddress] = useState(null) const [copiedAddress, setCopiedAddress] = useState(null) const [manualCopyAddress, setManualCopyAddress] = useState(null) const [history, setHistory] = useState([]) @@ -55,6 +59,7 @@ export default function Mountaintops() { const worker = useRef(null) const searchProgress = useRef<{ stage: number; next: string } | null>(null) const operation = useRef(false) + const copying = useRef(false) const current = useRef(null) current.current = session @@ -64,16 +69,16 @@ export default function Mountaintops() { const timer = setTimeout(() => setCopiedAddress(null), 2000) return () => clearTimeout(timer) }, [copiedAddress]) - const run = async (task: () => Promise, quiet = false) => { + const run = async (task: () => Promise, quiet = false, feedback: Activity | null = null) => { if (operation.current) return - operation.current = true; setBusy(true) + operation.current = true; setBusy(true); setActivity(feedback) if (!quiet) { setError(''); setMessage('Working… Check your wallet if prompted.') } 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) } + finally { operation.current = false; setBusy(false); setActivity(null) } } - const runPayment = (kind: 'send' | 'move', task: () => Promise) => run(async () => { - setPaymentInFlight(kind); setReceipt(null) - try { await task() } finally { setPaymentInFlight(null) } + const runPayment = (kind: 'send' | 'move', task: () => Promise, keyID: string | null = null) => run(async () => { + setPaymentInFlight(kind); setMovingKeyID(keyID); setReceipt(null) + try { await task() } finally { setPaymentInFlight(null); setMovingKeyID(null) } }) const runRefresh = (kind: RefreshState['kind'], keyID: string | undefined, task: () => Promise) => run(async () => { setRefreshing({ kind, keyID, detail: 'Checking your wallet…' }) @@ -126,13 +131,13 @@ export default function Mountaintops() { await reload(fresh) if (failure) throw failure setMessage('') - }) + }, false, { id: 'connect', title: 'Connecting your wallet', detail: 'Open your wallet if prompted.' }) // Only chain coverage is rechecked. No background address-deposit polling. useEffect(() => { if (!session) return const timer = setInterval(() => { - if (!operation.current && !worker.current) void run(async () => { await reload() }, true) + if (!operation.current && !worker.current) void run(async () => { await reload(); setMessage('') }, true, { id: 'background', title: 'Updating address status', detail: 'Checking your saved addresses…' }) }, 60_000) return () => clearInterval(timer) // eslint-disable-next-line react-hooks/exhaustive-deps @@ -151,7 +156,7 @@ export default function Mountaintops() { const next = await reload(fresh) setSession({ ...next, primary: receivingKeyID(next.book, next.coverage.stage, result.keyID) }); setCandidate(null) setMessage('New address saved and ready to receive.') - }) + }, false, { id: 'save-address', title: 'Saving your address', detail: 'Approve in your wallet if prompted.' }) } const mine = async (resumeStage?: number) => { @@ -180,12 +185,12 @@ export default function Mountaintops() { setPausedSearch({ stage: data.stage, next: data.next }); setTarget(String(data.stage)) setMessage('No match yet. You can keep searching for free.') } - if (data.kind === 'error') setError(String(data.message)) + if (data.kind === 'error') { setMessage(''); setError(String(data.message)) } } } - nextWorker.onerror = () => { nextWorker.terminate(); worker.current = null; setSearching(false); setError('Address worker failed. Published addresses remain in your wallet.') } + nextWorker.onerror = () => { nextWorker.terminate(); worker.current = null; setSearching(false); setMessage(''); setError('Address worker failed. Published addresses remain in your wallet.') } nextWorker.postMessage({ identityKey: fresh.identity, network: fresh.network, minimumStage: minimum, targetStage: chosen, start: resume ?? '1' }) - }) + }, false, { id: 'search', title: 'Preparing address search', detail: 'Checking your wallet and address rules…' }) } const cancelMine = () => { @@ -205,6 +210,7 @@ export default function Mountaintops() { } catch (e) { setError(e instanceof Error ? e.message : 'Address unavailable') } } const copyAddress = (displayed: AddressRecord) => { + if (copying.current) return const fresh = current.current if (!fresh) return const entry = fresh.book.find(item => item.keyID === displayed.keyID && item.address === displayed.address) @@ -226,8 +232,9 @@ export default function Mountaintops() { try { // Start the clipboard write directly in the click, before any await/RPC. if (!navigator.clipboard?.writeText) { manualCopy(); return } - void navigator.clipboard.writeText(entry.address).then(() => setCopiedAddress(entry.address), manualCopy) - } catch { manualCopy() } + copying.current = true; setCopyingAddress(entry.address) + void navigator.clipboard.writeText(entry.address).then(() => setCopiedAddress(entry.address), manualCopy).finally(() => { copying.current = false; setCopyingAddress(null) }) + } catch { copying.current = false; setCopyingAddress(null); manualCopy() } } const checkCoins = (keyID: string) => void runRefresh('single', keyID, async () => { const fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID)! @@ -272,7 +279,7 @@ export default function Mountaintops() { await finishPayment(fresh, () => importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage), { kind: 'move' }, () => { setBalances(values => ({ ...values, [keyID]: (values[keyID] ?? []).filter(coin => !coins.some(spent => spent.txid === coin.txid && spent.vout === coin.vout)) })) }) - }) + }, keyID) const reviewPayment = () => { if (!session || disabled || unresolvedActions(session.records).length) return try { @@ -319,22 +326,25 @@ export default function Mountaintops() { {entry.retiredAt &&

Receiving is disabled. You can still move earlier payments to your wallet.

} {pendingExpiry &&

Stop sharing this address. The chain-time notice ends {new Date(pending.deadline * 1000).toISOString().replace('.000Z', ' UTC')}; expiration begins in the following accepted block.

}
- {!entry.retiredAt && } + {!entry.retiredAt && copyAddress(entry)} />} {!entry.retiredAt && !selected && }
{copiedAddress === entry.address && Address copied.} {manualCopyAddress === entry.address &&

Automatic copy is unavailable. Select the address above and use your browser’s Copy command.

} {!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'}}
checkCoins(entry.keyID)} label={entry.retiredAt ? 'Check earlier payments' : total === undefined ? 'Check for payments' : 'Refresh'} />
- {Boolean(coins?.length) && <>
Wallet fees apply.
{paymentHold &&

{paymentHold}

}}} + {Boolean(coins?.length) && <>
0} label="Move to wallet" activeLabel="Moving…" onClick={() => importMoney(entry.keyID)} />Wallet fees apply.
{paymentHold &&

{paymentHold}

}}}
Address details

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

{!entry.retiredAt && !pendingExpiry && entry.network === 'mainnet' && longest > 0 &&

{level === longest ? 'Longest coverage of your saved addresses.' : 'Expires earlier than your longest-lasting saved address.'}

}{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.

}
} - return
+ return <> +
{activity ? `${activity.title}. ${activity.detail}` : refreshing ? `${refreshing.kind === 'addresses' ? 'Checking your addresses' : 'Checking for payments'}. ${refreshing.detail}` : paymentInFlight ? message : searching ? `Finding an address. ${message}` : copyingAddress ? 'Copying address…' : ''}
+

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.

: <> + {refreshing ? : activity ? : searching ? : null} + {!session ?

Your BSV, ready to receive.

Connect your wallet to find your addresses and payments.

Use the same BRC-100 wallet on any device.

: <> - void run(async () => { + void run(async () => { setError(''); setMessage('') try { let result = await refreshPaymentStatus(client, session.identity, session.network, session.records, action) @@ -355,28 +365,27 @@ export default function Mountaintops() { if (error instanceof WalletAccountChangedError) clearWalletSession() throw error } - }, true)} /> + }, true, { id: `review-${action.id}`, title: action.state === 'prepared' ? 'Canceling unfinished payment' : 'Checking payment status', detail: 'Reading the latest result from your wallet…' })} /> {receipt && { setReceipt(null); setView('receive') }} onAnother={() => { setReceipt(null); setReview(null); setView('send') }} />} {paymentInFlight === 'move' &&
} - {refreshing && } {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

} - {((message && !paymentInFlight && !refreshing) || error) &&
{message && !searching && !paymentInFlight && !refreshing &&

{message}

}{error &&

{error}

}
} + {((message && !searching && !paymentInFlight && !refreshing && !activity) || error) &&
{message && !searching && !paymentInFlight && !refreshing && !activity &&

{message}

}{error &&

{error}

}
} {view === 'receive' ?
{primary ? card(primary, true) :

Choose a receiving address

Find a new address or choose an active one below. Earlier payments remain yours.

}

Your payments

{!refreshing && (checkedCount > 0 && !allPaymentsChecked ?

{checkedCount} of {session.book.length} addresses checked for new payments.

: session.book.some(x => balances[x.keyID] === undefined) &&

Some payments still need checking.

)} - {session.book.filter(x => balances[x.keyID]?.length).map(entry =>
Received{balances[entry.keyID]!.reduce((sum, coin) => sum + coin.satoshis, 0).toLocaleString()} sats{(session.book.length > 1 || entry.retiredAt) && {entry.keyID === '1' ? 'Original address' : `Address …${entry.address.slice(-6)}`}{entry.retiredAt ? ' · earlier payments' : ''}}
Wallet fees apply
)} + {session.book.filter(x => balances[x.keyID]?.length).map(entry =>
Received{balances[entry.keyID]!.reduce((sum, coin) => sum + coin.satoshis, 0).toLocaleString()} sats{(session.book.length > 1 || entry.retiredAt) && {entry.keyID === '1' ? 'Original address' : `Address …${entry.address.slice(-6)}`}{entry.retiredAt ? ' · earlier payments' : ''}}
0} label="Move to wallet" activeLabel="Moving…" onClick={() => importMoney(entry.keyID)} />Wallet fees apply
)} {paymentHold && session.book.some(x => balances[x.keyID]?.length) &&

{paymentHold}

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

No available payments found.

}
-
{suggestedEntry ? 'Use a longer-lasting address' : 'Find a longer-lasting address'}

{suggestedEntry ? 'Already saved. Free to switch.' : 'Searching is free. Saving an address has wallet fees.'}

{searching ? : }
+
{suggestedEntry ? 'Use a longer-lasting address' : 'Find a longer-lasting address'}

{suggestedEntry ? 'Already saved. Free to switch.' : 'Searching is free. Saving an address has wallet fees.'}

{searching ? : suggestedEntry ? choose(suggestedEntry.keyID) : void mine()} />}
{suggestedEntry &&

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

Estimated · stage {lastCoveredStage(suggestedEntry.address)}
} - {searching &&

{message}

} - {candidate &&

New address found

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

Estimated · Stage {lastCoveredStage(candidate.address)}

Save once to recover this address on any device.

Wallet fees apply to save. Switching saved addresses is free.
} -
Advanced search

Search runs for up to 30 seconds at a time. Higher stages take more work and pass stricter future address rules.

{suggestedEntry && } - {pausedSearch && <>

Wallet fees apply. Otherwise you can repeat this search on another device for free.

} - {!searching && savedSearches.map(search =>

Saved in your wallet · next key ID {String(search.next)}

)} + {session.network !== 'mainnet' &&

Address search is available on Mainnet.

} + {candidate &&

New address found

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

Estimated · Stage {lastCoveredStage(candidate.address)}

Save once to recover this address on any device.

void publishFound(candidate)} />Wallet fees apply to save. Switching saved addresses is free.
} +
Advanced search

Search runs for up to 30 seconds at a time. Higher stages take more work and pass stricter future address rules.

{suggestedEntry && void mine()} />} + {pausedSearch && <> void run(async () => { const fresh = await reload(); await fresh.store.append('search', pausedSearch); await reload(fresh); setMessage('Search progress saved in your wallet.') }, false, { id: 'save-progress', title: 'Saving search progress', detail: 'Approve in your wallet if prompted.' })} />

Wallet fees apply. Otherwise you can repeat this search on another device for free.

} + {!searching && savedSearches.map(search =>

{ setTarget(String(search.stage)); void mine(Number(search.stage)) }} /> Saved in your wallet · next key ID {String(search.next)}

)}
Other addresses {session.book.filter(x => x.keyID !== primary?.keyID).length}

Switching is free for this session. Reconnecting opens your longest-lasting eligible saved address.

{session.book.filter(x => x.keyID !== primary?.keyID).map(x => card(x))} void runRefresh('addresses', undefined, async () => { await reload(); setMessage('Addresses and expiration checked.') })} />
@@ -394,6 +403,7 @@ export default function Mountaintops() { }}>
{paymentHold &&

{paymentHold}

} + {!paymentHold && (!recipient || !amount) &&

Enter a recipient and amount to continue.

}
} {history.length > 0 &&
Recent activity {history.length}

This session only. Your wallet keeps the payment records.

{history.map(payment =>
{payment.kind === 'move' ? 'Moved to wallet' : 'Sent'}{payment.satoshis !== undefined ? ` · ${payment.satoshis.toLocaleString()} sats` : ''}{payment.recipient &&

To {payment.recipient}

}

{payment.txid}

)}
} @@ -402,5 +412,5 @@ export default function Mountaintops() {
Expiration, fees & recovery

When does my address expire?

Each address shows a month-and-year estimate and the stage it meets. Choose More info for the schedule. Before block 1,000,000 arrives, estimates can move earlier or later. Low transaction volume can delay expiration.

When an address expires, stop using it everywhere. Mountaintops disables receiving and stops looking for new deposits. Earlier coins remain yours and can still be moved to your wallet.

Can I recover on another device?

Connect the same BRC-100 wallet account. Your saved addresses and coin evidence come from the wallet, without browser data or files from this device. Keep your wallet account and its recovery service available.

What costs money?

Searching and pausing are free. Saving a new address also makes it your receiving address in one encrypted 1-satoshi wallet record. Switching saved addresses is free for this session; reconnecting opens the longest-lasting eligible saved address. Saving search progress also needs a wallet record. Network and wallet service fees may apply to records. Moving or sending coins also incurs wallet fees.

Does a longer-lasting address cover every payment?

No. Funding TXID rules also apply, and from stage 13 the transaction must use version 1. Mountaintops prepares eligible transactions within a bounded work budget. External senders may create payments outside those rules. Eligibility never changes who owns the coins.

Technical status{session &&

{session.network} · checked through block {session.coverage.height.toLocaleString()} · stage {session.coverage.stage}

}

Client-only. Encrypted PushDrop recovery records use your BRC-100 wallet’s baskets. WhatsOnChain supplies chain data and historical recovery; unavailable or incomplete data cannot establish a balance.

{session && info && setInfo(null)} />} -
+
} diff --git a/frontend/src/PaymentReview.tsx b/frontend/src/PaymentReview.tsx index a07bd6d..49e71f8 100644 --- a/frontend/src/PaymentReview.tsx +++ b/frontend/src/PaymentReview.tsx @@ -1,6 +1,7 @@ import { useEffect, useRef } from 'react' import { bsvAmount } from './paymentAmount.ts' import PaymentProgress from './PaymentProgress.tsx' +import { ActionButton } from './ActionFeedback.tsx' export type PaymentDraft = { recipient: string; satoshis: number } @@ -13,6 +14,6 @@ export default function PaymentReview({ payment, busy, sending, phase, onBack, o

{bsvAmount(payment.satoshis)} BSV

To{payment.recipient}

Wallet and network fees are additional.

-
+
} diff --git a/frontend/src/PaymentStatus.tsx b/frontend/src/PaymentStatus.tsx index 37133e0..ade4d37 100644 --- a/frontend/src/PaymentStatus.tsx +++ b/frontend/src/PaymentStatus.tsx @@ -1,12 +1,13 @@ +import { ActionButton } from './ActionFeedback.tsx' type Props = { actions: Record[] checkedAt: number | null disabled: boolean - busy: boolean + activeID: string | null onReview: (action: Record) => void } -export default function PaymentStatus({ actions, checkedAt, disabled, busy, onReview }: Props) { +export default function PaymentStatus({ actions, checkedAt, disabled, activeID, onReview }: Props) { return actions.map(action => { const prepared = action.state === 'prepared' return
@@ -16,7 +17,7 @@ export default function PaymentStatus({ actions, checkedAt, disabled, busy, onRe

{prepared ? 'Unfinished payment' : 'Check your wallet'}

{prepared ? 'This payment has not been sent.' : 'Your wallet has not reported a clear result.'}

- + onReview(action)} />

{prepared ? 'Cancel it to start a new payment.' : 'Check this attempt before sending the same payment again.'}

diff --git a/frontend/src/RefreshProgress.tsx b/frontend/src/RefreshProgress.tsx index 94dbe38..35b51d4 100644 --- a/frontend/src/RefreshProgress.tsx +++ b/frontend/src/RefreshProgress.tsx @@ -1,3 +1,4 @@ +import { ActionButton } from './ActionFeedback.tsx' export type RefreshState = { kind: 'payments' | 'single' | 'addresses'; keyID?: string; detail: string } export function RefreshIcon({ spinning = false }: { spinning?: boolean }) { @@ -5,7 +6,7 @@ export function RefreshIcon({ spinning = false }: { spinning?: boolean }) { } export function RefreshButton({ active, disabled, label, ariaLabel, onClick }: { active: boolean; disabled: boolean; label: string; ariaLabel?: string; onClick: () => void }) { - return + return } onClick={onClick} /> } export default function RefreshProgress({ progress }: { progress: RefreshState }) { diff --git a/frontend/src/style.css b/frontend/src/style.css index 6f0920c..ce9a626 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -20,14 +20,19 @@ .copy-feedback{display:block;margin-top:9px;color:#b3e2cd} .refresh-icon{display:block;width:18px;height:18px;flex-shrink:0} .refresh-icon.is-spinning{animation:payment-orbit 1.3s linear infinite} -.refresh-button{display:inline-flex;align-items:center;justify-content:center;gap:8px} -.refresh-button[aria-busy=true]:disabled{opacity:1;background:#23453f;border-color:#77b5a1;color:#d5efe5;cursor:progress} +.action-button{display:inline-flex;align-items:center;justify-content:center;gap:8px} +.action-button[aria-busy=true]:disabled{opacity:1;background:#23453f;border-color:#77b5a1;color:#d5efe5;cursor:progress} +.loading-spinner{display:inline-block;width:18px;height:18px;flex:0 0 18px;border:2px solid #aee1cf40;border-top-color:#bce9d7;border-radius:50%;animation:payment-orbit 1.3s linear infinite} +.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0} +.activity-progress{display:flex;align-items:center;gap:14px;padding:18px 22px;border-color:#416e5d;box-shadow:none} +.activity-progress p{margin:0;line-height:1.5} +.activity-progress .progress-phase{font-size:.82rem;color:#b8d6cd;margin-top:3px} .refresh-progress{display:flex;align-items:center;gap:14px;padding:18px 22px;border-color:#416e5d;box-shadow:none} .refresh-mark{display:grid;place-items:center;width:44px;height:44px;flex:0 0 44px;border-radius:50%;background:#22463e;color:#bce9d7} .refresh-mark .refresh-icon{width:24px;height:24px} .refresh-progress p{margin:0;line-height:1.5} .refresh-progress .progress-phase{font-size:.82rem;color:#b8d6cd;margin-top:3px} -@media(prefers-reduced-motion:reduce){.refresh-icon.is-spinning{animation:none}} +@media(prefers-reduced-motion:reduce){.refresh-icon.is-spinning,.loading-spinner{animation:none}} .payment-hold{margin-bottom:0} .expiry-summary{display:flex;align-items:baseline;gap:12px;flex-wrap:wrap;margin:12px 0} .expiry-summary p{margin:0} diff --git a/frontend/test/browser/all-actions.mjs b/frontend/test/browser/all-actions.mjs new file mode 100644 index 0000000..b6feb35 --- /dev/null +++ b/frontend/test/browser/all-actions.mjs @@ -0,0 +1,116 @@ +import assert from 'node:assert/strict' +import path from 'node:path' +import { mkdir } from 'node:fs/promises' +import { createServer } from 'vite' +import { chromium } from 'playwright' + +const root = path.resolve(import.meta.dirname, '../..'), evidence = process.env.ACTIONS_EVIDENCE +if (evidence) await mkdir(evidence, { recursive: true }) +const server = await createServer({ root, server: { host: '127.0.0.1', port: 0 } }); await server.listen() +const origin = `http://127.0.0.1:${server.httpServer.address().port}` +const browser = await chromium.launch({ headless: true }) +try { + for (const width of [1440, 390, 320]) { + const context = await browser.newContext({ viewport: { width, height: 1000 }, serviceWorkers: 'block' }) + const page = await context.newPage(), errors = [], external = [] + page.on('pageerror', error => errors.push(error.message)) + await context.route('**/*', route => { if (new URL(route.request().url()).origin === origin) return route.continue(); external.push(route.request().url()); return route.abort() }) + const idle = () => page.waitForFunction(() => document.querySelector('main')?.getAttribute('aria-busy') === 'false') + const action = page.getByRole('status', { name: 'Action progress' }) + const release = () => page.getByRole('button', { name: 'Complete simulated action', exact: true }).click() + const shot = async name => { if (evidence) await page.screenshot({ path: path.join(evidence, `${name}-${width}.png`), fullPage: true }) } + const noActivity = async () => { await idle(); assert.equal(await action.count(), 0); assert.equal(await page.locator('button[aria-busy=true]').count(), 0) } + const activeButton = async label => { + const button = page.getByRole('button', { name: label, exact: true }) + assert.equal(await button.getAttribute('aria-busy'), 'true'); assert.equal(await button.isDisabled(), true) + assert.equal(await button.evaluate(element => getComputedStyle(element).opacity), '1') + } + const connect = async query => { + await page.goto(`${origin}/test/ui.html?${query}`) + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click(); await idle() + } + try { + await page.goto(`${origin}/test/ui.html?synthetic-worker&hold-connect&hold-copy`) + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click() + await action.getByText('Connecting your wallet', { exact: true }).waitFor(); await activeButton('Connecting…') + assert.match(await page.locator('[data-live-progress]').textContent(), /Connecting your wallet/) + assert.equal(await page.locator('[data-live-progress]').evaluate(element => element.closest('[aria-busy=true]') === null), true, 'live progress is outside the busy region') + await shot('connect'); await release(); await noActivity() + await page.getByRole('button', { name: 'Copy address', exact: true }).click() + await page.getByRole('button', { name: 'Complete simulated copy', exact: true }).waitFor() + const copy = page.getByRole('button', { name: 'Copy address', exact: true }) + assert.equal(await copy.innerText(), 'Copying…'); assert.equal(await copy.getAttribute('aria-busy'), 'true') + assert.equal(await page.getByText('Address copied.', { exact: true }).count(), 0) + await page.getByRole('button', { name: 'Complete simulated copy', exact: true }).click() + await page.getByText('Address copied.', { exact: true }).waitFor(); await noActivity() + + await page.locator('.address-search > summary').click() + await page.evaluate(() => window.fixtureHoldWalletCall('getNetwork')) + await page.getByRole('button', { name: 'Find an address', exact: true }).click() + await action.getByText('Preparing address search', { exact: true }).waitFor(); await activeButton('Preparing…') + await release() + await action.getByText('Finding an address', { exact: true }).waitFor() + assert.equal(await page.evaluate(() => window.fixtureWorkerCount()), 1) + await page.locator('.address-search > summary').click() + assert.equal(await action.isVisible(), true, 'search progress stays visible when its disclosure closes') + await shot('search'); await page.locator('.address-search > summary').click() + await page.getByRole('button', { name: 'Pause', exact: true }).click(); await noActivity() + await page.getByText('Search paused.', { exact: false }).waitFor() + await page.locator('.advanced > summary').click() + await page.evaluate(() => window.fixtureHoldWalletCall('createAction')) + await page.getByRole('button', { name: 'Save progress', exact: true }).click() + await action.getByText('Saving search progress', { exact: true }).waitFor(); await activeButton('Saving…') + await page.emulateMedia({ reducedMotion: 'reduce' }) + assert.equal(await action.locator('.loading-spinner').evaluate(element => getComputedStyle(element).animationName), 'none') + await page.emulateMedia({ reducedMotion: 'no-preference' }); await shot('save-progress') + await release(); await noActivity(); await page.getByText('Search progress saved in your wallet.', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Resume stage 2', exact: true }).click() + await action.getByText('Finding an address', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Finish simulated search', exact: true }).click(); await noActivity() + await page.getByRole('heading', { name: 'New address found', exact: true }).waitFor() + await page.evaluate(() => window.fixtureHoldWalletCall('createAction', true)) + await page.getByRole('button', { name: 'Save & use address', exact: true }).click() + await action.getByText('Saving your address', { exact: true }).waitFor(); await activeButton('Saving…') + await release(); await noActivity(); await page.getByRole('alert').waitFor() + assert.equal(await page.getByText('New address saved and ready to receive.', { exact: true }).count(), 0) + await page.evaluate(() => window.fixtureHoldWalletCall('createAction')) + await page.getByRole('button', { name: 'Save & use address', exact: true }).click() + await action.getByText('Saving your address', { exact: true }).waitFor(); await shot('save-address') + await release(); await noActivity(); await page.getByText('New address saved and ready to receive.', { exact: true }).waitFor() + await page.locator('.address-list > summary').click() + await page.getByRole('button', { name: 'Use for receiving', exact: true }).click(); await noActivity() + await page.getByText('Receiving address changed.', { exact: false }).waitFor() + await page.getByRole('button', { name: /More info about stage/ }).first().click() + await page.getByRole('dialog').waitFor(); await page.getByRole('button', { name: 'Close address information' }).click() + await page.getByRole('button', { name: 'Send', exact: true }).click() + await page.getByText('Enter a recipient and amount to continue.', { exact: true }).waitFor(); await noActivity() + await page.getByRole('button', { name: 'Receive', exact: true }).click() + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth)) + + await connect('pending=unprocessed') + await page.evaluate(() => window.fixtureHoldWalletCall('listActions')) + await page.getByRole('button', { name: 'Check payment in wallet', exact: true }).click() + await action.getByText('Checking payment status', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Complete simulated action', exact: true }).waitFor() + await release(); await noActivity(); assert.equal(await page.getByRole('region', { name: 'Wallet payment status' }).count(), 1) + await connect('pending=nosend') + await page.evaluate(() => window.fixtureHoldWalletCall('abortAction')) + await page.getByRole('button', { name: 'Cancel unsent payment', exact: true }).click() + await action.getByText('Canceling unfinished payment', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Complete simulated action', exact: true }).waitFor(); await shot('cancel') + await release(); await noActivity(); await page.getByText('Unsent payment canceled.', { exact: true }).waitFor() + if (width === 1440) { + await page.goto(`${origin}/test/ui.html`) + await page.clock.install() + await page.getByRole('button', { name: 'Connect wallet', exact: true }).click(); await idle() + await page.evaluate(() => window.fixtureHoldWalletCall('getNetwork')) + await page.clock.fastForward(60001) + await action.getByText('Updating address status', { exact: true }).waitFor() + await page.getByRole('button', { name: 'Complete simulated action', exact: true }).waitFor() + await release(); await noActivity() + } + assert.deepEqual(errors, []); assert.deepEqual(external, []) + console.log(`PASS ${width}px: connect/copy/search/pause/resume/save/review/cancel/background feedback; no external requests`) + } finally { await context.close() } + } +} finally { await browser.close(); await server.close() } diff --git a/frontend/test/ui.html b/frontend/test/ui.html index ba3e06a..8c8c5f7 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -9,6 +9,49 @@ 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 demo · no real funds · 0 simulated actions'; document.body.prepend(counter) +let holdWalletCall = new URL(location.href).searchParams.has('hold-connect') ? { method: 'getNetwork', fail: false } : null +window.fixtureHoldWalletCall = (method, fail = false) => { holdWalletCall = { method, fail } } +const holdAction = async label => new Promise(resolve => { + const finish = document.createElement('button'); finish.textContent = label + finish.onclick = () => { finish.remove(); resolve() }; counter.append(finish) +}) +const pauseWalletCall = async method => { + if (holdWalletCall?.method !== method) return + const held = holdWalletCall; holdWalletCall = null + await holdAction('Complete simulated action') + if (held.fail) throw new Error('Synthetic wallet request declined') +} +for (const method of ['getNetwork', 'getPublicKey', 'listActions', 'createAction', 'abortAction']) { + const original = wallet[method].bind(wallet) + wallet[method] = async args => { + await pauseWalletCall(method) + return original(args) + } +} +if (new URL(location.href).searchParams.has('hold-copy')) Object.defineProperty(navigator.clipboard, 'writeText', { value: async () => { await holdAction('Complete simulated copy') } }) +if (new URL(location.href).searchParams.has('synthetic-worker')) { + let workers = 0 + window.fixtureWorkerCount = () => workers + window.Worker = class { + constructor() { workers++; this.controls = []; this.stopped = false } + terminate() { this.stopped = true; this.controls.forEach(button => button.remove()) } + postMessage(args) { + const send = data => { if (!this.stopped) this.onmessage?.({ data }) } + queueMicrotask(() => { + send({ kind: 'started' }); send({ kind: 'progress', stage: args.minimumStage, next: '100', elapsed: 1000 }) + for (const [label, kind] of [['Finish simulated search', 'found'], ['Pause simulated search', 'paused'], ['Fail simulated search', 'error']]) { + const button = document.createElement('button'); button.textContent = label + button.onclick = () => { + const found = kind === 'found' ? firstMatch(args.identityKey, args.minimumStage, args.network, 10000n) : null + if (kind === 'found' && !found) throw new Error('Synthetic worker fixture has no eligible address') + send({ kind, ...found, stage: args.minimumStage, next: '100', message: 'Synthetic search error' }) + } + this.controls.push(button); counter.append(button) + } + }) + } + } +} const create = wallet.createAction.bind(wallet) let actions = 0 let submissions = 0 @@ -100,6 +143,7 @@ let aborts = 0 window.fixtureAbortCalls = () => aborts wallet.abortAction = async args => { + await pauseWalletCall('abortAction') aborts++ if (args.reference === pending.txid && pending.status === 'nosend') { pending.status = 'failed'; return { aborted: true } } return abort(args) From d8deb2b4a672183035980dd3dee730673cbcfbca Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 10:58:43 -0800 Subject: [PATCH 12/13] Qualify the frontend with the production non-root port and runtime --- ops/canary.Dockerfile | 4 ++-- ops/nginx.conf | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ops/canary.Dockerfile b/ops/canary.Dockerfile index d922420..15eb756 100644 --- a/ops/canary.Dockerfile +++ b/ops/canary.Dockerfile @@ -6,9 +6,9 @@ RUN cd frontend && npm ci COPY frontend ./frontend COPY shared ./shared RUN cd frontend && npm run build -FROM docker.io/nginx:alpine +FROM docker.io/nginxinc/nginx-unprivileged:alpine ARG SOURCE_REVISION LABEL org.opencontainers.image.source="https://github.com/p2ppsr/mountaintops" org.opencontainers.image.revision="$SOURCE_REVISION" COPY ops/nginx.conf /etc/nginx/conf.d/default.conf COPY --from=build /app/frontend/build /usr/share/nginx/html -EXPOSE 80 +EXPOSE 8080 diff --git a/ops/nginx.conf b/ops/nginx.conf index b3bc6ab..22c0e75 100644 --- a/ops/nginx.conf +++ b/ops/nginx.conf @@ -1,5 +1,5 @@ server { - listen 80; + listen 8080; server_name _; root /usr/share/nginx/html; index index.html; From 6342ff63857338c3b4cc0b22483a0dd99cc6318e Mon Sep 17 00:00:00 2001 From: Brayden Langley Date: Thu, 12 Nov 2026 11:01:00 -0800 Subject: [PATCH 13/13] Document wallet acceptance and consistent action feedback --- README.md | 77 +++++++++++++++++++++++++++++++++++-------------------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/README.md b/README.md index c403171..83c1b1d 100644 --- a/README.md +++ b/README.md @@ -22,7 +22,7 @@ Coin evidence and per-input derivation metadata are retained in the `mountaintop `shared/schedule.json` pins the normative schedule at BRC document blob `85eaa6219cec77350170d52d243e65122e453d39` ([merged proposal](https://github.com/bsv-blockchain/BRCs/blob/068e4b5eac90ebbe726fb067682bf72aadafa4ff/opinions/0234.md)). Mainnet block 1,000,000 establishes the MTP anchor. Receive cards show **Not earlier than [month year]**, an estimated earliest expiration at the first stage the address fails, including the 14-chain-day waiting round. Before the anchor exists, its median time is projected from a validated WoC tip height/hash/MTP at 600 seconds per block; these projections can move earlier or later and are explicitly estimates, not guaranteed minimum dates. Once available, the actual anchor replaces the projection. A More info modal explains the stage number, ownership, transaction eligibility, approximate stage blocks/dates and links to BRC-234. Missing optional tip evidence shows an unavailable estimate without changing stage-0 coverage. Testnet and final-stage addresses have no invented cutoff. Estimated dates/heights never drive expiration, receiving eligibility or mining. Calendar gates alone are not expiration dates: all-version non-coinbase volume, frozen pending rounds, the 14-MTP-day notice and following-block activation also apply. Coverage is replayed from parent-linked WoC block evidence and wallet checkpoints; reorged checkpoints are discarded. Initial catch-up after the anchor can be lengthy. Testnet has no fabricated mainnet sunset. -Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Every input, including wallet-added fee/change inputs, is checked against known-outpoint spend evidence before signing and again immediately before submission. A spent or unknown input stops the payment and aborts its unsubmitted preparation. A signature or wallet balance alone does not prove spendability. The same checks protect encrypted record saves: LocalKVStore prepares and signs without broadcasting, its SDK validates the token/template, then the app checks all inputs again before one explicit release. Unsubmitted record actions recover through native wallet labels; ordinary acknowledged unproven records do not block payments, while unresolved preparations do. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds; a match at broadcast remains provisional until confirmation. +Address, TXID and script-hash predicates are independent. The app displays funding coverage at confirmation without discarding coins outside those rules. Payments/imports prepare version-1 transactions with supported wallet APIs, bounded nonce variation, `noSend` signing, final-template and final-TXID inspection, fresh coverage checks, and one explicit `sendWith` submission. Every input, including wallet-added fee/change inputs, is checked against known-outpoint spend evidence before signing and again immediately before submission. A spent or unknown input stops the payment and aborts its unsubmitted preparation. A signature or wallet balance alone does not prove spendability. The same checks protect encrypted record saves: LocalKVStore prepares and signs without broadcasting, its SDK validates the token/template, then the app checks all inputs again before one explicit release. Unsubmitted record actions recover through native wallet labels; ordinary acknowledged unproven records do not block payments, while unresolved preparations do. Candidate payment outputs are never changed to grind. Abandoned candidates are aborted. The wallet may ask for permissions; metadata records have their own fees. The payment work budget is 30 seconds. Coverage at inclusion remains a chain-derived fact, independent of application completion on wallet acceptance. Native durable wallet action history and unique labels support recovery after an interrupted submission, without requiring an extra fee-paying record before the first import. An empty wallet can import its first coins. Signed noSend preparations can be canceled by TXID from a fresh device; unsigned or uncertain actions require wallet review. An uncertain outcome blocks automatic retries and requires checking wallet history. Out-of-session signable-reference recovery is not assumed. Mountaintops does not promise that a BRC-234 merge proves provider adoption, indefinite WoC availability, complete retrieval of data a provider no longer serves, or external wallet transaction-grinding support. Such failures remain explicit, with retained funds and keys intact. @@ -68,32 +68,53 @@ New actions use fixed labels and native TXIDs, avoiding a new label permission f The header and favicon use the same authored `/mountaintops.svg`. Wallet/PWA icons and the touch icon are PNG renders of that source at 192 and 512 pixels. Keep all variants in sync when changing the logo. The unused legacy Vite file remains only for cached old HTML during compatible releases; the current app and manifest never reference it. -## November 11 payment-status candidate - -The local review candidate distinguishes a submitted `unproven` payment waiting -for a mined proof from an unknown sending outcome. **Refresh payment status** -reads wallet history and shows the last check time without signing, rebroadcasting -or saving a record. Prepared unsent actions retain their separate cancel action. -All existing pending-payment guards, fixed labels, device-independent recovery, -receiving expiration and coin/input checks remain. No schema migration or live -release is included; operator merge and release review remain pending. +## Action feedback and payment outcomes + +Every asynchronous action shows an active button and a clear status: connection, +copy, send/move, payment/address refresh, search preparation and mining, saving an +address or search progress, unfinished-payment review/cancellation, and background +address checks. Progress ends on success or error; existing balances stay visible +through a refresh. Reduced-motion preferences stop decorative animation, and a +live announcement outside the busy region keeps status available to screen +readers. Switching a saved address, reviewing a draft, opening details and other +instant actions do not add artificial loading delays. + +Copy starts directly in the focused click using the currently validated address, +without waiting for wallet or chain calls. Receiving, network, retirement and +pending-expiration guards still apply. Coverage older than 90 seconds requires a +separate address check and a new explicit Copy click; the app never writes the +clipboard later in the background. Browser denial selects the address for manual +copying instead of displaying a raw clipboard error. + +Sending reviews an exact recipient/amount snapshot before wallet preparation. +Sats and BSV conversion preserves the recipient amount. Exactly one positive +submission acknowledgment must match the signed TXID. Wallet `sending`, +`unproven` and `completed` states acknowledge wallet ownership of the transaction +lifecycle and release the app payment hold. Mining, proof collection and broadcast +retries belong to the wallet. No post-acceptance metadata or chain read can turn +a successful acknowledgment into a failed payment or delay its receipt. + +Genuine unknown, incomplete or contradictory outcomes retain the exact-attempt +guard. Checking status reads only identity, network and native action history; +it never signs, resubmits, refreshes recovery records or writes a status token. +A previously observed unresolved action missing from later history remains +guarded in that session. Legacy action records resolve in memory. Unsent +preparations keep their separate cancellation action, checked against fresh +history before aborting. Known failure is never success or an automatic retry. +Input, template, coverage, expiry, ownership and recovery checks remain unchanged. Validation from `frontend/`: `npm test`, `npm run lint`, `npm run build`, and -`npm run test:browser`. Browser checks at 1440, 390 and 320 pixels cover delayed -proof, repeated refresh, blocked resend, completion, reconnect and unknown -outcomes using synthetic wallet state. They assert zero wallet transactions and -block external requests. `PAYMENT_STATUS_EVIDENCE` optionally saves synthetic -screenshots. The status API supplies no submission timestamp, so the UI reports -the observed check time rather than inventing elapsed submission time. Release -must retain the immutable asset bridge and existing CARS availability rules; -rollback is the prior compatible frontend, never deletion of wallet records. - -The second validation pass gives payment status its own read path using only -`getPublicKey`, `getNetwork` and `listActions`; it never calls the general reload, -coverage scanner, recovery store or expiration persistence. Conflicting and -unfamiliar statuses block admission, and a previously observed unresolved action -missing from a later response remains blocked in that session. Legacy final -records are resolved only in memory; the existing record-only unproven exception -is retained. A stale cancel button cannot abort an action now reported submitted. -The browser regression deliberately refuses recovery/chain reads during status -refresh; CI installs Chromium and runs this regression as well as unit checks. +`npm run test:browser`. Disposable SDK/browser checks at 1440, 390 and 320 pixels +cover all action states, delayed/declined/lost wallet results, single submission, +subsequent unmined-change payments, account boundaries, preserved balances, +clipboard focus/denial, and reduced motion. They block external requests and do +not use a real wallet. `ACTIONS_EVIDENCE`, `COPY_ADDRESS_EVIDENCE`, +`REFRESH_EVIDENCE` and `PAYMENT_STATUS_EVIDENCE` optionally save demo screenshots. +The status API supplies no submission timestamp; the UI reports the observed +check time instead of inventing elapsed submission time or a mining countdown. + +CI exports a committed Linux/amd64 qualification image for isolated startup and +endpoint-withdrawal testing. Its non-root runtime and port 8080 match production +constraints. Production releases retain the immutable old-HTML asset bridge, +existing CARS security/availability fields and wallet record compatibility. +Rollback must preserve wallet data and earlier assets.