5xYourTeam The Draft on the network holding tank (Marty approved the rules 2026-11-15): signed partner routes draftpartner.js, LOCAL ONLY

POST /api/partner/draft/{pool,adopt,release,status}, HMAC DRAFT_PARTNER_SECRET over 'draft.v1.' + ts + newline + body (X-Draft-Ts /
X-Draft-Sig, 5 min), 503 until the secret is set; GET /api/admin/draft (picks + log). Every pick is tank.adopt() with opts.partner:
the signed 5x claim (positions >= 1) replaces the own-$20-buy rule for these calls only (the member's own tank button keeps it); the
coach needs an account here with a wallet linked and someone on this contract in their line (else a pick who starts here would walk
up to the company), not flagged, under the people-held cap; max 10 open picks; max 2 adoptions per person; the 24 h grace; rule 3
plus a fresh hub lock check at adopt (hub silent = refused); pool also drops spam/flagged (fraud + link-farm list), throwaway and
mistyped email domains, anyone adopted twice. Cards carry no contact data (hub ids or opaque i_ ids, door, joined, last seen,
wallet yes/no, surfing credits; games null, not tracked here). The adoption email is the only mail: no payTrack reminders, no
payments-topic post. Sponsor moves via setSponsor (sponsorfollow + hub sponsor-change, by 'adopt' / 'release').

Pick window: adoption row expires +3 days; tank.sweep skips picks (hooks.isDraftPick); draftpartner.sweep (hourly) closes them by the
pick rule: started (payouts on / purchase) = done, adopted twice or locked = kept with the coach, hub silent = wait, else back to the
tank with the original join time (no new grace). Coach release after 48 h. rid makes adopt/release idempotent. A pick closed some
other way reconciles as 'moved'. MySQL tables draft_picks + draft_log (JSON fallback locally); every call logged with a code/reason.

Tests: qa/draft-partner.test.mjs 66/66 (real tank.js, mocked clock, fake hub + a local copy's routes on 8825), in run.sh member and
run.sh draft; bash qa/run.sh member exit 0 (bugs 0); tank-cap 13/13, sponsorfollow 30/30.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-11-15 07:20:14 -06:00
parent 7f57aedcb6
commit e17d8c4fbb
5 changed files with 672 additions and 12 deletions
+313
View File
@@ -0,0 +1,313 @@
'use strict';
// 5xYourTeam "The Draft" partner side (Marty approved the rules 2026-11-15). The network holding tank lives HERE (tank.js);
// 5xYourTeam coaches draft from it through four signed calls, and every pick is a real tank adoption through tank.adopt():
//
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card], excluded: {why: n} }
// POST /api/partner/draft/adopt { rid, coach, person, kind, week?, slot?, note? } -> { ok, ref, person, adoptionId, at, expires, holdUntil }
// POST /api/partner/draft/release { rid, coach, ref | person, why: 'coach' | 'return' } -> { ok, outcome: 'returned' | 'kept' | 'done' | <closed status>, already? }
// POST /api/partner/draft/status { ids: [person id] } -> { ok, people: { id: milestones | null } }
// coach = { wallet, hubId?, username?, positions } (the 5xYourTeam claim: positions = 5x positions this wallet holds)
// card = { id, username, door, joinedAt, lastSeen, wallet (bool), ready, holdUntil, opensAt, adoptions (outside 5x), adoptionsTotal, games, surfWei, surfCredits }
//
// Signature: X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256(DRAFT_PARTNER_SECRET, 'draft.v1.' + ts + '\n' + raw body), 5-minute
// window. A dedicated secret (not NETWORK_SSO_SECRET): this one can move sponsors. adopt and release carry a request id (rid): a
// retried or replayed call answers what the first one did and changes nothing.
//
// The rules (project-5xyourteam-draft, 11-15):
// - only 5xYourTeam position holders draft and coach: the signed claim (positions >= 1) REPLACES InstantAdPay's own-$20-buy rule
// for these calls only (the member's own tank button keeps its $20 rule); a coach needs an account here with a wallet linked,
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
// - max 10 open picks a coach (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
// - 24-hour sign-up grace (tank.adopt refuses it; the card carries opensAt); coaches never see contact data: no email, phone or
// address leaves this module, person ids are hub ids (or an opaque i_ id the hub does not know)
// - the only mail: tank.adopt's normal "X is now your sponsor" adoption email. No switch-on-payouts reminders for picks, no
// payments-topic post (5xYourTeam posts its own Draft Day card)
//
// Auto-assign vs the 3-day window (the conflict the 5x build flagged), the rule implemented:
// - a drafted person is an open adoption with a sponsor, so they are out of the tank: no 24-hour activation hold, no auto-assign,
// no sign-up announcement, no dormant-lead rescue while the pick window runs
// - the pick's adoption row expires at +3 days (not IAP's 7), and tank.sweep leaves it alone (hooks.isDraftPick): this module
// closes it at 3 days with the pick's rule (started = payouts on or a purchase, a wallet alone is not started)
// - a returned pick goes back with their ORIGINAL join time (account `created` is never touched, so no new sign-up grace) and,
// with a wallet linked, a fresh 24-hour activation hold like anyone back in the tank (never the company)
// - sponsor moves go through tank.js setSponsor (sponsorfollow + the hub's /v1/sponsor-change with by 'adopt' / 'release')
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const db = require('./db');
const H = 3600000, D = 86400000;
const RULES = { returnMs: 3 * D, holdMs: 48 * H, maxOpen: 10, maxAdoptions: 2 };
const ADDR = /^0x[0-9a-f]{40}$/;
const lc = v => String(v || '').trim().toLowerCase();
// throwaway / disposable inboxes: the adoption email would go nowhere. Plus a mistyped big-provider domain (emailcheck.js).
const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org',
'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com',
'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']);
const DOORS = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', vbb: 'Viral Banner Blitz',
ctb: 'CryptoTeamBuild', fivex: '5xYourTeam', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', dh: 'DownlineHydra', btc4hits: 'BTC4Hits', stackpol: 'Stack POL' };
let R = null; // { dataDir, accounts, chain, tank, ads, hooks: { hubInfo, resolvePerson, excluded, spamEmails, networkOn, suggestDomain }, requireHub, clock }
const clock = () => (R && R.clock ? R.clock() : Date.now());
const SECRET = () => String((R && R.secret) || process.env.DRAFT_PARTNER_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
// ---- storage: MySQL (draft_picks, draft_log) when DATABASE_URL is set, else a JSON document (local QA) ----
const J = {
st: null, FILE: () => path.join(R.dataDir, 'draft-partner.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.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.log = this.st.log || []; return this.st; },
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
async put(p) { const s = this.load(); const i = s.picks.findIndex(x => x.id === p.id); if (i >= 0) s.picks[i] = Object.assign({}, p); this.save(); },
async byId(id) { const x = this.load().picks.find(r => r.id === Number(id)); return x ? Object.assign({}, x) : null; },
async byRid(rid) { const x = this.load().picks.find(r => r.rid === rid); return x ? Object.assign({}, x) : null; },
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
async ofPerson(pid) { return this.load().picks.filter(r => r.personId === pid).map(x => Object.assign({}, x)); },
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
async openOfCoach(w) { return this.load().picks.filter(r => r.status === 'open' && r.coachWallet === w).map(x => Object.assign({}, x)); },
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
async countsByAdoptee() { const m = new Map(); for (const r of this.load().picks) m.set(r.adoptee, (m.get(r.adoptee) || 0) + 1); return m; },
async log(row) { const s = this.load(); s.log.push(row); if (s.log.length > 2000) s.log = s.log.slice(-2000); this.save(); },
async logs(n) { return this.load().log.slice(-(n || 100)).reverse(); }
};
const COLS = ['rid', 'adoptionId', 'adoptee', 'personId', 'coachEmail', 'coachWallet', 'coachHubId', 'kind', 'week', 'slot', 'ts', 'expires', 'holdUntil', 'status', 'closed', 'outcomeWhy', 'walletAt', 'payoutsAt', 'purchaseAt'];
const SQLC = { rid: 'rid', adoptionId: 'adoption_id', adoptee: 'adoptee', personId: 'person_id', coachEmail: 'coach_email', coachWallet: 'coach_wallet', coachHubId: 'coach_hub_id', kind: 'kind', week: 'week', slot: 'slot', ts: 'ts', expires: 'expires', holdUntil: 'hold_until', status: 'status', closed: 'closed', outcomeWhy: 'outcome_why', walletAt: 'wallet_at', payoutsAt: 'payouts_at', purchaseAt: 'purchase_at' };
const NUM = new Set(['adoptionId', 'ts', 'expires', 'holdUntil', 'closed', 'walletAt', 'payoutsAt', 'purchaseAt']);
const rowP = r => { if (!r) return null; const o = { id: Number(r.id) }; for (const k of COLS) { const v = r[SQLC[k]]; o[k] = NUM.has(k) ? Number(v || 0) : (v == null ? null : String(v)); } return o; };
const Q = {
async add(p) { const r = await db.q('INSERT INTO draft_picks (' + COLS.map(k => SQLC[k]).join(',') + ') VALUES (' + COLS.map(() => '?').join(',') + ')', COLS.map(k => p[k] == null ? null : p[k])); return Object.assign({ id: r.insertId }, p); },
async put(p) { await db.q('UPDATE draft_picks SET ' + COLS.map(k => SQLC[k] + '=?').join(',') + ' WHERE id=?', COLS.map(k => p[k] == null ? null : p[k]).concat([p.id])); },
async byId(id) { return rowP((await db.q('SELECT * FROM draft_picks WHERE id=?', [Number(id)]))[0]); },
async byRid(rid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE rid=?', [rid]))[0]); },
async byAdoption(aid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE adoption_id=?', [Number(aid)]))[0]); },
async ofPerson(pid) { return (await db.q('SELECT * FROM draft_picks WHERE person_id=? ORDER BY id', [pid])).map(rowP); },
async open() { return (await db.q("SELECT * FROM draft_picks WHERE status='open' ORDER BY id")).map(rowP); },
async openOfCoach(w) { return (await db.q("SELECT * FROM draft_picks WHERE status='open' AND coach_wallet=?", [w])).map(rowP); },
async recent(n) { return (await db.q('SELECT * FROM draft_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
async countsByAdoptee() { return new Map((await db.q('SELECT adoptee, COUNT(*) n FROM draft_picks GROUP BY adoptee')).map(r => [r.adoptee, Number(r.n)])); },
async log(x) { await db.q('INSERT INTO draft_log (ts,op,ok,code,reason,coach,person,ref,rid) VALUES (?,?,?,?,?,?,?,?,?)', [x.ts, x.op, x.ok ? 1 : 0, x.code || null, String(x.reason || '').slice(0, 400), x.coach || null, x.person || null, x.ref || null, x.rid || null]); },
async logs(n) { return (await db.q('SELECT * FROM draft_log ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(r => ({ ts: Number(r.ts), op: r.op, ok: !!r.ok, code: r.code, reason: r.reason, coach: r.coach, person: r.person, ref: r.ref, rid: r.rid })); }
};
const S = () => (db.enabled() ? Q : J);
async function ensureTables() {
if (!db.enabled()) return;
await db.q(`CREATE TABLE IF NOT EXISTS draft_picks (
id INT AUTO_INCREMENT PRIMARY KEY, rid VARCHAR(80) NOT NULL, adoption_id INT NOT NULL, adoptee VARCHAR(190) NOT NULL, person_id VARCHAR(40) NOT NULL,
coach_email VARCHAR(190) NOT NULL, coach_wallet VARCHAR(42) NOT NULL, coach_hub_id VARCHAR(40) NULL, kind VARCHAR(16) NULL, week VARCHAR(16) NULL, slot VARCHAR(16) NULL,
ts BIGINT NOT NULL, expires BIGINT NOT NULL, hold_until BIGINT NOT NULL, status VARCHAR(16) NOT NULL, closed BIGINT NULL, outcome_why VARCHAR(200) NULL,
wallet_at BIGINT NULL, payouts_at BIGINT NULL, purchase_at BIGINT NULL,
UNIQUE KEY rid (rid), KEY adoption (adoption_id), KEY person (person_id), KEY coach (coach_wallet, status), KEY st (status)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // 5xYourTeam draft picks (each one a tank adoption)
await db.q(`CREATE TABLE IF NOT EXISTS draft_log (
id INT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, op VARCHAR(16) NOT NULL, ok TINYINT NOT NULL, code VARCHAR(40) NULL, reason VARCHAR(400) NULL,
coach VARCHAR(42) NULL, person VARCHAR(40) NULL, ref VARCHAR(40) NULL, rid VARCHAR(80) NULL, KEY t (ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
}
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
// ---- signature ----
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
function verify(headers, raw) {
if (!enabled()) return { status: 503, error: 'draft partner not configured' };
const ts = String(headers['x-draft-ts'] || ''), sig = String(headers['x-draft-sig'] || '');
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' };
const want = sign(ts, raw);
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; }
}
// ---- helpers ----
const idOf = email => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; return hi && /^h_[0-9a-f]{16}$/.test(hi.id) ? hi.id : 'i_' + crypto.createHmac('sha256', SECRET() || 'local').update('pid:' + lc(email)).digest('hex').slice(0, 16); };
const doorOf = (email, via) => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; const k = lc((hi && hi.door) || via); return DOORS[k] || (k === 'hub' ? 'Network' : 'InstantAdPay'); };
function throwaway(email) {
const d = lc(email).split('@')[1] || ''; if (!d) return true;
if (THROWAWAY.has(d)) return true;
const fix = R.hooks && R.hooks.suggestDomain ? R.hooks.suggestDomain(d) : null; return !!(fix && fix !== d); // a mistyped provider: the mail bounces
}
function spamSet() { try { return new Set((R.hooks && R.hooks.spamEmails ? R.hooks.spamEmails() : []).map(lc)); } catch (e) { return new Set(); } }
const hubOff = () => R.requireHub !== false && !(R.hooks && R.hooks.networkOn && R.hooks.networkOn());
async function logCall(op, x) { const row = Object.assign({ ts: clock(), op }, x); try { await S().log(row); } catch (e) { console.error('draft log', e.message); } if (!x.ok) console.log('draft', op, 'refused', x.code || '', String(x.reason || '').slice(0, 120)); return row; }
const fail = async (op, code, reason, x) => { await logCall(op, Object.assign({ ok: false, code, reason }, x || {})); return { error: reason, code }; };
function purchasers() { const s = new Set(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) s.add(Number(ev.buyerId)); return s; }
// a coach: the wallet that holds the 5x position, then a position wallet here, then the hub's person for the hub id
async function coachAccount(c) {
const w = lc(c && c.wallet); if (!ADDR.test(w)) return { code: 'bad_coach', reason: 'Which coach? (wallet missing)' };
let a = await R.accounts.byAddress(w).catch(() => null);
if (!a && R.accounts.positionOwner) { const po = await R.accounts.positionOwner(w).catch(() => null); if (po && po.email) a = await R.accounts.byEmail(po.email); }
if (!a && c.hubId && R.hooks && R.hooks.resolvePerson) { try { const p = await R.hooks.resolvePerson({ id: String(c.hubId) }); if (p && p.email && !p.blocked) a = await R.accounts.byEmail(lc(p.email)); } catch (e) {} }
if (!a) return { code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link a wallet.' };
return { account: a, wallet: w };
}
// ---- the pool ----
let poolCache = null;
async function poolRows(fresh) {
if (!fresh && poolCache && clock() - poolCache.at < 30000) return poolCache;
const list = await R.tank.waiting(); const spam = spamSet(); const ex = { spam: 0, throwaway: 0, adoptedTwice: 0 };
const local = await R.tank.summaryMap(); const mine = await S().countsByAdoptee(); const rows = [];
for (const w of list) {
if ((R.hooks.excluded && R.hooks.excluded(w.email)) || spam.has(lc(w.email))) { ex.spam++; continue; }
if (throwaway(w.email)) { ex.throwaway++; continue; }
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
if (n >= RULES.maxAdoptions) { ex.adoptedTwice++; continue; }
rows.push({ email: w.email, card: { id: idOf(w.email), username: w.username || null, door: doorOf(w.email, w.via), joinedAt: Number(w.joined) || 0, lastSeen: Number(w.lastSeen) || 0,
// adoptions = OUTSIDE 5xYourTeam (5xYourTeam adds its own picks; counting them here too would double them); adoptionsTotal = all
wallet: !!w.wallet, ready: !!w.ready, holdUntil: w.holdUntil || 0, opensAt: w.opensAt || 0, adoptions: Math.max(0, n - (mine.get(w.email) || 0)), adoptionsTotal: n,
games: null, surfWei: null, surfCredits: Number(w.earned) || 0 } }); // games: InstantAdPay keeps no per-member game record (never invented)
}
poolCache = { at: clock(), rows, excluded: ex }; return poolCache;
}
async function pool() {
if (hubOff()) { await logCall('pool', { ok: false, code: 'hub_off', reason: 'the network hub is off, so locked people cannot be ruled out' }); return { ok: true, rules: rulesView(), pool: [], excluded: {}, hubOff: true }; }
const p = await poolRows(false);
return { ok: true, rules: rulesView(), pool: p.rows.map(r => r.card), excluded: p.excluded };
}
const rulesView = () => ({ returnHours: RULES.returnMs / H, holdHours: RULES.holdMs / H, maxOpen: RULES.maxOpen, maxAdoptions: RULES.maxAdoptions, graceHours: (RULES.graceMs || D) / H });
// ---- adopt ----
async function adopt(b) {
const rid = String(b.rid || '').slice(0, 80); const c = b.coach || {}; const pid = String(b.person || '').slice(0, 40); const kind = /^(draft|instant)$/.test(b.kind) ? b.kind : 'draft';
const x = { coach: lc(c.wallet) || null, person: pid || null, rid };
if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return fail('adopt', 'bad_rid', 'A request id (rid) is required.', x);
const prev = await S().byRid(rid);
if (prev) return { ok: true, repeat: true, ref: 'iap:' + prev.id, person: prev.personId, adoptionId: prev.adoptionId, at: prev.ts, expires: prev.expires, holdUntil: prev.holdUntil };
if (!(Number(c.positions) >= 1)) return fail('adopt', 'not_vested', 'Only 5xYourTeam position holders can draft and coach.', x);
if (hubOff()) return fail('adopt', 'hub_off', 'The network hub is off, so nobody can be drafted right now.', x);
const co = await coachAccount(c); if (!co.account) return fail('adopt', co.code, co.reason, x);
if ((await S().openOfCoach(co.wallet)).length >= RULES.maxOpen) return fail('adopt', 'full', 'Your team is full (' + RULES.maxOpen + ' open picks). Help one get started first.', x);
const hit = (await poolRows(true)).rows.find(r => r.card.id === pid);
if (!hit) return fail('adopt', 'gone', 'That player is no longer in the holding tank.', x);
const r = await R.tank.adopt(co.account.email, hit.email, String(b.note || ''), { partner: { positions: Number(c.positions), ttlMs: RULES.returnMs, maxOpen: RULES.maxOpen }, recordNote: '5xYourTeam draft pick (' + kind + (b.week ? ', week ' + String(b.week).slice(0, 10) : '') + (b.slot ? ', slot ' + String(b.slot).slice(0, 10) : '') + ')' });
if (!r || !r.ok) return fail('adopt', (r && r.code) || 'refused', (r && r.error) || 'The tank refused.', x);
poolCache = null;
const now = clock(); const acct = await R.accounts.byEmail(hit.email);
const pick = await S().add({ rid, adoptionId: Number(r.adoption.id), adoptee: hit.email, personId: pid, coachEmail: co.account.email, coachWallet: co.wallet, coachHubId: c.hubId ? String(c.hubId).slice(0, 40) : null,
kind, week: b.week ? String(b.week).slice(0, 16) : null, slot: b.slot ? String(b.slot).slice(0, 16) : null, ts: now, expires: now + RULES.returnMs, holdUntil: now + RULES.holdMs, status: 'open', closed: 0, outcomeWhy: null,
walletAt: acct && acct.address ? now : 0, payoutsAt: 0, purchaseAt: 0 });
await logCall('adopt', Object.assign(x, { ok: true, ref: 'iap:' + pick.id, reason: kind + ' pick by ' + (c.username ? '@' + String(c.username).slice(0, 40) : x.coach) }));
return { ok: true, ref: 'iap:' + pick.id, person: pid, adoptionId: pick.adoptionId, at: pick.ts, expires: pick.expires, holdUntil: pick.holdUntil };
}
// is the pick's adoption still the open one? (released on InstantAdPay itself, moved by a LinkSpin follow, ...) -> closed here too
async function reconcile(p) {
if (p.status !== 'open') return p;
const open = await R.tank.openOf(p.adoptee);
if (open.some(ad => Number(ad.id) === p.adoptionId)) return p;
p.status = 'moved'; p.closed = clock(); p.outcomeWhy = 'the adoption was closed on InstantAdPay (released, moved or followed from LinkSpin)'; await S().put(p);
await logCall('reconcile', { ok: true, code: 'moved', reason: p.outcomeWhy, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
return p;
}
// milestones seen so far (first-seen times; the chain events carry no timestamps here)
async function observe(p, a, buyers) {
if (!a) return p; const now = clock(); let ch = false;
if (a.address && !p.walletAt) { p.walletAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.payoutsAt) { p.payoutsAt = now; ch = true; }
if (Number(a.memberId) > 0 && !p.purchaseAt && buyers && buyers.has(Number(a.memberId))) { p.purchaseAt = now; ch = true; }
if (ch) await S().put(p); return p;
}
const started = (p, a) => !!(a && Number(a.memberId) > 0) || !!(p.payoutsAt || p.purchaseAt);
// close one open pick: 'coach' (released after the 48 h hold) or 'return' (3 days, not started). Shared by release() and sweep().
async function closePick(p, why, now) {
const a = await R.accounts.byEmail(p.adoptee);
await observe(p, a, purchasers());
if (started(p, a)) { p.status = 'done'; p.closed = now; p.outcomeWhy = 'started (payouts on or a purchase)'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'done'); return { outcome: 'done', why: p.outcomeWhy }; }
if (why === 'coach' && now < p.holdUntil) return { code: 'hold', reason: 'You picked them less than ' + (RULES.holdMs / H) + ' hours ago. Give them a little time first (' + Math.ceil((p.holdUntil - now) / H) + ' h left).' };
if (why === 'return' && now < p.expires) return { code: 'too_early', reason: 'The pick window runs until ' + new Date(p.expires).toISOString() + '.' };
const count = await R.tank.countAll(p.adoptee);
if (count >= RULES.maxAdoptions) { // their second adoption: they stay with this coach (the tank sweep rule, never back to nobody)
p.status = 'kept'; p.closed = now; p.outcomeWhy = 'adopted twice: stays with this coach'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired');
return { outcome: 'kept', why: p.outcomeWhy };
}
const lk = await R.tank.lockedWhy(p.adoptee);
if (lk === 'unknown') return { code: 'hub_unknown', reason: 'The network record cannot be checked right now. Try again later.' };
if (lk === 'locked') { p.status = 'kept'; p.closed = now; p.outcomeWhy = 'locked on a network contract: never moved'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired'); return { outcome: 'kept', why: p.outcomeWhy }; }
const note = why === 'return' ? '5xYourTeam pick returned: not started in ' + (RULES.returnMs / D) + ' days' : '5xYourTeam pick released by the coach';
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'release', note);
if (r && r.error) return { code: 'refused', reason: r.error };
await R.tank.closeAdoption(p.adoptionId, why === 'return' ? 'expired' : 'dropped'); // both still count toward their two adoptions
p.status = 'returned'; p.closed = now; p.outcomeWhy = note; await S().put(p); poolCache = null;
return { outcome: 'returned', why: note };
}
async function findPick(b) {
const ref = String(b.ref || ''); const m = /^iap:(\d+)$/.exec(ref);
if (m) return S().byId(Number(m[1]));
const pid = String(b.person || ''); const w = lc(b.coach && b.coach.wallet);
const rows = (await S().ofPerson(pid)).filter(p => p.coachWallet === w); return rows.find(p => p.status === 'open') || rows[rows.length - 1] || null;
}
async function release(b) {
const why = b.why === 'return' ? 'return' : 'coach'; const w = lc(b.coach && b.coach.wallet); const rid = String(b.rid || '').slice(0, 80);
const x = { coach: w || null, person: b.person ? String(b.person).slice(0, 40) : null, rid, ref: b.ref ? String(b.ref).slice(0, 40) : null };
let p = await findPick(b);
if (!p) return fail('release', 'no_pick', 'No such pick.', x);
if (p.coachWallet !== w) return fail('release', 'not_yours', 'Not your pick.', x);
x.person = p.personId; x.ref = 'iap:' + p.id;
p = await reconcile(p);
if (p.status !== 'open') { await logCall('release', Object.assign(x, { ok: true, code: 'already', reason: why + ': already ' + p.status })); return { ok: true, already: true, outcome: p.status }; }
const r = await closePick(p, why, clock());
if (!r.outcome) return fail('release', r.code, r.reason, x);
await logCall('release', Object.assign(x, { ok: true, code: r.outcome, reason: why + ': ' + r.why }));
return { ok: true, outcome: r.outcome };
}
// ---- status: milestones for the people 5xYourTeam holds picks for (anyone else answers null) ----
async function status(b) {
const ids = [...new Set((Array.isArray(b.ids) ? b.ids : []).map(v => String(v || '').slice(0, 40)).filter(Boolean))].slice(0, 500);
const buyers = purchasers(); const out = {};
const emails = []; const picksBy = {};
for (const id of ids) { const rows = await S().ofPerson(id); if (!rows.length) { out[id] = null; continue; } picksBy[id] = rows; emails.push(rows[0].adoptee); }
const tot = R.ads && R.ads.earnedTotals ? await R.ads.earnedTotals(emails).catch(() => ({})) : {};
for (const id of Object.keys(picksBy)) {
const rows = picksBy[id]; let last = rows[rows.length - 1]; const email = last.adoptee;
const a = await R.accounts.byEmail(email); if (!a) { out[id] = null; continue; }
last = await reconcile(last); last = await observe(last, a, buyers);
const count = await R.tank.countAll(email);
out[id] = { username: a.username || null, door: doorOf(email, a.joinedVia), lastSeen: Number(a.lastSeen) || 0,
wallet: a.address ? (rows.map(r => r.walletAt).filter(Boolean).sort((x, y) => x - y)[0] || clock()) : 0,
payouts: Number(a.memberId) > 0 ? (last.payoutsAt || clock()) : 0, purchase: Number(a.memberId) > 0 && buyers.has(Number(a.memberId)) ? (last.purchaseAt || clock()) : 0,
adoptions: Math.max(0, count - rows.length), // adoptions outside 5xYourTeam (5x counts its own picks itself)
games: null, surfWei: null, surfCredits: (tot[email] || {}).earned || 0,
pick: { ref: 'iap:' + last.id, status: last.status, coachWallet: last.coachWallet, expires: last.expires, holdUntil: last.holdUntil } };
}
return { ok: true, people: out };
}
// ---- the hourly sweep (server.js, beside tank.sweep): started picks close as done, unstarted ones past 3 days go back ----
let sweeping = null;
function sweep() { if (!sweeping) sweeping = sweepRun().finally(() => { sweeping = null; }); return sweeping; }
async function sweepRun() {
const now = clock(); const out = { done: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const buyers = purchasers();
for (let p of await S().open()) {
p = await reconcile(p); if (p.status !== 'open') { out.moved++; continue; }
const a = await R.accounts.byEmail(p.adoptee); await observe(p, a, buyers);
if (!started(p, a) && now < p.expires) continue;
const r = await closePick(p, 'return', now);
if (!r.outcome) { out.waiting++; continue; }
out[r.outcome] = (out[r.outcome] || 0) + 1;
await logCall('sweep', { ok: true, code: r.outcome, reason: r.why, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
}
return out;
}
// tank.sweep asks this before closing an expired adoption (the pick's own rule decides)
async function isDraftPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
async function adminView() { return { enabled: enabled(), rules: rulesView(), hubOff: hubOff(), picks: (await S().recent(200)).map(p => Object.assign({}, p, { adoptee: undefined, coachEmail: undefined })), log: await S().logs(200) }; }
// one entry for the HTTP routes (server.js) and the cross-repo test: op = pool | adopt | release | status
async function handle(op, body) {
if (op === 'pool') return pool();
if (op === 'adopt') return adopt(body);
if (op === 'release') return release(body);
if (op === 'status') return status(body);
return { error: 'unknown op', code: 'unknown_op' };
}
module.exports = { init, enabled, verify, sign, handle, pool, adopt, release, status, sweep, isDraftPick, adminView, RULES, _poolReset: () => { poolCache = null; } };
+287
View File
@@ -0,0 +1,287 @@
// 5xYourTeam "The Draft" partner routes (draftpartner.js + the tank.adopt partner path, 2026-11-15).
// node qa/draft-partner.test.mjs (also part of `bash qa/run.sh member`; `bash qa/run.sh draft` alone)
// Part A, no server: the REAL tank.js + draftpartner.js with in-memory accounts, a fake chain, a fake hub and a MOCKED CLOCK.
// signature, the pool rules (locked / sponsored / spam / throwaway / adopted twice / grace shown with opensAt / no contact data),
// adopt (the 5x claim replaces the $20 rule only here, wallet + contract line, 10 open, fresh lock check, hub off, rid repeat,
// the normal adoption email is the only mail), the auto-assign conflict rule (a drafted person is out of the tank; tank.sweep
// leaves a pick's adoption alone), release (48 h hold, back with the original join time, two adoptions = kept, started = done,
// locked = kept, hub silent = wait), the hourly sweep (wallet alone is not started), reconcile, status, the log.
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, DRAFT_ALLOW_NO_HUB=1): the HTTP routes answer signed calls only.
// 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';
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
const SECRET = 'draft-test-secret-' + 'x'.repeat(40);
let fails = 0, passes = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (cond || extra === undefined ? '' : ' ' + (typeof extra === 'string' ? extra : JSON.stringify(extra)))); if (!cond) fails++; else passes++; };
const H = 3600000, D = 86400000;
const addr = () => '0x' + crypto.randomBytes(20).toString('hex');
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 * D, 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 byAddress(w) { const x = String(w || '').toLowerCase(); return find(a => a.address && a.address.toLowerCase() === x); },
async positionOwner() { return null; },
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()].map(pub); },
isUnclaimedShell: () => false,
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(o) {
o = o || {};
for (const m of ['tank.js', 'draftpartner.js']) delete require.cache[require.resolve(path.join(SITE, m))];
const tank = require(path.join(SITE, 'tank.js'));
const dp = require(path.join(SITE, 'draftpartner.js'));
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-'));
const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const notices = []; const assigned = []; const deliberate = [];
const hub = { locked: new Set(), sponsored: new Set(), down: false, on: true, ids: new Map() };
const flagged = new Set(); const spamList = [];
const env = { now: Date.now() };
const follow = { setDeliberate: async (email, token, by, note) => { deliberate.push({ email, token, by, note }); return accounts.setSponsorRef(email, token); } };
const why = e => hub.down ? 'unknown' : hub.locked.has(e) ? 'locked' : hub.sponsored.has(e) ? 'sponsored' : null;
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) }, follow,
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
hooks: { network: () => null, isSuspended: () => false, excluded: e => flagged.has(e), payoutBlocked: async () => false, companyId: () => 1,
networkHeld: async accts => new Map(accts.map(a => [a.email, why(a.email)]).filter(x => x[1])),
networkLocked: async e => { const w = why(e); return w === 'locked' || w === 'unknown' ? w : null; },
isDraftPick: id => dp.isDraftPick(id),
assigned: r => { assigned.push(r); }, adminAlert: () => {}, claim: () => true, activated: () => false, notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
tank.setClock(() => env.now);
process.env.DRAFT_PARTNER_SECRET = SECRET;
const ready = dp.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse() }, tank, ads: { earnedTotals: async em => Object.fromEntries(em.map(e => [e, { earned: e.startsWith('surf') ? 420 : 0, balance: 0 }])) },
requireHub: true, clock: () => env.now,
hooks: { hubInfo: e => hub.ids.has(e) ? { id: hub.ids.get(e), door: 'linkspin' } : null, networkOn: () => hub.on, excluded: e => flagged.has(e), spamEmails: () => spamList,
suggestDomain: d => require(path.join(SITE, 'emailcheck.js')).suggestDomain(d) } });
let block = 1000;
// a coach: a wallet linked here and payouts on (member id), but NO $20 purchase (their vesting is the 5x position)
const coach = (email, memberId, extra) => accounts.add(email, Object.assign({ memberId, address: addr() }, extra || {}));
const buy = (memberId, cents) => events.push({ type: 'Purchase', buyerId: memberId, priceCents: cents || 2000, block: block++ });
return { tank, dp, ready, accounts, events, chats, mails, notices, assigned, deliberate, hub, flagged, spamList, env, coach, buy, dir };
}
const claimOf = (a, positions) => ({ wallet: a.address, username: a.username, positions: positions === undefined ? 1 : positions });
let ridN = 0; const rid = () => 'rid-test-' + (++ridN) + '-' + crypto.randomBytes(3).toString('hex');
async function partA() {
console.log('-- Part A: draftpartner.js + tank.js, mocked clock, fake hub');
// ---- signature ----
{
const B = bench(); await B.ready;
const raw = JSON.stringify({}); const ts = String(Date.now());
const good = B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw);
ok(good.body && typeof good.body === 'object', 'signature: a good signature passes');
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw, 'other-secret-' + 'y'.repeat(30)) }, raw).status === 401, 'signature: another secret is refused');
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw + ' ').status === 401, 'signature: a changed body is refused');
const old = String(Date.now() - 6 * 60000);
ok(B.dp.verify({ 'x-draft-ts': old, 'x-draft-sig': B.dp.sign(old, raw) }, raw).status === 401, 'signature: older than 5 minutes is refused');
const keep = process.env.DRAFT_PARTNER_SECRET; process.env.DRAFT_PARTNER_SECRET = 'short';
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': 'x' }, raw).status === 503, 'signature: no (or a short) secret = 503, nothing answers');
process.env.DRAFT_PARTNER_SECRET = keep;
}
// ---- the pool ----
const B = bench(); await B.ready; const { tank, dp, accounts, env, hub } = B;
accounts.add('live@x.co', { address: addr(), lastSeen: env.now - 2 * H });
accounts.add('plain@x.co');
accounts.add('surfer@x.co');
accounts.add('locked@x.co'); hub.locked.add('locked@x.co');
accounts.add('sponsoredhub@x.co'); hub.sponsored.add('sponsoredhub@x.co');
accounts.add('flagged@x.co'); B.flagged.add('flagged@x.co');
accounts.add('farm@x.co'); B.spamList.push('farm@x.co');
accounts.add('temp@mailinator.com');
accounts.add('typo@gmial.com');
accounts.add('fresh@x.co', { created: env.now - 2 * H });
accounts.add('kid@x.co', { sponsorRef: 'someone' });
accounts.add('twice@x.co');
hub.ids.set('live@x.co', 'h_0123456789abcdef');
const C1 = B.coach('coach1@x.co', 41); const C2 = B.coach('coach2@x.co', 42);
// twice@ has had two adoptions already (an old IAP one and a dropped one)
B.buy(43); B.coach('iapadopter@x.co', 43);
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // back in the tank by hand: 1 counted
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // 2 counted
for (const ad of await tank.openOf('twice@x.co')) await tank.closeAdoption(ad.id, 'dropped');
B.mails.length = 0; B.chats.length = 0;
const P = await dp.pool();
const names = P.pool.map(c => c.username).sort();
ok(P.ok && names.join(',') === ['fresh', 'live', 'plain', 'surfer'].join(','), 'pool: only people who pass every rule', names.join(','));
ok(P.excluded.spam === 2 && P.excluded.throwaway === 2 && P.excluded.adoptedTwice === 1, 'pool: spam/flagged, throwaway + mistyped domains and adopted-twice counted out', P.excluded);
ok(!names.includes('locked') && !names.includes('sponsoredhub') && !names.includes('kid'), 'pool: nobody locked on a contract, sponsored on the hub or sponsored here');
const live = P.pool.find(c => c.username === 'live'); const fresh = P.pool.find(c => c.username === 'fresh'); const plain = P.pool.find(c => c.username === 'plain');
ok(live.id === 'h_0123456789abcdef' && live.door === 'LinkSpin' && live.wallet === true && live.joinedAt > 0, 'card: hub id + door from the hub cache, wallet linked yes/no, joined', live);
ok(/^i_[0-9a-f]{16}$/.test(plain.id) && plain.door === 'InstantAdPay', 'card: someone the hub does not know gets an opaque i_ id');
ok(fresh.opensAt > env.now, 'card: a sign-up inside the 24-hour grace is shown with opensAt');
ok(live.games === null && live.surfWei === null && typeof live.surfCredits === 'number', 'card: games null (not tracked here), surfing as credits, never invented');
const keys = new Set(P.pool.flatMap(c => Object.keys(c)));
ok(!JSON.stringify(P).includes('@') && !keys.has('email') && !keys.has('address'), 'pool: no contact data (no email, no wallet address) in the answer');
ok(P.rules.returnHours === 72 && P.rules.holdHours === 48 && P.rules.maxOpen === 10 && P.rules.maxAdoptions === 2 && P.rules.graceHours === 24, 'pool: the rules travel with it', P.rules);
// ---- adopt ----
const a0 = await dp.adopt({ rid: rid(), coach: claimOf(C1, 0), person: plain.id, kind: 'draft' });
ok(a0.code === 'not_vested', 'adopt: no 5x position = refused (free members cannot adopt)', a0);
const a1 = await dp.adopt({ rid: rid(), coach: { wallet: addr(), positions: 1 }, person: plain.id });
ok(a1.code === 'coach_unknown', 'adopt: a wallet with no account here is refused', a1);
const nw = accounts.add('nowallet@x.co', { memberId: 0 });
accounts._by.get('nowallet@x.co').address = null;
const nwc = B.coach('freecoach@x.co', 0);
const a2 = await dp.adopt({ rid: rid(), coach: claimOf(nwc), person: plain.id });
ok(a2.code === 'no_contract_line', 'adopt: a coach with nobody on this contract in their line is refused (a pick would land under the company)', a2);
void nw;
hub.on = false;
const a3 = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: plain.id });
ok(a3.code === 'hub_off', 'adopt: hub off = nobody can be drafted', a3);
ok((await dp.pool()).pool.length === 0, 'pool: hub off = empty pool');
hub.on = true;
ok(!(await tank.eligibility('coach1@x.co')).ok, "the coach is NOT eligible for InstantAdPay's own tank button (keeps its $20 rule)");
const r1 = rid();
const g = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: fresh.id });
ok(g.code === 'grace', 'adopt: a sign-up inside the 24-hour grace is refused', g);
const ok1 = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id, kind: 'draft', week: '2026-11-16', slot: '1.1' });
ok(ok1.ok && /^iap:\d+$/.test(ok1.ref) && ok1.person === live.id && ok1.expires === env.now + 3 * D && ok1.holdUntil === env.now + 48 * H, 'adopt: a 5x coach with payouts on and no $20 buy adopts; 3-day window, 48 h hold', ok1);
const la = await accounts.byEmail('live@x.co');
ok(la.sponsorRef === 'coach1', 'adopt: the sponsor is now the coach (InstantAdPay record)', la.sponsorRef);
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'adopt'), "adopt: the move went through the deliberate path (sponsorfollow + the hub's sponsor-change, by 'adopt')");
const open = await tank.openOf('live@x.co');
ok(open.length === 1 && open[0].expires - open[0].ts === 3 * D && /5xYourTeam draft pick/.test(open[0].note), "adopt: the tank adoption's own window is 3 days, noted as a draft pick", open[0]);
ok(B.mails.length === 1 && B.mails[0].to === 'live@x.co' && /is now your sponsor on InstantAdPay/.test(B.mails[0].subject), 'mail: exactly one, the normal "X is now your sponsor" adoption email', B.mails.map(m => m.subject));
ok(B.chats.some(c => c.to === 'live@x.co' && /your coach from 5xYourTeam/.test(c.text)), 'adopt: a site chat from the coach (site messages only)');
ok(!tank.payView().some(x => x.email === 'live@x.co'), 'adopt: no switch-on-payouts reminder mails are queued for a pick');
ok(B.assigned.length === 0, 'adopt: no payments-topic pickup post');
const rep = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id });
ok(rep.ok && rep.repeat && rep.ref === ok1.ref && B.mails.length === 1, 'adopt: the same rid again answers the first result and sends nothing');
const tw = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: live.id });
ok(tw.code === 'gone', 'adopt: someone already picked is no longer in the pool', tw);
// fresh lock check at adopt (the pool cache is 30 s old at most; the adopt asks the hub again)
accounts.add('late@x.co'); const lp = (await dp.pool()).pool; dp._poolReset();
const late = (await dp.pool()).pool.find(c => c.username === 'late');
hub.locked.add('late@x.co'); const al = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
ok(al.code === 'gone' || al.code === 'locked', 'adopt: locked a moment ago = refused', al); hub.locked.delete('late@x.co'); void lp;
hub.down = true; dp._poolReset();
const ad = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
ok(ad.error && (ad.code === 'gone' || ad.code === 'hub_unknown'), 'adopt: a hub that does not answer refuses (the conservative side)', ad);
hub.down = false; dp._poolReset();
// 10 open picks at most
for (let i = 0; i < 10; i++) accounts.add('fill' + i + '@x.co');
const pl = (await dp.pool()).pool; let made = 0;
for (const c of pl.filter(c => /^fill/.test(c.username))) { const r = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: c.id }); if (r.ok) made++; }
const over = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: plain.id });
ok(made === 10 && over.code === 'full', 'adopt: 10 open picks a coach, the 11th is refused', { made, over });
// ---- auto-assign vs the pick window ----
env.now += 30 * H; // past any 24-hour activation hold
const tick = await tank.readyTick();
ok(!tick.assigned.some(x => x.adoptee === 'live@x.co') && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach1', 'conflict rule: a drafted person (wallet linked) is out of the tank, never auto-assigned while the pick runs');
ok(!(await tank.waiting()).some(w => w.email === 'live@x.co'), 'conflict rule: not on the waiting list while picked');
// ---- release ----
const early = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
ok(early.code === 'hold', 'release: not inside the 48-hour hold', early);
const notMine = await dp.release({ rid: rid(), coach: claimOf(C2), ref: ok1.ref, why: 'coach' });
ok(notMine.code === 'not_yours', 'release: another coach cannot release it', notMine);
const tooEarly = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'return' });
ok(tooEarly.code === 'too_early', 'return: not before the 3 days', tooEarly);
env.now += 20 * H; // 50 h after the pick
const rel = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
const back = await accounts.byEmail('live@x.co');
ok(rel.ok && rel.outcome === 'returned' && back.sponsorRef === '', 'release: after 48 h the pick goes back to the tank', rel);
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'release' && /released by the coach/.test(d.note)), "release: the move went through the deliberate path (by 'release')");
dp._poolReset();
const again = (await dp.pool()).pool.find(c => c.id === live.id);
ok(again && again.joinedAt === live.joinedAt && !again.opensAt, 'release: back in the pool with the ORIGINAL join time, no new sign-up grace', again);
ok(again.adoptionsTotal === 1 && again.adoptions === 0, 'release: the dropped pick still counts toward their two (total 1; 0 outside 5xYourTeam, which counts its own picks)', again);
const relAgain = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
ok(relAgain.ok && relAgain.already && relAgain.outcome === 'returned', 'release: a repeat answers "already" and changes nothing');
ok(B.mails.length === 11, 'mail: still only the adoption emails (1 + 10), nothing on release', B.mails.length);
// second adoption: C3 picks them again; at 3 days unstarted they stay with C3 (adopted twice)
const C3 = B.coach('coach3@x.co', 44);
const p2 = await dp.adopt({ rid: rid(), coach: claimOf(C3), person: live.id, kind: 'instant' });
ok(p2.ok, 'second pick of the same person (their 2nd adoption)', p2);
env.now += 3 * D + H;
const sw = await dp.sweep();
ok(sw.kept === 1 && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach3', 'sweep: at 3 days, a person on their 2nd adoption stays with the coach (kept)', sw);
dp._poolReset();
ok(!(await dp.pool()).pool.some(c => c.id === live.id), 'pool: someone adopted twice is never offered again');
// ---- the hourly sweep: wallet alone is not started; started = done; locked = kept; hub silent = wait ----
const C4 = B.coach('coach4@x.co', 45);
accounts.add('w1@x.co'); accounts.add('s1@x.co'); accounts.add('k1@x.co'); accounts.add('u1@x.co'); dp._poolReset();
const pool4 = (await dp.pool()).pool; const idOf = u => pool4.find(c => c.username === u).id;
const pw = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('w1') }); const ps = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('s1') });
const pk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('k1') }); const pu = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('u1') });
ok(pw.ok && ps.ok && pk.ok && pu.ok, 'four more picks for the sweep checks');
accounts._by.get('w1@x.co').address = addr(); // linked a wallet only
accounts._by.get('s1@x.co').address = addr(); accounts._by.get('s1@x.co').memberId = 77; B.buy(77, 1000); // switched on payouts + bought
// tank.sweep (the IAP 7-day sweep) leaves a pick's expired adoption alone
env.now += 3 * D + H;
hub.locked.add('k1@x.co');
const st0 = await dp.status({ ids: [idOf('s1'), idOf('w1'), 'h_ffffffffffffffff'] });
ok(st0.people['h_ffffffffffffffff'] === null, 'status: someone 5xYourTeam holds no pick for answers null');
ok(st0.people[idOf('s1')].payouts > 0 && st0.people[idOf('s1')].purchase > 0 && st0.people[idOf('w1')].wallet > 0 && !st0.people[idOf('w1')].payouts, 'status: milestones (wallet / payouts / purchase as first-seen times)', st0.people[idOf('w1')]);
ok(!JSON.stringify(st0).includes('@'), 'status: no contact data');
hub.down = true;
const swU = await dp.sweep();
ok(swU.waiting >= 1 && swU.done === 1 && (await accounts.byEmail('u1@x.co')).sponsorRef === 'coach4', 'sweep: hub not answering = the return waits, nobody moved', swU);
hub.down = false;
const sw2 = await dp.sweep();
ok(sw2.returned === 2 && sw2.kept === 1, 'sweep: started = done (even with the hub silent), wallet-only + plain = returned, locked = kept', sw2);
ok((await accounts.byEmail('w1@x.co')).sponsorRef === '' && (await accounts.byEmail('s1@x.co')).sponsorRef === 'coach4' && (await accounts.byEmail('k1@x.co')).sponsorRef === 'coach4', 'sweep: sponsors after the 3 days (wallet-only back to the tank; started and locked stay)');
const tsw = await tank.sweep();
ok(tsw.back === 0, 'tank.sweep: never touches a pick (the pick rule decides, not the 7-day wallet rule)', tsw);
// a pick whose tank adoption was closed some other way (released on InstantAdPay itself, a LinkSpin follow) reconciles
accounts.add('m1@x.co'); dp._poolReset(); const pm = (await dp.pool()).pool.find(c => c.username === 'm1');
const pmk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: pm.id });
for (const a of await tank.openOf('m1@x.co')) await tank.closeAdoption(a.id, 'moved');
const stm = await dp.status({ ids: [pm.id] });
ok(pmk.ok && stm.people[pm.id].pick.status === 'moved', 'reconcile: a pick closed on InstantAdPay shows as moved', stm.people[pm.id].pick);
// the log: every call with a reason
const av = await dp.adminView();
ok(av.log.length > 20 && av.log.every(l => l.op && l.ts && (l.ok || l.code)) && av.log.some(l => l.op === 'adopt' && !l.ok && l.code === 'not_vested') && av.log.some(l => l.op === 'sweep' && l.code === 'kept'), 'log: every call is logged with an outcome code / reason', av.log.slice(0, 3));
ok(!JSON.stringify(av.picks).includes('@'), 'admin view: picks carry no emails');
}
// ---------------- Part B: the routes on a local copy ----------------
async function partB() {
console.log('-- Part B: HTTP routes on a local copy');
const port = Number(process.env.DRAFT_E2E_PORT || 8825);
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-b-'));
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@iap.test', ADMIN_PASSWORD: 'localtest', DRAFT_PARTNER_SECRET: SECRET, DRAFT_ALLOW_NO_HUB: '1', LS_URL: 'http://127.0.0.1:9', HUB_ENABLED: '' });
delete env.DATABASE_URL; delete env.NODE_ENV;
const child = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] });
let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
const base = 'http://127.0.0.1:' + port;
try {
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(base + '/api/config')).ok; } catch (e) {} if (!up) await new Promise(r => setTimeout(r, 500)); }
ok(up, 'local copy up on :' + port, up ? undefined : log.slice(-600));
if (!up) return;
const call = async (op, body, opts) => { const raw = JSON.stringify(body || {}); const ts = String(Date.now()); const sig = (opts && opts.sig) || crypto.createHmac('sha256', SECRET).update('draft.v1.' + ts + '\n' + raw).digest('hex');
const r = await fetch(base + '/api/partner/draft/' + op, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig }, body: raw }); return { status: r.status, body: await r.json().catch(() => null) }; };
const p = await call('pool', {});
ok(p.status === 200 && p.body.ok && Array.isArray(p.body.pool) && p.body.rules.maxOpen === 10, 'POST /api/partner/draft/pool signed: 200 with rules + pool', p);
ok((await call('pool', {}, { sig: 'f'.repeat(64) })).status === 401, 'unsigned / wrong signature: 401');
ok((await call('nope', {})).status === 404, 'unknown op: 404');
const a = await call('adopt', { rid: 'rid-route-0001', coach: { wallet: addr(), positions: 1 }, person: 'h_0000000000000000' });
ok(a.status === 400 && a.body.code === 'coach_unknown', 'adopt for an unknown coach: 400 with a code', a.body);
const s = await call('status', { ids: ['h_0000000000000000'] });
ok(s.status === 200 && s.body.people['h_0000000000000000'] === null, 'status: 200, unknown person null');
ok((await fetch(base + '/api/admin/draft')).status === 401, 'GET /api/admin/draft needs the admin');
} finally { child.kill(); }
}
await partA();
if (!process.env.DRAFT_SKIP_B) await partB();
console.log(fails ? 'FAILED ' + fails + ' (passed ' + passes + ')' : 'ALL PASSED (' + passes + ')');
process.exit(fails ? 1 : 0);
+4
View File
@@ -7,6 +7,7 @@
# 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 walletnudge # game wallet push (any linked wallet, activated or not) + no-wallet nudge copy against a mock game (also runs in member)
# bash qa/run.sh draft # 5xYourTeam The Draft partner routes: pool / adopt / release / status rules on the real tank.js (mocked clock, fake hub) + the signed HTTP routes on a local copy (also runs in member)
# 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)
@@ -70,10 +71,13 @@ elif [ "$MODE" = "member" ]; then
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
node qa/tank-hold.mjs || status=1
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
node qa/walletnudge.test.cjs || status=1
node qa/bixpay.test.cjs || status=1
node qa/profile-policy.test.cjs || status=1
node qa/sov-heroes-store.cjs || status=1
elif [ "$MODE" = "draft" ]; then
node qa/draft-partner.test.mjs || status=1
elif [ "$MODE" = "theme" ]; then
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
elif [ "$MODE" = "policy" ]; then
+21
View File
@@ -55,6 +55,7 @@ const lssync = require('./lssync');
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
const hubsync = require('./hubsync'); // network hub: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED)
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
@@ -735,6 +736,7 @@ async function boot() {
hooks: { network: async (email, address) => (hubsync.enabled() ? await hubsync.hubSponsor(email).catch(() => null) : null) || lsinbound.networkSponsor(email, address),
networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null,
isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
isDraftPick: id => draftpartner.isDraftPick(id), // a 5xYourTeam pick's adoption: draftpartner.js owns its 3-day window
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
@@ -746,6 +748,11 @@ async function boot() {
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
hooks: { hubInfo: email => (hubsync.enabled() ? hubsync.hubInfo(email) : null), resolvePerson: q => (hubsync.enabled() ? hubsync.resolvePerson(q) : null), networkOn: () => hubsync.enabled(),
excluded: em => fraud.excluded(em), spamEmails: () => (((spamscan.view() || {}).last || {}).candidates || []).map(c => c.email), suggestDomain: d => require('./emailcheck').suggestDomain(d) } }).catch(e => console.error('draftpartner init', e.message));
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
@@ -827,6 +834,7 @@ async function boot() {
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
setInterval(() => draftpartner.sweep().then(r => { if (r.done || r.returned || r.kept || r.moved) console.log('draft sweep', JSON.stringify(r)); }).catch(e => console.error('draft sweep', e.message)), 60 * 60 * 1000); // 5xYourTeam picks: 3-day window
burner.init({ chain, ads, accounts });
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000);
@@ -3825,6 +3833,19 @@ const server = http.createServer(async (req, res) => {
}
if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); }
if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); }
// -- 5xYourTeam The Draft (draftpartner.js, 2026-11-15): signed partner calls, DRAFT_PARTNER_SECRET as X-Draft-Ts + X-Draft-Sig
if (p.startsWith('/api/partner/draft/') && req.method === 'POST') {
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 64000) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
const sg = draftpartner.verify(req.headers, raw); if (!sg.body) return json(res, sg.status, { error: sg.error });
const op = p.slice('/api/partner/draft/'.length);
if (!['pool', 'adopt', 'release', 'status'].includes(op)) return json(res, 404, { error: 'unknown op' });
const r = await draftpartner.handle(op, sg.body);
return json(res, r.error ? 400 : 200, r);
}
if (p === '/api/admin/draft' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await draftpartner.adminView());
}
if (p === '/api/admin/tank' && req.method === 'GET') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
return json(res, 200, await tank.adminView());
+47 -12
View File
@@ -114,6 +114,7 @@ async function waiting() {
// what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers
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,
via: a.joinedVia || null, // the door they came in by (the 5xYourTeam draft card shows it)
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,
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
@@ -139,6 +140,25 @@ async function eligibility(email) {
return { ok: true, account: a, open };
}
// 5xYourTeam coaches (Marty 2026-11-15: "not a fan of people adopting if they have nothing vested"; a $10 5x position qualifies,
// no IAP $20 package needed). draftpartner.js has already checked the signed claim from 5xYourTeam (p.positions); this is the
// InstantAdPay side of the same gate: a real account here with a wallet linked, not suspended or flagged, someone on THIS
// contract in their line (them or an upline with payouts on, else a pick who starts here would be walked up to the company, the
// one thing the tank exists to stop; the nameSponsor rule), and room under the same people-held-at-once cap as every adopter.
async function partnerEligibility(email, p) {
const a = await accounts.byEmail(email);
if (!a) return { ok: false, code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link the same wallet.' };
if (!(Number(p && p.positions) >= 1)) return { ok: false, code: 'not_vested', reason: 'Only 5xYourTeam position holders can draft and coach.' };
if (!a.address) return { ok: false, code: 'no_wallet', reason: 'Link a wallet on InstantAdPay first. A coach needs a linked wallet.' };
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) return { ok: false, code: 'excluded', reason: 'Adoptions are not available on this account.' };
const payee = await firstOnContract(a);
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Neither you nor anyone above you has switched on payouts on InstantAdPay, so a pick who starts there would land under the company. Switch on payouts on InstantAdPay first (one free transaction).' };
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'Your line cannot take new members right now.' };
const open = await impl().open(a.email); const held = await holding(open); const cap = Math.min(capOpen(), Number(p.maxOpen) > 0 ? Number(p.maxOpen) : capOpen());
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold.', full: true, cap, held: held.length };
return { ok: true, account: a, open };
}
async function view(email) {
const e = String(email || '').toLowerCase();
const el = await eligibility(e);
@@ -152,27 +172,36 @@ async function view(email) {
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
// partner = a 5xYourTeam draft pick (draftpartner.js, 2026-11-15): the coach qualifies by a 5x position instead of the $20 buy,
// the window is the pick's (3 days, partner.ttlMs), the hub is asked fresh that nobody locked is taken, no reminder mails
const partner = (opts && opts.partner) || null;
const e = String(adopterEmail || '').toLowerCase();
const el = await eligibility(e);
if (!el.ok) return { error: el.reason };
const el = partner ? await partnerEligibility(e, partner) : await eligibility(e);
if (!el.ok) return { error: el.reason, code: el.code || 'not_eligible' };
const me = el.account;
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
const list = await waiting();
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
if (!target) return { error: 'That member is no longer in the tank.' };
if (target.email === e) return { error: 'That is you.' };
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
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
if (!target) return { error: 'That member is no longer in the tank.', code: 'gone' };
if (target.email === e) return { error: 'That is you.', code: 'self' };
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.', code: 'grace' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.', code: 'linkspin' };
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.', code: 'adopted_twice' }; // the safety net never leaves anyone to the company
if (partner) { // never anyone locked on a network contract: asked fresh, a hub that does not answer refuses (the conservative side)
const lk = await lockedWhy(target.email);
if (lk) return { error: lk === 'locked' ? 'That member is locked to a sponsor on a network contract.' : 'The network record cannot be checked right now. Try again in a few minutes.', code: lk === 'locked' ? 'locked' : 'hub_unknown' };
if (await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
}
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 tgt0 = await accounts.byEmail(target.email); const b4h = !!(tgt0 && (tgt0.joinedVia === 'btc4hits' || tgt0.joinedRef === 'btc4hits')); // a BTC4Hits import (2026-11-11)
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. ' + (b4h ? 'Your BTC4Hits account moved to InstantAdPay' : '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: (opts && opts.recordNote) || text });
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + (partner ? ', your coach from 5xYourTeam' : '') + '. ' + (b4h ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so I picked you up from the holding tank' + (partner ? ' in The Draft' : '') + '. I will walk you through the first three steps whenever you are ready. Reply here.');
const ttl = partner && Number(partner.ttlMs) > 0 ? Number(partner.ttlMs) : TTL_MS;
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + ttl, 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
payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick)
if (!partner) payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick); a draft pick gets the adoption email only (Marty 2026-11-15)
const link = activateLink();
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
if (mailer && mailer.hasKey()) {
@@ -187,7 +216,7 @@ async function adopt(adopterEmail, who, note, opts) {
} catch (err) {}
}
}
return { ok: true, auto, 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, adoptee: target.email };
}
// pay it forward: give one of your own free referrals to the tank
@@ -226,6 +255,7 @@ async function sweep() {
let done = 0, back = 0, kept = 0;
for (const ad of await impl().open(null)) {
if (ad.expires > now) continue;
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue; // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
const a = await accounts.byEmail(ad.adoptee);
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
@@ -677,6 +707,10 @@ async function nameSponsor(email, who, opts) {
return { ok: true, name: nameOf(sp), sponsorEmail: sp.email, member: name };
}
// the open adoptions of one person (draftpartner.js checks a pick's adoption is still the open one), and closing one
async function openOf(email) { const e = String(email || '').toLowerCase(); return (await impl().open(null)).filter(ad => ad.adoptee === e); }
async function closeAdoption(id, status) { await impl().setStatus(id, status); }
async function adminView() {
const recent = await impl().recent(200);
const names = {};
@@ -684,4 +718,5 @@ async function adminView() {
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
}
module.exports = { init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
module.exports = { partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };