diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0c7e2d2..9d2ffd1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,4 +22,27 @@ 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 + 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/README.md b/README.md index fba9120..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. @@ -67,3 +67,54 @@ 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. + +## 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`. 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. 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..704c0dd 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -9,7 +9,11 @@ "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/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" }, "dependencies": { "@bsv/sdk": "4.0.0", @@ -28,6 +32,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/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 1b41c37..6ec0c96 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,19 +2,26 @@ 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 { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' +import { applyExpirations, bookFromRecords, validateAddress } from './addressBook.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' +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' import { availableRetainedCoins, refreshCoins, type Coin } from './coins.ts' -import { importCoins, sendCoins, unfinishedWalletActions } from './actions.ts' +import { importCoins, sendCoins, PaymentOutcomeUnknownError } from './actions.ts' import { preferCompatibleTransport } from './walletClient.ts' -import { assertWalletActionFinal } from './walletActionState.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>() @@ -27,6 +34,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') @@ -35,23 +43,52 @@ 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 [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([]) const [searching, setSearching] = useState(false) const [info, setInfo] = useState<{ stage: number; expired: boolean } | null>(null) 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 useEffect(() => () => { worker.current?.terminate() }, []) - const run = async (task: () => Promise, quiet = false) => { + useEffect(() => { + if (!copiedAddress) return + const timer = setTimeout(() => setCopiedAddress(null), 2000) + return () => clearTimeout(timer) + }, [copiedAddress]) + 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, 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…' }) + try { await task() } finally { setRefreshing(null) } + }) + const refreshDetail = (detail: string) => setRefreshing(previous => previous ? { ...previous, detail } : null) + + const clearWalletSession = () => { + setCopiedAddress(null); setManualCopyAddress(null) + setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setReceipt(null); setReview(null); setRecipient(''); setAmount('') } const reload = async (previous: Session | null = current.current): Promise => { @@ -59,8 +96,8 @@ export default function Mountaintops() { const { network } = await client.getNetwork({}) const { publicKey: identity } = await client.getPublicKey({ identityKey: true }) if (previous && (previous.identity !== identity || previous.network !== network)) { - setSession(null); setBalances({}); setCheckedPayments({}); setCandidate(null); setPausedSearch(null); setHistory([]); setTxid('') - throw new Error('Wallet account or network changed. Connect again to load its own records.') + clearWalletSession() + throw new WalletAccountChangedError() } const store = previous?.store ?? new WalletRecords(client, identity, network) let records = await store.load() @@ -73,9 +110,10 @@ 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()) return next } @@ -93,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 @@ -118,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) => { @@ -147,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 = () => { @@ -171,43 +209,95 @@ 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 checkCoins = (keyID: string) => void run(async () => { + 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) + 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 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 + } + 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 } + 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)! 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 importMoney = (keyID: string) => void run(async () => { + 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 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)! const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) - const submitted = await importCoins(client, fresh.store, entry, coins, fresh.coverage, setMessage) - setCheckedPayments(x => ({ ...x, [keyID]: false })) - setTxid(submitted); setHistory(x => [{ txid: submitted, description: 'Import to wallet', status: 'Submitted' }, ...x]); setBalances(x => ({ ...x, [keyID]: undefined })) - await reload(fresh); setMessage('Transfer submitted. Check your wallet for the final result.') - }) - const send = () => void run(async () => { + 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 { + 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 runPayment('send', 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(''); await reload(fresh) - setMessage('Payment submitted. Check your wallet for the final result.') + await finishPayment(fresh, () => sendCoins(client, fresh.store, intent.recipient, bsvAmount(intent.satoshis), fresh.coverage, setMessage), { ...intent, kind: 'send' }, () => {}) }) const disabled = busy || searching @@ -215,6 +305,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 ? '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()] @@ -227,67 +318,99 @@ 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.'}

} + {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 && copyAddress(entry)} />} {!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.
}} -
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.

}
+ {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) && <>
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.

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

Check your wallet before continuing

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

{pendingActions.map(action =>
Payment details

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

{session.network === 'mainnet' ? 'Mainnet' : 'Testnet'} · Connected + void run(async () => { + setError(''); setMessage('') + try { + let result = await refreshPaymentStatus(client, session.identity, session.network, session.records, action) + let canceled = false + const prepared = result.records.find(record => record.kind === 'action' && record.data.id === action.id && record.data.state === 'prepared' && record.data.reference === action.reference) + if (action.state === 'prepared' && typeof action.reference === 'string' && prepared) { + const aborted = await client.abortAction({ reference: action.reference }) + if (!aborted.aborted) throw new Error('Wallet did not acknowledge cancellation') + canceled = true + result = await refreshPaymentStatus(client, session.identity, session.network, result.records, action) + } + setSession({ ...session, records: result.records }); setStatusCheckedAt(Date.now()) + 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 } - await reload(fresh); setMessage('Wallet payment status checked.') - })}>{action.state === 'prepared' ? 'Cancel unsent payment' : 'Check wallet result'}
)}
} + }, 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' &&
} {session.receivingBlocked &&

{session.receivingBlocked}

} {session.coverage.persistenceWarning &&

{session.coverage.persistenceWarning}

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

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

} -

