// Paywell team app. Open source, public domain. TEST MODE: real accounts, ratings, reviews, scores and a real // Bitcoin wallet on the signet test network (test coins have no value). Daily bonuses are worked out and shown; // no real money moves until licensed payroll and custody partners are in place. (function () { 'use strict'; const $ = (s, r) => (r || document).querySelector(s); const esc = (t) => String(t == null ? '' : t).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); const usd = (cents) => (cents < 0 ? '−' : '') + '$' + (Math.abs(cents) / 100).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); const usdSats = (sats) => price ? usd(Math.round(sats / 1e8 * price * 100)) : (sats.toLocaleString() + ' sats'); const stars = (n) => '' + '★'.repeat(n) + '' + '★'.repeat(5 - n) + ''; const b64u = (buf) => { const b = new Uint8Array(buf); let s = ''; for (let i = 0; i < b.length; i++) s += String.fromCharCode(b[i]); return btoa(s).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); }; const unb64u = (s) => Uint8Array.from(atob(s.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((s.length + 3) % 4)), (c) => c.charCodeAt(0)); const enc = new TextEncoder(); const dayName = (d) => new Date(d + 'T12:00:00Z').toLocaleDateString('en-US', { weekday: 'short', month: 'short', day: 'numeric' }); const when = (t) => new Date(t).toLocaleString('en-US', { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }); const GIFS = [{ id: 'party', e: '🎉', word: 'Woohoo!', a: 'pop', bg: '#ffd166,#ef476f' }, { id: 'dog', e: '🐶', word: 'Good boy!', a: 'wag', bg: '#a0e7e5,#4cc9f0' }, { id: 'fire', e: '🔥', word: 'On fire', a: 'pulse', bg: '#ffb347,#ff5e62' }, { id: 'clap', e: '👏', word: 'Bravo', a: 'shake', bg: '#b8f2a5,#2ec4b6' }, { id: 'coffee', e: '☕', word: 'Coffee time', a: 'float', bg: '#f6d6ad,#c08552' }, { id: 'taco', e: '🌮', word: 'Taco Tuesday', a: 'spin', bg: '#ffe66d,#ff9f1c' }, { id: 'cat', e: '🐱', word: 'Mood', a: 'wag', bg: '#e0c3fc,#8ec5fc' }, { id: 'rocket', e: '🚀', word: 'Let’s go', a: 'launch', bg: '#a1c4fd,#5e60ce' }, { id: 'heart', e: '💚', word: 'Thank you', a: 'pulse', bg: '#c1f7d5,#2d6a4f' }]; const gifHtml = (g) => { const c = g.bg.split(','); return '' + g.e + '' + g.word + ''; }; const COLORS = ['#2d6a4f', '#c2185b', '#e76f51', '#5e60ce', '#0077b6', '#b5838d', '#6a994e', '#bc6c25']; const colorFor = (id) => COLORS[[...String(id)].reduce((a, c) => a + c.charCodeAt(0), 0) % COLORS.length]; let S = null; // summary from the server let price = 0; // USD per BTC let wallet = null; // { w, words } in memory only, after passkey unlock let chainState = null; // last wallet sync let cur = 'home', curCh = 'general', chatTimer = null, lastMsg = 0, chatMsgs = []; let lastCred = null; // credential id used this session (for the vault) // ---------- API ---------- async function api(path, body) { const r = await fetch(path, body === undefined ? { credentials: 'same-origin' } : { method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); const j = await r.json().catch(() => ({})); if (!r.ok) { const e = new Error(j.error || 'Something went wrong. Try again.'); e.status = r.status; throw e; } return j; } async function loadPrice() { try { const j = await api('/api/chain/price'); price = j.usd || 0; } catch (e) {} } // ---------- Passkeys (WebAuthn) with the PRF extension for the wallet lock ---------- let PRF_IN = null; async function prfIn() { if (!PRF_IN) PRF_IN = new Uint8Array(await crypto.subtle.digest('SHA-256', enc.encode('paywell-wallet-vault-v1'))); return PRF_IN; } const passkeysOk = () => !!(window.PublicKeyCredential && navigator.credentials && navigator.credentials.create); async function createPasskey(name) { const { challenge, rpId } = await api('/api/app/challenge', {}); const cred = await navigator.credentials.create({ publicKey: { challenge: unb64u(challenge), rp: { id: rpId, name: 'Paywell' }, user: { id: crypto.getRandomValues(new Uint8Array(16)), name: name + ' (Paywell)', displayName: name }, pubKeyCredParams: [{ type: 'public-key', alg: -7 }, { type: 'public-key', alg: -257 }], authenticatorSelection: { residentKey: 'required', requireResidentKey: true, userVerification: 'required' }, attestation: 'none', timeout: 120000, extensions: { prf: { eval: { first: await prfIn() } } }, } }); const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; return { payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), attestationObject: b64u(cred.response.attestationObject) }, prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, prfOn: !!(ext.prf && ext.prf.enabled), }; } async function getPasskey(allowId) { const { challenge, rpId } = await api('/api/app/challenge', {}); const pk = { challenge: unb64u(challenge), rpId, userVerification: 'required', timeout: 120000, extensions: { prf: { eval: { first: await prfIn() } } } }; if (allowId) pk.allowCredentials = [{ type: 'public-key', id: unb64u(allowId) }]; const cred = await navigator.credentials.get({ publicKey: pk }); const ext = cred.getClientExtensionResults ? cred.getClientExtensionResults() : {}; lastCred = cred.id; return { payload: { id: cred.id, clientDataJSON: b64u(cred.response.clientDataJSON), authenticatorData: b64u(cred.response.authenticatorData), signature: b64u(cred.response.signature) }, prf: ext.prf && ext.prf.results && ext.prf.results.first ? new Uint8Array(ext.prf.results.first) : null, }; } function passkeyError(e) { if (e && e.name === 'NotAllowedError') return 'The passkey step was cancelled or timed out. Try again.'; if (e && e.name === 'InvalidStateError') return 'This device already has a Paywell passkey. Use “Sign in” instead.'; return (e && e.message) || 'Something went wrong. Try again.'; } // ---------- Wallet lock: AES-GCM key from the passkey's PRF secret (HKDF), same as everywhere else in Paywell ---------- async function hkdf(prf, salt, info) { const k = await crypto.subtle.importKey('raw', prf, 'HKDF', false, ['deriveBits']); return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: salt.length ? salt : new Uint8Array(32), info: enc.encode(info) }, k, 256)); } async function vaultSave(credId, prf, words) { const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12)); const key = await crypto.subtle.importKey('raw', await hkdf(prf, salt, 'paywell-vault-key'), 'AES-GCM', false, ['encrypt']); const ct = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: enc.encode(credId) }, key, enc.encode(words))); const box = new Uint8Array(12 + ct.length); box.set(iv); box.set(ct, 12); await api('/api/vault/save', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')), blob: b64u(box), salt: b64u(salt) }); } async function vaultOpen(credId, prf) { const j = await api('/api/vault/get', { cred: credId, auth: b64u(await hkdf(prf, new Uint8Array(0), 'paywell-vault-auth')) }); const box = unb64u(j.blob); const key = await crypto.subtle.importKey('raw', await hkdf(prf, unb64u(j.salt), 'paywell-vault-key'), 'AES-GCM', false, ['decrypt']); return new TextDecoder().decode(await crypto.subtle.decrypt({ name: 'AES-GCM', iv: box.slice(0, 12), additionalData: enc.encode(credId) }, key, box.slice(12))); } async function unlockWallet(cred) { if (!cred.prf) throw new Error('This browser’s passkeys can’t open a locked wallet yet. Try Chrome or Safari, or use your own wallet.'); const words = await vaultOpen(cred.payload.id, cred.prf); wallet = { w: PWW.open(words) }; return wallet; } // ---------- Screens ---------- const panel = () => $('#panel'); function setTab(t) { cur = t; document.querySelectorAll('.tabs button').forEach((b) => b.setAttribute('aria-current', b.dataset.tab === t ? 'page' : 'false')); if (chatTimer) { clearInterval(chatTimer); chatTimer = null; } render(); } function shell(signedIn) { $('#app').classList.toggle('out', !signedIn); } function gate(msg) { shell(false); const setup = (location.hash.match(/setup=([A-Za-z0-9_-]+)/) || [])[1]; if (setup) return setupScreen(setup); panel().innerHTML = '

