// Conversion linkage end to end (2026-11-07, reporting only). Boots a local InstantAdPay AND a local LinkSpin on throwaway data dirs // (JSON stores, no DATABASE_URL, no mail key), pointed only at each other with a throwaway secret, and a mock Polygon RPC, so a real // Purchase log goes through the real chain.js and the real event fan-out. Nothing touches production or a real member. // node qa/netconv.test.mjs (or bash qa/run.sh netconv). Needs the LinkSpin repo beside this one (LS_SITE to override). // The funnel: spin link -> /join?lsclk -> cookie -> sign-up -> join counted on LinkSpin; wallet link signed with a throwaway key -> // wallet counted; Purchase on the mock chain, before member_id is stored -> purchase counted with its USD value, once, even when the // mock serves the log to a second scan; Reports and the Campaigns card show them. Sponsor stays exactly what the join link set. // Also: the page's own copy of the click (no cookie), own account not counted, LinkSpin down blocks nothing and the rows arrive later, // duplicate delivery. Part 2: lsreport.js against a fake SQL layer, two app copies racing the same events. import { spawn } from 'node:child_process'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; import http from 'node:http'; import crypto from 'node:crypto'; import { createRequire } from 'node:module'; import { fileURLToPath } from 'node:url'; const require = createRequire(import.meta.url); const HERE = path.dirname(fileURLToPath(import.meta.url)); const IAP_SITE = path.join(HERE, '..'); const LS_SITE = process.env.LS_SITE || path.join(IAP_SITE, '..', '..', 'linkspin', 'site'); const SECRET = 'qa-netconv-' + crypto.randomBytes(24).toString('hex'); const P = Number(process.env.NC_PORT || 8861), IAP = 'http://127.0.0.1:' + P, LS = 'http://127.0.0.1:' + (P + 1), RPC_PORT = P + 2; const sleep = ms => new Promise(r => setTimeout(r, ms)); let pass = 0, fail = 0; const ok = (c, name, extra) => { if (c) pass++; else fail++; console.log((c ? 'PASS ' : 'FAIL ') + name + (!c && extra !== undefined ? ' :: ' + (typeof extra === 'string' ? extra : JSON.stringify(extra)) : '')); }; async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 20000)) { try { const v = await fn(); if (v) return v; } catch (e) {} await sleep(500); } return null; } const hex = n => '0x' + BigInt(n).toString(16); const w = n => BigInt(n).toString(16).padStart(64, '0'); // ---- mock RPC ---- const rpc = { block: 1000, logs: [], memberAcct: {} }; const PUR = '0x11dc109cafd0f24c81621f745383ec82be7f2947c650355791e27b56ac83bc8c'; const purchaseLog = (block, buyerId, cents, tx, li) => ({ address: '0x07786E664AAfc0641eEB5297766935763dbA2288', topics: [PUR, '0x' + w(buyerId), '0x' + w(1)], data: '0x' + w(1000000000000000000n) + w(cents) + w(0) + w(500), blockNumber: hex(block), transactionHash: tx, logIndex: hex(li) }); const rpcSrv = http.createServer((q, s) => { let d = ''; q.on('data', c => d += c); q.on('end', () => { const b = JSON.parse(d || '{}'); let result = null; if (b.method === 'eth_blockNumber') result = hex(rpc.block); else if (b.method === 'eth_getLogs') { const f = parseInt(b.params[0].fromBlock, 16), t = parseInt(b.params[0].toBlock, 16); result = rpc.logs.filter(l => { const n = parseInt(l.blockNumber, 16); return n >= f && n <= t; }); } else if (b.method === 'eth_call') { const data = b.params[0].data; if (data.startsWith('0x5f59bb40')) { const id = Number(BigInt('0x' + data.slice(10))); const a = rpc.memberAcct[id]; result = '0x' + w(a ? BigInt(a) : 0) + w(0) + w(0) + w(a ? 1 : 0) + w(0); } else result = '0x' + w(0).repeat(10); } else result = '0x0'; s.writeHead(200, { 'Content-Type': 'application/json' }); s.end(JSON.stringify({ jsonrpc: '2.0', id: b.id, result })); }); }).listen(RPC_PORT, '127.0.0.1'); // ---- two sites ---- const now = Date.now(); const acct = (email, username, o) => Object.assign({ email, pass: null, sponsorRef: '', code: ('c' + username).slice(0, 7), username, address: null, created: now - 20 * 86400000, lastSeen: now - 3600000, memberId: 0 }, o || {}); function seed(dir, list) { fs.mkdirSync(path.join(dir, 'uploads'), { recursive: true }); const db = { v: 2, byEmail: {}, byAddress: {}, byCode: {}, joins: 0, positions: {} }; for (const a of list) { db.byEmail[a.email] = a; db.byCode[a.code] = a.email; } fs.writeFileSync(path.join(dir, 'accounts.json'), JSON.stringify(db)); } const iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-iap-')), lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nc-ls-')); const OWNER = 'orlando@qa.test'; seed(iapDir, [acct(OWNER, 'qaorlando', { memberId: 2 })]); seed(lsDir, [acct(OWNER, 'qaorlando', { memberId: 2 })]); fs.writeFileSync(path.join(iapDir, 'config.json'), JSON.stringify({ rpcs: ['https://127.0.0.1'], deployBlock: 990, telegramBotToken: '', adminEmail: 'admin@qa.test' })); const env = (port, dir, extra) => { const e = {}; for (const k of ['PATH', 'Path', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'USERPROFILE', 'HOME', 'APPDATA', 'LOCALAPPDATA', 'COMSPEC', 'windir']) if (process.env[k]) e[k] = process.env[k]; return Object.assign(e, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', LS_SYNC_SECRET: SECRET }, extra); }; const OUT = path.join(IAP_SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true }); const procs = []; function boot(site, port, dir, extra, log, args) { const fd = fs.openSync(log, 'a'); const p = spawn(process.execPath, (args || []).concat(['server.js']), { cwd: site, env: env(port, dir, extra), stdio: ['ignore', fd, fd] }); procs.push(p); return p; } const bootLs = () => boot(LS_SITE, P + 1, lsDir, { IAP_URL: IAP, SITE_HOST: '127.0.0.1:' + (P + 1) }, path.join(OUT, 'netconv-ls.log')); async function up(url) { for (let i = 0; i < 50; i++) { try { const r = await fetch(url + '/api/config', { signal: AbortSignal.timeout(2000) }); if (r.status < 500) return true; } catch (e) {} await sleep(500); } return false; } // a client with its own cookie jar and its own address, so the sign-up guards see separate people let ipN = 10; function client() { const jar = new Map(), ip = '198.51.100.' + (ipN++); const call = async (url, o) => { o = o || {}; const headers = Object.assign({ 'X-Forwarded-For': ip, 'User-Agent': 'Mozilla/5.0 NetconvQA ' + ip }, o.body ? { 'Content-Type': 'application/json' } : {}, jar.size ? { Cookie: [...jar].map(([k, v]) => k + '=' + v).join('; ') } : {}); const r = await fetch(url, { method: o.body ? 'POST' : 'GET', headers, body: o.body ? JSON.stringify(o.body) : undefined, redirect: 'manual' }); for (const c of r.headers.getSetCookie()) { const m = /^([^=]+)=([^;]*)/.exec(c); if (m) { if (/Max-Age=0/i.test(c) || m[2] === '') jar.delete(m[1]); else jar.set(m[1], m[2]); } } const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {} return { status: r.status, j, txt, headers: r.headers }; }; return { call, jar, ip }; } async function signUp(c, base, email, extra) { const st = await c.call(base + '/api/auth/email/start', { body: Object.assign({ email, fts: Date.now() - 8000, fage: 8000 }, extra || {}) }); if (!st.j || !st.j.devCode) throw new Error('no devCode: ' + st.txt.slice(0, 200)); return c.call(base + '/api/auth/email/verify', { body: Object.assign({ email, code: st.j.devCode }, extra || {}) }); } const accountRow = async email => { const r = await fetch(IAP + '/api/admin/member?email=' + encodeURIComponent(email), { headers: { Authorization: 'Bearer localtest' } }); return r.json().catch(() => null); }; const ledger = () => { try { return fs.readFileSync(path.join(lsDir, 'netconv.jsonl'), 'utf8').trim().split('\n').filter(Boolean).map(l => JSON.parse(l)); } catch (e) { return []; } }; const iapState = () => { try { return JSON.parse(fs.readFileSync(path.join(iapDir, 'lsreport.json'), 'utf8')); } catch (e) { return { clicks: {}, events: [] }; } }; async function signed(pth, body) { const raw = JSON.stringify(body); const ts = String(Date.now()); const sig = crypto.createHmac('sha256', SECRET).update(ts + '\n' + raw).digest('hex'); const r = await fetch(LS + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw }); return r.json(); } let lsProc = null; try { boot(IAP_SITE, P, iapDir, { LS_URL: LS, QA_RPC_PORT: String(RPC_PORT) }, path.join(OUT, 'netconv-iap.log'), ['--require', path.join(HERE, 'netconv-rpc-preload.cjs')]); lsProc = bootLs(); ok(await up(IAP), 'local InstantAdPay up'); ok(await up(LS), 'local LinkSpin up'); // the owner's spin link, pointed straight at the join page, no goal set up const own = client(); const so = await signUp(own, LS, OWNER); ok(so.status === 200, 'owner signed in on LinkSpin', so.txt.slice(0, 160)); const rot = (await own.call(LS + '/api/my/rotations', { body: { name: 'Bridge spin' } })).j.rotation; await own.call(LS + '/api/my/rotations/' + rot.id + '/dest', { body: { url: 'https://instantadpay.com/join/qaorlando', weight: 1 } }); const clickFor = async c => { const r = await c.call(LS + '/r/' + rot.code); const loc = r.headers.get('location'); return new URL(loc).searchParams.get('lsclk'); }; // 1 sign-up with the cookie const v1 = client(); const id1 = await clickFor(v1); ok(/^[a-f0-9]{10}$/.test(id1 || ''), 'the spin link hands the visitor a click id', id1); const land = await v1.call(IAP + '/join/qaorlando?lsclk=' + id1); ok(land.status === 200 && v1.jar.get('iap.lsclk') === id1, 'arrival keeps the click in a first-party cookie', [...v1.jar.keys()]); ok(v1.jar.get('iap.sponsor') === 'qaorlando', 'the sponsor cookie still lands beside it'); const r1 = await signUp(v1, IAP, 'lead1@qa.test'); ok(r1.status === 200 && r1.j.created, 'sign-up works', r1.txt.slice(0, 160)); ok(r1.j.account.sponsorRef === 'qaorlando', "the sponsor is the join link's, exactly", r1.j.account.sponsorRef); ok(iapState().clicks['lead1@qa.test'] && iapState().clicks['lead1@qa.test'].click === id1 || await waitFor(() => (iapState().clicks['lead1@qa.test'] || {}).click === id1, 3000), 'the click is on the account'); ok(await waitFor(() => ledger().find(r => r.ev === 'join' && r.owner === OWNER && r.click === id1), 15000), 'LinkSpin counted the join for the click owner'); // 2 the control: no click, same sponsor path, nothing reported const v0 = client(); await v0.call(IAP + '/join/qaorlando'); const r0 = await signUp(v0, IAP, 'plain@qa.test'); ok(r0.j.account.sponsorRef === 'qaorlando', 'a sign-up with no click gets the same sponsor'); await sleep(1000); ok(!iapState().clicks['plain@qa.test'], 'and nothing is kept or reported for it'); // 3 wallet link, signed with a throwaway key const { Wallet } = require(path.join(IAP_SITE, 'node_modules', 'ethers')); const wlt = Wallet.createRandom(); const addr = wlt.address; const ch = await v1.call(IAP + '/api/auth/challenge', { body: { address: addr } }); const vf = await v1.call(IAP + '/api/auth/verify', { body: { address: addr, signature: await wlt.signMessage(ch.j.message) } }); ok(vf.status === 200 && vf.j.linked, 'wallet linked', vf.txt.slice(0, 200)); ok(await waitFor(() => ledger().find(r => r.ev === 'wallet' && r.click === id1), 15000), 'LinkSpin counted the wallet'); // 4 a Purchase log on the mock chain, member_id not stored yet: the buyer is found through the contract's wallet for that id rpc.memberAcct[900] = addr; const TX = '0x' + 'ab'.repeat(32); rpc.logs.push(purchaseLog(1001, 900, 2000, TX, 3)); rpc.block = 1002; ok(await waitFor(() => ledger().find(r => r.ev === 'purchase' && r.tx === TX), 45000), 'a real Purchase event reached LinkSpin'); const pr = ledger().find(r => r.ev === 'purchase' && r.tx === TX); ok(pr && pr.value === 20, 'value = the USD price on the chain event ($20.00)', pr && pr.value); ok(pr && pr.owner === OWNER && pr.rot === rot.id, 'counted on the link and its owner'); // the same event a second time on its way to LinkSpin, plus a second package const k = pr.k; const dupd = await signed('/api/partner/conv', { op: 'events', events: [{ k, ev: 'purchase', click: id1, email: 'lead1@qa.test', value: 20, ts: Date.now() }] }); ok(dupd.results[0].result === 'dup', 'the same purchase delivered again is a dup', dupd); const TX2 = '0x' + 'cd'.repeat(32); rpc.logs.push(purchaseLog(1003, 900, 500, TX2, 1)); rpc.block = 1004; ok(await waitFor(() => ledger().find(r => r.tx === TX2), 45000), 'a second package counts on its own'); ok(await waitFor(() => (iapState().events || []).filter(r => r.ev === 'purchase').length === 2, 4000), 'two purchase rows on InstantAdPay', iapState().events); // a purchase by someone with no click reports nothing const v9 = client(); await signUp(v9, IAP, 'other@qa.test'); const w9 = Wallet.createRandom(); const c9 = await v9.call(IAP + '/api/auth/challenge', { body: { address: w9.address } }); await v9.call(IAP + '/api/auth/verify', { body: { address: w9.address, signature: await w9.signMessage(c9.j.message) } }); rpc.memberAcct[901] = w9.address; rpc.logs.push(purchaseLog(1005, 901, 5000, '0x' + 'ef'.repeat(32), 1)); rpc.block = 1006; await waitFor(() => JSON.parse(fs.readFileSync(path.join(iapDir, 'chain-index.json'), 'utf8')).lastBlock >= 1006, 45000); await sleep(1500); ok(!ledger().some(r => r.value === 50), 'a buyer with no click reports nothing'); // 5 the page's own copy of the click: no cookie reached the server const v2 = client(); const id2 = await clickFor(v2); const r2 = await signUp(v2, IAP, 'lead2@qa.test', { ref: 'qaorlando', lsclk: id2 }); ok(r2.j.created && v2.jar.get('iap.lsclk') === undefined, 'sign-up with no cookie, the page sent its own copy'); ok(await waitFor(() => ledger().find(r => r.ev === 'join' && r.click === id2), 15000), 'the join still counts'); // code requested in one browser, finished in another const v3a = client(), v3b = client(); const id3 = await clickFor(v3a); const s3 = await v3a.call(IAP + '/api/auth/email/start', { body: { email: 'lead3@qa.test', fts: Date.now() - 8000, ref: 'qaorlando', lsclk: id3 } }); await sleep(400); const f3 = await v3b.call(IAP + '/api/auth/email/verify', { body: { email: 'lead3@qa.test', code: s3.j.devCode } }); ok(f3.j.created, 'code finished in a second browser'); ok(await waitFor(() => ledger().find(r => r.ev === 'join' && r.click === id3), 15000), 'the click travelled with the email'); // a bad click id is ignored everywhere const v4 = client(); await v4.call(IAP + '/join/qaorlando?lsclk=../evil'); ok(!v4.jar.has('iap.lsclk'), 'a malformed click id sets nothing'); // lsid and non-join pages const v5 = client(); await v5.call(IAP + '/?lsid=abcdef0123'); ok(v5.jar.get('iap.lsclk') === 'abcdef0123', 'lsid on any page is kept too'); // 6 the owner's own account const v6 = client(); const id6 = await clickFor(v6); await v6.call(IAP + '/join/qaorlando?lsclk=' + id6); const claim = await signUp(v6, IAP, 'orlando2@qa.test'); ok(claim.j.created, 'control account'); // (the seeded owner already has an account: an existing sign-in binds nothing) const v7 = client(); const id7 = await clickFor(v7); await v7.call(IAP + '/join/qaorlando?lsclk=' + id7); await signUp(v7, IAP, OWNER); await sleep(800); ok(!iapState().clicks[OWNER] || !iapState().clicks[OWNER].bound, 'an existing account signing in binds no click'); const self = await signed('/api/partner/conv', { op: 'events', events: [{ k: 'join:selfcheck', ev: 'join', click: id7, email: OWNER, ts: Date.now() }] }); ok(self.results[0].result === 'self', "LinkSpin keeps the owner's own account as a test", self); // 7 Reports and the Campaigns card await waitFor(() => ledger().filter(r => r.ev === 'join').length >= 5, 8000); const rep = (await own.call(LS + '/api/my/reports?days=30')).j; const row = k2 => (rep.conversions || []).find(x => x.k === k2) || { n: 0, value: 0 }; const joins = ledger().filter(r => r.ev === 'join' && !r.self && r.owner === OWNER).length; ok(row('join').n === joins && row('purchase').n === 2 && row('purchase').value === 25 && row('wallet').n === 1, 'Reports > Conversions: every join, 1 wallet, 2 purchases $25.00', rep.conversions); ok(rep.totals.joins === joins && rep.totals.purchases === 1 && rep.totals.purchaseCount === 2, 'the tiles follow (1 buyer, 2 purchases)', rep.totals); ok(rep.top[0].conv === joins + 3, 'Top links Conv. counts the same events', rep.top[0]); const card = (await signUp(client(), IAP, OWNER)); const ownerIap = client(); await signUp(ownerIap, IAP, OWNER); const cv = (await ownerIap.call(IAP + '/api/my/conversions?fresh=1')).j; ok(cv && cv.ok && cv.network && (cv.network.rows.find(x => x.k === 'purchase') || {}).value === 25, 'InstantAdPay Campaigns card gets the same rows', cv && cv.network); // the two screens themselves, in a browser const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; if (fs.existsSync(PW)) { const pw = require(PW); const br = await pw.chromium.launch(); const open = async (jar, base, url) => { const ctx = await br.newContext({ viewport: { width: 1280, height: 900 } }); await ctx.addCookies([...jar].map(([name, value]) => ({ name, value, url: base }))); const p = await ctx.newPage(); const errs = []; p.on('pageerror', e => errs.push(e.message)); await p.goto(base + url, { waitUntil: 'domcontentloaded' }); return { p, errs }; }; const a = await open(own.jar, LS, '/reports'); await a.p.waitForFunction(() => /Purchases/.test((document.getElementById('convRows') || {}).textContent || ''), null, { timeout: 15000 }).catch(() => {}); const txt = await a.p.$eval('#convRows', e => e.textContent).catch(() => ''); ok(/Joins/.test(txt) && /Wallets/.test(txt) && /Purchases \u00b7 \$25\.00/.test(txt), 'LinkSpin Reports shows Joins, Wallets and Purchases with the value', txt); ok(a.errs.length === 0, 'no script errors on Reports', a.errs); await a.p.screenshot({ path: path.join(OUT, 'netconv-reports.png'), fullPage: false }); const b = await open(ownerIap.jar, IAP, '/my#campaigns'); await b.p.waitForFunction(() => { const e = document.getElementById('convNet'); return e && !e.hidden; }, null, { timeout: 20000 }).catch(() => {}); const nt = await b.p.$eval('#convNet', e => e.textContent).catch(() => ''); ok(/purchases \(\$25\.00\)/.test(nt), 'InstantAdPay Conversion tracking card shows the events', nt); ok(b.errs.length === 0, 'no script errors on Campaigns', b.errs); await br.close(); } else console.log('SKIP the two screens (no Playwright at ' + PW + ')'); // 8 LinkSpin down blocks nothing, rows arrive later lsProc.kill(); await sleep(600); const v8 = client(); await v8.call(IAP + "/join/qaorlando?lsclk=" + id1); const t0 = Date.now(); const r8 = await signUp(v8, IAP, 'whiledown@qa.test'); const ms = Date.now() - t0; ok(r8.status === 200 && r8.j.created, 'sign-up works with LinkSpin down'); ok(ms < 4000, 'and is not slowed by it', ms + ' ms'); ok(await waitFor(() => (iapState().events || []).find(r => r.email === 'whiledown@qa.test' && !r.pushed), 4000), 'the join waits in the queue'); const before = ledger().length; lsProc = bootLs(); ok(await up(LS), 'LinkSpin back'); ok(await waitFor(() => (iapState().events || []).find(r => r.email === 'whiledown@qa.test' && r.pushed), 60000), 'the queue delivers it once LinkSpin is back', iapState().events.filter(r => r.email === 'whiledown@qa.test')); const last = (iapState().events || []).find(r => r.email === 'whiledown@qa.test'); ok(last && last.outcome === 'other', "and id1's click already belongs to the first account, so it is refused, not counted", last); ok(ledger().length === before, 'nothing added to the ledger for it'); } catch (e) { ok(false, 'crashed: ' + e.message, e.stack); } finally { for (const p of procs) { try { p.kill(); } catch (e) {} } rpcSrv.close(); } // ---- part 2: two app copies against one SQL layer ---- { const fake = () => { const clicks = new Map(), events = new Map(); const q = async (sql, a) => { await sleep(1 + Math.random() * 3); if (/^SELECT click_id/.test(sql)) { const r = clicks.get(a[0]); return r ? [{ click_id: r.click, ts: r.ts, bound: r.bound }] : []; } if (/^INSERT IGNORE INTO ls_account_clicks/.test(sql)) { if (clicks.has(a[0])) return { affectedRows: 0 }; clicks.set(a[0], { click: a[1], ts: a[2], bound: 0 }); return { affectedRows: 1 }; } if (/^INSERT INTO ls_account_clicks/.test(sql)) { const r = clicks.get(a[0]); if (r && r.bound) return { affectedRows: 0 }; clicks.set(a[0], { click: a[1], ts: a[2], bound: 0 }); return { affectedRows: 1 }; } if (/^UPDATE ls_account_clicks/.test(sql)) { const r = clicks.get(a[2]); if (!r || r.bound) return { affectedRows: 0 }; Object.assign(r, { click: a[0], ts: a[1], bound: 1 }); return { affectedRows: 1 }; } if (/^INSERT IGNORE INTO ls_events/.test(sql)) { if (events.has(a[0])) return { affectedRows: 0 }; events.set(a[0], { k: a[0], ev: a[1], email: a[2], click_id: a[3], cents: a[4], ev_ts: a[5], tx: a[6], sk: a[7], pushed: 0 }); return { affectedRows: 1 }; } if (/^SELECT k, ev/.test(sql)) return [...events.values()].filter(r => !r.pushed).slice(0, a[0]); if (/^UPDATE ls_events/.test(sql)) { const r = events.get(a[1]); if (r) { r.pushed = 1; r.outcome = a[0]; } return { affectedRows: 1 }; } return []; }; return { enabled: () => true, q, events, clicks }; }; process.env.LS_SYNC_SECRET = SECRET; process.env.LS_URL = 'http://127.0.0.1:' + (P + 5); const load = db => { for (const k of Object.keys(require.cache)) if (/[\\/](lsreport|lsconv)\.js$/.test(k)) delete require.cache[k]; const m = require(path.join(IAP_SITE, 'lsreport.js')); m.init({ db, dataDir: os.tmpdir(), noTimers: true }); return m; }; const db = fake(); const A = load(db), B = load(db); ok(A !== B, 'two copies of the module'); const bound = await Promise.all([A.signup('x@qa.test', 'abcdef0123'), B.signup('x@qa.test', 'abcdef0123')]); ok(bound.filter(Boolean).length === 1, 'two copies binding the same sign-up: one wins', bound); const ev = { type: 'Purchase', tx: '0x1', li: 4, priceCents: 500, ts: Date.now() }; const pu = await Promise.all([A.purchase(ev, 'x@qa.test'), B.purchase(ev, 'x@qa.test')]); ok(pu.filter(Boolean).length === 1, 'two copies queueing the same purchase: one row', pu); await Promise.all([A.wallet('x@qa.test'), B.wallet('x@qa.test')]); ok([...db.events.keys()].sort().join() === [...new Set([...db.events.keys()])].sort().join() && db.events.size === 3, 'three rows: join, purchase, wallet', [...db.events.keys()]); const got = []; const srv = http.createServer((q, s) => { let d = ''; q.on('data', c => d += c); q.on('end', () => { const b = JSON.parse(d); for (const e of b.events) got.push(e); s.writeHead(200, { 'Content-Type': 'application/json' }); s.end(JSON.stringify({ ok: true, results: b.events.map(e => ({ k: e.k, result: 'counted' })) })); }); }).listen(P + 5, '127.0.0.1'); await Promise.all([A.flush(), B.flush()]); ok(got.length >= 3 && new Set(got.map(e => e.k)).size === 3, 'both copies may send a row; every row has one key, LinkSpin dedupes on it', got.length); ok([...db.events.values()].every(r => r.pushed), 'all marked sent'); ok(got.find(e => e.ev === 'purchase').value === 5, 'the purchase value goes as dollars ($5.00)'); const late = { type: 'Purchase', tx: '0x2', li: 1, priceCents: 500, ts: Date.now() + 32 * 86400000 }; ok(!(await A.purchase(late, 'x@qa.test')), 'a purchase past the click window is not even queued'); ok(!(await A.purchase({ type: 'Purchase', tx: '0x3', li: 1, priceCents: 500, ts: Date.now() }, 'noclick@qa.test')), 'an account with no click queues nothing'); srv.close(); } console.log('\n' + pass + ' passed, ' + fail + ' failed'); process.exit(fail ? 1 : 0);