From 4645d5605a588321b1dab5de8be2741c7c96af36 Mon Sep 17 00:00:00 2001 From: martbost Date: Tue, 27 Oct 2026 06:03:41 -0500 Subject: [PATCH] Holding tank activation hold (Marty approved 2026-10-27, "hold them for no longer than 24 hours"): a tank member is never bound under the fallback #1 - Align first: a tank member whose email or wallet already has a sponsor on LinkSpin (the inbound registry rows) is placed under that sponsor when they have a real account here, never a sponsor they were released/rescued from, never a loop (recorded in tank-ready.json, shown in Admin tank) - Hold: /api/me and /api/sponsor answer tankHold {since, until} instead of the fallback sponsor; Wallet tab hides Activate payouts and shows "You're being matched with a sponsor..." with time left, Getting started has no activate button, buy flows (my + home) refuse on tankHold. The 24-hour clock starts when the member is first seen with a wallet linked (already-linked members start at deploy) - Surface: Ready to activate badge + hours left, ready members on top (My line tank, Admin tank, Overview notice count); one Telegram line per newly ready member (digest when more than 3, e.g. the first tick after deploy) - Safety net (readyTick every 15 min + hourly sweep): unadopted 24 h after readyAt -> next eligible adopter in rotation (own $20+ buy, fewer than 2 open, signed in within 7 days, not suspended/flagged, not company, not a no-payout chain, not in their own downline; least recently auto-assigned first, ties by earliest qualification) through adopt() with "auto-assigned after 24 hours in the tank", chat + email to both, Telegram pickup "(auto-assigned)". Nobody eligible: keep holding, one admin alert - tank.eligibility is now exported (the Overview tank notice was silently failing on it) - Chatbot: tank-hold canned answer, holding-tank answer + system prompt updated, KNOWLEDGE_DATE 2026-10-27 - qa/tank-hold.mjs (mocked clock unit + local copy e2e), wired into run.sh member and run.sh tankhold; cache tags bumped Co-Authored-By: Claude Opus 5.5 --- chatbot.js | 8 +- lsinbound.js | 12 +- public/admin.html | 2 +- public/assets/admin.js | 9 +- public/assets/home.js | 5 + public/assets/my.js | 30 ++++- public/index.html | 2 +- public/my.html | 2 +- qa/run.sh | 4 + qa/tank-hold.mjs | 246 +++++++++++++++++++++++++++++++++++++++++ server.js | 82 +++++++++++--- tank.js | 194 ++++++++++++++++++++++++++++++-- 12 files changed, 557 insertions(+), 39 deletions(-) create mode 100644 qa/tank-hold.mjs diff --git a/chatbot.js b/chatbot.js index 49e487f..32dab5f 100644 --- a/chatbot.js +++ b/chatbot.js @@ -31,7 +31,7 @@ function key() { function enabled() { return !!key(); } // ---- canned answers: instant, free, always in voice ---- -const KNOWLEDGE_DATE = '2026-10-26'; // bump whenever the canned answers / prompt are brought up to date +const KNOWLEDGE_DATE = '2026-10-27'; // bump whenever the canned answers / prompt are brought up to date const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i; const CANNED = [ { id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'], @@ -131,9 +131,12 @@ const CANNED = [ { id: 'pif', title: 'Pay it forward (PIF)', q: ['How do I PIF someone?', 'Can I buy a package for my referral?', 'Should I fund someone from the tank?'], tags: ['pif', 'pay it forward', 'gift', 'holding tank'], re: /\b(pif|p\.i\.f|pay(ing)? it forward|paid it forward|gift (them|him|her|someone|a member)|send (them|him|her) (some )?pol)\b|\b(fund(ing)?|pay(ing)? for|cover(ing)?|buy(ing)?|purchas(e|ing)|front(ing)?|spot)\b[^.?!]{0,50}\b(for (them|him|her|someone|a member|a new member|my (referral|downline|member))|(their|his|her|someone'?s|a member'?s) (first )?(package|starter|activation|\$?20))\b|\b(front|spot|lend|loan|advance|stake|grubstake)\b[^.?!]{0,30}\b(them|him|her|someone|a member|a new member|my (referral|downline|member))\b/i, a: 'PIF is a gift you send from your own wallet, and the site never touches the money. That is different from other platforms, where the site takes money out of your account balance and buys the position for the other person: InstantAdPay has no balances, so the POL goes straight from your wallet to theirs, and they buy their package themselves, from their own wallet. It only appears on your own free referrals and on members you have adopted, and only once they have linked a wallet, so you cannot PIF somebody who is still sitting in the holding tank. The order is: adopt them from Members > My line > Holding tank, get them to link a wallet on their Wallet tab, then the PIF button shows up, you enter an amount and your own wallet app opens with their address already filled in. Now the part that matters most: do not send anything until you have actually talked to that person and they have told you they will use it. Once that POL leaves your wallet it is gone, there is no refund, no chargeback and nothing we can do to pull it back, because the money goes straight from your wallet to theirs and never touches us. The gift is theirs to keep whatever they do with it, so they can go quiet, spend it on something else, or never sign in again, and none of that is against any rule. Someone in the holding tank joined with nobody working with them and may never have engaged at all, which makes an unanswered PIF the easiest money on this site to lose. Get a reply, get a clear commitment that they are going to buy and build, see that they have linked a wallet and are actually active, and only then decide. If they do buy a $20 package the contract pays you 50 percent as their sponsor and they become one of your qualifying buyers, so a gift that works costs you about half; a gift to somebody who never answers costs you all of it. Never gift money you need, never borrow to do it, and treat every PIF as money you are content to lose.' }, + { id: 'tank-hold', title: 'Matched with a sponsor (activation 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 first time you switch on payouts or buy, so the site waits until a real member picks you up instead of placing you under the company. Once your wallet is linked, members see you at the top of their holding tank with a Ready to activate badge. If nobody adopts you within 24 hours, the site assigns you to the next eligible member in turn (someone active with their own $20 package). As soon as you have a sponsor, the Switch on payouts button comes back and you can buy. If you already have a sponsor on LinkSpin with the same email or wallet, you are placed under them right away.' }, { id: 'holding-tank', title: 'Holding tank and adoptions', q: ['What is the holding tank?', 'How do I adopt a member?'], tags: ['holding tank', 'adopt', 'unsponsored'], re: /(holding tank|adopt(ing|ion|ed)? (a |an |from|someone|member)|orphan(ed)? member|no sponsor|unsponsored|release to tank)/i, - a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances.' }, + a: 'The holding tank is where free members who joined without a sponsor wait, and anyone can be picked up first come. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 2 open adoptions, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' }, { id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'], re: /(qualif|unlock level|level 2|level 3|pass.?up)/i, a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' }, @@ -243,6 +246,7 @@ ${passTiersFact()}${refuelFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagen - WALLETS + BUYING POL (Training > Wallets and buying POL, /wallets, members only): preferred MetaMask (recommended; extra accounts for Qualified Start), Phantom (PHANTOM GOTCHA: Polygon is OFF by default; Settings > Active Networks > turn on Polygon, otherwise connect/buy fails or shows the wrong network; seen with Jim Watts' EB team 2026-09-13), SafePal, Coinbase Wallet; Trust works but blocks buys spending most of its POL (keep ~2x). MoonPay flow: connect wallet, Buy packages > "Buy POL with a card" opens MoonPay with POL on Polygon + the member's address prefilled; card/Apple Pay/Google Pay; first-time ID check; minimum order ~$30; buy package cost + 2-3 POL for fees; POL arrives in minutes; then buy. Exchanges: withdraw POL on the Polygon network. Never MATIC on Ethereum, never share the recovery phrase. - INTRO VIDEO ON THE WALL: Profile > social links has an "Intro video" field (YouTube, Vimeo or direct .mp4 link). It embeds on the member's public wall page (/wall/) right under their bio, above the three-level line and the join button. - HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 2 open adoptions, 7-day window; if the person never links a wallet or buys, they fall back into the tank; a person can be adopted twice at most). Adopting sets the sponsor, opens a chat and emails the member; their first purchase then binds to the adopter on-chain. Members can also "Release to tank" one of their own free referrals (pay it forward), but NOT someone they adopted less than 3 days ago: an adoption is a commitment, and a dropped adoption still counts toward that person's two-adoption lifetime limit. Releases are posted to the feed and Telegram like pickups. Admin sees the tank under Members. +- TANK ACTIVATION HOLD (2026-10-27, Marty: never default a tank member to the company): a tank member (no sponsor, not activated) can NOT switch on payouts or buy their first package yet; the Wallet tab and Getting started card say "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)." with the time left, and the activate button is hidden. The 24-hour clock starts when they link a wallet; they then show at the top of every holding tank with a green "Ready to activate" badge and hours left, and a post goes to the team's Telegram payments topic. If nobody adopts them in 24 hours, the site auto-assigns them to the next eligible adopter in rotation (own $20+ package, fewer than 2 open adoptions, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. - DAILY CLAIM STREAK: finishing the daily ad set and claiming pays 5 credits on day 1, 7 on day 2, 10 from day 3, and 25 on every 7th consecutive day; miss a day and it restarts. After the set, verified visits (up to 20 a day, 1 credit each) keep earning, and the credits are meant to be spent on a campaign. - FOUR-MINUTE OVERVIEW VIDEO (2026-09-16): 'InstantAdPay in four minutes' is the first card on Members > Training (group 'Start here') and embedded on the home page at instantadpay.com/#overview-video (hero button 'Watch the 4-minute overview'). Send it to anyone asking what the platform is; the tab-by-tab walkthrough videos on Training go deeper. It is evergreen: no dates, no launch talk. - ANTI-FRAUD CHECKS (2026-09-16): at sign-up the site records IP, browser type and a browser cookie id. A second account from a browser that already has one is refused, so is a burst of new accounts from one connection in a day, and so is a sign-up through an invite link whose owner used that same browser. A sign-up from the same IP as the sponsor is allowed but flagged (households are fine). Flagged accounts never count on the leaderboard and cannot adopt from the holding tank; a suspended account cannot sign in. If a member says they were refused at sign-up, or asks how to get a second account to qualify themselves: one account per person, sign in to the existing one, and use QUALIFIED START (Buy packages tab) to link extra wallets of their own as positions under that account; each linked wallet that buys $20+ counts as one of their qualifying buyers, credits pool, and half of each such purchase returns to their main wallet. Levels 2 and 3 open at 2 and 5 qualifying buyers whether those buyers are referrals or the member's own linked positions. Shared computer at work or a library: contact support. Never suggest a second account. diff --git a/lsinbound.js b/lsinbound.js index 7b12fbb..fc65bd3 100644 --- a/lsinbound.js +++ b/lsinbound.js @@ -178,4 +178,14 @@ function adminView() { const s = load(); return Object.assign({}, s.stats, { knownRows: Object.keys(s.rows).length, pendingSponsors: Object.keys(s.pending).length, last: s.last || null, lastError: s.stats.lastError || null, recent: s.log.slice(-25).reverse() }); } -module.exports = { init, receive, adminView }; +// The holding tank asks (tank.js alignToNetwork, 2026-10-27): does LinkSpin already know a sponsor for this person? +// The newest row LinkSpin sent for the same email, else for the same wallet. LinkSpin's sponsorEmail is always a real +// member there (its sponsorRef; LinkSpin never writes the company fallback into an account). Read only. +function networkSponsor(email, address) { + if (!R) return null; const s = load(); const e = norm(email); const w = norm(address); + const r = s.rows[e]; + if (r && r.sponsorEmail && r.sponsorEmail !== e) return { sponsorEmail: r.sponsorEmail, via: 'same email' }; + if (/^0x[0-9a-f]{40}$/.test(w)) for (const x of Object.values(s.rows)) if (x.wallet === w && x.sponsorEmail && x.sponsorEmail !== e && x.email !== e) return { sponsorEmail: x.sponsorEmail, via: 'same wallet' }; + return null; +} +module.exports = { init, receive, adminView, networkSponsor }; diff --git a/public/admin.html b/public/admin.html index 65bc646..3926106 100644 --- a/public/admin.html +++ b/public/admin.html @@ -641,6 +641,6 @@ - + diff --git a/public/assets/admin.js b/public/assets/admin.js index 56add13..3e28b1f 100644 --- a/public/assets/admin.js +++ b/public/assets/admin.js @@ -294,8 +294,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 = 'WaitingEmailJoinedLast sign-in' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '').join('') : 'empty'); + 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 held ' + (r.holdHours || 24) + ' h, then auto-assigned in rotation'; + // ready = wallet linked: 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 ? ' Ready to activate · ' + left(w) + '' : ''; + $('tankWait').innerHTML = 'WaitingEmailJoinedLast sign-in' + (r.waiting.length ? r.waiting.map(w => '' + esc(w.name) + rb(w) + '' + esc(w.email) + '' + when(w.joined) + '' + (w.lastSeen ? when(w.lastSeen) : 'never') + '').join('') : 'empty') + + ((r.aligned || []).length ? 'Aligned to their network sponsor (LinkSpin) instead of the tank' + r.aligned.slice(0, 15).map(x => '' + esc(x.email) + '' + esc(x.toName || x.to) + '' + when(x.at) + '' + esc(x.via || '') + '').join('') : ''); $('tankAdopt').innerHTML = 'MemberAdopted byWhenWindow endsStatus' + (r.adoptions.length ? r.adoptions.map(a => '' + esc(a.adopteeName) + '' + esc(a.adopterName) + '' + when(a.ts) + '' + (a.status === 'released' ? '' : when(a.expires)) + '' + esc(a.status) + '').join('') : 'none yet'); } catch (e) {} } diff --git a/public/assets/home.js b/public/assets/home.js index 513cbed..0263bd8 100644 --- a/public/assets/home.js +++ b/public/assets/home.js @@ -46,6 +46,11 @@ // resolve the sponsor at buy time: a code referrer who activated since // page load still gets locked in const spNow = await (await fetch('/api/sponsor')).json(); + if (spNow.sponsorBlocked === 'tankHold') { // holding tank (2026-10-27): never bound under the company, held for an adopter + let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours)."; + if (spNow.tankHold && spNow.tankHold.until) { const m = Math.max(1, Math.round((spNow.tankHold.until - Date.now()) / 60000)); t += spNow.tankHold.until > Date.now() ? ' Time left: ' + (m >= 60 ? Math.floor(m / 60) + ' h ' + (m % 60) + ' min' : m + ' min') + '.' : ' Any minute now.'; } + IAP.status(t + ' Your package can go through then.', 'ok'); return; + } const r = await IAPWallet.buy(Number(btn.dataset.id), spNow.sponsorId || 0, btn.dataset.cost); if (r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.'); IAP.status('Purchase settled on-chain. Credits are yours, payouts delivered. Watch it on the ledger.', 'ok'); diff --git a/public/assets/my.js b/public/assets/my.js index 737a74f..111553e 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -33,7 +33,16 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str return r; } + // holding tank activation hold (2026-10-27): no sponsor yet, so the activation waits for an adopter (24 hours at most) + let TANK_HOLD = null; + 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; + } 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 $20 or more. Every direct pays you 50 percent from their very first package.'; @@ -642,8 +651,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str 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 $5. The $20 Activation 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 = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