Paywell team app

Sign in with your face, fingerprint or screen lock. No username or password.

' + (msg ? '' : '') + (passkeysOk() ? '' : '

This browser doesn’t support passkeys. Try a recent Chrome, Safari, Edge or Firefox.

') + '
or
' + '

Start a test team

Try everything for real: passkey sign-in, ratings, peer reviews, scores, tiers, team chat and a Bitcoin wallet on the test network. Test coins have no value and no real money moves.

' + '' + '' + '
' + '

Joining a team? Open the setup link your team sent you.

'; } async function setupScreen(token) { panel().innerHTML = '

Checking your setup link…

'; try { const s = await api('/api/app/setup', { token }); panel().innerHTML = '

Welcome, ' + esc(s.name) + '

You’ve been added to ' + esc(s.team) + '. Save a passkey on this device and your face, fingerprint or screen lock becomes your sign-in.

' + '
'; } catch (e) { history.replaceState(null, '', '/app/'); gate(e.message); } } function payoutScreen(note) { panel().innerHTML = '

Where should your Bitcoin go?

Your daily Bitcoin bonus needs a wallet. You can change this any time.

' + (note ? '' : '') + '' + '' + '' + '
'; } function tierChip(t) { return '' + esc(S.tiers[t].name) + ''; } function scoreBar(n) { return ''; } const views = { home() { const s = S.score; const paidTo = S.me.payout === 'own' ? 'your own wallet' : 'your Paywell wallet'; return '

