Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Same design as InstantAdPay (shared sponsorfollow.js). Deliberate sponsor changes (tank adoption, rescue, release, adoption window ending, admin edit) are recorded and travel on the iapsync rows; InstantAdPay's deliberate changes are applied here only when the member is not bound or binding on the LinkSpin contract (memberId, wallet on chain, or an engine activation in flight), newer than our own, and both sides agreed before (or no sponsor here). Bound / diverged / race cases change nothing and are logged. Ordinary rows keep the fill-empty rule, except a sponsor emptied on purpose here is not refilled by an ordinary row. Carry: an InstantAdPay batch holds its members (carry.hold) so no auto-activation starts mid-batch; ensureOnChain waits, then re-reads the account so the contract binds the settled sponsor; wallets from a batch are linked after every sponsor decision; the wallet hook skips activation while a follow is pending and activates once it is settled. Registry keeps the follow record (loop guard) and a deliberate clear. Network tank, Admin > Members > Sponsor check and the partner endpoints as on InstantAdPay. Rows without the new facts hash as before (no resend on deploy). Tests: qa/sponsorfollow.test.cjs 27/27, qa/carry-hold.test.cjs ok, two-server e2e (in the InstantAdPay repo) 20/20, QA member walk 0 bugs. No sponsor was changed on production. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -43,6 +43,21 @@ const leaderboard = require('./leaderboard');
|
||||
const toolkit = require('./toolkit');
|
||||
const registry = require('./registry'); // network registry: who is who across properties (LinkSpin, 2026-09-15)
|
||||
const iapsync = require('./iapsync'); // reverse registry sync: LinkSpin-first members reach InstantAdPay (2026-10-15)
|
||||
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to InstantAdPay until chain-bound + one network tank (2026-10-22)
|
||||
let follow = null, followStore = null;
|
||||
const IAP_BASE = () => String(process.env.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||
let activationCache = { at: 0, map: null };
|
||||
function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor)
|
||||
if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map;
|
||||
const m = new Map(); for (const ev of chain.recentEvents(1e9)) if (ev.type === 'MemberActivated' && ev.account) { const k = String(ev.account).toLowerCase(); if (!m.has(k)) m.set(k, { id: ev.id, sponsorId: ev.sponsorId, block: ev.block, tx: ev.tx }); }
|
||||
activationCache = { at: Date.now(), map: m }; return m;
|
||||
}
|
||||
// signed partner body (registry sync secret, see sponsorfollow.verify): resolves { body } or { status, error }
|
||||
async function readPartnerSigned(req, maxBytes) {
|
||||
let raw; try { raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > maxBytes) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); }); } catch (e) { return { status: 413, error: 'too big' }; }
|
||||
const bad = SF.verify(raw, req.headers); if (bad) return bad;
|
||||
try { return { body: JSON.parse(raw || '{}') }; } catch (e) { return { status: 400, error: 'bad json' }; }
|
||||
}
|
||||
const helpdesk = require('./helpdesk'); // support: Help screen, /support, ticket link, chat hand-off, all on InstantAdPay's one desk (2026-10-16)
|
||||
const carry = require('./carry'); // sponsor carry-over: engine activation, claim window, notices
|
||||
const rotator = require('./rotator');
|
||||
@@ -601,12 +616,32 @@ async function boot() {
|
||||
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
|
||||
registry.init({ dataDir: DATA_DIR });
|
||||
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
|
||||
// payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first
|
||||
accounts.onWalletLinked(async email => { const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); });
|
||||
// sponsor follow (sponsorfollow.js): deliberate changes (tank adoption, rescue, release, window expiry, admin edit) are
|
||||
// recorded and follow to InstantAdPay, and InstantAdPay's are applied here, until the member is bound or binding on the
|
||||
// LinkSpin contract (memberId, wallet already on chain, or an engine activation in flight). Ordinary bindings: first platform.
|
||||
followStore = SF.create({ dataDir: DATA_DIR, platform: 'linkspin' });
|
||||
follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'instantadpay',
|
||||
isBound: async a => {
|
||||
if (Number(a.memberId) > 0) return { bound: true, why: 'LinkSpin member #' + a.memberId };
|
||||
if (carry.isBinding(a.email)) return { retry: true, why: 'a LinkSpin activation is in flight' };
|
||||
if (!a.address) return { bound: false };
|
||||
try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) { await accounts.setMemberId(a.email, id).catch(() => {}); return { bound: true, why: 'wallet is LinkSpin member #' + id }; } return { bound: false }; }
|
||||
catch (e) { return { retry: true, why: 'LinkSpin chain read failed' }; }
|
||||
},
|
||||
sponsorAccount: em => accounts.byEmail(em),
|
||||
wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; },
|
||||
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null,
|
||||
// a follow that waited (chain read, activation in flight, sponsor not here yet) is settled: switch payouts on now if the
|
||||
// wallet arrived meanwhile (the wallet hook below skipped it so the contract would not bind the old sponsor)
|
||||
afterResolve: async email => { const a = await accounts.byEmail(email); if (a && a.address && !(Number(a.memberId) > 0)) await carry.ensureOnChain(a, 0, 'wallet'); } });
|
||||
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000);
|
||||
// payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first.
|
||||
// Not while a deliberate sponsor change from InstantAdPay is still waiting to be applied (afterResolve above does it then).
|
||||
accounts.onWalletLinked(async email => { if (followStore.pendingFor(email)) { console.log('activation deferred: sponsor follow pending for', email); return; } const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); });
|
||||
// member numbers for accounts the engine activated before 2026-10-18 (the ledger names people by them); 60 s after boot so a deploy's old copy is gone
|
||||
setTimeout(() => carry.backfillMemberIds().then(r => console.log('memberId backfill', JSON.stringify(r))).catch(e => console.error('memberId backfill', e.message)), 60000);
|
||||
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
|
||||
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST }); accounts.onChange(email => iapsync.touch(email));
|
||||
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST, follow: followStore, tank: () => tank }); accounts.onChange(email => iapsync.touch(email));
|
||||
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);
|
||||
const ownHosts = () => [SITE_HOST].concat(String(siteConfig().linkDomains || '').split(',').map(x => x.trim().toLowerCase()).filter(Boolean), pagesHost() ? [pagesHost()] : []);
|
||||
@@ -629,7 +664,7 @@ async function boot() {
|
||||
zonereport.init({ dataDir: DATA_DIR });
|
||||
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
|
||||
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
|
||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL });
|
||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore });
|
||||
legacy.init({ dataDir: DATA_DIR });
|
||||
traffic.init({ dataDir: DATA_DIR });
|
||||
promos.init({ dataDir: DATA_DIR });
|
||||
@@ -1920,7 +1955,7 @@ const server = http.createServer(async (req, res) => {
|
||||
const r = await accounts.setUsername(e, un); if (r.error) return json(res, 400, r);
|
||||
console.log('admin username', e, un);
|
||||
}
|
||||
if (b.sponsorRef !== undefined) { const r = await accounts.setSponsorRef(e, String(b.sponsorRef || '').trim()); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); }
|
||||
if (b.sponsorRef !== undefined) { const r = await follow.setDeliberate(e, String(b.sponsorRef || '').trim(), 'admin', 'admin member card'); if (r.error) return json(res, 400, r); console.log('admin sponsor', e, String(b.sponsorRef || '').trim()); } // deliberate: follows to InstantAdPay until bound
|
||||
if (b.address !== undefined) {
|
||||
const a = String(b.address || '').trim().toLowerCase();
|
||||
if (a && !/^0x[0-9a-f]{40}$/.test(a)) return json(res, 400, { error: 'That is not a wallet address.' });
|
||||
@@ -2554,14 +2589,21 @@ const server = http.createServer(async (req, res) => {
|
||||
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return json(res, 401, { error: 'bad signature' });
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); }
|
||||
const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : [];
|
||||
const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0;
|
||||
// sponsor follow (2026-10-22): no engine activation may start for these people until the batch has settled their
|
||||
// sponsor (carry.hold); wallets are linked LAST, after every sponsor decision, for the same reason
|
||||
const held = rows.map(r => String(r.email || '').trim().toLowerCase()).filter(Boolean); carry.hold(held);
|
||||
try {
|
||||
const n = await registry.importRows(rows, 'instantadpay'); let shells = 0, updated = 0, followed = 0, kept = 0, wallets = [];
|
||||
for (const r of rows) {
|
||||
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
||||
let a = await accounts.byEmail(e);
|
||||
const created = !a;
|
||||
if (!a) { const x = await accounts.ensure(e, '', 'carried', 'network'); if (x.created) shells++; a = await accounts.byEmail(e); }
|
||||
if (!a) continue;
|
||||
if (Object.prototype.hasOwnProperty.call(r, 'tank')) followStore.setRemote(e, r.tank); // network tank: InstantAdPay's own adoptions of them
|
||||
if (created && SF.incomingOf(r)) { const inc = SF.incomingOf(r); followStore.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'instantadpay' }); } // a new shell carries the same record (no echo)
|
||||
if (r.username && !a.username) { try { await accounts.setUsername(e, r.username); updated++; } catch (err) {} }
|
||||
if (r.wallet && !a.address) { try { await accounts.linkWallet(e, r.wallet); updated++; } catch (err) {} }
|
||||
if (r.wallet && !a.address) wallets.push([e, r.wallet]);
|
||||
if (r.profile && typeof r.profile === 'object') { // the InstantAdPay profile fills only what is still empty here; the member can change it on this side any time (Marty 2026-10-11)
|
||||
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
|
||||
const av = String(pf.avatarUrl || '').trim(); const bio = String(pf.bio || '').trim().slice(0, 600); let soc = null;
|
||||
@@ -2573,11 +2615,56 @@ const server = http.createServer(async (req, res) => {
|
||||
// sponsors in a second pass: a batch is newest-first, so a member's row usually comes BEFORE their sponsor's, whose
|
||||
// shell did not exist yet in the first pass (the sponsor line was left empty until the next change, 2026-10-15)
|
||||
for (const r of rows) {
|
||||
const e = String(r.email || '').trim().toLowerCase(); if (!e || !r.sponsorEmail) continue;
|
||||
const e = String(r.email || '').trim().toLowerCase(); if (!e) continue;
|
||||
if (SF.incomingOf(r)) { // a DELIBERATE change on InstantAdPay: the follow rule decides (never on a member bound here)
|
||||
try { const d = await follow.applyIncoming(e, r); if (d.apply) followed++; else if (d.action !== 'same' && d.action !== 'ordinary') kept++; } catch (err) { console.error('sponsor follow', e, err.message); }
|
||||
continue; // decided by the follow rule (a refusal is logged for the Sponsor check), never by the fill-empty rule below
|
||||
}
|
||||
if (!r.sponsorEmail) continue;
|
||||
const a = await accounts.byEmail(e); if (!a || a.sponsorRef) continue;
|
||||
const pv = followStore.get(e); if (pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail) continue; // emptied on purpose (released / rescued here): an ordinary row does not refill it
|
||||
const sp = await accounts.byEmail(r.sponsorEmail); if (sp && sp.email !== a.email && (sp.username || sp.code)) { try { await accounts.setSponsorRef(e, sp.username || sp.code); updated++; } catch (err) {} }
|
||||
}
|
||||
return json(res, 200, { ok: true, rows: rows.length, imported: n, shells, updated, registry: await registry.count() });
|
||||
for (const [e, w] of wallets) { try { const x = await accounts.linkWallet(e, w); if (x && !x.error) updated++; } catch (err) {} } // last: activation reads the settled sponsor
|
||||
return json(res, 200, { ok: true, proto: SF.PROTO, rows: rows.length, imported: n, shells, updated, followed, followKept: kept, registry: await registry.count() });
|
||||
} finally { carry.unhold(held); }
|
||||
}
|
||||
// -- sponsor check between LinkSpin and InstantAdPay (2026-10-22, sponsorfollow.js). Partner side: InstantAdPay reads our
|
||||
// facts and, on an admin's pick in ITS Sponsor check, asks us to apply a sponsor (refused when the member is bound here).
|
||||
if (p === '/api/partner/sponsor-facts' && req.method === 'POST') {
|
||||
const sg = await readPartnerSigned(req, 2e6); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const emails = Array.isArray(sg.body.emails) ? sg.body.emails.slice(0, 5000) : null;
|
||||
return json(res, 200, { ok: true, proto: SF.PROTO, platform: 'linkspin', rows: await follow.facts(emails), view: followStore.view() });
|
||||
}
|
||||
if (p === '/api/partner/sponsor-apply' && req.method === 'POST') {
|
||||
const sg = await readPartnerSigned(req, 64000); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const b = sg.body; const r = await follow.adminApply(b.email, b.sponsorEmail || null, { note: String(b.note || 'Sponsor check on InstantAdPay').slice(0, 120) });
|
||||
console.log('sponsor check (from InstantAdPay)', b.email, '->', b.sponsorEmail || '(tank)', r.error || 'ok');
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/sponsor-check' && (req.method === 'GET' || req.method === 'POST')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const mine = await follow.facts(); let peer = null, peerError = null;
|
||||
try { peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; }
|
||||
const mm = peer ? SF.mismatches(peer.rows || [], mine) : { shared: 0, same: 0, rows: [] };
|
||||
return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'linkspin', peerError, follow: followStore.view(), peerFollow: peer ? peer.view : null }, mm), { 'Cache-Control': 'no-store' });
|
||||
}
|
||||
if (p === '/api/admin/sponsor-check/resolve' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req); const email = String(b.email || '').trim().toLowerCase();
|
||||
if (!email) return json(res, 400, { error: 'Which member?' });
|
||||
let r;
|
||||
if (b.use === 'instantadpay') { // InstantAdPay's sponsor, applied HERE (refused when bound here)
|
||||
const peer = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message }));
|
||||
if (peer.error) return json(res, 502, { error: 'Could not read InstantAdPay: ' + peer.error });
|
||||
const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' });
|
||||
r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used InstantAdPay's sponsor" });
|
||||
} else if (b.use === 'linkspin') { // our sponsor, applied ON INSTANTADPAY (InstantAdPay refuses when bound there)
|
||||
const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' });
|
||||
r = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on LinkSpin: used LinkSpin's sponsor" }, 30000).catch(e => ({ error: e.message }));
|
||||
} else return json(res, 400, { error: 'use must be instantadpay or linkspin' });
|
||||
console.log('sponsor check resolve', email, b.use, r.error || 'ok');
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/iapsync' && req.method === 'GET') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, iapsync.adminView()); }
|
||||
if (p === '/api/admin/iapsync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await iapsync.tick(!!(b && b.force))); }
|
||||
@@ -3434,7 +3521,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
if (!b.email) return json(res, 400, { error: 'Which member?' });
|
||||
const r = await accounts.setSponsorRef(b.email, b.sponsorRef);
|
||||
const r = await follow.setDeliberate(b.email, b.sponsorRef, 'admin', 'admin members table'); // deliberate: follows to InstantAdPay until bound
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/campaigns' && req.method === 'GET') {
|
||||
|
||||
Reference in New Issue
Block a user