aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/features/gifts.js8
-rw-r--r--src/features/messages.js65
-rw-r--r--src/features/withdraw-links.js195
-rw-r--r--src/i18n.js31
-rw-r--r--tools/lnurl-withdraw-links-test.js166
-rw-r--r--tools/notif-app-zap-test.js109
6 files changed, 569 insertions, 5 deletions
diff --git a/src/features/gifts.js b/src/features/gifts.js
index f23ecc8..c6ccbd9 100644
--- a/src/features/gifts.js
+++ b/src/features/gifts.js
@@ -8,6 +8,7 @@ import { decryptWithCode, npubOf } from '../nostr.js';
import { installGiftWallet, previewGift, giftOutpoints, giftClaimTxs, isRetiredGift, giftMinimum, lockGift, previewLockedGift } from './gifts-wallet.js';
import { t } from '../i18n.js';
import { qrSvg } from '../qr.js';
+import { withdrawLinks } from './withdraw-links.js';
import { fmtBtc, timeAgo, shortAddr } from '../format.js';
import { getEventHash, verifyEvent } from 'nostr-tools/pure';
import { sha256 } from '@noble/hashes/sha256';
@@ -26,6 +27,7 @@ export function giftsFeature(ctx) {
// every call degrades to null in an on-chain-only build.
const hook = ctx.hook || (() => null);
const arkGiftOf = (code) => hook('arkGiftDecode', code);
+ const wl = withdrawLinks(ctx); // prepaid LNURL-withdraw links, the gift link's sibling on Send
// ================================================================ GIFT / CLAIM
// Read a gift link, returning the code (and scrubbing it from the URL so the
@@ -1085,9 +1087,11 @@ export function giftsFeature(ctx) {
return { blob, claimCode, url: `${location.origin}/lg/${blob}` };
},
receiveTakeover() { return claimCelebration(); },
- sendView() { return ui.giftMode ? giftView() : null; },
+ sendView() { return ui.giftMode === 'lnurl' ? wl.view() : ui.giftMode ? giftView() : null; },
sendFormExtras() {
- return h('button', { class: 'linklike small', style: 'align-self:center;margin-top:2px', onClick: () => { ui.giftMode = true; ui.sendError = ''; render(); } }, '🎁 ' + t('giftLink'));
+ return h('div', { class: 'row gap6 wrap', style: 'justify-content:center;column-gap:18px' },
+ h('button', { class: 'linklike small', style: 'margin-top:2px', onClick: () => { ui.giftMode = true; ui.sendError = ''; render(); } }, '🎁 ' + t('giftLink')),
+ wl.entry());
},
balanceLines() {
const locked = wallet.giftLockedValue();
diff --git a/src/features/messages.js b/src/features/messages.js
index 6c4f5f8..4ba4bfb 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -4375,6 +4375,8 @@ export function messagesFeature(ctx) {
if (persist) persistThread(c);
}
const tagOf = (ev, k) => (ev.tags.find((x) => x[0] === k) || [])[1];
+ const APP_KIND = 32267; // a Zapstore app listing (NIP-82): zaps on one are zaps on your app
+ const APP_RELAYS = ['wss://relay.zapstore.dev'];
function receiptSats(ev) {
if (ev.kind === 9737) {
const net = tagOf(ev, 'network');
@@ -4395,6 +4397,16 @@ export function messagesFeature(ctx) {
if (ev.kind === 9737) return String(ev.content || '').slice(0, 200);
try { return String((JSON.parse(tagOf(ev, 'description') || 'null') || {}).content || '').slice(0, 200); } catch { return ''; }
}
+ // The address (kind:pubkey:d) a zap was for, when it wasn't a note: a
+ // stream (30311) or a Zapstore app listing (32267). LNURL servers often
+ // leave the a tag off the receipt (Zapstore's did, 2026-11-07), so the zap
+ // request inside it is asked too.
+ function zapAddrOf(ev) {
+ const a = (e) => ((e && e.tags) || []).find((x) => x[0] === 'a' && x[1]);
+ const own = a(ev);
+ if (own) return own[1];
+ try { const r = a(JSON.parse(tagOf(ev, 'description') || 'null')); return r ? r[1] : null; } catch { return null; }
+ }
function zapperOf(ev) {
if (ev.kind === 9737) {
// Signed by the wallet key; the sender tag names the person behind it.
@@ -18455,9 +18467,11 @@ export function messagesFeature(ctx) {
if (ZAP_KINDS.includes(ev.kind)) {
const actor = zapperOf(ev), sats = receiptSats(ev);
if (!actor || my.includes(actor) || !sats) return null;
- // a zap on a stream names it by address (a 30311), not by an e tag
- const stream = !lastE ? ((ev.tags || []).find((x) => x[0] === 'a' && String(x[1] || '').startsWith(LIVE_KIND + ':')) || [])[1] || null : null;
- return { id: ev.id, what: 'zap', actor, target: lastE, stream, hint, sats, text: zapText(ev), ts: ev.created_at };
+ // a zap on a stream or an app names it by address, not by an e tag
+ const addr = !lastE ? zapAddrOf(ev) : null;
+ const stream = addr && addr.startsWith(LIVE_KIND + ':') ? addr : null;
+ const app = addr && addr.startsWith(APP_KIND + ':') ? addr : null;
+ return { id: ev.id, what: 'zap', actor, target: lastE, stream, ...(app ? { app } : {}), hint, sats, text: zapText(ev), ts: ev.created_at };
}
if (my.includes(ev.pubkey)) return null;
if (ev.kind === 7) {
@@ -18494,6 +18508,12 @@ export function messagesFeature(ctx) {
const old = c.items.find((y) => y.id === x.id);
if (old && !old.emojiUrl) { old.emojiUrl = x.emojiUrl; old.emoji = x.emoji; healed = true; }
}
+ // ...and a zap on an app saved before rows knew one
+ for (const x of items) {
+ if (!x || !x.app || !known.has(x.id)) continue;
+ const old = c.items.find((y) => y.id === x.id);
+ if (old && !old.app) { old.app = x.app; healed = true; }
+ }
const add = items.filter((x) => x && !hiddenPk(x.actor) && !known.has(x.id) && known.add(x.id));
if (!add.length) { if (healed) persistNotifs(); return healed; }
warmNotifFaces(add);
@@ -18611,7 +18631,32 @@ export function messagesFeature(ctx) {
return ref && ref.type === 'pubkey' ? '@' + displayName(ref.pk) : m.slice(6, 18) + '\u2026';
}).replace(/\s+/g, ' ').trim();
}
+ // Zapstore app listings (NIP-82 kind 32267): a zap on one is a zap on your
+ // app. Its name is asked of Zapstore's relay once per session.
+ const appIdOf = (addr) => String(addr || '').split(':').slice(2).join(':');
+ const appNames = new Map(); // app id -> name | null (asking / none)
+ function appName(addr) {
+ const id = appIdOf(addr);
+ if (!id) return null;
+ if (!appNames.has(id)) {
+ appNames.set(id, null);
+ queryOn(APP_RELAYS, { kinds: [APP_KIND], '#d': [id], limit: 5 }, 5000).then((evs) => {
+ const ev = (evs || []).sort((a, b) => b.created_at - a.created_at)[0];
+ const name = ev && tagOf(ev, 'name');
+ if (name) { appNames.set(id, String(name).slice(0, 60)); scheduleRepaint(); }
+ }).catch(() => {});
+ }
+ return appNames.get(id);
+ }
+ const openApp = (addr) => {
+ const url = 'https://zapstore.dev/apps/' + encodeURIComponent(appIdOf(addr));
+ if (ctx.openExternal) ctx.openExternal(url); else window.open(url, '_blank', 'noopener');
+ };
function notifLabel(x) {
+ if (x.what === 'zap' && x.app) {
+ const name = appName(x.app);
+ return name ? t('alertZapApp', { name, sats: fmtSats(x.sats) + ' sats' }) : t('alertZapAppAnon', { sats: fmtSats(x.sats) + ' sats' });
+ }
if (x.what === 'zap') return t('alertZap', { sats: fmtSats(x.sats) + ' sats' });
if (x.what === 'react') {
const code = shortcodeOf(x.emoji);
@@ -18649,6 +18694,20 @@ export function messagesFeature(ctx) {
// a zap on a stream opens the stream; one on your profile (no post
// at all) opens the zapper's — the tap used to do nothing
else if (x.stream) { const [, pk, ...d] = x.stream.split(':'); stopNotifWatch(); openLiveRef({ pk, d: d.join(':') }).catch(() => {}); }
+ else if (x.app) openApp(x.app);
+ // a row saved before rows read the zap request's address: look at
+ // the receipt once, then go where it says
+ else if (x.what === 'zap' && !x.addrChecked) {
+ x.addrChecked = true;
+ queryOn(zapRelays(), { ids: [x.id] }, 4500).catch(() => []).then((evs) => {
+ const addr = evs && evs[0] ? zapAddrOf(evs[0]) : null;
+ if (addr && addr.startsWith(APP_KIND + ':')) x.app = addr;
+ else if (addr && addr.startsWith(LIVE_KIND + ':')) x.stream = addr;
+ persistNotifs();
+ render();
+ open();
+ });
+ }
else { stopNotifWatch(); openProfile(x.actor); }
}
};
diff --git a/src/features/withdraw-links.js b/src/features/withdraw-links.js
new file mode 100644
index 0000000..a63d180
--- /dev/null
+++ b/src/features/withdraw-links.js
@@ -0,0 +1,195 @@
+// Prepaid Lightning withdraw links (LNURL-withdraw): make a link or QR that
+// whoever holds it can pull sats from — a voucher, a faucet, a printed card —
+// even while this wallet is asleep. "Do we have lnurl withdraw links
+// somewhere? can we add them?" → "Prepaid" (Adam, 2026-11-07).
+//
+// The money is paid up front, from Spending over Lightning, to the coinos
+// registrar (coinosv3-server names/withdraw.js), which pays each claim out of
+// it; until claimed it sits there, and the creator can take back whatever is
+// left at any time ("Take back"), which closes the link. Links belong to the
+// wallet's own nostr key, so every device with the seed sees them.
+//
+// It lives on the Send page as a sibling of the gift link: ui.giftMode ===
+// 'lnurl' (giftMode is already a navigation field with its resets).
+import { nip98Header } from '../nip98.js';
+import { encodeLnurl } from '../lnurl.js';
+import { qrSvg } from '../qr.js';
+import { getNetwork } from '../api.js';
+import { t } from '../i18n.js';
+
+const REGISTRAR = 'https://names.coinos.io';
+const NOTE_MAX = 120;
+const net = () => (getNetwork() === 'mutinynet' ? 'mutinynet' : 'mainnet');
+const available = () => ['mainnet', 'mutinynet'].includes(getNetwork());
+
+export function withdrawLinks(ctx) {
+ const { h, ui, render, wallet, toast, copyBtn, goBack, fmtAmount, unitLabel, unitTag, parseAmount, getUnit } = ctx;
+ const hook = ctx.hook || (() => null);
+ const base = () => ctx.withdrawRegistrar || REGISTRAR;
+ // ui.wl: { list: [...]|null, listError, amount, uses, note, busy, error, open: id|null, made: id|null, taking: id|null }
+ const st = () => (ui.wl ||= { list: null, amount: '', uses: '1', note: '' });
+
+ const signer = { signEvent: (e) => wallet.nostrSign(e) };
+ async function call(method, path, payload) {
+ const url = base() + path;
+ const body = payload ? JSON.stringify(payload) : '';
+ const auth = await nip98Header(signer, url, method, body);
+ const r = await fetch(url, { method, headers: { authorization: auth, ...(body ? { 'content-type': 'application/json' } : {}) }, ...(body ? { body } : {}) });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok || j.error) throw new Error(j.error || `registrar refused (${r.status})`);
+ return j;
+ }
+
+ async function load() {
+ const s = st();
+ try {
+ const j = await call('GET', '/withdraw/mine');
+ s.list = (j.links || []).filter((l) => l.net === net());
+ s.listError = '';
+ } catch (e) { s.listError = e.message; s.list ||= []; }
+ render();
+ }
+
+ function open() {
+ ui.wl = null;
+ ui.giftMode = 'lnurl';
+ ui.sendError = '';
+ st();
+ render();
+ load();
+ }
+
+ const lnurlOf = (l) => encodeLnurl(l.url).toUpperCase();
+ const amt = (sat) => fmtAmount(sat) + ' ' + unitLabel();
+
+ async function create() {
+ const s = st();
+ const sat = parseAmount(s.amount, getUnit()) || 0;
+ const uses = Math.floor(Number(s.uses) || 1);
+ s.error = '';
+ if (!(sat >= 1)) { s.error = t('wlAmountInvalid'); render(); return; }
+ if (!(uses >= 1 && uses <= 1000)) { s.error = t('wlUsesInvalid'); render(); return; }
+ if (wallet.watchOnly) { s.error = t('lnWithdrawWatchOnly'); render(); return; }
+ if (!hook('arkReady')) { s.error = t('hatNeedSpending'); render(); return; }
+ const total = sat * uses;
+ if ((hook('arkSpendableSat') || 0) < total + Math.max(10, Math.ceil(total * 0.002))) { s.error = t('wlNoFunds', { amount: amt(total) }); render(); return; }
+ s.busy = true; render();
+ try {
+ const inv = await call('POST', '/withdraw/new', { sat, uses, note: String(s.note || '').trim().slice(0, NOTE_MAX), net: net() });
+ await hook('arkPayInvoice', inv.invoice, { maxAmountSat: inv.totalSat });
+ let link = null;
+ for (let i = 0; i < 10 && !link; i++) {
+ try { link = await call('POST', '/withdraw/funded', { id: inv.id }); }
+ catch (e) { if (!/not paid/i.test(e.message)) throw e; await new Promise((r) => setTimeout(r, 1500)); }
+ }
+ if (!link) throw new Error(t('wlNotConfirmed'));
+ s.list = [link, ...(s.list || []).filter((l) => l.id !== link.id)];
+ s.made = link.id; s.open = link.id;
+ s.amount = ''; s.uses = '1'; s.note = '';
+ } catch (e) {
+ s.error = e.message || String(e);
+ } finally { s.busy = false; render(); }
+ }
+
+ async function takeBack(l) {
+ const s = st();
+ s.taking = l.id; s.error = ''; render();
+ let lnId = null;
+ try {
+ if (l.remainingSat > 0) {
+ const inv = await hook('arkLnInvoice', l.remainingSat, t('wlTakeBackMemo'));
+ if (!inv || !inv.invoice) throw new Error(t('lnWithdrawNoInvoice'));
+ lnId = inv.id;
+ // the wallet has to claim the held payment while the registrar pays it
+ hook('arkLnWatch', inv.id, () => {});
+ const r = await call('POST', '/withdraw/reclaim', { id: l.id, invoice: inv.invoice });
+ Object.assign(l, r);
+ toast(r.paid === false ? t('wlTakeBackFailed') : t('wlTakenBack', { amount: amt(inv.amountSat) }));
+ } else {
+ Object.assign(l, await call('POST', '/withdraw/reclaim', { id: l.id }));
+ }
+ } catch (e) {
+ if (lnId) hook('arkLnCancel', lnId);
+ s.error = e.message || String(e);
+ } finally { s.taking = null; render(); load(); }
+ }
+
+ function linkCard(l) {
+ const s = st();
+ const lnurl = lnurlOf(l);
+ let svg = null;
+ try { svg = qrSvg(lnurl, { ec: 'M', mode: 'Alphanumeric' }); } catch {}
+ const live = l.status === 'open' && l.remainingSat > 0 && l.used < l.uses;
+ return h('div', { class: 'card col', style: 'align-items:center;gap:10px' },
+ h('h3', { style: 'align-self:stretch' }, s.made === l.id ? t('wlReady') : t('wlTitle')),
+ live && svg ? h('div', { html: svg }) : null,
+ l.note ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, l.note) : null,
+ h('div', { class: 'small muted', style: 'text-align:center' },
+ l.uses > 1 ? t('wlTermsMany', { amount: amt(l.sat), n: l.uses - l.used, total: l.uses }) : t('wlTermsOne', { amount: amt(l.sat) }),
+ ' · ', t('wlLeft', { amount: amt(l.remainingSat) })),
+ live ? h('div', { class: 'addr-box break mono', style: 'width:100%;font-size:11px' }, lnurl) : h('div', { class: 'notice small' }, l.status === 'closed' ? t('wlClosed') : t('wlUsedUp')),
+ live ? h('div', { class: 'row gap6 wrap', style: 'width:100%' }, copyBtn(lnurl, t('wlCopy'))) : null,
+ live ? h('div', { class: 'small faint', style: 'text-align:center' }, t('wlBearer')) : null,
+ s.error && h('div', { class: 'notice err', style: 'width:100%' }, s.error),
+ live || (l.status === 'open' && l.remainingSat > 0)
+ ? (s.taking === l.id
+ ? h('button', { class: 'btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
+ : h('button', { class: 'btn-ghost btn-block', onClick: () => takeBack(l) }, t('wlTakeBack', { amount: amt(l.remainingSat) })))
+ : null,
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { s.open = null; s.made = null; s.error = ''; render(); } }, t('back')));
+ }
+
+ function formCard() {
+ const s = st();
+ const sat = parseAmount(s.amount, getUnit()) || 0;
+ const uses = Math.max(1, Math.floor(Number(s.uses) || 1));
+ return h('div', { class: 'card col gap6' },
+ h('h3', {}, t('wlTitle')),
+ h('div', { class: 'small muted' }, t('wlDesc')),
+ h('div', { class: 'input-group' },
+ h('input', { id: 'wl-amount', type: 'number', min: '0', inputmode: 'decimal', step: getUnit() === 'sats' ? '1' : '0.00000001',
+ placeholder: t('wlAmount'), value: s.amount, onInput: (e) => { s.amount = e.target.value; render(); } }),
+ h('div', { style: 'display:flex;align-items:center' }, unitTag())),
+ h('label', { class: 'row gap6', style: 'align-items:center' },
+ h('span', { class: 'small grow' }, t('wlUses')),
+ h('input', { id: 'wl-uses', type: 'number', min: '1', max: '1000', step: '1', inputmode: 'numeric', style: 'width:90px',
+ value: s.uses, onInput: (e) => { s.uses = e.target.value; render(); } })),
+ h('textarea', { class: 'gift-note-input', rows: 2, maxlength: NOTE_MAX, placeholder: t('wlNote'), value: s.note, onInput: (e) => { s.note = e.target.value; } }),
+ h('div', { class: 'small faint' }, sat >= 1 && uses > 1 ? t('wlPayNowMany', { total: amt(sat * uses), n: uses, amount: amt(sat) }) : t('wlPayNow')),
+ s.error && !s.open ? h('div', { class: 'notice err' }, s.error) : null,
+ s.busy
+ ? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
+ : h('button', { id: 'wl-create', class: 'btn-primary btn-block', onClick: create }, sat >= 1 ? t('wlCreateFor', { amount: amt(sat * uses) }) : t('wlCreate')));
+ }
+
+ function listCard() {
+ const s = st();
+ if (s.list == null) return h('div', { class: 'card', style: 'text-align:center' }, h('span', { class: 'spinner sm' }));
+ if (!s.list.length) return s.listError ? h('div', { class: 'notice err small' }, s.listError) : null;
+ return h('div', { class: 'card col gap6' },
+ h('span', { class: 'small muted' }, t('wlYours')),
+ ...s.list.map((l) => h('button', { class: 'row between wl-row', style: 'text-align:left', onClick: () => { s.open = l.id; s.made = null; s.error = ''; render(); } },
+ h('span', { class: 'small' }, amt(l.sat), l.uses > 1 ? ` × ${l.uses}` : '', l.note ? h('span', { class: 'faint' }, ' · ' + l.note) : null),
+ h('span', { class: 'small faint' },
+ l.status === 'closed' ? t('wlClosedTag') : l.remainingSat < 1 || l.used >= l.uses ? t('wlUsedUpTag') : t('wlLeft', { amount: amt(l.remainingSat) })))));
+ }
+
+ function view() {
+ const s = st();
+ if (!available()) {
+ return h('div', { class: 'col', style: 'gap:12px' },
+ h('div', { class: 'card col' }, h('h3', {}, t('wlTitle')), h('div', { class: 'small muted' }, t('wlMainnetOnly'))),
+ h('button', { class: 'btn-ghost btn-block', onClick: () => goBack(() => { ui.giftMode = false; }) }, t('back')));
+ }
+ const l = s.open && (s.list || []).find((x) => x.id === s.open);
+ if (l) return h('div', { class: 'col', style: 'gap:12px' }, linkCard(l));
+ return h('div', { class: 'col', style: 'gap:12px' },
+ formCard(),
+ listCard(),
+ h('button', { class: 'btn-ghost btn-block', onClick: () => { ui.wl = null; goBack(() => { ui.giftMode = false; }); } }, t('back')));
+ }
+
+ const entry = () => h('button', { id: 'wl-open', class: 'linklike small', style: 'align-self:center;margin-top:2px', onClick: open }, '⚡ ' + t('wlTitle'));
+
+ return { view, entry, open };
+}
diff --git a/src/i18n.js b/src/i18n.js
index b45638e..af0bdfb 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -476,6 +476,8 @@ const STR = {
alertsNew: '{n} new',
alertsEmpty: 'Nothing yet. Zaps, reactions and replies to your posts will show up here.',
alertZap: 'zapped you {sats}',
+ alertZapApp: 'zapped your app {name} {sats}',
+ alertZapAppAnon: 'zapped your app {sats}',
alertReact: 'reacted {emoji}',
alertBoost: 'boosted your post',
alertReply: 'replied to you',
@@ -1743,6 +1745,35 @@ const STR = {
lnWithdrawPaid: 'Received {amount}',
lnWithdrawNotPaid: 'They took the invoice but the payment didn’t arrive. Check with them before trying again.',
lnWithdrawNoInvoice: 'Couldn’t make an invoice to be paid to.',
+ wlTitle: 'Withdraw link',
+ wlReady: 'Your withdraw link is ready',
+ wlDesc: 'A Lightning link or QR code that anyone can withdraw sats from, like a voucher. It works with most Lightning wallets, even while your phone is off. You pay for it up front; Coinos holds the sats until they’re claimed, and you can take back whatever is left at any time.',
+ wlAmount: 'Amount per withdrawal',
+ wlUses: 'How many withdrawals',
+ wlNote: 'Description (optional)',
+ wlPayNow: 'Paid now from Spending.',
+ wlPayNowMany: '{total} paid now from Spending: {n} withdrawals of up to {amount}.',
+ wlCreate: 'Create withdraw link',
+ wlCreateFor: 'Create link for {amount}',
+ wlAmountInvalid: 'Enter an amount.',
+ wlUsesInvalid: 'Between 1 and 1000 withdrawals.',
+ wlNoFunds: 'Not enough in Spending for {amount}.',
+ wlNotConfirmed: 'Paid, but the link isn’t confirmed yet. It will appear under your links in a moment.',
+ wlTermsOne: 'Up to {amount}, once',
+ wlTermsMany: 'Up to {amount} each, {n} of {total} withdrawals left',
+ wlLeft: '{amount} left',
+ wlCopy: 'Copy LNURL',
+ wlBearer: 'Anyone with this link or QR code can withdraw from it. Share it only with whoever it’s for.',
+ wlTakeBack: 'Take back {amount}',
+ wlTakeBackMemo: 'Withdraw link taken back',
+ wlTakenBack: '{amount} is back in Spending',
+ wlTakeBackFailed: 'Couldn’t pay it back just now. The link stays open; try again in a moment.',
+ wlClosed: 'This link is closed.',
+ wlUsedUp: 'This link has been used up.',
+ wlClosedTag: 'closed',
+ wlUsedUpTag: 'used up',
+ wlYours: 'Your withdraw links',
+ wlMainnetOnly: 'Withdraw links are only available on mainnet.',
lnWithdrawWatchOnly: 'This device can’t receive: the wallet is watch-only here.',
lnWithdrawMemo: 'Withdrawal from {domain}',
lnPayAmount: 'Amount',
diff --git a/tools/lnurl-withdraw-links-test.js b/tools/lnurl-withdraw-links-test.js
new file mode 100644
index 0000000..b349e17
--- /dev/null
+++ b/tools/lnurl-withdraw-links-test.js
@@ -0,0 +1,166 @@
+// Prepaid withdraw links (src/features/withdraw-links.js + coinosv3-server
+// names/withdraw.js): create one from Send (it pays the registrar up front),
+// get an LNURL QR, have it claimed — here by our own LNURL-withdraw redeem
+// flow (zaps.js), the same road any Lightning wallet takes — and take back
+// what's left. The registrar is the real withdraw service behind a stand-in
+// HTTP server (NIP-98 checked) with a fake Lightning node; the Ark side is
+// faked through the hooks. Run: bun tools/lnurl-withdraw-links-test.js
+import assert from 'node:assert/strict';
+import { verifyEvent } from 'nostr-tools/pure';
+import puppeteer from './puppeteer.js';
+import { withdrawService } from '../../coinosv3-server/names/withdraw.js';
+
+const app = await Bun.file('src/app.js').text();
+const domHelper = app.slice(app.indexOf('function h(tag,'), app.indexOf('// ---------------------------------------------------------------- morphing'));
+const entry = `
+import { withdrawLinks } from './src/features/withdraw-links.js';
+import { zapsFeature } from './src/features/zaps.js';
+import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure';
+${domHelper}
+const sk = generateSecretKey();
+const ui = { screen: 'wallet', tab: 'send', giftMode: false, send: { recipients: [{ address: '', amount: '' }] } };
+let lnInvoices = 0; const watched = [];
+const wallet = { watchOnly: false, nostrSign: async (e) => finalizeEvent(e, sk), loadFeatureState: (k, d) => d, saveFeatureState: () => {} };
+const api = async (p) => (await fetch(p)).json();
+const ctx = {
+ h, ui, wallet, render, toast: (m) => (window.toasts = (window.toasts || [])).push(m),
+ withdrawRegistrar: location.origin,
+ copyBtn: (v, label) => h('button', { class: 'btn-sm', onClick: () => { window.copied = v; } }, label),
+ goBack: (fn) => { fn(); render(); },
+ blankSend: () => ({ recipients: [{ address: '', amount: '' }] }),
+ fmtAmount: (n) => Number(n).toLocaleString('en-US'), unitLabel: () => 'sats', unitTag: () => h('span', { class: 'unit-tag' }, 'sats'),
+ parseAmount: (v) => { const n = Number(String(v).replace(/,/g, '')); return isFinite(n) && n > 0 ? Math.round(n) : null; }, getUnit: () => 'sats',
+ amountField: (sat) => String(sat),
+ hook(name, ...a) {
+ if (name === 'arkReady' || name === 'canLnPay') return true;
+ if (name === 'arkSpendableSat') return window.spendable ?? 100000;
+ if (name === 'arkPayInvoice') { window.paidInvoices = (window.paidInvoices || 0) + 1; return api('/__pay?bolt11=' + a[0]); }
+ // a coinos wallet's Lightning receive lives on the registrar's own node
+ if (name === 'arkLnInvoice') { lnInvoices++; return api('/__mkinv?own=1&sat=' + a[0]).then((r) => ({ id: 'ln' + lnInvoices, invoice: r.bolt11, amountSat: a[0] })); }
+ if (name === 'arkLnWatch') { watched.push(a[0]); return true; }
+ if (name === 'arkLnUnwatch' || name === 'arkLnCancel') return true;
+ return null;
+ },
+};
+const wl = withdrawLinks(ctx);
+const zaps = zapsFeature(ctx);
+function render() {
+ const v = (ui.giftMode === 'lnurl' && wl.view()) || zaps.sendView() || h('div', { id: 'closed' }, wl.entry());
+ document.querySelector('#app').replaceChildren(v);
+}
+window.test = { ui, render, pk: getPublicKey(sk), redeem: (s) => zaps.matchSendText(s, false), watched };
+render();
+`;
+const bundle = await Bun.build({
+ entrypoints: ['wl-test-entry'], target: 'browser',
+ plugins: [{ name: 'wl-test', setup(build) {
+ build.onResolve({ filter: /^wl-test-entry$/ }, () => ({ path: 'entry', namespace: 'wl-test' }));
+ build.onLoad({ filter: /.*/, namespace: 'wl-test' }, () => ({ contents: entry, loader: 'js', resolveDir: process.cwd() }));
+ } }],
+});
+assert(bundle.success, bundle.logs.join('\n'));
+const css = await Bun.file('src/style.css').text();
+const js = await bundle.outputs[0].text();
+const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><style>${css}</style><div id="app"></div><script type="module">${js}</script>`;
+
+// ---- the stand-in registrar: the real service, a fake node ----
+const OUR = '02' + 'aa'.repeat(32), THEIRS = '03' + 'bb'.repeat(32);
+const invoices = {}, decoded = {}, outbound = {};
+let seq = 0, circular = 0;
+const mk = (sat, payee) => { const hash = (++seq).toString(16).padStart(64, '0'); const b = 'lnbc' + sat + 'n1fake' + seq; decoded[b] = { valid: true, payment_hash: hash, amount_msat: sat * 1000, payee, created_at: Math.floor(Date.now() / 1000), expiry: 3600 }; return { b, hash }; };
+const ln = { async call(m, p) {
+ if (m === 'invoice') { const { b, hash } = mk(p.amount_msat / 1000, OUR); invoices[hash] = { status: 'unpaid', bolt11: b }; return { bolt11: b, payment_hash: hash }; }
+ if (m === 'listinvoices') return { invoices: invoices[p.payment_hash] ? [invoices[p.payment_hash]] : [] };
+ if (m === 'decode') { if (!decoded[p.string]) throw new Error('bad'); return decoded[p.string]; }
+ if (m === 'pay') { const d = decoded[p.bolt11]; outbound[d.payment_hash] = 'complete'; return { status: 'complete', amount_msat: d.amount_msat, amount_sent_msat: d.amount_msat }; }
+ if (m === 'waitsendpay') { outbound[p.payment_hash] = 'complete'; return { status: 'complete' }; }
+ if (m === 'listsendpays') return { payments: outbound[p.payment_hash] ? [{ status: outbound[p.payment_hash] }] : [] };
+ throw new Error('unexpected ' + m);
+} };
+const state = {};
+let svc; // made once the server has its port: the service's URLs are built on it
+const nip98 = async (req, url, body) => {
+ const evt = JSON.parse(atob((req.headers.get('authorization') || '').replace(/^Nostr /, '')));
+ assert(verifyEvent(evt) && evt.kind === 27235 && new URL(evt.tags.find((t) => t[0] === 'u')[1]).pathname === url.pathname);
+ return evt.pubkey;
+};
+const server = Bun.serve({ port: 0, async fetch(req) {
+ const u = new URL(req.url);
+ const j = (b, s = 200) => Response.json(b, { status: s });
+ if (u.pathname === '/__pay') { const d = decoded[u.searchParams.get('bolt11')]; invoices[d.payment_hash].status = 'paid'; return j({ ok: true }); }
+ if (u.pathname === '/__mkinv') { const { b } = mk(Number(u.searchParams.get('sat')), u.searchParams.get('own') ? OUR : THEIRS); return j({ bolt11: b }); }
+ const w = u.pathname.match(/^\/w\/([A-Za-z0-9_-]+)(\/cb)?$/);
+ if (w) return j(w[2] ? await svc.callback(w[1], u.searchParams.get('k1'), u.searchParams.get('pr')) : svc.params(w[1]));
+ if (u.pathname.startsWith('/withdraw/')) {
+ const body = req.method === 'POST' ? await req.text() : '';
+ const pk = await nip98(req, u, body);
+ const b = body ? JSON.parse(body) : {};
+ try {
+ if (u.pathname === '/withdraw/mine') return j({ links: svc.mine(pk) });
+ if (u.pathname === '/withdraw/new') return j(await svc.create({ pubkey: pk, ...b }));
+ if (u.pathname === '/withdraw/funded') return j(await svc.confirmFunded(b.id, pk));
+ if (u.pathname === '/withdraw/reclaim') return j(await svc.reclaim(b.id, pk, b.invoice));
+ } catch (e) { return j({ error: e.message }, e.status || 500); }
+ }
+ return new Response(html, { headers: { 'content-type': 'text/html' } });
+} });
+svc = withdrawService({ state, persist: () => {}, lnFor: () => ln, ourNodeId: async () => OUR,
+ circularPick: async () => ({ cap: 1e9 }), payCircular: async () => { circular++; return { feeMsat: 0 }; }, publicBase: server.url.origin.replace(/\/$/, '') });
+
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+const page = await browser.newPage();
+const errors = [];
+page.on('pageerror', (e) => errors.push(e.message));
+const pause = (ms) => new Promise((r) => setTimeout(r, ms));
+const check = (name, value, detail = '') => { assert(value, name + (detail ? ' — ' + detail : '')); console.log(' ✓ ' + name); };
+const text = () => page.evaluate(() => document.body.innerText.replace(/\s+/g, ' '));
+const waitText = async (re, ms = 6000) => { for (let i = 0; i < ms / 100; i++) { if (re.test(await text())) return true; await pause(100); } return false; };
+const click = (label) => page.evaluate((x) => { const b = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().startsWith(x)); if (!b) return false; b.click(); return true; }, label);
+const type = (sel, v) => page.evaluate(([s, val]) => { const i = document.querySelector(s); i.value = val; i.dispatchEvent(new Event('input', { bubbles: true })); }, [sel, v]);
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto(server.url.href);
+ await page.waitForSelector('#wl-open');
+ console.log('[making a link]');
+ await page.click('#wl-open');
+ check('Send opens the withdraw-link page', await waitText(/A Lightning link or QR code that anyone can withdraw sats from/));
+ await page.click('#wl-create');
+ check('no amount: asked for one, nothing paid', await waitText(/Enter an amount/) && !(await page.evaluate(() => window.paidInvoices)));
+ await type('#wl-amount', '500'); await type('#wl-uses', '3');
+ check('the button and the line say what gets paid now', /Create link for 1,500 sats/.test(await text()) && /1,500 sats paid now from Spending: 3 withdrawals of up to 500 sats/.test(await text()), await text());
+ await page.evaluate(() => { window.spendable = 1000; });
+ await page.click('#wl-create');
+ check('more than Spending holds: refused before paying', await waitText(/Not enough in Spending for 1,500 sats/) && !(await page.evaluate(() => window.paidInvoices)));
+ await page.evaluate(() => { window.spendable = 100000; });
+ await type('textarea', 'Meetup door prize');
+ await page.click('#wl-create');
+ check('it pays the registrar once and shows the link', await waitText(/Your withdraw link is ready/) && (await page.evaluate(() => window.paidInvoices)) === 1, await text());
+ check('…with a QR, the terms and the note', !!(await page.$('svg')) && /Up to 500 sats each, 3 of 3 withdrawals left/.test(await text()) && /Meetup door prize/.test(await text()), await text());
+ const lnurl = await page.evaluate(() => [...document.querySelectorAll('.addr-box')].map((e) => e.textContent.trim())[0]);
+ check('the link is an LNURL', /^LNURL1[0-9A-Z]+$/.test(lnurl), lnurl);
+ const link = Object.values(state.withdraws)[0];
+ check('the registrar holds it funded', link.status === 'open' && link.totalSat === 1500 && link.pubkey === (await page.evaluate(() => test.pk)));
+
+ console.log('\n[claiming it with a Lightning wallet: ours]');
+ await click('Back');
+ await page.evaluate(() => { test.ui.giftMode = false; });
+ check('the redeem flow takes the LNURL', await page.evaluate((s) => test.redeem(s), lnurl));
+ check('…and reads the link\'s terms', await waitText(/will pay you between 1 and 500 sats/) && /Meetup door prize/.test(await text()), await text());
+ await click('Withdraw');
+ check('the claim is paid out of the link', await waitText(/has your invoice for 500 sats/) && (await (async () => { await pause(100); return link.claims[0]?.status === 'paid'; })()), JSON.stringify(link.claims));
+ check('…round the circular route (a coinos wallet\'s own invoice)', circular === 1);
+
+ console.log('\n[taking back the rest]');
+ await page.evaluate(() => { test.ui.lnWithdraw = null; test.ui.giftMode = false; test.render(); });
+ await page.evaluate(() => document.querySelector('#wl-open').click());
+ check('the list shows what is left', await waitText(/Your withdraw links/) && /1,000 sats left/.test(await text()), await text());
+ await page.evaluate(() => document.querySelector('.wl-row').click());
+ check('the link page shows 2 of 3 left', await waitText(/2 of 3 withdrawals left/));
+ await click('Take back 1,000 sats');
+ check('take back pays the remainder to the wallet and closes the link', await waitText(/This link is closed/) && link.status === 'closed' && link.spentSat === 1500, JSON.stringify(link));
+ check('…and the wallet watched for that payment', (await page.evaluate(() => test.watched.length)) >= 1);
+ check('…the toast says so', (await page.evaluate(() => window.toasts || [])).some((m) => /1,000 sats is back in Spending/.test(m)));
+ check('a closed link refuses claims', svc.params(link.id).status === 'ERROR');
+ check('no page errors', errors.length === 0, errors.join('; '));
+ console.log('\n✅ prepaid withdraw links');
+} catch (e) { console.error('\n❌', e.message); process.exitCode = 1; } finally { await browser.close(); server.stop(true); }
diff --git a/tools/notif-app-zap-test.js b/tools/notif-app-zap-test.js
new file mode 100644
index 0000000..3ee2030
--- /dev/null
+++ b/tools/notif-app-zap-test.js
@@ -0,0 +1,109 @@
+// Notifications: a zap on your Zapstore app listing (kind 32267) reads
+// "zapped your app PAFF" and opens the app's Zapstore page. It opened the
+// zapper's profile: Zapstore's receipt carries no a tag (only the zap request
+// inside it does), so the row looked like a zap on nothing (Adam, 2026-11-07:
+// "clicking this franzap zap notification keeps bringing me to his profile").
+// A row saved before reads the receipt once on tap and goes there too.
+// Run: bun tools/notif-app-zap-test.js
+import puppeteer, { seedWords, skipSeedCheck } from './puppeteer.js';
+import { cacheKeyFor } from '../src/wallet.js';
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+import { privateKeyFromSeedWords } from 'nostr-tools/nip06';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const A = generateSecretKey(), B = generateSecretKey();
+const now = Math.floor(Date.now() / 1000);
+const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 5317, fetch: (req) => {
+ const path = new URL(req.url).pathname;
+ if (path.endsWith('.png')) return new Response(PNG, { headers: { 'content-type': 'image/png' } });
+ if (path.startsWith('/punks') || path === '/verify-worker.js') return new Response(Bun.file('dist' + path));
+ return new Response(html, { headers: { 'content-type': 'text/html' } });
+} });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] });
+const page = await browser.newPage();
+const errs = [];
+page.on('pageerror', (e) => errs.push(String(e)));
+const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
+const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
+
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto('http://localhost:5317/', { waitUntil: 'domcontentloaded' });
+ await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
+ await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
+ await click('create a new wallet'); await sleep(600);
+ await seedWords(page);
+ const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
+ await skipSeedCheck(page);
+ await waitText('receive', 20000);
+ const base = cacheKeyFor(mn + '\n');
+ const ME = getPublicKey(privateKeyFromSeedWords(mn));
+ const APP = '32267:' + 'c'.repeat(64) + ':club.paff.app';
+ const zap = (sk, sats, ts, content) => {
+ const req = finalizeEvent({ kind: 9734, created_at: ts, content, tags: [['p', ME], ['amount', String(sats * 1000)], ['a', APP]] }, sk);
+ // the receipt Zapstore's LNURL server publishes: p and P, no a tag
+ return finalizeEvent({ kind: 9735, created_at: ts, content: '', tags: [['p', ME], ['P', req.pubkey], ['amount', String(sats * 1000)], ['description', JSON.stringify(req)]] }, generateSecretKey());
+ };
+ const OLD = zap(A, 10000, now - 120, 'Love it'); // saved by the old code, without the app
+ const NEW = zap(B, 2100, now - 60, 'great app');
+ const LISTING = finalizeEvent({ kind: 32267, created_at: now - 3600, content: '', tags: [['d', 'club.paff.app'], ['name', 'PAFF']] }, generateSecretKey());
+ await page.evaluateOnNewDocument((evs, listing) => {
+ window.__opened = [];
+ window.open = (u) => { window.__opened.push(u); return null; };
+ const Real = window.WebSocket;
+ window.WebSocket = function (...a) {
+ const ws = new Real(...a);
+ const send = ws.send.bind(ws);
+ ws.send = (data) => {
+ try {
+ const m = JSON.parse(data);
+ if (m[0] === 'REQ') {
+ const fs = m.slice(2);
+ const hit = [
+ // the notifications sync only hands the NEW one; the old row is already held
+ ...evs.slice(1).filter(() => fs.some((f) => (f.kinds || []).includes(9735) && (f['#p'] || []).length)),
+ ...evs.filter((ev) => fs.some((f) => (f.ids || []).includes(ev.id))),
+ ...(fs.some((f) => (f.kinds || []).includes(32267)) ? [listing] : []),
+ ];
+ setTimeout(() => {
+ for (const e of hit) ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', m[1], e]) }));
+ ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
+ }, 0);
+ return;
+ }
+ if (m[0] === 'EVENT' || m[0] === 'NEG-OPEN') return;
+ } catch {}
+ return send(data);
+ };
+ return ws;
+ };
+ window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
+ }, [OLD, NEW], LISTING);
+ await page.evaluate(([k, me, old]) => {
+ const st = JSON.parse(localStorage.getItem(k + ':messages') || '{}');
+ st.notifs = [{ id: old.id, what: 'zap', actor: JSON.parse(old.tags.find((t) => t[0] === 'description')[1]).pubkey, target: null, stream: null, hint: [], sats: 10000, text: 'Love it', ts: old.created_at }];
+ st.notifsPk = me; st.notifsV = 2;
+ localStorage.setItem(k + ':messages', JSON.stringify(st));
+ }, [base, ME, OLD]);
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await waitText('receive', 20000);
+ await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Notifications"]')?.click());
+ console.log('\n[a zap on your app]');
+ check('a new one reads "zapped your app PAFF"', await waitText('zapped your app paff 2.1k sats', 15000),
+ await page.evaluate(() => [...document.querySelectorAll('.alert-row')].map((r) => r.innerText.replace(/\s+/g, ' ')).join(' | ')));
+ await page.evaluate(() => [...document.querySelectorAll('.alert-row')].find((r) => /great app/.test(r.innerText))?.click());
+ await sleep(300);
+ check('...and opens its Zapstore page', (await page.evaluate(() => window.__opened)).includes('https://zapstore.dev/apps/club.paff.app'), JSON.stringify(await page.evaluate(() => window.__opened)));
+ await page.evaluate(() => { window.__opened = []; [...document.querySelectorAll('.alert-row')].find((r) => /Love it/.test(r.innerText))?.click(); });
+ for (let i = 0; i < 40 && !(await page.evaluate(() => window.__opened.length)); i++) await sleep(250);
+ check('a row saved before reads its receipt on tap and opens the app too', (await page.evaluate(() => window.__opened)).includes('https://zapstore.dev/apps/club.paff.app'), JSON.stringify(await page.evaluate(() => window.__opened)));
+ check('...and is labelled as an app zap from then on', await waitText('zapped your app paff 10k sats', 5000));
+ check('still in Notifications, not a profile', await page.evaluate(() => !!document.querySelector('.alert-row')));
+ check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
+} finally { await browser.close(); server.stop(true); }
+console.log(ok ? '\n✅ zaps on your app open the app' : '\n❌ failed');
+process.exit(ok ? 0 : 1);