From c00078c6bb083c6ef0c0be813a28cf9117d98a25 Mon Sep 17 00:00:00 2001 From: Ty J Everett Date: Thu, 29 Oct 2026 12:31:06 -0700 Subject: [PATCH 1/2] Make saved receive selection free and explain estimated sunsets --- README.md | 8 ++-- frontend/src/App.tsx | 51 ++++++++++++--------- frontend/src/ReceiveInfo.tsx | 30 +++++++++++++ frontend/src/coverageClient.ts | 15 ++++++- frontend/src/receiveUX.ts | 43 ++++++++++++++++++ frontend/src/style.css | 2 + frontend/test/fixtureWallet.mjs | 2 +- frontend/test/receiveUX.test.mjs | 77 ++++++++++++++++++++++++++++++++ frontend/test/ui.html | 13 ++++++ 9 files changed, 212 insertions(+), 29 deletions(-) create mode 100644 frontend/src/ReceiveInfo.tsx create mode 100644 frontend/src/receiveUX.ts create mode 100644 frontend/test/receiveUX.test.mjs diff --git a/README.md b/README.md index 89c1643..fba9120 100644 --- a/README.md +++ b/README.md @@ -4,11 +4,11 @@ A client-only BRC-100 wallet application at [mountaintops.net](https://mountaint ## Receiving, expiration and recovery -The main Receive view shows one selected address, its expiration status and payment controls. Payments to all addresses are checked explicitly and shown together, so switching receiving addresses does not hide earlier funds. Each import still uses its own address/key and the existing verified-input flow. Other addresses, advanced search targets, transaction eligibility and recovery explanations are collapsed until needed; Send has its own view. A saved address with longer coverage is offered directly before suggesting more mining. Expiration warnings and fees remain beside the affected action. +The main Receive view shows one selected address, its expiration status and payment controls. Payments to all addresses are checked explicitly and shown together, so switching receiving addresses does not hide earlier funds. Each import still uses its own address/key and the existing verified-input flow. Other addresses, advanced search targets, transaction eligibility and recovery explanations are collapsed until needed; Send has its own view. A fresh connection opens the longest-lasting eligible saved address, with a stable lowest-key-ID tie break. Switching to any other saved eligible address is free in-memory session state and survives background refreshes. It creates no preference transaction and uses no browser storage. Reconnecting or opening another device uses the deterministic default again; all addresses and retained funds recover from the wallet regardless of this display choice. Legacy selection records remain readable for compatible clients but no longer control the new default. Expiration warnings and fees remain beside the affected action. -The original address keeps the exact `[1, 'mountaintops']`, decimal key ID `1`, counterparty `anyone`, `forSelf: true` derivation. Browser workers search canonical decimal key IDs from `1` upward, returning the first match for a fixed BRC-234 target. The suggested target uses a measured 30-second, 95th-percentile work estimate; each work slice is bounded to 30 seconds. Search is free. A match requires explicit **Save & use address** (wallet fees apply) before the address can be displayed/shared. One encrypted address-publication record also selects it for receiving, avoiding a second fee-bearing preference transaction. Switching to an older saved address remains an explicit durable selection, with applicable wallet fees. Pausing is free; saving resumable progress to the wallet is an explicit fee-bearing step. Unsaved work can always be repeated deterministically from ID 1; no published address depends on that session's memory. +The original address keeps the exact `[1, 'mountaintops']`, decimal key ID `1`, counterparty `anyone`, `forSelf: true` derivation. Browser workers search canonical decimal key IDs from `1` upward, returning the first match for a fixed BRC-234 target. The suggested target uses a measured 30-second, 95th-percentile work estimate; each work slice is bounded to 30 seconds. Search is free. A match requires explicit **Save & use address** (wallet fees apply) before the address can be shared for receiving. One encrypted address-publication record makes it recoverable; the current session selects it without another wallet action. Switching an already saved address is free; only publishing a newly found address or explicitly saving search progress requires a record fee. Pausing is free; saving resumable progress to the wallet is an explicit fee-bearing step. Unsaved work can always be repeated deterministically from ID 1; no published address depends on that session's memory. -Address publications, primary selections, search progress, permanent receiving retirements, chain checkpoints, bounded-history completion are immutable encrypted on-chain PushDrop records using SDK `LocalKVStore` in wallet basket `mntops v1`. Each metadata record uses a 1-satoshi output plus applicable network and wallet service fees and the wallet's permission flow. There are no certificate APIs or certificate storage. Independent random record keys allow concurrent-device records to merge without overwriting another device's address history. A published address is never acknowledged until the wallet can read its record back. Optional `useForReceiving: true` on an address record participates in the same ordered selection stream as legacy `primary` records. Older clients can still recover the address; they must reload an updated build to interpret the combined selection. +Address publications, primary selections, search progress, permanent receiving retirements, chain checkpoints, bounded-history completion are immutable encrypted on-chain PushDrop records using SDK `LocalKVStore` in wallet basket `mntops v1`. Each metadata record uses a 1-satoshi output plus applicable network and wallet service fees and the wallet's permission flow. There are no certificate APIs or certificate storage. Independent random record keys allow concurrent-device records to merge without overwriting another device's address history. A published address is never acknowledged until the wallet can read its record back. Optional legacy `useForReceiving: true` and `primary` records are preserved for older compatible clients; new clients need no durable display-preference stream. Older clients can still recover the address; they must reload an updated build to interpret the combined selection. Restore the same BRC-100 wallet account and its supported storage/recovery service on any device. Browser storage, the old device, an open tab, manually saved key IDs and exports are not recovery dependencies. The original address can be reconstructed without a storage transaction. As with other BRC-100 applications, the wallet account and its storage service must remain available. @@ -20,7 +20,7 @@ Coin evidence and per-input derivation metadata are retained in the `mountaintop ## BRC-234 rules and payment construction -`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. 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. +`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. diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index 4697876..15f5483 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -2,7 +2,9 @@ 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, primaryFromRecords } from './addressBook.ts' +import { applyExpirations, bookFromRecords } from './addressBook.ts' +import { calendarEstimate, expirationEstimate, receivingKeyID } from './receiveUX.ts' +import ReceiveInfo from './ReceiveInfo.tsx' import { readCoverage, type Coverage } from './coverageClient.ts' import { refreshCoins, type Coin } from './coins.ts' import { importCoins, sendCoins, unfinishedWalletActions } from './actions.ts' @@ -35,6 +37,7 @@ export default function Mountaintops() { const [txid, setTxid] = useState('') const [history, setHistory] = useState<{ txid: string; description: string; status: string }[]>([]) const [searching, setSearching] = useState(false) + const [infoStage, setInfoStage] = useState(null) const worker = useRef(null) const searchProgress = useRef<{ stage: number; next: string } | null>(null) const operation = useRef(false) @@ -70,7 +73,7 @@ export default function Mountaintops() { records = await store.load() if (!receivingBlocked) book = bookFromRecords(identity, network, records) records = [...records, ...await unfinishedWalletActions(client, network)] - const next = { identity, network, store, records, book, coverage, primary: receivingBlocked ? null : primaryFromRecords(book, records, coverage.stage), receivingBlocked } + const next = { identity, network, store, records, book, coverage, primary: receivingBlocked ? null : receivingKeyID(book, coverage.stage, previous?.primary), receivingBlocked } setSession(next) return next } @@ -95,8 +98,8 @@ export default function Mountaintops() { const expected = await client.getPublicKey({ protocolID: [1, 'mountaintops'], keyID: result.keyID, counterparty: 'anyone', forSelf: true }) if (PublicKey.fromString(expected.publicKey).toAddress(fresh.network) !== result.address) throw new Error('Mined public key does not match the wallet') if (!existing) await fresh.store.append('address', { keyID: result.keyID, address: result.address, targetStage: result.stage, useForReceiving: true }) - else if (fresh.primary !== result.keyID) await fresh.store.append('primary', { keyID: result.keyID }) - await reload(fresh); setCandidate(null) + 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.') }) } @@ -141,14 +144,16 @@ export default function Mountaintops() { if (progress) { setPausedSearch(progress); setTarget(String(progress.stage)) } setMessage('Search paused. Your saved addresses are safe in your wallet.') } - const choose = (keyID: string) => void run(async () => { - const fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID) - if (fresh.receivingBlocked) throw new Error(fresh.receivingBlocked) - if (!entry) throw new Error('Address not found') - assertReceivable(entry, fresh.coverage.stage) - if (fresh.primary !== keyID) await fresh.store.append('primary', { keyID }) - await reload(fresh); setMessage('Receiving address updated.') - }) + const choose = (keyID: string) => { + const fresh = current.current + if (!fresh || disabled || fresh.receivingBlocked) return + const entry = fresh.book.find(x => x.keyID === keyID) + if (!entry) return + try { + assertReceivable(entry, fresh.coverage.stage) + 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 fresh = await reload(); const entry = fresh.book.find(x => x.keyID === keyID)! const coins = await refreshCoins(client, fresh.store, entry, fresh.coverage, setMessage) @@ -185,6 +190,7 @@ export default function Mountaintops() { }) const disabled = busy || searching + const calendar = session ? calendarEstimate(session.coverage) : null 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) : [] @@ -195,22 +201,22 @@ export default function Mountaintops() { const total = coins?.reduce((sum, coin) => sum + coin.satoshis, 0) const pending = session!.coverage.state?.pending const pendingExpiry = !entry.retiredAt && pending && !addressMatches(entry.address, pending.target) - const longest = Math.max(...session!.book.map(x => lastCoveredStage(x.address))) + 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' : entry.network !== 'mainnet' ? 'Testnet address' : level === 27 ? 'No expiration scheduled' : 'Expiration date not set yet' + const expiration = entry.retiredAt ? 'Expired — do not send here' : pendingExpiry ? 'Expiration pending — stop sharing' : entry.network !== 'mainnet' ? 'No testnet expiration schedule' : expirationEstimate(level, calendar) return

{name}

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

{expiration}

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

{level === longest ? 'Longest coverage of your saved addresses.' : level === 0 ? 'Expires before your longer-lasting addresses.' : 'Longer coverage than your original address.'}

} + {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.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 && !selected && }
- {!entry.retiredAt && !selected &&

Wallet fees apply when switching addresses.

} {!selected && <>
{total !== undefined ? <>{total.toLocaleString()} sats{money(total)} · available here : 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.

}
@@ -242,22 +248,23 @@ export default function Mountaintops() { {session.book.some(x => balances[x.keyID]?.length) &&

Wallet fees apply when moving coins.

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

No available payments found.

} -

A longer-lasting address

{suggestedEntry ? 'Saved in your wallet. Fees apply to switch.' : 'Free to find. Wallet fees apply to save it.'}

{searching ? : }
- {suggestedEntry && {suggestedEntry.address}} +

A longer-lasting address

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

{searching ? : }
+ {suggestedEntry &&

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

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

{message}

} - {candidate &&

New address found

Save it so you can recover it on any device.

Wallet fees apply. No separate switching fee.
} -
Advanced search

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

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

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

Each address has its own expiration. Expired addresses cannot receive; earlier payments remain yours.

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

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

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

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}

)}
} {!session && error &&

{error}

} -
Expiration, fees & recovery

