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
+60 -13
View File
@@ -15,7 +15,7 @@ let ethers = null; try { ethers = require('ethers'); } catch (e) {}
const fs = require('fs');
const path = require('path');
let X = {}; // { dataDir, accounts, registry, chain, mailer, messages, siteConfig, adminEmail }
let X = {}; // { dataDir, accounts, registry, chain, mailer, messages, siteConfig, adminEmail, tankGate, claim, payoutBlocked, sendActivate + now (tests) }
const DAY = 86400000;
const ABI = ['function activateFor(address account, uint32 sponsorId) returns (uint32)', 'function engineSigner() view returns (address)'];
const norm = e => String(e || '').trim().toLowerCase();
@@ -145,7 +145,15 @@ async function ensureOnChain(acct, depth, why) {
if (acct.email && isHeld(acct.email)) await waitUnheld(acct.email);
if (acct.email) { try { const fresh = await X.accounts.byEmail(acct.email); if (fresh && fresh.address) acct = fresh; } catch (e) {} }
try { const id = await X.chain.memberIdByAccount(acct.address); if (id) { if (Number(acct.memberId) !== Number(id)) await X.accounts.setMemberId(acct.email, id).catch(() => {}); return id; } } catch (e) {}
if (!engineReady() || depth > 25) return 0;
// holding tank (2026-10-27, tank.gate): no sponsor here -> align to the network sponsor first (InstantAdPay knows one);
// nobody known and this is the member's OWN plain activation (wallet linked, admin seeding) -> held for an adopter, never
// bound under the fallback. A sponsor placed on the contract because someone below them is buying is never held.
if (!acct.sponsorRef && !(Number(acct.memberId) > 0) && X.tankGate) {
let g = null; try { g = await X.tankGate(acct, { own: depth === 0 && (why === 'wallet' || !!X.seeding) }); } catch (e) { g = null; }
if (g && g.aligned) { try { const fresh = await X.accounts.byEmail(acct.email); if (fresh) acct = fresh; } catch (e) {} }
else if (g && g.hold) { logEvent({ type: 'tankHold', email: acct.email, until: g.hold.until || null }); return 0; }
}
if (!sendReady() || depth > 25) return 0;
const me = norm(acct.email); inflight.add(me); let id = 0; // binding from here: the sponsor read below is the one the contract gets
let sponsorId = 0, txHash = null, lastErr = null; // read after the finally below, so declared out here (inside the try they were not defined there, 2026-10-22..27)
try {
@@ -155,16 +163,7 @@ async function ensureOnChain(acct, depth, why) {
}
if (!sponsorId) sponsorId = Number((X.siteConfig && X.siteConfig().defaultSponsorId) || 1) || 1;
try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet
// send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations
// mined while a 403 on the follow-up read logged them as failures and skipped their notices)
for (let attempt = 0; attempt < 3 && !id; attempt++) {
try {
const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w);
const tx = await ctr.activateFor(acct.address, sponsorId, { gasLimit: 160000n }); txHash = tx.hash;
await tx.wait(1);
} catch (e) { lastErr = e; }
for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); }
}
const sent = await (X.sendActivate || sendActivateFor)(acct.address, sponsorId); id = sent.id; txHash = sent.txHash; lastErr = sent.lastErr;
} finally { if (!id) inflight.delete(me); } // on success the flag stays until the member number is saved below
if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; }
logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash });
@@ -175,6 +174,54 @@ async function ensureOnChain(acct, depth, why) {
await noticeActivated(acct, why);
return id;
}
// send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations
// mined while a 403 on the follow-up read logged them as failures and skipped their notices)
async function sendActivateFor(address, sponsorId) {
let id = 0, txHash = null, lastErr = null;
for (let attempt = 0; attempt < 3 && !id; attempt++) {
try {
const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w);
const tx = await ctr.activateFor(address, sponsorId, { gasLimit: 160000n }); txHash = tx.hash;
await tx.wait(1);
} catch (e) { lastErr = e; }
for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(address)) || 0; } catch (e) {} if (!id) await sleep(3000); }
}
return { id, txHash, lastErr };
}
const sendReady = () => !!X.sendActivate || engineReady();
// ---- holding tank: switch payouts on the moment a tank member gets a sponsor (Marty approved 2026-10-27) ----
// An adoption (manual or the 24-hour rotation) or a network alignment gives a held member a sponsor; with a wallet linked,
// the engine activates them right away UNDER THAT SPONSOR. Strict, unlike ensureOnChain: never the fallback position.
// - already on the contract: nothing sent ({ id, already })
// - the sponsor must be on the contract (the engine places a sponsor who has a wallet first, as ensureOnChain does) and not
// on a no-payout chain; otherwise nothing is sent and the caller retries on its next tick ({ error, retry })
// - one sender across app copies: a marks claim per member per 10-minute window (deploy overlap), plus the in-process flag
// Returns { id, tx, sponsorId, sponsorEmail } when this call activated them.
async function activateAssigned(email) {
let a = await X.accounts.byEmail(email); if (!a || !a.address) return { error: 'no wallet linked', retry: false };
if (isHeld(a.email)) { await waitUnheld(a.email); a = (await X.accounts.byEmail(email)) || a; }
let onId = 0; try { onId = Number(await X.chain.memberIdByAccount(a.address)) || 0; } catch (e) { return { error: 'chain read failed', retry: true }; }
if (onId) { if (Number(a.memberId) !== onId) await X.accounts.setMemberId(a.email, onId).catch(() => {}); return { id: onId, already: true }; }
if (!a.sponsorRef) return { error: 'no sponsor yet', retry: false };
let sp = await X.accounts.byCode(a.sponsorRef); if (!sp) sp = await X.accounts.byUsername(a.sponsorRef);
if (!sp) return { error: 'sponsor ' + a.sponsorRef + ' not found', retry: true };
if (!sp.address) return { error: 'sponsor has no wallet yet', retry: true };
if (!sendReady()) return { error: 'engine not configured', retry: true };
const me = norm(a.email); if (inflight.has(me)) return { error: 'activation already in flight', retry: true };
const sponsorId = await ensureOnChain(sp, 1);
if (!sponsorId) return { error: 'sponsor not on the contract yet', retry: true };
if (X.payoutBlocked && await Promise.resolve(X.payoutBlocked(sponsorId)).catch(() => true)) return { error: 'sponsor #' + sponsorId + ' is on a no-payout chain', retry: false };
if (X.claim && !(await Promise.resolve(X.claim('tankact:' + me + ':' + Math.floor((X.now ? X.now() : Date.now()) / 600000))).catch(() => false))) return { error: 'another app copy is sending it', retry: true };
inflight.add(me); let sent = { id: 0 };
try { sent = await (X.sendActivate || sendActivateFor)(a.address, sponsorId); }
finally { if (!sent.id) inflight.delete(me); }
if (!sent.id) { logEvent({ type: 'activateFailed', email: a.email, why: 'assigned', sponsorId, error: String((sent.lastErr && (sent.lastErr.shortMessage || sent.lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return { error: 'activation failed', retry: true }; }
logEvent({ type: 'activated', email: a.email, id: sent.id, sponsorId, tx: sent.txHash, why: 'assigned' });
await X.accounts.setMemberId(a.email, sent.id).catch(() => {});
inflight.delete(me);
return { id: sent.id, tx: sent.txHash || null, sponsorId, sponsorEmail: sp.email };
}
async function noticeActivated(acct, why) {
const own = X.seeding || why === 'wallet'; // switched on because their own wallet arrived, not because someone below them bought
await tell(acct.email, own ? 'Your LinkSpin payouts are switched on' : 'We set up your LinkSpin position so you would not miss a payout',
@@ -223,4 +270,4 @@ async function seedAll(limit) {
}
function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; }
module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady, backfillMemberIds, hold, unhold, isHeld, isBinding };
module.exports = { init, onJoin, resolveForChain, ensureOnChain, activateAssigned, seedAll, status, engineReady, backfillMemberIds, hold, unhold, isHeld, isBinding };
+6 -2
View File
@@ -25,7 +25,7 @@ let DATA_DIR = null;
let chain = null;
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
const CONTRACT = '0x26Bdc556b94399bEdd69ae3ACA5aA6c54D946e8b';
const KNOWLEDGE_DATE = '2026-10-26'; // the day the CANNED answers and FACTS below were last checked against the site
const KNOWLEDGE_DATE = '2026-10-27'; // the day the CANNED answers and FACTS below were last checked against the site
function init(opts) {
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn; DATA_DIR = opts.dataDir; chain = opts.chain; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
@@ -130,9 +130,12 @@ const CANNED = [
{ id: 'control-room', title: 'The Control Room screens', q: ['Where do I find my links?', 'What is on the dashboard?', 'Which screen has my campaigns?'], tags: ['control room', 'dashboard', 'menu', 'tools'],
re: /(control room|dashboard|where (do|can) i (find|see)|which screen|menu|navigation|more tools|\/tools)/i,
a: 'Your Control Room has these screens: Links (spin links), Pages (the page builder), Zones (ad slots on your site plus Audiences), Ads (your campaigns and the daily ad set), Credits (buy packages, link your wallet, switch on payouts), Reports (every link in one view), Team (your line, three levels) and Wallet (what was paid to you). More, at ' + SITE_URL + '/tools, holds Promo tools, Training, the Pipeline follow-up board, My line and your Profile.' },
{ id: 'tank-hold', title: 'Matched with a sponsor (payouts on hold)', q: ['Why can I not switch on payouts?', 'It says I am being matched with a sponsor'], tags: ['holding tank', 'switch on payouts', 'matched with a sponsor', 'ready to activate'],
re: /(being matched|matched with a sponsor|(can.?t|cannot|unable to) (i )?(switch on|turn on|activate) (my )?payouts|activate (button|payouts) (is )?(gone|missing|hidden)|ready to activate)/i,
a: 'You joined without a sponsor, so you are in the holding tank. The contract locks your sponsor for good the moment your payouts are switched on, so the site waits for a real member to pick you up instead of placing you under the company. First it checks the network: if InstantAdPay already has a sponsor for your email or wallet, you are placed under them right away. Otherwise members see you at the top of their holding tank with a Ready to activate badge once your wallet is linked, and if nobody adopts you within 24 hours the site assigns you to the next eligible member in turn (someone active with their own $25 package). As soon as you have a sponsor, the site switches your payouts on under them for you (no cost to you) and tells you, with the transaction link. Buying is never held: you can buy a package at any time, but a purchase made before you have a sponsor places you under the platform position for good.' },
{ id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'no sponsor'],
re: /(holding tank|adopt|no sponsor|without a sponsor|orphan)/i,
a: 'Members who join from the public site with no sponsor wait in the holding tank under More, My line. A member who has switched on payouts and bought their own qualifying package can adopt one, first come, with a 7-day window for the new member to link a wallet or buy; otherwise they return to the tank. Adopting sets the sponsor, and their first purchase then binds to the adopter on the contract.' },
a: 'Members who join from the public site with no sponsor wait in the holding tank under More, My line, unless the network already knows their sponsor (the same email or wallet on InstantAdPay), in which case they are placed under that sponsor. A member who has switched on payouts and bought their own qualifying package can adopt one, first come, with a 7-day window for the new member to link a wallet or buy; otherwise they return to the tank. Adopting sets the sponsor, and their first purchase then binds to the adopter on the contract. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list; adopting one switches their payouts on under you right away. If nobody adopts them within 24 hours, the site assigns them to the next eligible adopter in turn (own $25 package, fewer than 2 open adoptions, signed in within the last 7 days); the one assigned least recently goes first. Someone waiting in the InstantAdPay tank as well is assigned there, and the adoption carries over to LinkSpin.' },
{ id: 'team', title: 'My line: the Team screen', q: ['How do I see my downline?', 'Who is in my team?'], tags: ['team', 'my line', 'downline', 'levels'],
re: /(my line|downline|my team|who (is|are) (in|on) my|three levels|level 1\b)/i,
a: 'Team shows your line as a working table, three levels deep: who joined through your link, who has switched on payouts, who has bought, and how many qualifying buyers each person has. The chip count is what opens your levels: two qualifying buyers ($25 or larger) open level 2, five open level 3.' },
@@ -171,6 +174,7 @@ ${refuelFact()}- PRODUCT, all free with an email account: SPIN LINKS (the rotato
- ACCOUNT: join at ${SITE_URL}/join with email only, a six-digit code, no password. Wallet linking happens inside the Control Room (Credits screen): one signature to link, then payouts switch on by activating (one transaction, gas only) or by buying any package. SafePal is the recommended wallet; MetaMask, Phantom (turn Polygon on first) and any WalletConnect wallet work; Trust Wallet blocks a buy that spends most of its POL. No card button on the site: members buy POL with a card on any major exchange or on-ramp, then send it to their own wallet on the Polygon network (guide at ${SITE_URL}/wallets); never name a specific exchange or on-ramp brand.
- SPONSOR: the invite link opened most recently sets the sponsor (30-day cookie), shown on the join page, locked when the account is created; the contract binds the buyer to that sponsor at the first purchase. CARRY-OVER: Crypto Team Build Network members who sign in with the email they use on InstantAdPay get their InstantAdPay sponsor from the network registry automatically when no invite link was used. Wrong sponsor before the first purchase: the admin can move the account. Members should switch on payouts before their people buy.
- CONTROL ROOM screens: Links, Pages, Zones (with Audiences), Ads, Credits, Reports, Team (three levels, who has payouts on, who bought, qualifying-buyer counts), Wallet (what was paid to this wallet, payout history). More at ${SITE_URL}/tools: Promo tools, Training, Pipeline (a follow-up board for prospects and directs), My line (including the holding tank: members who joined with no sponsor wait there and can be adopted by a member with payouts on and their own qualifying package), Profile.
- HOLDING TANK ACTIVATION HOLD (2026-10-27): a member with no sponsor is first matched to their network sponsor (the same email or wallet with a sponsor on InstantAdPay). Nobody known: the free Switch on payouts waits for an adopter and the Credits screen says "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left; they show at the top of every holding tank with a green Ready to activate badge and the hours left, and the shared payments topic on Telegram is told. Nobody adopts in 24 hours: the site assigns them to the next eligible adopter in rotation (own $25+ package, fewer than 2 open adoptions, signed in within 7 days; least recently auto-assigned first), and the pickup is posted marked (auto-assigned). The moment they have a sponsor (adopted, assigned or matched), the site switches their payouts on under that sponsor (engine-paid) and sends them the transaction link. A PURCHASE IS NEVER HELD: a tank member can buy at any time; with no sponsor yet that purchase places them under the platform position for good. Someone who arrived through a sponsor link is never held.
- PRE-LAUNCH (since 2026-10-17): LinkSpin is open to everyone for pre-launch testing until the official launch on November 15, 2026. Everything is live and working (links, sources, zones, ads, credits, payouts), but features and screens may change while it is tested. A notice at the top of every member screen says so. If someone got a reminder email about a member they have not contacted, they can ignore it: nothing changed in their line.
- SUPPORT (LIVE 2026-10-16): members open Help in the Control Room (${SITE_URL}/help) to send Marty a ticket (pick a category, a subject, the message), see each ticket's status (Open, Waiting on you, Closed), and read and answer his replies; a badge on the Help item shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at ${SITE_URL}/support, gets a private link to follow the ticket without signing in, and can reply there. The chat can also pass a conversation to support ("Send this to support"). Marty answers every ticket himself; there is no support email address, point people to ${SITE_URL}/support instead. Tickets share one desk with the rest of the Crypto Team Build Network.
- Leaderboard at ${SITE_URL}/leaderboard ranks members by packages sold to direct referrals (weekly, monthly, all time; prizes are credits, never cash). Release notes and roadmap at ${SITE_URL}/whats-new.
+1 -1
View File
@@ -535,6 +535,6 @@
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/admin-kb.js?v=20261020kb"></script>
<script src="/assets/admin.js?v=20261023ov"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
<script src="/assets/admin.js?v=20261027th"></script><script src="/assets/admin-sponsorcheck.js?v=20261022sc"></script><script src="/assets/admin-refill.js?v=20261024rf"></script><script src="/assets/admin-kits.js?v=20261024kit"></script>
</body>
</html>
+7 -2
View File
@@ -296,8 +296,13 @@
async function loadTank() {
try {
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
$('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window';
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>');
const nReady = r.waiting.filter(w => w.ready).length;
$('tankAdmSub').textContent = r.waiting.length + ' waiting' + (nReady ? ' (' + nReady + ' ready to activate)' : '') + ' · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window · ready members: the free activation is held ' + (r.holdHours || 24) + ' h (a purchase never is), then auto-assigned in rotation';
// ready = wallet linked: the plain activation is held (never the company) until someone adopts them or the 24-hour safety net assigns them (2026-10-27)
const left = w => { const ms = (w.holdUntil || 0) - Date.now(); if (ms <= 0) return 'assigning now'; const m = Math.round(ms / 60000); return (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + ' left'; };
const rb = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e">Ready to activate · ' + left(w) + '</span>' : '';
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (InstantAdPay) instead of the tank</th></tr>' + r.aligned.slice(0, 15).map(x => '<tr><td>' + esc(x.email) + '</td><td>' + esc(x.toName || x.to) + '</td><td class="when">' + when(x.at) + '</td><td class="muted">' + esc(x.via || '') + '</td></tr>').join('') : '');
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
} catch (e) {}
}
+11 -1
View File
@@ -82,6 +82,7 @@
$('walletBox').innerHTML = addr
? '<div class="code" style="display:block">' + esc(addr) + '</div>'
+ (on ? '<div class="ok"><span class="dot"></span>Payouts on. Every package your people buy pays this wallet in the same transaction.</div>'
: ME.tankHold ? '<div class="ink2" id="tankHoldNote" style="font-size:13px;color:#22c55e">' + esc(tankHoldText(ME.tankHold)) + '</div>' // held for an adopter: no activate button
: '<div class="ink2" style="font-size:13px">Linked, but payouts are off until this wallet is on the contract. Buying a package does that. So does the free activation below (gas only).</div><div class="acts"><button class="btn blue" type="button" id="activateBtn">Switch on payouts (free)</button></div>')
+ '<div class="acts"><a class="btn sm" href="' + esc((CFG && CFG.explorer) || 'https://polygonscan.com') + '/address/' + esc(addr) + '" target="_blank" rel="noopener">Open on the explorer</a><button class="btn sm" type="button" id="switchBtn">Switch account</button><button class="btn sm" type="button" id="dropBtn">Disconnect</button></div>'
+ posBlock()
@@ -145,8 +146,17 @@
}
async function guard(btn, fn) { if (btn.disabled) return; btn.disabled = true; try { await fn(); } catch (e) { CR.toast((e && e.message) || 'Something went wrong.', true); } finally { btn.disabled = false; } }
// holding tank (2026-10-27): no sponsor yet, so the free Switch on payouts waits for an adopter (24 hours at most).
// A purchase is never held: buying goes ahead as before.
const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
function tankHoldText(h) {
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
return t;
}
// a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default)
function holdText(sp) {
if (sp.sponsorBlocked === 'tankHold') return tankHoldText(sp.tankHold); // the free activation only (intent=activate), never a buy
const who = sp.sponsorName ? ('@' + String(sp.sponsorName).replace(/^@/, '')) : 'your sponsor';
if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. ') + 'Your first purchase waits until ' + (sp.claim.deadline ? new Date(sp.claim.deadline).toLocaleDateString() : 'they do') + ', then it goes ahead with the nearest member above who has one. Nothing was charged.';
if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts first (one free transaction).';
@@ -155,7 +165,7 @@
}
async function linkWallet() { CR.toast('Check your wallet for the free link signature…'); await IAPWallet.signIn(); CR.toast('Wallet linked. Earnings pay there from now on.'); await load(); }
async function activate() {
const sp = await CR.get('/api/sponsor?intent=buy'); if (sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; }
const sp = await CR.get('/api/sponsor?intent=activate'); if (sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; if (sp.sponsorBlocked === 'tankHold') { ME.tankHold = sp.tankHold || {}; paintWallet(); } return; }
CR.toast('Confirm the free activation in your wallet…');
const r = await IAPWallet.activate(sp.sponsorId || 0);
if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
+25 -6
View File
@@ -26,7 +26,17 @@
return r;
}
// holding tank (2026-10-27): no sponsor yet, so the free Switch on payouts waits for an adopter (24 hours at most).
// A purchase is never held: buying goes ahead as before.
const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
function tankHoldText(h) {
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
return t;
}
let TANK_HOLD = null;
function nextMove(d) {
if (TANK_HOLD && d.address && !d.memberId) return tankHoldText(TANK_HOLD);
if (!d.address) return 'Grab your link below and start sharing today. Then link your wallet (one free signature) so every payment can lock to you before your people start buying.';
if (!d.memberId) return 'Your wallet is linked. Switch on payouts above (one free transaction) and every purchase in your line pays you the moment it happens.';
if (d.buyerCount === 0) return 'Payouts are on and your link is live. Your next milestone: your first buyer of $25 or more. Every direct pays you 50 percent from their very first package.';
@@ -498,8 +508,9 @@
payouts: ['Switch on payouts', 'One small transaction registers your wallet with the contract so commissions can reach it. Buying any package does this automatically.', 'Activate payouts', () => jumpTo('wallet', 'activateBtn')],
package: ['Your first package', 'From $10. The $25 package is the one that counts you as a qualifying buyer for your sponsor and unlocks adopting from the holding tank.', 'See packages', () => jumpTo('buy', null)]
}[cur.k];
$('gsNow').innerHTML = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p><button type="button" class="btn" id="gsGo">' + copy[2] + '</button>';
$('gsGo').addEventListener('click', copy[3]);
if (cur.k === 'payouts' && TANK_HOLD) { copy[0] = 'Matching you with a sponsor'; copy[1] = tankHoldText(TANK_HOLD); copy[2] = null; } // no activate button while held
$('gsNow').innerHTML = '<p><b>Next: ' + copy[0] + '</b>' + copy[1] + (cur.k === 'wallet' ? ' <a href="/wallets" target="_blank" rel="noopener" style="color:var(--mint)">Wallet guide</a>' : '') + '</p>' + (copy[2] ? '<button type="button" class="btn" id="gsGo">' + copy[2] + '</button>' : '');
if (copy[2]) $('gsGo').addEventListener('click', copy[3]);
card.hidden = false;
}
function jumpTo(pane, id) {
@@ -600,7 +611,8 @@
tn.hidden = !(tw && tw.count);
if (tw && tw.count) tn.innerHTML = '<b>' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank</b> \u00b7 '
+ tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. <a href="#line">Adopt them from My line</a>'
+ (tw.eligible ? '.' : ' (you need your own $25 package first).');
+ (tw.eligible ? '.' : ' (you need your own $25 package first).')
+ (tw.ready ? ' <b style="color:#22c55e">' + tw.ready + ' of them ' + (tw.ready === 1 ? 'has' : 'have') + ' linked a wallet and ' + (tw.ready === 1 ? 'is' : 'are') + ' ready to switch on payouts.</b>' : '');
}
} catch (e) {}
if (d.username) { // wall link rides the username
@@ -697,6 +709,7 @@
else if (!render.waiting) { render.waiting = true; window.addEventListener('ls:session', () => { render.waiting = false; render(); }, { once: true }); }
}
if (!signedIn) return;
TANK_HOLD = (!me.memberId && me.tankHold) || null;
if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL
// REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be
// skipped or dismissed; it resolves only when a username is saved, then the area renders.
@@ -726,13 +739,16 @@
else who.push('<span style="display:inline-flex;align-items:center;gap:8px"><span aria-hidden="true" style="display:inline-flex;align-items:center;justify-content:center;width:20px;height:20px;border-radius:50%;border:2px solid var(--muted);color:var(--muted);font-weight:900;font-size:12px;line-height:1">!</span><b>No wallet connected yet</b> <span class="muted">(link one below)</span></span>');
if (me.memberId) who.push('on-chain <b>member #' + me.memberId + '</b>'
+ (me.onchainSponsorId ? ', sponsored by #' + me.onchainSponsorId : ''));
else if (me.sponsorId) who.push('invited by member #' + me.sponsorId);
else if (me.sponsorId && !TANK_HOLD) who.push('invited by member #' + me.sponsorId);
$('posLine').innerHTML = who.join('<br>');
$('creditLine').textContent = (me.credits || 0).toLocaleString();
loadPositions(me);
$('linkCard').hidden = !!me.address;
$('activateCard').hidden = !(me.address && !me.memberId);
{ let hn = $('tankHoldNote'); // held for an adopter: say so, and no activate button
if (!hn) { hn = document.createElement('p'); hn.id = 'tankHoldNote'; hn.className = 'small'; hn.style.cssText = 'margin:8px 0 0;color:#22c55e'; $('activateBtn').insertAdjacentElement('beforebegin', hn); }
hn.hidden = !TANK_HOLD; hn.textContent = TANK_HOLD ? tankHoldText(TANK_HOLD) : ''; $('activateBtn').hidden = !!TANK_HOLD; }
$('activityArea').hidden = !me.memberId;
$('campGate').hidden = true; // earned credits fund campaigns for everyone
$('campaignCard').hidden = false;
@@ -1265,7 +1281,8 @@
$('tankMine').querySelectorAll('[data-tchat]').forEach(b => b.addEventListener('click', () => openConvo(b.dataset.tchat, b.dataset.tname)));
$('tankMine').querySelectorAll('[data-pif]').forEach(b => b.addEventListener('click', () => pif(b.dataset.pif, b.dataset.pname, b.dataset.paddr)));
if (!r.waiting.length) { el.innerHTML = '<p class="muted small">The tank is empty. Anyone who joins from the public site without a sponsor lands here.</p>'; return; }
el.innerHTML = r.waiting.map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + '</span>'
const readyBadge = w => w.ready ? ' <span class="badge" style="background:rgba(34,197,94,.15);border-color:#22c55e;color:#22c55e" title="Wallet linked. If nobody adopts them, the site assigns them to the next eligible adopter when the time runs out.">Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '</span>' : '';
el.innerHTML = r.waiting.slice().sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0)).map(w => '<div class="lin-row"><span class="nm">' + esc(w.name) + readyBadge(w) + '</span>'
+ '<span class="em">joined ' + ago(w.joined) + '</span>'
+ '<span class="dt">last sign-in: <b>' + ago(w.lastSeen) + '</b></span>'
+ (r.eligible ? '<button class="btn small" type="button" data-adopt="' + esc(w.username || w.email) + '" data-aname="' + esc(w.name) + '">Adopt</button>' : '') + '</div>').join('');
@@ -2268,10 +2285,12 @@
if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. They have until ' + new Date(sp.claim.deadline).toLocaleString() + ' to do it, and we have told them. ') + 'You can use everything else meanwhile; your purchase waits so it pays the right person.';
if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts (Wallet tab, one free transaction), then try again.';
if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.';
if (sp.sponsorBlocked === 'tankHold') return tankHoldText(sp.tankHold);
return 'Your sponsor link could not be matched to a member. Send a ticket from Help (/help) before buying so ' + who + ' gets credit.';
}
$('activateBtn').addEventListener('click', busy($('activateBtn'), async () => {
const me = await (await fetch('/api/sponsor?intent=buy')).json();
const me = await (await fetch('/api/sponsor?intent=activate')).json(); // the free activation: a tank member waits for an adopter (a buy never does)
if (me.sponsorBlocked === 'tankHold') { TANK_HOLD = me.tankHold || {}; IAP.status(tankHoldText(me.tankHold), 'ok'); await render(); return; }
if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; }
IAP.status('Confirm the free activation in your wallet…');
const r = await IAPWallet.activate(me.sponsorId || 0);
+1 -1
View File
@@ -83,7 +83,7 @@
<script src="/assets/common.js?v=20261023ov"></script>
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/cr-shell.js?v=20261025ff"></script>
<script src="/assets/credits-screen.js?v=20261026a"></script>
<script src="/assets/credits-screen.js?v=20261027th"></script>
<script src="/assets/fuel.js?v=20261025ff"></script>
</body>
</html>
+1 -1
View File
@@ -1012,7 +1012,7 @@
<script src="/assets/tools.js?v=20261011a"></script>
<script src="/assets/wallet.js?v=20261021a"></script>
<script src="/assets/promo.js?v=20261020bs3"></script>
<script src="/assets/my.js?v=20261026a"></script>
<script src="/assets/my.js?v=20261027th"></script>
<script src="/assets/chat.js?v=20261016a"></script>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
// carry.ensureOnChain after the send (regression, 2026-10-27): txHash / lastErr were declared inside the try block and read
// after its finally, so EVERY engine activation threw "txHash is not defined" once the tx was mined (memberId not saved, no
// notice, in-flight flag stuck, and a buyer whose sponsor needed activating fell back to #1 in /api/sponsor?intent=buy).
// No real chain: the RPC is a dead local port (the send fails at once) and the stub chain then reports the member as on-chain,
// the same "mined although the follow-up read failed" path as the 2026-10-15 seed. node qa/carry-activate.test.cjs
'use strict';
const assert = require('assert');
const os = require('os');
const fs = require('fs');
const path = require('path');
process.env.ENGINE_KEY = '0x' + '11'.repeat(32); // throwaway key, never funded; the RPC below is unreachable
const carry = require(path.join(__dirname, '..', 'carry.js'));
(async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-carry-act-'));
let sent = false; const saved = [];
const acct = { email: 'm@x.co', address: '0x' + '2'.repeat(40), sponsorRef: '', memberId: 0 };
carry.init({ dataDir: dir, siteConfig: () => ({ defaultSponsorId: 1, carryNotices: '0' }),
accounts: { byEmail: async () => Object.assign({}, acct), setMemberId: async (e, id) => { saved.push([e, id]); } },
chain: { getConfig: () => ({ rpc: 'http://127.0.0.1:1', rpcs: ['http://127.0.0.1:1'], chainId: 137, contract: '0x' + '3'.repeat(40) }),
memberCount: async () => 50, memberIdByAccount: async () => { if (!sent) { sent = true; return 0; } return 77; } } });
const id = await carry.ensureOnChain(acct, 0, 'wallet');
assert.strictEqual(id, 77, 'returns the member number instead of throwing');
assert.deepStrictEqual(saved, [['m@x.co', 77]], 'member number saved on the account');
assert.ok(!carry.isBinding('m@x.co'), 'in-flight flag cleared');
const log = carry.status().log; assert.ok(log.some(e => e.type === 'activated' && e.id === 77), 'activation logged');
console.log('carry-activate: ok');
fs.rmSync(dir, { recursive: true, force: true });
})().catch(e => { console.error('carry-activate: FAIL', e.message); process.exit(1); });
+7 -1
View File
@@ -5,7 +5,8 @@
# 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 + carry hold guard
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests + carry hold guard + carry activation regression
# bash qa/run.sh tankhold # holding tank: network alignment first, plain-activation hold (never a purchase), 24-hour rotation, payouts on at assignment (unit with a mocked clock + fake engine, then a local copy with a mock InstantAdPay)
# bash qa/run.sh lsid # page-builder lead -> rotator conversion + postback, audience pixel events and cookieless hits
# bash qa/run.sh convpixel # conversion pixel: ad click ids, landing tag + goal pixel (url/stored/cookie/soft), dedupe, window, owner check, cost per goal, IAP partner calls, browser + framed
# bash qa/run.sh loginqueue # prepaid login-slot queue: ads.js unit test (two app copies promoting at once) + HTTP/Ads-screen e2e on a local copy
@@ -15,6 +16,8 @@
# mail key, devCode sign-in), so nothing touches production data. Reports land in qa/out/.
set -u
cd "$(dirname "$0")/.."
# no node_modules in this checkout: borrow InstantAdPay's (same ethers major) so ethers-based tests can load
[ -d node_modules ] || [ -n "${NODE_PATH:-}" ] || { [ -d ../../onchain-ad-membership/site/node_modules ] && export NODE_PATH="$(cd ../../onchain-ad-membership/site/node_modules && pwd)"; }
MODE="${1:-all}"
OUT="qa/out"; mkdir -p "$OUT"
TMP="${TMPDIR:-${TEMP:-/tmp}}/iap-qa-$$"
@@ -43,6 +46,9 @@ elif [ "$MODE" = "member" ]; then
elif [ "$MODE" = "sponsorfollow" ]; then
node qa/sponsorfollow.test.cjs || status=1
node qa/carry-hold.test.cjs || status=1
node qa/carry-activate.test.cjs || status=1
elif [ "$MODE" = "tankhold" ]; then
node qa/tank-hold.test.mjs || status=1
elif [ "$MODE" = "loginqueue" ]; then
node qa/loginqueue.test.cjs || status=1
node qa/loginqueue.e2e.mjs || status=1
+296
View File
@@ -0,0 +1,296 @@
// Holding tank on LinkSpin (2026-10-27): network ALIGNMENT first, the plain-activation hold, the 24-hour rotation, and
// payouts switched on the moment someone is assigned. node qa/tank-hold.test.mjs (or: bash qa/run.sh tankhold)
// Marty's rules under test: align with the network sponsor first; NEVER hold a purchase ("they'll just pay number one");
// hold only the free Switch on payouts for someone nobody knows; never fall back to #1 for an assigned member.
// Part A, no server: the real tank.js + carry.js with in-memory accounts, a fake chain, a fake engine sender (no key, no
// RPC) and a MOCKED CLOCK (tank.setClock); marks.js on a throwaway dir for the cross-copy claims.
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, no ENGINE_KEY, a throwaway LS_SYNC_SECRET and
// IAP_URL pointed at a mock InstantAdPay on 127.0.0.1 that answers sponsor-facts): /api/me + /api/sponsor per intent,
// live alignment, a sponsored member never held, admin tank, the Credits screen in a browser. Never production.
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import crypto from 'node:crypto';
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
const require = createRequire(path.join(SITE, 'package.json'));
delete process.env.DATABASE_URL; delete process.env.ENGINE_KEY; delete process.env.ENGINE_KEY_FILE;
let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra && !cond ? ' ' + extra : '')); if (!cond) fails++; };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const H = 3600000;
const addr = () => '0x' + crypto.randomBytes(20).toString('hex');
// ---------------- Part A ----------------
function fakeAccounts() {
const by = new Map(); let n = 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' + (n++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - 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 }; },
async setMemberId(e, id) { const a = by.get(e); if (a) a.memberId = Number(id) || 0; return { ok: true }; },
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)); }
};
}
function bench() {
for (const f of ['tank.js', 'carry.js', 'marks.js']) delete require.cache[require.resolve(path.join(SITE, f))];
const tank = require(path.join(SITE, 'tank.js')); const carry = require(path.join(SITE, 'carry.js')); const marks = require(path.join(SITE, 'marks.js'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-'));
marks.init({ dataDir: dir });
const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {}; const iap = new Set();
const blocked = new Set(); const onchain = new Map(); const sends = []; const env = { now: Date.now(), failSends: 0 }; let nextId = 500;
const chain = { recentEvents: () => events.slice().reverse(), getConfig: () => ({ explorer: 'https://polygonscan.com' }), memberCount: async () => 10000,
memberIdByAccount: async a => onchain.get(String(a).toLowerCase()) || 0 };
carry.init({ dataDir: dir, accounts, chain, siteConfig: () => ({ defaultSponsorId: 1, carryNotices: '0' }), messages: { deliver: async () => {} },
tankGate: (a, o) => tank.gate(a, o), claim: k => marks.claim(k), now: () => env.now, payoutBlocked: async id => blocked.has(id),
sendActivate: async (address, sponsorId) => { sends.push({ address: address.toLowerCase(), sponsorId }); await sleep(5);
if (env.failSends > 0) { env.failSends--; return { id: 0, txHash: null, lastErr: new Error('gas price spike (test)') }; }
const id = nextId++; onchain.set(address.toLowerCase(), id); return { id, txHash: '0x' + crypto.randomBytes(32).toString('hex'), lastErr: null }; } });
tank.init({ dataDir: dir, accounts, chain,
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject, text) => { mails.push({ to, subject, text }); } }, site: 'https://linkspin.test',
hooks: { network: async e => net[e] || null, iapOwns: async e => iap.has(e), payoutBlocked: async id => blocked.has(id), companyId: () => 1,
lifted: e => carry.activateAssigned(e), claim: k => marks.claim(k), bound: async a => onchain.get(String(a.address).toLowerCase()) || 0,
assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); } } });
tank.setClock(() => env.now);
let block = 1000;
const buyer = (email, memberId, o) => { const w = addr(); const a = accounts.add(email, Object.assign({ memberId, address: w, lastSeen: env.now - H }, o || {})); onchain.set(w, memberId); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2500, block: block++ }); return a; };
return { tank, carry, marks, accounts, events, chats, mails, alerts, assigned, net, iap, blocked, onchain, sends, env, buyer, dir };
}
async function partA() {
console.log('-- Part A: tank.js + carry.js, mocked clock, fake engine');
{ // the hold is for the plain activation only; a purchase never waits
const B = bench(); const { tank, carry, accounts, env, sends } = B; const t0 = env.now;
accounts.add('free@x.co');
const h0 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: hold record, no clock yet');
accounts._by.get('free@x.co').address = addr();
const id0 = await carry.ensureOnChain(await accounts.byEmail('free@x.co'), 0, 'wallet');
ok(id0 === 0 && sends.length === 0, 'wallet linked, nobody known: the engine does NOT switch payouts on under #1');
const h1 = await tank.holdFor(await accounts.byEmail('free@x.co'));
ok(h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'clock started at the wallet link, until = +24 h');
ok(carry.status().log.some(e => e.type === 'tankHold' && e.email === 'free@x.co'), 'the hold is logged in carry state');
accounts.add('kid@x.co', { sponsorRef: 'someone', address: addr() });
ok((await tank.holdFor(await accounts.byEmail('kid@x.co'))) === null, 'a member with a sponsor is never held');
// a sponsor placed on the contract because someone below is BUYING: never held (today's fallback stands)
accounts.add('upl@x.co', { address: addr() }); accounts.add('buyer@x.co', { sponsorRef: 'upl', address: addr() });
const sid = await carry.ensureOnChain(await accounts.byEmail('upl@x.co'), 0);
ok(sid > 0 && sends.length === 1 && sends[0].sponsorId === 1, 'tank member whose referral is buying: activated (under #1, the purchase is never held)', JSON.stringify(sends));
const w = await tank.waiting(); const fr = w.find(x => x.email === 'free@x.co');
ok(w[0] && w[0].email === 'free@x.co' && fr.ready && fr.holdUntil === t0 + 24 * H && fr.wallet, 'waiting(): ready member on top with holdUntil');
}
{ // ALIGN FIRST: the network knows a sponsor
const B = bench(); const { tank, carry, accounts, net, sends } = B;
B.buyer('boss@x.co', 31);
accounts.add('t1@x.co', { address: addr() }); net['t1@x.co'] = { sponsorEmail: 'boss@x.co', via: 'same email' };
const id = await carry.ensureOnChain(await accounts.byEmail('t1@x.co'), 0, 'wallet');
ok(id > 0 && sends.length === 1 && sends[0].sponsorId === 31 && (await accounts.byEmail('t1@x.co')).sponsorRef === 'boss', 'InstantAdPay knows the sponsor: aligned and switched on under #31, not held, not #1', JSON.stringify(sends));
ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @boss from InstantAdPay'), 'alignment recorded with the reason');
accounts.add('t2@x.co', { address: addr() }); net['t2@x.co'] = { sponsorEmail: 'boss@x.co', via: 'same wallet' };
const h2 = await tank.holdFor(await accounts.byEmail('t2@x.co'));
ok(h2 && h2.aligned && h2.aligned.via === 'same wallet', '/api/me path: aligned (by wallet), not held');
await sleep(40);
ok(sends.some(s => s.sponsorId === 31 && s.address === (B.accounts._by.get('t2@x.co').address)), '...and payouts switched on under the aligned sponsor right away');
accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'network sponsor with no LinkSpin account: held');
accounts.add('t4@x.co', { sponsorRef: 'boss' });
const rel = await tank.release('boss@x.co', 't4@x.co'); ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel));
net['t4@x.co'] = { sponsorEmail: 'boss@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them');
accounts.add('t5@x.co'); accounts.add('child@x.co', { sponsorRef: 't5', memberId: 33 }); net['t5@x.co'] = { sponsorEmail: 'child@x.co' };
ok((await tank.holdFor(await accounts.byEmail('t5@x.co'))).hold, 'never aligned under their own downline');
}
{ // 24-hour rotation + activation right away under the adopter
const B = bench(); const { tank, accounts, env, sends, chats, mails } = B; const t0 = env.now;
accounts.add('free@x.co', { address: addr() });
B.buyer('a@x.co', 11); B.buyer('b@x.co', 12); B.buyer('c@x.co', 13);
B.buyer('d@x.co', 14, { lastSeen: env.now - 8 * 86400000 }); B.buyer('e@x.co', 1); B.buyer('f@x.co', 16); B.blocked.add(16);
const tk = await tank.readyTick();
ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh));
ok((await tank.readyTick()).fresh.length === 0, '...and not twice');
ok(tk.assigned.length === 0, 'not assigned before 24 h');
env.now = t0 + 24 * H - 10 * 60000;
const r1 = await tank.readyTick();
ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', '24 h: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned));
const fa = await accounts.byEmail('free@x.co');
ok(fa.sponsorRef === 'a' && fa.memberId > 0, 'assigned AND on the contract right away', JSON.stringify({ s: fa.sponsorRef, id: fa.memberId }));
ok(sends.length === 1 && sends[0].sponsorId === 11, 'engine activation under the adopter #11, never #1', JSON.stringify(sends));
const ch = chats.find(c => c.from === 'a@x.co' && c.to === 'free@x.co');
ok(ch && /Your payouts are now on under @a/.test(ch.text) && /https:\/\/polygonscan\.com\/tx\/0x[0-9a-f]{64}/.test(ch.text), 'assignment chat says payouts are on under @a with the Polygonscan link', ch && ch.text);
ok(mails.some(m => m.to === 'free@x.co' && /Your payouts are now on under @a/.test(m.text)) && mails.some(m => m.to === 'a@x.co' && /their payouts are switched on under you/.test(m.text)), 'both sides emailed (member email carries the payouts line)');
ok((await tank.adminView()).adoptions[0].note === 'auto-assigned after 24 hours in the tank', 'adoption record note');
ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup "(auto-assigned)")');
// B next; then C (stale D, company E, no-payout F skipped); then back to A
accounts.add('free2@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
const r2 = await tank.readyTick(); ok(r2.assigned.length === 1 && r2.assigned[0].adopter === 'b@x.co', 'rotation: B next', JSON.stringify(r2.assigned));
accounts.add('free3@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
const r3 = await tank.readyTick(); ok(r3.assigned.length === 1 && r3.assigned[0].adopter === 'c@x.co', 'rotation: C (stale, company and no-payout chain skipped)', JSON.stringify(r3.assigned));
// activation fails (gas): stays assigned, retried next tick, never #1
B.env.failSends = 1; for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
accounts.add('free4@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
for (const em of ['a@x.co', 'b@x.co', 'c@x.co']) accounts._by.get(em).lastSeen = env.now - H;
const n0 = sends.length; const r4 = await tank.readyTick();
const f4 = await accounts.byEmail('free4@x.co');
ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co' && f4.sponsorRef === 'a' && !f4.memberId, 'rotation wraps to A; activation failed, sponsor kept, not on the contract yet', JSON.stringify({ a: r4.assigned, f4 }));
env.now += 15 * 60000; const r5 = await tank.readyTick(); // the next tick, a new claim window
const f4b = await accounts.byEmail('free4@x.co');
ok(f4b.memberId > 0 && sends.slice(n0).every(s => s.sponsorId === 11), 'retried on a later tick and switched on under A (#11), never #1', JSON.stringify(sends.slice(n0)));
ok(chats.some(c => c.to === 'free4@x.co' && /Your LinkSpin payouts are now on under @a/.test(c.text)), 'follow-up chat once the retried activation lands');
// A full (2 open), B + C stale: nobody eligible -> keep holding, one admin alert
accounts._by.get('b@x.co').lastSeen = env.now - 8 * 86400000; accounts._by.get('c@x.co').lastSeen = env.now - 8 * 86400000;
accounts.add('free5@x.co', { address: addr() }); await tank.readyTick(); env.now += 24 * H;
const r6 = await tank.readyTick(); const f5 = await accounts.byEmail('free5@x.co');
ok(r6.assigned.length === 0 && r6.held === 1 && !f5.sponsorRef && !f5.memberId, 'nobody eligible: keeps holding, never the company');
ok(B.alerts.length === 1 && /free5@x\.co/.test(B.alerts[0]), 'admin alerted once');
await tank.readyTick(); await tank.sweep(); ok(B.alerts.length === 1, 'no second alert');
void r5;
}
{ // manual adoption of a ready member: payouts on right away, follow-up chat with the link
const B = bench(); const { tank, accounts, sends, chats } = B;
accounts.add('m1@x.co', { address: addr() }); B.buyer('ad@x.co', 41); await tank.readyTick();
const r = await tank.adopt('ad@x.co', 'm1', 'Hi there');
ok(r.ok, 'manual adopt ok', JSON.stringify(r)); await sleep(60);
const m1 = await accounts.byEmail('m1@x.co');
ok(m1.memberId > 0 && sends.length === 1 && sends[0].sponsorId === 41, 'manual adoption: engine activation under the adopter #41', JSON.stringify(sends));
ok(chats.some(c => c.from === 'ad@x.co' && c.to === 'm1@x.co' && /payouts are now on under @ad/.test(c.text) && /polygonscan\.com\/tx\//.test(c.text)), 'member told in chat: payouts on under @ad with the Polygonscan link');
}
{ // cross-site + cross-copy guards
const B = bench(); const { tank, carry, accounts, env, sends, iap } = B;
accounts.add('both@x.co', { address: addr() }); B.buyer('a@x.co', 11); iap.add('both@x.co');
const t1 = await tank.readyTick(); ok(t1.fresh.length === 0, 'someone in the InstantAdPay tank: not announced here (InstantAdPay posts it)');
env.now += 24 * H; const t2 = await tank.readyTick();
ok(t2.assigned.length === 0 && t2.deferred === 1 && !(await accounts.byEmail('both@x.co')).sponsorRef, 'InstantAdPay owns the auto-assign: LinkSpin defers');
iap.delete('both@x.co');
await B.marks.claim('tankauto:both@x.co:' + Math.floor(env.now / 600000)); // the other app copy already took this window
const t3 = await tank.readyTick(); ok(t3.assigned.length === 0, 'deploy overlap: the window claimed by another copy, this copy does not assign');
env.now += 15 * 60000; for (const a of accounts._by.values()) if (a.email === 'a@x.co') a.lastSeen = env.now - H;
const t4 = await tank.readyTick(); ok(t4.assigned.length === 1, 'next window: assigned once');
// two concurrent activations of the same member: one send
accounts.add('dup@x.co', { address: addr(), sponsorRef: 'a' });
const [x, y] = await Promise.all([carry.activateAssigned('dup@x.co'), carry.activateAssigned('dup@x.co')]);
ok(sends.filter(s => s.address === accounts._by.get('dup@x.co').address).length === 1 && ((x.id && !y.id) || (!x.id && y.id)), 'two concurrent activations: exactly one engine send', JSON.stringify([x, y]));
accounts.add('dup2@x.co', { address: addr(), sponsorRef: 'a' });
await B.marks.claim('tankact:dup2@x.co:' + Math.floor(env.now / 600000));
const z = await carry.activateAssigned('dup2@x.co'); ok(!z.id && z.retry, 'another app copy holds the activation claim: nothing sent, retried later', JSON.stringify(z));
B.blocked.add(11); accounts.add('nop@x.co', { address: addr(), sponsorRef: 'a' });
const q = await carry.activateAssigned('nop@x.co'); ok(!q.id && /no-payout/.test(q.error), 'sponsor on a no-payout chain: not activated', JSON.stringify(q));
accounts.add('nowal@x.co', { address: addr(), sponsorRef: 'shellsp' }); accounts.add('shellsp@x.co', { username: 'shellsp' });
const n = await carry.activateAssigned('nowal@x.co'); ok(!n.id && n.retry && /no wallet/.test(n.error), 'sponsor without a wallet: not activated (never #1), retried', JSON.stringify(n));
}
}
// ---------------- Part B ----------------
async function partB() {
console.log('-- Part B: local copy + mock InstantAdPay');
const PORT = Number(process.env.TANKHOLD_PORT || 8803), IAPPORT = PORT + 1;
const BASE = 'http://127.0.0.1:' + PORT; const ADMIN_PW = 'localtest-th';
const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'ls-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads'));
const SECRET = crypto.randomBytes(24).toString('hex'); // throwaway
const iapRows = {}; let factsCalls = 0;
const mock = http.createServer((req, res) => { let d = ''; req.on('data', c => d += c); req.on('end', () => {
const sig = crypto.createHmac('sha256', SECRET).update(String(req.headers['x-ls-ts'] || '') + '\n' + d).digest('hex');
if (sig !== req.headers['x-ls-sig']) { res.writeHead(401); return res.end('{"error":"bad signature"}'); }
let b = {}; try { b = JSON.parse(d || '{}'); } catch (e) {}
let out = { ok: true, proto: 2 };
if (req.url === '/api/partner/sponsor-facts') { factsCalls++; out = { ok: true, proto: 2, platform: 'instantadpay', rows: (b.emails || []).map(e => iapRows[e]).filter(Boolean), view: {} }; }
res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify(out)); }); });
await new Promise(r => mock.listen(IAPPORT, '127.0.0.1', r));
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_PASSWORD: ADMIN_PW, ADMIN_EMAIL: 'admin@th.test', LS_SYNC_SECRET: SECRET, IAP_URL: 'http://127.0.0.1:' + IAPPORT });
for (const k of ['NODE_ENV', 'DATABASE_URL', 'ENGINE_KEY', 'ENGINE_KEY_FILE', 'OUTBOUND', 'LS_TESTERS', 'CURTAIN', 'NAS_DB_HOST', 'NAS_DB_USER', 'NAS_DB_PASSWORD', 'NAS_DB_NAME', 'SENDGRID_KEY', 'SENDGRID_API_KEY', 'OPENROUTER_API_KEY']) delete env[k];
const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] });
let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
let browser = null;
const req = (method, p, o) => new Promise((resolve, reject) => { o = o || {};
const headers = Object.assign({ 'User-Agent': 'Mozilla/5.0 QA', 'X-Forwarded-For': o.ip || '10.8.0.1' }, o.headers || {}); if (o.cookie) headers.Cookie = o.cookie;
let body = o.body; if (body) { body = Buffer.from(JSON.stringify(body)); headers['Content-Type'] = 'application/json'; headers['Content-Length'] = body.length; }
const r = http.request({ host: '127.0.0.1', port: PORT, path: p, method, headers }, res => { const ch = []; res.on('data', c => ch.push(c)); res.on('end', () => { const buf = Buffer.concat(ch); let j = null; try { j = JSON.parse(buf.toString()); } catch (e) {} resolve({ status: res.statusCode, headers: res.headers, json: j, text: buf.toString() }); }); });
r.on('error', reject); if (body) r.write(body); r.end(); });
let ipn = 1;
async function signIn(email, extraCookie) {
const ip = '10.8.' + (ipn++) + '.7';
const s = await req('POST', '/api/auth/email/start', { ip, cookie: extraCookie, body: { email, fts: Date.now() - 8000, hp_field_x9: '' } });
if (!s.json || !s.json.devCode) throw new Error('no devCode for ' + email + ': ' + s.text.slice(0, 200));
const v = await req('POST', '/api/auth/email/verify', { ip, cookie: extraCookie, body: { email, code: s.json.devCode } });
const c = [].concat(v.headers['set-cookie'] || []).map(x => x.split(';')[0]).join('; ');
return extraCookie ? c + '; ' + extraCookie : c;
}
const { ethers } = require('ethers');
async function linkWallet(cookie) {
const w = ethers.Wallet.createRandom();
const c = await req('POST', '/api/auth/challenge', { cookie, body: { address: w.address } });
const signature = await w.signMessage(c.json.message);
return (await req('POST', '/api/auth/verify', { cookie, body: { address: w.address, signature } })).json;
}
const ADMIN = { Authorization: 'Bearer ' + ADMIN_PW };
try {
let up = false; for (let i = 0; i < 60 && !up; i++) { try { up = (await req('GET', '/api/config')).status === 200; } catch (e) { await sleep(500); } }
if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500));
// 1. nobody knows them: tankHold on /api/me, the free activation held, a purchase NOT held
const tc = await signIn('qa-tank@example.com');
await req('POST', '/api/my/profile', { cookie: tc, body: { username: 'qatankone' } });
const lw = await linkWallet(tc); ok(lw && lw.linked, 'tank member links a wallet', JSON.stringify(lw));
const me = (await req('GET', '/api/me', { cookie: tc })).json;
ok(me && me.tankHold && me.tankHold.until - me.tankHold.since === 24 * H, '/api/me answers tankHold with a 24-hour clock', JSON.stringify(me && me.tankHold));
ok(me && me.sponsorBlocked !== 'tankHold', '/api/me never blocks (the buy flow reads it)', JSON.stringify({ b: me && me.sponsorBlocked }));
const act = (await req('GET', '/api/sponsor?intent=activate', { cookie: tc })).json;
ok(act && act.sponsorBlocked === 'tankHold' && !act.sponsorId && act.tankHold && act.tankHold.until === me.tankHold.until, 'Switch on payouts (intent=activate): held, no fallback sponsor', JSON.stringify({ id: act && act.sponsorId, b: act && act.sponsorBlocked }));
const buy = (await req('GET', '/api/sponsor?intent=buy', { cookie: tc })).json;
ok(buy && !buy.sponsorBlocked && !buy.tankHold, 'a PURCHASE (intent=buy) is never held, no hold text', JSON.stringify({ id: buy && buy.sponsorId, b: buy && buy.sponsorBlocked, h: buy && buy.tankHold }));
const adm = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json;
const row = adm && adm.waiting && adm.waiting.find(w => w.email === 'qa-tank@example.com');
ok(row && row.ready && row.holdUntil === me.tankHold.until, 'admin tank: Ready with holdUntil');
// 2. InstantAdPay knows their sponsor (live signed sponsor-facts): aligned, not held
const bc = await signIn('qa-boss@example.com'); await req('POST', '/api/my/profile', { cookie: bc, body: { username: 'qaboss' } });
iapRows['qa-tank2@example.com'] = { email: 'qa-tank2@example.com', sponsorEmail: 'qa-boss@example.com', sponsorRef: 'qaboss', memberId: 0, wallet: true, joinedVia: null, lastSeen: Date.now() };
const tc2 = await signIn('qa-tank2@example.com');
const me2 = (await req('GET', '/api/me', { cookie: tc2 })).json;
ok(me2 && !me2.tankHold && me2.sponsorName === '@qaboss', 'IAP knows the sponsor: aligned on /api/me, not held', JSON.stringify({ h: me2 && me2.tankHold, n: me2 && me2.sponsorName }));
const act2 = (await req('GET', '/api/sponsor?intent=activate', { cookie: tc2 })).json;
ok(act2 && act2.sponsorBlocked !== 'tankHold', '...and the free activation is not held', JSON.stringify(act2 && act2.sponsorBlocked));
const adm2 = (await req('GET', '/api/admin/tank', { headers: ADMIN })).json;
ok(adm2.aligned && adm2.aligned.some(x => x.email === 'qa-tank2@example.com' && x.to === 'qa-boss@example.com' && x.via === 'InstantAdPay sponsor'), 'admin tank lists the alignment (via InstantAdPay sponsor)');
ok(factsCalls >= 1, 'the live lookup went to the (mock) InstantAdPay, signed');
// 3. joined through a link: never held
const jc = await signIn('qa-kid@example.com', 'iap.sponsor=qaboss'); await linkWallet(jc);
const me3 = (await req('GET', '/api/me', { cookie: jc })).json;
ok(me3 && !me3.tankHold, 'member who joined through a sponsor link: no hold', JSON.stringify(me3 && me3.tankHold));
// 4. the Credits screen: hold note, no Switch on payouts button, the buy button still there
const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
let chromium = null; try { chromium = (await import(pathToFileURL(PW + '/index.js').href)).default.chromium; } catch (e) { console.log('SKIP browser check (no Playwright at ' + PW + ')'); }
if (chromium) {
browser = await chromium.launch();
const ctx = await browser.newContext({ viewport: { width: 390, height: 900 } });
await ctx.addInitScript(() => { try { sessionStorage.setItem('ls.la', '1'); } catch (e) {} });
await ctx.addCookies(tc.split('; ').filter(Boolean).map(kv => { const i = kv.indexOf('='); return { name: kv.slice(0, i), value: kv.slice(i + 1), domain: '127.0.0.1', path: '/' }; }));
const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message));
await page.goto(BASE + '/credits', { waitUntil: 'load' });
await page.waitForFunction(() => { const w = document.getElementById('walletBox'); return w && w.textContent.trim().length > 0; }, null, { timeout: 30000 }).catch(() => {}); await page.waitForTimeout(500);
const st = await page.evaluate(() => { const n = document.getElementById('tankHoldNote'); const hb = document.getElementById('holdBox');
return { note: n ? n.textContent : null, act: !!document.getElementById('activateBtn'), buy: !!document.getElementById('buyBtn'), hold: hb && !hb.hidden ? hb.textContent : null, wb: (document.getElementById('walletBox') || {}).textContent || null, url: location.href }; });
ok(st.note && st.note.startsWith("You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).") && /Time left: \d+ h \d+ min\./.test(st.note), 'Credits: hold text with time left', JSON.stringify(st));
ok(!st.act && st.buy && !st.hold, 'Credits: no Switch on payouts button, Buy still there, no hold box on the buy side', JSON.stringify(st));
try { fs.mkdirSync(path.join(SITE, 'qa/out'), { recursive: true }); await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-credits.png'), fullPage: true }); } catch (e) {}
ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200));
}
} finally {
if (browser) await browser.close().catch(() => {});
try { srv.kill(); } catch (e) {}
mock.close(); await sleep(500);
try { fs.rmSync(DATA, { recursive: true, force: true }); } catch (e) {}
}
}
await partA();
if (process.argv[2] !== 'unit') await partB();
console.log(fails ? '\n' + fails + ' FAILED' : '\nall passed');
process.exit(fails ? 1 : 0);
+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') {
+273 -13
View File
@@ -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 };