Hi, ' + esc(S.me.name) + '

' + esc(S.org.name) + ' · ' + esc(S.me.tierName) + ' (' + S.me.shares + ' bonus share' + (S.me.shares === 1 ? '' : 's') + ')

' + '

Today’s Bitcoin bonus

' + usd(S.todayCents) + '

Paid automatically every day to ' + paidTo + '. Test mode: worked out for real, no money moves.

' + '

Your score: ' + s.score + '

' + scoreBar(s.score) + '

Customers ' + (s.customerN ? s.customerAvg + ' ★ (' + s.customerN + ')' : 'no ratings yet') + ' · 60%
Teammates ' + (s.peerN ? s.peerAvg + ' ★ (' + s.peerN + ')' : 'no reviews yet') + ' · 40%' + (!s.customerN && !s.peerN ? '
Everyone starts at 70 until reviews come in.' : '') + '

' + '

How today’s bonus is worked out

Score ' + s.score + ' × ' + S.me.shares + ' share' + (S.me.shares === 1 ? '' : 's') + ' (' + esc(S.me.tierName) + ') × ' + usd(S.org.shareCents) + ' per share = ' + usd(S.todayCents) + '

Your wage is separate: at least the minimum wage where you work, and reviews never lower it.

' + '

Daily bonuses

' + (S.days.length ? S.days.map((d) => '
' + dayName(d.day) + 'Score ' + d.score + ' · ' + esc(S.tiers[d.tier].name) + '
' + usd(d.cents) + '
test
').join('') : '

Your first daily bonus shows here tomorrow.

') + '
' + '
'; }, checkin() { const mates = S.team.filter((m) => m.id !== S.me.id); return '

Daily check-in

Rate each teammate you worked with today, 1 to 5 stars, on teamwork, care and reliability. One review per teammate per day. They see the stars and your note, never who wrote it. Only your own team can see reviews.

' + (mates.length ? mates.map((m) => { const done = S.reviewedToday.includes(m.id); return '
' + esc(m.name) + '' + esc(S.tiers[m.tier].name) + '
' + (done ? 'Reviewed today ✓' : '') + '
' + (done ? '' : '
' + [1, 2, 3, 4, 5].map((n) => '').join('') + '

') + '
'; }).join('') : '

No teammates yet. ' + (S.me.admin ? 'Add people in the Team tab.' : 'Your team will add people soon.') + '

