diff options
| -rw-r--r-- | src/ark/manager.js | 31 | ||||
| -rw-r--r-- | src/features/ark.js | 171 | ||||
| -rw-r--r-- | src/i18n.js | 12 | ||||
| -rw-r--r-- | tools/ark-htlc-orphan.test.js | 33 | ||||
| -rw-r--r-- | tools/ark-offline-init.test.js | 22 | ||||
| -rw-r--r-- | tools/ark/cooperative-exit-ui-test.js | 14 | ||||
| -rw-r--r-- | tools/ark/custody-ui-test.js | 45 |
7 files changed, 225 insertions, 103 deletions
diff --git a/src/ark/manager.js b/src/ark/manager.js index 79fdcd0..33bac55 100644 --- a/src/ark/manager.js +++ b/src/ark/manager.js @@ -208,8 +208,12 @@ export function renewPolicy(tier, network) { } export class ArkManager { - constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint, honorsExpired = false }) { + constructor({ account, storage, arkUrl, esploraUrl, network = 'regtest', onUpdate, lnQuoteUrl, statusHint, honorsExpired = false, infoHint = null }) { this.account = account; // HDKey node; ark keys derived beneath it + // The server's last published info, kept by the app: lets the wallet open + // when the server can't be reached (see init) + this.infoHint = infoHint || null; + this.offline = false; // the server cosigns spends of a coin past its timelock (coinos): such a // coin stays money here — spendable, receivable — just not exitable this.honorsExpired = !!honorsExpired; @@ -275,7 +279,19 @@ export class ArkManager { seen.add(m.vtxoId); return true; }); - this.info = await getArkInfo(this.arkUrl); + try { + this.info = await getArkInfo(this.arkUrl); + this.offline = false; + } catch (e) { + // The server is unreachable. With its last published info in hand the + // wallet still opens on its own records: coins read, a unilateral exit + // can start (that needs the chain, not the server), and anything that + // does need the server fails when it asks. Without that info there is + // no server key to check anything against — then it really is closed. + if (!this.infoHint) throw e; + this.info = this.infoHint; + this.offline = true; + } const hs = await handshake(this.arkUrl).catch(() => null); this.psa = hs?.psa; this.serverPub = hex.decode(this.info.serverPubkey); @@ -825,8 +841,13 @@ export class ArkManager { v.state = owner.step === 'done' || owner.step === 'failed' ? 'spent' : 'pending'; changed = true; } + // An HTLC coin whose payment no action names any more (done ln-pays are + // pruned after a while) is an orphan too: five 22-sat ones sat 'pending' + // in a wallet for days, counted as money on its way. The server's answer + // settles it — spent is spent; one still open stays pending, since an + // HTLC coin is never this wallet's to spend (see below). const candidates = this.state.vtxos.filter((v) => v.state === 'spendable' - || (v.state === 'pending' && !held.has(v.id) && v.bytes && this._policyType(v) === 'pubkey')); + || (v.state === 'pending' && !held.has(v.id) && v.bytes)); const was = candidates.map((v) => v.state); // what each was when this pass began // Each status query signs a challenge (schnorr) and may decode the vtxo — // real secp256k1 work. Building them all in one synchronous map was a @@ -851,8 +872,8 @@ export class ArkManager { // an orphan the server still counts is simply spendable again; one it // holds as spent is gone, and the pay that took it was recorded (or // will merge in) elsewhere — no row of its own - if (states[i] === VTXO_STATE_SPENDABLE) { v.state = 'spendable'; changed = true; } - else if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; } + if (states[i] === VTXO_STATE_SPENT) { v.state = 'spent'; changed = true; } + else if (states[i] === VTXO_STATE_SPENDABLE && this._policyType(v) === 'pubkey') { v.state = 'spendable'; changed = true; } return; } if (states[i] !== VTXO_STATE_SPENT) return; diff --git a/src/features/ark.js b/src/features/ark.js index 4b15099..94dfc09 100644 --- a/src/features/ark.js +++ b/src/features/ark.js @@ -38,7 +38,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()); } @@ -467,6 +467,10 @@ export function arkFeature(ctx) { // 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. @@ -475,7 +479,12 @@ export function arkFeature(ctx) { 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) localStorage.setItem(ARK_INFO_KEY + url, JSON.stringify({ info, tip: tip || 0, at: Date.now() })); } catch {} + 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) { @@ -485,6 +494,7 @@ export function arkFeature(ctx) { } 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() { @@ -505,6 +515,7 @@ export function arkFeature(ctx) { 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 @@ -654,6 +665,9 @@ export function arkFeature(ctx) { 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 @@ -670,9 +684,10 @@ export function arkFeature(ctx) { const inited = mgr.init().then(() => { if (gen !== arkInitGen) return; arkInited = mgr; // readable now; `ark` (and the mailbox) wait for the snapshot - rememberArkInfo(cfg.ark, mgr.info, mgr._tipH); + 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. @@ -2445,6 +2460,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; @@ -2455,6 +2476,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 @@ -2467,6 +2502,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'), @@ -2507,22 +2543,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(exitable.length)), - row(t('arkExitConfirmAmount'), fmtSats(exitable.reduce((n, v) => n + v.amountSat, 0)) + ' 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 || !exitable.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 @@ -2597,37 +2634,19 @@ 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'))))))))), - 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' }, 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, - !spend.length ? null : 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'))), - // The ticked coins are what leaves: a subset goes on-chain as exactly - // those coins (no fresh coin split off the whole balance first), all - // of them — or nothing ticked — means the whole balance as before. - (() => { - const subset = selCoins.length > 0 && selCoins.length < spend.length; - const coopSat = subset ? selCoins.reduce((n, v) => n + v.amountSat, 0) : spendableSat; - return 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')), - subset ? h('p', { class: 'small muted', style: 'margin:0' }, selCoins.length === 1 ? t('arkCoopSelectedOne') : t('arkCoopSelected', { n: selCoins.length })) : null, - h('button', { class: 'btn-primary btn-block ark-coop-go', disabled: !!ui.arkBusy || !coopSat || wallet.watchOnly, onClick: () => { + 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; @@ -2635,13 +2654,11 @@ export function arkFeature(ctx) { ctx.showSend({ fresh: true }); ui.arkOffboardSend = { address, amount: String(coopSat), fromCoins: true, vtxoIds }; render(); - } }, t('arkOffboardBtn', { n: fmtAmount(coopSat) + ' ' + unitLabel() }))); - })(), - h('div', { class: 'card col', style: 'gap:8px' }, - h('h4', { style: 'margin:0' }, t('arkCoinsExitTitle')), - h('p', { class: 'small muted', style: 'margin:0' }, - exitable.length ? t('arkCoinsExitDesc', { fee: fmtSats(exitFee), after: fmtSats(afterFee) }) : t('arkExitNoneExitable')), - h('button', { class: 'btn-ghost btn-block', disabled: !!ui.arkBusy || !exitable.length || !mgr, onClick: () => { ui.arkExitConfirm = true; render(); } }, t('arkCoinsExitBtn'))), + } }, 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, + embedded ? custodyCard() : null, embedded ? null : h('button', { class: 'btn-ghost btn-block', onClick: back }, t('back'))); } @@ -2673,18 +2690,19 @@ export function arkFeature(ctx) { { 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('h3', { style: 'margin:0' }, t('arkCustodyTitle')), + h('h4', { style: 'margin:0' }, t('arkCustodyTitle')), h('p', { class: 'small muted', style: 'margin:0' }, t('arkCustodyDesc', { days: lifeDays })), - h('div', { class: 'col', style: 'gap:8px' }, ...tiers.map((x) => h('label', { - class: 'row gap6 ark-custody-opt' + (x.id === cur ? ' active' : ''), style: 'align-items:flex-start;cursor:pointer', - 'data-tier': x.id, - }, - h('input', { type: 'radio', name: 'arkCustody', value: x.id, checked: x.id === cur, disabled: !honors, style: 'flex:0 0 auto;margin:3px 0 0', - onChange: () => applyCustody(x.id) }), - h('div', { class: 'col', style: 'gap:2px;flex:1' }, - h('div', { class: 'row between gap6', style: 'align-items:baseline' }, h('span', { style: 'white-space:nowrap' }, x.label), h('span', { class: 'small' + (x.id === 'custodial' ? ' faint' : ''), style: 'text-align:right' }, x.cost)), - h('div', { class: 'small muted' }, x.desc))))), + 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'))); } @@ -2905,9 +2923,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 = exitableCoins(mgr.state, mgr._tipH || 0); + 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; @@ -2922,16 +2940,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 = exitableCoins(mgr.state, mgr._tipH || 0); + // 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) })); } @@ -3201,6 +3230,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', @@ -3423,13 +3453,19 @@ export function arkFeature(ctx) { 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) return; + if (netSat(renewSet) < 330 || !worthIt(renewSet)) return; await mgr.refresh(renewSet.map((v) => v.id)); render(); return; @@ -3464,6 +3500,7 @@ export function arkFeature(ctx) { 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 @@ -3766,7 +3803,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' }, @@ -3804,7 +3841,7 @@ export function arkFeature(ctx) { // 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 h('div', { class: 'col', style: 'gap:16px' }, custodyCard(), 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() { diff --git a/src/i18n.js b/src/i18n.js index 16b93d4..edf9102 100644 --- a/src/i18n.js +++ b/src/i18n.js @@ -782,12 +782,12 @@ const STR = { arkCoopSelectedOne: 'Only the coin ticked above will move.', arkCoopSelectedAmt: '{n} selected coins · {amount}', arkCoopSelectedAmtOne: '1 selected coin · {amount}', - arkCustodyTitle: 'Custody', - arkCustodyDesc: 'Each coin expires about {days} days after it was made. Until then you can bring it on-chain yourself, without Coinos. Renewing a coin before it expires keeps that right for another {days} days and costs a small fee. Coinos keeps honoring expired coins, so renewing is a choice:', + arkCustodyTitle: 'Custody strategy', + arkCustodyDesc: 'Each coin expires about {days} days after it was made. Until then you can bring it on-chain yourself, without Coinos; after that, Coinos keeps honoring it. Renewing before expiry keeps your own exit, for a fee, so it is a choice:', arkCustodyCustodial: 'Allow coins to expire', arkCustodyCustodialDesc: 'Nothing renews and no renewal fees are paid. A coin keeps its own exit until it expires. After that, paying still works, but bringing it on-chain needs Coinos’s cooperation.', arkCustodySelf: 'Minimize renewal cost', - arkCustodySelfDesc: 'Coins renew in the last hours before they expire, when renewal is cheapest, so you can always exit on your own without Coinos. Roughly once every {days} days per coin.', + arkCustodySelfDesc: 'Coins renew in the last hours before they expire, when renewal is cheapest, so you can always exit on your own without Coinos. Roughly once every {days} days per coin. Coins too small to be worth the fee are left alone.', arkCustodyExit: 'Minimize exit cost', arkCustodyExitDesc: 'Every transfer adds a hop to a coin’s history, and a unilateral exit pays one on-chain transaction per hop. This renews a coin before it expires, and also as soon as its history is {hops} hops deep, so bringing any coin on-chain stays close to a fresh coin’s price. Only for coins worth it: never more than a tenth of a coin on its renewal.', arkCustodyCostNone: 'no fees', @@ -820,8 +820,10 @@ const STR = { arkRenewStageRetry: 'The last check with the server didn’t go through; the wallet keeps trying.', arkRenewingHistory: 'Renewing', arkRenewingOpen: 'See the coins', - arkCoinsExitTitle: 'Unilateral exit', - arkCoinsCoopTitle: 'Co-operative exit', + arkCoinsExitTitle: 'Exit', + arkCoinsCoopTitle: 'Withdraw', + arkCoinsWithdrawBtn: 'Withdraw {amount}', + arkCoinsExitBtnAmt: 'Exit {amount}', arkOffboardBadAddress: 'Enter a valid on-chain address for this network.', arkCoinsExitBtn: 'Exit now', arkExitConfirmTitle: 'Start a unilateral exit?', diff --git a/tools/ark-htlc-orphan.test.js b/tools/ark-htlc-orphan.test.js new file mode 100644 index 0000000..cc127be --- /dev/null +++ b/tools/ark-htlc-orphan.test.js @@ -0,0 +1,33 @@ +// bun test tools/ark-htlc-orphan.test.js — an HTLC coin whose payment's +// action has been pruned is an orphan the server settles: spent means spent +// (it stopped counting as pending money), still-open stays pending, and a +// coin a live payment holds is never asked about. +import { test, expect, mock } from 'bun:test'; +import * as proto from '../src/ark/proto.js'; +const asked = []; +mock.module('../src/ark/proto.js', () => ({ ...proto, getVtxoStatus: async (url, raw) => { asked.push(raw[0]); return raw[0] === 1 ? proto.VTXO_STATE_SPENT : proto.VTXO_STATE_SPENDABLE; } })); +const { ArkManager } = await import('../src/ark/manager.js'); +test('orphan HTLC coins are settled by the server\'s answer', async () => { + const m = Object.create(ArkManager.prototype); + m.state = { + vtxos: [ + { id: 'gone', state: 'pending', amountSat: 22, bytes: 'x', policy: 'serverHtlcSend', tag: 1 }, // payment done long ago, action pruned: server says spent + { id: 'open', state: 'pending', amountSat: 22, bytes: 'x', policy: 'serverHtlcSend', tag: 2 }, // orphan the server still holds open + { id: 'held', state: 'pending', amountSat: 22, bytes: 'x', policy: 'serverHtlcSend', tag: 3 }, // a live payment's: not asked about + { id: 'coin', state: 'pending', amountSat: 500, bytes: 'x', policy: 'pubkey', tag: 2 }, // a plain orphan the server counts: spendable again + ], + actions: [{ type: 'ln-pay', step: 'initiated', parts: [{ inputId: 'in1' }], htlcVtxoIds: ['held'] }], + scheduled: [], + }; + m.arkUrl = 'x'; + m._decoded = (v) => ({ point: { raw: Uint8Array.of(v.tag) }, policy: { type: v.policy } }); + m._keyForVtxo = () => ({ privkey: new Uint8Array(32) }); + m._save = () => {}; m._movement = () => {}; m._remoteBusy = () => new Set(); + await m.reconcile(); + const st = Object.fromEntries(m.state.vtxos.map((v) => [v.id, v.state])); + expect(st.gone).toBe('spent'); + expect(st.open).toBe('pending'); + expect(st.held).toBe('pending'); + expect(st.coin).toBe('spendable'); + expect(asked.sort()).toEqual([1, 2, 2]); +}); diff --git a/tools/ark-offline-init.test.js b/tools/ark-offline-init.test.js new file mode 100644 index 0000000..922682d --- /dev/null +++ b/tools/ark-offline-init.test.js @@ -0,0 +1,22 @@ +// bun test tools/ark-offline-init.test.js — the Ark server gone: with the +// server's last published info in hand the manager still opens (coins read, +// exits can start); without it, init fails as before. +import { test, expect, mock } from 'bun:test'; +import * as proto from '../src/ark/proto.js'; +mock.module('../src/ark/proto.js', () => ({ ...proto, + getArkInfo: async () => { throw new Error('fetch failed'); }, + handshake: async () => { throw new Error('fetch failed'); }, +})); +const { ArkManager } = await import('../src/ark/manager.js'); +const serverPubkey = '02' + 'ab'.repeat(32); +const hint = { serverPubkey, vtxoExpiryDelta: 8640, vtxoExitDelta: 144, refreshFees: { baseFeeSat: 300, ppmExpiryTable: [] }, offboardFees: { baseFeeSat: 0, fixedAdditionalVb: 0, ppmExpiryTable: [] }, lnSendFees: {}, lnReceiveFees: {} }; +const mk = (infoHint) => new ArkManager({ account: null, storage: { load: () => ({ v: 1, serverPubkey, vtxos: [], actions: [], movements: [], scheduled: [] }), save() {} }, arkUrl: 'http://x', esploraUrl: 'http://y', network: 'mainnet', infoHint }); +test('with cached info the manager opens offline', async () => { + const m = await mk(hint).init(); + expect(m.offline).toBe(true); + expect(m.info.refreshFees.baseFeeSat).toBe(300); + expect(Buffer.from(m.serverPub).toString('hex')).toBe(serverPubkey); +}); +test('without cached info the old failure stands', async () => { + await expect(mk(null).init()).rejects.toThrow('fetch failed'); +}); diff --git a/tools/ark/cooperative-exit-ui-test.js b/tools/ark/cooperative-exit-ui-test.js index 506bca6..03e65d5 100644 --- a/tools/ark/cooperative-exit-ui-test.js +++ b/tools/ark/cooperative-exit-ui-test.js @@ -66,10 +66,9 @@ try { }); await page.waitForSelector('.coin-table'); }; - const coopButton = () => page.evaluate(() => [...document.querySelectorAll('.card')] - .find((c) => c.querySelector('h4')?.textContent === 'Co-operative exit').querySelector('button').click()); + const coopButton = () => page.evaluate(() => document.querySelector('.ark-coop-go').click()); const send = () => page.evaluate(() => [...document.querySelectorAll('.card')] - .find((c) => c.querySelector('h3')?.textContent === 'Co-operative exit').querySelector('.btn-primary').click()); + .find((c) => c.querySelector('h3')?.textContent === 'Withdraw').querySelector('.btn-primary').click()); const edit = (selector, value) => page.$eval(selector, (e, value) => { e.value = value; e.dispatchEvent(new Event('input', { bubbles: true })); }, value); // The balance card's gear is the way in: Spending's settings lead with // its coins and carry what a unilateral exit costs; the home screen no @@ -114,13 +113,16 @@ try { await page.evaluate(() => { window.forceArkReady = false; coopApp.wallet.saveFeatureState('arkDepth', null); coopApp.ui.screen = 'wallet'; coopApp.render(); }); await manage(); - assert.deepEqual(await page.$$eval('.card h4', (es) => es.map((e) => e.textContent)), ['Renewal', 'Co-operative exit', 'Unilateral exit']); + // the three actions sit right under the table, named for the ticked total; no explainer cards + assert.deepEqual(await page.$$eval('.ark-coin-actions button', (es) => es.map((e) => e.textContent)), ['Renew now', 'Withdraw 20,000 sats', 'Exit 20,000 sats']); + assert.deepEqual(await page.$$eval('.card h4', (es) => es.map((e) => e.textContent)), []); await coopButton(); await page.waitForSelector('input.mono-input'); const savings = await page.evaluate(() => coopApp.wallet.freshReceive().address); assert.equal(await page.$eval('input.mono-input', (e) => e.value), savings); assert.equal(await page.$eval('input[type="number"]', (e) => e.value), '20000'); assert.equal(await page.$eval('.card .btn-primary', (e) => e.textContent), 'Send'); + assert.match(await page.evaluate(() => document.body.innerText), /one transaction into Savings, ready after a single confirmation/, 'the withdraw explainer is on the form'); assert.deepEqual(await page.evaluate(() => coopCalls), [], 'opening the form never starts an exit'); await page.evaluate(() => [...document.querySelectorAll('.card button')].find((b) => b.textContent.includes('Back')).click()); await page.waitForSelector('.coin-table'); @@ -165,7 +167,7 @@ try { // ticking a subset on Manage: exactly those coins go, no split, the amount is theirs and not a field await manage(); await page.evaluate(() => { coopApp.ui.arkCoinsSel = new Set(['coin-b']); coopApp.render(); }); - assert.match(await page.evaluate(() => [...document.querySelectorAll('.card')].find((c) => c.querySelector('h4')?.textContent === 'Co-operative exit').innerText), /Only the coin ticked above will move[\s\S]*Move 8,000 sats to Savings/); + assert.deepEqual(await page.$$eval('.ark-coin-actions button', (es) => es.map((e) => e.textContent)), ['Renew 1 selected for free', 'Withdraw 8,000 sats', 'Exit 8,000 sats'], 'the buttons name the ticked total'); await coopButton(); await page.waitForSelector('.ark-coop-chosen'); assert.match(await page.$eval('.ark-coop-chosen', (e) => e.textContent), /1 selected coin · 8,000 sats/); @@ -180,7 +182,7 @@ try { assert.equal(await page.evaluate(() => coopApp.ui.arkOffboardSend), null); await manage(); await page.evaluate(() => { coopManager.state.vtxos.forEach((v) => v.state = 'pending'); coopManager.state.actions = [{ type: 'refresh', step: 'submitted', inputIds: ['coin-a', 'coin-b'], inAmountSat: 20000 }]; coopApp.render(); }); - assert(await page.evaluate(() => [...document.querySelectorAll('.card')].find((c) => c.querySelector('h4')?.textContent === 'Co-operative exit').querySelector('button').disabled)); + assert(await page.evaluate(() => document.querySelector('.ark-coop-go').disabled)); await page.evaluate(() => { const { ui, render } = coopApp; ui.arkCoinsPage = null; ui.tab = 'send'; diff --git a/tools/ark/custody-ui-test.js b/tools/ark/custody-ui-test.js index 7ebc2ea..9c238f5 100644 --- a/tools/ark/custody-ui-test.js +++ b/tools/ark/custody-ui-test.js @@ -77,39 +77,43 @@ try { let tx = await text(); assert.match(tx, /Custody/); - assert.match(tx, /Allow coins to expire[\s\S]*no fees/); - assert.match(tx, /keeps its own exit until it expires/); - assert.doesNotMatch(tx, /timelock|Spending coin carries|old Coinos/, 'no jargon on the card'); - assert.match(tx, /Minimize renewal cost[\s\S]*300 sats per renewal/); - assert.match(tx, /Minimize exit cost[\s\S]*300 sats near expiry, 0\.2% \+ 300 sats when early/); - assert.match(tx, /4 hops deep/); - const checked = await page.$$eval('.ark-custody input[type=radio]', (els) => els.filter((e) => e.checked).map((e) => e.value)); - assert.deepEqual(checked, ['custodial'], 'coinos holds the coins by default'); + const opts = await page.$$eval('.ark-custody option', (es) => es.map((e) => e.value + '=' + e.textContent)); + assert.deepEqual(opts, ['custodial=Allow coins to expire', 'self=Minimize renewal cost', 'exit=Minimize exit cost']); + assert.equal(await page.$eval('.ark-custody-cost', (e) => e.textContent), 'no fees'); + assert.equal(await page.$eval('#ark-custody-select', (e) => e.value), 'custodial', 'coins expire by default'); assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'custodial'); + assert.match(await page.$eval('.ark-custody-desc', (e) => e.textContent), /keeps its own exit until it expires/); + assert.doesNotMatch(tx, /Coins renew in the last hours|Every transfer adds a hop/, 'only the chosen strategy is described'); + assert.doesNotMatch(tx, /timelock|Spending coin carries|old Coinos/, 'no jargon on the card'); + const order = await page.$$eval('.card h4, .card h3', (es) => es.map((e) => e.textContent).filter((x) => /Spending coins|Custody strategy|Renewal/.test(x))); + assert.deepEqual(order, ['Spending coins', 'Custody strategy'], 'coins first, then the strategy; no explainer cards'); assert.match(tx, /held by Coinos/, 'the coin past its timelock is held, not "expired"'); assert.doesNotMatch(tx, /5,000 sats\s+expired/, 'the row never says "expired"'); - assert.match(tx, /With “Allow coins to expire”, nothing renews on its own/); + assert.doesNotMatch(tx, /nothing renews on its own/, 'the renewal explainer is not on the page…'); + const renewSheet = async () => { await page.click('.ark-renew-ask'); await sleep(200); const t = await text(); await page.evaluate(() => [...document.querySelectorAll('.ark-renew-confirm button')].find((b) => b.textContent === 'Cancel').click()); await sleep(200); return t; }; + assert.match(await renewSheet(), /With “Allow coins to expire”, nothing renews on its own[\s\S]*more than 15 days left/, '…it is on the Renew confirmation, with the fee schedule'); if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT, fullPage: true }); - console.log('✓ the custody card: three tiers with their prices, coinos holding by default, a past-timelock coin shown as held'); + console.log('✓ the custody card: a drop-down of three strategies with their prices, coins expire by default, one description, a past-timelock coin shown as held'); // the unilateral exit only counts the coin still inside its timelock - assert.match(tx, /Exit now/); - const exitBtn = await page.$$eval('button', (bs) => bs.filter((b) => b.textContent === 'Exit now').map((b) => b.disabled)); - assert.deepEqual(exitBtn, [false]); - await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => b.textContent === 'Exit now').click()); await sleep(200); + assert.equal(await page.$eval('.ark-exit-ask', (b) => b.textContent), 'Exit 20,800 sats', 'the exit button names the ticked coins still inside their timelock'); + assert.equal(await page.$eval('.ark-exit-ask', (b) => b.disabled), false); + await page.click('.ark-exit-ask'); await sleep(200); tx = await text(); assert.match(tx, /Coins\s*2/); assert.match(tx, /Amount\s*20,800 sats/); + assert.match(tx, /If the server vanished today/, 'the exit explainer is on the confirmation'); await page.evaluate(() => [...document.querySelectorAll('button')].find((b) => b.textContent === 'Cancel').click()); await sleep(200); console.log('✓ a unilateral exit counts only the coin still inside its timelock'); // opt into keeping the exit: persisted, the page reprices, renewal starts covering - await page.click('.ark-custody-opt[data-tier=self] input'); await sleep(400); + await page.select('#ark-custody-select', 'self'); await sleep(400); assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'self'); assert.equal(await page.evaluate(() => coopApp.wallet.loadFeatureState('arkCustody')), 'self', 'saved with the wallet'); tx = await text(); assert.match(tx, /Custody choice saved/); - assert.doesNotMatch(tx, /nothing renews on its own/); - assert.match(tx, /renews coins automatically once they are close to expiring/); + assert.match(await renewSheet(), /renews coins automatically once they are close to expiring/); + assert.match(await page.$eval('.ark-custody-desc', (e) => e.textContent), /Coins renew in the last hours/); + assert.equal(await page.$eval('.ark-custody-cost', (e) => e.textContent), '300 sats per renewal'); const calls = await page.evaluate(() => coopFeature.autoRefreshCalls); assert.deepEqual(calls[0], ['ensure', 6, 8, 1], 'backstop orders registered at once (regtest margin 6)'); assert.deepEqual(calls[1], ['refresh', ['coin-1', 'coin-2']], 'the coin past its timelock is renewed now with the small change; the deep healthy one is left alone'); @@ -117,14 +121,15 @@ try { // the exit tier also flattens the deep coin — but not the deep 800-sat one on its own merits await page.evaluate(() => { coopFeature.autoRefreshCalls.length = 0; }); - await page.click('.ark-custody-opt[data-tier=exit] input'); await sleep(400); + await page.select('#ark-custody-select', 'exit'); await sleep(400); assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'exit'); + assert.equal(await page.$eval('.ark-custody-cost', (e) => e.textContent), '300 sats near expiry, 0.2% + 300 sats when early'); const calls2 = await page.evaluate(() => coopFeature.autoRefreshCalls); assert.deepEqual(calls2[1], ['refresh', ['coin-1', 'coin-0', 'coin-2']], 'expired + deep (worth it) + small change ride one round'); console.log('✓ "Keep my exit cheap" renews the deep coin too, when the fee is under a tenth of it'); - await page.click('.ark-custody-opt[data-tier=custodial] input'); await sleep(300); + await page.select('#ark-custody-select', 'custodial'); await sleep(300); assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'custodial'); - assert.match(await text(), /nothing renews on its own/); + assert.match(await renewSheet(), /nothing renews on its own/); console.log('✓ the other tiers switch the same way, and back'); assert.deepEqual(errors, [], 'no page errors'); console.log('\n✅ custody is a choice, made on the Spending page'); |
