From 07cc1944e615190677c71c4062e2e33846b923bc Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 16:20:24 -0600 Subject: [PATCH] VBBShop hooks (inert until configured, nothing deployed): GET /api/my/voucher signs an EIP-712 sponsor voucher with KEEPER_KEY when the hub lookup names the member's network sponsor (new optional `sponsor` field; none or self = no voucher); shop.js watcher reads Purchase logs (CONTRACT_ADDRESS + CHAIN_RPC, confirmed blocks, 1,000-block ranges) and credits packs once per txHash:logIndex, dedupe marks saved in vbb.json with the credits; admin status shows the watcher, never the key. Packages page stays coming soon. Smoke 117/117 (fake chain + voucher checks) Co-Authored-By: Claude Opus 5.5 --- .env.example | 12 +++++-- config.js | 10 +++++- docker-compose.yml | 4 +++ qa/smoke.mjs | 70 +++++++++++++++++++++++++++++++----- server.js | 15 ++++++-- shop.js | 88 ++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 186 insertions(+), 13 deletions(-) create mode 100644 shop.js diff --git a/.env.example b/.env.example index e1f66ee..f64090a 100644 --- a/.env.example +++ b/.env.example @@ -1,4 +1,4 @@ -# Viral Banner Blitz app env (Coolify later). Never commit real values. v1 is off-chain: no contract, no payments. +# Viral Banner Blitz app env (Coolify later). Never commit real values. v1 takes no payments in the UI (packages: coming soon). DOCSTORE_URL= # mysql://user:pass@host:3306/vbb REQUIRED for any real launch (files are local prototype only) SITE_HOST=viralbannerblitz.com SESSION_SECRET= # random hex; default = generated into DATA_DIR/.secret @@ -15,7 +15,7 @@ FREE_CREDIT_CAP=7 # free credits bank up to this many MAX_QUEUED_PER_MEMBER=3 CREDIT_PACKS=10:3,40:10 # credits:usd, shown as coming soon LOOK_USD=2 # banner look, shown as coming soon -SPONSOR_PCT=30 # planned on-chain split (company gets the rest); not used in v1 +SPONSOR_PCT=30 # display only; the real split is fixed in VBBShop (sponsor 30, prize 10, company 60) PRIZE_PCT=10 # weekly prize pot = this % of the week's sales PRIZE_FLOOR_USD=20 # never less (company tops it up) PRIZE_CAP_USD=50 # never more (internal, not shown) @@ -23,3 +23,11 @@ PRIZE_PLACES=50,30,20 # % of each board's half, 1st/2nd/3rd LINK_PROBE=1 # 0 skips the target-link frame check (local tests only) CF_PROXIED=0 # 1 only if Cloudflare proxies the domain (then cf-connecting-ip is trusted) NETWORK_LOOKUP_URL= # default InstantAdPay /api/network/member; empty = off +# VBBShop (../contracts). All empty = inert. Vouchers need KEEPER_KEY + CONTRACT_ADDRESS; the watcher needs CONTRACT_ADDRESS + CHAIN_RPC. +CONTRACT_ADDRESS= # the deployed VBBShop (not deployed yet) +CHAIN_RPC= # server-side Polygon RPC for the purchase watcher +SHOP_START_BLOCK= # the deploy block; the first scan starts here +SHOP_CONFIRMATIONS=10 # credit only this many blocks behind the head +SHOP_POLL_MS=30000 +KEEPER_KEY= # private key of the contract's keeper (signs sponsor vouchers). Coolify secret only, never in git +VOUCHER_SECONDS=1800 # a voucher is good for 30 minutes diff --git a/config.js b/config.js index ac4bde2..3a1665f 100644 --- a/config.js +++ b/config.js @@ -1,5 +1,6 @@ // All runtime config comes from env (Coolify sets these). Read once. -// VBB v1 is off-chain: no contract, no payments. Planned prices are shown as "coming soon"; rewards are recorded, not credited yet. +// VBB v1 takes no payments in the UI: planned prices show as "coming soon"; rewards are recorded, not credited yet. The VBBShop +// contract hooks (shop.js: sponsor vouchers + purchase watcher) stay inert until CONTRACT_ADDRESS / CHAIN_RPC / KEEPER_KEY are set. const path = require('path'); let cfg = null; @@ -39,6 +40,13 @@ function get() { // Half the pot per leaderboard, split 50/30/20 across the top three. The cap is internal: the public page never shows it. prizePot: { pct: num(e.PRIZE_PCT, 10, 0, 100), floorUsd: num(e.PRIZE_FLOOR_USD, 20, 0, 100000), capUsd: num(e.PRIZE_CAP_USD, 50, 0, 100000), places: list(e.PRIZE_PLACES, '50,30,20').map(Number).filter(x => x >= 0) }, + // VBBShop (../contracts). KEEPER_KEY is read by shop.js only, never kept here. + contractAddress: /^0x[0-9a-fA-F]{40}$/.test(String(e.CONTRACT_ADDRESS || '').trim()) ? require('ethers').getAddress(String(e.CONTRACT_ADDRESS).trim()) : '', + chainRpc: String(e.CHAIN_RPC || '').trim(), // the watcher's RPC (server side); '' = watcher off + shopStartBlock: num(e.SHOP_START_BLOCK, 0, 0, 1e12), // the deploy block (first scan starts here) + shopConfirmations: num(e.SHOP_CONFIRMATIONS, 10, 0, 1000), // credit only this many blocks behind the head + shopPollMs: num(e.SHOP_POLL_MS, 30000, 200, 3600000), + voucherSeconds: num(e.VOUCHER_SECONDS, 1800, 60, 86400), // a sponsor voucher is good for 30 minutes linkProbe: e.LINK_PROBE !== '0', // check the target link answers and allows frames (off in the local smoke test) iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''), diff --git a/docker-compose.yml b/docker-compose.yml index e05a9d7..06d5117 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -12,6 +12,10 @@ services: ADMIN_TOKEN: ${ADMIN_TOKEN:-} NETWORK_SSO_SECRET: ${NETWORK_SSO_SECRET:-} WALLETCONNECT_PROJECT_ID: ${WALLETCONNECT_PROJECT_ID:-} + CONTRACT_ADDRESS: ${CONTRACT_ADDRESS:-} + CHAIN_RPC: ${CHAIN_RPC:-} + SHOP_START_BLOCK: ${SHOP_START_BLOCK:-} + KEEPER_KEY: ${KEEPER_KEY:-} volumes: - vbb-data:/app/data # uploads only once DOCSTORE_URL is set expose: diff --git a/qa/smoke.mjs b/qa/smoke.mjs index c1f2bf1..e49d761 100644 --- a/qa/smoke.mjs +++ b/qa/smoke.mjs @@ -1,8 +1,9 @@ // VBB local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out), // with a tiny loop (5 places, 3 visitors per shift) so shifts and cycles happen in seconds, then checks the splash, // verified visitors (bots, early, repeats, the per-IP cap), shifts + a cycle + the reward ledger, posting banners -// (upload, checks, credits), network sign-in, the leaderboard, the admin endpoint, a restart, and page renders. -// Nothing leaves this machine: the network lookup is off, the link probe is off, no real wallet, no money. +// (upload, checks, credits), network sign-in, the leaderboard, the admin endpoint, a restart, the VBBShop hooks (sponsor vouchers, +// purchase crediting from a fake chain), and page renders. +// Nothing leaves this machine: the network lookup and the chain are local stand-ins, the link probe is off, no real wallet, no money. // // node qa/smoke.mjs (Playwright renders too, if it is installed at PLAYWRIGHT) // SKIP_UI=1 node qa/smoke.mjs (HTTP checks only) @@ -23,12 +24,22 @@ const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_ const PORT = Number(process.env.SMOKE_APP_PORT || 3217), BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'); // stand-in for the network member lookup: wallets in NET are network members, everyone else is a stranger -const NET = new Set(); const LOOKUP_PORT = PORT + 1; +// NETSP: wallet -> that member's network sponsor wallet (the hub's `sponsor` field) +const NET = new Set(); const NETSP = new Map(); const LOOKUP_PORT = PORT + 1; require('node:http').createServer((q, r) => { const a = (new URL(q.url, 'http://x').searchParams.get('a') || '').toLowerCase(); - r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(NET.has(a) ? { address: a, username: 'net' + a.slice(2, 10) } : {})); }).listen(LOOKUP_PORT, '127.0.0.1').unref(); + r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(NET.has(a) ? { address: a, username: 'net' + a.slice(2, 10), sponsor: NETSP.get(a) || null } : {})); }).listen(LOOKUP_PORT, '127.0.0.1').unref(); +// stand-in Polygon JSON-RPC for the purchase watcher: CHAIN.logs are served by block range (or all of them when replayAll is on, +// like a flaky RPC re-sending old logs). Nothing here is a real chain. +const CHAIN = { head: 1, logs: [], replayAll: false }; const CHAIN_PORT = PORT + 2; +const SHOP = '0x00000000000000000000000000000000000B0B05', KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1 +require('node:http').createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; const j = JSON.parse(b || '{}'); let result = null; + if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16); + if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); } + r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result })); }).listen(CHAIN_PORT, '127.0.0.1').unref(); const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', LOOP_SIZE: '5', VISITORS_PER_SHIFT: '3', VIEWS_PER_CYCLE: '150', VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + (PORT + 1) + '/api/network/member', - NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid' }); + NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', + CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200' }); const sleep = ms => new Promise(r => setTimeout(r, ms)); let pass = 0, fail = 0; let srv = null; const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 400) : '')); } }; @@ -69,6 +80,7 @@ async function stop() { const p = srv; srv = null; if (!p) return; const done = // a signed-in member by wallet signature async function walletMember(o = {}) { const w = ethers.Wallet.createRandom(); const c = client(); if (!o.stranger) NET.add(w.address.toLowerCase()); + if (o.sponsor) NETSP.set(w.address.toLowerCase(), o.sponsor === 'self' ? w.address.toLowerCase() : o.sponsor.toLowerCase()); const ch = await c.json('/api/auth/challenge', { address: w.address }); const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) }); c.address = w.address.toLowerCase(); c.ok = v.ok === true && !!c.jar['vbb.sid']; @@ -246,9 +258,51 @@ async function main() { ok(safety.frameVerdict({}) === true && safety.frameVerdict({ 'x-frame-options': 'DENY' }) === false && safety.frameVerdict({ 'content-security-policy': "frame-ancestors 'self'" }) === false && safety.frameVerdict({ 'content-security-policy': 'frame-ancestors *' }) === true, 'frameVerdict reads X-Frame-Options and frame-ancestors'); ok(safety.privateIp('10.1.2.3') && safety.privateIp('127.0.0.1') && safety.privateIp('::1') && safety.privateIp('169.254.1.1') && !safety.privateIp('8.8.8.8'), 'private address check'); - // ---- 12. page renders (Playwright, if installed) ---- + console.log('12. VBBShop hooks: sponsor vouchers + purchase crediting (fake chain)'); + const shopUnit = require(path.join(APP, 'shop.js')); shopUnit.init({ contractAddress: '', chainRpc: '', chainId: 137 }); + ok(!shopUnit.watching() && !shopUnit.voucherOn(), 'without CONTRACT_ADDRESS / CHAIN_RPC the watcher is off; without the key, vouchers are off'); + const keeperAddr = new ethers.Wallet(KEEPER_PK).address; + const spW = ethers.Wallet.createRandom().address.toLowerCase(); + const V = await walletMember({ sponsor: spW }); + let vo = await V.json('/api/my/voucher'); + const vt = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] }; + const vdom = { name: 'VBBShop', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP) }; + ok(vo.voucher && vo.voucher.buyer.toLowerCase() === V.address && vo.voucher.sponsor.toLowerCase() === spW && vo.voucher.contract === ethers.getAddress(SHOP) && vo.voucher.chainId === 137, 'voucher names the member, their network sponsor, the contract and the chain', vo); + ok(vo.voucher && ethers.verifyTypedData(vdom, vt, { buyer: vo.voucher.buyer, sponsor: vo.voucher.sponsor, deadline: vo.voucher.deadline }, vo.voucher.sig) === keeperAddr, 'voucher is an EIP-712 signature by the keeper key'); + const nowS = Math.floor(Date.now() / 1000); + ok(vo.voucher && vo.voucher.deadline > nowS + 1700 && vo.voucher.deadline <= nowS + 1801, 'voucher is good for 30 minutes', vo.voucher && vo.voucher.deadline - nowS); + ok(!JSON.stringify(vo).includes(KEEPER_PK.slice(2, 12)), 'the key never appears in the answer'); + vo = await A.json('/api/my/voucher'); ok(vo._status === 200 && vo.voucher === null && vo.why === 'no-sponsor', 'no network sponsor known: no voucher', vo); + const SELF = await walletMember({ sponsor: 'self' }); vo = await SELF.json('/api/my/voucher'); ok(vo.voucher === null && vo.why === 'no-sponsor', 'the hub naming the member as their own sponsor: no voucher', vo); + vo = await X.json('/api/my/voucher'); ok(vo.voucher === null, 'a wallet the network does not know: no voucher', vo); + r = await anon.req('/api/my/voucher'); ok(r.status === 401, 'voucher needs sign-in'); + // a Purchase log for V: 2 x pack10 = 20 credits + const SHOP_IF = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']); + const mkLog = o => { const e = SHOP_IF.encodeEventLog('Purchase', [o.orderId, o.buyer, o.sku, o.qty, o.ref || 0, o.credits, o.usdCents, o.wei, o.sponsor || ethers.ZeroAddress, o.sponsorPaid || 0]); + return { address: o.address || SHOP, topics: e.topics, data: e.data, blockNumber: '0x' + o.block.toString(16), transactionHash: o.tx, logIndex: '0x' + o.logIndex.toString(16), removed: false }; }; + const credits0 = (await V.json('/api/my')).credits; + const tx1 = '0x' + 'ab'.repeat(32); + CHAIN.logs.push(mkLog({ orderId: 1, buyer: V.address, sku: 1, qty: 2, credits: 20, usdCents: 600, wei: 70000000000000000000n, sponsor: spW, sponsorPaid: 21000000000000000000n, block: 3, tx: tx1, logIndex: 4 })); + CHAIN.head = 5; await sleep(900); + my = await V.json('/api/my'); ok(my.credits === credits0 + 20, 'a Purchase event credits the pack (2 x 10 credits)', { before: credits0, after: my.credits }); + // the same log again: in a later block range, and re-sent on every poll + CHAIN.logs.push(Object.assign({}, CHAIN.logs[0], { blockNumber: '0x7' })); CHAIN.replayAll = true; CHAIN.head = 9; await sleep(900); + my = await V.json('/api/my'); ok(my.credits === credits0 + 20, 'the same txHash:logIndex delivered again credits nothing', my.credits); + // a log from another contract address is ignored; a second real order credits + CHAIN.logs.push(mkLog({ address: '0x000000000000000000000000000000000000dEaD', orderId: 9, buyer: V.address, sku: 2, qty: 1, credits: 40, usdCents: 1000, wei: 1n, block: 10, tx: '0x' + 'cd'.repeat(32), logIndex: 0 })); + CHAIN.logs.push(mkLog({ orderId: 2, buyer: V.address, sku: 2, qty: 1, credits: 40, usdCents: 1000, wei: 118000000000000000000n, sponsor: spW, sponsorPaid: 35400000000000000000n, block: 10, tx: tx1, logIndex: 9 })); + CHAIN.head = 12; await sleep(900); + my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'another contract log is ignored; a second order (same tx, other log index) credits 40', my.credits); + const ads = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN }); + ok(ads.shop && ads.shop.watching && ads.shop.vouchers && ads.shop.purchases === 2 && ads.shop.creditsSold === 60 && ads.shop.dupes >= 2 && ads.shop.lastBlock === 12 && ads.shop.keeper === keeperAddr && !JSON.stringify(ads).includes(KEEPER_PK.slice(2, 12)), 'admin sees the watcher: 2 purchases, 60 credits, duplicates skipped, no key', ads.shop); + // restart: the dedupe marks survive, the replaying RPC still credits nothing + await sleep(1200); await stop(); await boot(); await sleep(900); + my = await V.json('/api/my'); ok(my.credits === credits0 + 60, 'after a restart the replayed logs still credit nothing', my.credits); + const cfgNow = await (await fetch(BASE + '/api/config')).json(); ok(!JSON.stringify(cfgNow).toLowerCase().includes(SHOP.slice(2).toLowerCase()), 'public config does not offer the contract yet (packages stay coming soon)'); + + // ---- 13. page renders (Playwright, if installed) ---- if (!process.env.SKIP_UI && fs.existsSync(PW)) { - console.log('12. page renders (Playwright)'); + console.log('13. page renders (Playwright)'); const { chromium } = require(PW); const browser = await chromium.launch(); const errs = []; @@ -284,7 +338,7 @@ async function main() { } ok(errs.length === 0, 'no page errors', errs); await browser.close(); - } else console.log('12. page renders skipped (SKIP_UI or no Playwright at ' + PW + ')'); + } else console.log('13. page renders skipped (SKIP_UI or no Playwright at ' + PW + ')'); await stop(); console.log('\n' + pass + ' passed, ' + fail + ' failed'); diff --git a/server.js b/server.js index 904b1f7..4664138 100644 --- a/server.js +++ b/server.js @@ -1,5 +1,6 @@ // Viral Banner Blitz web app (viralbannerblitz.com rebuild, "VBB"). Plain Node http server, no framework (the InstantAdPay and // Downline Banners pattern). v1 is off-chain: no contract, no prices, no money. +// VBBShop hooks (shop.js): GET /api/my/voucher signs a sponsor voucher; the purchase watcher credits packs. Both inert until configured. // Pages: / (splash: the loop, the next-shift bar, the queue), /my (My Banners), /leaders, /how, /packages, /admin. // Engine: loop.js. Data: store.js on docstore.js (MySQL when DOCSTORE_URL is set). Checks: safety.js. Network sign-in: networksso.js. 'use strict'; @@ -17,6 +18,7 @@ const store = require('./store'); const loop = require('./loop'); const safety = require('./safety'); const networksso = require('./networksso'); +const shop = require('./shop'); const PUB = path.join(__dirname, 'public'); const UPL = path.join(C.dataDir, 'uploads'); @@ -89,7 +91,7 @@ async function netMember(q) { try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref(); const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a); const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json(); - if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username) }; } catch (e) { return null; } + if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), sponsor: ADDR_RE.test(j.sponsor || '') ? j.sponsor.toLowerCase() : null }; } catch (e) { return null; } netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear(); return m; } @@ -292,6 +294,14 @@ const server = http.createServer(async (req, res) => { const me = s.address; if (!store.member(me)) signedIn(me, { via: 'wallet' }); if (p === '/api/my' && req.method === 'GET') { await verifyNet(me); const m = store.member(me); const granted = grantDaily(m); m.lastSeen = Date.now(); return json(res, 200, Object.assign(myData(me), { grantedNow: granted })); } + // sponsor voucher for VBBShop.buy: only when the hub knows this member's network sponsor (a wallet that is not their own) + if (p === '/api/my/voucher' && req.method === 'GET') { + if (limited(req, 'voucher', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' }); + if (!shop.voucherOn()) return json(res, 200, { voucher: null, why: 'off' }); + const n = await netMember({ a: me }).catch(() => null); const sp = n && n.address === me ? n.sponsor : null; + if (!sp || sp === me) return json(res, 200, { voucher: null, why: 'no-sponsor' }); + return json(res, 200, { voucher: await shop.voucher(me, sp) }); + } if (p === '/api/my/upload' && req.method === 'POST') { if (limited(req, 'upload', 40, 3600000)) return json(res, 429, { error: 'Too many uploads this hour.' }); let buf; try { buf = await readRaw(req, safety.MAX_UPLOAD + 1); } catch (e) { return json(res, 400, { error: 'The file is over 100 KB.' }); } @@ -333,7 +343,7 @@ const server = http.createServer(async (req, res) => { queue: { length: S.queue.length, next: S.queue.slice(0, 20) }, progress: S.progress, held: S.progress >= C.perShift && !S.queue.length, today: { visits: t.visits || 0, shifts: t.shifts || 0, cycles: t.cycles || 0, posts: t.posts || 0, clicks: t.clicks || 0 }, totals: S.totals, ledger: { entries: L.length, views: L.reduce((x, e) => x + e.views, 0), viewsByStatus: byStatus, credited: 0 }, - members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, docstore: docstore.view() }); + members: store.members().length, banners: S.banners.length, visitsKept: store.visits().length, shop: shop.view(), docstore: docstore.view() }); } if (p === '/api/admin/ledger' && req.method === 'GET') { const n = Math.min(2000, Math.max(1, Number(u.searchParams.get('n')) || 200)); const L = store.ledger(); @@ -363,6 +373,7 @@ function saveUpload(owner, buf, ext) { store.load(); loop.init({ onCycle: (b, e) => console.log('cycle', 'banner #' + b.id, e.views + ' network views recorded') }); store.pruneVisits(); loop.rebuildIndex(); + shop.init(C); // inert without CONTRACT_ADDRESS + CHAIN_RPC (watcher) / KEEPER_KEY (vouchers) setInterval(() => { if (store.pruneVisits()) loop.rebuildIndex(); }, 3600000).unref(); server.listen(C.port, () => console.log('Viral Banner Blitz on :' + C.port + ' loop ' + C.loopSize + ', ' + C.perShift + ' visitors per shift, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)'))); })().catch(e => { console.error('start failed:', e.message); process.exit(1); }); diff --git a/shop.js b/shop.js new file mode 100644 index 0000000..6a7b44f --- /dev/null +++ b/shop.js @@ -0,0 +1,88 @@ +// On-chain purchases (VBBShop, ../contracts). Two jobs, each inert until it is configured: +// (a) sponsor vouchers: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Voucher(buyer, sponsor, deadline) for a +// signed-in member whose network sponsor the hub knows. The contract binds that sponsor on the member's first purchase. +// (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and credits the buyer +// once per txHash:logIndex. The dedupe mark and the credits live in the same document (vbb.json), so they save together. +// The key never enters config or any API answer. Packages stay "coming soon" in the UI until Marty says go. +'use strict'; +const { Wallet, Interface, getAddress } = require('ethers'); +const store = require('./store'); + +const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; +const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 credits, uint256 usdCents, uint256 weiPaid, address sponsor, uint256 sponsorPaid)']); +const TOPIC = IFACE.getEvent('Purchase').topicHash; +const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'sponsor', type: 'address' }, { name: 'deadline', type: 'uint256' }] }; +const st = { polls: 0, credited: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null }; +let C = null, keeper = null, busy = false, timer = null; + +function init(cfg) { + C = cfg; keeper = null; + const k = String(process.env.KEEPER_KEY || '').trim(); + if (k) { try { keeper = new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { console.error('shop: KEEPER_KEY is not a valid private key; vouchers off'); } } + if (timer) { clearTimeout(timer); timer = null; } + if (watching()) { console.log('shop: watching', C.contractAddress, 'for purchases'); tick(); } +} +const voucherOn = () => !!(C && keeper && C.contractAddress); +const watching = () => !!(C && C.contractAddress && C.chainRpc); +const domain = () => ({ name: 'VBBShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress }); + +// a voucher binding `sponsor` to `buyer`, or null (off, bad sponsor, self-sponsor) +async function voucher(buyer, sponsor) { + if (!voucherOn() || !ADDR_RE.test(buyer || '') || !ADDR_RE.test(sponsor || '')) return null; + const b = getAddress(buyer), s = getAddress(sponsor); if (b === s) return null; + const deadline = Math.floor(Date.now() / 1000) + C.voucherSeconds; + const sig = await keeper.signTypedData(domain(), TYPES, { buyer: b, sponsor: s, deadline }); + return { buyer: b, sponsor: s, deadline, sig, contract: C.contractAddress, chainId: C.chainId }; +} + +// credit one Purchase log. false = already credited (or not ours). +function apply(ev) { + const S = store.state(); const P = S.purchases || (S.purchases = {}); + const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; + if (P[key]) { st.dupes++; return false; } + const a = ev.buyer.toLowerCase(); const m = store.member(a) || store.upsertMember(a, { via: 'wallet' }); + let applied = 'credits'; + if (ev.credits > 0) m.credits += ev.credits; + else { const b = Number.isSafeInteger(Number(ev.ref)) ? store.banner(Number(ev.ref)) : null; if (b && b.owner === a) { b.look = true; store.saveBanner(b); applied = 'look'; } else applied = 'unmatched'; } + P[key] = { at: Date.now(), block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, credits: ev.credits, usdCents: ev.usdCents, + weiPaid: ev.weiPaid, sponsor: ev.sponsor, sponsorPaid: ev.sponsorPaid, applied }; + store.save(); st.credited++; + console.log('shop: order', ev.orderId, 'sku', ev.sku, 'x' + ev.qty, a, applied === 'credits' ? '+' + ev.credits + ' credits' : applied); + return true; +} +function decode(l) { + if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase() || (l.topics || [])[0] !== TOPIC) return null; + const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; + return { txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), orderId: Number(d.orderId), buyer: d.buyer, sku: Number(d.sku), + qty: Number(d.qty), ref: d.ref.toString(), credits: Number(d.credits), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), sponsor: d.sponsor.toLowerCase(), sponsorPaid: d.sponsorPaid.toString() }; +} + +async function rpc(method, params) { + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 10000); t.unref(); + try { const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: ac.signal })).json(); + if (j.error) throw new Error(method + ': ' + (j.error.message || JSON.stringify(j.error))); return j.result; } finally { clearTimeout(t); } +} +// confirmed blocks only, 1,000 blocks per getLogs (public RPC limits); the last scanned block is saved with the credits +async function poll() { + if (busy || !watching()) return; busy = true; st.polls++; + try { + const S = store.state(); const sh = S.shop || (S.shop = {}); + const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head; + if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 1; if (!C.shopStartBlock) console.log('shop: no SHOP_START_BLOCK, watching from block', head + 1); store.save(); } + while (sh.lastBlock < head) { + const from = sh.lastBlock + 1, to = Math.min(head, from + 999); + const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]); + for (const l of logs || []) { const ev = decode(l); if (ev) apply(ev); else st.ignored++; } + sh.lastBlock = to; store.save(); + } + } catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); } + finally { busy = false; } +} +function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); } + +function view() { + const P = (store.state() && store.state().purchases) || {}; const list = Object.values(P); + return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null, + lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, purchases: list.length, creditsSold: list.reduce((t, x) => t + (x.credits || 0), 0), unmatched: list.filter(x => x.applied === 'unmatched').length }, st); +} +module.exports = { init, voucher, voucherOn, watching, apply, poll, view, TOPIC, IFACE, TYPES };