When does my address expire?

The date depends on BRC-234 chain conditions. Until it is known, each address shows “Expiration date not set yet.” Address details show its exact stage and eligibility gate. A gate is not a guaranteed expiration date.

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. Saving search progress or switching to an older saved address each needs its own record so your choice can be recovered on another device. Network and wallet service fees may apply. 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.

+
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 && infoStage !== null && setInfoStage(null)} />} } diff --git a/frontend/src/ReceiveInfo.tsx b/frontend/src/ReceiveInfo.tsx new file mode 100644 index 0000000..9e04611 --- /dev/null +++ b/frontend/src/ReceiveInfo.tsx @@ -0,0 +1,30 @@ +import { useEffect, useRef } from 'react' +import { ANCHOR_HEIGHT, stages } from '../../shared/brc234.ts' +import type { Coverage } from './coverageClient.ts' +import { calendarEstimate, expirationEstimate, monthYear, stageEstimate } from './receiveUX.ts' + +export default function ReceiveInfo({ stage, coverage, onClose }: { stage: number; coverage: Coverage; onClose: () => void }) { + const dialog = useRef(null) + const calendar = calendarEstimate(coverage) + useEffect(() => { dialog.current?.showModal() }, []) + return +

How address expiration works

+

BRC-234 gradually narrows free blockchain lookups. Higher stages need harder-to-find addresses and last longer.

+
This address: stage {stage}

{expirationEstimate(stage, calendar)}{calendar && stage < 27 ? ' (estimate).' : '.'}

{stage === 27 ? 'BRC-234 defines no later stage. Provider availability and payment rules still apply.' : `Receiving expires when stage ${stage + 1} or a stricter stage activates.`}
+

{calendar?.projectedAnchor ? `Block 1,000,000 is projected for ${monthYear(calendar.anchor)} at about 10 minutes per block. Until it arrives, “not earlier than” dates are estimates that may move earlier or later.` : calendar ? `The schedule starts at block 1,000,000 (${monthYear(calendar.anchor)}). Dates use that block’s chain time.` : 'The calendar estimate is unavailable. Receiving eligibility still follows verified chain conditions.'} Low transaction volume can delay expiration.

+

Earlier coins remain yours. At expiration, replace this address everywhere. Mountaintops stops receiving and checking for new deposits; earlier coins can still be moved to your wallet.

+ Read the full BRC-234 proposal ↗ +
Stage schedule & payment rules +

An address passing stage N expires at the first active stage above N. Calendar and volume gates must pass, followed by a 14-day chain-time wait and activation in the following block. Stages may be skipped. These are the earliest modeled activations with enough transactions; block estimates assume 10 minutes per block. Pre-anchor estimates are not guaranteed minimum dates.

+ {calendar &&
+ + {stages.slice(1).map(row => { + const estimate = stageEstimate(row.stage, calendar) + const activated = coverage.activations.find(event => event.stage === row.stage) + return + })} +
Estimated stage activations · chain time
StageNot earlier thanApprox. block
Anchor{monthYear(calendar.anchor)}{calendar.projectedAnchor ? ' · projected' : ''}{ANCHOR_HEIGHT.toLocaleString()}
{row.stage}{activated ? `${monthYear(activated.mtp)} · activated` : monthYear(estimate.time)}{(activated?.height ?? estimate.height).toLocaleString()}{activated ? '' : ' ≈'}
} +

Payment transactions have their own eligibility rules, including transaction version 1 from stage 13. A longer-lasting address alone does not make every payment eligible for free lookup. These rules do not change coin ownership.

+
+
+} diff --git a/frontend/src/coverageClient.ts b/frontend/src/coverageClient.ts index c9f1b62..c649566 100644 --- a/frontend/src/coverageClient.ts +++ b/frontend/src/coverageClient.ts @@ -3,7 +3,7 @@ import { whatsOnChainFetch } from './whatsOnChainClient.ts' import type { WalletRecords, RecoveryRecord } from './walletRecords.ts' export type Activation = { stage: number; height: number; hash: string; mtp: number } -export type Coverage = { network: Network; height: number; hash: string; stage: number; anchorMtp: number | null; state: ChainState | null; activations: Activation[]; checkedAt: number; persistenceWarning?: string } +export type Coverage = { network: Network; height: number; hash: string; stage: number; anchorMtp: number | null; tipMtp?: number; state: ChainState | null; activations: Activation[]; checkedAt: number; persistenceWarning?: string } export type BlockInfo = { height: number; hash: string; previousblockhash: string; mediantime: number; txcount?: number; num_tx?: number } const hex64 = /^[a-f0-9]{64}$/ export function apiBase(network: Network): string { return `https://api.whatsonchain.com/v1/bsv/${network === 'mainnet' ? 'main' : 'test'}` } @@ -31,7 +31,18 @@ function validateBlock(block: BlockInfo, height: number): BlockInfo { export async function readCoverage(network: Network, records: RecoveryRecord[], store: WalletRecords, progress: (message: string) => void = () => {}): Promise { const tip = await wocJson<{ blocks: number; bestblockhash: string }>(network, '/chain/info') if (!Number.isSafeInteger(tip.blocks) || tip.blocks < 0 || !hex64.test(tip.bestblockhash)) throw new Error('Invalid chain tip') - if (network !== 'mainnet' || tip.blocks < ANCHOR_HEIGHT) return { network, height: tip.blocks, hash: tip.bestblockhash, stage: 0, anchorMtp: null, state: null, activations: [], checkedAt: Date.now() } + if (network !== 'mainnet' || tip.blocks < ANCHOR_HEIGHT) { + let tipMtp: number | undefined + if (network === 'mainnet') { + // Calendar estimates are optional display data. A failed estimate lookup + // must not invent a date or change the pre-anchor coverage rules. + try { + const block = validateBlock(await wocJson(network, `/block/height/${tip.blocks}`), tip.blocks) + if (block.hash === tip.bestblockhash) tipMtp = block.mediantime + } catch { /* Receiving remains stage 0; show the estimate as unavailable. */ } + } + return { network, height: tip.blocks, hash: tip.bestblockhash, stage: 0, anchorMtp: null, tipMtp, state: null, activations: [], checkedAt: Date.now() } + } let state: ChainState | null = null let activations: Activation[] = [] diff --git a/frontend/src/receiveUX.ts b/frontend/src/receiveUX.ts new file mode 100644 index 0000000..2fb0aa3 --- /dev/null +++ b/frontend/src/receiveUX.ts @@ -0,0 +1,43 @@ +import { ANCHOR_HEIGHT, NOTICE_SECONDS, assertReceivable, eligibilityTime, lastCoveredStage, type AddressRecord } from '../../shared/brc234.ts' +import type { Coverage } from './coverageClient.ts' + +const BLOCK_SECONDS = 600 +export type CalendarEstimate = { anchor: number; projectedAnchor: boolean } + +// Presentation only. Estimated dates/heights must never activate a stage, +// retire an address, or establish transaction eligibility. +export function calendarEstimate(coverage: Pick): CalendarEstimate | null { + if (coverage.network !== 'mainnet') return null + if (coverage.anchorMtp !== null) return { anchor: coverage.anchorMtp, projectedAnchor: false } + if (coverage.height >= ANCHOR_HEIGHT || !Number.isSafeInteger(coverage.tipMtp)) return null + return { anchor: coverage.tipMtp! + (ANCHOR_HEIGHT - coverage.height) * BLOCK_SECONDS, projectedAnchor: true } +} + +export function stageEstimate(stage: number, calendar: CalendarEstimate): { time: number; height: number } { + // Both gates must pass before the 14-chain-day waiting round can begin; + // activation is in the following block. Volume can only postpone this model. + const time = stage === 0 ? calendar.anchor : eligibilityTime(calendar.anchor, stage) + NOTICE_SECONDS + return { time, height: ANCHOR_HEIGHT + Math.ceil((time - calendar.anchor) / BLOCK_SECONDS) + (stage === 0 ? 0 : 1) } +} + +export function monthYear(timestamp: number): string { + return new Intl.DateTimeFormat('en', { month: 'long', year: 'numeric', timeZone: 'UTC' }).format(new Date(timestamp * 1000)) +} + +export function expirationEstimate(lastStage: number, calendar: CalendarEstimate | null): string { + if (lastStage === 27) return 'No expiration scheduled' + if (!calendar) return 'Expiration estimate unavailable' + return `Not earlier than ${monthYear(stageEstimate(lastStage + 1, calendar).time)}` +} + +// A display choice is free, in-memory state. A fresh connection deterministically +// opens the longest-lasting eligible saved address, with a stable key-ID tie break. +// No preference token, browser storage, or device state is needed for recovery. +export function receivingKeyID(book: AddressRecord[], stage: number, choice?: string | null): string | null { + const eligible = book.filter(entry => { + try { assertReceivable(entry, stage); return true } catch { return false } + }) + if (eligible.some(entry => entry.keyID === choice)) return choice! + eligible.sort((a, b) => lastCoveredStage(b.address) - lastCoveredStage(a.address) || (BigInt(a.keyID) < BigInt(b.keyID) ? -1 : BigInt(a.keyID) > BigInt(b.keyID) ? 1 : 0)) + return eligible[0]?.keyID ?? null +} diff --git a/frontend/src/style.css b/frontend/src/style.css index 131d577..19aa588 100644 --- a/frontend/src/style.css +++ b/frontend/src/style.css @@ -1,3 +1,5 @@ :root{font-family:Inter,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;color:#edf3f5;background:#101b23;font-synthesis:none;color-scheme:dark}*{box-sizing:border-box}body{margin:0;background:linear-gradient(#101b2355,#101b23ee 680px),url('/mountains.jpg') center top/cover fixed;min-height:100vh}main{max-width:760px;margin:auto;padding:40px 24px 32px}header{margin:0 0 32px}.brand{display:flex;align-items:center;gap:10px}.mountain-mark{display:block;width:40px;height:40px;flex-shrink:0}h1{font-size:1.6rem;letter-spacing:-.04em;margin:0}header p{color:#b7c9cd;font-size:.95rem;margin:8px 0 0 50px}h2{font-size:1.55rem;letter-spacing:-.03em;margin:0 0 12px}h3{font-size:1.05rem;margin:0}p{line-height:1.55;margin:12px 0}section{background:#142630f7;border:1px solid #344b55;border-radius:18px;padding:28px;margin:18px 0;box-shadow:0 16px 48px #0002}.view-tabs{display:flex;align-items:center;gap:4px;border-bottom:1px solid #40535a;padding-bottom:10px}.view-tabs button{background:transparent;color:#b8cbd1;padding:9px 22px}.view-tabs button[aria-pressed=true]{background:#e2f1ed;color:#15342e}.connection{margin-left:auto;font-size:.8rem;color:#a6c0b6}.receive-panel{padding:0;overflow:hidden}.address-card{padding:24px;border:1px solid #3b535d;border-radius:12px;background:#19303a;margin:14px 0}.address-card.selected{background:transparent;margin:0;border:0;border-radius:0;padding:28px}.card-heading{display:flex;align-items:center;gap:12px;justify-content:space-between;margin-bottom:18px}.selected h3{font-size:1.3rem;letter-spacing:-.02em}.badge{background:#264d43;color:#b9e4d2;border-radius:20px;padding:4px 9px;font-size:.72rem;font-weight:650;white-space:nowrap}.badge.caution{background:#61422c;color:#ffe0b1}.address{display:block;overflow-wrap:anywhere;background:#0e2029;border:1px solid #344e59;border-radius:9px;padding:16px;font-size:clamp(.9rem,2.6vw,1.05rem);letter-spacing:.01em;line-height:1.6}.coverage{color:#c6dbd8;font-size:.9rem;margin-bottom:4px}.coverage-comparison{margin:0}.expired{border-color:#c38c57}.expiry-warning{color:#ffd29a;font-weight:600}.buttons{display:flex;gap:10px;flex-wrap:wrap;margin:18px 0 0}button{font:inherit;font-size:.9rem;font-weight:650;cursor:pointer;background:#deebe9;color:#15342e;border:1px solid transparent;border-radius:8px;padding:11px 16px;margin:0}button:hover:not(:disabled){background:#fff}button:focus-visible,input:focus-visible,select:focus-visible,summary:focus-visible{outline:3px solid #ffd39a;outline-offset:3px}button:disabled{opacity:.45;cursor:default}.accent{background:#aee1cf;color:#113d30}.secondary{background:transparent;border-color:#58717b;color:#d4e5e7}.secondary:hover:not(:disabled){background:#29434c}.small{color:#a9c1c8;font-size:.82rem}.fee-note{display:block;margin:9px 0 0}.funds-row{display:flex;align-items:center;justify-content:space-between;gap:16px;border-top:1px solid #344b55;padding-top:20px;margin-top:22px}.funds-row>div{display:flex;flex-direction:column;gap:3px}.funds{font-size:1.55rem;letter-spacing:-.025em}.funds-row button{flex-shrink:0}.import-row{display:flex;align-items:center;gap:12px;margin-top:16px}.technical{font-size:.82rem;color:#adc3c9;margin:20px 0 0}.technical p{font-size:.82rem}.technical summary{font-weight:400}.mining{border-top:1px solid #344b55;padding:24px 28px;background:#172c35}.section-heading{display:flex;align-items:center;justify-content:space-between;gap:20px}.section-heading p{margin:5px 0 0}.section-heading button{flex-shrink:0}.result{padding:20px;margin:20px 0 0;background:#203e46;border:1px solid #6c9e9b;border-radius:12px}.result p{font-size:.9rem}.result .address-card{margin-bottom:0;padding:16px}.result-title{font-weight:650}.advanced{font-size:.82rem;color:#a9c1c8;margin:20px 0 0}.advanced label{font-size:.85rem}.saved-preview{margin-top:16px;font-size:.85rem}.address-list{padding:22px 28px;margin:0;border-top:1px solid #344b55}.count{font-size:.75rem;font-weight:400;background:#334c56;padding:2px 7px;border-radius:20px;margin-left:6px;color:#ccdadf}.ownership-note{text-align:center;font-size:.8rem;color:#abc5c8;padding:18px;margin:0;border-top:1px solid #344b55}.empty-state{padding:28px}.activity,.help{padding:19px 0;border-bottom:1px solid #344b55;margin:0;color:#c6d8dd;font-size:.88rem}.help h3{font-size:.95rem;margin-top:24px}.help p{font-size:.85rem;color:#b7cbd0}.help details{font-size:.82rem;margin-top:20px}.connect{padding:40px 28px}.connect>p{color:#b9cdd2;max-width:420px}.connect>button{margin:12px 0}.connect .small{font-size:.82rem}.feedback{margin-top:16px}.notice,.error{border-radius:10px;padding:12px 16px;overflow-wrap:anywhere;font-size:.87rem}.notice{background:#1b3844;border:1px solid #3e6778;margin:0 0 12px}.error{background:#481e2c;border:1px solid #e99aaa}.warning{border-color:#c38c57}.warning h2{font-size:1.15rem}.warning p{font-size:.9rem}.warning details{margin:12px 0}label{display:block;line-height:1.6;font-weight:600;font-size:.9rem;margin:20px 0}input,select{display:block;width:100%;font:inherit;color:#edf3f5;background:#0e2029;border:1px solid #58717b;border-radius:8px;padding:12px;margin-top:7px}select{white-space:normal}.send-panel>button{width:100%;margin-top:8px}summary{cursor:pointer;font-weight:550}summary::marker{color:#91b1bb}.transaction{overflow-wrap:anywhere;background:#0e2029;padding:12px;border-radius:8px;font-size:.82rem}a{color:#aed8df}footer{display:flex;justify-content:space-between;flex-wrap:wrap;gap:16px;color:#8faab4;font-size:.75rem;padding:28px 0;line-height:1.6}footer div{display:flex;gap:18px}footer a{color:#a9c3ca}@media(max-width:520px){main{padding:24px 16px}header{margin-bottom:24px}.brand h1{font-size:1.4rem}.connection{font-size:.7rem}.view-tabs button{padding:9px 17px}.address-card.selected,.mining,.address-list{padding:22px 18px}.address-card{padding:18px}.card-heading{gap:8px}.selected h3{font-size:1.15rem}.address{padding:12px;font-size:.78rem}.section-heading{align-items:flex-start;flex-direction:column;gap:14px}.section-heading button{width:100%}.funds-row{gap:10px}.funds-row button{max-width:150px;font-size:.8rem}.funds-row .small{font-size:.73rem}.result{padding:16px}.import-row{flex-wrap:wrap}.connect{padding:30px 22px}section{padding:22px}.ownership-note{font-size:.75rem}} .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}} + +.lifetime-meta{display:flex;align-items:center;gap:12px;color:#a9c1c8;font-size:.8rem;margin:5px 0 8px}.text-button{background:none;border:0;color:#b8e3d7;text-decoration:underline;text-underline-offset:3px;padding:4px 0;font-size:.8rem;font-weight:500}.text-button:hover:not(:disabled){background:none;color:#fff}.coverage{font-weight:600}.receive-info{width:min(640px,calc(100% - 32px));max-height:85dvh;overflow:auto;background:#142630;color:#edf3f5;border:1px solid #58717b;border-radius:16px;padding:28px;box-shadow:0 24px 90px #0008}.receive-info::backdrop{background:#07141dcc;backdrop-filter:blur(3px)}.modal-heading{display:flex;align-items:flex-start;gap:18px;justify-content:space-between}.modal-heading h2{font-size:1.35rem}.modal-heading button{flex-shrink:0}.receive-info p{font-size:.9rem}.receive-info details{margin:20px 0;font-size:.9rem}.stage-summary{background:#203e46;border-radius:10px;padding:16px;margin:18px 0}.stage-summary p{margin:6px 0}.schedule-scroll{max-height:300px;overflow:auto;border:1px solid #40535a;border-radius:8px;margin:16px 0}table{width:100%;border-collapse:collapse;font-size:.78rem;text-align:left}caption{padding:12px;text-align:left;color:#a9c1c8}th,td{padding:9px;border-bottom:1px solid #344b55}th{background:#203e46;position:sticky;top:0}.receive-info>a{font-size:.9rem}@media(max-width:520px){.receive-info{padding:20px}.modal-heading{gap:10px}.modal-heading h2{font-size:1.1rem}.modal-heading button{padding:8px 10px}.receive-info p{font-size:.85rem}th,td{padding:8px 6px}} diff --git a/frontend/test/fixtureWallet.mjs b/frontend/test/fixtureWallet.mjs index 06c394c..fe126b5 100644 --- a/frontend/test/fixtureWallet.mjs +++ b/frontend/test/fixtureWallet.mjs @@ -64,7 +64,7 @@ export class FixtureWallet extends ProtoWallet { const original = args.outputs?.[index] 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, status: options?.noSend ? 'nosend' : 'unproven', labels: args.labels ?? [], description: args.description }) + 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 }) return { txid, tx: tx.toAtomicBEEF() } } async abortAction() { return { aborted: true } } diff --git a/frontend/test/receiveUX.test.mjs b/frontend/test/receiveUX.test.mjs new file mode 100644 index 0000000..31edcf7 --- /dev/null +++ b/frontend/test/receiveUX.test.mjs @@ -0,0 +1,77 @@ +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 { 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('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 }) + assert.deepEqual(stageEstimate(0, calendar), { time: anchor, height: ANCHOR_HEIGHT }) + assert.equal(stageEstimate(1, calendar).time, eligibilityTime(anchor, 1) + NOTICE_SECONDS) + assert.equal(expirationEstimate(0, calendar), 'Not earlier than March 2031') + for (let stage = 1; stage <= 27; stage++) { + const current = stageEstimate(stage, calendar) + assert.ok(current.time > stageEstimate(stage - 1, calendar).time) + assert.equal(current.height, ANCHOR_HEIGHT + Math.ceil((current.time - anchor) / 600) + 1) + } + assert.equal(stageEstimate(27, calendar).time, eligibilityTime(anchor, 27) + NOTICE_SECONDS) + assert.equal(expirationEstimate(27, calendar), 'No expiration scheduled') + assert.equal(monthYear(Date.parse('2031-03-01T00:00:00Z') / 1000), 'March 2031') +}) + +test('actual anchor replaces the projection, testnet and missing chain evidence never invent dates', () => { + assert.deepEqual(calendarEstimate({ ...coverage, height: 1000002, anchorMtp: anchor + 50 }), { anchor: anchor + 50, projectedAnchor: false }) + for (const unknown of [{ ...coverage, tipMtp: undefined }, { ...coverage, network: 'testnet' }, { ...coverage, height: 1000001 }]) assert.equal(calendarEstimate(unknown), null) + assert.equal(expirationEstimate(0, null), 'Expiration estimate unavailable') + // Calendar presentation cannot disable a valid address or reactivate an expired one. + const entry = { keyID: '1', address: '1Ktest', network: 'mainnet', retiredAt: null } + assert.doesNotThrow(() => assertReceivable(entry, 0)) + assert.throws(() => assertReceivable({ ...entry, retiredAt: { height: 1000002 } }, 0), /Expired/) +}) + +test('free session choices survive refresh, fresh sessions default deterministically, and expired choices fall back', () => { + const book = [ + { keyID: '1', address: '1Ktest', network: 'mainnet', retiredAt: null }, + { keyID: '18', address: '1Chitest', network: 'mainnet', retiredAt: null }, + { keyID: '17', address: '1Chitest', network: 'mainnet', retiredAt: null } + ] + assert.equal(receivingKeyID(book, 0), '17') + assert.equal(receivingKeyID([...book].reverse(), 0), '17') + assert.equal(receivingKeyID(book, 0, '1'), '1') + assert.equal(receivingKeyID(book, 1, '1'), '17') + book[2].retiredAt = { height: 1000002 } + assert.equal(receivingKeyID(book, 0, '17'), '18') + assert.equal(receivingKeyID(book, 27), null) + assert.equal(receivingKeyID(book.map(x => ({ ...x, retiredAt: { height: 1000002 } })), 0), null) +}) + +test('pre-anchor calendar lookup validates tip identity, remains read-only and fails independently of coverage', async () => { + const previous = globalThis.fetch + let mode = 'valid', writes = 0 + const calls = [] + globalThis.fetch = async url => { + calls.push(String(url)) + if (String(url).endsWith('/chain/info')) return Response.json({ blocks: coverage.height, bestblockhash: 'a'.repeat(64) }) + if (mode === 'unavailable') throw new Error('Display estimate unavailable') + return Response.json({ height: coverage.height, hash: (mode === 'reorg' ? 'b' : 'a').repeat(64), previousblockhash: 'c'.repeat(64), mediantime: coverage.tipMtp }) + } + const store = { append: async () => { writes++; throw new Error('Unexpected wallet transaction') } } + try { + const fresh = await readCoverage('mainnet', [], store) + assert.equal(fresh.tipMtp, coverage.tipMtp) + assert.equal(calendarEstimate(fresh).anchor, anchor) + for (mode of ['reorg', 'unavailable']) { + const incomplete = await readCoverage('mainnet', [], store) + assert.equal(incomplete.stage, 0) + assert.equal(calendarEstimate(incomplete), null) + } + calls.length = 0 + assert.equal(calendarEstimate(await readCoverage('testnet', [], store)), null) + assert.equal(calls.length, 1) + assert.equal(writes, 0) + } finally { globalThis.fetch = previous } +}) diff --git a/frontend/test/ui.html b/frontend/test/ui.html index 02fc766..c5cf2a6 100644 --- a/frontend/test/ui.html +++ b/frontend/test/ui.html @@ -1,14 +1,27 @@ Mountaintops isolated UI fixture