Holding tank on LinkSpin (ported from InstantAdPay 4645d56, Marty 2026-10-27): network sponsor ALIGNMENT first, the free activation held (never a purchase), 24-hour rotation, payouts switched on the moment someone is assigned
- Align first, every path (/api/me, /api/sponsor all intents incl. buy, carry.ensureOnChain via tank.gate, 15-min readyTick): a tank member (no sponsorRef, no member number, no resolvable cookie) whose email has a sponsor in the InstantAdPay registry rows, else a signed sponsor-facts call (3 s timeout, 10 min cache, one batch per tick), else the same wallet, is placed under that sponsor through accounts.setSponsorRef when the sponsor has a LinkSpin account; never a sponsor they were adopted/released/rescued away from, never a loop. Recorded in tank-ready.json, listed in Admin tank - Hold ONLY the plain Switch on payouts (Marty: "I would never want to hold up a purchase ... they'll just pay number one"): the engine's wallet-link activation and seeding wait, /api/sponsor?intent=activate answers sponsorBlocked tankHold; intent=buy and /api/me never block (buys go ahead under #1 as before). A sponsor activated because someone below is buying is never held. Activate buttons now call intent=activate - Ready badge + hours left (My line tank, Admin tank, Overview count); one shared-payments-topic line per newly ready member (digest when more than 3) - 24-hour rotation through adopt(): own $25+ buy, fewer than 2 open, seen within 7 days, not company/#1, not a no-payout chain, not own downline; least recently auto-assigned first. Nobody eligible: keep holding, one admin alert. Never #1 - Payouts on at assignment (Marty approved 2026-10-27): adopted, auto-assigned or aligned member with a wallet is activated right away by carry.activateAssigned (strict: sponsor must be on the contract and not on a no-payout chain, never the fallback; retried every tick for 7 days); the auto-assign chat/email say "Your payouts are now on under @sponsor" with the Polygonscan link, a manual adoption gets a follow-up chat + email - Deploy overlap: marks.js claims for the activation (per member per 10 min), the auto-assign, the ready post and the admin alert - Cross-site: someone waiting in InstantAdPay's own tank (claimed account there, no sponsor, not a member there, wallet linked) is auto-assigned by InstantAdPay only (live sponsor-facts, registry fallback); LinkSpin defers and does not post them - Chatbot: tank-hold canned answer, holding-tank answer + facts, KNOWLEDGE_DATE 2026-10-27; cache tags my.js / credits-screen.js / admin.js 20261027th - QA: qa/tank-hold.test.mjs (unit with mocked clock + fake engine, then a local copy with a mock InstantAdPay and a browser check of Credits), qa/carry-activate.test.cjs (regression for the 10-22 scoping bug), run.sh tankhold + sponsorfollow; run.sh borrows InstantAdPay's node_modules when this checkout has none Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -63,7 +63,8 @@ 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; follow = opts.follow || null; store = opts.store || null; 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();
|
||||
hooks = opts.hooks || {}; RS.st = null; RS.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;
|
||||
@@ -80,8 +81,11 @@ 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(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));
|
||||
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: !!a.address,
|
||||
// wallet linked = ready to switch on payouts, the plain activation held for an adopter (24-hour clock, autoAssign after that)
|
||||
...(() => { const r = a.address ? readyRec(a.email) : null; return r ? { ready: true, readyAt: r.readyAt, holdUntil: r.readyAt + READY_MS } : { ready: false }; })() }))
|
||||
// ready members first (least time left first), then newest sign-in
|
||||
.sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0) || (a.ready && b.ready ? a.readyAt - b.readyAt : 0) || (b.lastSeen || b.joined) - (a.lastSeen || a.joined));
|
||||
}
|
||||
|
||||
// has this member bought a $25 or larger package themselves? (the qualifying-for-yourself buy)
|
||||
@@ -108,10 +112,11 @@ async function view(email) {
|
||||
const a = await accounts.byEmail(ad.adoptee);
|
||||
mine.push({ id: ad.id, name: a ? nameOf(a) : mask(ad.adoptee), email: ad.adoptee, ts: ad.ts, expires: ad.expires, lastSeen: a ? (a.lastSeen || 0) : 0, wallet: !!(a && a.address), address: (a && a.address) || null, bought: !!(a && a.memberId) });
|
||||
}
|
||||
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, waiting: await waiting(), mine };
|
||||
return { eligible: el.ok, reason: el.ok ? '' : el.reason, cap: CAP_OPEN, ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, waiting: await waiting(), mine };
|
||||
}
|
||||
|
||||
async function adopt(adopterEmail, who, note) {
|
||||
async function adopt(adopterEmail, who, note, opts) {
|
||||
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
||||
const e = String(adopterEmail || '').toLowerCase();
|
||||
const el = await eligibility(e);
|
||||
if (!el.ok) return { error: el.reason };
|
||||
@@ -122,21 +127,36 @@ async function adopt(adopterEmail, who, note) {
|
||||
if (!target) return { error: 'That member is no longer in the tank.' };
|
||||
if (target.email === e) return { error: 'That is you.' };
|
||||
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.' };
|
||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
||||
const token = me.username || me.code || String(me.memberId);
|
||||
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.');
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: text });
|
||||
try { await messages.sendChat(me.memberId || 0, e, target.email, text); } catch (err) {}
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
||||
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = clock(); rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
|
||||
// wallet already linked: the engine switches their payouts on under the adopter right away (Marty approved 2026-10-27)
|
||||
let act = null; const tgt = await accounts.byEmail(target.email);
|
||||
if (tgt && tgt.address && !(Number(tgt.memberId) > 0) && hooks.lifted) {
|
||||
markLift(target.email);
|
||||
if (auto) act = await liftRun(target.email, { quiet: true });
|
||||
else liftRun(target.email).catch(err => console.error('tank lift', err.message));
|
||||
}
|
||||
const payLine = act && act.id && act.tx ? '\n\nYour payouts are now on under ' + nameOf(me) + ': the site placed your wallet on the LinkSpin contract, so purchases in your line pay you from now on. Proof: ' + txLink(act.tx) : '';
|
||||
try { await messages.sendChat(me.memberId || 0, e, target.email, text + payLine); } catch (err) {}
|
||||
if (mailer && mailer.hasKey()) {
|
||||
try {
|
||||
await mailer.send(target.email, nameOf(me) + ' is now your sponsor on LinkSpin',
|
||||
'You joined LinkSpin without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nLinkSpin');
|
||||
'You joined LinkSpin without a sponsor. ' + nameOf(me) + ' has picked you up from the holding tank and is your sponsor now, which means a real person to walk you through the first steps.\n\nTheir message:\n\n' + text + payLine + '\n\nReply in your member area: ' + siteUrl + '/my#messages\n\nLinkSpin');
|
||||
} catch (err) {}
|
||||
if (auto) {
|
||||
try {
|
||||
await mailer.send(e, 'LinkSpin: ' + target.name + ' from the holding tank is now in your line',
|
||||
target.name + ' linked a wallet and waited 24 hours in the holding tank without anyone picking them up, so the site assigned them to you (adopters take turns). You are their sponsor now: ' + (act && act.id ? 'their payouts are switched on under you' : 'their payouts switch on under you as soon as the engine can place them') + ', and their purchases pay you.\n\nWe sent them this chat from you:\n\n' + text + '\n\nSay hello and help them with their first steps: ' + siteUrl + '/tools#line\n\nLinkSpin');
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
return { ok: true, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
||||
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
||||
}
|
||||
|
||||
// pay it forward: give one of your own free referrals to the tank
|
||||
@@ -181,7 +201,8 @@ async function sweep() {
|
||||
await impl().setStatus(ad.id, 'expired'); back++;
|
||||
}
|
||||
const r = await rescueSweep();
|
||||
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead };
|
||||
const au = await autoAssign().catch(e => { console.error('tank autoAssign', e.message); return { assigned: [], held: 0 }; }); // the 24-hour safety net (also every 15 min in readyTick)
|
||||
return { done, back, kept, warned: r.warned, rescued: r.rescued, dead: r.dead, autoAssigned: au.assigned.length, held: au.held };
|
||||
}
|
||||
|
||||
// pay-it-forward gift record: the sponsor already sent POL wallet-to-wallet; we
|
||||
@@ -307,11 +328,250 @@ async function historyMap() {
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── network alignment + activation hold (2026-10-27, ported from InstantAdPay 4645d56) ──
|
||||
// Marty: "on LinkSpin we should always attempt to align with the sponsor first. That's the goal and a top priority."
|
||||
// The contract binds a sponsor for good at the first activation or purchase. A tank member (no sponsor, no member
|
||||
// number) used to be bound under the fallback position (#1) the moment a wallet landed (the engine switches payouts on
|
||||
// at wallet link), which took them out of the tank for ever. Now, in this order:
|
||||
// 1. ALIGN (every path: /api/me, /api/sponsor incl. buys, carry.ensureOnChain, the 15-minute tick): someone the
|
||||
// network already knows (InstantAdPay has a sponsor for the same email or wallet: the registry rows it sends, else
|
||||
// a short signed sponsor-facts call) is placed under that sponsor, when the sponsor has an account here, is not a
|
||||
// sponsor this person was released / rescued / adopted away from, and it closes no loop. Ordinary sponsor write
|
||||
// (accounts.setSponsorRef): InstantAdPay already agrees, so nothing follows anywhere; the walk-up then works as usual.
|
||||
// 2. HOLD, only a plain "switch on payouts" with no purchase (Marty, 2026-10-27: "I would never want to hold up a
|
||||
// purchase ... they'll just pay number one"): the engine's wallet-link activation and the free Switch on payouts
|
||||
// button wait for an adopter. A purchase always goes ahead (under #1 when nobody is known). The clock starts when
|
||||
// the member is first seen in the tank with a wallet linked ("ready").
|
||||
// 3. SAFETY NET: a ready member nobody adopted within 24 hours goes to the next eligible adopter in rotation (least
|
||||
// recently auto-assigned first, ties by who qualified first) through the same adopt() path. Nobody eligible: keep
|
||||
// holding, alert the admin once. Never the company.
|
||||
// Cross-site: someone InstantAdPay holds in ITS tank (a real account there, no sponsor, not bound there) is
|
||||
// auto-assigned by InstantAdPay only (hooks.iapOwns); their adoption follows here as an ordinary 'adopt' follow.
|
||||
const READY_MS = 24 * 3600 * 1000; // the longest a ready member is held
|
||||
const TICK_MS = 15 * 60 * 1000; // readyTick cadence: auto-assign starts one tick early so the hold never runs past 24 h
|
||||
const AUTO_SEEN_MS = 7 * 86400000; // an auto-assign adopter signed in within the last 7 days
|
||||
let hooks = {};
|
||||
let clock = () => Date.now(); // qa/tank-hold.test.mjs mocks it
|
||||
function setClock(fn) { clock = typeof fn === 'function' ? fn : (() => Date.now()); }
|
||||
const RS = {
|
||||
st: null, FILE: () => path.join(DATA_DIR, 'tank-ready.json'),
|
||||
load() {
|
||||
if (this.st) return this.st;
|
||||
try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; }
|
||||
if (!this.st || typeof this.st !== 'object') this.st = {};
|
||||
this.st.ready = this.st.ready || {}; this.st.adopters = this.st.adopters || {}; this.st.aligned = this.st.aligned || [];
|
||||
return this.st;
|
||||
},
|
||||
save() { try { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('tank-ready save', e.message); } }
|
||||
};
|
||||
const holdOf = rec => rec ? { since: rec.readyAt, until: rec.readyAt + READY_MS } : null;
|
||||
// first time seen in the tank with a wallet linked: the 24-hour clock starts (accounts already linked at deploy start then)
|
||||
function markReady(a) {
|
||||
if (!a || !inTank(a) || !a.address) return null;
|
||||
const st = RS.load(); const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
||||
const cur = st.ready[e];
|
||||
if (!cur || cur.done) { st.ready[e] = { readyAt: clock(), notified: cur ? cur.notified || false : false }; RS.save(); } // back in the tank later: a fresh clock
|
||||
return st.ready[e];
|
||||
}
|
||||
function readyRec(email) { const r = RS.load().ready[String(email || '').toLowerCase()]; return r && !r.done ? r : null; }
|
||||
// sponsors this person was moved away from on purpose (adopted then dropped, released, rescued) never count
|
||||
async function previousSponsors(email) {
|
||||
const e = String(email || '').toLowerCase(); const out = new Set();
|
||||
for (const ad of await impl().all()) if (ad.adoptee === e && ad.adopter && !String(ad.adopter).startsWith('dead:')) out.add(String(ad.adopter).toLowerCase());
|
||||
const pv = store && store.get(e); if (pv && pv.prevEmail) out.add(String(pv.prevEmail).toLowerCase());
|
||||
const m = await impl().mark(e); if (m && m.sponsor) out.add(String(m.sponsor).toLowerCase());
|
||||
return out;
|
||||
}
|
||||
async function alignToNetwork(a, opts) {
|
||||
if (!a || !inTank(a) || !hooks.network) return null;
|
||||
const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
||||
const n = await Promise.resolve(hooks.network(e, a.address || null)).catch(() => null); if (!n || !n.sponsorEmail) return null;
|
||||
const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null;
|
||||
if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from
|
||||
const sp = await accounts.byEmail(spEmail); if (!sp) return null; // the sponsor must have a LinkSpin account (a carried shell counts: the walk-up covers no wallet)
|
||||
if (hooks.isSuspended && hooks.isSuspended(sp.email)) return null;
|
||||
const token = sp.username || sp.code || (sp.memberId ? String(sp.memberId) : ''); if (!token) return null;
|
||||
let cur = sp; const seen = new Set(); // never a loop (they cannot sit under their own downline)
|
||||
for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
||||
const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null;
|
||||
const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null;
|
||||
const st = RS.load(); const via = n.via || 'same email';
|
||||
const why = 'aligned to network sponsor ' + nameOf(sp) + ' from InstantAdPay (' + via + ')';
|
||||
st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via, at: clock(), why });
|
||||
if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300);
|
||||
if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; }
|
||||
RS.save();
|
||||
console.log('tank align', e, '->', sp.email, why);
|
||||
if (hooks.aligned) { try { await hooks.aligned({ email: e, name: nameOf(fresh), sponsorEmail: sp.email, sponsorName: nameOf(sp), why }); } catch (err) {} }
|
||||
// a wallet is already linked: switch payouts on now under the aligned sponsor (not from carry itself, which is already
|
||||
// activating them, and not while a purchase is about to register them anyway)
|
||||
if (fresh.address && hooks.lifted && !(opts && opts.noLift)) { markLift(e); liftRun(e).catch(err => console.error('tank lift', err.message)); }
|
||||
return { to: sp.email, toName: nameOf(sp), via, why };
|
||||
}
|
||||
// /api/me and /api/sponsor, when the fallback position would be used: align first, else the hold record (the server
|
||||
// blocks only a plain activation with it; a purchase goes ahead)
|
||||
async function holdFor(a, opts) {
|
||||
if (!a || !inTank(a)) return null;
|
||||
const al = await alignToNetwork(a, opts).catch(e => { console.error('tank align', e.message); return null; });
|
||||
if (al) return { aligned: al };
|
||||
const rec = markReady(a);
|
||||
return { hold: rec ? holdOf(rec) : { since: null, until: null } };
|
||||
}
|
||||
// carry.ensureOnChain asks before activating someone with no sponsor: align first; `own` = the member's own plain
|
||||
// activation (wallet linked, Switch on payouts, admin seeding), held; otherwise (a sponsor being placed on the contract
|
||||
// because someone below them is buying) the purchase is never held, so the caller keeps today's fallback
|
||||
async function gate(a, opts) {
|
||||
if (!a || !inTank(a)) return null;
|
||||
const al = await alignToNetwork(a, { noLift: true }).catch(e => { console.error('tank align', e.message); return null; });
|
||||
if (al) return { aligned: al };
|
||||
if (opts && opts.own && a.address) { const rec = markReady(a); return { hold: holdOf(rec) || { since: null, until: null } }; }
|
||||
return null;
|
||||
}
|
||||
// adopters for the safety net, in rotation order
|
||||
async function rotation(excludeEmail) {
|
||||
const qual = new Map(); // member # -> block of their first own $25+ purchase
|
||||
for (const ev of chain.recentEvents(200000)) if (ev.type === 'Purchase' && Number(ev.priceCents) >= MIN_OWN_BUY_CENTS && ev.buyerId) { const b = Number(ev.block) || 0; const id = Number(ev.buyerId); if (!qual.has(id) || b < qual.get(id)) qual.set(id, b); }
|
||||
const company = Number(hooks.companyId ? hooks.companyId() : 1) || 1; const now = clock(); const st = RS.load(); const out = [];
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
const id = Number(a.memberId) || 0;
|
||||
if (!id || id === company || id === 1 || !qual.has(id) || a.email === excludeEmail) continue;
|
||||
if (!a.lastSeen || now - a.lastSeen > AUTO_SEEN_MS) continue;
|
||||
if (hooks.isSuspended && hooks.isSuspended(a.email)) continue;
|
||||
out.push({ a, last: Number(st.adopters[a.email]) || 0, q: qual.get(id) });
|
||||
}
|
||||
out.sort((x, y) => x.last - y.last || x.q - y.q);
|
||||
return out;
|
||||
}
|
||||
async function inDownlineOf(adoptee, adopter) { // is the adopter somewhere under the adoptee? (adopting them would close a loop)
|
||||
let cur = await accounts.sponsorOf(adopter.email); const seen = new Set();
|
||||
for (let i = 0; cur && i < 60; i++) { if (cur.email === adoptee || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
||||
return false;
|
||||
}
|
||||
let autoBusy = null; // readyTick (15 min) and sweep (hourly) never run the safety net at the same time
|
||||
function autoAssign() { if (!autoBusy) autoBusy = autoAssignRun().finally(() => { autoBusy = null; }); return autoBusy; }
|
||||
async function autoAssignRun() {
|
||||
const st = RS.load(); const now = clock(); const out = { assigned: [], held: 0, deferred: 0 };
|
||||
const due = [];
|
||||
for (const [e, rec] of Object.entries(st.ready)) {
|
||||
if (rec.done) continue;
|
||||
const a = await accounts.byEmail(e);
|
||||
if (!a || !inTank(a)) { rec.done = clock(); if (a && a.address && !(Number(a.memberId) > 0) && a.sponsorRef && hooks.lifted && !rec.lifted) rec.liftPending = rec.liftPending || clock(); continue; } // sponsored meanwhile (a follow from InstantAdPay, an admin edit): payouts switch on in the lift loop
|
||||
if (remoteOpen(e) || !a.address) continue; // picked up on InstantAdPay (the follow lands here shortly) / wallet unlinked
|
||||
if (now < rec.readyAt + READY_MS - TICK_MS) continue;
|
||||
if (hooks.bound) { // already on the contract (activated elsewhere, member number not saved yet): not a tank member at all
|
||||
const id = await Promise.resolve(hooks.bound(a)).catch(() => -1);
|
||||
if (id > 0) { rec.done = clock(); rec.bound = id; continue; }
|
||||
if (id < 0) continue; // chain unreadable: try again next tick
|
||||
}
|
||||
due.push([e, rec, a]);
|
||||
}
|
||||
due.sort((x, y) => x[1].readyAt - y[1].readyAt);
|
||||
let pool = null;
|
||||
for (const [e, rec, a] of due) {
|
||||
// the double-assign guard: InstantAdPay holds this person in its own tank, so its safety net assigns them (asked fresh)
|
||||
if (hooks.iapOwns && await Promise.resolve(hooks.iapOwns(e, { fresh: true })).catch(() => false)) { out.deferred++; if (!rec.deferred) { rec.deferred = clock(); RS.save(); } continue; }
|
||||
if (!(await claimOnce('tankauto:' + e + ':' + Math.floor(clock() / 600000)))) continue; // the other app copy (deploy overlap) has this one
|
||||
if (!pool) pool = await rotation(e);
|
||||
let done = null;
|
||||
for (const c of pool) {
|
||||
if (c.a.email === e) continue;
|
||||
if ((await impl().open(c.a.email)).length >= CAP_OPEN) continue;
|
||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(c.a.memberId))).catch(() => true)) continue; // no-payout chain: they would fall to the company after all
|
||||
if (await inDownlineOf(e, c.a)) continue;
|
||||
const msg = 'Hi, I am ' + nameOf(c.a) + '. You joined LinkSpin without a sponsor and nobody picked you up from the holding tank within 24 hours, so you were matched with me. I will walk you through the first steps whenever you are ready. Reply here.';
|
||||
const r = await adopt(c.a.email, a.username || e, msg, { auto: true, recordNote: 'auto-assigned after 24 hours in the tank' });
|
||||
if (r && r.ok) { done = { adoptee: e, adopter: c.a.email, adopterName: r.adopterName, adopteeName: r.adopteeName }; break; }
|
||||
}
|
||||
if (done) {
|
||||
st.adopters[done.adopter] = clock(); rec.done = clock(); rec.autoAssigned = done.adopter;
|
||||
for (const c of pool) c.last = Number(st.adopters[c.a.email]) || 0;
|
||||
pool.sort((x, y) => x.last - y.last || x.q - y.q);
|
||||
out.assigned.push(done); RS.save();
|
||||
if (hooks.assigned) { try { await hooks.assigned(done); } catch (err) {} }
|
||||
} else {
|
||||
out.held++;
|
||||
if (!rec.noAdopterAlerted) {
|
||||
rec.noAdopterAlerted = clock(); RS.save();
|
||||
if (hooks.adminAlert && await claimOnce('tankalert:' + e + ':' + rec.readyAt)) { try { await hooks.adminAlert('LinkSpin holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $25+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not on a no-payout chain). Their payouts stay switched off (a purchase still goes ahead), never under the company. Adopt them from More > My line > Holding tank, or set their sponsor in Admin.'); } catch (err) {} }
|
||||
}
|
||||
}
|
||||
}
|
||||
RS.save();
|
||||
return out;
|
||||
}
|
||||
// every 15 minutes (server.js): align whoever the network already knows, start the clock for new ready members,
|
||||
// run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them; members
|
||||
// InstantAdPay owns are announced there, not twice in the shared topic).
|
||||
async function readyTick() {
|
||||
const st = RS.load(); const fresh = []; let aligned = 0;
|
||||
const tankers = (await accounts.listAll(5000)).filter(inTank);
|
||||
if (hooks.prefetch) { try { await hooks.prefetch(tankers.map(a => a.email)); } catch (e) {} } // one signed batch call to InstantAdPay, not one per member
|
||||
for (const a of tankers) {
|
||||
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
||||
if (remoteOpen(a.email)) continue;
|
||||
const rec = markReady(a);
|
||||
if (rec && !rec.notified) {
|
||||
rec.notified = clock();
|
||||
const iap = hooks.iapOwns ? await Promise.resolve(hooks.iapOwns(a.email)).catch(() => false) : false;
|
||||
if (!iap && await claimOnce('tankready:' + a.email + ':' + rec.readyAt)) fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS });
|
||||
}
|
||||
}
|
||||
RS.save();
|
||||
const lifted = await liftPendingRun();
|
||||
const auto = await autoAssign();
|
||||
return { fresh, aligned, assigned: auto.assigned, held: auto.held, deferred: auto.deferred, lifted };
|
||||
}
|
||||
// ── switching payouts on once a tank member has a sponsor (Marty approved 2026-10-27) ──
|
||||
// hooks.lifted(email) = carry.activateAssigned: strict (never the fallback), claimed per member per 10 minutes across app
|
||||
// copies. A failure (RPC, gas, sponsor not on the contract yet) stays pending and is retried every tick for 7 days.
|
||||
const txLink = tx => String((chain && chain.getConfig && chain.getConfig().explorer) || 'https://polygonscan.com').replace(/\/+$/, '') + '/tx/' + tx;
|
||||
const claimOnce = async key => { if (!hooks.claim) return true; try { return !!(await hooks.claim(key)); } catch (e) { return false; } };
|
||||
function markLift(email) {
|
||||
const st = RS.load(); const e = String(email || '').toLowerCase(); if (!e) return;
|
||||
const rec = st.ready[e] || (st.ready[e] = { readyAt: clock(), notified: clock() });
|
||||
if (!rec.done) rec.done = clock();
|
||||
if (!rec.lifted) rec.liftPending = rec.liftPending || clock();
|
||||
RS.save();
|
||||
}
|
||||
async function liftRun(email, opts) {
|
||||
if (!hooks.lifted) return null;
|
||||
const e = String(email || '').toLowerCase();
|
||||
let r; try { r = await hooks.lifted(e); } catch (err) { r = { error: err.message, retry: true }; }
|
||||
const st = RS.load(); const rec = st.ready[e];
|
||||
if (r && r.id) {
|
||||
if (rec) { rec.liftPending = 0; rec.lifted = clock(); rec.liftTx = r.tx || null; delete rec.liftError; }
|
||||
RS.save();
|
||||
if (r.tx && !(opts && opts.quiet)) await liftNotify(e, r); // `already` (activated some other way): nothing to announce
|
||||
} else if (rec) {
|
||||
if (r && r.retry === false) rec.liftPending = 0;
|
||||
rec.liftTries = (rec.liftTries || 0) + 1; rec.liftError = String((r && r.error) || 'unknown').slice(0, 120); RS.save();
|
||||
}
|
||||
return r;
|
||||
}
|
||||
async function liftNotify(email, r) {
|
||||
const sp = r.sponsorEmail ? await accounts.byEmail(r.sponsorEmail) : null; if (!sp) return;
|
||||
const text = 'Your LinkSpin payouts are now on under ' + nameOf(sp) + '. The site placed your wallet on the LinkSpin contract (no cost to you), so every purchase in your line pays your wallet in the same transaction from now on. Proof: ' + txLink(r.tx);
|
||||
try { await messages.sendChat(sp.memberId || 0, sp.email, email, text); } catch (err) {}
|
||||
if (mailer && mailer.hasKey()) { try { await mailer.send(email, 'Your LinkSpin payouts are on under ' + nameOf(sp), text + '\n\nSee your line: ' + siteUrl + '/tools#line\n\nLinkSpin'); } catch (err) {} }
|
||||
}
|
||||
async function liftPendingRun() {
|
||||
const st = RS.load(); let done = 0;
|
||||
for (const [e, rec] of Object.entries(st.ready)) {
|
||||
if (!rec.liftPending) continue;
|
||||
if (clock() - rec.liftPending > 7 * 86400000) { rec.liftPending = 0; rec.liftError = 'gave up after 7 days: ' + (rec.liftError || ''); RS.save(); continue; }
|
||||
const a = await accounts.byEmail(e);
|
||||
if (!a || Number(a.memberId) > 0 || !a.address || !a.sponsorRef) { rec.liftPending = 0; RS.save(); continue; } // bought, unlinked or back in the tank: nothing to switch on
|
||||
const r = await liftRun(e); if (r && r.id) done++;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
function alignedRecent(n) { return RS.load().aligned.slice(-(n || 50)).reverse(); }
|
||||
|
||||
async function adminView() {
|
||||
const recent = await impl().recent(200);
|
||||
const names = {};
|
||||
for (const ad of recent) for (const em of [ad.adoptee, ad.adopter]) if (!(em in names)) { const a = await accounts.byEmail(em); names[em] = a ? nameOf(a) : em; }
|
||||
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 };
|
||||
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, holdHours: READY_MS / 3600000, aligned: alignedRecent(30) };
|
||||
}
|
||||
|
||||
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 };
|
||||
module.exports = { init, view, adopt, holdFor, gate, markReady, readyRec, readyTick, autoAssign, alignToNetwork, alignedRecent, setClock, eligibility, inTank, READY_MS, 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