') + '
'; }, ratings() { const r = S.ratings, p = S.peers; return '

Your ratings and reviews

Customer ratings (60% of your score) and teammate reviews (40%), from the last four weeks. Customers’ contact details stay private.

' + '

Ask a customer to rate a visit

Makes a one-time rating link for a visit you just did. In a real shop this comes on the receipt by itself.

' + '

From customers

' + (r.length ? r.map((x) => '
' + stars(x.stars) + '' + esc(x.brand) + '' + when(x.created) + (x.note ? ' · “' + esc(x.note) + '”' : '') + '
' + (x.status === 'counted' ? 'Counted' : 'Being checked') + '
').join('') : '

No customer ratings yet. Make a rating link above to try it.

') + '
' + '

From teammates

' + (p.length ? p.map((x) => '
' + stars(x.stars) + '' + dayName(x.day) + (x.note ? ' · “' + esc(x.note) + '”' : '') + '
').join('') : '

No teammate reviews yet.

') + '
' + '

Fair rules

1 and 2 star customer ratings are checked before they count. Ratings about prices, scheduling or company rules don’t count. You can dispute any rating within 14 days, and it has no effect while it’s reviewed. Reviews never lower your wage. How disputes work

'; }, take() { const need = S.me.payout === 'paywell' && !wallet; return '

Get paid

Show this to the customer. They scan it, or tap it on Android, and pay from any Bitcoin wallet. Shown in dollars. No tip screen, ever.

' + (need ? '

Unlock your wallet first so we know where the payment goes.

' : '
') + '
'; }, wallet() { const own = S.me.payout === 'own'; let h = '

Where your daily bonus goes

' + (own ? 'Your own wallet' + esc(S.me.payoutAddr) + '' : 'Your Paywell walletMade with your account. Your passkey locks its backup; we can’t open it.') + '
'; if (!own || wallet) { if (!wallet) h += '

Wallet

Locked. Your passkey opens it.

'; else { const st = chainState; h += '

Wallet balance

' + (st ? usdSats(st.balance) : '…') + '

' + (st ? st.balance.toLocaleString() + ' sats on the test network' + (price ? ' · ' + usd(Math.round(price * 100)) + ' per BTC' : '') : 'Checking the network…') + '

' + '
' + '

Activity

' + (st && st.history.length ? st.history.slice(0, 30).map((t) => '
' + (t.delta >= 0 ? 'Received' : 'Sent') + '' + (t.time ? when(t.time) : 'Just now') + (t.confirmed ? '' : ' · pending') + '
' + (t.delta >= 0 ? '+' : '−') + usdSats(Math.abs(t.delta)) + '
').join('') : '

Nothing yet. Get free test coins from a signet faucet, then send them to your Receive address.

Get free test coins

') + '
'; } } h += '
Test network only: test coins have no value. Trading between Bitcoin and dollars goes through a licensed exchange partner and opens with live mode.
'; return h; }, chat() { const ch = [['general', 'Hellos, news and everyday stuff'], ['shout-outs', 'Great days and high fives'], ['random', 'Anything goes (keep it kind)']]; return '
' + '
#' + curCh + '' + ch.find((c) => c[0] === curCh)[1] + '

Loading…

' + '' + '
'; }, team() { let h = '

' + esc(S.org.name) + '

Three tiers: Explorer (1 share), Builder (1½), Guide (2). Tiers are reviewed every three months.

' + S.team.map((m) => '
' + esc(m.name) + (m.id === S.me.id ? ' (you)' : '') + '' + esc(S.tiers[m.tier].name) + '
' + (S.me.admin && m.id !== S.me.id ? '' : tierChip(m.tier)) + '
').join('') + '
'; if (S.me.admin) h += '

Add a teammate

Makes a one-time setup link (good for 24 hours). Send it only to them, by text or email. Opening it lets them save a passkey and join.

'; return h + '
'; }, security() { return '

Security

