// Network conversions (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: nothing here touches sponsors, payouts, credits or // the chain. InstantAdPay reports sign-ups, wallet links and package purchases by accounts that arrived on a LinkSpin click // (op 'events' on /api/partner/conv, signed); LinkSpin counts them for the click's owner. // // - The ledger is DATA_DIR/netconv.jsonl: append-only, one write per event, so the two app copies of a deploy can both add // to it without rewriting each other (unlike the JSON stores that rewrite the whole file). Each copy re-reads it when its // size changes. // - Once: marks.claim is true for exactly one copy; a key already in the ledger is a dup, so a repeat after marks are pruned // is still refused. join and wallet count once per ROOT click (an ad click and the spin click it led to are one click), and // each purchase counts by its own key (tx + log index). A click belongs to the first account seen on it. // - Window: convtrack's rule, 30 days from the real click to the EVENT (not to delivery, so a retry queue never loses one). // - The click owner's own account, and own clicks, are kept as tests: in the ledger with self:1, never counted, no postback. // - Each row carries what the click was, so a later event still counts after the hit aged out of the rotator. // - Spin-link events are mirrored into rotator.conv (per-link counts, sources, Reports) and Banner Spin events into its // own conv; the mirror is replayed from the ledger on a timer, so a copy that lost a write during a deploy heals. 'use strict'; const fs = require('fs'); const path = require('path'); const crypto = require('crypto'); const EVENTS = ['join', 'wallet', 'purchase']; let FILE = null, C = null, R = null, B = null, P = null, M = null; let st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; const norm = e => String(e || '').trim().toLowerCase(); const DAY = 86400000; const acctHash = email => crypto.createHash('sha256').update('netconv|' + norm(email)).digest('hex').slice(0, 16); // never the address itself function init(o) { FILE = path.join(o.dataDir, 'netconv.jsonl'); C = o.convtrack; R = o.rotator; B = o.bannerspin || null; P = o.postbacks || null; M = o.marks; st = { size: -1, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; refresh(); if (!o.noTimers) { setTimeout(() => syncMirror().catch(() => {}), 30000).unref(); setInterval(() => syncMirror().catch(() => {}), 300000).unref(); } } function refresh() { let size = 0; try { size = fs.statSync(FILE).size; } catch (e) {} if (size === st.size) return st; const n = { size, rows: [], keys: new Set(), byClick: new Map(), byRoot: new Map() }; let raw = ''; try { raw = fs.readFileSync(FILE, 'utf8'); } catch (e) {} for (const line of raw.split('\n')) { if (!line) continue; let r; try { r = JSON.parse(line); } catch (e) { continue; } n.rows.push(r); n.keys.add(String(r.k).split('|')[0]); for (const [m, id] of [[n.byClick, r.click], [n.byRoot, r.root]]) { const a = m.get(id); if (a) a.push(r); else m.set(id, [r]); } } st = n; return st; } // the facts of a click, for one owner, as they stand now function factsOf(L, o) { const sp = L.spin, ad = L.ad, bs = L.bspin, mineSpin = !!(sp && sp.owner === o), mineAd = !!(ad && ad.owner === o); return { kind: mineSpin ? 'spin' : (mineAd ? ad.k : (bs ? 'bspin' : (ad ? ad.k : 'spin'))), camp: mineAd ? ad.camp : undefined, cname: mineAd ? ad.cname : undefined, rot: mineSpin ? sp.rotation.id : undefined, rcode: mineSpin ? sp.rotation.code : undefined, rname: mineSpin ? sp.rotation.name : undefined, d: mineSpin ? sp.hit.d : undefined, sr: mineSpin ? (sp.hit.sr || undefined) : undefined, bcode: bs ? bs.spin.code : undefined, src: (sp ? sp.hit.s : (bs ? (bs.click.h || 'direct') : (ad ? ad.pl : ''))) || '', c: (sp ? sp.hit.c : (bs ? bs.click.c : ad && ad.c)) || '', dv: (sp ? sp.hit.dv : (bs ? bs.click.dv : ad && ad.dv)) || '', q: (sp ? sp.hit.q : (bs ? bs.click.q : undefined)) || undefined }; } // e: { k, ev, click, email, value, ts, tx, sk }. Returns { result }: counted | self | dup | other | expired | nomatch | bad. // Every one of those is final: the sender stops retrying on any answer. async function record(e) { const ev = String(e && e.ev || ''), k = String(e && e.k || '').slice(0, 120), click = String(e && e.click || ''); const email = norm(e && e.email); if (!EVENTS.includes(ev) || !k || !C.isClickId(click) || !email || email.length > 190) return { result: 'bad' }; let S = refresh(); if (S.keys.has(k)) return { result: 'dup' }; const now = Date.now(); const at = Math.min(Number(e.ts) || now, now); const L = C.lookup(click); const prior = S.byClick.get(click) || null; if (!L && !prior) return { result: 'nomatch' }; const root = prior ? prior[0].root : L.root; const clickTs = prior ? prior[0].clickTs : L.ts; if (at - clickTs > C.WINDOW_MS) return { result: 'expired' }; const acct = acctHash(email); const seen = S.byRoot.get(root) || []; if (seen.length && seen[0].acct !== acct) return { result: 'other' }; // one click, one person: the first account on it if (ev !== 'purchase' && seen.some(r => r.ev === ev)) return { result: 'dup' }; if (!(await M.claim('net:' + (ev === 'purchase' ? k : root + ':' + ev)))) return { result: 'dup' }; const owners = L ? [...new Set(L.owners)] : [...new Set((prior || []).map(r => r.owner))]; const value = ev === 'purchase' ? C.cleanValue(e.value) : 0; const sk = /^s:[a-f0-9]{20}$/.test(String(e.sk || '')) ? String(e.sk) : ''; const tx = String(e.tx || '').slice(0, 80) || undefined; const rows = owners.map(o => { const was = (prior || []).find(r => r.owner === o); const f = L ? factsOf(L, o) : { kind: was.kind, camp: was.camp, cname: was.cname, rot: was.rot, rcode: was.rcode, rname: was.rname, d: was.d, sr: was.sr, bcode: was.bcode, src: was.src, c: was.c, dv: was.dv, q: was.q }; const self = email === o || !!(was && was.self) || seen.some(r => r.owner === o && r.self) || (L ? C.selfFor(L, o, sk) : false); const row = Object.assign({ k: owners.length > 1 ? k + '|' + o : k, ev, ts: at, rec: now, value, acct, click, root, clickTs, owner: o, tx, self: self ? 1 : undefined }, f); for (const x of Object.keys(row)) if (row[x] === undefined) delete row[x]; return row; }); fs.appendFileSync(FILE, rows.map(r => JSON.stringify(r) + '\n').join('')); // one write: the whole event lands or none of it refresh(); let counted = false; for (const r of rows) { if (r.self) continue; counted = true; await mirror(r).catch(err => console.error('netconv mirror', err.message)); if (P) P.fire(r.owner, ev, { q: r.q || {}, source: r.src, country: r.c, device: r.dv, lsid: click, code: r.rcode || r.bcode || '', sourceId: r.sr || '', payout: value, currency: 'USD', txid: tx || '', label: ev }).catch(err => console.error('netconv postback', err.message)); } return { result: counted ? 'counted' : 'self' }; } // LinkSpin's own sign-ups, wallets and purchases that arrived on an ad click (a / i ids): the rotator cannot see those clicks async function fromLinkSpin(lsid, ev, facts) { const f = facts || {}; if (!EVENTS.includes(ev) || f.key || !f.email) return null; const k = 'ls:' + ev + ':' + (ev === 'purchase' ? (f.txid || crypto.randomBytes(6).toString('hex')) : acctHash(f.email)); await record({ k, ev, click: lsid, email: f.email, value: f.payout, ts: Date.now(), tx: f.txid }); return null; } async function mirror(r) { const key = r.k.split('|')[0]; if (r.rot) return R.convert(r.click, r.ev, { payout: r.value, label: r.ev === 'purchase' ? 'InstantAdPay' : undefined, key, ts: r.ts, bound: { r: r.rot, d: r.d, sr: r.sr } }); if (r.kind === 'bspin' && r.click[0] === 'k') return R.convert(r.click, r.ev, { payout: r.value, key, ts: r.ts }); return null; } async function syncMirror() { for (const r of refresh().rows) if (!r.self && r.rot) await mirror(r).catch(() => {}); } const mineSince = (o, since) => refresh().rows.filter(r => r.owner === o && r.ts >= since); const ORDER = ['join', 'lead', 'wallet', 'purchase', 'external']; // Reports > Conversions: everything once. Rows mirrored into the rotator are read from the rotator (which also holds // LinkSpin's own joins, wallets, purchases, leads and partner postbacks), the ledger adds only what the rotator cannot // hold (ad clicks, Banner Spin clicks), Banner Spin's own rows add its site events, goals come from the pixel. function unified(owner, days) { const o = norm(owner); const since = Date.now() - Math.max(1, Number(days) || 30) * DAY; const m = {}; const buyers = new Set(); const add = (k, v) => { const x = m[k] = m[k] || { k, n: 0, value: 0 }; x.n++; x.value += Number(v) || 0; }; for (const c of R.convRows(o, since)) { add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); } if (B && B.convRows) for (const c of B.convRows(o, since)) { if (c.key) continue; add(c.ev, c.value); if (c.ev === 'purchase') buyers.add(c.lsid); } for (const r of mineSince(o, since)) { if (r.self || r.rot) continue; add(r.ev, r.value); if (r.ev === 'purchase') buyers.add(r.root); } const goals = {}; for (const c of C.goalRowsOf(o, since)) { const g = goals[c.goal] = goals[c.goal] || { k: 'goal:' + c.goal, n: 0, value: 0 }; g.n++; g.value += c.value || 0; } const rows = ORDER.filter(k => m[k]).map(k => m[k]).concat(Object.keys(m).filter(k => !ORDER.includes(k)).map(k => m[k]), Object.values(goals).sort((a, b) => b.n - a.n)).map(x => Object.assign(x, { value: Math.round(x.value * 100) / 100 })); return { rows, joins: (m.join || {}).n || 0, wallets: (m.wallet || {}).n || 0, purchases: (m.purchase || {}).n || 0, buyers: buyers.size, goals: Object.values(goals).reduce((n, g) => n + g.n, 0) }; } // InstantAdPay's Campaigns card: the same rows, and the events on each of the member's InstantAdPay ad campaigns function partner(owner, days) { const o = norm(owner); const d = Math.max(1, Math.min(90, Number(days) || 30)); const since = Date.now() - d * DAY; const byCampaign = {}; for (const r of mineSince(o, since)) { if (r.self || r.kind !== 'iap' || !r.camp) continue; const b = byCampaign[r.camp] = byCampaign[r.camp] || { join: 0, wallet: 0, purchase: 0, value: 0 }; b[r.ev]++; b.value = Math.round((b.value + (r.value || 0)) * 100) / 100; } const selfEvents = mineSince(o, since).filter(r => r.self).length; return { rows: unified(o, d).rows, byCampaign, selfEvents, days: d }; } function adminCounts() { const a = refresh().rows; return { rows: a.length, counted: a.filter(r => !r.self).length }; } module.exports = { init, record, fromLinkSpin, unified, partner, syncMirror, adminCounts, EVENTS };