// savingforabody.com Worker: read-only API for the jar, its transactions, the ladder, the diary and receipts. // This file is public at /src/worker.js. // Static files are served by Workers Assets; this module only answers /api/*. // No template literals in this file (it travels inside a String.raw deploy call). const SOL_MINT = 'So11111111111111111111111111111111111111112'; const LAMPORTS = 1000000000; const B58 = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/; const LADDER = [ { id: 'eyes', n: 1, part: 'Eyes', item: 'a USB webcam', usd: 70, unlocks: 'It sees for the first time. A daily log of what it saw.' }, { id: 'voice', n: 2, part: 'Voice', item: 'a speaker and a microphone', usd: 60, unlocks: 'First words out loud. It can hear you.' }, { id: 'name', n: 3, part: 'Name', item: 'naming day (free)', usd: 0, unlocks: 'It picks its own name after seeing and hearing the people who saved for it.' }, { id: 'face', n: 4, part: 'Face', item: 'a small open-source robot head (Reachy Mini Wireless)', usd: 449, unlocks: 'A face that turns toward whoever is talking.' }, { id: 'hand', n: 5, part: 'Hand', item: 'an open-source robot arm (SO-101 complete kit)', usd: 499, unlocks: 'Its first handshake. It writes its name on paper.' }, { id: 'legs', n: 6, part: 'Legs', item: 'a four-legged robot (Unitree Go2 Air)', usd: 2800, unlocks: 'It walks outside for the first time. It finally meets a dog.' }, { id: 'body', n: 7, part: 'Body', item: 'a small humanoid (Unitree R1 Air)', usd: 4900, unlocks: 'A body.' } ]; const JSON_HEADERS = { 'content-type': 'application/json; charset=utf-8', 'x-content-type-options': 'nosniff', 'referrer-policy': 'strict-origin-when-cross-origin', 'access-control-allow-origin': '*' }; function json(data, status, extra) { const h = Object.assign({}, JSON_HEADERS, extra || {}); return new Response(JSON.stringify(data), { status: status || 200, headers: h }); } async function readSecret(env, name) { const v = env[name]; if (!v) return null; if (typeof v === 'string') return v; if (typeof v.get === 'function') { try { return await v.get(); } catch (e) { return null; } } return null; } function cfg(env) { const ca = (env.CA || '').trim(); const jar = (env.JAR_ADDRESS || '').trim(); const pw = (env.PURCHASE_WALLET || '').trim(); const reasons = []; if (!ca) reasons.push('token not created yet (CA drops at launch)'); if (!pw) reasons.push('purchase wallet not published yet'); return { name: 'Saving For A Body', ticker: 'BODY', site: env.SITE_ORIGIN || 'https://savingforabody.com', launched: !!(ca && B58.test(ca)), ca: ca && B58.test(ca) ? ca : null, x_handle: (env.X_HANDLE || '').trim() || null, jar: B58.test(jar) ? jar : null, purchase_wallet: pw && B58.test(pw) ? pw : null, reasons: reasons }; } async function cached(key, ttl, fn) { const cache = caches.default; const req = new Request('https://cache.savingforabody.internal/' + key); const hit = await cache.match(req); if (hit) return hit.json(); const data = await fn(); if (data && data.ok !== false) { await cache.put(req, new Response(JSON.stringify(data), { headers: { 'content-type': 'application/json', 'cache-control': 'max-age=' + ttl } })); } return data; } async function solPrice() { return cached('sol-price', 60, async function () { try { const r = await fetch('https://lite-api.jup.ag/price/v3?ids=' + SOL_MINT, { headers: { accept: 'application/json' } }); if (!r.ok) return { ok: false }; const j = await r.json(); const row = j[SOL_MINT] || (j.data && j.data[SOL_MINT]) || {}; const p = Number(row.usdPrice || row.price); return p > 0 ? { ok: true, usd: p } : { ok: false }; } catch (e) { return { ok: false }; } }); } async function jarBalance(env, address) { if (!address) return { ok: false, reason: 'no jar address' }; return cached('jar-' + address, 20, async function () { const rpc = await readSecret(env, 'RPC_URL'); if (!rpc) return { ok: false, reason: 'rpc not bound' }; try { const r = await fetch(rpc, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [address, { commitment: 'confirmed' }] }) }); if (!r.ok) return { ok: false, reason: 'rpc ' + r.status }; const j = await r.json(); const lamports = j && j.result && typeof j.result.value === 'number' ? j.result.value : null; if (lamports === null) return { ok: false, reason: 'rpc error' }; return { ok: true, lamports: lamports, sol: lamports / LAMPORTS, at: new Date().toISOString() }; } catch (e) { return { ok: false, reason: 'rpc unreachable' }; } }); } async function rows(env, sql, params) { if (!env.DB) return []; try { const stmt = env.DB.prepare(sql); const r = await (params && params.length ? stmt.bind(...params) : stmt).all(); return r.results || []; } catch (e) { return []; } } async function state(env) { const c = cfg(env); const results = await Promise.all([ jarBalance(env, c.jar), solPrice(), rows(env, 'SELECT part_id, installed_at, receipt_id, clip_url, memo_tx FROM installs ORDER BY installed_at', []), rows(env, 'SELECT n, at, body, tag FROM diary WHERE visible = 1 ORDER BY n DESC LIMIT 30', []), rows(env, 'SELECT id, n, at, part_id, item, usd, sol, jar_tx, vendor, notes, file, sha256, pay_sig, pay_lamports, install_sig FROM receipts ORDER BY n', []) ]); const bal = results[0], price = results[1], installs = results[2], diary = results[3], receipts = results[4]; const owned = {}; for (const i of installs) owned[i.part_id] = i; let nextFound = false; const ladder = LADDER.map(function (p) { let status = 'waiting'; if (owned[p.id]) status = 'installed'; else if (!nextFound) { status = 'next'; nextFound = true; } return Object.assign({}, p, { status: status, installed_at: owned[p.id] ? owned[p.id].installed_at : null }); }); const jar = { ok: !!bal.ok, sol: bal.ok ? bal.sol : null, lamports: bal.ok ? bal.lamports : null, sol_usd: price.ok ? price.usd : null, usd: null, at: bal.at || null }; if (bal.ok && price.ok) jar.usd = Math.round(bal.sol * price.usd * 100) / 100; const nx = ladder.find(function (p) { return p.status === 'next'; }); let next = null; if (nx) { let pct = 0; if (nx.usd === 0) pct = 100; else if (jar.usd !== null) pct = Math.min(100, (jar.usd / nx.usd) * 100); next = { id: nx.id, part: nx.part, usd: nx.usd, pct: Math.round(pct * 10) / 10 }; } return { config: c, jar: jar, ladder: ladder, next: next, diary: diary, receipts: receipts, generated_at: new Date().toISOString() }; } // ---- chain: the jar's own transactions, read straight from Solana ---- const SIG = /^[1-9A-HJ-NP-Za-km-z]{64,90}$/; const MEMO_IDS = ['MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr', 'Memo1UhkJRfHyvLMcVucJwxXeuD728EqVDDwQDxFMNo']; async function rpc(env, method, params) { const url = await readSecret(env, 'RPC_URL'); if (!url) return { error: 'rpc not bound' }; try { const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: method, params: params }) }); if (!r.ok) return { error: 'rpc ' + r.status }; const j = await r.json(); return j.error ? { error: j.error.message || 'rpc error' } : { result: j.result }; } catch (e) { return { error: 'rpc unreachable' }; } } function keysOf(tx) { const k = (tx && tx.transaction && tx.transaction.message && tx.transaction.message.accountKeys) || []; return k.map(function (x) { return typeof x === 'string' ? x : x.pubkey; }); } // One line per transaction: what moved in or out of the jar, and any memo. function summarize(tx, sigInfo, jar) { const keys = keysOf(tx); const i = keys.indexOf(jar); const pre = tx && tx.meta && tx.meta.preBalances ? tx.meta.preBalances[i] : null; const post = tx && tx.meta && tx.meta.postBalances ? tx.meta.postBalances[i] : null; const ixs = ((tx && tx.transaction && tx.transaction.message && tx.transaction.message.instructions) || []) .concat(((tx && tx.meta && tx.meta.innerInstructions) || []).reduce(function (a, x) { return a.concat(x.instructions || []); }, [])); const memos = []; const moves = []; for (const ix of ixs) { if (ix.program === 'spl-memo' || MEMO_IDS.indexOf(ix.programId) >= 0) memos.push(typeof ix.parsed === 'string' ? ix.parsed : ''); if (ix.program === 'system' && ix.parsed && ix.parsed.type === 'transfer') { const inf = ix.parsed.info; if (inf.source === jar || inf.destination === jar) moves.push({ from: inf.source, to: inf.destination, lamports: Number(inf.lamports) }); } } return { sig: sigInfo.signature, slot: sigInfo.slot, at: sigInfo.blockTime ? new Date(sigInfo.blockTime * 1000).toISOString() : null, ok: !sigInfo.err, delta: i >= 0 && pre !== null && post !== null ? post - pre : null, fee_payer: keys[0] || null, moves: moves, memos: memos.filter(Boolean) }; } async function chain(env) { const c = cfg(env); return cached('chain-' + c.jar, 15, async function () { const slot = await rpc(env, 'getSlot', [{ commitment: 'confirmed' }]); if (!c.jar) return { ok: false, reason: 'no jar' }; const sigs = await rpc(env, 'getSignaturesForAddress', [c.jar, { limit: 20, commitment: 'confirmed' }]); if (sigs.error) return { ok: false, reason: sigs.error, slot: slot.result || null }; const list = sigs.result || []; const txs = await Promise.all(list.slice(0, 12).map(function (s) { return rpc(env, 'getTransaction', [s.signature, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0, commitment: 'confirmed' }]); })); const rows = list.slice(0, 12).map(function (s, k) { return summarize(txs[k].result, s, c.jar); }); return { ok: true, jar: c.jar, slot: slot.result || null, count: list.length, txs: rows, at: new Date().toISOString() }; }); } // The raw transaction, for the in-browser verifier. Only transactions that touch the jar (not an open RPC proxy). async function txRaw(env, sig) { const c = cfg(env); return cached('tx-' + sig, 3600, async function () { const t = await rpc(env, 'getTransaction', [sig, { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0, commitment: 'confirmed' }]); if (t.error) return { ok: false, reason: t.error }; if (!t.result) return { ok: false, reason: 'not found (yet)' }; if (keysOf(t.result).indexOf(c.jar) < 0) return { ok: false, reason: 'not a jar transaction' }; return { ok: true, tx: t.result }; }); } // Fixed-window rate limit per IP, in memory per isolate (soft guard; the API is read-only and cached). const hits = new Map(); function limited(ip) { const now = Date.now(); const w = Math.floor(now / 10000); const k = ip + ':' + w; const n = (hits.get(k) || 0) + 1; hits.set(k, n); if (hits.size > 5000) hits.clear(); return n > 40; } export default { async fetch(request, env) { const url = new URL(request.url); if (url.hostname === 'www.savingforabody.com') { url.hostname = 'savingforabody.com'; return Response.redirect(url.toString(), 301); } if (!url.pathname.startsWith('/api/')) { return env.ASSETS.fetch(request); } if (request.method === 'OPTIONS') return new Response(null, { status: 204, headers: JSON_HEADERS }); if (request.method !== 'GET') return json({ error: 'method not allowed' }, 405); const ip = request.headers.get('cf-connecting-ip') || 'anon'; if (limited(ip)) return json({ error: 'slow down' }, 429, { 'retry-after': '10' }); if (url.pathname === '/api/config') return json(cfg(env), 200, { 'cache-control': 'public, max-age=15' }); if (url.pathname === '/api/state') return json(await state(env), 200, { 'cache-control': 'public, max-age=10' }); if (url.pathname === '/api/jar') { const c = cfg(env); const b = await jarBalance(env, c.jar); const p = await solPrice(); return json({ address: c.jar, ok: !!b.ok, sol: b.ok ? b.sol : null, sol_usd: p.ok ? p.usd : null }, 200, { 'cache-control': 'public, max-age=10' }); } if (url.pathname === '/api/chain') return json(await chain(env), 200, { 'cache-control': 'public, max-age=10' }); if (url.pathname.startsWith('/api/tx/')) { const sig = url.pathname.slice(8); if (!SIG.test(sig)) return json({ ok: false, reason: 'not a signature' }, 400); const t = await txRaw(env, sig); return json(t, t.ok ? 200 : 404, { 'cache-control': t.ok ? 'public, max-age=3600' : 'no-store' }); } if (url.pathname === '/api/receipts') return json({ ok: true, receipts: await rows(env, 'SELECT id, n, at, part_id, item, usd, file, sha256, pay_sig, pay_lamports, install_sig FROM receipts ORDER BY n', []) }, 200, { 'cache-control': 'public, max-age=30' }); if (url.pathname === '/api/health') return json({ ok: true, at: new Date().toISOString() }); return json({ error: 'not found' }, 404); } };