' + '
✓
Passkey sign-in
Your face, fingerprint or screen lock is your sign-in. No username, no password, nothing to steal or forget.
' + '
✓
Wallet locked by your passkey
Your wallet’s backup is locked on your device before it reaches us. We store it but can’t open it. Nothing to write down.
' + '
✓
Confirm before money moves
Sending, and changing where your bonus goes, always asks for your passkey again.
' + '
✓
Reviews stay in your team
Only signed-in members of your own team can see your team’s ratings and reviews.
' + '

We will never ask for a setup link or recovery words, by phone, text, email or in person. Anyone who asks is trying to steal from you.
'; }, }; function render() { if (!S) return; shell(true); panel().innerHTML = views[cur] ? views[cur]() : views.home(); if (cur === 'chat') { lastMsg = 0; chatMsgs = []; pollChat(); chatTimer = setInterval(pollChat, 4000); } if (cur === 'wallet' && wallet && !chainState) refreshWallet(); } async function refresh() { S = await api('/api/app/me'); render(); } // ---------- Chat ---------- function msgHtml(m) { const g = (m.body.match(/^:gif:([a-z]+):$/) || [])[1]; const gif = g && GIFS.find((x) => x.id === g); return '
' + esc(m.name[0] || '?') + '
' + esc(m.name) + '' + when(m.created) + '
' + (gif ? gifHtml(gif) : '

' + esc(m.body) + '

') + '
'; } async function pollChat(body) { try { const j = body ? await api('/api/app/chat?c=' + curCh + '&since=' + lastMsg, { channel: curCh, body }) : await api('/api/app/chat?c=' + curCh + '&since=' + lastMsg); if (j.messages.length) { chatMsgs = chatMsgs.concat(j.messages); lastMsg = j.messages[j.messages.length - 1].id; } const box = $('#msgs'); if (!box) return; const atEnd = box.scrollHeight - box.scrollTop - box.clientHeight < 60; box.innerHTML = chatMsgs.length ? chatMsgs.map(msgHtml).join('') : '

No messages yet. Say hello! 👋

'; if (atEnd || body || j.messages.length) box.scrollTop = box.scrollHeight; } catch (e) { if (e.status === 401) { S = null; gate(); } } } // ---------- Wallet actions ---------- async function refreshWallet() { if (!wallet) return; try { chainState = await PWW.sync(wallet.w); } catch (e) { chainState = chainState || { balance: 0, history: [], utxos: [], nextReceive: 0, nextChange: 0 }; } if (cur === 'wallet') render(); } function receiveBox() { const a = wallet.w.address(chainState ? chainState.nextReceive : 0); $('#wbox').innerHTML = '

Your receive address

' + PWW.qrSvg('bitcoin:' + a) + '

' + esc(a) + '

'; } function sendBox() { $('#wbox').innerHTML = '

Send Bitcoin

Bitcoin payments can’t be undone. Check the address and amount.

