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:
martbost
2026-10-27 07:26:51 -05:00
parent fd064b1db1
commit 2d0413037d
13 changed files with 853 additions and 61 deletions
+137 -20
View File
@@ -656,7 +656,8 @@ async function boot() {
coach.init({ dataDir: DATA_DIR, chain, accounts, mailer, ads, tank, lb: () => leaderboard, siteConfig });
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
registry.init({ dataDir: DATA_DIR });
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST,
tankGate: (a, o) => tank.gate(a, o), claim: k => marks.claim(k), payoutBlocked: id => payoutChainBlocked(id, 2) }); // holding tank (2026-10-27): network sponsor first, a plain activation held, a purchase never
// sponsor follow (sponsorfollow.js): deliberate changes (tank adoption, rescue, release, window expiry, admin edit) are
// recorded and follow to InstantAdPay, and InstantAdPay's are applied here, until the member is bound or binding on the
// LinkSpin contract (memberId, wallet already on chain, or an engine activation in flight). Ordinary bindings: first platform.
@@ -707,7 +708,13 @@ async function boot() {
zonereport.init({ dataDir: DATA_DIR });
snapshot.init({ dataDir: DATA_DIR, db, chain, siteConfig, send: async (c, t, th) => { await telegramSend(c, t, th); return true; } });
setInterval(() => snapshot.tick().catch(e => console.error('snapshot', e.message)), 10 * 60 * 1000);
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore });
tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, site: SITE_URL, follow, store: followStore,
// network alignment + activation hold + 24-hour safety net (2026-10-27): a tank member's plain activation is never
// bound under the fallback position; their InstantAdPay sponsor first, else an adopter (a purchase is never held)
hooks: { network: (email, address) => networkSponsor(email, address), prefetch: emails => iapFacts(emails, { timeout: 20000 }),
iapOwns: (email, o) => iapOwnsTank(email, o), bound: async a => { const id = Number(await chain.memberIdByAccount(a.address)) || 0; if (id) await accounts.setMemberId(a.email, id).catch(() => {}); return id; },
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
lifted: email => tankLifted(email), claim: k => marks.claim(k), assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text) } });
legacy.init({ dataDir: DATA_DIR });
traffic.init({ dataDir: DATA_DIR });
promos.init({ dataDir: DATA_DIR });
@@ -728,6 +735,8 @@ async function boot() {
setInterval(() => leaderboard.rolloverTick().catch(e => console.error('leaderboard rollover', e.message)), 60 * 60 * 1000);
console.log('blog syndication:', syndicate.enabled() ? 'on (X + Instagram via Blotato)' : 'off (no blotato.key)');
setInterval(() => tankNotifyTick().catch(e => console.error('tank notify', e.message)), 15 * 60 * 1000); // new tank arrivals -> Telegram
setTimeout(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 3 * 60 * 1000); // after the first iapsync / registry rows
setInterval(() => tankReadyTick().catch(e => console.error('tank ready', e.message)), 15 * 60 * 1000); // align / 24-hour hold / safety net
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
@@ -1130,6 +1139,99 @@ async function tankNotifyTick() {
+ '\nAdopt from Team \u203a Waiting on a wallet: <a href="' + SITE_URL + '/team">' + SITE_HOST + '/team</a>';
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
}
// ---- holding tank: network alignment, activation hold, 24-hour safety net (2026-10-27, ported from InstantAdPay) ----
const nrm = v => String(v || '').trim().toLowerCase();
// InstantAdPay's own facts for a few people (signed /api/partner/sponsor-facts, the same call the Sponsor check uses),
// cached 10 minutes, misses included; unreachable = 2 minutes without asking again. Map email -> row | null (no account
// there); an email missing from the map = unknown (never asked successfully).
const iapFactsCache = new Map(); let iapFactsDownUntil = 0;
async function iapFacts(emails, opts) {
const now = Date.now(); const want = [...new Set((emails || []).map(nrm).filter(Boolean))];
const miss = opts && opts.fresh ? want : want.filter(e => { const c = iapFactsCache.get(e); return !c || now - c.at > 10 * 60000; });
if (miss.length && now >= iapFactsDownUntil && String(process.env.LS_SYNC_SECRET || '').trim().length >= 32) {
try {
const got = new Map();
for (let i = 0; i < miss.length; i += 2000) {
const r = await SF.peerPost(IAP_BASE(), '/api/partner/sponsor-facts', { emails: miss.slice(i, i + 2000) }, (opts && opts.timeout) || 3000);
for (const x of (r && r.rows) || []) got.set(nrm(x.email), x);
}
if (iapFactsCache.size > 20000) iapFactsCache.clear();
for (const e of miss) iapFactsCache.set(e, { at: now, row: got.get(e) || null });
} catch (e) { iapFactsDownUntil = now + 2 * 60000; console.log('tank: InstantAdPay sponsor-facts unreachable:', e.message); }
}
const out = new Map(); for (const e of want) { const c = iapFactsCache.get(e); if (c) out.set(e, c.row); }
return out;
}
// the network sponsor for a LinkSpin tank member: the registry rows InstantAdPay sent (same email, else same wallet),
// else InstantAdPay asked directly. Read only; tank.alignToNetwork decides whether it may be used.
async function networkSponsor(email, address) {
const e = nrm(email); if (!e) return null;
const r = await registry.get(e);
if (r && r.sponsorEmail && nrm(r.sponsorEmail) !== e) return { sponsorEmail: nrm(r.sponsorEmail), via: 'same email' };
const row = (await iapFacts([e])).get(e);
if (row && row.sponsorEmail && nrm(row.sponsorEmail) !== e) return { sponsorEmail: nrm(row.sponsorEmail), via: 'InstantAdPay sponsor' };
const w = nrm(address);
if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of await registry.all()) if (nrm(x.wallet) === w && x.sponsorEmail && nrm(x.email) !== e && nrm(x.sponsorEmail) !== e) return { sponsorEmail: nrm(x.sponsorEmail), via: 'same wallet' };
return null;
}
// the double-assign guard: is this person waiting in InstantAdPay's OWN tank (a real account there, no sponsor, not a
// member there, wallet linked there)? Then InstantAdPay's 24-hour safety net assigns them and the adoption follows here;
// LinkSpin's does not. InstantAdPay unreachable: the registry decides (first seen on InstantAdPay and no sponsor = theirs).
async function iapOwnsTank(email, opts) {
const e = nrm(email); const m = await iapFacts([e], { fresh: !!(opts && opts.fresh), timeout: 5000 });
if (m.has(e)) {
const r = m.get(e); if (!r) return false;
const shell = r.joinedVia === 'linkspin' && !r.lastSeen && !(Number(r.memberId) > 0); // a waiting copy of a LinkSpin account: never in its tank
return !shell && !r.sponsorRef && !(Number(r.memberId) > 0) && !!r.wallet;
}
const reg = await registry.get(e);
return !!(reg && reg.firstProperty === 'instantadpay' && !reg.sponsorEmail);
}
// a held member got a sponsor (adopted, the 24-hour rotation, aligned, followed from InstantAdPay): the engine switches
// their payouts on now under THAT sponsor (carry.activateAssigned: strict, never the fallback; Marty approved 2026-10-27)
async function tankLifted(email) {
if (followStore.pendingFor(email)) return { error: 'a sponsor follow is still settling', retry: true }; // afterResolve / the next tick
const r = await carry.activateAssigned(email);
if (r && r.id && r.tx) console.log('tank lift: payouts on for', email, 'member #' + r.id, 'under #' + r.sponsorId, r.tx);
else if (r && r.error) console.log('tank lift: not yet for', email, '(' + r.error + ')');
return r;
}
// a holding-tank pickup: the live feed + one line in the shared payments topic (manual adoptions since 2026-09-12;
// the 24-hour safety net says "(auto-assigned)", 2026-10-27)
function tankPickupPost(adopterName, adopteeName, auto) {
pushFeed({ type: 'Adopted', sponsor: adopterName, member: adopteeName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>LinkSpin</b> \u00b7 <b>' + clean(adopterName) + '</b> picked up <b>' + clean(adopteeName) + '</b> from the holding tank and is now their sponsor' + (auto ? ' (auto-assigned)' : ''), sc.telegramEchoTopicId).catch(() => {});
} catch (e) {}
}
// admin-only channel (never a member-visible topic: it names an email)
async function tankAdminAlert(text) {
const sc = siteConfig(); const html = String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, html);
if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'LinkSpin: holding tank needs an adopter', text);
console.log('tank: no admin channel configured, alert not sent:', text);
}
// every 15 min: align members the network already knows, start the 24-hour clock for anyone who linked a wallet, run the
// safety net, and tell the shared payments topic once per member who became ready (members InstantAdPay holds in its own
// tank are announced by InstantAdPay, not twice)
async function tankReadyTick() {
const r = await tank.readyTick();
if (r.aligned || r.assigned.length || r.held || r.deferred || r.fresh.length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held, deferred: r.deferred }));
const sc = siteConfig();
if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r;
const clean = t => String(t || '').replace(/[<>&]/g, '');
const link = SITE_URL + '/tools#line';
if (r.fresh.length <= 3) {
for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + (w.username ? '@' + clean(w.username) : 'A new member') + ' linked a wallet and is ready to switch on payouts. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
} else { // first run after deploy (the members already linked) or a busy quarter hour: one digest, not a wall of posts
const named = r.fresh.filter(w => w.username).map(w => '@' + clean(w.username));
await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} <b>LinkSpin</b> \u00b7 ' + r.fresh.length + ' members linked a wallet and are ready to switch on payouts' + (named.length ? ': ' + named.slice(0, 12).join(', ') + (named.length > 12 ? ' and ' + (named.length - 12) + ' more' : '') : '') + '. Adopt them from the holding tank in the next 24 hours: ' + link, sc.telegramEchoTopicId).catch(() => {});
}
return r;
}
// one sendMessage call; never throws, never logs the token
async function telegramSend(chatId, text, threadId) {
const sc = siteConfig();
@@ -1494,13 +1596,25 @@ const server = http.createServer(async (req, res) => {
// cookie only for anonymous visitors with no account sponsor yet. (Reading
// the cookie alone was orphaning buyers to root when the cookie was absent.)
const s = await auth.fromRequest(req);
const acct = s && s.email ? await accounts.byEmail(s.email) : null;
const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || '';
const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id;
let acct = s && s.email ? await accounts.byEmail(s.email) : null;
let tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || '';
let spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id;
// LinkSpin carry-over: a sponsor with a wallet is activated on this contract by the engine before the
// member's first transaction. A purchase is NEVER held (Marty, 2026-10-15): no wallet / unknown sponsor
// walks up to the nearest ancestor with a wallet, else the company. intent=buy commits the move + notices.
const intentBuy = u.searchParams.get('intent') === 'buy';
const intentActivate = u.searchParams.get('intent') === 'activate'; // the free Switch on payouts button (2026-10-27)
// holding tank (2026-10-27): no sponsor, no member number, no resolvable cookie -> the network sponsor first (every
// intent, buys included). Nobody known: a plain activation is held for an adopter; a purchase goes ahead under the
// fallback as before (Marty: "I would never want to hold up a purchase ... they'll just pay number one").
let tankHold = null;
if (acct && !acct.sponsorRef && !(Number(acct.memberId) > 0) && !sponsorId) {
try {
const h = await tank.holdFor(acct, { noLift: intentBuy || intentActivate });
if (h && h.aligned) { acct = (await accounts.byEmail(acct.email)) || acct; tok = acct.sponsorRef || tok; spd = await resolveSponsorDetailed(tok); sponsorId = spd.id; }
else if (h && h.hold) tankHold = h.hold;
} catch (e) { console.error('tank hold', e.message); }
}
let sponsorRouted = null;
if (acct && !sponsorId) {
try {
@@ -1511,11 +1625,12 @@ const server = http.createServer(async (req, res) => {
}
let sponsorBlocked = null; // only a momentary chain lookup failure: the client says "try again in a minute", nothing is charged
if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'rpc') sponsorBlocked = 'rpc';
if (tankHold && intentActivate && !sponsorId) sponsorBlocked = 'tankHold'; // the free activation only, never a purchase
if (sponsorRouted && intentBuy) sponsorBlockedAlert(acct.email, Object.assign({ tok, routedTo: sponsorRouted.to }, spd));
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; }
// orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands
// the new member under the configured catch position (#1) instead of root
if (!sponsorId && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
if (!sponsorId && sponsorBlocked !== 'tankHold' && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1;
// a brand-new contract has no catch position yet: the first member joins with sponsor 0 and BECOMES #1 (Marty's reverted
// activate(1) on 2026-10-08: 'Unknown sponsor' because memberCount was 0)
if (sponsorId) { try { if (sponsorId > await chain.memberCount()) { console.log('sponsor', sponsorId, 'not on chain yet, using 0'); sponsorId = 0; } } catch (e) {} }
@@ -1531,7 +1646,7 @@ const server = http.createServer(async (req, res) => {
if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok));
if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} }
}
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, tankHold: intentBuy ? null : tankHold, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
}
if (p === '/api/stats' && req.method === 'GET') {
let members = 0; try { members = await chain.memberCount(); } catch (e) {}
@@ -1849,8 +1964,18 @@ const server = http.createServer(async (req, res) => {
const s = await auth.fromRequest(req);
if (!s) return json(res, 200, { signedIn: false });
const memberId = await auth.refreshMemberId(s);
const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
let spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
// holding tank (2026-10-27): the network sponsor first; nobody known = tankHold (the Switch on payouts button waits
// for an adopter, 24 h at most). sponsorId keeps today's fallback so a purchase is never held.
let tankHold = null;
if (acct && !acct.sponsorRef && !(Number(acct.memberId) > 0) && !memberId && !sponsorId) {
try {
const h = await tank.holdFor(acct);
if (h && h.aligned) { acct = (await accounts.byEmail(acct.email)) || acct; spdMe = await resolveSponsorDetailed(acct.sponsorRef); sponsorId = spdMe.id; }
else if (h && h.hold) tankHold = h.hold;
} catch (e) { console.error('tank hold', e.message); }
}
const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason === 'rpc') ? 'rpc' : null; // never hold: the buy/activate paths resolve through /api/sponsor?intent=buy (carry walk-up)
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0;
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
@@ -1860,7 +1985,7 @@ const server = http.createServer(async (req, res) => {
const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
address: s.address || (acct && acct.address) || null, memberId,
username: (acct && acct.username) || null,
refCode: (acct && acct.code) || null, sponsorId,
refCode: (acct && acct.code) || null, sponsorId, tankHold,
// profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned)
avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null,
socials: (acct && acct.socials) || null,
@@ -1888,7 +2013,7 @@ const server = http.createServer(async (req, res) => {
try {
if (!tankWaitCache || Date.now() - tankWaitCache.ts > 60000) tankWaitCache = { ts: Date.now(), list: await tank.waiting() };
const tw = tankWaitCache.list;
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok };
tankWaiting = { count: tw.length, names: tw.slice(0, 6).map(w => w.name), eligible: !!(await tank.eligibility(s.email)).ok, ready: tw.filter(w => w.ready).length };
} catch (e) {}
const sc0 = siteConfig();
const out = { memberId, tankWaiting, email: s.email || (acct && acct.email) || null,
@@ -2311,15 +2436,7 @@ const server = http.createServer(async (req, res) => {
if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' });
const b = await readBody(req);
const r = await tank.adopt(s.email, b.who, b.note);
if (r.ok) { // tell the payments topic who picked whom up (Marty, 2026-09-12)
pushFeed({ type: 'Adopted', sponsor: r.adopterName, member: r.adopteeName, ts: Date.now() });
try {
const sc = siteConfig();
const clean = t => String(t || '').replace(/[<>&]/g, '');
if (sc.telegramBotToken && sc.telegramEchoChatId)
telegramSend(sc.telegramEchoChatId, '\u{1F91D} <b>LinkSpin</b> \u00b7 <b>' + clean(r.adopterName) + '</b> picked up <b>' + clean(r.adopteeName) + '</b> from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {});
} catch (e) {}
}
if (r.ok) tankPickupPost(r.adopterName, r.adopteeName, false); // tell the payments topic who picked whom up (Marty, 2026-09-12)
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/my/tank/release' && req.method === 'POST') {