'; - $('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 = '

Next: ' + copy[0] + '' + copy[1] + (cur.k === 'wallet' ? ' Wallet guide' : '') + '

' + (copy[2] ? '' : ''); + if (copy[2]) $('gsGo').addEventListener('click', copy[3]); card.hidden = false; } // member welcome offer from the games (2026-10-05): a game's after-win card sends players to /my?from=#buy. @@ -758,7 +768,8 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str tn.hidden = !(tw && tw.count); if (tw && tw.count) tn.innerHTML = '' + tw.count + (tw.count === 1 ? ' person is' : ' people are') + ' waiting for a sponsor in the holding tank \u00b7 ' + tw.names.map(esc).join(', ') + (tw.count > tw.names.length ? ' and more' : '') + '. Adopt them from My line' - + (tw.eligible ? '.' : ' (you need your own $20 package first).'); + + (tw.eligible ? '.' : ' (you need your own $20 package first).') + + (tw.ready ? ' ' + tw.ready + ' of them ' + (tw.ready === 1 ? 'has' : 'have') + ' linked a wallet and ' + (tw.ready === 1 ? 'is' : 'are') + ' ready to switch on payouts.' : ''); } } catch (e) {} // Share the presentation (2026-10-15): instantadpay.com/presentation?ref= sets the same sponsor cookie as /join @@ -871,6 +882,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str $('memberArea').hidden = !signedIn; if ($('mcFinish')) $('mcFinish').hidden = !walletOnly; if (!signedIn) return; + TANK_HOLD = (!me.memberId && me.tankHold) || null; if ($('adminLink')) $('adminLink').hidden = !me.isAdmin; // admin portal link, only for ADMIN_EMAIL if (!render.gamesChecked) { render.gamesChecked = true; fetch('/api/my/games').then(r => r.json()).then(g => { if ($('gamesNav')) $('gamesNav').hidden = !(g.games && g.games.length); }).catch(() => {}); } // Games appears once any game is live (admin sees previews) // REQUIRED first step (Marty, 2026-09-12): no username, nothing else. The modal cannot be @@ -926,6 +938,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str 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; @@ -1837,10 +1852,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str } catch (e) {} } function renderTank(el, r) { - const rows = listApply('tank', r.waiting); + const rows = listApply('tank', r.waiting).sort((a, b) => (b.ready ? 1 : 0) - (a.ready ? 1 : 0)); // ready to activate always on top (stable: the chosen order stays inside each group) el.innerHTML = ''; el.appendChild(listBar('tank', r.waiting.length, rows.length, () => renderTank(el, r), { hide: ['payouts'] })); // nobody in the tank has payouts on - el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + '' + const readyBadge = w => w.ready ? ' Ready to activate \u00b7 ' + (w.holdUntil > Date.now() ? holdLeft(w.holdUntil - Date.now()) + ' left' : 'assigning now') + '' : ''; + el.insertAdjacentHTML('beforeend', rows.length ? rows.map(w => '
' + esc(w.name) + readyBadge(w) + '' + 'joined ' + ago(w.joined) + '' + memberChips(w) + '' + 'last sign-in: ' + ago(w.lastSeen) + '' + (r.eligible ? '' : '') + '
').join('') @@ -2929,7 +2945,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.'); } const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy'); - if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company + if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), spNow.sponsorBlocked === 'tankHold' ? 'ok' : 'bad'); return; } // first activation must not hand a sponsored member to the company if (!fromPos && !meNow.memberId && spNow.sponsorRouted) IAP.status((spNow.sponsorRouted.from || 'Your sponsor') + ' has not switched on payouts, so this purchase credits ' + spNow.sponsorRouted.to + ' instead. You are not held up; carrying on.', 'ok'); // pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any // transaction that spends most of the balance ("drain your wallet"), so Trust users @@ -3179,10 +3195,12 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str const who = sp.sponsorName || 'your sponsor'; 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. Message support before buying so ' + who + ' gets credit.'; } $('activateBtn').addEventListener('click', busy($('activateBtn'), async () => { const me = await (await fetch('/api/me')).json(); + if (me.tankHold || me.sponsorBlocked === 'tankHold') { TANK_HOLD = me.tankHold || {}; IAP.status(tankHoldText(me.tankHold), 'ok'); await render(); return; } // never bound under the company 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); diff --git a/public/index.html b/public/index.html index 5e1eed7..4d76154 100644 --- a/public/index.html +++ b/public/index.html @@ -507,7 +507,7 @@ - + diff --git a/public/my.html b/public/my.html index 53a29b3..25fc43b 100644 --- a/public/my.html +++ b/public/my.html @@ -1223,7 +1223,7 @@ - + diff --git a/qa/run.sh b/qa/run.sh index 72892f4..fd5bf7e 100644 --- a/qa/run.sh +++ b/qa/run.sh @@ -5,6 +5,7 @@ # 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 tankhold # holding-tank activation hold, 24-hour safety net (mocked clock) and LinkSpin alignment: unit + local copy (also runs in member) # bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data) # bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it) # bash qa/run.sh gamepass # Game Pass buy flow + account-wide POL caps (polgrant) on their own local copy (qa/gamepass.mjs boots it) @@ -40,6 +41,9 @@ if [ "$MODE" = "public" ]; then node qa/chatbot-sync.mjs || status=1 elif [ "$MODE" = "member" ]; then start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796 + node qa/tank-hold.mjs || status=1 +elif [ "$MODE" = "tankhold" ]; then + node qa/tank-hold.mjs || status=1 elif [ "$MODE" = "sponsorfollow" ]; then node qa/sponsorfollow.test.cjs || status=1 node qa/sponsorfollow-e2e.mjs || status=1 diff --git a/qa/tank-hold.mjs b/qa/tank-hold.mjs new file mode 100644 index 0000000..83a4a69 --- /dev/null +++ b/qa/tank-hold.mjs @@ -0,0 +1,246 @@ +// Holding-tank activation hold + 24-hour safety net + network alignment (2026-10-27). +// node qa/tank-hold.mjs (or: bash qa/run.sh tankhold; also part of `bash qa/run.sh member`) +// Part A, no server: tank.js with in-memory accounts, a fake chain and a MOCKED CLOCK (tank.setClock): +// ready clock starts at first sight of a linked wallet, the hold, alignment to a LinkSpin sponsor (and the refusals: +// released-from sponsor, unclaimed shell, loop), the safety net at 24 h (rotation order, cap, 7-day sign-in, company +// excluded, no-payout chain skipped, own-downline skipped), nobody eligible = keep holding + one admin alert. +// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, devCode sign-in, LS_URL pointed at a dead local port so nothing +// reaches LinkSpin): a tank account links a wallet -> /api/me + /api/sponsor answer tankHold with no fallback sponsor, +// the Wallet tab hides Activate payouts and shows the hold text, the Getting started card has no activate button, +// Admin tank shows the ready badge; a member who joined through a link is never held; a LinkSpin row naming a sponsor +// aligns a tank member instead of holding them. Never production. Exit code 1 on any failure. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +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; // JSON stores only +let fails = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (extra ? ' ' + extra : '')); if (!cond) fails++; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +const H = 3600000; + +// ---------------- Part A ---------------- +function fakeAccounts() { + const by = new Map(); let nextId = 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' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * 86400000, lastSeen: Date.now() - H, joinedVia: null }, 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 listAll() { return [...by.values()].filter(a => !(a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId)).map(pub); }, + isUnclaimedShell: a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId, + 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() { + const tankPath = path.join(SITE, 'tank.js'); delete require.cache[require.resolve(tankPath)]; + const tank = require(tankPath); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-')); + const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const alerts = []; const assigned = []; const net = {}; + const blocked = new Set(); + const env = { now: Date.now() }; + tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) }, + messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 }, + mailer: { hasKey: () => true, send: async (to, subject) => { mails.push({ to, subject }); } }, site: 'https://iap.test', + hooks: { network: e => net[e] || null, isSuspended: () => false, excluded: () => false, payoutBlocked: async id => blocked.has(id), companyId: () => 1, + assigned: r => { assigned.push(r); }, adminAlert: t => { alerts.push(t); } } }); + tank.setClock(() => env.now); + let block = 1000; + const buyer = (email, memberId, o) => { const a = accounts.add(email, Object.assign({ memberId, address: '0x' + crypto.randomBytes(20).toString('hex'), lastSeen: env.now - H }, o || {})); events.push({ type: 'Purchase', buyerId: memberId, priceCents: 2000, block: block++ }); return a; }; + return { tank, accounts, events, chats, mails, alerts, assigned, net, blocked, env, buyer, dir }; +} +async function partA() { + console.log('-- Part A: tank.js with a mocked clock'); + { // hold + ready clock + safety net rotation + const B = bench(); const { tank, accounts, env } = B; + const t0 = env.now; + accounts.add('free@x.co'); // in the tank, no wallet + const h0 = await tank.holdFor(await accounts.byEmail('free@x.co')); + ok(h0 && h0.hold && h0.hold.since === null, 'tank member without a wallet: held, no clock yet'); + accounts._by.get('free@x.co').address = '0x' + 'a'.repeat(40); + const h1 = await tank.holdFor(await accounts.byEmail('free@x.co')); + ok(h1 && h1.hold && h1.hold.since === t0 && h1.hold.until === t0 + 24 * H, 'wallet linked: clock starts now, until = +24 h'); + env.now = t0 + 5 * H; + const h2 = await tank.holdFor(await accounts.byEmail('free@x.co')); + ok(h2.hold.since === t0, 'the clock does not restart on later visits'); + const sponsored = accounts.add('kid@x.co', { sponsorRef: 'someone', address: '0x' + 'b'.repeat(40) }); + ok((await tank.holdFor(sponsored)) === null, 'a member with a sponsor is never held'); + const w = await tank.waiting(); + ok(w[0] && w[0].email === 'free@x.co' && w[0].ready && w[0].holdUntil === t0 + 24 * H, 'waiting(): ready member first with holdUntil'); + // adopters: A qualified first, B second, C third; D stale (8 days), E company #1, F blocked chain, G full (2 open) + 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(); // 5 h in: nothing due + ok(tk.fresh.length === 1 && tk.fresh[0].email === 'free@x.co', 'readyTick announces the ready member once', JSON.stringify(tk.fresh.map(x => x.email))); + 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; // 23 h 50 min: inside the last tick, so the hold never runs past 24 h + const r1 = await tank.readyTick(); + ok(r1.assigned.length === 1 && r1.assigned[0].adopter === 'a@x.co', 'safety net: first in rotation = earliest qualified (A)', JSON.stringify(r1.assigned)); + const fa = await accounts.byEmail('free@x.co'); + ok(fa.sponsorRef === 'a', 'adoptee now sponsored by A', fa.sponsorRef); + ok((await tank.holdFor(fa)) === null, 'hold lifted once sponsored'); + const recs = (await tank.adminView()).adoptions; + ok(recs[0] && recs[0].note === 'auto-assigned after 24 hours in the tank' && recs[0].status === 'open', 'adoption record note', recs[0] && recs[0].note); + ok(B.chats.some(c => c.from === 'a@x.co' && c.to === 'free@x.co'), 'sponsor chat opened'); + ok(B.mails.some(m => m.to === 'free@x.co') && B.mails.some(m => m.to === 'a@x.co' && /holding tank is now in your line/.test(m.subject)), 'both sides emailed'); + ok(B.assigned.length === 1, 'assigned hook fired (Telegram pickup line with "(auto-assigned)")'); + // second ready member: rotation moves to B (A was just auto-assigned) + accounts.add('free2@x.co', { address: '0x' + 'c'.repeat(40) }); + 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: least recently auto-assigned next (B)', JSON.stringify(r2.assigned)); + // third: C; D stale, E company, F blocked chain never picked + accounts.add('free3@x.co', { address: '0x' + 'd'.repeat(40) }); + 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)); + // fourth: everyone in rotation has been used once: back to A (oldest auto-assign) + accounts.add('free4@x.co', { address: '0x' + 'e'.repeat(40) }); + 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 r4 = await tank.readyTick(); + ok(r4.assigned.length === 1 && r4.assigned[0].adopter === 'a@x.co', 'rotation wraps to the least recently assigned (A)', JSON.stringify(r4.assigned)); + // A now has 2 open adoptions (free + free4): full. Make B and C stale: nobody eligible + 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: '0x' + 'f'.repeat(40) }); + await tank.readyTick(); env.now += 24 * H; + const r5 = await tank.readyTick(); + const f5 = await accounts.byEmail('free5@x.co'); + ok(r5.assigned.length === 0 && r5.held === 1 && !f5.sponsorRef, '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 on later ticks / the hourly sweep'); + const h5 = await tank.holdFor(f5); + ok(h5 && h5.hold && h5.hold.until <= env.now, 'still held past the clock (client shows "Any minute now")'); + } + { // own-downline adopter skipped + const B = bench(); const { tank, accounts, env } = B; + accounts.add('top@x.co', { address: '0x' + '1'.repeat(40) }); + B.buyer('under@x.co', 21, { sponsorRef: 'top' }); B.buyer('other@x.co', 22); + await tank.readyTick(); env.now += 24 * H; + const r = await tank.readyTick(); + ok(r.assigned.length === 1 && r.assigned[0].adopter === 'other@x.co', 'an adopter in the member\'s own downline is skipped', JSON.stringify(r.assigned)); + } + { // network alignment + const B = bench(); const { tank, accounts, net } = B; + accounts.add('lsboss@x.co', { memberId: 31 }); + accounts.add('t1@x.co', { address: '0x' + '2'.repeat(40) }); net['t1@x.co'] = { sponsorEmail: 'lsboss@x.co', via: 'same email' }; + const h = await tank.holdFor(await accounts.byEmail('t1@x.co')); + ok(h && h.aligned && (await accounts.byEmail('t1@x.co')).sponsorRef === 'lsboss', 'LinkSpin sponsor with an account here: aligned, not held', JSON.stringify(h)); + ok((await tank.adminView()).aligned[0].why.includes('aligned to network sponsor @lsboss from LinkSpin'), 'alignment recorded with the reason'); + accounts.add('shell@x.co', { joinedVia: 'linkspin', lastSeen: 0 }); + accounts.add('t2@x.co'); net['t2@x.co'] = { sponsorEmail: 'shell@x.co' }; + ok((await tank.holdFor(await accounts.byEmail('t2@x.co'))).hold, 'sponsor only an unclaimed LinkSpin shell here: held, not aligned'); + accounts.add('t3@x.co'); net['t3@x.co'] = { sponsorEmail: 'nobody@x.co' }; + ok((await tank.holdFor(await accounts.byEmail('t3@x.co'))).hold, 'sponsor with no account here: held'); + // released from lsboss on purpose: never back to them + accounts.add('t4@x.co', { sponsorRef: 'lsboss' }); + const rel = await tank.release('lsboss@x.co', 't4@x.co'); + ok(rel && rel.ok, 'release to the tank (setup)', JSON.stringify(rel)); + net['t4@x.co'] = { sponsorEmail: 'lsboss@x.co' }; + ok((await tank.holdFor(await accounts.byEmail('t4@x.co'))).hold, 'never aligned back to a sponsor who released them'); + // loop: the LinkSpin sponsor sits under the tank member + 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'); + } +} + +// ---------------- Part B ---------------- +async function partB() { + console.log('-- Part B: local copy'); + const PORT = Number(process.env.TANKHOLD_PORT || 8799); + const BASE = 'http://127.0.0.1:' + PORT; const ADMIN = 'localtest'; + const DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-tankhold-srv-')); fs.mkdirSync(path.join(DATA, 'uploads')); + const LSSECRET = crypto.randomBytes(24).toString('hex'); // throwaway + const srv = spawn(process.execPath, ['server.js'], { cwd: SITE, stdio: ['ignore', 'pipe', 'pipe'], + env: Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, NODE_ENV: 'development', ADMIN_EMAIL: 'qa-admin@example.com', ADMIN_PASSWORD: ADMIN, LS_SYNC_SECRET: LSSECRET, LS_URL: 'http://127.0.0.1:1' }) }); + let log = ''; srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d); + let browser = null; + try { + let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(BASE + '/api/config')).ok; } catch (e) { await sleep(500); } } + if (!up) throw new Error('local server did not come up:\n' + log.slice(-1500)); + const api = async (p, body, hdr) => { const r = await fetch(BASE + p, body ? { method: body.method || 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, hdr || {}), body: JSON.stringify(body.data || body) } : { headers: hdr || {} }); let j = null; try { j = await r.json(); } catch (e) {} return { status: r.status, j }; }; + const adminH = { Authorization: 'Bearer ' + ADMIN }; + await api('/api/admin/site', { method: 'PATCH', data: { fraudMaxSignupsPerIpDay: 20 } }, adminH); + async function signIn(email, username, extraCookie) { + const s = await api('/api/auth/email/start', { email, fts: Date.now() - 5000 }, extraCookie ? { Cookie: extraCookie } : null); + const v = await fetch(BASE + '/api/auth/email/verify', { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extraCookie ? { Cookie: extraCookie } : {}), body: JSON.stringify({ email, code: s.j && s.j.devCode }) }); + const cookie = (v.headers.getSetCookie ? v.headers.getSetCookie() : [v.headers.get('set-cookie')]).map(c => String(c).split(';')[0]).filter(c => /^iap\./.test(c) || c.includes('=')).join('; '); + if (username) await api('/api/my/profile', { username }, { Cookie: cookie }); + return cookie; + } + const { ethers } = require('ethers'); + async function linkWallet(cookie) { + const w = ethers.Wallet.createRandom(); + const c = await api('/api/auth/challenge', { address: w.address }, { Cookie: cookie }); + const signature = await w.signMessage(c.j.message); + const v = await api('/api/auth/verify', { address: w.address, signature }, { Cookie: cookie }); + return { w, v }; + } + // 1. tank member with a wallet + const tc = await signIn('qa-tank@example.com', 'qatankone'); + const lw = await linkWallet(tc); + ok(lw.v.j && lw.v.j.linked, 'tank member links a wallet', JSON.stringify(lw.v.j)); + const me = (await api('/api/me', null, { Cookie: tc })).j; + 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.sponsorId && me.sponsorBlocked === 'tankHold', '/api/me: no fallback sponsor (sponsorId ' + (me && me.sponsorId) + ')'); + const sp = (await api('/api/sponsor?intent=buy', null, { Cookie: tc })).j; + ok(sp && !sp.sponsorId && sp.sponsorBlocked === 'tankHold' && sp.tankHold && sp.tankHold.until === me.tankHold.until, '/api/sponsor (buy) holds too, no fallback', JSON.stringify({ id: sp && sp.sponsorId, b: sp && sp.sponsorBlocked })); + const adm = (await api('/api/admin/tank', null, adminH)).j; + 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. joined through a link: never held, today's behaviour + const jc = await signIn('qa-kid@example.com', 'qakidone', 'iap.sponsor=qatankone'); + await linkWallet(jc); + const me2 = (await api('/api/me', null, { Cookie: jc })).j; + ok(me2 && !me2.tankHold && me2.sponsorBlocked !== 'tankHold' && me2.sponsorId > 0, 'member with a sponsor link: no hold, sponsor resolves as before', JSON.stringify({ id: me2 && me2.sponsorId, b: me2 && me2.sponsorBlocked, routed: me2 && me2.sponsorRouted })); + // 3. LinkSpin knows a sponsor for this email: aligned instead of held + await signIn('qa-lsboss@example.com', 'qalsboss'); + const tc3 = await signIn('qa-tank3@example.com', 'qatankthree'); + const raw = JSON.stringify({ rows: [{ email: 'qa-tank3@example.com', username: 'qatankthree', sponsorEmail: 'qa-lsboss@example.com', joinedAt: Date.now() - 86400000 }] }); + const ts = String(Date.now()); const sig = crypto.createHmac('sha256', LSSECRET).update(ts + '\n' + raw).digest('hex'); + const pr = await fetch(BASE + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw }); + ok(pr.ok, 'LinkSpin row accepted (first-platform rule leaves the sponsor empty)'); + const me3 = (await api('/api/me', null, { Cookie: tc3 })).j; + ok(me3 && !me3.tankHold && me3.sponsorBlocked !== 'tankHold', 'tank member LinkSpin knows: aligned, not held', JSON.stringify({ b: me3 && me3.sponsorBlocked, h: me3 && me3.tankHold })); + const adm3 = (await api('/api/admin/tank', null, adminH)).j; + ok(adm3 && adm3.aligned && adm3.aligned.some(x => x.email === 'qa-tank3@example.com' && x.to === 'qa-lsboss@example.com'), 'admin tank lists the alignment'); + // 4. the page: Wallet tab + Getting started card + const PW = process.env.PW || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; + const { chromium } = (await import(pathToFileURL(PW + '/index.js').href)).default; + browser = await chromium.launch(); + const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); + await ctx.addInitScript(() => { try { sessionStorage.setItem('iap.welcome.v1', '1'); localStorage.removeItem('iap.gs.collapsed'); } catch (e) {} }); + await ctx.addCookies(tc.split('; ').filter(Boolean).map(c => { const i = c.indexOf('='); return { name: c.slice(0, i), value: c.slice(i + 1), url: BASE }; })); + const page = await ctx.newPage(); const errs = []; page.on('pageerror', e => errs.push(e.message)); + await page.goto(BASE + '/my#wallet', { waitUntil: 'load' }); await page.waitForTimeout(4000); + const st = await page.evaluate(() => { const b = document.getElementById('activateBtn'); const n = document.getElementById('tankHoldNote'); const g = document.getElementById('gsNow'); + return { card: !document.getElementById('activateCard').hidden, btnHidden: !!(b && b.hidden), note: n && !n.hidden ? n.textContent : null, gs: g ? g.textContent : '', gsBtn: !!document.getElementById('gsGo') }; }); + ok(st.card && st.btnHidden, 'Wallet tab: Activate payouts button hidden', JSON.stringify(st)); + 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), 'hold text with time left', st.note); + ok(/Matching you with a sponsor/.test(st.gs) && !st.gsBtn, 'Getting started: hold text, no activate button', st.gs.slice(0, 120)); + await page.screenshot({ path: path.join(SITE, 'qa/out/tank-hold-wallet.png') }).catch(() => {}); + ok(!errs.length, 'no page errors', errs.join(' | ').slice(0, 200)); + } finally { + if (browser) await browser.close().catch(() => {}); + try { srv.kill(); } catch (e) {} + 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); diff --git a/server.js b/server.js index c1a1527..a7ad5bd 100644 --- a/server.js +++ b/server.js @@ -634,7 +634,11 @@ async function boot() { sponsorAccount: em => accounts.byEmail(em), wouldCycle: async (email, sp) => { let cur = sp; const seen = new Set(); for (let i = 0; cur && i < 60; i++) { if (cur.email === email || seen.has(cur.email)) return true; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); } return false; }, activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null }); - tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore }); + tank.init({ dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore, + // activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position + hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em), + payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1, + assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text) } }); // LinkSpin registry sync (2026-10-08): every account change is pushed to LinkSpin within seconds; a 2-minute reconcile catches the rest lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email)); lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore }); @@ -712,6 +716,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)), 2 * 60 * 1000); // after the LinkSpin inbound state is loaded + 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 @@ -1465,6 +1471,43 @@ async function tankNotifyTick() { + '\nAdopt from My line \u203a Holding tank: instantadpay.com/my'; await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId); } +// 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} InstantAdPay \u00b7 ' + clean(adopterName) + ' picked up ' + clean(adopteeName) + ' from the holding tank and is now their sponsor' + (auto ? ' (auto-assigned)' : ''), sc.telegramEchoTopicId).catch(() => {}); + } catch (e) {} +} +// admin-only channels (never a member-visible topic: it names an email), the same order as the video-sweep alerts +async function tankAdminAlert(text) { + const sc = siteConfig(); const hermes = String(process.env.HERMES_BOT_TOKEN || '').trim(); + const html = String(text).replace(/&/g, '&').replace(//g, '>'); + if (hermes && sc.telegramAdminChatId) return tgSendAs(hermes, sc.telegramAdminChatId, html); + if (sc.telegramBotToken && sc.telegramAdminChatId) return telegramSend(sc.telegramAdminChatId, html); + if (ADMIN_EMAIL && mailer.hasKey()) return mailer.send(ADMIN_EMAIL, 'InstantAdPay: holding tank needs an adopter', text); + console.log('tank: no admin channel configured, alert not sent:', text); +} +// holding tank every 15 min (2026-10-27): 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 +async function tankReadyTick() { + const r = await tank.readyTick(); + if (r.aligned || r.assigned.length || r.held || r.fresh.length) console.log('tank ready tick', JSON.stringify({ fresh: r.fresh.length, aligned: r.aligned, assigned: r.assigned.length, held: r.held })); + const sc = siteConfig(); + if (!r.fresh.length || !sc.telegramBotToken || !sc.telegramEchoChatId) return r; + const clean = t => String(t || '').replace(/[<>&]/g, ''); + const link = 'https://instantadpay.com/my#line'; + if (r.fresh.length <= 3) { + for (const w of r.fresh) await telegramSend(sc.telegramEchoChatId, '\u{1F7E2} ' + (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} ' + 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(); @@ -2270,9 +2313,20 @@ const server = http.createServer(async (req, res) => { } } else if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; if (u.searchParams.get('intent') === 'buy') sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); } if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; } + // holding tank (2026-10-27): a signed-in member with no sponsor and no member number is never bound under the + // fallback. Network sponsor first (LinkSpin), else the hold (the buy and activate buttons refuse on tankHold). + let tankHold = null; + if (!sponsorId && acct && !acct.sponsorRef && !acct.memberId) { + try { + const h = await tank.holdFor(acct); + if (h && h.aligned) { const a2 = await accounts.byEmail(acct.email); const sp2 = await resolveSponsorDetailed(a2 && a2.sponsorRef); if (sp2.id && !(await payoutChainBlocked(sp2.id, 2))) sponsorId = sp2.id; else tankHold = { since: null, until: null }; } // aligned: their sponsor's position (or held while it is not usable yet) + else if (h && h.hold) tankHold = h.hold; + } catch (e) { tankHold = { since: null, until: null }; } + if (tankHold) sponsorBlocked = 'tankHold'; + } // 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 && !tankHold && (!acct || acct.memberId !== (Number(siteConfig().defaultSponsorId) || 1))) sponsorId = Number(siteConfig().defaultSponsorId) || 1; let name = null, avatarUrl = null, own = false; // the join page names the owner of the LINK it was opened with (?ref=token), not the visitor's own // sponsor: a member previewing their own invite page was seeing their upline's name (Jim, 2026-09-13) @@ -2295,7 +2349,7 @@ const server = http.createServer(async (req, res) => { let invited = !!showTok; if (!invited && tok) { try { invited = !(await fraud.hasAccountOnDevice(req)); } catch (e) { invited = true; } } if (acct) invited = false; // already a member: they are not joining anybody's line - return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited, 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, sponsorName: spd.name || null, invited, 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) {} @@ -2669,7 +2723,9 @@ 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; + let acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null; + // holding tank (2026-10-27): someone the network already knows is placed under that sponsor first (tank.js alignToNetwork) + if (acct && !acct.sponsorRef && !acct.memberId && !memberId) { try { if (await tank.alignToNetwork(acct)) acct = (await accounts.byEmail(acct.email)) || acct; } catch (e) {} } const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id; let sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null; let sponsorRouted = null; @@ -2680,12 +2736,16 @@ const server = http.createServer(async (req, res) => { } if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0; const _defSpon = Number(siteConfig().defaultSponsorId) || 1; - if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) + // a holding-tank member is never bound under the fallback: held for an adopter (24 h at most, then the rotation) + let tankHold = null; + if (!sponsorId && !memberId && acct && !acct.sponsorRef && !acct.memberId) { try { const h = await tank.holdFor(acct); if (h && h.hold) tankHold = h.hold; } catch (e) { tankHold = { since: null, until: null }; } } + if (tankHold) sponsorBlocked = 'tankHold'; + else if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor) if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'shardsofvalor'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, 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, @@ -2713,7 +2773,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, @@ -3172,13 +3232,7 @@ const server = http.createServer(async (req, res) => { if (fraud.excluded(s.email)) return json(res, 403, { error: 'Adoptions are not available on this account. Contact support at instantadpay.com/support.' }); 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} InstantAdPay \u00b7 ' + clean(r.adopterName) + ' picked up ' + clean(r.adopteeName) + ' from the holding tank and is now their sponsor', sc.telegramEchoTopicId).catch(() => {}); - } catch (e) {} + tankPickupPost(r.adopterName, r.adopteeName, false); } return json(res, r.error ? 400 : 200, r); } diff --git a/tank.js b/tank.js index f2cd779..76fceed 100644 --- a/tank.js +++ b/tank.js @@ -63,7 +63,8 @@ const rowA = r => ({ id: r.id, adoptee: r.adoptee, adopter: r.adopter, ts: Numbe const impl = () => db.enabled() ? D : J; let ads = null; -function init(opts) { DATA_DIR = opts.dataDir; accounts = opts.accounts; chain = opts.chain; messages = opts.messages; mailer = opts.mailer; ads = opts.ads || null; 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; ads = opts.ads || null; 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 LinkSpin // 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; @@ -85,8 +86,11 @@ async function waiting() { const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {}; return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0, wallet: !!a.address, activated: !!a.memberId, // in the tank "activated" is always false (payouts on = out of the tank); wallet can still be linked - earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0 })) - .sort((a, b) => (b.lastSeen || b.joined) - (a.lastSeen || a.joined)); + earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0, + // wallet linked = ready to switch on payouts, 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 $20+ package themselves? (the qualifying-for-yourself buy) @@ -113,10 +117,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 }; @@ -127,21 +132,28 @@ 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 InstantAdPay 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 }); + 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 = now; rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now try { await messages.sendChat(me.memberId || 0, e, target.email, text); } catch (err) {} if (mailer && mailer.hasKey()) { try { await mailer.send(target.email, nameOf(me) + ' is now your sponsor on InstantAdPay', 'You joined InstantAdPay 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\nInstantAdPay'); } catch (err) {} + if (auto) { + try { + await mailer.send(e, 'InstantAdPay: ' + 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: when they switch on payouts or buy, it locks under you.\n\nWe sent them this chat from you:\n\n' + text + '\n\nSay hello and help them with their first steps: ' + siteUrl + '/my#line\n\nInstantAdPay'); + } 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 @@ -186,7 +198,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 @@ -308,11 +321,170 @@ async function historyMap() { return out; } +// ── activation hold (Marty, 2026-10-27: "hold them for no longer than 24 hours") ── +// The contract binds a sponsor for good at the first activation or purchase. A tank member (no sponsor, no member +// number) who switched on payouts used to be bound under the fallback position (#1), which took them out of the tank +// for ever. Now, in this order: +// 1. ALIGN: someone the network already knows (LinkSpin has a sponsor for the same email or wallet) is placed under +// that sponsor, when the sponsor has a real account here and is not a sponsor this person was released or rescued +// from. Ordinary sponsor write (accounts.setSponsorRef): LinkSpin already agrees, so nothing follows anywhere. +// 2. HOLD: otherwise /api/me and /api/sponsor answer tankHold instead of the fallback and the site refuses the +// activation / first purchase. The clock starts when the member is first seen 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. +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.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 here 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) { + if (!a || !inTank(a) || !hooks.network) return null; + const e = String(a.email || '').toLowerCase(); if (!e) return null; + const n = hooks.network(e, a.address || 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 || (accounts.isUnclaimedShell && accounts.isUnclaimedShell(sp))) return null; // the sponsor must really be here + 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 why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')'; + st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', 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) {} } + return { to: sp.email, toName: nameOf(sp), via: n.via || 'email', why }; +} +// /api/me and /api/sponsor, when the fallback position would be used: align first, else the hold +async function holdFor(a) { + if (!a || !inTank(a)) return null; + const al = await alignToNetwork(a).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 } }; +} +// adopters for the safety net, in rotation order +async function rotation(excludeEmail) { + const qual = new Map(); // member # -> block of their first own $20+ 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; + const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) continue; // suspended or fraud-flagged: the same rule as a manual adoption + 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 }; + 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(); continue; } // adopted, aligned, bought or gone: the hold has lifted + if (remoteOpen(e) || !a.address) continue; // picked up on LinkSpin (the follow lands here shortly) / wallet unlinked + if (now < rec.readyAt + READY_MS - TICK_MS) continue; + 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) { + 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 InstantAdPay 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) { try { await hooks.adminAlert('InstantAdPay holding tank: ' + nameOf(a) + ' (' + e + ') linked a wallet ' + Math.round((now - rec.readyAt) / 3600000) + ' hours ago and nobody is eligible to take them (own $20+ package, fewer than ' + CAP_OPEN + ' open adoptions, signed in within 7 days, not suspended or on a no-payout chain). They stay on hold, never under the company. Adopt them from 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). +async function readyTick() { + const st = RS.load(); const fresh = []; let aligned = 0; + for (const a of await accounts.listAll(5000)) { + if (!inTank(a)) continue; + if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; } + if (remoteOpen(a.email)) continue; + const rec = markReady(a); + if (rec && !rec.notified) { rec.notified = clock(); fresh.push({ email: a.email, name: nameOf(a), username: a.username || null, until: rec.readyAt + READY_MS }); } + } + RS.save(); + const auto = await autoAssign(); + return { fresh, aligned, assigned: auto.assigned, held: auto.held }; +} +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, markReady, readyRec, readyTick, autoAssign, alignToNetwork, alignedRecent, setClock, eligibility, 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 };