Sponsor follow + one network holding tank + Sponsor check (Marty, 2026-10-22, approved 1-3)
Same design as InstantAdPay (shared sponsorfollow.js). Deliberate sponsor changes (tank adoption, rescue, release, adoption window ending, admin edit) are recorded and travel on the iapsync rows; InstantAdPay's deliberate changes are applied here only when the member is not bound or binding on the LinkSpin contract (memberId, wallet on chain, or an engine activation in flight), newer than our own, and both sides agreed before (or no sponsor here). Bound / diverged / race cases change nothing and are logged. Ordinary rows keep the fill-empty rule, except a sponsor emptied on purpose here is not refilled by an ordinary row. Carry: an InstantAdPay batch holds its members (carry.hold) so no auto-activation starts mid-batch; ensureOnChain waits, then re-reads the account so the contract binds the settled sponsor; wallets from a batch are linked after every sponsor decision; the wallet hook skips activation while a follow is pending and activates once it is settled. Registry keeps the follow record (loop guard) and a deliberate clear. Network tank, Admin > Members > Sponsor check and the partner endpoints as on InstantAdPay. Rows without the new facts hash as before (no resend on deploy). Tests: qa/sponsorfollow.test.cjs 27/27, qa/carry-hold.test.cjs ok, two-server e2e (in the InstantAdPay repo) 20/20, QA member walk 0 bugs. No sponsor was changed on production. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -16,6 +16,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 = 2500; // adopter must have bought a qualifying ($25+) 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)
|
||||
@@ -29,10 +32,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(); }
|
||||
};
|
||||
@@ -45,10 +49,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 D = {
|
||||
const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Number(r.ts), expires: Number(r.expires), status: r.status, note: r.note || null, closed: r.closed ? Number(r.closed) : null });
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; 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; 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 InstantAdPay
|
||||
// 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 = 'InstantAdPay';
|
||||
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(2000);
|
||||
return all.filter(inTank).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: false }))
|
||||
return all.filter(a => inTank(a) && !remoteOpen(a.email)).map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: false }))
|
||||
.sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
||||
}
|
||||
|
||||
@@ -108,9 +121,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 LinkSpin 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.');
|
||||
@@ -135,12 +149,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 InstantAdPay 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;
|
||||
@@ -160,7 +177,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();
|
||||
@@ -230,10 +247,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 InstantAdPay: 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;
|
||||
}
|
||||
@@ -249,7 +268,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, 'LinkSpin: ' + 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) {} }
|
||||
@@ -259,6 +278,35 @@ async function rescueSweep() {
|
||||
return { warned, rescued, dead };
|
||||
}
|
||||
|
||||
// -- network tank (sponsorfollow.js) --
|
||||
// a deliberate sponsor change arrived from InstantAdPay 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 = {};
|
||||
@@ -266,4 +314,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