1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
|
// v3.coinos.io/<name>/receive (and /<name>/pay): a page anyone can open to
// pay a coinos name over Lightning, no wallet of their own on this site
// needed. The link a shop or a blog puts behind its "Donate / Pay in
// Bitcoin" button, as coinos.io/<name>/receive was on the old coinos
// ("The old Coinos I could point this link onto my website ... I'm not
// seeing an option to do this thru V3", JuryImagePro, relayed by Adam
// 2026-11-23).
//
// Its own small page, not the app: a visitor from a website should not
// boot a whole wallet to see a QR code. Everything comes from the names
// registrar's public LNURL-pay endpoints; the invoice is minted by the
// recipient's wallet when it is open, by coinos' node otherwise (forwarded
// on settle). Only the second can be watched (LUD-21 verify), so the page
// says "Paid" when it can and otherwise leaves it to the payer's wallet.
//
// On-chain is not offered: a v3 name publishes no on-chain address.
import { bech32 } from '@scure/base';
import { qrSvg } from './qr.js';
const REGISTRAR = 'https://names.coinos.io';
const DOMAIN = /(^|\.)staging\./.test(location.hostname) ? 'staging.coinos.io' : 'coinos.io';
const PROFILE_RELAYS = ['wss://relay.coinos.io', 'wss://purplepag.es', 'wss://relay.damus.io'];
const $ = (id) => document.getElementById(id);
const el = (tag, attrs = {}, ...kids) => {
const n = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) {
if (v == null || v === false) continue;
if (k.startsWith('on')) n.addEventListener(k.slice(2).toLowerCase(), v);
else if (k === 'html') n.innerHTML = v;
else n.setAttribute(k, v === true ? '' : v);
}
for (const k of kids.flat()) if (k != null && k !== false) n.append(k);
return n;
};
const fmt = (n) => Number(n).toLocaleString('en-US');
const m = location.pathname.match(/^\/([A-Za-z0-9_][A-Za-z0-9._-]{0,29})\/(?:receive|pay)\/?$/);
const name = m ? m[1].toLowerCase() : '';
const address = `${name}@${DOMAIN}`;
const lnurlpUrl = `${REGISTRAR}/lnurlp/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`;
const params = new URLSearchParams(location.search);
let payReq = null; // the name's LNURL-pay answer
let watch = null; // the verify poll for the invoice on screen
async function getJson(url, ms = 10000) {
const r = await fetch(url, { signal: AbortSignal.timeout(ms) });
const j = await r.json().catch(() => null);
if (!r.ok || !j || j.status === 'ERROR') throw new Error((j && j.reason) || `HTTP ${r.status}`);
return j;
}
// The name's face: its nostr profile, best effort. The page works without it.
function fetchProfile(pk) {
return new Promise((resolve) => {
let best = null, left = PROFILE_RELAYS.length;
const socks = [];
const done = () => { for (const s of socks) try { s.close(); } catch {} resolve(best); };
const timer = setTimeout(done, 2500);
for (const url of PROFILE_RELAYS) {
let ws;
try { ws = new WebSocket(url); } catch { if (!--left) { clearTimeout(timer); done(); } continue; }
socks.push(ws);
ws.onopen = () => ws.send(JSON.stringify(['REQ', 'p', { kinds: [0], authors: [pk], limit: 1 }]));
ws.onmessage = (e) => {
let msg; try { msg = JSON.parse(e.data); } catch { return; }
if (msg[0] === 'EVENT' && msg[2]?.pubkey === pk && (!best || msg[2].created_at > best.created_at)) best = msg[2];
if (msg[0] === 'EOSE' || msg[0] === 'CLOSED') { ws.close(); if (!--left) { clearTimeout(timer); done(); } }
};
ws.onerror = () => { if (!--left) { clearTimeout(timer); done(); } };
}
});
}
async function copy(text, btn) {
try { await navigator.clipboard.writeText(text); } catch {
const ta = el('textarea', {}, text); document.body.append(ta); ta.select();
try { document.execCommand('copy'); } catch {} ta.remove();
}
const was = btn.textContent;
btn.textContent = 'Copied';
setTimeout(() => { btn.textContent = was; }, 1500);
}
function qrBox(data, label) {
return el('a', { class: 'qr', href: data, 'aria-label': label, html: qrSvg(data, { ec: 'L', mode: /^[0-9A-Z $%*+\-./:]+$/.test(data) ? 'Alphanumeric' : undefined }) });
}
function stopWatch() { if (watch) { clearInterval(watch); watch = null; } }
// The start: the name's own QR (any amount, picked in the payer's wallet)
// and a form for a set amount.
function showStart() {
stopWatch();
const lnurl = bech32.encode('lnurl', bech32.toWords(new TextEncoder().encode(lnurlpUrl)), 2000).toUpperCase();
const minSat = Math.ceil((payReq.minSendable || 1000) / 1000);
const maxSat = Math.floor((payReq.maxSendable || 1e11) / 1000);
const amount = el('input', { id: 'amount', type: 'text', inputmode: 'numeric', placeholder: 'Amount in sats', autocomplete: 'off', value: params.get('amount') || null });
const note = payReq.commentAllowed ? el('input', { id: 'note', type: 'text', maxlength: String(payReq.commentAllowed), placeholder: 'Note (optional)', value: params.get('memo') || params.get('note') || null }) : null;
const err = el('div', { class: 'err', id: 'err' });
const go = el('button', { class: 'primary', type: 'submit' }, 'Create invoice');
const form = el('form', {
class: 'amount-form',
onSubmit: async (e) => {
e.preventDefault();
err.textContent = '';
const sat = Number(String(amount.value).replace(/[\s,_]/g, ''));
if (!Number.isInteger(sat) || sat < minSat) { err.textContent = `Enter at least ${fmt(minSat)} sats.`; amount.focus(); return; }
if (sat > maxSat) { err.textContent = `At most ${fmt(maxSat)} sats.`; amount.focus(); return; }
go.disabled = true; go.textContent = 'Creating invoice…';
try { await createInvoice(sat, note ? note.value.trim() : ''); } catch (x) {
err.textContent = 'Could not create an invoice: ' + (x.message || x);
} finally { go.disabled = false; go.textContent = 'Create invoice'; }
},
}, el('label', { for: 'amount' }, 'Pay a set amount'), amount, note, go, err);
const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(address, e.currentTarget) }, 'Copy address');
$('body').replaceChildren(
el('div', { class: 'card' },
qrBox('lightning:' + lnurl, 'Open in a Lightning wallet'),
el('p', { class: 'hint' }, 'Scan with any Lightning wallet and pick the amount there.'),
el('div', { class: 'row' }, el('code', { class: 'addr' }, address), copyBtn)),
el('div', { class: 'card' }, form));
}
async function createInvoice(sat, comment) {
const u = new URL(payReq.callback);
u.searchParams.set('amount', String(sat * 1000));
if (comment) u.searchParams.set('comment', comment);
const j = await getJson(u.toString(), 30000);
if (!j.pr) throw new Error('no invoice came back');
showInvoice(sat, j.pr, j.verify || null);
}
function showInvoice(sat, pr, verify) {
stopWatch();
const status = el('div', { class: 'status', id: 'status' }, verify ? 'Waiting for payment…' : 'Pay it from your Lightning wallet.');
const copyBtn = el('button', { class: 'ghost', type: 'button', onClick: (e) => copy(pr, e.currentTarget) }, 'Copy invoice');
const open = el('a', { class: 'button primary', href: 'lightning:' + pr }, 'Open in wallet');
const back = el('button', { class: 'link', type: 'button', onClick: showStart }, '← Another amount');
$('body').replaceChildren(el('div', { class: 'card', id: 'invoice' },
el('div', { class: 'big' }, fmt(sat), el('span', {}, ' sats')),
qrBox('lightning:' + pr.toUpperCase(), 'Open in a Lightning wallet'),
el('div', { class: 'row' }, copyBtn, open),
status, back));
if (!verify) return;
const started = Date.now();
watch = setInterval(async () => {
if (Date.now() - started > 15 * 60_000) { stopWatch(); status.textContent = 'This invoice has expired.'; return; }
try {
const v = await getJson(verify, 8000);
if (v.settled) { stopWatch(); paid(sat); }
} catch {}
}, 3000);
}
function paid(sat) {
$('body').replaceChildren(el('div', { class: 'card done', id: 'paid' },
el('div', { class: 'tick', 'aria-hidden': 'true' }, '✓'),
el('div', { class: 'big' }, 'Paid'),
el('p', {}, `${fmt(sat)} sats sent to ${address}. Thank you!`),
el('button', { class: 'link', type: 'button', onClick: showStart }, 'Pay again')));
}
async function main() {
if (!name) { $('body').replaceChildren(el('div', { class: 'card' }, el('p', {}, 'No such page.'))); return; }
$('who').textContent = address;
document.title = `Pay ${address}`;
let rec = null;
try {
[payReq, rec] = await Promise.all([getJson(lnurlpUrl), getJson(`${REGISTRAR}/name/${encodeURIComponent(name)}?domain=${encodeURIComponent(DOMAIN)}`).catch(() => null)]);
} catch (x) {
$('body').replaceChildren(el('div', { class: 'card' }, el('p', { class: 'err' },
/unknown address/i.test(x.message) ? `${address} is not a coinos address.` : `Could not reach ${address} right now. Try again in a moment.`)));
return;
}
showStart();
const pk = rec && /^[0-9a-f]{64}$/.test(rec.pubkey || '') ? rec.pubkey : null;
if (!pk) return;
$('profile-link').href = '/' + name;
const ev = await fetchProfile(pk);
let p = null; try { p = ev && JSON.parse(ev.content); } catch {}
if (!p) return;
const shown = String(p.display_name || p.name || '').trim().slice(0, 60);
if (shown) { $('display').textContent = shown; document.title = `Pay ${shown}`; }
if (/^https:\/\//.test(p.picture || '')) { const img = $('avatar'); img.src = p.picture; img.hidden = false; }
}
main();
|