'; } // ---------- Events ---------- document.addEventListener('click', async (e) => { const t = e.target.closest('button, a'); if (!t) return; if (t.dataset.tab) { setTab(t.dataset.tab); return; } if (t.dataset.go) { setTab(t.dataset.go); return; } if (t.dataset.ch) { curCh = t.dataset.ch; render(); return; } if (t.dataset.copy) { try { await navigator.clipboard.writeText(t.dataset.copy); t.textContent = 'Copied ✓'; } catch (x) {} return; } if (t.dataset.gif) { $('#gifs').hidden = true; pollChat(':gif:' + t.dataset.gif + ':'); return; } const act = t.dataset.act; if (!act) return; try { if (act === 'gifs') { const g = $('#gifs'); g.hidden = !g.hidden; return; } if (act === 'signin') { t.disabled = true; t.textContent = 'Waiting for your passkey…'; const c = await getPasskey(); await api('/api/app/login', { credential: c.payload }); S = await api('/api/app/me'); if (S.me.payout === 'paywell' && c.prf) { try { await unlockWallet(c); } catch (x) {} } cur = 'home'; render(); loadPrice(); return; } if (act === 'join') { t.disabled = true; t.textContent = 'Waiting for your passkey…'; const c = await createPasskey(t.dataset.name); await api('/api/app/register', { credential: c.payload, setup: t.dataset.token }); history.replaceState(null, '', '/app/'); await afterSignup(c); return; } if (act === 'unlock') { const c = await getPasskey(); await unlockWallet(c); chainState = null; render(); refreshWallet(); return; } if (act === 'refresh') { chainState = null; render(); refreshWallet(); return; } if (act === 'receive') { if (chainState) receiveBox(); return; } if (act === 'send') { sendBox(); return; } if (act === 'payout') { payoutScreen(); return; } if (act === 'signout') { await api('/api/app/logout', {}); S = null; wallet = null; chainState = null; gate(); return; } } catch (x) { const msg = passkeyError(x); const where = $('#werr') || $('#serr'); if (S && !where) { alertBox(msg); } else if (where) where.textContent = msg; else gate(msg); } }); function alertBox(msg) { const p = document.createElement('p'); p.className = 'err'; p.setAttribute('role', 'alert'); p.textContent = msg; panel().prepend(p); } async function afterSignup(c) { S = await api('/api/app/me'); lastCred = c.payload.id; window._signupCred = c; payoutScreen(); } document.addEventListener('change', async (e) => { if (e.target.name === 'pm') { const b = $('#ownbox'); if (b) b.hidden = e.target.value !== 'own'; } if (e.target.dataset && e.target.dataset.tier) { try { await api('/api/app/tier', { person: e.target.dataset.tier, tier: Number(e.target.value) }); await refresh(); } catch (x) { alertBox(x.message); } } }); document.addEventListener('input', (e) => { if (e.target.id === 'samt') { const v = parseFloat(e.target.value) || 0; $('#sout').textContent = v && price ? Math.round(v / price * 1e8).toLocaleString() + ' sats' : ''; } }); document.addEventListener('submit', async (e) => { const f = e.target; e.preventDefault(); const btn = f.querySelector('button[type=submit]'); const fail = (msg) => { let p = f.querySelector('.err'); if (!p) { p = document.createElement('p'); p.className = 'err'; p.setAttribute('role', 'alert'); f.appendChild(p); } p.textContent = msg; if (btn) btn.disabled = false; }; try { if (btn) btn.disabled = true; if (f.id === 'startteam') { const name = $('#sname').value.trim(), team = $('#steam').value.trim(); if (!name || !team) return fail('Add your first name and a team name.'); const c = await createPasskey(name); await api('/api/app/register', { credential: c.payload, name, team }); await afterSignup(c); return; } if (f.id === 'payoutf') { const mode = f.querySelector('input[name=pm]:checked').value; if (mode === 'own') { const addr = $('#oaddr').value.trim(); if (!PWW.validAddress(addr)) return fail('That doesn’t look like a test-network Bitcoin address (they start with tb1).'); const c = await getPasskey(); await api('/api/app/payout', { mode: 'own', addr, credential: c.payload }); } else { // Make the wallet here, lock its backup with the passkey and store the locked copy with us. let c = window._signupCred && window._signupCred.prf ? window._signupCred : null; if (!c) c = await getPasskey(); if (!c.prf) return fail('This browser’s passkeys can’t lock a wallet backup yet. Choose “Use my own wallet”, or try Chrome or Safari.'); let words = null; try { words = await vaultOpen(c.payload.id, c.prf); } catch (x) { words = PWW.newWords(); await vaultSave(c.payload.id, c.prf, words); } wallet = { w: PWW.open(words) }; const body = { mode: 'paywell', walletAddr: wallet.w.address(0) }; if (S.me.payout === 'own') { const c2 = await getPasskey(c.payload.id); body.credential = c2.payload; } await api('/api/app/payout', body); } window._signupCred = null; S = await api('/api/app/me'); cur = mode === 'own' ? 'home' : 'wallet'; chainState = null; render(); loadPrice(); return; } if (f.classList.contains('peer')) { const st = f.querySelector('input[name=st]:checked'); if (!st) return fail('Pick 1 to 5 stars.'); await api('/api/app/peer', { person: f.dataset.person, stars: Number(st.value), note: f.note.value }); S = await api('/api/app/me'); render(); return; } if (f.id === 'visitf') { const j = await api('/api/app/visit', { service: $('#vsvc').value }); $('#vout').innerHTML = '
' + PWW.qrSvg(j.url) + '

