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 };