Payments to your addresses

-

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

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

Wallet fees apply when moving coins.

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

No available payments found.

} +

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

}
-

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 ? 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))}
-

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}

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

)}
+ +
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() }}> + + +
setAmount(e.target.value)} placeholder="0" inputMode={unit === 'sats' ? 'numeric' : 'decimal'} maxLength={32} />
+ + {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}

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

{session && info && setInfo(null)} />} -
+
} 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/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..49e71f8 --- /dev/null +++ b/frontend/src/PaymentReview.tsx @@ -0,0 +1,19 @@ +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 } + +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
+ {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/PaymentStatus.tsx b/frontend/src/PaymentStatus.tsx new file mode 100644 index 0000000..ade4d37 --- /dev/null +++ b/frontend/src/PaymentStatus.tsx @@ -0,0 +1,30 @@ +import { ActionButton } from './ActionFeedback.tsx' +type Props = { + actions: Record[] + checkedAt: number | null + disabled: boolean + activeID: string | null + onReview: (action: Record) => void +} + +export default function PaymentStatus({ actions, checkedAt, disabled, activeID, onReview }: Props) { + return actions.map(action => { + const prepared = action.state === 'prepared' + return
+
+ +
+

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

+
+ Details + {action.txid ?

{String(action.txid)}

:

No transaction ID was returned.

} + {checkedAt &&

Last checked .

} +
+
+ }) +} diff --git a/frontend/src/RefreshProgress.tsx b/frontend/src/RefreshProgress.tsx new file mode 100644 index 0000000..35b51d4 --- /dev/null +++ b/frontend/src/RefreshProgress.tsx @@ -0,0 +1,14 @@ +import { ActionButton } from './ActionFeedback.tsx' +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 } onClick={onClick} /> +} + +export default function RefreshProgress({ progress }: { progress: RefreshState }) { + return

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

{progress.detail}

+} 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/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) } 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/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 19aa588..ce9a626 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -2,4 +2,86 @@ .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.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} +.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} +.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} +.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,.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} +.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} +.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} +.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} +.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 107f8c4..416a597 100644 --- a/frontend/src/walletActionState.ts +++ b/frontend/src/walletActionState.ts @@ -1,6 +1,11 @@ -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' +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 = [] @@ -13,23 +18,92 @@ 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. - 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.') +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}`)) } -export async function unfinishedWalletActions(wallet: WalletInterface, network: WalletRecords['network']): Promise { +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 { + return statusFromActions(await walletActions(wallet), action) +} + +export function walletStatusMessage(status: Awaited>): string { + 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.' + return 'The payment outcome is not known. Check wallet activity before continuing. Do not send it again.' +} + +export async function assertWalletActionResolved(wallet: WalletInterface, action: Record): Promise { + const status = await walletActionStatus(wallet, action) + if (status === 'unknown') throw new Error(walletStatusMessage(status)) +} + +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) + for (const [key, group] of groups) { + const action = group[0], statuses = new Set(group.map(row => row.status)) + const consistent = statuses.size === 1 + 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' : '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) + 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 guard until the wallet acknowledges its outcome. + native.push({ ...record, data: { ...record.data, state: '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/actions.test.mjs b/frontend/test/actions.test.mjs index fb7ca25..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, '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/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/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/browser/payment-status.mjs b/frontend/test/browser/payment-status.mjs new file mode 100644 index 0000000..5d927bd --- /dev/null +++ b/frontend/test/browser/payment-status.mjs @@ -0,0 +1,174 @@ +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 }) +const destination = '1BoatSLRHtKNngkdXEeobR76b53LETtpyT' + +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() + }) + 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 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)) + + // 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() + 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 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) { + 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') }) + 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.deepEqual(errors, []); assert.deepEqual(unexpected, []) + 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/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/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/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/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 new file mode 100644 index 0000000..b319a78 --- /dev/null +++ b/frontend/test/paymentStatus.test.mjs @@ -0,0 +1,79 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { walletActionStatus, walletStatusMessage, unfinishedWalletActions, assertWalletActionResolved, refreshPaymentStatus, paymentActionRecords } from '../src/walletActionState.ts' + +const txid = 'a'.repeat(64) +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()]), []) + } + 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'), []) +}) + +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(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('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('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 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.length, 1) + rows = [row('unproven')] + result = await refreshPaymentStatus(wallet, identity, 'mainnet', result.records, { txid }) + 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', [guard()], { txid }), /account or network changed/) + await assert.rejects(refreshPaymentStatus(wallet, identity, 'testnet', [guard()], { txid }), /account or network changed/) +}) + +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 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 ed00b5b..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' }), /no final result/) - await assert.rejects(assertWalletActionFinal(wallet, { txid: 'f'.repeat(64) }), /no final result/) + 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/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 7595c49..8c8c5f7 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -8,12 +8,101 @@ 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) +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 -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 }) } +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')) { + 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++ + 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 +} +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 }) @@ -46,5 +135,25 @@ 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) + const abort = wallet.abortAction.bind(wallet) + 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) + } + 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') 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' } 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;