diff options
Diffstat (limited to 'src/features')
| -rw-r--r-- | src/features/ark.js | 658 | ||||
| -rw-r--r-- | src/features/gifts-wallet.js | 4 | ||||
| -rw-r--r-- | src/features/gifts.js | 167 | ||||
| -rw-r--r-- | src/features/messages.js | 396 | ||||
| -rw-r--r-- | src/features/names.js | 106 | ||||
| -rw-r--r-- | src/features/nostrlogin.js | 10 | ||||
| -rw-r--r-- | src/features/nwc.js | 62 |
7 files changed, 1091 insertions, 312 deletions
diff --git a/src/features/ark.js b/src/features/ark.js index 3ef6cea..b8e83a7 100644 --- a/src/features/ark.js +++ b/src/features/ark.js @@ -8,7 +8,7 @@ import * as btc from '@scure/btc-signer'; import { HDKey } from '@scure/bip32'; import { hex, base32nopad, bech32 } from '@scure/base'; import { sha256 } from '@noble/hashes/sha256'; -import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, backstopMargin } from '../ark/manager.js'; +import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, sameDelivery, renewPolicy, CUSTODY_TIERS } from '../ark/manager.js'; export { remoteRenewalsInFlight }; // Coins this device may offer: spendable, and not held by a renewal another @@ -18,6 +18,17 @@ function freeCoins(st) { const busy = new Set(remoteRenewalsInFlight(st).flatMap((r) => r.inputIds || [])); return (st.vtxos || []).filter((v) => v.state === 'spendable' && !busy.has(v.id)); } +// The coins a unilateral exit can still take on-chain. Past its timelock a +// coin's tree is the server's to sweep (and it has): only the server can +// honor it now, and it does — but no exit transaction will ever confirm. +function exitableCoins(st, tip) { + return freeCoins(st).filter((v) => !(tip && v.expiryHeight && v.expiryHeight <= tip)); +} +// The crash-loop guard's phase notes (build.js BOOT_GUARD, app.js bootPhase): +// a boot iOS killed shows the last one it reached, and three in a row open +// the app in safe mode, where nothing connects on its own. +const bootPhase = (p) => { try { localStorage.setItem('coinos-boot-phase', p); } catch {} }; +const safeBoot = () => !!(typeof window !== 'undefined' && window.__safeBoot); import { loadBg, saveBg, buildBg, disarmSiblingRecords } from '../nwc-bg.js'; import { boardFee, p2trAddress } from '../ark/board.js'; import { maybeBolt11, maybeLnInvoice, lnSendFee, lnShortfall } from '../ark/lightning.js'; @@ -32,7 +43,7 @@ import { t } from '../i18n.js'; import { rateNow } from '../rates.js'; import { resolveBip353, parsePaymentName, parseBip21 as parseBip21Uri } from '../bip353.js'; import { parseZapTarget, fetchPayParams, requestInvoice } from '../lnurl.js'; -import { shortAddr, shortTxid, timeAgo, fmtSats, ARK_ICON, ARK_MARK, BITCOIN_ICON } from '../format.js'; +import { shortAddr, shortTxid, timeAgo, fmtSats, fmtBtc, ARK_ICON, ARK_MARK, BITCOIN_ICON } from '../format.js'; // t?ark1… bech32m — an Ark address for this or another ASP. export function isArkAddress(a) { return /^t?ark1[a-z0-9]{20,}$/i.test((a || '').trim()); } @@ -454,8 +465,41 @@ export function arkFeature(ctx) { // One manager per open wallet; null when Ark is off in Settings, watch-only, // or not yet dialed (lazy: fresh wallets connect on first use). let ark = null; + // The same manager the moment its own init is done (server info, tip, + // persisted coins) — before the Nostr snapshot restore that `ark` also + // waits for, which can take ten seconds on a slow relay/Blossom day. For + // READING only: the pages price and label coins from it; anything that + // acts (a renewal, an exit) still waits for `ark`. + let arkInited = null; + const arkView = () => ark || arkInited; + // An amount in bitcoin terms whatever the display unit: sats, or BTC when + // that is the unit chosen — never fiat. A co-operative exit moves coins, + // and the number on its button is the coins' own. + const fmtNative = (sat) => (unitLabel() === 'BTC' ? fmtBtc(sat) + ' BTC' : fmtSats(sat) + ' sats'); + // The last server info and chain tip seen, per server, so the first paint + // after a refresh shows the real renewal price and expiries instead of + // "free" and "—" for the half second the info call takes. + const ARK_INFO_KEY = 'btc-wallet-arkinfo:'; + function cachedArkInfo(url) { + try { return url ? JSON.parse(localStorage.getItem(ARK_INFO_KEY + url) || 'null') : null; } catch { return null; } + } + function rememberArkInfo(url, info, tip) { + try { + if (!url || !info) return; + // no tip yet (right after init): keep the last one seen, dated as it was + const prev = tip ? null : cachedArkInfo(url); + localStorage.setItem(ARK_INFO_KEY + url, JSON.stringify(tip ? { info, tip, at: Date.now() } : { info, tip: (prev && prev.tip) || 0, at: (prev && prev.at) || Date.now() })); + } catch {} + } + // the tip, live or estimated from the last one seen (a block per ten minutes) + function arkTipNow(mgr) { + if (mgr && mgr._tipH) return mgr._tipH; + const c = cachedArkInfo((getArkConfig() || {}).ark); + return c && c.tip ? c.tip + Math.floor((Date.now() - (c.at || Date.now())) / 600_000) : 0; + } let arkTimer = null; let arkConnectPromise = null; + let arkInitPromise = null; // the manager's own init, apart from the snapshot gate let arkInitGen = 0; // guards against a stale init() resolving after a wallet switch function stopArk() { @@ -474,7 +518,9 @@ export function arkFeature(ctx) { clearTimeout(lnTagT); lnTagSeen = -1; ark = null; + arkInited = null; arkConnectPromise = null; + arkInitPromise = null; // The renewal warning describes the coins of the wallet we're leaving. // Switching accounts used to carry it onto the next one — with the old // wallet's amount and deadline, over the new wallet's balance — and the @@ -506,9 +552,11 @@ export function arkFeature(ctx) { // holds is on screen the moment it can be. const store = wallet._arkStore; if (store && !store.ready) { + bootPhase('ark-store'); store.open().then(() => { ctx.forgetAmountAnim && ctx.forgetAmountAnim(); render(); initArk(); }).catch(() => {}); return; } + if (safeBoot()) return; // safe mode: the coins show from the store; nothing dials out unasked if (arkAvailable() && arkWanted()) { lastAutoInit = Date.now(); connectArk().then(() => rescueOtherServers()).catch(() => {}); } } @@ -541,7 +589,7 @@ export function arkFeature(ctx) { adopt: (serverPubkey) => wallet.adoptArkState(serverPubkey, p.ark), save: (s) => { wallet.saveArkState(mergeArkStates(s, wallet.loadArkState(p.ark)), p.ark); }, }, - arkUrl: p.ark, esploraUrl: p.esplora, network: getNetwork(), + arkUrl: p.ark, esploraUrl: p.esplora, network: getNetwork(), honorsExpired: !!p.honorsExpired, }); await mgr.init(); const done = () => (mgr.state.movements || []).filter((m) => m.type === 'ln-receive' && m.status === 'complete'); @@ -555,7 +603,7 @@ export function arkFeature(ctx) { } } function maybeInitArk() { - if (ark || arkConnectPromise) return; + if (ark || arkConnectPromise || safeBoot()) return; if (Date.now() - lastAutoInit < 20000) return; // A fresh snapshot may be held under its server pubkey, so arkWanted() // cannot see it until the handshake identifies the server and adopts it. @@ -623,6 +671,10 @@ export function arkFeature(ctx) { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), + honorsExpired: !!cfg.honorsExpired, + // the server's last published info: the wallet opens on it when the + // server is gone, so coins can still be read and exited + infoHint: (cachedArkInfo(cfg.ark) || {}).info || null, // the wallet's own tx table as a second witness for confirmations — // its data source is user-configurable and often healthier than the // ark preset's esplora from this device @@ -636,9 +688,27 @@ export function arkFeature(ctx) { // Open the server connection while Nostr restores, but do not replay the // mailbox before the snapshot's history and cursor have arrived. const restored = Promise.resolve(wallet.nostrRestoreReady || wallet.syncFromNostr?.()).catch(() => false); - arkConnectPromise = Promise.all([mgr.init(), restored]).then(() => { + bootPhase('ark-init'); + const inited = mgr.init().then(() => { + if (gen !== arkInitGen) return; + bootPhase('ark-inited'); + arkInited = mgr; // readable now; `ark` (and the mailbox) wait for the snapshot + if (!mgr.offline) rememberArkInfo(cfg.ark, mgr.info, mgr._tipH); + render(); + }); + arkInitPromise = inited; + // The tip: expiries and exit costs are judged against it, and init alone + // never asks for it (the first sync does, after the snapshot gate). Ask + // now, off the connect path, and remember it for the next refresh. + inited.then(() => mgr._tipMemo()).then(() => { + if (gen !== arkInitGen || !mgr._tipH) return; + rememberArkInfo(cfg.ark, mgr.info, mgr._tipH); + render(); + }).catch(() => {}); + arkConnectPromise = Promise.all([inited, restored]).then(() => { if (gen !== arkInitGen) throw new Error('superseded'); // wallet switched mid-connect ark = mgr; + bootPhase('ark-adopt'); // Sync may have arrived while init awaited the server handshake. adoptArkSnapshot(mgr, wallet.loadArkState(cfg.ark)); // Boards that died before funding (a failed tx build, a closed tab) @@ -679,12 +749,14 @@ export function arkFeature(ctx) { // sync() already reconciles on its first pass. Start the live stream // afterwards, at the caught-up cursor: running both together replayed // the backlog one message/render at a time alongside the batch read. + bootPhase('ark-sync'); tick().finally(() => { if (ark === mgr) mgr.startMailboxStream(); }); mergeBgWorkerState(mgr).catch(() => {}); // absorb what the SW did while we were closed // Receives arrive in real time over the mailbox stream; the poll is the // fallback and what drives in-flight boards/refreshes forward. scheduleLnTag(mgr); // receives that landed while this device was closed arkTimer = setInterval(() => { if (ark === mgr) tick(); }, getNetwork() === 'regtest' ? 5000 : 30000); + bootPhase('ark-ready'); render(); return mgr; }).catch((e) => { @@ -923,6 +995,26 @@ export function arkFeature(ctx) { // connections/offer belong to the nwc feature; when it isn't the caller // (an auto-withdraw setting changed, say) carry forward what's mirrored // rather than blanking someone's wallet connections. + // The mirror carries hundreds of pre-derived keys (BG_KEY_LOOKAHEAD) and + // is rewritten after every state change: derive each index once per + // account, not once per write. + const bgKeyMemo = new WeakMap(); // account node -> Map('chain:i' -> hex) + function bgKeyFor(account) { + let m = bgKeyMemo.get(account); + if (!m) { m = new Map(); bgKeyMemo.set(account, m); } + const chains = new Map(); + return (chain, i) => { + const k = chain + ':' + i; + let v = m.get(k); + if (!v) { + let node = chains.get(chain); + if (!node) { node = account.deriveChild(chain); chains.set(chain, node); } + v = hex.encode(node.deriveChild(i).privateKey); + m.set(k, v); + } + return v; + }; + } async function writeBgMirror(connections, offer, prefs) { const cfg = getArkConfig(); if (!cfg || !ark || !ark.info || !ark.state) return; @@ -931,14 +1023,15 @@ export function arkFeature(ctx) { if (offer === undefined) offer = (prev && prev.offer) || null; if (prefs === undefined) prefs = (prev && prev.prefs) || undefined; const rec = buildBg({ - ark: { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), serverPubkey: ark.info.serverPubkey }, + ark: { arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), serverPubkey: ark.info.serverPubkey, honorsExpired: !!cfg.honorsExpired }, mgrState: ark.state, - keyFor: (chain, i) => hex.encode(ark.account.deriveChild(chain).deriveChild(i).privateKey), + custody: getCustody(), + keyFor: bgKeyFor(ark.account), connections, offer, autowithdraw: await awMirror(prev), }); - if (prev) rec.spends = prev.spends; // the worker's log survives rewrites + if (prev) { rec.spends = prev.spends; rec.pendingPays = prev.pendingPays; } // the worker's log survives rewrites if (prefs) rec.prefs = prefs; // notification choices the worker honours await saveBg(wallet._cacheKey(), rec); await disarmSiblingRecords(wallet._cacheKey(), rec).catch(() => {}); @@ -957,6 +1050,7 @@ export function arkFeature(ctx) { return; } if (!rec.mgr) return; + bootPhase('ark-merge'); const merged = mergeArkStates(mgr.state, rec.mgr); // the worker's view of OUR vtxos is newer for anything it spent const workerState = new Map((rec.mgr.vtxos || []).map((v) => [v.id, v.state])); @@ -966,8 +1060,11 @@ export function arkFeature(ctx) { merged.nextKeyIndex = Math.max(merged.nextKeyIndex || 1, rec.mgr.nextKeyIndex || 1); mgr.state = merged; mgr._save(); + bootPhase('ark-merged'); await mgr.reconcile().catch(() => {}); + bootPhase('ark-reconciled'); await mgr.resumePending().catch(() => {}); + bootPhase('ark-resumed'); } // A leftover chain-6 pouch from before whole-balance background spending: @@ -987,7 +1084,7 @@ export function arkFeature(ctx) { const pm = await new ArkManager({ account: shim, storage: { load: () => state, save: (s2) => { state = s2; } }, - arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), + arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired, }).init(); const dest = mgr.address(); for (let guard = 0; guard < 30; guard++) { @@ -1422,9 +1519,12 @@ export function arkFeature(ctx) { h('span', { class: g.claimed ? 'tag conf' : 'tag' }, g.claimed ? t('giftClaimedTag') : g.revoked ? t('giftRevokedTag') : t('giftUnclaimedTag'))); })(), - (() => { const pk = zapNoteFor(m); return pk ? ctx.hook('profileChip', pk) : null; })(), - m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null), - h('div', { class: 'small faint' }, timeAgo(m.ts / 1000))), + (() => { const pk = zapNoteFor(m); return pk ? ctx.hook('profileChip', pk) : null; })()), + // the status tag sits by the time, not the name: in the narrow wallet + // column the title row has room for the label and the chip, not a + // third thing — the chip was breaking mid-name to make space + h('div', { class: 'row gap6 small faint' }, timeAgo(m.ts / 1000), + m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null)), h('div', { style: 'text-align:right' }, // in fiat this is what the payment was worth when it was made h('div', { class: failed ? 'muted' : incoming ? 'amount-pos' : 'amount-neg' }, fmtAmount(m.amountSat, m.ts / 1000))) @@ -1593,6 +1693,7 @@ export function arkFeature(ctx) { })(), m.to ? row(t('arkPayTo'), shortAddr(m.to, 16, 12)) : null, m.vtxoId ? row(t('arkVtxoId'), shortTxid(m.vtxoId)) : null, + m.type === 'receive' ? coinListRows(t('arkVtxoId'), m.vtxoIds) : null, // the coins this payment consumed — a send can gather up to 24 inputs coinListRows(t('arkVtxoInputs'), m.inputIds), // An offboard's fee is two different pockets — the miners' cut for the @@ -1641,7 +1742,7 @@ export function arkFeature(ctx) { const g = giftForMovement(m); const open = g && !g.claimed && !g.revoked; const chips = [ - open ? copyBtn(`${location.origin}/g/${encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex))}`, t('giftCopyLinkAgain')) : null, + open ? copyBtn(`${location.origin}/g/${encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex))}${g.note ? '#m=' + encodeURIComponent(g.note) : ''}`, t('giftCopyLinkAgain')) : null, m.preimage ? copyBtn(m.preimage, t('copyPreimage')) : null, m.txid ? copyBtn(m.txid, t('copyTxid')) : null, m.txid ? h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('viewOnMempool')) : null, @@ -2147,23 +2248,8 @@ export function arkFeature(ctx) { const spk = btc.OutScript.encode(btc.Address(wallet.netCfg.net).decode(target.address)); // Offboarding moves whole vtxos, so carve out the exact amount first // when we're not sending everything. - const spendables = () => freeCoins(mgr.state); - const total = spendables().reduce((n, v) => n + v.amountSat, 0); - let ids; - if (amountSat < total) { - let exact = spendables().find((v) => v.amountSat === amountSat); - if (!exact) { - const before = new Set(spendables().map((v) => v.id)); - await mgr.send(mgr.address(), amountSat); - for (let i = 0; i < 30 && !exact; i++) { - await new Promise((r) => setTimeout(r, 2000)); - await mgr.sync().catch(() => {}); - exact = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id)); - } - if (!exact) throw new Error(t('arkSplitTimeout')); - } - ids = [exact.id]; - } + const total = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0); + const ids = amountSat < total ? await carveCoins(mgr, amountSat) : undefined; await mgr.startOffboard(spk, target.address, ids); return; } @@ -2301,7 +2387,7 @@ export function arkFeature(ctx) { // page, or a tap before the manager has connected (the first seconds // after boot) found no coins and closed itself — Manage needed two taps. // The manager is dialled meanwhile; what needs it live waits for it. - const mgr = ark; + const mgr = arkView(); const st = (mgr && mgr.state) || arkStateNow(); // another device's renewal holds its coins just the same: greyed here too const elsewhere = st ? remoteRenewalsInFlight(st) : []; @@ -2313,7 +2399,11 @@ export function arkFeature(ctx) { const renewing = ((st && st.actions) || []).filter((a) => a.type === 'refresh' && !['done', 'failed'].includes(a.step)); const inRound = new Set([...renewing, ...elsewhere].flatMap((a) => a.inputIds || [])); const pendingCoins = ((st && st.vtxos) || []).filter((v) => (v.state === 'pending' || v.state === 'spendable') && inRound.has(v.id)); - const tip = (mgr && mgr._tipH) || 0; + const tip = arkTipNow(mgr); + // the coinos servers keep honoring a coin past its timelock: it is held + // by coinos, not expired — still money, just not exitable on its own + const honors = !!(mgr && mgr.honorsExpired); + const exitable = exitableCoins(st, tip); const back = embedded ? () => { ui.arkCoinsSel = null; ui.arkRenewConfirm = null; ctx.goHome(); } : () => ctx.goBack(() => { ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkRenewConfirm = null; }); // the page is a history entry now @@ -2335,7 +2425,7 @@ export function arkFeature(ctx) { const expiresOf = (v) => { if (!v.expiryHeight || !tip) return '—'; const blocks = v.expiryHeight - tip; - if (blocks <= 0) return t('arkCoinsExpired'); + if (blocks <= 0) return honors ? t('arkCoinsHeld') : t('arkCoinsExpired'); return blocks >= 144 ? Math.round(blocks / 144) + 'd' : Math.max(1, Math.round(blocks / 6)) + 'h'; }; // what pulling THIS coin on-chain alone would cost: every hop's fee @@ -2353,10 +2443,11 @@ export function arkFeature(ctx) { // bracket the share is zero, where the wallet renews on its own anyway. // A flat base fee (the round's on-chain cost, which coinos stopped // absorbing in October 2026) rides on top of every bracket. - const table = (((mgr && mgr.info) || {}).refreshFees || {}).ppmExpiryTable || []; - const baseSat = (((mgr && mgr.info) || {}).refreshFees || {}).baseFeeSat || 0; + const infoNow = (mgr && mgr.info) || (cachedArkInfo((getArkConfig() || {}).ark) || {}).info || {}; + const table = (infoNow.refreshFees || {}).ppmExpiryTable || []; + const baseSat = (infoNow.refreshFees || {}).baseFeeSat || 0; const baseCost = fmtSats(baseSat) + ' sats'; - const roundMins = Math.max(1, Math.round((((mgr && mgr.info) || {}).roundIntervalSecs || 120) / 60)); + const roundMins = Math.max(1, Math.round((infoNow.roundIntervalSecs || 120) / 60)); const roundEvery = roundMins === 1 ? t('arkCoinsRoundEveryOne') : t('arkCoinsRoundEvery', { n: roundMins }); const ppmFor = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0; // A coin's SHARE of the renewal fee, fractional: the server totals the @@ -2394,6 +2485,12 @@ export function arkFeature(ctx) { for (const id of ui.arkCoinsSel) if (!ids.has(id)) ui.arkCoinsSel.delete(id); const sel = ui.arkCoinsSel; const selCoins = spend.filter((v) => sel.has(v.id)); + // the three actions below the table act on the ticked coins + const selExitable = selCoins.filter((v) => exitable.includes(v)); + const selExitSat = selExitable.reduce((n, v) => n + v.amountSat, 0); + let selExitFee = 0; try { if (mgr) selExitFee = estimateExitFeeSat(mgr, selExitable); } catch {} + const subset = selCoins.length > 0 && selCoins.length < spend.length; + const coopSat = subset ? selCoins.reduce((n, v) => n + v.amountSat, 0) : spendableSat; let selFee = 0; try { selFee = mgr.refreshFee(selCoins, tip); } catch {} const renew = () => { if (!selCoins.length || !mgr) return; @@ -2404,6 +2501,20 @@ export function arkFeature(ctx) { ui.arkRenewConfirm = null; render(); // the page stays: the coins show as renewing }; + // What a renewal is and what it costs, told where it is decided: on the + // confirmation, not as a card on the page (the page is the coins and + // their three buttons; the explainers were a wall under them). + const renewExplainer = () => [ + h('p', { class: 'small muted', style: 'margin:0' }, getCustody() === 'custodial' && honors + ? t('arkCoinsRenewDescCustodial', { every: roundEvery, base: baseSat ? baseCost : t('arkDepthFree') }) + : baseSat + ? t('arkCoinsRenewDescBase', { every: roundEvery, base: baseCost }) + : t('arkCoinsRenewDesc', { every: roundEvery })), + schedule.length ? h('div', { class: 'col', style: 'gap:2px;margin:2px 0' }, + ...schedule.map((r) => h('div', { class: 'row between' }, + h('span', { class: 'small muted' }, r.label), + h('span', { class: 'small' + (r.free ? ' faint' : '') }, r.cost)))) : null, + ]; // "Renew" asks once, with the numbers on the table: the coins it takes // can't be spent until the round's transaction confirms, it can't be // called back, and by default it takes every coin. (A user renewed their @@ -2416,6 +2527,7 @@ export function arkFeature(ctx) { h('div', { class: 'card col', style: 'gap:10px' }, h('h3', { style: 'margin:0' }, t('arkRenewConfirmTitle')), h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmBody')), + ...renewExplainer(), h('div', { class: 'col', style: 'gap:4px' }, row(t('arkExitConfirmCoins'), String(selCoins.length)), row(t('arkExitConfirmAmount'), fmtSats(selSat) + ' sats'), @@ -2423,7 +2535,7 @@ export function arkFeature(ctx) { row(t('arkRenewConfirmLeft'), fmtSats(leftSat) + ' sats', leftSat ? '' : 'err')), leftSat ? null : h('div', { class: 'notice err small' }, t('arkRenewConfirmAll')), h('p', { class: 'small muted', style: 'margin:0' }, t('arkRenewConfirmWait')), - h('button', { class: 'btn-primary btn-block ark-renew-go', disabled: !!ui.arkBusy || !mgr, onClick: renew }, + h('button', { class: 'btn-primary btn-block ark-renew-go', disabled: !!ui.arkBusy || !ark, onClick: renew }, selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))), h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.arkRenewConfirm = null; render(); } }, t('cancel'))); } @@ -2456,22 +2568,23 @@ export function arkFeature(ctx) { // is published: an exit cannot be called back. if (ui.arkExitConfirm) { const savings = wallet.spendable || 0; - const short = savings < exitFee; + const short = savings < selExitFee; const row = (k, v, cls = '') => h('div', { class: 'row between' }, h('span', { class: 'small muted' }, k), h('span', { class: 'small' + (cls ? ' ' + cls : '') }, v)); return h('div', { class: 'col', style: 'gap:16px' }, h('div', { class: 'card col', style: 'gap:10px' }, h('h3', { style: 'margin:0' }, t('arkExitConfirmTitle')), h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmBody')), + h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoinsExitDesc', { fee: fmtSats(selExitFee), after: fmtSats(afterFee) })), h('div', { class: 'col', style: 'gap:4px' }, - row(t('arkExitConfirmCoins'), String(spend.length)), - row(t('arkExitConfirmAmount'), fmtSats(totalSat) + ' sats'), - row(t('arkExitConfirmFee'), fmtSats(exitFee) + ' sats'), + row(t('arkExitConfirmCoins'), String(selExitable.length)), + row(t('arkExitConfirmAmount'), fmtSats(selExitSat) + ' sats'), + row(t('arkExitConfirmFee'), fmtSats(selExitFee) + ' sats'), row(t('arkExitConfirmSavings'), fmtSats(savings) + ' sats', short ? 'err' : '')), - short ? h('div', { class: 'notice err small' }, t('arkExitFeeShort', { need: fmtSats(exitFee), have: fmtSats(savings) })) : null, + short ? h('div', { class: 'notice err small' }, t('arkExitFeeShort', { need: fmtSats(selExitFee), have: fmtSats(savings) })) : null, h('p', { class: 'small muted', style: 'margin:0' }, t('arkExitConfirmWait')), - h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || short || !spend.length, onClick: () => { + h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || short || !selExitable.length, onClick: () => { ui.arkExitConfirm = null; - doArkExit(); + doArkExit(selExitable.map((v) => v.id)); ui.arkCoinsSel = null; back(); ui.tab = 'history'; // the exit lives as a pending record there @@ -2522,7 +2635,8 @@ export function arkFeature(ctx) { h('tbody', {}, ...spend.map((v) => { const f = feeNowOf(v); const xf = exitFeeOf(v); - const due = !!(v.expiryHeight && tip && v.expiryHeight - tip <= 0) || !!v.expiryRejected; + const past = !!(v.expiryHeight && tip && v.expiryHeight - tip <= 0); + const due = (past && !honors) || !!v.expiryRejected; // expired and under the floor: nothing can renew it, so the // last column offers to give it up const lost = due && v.amountSat < 330; @@ -2545,43 +2659,78 @@ export function arkFeature(ctx) { h('td', { class: 'num' }, fmtSats(v.amountSat), h('span', { class: 'small faint' }, ' sats')), h('td', { class: 'num' }, expiresOf(v)), h('td', { class: 'num' }, '—'), - h('td', { class: 'num' }, h('span', { class: 'tag pending' }, t('arkCoinsRenewing'))))))))), + h('td', { class: 'num' }, h('span', { class: 'tag pending' }, t('arkCoinsRenewing')))))))), + // What the ticked coins can do, right under them: renew, withdraw + // (the co-operative exit, into Savings) or exit on their own. Each + // names the ticked total it acts on. + // present even while every coin is in a round: disabled, so the page + // keeps its shape and says why nothing can be done + h('div', { class: 'col ark-coin-actions', style: 'gap:6px;margin-top:4px' }, + h('button', { class: 'btn-primary btn-block ark-renew-ask', disabled: !!ui.arkBusy || !selCoins.length || !ark, onClick: () => { ui.arkRenewConfirm = true; render(); try { window.scrollTo({ top: 0 }); } catch {} } }, + !selCoins.length ? t('arkCoinsRenewNone') + : selCoins.length < spend.length + ? t('arkCoinsRenewSome', { n: selCoins.length, fee: selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree') }) + : selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn')), + h('button', { class: 'btn-ghost btn-block ark-coop-go', disabled: !!ui.arkBusy || !coopSat || !selCoins.length || wallet.watchOnly, onClick: () => { + const address = wallet.freshReceive().address; + const vtxoIds = subset ? selCoins.map((v) => v.id) : undefined; + ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkExitPage = null; ui.arkExitConfirm = null; ui.arkRenewConfirm = null; + ui.arkOffboarded = null; ui.arkError = ''; + ctx.showSend({ fresh: true }); + ui.arkOffboardSend = { address, amount: String(coopSat), fromCoins: true, vtxoIds }; + render(); + } }, t('arkCoinsWithdrawBtn', { amount: fmtNative(coopSat) })), + h('button', { class: 'btn-ghost btn-block ark-exit-ask', disabled: !!ui.arkBusy || !selExitable.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } }, + t('arkCoinsExitBtnAmt', { amount: fmtNative(selExitSat) })))), renewingCard, - h('div', { class: 'card col', style: 'gap:8px' }, - h('h4', { style: 'margin:0' }, t('arkCoinsRenewTitle')), - // the round cadence comes from the server (it has been an hour and - // is two minutes as of September 2026) — never a number baked in here - h('p', { class: 'small muted', style: 'margin:0' }, baseSat - ? t('arkCoinsRenewDescBase', { every: roundEvery, base: baseCost }) - : t('arkCoinsRenewDesc', { every: roundEvery })), - schedule.length ? h('div', { class: 'col', style: 'gap:2px;margin:2px 0' }, - ...schedule.map((r) => h('div', { class: 'row between' }, - h('span', { class: 'small muted' }, r.label), - h('span', { class: 'small' + (r.free ? ' faint' : '') }, r.cost)))) : null, - !spend.length ? null : h('button', { class: 'btn-primary btn-block ark-renew-ask', disabled: !!ui.arkBusy || !selCoins.length || !mgr, onClick: () => { ui.arkRenewConfirm = true; render(); try { window.scrollTo({ top: 0 }); } catch {} } }, - !selCoins.length ? t('arkCoinsRenewNone') - : selCoins.length < spend.length - ? t('arkCoinsRenewSome', { n: selCoins.length, fee: selFee > 0 ? fmtSats(selFee) + ' sats' : t('arkDepthFree') }) - : selFee > 0 ? t('arkCoinsRenewNowFee', { fee: fmtSats(selFee) + ' sats' }) : t('arkDepthRenewBtn'))), - h('div', { class: 'card col', style: 'gap:8px' }, - h('h4', { style: 'margin:0' }, t('arkCoinsCoopTitle')), - h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')), - h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy || !spendableSat || wallet.watchOnly, onClick: () => { - const address = wallet.freshReceive().address; - ui.arkCoinsPage = null; ui.arkCoinsSel = null; ui.arkExitPage = null; ui.arkExitConfirm = null; ui.arkRenewConfirm = null; - ui.arkOffboarded = null; ui.arkError = ''; - ctx.showSend({ fresh: true }); - ui.arkOffboardSend = { address, amount: String(spendableSat), fromCoins: true }; - render(); - } }, t('arkOffboardBtn', { n: fmtAmount(spendableSat) + ' ' + unitLabel() }))), - h('div', { class: 'card col', style: 'gap:8px' }, - h('h4', { style: 'margin:0' }, t('arkCoinsExitTitle')), - h('p', { class: 'small muted', style: 'margin:0' }, - t('arkCoinsExitDesc', { fee: fmtSats(exitFee), after: fmtSats(afterFee) })), - h('button', { class: 'btn-ghost btn-block', disabled: !!ui.arkBusy || !spend.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } }, t('arkCoinsExitBtn'))), + embedded ? custodyCard() : null, embedded ? null : h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back'))); } + // Who holds the coins once their timelock runs out — the user's call, made + // here, with what each option costs in the server's own numbers. The + // default is coinos: most people come from v2, where coinos held + // everything, and the server honors a coin past its timelock anyway. The + // two renewing tiers are the opt-ins, for those who want the exit kept + // (self) or kept cheap by flattening deep histories early (exit). Only + // shown on a server that honors expired coins; elsewhere renewal is the + // only way to keep money. + function custodyCard() { + if (!arkAvailable() || wallet.watchOnly) return null; + const cfg = getArkConfig(); + const view = arkView(); + const info = (view && view.info) || (cachedArkInfo(cfg && cfg.ark) || {}).info || null; + const honors = !!(cfg && cfg.honorsExpired); + const cur = getCustody(); // never 'custodial' on a server that doesn't honor expired coins + const base = (info && info.refreshFees && info.refreshFees.baseFeeSat) || 0; + const table = (info && info.refreshFees && info.refreshFees.ppmExpiryTable) || []; + const ppmAt = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0; + const lifeDays = Math.max(1, Math.round(((info && info.vtxoExpiryDelta) || 8640) / 144)); + const baseCost = !info ? '…' : base ? fmtSats(base) + ' sats' : t('arkDepthFree'); + // an early renewal pays the bracket a fresh coin sits in (the top one) + const earlyPct = pct(ppmAt(((info && info.vtxoExpiryDelta) || 8640) - 1)); + const hops = (renewPolicy('exit', getNetwork()) || {}).maxDepth || 4; + const tiers = [ + { id: 'custodial', label: t('arkCustodyCustodial'), desc: t('arkCustodyCustodialDesc'), cost: t('arkCustodyCostNone') }, + { id: 'self', label: t('arkCustodySelf'), desc: t('arkCustodySelfDesc', { days: lifeDays }), cost: t('arkCustodyCostSelf', { base: baseCost }) }, + { id: 'exit', label: t('arkCustodyExit'), desc: t('arkCustodyExitDesc', { hops }), cost: t('arkCustodyCostExit', { pct: earlyPct, base: baseCost }) }, + ].filter((x) => honors || x.id !== 'custodial'); + const chosen = tiers.find((x) => x.id === cur) || tiers[0]; + // A drop-down, and only the chosen strategy's description under it: three + // paragraphs at once read as a wall, and two of them are about choices + // the reader has not made. + return h('div', { class: 'card col ark-custody', style: 'gap:10px' }, + h('h4', { style: 'margin:0' }, t('arkCustodyTitle')), + h('p', { class: 'small muted', style: 'margin:0' }, t('arkCustodyDesc', { days: lifeDays })), + h('select', { id: 'ark-custody-select', disabled: !honors, onChange: (e) => applyCustody(e.target.value) }, + ...tiers.map((x) => h('option', { value: x.id, selected: x.id === cur }, x.label))), + // the price under the choice, not in the option (a long option text + // overflows the select on a phone) + h('div', { class: 'small ark-custody-cost' }, chosen.cost), + h('p', { class: 'small muted ark-custody-desc', style: 'margin:0' }, chosen.desc), + honors ? null : h('p', { class: 'small faint', style: 'margin:0' }, t('arkCustodyNotHere'))); + } + // What each server charges and promises, from its own published info — // laid side by side under the switcher so the choice is an informed one. const serverInfos = new Map(); // url -> info | null (failed) | undefined (loading) @@ -2799,9 +2948,9 @@ export function arkFeature(ctx) { // Fee = size × rate needs none of it. Still memoized on the coin set + // feerate, since the advisory asks on every wallet render. let _exitFeeMemo = { key: null, val: 0 }; - function estimateExitFeeSat(mgr) { + function estimateExitFeeSat(mgr, only = null) { const feeRate = Math.max(1, (wallet.feeRates && wallet.feeRates.halfHourFee) || 2); - const coins = freeCoins(mgr.state); + const coins = only || exitableCoins(mgr.state, mgr._tipH || 0); const key = feeRate + '|' + coins.map((v) => v.id).join(','); if (_exitFeeMemo.key === key) return _exitFeeMemo.val; let total = 0; @@ -2816,16 +2965,27 @@ export function arkFeature(ctx) { return total; } - async function doArkExit() { + // ids: exactly these coins (the Manage page's ticked ones); else every coin + async function doArkExit(ids = null) { ui.arkBusy = 'exit'; ui.arkError = ''; render(); try { - const mgr = await connectArk(); - const spendables = freeCoins(mgr.state); - if (!spendables.length) throw new Error(t('arkNotConnected')); + // The manager's own init is enough for an exit — the server may be + // gone (that is what a unilateral exit is for), and the snapshot gate + // the full connect also waits on may never clear without the relays. + let mgr = arkView(); + if (!mgr) { + connectArk().catch(() => {}); + for (let i = 0; i < 50 && !arkInitPromise; i++) await new Promise((r) => setTimeout(r, 100)); + try { await arkInitPromise; } catch {} + mgr = arkView(); + } + if (!mgr) throw new Error(t('arkNotConnected')); + const spendables = exitableCoins(mgr.state, mgr._tipH || 0).filter((v) => !ids || ids.includes(v.id)); + if (!spendables.length) throw new Error(freeCoins(mgr.state).length ? t('arkExitNoneExitable') : t('arkNotConnected')); // Fees are paid hop by hop from Savings as the exit unrolls — an exit // that can't fund its hops just stalls at step zero. Refuse to start // one Savings can't carry, with the number on the table. - const feeEst = estimateExitFeeSat(mgr); + const feeEst = estimateExitFeeSat(mgr, spendables); if ((wallet.spendable || 0) < feeEst) { throw new Error(t('arkExitFeeShort', { need: fmtSats(feeEst), have: fmtSats(wallet.spendable || 0) })); } @@ -2983,7 +3143,7 @@ export function arkFeature(ctx) { load: () => { try { return JSON.parse(localStorage.getItem(key) || 'null'); } catch { return null; } }, save: (s) => { try { localStorage.setItem(key, JSON.stringify(s)); } catch {} }, }, - arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), + arkUrl: cfg.ark, esploraUrl: cfg.esplora, network: getNetwork(), honorsExpired: !!cfg.honorsExpired, }); await mgr.init(); return mgr; @@ -3031,7 +3191,7 @@ export function arkFeature(ctx) { // Fund a fresh bearer gift identity. Shared by the gifts feature's hook and // the zap flow's locked-gift fallback; `lockedTo` records who a locked gift // was for (the sender can still revoke either kind while unclaimed). - async function createArkGift(amountSat, lockedTo = null) { + async function createArkGift(amountSat, lockedTo = null, note = null) { const mgr = await connectArk(); const secret = crypto.getRandomValues(new Uint8Array(32)); const secretHex = hex.encode(secret); @@ -3041,7 +3201,7 @@ export function arkFeature(ctx) { const action = mgr.state.actions.find((a) => a.id === actionId); if (!action || action.step === 'failed') throw new Error(action?.error || t('claimFailed')); const vtxoId = decodeVtxo(hex.decode((action.destBytesList || [action.destBytes])[0])).id; - arkGiftRecords().push({ id: vtxoId, amountSat, secretHex, created: Date.now(), revoked: false, claimed: false, ...(lockedTo ? { lockedTo } : {}) }); + arkGiftRecords().push({ id: vtxoId, amountSat, secretHex, created: Date.now(), revoked: false, claimed: false, ...(lockedTo ? { lockedTo } : {}), ...(note ? { note } : {}) }); mgr._save(); return { code: encodeArkGiftCode(getNetwork(), amountSat, secret), amount: amountSat, address }; } @@ -3075,7 +3235,7 @@ export function arkFeature(ctx) { async function quoteOffboard(o, address) { o.quoteFor = address; o.quote = null; let quote = null; - try { quote = await (await connectArk()).offboardQuote(addrScript(address)); } + try { quote = await (await connectArk()).offboardQuote(addrScript(address), o.vtxoIds); } catch {} // no quote: the send itself still says what went wrong if (o.quoteFor !== address) return; // the address changed meanwhile o.quote = quote; o.quoteDone = true; @@ -3083,7 +3243,9 @@ export function arkFeature(ctx) { } function arkOffboardSendView() { const o = ui.arkOffboardSend; - const spendable = arkBalance()?.spendableSat || 0; + // chosen coins: the amount is theirs and is not a field + const chosen = o.vtxoIds ? freeCoins(arkStateNow()).filter((v) => o.vtxoIds.includes(v.id)) : null; + const spendable = chosen ? chosen.reduce((n, v) => n + v.amountSat, 0) : (arkBalance()?.spendableSat || 0); if (o.quoteFor !== o.address) { o.quote = null; o.quoteDone = false; o.quoteFor = o.address; let ok = false; try { addrScript(o.address); ok = true; } catch {} @@ -3093,6 +3255,7 @@ export function arkFeature(ctx) { const tooSmall = !!q && spendable < q.minSat; return h('div', { class: 'card col', style: 'gap:12px' }, h('h3', {}, t(o.fromCoins ? 'arkCoinsCoopTitle' : 'arkExitSendTitle')), + o.fromCoins ? h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')) : null, h('label', { class: 'field' }, h('span', { class: 'lab' }, t('recipient')), h('input', { type: 'text', class: 'mono-input', value: o.address, spellcheck: 'false', autocomplete: 'off', autocapitalize: 'none', @@ -3103,10 +3266,11 @@ export function arkFeature(ctx) { fee: fmtSats(q.totalSat), chain: fmtSats(q.chainSat), service: fmtSats(q.serviceSat), min: fmtSats(q.minSat), })) : !o.quoteDone ? h('div', { class: 'small faint' }, t('arkOffboardQuoting')) : null, tooSmall ? h('div', { class: 'notice' }, t('arkOffboardBelowMin', { n: fmtSats(spendable), min: fmtSats(q.minSat) })) : null, - h('div', { class: 'input-group' }, - h('input', { type: 'number', min: '1', placeholder: String(spendable), value: o.amount, - onInput: (e) => { o.amount = e.target.value; } }), - h('button', { type: 'button', onClick: () => { o.amount = String(spendable); render(); } }, t('max'))), + chosen ? h('div', { class: 'small ark-coop-chosen' }, chosen.length === 1 ? t('arkCoopSelectedAmtOne', { amount: fmtSats(spendable) + ' sats' }) : t('arkCoopSelectedAmt', { n: chosen.length, amount: fmtSats(spendable) + ' sats' })) + : h('div', { class: 'input-group' }, + h('input', { type: 'number', min: '1', placeholder: String(spendable), value: o.amount, + onInput: (e) => { o.amount = e.target.value; } }), + h('button', { type: 'button', onClick: () => { o.amount = String(spendable); render(); } }, t('max'))), ui.arkError ? h('div', { class: 'notice err' }, ui.arkError) : null, h('div', { class: 'row gap6' }, h('button', { class: 'btn-ghost grow', onClick: () => { @@ -3116,7 +3280,7 @@ export function arkFeature(ctx) { ui.arkBusy === 'offboard' ? h('button', { class: 'btn-primary grow', disabled: true }, h('span', { class: 'spinner sm' })) : h('button', { class: 'btn-primary grow', disabled: tooSmall, onClick: () => { - const amount = String(o.amount ?? '').trim(); + const amount = chosen ? String(spendable) : String(o.amount ?? '').trim(); const sats = amount ? Number(amount) : spendable; if (!Number.isSafeInteger(sats) || sats <= 0 || sats > spendable) { ui.arkError = t('enterValidAmtForN', { n: 1 }); render(); return; } try { addrScript(o.address); } catch { ui.arkError = t('arkOffboardBadAddress'); render(); return; } @@ -3125,7 +3289,7 @@ export function arkFeature(ctx) { ui.arkCoopFailed = false; ui.arkError = t('arkOffboardAmtBelowMin', { min: fmtSats(q.minSat), fee: fmtSats(q.totalSat) }); render(); return; } - doArkOffboard(sats >= spendable ? 0 : sats, o.address); + doArkOffboard(sats >= spendable ? 0 : sats, o.address, chosen ? o.vtxoIds : undefined); } }, t('arkSendBtn'))), // This send IS the cooperative exit. The trustless fallback only // appears when cooperation actually failed (not when the amount was @@ -3161,29 +3325,69 @@ export function arkFeature(ctx) { })()); } - async function doArkOffboard(amountSat, destAddress = null) { + // A set of coins adding up to exactly `amountSat`: one coin of that size, + // else the smallest subset of the free coins that sums to it (largest coins + // first, so an offboard takes as few inputs as it can). null when no subset + // fits. Reachable sums are built up coin by coin, capped so a balance in + // hundreds of dust coins can't stall the tap. + function exactCoins(coins, amountSat) { + const one = coins.find((v) => v.amountSat === amountSat); + if (one) return [one]; + const sorted = [...coins].filter((v) => v.amountSat > 0 && v.amountSat < amountSat).sort((a, b) => b.amountSat - a.amountSat); + const reach = new Map([[0, null]]); // sum -> { coin, prev } that first reached it + for (const v of sorted) { + const add = []; + for (const sum of reach.keys()) { + const next = sum + v.amountSat; + if (next <= amountSat && !reach.has(next)) add.push([next, { coin: v, prev: sum }]); + } + for (const [sum, via] of add) reach.set(sum, via); + if (reach.has(amountSat)) break; + if (reach.size > 50_000) return null; + } + if (!reach.has(amountSat)) return null; + const picked = []; + for (let sum = amountSat; sum > 0;) { const via = reach.get(sum); picked.push(via.coin); sum = via.prev; } + return picked; + } + // The coins that leave Spending for an on-chain send of `amountSat`. An + // offboard moves whole vtxos, so the amount has to be covered exactly: + // by coins already in the wallet when they fit (a balance that happens to + // add up, or the halves an earlier split left behind), else an exact amount + // is split off by paying it to this wallet's own address. A payment spread + // over several inputs arrives as several coins, one per input with the last + // carrying the remainder, so what the split yields is every coin that lands + // on the receive key and adds up to the amount, not a single coin of that + // size: looking for one made every partial on-chain send from a balance + // in two or more coins time out (Jarryd, 2026-10-23, three splits and no + // send). Change from the split carries its own key index and stays. + async function carveCoins(mgr, amountSat) { + const free = () => freeCoins(mgr.state); + const have = exactCoins(free(), amountSat); + if (have) return have.map((v) => v.id); + const before = new Set(free().map((v) => v.id)); + await mgr.send(mgr.address(), amountSat); + for (let i = 0; i < 30; i++) { + await mgr.sync().catch(() => {}); + const landed = free().filter((v) => !before.has(v.id) && !v.keyIndex); + const hit = exactCoins(landed, amountSat); + if (hit) return hit.map((v) => v.id); + await new Promise((r) => setTimeout(r, 2000)); + } + throw new Error(t('arkSplitTimeout')); + } + + // vtxoIds: exactly these coins go (the coins page's ticked subset); + // otherwise an amount is split off the balance, or everything goes. + async function doArkOffboard(amountSat, destAddress = null, vtxoIds = undefined) { ui.arkBusy = 'offboard'; ui.arkError = ''; ui.arkCoopFailed = false; render(); try { const address = destAddress || wallet.freshReceive().address; const spk = addrScript(address); const mgr = await connectArk(); - const spendables = () => freeCoins(mgr.state); - const total = spendables().reduce((n, v) => n + v.amountSat, 0); - let ids; // undefined = all spendable vtxos - if (amountSat && amountSat < total) { - let target = spendables().find((v) => v.amountSat === amountSat); - if (!target) { - const before = new Set(spendables().map((v) => v.id)); - await mgr.send(mgr.address(), amountSat); - for (let i = 0; i < 30 && !target; i++) { - await new Promise((r) => setTimeout(r, 2000)); - await mgr.sync().catch(() => {}); - target = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id)); - } - if (!target) throw new Error(t('arkSplitTimeout')); - } - ids = [target.id]; - } + const total = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0); + let ids = vtxoIds; // undefined = all spendable vtxos + if (!ids && amountSat && amountSat < total) ids = await carveCoins(mgr, amountSat); const action = await mgr.startOffboard(spk, address, ids); ui.arkOffboardAmt = ''; ui.arkMoveOpen = false; @@ -3199,25 +3403,63 @@ export function arkFeature(ctx) { ui.arkBusy = null; render(); } - // VTXO upkeep, invisibly: a send needs a single vtxo covering the amount - // (fragmentation breaks coin selection) and every vtxo expires at - // expiryHeight (unrenewed, the ASP can eventually sweep it). Rather than - // exposing a refresh button, consolidate-and-renew automatically when a - // vtxo is inside the renewal window or fragmentation builds up. The round - // fee this spends is the cost of keeping the money spendable at all. - // The ASP's refresh fee brackets reward renewing LATE — under 96 blocks of - // remaining life a renewal is free, and this ASP keeps honoring (and freely - // rescuing) a coin even past its expiry, so aiming inside the free window - // risks nothing. ~16 hours of margin on mainnet. - const renewWindow = () => (getNetwork() === 'regtest' ? 24 : 96); - // How close to expiry the SERVER's own backstop renewal is aimed. The - // window above only helps a wallet someone opens inside it; this one is a - // participation registered far in advance that the ASP runs on its own, - // whether or not anybody is looking. It sits well inside renewWindow so an - // app that IS open still renews first (and the untouched backstop is - // dropped), and far enough from expiry — 36 blocks, six hourly rounds — for - // the round to actually run in time. Both are in the free fee bracket. - const backstopWindow = () => backstopMargin(getNetwork()); + // VTXO upkeep, by the user's choice of custody (Settings → Spending): + // custodial (the default) — nothing renews. A coin past its timelock is + // coinos's IOU: the server sweeps the tree and keeps cosigning spends of + // the coin (captaind allow_expired_arkoor), so the balance works as a v2 + // one did, and no renewal fee is ever paid. The holder trusts coinos. + // self — renew in the last hours before expiry, the free ppm bracket, one + // base fee per round (~300 sats): a unilateral exit is always possible. + // exit — the same, plus a coin is renewed as soon as its history is four + // hops deep: an exit pays one on-chain transaction per hop, so this + // keeps the exit price of every coin near a fresh coin's. Costs the + // top bracket + base each time, so only for coins worth it. + // The policy's window is when THIS app renews a coin (blocks of life left); + // margin/grid aim the SERVER's own backstop order — a participation the ASP + // runs on its own, registered far in advance, snapped to a grid so every + // wallet's orders share one round. renewPolicy() in ark/manager.js. + // + // Consolidation is gone from here: it used to trigger at 20 coins, bill the + // top ppm bracket on every fresh coin, and was 84% of all renewal fees paid + // in Sep–Oct 2026 — the "money draining" people saw. Multi-input sends take + // up to MAX_SEND_INPUTS coins; small change folds into a renewal that is + // happening anyway, for next to nothing; the Manage page consolidates on + // request. + const CUSTODY_DEFAULT = 'custodial'; + // The tier in force: the stored choice, except that "coinos holds my coins" + // exists only on a server that honors a coin past its timelock. Anywhere + // else (Second, a custom captaind) an expired coin is gone, so renewal is + // automatic there whatever is stored — the stored default stays on the + // record for a later switch back to a coinos server. From 2026-10-22 to + // 10-23 the stored default applied everywhere, and a wallet on such a + // server renewed nothing and warned of nothing, in the app and the worker. + function getCustody() { + let v = wallet.loadFeatureState ? wallet.loadFeatureState('arkCustody', null) : null; + if (v === 'early') v = 'exit'; // the third tier's first name (one day in October 2026) + const tier = CUSTODY_TIERS.includes(v) ? v : CUSTODY_DEFAULT; + if (tier !== 'custodial') return tier; + const cfg = getArkConfig(); + return cfg && !cfg.honorsExpired ? 'self' : tier; + } + function setCustody(tier) { if (wallet.saveFeatureState) wallet.saveFeatureState('arkCustody', tier); } + const custodyPolicy = () => renewPolicy(getCustody(), getNetwork()); + // Switching: a renewing tier starts covering coins right away (the throttles + // are reset so the next sync registers backstops and renews what is due), + // and the worker's mirror learns the tier so closed-app renewals follow it. + // Orders already registered with the server keep running whatever the tier + // (there is no cancel; a spent input voids one) — they were priced when + // registered and renew one coin each, once. + function applyCustody(tier) { + if (!CUSTODY_TIERS.includes(tier)) return; + const same = tier === getCustody(); + setCustody(tier); // the record keeps the choice even when it is already in force here + if (same) return; + arkAutoRefreshAt = 0; arkBackstopAt = 0; arkRenewWarn = null; + if (ark && ark.state) maybeAutoRefresh(ark).catch(() => {}); + writeBgMirror().catch(() => {}); + toast(t('arkCustodySaved')); + render(); + } let arkAutoRefreshAt = 0; let arkBackstopAt = 0; // Set when the balance is too small to renew itself (total minus round fee @@ -3248,12 +3490,38 @@ export function arkFeature(ctx) { return true; } + // Whatever the tier, a coin whose history has run very deep is renewed: + // the server stops cosigning spends of a coin at its depth cap, so this is + // what keeps such a coin spendable, and it waives the base fee for a + // refresh of deep coins alone — so they go in a round of their own, never + // mixed with coins that would make it pay. A wallet paying hourly from one + // change chain (a subscription) is the usual way to get here. + async function flattenDeepCoins(mgr, tip) { + const deep = mgr.deepCoins ? mgr.deepCoins() : []; + if (!deep.length) return false; + if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return false; + const feeSat = mgr.refreshFee(deep, tip); + const totalSat = deep.reduce((n, v) => n + v.amountSat, 0); + if (totalSat - feeSat < 330 || feeSat * 10 > totalSat) return false; // dust, or a server charging full price: left alone + await mgr.refresh(deep.map((v) => v.id)); + render(); + return true; + } + async function maybeAutoRefresh(mgr) { if (wallet.watchOnly || !mgr || !mgr.state) return; if (Date.now() - arkAutoRefreshAt < 30 * 60_000) return; + const policy = custodyPolicy(); + if (mgr.deepCoins && mgr.deepCoins().length) { + arkAutoRefreshAt = Date.now(); + try { if (await flattenDeepCoins(mgr, await mgr.chain.tipHeight())) return; } catch {} + } + // "coinos holds my coins": nothing renews on its own and nothing warns. + // The server honors a coin past its timelock, and the holder chose this. + if (!policy) { arkRenewWarn = null; return; } // NOT filtered by expiryRejected. A coin the server refused as expired // can still be REFRESHED — that is the one thing an expired vtxo can - // still do — and excluding it here meant a wallet holding nothing else + // always do — and excluding it here meant a wallet holding nothing else // did nothing at all: no renewal attempt, and no warning either. const spendables = freeCoins(mgr.state); if (!spendables.length) { arkRenewWarn = null; return; } @@ -3265,25 +3533,43 @@ export function arkFeature(ctx) { // stamped, and this must not then run on every five-second sync. if (Date.now() - arkBackstopAt > 30 * 60_000) { arkBackstopAt = Date.now(); - await mgr.ensureScheduledRefreshes(backstopWindow()).catch(() => {}); + await mgr.ensureScheduledRefreshes(policy.margin, 8, policy.grid).catch(() => {}); } // never start a round while any other action is still in flight if ((mgr.state.actions || []).some((a) => !['done', 'failed'].includes(a.step))) return; arkAutoRefreshAt = Date.now(); try { const tip = await mgr.chain.tipHeight(); - const RENEW_BLOCKS = renewWindow(); - const expiringCoins = spendables.filter((v) => v.expiryHeight && v.expiryHeight - tip < RENEW_BLOCKS); - const expiring = expiringCoins.length > 0; - // Fragmentation alone is no longer worth paying for: multi-input sends - // handle up to 24 coins, and consolidating FRESH coins bills the round - // fee's top ppm bracket (a burst of refund coins after failed payments - // once cost a user ~1% overnight). Consolidate only when the coin count - // itself approaches the 24-input send ceiling. - const fragmented = spendables.length >= 20; + const expiringCoins = spendables.filter((v) => v.expiryHeight && v.expiryHeight - tip < policy.window); + // The exit tier also renews a coin whose history has grown deep — each + // hop is one more on-chain transaction in a unilateral exit — but only + // a coin worth it: never more than a tenth of the coin on its renewal + // (300 sats to flatten a 21-sat coin's history would be absurd, and + // such a coin's exit is uneconomic whatever its depth). + const depthOf = (v) => { try { return mgr._decoded(v).genesis.length; } catch { return 0; } }; + const deepCoins = !policy.maxDepth ? [] : spendables.filter((v) => + !expiringCoins.includes(v) && depthOf(v) >= policy.maxDepth && mgr.refreshFee([v], tip) * 10 <= v.amountSat); + if (!expiringCoins.length && !deepCoins.length) { arkRenewWarn = null; return; } + // Worth it, or not at all: an automatic renewal never spends more than + // a tenth of what it renews. 301 sats to renew a 1,000-sat coin and + // four bits of change restored an exit nobody would ever use (the + // exit itself would cost more than the coins). Coins left alone stay + // spendable — the server keeps honoring them. + const worthIt = (set) => mgr.refreshFee(set, tip) * 10 <= set.reduce((n, v) => n + v.amountSat, 0); + if (!expiringCoins.length) { + // nothing is expiring: this round is for the deep coins alone, and + // they pay for it — the floor logic below still applies + arkRenewWarn = null; + let renewSet = [...deepCoins, ...spendables.filter((v) => !deepCoins.includes(v) && v.amountSat < 1000)]; + const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip); + if (netSat(renewSet) < 330 || !worthIt(renewSet)) return; + await mgr.refresh(renewSet.map((v) => v.id)); + render(); + return; + } const totalSat = spendables.reduce((n, v) => n + v.amountSat, 0); const renewable = totalSat - mgr.refreshFee(spendables, tip) >= 330; - if (expiring && !renewable) { + if (!renewable) { // Can't save these coins ourselves — tell the user while receiving // any amount (or spending) can still beat the clock. const minExpiry = Math.min(...spendables.map((v) => v.expiryHeight || Infinity)); @@ -3294,26 +3580,25 @@ export function arkFeature(ctx) { return; } arkRenewWarn = null; - if (!expiring && !fragmented) return; // Renew ONLY the coins that need it: dragging far-from-expiry coins // into the round would bill their (higher) fee bracket for nothing. - // The rare fragmentation consolidation still sweeps everything. - // - // But the subset must clear the server's 330-sat output floor BY - // ITSELF — the renewable check above prices the whole balance. Two - // dust coins at expiry (133 sats between them) failed their renewal - // round silently every 30 minutes forever. Pull in the smallest - // healthy coins until the renewed output is mintable. - let renewSet = expiringCoins; - if (!fragmented) { - const extras = spendables - .filter((v) => !expiringCoins.includes(v)) - .sort((a, b) => a.amountSat - b.amountSat); - const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip); - while (netSat(renewSet) < 330 && extras.length) renewSet = [...renewSet, extras.shift()]; - if (netSat(renewSet) < 330) return; // whole balance can't clear the floor — the warn above covers it - } - await mgr.refresh(fragmented ? undefined : renewSet.map((v) => v.id)); + // Small change rides along, though: a coin under 1,000 sats costs at + // most 2 sats of ppm in this round, and folding it in now spares it a + // whole base fee's worth of round of its own when its turn comes. + let renewSet = [...expiringCoins, ...deepCoins, ...spendables.filter((v) => !expiringCoins.includes(v) && !deepCoins.includes(v) && v.amountSat < 1000)]; + // The set must clear the server's 330-sat output floor BY ITSELF — the + // renewable check above prices the whole balance. Two dust coins at + // expiry (133 sats between them) failed their renewal round silently + // every 30 minutes forever. Pull in the smallest healthy coins until the + // renewed output is mintable. + const extras = spendables + .filter((v) => !renewSet.includes(v)) + .sort((a, b) => a.amountSat - b.amountSat); + const netSat = (set) => set.reduce((n, v) => n + v.amountSat, 0) - mgr.refreshFee(set, tip); + while (netSat(renewSet) < 330 && extras.length) renewSet = [...renewSet, extras.shift()]; + if (netSat(renewSet) < 330) return; // whole balance can't clear the floor — the warn above covers it + if (!worthIt(renewSet)) return; // not worth a tenth of itself: left alone, still spendable + await mgr.refresh(renewSet.map((v) => v.id)); render(); } catch {} // transient — the next throttled attempt retries } @@ -3595,7 +3880,7 @@ export function arkFeature(ctx) { const b = arkBalance() || { spendableSat: 0, pendingSat: 0 }; const spendable = b.spendableSat; const total = b.spendableSat + b.pendingSat; - const nSpend = freeCoins(arkStateNow()).length; + const nSpend = exitableCoins(arkStateNow(), (ark && ark._tipH) || 0).length; const exitingSat = ((arkStateNow() && arkStateNow().actions) || []) .filter((a) => a.type === 'exit' && !['done', 'failed'].includes(a.step)) .reduce((n, a) => n + a.amountSat, 0); @@ -3615,7 +3900,7 @@ export function arkFeature(ctx) { h('p', { class: 'small muted', style: 'margin:0' }, t('arkCoopDesc')), spendable > 0 ? h('button', { class: 'btn-primary btn-block', disabled: !!ui.arkBusy, onClick: () => doArkOffboard() }, - ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('arkOffboardBtn', { n: fmtAmount(spendable) + ' ' + unitLabel() })) + ui.arkBusy === 'offboard' ? h('span', { class: 'spinner sm' }) : t('arkOffboardBtn', { n: fmtNative(spendable) })) : h('div', { class: 'small faint' }, exitingSat > 0 ? t('arkExitCoopHeld') : t('arkExitNoBalance'))), // unilateral h('div', { class: 'card col', style: 'gap:8px' }, @@ -3650,10 +3935,10 @@ export function arkFeature(ctx) { new Promise((r) => setTimeout(r, 800)), ]); }, - // the Spending face's settings page leads with its coins + // the Spending face's settings page: the custody choice, then its coins spendingSettings() { if (wallet.watchOnly) return null; // a locked wallet can't renew or exit - return arkCoinsPage({ embedded: true }); + return arkCoinsPage({ embedded: true }); // the custody strategy sits inside, after the coins }, // the wallet's own pages keep the top nav: these are pages, not takeovers screenView() { @@ -3840,9 +4125,21 @@ export function arkFeature(ctx) { async arkBgNoteSpends(spends) { const mgr = await connectArk(); for (const sp of spends) { + // The worker's own manager wrote this payment's row into the mirror, + // and the merge on connect brings it over: a second row here showed + // every closed-app payment twice (PullCap, 2026-10-23). Stamp the + // row that exists instead; lnFoldedIds hides a twin that still + // forms when the merge lands after this note. + const twin = (mgr.state.movements || []).find((m) => m.type === 'ln-send' + && ((sp.preimage && m.preimage === sp.preimage) || (sp.paymentHash && m.paymentHash === sp.paymentHash))); + if (twin) { + if (!/while closed/.test(twin.detail || '')) twin.detail = `while closed · fee ${sp.feeSat || 0} sat`; + continue; + } mgr._movement({ type: 'ln-send', amountSat: sp.amountSat, status: 'complete', detail: `while closed · fee ${sp.feeSat || 0} sat`, invoice: sp.invoice || '', preimage: sp.preimage || '', + paymentHash: sp.paymentHash || undefined, }); } mgr._save(); @@ -4016,7 +4313,22 @@ export function arkFeature(ctx) { for (const m of s.movements || []) for (const id of m.inputIds || []) accounted.add(id); const out = []; const seenCoin = new Set(); + // One payment delivered as several coins (a gift held in two, a + // dust-padded split) is one row: receives from the same mailbox + // message (`batch`; older rows: the same delivery instant) fold. + const folded = new Map(); for (const m of moves) { + if (m.type === 'receive' && sameDelivery(out[out.length - 1], m)) { + const last = out[out.length - 1]; + if (!folded.has(last.id)) { + const f = { ...last, vtxoIds: [last.vtxoId], vtxoId: null }; + out[out.length - 1] = f; folded.set(f.id, f); + } + const f = folded.get(last.id); + f.amountSat += m.amountSat; + f.vtxoIds.push(m.vtxoId); + continue; + } if (m.type !== 'reconcile') { out.push(m); continue; } if (m.vtxoId && (seenCoin.has(m.vtxoId) || accounted.has(m.vtxoId))) continue; if (m.vtxoId) seenCoin.add(m.vtxoId); @@ -4029,6 +4341,7 @@ export function arkFeature(ctx) { out.push({ ...m, count: 1, vtxoIds: m.vtxoId ? [m.vtxoId] : [] }); } } + this._histFolded = folded; // a folded row's detail shows the whole payment return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) }))); }, historyDetail() { @@ -4048,7 +4361,8 @@ export function arkFeature(ctx) { if (done) return arkMoveDetailView(done); if (a && !['done', 'failed'].includes(a.step)) return arkMoveDetailView(lnPendingMove(a)); } - const m = s ? (s.movements || []).find((x) => x.id === ui.arkMoveDetail) : null; + if (s) this.historyEntries(); // (memoized) keeps the folded rows current + const m = s ? (this._histFolded && this._histFolded.get(ui.arkMoveDetail)) || (s.movements || []).find((x) => x.id === ui.arkMoveDetail) : null; if (m) return arkMoveDetailView(m); ui.arkMoveDetail = null; return null; @@ -4113,7 +4427,11 @@ export function arkFeature(ctx) { // and it is one tap away on the Manage page. What it cannot do is be // spent over Ark or exited unilaterally, so saying nothing is the one // option that isn't honest. - if (!wallet.watchOnly && ark && ark.balance) { + // On the coinos servers a coin past its timelock is still money (the + // server keeps cosigning its spends) — the balance counts it and + // there is nothing to warn about; the custody tier the user chose + // says what expiry means to them. Elsewhere, the old warning. + if (!wallet.watchOnly && ark && ark.balance && !ark.honorsExpired) { let expiredSat = 0; try { expiredSat = ark.balance().expiredSat || 0; } catch {} // Expired dust (under the 330-sat floor) cannot be renewed or exited @@ -4195,7 +4513,7 @@ export function arkFeature(ctx) { setNetwork(g.net); return true; }, - arkGiftCreate(amountSat) { return createArkGift(amountSat); }, + arkGiftCreate(amountSat, note) { return createArkGift(amountSat, null, note); }, // Claim-side status: claimable (with the live amount), taken, wrongnet, or // unknown (not visible here — wrong server or not yet delivered). async arkGiftStatus(code) { diff --git a/src/features/gifts-wallet.js b/src/features/gifts-wallet.js index 824ddc0..9532125 100644 --- a/src/features/gifts-wallet.js +++ b/src/features/gifts-wallet.js @@ -274,9 +274,9 @@ export function installGiftWallet(wallet) { // gift's link/QR can be re-viewed later and a claimed one identified in history. _giftRecordsKey() { return this._cacheKey() + ':giftrec'; }, - recordGift({ code, locked, amount, claimCode, outpoints }) { + recordGift({ code, locked, amount, claimCode, outpoints, note, from }) { if (!outpoints || !outpoints.length) return; - this.giftRecords()[outpoints[0]] = { id: outpoints[0], code, locked: !!locked, amount, claimCode: claimCode || null, outpoints, created: Date.now(), revoked: false }; + this.giftRecords()[outpoints[0]] = { id: outpoints[0], code, locked: !!locked, amount, claimCode: claimCode || null, outpoints, created: Date.now(), revoked: false, ...(note ? { note } : {}), ...(from ? { from } : {}) }; this._saveGiftRecords(); try { this.saveCache(); } catch {} // publish the new gift to cross-device sync }, diff --git a/src/features/gifts.js b/src/features/gifts.js index 56fd99e..42e794d 100644 --- a/src/features/gifts.js +++ b/src/features/gifts.js @@ -9,13 +9,17 @@ import { installGiftWallet, previewGift, giftOutpoints, giftClaimTxs, isRetiredG import { t } from '../i18n.js'; import { qrSvg } from '../qr.js'; import { fmtBtc, timeAgo, shortAddr } from '../format.js'; +import { getEventHash, verifyEvent } from 'nostr-tools/pure'; +import { sha256 } from '@noble/hashes/sha256'; +import { bytesToHex, hexToBytes } from '@noble/hashes/utils'; +import { base32nopad } from '@scure/base'; export function giftsFeature(ctx) { const { h, ui, render, wallet, toast, copyBtn, pasteBtn, blankSend, goBack, goHome, openExternal, fmtAmount, unitLabel, unitTag, parseAmount, getUnit, toggleUnit, download, brandHeader, activeAccount, setAccounts, getAccounts, claimTargets, - enterWallet, activateAccount, commitAccount, + enterWallet, activateAccount, commitAccount, pickConfirm, } = ctx; installGiftWallet(wallet); // gift primitives live outside the core wallet // Ark-gift support comes from the ark feature (when this build ships it); @@ -32,6 +36,8 @@ export function giftsFeature(ctx) { try { const am = location.pathname.match(/^\/ag\/([A-Za-z0-9]+)\/?$/i); // ark gift if (am) { + ui.claimNote = readNoteFrag(); + ui.claimFrom = readFromFrag(am[1]); history.replaceState(null, '', '/'); return arkGiftOf(am[1]) ? am[1] : null; } @@ -43,6 +49,7 @@ export function giftsFeature(ctx) { if (hm) code = hm[1]; } if (!code) return null; + if (pm) { ui.claimNote = readNoteFrag(); ui.claimFrom = readFromFrag(code); } history.replaceState(null, '', '/'); return previewGift(code) ? code : null; } catch { @@ -57,6 +64,8 @@ export function giftsFeature(ctx) { try { const m = location.pathname.match(/^\/lg\/([A-Za-z0-9_-]+)\/?$/); if (!m) return null; + ui.claimNote = null; + ui.claimFrom = null; history.replaceState(null, '', '/'); return previewLockedGift(m[1]); } catch { return null; } @@ -120,6 +129,77 @@ export function giftsFeature(ctx) { if (!acceptLockedPayload(payload)) { ui.claimError = t('claimCodeWrong'); render(); } } + // A gift's note rides its link after the # (#m=<text>): the fragment never + // leaves the browser, so no server sees it, and it is only as private as the + // link itself (which already IS the money). + const GIFT_NOTE_MAX = 280; + // Who it's from rides there too (f=…): the sender's nostr key, signed over + // the gift's code, so a link can't be passed on as someone else's gift. + // 100 bytes in base32: pubkey, created_at, schnorr sig. + const giftFrag = (note, from) => { + const p = []; + if (note) p.push('m=' + encodeURIComponent(note)); + if (from) p.push('f=' + from); + return p.length ? '#' + p.join('&') : ''; + }; + function readNoteFrag() { + try { + const m = new URLSearchParams(location.hash.slice(1)).get('m'); + return m ? m.trim().slice(0, GIFT_NOTE_MAX) || null : null; + } catch { return null; } + } + const GIFT_FROM_KIND = 27121; // ephemeral range: never meant for a relay + const giftFromTmpl = (code, created_at) => ({ + kind: GIFT_FROM_KIND, created_at, content: '', + tags: [['x', bytesToHex(sha256(new TextEncoder().encode(String(code).toUpperCase())))]], + }); + // the sender's pubkey, if the link's f= is their signature over this code + function readFromFrag(code) { + try { + const f = [...new URLSearchParams(location.hash.slice(1))].find(([k]) => k.toLowerCase() === 'f')?.[1]; + const b = f && base32nopad.decode(f.toUpperCase()); + if (!b || b.length !== 100) return null; + const ev = { ...giftFromTmpl(code, new DataView(b.buffer, b.byteOffset).getUint32(32)), + pubkey: bytesToHex(b.slice(0, 32)), sig: bytesToHex(b.slice(36)) }; + ev.id = getEventHash(ev); + return verifyEvent(ev) ? ev.pubkey : null; + } catch { return null; } + } + // Sign a new gift as ours (the messages feature holds the identity); null + // when there's no identity, the signer refuses, or it takes too long. + async function signGiftFrom(code) { + try { + const ev = await Promise.race([ + hook('signGiftFrom', giftFromTmpl(code, Math.floor(Date.now() / 1000))), + new Promise((r) => setTimeout(() => r(null), 20_000)), + ]); + if (!ev || !ev.sig) return null; + const b = new Uint8Array(100); + b.set(hexToBytes(ev.pubkey), 0); + new DataView(b.buffer).setUint32(32, ev.created_at); + b.set(hexToBytes(ev.sig), 36); + return base32nopad.encode(b); + } catch { return null; } + } + const GIFT_ANON_KEY = 'giftAnon'; + const giftAnon = () => { try { return localStorage.getItem(GIFT_ANON_KEY) === '1'; } catch { return false; } }; + // who sent it, and that claiming follows them + const giftFromView = () => (ui.claimFrom + ? h('div', { class: 'col', style: 'align-items:center;gap:4px' }, + h('div', { class: 'row gap6', style: 'align-items:center;justify-content:center' }, + h('span', { class: 'small muted' }, t('giftFrom')), + hook('profileChip', ui.claimFrom, undefined, () => {}) + || h('span', { class: 'small mono' }, (npubOf(ui.claimFrom) || '').slice(0, 16) + '…')), + h('div', { class: 'small faint' }, t('giftClaimFollows'))) + : null); + // the sender's words, quoted above the amount wherever the gift is opened + const giftNoteView = () => (ui.claimNote + ? h('blockquote', { class: 'gift-note' }, ui.claimNote) + : null); + // with a note or a sender the link has a # in it: a byte-mode QR (the + // bare link is upper-cased into the denser alphanumeric mode) + const giftQr = (url, hasFrag) => qrSvg(hasFrag ? url : url.toUpperCase(), { ec: 'L', mode: hasFrag ? undefined : 'Alphanumeric' }); + // Entry point for claiming a gift code. If the recipient already has wallet(s), // offer to claim into one or make a new one; otherwise go straight to a fresh // wallet (the original first-timer flow). @@ -171,6 +251,8 @@ export function giftsFeature(ctx) { h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' }, h('div', { class: 'check-badge', style: 'background:var(--accent)' }, '🎁'), h('h2', { style: 'margin:0' }, t('giftWelcome')), + giftFromView(), + giftNoteView(), pv ? h('div', { class: 'amt', style: 'font-size:30px' }, h('span', { class: 'amount-pos' }, fmtAmount(pv.room)), ' ', unitTag('unit')) : null, h('div', { class: 'small faint' }, claimFeeNote(code)), h('p', { class: 'muted', style: 'margin:0' }, t('claimIntoPrompt')) @@ -214,7 +296,7 @@ export function giftsFeature(ctx) { ), h('div', { class: 'row gap6' }, copyBtn(wallet.mnemonic, t('copyPhrase'))), h('button', { class: 'btn-primary btn-block', onClick: () => { ui.confirm = pickConfirm(words); ui.claimError = ''; ui.claimStep = 'verify'; render(); } }, t('verifyBackup')), - h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); render(); } }, t('skipVerification')) + h('button', { class: 'btn-block', onClick: finishClaim }, t('skipVerification')) ) ); } @@ -246,13 +328,11 @@ export function giftsFeature(ctx) { onClick: () => { const ok = ui.confirm.every((c) => c.value.toLowerCase() === words[c.index]); if (!ok) { ui.claimError = t('wordsMismatch'); render(); return; } - ui.screen = 'wallet'; ui.claimStep = null; ui.claimError = ''; - landAccount(); - render(); + finishClaim(); }, }, t('openWallet')) ), - h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); render(); } }, t('skipVerification')) + h('button', { class: 'btn-block', onClick: finishClaim }, t('skipVerification')) ) ); } @@ -313,6 +393,8 @@ export function giftsFeature(ctx) { h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' }, h('div', { class: 'check-badge', style: 'background:var(--accent)' }, '🎁'), h('h2', { style: 'margin:0' }, t('giftWelcome')), + giftFromView(), + giftNoteView(), h('div', { class: 'amt', style: 'font-size:30px' }, h('span', { class: 'amount-pos' }, fmtAmount(total)), ' ', unitTag('unit') ), @@ -324,10 +406,12 @@ export function giftsFeature(ctx) { !ui.claimError && ui.claimNotVisible && h('div', { class: 'notice info' }, t('claimNotVisibleBody')), ui.busy || ui.claimChecking ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' })) + // an ark gift costs nothing to claim: just the button (an on-chain + // one says what its network fee will take) : h('button', { class: 'btn-primary btn-block', onClick: doClaim }, - t('claimBtn'), ' ', - h('span', { style: 'font-size:0.85em;opacity:0.9' }, - '(' + (ag ? t('claimArkFree') : t('claimFeeNote', { n: fmtAmount(estFee) + ' ' + unitLabel() })) + ')')) + ...(ag ? [t('claimNowBtn')] : [t('claimBtn'), ' ', + h('span', { style: 'font-size:0.85em;opacity:0.9' }, + '(' + t('claimFeeNote', { n: fmtAmount(estFee) + ' ' + unitLabel() }) + ')')])) ); } @@ -388,10 +472,21 @@ export function giftsFeature(ctx) { if (ctx.setAccount) ctx.setAccount('spending'); } + // The seed is written down: into the new wallet — by way of the + // wizard's username, avatar and cover, so a gift's recipient arrives as + // someone people can pay by name (skippable, like any first run). + function finishClaim() { + ui.screen = 'wallet'; ui.claimStep = null; ui.claimError = ''; + landAccount(); + if (ctx.offerProfileSetup) ctx.offerProfileSetup({ home: ui.claimVia === 'ark' ? 'spending' : 'savings' }); + render(); + } + function afterClaim(amount) { ui.claimedAmount = amount; const wasProvisional = !!(activeAccount() && activeAccount().provisional); commitAccount(); // claimed — keep a fresh gift wallet (no-op for an existing one) + if (ui.claimFrom) hook('followGiftSender', ui.claimFrom); if (wasProvisional) { ui.claimStep = 'backup'; // fresh wallet — show the new seed to back up } else { @@ -526,13 +621,14 @@ export function giftsFeature(ctx) { // the sender can re-share an unclaimed gift. function viewGiftView() { const g = ui.viewGift; // { code, locked, amount, claimCode } - const url = `${location.origin}/g/${g.code}`; + const url = `${location.origin}/g/${g.code}${giftFrag(g.note, g.from)}`; let svg = null; - try { svg = qrSvg(url.toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }); } catch {} + try { svg = giftQr(url, !!(g.note || g.from)); } catch {} return h('div', { class: 'col', style: 'gap:16px;padding:16px;max-width:460px;margin:0 auto;width:100%' }, h('div', { class: 'card col', style: 'gap:12px;align-items:center' }, h('h3', { style: 'margin:0' }, t('giftView')), g.amount != null ? h('div', { class: 'amt' }, fmtAmount(g.amount), ' ', unitTag()) : null, + g.note ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, g.note) : null, svg ? h('div', { html: svg }) : h('div', { class: 'small faint', style: 'text-align:center;padding:8px' }, t('giftQrTooLong')), h('div', { class: 'addr-box break', style: 'width:100%;font-size:12px' }, url), copyBtn(url, t('copyLink')), @@ -567,9 +663,9 @@ export function giftsFeature(ctx) { } ui.busy = true; ui.giftError = ''; render(); try { - const g = await hook('arkGiftCreate', amt); + const g = await hook('arkGiftCreate', amt, giftNoteNow()); ui.giftIsArk = true; - finishGift(g, amt); + await finishGift(g, amt); } catch (e) { ui.giftError = e.message; } @@ -611,12 +707,21 @@ export function giftsFeature(ctx) { doCreateGift(amt, rate); } - // Finalize a freshly-built gift: a plain bearer link. - function finishGift(g, fallbackAmt) { + // Finalize a freshly-built gift: a plain bearer link, signed as ours + // unless the sender would rather stay anonymous. Recorded before the + // signer is asked, so a signer that never answers can't lose the gift. + async function finishGift(g, fallbackAmt) { const amount = g.amount || fallbackAmt || 0; + const note = giftNoteNow(); // the link says what was typed when it was made + const rec = { code: g.code, locked: false, amount, outpoints: g.reserved, note }; + wallet.recordGift(rec); + const from = giftAnon() ? null : await signGiftFrom(g.code); + if (from) wallet.recordGift({ ...rec, from }); ui.giftCode = g.code; - wallet.recordGift({ code: g.code, locked: false, amount, outpoints: g.reserved }); + ui.giftNoteMade = note; + ui.giftFromMade = from; } + const giftNoteNow = () => String(ui.giftNote || '').trim().slice(0, GIFT_NOTE_MAX) || null; function giftCard() { const active = wallet.outstandingGifts(); @@ -631,13 +736,14 @@ export function giftsFeature(ctx) { // (many-input) gift can exceed QR capacity — then fall back to the link. (() => { let svg = null; - try { svg = qrSvg(giftUrl().toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }); } catch {} + try { svg = giftQr(giftUrl(), !!(ui.giftNoteMade || ui.giftFromMade)); } catch {} return svg ? h('div', { html: svg }) : h('div', { class: 'small faint', style: 'text-align:center;padding:8px' }, t('giftQrTooLong')); })(), + ui.giftNoteMade ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, ui.giftNoteMade) : null, h('div', { class: 'addr-box break', style: 'width:100%;font-size:12px' }, giftUrl()), h('div', { class: 'row gap6 wrap' }, copyBtn(giftUrl(), t('copyLink')), - h('button', { class: 'btn-sm grow', onClick: () => { ui.giftCode = null; ui.giftAmount = ''; ui.giftMax = false; ui.giftIsArk = false; render(); } }, t('giftAnother')) + h('button', { class: 'btn-sm grow', onClick: () => { ui.giftCode = null; ui.giftAmount = ''; ui.giftNote = ''; ui.giftNoteMade = null; ui.giftFromMade = null; ui.giftMax = false; ui.giftIsArk = false; render(); } }, t('giftAnother')) ) ) : ui.giftSplitOffer @@ -692,6 +798,15 @@ export function giftsFeature(ctx) { ui.giftSource === 'chain' ? h('div', { class: 'notice warn small' }, t('giftChainWarn')) : null, + // an optional note, shown to whoever opens the gift + h('textarea', { class: 'gift-note-input', rows: 2, maxlength: GIFT_NOTE_MAX, placeholder: t('giftNotePlaceholder'), + value: ui.giftNote || '', onInput: (e) => { ui.giftNote = e.target.value; } }), + // the link names its sender (and claiming follows them) unless unticked + h('label', { class: 'row gap6', style: 'align-items:center;cursor:pointer' }, + h('input', { type: 'checkbox', checked: !giftAnon(), onChange: (e) => { + try { if (e.target.checked) localStorage.removeItem(GIFT_ANON_KEY); else localStorage.setItem(GIFT_ANON_KEY, '1'); } catch {} + } }), + h('span', { class: 'small' }, t('giftFromMe'))), ui.giftError && h('div', { class: 'notice err' }, ui.giftError), ui.busy ? h('button', { class: 'btn-block', disabled: true }, h('span', { class: 'spinner sm' })) @@ -864,36 +979,40 @@ export function giftsFeature(ctx) { // Gift link: presign a chosen amount as a #gift= PSBT that whoever opens claims // into a fresh wallet only they control. The coin is reserved until claimed. function giftUrl() { - return `${location.origin}/${ui.giftIsArk ? 'ag' : 'g'}/${ui.giftCode}`; + return `${location.origin}/${ui.giftIsArk ? 'ag' : 'g'}/${ui.giftCode}${giftFrag(ui.giftNoteMade, ui.giftFromMade)}`; } function giftRate() { return (wallet.feeRates && wallet.feeRates.halfHourFee) || 5; } - function doCreateGift(amt, rate) { + async function doCreateGift(amt, rate) { + ui.busy = true; render(); try { - finishGift(wallet.createGift(amt, rate), amt); + await finishGift(wallet.createGift(amt, rate), amt); ui.giftError = ''; ui.giftSplitOffer = null; } catch (e) { ui.giftError = e.message; ui.giftSplitOffer = null; } + ui.busy = false; render(); } // Gift the whole spendable balance as a no-change sweep (the recipient receives // everything minus their claim fee). - function doCreateGiftAll(rate) { + async function doCreateGiftAll(rate) { + ui.busy = true; render(); try { - finishGift(wallet.createGiftAll(rate)); + await finishGift(wallet.createGiftAll(rate)); ui.giftError = ''; ui.giftMax = false; ui.giftSplitOffer = null; } catch (e) { ui.giftError = e.message; } + ui.busy = false; render(); } @@ -906,7 +1025,7 @@ export function giftsFeature(ctx) { ui.busy = true; ui.giftError = ''; render(); try { const rate = (wallet.feeRates && wallet.feeRates.halfHourFee) || 5; - finishGift(await wallet.createGiftFromSplit(amt, rate), amt); + await finishGift(await wallet.createGiftFromSplit(amt, rate), amt); ui.giftSplitOffer = null; ui.giftError = ''; } catch (e) { diff --git a/src/features/messages.js b/src/features/messages.js index 2b175e2..76d8c4f 100644 --- a/src/features/messages.js +++ b/src/features/messages.js @@ -67,7 +67,12 @@ import { mergeFeeds } from '../feed-sync.js'; // coinos's own relay and primal: both take DM gift wraps and pass call // messages (ephemeral 21059) on live. nos.lol was here until 2026-10-19 — it // refused or ignored the household IP's publishes, call answers among them. -const DM_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net']; +// messages.coinos.io (Magnitude Relay, built for gift-wrapped messages) leads; +// relay.coinos.io stays on while older inbox lists still name it +const MESSAGES_RELAY = 'wss://messages.coinos.io'; +const DM_RELAYS = [MESSAGES_RELAY, 'wss://relay.coinos.io', 'wss://relay.primal.net']; +// what this app put in a wallet key's kind 10050 before messages.coinos.io +const OLD_DM_DEFAULTS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://relay.damus.io']; const NOTIFIER = 'https://nwcpush.coinos.io'; const APP_BASE = 'https://v3.coinos.io'; const CACHE_MAX = 50; // messages kept per channel / per DM thread in feature state @@ -3314,12 +3319,19 @@ export function messagesFeature(ctx) { // — the user's other clients own that. And when a login identity IS active, // don't advertise the seed key at all: it's internal, not a second inbox // (advertising it is what let DMs land on a phantom identity). + // A list this app wrote with its old defaults (nothing else in it) is + // brought up to today's, so senders find messages.coinos.io first. async function ensureDmRelayList() { if (!wallet.nostr || !wallet.nostr.sk) return; if (hook('nostrLoginIdentity')) return; const pk = wallet.nostr.pk; const existing = await queryOn(DM_RELAYS, { kinds: [10050], authors: [pk] }, 2500); - if (existing.length) return; + if (existing.length) { + const latest = existing.reduce((a, b) => (b.created_at > a.created_at ? b : a)); + const urls = latest.tags.filter((x) => x[0] === 'relay').map((x) => String(x[1] || '').replace(/\/$/, '')); + const ours = urls.length && urls.every((u) => OLD_DM_DEFAULTS.includes(u)); + if (!ours || urls.includes(DM_RELAYS[0])) return; + } const evt = finalizeEvent({ kind: 10050, content: '', @@ -4123,7 +4135,8 @@ export function messagesFeature(ctx) { // ---- profile notes: latest public posts & replies ----------------------- - const NOTE_RELAYS = [...new Set([...PROFILE_RELAYS, ...DM_RELAYS])]; + // (not messages.coinos.io: it takes messages, not posts) + const NOTE_RELAYS = [...new Set([...PROFILE_RELAYS, ...DM_RELAYS.filter((r) => r !== MESSAGES_RELAY)])]; // ---- zap tallies --------------------------------------------------------- // How much a post or chat message has been zapped: the public receipts @@ -4528,10 +4541,12 @@ export function messagesFeature(ctx) { const momentsOn = (id, file) => [...(timedActivity.get(id)?.values() || [])] .filter(x => x.moment.url === mediaMoment(file, 0)?.url && !hiddenPk(x.ev.pubkey) && !isDeleted(x.ev)) .sort((a, b) => a.moment.seconds - b.moment.seconds) - .map(x => ({ ...x, text: displayName(x.ev.kind === 9735 || x.ev.kind === 9737 ? zapperOf(x.ev) || x.ev.pubkey : x.ev.pubkey) + ' · ' + String(x.text || x.icon).slice(0, 240) })); + .map(x => ({ ...x, text: displayName(x.ev.kind === 9735 || x.ev.kind === 9737 ? zapperOf(x.ev) || x.ev.pubkey : x.ev.pubkey) + ' · ' + String(momentStripped(x.ev, x.text) || x.icon).slice(0, 240) })); // how a moment shows on a bar: a reaction as its emoji (a :code: as its - // picture, from the reaction's own tag), a zap ⚡, a reply ↩ + // picture, from the reaction's own tag), a zap ⚡, a reply as its + // author's face function momentGlyph(x) { + if (x.ev.kind === 1 || x.ev.kind === 1111) return avatar(x.ev.pubkey, 'chat-avatar media-mark-face', false); if (x.ev.kind !== 7) return x.icon; const code = shortcodeOf(x.ev.content); const tag = code && x.ev.tags.find(t => t[0] === 'emoji' && t[1] === code && t[2]); @@ -4551,6 +4566,19 @@ export function messagesFeature(ctx) { } return null; } + // A comment made at a moment of a clip opens with its time as a link that + // plays the clip from there; the "[0:03] " other clients read as text is + // left out of the words beside it. + function momentLink(ev) { + const m = readMoment(ev); + if (!m) return null; + return h('a', { class: 'media-time-link', href: m.url + '#t=' + m.seconds, target: '_blank', rel: 'noopener noreferrer', onClick: e => { + e.stopPropagation(); + const player = [...document.querySelectorAll('audio, video')].find(v => mediaMoment(v.dataset.clip || v.getAttribute('src'), 0)?.url === m.url); + if (player) { e.preventDefault(); const seek = () => { player.currentTime = Math.min(m.seconds, Number.isFinite(player.duration) ? player.duration : m.seconds); }; if (player.readyState) seek(); else player.addEventListener('loadedmetadata', seek, { once: true }); player.play().catch(() => {}); player.scrollIntoView({ block: 'center' }); } + } }, '▶ ' + mediaClock(m.seconds)); + } + const momentStripped = (ev, text) => (readMoment(ev) ? String(text || '').replace(/^\s*\[\d{1,2}(?::\d{2}){1,2}\]\s*/, '') : text); const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, mediaMoment: m } : ev; }; function attachMediaTimeline(player, url, explicitEvent) { if (player._timeline) return; @@ -4562,7 +4590,8 @@ export function messagesFeature(ctx) { }; const box = player.parentElement; box._skipMorph = true; - box.append(mediaTimeline(player, url, { h, event, label: t, moments: momentsOn, glyph: momentGlyph })); + box.append(mediaTimeline(player, url, { h, event, label: t, moments: momentsOn, glyph: momentGlyph, + onMarks: player.tagName === 'VIDEO' ? (on) => ownBar(player, on) : null })); player.dispatchEvent(new Event('timeupdate')); } function noteEvent(ev) { @@ -6716,7 +6745,8 @@ export function messagesFeature(ctx) { const d = {}; if (!have.size && +f.size > 0) d.size = +f.size; // no size, but a bitrate (bits/s) and a duration (Primal posts these): near enough - else if (!have.size && +f.bitrate > 0 && +f.duration > 0) d.size = Math.round(+f.bitrate * +f.duration / 8); + // (a guess: never taken for the file's identity, see mediaItems) + else if (!have.size && +f.bitrate > 0 && +f.duration > 0) { d.size = Math.round(+f.bitrate * +f.duration / 8); d.sizeGuess = true; } if (!have.dur && +f.duration > 0) d.dur = +f.duration; const m = /^(\d+)(?:\.0+)?x(\d+)(?:\.0+)?$/.exec(f.dim || ''); if (!have.w && m) { d.w = +m[1]; d.h = +m[2]; } @@ -6820,14 +6850,14 @@ export function messagesFeature(ctx) { for (const p of parts) { if (o >= buf.length) break; buf.set(p.subarray(0, buf.length - o), o); o += p.length; } const head = readMp4Head(buf); const d = { probed: true, ranges, faststart: head.faststart === true, failedAt: undefined, goneAt: undefined, ...(head.moovEnd ? { moovEnd: head.moovEnd } : {}), ...(head.hevc ? { hevc: true } : {}), ...(head.dur && !(videoInfo.get(url) || {}).dur ? { dur: head.dur } : {}) }; - if (total > 0) d.size = total; + if (total > 0) { d.size = total; d.sizeGuess = undefined; } else { // a server that hides Content-Range from scripts (Primal's) still // says Content-Length to a HEAD, which any page may read try { const hr = await fetch(url, { method: 'HEAD', cache: 'no-store', signal: AbortSignal.timeout(5000) }); const n = +hr.headers.get('content-length'); - if (hr.ok && n > 0) d.size = n; + if (hr.ok && n > 0) { d.size = n; d.sizeGuess = undefined; } } catch {} } if (head.w && !(videoInfo.get(url) || {}).w) { d.w = head.w; d.h = head.h; } @@ -7948,7 +7978,7 @@ export function messagesFeature(ctx) { // known, never taller than the screen; only a clip taller than that sits // in a black frame, rather than in a strip at the left. const videoBoxStyle = (d) => d && d.width && d.height - ? `width:100%;aspect-ratio:${d.width}/${d.height};max-height:100vh;object-fit:contain` + ? `width:100%;aspect-ratio:${d.width}/${d.height};max-height:var(--vid-cap);object-fit:contain` : 'width:100%;aspect-ratio:16/9;object-fit:contain'; // Over a clip that waits for a tap: what it costs, and the tap that plays // it (with sound — the reader asked for this one). The box is left alone @@ -7966,7 +7996,7 @@ export function messagesFeature(ctx) { if (v) { if (v.getAttribute('src') !== playSrc(url)) v.setAttribute('src', playSrc(url)); v.preload = 'auto'; - v.play().catch(() => { wokeClips.add(url); box.classList.remove('idle'); v.controls = true; }); + v.play().catch(() => { wokeClips.add(url); box.classList.remove('idle'); nativeControls(v); }); } } }, h('span', { class: 'vid-heavy-play', 'aria-hidden': 'true' }, '\u25b6'), h('span', {}, heavyLabel(url))); box.append(cover); @@ -7986,6 +8016,7 @@ export function messagesFeature(ctx) { const h264Of = (url) => VMEDIA + 'h264.mp4?u=' + encodeURIComponent(url); const noPicture = new Set(), h264Failed = new Set(); const serverThumbFailed = new Set(); // clips vmedia had no picture for (this session) + const deadTiles = new Set(); // grid pictures that wouldn't load (this session): left out // A picture from a host that won't hand over its bytes (no CORS: primal's // blossom, nostrcheck, most personal sites) can't have its column copy made // here, so the server makes it (pic.webp: 1100px wide, or a 360px square @@ -8093,10 +8124,38 @@ export function messagesFeature(ctx) { }); } // A tap on the picture itself (not the player's own play button or its - // control bar): inline, it goes full screen — the corner button is a + // control bar): inline, a mouse click pauses a playing clip; a paused one + // (or any touch) goes full screen — the corner button is a // reach on a phone. Full screen, it pauses a playing clip, and a tap on a // paused one comes back out. The player's controls are inside the video // element, so where they sit is judged from the tap's position. + // The big play/pause over a feed clip is for a mouse: <html> carries + // .has-mouse while the last pointer was one (a touch laptop switches with + // the hand), and CSS shows the button on :hover (a repaint can't drop it). + if (typeof document !== 'undefined') { + const mouseIs = (on) => document.documentElement.classList.toggle('has-mouse', on); + document.addEventListener('pointermove', (e) => { if (e.pointerType === 'mouse') mouseIs(true); }, { passive: true }); + document.addEventListener('pointerdown', (e) => { if (e.pointerType !== 'mouse') mouseIs(false); }, { passive: true }); + } + // A clip whose post has timed reactions seeks on the moments bar under it + // (the reactions sit on it at their moments), so the player's own controls + // — a second seek bar — stay off; the middle button and the sound button + // are its controls then (Adam: "hide the main seek bar … and only show a + // moments seek bar"). Otherwise the player's controls, once it has woken. + const nativeControls = (v) => { v.controls = !v._ownBar; }; + function ownBar(player, on) { + const box = player.closest('.note-video-box'); + if (!box || player._ownBar === on) return; + player._ownBar = on; + box.classList.toggle('own-bar', on); + if (!box.classList.contains('idle')) nativeControls(player); + // with no player controls, the sound button stays to turn it back down + if (on && !box.querySelector('.vid-sound')) { + const b = soundBtn((button) => { player.muted = !player.muted; button.setSound(!player.muted); }); + b.setSound(!player.muted); + box.append(b); + } + } const fsElement = () => (typeof document !== 'undefined' && (document.fullscreenElement || document.webkitFullscreenElement)) || null; let videoTapAt = 0; // a touch's tap on a clip, taken at pointerup: the click after it lands on whatever opened function videoTap(e, url) { @@ -8118,12 +8177,24 @@ export function messagesFeature(ctx) { else (document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)?.catch?.(() => {}); return true; } + // a mouse click on a playing clip just pauses it (Adam: "clicking on a + // video that's playing should pause the video, not full screen it"); it + // keeps its controls and the middle button resumes it, and a click on it + // paused opens the pager. A touch has no middle button: its tap still opens. + if (!v.paused && e.pointerType === 'mouse') { + v.pause(); + wokeClips.add(url); + const box = v.closest('.note-video-box'); + if (box) { box.classList.remove('idle'); box._skipMorph = true; } + nativeControls(v); + return true; + } if (openClip(v, url)) return true; // a clip still idle (autoplaying, no controls) becomes the reader's wokeClips.add(url); const box = v.closest('.note-video-box'); if (box) { box.classList.remove('idle'); box._skipMorph = true; } - v.controls = true; + nativeControls(v); const go = v.requestFullscreen || v.webkitRequestFullscreen || v.webkitEnterFullscreen; if (!go) return true; // (the screen isn't turned for it: a wide clip plays with bars, and the @@ -8185,13 +8256,38 @@ export function messagesFeature(ctx) { if (videoTap(e, url)) el._tapAt = videoTapAt = Date.now(); }); v.muted = !loud; // the property, not just the attribute: a script-made element autoplays only muted - const box = h('div', { class: 'note-video-box' + (idle ? ' idle' : '') }, v); + // a tall clip is held to the cap's height and the box narrows to its + // shape, instead of a full-width box of black bars (Adam, on a 1920 screen) + const boxCap = (w, ht) => w && ht ? `max-width:calc(var(--vid-cap) * ${w} / ${ht})` : undefined; + const known = feedMedia(url); + const box = h('div', { class: 'note-video-box' + (idle ? ' idle' : ''), style: boxCap(known && known.width, known && known.height) }, v); + v.addEventListener('loadedmetadata', () => { if (v.videoWidth && v.videoHeight) box.style.maxWidth = `calc(var(--vid-cap) * ${v.videoWidth} / ${v.videoHeight})`; }); if (loud) box._skipMorph = true; + // With a mouse: a big play/pause button in the middle while the pointer is + // over the clip. It plays or pauses in place, never full screen (a click + // elsewhere on a paused clip opens the pager). Touch keeps its taps. + const pp = h('button', { class: 'vid-pp', type: 'button', 'aria-label': t('videoPlay'), onClick: (e) => { + e.stopPropagation(); e.preventDefault(); + const player = e.currentTarget.closest('.note-video-box')?.querySelector('video'); + if (!player) return; + if (player.paused) { tappedClips.add(url); player.play().catch(() => {}); } else player.pause(); + } }, h('span', { class: 'vid-pp-i', 'aria-hidden': 'true' })); + const ppState = () => { + const live = v.closest('.note-video-box'); + const b = live && live.querySelector('.vid-pp'); + if (!b) return; + b.classList.toggle('playing', !v.paused); + b.setAttribute('aria-label', t(v.paused ? 'videoPlay' : 'videoPause')); + }; + v.addEventListener('play', ppState); + v.addEventListener('pause', ppState); + box.append(pp); + // remembered by clip, so a repaint draws the box as it now stands const wake = () => { wokeClips.add(url); box.classList.remove('idle'); - v.controls = true; + nativeControls(v); }; v.addEventListener('playing', wake); const btn = loud ? null : soundBtn((button) => { @@ -8200,14 +8296,19 @@ export function messagesFeature(ctx) { const liveBox = button.closest('.note-video-box'); const player = liveBox?.querySelector('video'); if (!player) return; + if (player._ownBar && !player.muted) { player.muted = true; button.setSound(false); return; } player.muted = false; unmutedClips.add(url); liveBox._skipMorph = true; // the box is the viewer's now: no repaint rebuilds it muted if (player.paused) player.play().catch(() => {}); - button.remove(); // the player's own controls carry mute from here + // the player's own controls carry mute from here — unless they're off + // for the moments bar: then this button turns it down again + if (player._ownBar) button.setSound(true); else button.remove(); }); v.onvolumechange = () => { - if (!v.muted) { unmutedClips.add(url); if (btn && btn.isConnected) btn.remove(); } // unmuted from the native control: same + const b = v.closest('.note-video-box')?.querySelector('.vid-sound'); + if (v._ownBar && b && b.setSound) b.setSound(!v.muted); + if (!v.muted) { unmutedClips.add(url); if (btn && btn.isConnected && !v._ownBar) btn.remove(); } // unmuted from the native control: same else unmutedClips.delete(url); // muted again from the control: the next box starts quiet }; if (btn) box.append(btn); @@ -9307,7 +9408,7 @@ export function messagesFeature(ctx) { }; return h('div', { class: 'col live-page', style: 'gap:12px' }, ctx.brandHeader(!ui.pubProf && wallet.loaded), - h('div', { class: 'card col', style: 'gap:10px' }, + h('div', { class: 'card col live-main', style: 'gap:10px' }, h('div', { class: 'row gap6', style: 'align-items:center' }, mine ? h('button', { class: 'iconbtn chat-back', onClick: () => { if (confirm(t('goLiveEndAsk'))) endBroadcast(); } }, '‹') : backBtn(() => { ui.liveStream = null; }), @@ -9359,7 +9460,7 @@ export function messagesFeature(ctx) { watchersRow(w), liveSummary(ev) ? h('div', { class: 'small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, liveSummary(ev).slice(0, 600)) : null, ui.liveReport && ui.liveReport.a === s.a ? liveReportPanel(ev) : null), - h('div', { class: 'card col', style: 'gap:8px' }, + h('div', { class: 'card col live-chat-card', style: 'gap:8px' }, h('div', { class: 'small muted' }, t('liveChat')), h('div', { class: 'live-chat', 'data-key': 'live-chat:' + s.a, @@ -11075,6 +11176,10 @@ export function messagesFeature(ctx) { return null; } const hidden = (ev) => !!hiddenWhy(ev); + // A list row with nothing left to show: a post its author deleted, or a + // repost of one (a deletion that lands after the row did, too). Threads + // keep their deleted posts' places; lists just drop them. + const goneHere = (ev) => isDeleted(ev) || (ev.kind === REPOST && !!repostInner(ev) && isDeleted(repostInner(ev))); const hiddenPk = (pk) => !!pk && !isMe(pk) && (isMuted(pk) || (baselineMutes() || { set: new Set() }).set.has(pk) || isSpammer(pk) || reportsNow().mine.has(pk)); const visiblePks = (pks) => [...(pks || [])].filter((pk) => !hiddenPk(pk)); @@ -11988,13 +12093,9 @@ export function messagesFeature(ctx) { zapText(ev) ? h('div', {}, ...noteBody(zapText(ev))) : null) : foreign ? h('div', { class: 'note-text small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, (ev.kind === 64 ? '\u265f ' : '') + altText) - : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...(ev.kind === ARTICLE ? (open ? [articleCard(ev)] : articleBody(ev)) : noteBody(shownTranslation(ev)?.text ?? noteText(ev), 0, noteEmojiTags(ev)))), - readMoment(ev) ? h('a', { class: 'small media-time-link', href: readMoment(ev).url + '#t=' + readMoment(ev).seconds, target: '_blank', rel: 'noopener noreferrer', onClick: e => { - e.stopPropagation(); - const m = readMoment(ev); - const player = [...document.querySelectorAll('audio, video')].find(v => mediaMoment(v.dataset.clip || v.getAttribute('src'), 0)?.url === m.url); - if (player) { e.preventDefault(); const seek = () => { player.currentTime = Math.min(m.seconds, Number.isFinite(player.duration) ? player.duration : m.seconds); }; if (player.readyState) seek(); else player.addEventListener('loadedmetadata', seek, { once: true }); player.play().catch(() => {}); player.scrollIntoView({ block: 'center' }); } - } }, '▶ ' + mediaClock(readMoment(ev).seconds)) : null, + : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, + momentLink(ev), + ...(ev.kind === ARTICLE ? (open ? [articleCard(ev)] : articleBody(ev)) : noteBody(momentStripped(ev, shownTranslation(ev)?.text ?? noteText(ev)), 0, noteEmojiTags(ev)))), foreign || pending ? null : translateLine(ev), ev.kind === POLL ? pollBox(ev) : null, pending ? null : noteActions(pk, ev, { canZap }), @@ -12445,7 +12546,9 @@ export function messagesFeature(ctx) { onKeydown: (e) => { mentionKey(e); if (e.defaultPrevented) return; - if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); e.target.closest('.col').querySelector('.thread-reply-send')?.click(); return; } + // a phone's Return is a new line (Reply is the button); a + // keyboard's Enter sends + if (e.key === 'Enter' && !e.shiftKey && !matchMedia('(pointer: coarse)').matches) { e.preventDefault(); e.target.closest('.col').querySelector('.thread-reply-send')?.click(); return; } if (e.ctrlKey && (e.key === 'j' || e.key === 'J')) { e.preventDefault(); const el = e.target; @@ -12486,7 +12589,19 @@ export function messagesFeature(ctx) { previewBtn(!!s.preview, () => { s.preview = !s.preview; render(); }), h('button', { class: 'btn-ghost btn-sm thread-reply-cancel', type: 'button', - onClick: () => { s.replying = false; s.preview = false; s.mediaMoment = null; render(); }, + // Cancel discards: the typed text, its attachments and the box. + // (It only folded the `replying` flag before, and the box stays + // up while a draft has text — so with anything typed it did + // nothing visible.) The field may still be focused, and the + // morph leaves a focused field's value alone: clear it by hand. + onClick: () => { + const text = s.draft || ''; + s.draft = ''; s.replying = false; s.preview = false; s.mediaMoment = null; + ui.postMedia = (ui.postMedia || []).filter((m) => !text.includes(m.url)); + const inp = document.querySelector('.thread-reply-input'); + if (inp) inp.value = ''; + render(); + }, }, t('cancel'))), h('button', { class: 'btn-primary btn-sm thread-reply-send', disabled: !!s.sending || !!ui.postUploading, @@ -12585,12 +12700,32 @@ export function messagesFeature(ctx) { ...noteOverlays()); } - async function publishProfileFields(fields, opts = {}) { + // Every kind-0 publish merges over the newest copy on the relays, so two + // publishes in flight at once clobber each other: both read the same base, + // the later one lands without the earlier one's fields. That exact race + // put a migrated user's released placeholder name back into their lud16 + // (the rename repointed it, the legacy-avatar import republished the old + // base nine seconds later). One at a time, and the base is never older + // than what this session last wrote. + let kind0Chain = Promise.resolve(); + let kind0Last = null; // { at, content } — the newest kind 0 we published + const withKind0Lock = (fn) => { const p = kind0Chain.then(fn, fn); kind0Chain = p.catch(() => {}); return p; }; + async function newestKind0(pk) { + const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [pk] }, 3000); + let newest = evs.sort((a, b) => b.created_at - a.created_at)[0] || null; + if (kind0Last && kind0Last.pk === pk && (!newest || newest.created_at <= kind0Last.at)) newest = kind0Last; + let base = {}; + try { base = newest ? JSON.parse(newest.content) : {}; } catch {} + return base; + } + // Strictly later than the last one we sent: relays keep the LOWEST id of + // two replaceable events with the same second, so a second publish in + // the same second as the first could lose to it. + const kind0Stamp = (pk) => { const now = Math.floor(Date.now() / 1000); return kind0Last && kind0Last.pk === pk ? Math.max(now, kind0Last.at + 1) : now; }; + function publishProfileFields(fields, opts = {}) { return withKind0Lock(() => publishProfileFieldsNow(fields, opts)); } + async function publishProfileFieldsNow(fields, opts = {}) { const id = await requireIdentity(); - const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000); - const newest = evs.sort((a, b) => b.created_at - a.created_at)[0]; - let base = {}; - try { base = newest ? JSON.parse(newest.content) : {}; } catch {} + const base = await newestKind0(id.pubkey); if (opts.onlyWhen && !opts.onlyWhen(base)) return true; // condition says leave it be const merged = { ...base }; // fillOnly fields are offers, not orders: the onboarding wizard suggests @@ -12606,10 +12741,11 @@ export function messagesFeature(ctx) { } if (merged.name && !(fill.has('name') && taken('name'))) merged.display_name = merged.name; if (JSON.stringify(merged) === JSON.stringify(base)) return true; // nothing to say - const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) }; + const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: kind0Stamp(id.pubkey) }; const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt); if (!ok) throw new Error(t('msgSendFailed')); + kind0Last = { pk: id.pubkey, at: evt.created_at, content: evt.content }; fullProfiles.set(id.pubkey, merged); profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null, t: Date.now() }); return true; @@ -12623,11 +12759,20 @@ export function messagesFeature(ctx) { ui.profSaving = true; render(); try { + await withKind0Lock(() => saveProfileNow(id, e)); + ui.profEdit = null; ui.profEditFilled = false; + toast(t('profSaved')); + } catch (err) { + if (ui.profEdit === e && e.uname === err.migrationName) e.migrationName = err.migrationName; + toast(err.message || String(err)); + } finally { + ui.profSaving = false; + render(); + } + } + async function saveProfileNow(id, e) { // merge over the newest published kind 0 so unknown fields round-trip - const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000); - const newest = evs.sort((a, b) => b.created_at - a.created_at)[0]; - let base = {}; - try { base = newest ? JSON.parse(newest.content) : {}; } catch {} + const base = await newestKind0(id.pubkey); // A changed username claims first — if the name is taken (or invalid) // the save stops here and the editor stays open to fix it. const oldAddr = hook('namesAddress'); @@ -12647,26 +12792,62 @@ export function messagesFeature(ctx) { // when empty; move them when they pointed at our (old) address. A // deliberately foreign lud16/nip05 is the user's business. if (addr) { - for (const k of ['lud16', 'nip05']) - if (!merged[k] || merged[k] === oldAddr) merged[k] = addr; + const domain = addr.split('@')[1]; + for (const k of ['lud16', 'nip05']) { + const cur = merged[k]; + if (!cur || cur === oldAddr) { merged[k] = addr; continue; } + // a name at our own domain that is not ours and no longer answers + // (the placeholder a migration released) is ours now — Save is the + // heal an interactive signer can't do in the background + if (typeof cur === 'string' && cur !== addr && cur.split('@')[1] === domain && !/^_@/.test(cur) && await addressDead(cur)) merged[k] = addr; + } } if (merged.name) merged.display_name = merged.name; - const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) }; + const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: kind0Stamp(id.pubkey) }; const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial); const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt); if (!ok) throw new Error(t('msgSendFailed')); + kind0Last = { pk: id.pubkey, at: evt.created_at, content: evt.content }; fullProfiles.set(id.pubkey, merged); profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null }); - ui.profEdit = null; ui.profEditFilled = false; - toast(t('profSaved')); - } catch (err) { - if (ui.profEdit === e && e.uname === err.migrationName) e.migrationName = err.migrationName; - toast(err.message || String(err)); - } finally { - ui.profSaving = false; - render(); + } + // A payment-address rename released the old name: repoint the kind 0's + // lud16 and nip05 — but only where they pointed at the released address + // (or were empty). Deliberately different values are not ours to touch. + function repointAddress(oldAddr, newAddr) { + const follows = (k) => (base) => !base[k] || base[k] === oldAddr; + return publishProfileFields({ lud16: newAddr, nip05: newAddr }, { + onlyWhen: (base) => ['lud16', 'nip05'].some((k) => follows(k)(base) && base[k] !== newAddr), + fieldWhen: { lud16: follows('lud16'), nip05: follows('nip05') }, + }); + } + // Our kind 0 still names an address at our own domain that is not the one + // we hold — a placeholder name released by a migration whose repoint lost + // the race above. Repointed once the domain confirms the old name is dead; + // a same-domain name that still answers (a second account, say) is left + // alone. Once per address per session. + const addrHealed = new Set(); + async function healStaleAddress(olds, myAddr) { + // Amber by intent needs a tap per signature: a background publish would + // sit in the kind-0 queue forever and block every later one. Save in the + // profile editor repoints the address for these users instead. + const id = await identity().catch(() => null); + if (!id || (id.signer && id.signer.interactive)) return; + for (const old of olds) { + if (addrHealed.has(old)) continue; + addrHealed.add(old); + try { if (await addressDead(old)) await repointAddress(old, myAddr); } catch {} } } + async function addressDead(addr) { + const [name, domain] = addr.split('@'); + try { + const r = await fetch(`https://${domain}/.well-known/lnurlp/${encodeURIComponent(name)}`, { cache: 'no-store' }); + if (!r.ok) return true; + const j = await r.json().catch(() => null); + return !j || j.status === 'ERROR' || !j.callback; + } catch { return false; } // unreachable is not dead + } function profileScreen() { const pk = ui.profilePk; @@ -12806,9 +12987,17 @@ export function messagesFeature(ctx) { // authoritative locally, a deep link carries the address in the URL // (seeded as `addr`), and the light cache remembers it from last time. const lp = profileOf(pk) || {}; - const rawNip05 = (full && full.nip05) || (mine && myAddr) || lp.nip05 || lp.addr || null; + // Our own page never shows a name at our domain that the registrar says + // is no longer ours (see healStaleAddress): the claimed address is the + // truth here, and the kind 0 is brought in line in the background. + const stale = (v) => mine && myAddr && typeof v === 'string' && v !== myAddr && v.split('@')[1] === myAddr.split('@')[1] && !/^_@/.test(v) ? v : null; + if (full) { const olds = [...new Set([stale(full.lud16), stale(full.nip05)].filter(Boolean))]; if (olds.length) healStaleAddress(olds, myAddr); } + const rawNip05 = (full && (stale(full.nip05) ? myAddr : full.nip05)) || (mine && myAddr) || lp.nip05 || lp.addr || null; const nip05 = rawNip05 ? String(rawNip05).replace(/^_@/, '') : null; - const lud16 = (full && full.lud16 ? String(full.lud16) : null) || lp.lud16 || null; + // the lightning line too: a stale same-domain lud16 (jar@ after the + // rename to jarryd@) showed under the right NIP-05 as a second address + const rawLud = (full && full.lud16 ? String(full.lud16) : null) || lp.lud16 || null; + const lud16 = rawLud ? (stale(rawLud) ? myAddr : rawLud) : null; const showLud = lud16 && !/^npub1/i.test(lud16) && lud16 !== nip05; // an about of "~" or a lone character is noise, not a bio. // Until the full kind 0 lands, the light profile cache answers — it was @@ -13052,7 +13241,8 @@ export function messagesFeature(ctx) { // Streams joins the tabs once they've streamed const streamed = pastOf(pk).length > 0; const tab = profTab(pk) === 'streams' && !streamed ? 'posts' : profTab(pk); - const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e)); + // a post its author deleted leaves the list (no "was deleted" row) + const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e) && !goneHere(e)); // a tab that holds only a few of the pages fetched so far (someone // who mostly replies, or mostly posts) asks for older ones by itself: // too short to scroll means the scroll that loads more never comes @@ -13085,7 +13275,7 @@ export function messagesFeature(ctx) { return h('div', { class: 'col', style: 'gap:8px' }, tabs, h('div', { class: 'card col notes-feed', style: 'gap:0', 'data-key': 'prof-notes:' + tab }, - ...(c.winList = () => c.notes.filter((e) => (profTab(pk) === 'replies') === replyish(e)), windowedRows(c, shown, (ev) => keyed(noteRow(pk, ev, name, { context: profTab(pk) === 'replies' }), ev.id)))), + ...(c.winList = () => c.notes.filter((e) => (profTab(pk) === 'replies') === replyish(e) && !goneHere(e)), windowedRows(c, shown, (ev) => keyed(noteRow(pk, ev, name, { context: profTab(pk) === 'replies' }), ev.id)))), c.loadingMore ? h('div', { class: 'row gap6', style: 'justify-content:center;padding:4px 0' }, h('span', { class: 'spinner sm' })) @@ -13496,7 +13686,9 @@ export function messagesFeature(ctx) { const key = mediaIdxKey(feedId); let r = mediaIdx.get(key); if (r) return r; - r = { key, replies: !!(feedDef(feedId) || {}).replies, images: new Map(), videos: new Map(), articles: new Map(), art: { until: 0, end: 0, empty: 0, head: 0 }, checked: new Set(), until: 0, end: false, empty: 0, loaded: false }; + const order = () => ({ seq: new Map(), top: 0, bottom: 0, newest: 0 }); + r = { key, replies: !!(feedDef(feedId) || {}).replies, images: new Map(), videos: new Map(), articles: new Map(), art: { until: 0, end: 0, empty: 0, head: 0 }, checked: new Set(), until: 0, end: false, empty: 0, loaded: false, + order: { images: order(), videos: order() } }; mediaIdx.set(key, r); loadMediaIndex(key).then(async (rec) => { if (rec) { @@ -14021,13 +14213,41 @@ export function messagesFeature(ctx) { // the screen leaves them to the next) if (again && urls.length) said.set(again, ev.id); for (const url of urls) { + if (deadTiles.has(url)) continue; const f = sameFile(url); if (seen.has(f)) continue; seen.add(f); + // the same clip uploaded twice by one person (a note and a video + // event a few minutes apart) gets two hashes but keeps its size to + // the byte + const d = kind === 'videos' ? videoInfo.get(url) || {} : {}; + const twin = d.size && !d.sizeGuess ? ev.pubkey + '|' + d.size : null; + if (twin && seen.has(twin)) continue; + if (twin) seen.add(twin); out.push({ ev, url }); } } - return out; + return settledOrder(r, kind, out); + } + // The grid's order holds for the session (Adam, 2026-10-23: clips the + // crawl found landed in the middle of the grid, above an older tail the + // index had from before, and the tiles already there jumped): what it + // shows first is newest first, and whatever turns up after goes under what + // is already there, in its own date order. Only a post newer than the top + // tile goes above it. Nothing is settled until the kept index is in, so + // the first paint is one date order, not two batches. + function settledOrder(r, kind, out) { + if (!r.loaded) return out; + const o = r.order[kind]; + const key = (it) => it.ev.id + '|' + it.url; + const fresh = out.filter((it) => !o.seq.has(key(it))); + if (fresh.length) { + const above = o.seq.size ? fresh.filter((it) => it.ev.created_at > o.newest) : []; + for (const it of above.reverse()) o.seq.set(key(it), --o.top); + for (const it of fresh) if (!o.seq.has(key(it))) o.seq.set(key(it), ++o.bottom); + for (const it of fresh) if (it.ev.created_at > o.newest) o.newest = it.ev.created_at; + } + return out.sort((a, b) => o.seq.get(key(a)) - o.seq.get(key(b))); } // The feed's pictures (or clips) in reading order — every one of a post // before the next post's — for the pager opened from one in the feed: the @@ -14276,11 +14496,18 @@ export function messagesFeature(ctx) { onLoad: (e) => arFromStill(e.currentTarget, it.url), onError: (e) => { if (fromServer) { serverThumbFailed.add(it.url); render(); return; } // the frame grab's turn + // remembered, not only a class on the tile: the next + // repaint rewrites the class list, and the broken-picture + // glyph came back (a deleted nostr.media file in #artstr) + deadTiles.add(it.url); const b = e.target.closest('.media-tile'); if (b) b.classList.add('broken'); + scheduleRepaint(); } }) // no still to show: the clip's first frame, fetched once the tile is near : h('video', { 'data-src': it.url + '#t=0.1', muted: true, playsinline: true, preload: 'metadata' }), - mediaMode === 'videos' && poster && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null, + // (drawn here whatever the tile shows, so a repaint keeps the one + // the frame-grab added) + mediaMode === 'videos' && videoInfo.get(it.url)?.size && videoHeavy(it.url) ? h('span', { class: 'media-tile-badge' }, heavyLabel(it.url)) : null, mediaMode === 'videos' ? h('span', { class: 'media-tile-play', 'aria-hidden': 'true' }, '▶') : null); })); } @@ -14294,8 +14521,14 @@ export function messagesFeature(ctx) { if (!e.isIntersecting) continue; const v = e.target; tileObs.unobserve(v); - const tile = v.closest('.media-tile'); - if (tile) tile._skipMorph = true; + // the player (and whatever stands in for it) is left alone by + // repaints, which would strip its src; the tile around it keeps up + // with them (its shape when the grid's layout changes, its class). + // Freezing the whole tile kept a tile built for one-to-a-row out of + // the justified rows: no --ar, no width. + v._skipMorph = true; + const standIn = (el) => { el._skipMorph = true; return el; }; + const badge = (el) => { if (!el.parentNode.querySelector('.media-tile-badge')) el.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); }; // A first frame costs the start of the file when the index leads or // the server serves ranges — whatever the clip's size. Only an // index-last file without ranges would have to come down whole for @@ -14313,7 +14546,7 @@ export function messagesFeature(ctx) { img.addEventListener('load', () => arFromStill(img, url), { once: true }); img.src = videoThumbs.get(url); v.replaceWith(img); - if (heavy && d.size) img.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); + if (heavy && d.size) badge(img); return; } if (!v.isConnected) return; @@ -14325,7 +14558,7 @@ export function messagesFeature(ctx) { const cap = setTimeout(() => { if (v.readyState >= 2 || !v.isConnected) return; try { v.removeAttribute('src'); v.load(); } catch {} - v.replaceWith(h('span', { class: 'media-tile-cost' }, '')); + v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, ''))); }, 8000); v.addEventListener('loadeddata', () => clearTimeout(cap), { once: true }); } @@ -14333,11 +14566,23 @@ export function messagesFeature(ctx) { // (a plain load: shown, not kept — a player's pixels can only be // read from a CORS load, and those fail on a cached plain copy) v.muted = true; + // a clip the player can't load either is gone as far as the grid + // goes: a deleted file whose 404 came without CORS headers + // (Primal's blossom) only looked like a quiet host to the probe, + // and its tile sat blank. Left out for a day, like a 404 the + // probe could read. + v.addEventListener('error', () => { + if (!v.isConnected || !v.getAttribute('src')) return; // let go of by the eight-second cap + noteVideoInfo(url, { goneAt: Date.now() }); + const b = v.closest('.media-tile'); + if (b) b.classList.add('broken'); + scheduleRepaint(); + }, { once: true }); v.src = v.getAttribute('data-src'); - if (heavy && d.size) v.after(h('span', { class: 'media-tile-badge' }, heavyLabel(url))); + if (heavy && d.size) badge(v); return; } - v.replaceWith(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : '')); + v.replaceWith(standIn(h('span', { class: 'media-tile-cost' }, d && d.size ? heavyLabel(url) : ''))); }); } }, { rootMargin: '400px 0px' }); @@ -15833,7 +16078,7 @@ export function messagesFeature(ctx) { // (a reply whose post every lookup came back without isn't shown: a // "Couldn't find that note" over it told nobody anything — Adam, 2026-10-20) const repliesHere = feedReplies(c); - const shownHere = (ev) => !hidden(ev) && !(curatedFeed && notForPublic(ev)) && !(repliesHere && orphaned(ev)); + const shownHere = (ev) => !hidden(ev) && !goneHere(ev) && !(curatedFeed && notForPublic(ev)) && !(repliesHere && orphaned(ev)); const visible = c.notes.filter(shownHere); // Every child keyed by its post, hairlines included, so the morph // reconciles the list by post: a new one at the top is inserted as its @@ -18198,13 +18443,9 @@ export function messagesFeature(ctx) { // A payment-address rename released the old name: repoint the kind 0's // lud16 and nip05 — but only where they pointed at the released address // (or were empty). Deliberately different values are not ours to touch. - addressRenamed(oldAddr, newAddr) { - const follows = (k) => (base) => !base[k] || base[k] === oldAddr; - return publishProfileFields({ lud16: newAddr, nip05: newAddr }, { - onlyWhen: (base) => ['lud16', 'nip05'].some((k) => follows(k)(base) && base[k] !== newAddr), - fieldWhen: { lud16: follows('lud16'), nip05: follows('nip05') }, - }).catch(() => {}); - }, + addressRenamed(oldAddr, newAddr) { return repointAddress(oldAddr, newAddr).catch(() => {}); }, + // the profile editor's Save, without the editor (tests) + async saveProfileDraft(e) { const id = await identity(); return withKind0Lock(() => saveProfileNow(id, { name: '', about: '', picture: '', banner: '', ...e })); }, // opens the profile, unless the caller has a step to take first (the // Accounts page switches to that identity before showing its profile) profileChip(pk, size, onOpen) { @@ -18216,6 +18457,21 @@ export function messagesFeature(ctx) { }, avatar(pk, 'chat-avatar ' + (big ? 'send-avatar' : 'mini'), false), h('span', { class: big ? '' : 'small' }, displayName(pk))); }, + // a gift link names its sender: sign its template as us (gifts.js) + async signGiftFrom(tmpl) { + const id = await identity(); + if (!id) return null; + return id.signer instanceof Uint8Array ? finalizeEvent(tmpl, id.signer) : id.signer.signEvent(tmpl); + }, + // A claimed gift's sender: follow them, once any follow publish in + // flight (a fresh wallet's starter follows) has landed — followMany + // drops a call that arrives mid-publish. + async followGiftSender(pk) { + for (let i = 0; followsPub && i < 60; i++) await new Promise((r) => setTimeout(r, 500)); + if (!(await identity())) return false; + await followMany([pk]).catch(() => {}); + return true; + }, // A sign-in (Google, passkey, key) that found no wallet on its identity: // the same start, but only the follows of an identity that follows // nobody yet — an established nostr user keeps their own list. diff --git a/src/features/names.js b/src/features/names.js index 45b0b36..d57bb19 100644 --- a/src/features/names.js +++ b/src/features/names.js @@ -455,29 +455,35 @@ export function namesFeature(ctx) { // said as it's typed, not after a round trip (the registrar is the judge: // a name claimed before the rule can still be retaken by its owner) nameRuleHint(ui.nameClaim) ? h('div', { class: 'small', style: 'color:var(--red,#c0392b)' }, t('namesRule')) : null, - h('button', { class: 'btn-primary btn-block', disabled: ui.busy, onClick: async () => { - const name = (ui.nameClaim || '').toLowerCase().trim(); - if (!name) return; - ui.busy = true; ui.nameClaimError = null; ui.nameClaimMigration = null; render(); - try { - // Sign with the login identity when one can be (re)attached: the - // registrar lets a migrated coinos user's own identity take their - // name back, which the wallet key alone could never prove. - const signer = await Promise.resolve(hook('nostrLoginResume')).catch(() => null); - await claimRequestedName(name, signer ? { signer, manager: wallet.nostrPubkey() } : {}); - // the wizard's Spending step tells a name claimed here from one - // the registrar handed back (an account set up before) - if (ui.onb && ui.onb.step === 'spend') ui.onb.claimedHere = name; - ui.nameClaim = ''; - ui.nameEditOpen = false; - toast(t('namesClaimed', { name: `${name}@${DOMAIN()}` })); - } catch (e) { - ui.nameClaimError = e.message; - if (ui.nameClaim === name) ui.nameClaimMigration = e.migrationName || null; - } - ui.busy = false; render(); - } }, ui.busy ? h('span', { class: 'spinner' }) : t('namesClaim')), - ui.nameClaimMigration && ui.nameClaimMigration === ui.nameClaim && DOMAIN() === 'coinos.io' + h('button', { class: 'btn-primary btn-block', disabled: ui.busy, onClick: () => claimTyped(ui.nameClaim) }, ui.busy ? h('span', { class: 'spinner' }) : t('namesClaim')), + migrateLink()); + } + async function claimTyped(typed) { + const name = (typed || '').toLowerCase().trim(); + if (!name) return; + ui.busy = true; ui.nameClaimError = null; ui.nameClaimMigration = null; render(); + try { + // Sign with the login identity when one can be (re)attached: the + // registrar lets a migrated coinos user's own identity take their + // name back, which the wallet key alone could never prove. + const signer = await Promise.resolve(hook('nostrLoginResume')).catch(() => null); + await claimRequestedName(name, signer ? { signer, manager: wallet.nostrPubkey() } : {}); + // the wizard's Spending step tells a name claimed here from one + // the registrar handed back (an account set up before) + if (ui.onb && ui.onb.step === 'spend') ui.onb.claimedHere = name; + ui.nameClaim = ''; + ui.nameEdit = null; + ui.nameEditOpen = false; + toast(t('namesClaimed', { name: `${name}@${DOMAIN()}` })); + } catch (e) { + ui.nameClaimError = e.message; + if ((ui.nameEdit ?? ui.nameClaim) === name) ui.nameClaimMigration = e.migrationName || null; + } + ui.busy = false; render(); + } + // "I have a coinos account": a name the registrar holds for a legacy user + function migrateLink() { + return ui.nameClaimMigration && ui.nameClaimMigration === (ui.nameEdit ?? ui.nameClaim) && DOMAIN() === 'coinos.io' ? h('button', { type: 'button', class: 'linklike small', onClick: () => { @@ -490,7 +496,48 @@ export function namesFeature(ctx) { location.href = `https://coinos.io/migrate?to=${encodeURIComponent(addr)}&back=${encodeURIComponent(location.origin + '/')}`; } }, - }, t('onbHaveCoinos')) : null); + }, t('onbHaveCoinos')) : null; + } + + // Settings: the address and changing it are one card — the name sits in + // its own field; typing a different one offers the change (and says the + // old address stops working), otherwise Copy and Release. + function addressCard(st) { + const domain = st.domain || DOMAIN(); + const addr = `${st.name}@${domain}`; + const typed = ui.nameEdit ?? st.name; + const changed = !!typed && typed !== st.name; + return h('div', { class: 'card col', 'data-key': 'names' }, + h('h3', {}, t('namesTitle')), + ui.nameClaimError ? h('div', { class: 'notice err' }, ui.nameClaimError) : null, + h('div', { class: 'row gap6 name-field' }, + h('input', { + type: 'text', class: 'mono-input', placeholder: t('namesPlaceholder'), style: 'flex:1', + autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', 'aria-label': t('namesCustom'), + value: typed, + onInput: (e) => { + const was = changed; + ui.nameEdit = e.target.value.toLowerCase().trim(); + ui.nameClaimError = null; + if (ui.nameClaimMigration) ui.nameClaimMigration = null; + if ((!!ui.nameEdit && ui.nameEdit !== st.name) !== was || nameRuleHint(ui.nameEdit)) render(); + }, + }), + h('span', { class: 'muted', style: 'align-self:center' }, '@' + domain)), + changed && nameRuleHint(typed) ? h('div', { class: 'small', style: 'color:var(--red,#c0392b)' }, t('namesRule')) : null, + changed + ? h('div', { class: 'col', style: 'gap:8px' }, + h('p', { class: 'small muted', style: 'margin:0' }, t('namesCustomHow')), + h('div', { class: 'row gap6' }, + h('button', { class: 'btn-ghost btn-sm', disabled: ui.busy, onClick: () => { ui.nameEdit = null; ui.nameClaimError = null; ui.nameClaimMigration = null; render(); } }, t('cancel')), + h('button', { class: 'btn-primary btn-sm grow', disabled: ui.busy, onClick: () => claimTyped(typed) }, + ui.busy ? h('span', { class: 'spinner sm' }) : t('namesChangeTo', { addr: typed }))), + migrateLink()) + : h('div', { class: 'row gap6' }, + copyBtn(addr, t('namesCopy')), + h('button', { class: 'btn-ghost btn-sm', onClick: async () => { + await release(); toast(t('namesReleased')); render(); + } }, t('namesRelease')))); } // Settings: one card per concern, all laid out (no collapsed sections — @@ -519,14 +566,7 @@ export function namesFeature(ctx) { h('div', { class: 'addr-box break', style: 'font-size:11px' }, `${st.name}.user._bitcoin-payment.yourdomain.com. CNAME ${st.name}.user._bitcoin-payment.${domain}.`)), card('ownnode', t('namesOwnNode'), t('namesOwnNodeMenuHow'), ownNodeSection()), - card('custom', t('namesCustom'), t('namesCustomHow'), claimForm(false)), - card('names', t('namesTitle'), null, - h('div', { class: 'addr-box break', style: 'font-size:14px' }, addr), - h('div', { class: 'row gap6' }, - copyBtn(addr, t('namesCopy')), - h('button', { class: 'btn-ghost btn-sm', onClick: async () => { - await release(); toast(t('namesReleased')); render(); - } }, t('namesRelease')))), + addressCard(st), ].filter(Boolean); } // The terminal's cards live on the Point of sale settings page now — no @@ -884,7 +924,7 @@ export function namesFeature(ctx) { checked = false; lastError = null; // The claim field is a draft for THIS account — a name typed before a // logout used to greet the next account that opened on this device. - ui.nameClaim = null; ui.nameClaimError = null; ui.nameClaimMigration = null; suggestedFor = null; + ui.nameClaim = null; ui.nameEdit = null; ui.nameClaimError = null; ui.nameClaimMigration = null; suggestedFor = null; refresh(); }, // The pencil by the address opens this: choosing a name gets a page of diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js index f7f9e16..f39f9c3 100644 --- a/src/features/nostrlogin.js +++ b/src/features/nostrlogin.js @@ -16,7 +16,7 @@ import { qrSvg } from '../qr.js'; import { extensionSigner, bunkerSigner, keySigner, parseNostrSecret, walletForSigner, publishWalletBackup, fetchWalletBackup, nostrConnect, nostrConnectPending, resumeBunker, - amberAvailable, amberSigner, amberPending, amberDeliver, amberCancel, onAmberChange } from '../nostr-login.js'; + amberAvailable, amberSigner, amberPending, amberDeliver, amberCancel, amberOpen, onAmberChange } from '../nostr-login.js'; // The nostr ostrich, in the brand's monochrome. const OSTRICH = '<svg width="23" height="23" style="display:block" viewBox="0 0 2000 2000" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="ng" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#B84FE8"/><stop offset="100%" stop-color="#6D28D9"/></linearGradient></defs><circle cx="1000" cy="1000" r="1000" fill="url(#ng)"/><g transform="translate(1000 1000) scale(0.82) translate(-1000 -1000)"><path d="M1574.29 770.408C1532.04 840.612 1445.92 888.367 1437.96 892.449C1421.84 901.02 1415.92 913.469 1416.94 932.041C1417.96 950.612 1413.47 1042.65 1357.35 1083.27C1328.57 1104.08 1212.45 1131.02 1159.18 1140C1131.84 1144.69 1125.51 1153.06 1110.41 1162.04C1090 1174.69 1017.55 1275.1 1005.31 1297.35C1006.94 1297.14 1233.67 1226.73 1243.88 1225.1C1270.82 1221.02 1291.22 1228.78 1304.49 1248.37C1317.14 1267.14 1329.59 1286.12 1342.04 1305.1C1346.53 1311.84 1350.82 1318.78 1355.1 1325.71L1359.59 1332.86C1361.22 1335.51 1363.47 1338.57 1364.49 1342.65C1365.31 1345.51 1367.14 1355.1 1361.63 1360.82C1356.53 1366.12 1347.76 1366.12 1343.06 1364.9C1338.57 1363.67 1331.84 1361.02 1326.33 1356.53L1318.78 1350.2C1312.86 1345.1 1301.63 1342.65 1292.86 1343.06C1282.65 1343.47 1269.18 1340.2 1262.65 1336.12C1250 1327.96 1246.73 1307.55 1246.73 1307.35C1245.1 1300.61 1240.2 1298.78 1235.71 1298.78C1227.55 1298.57 1221.22 1301.02 1214.69 1302.86C1184.9 1311.84 1155.31 1321.02 1125.51 1330.41L1082.86 1343.67C1061.84 1350.2 1040.82 1356.73 1020 1363.67C1014.29 1365.51 1008.78 1368.37 1002.86 1371.43C1000.41 1372.65 997.959 1373.88 995.51 1375.1C993.061 1376.33 990.408 1377.76 987.959 1379.18C982.449 1382.24 976.531 1385.51 970 1387.35C948.776 1393.67 930.204 1384.49 921.429 1363.27C915.714 1349.59 920.816 1322.45 923.878 1314.49C943.061 1264.69 1005.51 1170.82 1005.51 1170.2C1004.49 1169.8 936.327 1197.14 925.102 1205.71C894.286 1229.18 822.041 1284.69 821.02 1290C816.327 1314.69 801.02 1333.27 777.551 1342.45C760.612 1348.98 750.408 1362.45 740.408 1375.51C740.408 1375.51 559.388 1624.9 547.143 1638.37C543.469 1642.45 509.592 1677.96 500.612 1694.49C498.571 1698.57 490.816 1714.9 488.776 1718.98C487.143 1722.24 483.469 1731.02 469.592 1730.41C455.714 1729.8 455.306 1710.41 454.694 1702.04C453.265 1681.43 457.755 1661.22 468.571 1640C469.592 1637.96 481.837 1619.39 477.347 1604.49C473.265 1591.43 469.388 1571.22 475.51 1561.02C485.102 1544.9 502.041 1544.29 524.694 1540.61C540.408 1537.96 551.837 1530.2 562.857 1514.08C586.122 1480.2 673.674 1355.92 693.469 1327.14C698.776 1319.59 702.857 1309.8 704.694 1300.2C710.408 1271.22 727.959 1251.02 758.571 1238.57C765.102 1235.92 886.939 1134.08 886.939 1121.02C886.939 1111.63 873.674 1106.53 863.469 1103.67C862.041 1103.27 785.51 1083.47 750.612 1067.55C731.633 1058.98 717.347 1051.43 700.408 1039.18C677.347 1022.24 631.225 1030.41 624.49 1031.43C591.837 1036.12 567.551 1050.82 540 1069.39C535.102 1072.86 510 1081.84 497.347 1074.69C472.653 1060.61 418.367 1035.31 398.367 1004.9C389.184 990.816 390.408 967.959 396.939 942.653C417.959 883.878 448.98 857.551 506.327 841.633C547.143 827.551 629.388 824.49 668.98 821.429C671.633 820.612 759.388 818.571 821.02 786.939C862.041 765.918 983.878 684.898 1159.18 690.408C1230 692.653 1363.88 761.837 1415.51 763.878C1468.16 766.122 1494.49 760.204 1524.9 728.776C1533.47 719.796 1570 641.02 1535.51 597.959C1522.65 582.041 1509.39 567.755 1494.08 554.694C1473.47 537.143 1452.04 520.408 1433.47 500.612C1392.45 457.143 1379.8 397.755 1399.18 351.429C1411.63 318.98 1437.76 304.898 1475.51 312.245C1502.04 317.347 1521.43 341.225 1540.41 353.878C1551.02 361.02 1568.78 365.102 1580.41 367.959C1595.1 371.429 1606.12 382.653 1605.51 390.204C1604.9 397.755 1585.51 404.286 1566.94 402.857C1544.9 401.429 1507.14 401.225 1484.49 408.776C1469.39 414.286 1462.65 431.02 1467.14 447.551C1470.82 461.02 1499.59 485.102 1510.41 494.082C1532.04 511.837 1555.1 527.959 1573.06 550.204C1593.27 575.51 1603.88 604.286 1607.14 636.122C1612.04 684.898 1599.18 728.776 1574.29 770.408Z" fill="#fff"/></g></svg>'; @@ -408,7 +408,13 @@ export function nostrLoginFeature(ctx) { if (!p) return null; const e = ui.amberPaste || (ui.amberPaste = { text: '' }); return h('div', { class: 'card col amber-wait', style: 'gap:8px' }, - h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small' }, t('nlAmberWait'))), + // a request waiting for a tap (see amberOpen): the Open button is the + // way forward, not the spinner + p.needsTap + ? h('div', { class: 'col', style: 'gap:6px' }, + h('div', { class: 'small' }, t('nlAmberTap')), + h('button', { class: 'btn-primary btn-block amber-open', type: 'button', onClick: () => amberOpen() }, t('nlAmberOpen'))) + : h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small' }, t('nlAmberWait'))), h('div', { class: 'small muted' }, t('nlAmberPasteHint')), h('div', { class: 'row gap6' }, h('input', { type: 'text', class: 'grow amber-paste', placeholder: t('nlAmberPastePh'), value: e.text, autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', diff --git a/src/features/nwc.js b/src/features/nwc.js index ec79081..a2730f5 100644 --- a/src/features/nwc.js +++ b/src/features/nwc.js @@ -30,7 +30,7 @@ import { t } from '../i18n.js'; import { dlog } from '../debug.js'; import { qrSvg } from '../qr.js'; import { getNetwork } from '../api.js'; -import { loadBg, saveBg, clearBg } from '../nwc-bg.js'; +import { loadBg, saveBg, clearBg, readBgLog } from '../nwc-bg.js'; import { encodeNoffer } from '../noffer.js'; import { maybeBolt11 } from '../ark/lightning.js'; import { withRequestLock } from '../nwc-lock.js'; @@ -56,7 +56,7 @@ const nowSec = () => Math.floor(Date.now() / 1000); const errRes = (code, message) => ({ error: { code, message } }); export function nwcFeature(ctx) { - const { h, ui, render, wallet, hook, fmtAmount, unitLabel, copyBtn, toast } = ctx; + const { h, ui, render, wallet, hook, fmtAmount, unitLabel, copyBtn, copy, toast } = ctx; // Relay transport, injectable so the protocol can be driven in tests // without a live relay. const { @@ -478,11 +478,21 @@ export function nwcFeature(ctx) { try { res = await hook('arkPayInvoice', invoice, { maxAmountSat: c.maxSat }); } catch (e) { - // The ASP already holds a payment for this invoice: another device - // of this wallet took the same request first. Its outcome is ours — - // wait for it rather than report a failure over a zap that is - // paying. The payer records the spend; this side only relays. - if (!/already in progress/i.test(e.message || '')) throw e; + // A payment for this invoice already exists: ours, begun on an + // earlier request (the worker started it while closed, say), or + // another device's — the ASP refuses a second HTLC for one invoice. + // Its outcome is the answer, never an error whose text says "paid": + // a client once read "already paid or is being paid" as paid, hours + // before the money moved. The payer records the spend; this side + // only relays. + if (!/already in progress|already paid/i.test(e.message || '')) throw e; + const mine = await hook('arkLnLookup', { paymentHash: dec.paymentHash }).catch(() => null); + if (mine && mine.type === 'outgoing' && mine.state === 'settled' && mine.preimage) { + return { sibling: true, result: { preimage: mine.preimage, fees_paid: 0 } }; + } + if (mine && mine.type === 'outgoing' && mine.state === 'pending') { + return errRes('OTHER', 'a payment for this invoice is still in progress; ask again in a moment'); + } const out = await hook('arkLnOutcome', dec.paymentHash, 60000); if (!out || out.status !== 'success') throw e; return { sibling: true, result: { preimage: out.preimage, fees_paid: 0 } }; @@ -822,6 +832,25 @@ export function nwcFeature(ctx) { // wrong keys — background wake-ups silently die the first time a // connection is recreated. Debounced; the server replaces by endpoint. let regTimer = null; + // The browser's subscription, made again when it's gone: iOS drops it after + // three pushes that showed no notification (and a key rotation strands an + // old one), and nothing else re-arms a wallet whose `background` is still on. + async function currentSub() { + const reg = await navigator.serviceWorker.ready; + const { publicKey } = await (await fetch(`${NOTIFIER}/vapid`)).json(); + const want = b64ToBytes(publicKey); + let sub = await reg.pushManager.getSubscription(); + if (sub) { + let have = []; + try { have = new Uint8Array(sub.options.applicationServerKey || []); } catch {} + if (have.length === want.length && have.every((b, i) => b === want[i])) return sub.toJSON(); + try { await sub.unsubscribe(); } catch {} + } + if (typeof Notification === 'undefined' || Notification.permission !== 'granted') return null; + sub = await reg.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: want }); + dlog('nwc: push subscription was gone, made a new one'); + return sub.toJSON(); + } function refreshRegistration() { if (!load().background) return; if (typeof navigator === 'undefined' || !('serviceWorker' in navigator)) return; @@ -831,8 +860,7 @@ export function nwcFeature(ctx) { const pks = watchPks(); if (!pks.length) return; const up2 = upEndpoint(); - const sub = up2 ? { endpoint: up2, unifiedpush: true } - : await (await navigator.serviceWorker.ready).pushManager.getSubscription().then((x) => x && x.toJSON()); + const sub = up2 ? { endpoint: up2, unifiedpush: true } : await currentSub(); if (!sub) return; await fetch(`${NOTIFIER}/register`, { method: 'POST', headers: { 'content-type': 'application/json' }, @@ -949,7 +977,7 @@ export function nwcFeature(ctx) { if (typeof window !== 'undefined') { window.addEventListener('online', () => listen()); document.addEventListener('visibilitychange', () => { - if (document.visibilityState === 'visible' && conns().length) listen(); + if (document.visibilityState === 'visible' && conns().length) { listen(); refreshRegistration(); } }); } } @@ -1075,7 +1103,19 @@ export function nwcFeature(ctx) { h('button', { class: 'btn-sm', onClick: () => { const s = load(); s.paySentNotify = !on; save(s); writeBg(); render(); } }, on ? t('nwcOn') : t('nwcOff'))), - h('div', { class: 'small faint' }, t('notifPaySentHint')))]; + h('div', { class: 'small faint' }, t('notifPaySentHint'))), + // the worker's diary, for the report that says where a closed wallet + // got to (a phone stops it without a trace) + h('div', { class: 'card col', style: 'gap:10px' }, + h('div', { class: 'row between' }, + h('span', { class: 'small' }, t('nwcWorkerLog')), + h('button', { class: 'btn-sm', onClick: async () => { + const lines = await readBgLog(); + if (!lines.length) { toast(t('nwcWorkerLogEmpty')); return; } + await copy(lines.join('\n')); + toast(t('copied')); + } }, t('copy'))), + h('div', { class: 'small faint' }, t('nwcWorkerLogHint')))]; }, }; } |
