Files
linkspin/qa/sponsorfollow.test.cjs
T
martbost a5c2c38106 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>
2026-10-22 09:05:20 -05:00

296 lines
20 KiB
JavaScript

// Unit tests for the sponsor follow rule + the one network holding tank (sponsorfollow.js, tank.js). The SAME file ships in
// InstantAdPay and LinkSpin. No server, no network, no chain: two in-process "platforms" (two instances of this repo's
// tank.js, each with its own in-memory accounts, follow store and throwaway data dir) and a mini sync that builds rows the
// way lssync.js / iapsync.js do (rowFields + tank summary) and delivers them the way the inbound handlers do.
// node qa/sponsorfollow.test.cjs
'use strict';
const assert = require('assert');
const fs = require('fs');
const os = require('os');
const path = require('path');
const SITE = path.join(__dirname, '..');
const SF = require(path.join(SITE, 'sponsorfollow.js'));
delete process.env.DATABASE_URL; // JSON stores only
let passed = 0, failed = 0; const results = [];
async function t(name, fn) { try { await fn(); passed++; results.push('ok ' + name); } catch (e) { failed++; results.push('FAIL ' + name + '\n ' + (e && e.stack || e).split('\n').slice(0, 3).join('\n ')); } }
// ---------- pure rule ----------
const H = 3600000, T0 = Date.UTC(2026, 9, 22, 15, 0, 0);
const inc = (o) => Object.assign({ sponsorEmail: 'a@x.co', at: T0, by: 'adopt', prevEmail: null, origin: 'instantadpay' }, o);
const loc = (o) => Object.assign({ sponsorEmail: null, prov: null, bound: false }, o);
async function pure() {
await t('ordinary incoming row (no sponsorSetBy) is left to the first-platform rule', () => {
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), { sponsorEmail: 'a@x.co' }).action, 'ordinary');
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'join' })).action, 'ordinary');
assert.strictEqual(SF.incomingOf({ sponsorEmail: 'a@x.co', sponsorSetBy: 'join', sponsorSetAt: T0 }), null);
});
await t('deliberate adoption fills an empty sponsor (one network tank)', () => {
const d = SF.decide(loc(), inc()); assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
});
await t('bound member never changes, even for a newer deliberate change', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', bound: true }), inc({ prevEmail: 'b@x.co' })); assert.strictEqual(d.action, 'bound'); assert.ok(!d.apply); assert.ok(d.conflict);
assert.strictEqual(SF.decide(loc({ bound: true }), inc()).action, 'bound');
});
await t('newer deliberate change wins when both sides agreed before it', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co' }), inc({ by: 'rescue', sponsorEmail: null, prevEmail: 'b@x.co' }));
assert.strictEqual(d.action, 'apply'); assert.ok(d.apply);
});
await t('clear back to the tank applies (sponsorEmail null)', () => {
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0 - 9 * 86400000, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ by: 'expire', sponsorEmail: null, prevEmail: 'a@x.co', at: T0 }));
assert.strictEqual(d.action, 'apply');
});
await t('ordinary sponsor that already differed from the sender is NOT moved (diverged, reported)', () => {
const d = SF.decide(loc({ sponsorEmail: 'c@x.co' }), inc({ prevEmail: null }));
assert.strictEqual(d.action, 'diverged'); assert.ok(!d.apply); assert.ok(d.conflict);
});
await t('older incoming deliberate change loses to a newer local one (stale)', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 2 * H, by: 'admin', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'stale'); assert.ok(!d.apply);
});
await t('newer incoming deliberate change beats an older local deliberate one', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 2 * H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'apply');
});
await t('conflict window: earlier incoming wins over a later local change, flagged', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 + 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'conflict-apply'); assert.ok(d.apply); assert.ok(d.conflict);
});
await t('conflict window: later incoming loses to an earlier local change, flagged, not applied', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0 - 60000, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 }));
assert.strictEqual(d.action, 'conflict-keep'); assert.ok(!d.apply); assert.ok(d.conflict);
});
await t('two changes from the same platform minutes apart are sequential, not a race', () => {
const d = SF.decide(loc({ sponsorEmail: 'a@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'a@x.co', origin: 'instantadpay' } }), inc({ at: T0 + 60000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'a@x.co' }));
assert.strictEqual(d.action, 'apply');
});
await t('a sender that built on our current sponsor is sequential, not a race', () => {
const d = SF.decide(loc({ sponsorEmail: 'b@x.co', prov: { at: T0, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0 + 120000, by: 'admin', sponsorEmail: 'z@x.co', prevEmail: 'b@x.co', origin: 'instantadpay' }));
assert.strictEqual(d.action, 'apply');
});
await t('same sponsor already: no-op (the ping-pong stopper)', () => {
assert.strictEqual(SF.decide(loc({ sponsorEmail: 'A@x.co ' }), inc()).action, 'same');
});
await t('a local record that no longer describes the current sponsor is ignored (later ordinary change)', () => {
const d = SF.decide(loc({ sponsorEmail: 'w@x.co', prov: { at: T0 + H, by: 'adopt', sponsorEmail: 'b@x.co', origin: 'linkspin' } }), inc({ at: T0, prevEmail: null }));
assert.strictEqual(d.action, 'diverged');
assert.strictEqual(SF.rowFields({ at: T0, by: 'adopt', sponsorEmail: 'b@x.co' }, 'w@x.co'), null);
});
await t('back-compat: rows without the new facts hash exactly as before (no resend on deploy)', () => {
assert.strictEqual(SF.hashExtra({ email: 'm@x.co', sponsorEmail: 'a@x.co', tank: null }), '');
assert.notStrictEqual(SF.hashExtra({ sponsorSetBy: 'adopt', sponsorSetAt: T0 }), '');
});
}
// ---------- two platforms in one process ----------
function fakeAccounts() {
const by = new Map(); let nextId = 100;
const pub = a => a ? Object.assign({}, a) : null;
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
return {
_by: by,
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: T0 - 30 * 86400000, lastSeen: T0 - H }, o || {}); by.set(email, a); return pub(a); },
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true, account: pub(a) }; },
async listAll() { return [...by.values()].map(pub); },
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); },
async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = id; }
};
}
function platform(name, peerName) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-' + name + '-'));
delete require.cache[require.resolve(path.join(SITE, 'tank.js'))];
const tank = require(path.join(SITE, 'tank.js'));
const accounts = fakeAccounts();
const purchases = [];
const chain = { recentEvents: () => purchases, getConfig: () => ({}) };
const chats = [];
const messages = { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 };
const store = SF.create({ dataDir: dir, platform: name });
const bound = new Set();
const glue = SF.glue({ store, accounts, tank: () => tank, peer: peerName,
isBound: async a => Number(a.memberId) > 0 || bound.has(a.email) ? { bound: true, why: name + ' member #' + a.memberId } : { bound: false },
sponsorAccount: em => accounts.byEmail(em),
wouldCycle: async (email, sp) => { let cur = sp; for (let i = 0; cur && i < 60; i++) { if (cur.email === email) return true; cur = await accounts.sponsorOf(cur.email); } return false; } });
tank.init({ dataDir: dir, chain, accounts, messages, mailer: null, site: 'https://' + name + '.test', follow: glue, store });
const P = { name, dir, tank, accounts, store, glue, chats, purchases, bound, hashes: {} };
// what the sync module would send for one account (lssync/iapsync rowFor)
P.rowFor = async email => {
const a = await accounts.byEmail(email); const sp = await accounts.sponsorOf(email);
const row = { email, username: a.username, sponsorEmail: sp && sp.email !== email ? sp.email : null };
Object.assign(row, SF.rowFields(store.get(email), row.sponsorEmail) || {});
row.tank = (await tank.summaryFor(email)) || null;
return row;
};
return P;
}
// deliver one row from P to Q the way the inbound handlers do (tank state first, then the follow rule)
async function deliver(P, Q, email) {
const row = await P.rowFor(email);
if (Object.prototype.hasOwnProperty.call(row, 'tank')) Q.store.setRemote(email, row.tank);
const d = await Q.glue.applyIncoming(email, row);
return { row, d };
}
// a mini "both sides synced" loop: push changed rows both ways until nothing changes (with a guard against ping-pong)
async function settle(P, Q, emails) {
let rounds = 0, moves = 0;
for (; rounds < 6; rounds++) {
let changed = 0;
for (const [X, Y] of [[P, Q], [Q, P]]) for (const e of emails) {
const row = await X.rowFor(e); const h = JSON.stringify(row);
if (X.hashes[e] === h) continue; X.hashes[e] = h; changed++;
Y.store.setRemote(e, row.tank); const d = await Y.glue.applyIncoming(e, row); if (d.apply) moves++;
}
if (!changed) break;
}
return { rounds, moves };
}
const spOf = async (P, e) => { const s = await P.accounts.sponsorOf(e); return s ? s.email : null; };
function people(P, Q) {
for (const X of [P, Q]) {
X.accounts.add('adopter@x.co', { memberId: 7, username: 'adopter' });
X.accounts.add('other@x.co', { memberId: 8, username: 'otheradopter' });
X.accounts.add('lead@x.co', { username: 'lead' });
X.accounts.add('old@x.co', { username: 'oldsponsor', memberId: 9 });
X.purchases.push({ type: 'Purchase', buyerId: 7, priceCents: 2500 }, { type: 'Purchase', buyerId: 8, priceCents: 2500 });
}
}
async function network() {
await t('network tank: adopting on one platform makes the person adopted on both (same adopter), notices only once', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'));
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
const r = await P.tank.adopt('adopter@x.co', 'lead', 'hi'); assert.ok(r.ok, JSON.stringify(r));
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'apply');
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'), 'hidden on the other side');
assert.strictEqual(P.chats.length, 1); assert.strictEqual(Q.chats.length, 0, 'no chat on the quiet side');
const qr = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(qr.error, 'cannot be adopted twice across the network');
});
await t('ping-pong guard: the applied change comes back as "same" and settles in one round trip', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead');
const s = await settle(P, Q, ['lead@x.co']);
assert.strictEqual(s.moves, 1); assert.ok(s.rounds <= 3, 'rounds ' + s.rounds);
const back = await Q.rowFor('lead@x.co'); const fromP = await P.rowFor('lead@x.co');
assert.strictEqual(back.sponsorSetAt, fromP.sponsorSetAt); assert.strictEqual(back.sponsorSetOrigin, 'instantadpay');
assert.strictEqual((await P.glue.applyIncoming('lead@x.co', back)).action, 'same');
});
await t('waiting list hides someone with an open adoption elsewhere even if the follow could not apply', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
Q.bound.add('lead@x.co'); // say LinkSpin cannot take the change
await P.tank.adopt('adopter@x.co', 'lead');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'bound');
assert.ok(!(await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
assert.ok(Q.store.recent(5).some(x => x.action === 'bound' && x.conflict), 'logged for the report');
});
await t('release mirrors: releasing on the quiet side clears both and closes the open adoption as dropped', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
// the 3-day commitment counts on the quiet side too
const early = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(early.error && /commitment/.test(early.error), JSON.stringify(early));
// four days later
const realNow = Date.now; Date.now = () => realNow() + 4 * 86400000;
try {
const r = await Q.tank.release('adopter@x.co', 'lead@x.co'); assert.ok(r.ok, JSON.stringify(r));
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), null); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
const pad = (await P.tank.adminView()).adoptions.find(a => a.adoptee === 'lead@x.co');
assert.strictEqual(pad.status, 'dropped');
assert.ok((await P.tank.waiting()).some(w => w.email === 'lead@x.co'), 'back in the tank on both');
assert.ok((await Q.tank.waiting()).some(w => w.email === 'lead@x.co'));
} finally { Date.now = realNow; }
});
await t('expiry mirrors: the adopting side ends the window and the other side follows the clear', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
const realNow = Date.now; Date.now = () => realNow() + 8 * 86400000;
try {
const sw = await P.tank.sweep(); assert.strictEqual(sw.back, 1);
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
assert.strictEqual(Q.store.get('lead@x.co').by, 'expire');
} finally { Date.now = realNow; }
});
await t('two adoptions per person count across both platforms', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
try {
await P.tank.adopt('adopter@x.co', 'lead'); await settle(P, Q, ['lead@x.co']);
off = 8 * 86400000; await P.tank.sweep(); await settle(P, Q, ['lead@x.co']);
const r2 = await Q.tank.adopt('other@x.co', 'lead'); assert.ok(r2.ok, JSON.stringify(r2)); await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), 'other@x.co');
off = 16 * 86400000; await Q.tank.sweep(); await settle(P, Q, ['lead@x.co']);
// adopted once on each side now: a third adoption anywhere is refused
if (!(await P.tank.waiting()).some(w => w.email === 'lead@x.co')) { /* kept where they are after two */ }
const r3 = await P.tank.adopt('adopter@x.co', 'lead'); assert.ok(r3.error, JSON.stringify(r3));
} finally { Date.now = realNow; }
});
await t('race: both sides adopt within minutes -> the earlier adoption wins on both, the later one is a conflict', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
const realNow = Date.now; let off = 0; Date.now = () => realNow() + off;
try {
await P.tank.adopt('adopter@x.co', 'lead');
off = 90000; await Q.tank.adopt('other@x.co', 'lead'); // 90 s later on LinkSpin, before the sync arrived
off = 100000;
const a = await deliver(Q, P, 'lead@x.co'); // the later change reaches the earlier side: kept, flagged
assert.strictEqual(a.d.action, 'conflict-keep');
const b = await deliver(P, Q, 'lead@x.co'); // the earlier change reaches the later side: applied, flagged
assert.strictEqual(b.d.action, 'conflict-apply');
await settle(P, Q, ['lead@x.co']);
assert.strictEqual(await spOf(P, 'lead@x.co'), 'adopter@x.co'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'adopter@x.co');
const qad = (await Q.tank.adminView()).adoptions.find(x => x.adopter === 'other@x.co');
assert.strictEqual(qad.status, 'conflict');
assert.ok(P.store.recent(10).some(x => x.action === 'conflict-keep'));
} finally { Date.now = realNow; }
});
await t('ordinary join on the other side is never overwritten by an adoption here (diverged, reported)', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
await Q.accounts.setSponsorRef('lead@x.co', 'oldsponsor'); // joined LinkSpin through @oldsponsor's link
await P.tank.adopt('adopter@x.co', 'lead');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'diverged'); assert.strictEqual(await spOf(Q, 'lead@x.co'), 'old@x.co');
});
await t('rescue clears the other side when both had the same sponsor', async () => {
const P = platform('instantadpay', 'linkspin'), Q = platform('linkspin', 'instantadpay'); people(P, Q);
for (const X of [P, Q]) await X.accounts.setSponsorRef('lead@x.co', 'oldsponsor');
await P.glue.setDeliberate('lead@x.co', '', 'rescue', 'test');
const { d } = await deliver(P, Q, 'lead@x.co');
assert.strictEqual(d.action, 'apply'); assert.strictEqual(await spOf(Q, 'lead@x.co'), null);
});
await t('admin pick from the mismatch report applies on the unbound side and refuses on a bound one', async () => {
const P = platform('instantadpay', 'linkspin'); P.accounts.add('m@x.co'); P.accounts.add('s@x.co', { username: 'sss' });
const ok = await P.glue.adminApply('m@x.co', 's@x.co'); assert.ok(ok.ok, JSON.stringify(ok)); assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
assert.strictEqual(P.store.get('m@x.co').by, 'admin');
P.bound.add('m@x.co'); const no = await P.glue.adminApply('m@x.co', null); assert.ok(no.error && /bound/.test(no.error));
assert.strictEqual(await spOf(P, 'm@x.co'), 's@x.co');
});
await t('mismatch report: differ / one-sided rows, matches counted', async () => {
const r = SF.mismatches([{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's1' }, { email: 'c@x', sponsorEmail: null }, { email: 'd@x', sponsorEmail: 's2' }],
[{ email: 'a@x', sponsorEmail: 's1' }, { email: 'b@x', sponsorEmail: 's2' }, { email: 'c@x', sponsorEmail: 's3' }, { email: 'e@x', sponsorEmail: 's4' }]);
assert.strictEqual(r.shared, 3); assert.strictEqual(r.same, 1); assert.deepStrictEqual(r.rows.map(x => x.email + ':' + x.kind), ['b@x:differ', 'c@x:ls-only']);
});
await t('pending follow: retried later and settled (sponsor account arrives)', async () => {
const Q = platform('linkspin', 'instantadpay'); Q.accounts.add('lead@x.co');
const row = { email: 'lead@x.co', sponsorEmail: 'late@x.co', sponsorSetAt: T0, sponsorSetBy: 'adopt', sponsorPrevEmail: null, sponsorSetOrigin: 'instantadpay' };
assert.strictEqual((await Q.glue.applyIncoming('lead@x.co', row)).action, 'pending');
Q.accounts.add('late@x.co', { username: 'late' });
const rr = await Q.glue.retryPending(); assert.strictEqual(rr.settled, 1);
assert.strictEqual(await spOf(Q, 'lead@x.co'), 'late@x.co'); assert.strictEqual(Q.store.pendingFor('lead@x.co'), null);
});
}
(async () => {
await pure(); await network();
console.log(results.join('\n'));
console.log('\nsponsorfollow: ' + passed + ' passed, ' + failed + ' failed');
process.exit(failed ? 1 : 0);
})();