' + esc(j.url) + '

Open it as the customer

Works once, for 14 days. Refresh this tab after rating to see it count.

'; btn.disabled = false; return; } if (f.id === 'takef') { const dollars = parseFloat($('#tamt').value) || 0; if (!price) await loadPrice(); const addr = S.me.payout === 'own' ? S.me.payoutAddr : wallet.w.address(chainState ? chainState.nextReceive : 0); const visit = await api('/api/app/visit', { service: $('#tfor').value || 'Payment' }); const btcAmt = dollars && price ? (dollars / price).toFixed(8).replace(/0+$/, '').replace(/\.$/, '') : ''; const bip21 = 'bitcoin:' + addr + (btcAmt ? '?amount=' + btcAmt : '') + ($('#tfor').value ? (btcAmt ? '&' : '?') + 'label=' + encodeURIComponent($('#tfor').value) : ''); const link = 'https://paywell.company/pay/?u=' + encodeURIComponent(bip21) + '&r=' + encodeURIComponent(visit.url); $('#tbox').innerHTML = '

' + (dollars ? usd(Math.round(dollars * 100)) : 'Any amount') + '

' + PWW.qrSvg(link) + '

Ask them to scan this with their phone camera. It opens the payment, then asks them to rate the visit. No tip.

' + ('NDEFReader' in window ? ' ' : '') + '

'; btn.disabled = false; return; } if (f.id === 'sendf') { const to = $('#sto').value.trim(), dollars = parseFloat($('#samt').value) || 0; if (!price) await loadPrice(); if (!dollars || !price) return fail('Enter an amount in dollars.'); const sats = Math.round(dollars / price * 1e8); const fees = await api('/api/chain/fees').catch(() => ({})); const rate = Math.max(1, Math.ceil(fees['3'] || 2)); if (!chainState) chainState = await PWW.sync(wallet.w); const tx = PWW.buildPayment(wallet.w, chainState, to, sats, rate); if (!confirm('Send ' + usd(Math.round(dollars * 100)) + ' (' + sats.toLocaleString() + ' test sats) plus a network fee of about ' + usdSats(tx.fee) + '? You’ll confirm with your passkey next.')) { btn.disabled = false; return; } await getPasskey(lastCred || undefined); // a fresh face, fingerprint or screen-lock check before money moves const r = await fetch('/api/chain/tx', { method: 'POST', body: tx.hex }).then((x) => x.json()); if (r.error) return fail('The network didn’t take it: ' + r.error); $('#wbox').innerHTML = '
✓

Sent

' + esc(r.txid) + '

'; setTimeout(refreshWallet, 3000); return; } if (f.id === 'invitef') { const j = await api('/api/app/invite', { name: $('#iname').value, tier: Number($('#itier').value) }); $('#iout').innerHTML = '

' + esc(j.url) + '

Good for 24 hours, works once.

'; btn.disabled = false; await refresh(); return; } if (f.id === 'say') { const v = $('#sayin').value.trim(); if (!v) { btn.disabled = false; return; } $('#sayin').value = ''; await pollChat(v); btn.disabled = false; $('#sayin').focus(); return; } } catch (x) { fail(passkeyError(x)); } }); document.addEventListener('click', async (e) => { const b = e.target.closest('#nfcw'); if (!b) return; try { const w = new NDEFReader(); await w.write({ records: [{ recordType: 'url', data: b.dataset.link }] }); $('#nfcmsg').textContent = 'Written. Customers can tap that tag with their phone to pay.'; } catch (x) { $('#nfcmsg').textContent = 'Couldn’t write the tag: ' + (x.message || x); } }); // ---------- Start ---------- (async () => { loadPrice(); if (/setup=/.test(location.hash)) { gate(); return; } try { S = await api('/api/app/me'); render(); } catch (e) { gate(e.status === 401 ? '' : e.message); } })(); window.addEventListener('hashchange', () => { if (/setup=/.test(location.hash)) gate(); }); })();