Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Deliberate sponsor changes (tank adoption, dormant-lead rescue, release, adoption window ending, admin edit) are now recorded (sponsorfollow.json: when, how, the sponsor before, origin) and travel on the LinkSpin sync rows as sponsorSetAt/By/PrevEmail/Origin. A deliberate change from LinkSpin is applied here (a clear back to the tank included) only when the member is not bound on the InstantAdPay contract (memberId or wallet on chain), it is newer than our own deliberate change, and both sides agreed before it (or we have no sponsor). Bound, diverged and race cases change nothing and are logged. Race within 15 min: the earlier change wins on both. Ordinary bindings keep the first-platform rule. Accounts with no record behave as before; rows without the new facts hash exactly as before (no resend on deploy). Network tank: rows carry this site's own adoptions of a person; the waiting list hides someone adopted on LinkSpin, the two-adoptions limit counts both sites, the 3-day hold applies to a LinkSpin adoption too, follows close local open adoptions quietly (no chat, mail or feed post). Admin > Members > Sponsor check: shared members whose sponsor differs or is one-sided, each side's when/how, chain binding, and Use InstantAdPay's / Use LinkSpin's sponsor (applied on the other site, refused when bound there). Partner endpoints /api/partner/sponsor-facts and /api/partner/sponsor-apply (same HMAC as the registry rows). Tests: qa/sponsorfollow.test.cjs 27/27, qa/sponsorfollow-e2e.mjs 20/20 (local IAP + local LinkSpin, throwaway data), 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:
+35
-8
@@ -16,7 +16,15 @@
|
||||
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
|
||||
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
|
||||
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
|
||||
// - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy
|
||||
// adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear
|
||||
// back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the
|
||||
// change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound,
|
||||
// diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly.
|
||||
// - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list
|
||||
// hides someone adopted on LinkSpin and the two-adoptions limit counts both sites.
|
||||
'use strict';
|
||||
const SF = require('./sponsorfollow');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -35,7 +43,7 @@ function load() {
|
||||
}
|
||||
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
|
||||
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
||||
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync }
|
||||
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) }
|
||||
|
||||
function clean(x) {
|
||||
if (!x || typeof x !== 'object') return null;
|
||||
@@ -44,9 +52,18 @@ function clean(x) {
|
||||
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
|
||||
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
|
||||
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
|
||||
return { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
||||
const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
||||
if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js)
|
||||
out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy);
|
||||
const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null;
|
||||
out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now
|
||||
return out;
|
||||
}
|
||||
const tokenOf = a => a.username || a.code;
|
||||
// released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js)
|
||||
const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); };
|
||||
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
|
||||
|
||||
// would binding `email` under `sp` close a loop (sp already sits below email)?
|
||||
@@ -94,7 +111,14 @@ async function place(email, depth, ctx) {
|
||||
ctx.done.add(email); R.lssync.mute(email);
|
||||
let a = await A.byEmail(email); let wrote = false;
|
||||
if (!r) return a;
|
||||
if (!a) {
|
||||
const inc = SF.incomingOf(r);
|
||||
if (a && inc && R.follow) {
|
||||
// a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here)
|
||||
const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) });
|
||||
if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); }
|
||||
else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); }
|
||||
a = await A.byEmail(email);
|
||||
} else if (!a) {
|
||||
let tok = '';
|
||||
if (r.sponsorEmail) {
|
||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||
@@ -104,7 +128,9 @@ async function place(email, depth, ctx) {
|
||||
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
|
||||
a = x.account;
|
||||
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
|
||||
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail) {
|
||||
// a new waiting account built from a deliberate change carries the same record, so its row does not echo back
|
||||
if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' });
|
||||
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) {
|
||||
// our own waiting account, still without a sponsor: this row (or a later one) names one
|
||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
|
||||
@@ -119,7 +145,7 @@ async function resolvePending(ctx) {
|
||||
const s = load(); const A = R.accounts;
|
||||
for (const [email, spEmail] of Object.entries(s.pending)) {
|
||||
const a = await A.byEmail(email);
|
||||
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef) { delete s.pending[email]; continue; } // claimed or bound meanwhile: leave it
|
||||
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it
|
||||
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
|
||||
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
|
||||
R.lssync.mute(email); ctx.done.add(email);
|
||||
@@ -129,9 +155,10 @@ async function resolvePending(ctx) {
|
||||
}
|
||||
async function handle(rows) {
|
||||
const s = load(); s.stats.batches++;
|
||||
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0 };
|
||||
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
|
||||
const ctx = { sum, done: new Set() }; const batch = [];
|
||||
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
|
||||
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
|
||||
try {
|
||||
for (const r of batch) {
|
||||
try { await place(r.email, 0, ctx); }
|
||||
@@ -141,9 +168,9 @@ async function handle(rows) {
|
||||
} finally {
|
||||
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
|
||||
}
|
||||
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors']) s.stats[k] += sum[k];
|
||||
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k];
|
||||
s.last = Object.assign({ at: Date.now() }, sum); save();
|
||||
return sum;
|
||||
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
|
||||
}
|
||||
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
|
||||
function receive(rows) { const run = chain_.then(() => handle(rows)); chain_ = run.catch(() => {}); return run; }
|
||||
|
||||
@@ -5,8 +5,15 @@
|
||||
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
|
||||
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
|
||||
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
|
||||
//
|
||||
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
|
||||
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
|
||||
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
|
||||
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
|
||||
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const SF = require('./sponsorfollow');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
@@ -20,11 +27,16 @@ function load() { if (state) return state; try { state = JSON.parse(fs.readFileS
|
||||
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
||||
|
||||
function init(deps) { R = deps; load(); }
|
||||
async function rowFor(acct, byRef) {
|
||||
async function rowFor(acct, byRef, tankMap) {
|
||||
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
|
||||
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
|
||||
return { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
||||
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
||||
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
|
||||
const T = R.tank && R.tank();
|
||||
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
|
||||
return row;
|
||||
}
|
||||
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
|
||||
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
|
||||
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
|
||||
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||
@@ -36,7 +48,7 @@ function profileOf(a) {
|
||||
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
|
||||
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
|
||||
}
|
||||
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|')).digest('hex').slice(0, 16);
|
||||
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
|
||||
|
||||
async function post(rows) {
|
||||
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
|
||||
@@ -48,8 +60,9 @@ async function post(rows) {
|
||||
async function push(rows) {
|
||||
const st = load(); let sent = 0;
|
||||
for (let i = 0; i < rows.length; i += 100) {
|
||||
const chunk = rows.slice(i, i + 100); await post(chunk); sent += chunk.length;
|
||||
for (const r of chunk) st.hashes[r.email] = hashOf(r);
|
||||
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
|
||||
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
|
||||
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
|
||||
}
|
||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
||||
}
|
||||
@@ -65,7 +78,8 @@ async function tick(force) {
|
||||
try {
|
||||
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const sent = rows.length ? await push(rows) : 0;
|
||||
return { accounts: all.length, changed: rows.length, sent };
|
||||
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
||||
@@ -82,7 +96,9 @@ async function release(email, sent) {
|
||||
const a = await R.accounts.byEmail(e);
|
||||
if (a && sent) {
|
||||
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
|
||||
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail)) { load().hashes[e] = hashOf(r); save(); same = true; }
|
||||
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
|
||||
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
|
||||
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
|
||||
}
|
||||
} catch (err) {}
|
||||
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
|
||||
|
||||
+8
-1
@@ -265,6 +265,13 @@
|
||||
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
|
||||
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
|
||||
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
|
||||
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
|
||||
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
|
||||
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
|
||||
@@ -595,6 +602,6 @@
|
||||
|
||||
<script src="/assets/common.js?v=20261016n"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261020kb"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
|
||||
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
|
||||
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
if (!$('scRun')) return;
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit' };
|
||||
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||
function side(f) {
|
||||
if (!f) return '<span class="muted">no account</span>';
|
||||
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
|
||||
const how = [];
|
||||
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
|
||||
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
|
||||
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
|
||||
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
|
||||
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
|
||||
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
|
||||
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
|
||||
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
|
||||
}
|
||||
let last = null;
|
||||
async function run() {
|
||||
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
|
||||
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||
last = r;
|
||||
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
|
||||
const differ = r.rows.filter(x => x.kind === 'differ').length;
|
||||
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
|
||||
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
|
||||
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
|
||||
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
|
||||
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
|
||||
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
|
||||
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
|
||||
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
|
||||
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
|
||||
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
|
||||
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
|
||||
finally { $('scRun').disabled = false; }
|
||||
}
|
||||
$('scRun').addEventListener('click', run);
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
|
||||
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
|
||||
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
|
||||
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
|
||||
let ok = false;
|
||||
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
|
||||
if (!ok) return;
|
||||
b.disabled = true;
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
|
||||
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
|
||||
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
|
||||
});
|
||||
})();
|
||||
@@ -5,6 +5,7 @@
|
||||
# bash qa/run.sh earn # local copy: earning flows end to end (~2-3 min)
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
# bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it)
|
||||
# bash qa/run.sh sov-passes # Explorer/Champion tiers: store unit checks + admin buys Explorer with seeded purchased credits on a local copy (screenshots D:/tmp/sov-passes)
|
||||
@@ -35,6 +36,9 @@ if [ "$MODE" = "public" ]; then
|
||||
node qa/chatbot-sync.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
elif [ "$MODE" = "sponsorfollow" ]; then
|
||||
node qa/sponsorfollow.test.cjs || status=1
|
||||
node qa/sponsorfollow-e2e.mjs || status=1
|
||||
elif [ "$MODE" = "kb" ]; then
|
||||
node qa/kb-retrieval.cjs || status=1
|
||||
node qa/kb-chat.mjs || status=1
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
// End-to-end check of the sponsor follow through the REAL sync code (lssync.js -> LinkSpin /api/partner/registry and
|
||||
// iapsync.js -> InstantAdPay /api/partner/registry, the hash and registry loop guards, the Sponsor check endpoints).
|
||||
// Boots a local InstantAdPay AND a local LinkSpin, each on a throwaway data dir seeded with the same few accounts (JSON
|
||||
// stores, no DATABASE_URL, no mail key, no engine key), pointed ONLY at each other with a throwaway LS_SYNC_SECRET.
|
||||
// Nothing touches production. Needs the LinkSpin repo beside this one (LS_SITE to override).
|
||||
// node qa/sponsorfollow-e2e.mjs
|
||||
import { spawn, execSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
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-sponsorfollow-' + 'x'.repeat(40);
|
||||
process.env.LS_SYNC_SECRET = SECRET;
|
||||
const SF = require(path.join(IAP_SITE, 'sponsorfollow.js'));
|
||||
const IAP_PORT = 8811, LS_PORT = 8812, IAP = 'http://127.0.0.1:' + IAP_PORT, LS = 'http://127.0.0.1:' + LS_PORT;
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let pass = 0, fail = 0; const lines = [];
|
||||
const ok = (cond, name, extra) => { if (cond) { pass++; lines.push('ok ' + name); } else { fail++; lines.push('FAIL ' + name + (extra ? '\n ' + extra : '')); } };
|
||||
|
||||
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 base = () => [acct('adopter@qa.test', 'adopter', { memberId: 0 }), acct('old@qa.test', 'oldsponsor'), acct('lead1@qa.test', 'leadone'), acct('lead2@qa.test', 'leadtwo', { sponsorRef: 'oldsponsor' }), acct('lead4@qa.test', 'leadfour', { sponsorRef: 'oldsponsor' })];
|
||||
const iapDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-iap-')), lsDir = fs.mkdtempSync(path.join(os.tmpdir(), 'sf-e2e-ls-'));
|
||||
// lead3 is bound on InstantAdPay (memberId), lead4 joined LinkSpin under someone else (ordinary, already different)
|
||||
seed(iapDir, base().concat([acct('lead3@qa.test', 'leadthree', { memberId: 42, sponsorRef: 'oldsponsor' })]));
|
||||
seed(lsDir, base().map(a => a.email === 'lead4@qa.test' ? Object.assign(a, { sponsorRef: 'adopter' }) : a).concat([acct('lead3@qa.test', 'leadthree', { sponsorRef: 'oldsponsor' })]));
|
||||
|
||||
const env = (port, dir, extra) => Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@qa.test', ADMIN_PASSWORD: 'localtest', LS_SYNC_SECRET: SECRET, DATABASE_URL: '', SENDGRID_API_KEY: '', ENGINE_KEY: '', ENGINE_KEY_FILE: '' }, extra);
|
||||
for (const k of ['DATABASE_URL', 'NETWORK_DB_URL']) delete process.env[k];
|
||||
const procs = [];
|
||||
function boot(site, port, dir, extra, log) {
|
||||
const p = spawn(process.execPath, ['server.js'], { cwd: site, env: env(port, dir, extra), stdio: ['ignore', fs.openSync(log, 'w'), fs.openSync(log, 'a')] });
|
||||
procs.push(p); return p;
|
||||
}
|
||||
async function up(url) { for (let i = 0; i < 40; i++) { try { const r = await fetch(url + '/api/config', { signal: AbortSignal.timeout(2000) }); if (r.status < 500) return true; } catch (e) {} await sleep(1000); } return false; }
|
||||
const admin = async (url, pth, body, method) => { const r = await fetch(url + pth, { method: method || (body ? 'POST' : 'GET'), headers: { Authorization: 'Bearer localtest', 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : undefined }); return r.json(); };
|
||||
const facts = async (url, email) => ((await SF.peerPost(url, '/api/partner/sponsor-facts', { emails: [email] })).rows || [])[0] || null;
|
||||
async function waitFor(fn, ms) { const t0 = Date.now(); while (Date.now() - t0 < (ms || 20000)) { try { if (await fn()) return true; } catch (e) {} await sleep(700); } return false; }
|
||||
|
||||
const OUT = path.join(IAP_SITE, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
|
||||
try {
|
||||
boot(IAP_SITE, IAP_PORT, iapDir, { LS_URL: LS }, path.join(OUT, 'sf-e2e-iap.log'));
|
||||
boot(LS_SITE, LS_PORT, lsDir, { IAP_URL: IAP, SITE_HOST: '127.0.0.1:' + LS_PORT, TANK_RESCUE: '' }, path.join(OUT, 'sf-e2e-ls.log'));
|
||||
ok(await up(IAP), 'local InstantAdPay up'); ok(await up(LS), 'local LinkSpin up');
|
||||
|
||||
// 1. a deliberate change on InstantAdPay (admin edit from the tank) follows to LinkSpin
|
||||
let r = await admin(IAP, '/api/admin/member', { email: 'lead1@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||
ok(!r.error, 'IAP admin sets lead1 -> @adopter', JSON.stringify(r));
|
||||
ok(await waitFor(async () => (await facts(LS, 'lead1@qa.test')).sponsorEmail === 'adopter@qa.test'), 'LinkSpin follows: lead1 under adopter');
|
||||
const l1 = await facts(LS, 'lead1@qa.test'); ok(l1 && l1.prov && l1.prov.by === 'admin' && l1.prov.origin === 'instantadpay', 'LinkSpin keeps the same record (by admin, origin instantadpay)', JSON.stringify(l1 && l1.prov));
|
||||
|
||||
// 2. a deliberate change on LinkSpin (both had @oldsponsor) follows to InstantAdPay, a clear back to the tank
|
||||
r = await admin(LS, '/api/admin/member', { email: 'lead2@qa.test', sponsorRef: '' }, 'PATCH');
|
||||
ok(!r.error, 'LinkSpin admin clears lead2 to the tank', JSON.stringify(r));
|
||||
ok(await waitFor(async () => (await facts(IAP, 'lead2@qa.test')).sponsorEmail === null), 'InstantAdPay follows the clear: lead2 in the tank');
|
||||
|
||||
// 3. bound on InstantAdPay: a LinkSpin change does not move it there; reported; resolve refuses on the bound side
|
||||
r = await admin(LS, '/api/admin/member', { email: 'lead3@qa.test', sponsorRef: 'adopter' }, 'PATCH');
|
||||
await sleep(6000);
|
||||
ok((await facts(IAP, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'bound on InstantAdPay: sponsor there unchanged');
|
||||
|
||||
// 4. ping-pong: let both ticks run; nothing keeps bouncing
|
||||
const s1 = await admin(IAP, '/api/admin/lssync'), t1 = await admin(LS, '/api/admin/iapsync');
|
||||
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||
await admin(IAP, '/api/admin/lssync/run', {}); await admin(LS, '/api/admin/iapsync/run', {}); await sleep(1500);
|
||||
const s2 = await admin(IAP, '/api/admin/lssync/run', {}), t2 = await admin(LS, '/api/admin/iapsync/run', {});
|
||||
ok(s2.sent === 0 && t2.sent === 0, 'no ping-pong: a third reconcile on each side sends 0 rows', JSON.stringify({ s1: s1.pushed, s2, t1: t1.pushed, t2 }));
|
||||
|
||||
// 5. the Sponsor check on both apps lists lead3 (bound on IAP) and lead4 (ordinary, different) and nothing else
|
||||
const rep = await admin(IAP, '/api/admin/sponsor-check'); const rep2 = await admin(LS, '/api/admin/sponsor-check');
|
||||
const emails = x => (x.rows || []).map(y => y.email).sort().join(',');
|
||||
ok(!rep.peerError && emails(rep) === 'lead3@qa.test,lead4@qa.test', 'IAP Sponsor check rows = lead3, lead4', JSON.stringify({ e: emails(rep), err: rep.peerError }));
|
||||
ok(emails(rep2) === emails(rep), 'LinkSpin Sponsor check shows the same rows');
|
||||
const r3 = (rep.rows || []).find(x => x.email === 'lead3@qa.test');
|
||||
ok(r3 && r3.iap.bound && !r3.ls.bound, 'lead3: bound on InstantAdPay, not on LinkSpin');
|
||||
ok(r3 && (r3.iap.log || []).some(l => l.action === 'bound'), 'lead3: the refused follow is in the InstantAdPay log');
|
||||
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'linkspin' });
|
||||
ok(r.error && /bound/.test(r.error), "resolve 'Use LinkSpin's sponsor' on the bound side is refused", JSON.stringify(r));
|
||||
r = await admin(LS, '/api/admin/sponsor-check/resolve', { email: 'lead3@qa.test', use: 'instantadpay' });
|
||||
ok(r.ok, "resolve from LinkSpin admin: 'Use InstantAdPay's sponsor' applies on LinkSpin", JSON.stringify(r));
|
||||
ok((await facts(LS, 'lead3@qa.test')).sponsorEmail === 'old@qa.test', 'lead3 now @oldsponsor on both');
|
||||
r = await admin(IAP, '/api/admin/sponsor-check/resolve', { email: 'lead4@qa.test', use: 'instantadpay' });
|
||||
ok(r.ok, "resolve from InstantAdPay admin: lead4 'Use InstantAdPay's sponsor' applied on LinkSpin through the partner call", JSON.stringify(r));
|
||||
await sleep(5000);
|
||||
const rep3 = await admin(IAP, '/api/admin/sponsor-check');
|
||||
ok((rep3.rows || []).length === 0, 'after both picks the Sponsor check is empty', emails(rep3));
|
||||
ok((await facts(IAP, 'lead4@qa.test')).sponsorEmail === 'old@qa.test', 'lead4 on InstantAdPay untouched by its own pick');
|
||||
|
||||
// 6. an old peer (no proto 2): rows carrying the new facts are sent again later (checked through the stored hashes)
|
||||
const st = JSON.parse(fs.readFileSync(path.join(iapDir, 'sponsorfollow.json'), 'utf8'));
|
||||
ok(st.peer && st.peer.proto === 2, 'IAP saw LinkSpin answer proto 2');
|
||||
} catch (e) { fail++; lines.push('FAIL exception ' + (e && e.stack || e)); }
|
||||
finally {
|
||||
for (const p of procs) { try { p.kill(); } catch (e) {} }
|
||||
if (process.platform === 'win32') for (const port of [IAP_PORT, LS_PORT]) { try { const o = execSync('netstat -ano | findstr :' + port, { encoding: 'utf8' }); for (const pid of new Set(o.split(/\r?\n/).map(l => l.trim().split(/\s+/).pop()).filter(x => /^\d+$/.test(x) && x !== '0'))) { try { execSync('taskkill /F /PID ' + pid, { stdio: 'ignore' }); } catch (e) {} } } catch (e) {} }
|
||||
await sleep(500);
|
||||
for (const d of [iapDir, lsDir]) { try { fs.rmSync(d, { recursive: true, force: true }); } catch (e) {} }
|
||||
}
|
||||
console.log(lines.join('\n')); console.log('\nsponsorfollow e2e: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -0,0 +1,295 @@
|
||||
// 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);
|
||||
})();
|
||||
@@ -49,6 +49,15 @@ const sbcheck = require('./sbcheck');
|
||||
const reach = require('./reach');
|
||||
const lssync = require('./lssync');
|
||||
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
|
||||
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
|
||||
let follow = null, followStore = null;
|
||||
const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').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;
|
||||
}
|
||||
const gamestats = require('./gamestats');
|
||||
const marks = require('./marks');
|
||||
const gamepass = require('./gamepass'); // the $5 weekly Game Pass + the account-wide POL cap service the games call (2026-10-16)
|
||||
@@ -572,12 +581,27 @@ async function boot() {
|
||||
override.init({ dataDir: DATA_DIR, chain, siteConfig, notify: supportTelegram });
|
||||
setInterval(() => override.tick().catch(e => console.error('override', e.message)), 30 * 60 * 1000);
|
||||
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
|
||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com' });
|
||||
// sponsor follow (sponsorfollow.js): a deliberate change (tank adoption, rescue, release, window expiry, admin edit) is
|
||||
// recorded and follows to LinkSpin, and LinkSpin's deliberate changes are applied here, until the member is bound on
|
||||
// InstantAdPay's contract (memberId, or the wallet already on chain). Ordinary bindings keep the first-platform rule.
|
||||
followStore = SF.create({ dataDir: DATA_DIR, platform: 'instantadpay' });
|
||||
follow = SF.glue({ store: followStore, accounts, tank: () => tank, peer: 'linkspin',
|
||||
isBound: async a => {
|
||||
if (Number(a.memberId) > 0) return { bound: true, why: 'InstantAdPay member #' + a.memberId };
|
||||
if (!a.address) return { bound: false };
|
||||
try { const id = Number(await chain.memberIdByAccount(a.address)) || 0; return id ? { bound: true, why: 'wallet is InstantAdPay member #' + id } : { bound: false }; }
|
||||
catch (e) { return { retry: true, why: 'InstantAdPay 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 });
|
||||
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore });
|
||||
// LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest
|
||||
lssync.init({ dataDir: DATA_DIR, accounts }); accounts.onChange(email => lssync.touch(email));
|
||||
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync });
|
||||
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
|
||||
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
|
||||
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
|
||||
walletnudge.init({ dataDir: DATA_DIR, accounts, mailer, optedIn: updates.optedIn, site: 'https://instantadpay.com',
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); } });
|
||||
setTimeout(() => walletnudge.tick().catch(e => console.error('walletnudge', e.message)), 3 * 60 * 1000); // past the deploy overlap window
|
||||
@@ -2750,7 +2774,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 LinkSpin 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.' });
|
||||
@@ -3094,6 +3118,43 @@ const server = http.createServer(async (req, res) => {
|
||||
const rows = Array.isArray(b.rows) ? b.rows.slice(0, 500) : [];
|
||||
return json(res, 200, Object.assign({ ok: true }, await lsinbound.receive(rows)));
|
||||
}
|
||||
// -- sponsor check between InstantAdPay and LinkSpin (2026-10-22, sponsorfollow.js). Partner side: LinkSpin 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 readLsSigned(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: 'instantadpay', rows: await follow.facts(emails), view: followStore.view() });
|
||||
}
|
||||
if (p === '/api/partner/sponsor-apply' && req.method === 'POST') {
|
||||
const sg = await readLsSigned(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 LinkSpin').slice(0, 120) });
|
||||
console.log('sponsor check (from LinkSpin)', 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') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const mine = await follow.facts(); let peer = null, peerError = null;
|
||||
try { peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { all: true }, 90000); } catch (e) { peerError = e.message; }
|
||||
const mm = peer ? SF.mismatches(mine, peer.rows || []) : { shared: 0, same: 0, rows: [] };
|
||||
return json(res, 200, Object.assign({ ok: true, at: Date.now(), here: 'instantadpay', 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 === 'linkspin') { // LinkSpin's sponsor, applied HERE (refused when bound here)
|
||||
const peer = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-facts', { emails: [email] }, 30000).catch(e => ({ error: e.message }));
|
||||
if (peer.error) return json(res, 502, { error: 'Could not read LinkSpin: ' + peer.error });
|
||||
const row = (peer.rows || [])[0]; if (!row) return json(res, 404, { error: email + ' has no LinkSpin account.' });
|
||||
r = await follow.adminApply(email, row.sponsorEmail || null, { note: "Sponsor check: used LinkSpin's sponsor" });
|
||||
} else if (b.use === 'instantadpay') { // our sponsor, applied ON LINKSPIN (LinkSpin refuses when bound there)
|
||||
const row = (await follow.facts([email]))[0]; if (!row) return json(res, 404, { error: email + ' has no InstantAdPay account.' });
|
||||
r = await SF.peerPost(LS_BASE(), '/api/partner/sponsor-apply', { email, sponsorEmail: row.sponsorEmail || null, note: "Sponsor check on InstantAdPay: used InstantAdPay'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);
|
||||
}
|
||||
// -- help desk for LinkSpin (2026-10-16): LinkSpin has no desk of its own; its Help screen, /support page, private ticket
|
||||
// link and chat hand-off all proxy here, signed like the registry rows. LinkSpin runs the person-facing guards (sign-in,
|
||||
// honeypot, form age, icon check) and vouches for the email; this side only ever touches platform 'linkspin' tickets
|
||||
@@ -4823,7 +4884,7 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true, signals: await fraud.get(b.email) });
|
||||
}
|
||||
if (b.flags !== undefined) { const f = b.flags === null ? (await fraud.clearFlags(b.email), []) : await fraud.addFlags(b.email, [].concat(b.flags)); return json(res, 200, { ok: true, flags: f }); }
|
||||
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 LinkSpin until bound
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/fraud' && req.method === 'GET') { // duplicate signals: shared browsers / IPs, flagged and suspended accounts
|
||||
|
||||
@@ -0,0 +1,286 @@
|
||||
// Sponsor follow + one network holding tank (Marty, 2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
//
|
||||
// Background: the registry sync between the two sites (IAP lssync.js / lsinbound.js, LinkSpin iapsync.js + its
|
||||
// /api/partner/registry) never overwrites a sponsor (first-platform rule). That is right for ordinary bindings (join link,
|
||||
// cookie, last touch, carry-over), but a DELIBERATE change on one side (tank adoption, dormant-lead rescue, release to the
|
||||
// tank, an adoption falling back at the end of its window, an admin edit) stayed on that side only.
|
||||
//
|
||||
// The follow rule (decide() below, unit-tested in qa/sponsorfollow.test.cjs / tests/sponsorfollow.test.cjs):
|
||||
// - A deliberate change is recorded here with when, how and the sponsor before it (record()). Sync rows carry it as
|
||||
// sponsorSetAt / sponsorSetBy / sponsorPrevEmail / sponsorSetOrigin, and only while it still describes the current
|
||||
// sponsor (rowFields()), so a later ordinary change never travels as if it were deliberate.
|
||||
// - The receiver applies the incoming sponsor (a clear back to the tank included) only when ALL hold:
|
||||
// the change is deliberate; the member is NOT bound (or binding) on the receiver's contract; it is newer than the
|
||||
// receiver's own deliberate change; and the receiver either agreed with the sender before the change
|
||||
// (receiver's sponsor == sponsorPrevEmail), has no sponsor, or has an older deliberate change of its own.
|
||||
// Otherwise nothing moves: 'bound' and 'diverged' are logged for the admin mismatch report (conservative: when the
|
||||
// two sides already disagreed before the change, a person decides).
|
||||
// - Race: both sides changed independently within WINDOW_MS -> the EARLIER change wins on both sides and the case is
|
||||
// logged as a conflict (the later one is undone on the side that made it, and reported, never silently kept).
|
||||
// - Ping-pong: the receiver stores the incoming record unchanged (same at/by/origin), so its own row carries the same
|
||||
// facts back and the sender sees 'same' (plus the hash / registry loop guards of the sync modules).
|
||||
// - Accounts with no record (everything before this shipped) are "old, non-deliberate": nothing is rewritten on deploy.
|
||||
//
|
||||
// Network tank: each platform keeps its own adoptions; rows carry a small tank summary (own adoption count and the open
|
||||
// adoption, if any) which the other side stores as remote state: its waiting list hides a member with an open adoption
|
||||
// elsewhere, and the two-adoptions-per-person lifetime limit counts both platforms. The adoption itself reaches the other
|
||||
// side as an ordinary deliberate follow (by 'adopt'), applied quietly (no chat, mail or feed post there).
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const DELIBERATE = ['adopt', 'rescue', 'release', 'expire', 'admin'];
|
||||
const WINDOW_MS = 15 * 60 * 1000;
|
||||
const PROTO = 2; // wire version: 2 = rows may carry sponsorSet* + tank, peers answer { proto: 2 }
|
||||
const n = v => String(v == null ? '' : v).trim().toLowerCase();
|
||||
const isDeliberate = by => DELIBERATE.includes(String(by || ''));
|
||||
|
||||
// ---- the rule (pure) ----
|
||||
// local { sponsorEmail, prov: {at, by, sponsorEmail, prevEmail, origin} | null, bound: bool }
|
||||
// incoming { sponsorEmail, at, by, prevEmail, origin }
|
||||
// -> { action, apply: bool, conflict: bool, reason }
|
||||
// actions: ordinary (caller keeps today's fill-empty rule) | same | bound | stale | conflict-keep | conflict-apply |
|
||||
// diverged | apply
|
||||
function decide(local, incoming, opts) {
|
||||
const win = (opts && opts.windowMs) || WINDOW_MS;
|
||||
const inc = incoming || {}; const loc = local || {};
|
||||
if (!isDeliberate(inc.by) || !(Number(inc.at) > 0)) return { action: 'ordinary', apply: false, reason: 'not a deliberate change' };
|
||||
if (n(inc.sponsorEmail) === n(loc.sponsorEmail)) return { action: 'same', apply: false, reason: 'already the same sponsor' };
|
||||
if (loc.bound) return { action: 'bound', apply: false, conflict: true, reason: 'member is bound on this contract; the sponsor here cannot move' };
|
||||
const lp = loc.prov && isDeliberate(loc.prov.by) && Number(loc.prov.at) > 0 && n(loc.prov.sponsorEmail) === n(loc.sponsorEmail) ? loc.prov : null;
|
||||
const at = Number(inc.at);
|
||||
if (lp) {
|
||||
const lat = Number(lp.at);
|
||||
// sequential, not a race: the earlier record came from the same platform, or the sender built on our current sponsor
|
||||
const sequential = (lp.origin && inc.origin && n(lp.origin) === n(inc.origin)) || n(inc.prevEmail) === n(loc.sponsorEmail);
|
||||
if (at === lat && !sequential) return { action: 'conflict-keep', apply: false, conflict: true, reason: 'two different changes with the same time; nothing moved' };
|
||||
if (!sequential && Math.abs(at - lat) <= win) {
|
||||
if (at < lat) return { action: 'conflict-apply', apply: true, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (incoming) wins on both' };
|
||||
return { action: 'conflict-keep', apply: false, conflict: true, reason: 'both sides changed within ' + Math.round(win / 60000) + ' min; the earlier change (this side) wins on both' };
|
||||
}
|
||||
if (at <= lat) return { action: 'stale', apply: false, reason: 'this side has a newer deliberate change' };
|
||||
return { action: 'apply', apply: true, reason: 'newer deliberate change' };
|
||||
}
|
||||
if (!n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'no sponsor here' };
|
||||
if (n(inc.prevEmail) === n(loc.sponsorEmail)) return { action: 'apply', apply: true, reason: 'both sides had the same sponsor before the change' };
|
||||
return { action: 'diverged', apply: false, conflict: true, reason: 'the two sides already had different sponsors before this change; left for the admin' };
|
||||
}
|
||||
|
||||
// the follow fields a sync row carries for an account (only while the record still describes the current sponsor)
|
||||
function rowFields(prov, currentSponsorEmail) {
|
||||
if (!prov || !isDeliberate(prov.by) || !(Number(prov.at) > 0)) return null;
|
||||
if (n(prov.sponsorEmail) !== n(currentSponsorEmail)) return null;
|
||||
return { sponsorSetAt: Number(prov.at), sponsorSetBy: prov.by, sponsorPrevEmail: prov.prevEmail ? n(prov.prevEmail) : null, sponsorSetOrigin: prov.origin || null };
|
||||
}
|
||||
// what a received row says about a deliberate change (null when it says nothing)
|
||||
function incomingOf(row) {
|
||||
if (!row || !isDeliberate(row.sponsorSetBy) || !(Number(row.sponsorSetAt) > 0)) return null;
|
||||
return { sponsorEmail: row.sponsorEmail ? n(row.sponsorEmail) : null, at: Number(row.sponsorSetAt), by: String(row.sponsorSetBy), prevEmail: row.sponsorPrevEmail ? n(row.sponsorPrevEmail) : null, origin: row.sponsorSetOrigin ? n(row.sponsorSetOrigin) : null };
|
||||
}
|
||||
// hash suffix: empty when the row has none of the new fields, so every existing row hashes exactly as before (no resend)
|
||||
function hashExtra(r) {
|
||||
const parts = [];
|
||||
if (r && r.sponsorSetBy) parts.push('f:' + [r.sponsorSetAt, r.sponsorSetBy, r.sponsorPrevEmail || '', r.sponsorSetOrigin || ''].join(','));
|
||||
if (r && r.tank) parts.push('t:' + [r.tank.count || 0, r.tank.open ? 1 : 0, r.tank.adopterEmail || '', r.tank.ts || '', r.tank.expires || ''].join(','));
|
||||
return parts.length ? '|' + parts.join('|') : '';
|
||||
}
|
||||
function cleanTank(t) {
|
||||
if (!t || typeof t !== 'object') return null;
|
||||
const count = Math.max(0, Math.min(99, Number(t.count) || 0)); const open = !!t.open;
|
||||
if (!count && !open) return null;
|
||||
return { count, open, adopterEmail: open && t.adopterEmail ? n(t.adopterEmail) : null, ts: open ? Number(t.ts) || null : null, expires: open ? Number(t.expires) || null : null };
|
||||
}
|
||||
|
||||
// ---- store: records, remote tank state, pending follows, the conflict log ----
|
||||
function create(opts) {
|
||||
const platform = n(opts.platform); const dataDir = opts.dataDir;
|
||||
const FILE = () => path.join(dataDir, 'sponsorfollow.json');
|
||||
let st = null;
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||
if (!st || typeof st !== 'object') st = {};
|
||||
st.prov = st.prov || {}; st.remote = st.remote || {}; st.pending = st.pending || {}; st.log = st.log || []; st.peer = st.peer || {};
|
||||
return st;
|
||||
}
|
||||
function save() { try { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('sponsorfollow save', e.message); } }
|
||||
const api = {
|
||||
platform, PROTO, WINDOW_MS, DELIBERATE, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate,
|
||||
get(email) { return load().prov[n(email)] || null; },
|
||||
// a deliberate change made on this platform (origin = this platform), or one received and applied (origin kept)
|
||||
record(email, rec) {
|
||||
const e = n(email); if (!e || !isDeliberate(rec.by)) return null;
|
||||
const r = { at: Number(rec.at) || Date.now(), by: rec.by, sponsorEmail: rec.sponsorEmail ? n(rec.sponsorEmail) : null, prevEmail: rec.prevEmail ? n(rec.prevEmail) : null, origin: n(rec.origin || platform) };
|
||||
if (rec.note) r.note = String(rec.note).slice(0, 160);
|
||||
load().prov[e] = r; save(); return r;
|
||||
},
|
||||
remote(email) { return load().remote[n(email)] || null; },
|
||||
setRemote(email, tank) {
|
||||
const e = n(email); const t = cleanTank(tank); const s = load();
|
||||
const cur = s.remote[e] ? JSON.stringify(s.remote[e]) : null;
|
||||
if (!t) { if (cur) { delete s.remote[e]; save(); } return; }
|
||||
if (cur !== JSON.stringify(t)) { s.remote[e] = t; save(); }
|
||||
},
|
||||
remoteOpen(email, now) { const t = api.remote(email); return !!(t && t.open && (!t.expires || t.expires > (now || Date.now()))); },
|
||||
remoteCount(email) { const t = api.remote(email); return t ? Number(t.count) || 0 : 0; },
|
||||
pending() { return Object.assign({}, load().pending); },
|
||||
pendingFor(email) { return load().pending[n(email)] || null; },
|
||||
setPending(email, incoming, why) { const s = load(); s.pending[n(email)] = Object.assign({}, incoming, { why: String(why || '').slice(0, 120), since: (s.pending[n(email)] && s.pending[n(email)].since) || Date.now() }); save(); },
|
||||
clearPending(email) { const s = load(); if (s.pending[n(email)]) { delete s.pending[n(email)]; save(); } },
|
||||
note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 500) s.log = s.log.slice(-500); save(); },
|
||||
recent(k) { return load().log.slice(-(k || 100)).reverse(); },
|
||||
conflictsFor(email) { const e = n(email); return load().log.filter(x => x.email === e && x.conflict); },
|
||||
setPeer(proto) { const s = load(); if (s.peer.proto !== proto) { s.peer.proto = proto; s.peer.at = Date.now(); save(); } },
|
||||
peerProto() { return Number(load().peer.proto) || 1; },
|
||||
view() { const s = load(); return { records: Object.keys(s.prov).length, remoteTank: Object.keys(s.remote).length, pending: Object.keys(s.pending).length, peerProto: Number(s.peer.proto) || 1, recent: s.log.slice(-40).reverse() }; },
|
||||
_state: load, _reset() { st = null; }
|
||||
};
|
||||
return api;
|
||||
}
|
||||
|
||||
// ---- signed partner calls (the same HMAC the registry sync uses: hex HMAC-SHA256(ts + "\n" + raw), LS_SYNC_SECRET) ----
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
function verify(raw, headers) {
|
||||
const secret = SECRET(); if (secret.length < 32) return { status: 503, error: 'sync not configured' };
|
||||
const ts = String(headers['x-ls-ts'] || ''), sig = String(headers['x-ls-sig'] || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 10 * 60000) return { status: 401, error: 'stale' };
|
||||
const want = crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
|
||||
return null;
|
||||
}
|
||||
async function peerPost(baseUrl, pth, body, timeoutMs) {
|
||||
const secret = SECRET(); if (secret.length < 32) throw new Error('sync not configured (LS_SYNC_SECRET)');
|
||||
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(String(baseUrl).replace(/\/+$/, '') + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 30000) });
|
||||
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
||||
if (!r.ok) throw new Error((j && j.error) || ('peer ' + r.status + ' ' + txt.slice(0, 120)));
|
||||
return j || {};
|
||||
}
|
||||
|
||||
// ---- the admin mismatch report (pure): both sides' facts -> rows that differ ----
|
||||
// facts row: { email, username, sponsorEmail, sponsorRef, prov, bound, boundWhy, memberId, created, joinedVia, adoptions, activation }
|
||||
function mismatches(iapRows, lsRows) {
|
||||
const L = new Map((lsRows || []).map(r => [n(r.email), r]));
|
||||
const out = []; let shared = 0, same = 0;
|
||||
for (const a of iapRows || []) {
|
||||
const b = L.get(n(a.email)); if (!b) continue; shared++;
|
||||
const sa = n(a.sponsorEmail), sb = n(b.sponsorEmail);
|
||||
if (sa === sb) { same++; continue; }
|
||||
out.push({ email: n(a.email), username: a.username || b.username || null, kind: sa && sb ? 'differ' : sa ? 'iap-only' : 'ls-only', iap: a, ls: b });
|
||||
}
|
||||
out.sort((x, y) => (x.kind === 'differ' ? 0 : 1) - (y.kind === 'differ' ? 0 : 1) || x.email.localeCompare(y.email));
|
||||
return { shared, same, rows: out };
|
||||
}
|
||||
|
||||
// ---- the platform glue: one implementation, per-platform hooks ----
|
||||
// deps: { store, accounts, tank: () => tankModule|null, peer: 'linkspin'|'instantadpay',
|
||||
// isBound: async acct => { bound, why, retry }, // retry = cannot tell right now (chain read failed, activation in flight)
|
||||
// sponsorAccount: async email => acct|null, // the sponsor's account here (may build a waiting shell)
|
||||
// wouldCycle: async (email, spAcct) => bool, // optional
|
||||
// activationOf: acct => { id, sponsorId, block, tx } | null,
|
||||
// afterResolve: async email => {} } // optional, after a pending follow is settled
|
||||
function glue(deps) {
|
||||
const S = deps.store, A = deps.accounts;
|
||||
const tokenOf = a => a.username || a.code || (a.memberId ? String(a.memberId) : '');
|
||||
async function accountOfRef(ref) {
|
||||
const t = n(ref); if (!t) return null;
|
||||
return (await A.byUsername(t).catch(() => null)) || (await A.byCode(t).catch(() => null)) || (/^\d+$/.test(t) && A.byMemberId ? await A.byMemberId(Number(t)).catch(() => null) : null) || null;
|
||||
}
|
||||
async function emailOfRef(ref) { const a = await accountOfRef(ref); return a ? n(a.email) : null; }
|
||||
// a deliberate change made on THIS platform: record first (so the ~3 s sync touch already carries it), then write
|
||||
async function setDeliberate(email, token, by, note) {
|
||||
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No such account.' };
|
||||
const prev = await emailOfRef(a.sponsorRef); const tok = n(token);
|
||||
const next = tok ? await emailOfRef(tok) : null;
|
||||
if (isDeliberate(by)) S.record(e, { by, sponsorEmail: next, prevEmail: prev, note });
|
||||
return A.setSponsorRef(e, tok);
|
||||
}
|
||||
async function closeLocalAdoptions(email, inc, d) {
|
||||
const T = deps.tank && deps.tank(); if (!T || !T.onFollow) return;
|
||||
try { await T.onFollow(email, inc, d); } catch (e) { console.error('tank onFollow', e.message); }
|
||||
}
|
||||
// a row from the other platform that carries a deliberate change
|
||||
async function applyIncoming(email, row, opts) {
|
||||
const inc = incomingOf(row); if (!inc) return { action: 'ordinary' };
|
||||
const e = n(email); const a = await A.byEmail(e); if (!a) return { action: 'no-account' };
|
||||
const cur = await emailOfRef(a.sponsorRef);
|
||||
if (n(cur) === n(inc.sponsorEmail)) { S.clearPending(e); return { action: 'same', apply: false }; } // nothing to move (no chain read needed)
|
||||
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: 'bound check failed: ' + err.message }))) || {};
|
||||
if (b.retry && !b.bound) { S.setPending(e, inc, b.why); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: b.why }); return { action: 'pending', reason: b.why }; }
|
||||
const d = decide({ sponsorEmail: cur, prov: S.get(e), bound: !!b.bound }, inc, opts);
|
||||
if (!d.apply) {
|
||||
S.clearPending(e);
|
||||
if (d.action !== 'same') S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, prev: inc.prevEmail, reason: d.reason + (b.bound && b.why ? ' (' + b.why + ')' : ''), conflict: !!d.conflict });
|
||||
return d;
|
||||
}
|
||||
let tok = '';
|
||||
if (inc.sponsorEmail) {
|
||||
const sp = await ((opts && opts.sponsorAccount) || deps.sponsorAccount)(inc.sponsorEmail);
|
||||
if (!sp) { S.setPending(e, inc, 'the new sponsor has no account here yet'); S.note({ email: e, action: 'pending', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'sponsor account missing' }); return { action: 'pending', reason: 'sponsor account missing' }; }
|
||||
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) { S.clearPending(e); S.note({ email: e, action: 'refused', by: inc.by, from: cur, to: inc.sponsorEmail, reason: 'would sponsor themselves or close a loop', conflict: true }); return { action: 'refused', reason: 'loop' }; }
|
||||
tok = tokenOf(sp);
|
||||
if (!tok) { S.setPending(e, inc, 'the new sponsor has no username or code here yet'); return { action: 'pending', reason: 'sponsor token missing' }; }
|
||||
}
|
||||
S.record(e, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || deps.peer });
|
||||
const r = await A.setSponsorRef(e, tok);
|
||||
if (r && r.error) { S.note({ email: e, action: 'error', reason: r.error, conflict: true }); return { action: 'error', reason: r.error }; }
|
||||
await closeLocalAdoptions(e, inc, d);
|
||||
S.clearPending(e);
|
||||
S.note({ email: e, action: d.action, by: inc.by, at: inc.at, origin: inc.origin, from: cur, to: inc.sponsorEmail, reason: d.reason, conflict: !!d.conflict });
|
||||
return d;
|
||||
}
|
||||
// follows that could not be settled yet (chain unreadable, activation in flight, sponsor not here yet): retried on the sync tick
|
||||
async function retryPending(maxAgeMs) {
|
||||
const out = { tried: 0, settled: 0, dropped: 0 }; const now = Date.now();
|
||||
for (const [e, p] of Object.entries(S.pending())) {
|
||||
if (now - (p.since || now) > (maxAgeMs || 7 * 86400000)) { S.clearPending(e); S.note({ email: e, action: 'gave-up', by: p.by, to: p.sponsorEmail, reason: 'pending for 7 days: ' + (p.why || ''), conflict: true }); out.dropped++; continue; }
|
||||
out.tried++;
|
||||
const r = await applyIncoming(e, { sponsorEmail: p.sponsorEmail, sponsorSetAt: p.at, sponsorSetBy: p.by, sponsorPrevEmail: p.prevEmail, sponsorSetOrigin: p.origin }).catch(err => ({ action: 'error', reason: err.message }));
|
||||
if (r.action !== 'pending') { out.settled++; if (deps.afterResolve) { try { await deps.afterResolve(e); } catch (err) {} } }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// the admin's pick in the mismatch report: apply `sponsorEmail` (null = back to the tank) here unless bound here
|
||||
async function adminApply(email, sponsorEmail, opts) {
|
||||
const e = n(email); const a = await A.byEmail(e); if (!a) return { error: 'No account for ' + e + ' here.' };
|
||||
const b = (await deps.isBound(a).catch(err => ({ retry: true, why: err.message }))) || {};
|
||||
if (b.bound) return { error: 'Refused: ' + e + ' is already bound on this platform\'s contract (' + (b.why || 'on chain') + '). Its sponsor here cannot change.' };
|
||||
if (b.retry) return { error: 'Could not confirm that ' + e + ' is not on the contract yet (' + (b.why || 'chain read failed') + '). Nothing changed. Try again in a minute.' };
|
||||
let tok = '';
|
||||
if (sponsorEmail) {
|
||||
const sp = await deps.sponsorAccount(n(sponsorEmail));
|
||||
if (!sp) return { error: 'The sponsor ' + n(sponsorEmail) + ' has no account here. Nothing changed.' };
|
||||
if (n(sp.email) === e || (deps.wouldCycle && await deps.wouldCycle(e, sp))) return { error: 'That would make the member their own upline. Nothing changed.' };
|
||||
tok = tokenOf(sp); if (!tok) return { error: 'The sponsor has no username or code here yet. Nothing changed.' };
|
||||
}
|
||||
const prev = await emailOfRef(a.sponsorRef);
|
||||
S.record(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null, prevEmail: prev, origin: (opts && opts.origin) || S.platform, note: (opts && opts.note) || 'mismatch report' });
|
||||
const r = await A.setSponsorRef(e, tok); if (r && r.error) return r;
|
||||
await closeLocalAdoptions(e, { by: 'admin', sponsorEmail: sponsorEmail ? n(sponsorEmail) : null }, { action: 'admin' });
|
||||
S.clearPending(e);
|
||||
S.note({ email: e, action: 'admin-fix', by: 'admin', from: prev, to: sponsorEmail ? n(sponsorEmail) : null, reason: (opts && opts.note) || 'mismatch report' });
|
||||
return { ok: true, email: e, from: prev, to: sponsorEmail ? n(sponsorEmail) : null };
|
||||
}
|
||||
// this platform's facts for the mismatch report (no chain reads: memberId + the indexed activation event)
|
||||
async function facts(onlyEmails) {
|
||||
const all = await A.listAll(50000, { shells: true });
|
||||
const only = onlyEmails && onlyEmails.length ? new Set(onlyEmails.map(n)) : null;
|
||||
const byTok = new Map(); for (const a of all) { if (a.username) byTok.set(n(a.username), a); if (a.code) byTok.set(n(a.code), a); if (a.memberId) byTok.set(String(a.memberId), a); }
|
||||
const T = deps.tank && deps.tank();
|
||||
const hist = T && T.historyMap ? await T.historyMap().catch(() => new Map()) : new Map();
|
||||
const logBy = new Map(); for (const x of S.recent(500)) { if (!x.email) continue; if (!logBy.has(x.email)) logBy.set(x.email, []); if (logBy.get(x.email).length < 6) logBy.get(x.email).push(x); }
|
||||
return all.filter(a => a.email && (!only || only.has(n(a.email)))).map(a => {
|
||||
const e = n(a.email); const sp = a.sponsorRef ? byTok.get(n(a.sponsorRef)) : null;
|
||||
const act = deps.activationOf ? deps.activationOf(a) : null;
|
||||
return { email: e, username: a.username || null, sponsorRef: a.sponsorRef || '', sponsorEmail: sp && n(sp.email) !== e ? n(sp.email) : null, sponsorName: sp ? (sp.username ? '@' + sp.username : n(sp.email)) : null,
|
||||
deadLink: !!(a.sponsorRef && !sp), prov: S.get(e), memberId: Number(a.memberId) || 0, bound: Number(a.memberId) > 0 || !!act, activation: act || null,
|
||||
created: Number(a.created) || null, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null, lastSeen: Number(a.lastSeen) || 0, wallet: !!a.address,
|
||||
adoptions: hist.get(e) || [], remoteTank: S.remote(e), pending: S.pendingFor(e), log: logBy.get(e) || [] };
|
||||
});
|
||||
}
|
||||
return { setDeliberate, applyIncoming, retryPending, adminApply, facts, emailOfRef, accountOfRef, tokenOf };
|
||||
}
|
||||
|
||||
module.exports = { create, glue, decide, rowFields, incomingOf, hashExtra, cleanTank, isDeliberate, verify, peerPost, mismatches, DELIBERATE, WINDOW_MS, PROTO };
|
||||
@@ -15,6 +15,9 @@ const CAP_OPEN = 2; // open adoptions per adopter
|
||||
const TTL_MS = 7 * 86400000; // an adoption's window to convert
|
||||
const MAX_ADOPTIONS = 2; // per adoptee, lifetime (dropped adoptions count too, since 2026-09-13)
|
||||
const HOLD_MS = 3 * 24 * 3600 * 1000; // an adoption is a commitment: no releasing someone you picked up less than 3 days ago (Marty, 2026-09-13)
|
||||
// statuses that do not count toward a person's two adoptions: a release record, and the later side of a network race
|
||||
// (both sites adopted the same person within minutes; the earlier adoption won on both, sponsorfollow.js)
|
||||
const NOT_COUNTED = ['released', 'conflict'];
|
||||
const MIN_OWN_BUY_CENTS = 2000; // adopter must have bought a $20+ package themselves
|
||||
const WARN_DAYS = 10; // dormant lead: sponsor warned after this many days without contact
|
||||
const RESCUE_DAYS = 14; // ...and the lead moves to the tank after this many (warning at least 4 days old)
|
||||
@@ -28,10 +31,11 @@ const J = {
|
||||
save() { try { fs.writeFileSync(this.FILE(), JSON.stringify(this.db)); } catch (e) {} },
|
||||
async add(a) { const row = Object.assign({ id: this.db.nextId++ }, a); this.db.adoptions.push(row); this.save(); return row; },
|
||||
async open(adopter) { return this.db.adoptions.filter(x => x.status === 'open' && (!adopter || x.adopter === adopter)); },
|
||||
async countFor(adoptee) { return this.db.adoptions.filter(x => x.adoptee === adoptee && x.status !== 'released').length; },
|
||||
async countFor(adoptee) { return this.db.adoptions.filter(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)).length; },
|
||||
async setStatus(id, status) { const x = this.db.adoptions.find(r => r.id === id); if (x) { x.status = status; x.closed = Date.now(); this.save(); } },
|
||||
async recent(n) { return this.db.adoptions.slice(-(n || 100)).reverse(); },
|
||||
async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && x.status !== 'released'); },
|
||||
async hasRecord(adoptee) { return this.db.adoptions.some(x => x.adoptee === adoptee && !NOT_COUNTED.includes(x.status)); },
|
||||
async all() { return this.db.adoptions.slice(); },
|
||||
async mark(lead) { return this.db.marks[lead] || null; },
|
||||
async setMark(lead, f) { this.db.marks[lead] = Object.assign(this.db.marks[lead] || {}, f); this.save(); }
|
||||
};
|
||||
@@ -44,10 +48,11 @@ const D = {
|
||||
const rows = adopter ? await db.q("SELECT * FROM adoptions WHERE status='open' AND adopter=?", [adopter]) : await db.q("SELECT * FROM adoptions WHERE status='open'");
|
||||
return rows.map(rowA);
|
||||
},
|
||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status<>'released'", [adoptee]); return Number(r[0].n); },
|
||||
async countFor(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n); },
|
||||
async setStatus(id, status) { await db.q('UPDATE adoptions SET status=?, closed=? WHERE id=?', [status, Date.now(), Number(id)]); },
|
||||
async recent(n) { return (await db.q('SELECT * FROM adoptions ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowA); },
|
||||
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status<>'released'", [adoptee]); return Number(r[0].n) > 0; },
|
||||
async hasRecord(adoptee) { const r = await db.q("SELECT COUNT(*) n FROM adoptions WHERE adoptee=? AND status NOT IN ('released','conflict')", [adoptee]); return Number(r[0].n) > 0; },
|
||||
async all() { return (await db.q('SELECT * FROM adoptions ORDER BY id')).map(rowA); },
|
||||
async mark(lead) { const r = await db.q('SELECT * FROM lead_marks WHERE `lead`=?', [lead]); return r[0] ? { sponsor: r[0].sponsor, contacted: Number(r[0].contacted_ts || 0), warned: Number(r[0].warned_ts || 0) } : null; },
|
||||
async setMark(lead, f) {
|
||||
const cur = (await this.mark(lead)) || {}; const m = Object.assign(cur, f);
|
||||
@@ -58,7 +63,15 @@ const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Numbe
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
let ads = null;
|
||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; J.load(); }
|
||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; if (opts.site) siteUrl = opts.site; follow = opts.follow || null; store = opts.store || null; J.load(); }
|
||||
// every sponsor change the tank makes is deliberate: recorded (when, how, the sponsor before) so it follows to LinkSpin
|
||||
// until the member is bound on a contract (sponsorfollow.js). Without the follow glue (tests) it is a plain write.
|
||||
let follow = null, store = null;
|
||||
const setSponsor = (email, token, by, note) => follow ? follow.setDeliberate(email, token, by, note) : accounts.setSponsorRef(email, token);
|
||||
const OTHER = 'LinkSpin';
|
||||
const remoteOpen = email => !!(store && store.remoteOpen(email));
|
||||
const remoteCount = email => store ? store.remoteCount(email) : 0;
|
||||
const countAll = async email => (await impl().countFor(email)) + remoteCount(email); // the two-adoptions limit counts both platforms
|
||||
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
||||
@@ -67,7 +80,7 @@ const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or
|
||||
// waiting list: newest sign-in first so a live one is easy to spot
|
||||
async function waiting() {
|
||||
const all = await accounts.listAll(5000);
|
||||
const rows = all.filter(inTank);
|
||||
const rows = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
||||
// what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers
|
||||
const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {};
|
||||
return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0,
|
||||
@@ -113,9 +126,10 @@ async function adopt(adopterEmail, who, note) {
|
||||
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
||||
if (!target) return { error: 'That member is no longer in the tank.' };
|
||||
if (target.email === e) return { error: 'That is you.' };
|
||||
if (await impl().countFor(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' };
|
||||
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
|
||||
if (await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' };
|
||||
const token = me.username || me.code || String(me.memberId);
|
||||
const r = await accounts.setSponsorRef(target.email, token);
|
||||
const r = await setSponsor(target.email, token, 'adopt');
|
||||
if (r.error) return r;
|
||||
const now = Date.now();
|
||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. You joined InstantAdPay without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||
@@ -140,12 +154,15 @@ async function release(ownerEmail, directEmail) {
|
||||
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
|
||||
// picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13)
|
||||
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
|
||||
const young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
||||
let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
||||
// adopted on LinkSpin by this same member: the same 3-day commitment applies here
|
||||
const rt = store && store.remote(d);
|
||||
if (!young && rt && rt.open && rt.adopterEmail === o && rt.ts && Date.now() - rt.ts < HOLD_MS && remoteOpen(d)) young = { ts: rt.ts };
|
||||
if (young) {
|
||||
const hrs = Math.ceil((HOLD_MS - (Date.now() - young.ts)) / 3600000);
|
||||
return { error: 'You picked ' + nameOf(direct) + ' up from the tank ' + Math.max(1, Math.round((Date.now() - young.ts) / 3600000)) + ' hour(s) ago. An adoption is a commitment: message them, help them link a wallet, and if it goes nowhere you can release them in ' + hrs + ' hour(s).' };
|
||||
}
|
||||
const r = await accounts.setSponsorRef(d, '');
|
||||
const r = await setSponsor(d, '', 'release');
|
||||
if (r.error) return r;
|
||||
// an open adoption of this person closes as dropped, and a dropped adoption still counts toward their two
|
||||
let closed = 0;
|
||||
@@ -165,7 +182,7 @@ async function sweep() {
|
||||
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
||||
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
|
||||
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||
await accounts.setSponsorRef(ad.adoptee, '');
|
||||
await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
|
||||
await impl().setStatus(ad.id, 'expired'); back++;
|
||||
}
|
||||
const r = await rescueSweep();
|
||||
@@ -231,10 +248,12 @@ async function rescueSweep() {
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
|
||||
if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules
|
||||
const pv = store && store.get(a.email);
|
||||
if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on LinkSpin: the tank's window rules there
|
||||
const sp = await sponsorOf(a);
|
||||
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
||||
if (now - (a.created || 0) < 86400000) continue;
|
||||
await accounts.setSponsorRef(a.email, '');
|
||||
await setSponsor(a.email, '', 'rescue', 'dead sponsor link ' + a.sponsorRef);
|
||||
await impl().add({ adoptee: a.email, adopter: 'dead:' + a.sponsorRef, ts: now, expires: now, status: 'rescued', note: 'sponsor link ' + a.sponsorRef + ' resolves to nobody' });
|
||||
dead++; continue;
|
||||
}
|
||||
@@ -250,7 +269,7 @@ async function rescueSweep() {
|
||||
warned++; continue;
|
||||
}
|
||||
if (days >= RESCUE_DAYS && now - m.warned >= (RESCUE_DAYS - WARN_DAYS) * 86400000) {
|
||||
await accounts.setSponsorRef(a.email, '');
|
||||
await setSponsor(a.email, '', 'rescue', 'no contact for ' + Math.floor(days) + ' days');
|
||||
await impl().add({ adoptee: a.email, adopter: sp.email, ts: now, expires: now, status: 'rescued', note: 'rescued from ' + nameOf(sp) + ' after ' + Math.floor(days) + ' days without contact' });
|
||||
if (mailer && mailer.hasKey()) { try { await mailer.send(sp.email, 'InstantAdPay: ' + nameOf(a) + ' moved to the holding tank',
|
||||
nameOf(a) + ' joined through your link ' + Math.floor(days) + ' days ago and was never contacted, so they have moved to the holding tank where another member can pick them up. Nothing on-chain changed. Your other referrals are unaffected.\n\n' + siteUrl + '/my#line'); } catch (e) {} }
|
||||
@@ -260,6 +279,35 @@ async function rescueSweep() {
|
||||
return { warned, rescued, dead };
|
||||
}
|
||||
|
||||
// -- network tank (sponsorfollow.js) --
|
||||
// a deliberate sponsor change arrived from LinkSpin and was applied here: open adoptions of this person by someone else
|
||||
// close quietly (no chat, no mail: the platform where it happened already told everyone)
|
||||
async function onFollow(email, inc, d) {
|
||||
const e = String(email || '').toLowerCase(); const to = String((inc && inc.sponsorEmail) || '').toLowerCase();
|
||||
const status = d && d.conflict ? 'conflict' : ({ release: 'dropped', expire: 'expired', rescue: 'expired' }[inc && inc.by] || 'moved');
|
||||
let closed = 0;
|
||||
for (const ad of await impl().open(null)) if (ad.adoptee === e && ad.adopter !== to) { await impl().setStatus(ad.id, status); closed++; }
|
||||
return closed;
|
||||
}
|
||||
// what a sync row says about this platform's own adoptions of a person: how many count, and the open one if any
|
||||
function summaryOf(rows) {
|
||||
let count = 0, open = null;
|
||||
for (const x of rows) { if (!NOT_COUNTED.includes(x.status)) count++; if (x.status === 'open' && (!open || x.ts > open.ts)) open = x; }
|
||||
if (!count && !open) return null;
|
||||
return { count, open: !!open, adopterEmail: open ? open.adopter : null, ts: open ? open.ts : null, expires: open ? open.expires : null };
|
||||
}
|
||||
async function summaryMap() {
|
||||
const by = new Map(); for (const x of await impl().all()) { if (!by.has(x.adoptee)) by.set(x.adoptee, []); by.get(x.adoptee).push(x); }
|
||||
const out = new Map(); for (const [k, rows] of by) { const s = summaryOf(rows); if (s) out.set(k, s); } return out;
|
||||
}
|
||||
async function summaryFor(email) { const e = String(email || '').toLowerCase(); return summaryOf((await impl().all()).filter(x => x.adoptee === e)); }
|
||||
async function historyMap() {
|
||||
const out = new Map();
|
||||
for (const x of await impl().all()) { if (!out.has(x.adoptee)) out.set(x.adoptee, []); out.get(x.adoptee).push({ adopter: x.adopter, ts: x.ts, status: x.status, closed: x.closed || null, note: x.status === 'open' ? null : (x.note || null) }); }
|
||||
for (const v of out.values()) v.splice(0, Math.max(0, v.length - 6));
|
||||
return out;
|
||||
}
|
||||
|
||||
async function adminView() {
|
||||
const recent = await impl().recent(200);
|
||||
const names = {};
|
||||
@@ -267,4 +315,4 @@ async function adminView() {
|
||||
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: CAP_OPEN, ttlDays: TTL_MS / 86400000 };
|
||||
}
|
||||
|
||||
module.exports = { init, view, adopt, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS };
|
||||
module.exports = { init, view, adopt, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, CAP_OPEN, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||
|
||||
Reference in New Issue
Block a user