Compare commits
354 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c06c58daf | |||
| e1bee03b95 | |||
| e17d8c4fbb | |||
| 7f57aedcb6 | |||
| 968e60835f | |||
| 911dd623c0 | |||
| 4ccdb914c7 | |||
| 82eab8016b | |||
| 4787390e8b | |||
| d033cc7122 | |||
| efb054d916 | |||
| 32f001aade | |||
| edc484db27 | |||
| 836c7b17c2 | |||
| a01d6f2e8c | |||
| ff568d973c | |||
| 5398faadee | |||
| a7c36a908a | |||
| 92288a30f5 | |||
| d626469980 | |||
| e98a6ebcd8 | |||
| f29f6d1407 | |||
| 9efdfc8ee9 | |||
| 4e2178d779 | |||
| f20062133f | |||
| 24b4ae9134 | |||
| 2d4fc7a9f3 | |||
| 00cfd09c8f | |||
| 4cf3512106 | |||
| 1f584f894f | |||
| ff2f668583 | |||
| fab7732620 | |||
| 5c896cb782 | |||
| 74354346a3 | |||
| dbdeb5a7e6 | |||
| 85d43f7483 | |||
| cedb291aaa | |||
| 574a0cafb1 | |||
| 55d3597f12 | |||
| fe70c857be | |||
| 5585abb663 | |||
| db1ab8359c | |||
| 3eae242dc3 | |||
| 5e8dee7517 | |||
| ffcc0c6339 | |||
| 0013416af7 | |||
| 52eaa20171 | |||
| e00c820d2f | |||
| ef28c16502 | |||
| 3991a5eb79 | |||
| d06394a3d3 | |||
| 2e4d18d77d | |||
| f20e845cf1 | |||
| 5f38c1486d | |||
| 87ea24b8f0 | |||
| 1da37f05ab | |||
| 054ce10985 | |||
| bafeff9bf4 | |||
| 627341e8ad | |||
| 2aa98bdbd2 | |||
| 03284aa281 | |||
| bfbea142b6 | |||
| 973fc80570 | |||
| a845155c88 | |||
| abfb3e3199 | |||
| e61475f89b | |||
| 2e935b3081 | |||
| 769c04e639 | |||
| fb2383ffae | |||
| 0865a4967b | |||
| 7d28ec7b5f | |||
| c0a435343a | |||
| c6b4a84abc | |||
| 7f3f057db0 | |||
| ae3a08b991 | |||
| 4bcc867679 | |||
| 27d7215f0f | |||
| 0aaffc308e | |||
| 4ae7a318da | |||
| 1aec9caf6c | |||
| fdc95b5ed6 | |||
| ce33d71427 | |||
| b4989ab59f | |||
| 47ce40b858 | |||
| f0811ecf70 | |||
| 53978476bb | |||
| 2f2cf24946 | |||
| fda27ad43f | |||
| 012250360e | |||
| 337d4f9e8f | |||
| ec4ada08d7 | |||
| a058fd515d | |||
| c621fecb54 | |||
| 13e0644355 | |||
| ed6febe0b8 | |||
| 6e1ab102f1 | |||
| 01154c0856 | |||
| 7d134e55a2 | |||
| 8b28d028a6 | |||
| f1482deb12 | |||
| 6096bf38c6 | |||
| 1089942bca | |||
| fa5acf0745 | |||
| 8b03dd2311 | |||
| 59607d0c94 | |||
| e5c55c2d8b | |||
| 4645d5605a | |||
| fc81c6a4db | |||
| 06f0a87452 | |||
| 27d663ca29 | |||
| b239417cc5 | |||
| 47638ac1fe | |||
| 7f80d82486 | |||
| cecba6b313 | |||
| a4642341aa | |||
| 962cdf08b5 | |||
| 13f3ff56f8 | |||
| bf5cf62caf | |||
| 8ca5ed99e8 | |||
| f322786071 | |||
| 5802fd9835 | |||
| 1b77825256 | |||
| 974d888314 | |||
| 8ecef442a1 | |||
| 6b3cdaaa70 | |||
| 15f5374fac | |||
| 50337bfbbc | |||
| 6cc868d10a | |||
| 61c0c52c3b | |||
| 7cadeaa2d9 | |||
| 42a1cce2f1 | |||
| ce977698b9 | |||
| 46bb7dd9dd | |||
| ebdab6c545 | |||
| 43e841721a | |||
| 87a45169d0 | |||
| 38369d6858 | |||
| 91f2e2ec74 | |||
| 4587b5cc58 | |||
| eac83c3eee | |||
| e2eb1578aa | |||
| 89b5969b25 | |||
| c45f1769e7 | |||
| 610f47c625 | |||
| a405c2cdd1 | |||
| 31b167e046 | |||
| 6a3313a861 | |||
| 839c867595 | |||
| 32eefae473 | |||
| 7e902b9b26 | |||
| 4e51470cf5 | |||
| 06b0924651 | |||
| 16ec626d2c | |||
| 1c2928553a | |||
| 3ee605a8bf | |||
| 8b1395a90c | |||
| 9992dd061d | |||
| 2e0a4af28f | |||
| 6f194596fe | |||
| 1e040f21ff | |||
| 4df932723e | |||
| 0e528ae854 | |||
| 7af47ae921 | |||
| 0aa22e9984 | |||
| 0688bdeb72 | |||
| 5e8f2c0b6b | |||
| 34a1de0b15 | |||
| 017017ad63 | |||
| d520eb67af | |||
| 716dd8066f | |||
| 34d2284051 | |||
| af66f7f865 | |||
| e490e15abf | |||
| ad17017250 | |||
| 524ce843dc | |||
| 80885705d2 | |||
| e2d15aa751 | |||
| 8fe527ab67 | |||
| 6f6412d908 | |||
| 9be58bd5ef | |||
| f0c868ef23 | |||
| 79e48b3cad | |||
| 9b7b166097 | |||
| 4c470d8e3c | |||
| 084d1ea3d6 | |||
| 4d6a0f2f83 | |||
| d0cc45eadb | |||
| 0db7c94728 | |||
| be268beb66 | |||
| bb11f8183d | |||
| 7aec7d5169 | |||
| d86f2fbcf8 | |||
| ae72a06a85 | |||
| 4759cabf09 | |||
| 2df64f6247 | |||
| ba811e48f8 | |||
| 375ddf75bd | |||
| 7a79b4a930 | |||
| c40b7ccb5c | |||
| c43f166418 | |||
| ab83e37d23 | |||
| 06f2665809 | |||
| 8d3fc12862 | |||
| f417d416da | |||
| a63f6206a3 | |||
| 10617df866 | |||
| 0f56d3c7bb | |||
| a5acf0c848 | |||
| 1287f94669 | |||
| b796a7a64e | |||
| 041a3d41ae | |||
| 9cf039270e | |||
| a6c523c6aa | |||
| 23da5b61ba | |||
| 7b4c2ef9e5 | |||
| 1ffca3030c | |||
| ef6c6b584e | |||
| 84d54eda16 | |||
| fcb9edd2eb | |||
| f8e55413ee | |||
| 310992e40f | |||
| 4b7b1c5d95 | |||
| 69b7395387 | |||
| d8a31ddd40 | |||
| f7c4d34a35 | |||
| 1c9db665b3 | |||
| 7d20cd2c35 | |||
| efb6020e40 | |||
| f53bd67d30 | |||
| 75339757e5 | |||
| d4b0e74829 | |||
| af5a53b833 | |||
| d07a32a837 | |||
| 67cb82eef3 | |||
| 7131adfc42 | |||
| 5f6ab1b35c | |||
| a61a4f8745 | |||
| d93d26f2e3 | |||
| 7e949c86ec | |||
| 468def461c | |||
| 8285e31fbd | |||
| b82f63f803 | |||
| dfd0b9dbed | |||
| 04fad66dab | |||
| 616bd37142 | |||
| ca065e456e | |||
| 2a96d5c672 | |||
| 5c31f4540c | |||
| 28b90dcae4 | |||
| 98c24c2e6b | |||
| 6191c07fa5 | |||
| ef8b256172 | |||
| 5a39b2599f | |||
| 9142efef01 | |||
| 8251c0e693 | |||
| ba5cdfdf4b | |||
| a32c1ab3c9 | |||
| e3b2c7b579 | |||
| ec57a926fc | |||
| 503a252fc8 | |||
| 18813a4127 | |||
| d1a638b66b | |||
| f9299e5ef3 | |||
| c99896c131 | |||
| f09ff71c56 | |||
| e09babc1ff | |||
| 376a4b04f2 | |||
| 1ac5e1d206 | |||
| 5a4b27f50e | |||
| a453366964 | |||
| 9b904b1a64 | |||
| 4e35a83fdd | |||
| eb3cfebf1f | |||
| ca7a579990 | |||
| 3f758cdd38 | |||
| 563ece9896 | |||
| b53de647b9 | |||
| 1932b625ac | |||
| a3905a0b5a | |||
| 7775ed87ef | |||
| 067460c0e6 | |||
| 56eb1f2d4f | |||
| 22407fe9ae | |||
| 0fd67b407a | |||
| 0112422c72 | |||
| 30c95026f9 | |||
| e484025d6d | |||
| 737ed28e1d | |||
| 8f61d11d43 | |||
| 217802d577 | |||
| 2c2d93b2dc | |||
| a5a991d024 | |||
| 9809953ae0 | |||
| dbbce34202 | |||
| 3b57bbc9cf | |||
| 27c9d51fde | |||
| b6850d4342 | |||
| 6804a26c5d | |||
| bc713f57b0 | |||
| 5c54bd3905 | |||
| 4a38d9ce79 | |||
| 0414560ecb | |||
| 9212128b0d | |||
| da7e421daf | |||
| be102a4b16 | |||
| 0e32a57424 | |||
| be313e6202 | |||
| 513c713292 | |||
| f56f363090 | |||
| 5a522f0ede | |||
| dd53d132d6 | |||
| 5fe6058e76 | |||
| 5d0e89be6f | |||
| 2b2e131c3e | |||
| f1b37e0c4a | |||
| 587272673b | |||
| 3ae9ab55e9 | |||
| 972421fbbe | |||
| a2d7bede82 | |||
| f7d9fd65cb | |||
| 75d084c4b7 | |||
| a7a15615ec | |||
| b5baaf27e8 | |||
| b197d74234 | |||
| a60905a9fb | |||
| 58dc3864cd | |||
| 37a78de339 | |||
| 43463366ec | |||
| d43836a892 | |||
| 9c90a95f4c | |||
| a765b97421 | |||
| 8a6029cd90 | |||
| 5b54debf72 | |||
| 79023e5f46 | |||
| 04fd4db9ca | |||
| 7ce7aeffa4 | |||
| 61be49c303 | |||
| e6b5a9fb22 | |||
| b55388c83b | |||
| 39951cfac5 | |||
| 257b06d6d2 | |||
| 34e9d32a8a | |||
| fd7b5d7ed7 | |||
| 06a83a0b97 | |||
| c20a5ed56b | |||
| ab2431be11 | |||
| a9cffb87d4 | |||
| 927b13a7cf | |||
| 53f0970209 | |||
| d562d61cbc | |||
| 30f84c6aa2 | |||
| 273715dc17 | |||
| e1309d43b7 | |||
| 6e3f631cc6 |
@@ -36,8 +36,12 @@ const pub = a => a ? { email: a.email, sponsorRef: a.sponsorRef || '', code: a.c
|
||||
username: a.username || null, memberId: a.memberId || 0, joinedVia: a.joinedVia || null, joinedRef: a.joinedRef || null,
|
||||
lineBannerUrl: a.lineBannerUrl || null, lineTargetUrl: a.lineTargetUrl || null, wallOffers: a.wallOffers || null,
|
||||
avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null,
|
||||
bixPartnerLink: a.bixPartnerLink || null, // BixPay partner link (bixpay.js, 2026-10-29): one identity, follows the member to LinkSpin/CTB
|
||||
profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js)
|
||||
chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0,
|
||||
theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (common.js IAP.themeSync)
|
||||
address: a.address || null, created: a.created } : null;
|
||||
const THEMES = new Set(['auto', 'light', 'dark']);
|
||||
const USER_RE = /^[a-zA-Z0-9_]{3,20}$/;
|
||||
const normUser = u => String(u || '').trim().toLowerCase();
|
||||
|
||||
@@ -116,16 +120,19 @@ const J = {
|
||||
acct.wallOffers = json || null; this.save();
|
||||
return { ok: true, account: pub(acct) };
|
||||
},
|
||||
async setProfile(e, avatarUrl, bio, socials) {
|
||||
async setProfile(e, avatarUrl, bio, socials, quarantined) {
|
||||
const acct = this.db.byEmail[e];
|
||||
if (!acct) return { error: 'No such account.' };
|
||||
if (avatarUrl !== undefined) acct.avatarUrl = avatarUrl || null;
|
||||
if (bio !== undefined) acct.bio = bio || null;
|
||||
if (socials !== undefined) acct.socials = socials || null;
|
||||
if (quarantined !== undefined) acct.profileQuarantined = !!quarantined;
|
||||
this.save();
|
||||
return { ok: true, account: pub(acct) };
|
||||
},
|
||||
async setBixLink(e, link) { const acct = this.db.byEmail[e]; if (!acct) return { error: 'No such account.' }; acct.bixPartnerLink = link || null; this.save(); return { ok: true, account: pub(acct) }; },
|
||||
async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { a.lastSeen = Date.now(); this.save(); } },
|
||||
async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; },
|
||||
async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; },
|
||||
async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; },
|
||||
async setMute(owner, target, muted) {
|
||||
@@ -228,8 +235,8 @@ const J = {
|
||||
const rowPub = r => r ? pub({ email: r.email, sponsorRef: r.sponsor_ref, code: r.code,
|
||||
username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null,
|
||||
lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null,
|
||||
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials,
|
||||
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0),
|
||||
avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, bixPartnerLink: r.bix_partner_link || null, profileQuarantined: !!r.profile_quarantined,
|
||||
chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null,
|
||||
address: r.address, created: Number(r.created) }) : null;
|
||||
const D = {
|
||||
async signup(e, password, ref) {
|
||||
@@ -283,13 +290,16 @@ const D = {
|
||||
await db.q('UPDATE accounts SET wall_offers=? WHERE email=?', [json || null, e]);
|
||||
return { ok: true, account: await this.byEmail(e) };
|
||||
},
|
||||
async setProfile(e, avatarUrl, bio, socials) {
|
||||
async setProfile(e, avatarUrl, bio, socials, quarantined) {
|
||||
if (avatarUrl !== undefined) await db.q('UPDATE accounts SET avatar_url=? WHERE email=?', [avatarUrl || null, e]);
|
||||
if (bio !== undefined) await db.q('UPDATE accounts SET bio=? WHERE email=?', [bio || null, e]);
|
||||
if (socials !== undefined) await db.q('UPDATE accounts SET socials=? WHERE email=?', [socials || null, e]);
|
||||
if (quarantined !== undefined) await db.q('UPDATE accounts SET profile_quarantined=? WHERE email=?', [quarantined ? 1 : 0, e]);
|
||||
return { ok: true, account: await this.byEmail(e) };
|
||||
},
|
||||
async setBixLink(e, link) { const r = await db.q('UPDATE accounts SET bix_partner_link=? WHERE email=?', [link || null, e]); if (!r || !r.affectedRows) return { error: 'No such account.' }; return { ok: true, account: await this.byEmail(e) }; },
|
||||
async touchSeen(e) { await db.q('UPDATE accounts SET last_seen=? WHERE email=?', [Date.now(), e]); },
|
||||
async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; },
|
||||
async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; },
|
||||
async getMutes(e) {
|
||||
const r = await db.q('SELECT chat_mutes FROM accounts WHERE email=?', [e]);
|
||||
@@ -399,10 +409,15 @@ async function signup(email, password, sponsorRef) {
|
||||
return impl().signup(e, String(password), String(sponsorRef || ''));
|
||||
}
|
||||
async function login(email, password) { return impl().login(normEmail(email), String(password || '')); }
|
||||
// change listener (2026-10-08): LinkSpin's registry sync hears about created / named / wallet-linked / re-sponsored accounts
|
||||
let changeFn = null; function onChange(fn) { changeFn = fn; } const changed = e => { try { if (changeFn) changeFn(e); } catch (err) {} };
|
||||
let walletFn = null; function onWalletLinked(fn) { walletFn = fn; } // reporting only (lsreport.js, 2026-11-07): told after a main wallet is linked, never in the way of it
|
||||
async function ensure(email, sponsorRef, via, joinedRef) {
|
||||
const e = normEmail(email);
|
||||
if (!EMAIL_RE.test(e)) return { error: 'That email address does not look right.' };
|
||||
return impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null, String(joinedRef || '').toLowerCase().slice(0, 80) || null);
|
||||
const r = await impl().ensure(e, String(sponsorRef || ''), String(via || '').toLowerCase().slice(0, 20) || null, String(joinedRef || '').toLowerCase().slice(0, 80) || null);
|
||||
if (r && !r.error) changed(e);
|
||||
return r;
|
||||
}
|
||||
async function byEmail(email) { return impl().byEmail(normEmail(email)); }
|
||||
async function byAddress(address) { return impl().byAddress(normAddr(address)); }
|
||||
@@ -428,7 +443,7 @@ async function setUsername(email, username) {
|
||||
if (!USER_RE.test(n)) return { error: 'Usernames are 3 to 20 letters, numbers, or underscores.' };
|
||||
if (/^\d+$/.test(n)) return { error: 'Usernames need at least one letter.' }; // keep /join/<number> unambiguous
|
||||
if (reservedUsername(n)) return { error: 'That username is reserved. Names that suggest you are InstantAdPay, our staff or one of our sites are not allowed. Please pick another.' };
|
||||
return impl().setUsername(normEmail(email), n);
|
||||
const r = await impl().setUsername(normEmail(email), n); if (r && !r.error) changed(normEmail(email)); return r;
|
||||
}
|
||||
async function setMemberId(email, id) { return impl().setMemberId(normEmail(email), Number(id) || 0); }
|
||||
async function namesForMembers(ids) { return impl().namesForMembers([...new Set(ids)].filter(n => n > 0)); }
|
||||
@@ -460,14 +475,23 @@ async function downline(email, depth = 3) {
|
||||
async function linkWallet(email, address) {
|
||||
const a = normAddr(address);
|
||||
if (!/^0x[0-9a-f]{40}$/.test(a)) return { error: 'Bad wallet address.' };
|
||||
return impl().linkWallet(normEmail(email), a);
|
||||
const r = await impl().linkWallet(normEmail(email), a); if (r && !r.error) { changed(normEmail(email)); try { if (walletFn) walletFn(normEmail(email)); } catch (err) {} } return r;
|
||||
}
|
||||
async function count() { return impl().count(); }
|
||||
// admin: newest-first account list, and re-pointing a member's sponsor (a
|
||||
// username, share code, or numeric member id: the same tokens join links use)
|
||||
async function listAll(limit = 500) { return impl().listAll(limit); }
|
||||
// A waiting account made from a LinkSpin registry row (lsinbound.js, 2026-10-15) that its owner has not signed in to yet.
|
||||
// It exists so the LinkSpin line is already in place; it is not a member yet, so the sweeps that mail, count or adopt
|
||||
// members (listAll by default) leave it out. It becomes an ordinary account the first time its owner signs in (lastSeen).
|
||||
// BTC4Hits members imported 2026-11-11 (btc4hits-migration, joinedVia 'btc4hits') are the same kind of waiting account.
|
||||
// Network hub members who joined at another door (hubsync.js, 2026-11-12, only while HUB_ENABLED) arrive as joinedVia 'hub'.
|
||||
const SHELL_VIAS = new Set(['linkspin', 'btc4hits', 'hub']);
|
||||
const isUnclaimedShell = a => !!a && SHELL_VIAS.has(a.joinedVia) && !a.lastSeen && !a.memberId;
|
||||
// the limit counts members, not waiting accounts: newest-first LIMIT before the filter let thousands of waiting accounts push
|
||||
// older real members out of the sweeps that read listAll(5000) (tank, coach, leaderboard, Friday, Wednesday)
|
||||
async function listAll(limit = 500, opts) { if (opts && opts.shells) return impl().listAll(limit); const all = await impl().listAll(1e7); return all.filter(a => !isUnclaimedShell(a)).slice(0, limit); }
|
||||
async function identities() { return impl().identities(); }
|
||||
async function setSponsorRef(email, ref) { return impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); }
|
||||
async function setSponsorRef(email, ref) { const r = await impl().setSponsorRef(normEmail(email), String(ref || '').trim().toLowerCase().slice(0, 40)); if (r && !r.error) changed(normEmail(email)); return r; }
|
||||
|
||||
// resolve a member's DIRECT sponsor account (the token they joined under)
|
||||
async function sponsorOf(email) {
|
||||
@@ -491,12 +515,14 @@ async function getChatSettings(email) {
|
||||
return { available: a ? a.chatAvailable !== false : true, mutes: await impl().getMutes(String(email || '').toLowerCase()) };
|
||||
}
|
||||
|
||||
module.exports = { init, signup, login, ensure, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, identities, setSponsorRef,
|
||||
module.exports = { init, signup, login, ensure, onChange, onWalletLinked, isUnclaimedShell, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, identities, setSponsorRef,
|
||||
setUsername, reservedUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, count,
|
||||
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
|
||||
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
|
||||
setProfile: (e, a, bio, socials) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials),
|
||||
setProfile: async (e, a, bio, socials, quarantined) => { const r = await impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined); if (!(r && r.error)) changed(String(e || '').toLowerCase()); return r; }, // profile edits reach LinkSpin too
|
||||
setBixLink: async (e, link) => { const r = await impl().setBixLink(normEmail(e), link ? String(link).slice(0, 300) : null); if (!(r && r.error)) changed(normEmail(e)); return r; }, // the BixPay partner link rides to LinkSpin in the profile row (lssync.js)
|
||||
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
|
||||
setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no changed() tap, LinkSpin does not mirror it either (its accounts.js says the same)
|
||||
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null),
|
||||
positionByAddress: a => impl().positionByAddress(normAddr(a)),
|
||||
removeAccount: e => impl().removeAccount(String(e || '').toLowerCase()),
|
||||
|
||||
@@ -71,7 +71,7 @@ async function view(email) {
|
||||
try { out.credits = await ads.balances([...ids], acct.email); } catch (e) { out.credits = null; }
|
||||
try { out.earnedSplit = await ads.earnedSplit(acct.email); } catch (e) {}
|
||||
// campaigns
|
||||
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: c.views, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
|
||||
try { out.campaigns = (await ads.listCampaigns(acct.email)).map(c => ({ id: c.id, type: c.type, status: c.status, name: c.name || c.title || '', budget: c.budget, spent: c.spent, created: c.created, views: (Number(c.imps) || 0) + (Number(c.impsNas) || 0), pack: c.type === 'visits' ? (Number(c.body) || 0) : 0, clicks: c.clicks })); } catch (e) { out.campaigns = []; }
|
||||
// line (3 levels) with wallet / bought / qualified per person
|
||||
const levels = await accounts.downline(acct.email, 3).catch(() => []);
|
||||
const boughtIds = new Set(chain.recentEvents(1e9).filter(ev => ev.type === 'Purchase').map(ev => ev.buyerId));
|
||||
|
||||
@@ -12,7 +12,7 @@ function refunded() { const out = {}; try { for (const f of fs.readdirSync(R.dat
|
||||
async function run() {
|
||||
const out = { checkedAt: Date.now(), checks: [] };
|
||||
if (!db.enabled()) { out.checks.push({ name: 'Counters', ok: true, detail: 'JSON mode: not checked', issues: [] }); return out; }
|
||||
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house FROM campaigns WHERE house=0 OR house IS NULL");
|
||||
const camps = await db.q("SELECT id, name, type, status, imps, clicks, spent, accrued, budget, created, starts, house, expires FROM campaigns WHERE house=0 OR house IS NULL");
|
||||
const back = refunded(); for (const c of camps) if (back[c.id]) c.spent = Math.max(0, Number(c.spent) - back[c.id]); // already made right
|
||||
const logStart = (await db.q('SELECT MIN(day) d FROM camp_hours'))[0].d; const logStartMs = logStart ? Date.parse(logStart + 'T00:00:00Z') : 0;
|
||||
const byType = t => camps.filter(c => c.type === t);
|
||||
@@ -20,9 +20,21 @@ async function run() {
|
||||
// 1. per-view formats: campaign.imps must equal the rows in the log that paid for them
|
||||
for (const [type, table, label] of [['video', 'video_seen', 'completed watches'], ['visits', 'visit_seen', 'verified visits'], ['solo', 'solo_inbox', 'inbox deliveries']]) {
|
||||
const rows = await db.q('SELECT campaign_id, COUNT(*) n FROM ' + table + ' GROUP BY campaign_id'); const logN = {}; for (const r of rows) logN[r.campaign_id] = Number(r.n);
|
||||
const issues = []; let tot = 0, logTot = 0;
|
||||
for (const c of byType(type)) { const l = logN[c.id] || 0; tot += Number(c.imps); logTot += l; if (Number(c.imps) !== l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' ' + label); }
|
||||
add(type + ' views vs ' + label, issues, tot + ' views recorded, ' + logTot + ' ' + label);
|
||||
// visits are proven by three logs (2026-10-04: 37 false alarms): our viewer (visit_seen), repeat door knocks on Spooky Doors
|
||||
// (visit_repeat), and visits delivered on PassiveDrip's PTC page (pdsync.json, read from PassiveDrip, never derived).
|
||||
// A counter BELOW its proof is the advertiser getting a visit free; only a counter ABOVE its proof can overcharge them.
|
||||
let extra = {};
|
||||
if (type === 'visits') {
|
||||
for (const r of await db.q('SELECT campaign_id, COUNT(*) n FROM visit_repeat GROUP BY campaign_id')) extra[r.campaign_id] = (extra[r.campaign_id] || 0) + Number(r.n);
|
||||
try { const pd = JSON.parse(fs.readFileSync(path.join(R.dataDir, 'pdsync.json'), 'utf8')).served || {}; for (const [id, n] of Object.entries(pd)) extra[id] = (extra[id] || 0) + Number(n || 0); } catch (e) {}
|
||||
}
|
||||
const issues = []; let tot = 0, logTot = 0, under = 0;
|
||||
for (const c of byType(type)) {
|
||||
const l = (logN[c.id] || 0) + (extra[c.id] || 0); tot += Number(c.imps); logTot += l;
|
||||
if (type === 'visits') { if (Number(c.imps) > l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' counted vs ' + l + ' proven (' + (Number(c.imps) - l) + ' not proven)'); else if (Number(c.imps) < l) under++; }
|
||||
else if (Number(c.imps) !== l) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': ' + c.imps + ' views vs ' + l + ' ' + label);
|
||||
}
|
||||
add(type + ' views vs ' + label, issues, tot + ' views recorded, ' + logTot + ' ' + label + (type === 'visits' ? ' (our viewer + repeat door visits + PassiveDrip)' + (under ? '; ' + under + ' campaign(s) got a visit or two free' : '') : ''));
|
||||
}
|
||||
// 2. banner/text: imps must equal the hourly log (both bumped on serve)
|
||||
{
|
||||
@@ -36,8 +48,8 @@ async function run() {
|
||||
{
|
||||
const rows = await db.q('SELECT campaign_id, COUNT(DISTINCT day) d FROM camp_hours WHERE n>0 GROUP BY campaign_id'); const shown = {}; for (const r of rows) shown[r.campaign_id] = Number(r.d);
|
||||
const issues = [];
|
||||
for (const c of byType('login')) { const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
|
||||
add('login ads: days charged vs days shown', issues, byType('login').length + ' campaigns compared');
|
||||
for (const c of byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status))) { /* a reservation in the login-ad line is paid up front and has no end date yet (2026-10-23) */ const charged = Math.round((Number(c.spent) + Number(c.accrued || 0)) / 100), s = shown[c.id] || 0; if (charged > s) issues.push('#' + c.id + ' ' + c.name.slice(0, 30) + ': charged ' + charged + ' day(s), shown on ' + s); }
|
||||
add('login ads: days charged vs days shown', issues, byType('login').filter(c => !c.expires && !['queued', 'cancelled'].includes(c.status)).length + ' per-day campaigns compared (30-day slots are paid up front)');
|
||||
}
|
||||
// 4. featured: a live booking older than two hours must have views
|
||||
{
|
||||
|
||||
@@ -146,10 +146,15 @@ function sessionCookie(token) {
|
||||
return `iap.sid=${encodeURIComponent(token)}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL / 1000}${IS_PROD ? '; Secure' : ''}`;
|
||||
}
|
||||
function clearCookie() { return 'iap.sid=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'; }
|
||||
// onSeen (2026-10-26): told the email + request of every resolved session (conversion tracking keeps the soft keys a member
|
||||
// signs in from, so their own clicks count as tests on LinkSpin). Never throws into the caller.
|
||||
let seenFn = null; function onSeen(fn) { seenFn = fn; }
|
||||
async function fromRequest(req) {
|
||||
const m = /(?:^|;\s*)iap\.sid=([^;]+)/.exec(req.headers.cookie || '');
|
||||
if (!m) return null;
|
||||
return impl().get(decodeURIComponent(m[1]));
|
||||
const s = await impl().get(decodeURIComponent(m[1]));
|
||||
if (s && s.email && seenFn) { try { seenFn(s.email, req); } catch (e) {} }
|
||||
return s;
|
||||
}
|
||||
async function refreshMemberId(sess) {
|
||||
if (!sess) return 0;
|
||||
@@ -172,4 +177,4 @@ async function logout(req) {
|
||||
if (s) await impl().drop(s.token);
|
||||
}
|
||||
|
||||
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, refreshMemberId, logout };
|
||||
module.exports = { init, makeChallenge, verifyChallenge, mintSession, updateSession, sessionCookie, clearCookie, fromRequest, onSeen, refreshMemberId, logout };
|
||||
|
||||
@@ -8,7 +8,7 @@ const path = require('path');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
let PUBLIC_DIR = null;
|
||||
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 } };
|
||||
const ART = { payouts: { file: 'badge-spark.jpg', ribbonY: 0.728 }, firstBuyer: { file: 'badge-surge.jpg', ribbonY: 0.76 }, level2: { file: 'badge-circuit.jpg', ribbonY: 0.72 }, level3: { file: 'badge-nexus.jpg', ribbonY: 0.73 }, fridays: { file: 'badge-fridays.jpg', ribbonY: 0.719 }, gamepass: { file: 'badge-gamepass.jpg', ribbonY: 0.84 }, stackpro: { file: 'badge-stackpro.jpg', ribbonY: 0.855 }, refuelStart: { file: 'badge-refuelstart.jpg', ribbonY: 0.735 }, refuel3: { file: 'badge-refuel3.jpg', ribbonY: 0.783 }, refuel6: { file: 'badge-refuel6.jpg', ribbonY: 0.716 }, refuel12: { file: 'badge-refuel12.jpg', ribbonY: 0.744 } };
|
||||
let FONT;
|
||||
function font() {
|
||||
if (FONT !== undefined) return FONT;
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
// BixPay card integration, phase 1 (Marty approved 2026-10-29; spec docs/BIXPAY-INTEGRATION.md).
|
||||
// BIX is a separate company: a self-custody wallet with a Visa card spent from USDT/USDC. We only carry each member's
|
||||
// PARTNER link (bix.ibportal.io/auth/register?e=<token>&a=1) so anyone who gets a card through their pages is credited to
|
||||
// them in the BIX portal. Nothing is settled on our side: the portal tracks directs and levels itself.
|
||||
//
|
||||
// One identity, sponsor follows (feedback-one-identity-sponsor-follows): the link a visitor gets is the member's own,
|
||||
// else the first sponsor up the chain (10 levels) with one, else the company link (site config bixCompanyLink). Every
|
||||
// surface says WHOSE link is in play ("you" / "@sponsor" / "network") so members add their own and sponsors get their
|
||||
// teams signed up.
|
||||
//
|
||||
// Everything is gated by site config bixpayLive ('0' = nothing shows; the admin flips it in Admin > Settings).
|
||||
// Clicks: every surface links through /go/bixpay?s=<surface>[&m=<member>] which counts here (DATA_DIR/bixpay-clicks.json)
|
||||
// and 302s to the resolved partner link. Counts per surface land in the admin Traffic tab, per member on the Promo tab.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = {}; // { dataDir, accounts, siteConfig, refAccount }
|
||||
const HOST = 'bix.ibportal.io';
|
||||
const PATH = '/auth/register';
|
||||
const MAX_LEN = 300;
|
||||
const MAX_LEVELS = 10;
|
||||
// Marty's own PARTNER link (IB12143793): the company fallback until Admin > Settings bixCompanyLink says otherwise
|
||||
const DEFAULT_COMPANY_LINK = 'https://bix.ibportal.io/auth/register?e=XqwU9T1aJ5N0UJ0yr9x0TGUiSQTsVCkTM01MIovVNnc&a=1';
|
||||
const SURFACES = ['wallet', 'overview', 'email', 'nudge', 'promo', 'guide', 'chat'];
|
||||
const CUSTOMER_LINK_MSG = "That's the card-customer link. Paste the Partner link from your BIX portal profile instead.";
|
||||
const ANNOUNCE_MS = 7 * 86400000; // the Overview announcement card shows for the first week after the switch is flipped
|
||||
|
||||
function init(opts) { R = opts || {}; }
|
||||
const cfg = () => { try { return (R.siteConfig && R.siteConfig()) || {}; } catch (e) { return {}; } };
|
||||
function live() { return String(cfg().bixpayLive == null ? '0' : cfg().bixpayLive) === '1'; }
|
||||
function companyLink() { const v = validate(cfg().bixCompanyLink); return v.ok ? v.link : DEFAULT_COMPANY_LINK; }
|
||||
// the Overview announcement runs a week from bixpayLiveSince (stamped by the admin settings route when the switch is flipped on)
|
||||
function announcing() { if (!live()) return false; const t = Date.parse(String(cfg().bixpayLiveSince || '')); return !(t > 0) || Date.now() - t < ANNOUNCE_MS; }
|
||||
|
||||
// A pasted partner link -> { ok: true, link } (normalised to e= and a=1 only) or { error }.
|
||||
// The card-customer link carries appId=3 (it makes a card customer, not a partner): refused with the message members see.
|
||||
function validate(input) {
|
||||
const s = String(input == null ? '' : input).trim();
|
||||
if (!s) return { error: 'Paste your BixPay partner link first.' };
|
||||
if (s.length > MAX_LEN) return { error: 'That link is too long. Copy the Partner link from your BIX portal profile.' };
|
||||
let u; try { u = new URL(s); } catch (e) { return { error: 'That is not a full link. It starts with https://bix.ibportal.io/auth/register?e=' }; }
|
||||
if (u.protocol !== 'https:' || u.hostname.toLowerCase() !== HOST) return { error: 'A BixPay partner link lives on https://bix.ibportal.io. Copy it from your BIX portal profile (Profile > Partner).' };
|
||||
if (u.pathname.replace(/\/+$/, '') !== PATH) return { error: 'That is not the register link. It looks like https://bix.ibportal.io/auth/register?e=...&a=1' };
|
||||
if (u.searchParams.has('appId') || u.searchParams.has('appid')) return { error: CUSTOMER_LINK_MSG };
|
||||
const e = String(u.searchParams.get('e') || '').trim();
|
||||
if (!/^[A-Za-z0-9_-]{16,128}$/.test(e)) return { error: 'The link is missing its e= token. Copy the whole Partner link from your BIX portal profile.' };
|
||||
if (String(u.searchParams.get('a') || '').trim() !== '1') return { error: 'The link needs a=1 on the end. Copy the whole Partner link from your BIX portal profile.' };
|
||||
return { ok: true, link: 'https://' + HOST + PATH + '?e=' + e + '&a=1' };
|
||||
}
|
||||
|
||||
const nameOf = a => a ? (a.username ? '@' + a.username : a.memberId ? 'member #' + a.memberId : 'your sponsor') : null;
|
||||
// bixLinkFor(member): own link, else the first sponsor up the chain with one (10 levels), else the company link.
|
||||
// -> { link, whose: 'you' | 'sponsor' | 'network', name, email } (name/email = the sponsor whose link it is)
|
||||
async function resolve(acct) {
|
||||
if (acct && validate(acct.bixPartnerLink).ok) return { link: validate(acct.bixPartnerLink).link, whose: 'you', name: nameOf(acct), email: acct.email };
|
||||
if (acct && R.accounts && R.accounts.sponsorOf) {
|
||||
const seen = new Set([String(acct.email || '').toLowerCase()]);
|
||||
let cur = acct;
|
||||
for (let i = 0; i < MAX_LEVELS && cur; i++) {
|
||||
let s = null; try { s = await R.accounts.sponsorOf(cur.email); } catch (e) { s = null; }
|
||||
if (!s || seen.has(String(s.email).toLowerCase())) break;
|
||||
seen.add(String(s.email).toLowerCase());
|
||||
const v = validate(s.bixPartnerLink);
|
||||
if (v.ok) return { link: v.link, whose: 'sponsor', name: nameOf(s), email: s.email };
|
||||
cur = s;
|
||||
}
|
||||
}
|
||||
return { link: companyLink(), whose: 'network', name: null, email: null };
|
||||
}
|
||||
// the same for a public page: the referrer token (?ref / the sponsor cookie) resolves like the member it names
|
||||
async function resolveRef(tok) {
|
||||
let a = null; try { a = tok && R.refAccount ? await R.refAccount(tok) : null; } catch (e) { a = null; }
|
||||
return resolve(a);
|
||||
}
|
||||
// the line every surface shows under the button
|
||||
function usingLine(r) { return r.whose === 'you' ? 'Using: your link.' : r.whose === 'sponsor' ? 'Using: ' + r.name + "'s link. Add yours in Profile." : 'Using: the network link. Add yours in Profile.'; }
|
||||
|
||||
// tracked link for a surface (+ the member it belongs to: the sharer on promo/guide/email, the viewer on the dashboard cards)
|
||||
const SITE = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||
function goLink(surface, token) { return SITE() + '/go/bixpay?s=' + encodeURIComponent(surface) + (token ? '&m=' + encodeURIComponent(String(token)) : ''); }
|
||||
// one sentence for payout emails and the games' wallet nudges (text), only while live
|
||||
function emailLine(token) { return live() ? 'Want to spend it? A BixPay Visa card turns POL into everyday purchases: ' + goLink('email', token) : ''; }
|
||||
function nudgeLine(token) { return live() ? 'Want to spend it? A BixPay Visa card turns POL into everyday purchases: ' + goLink('nudge', token) : ''; }
|
||||
|
||||
// ---- clicks ----
|
||||
const FILE = () => path.join(R.dataDir || '.', 'bixpay-clicks.json');
|
||||
const blank = () => ({ v: 1, total: {}, days: {}, members: {} });
|
||||
let S = null;
|
||||
function load() { if (S) return S; try { S = Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { S = blank(); } return S; }
|
||||
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(S)); } catch (e) {} }
|
||||
const day = ts => new Date(ts).toISOString().slice(0, 10);
|
||||
function click(surface, email) {
|
||||
const s = SURFACES.includes(surface) ? surface : 'other';
|
||||
const st = load();
|
||||
st.total[s] = (st.total[s] || 0) + 1;
|
||||
const d = day(Date.now()); st.days[d] = st.days[d] || {}; st.days[d][s] = (st.days[d][s] || 0) + 1;
|
||||
const e = String(email || '').trim().toLowerCase();
|
||||
if (e) { const m = st.members[e] = st.members[e] || { total: 0 }; m.total++; m[s] = (m[s] || 0) + 1; m.last = Date.now(); }
|
||||
// bounded: 400 days
|
||||
const cutoff = day(Date.now() - 400 * 86400000); for (const k of Object.keys(st.days)) if (k < cutoff) delete st.days[k];
|
||||
save();
|
||||
return { surface: s, email: e || null };
|
||||
}
|
||||
function memberClicks(email) {
|
||||
const m = load().members[String(email || '').trim().toLowerCase()];
|
||||
if (!m) return { total: 0 };
|
||||
return Object.assign({}, m);
|
||||
}
|
||||
function adminView(days) {
|
||||
const st = load(); const n = Math.min(365, Math.max(1, Number(days) || 30));
|
||||
const since = day(Date.now() - n * 86400000);
|
||||
const bySurface = {}; let total = 0;
|
||||
for (const [d, row] of Object.entries(st.days)) if (d >= since) for (const [s, c] of Object.entries(row)) { bySurface[s] = (bySurface[s] || 0) + c; total += c; }
|
||||
const daily = Object.entries(st.days).filter(([d]) => d >= since).sort((a, b) => a[0] < b[0] ? 1 : -1).map(([d, row]) => ({ day: d, clicks: Object.values(row).reduce((x, y) => x + y, 0) }));
|
||||
const members = Object.entries(st.members).map(([email, m]) => ({ email, total: m.total || 0, last: m.last || 0, promo: m.promo || 0 })).sort((a, b) => b.total - a.total).slice(0, 50);
|
||||
return { days: n, total, allTime: Object.values(st.total).reduce((x, y) => x + y, 0), bySurface, daily, members, surfaces: SURFACES };
|
||||
}
|
||||
function _reset() { S = null; }
|
||||
|
||||
module.exports = { init, live, announcing, validate, resolve, resolveRef, usingLine, companyLink, goLink, emailLine, nudgeLine, click, memberClicks, adminView, SURFACES, CUSTOMER_LINK_MSG, DEFAULT_COMPANY_LINK, MAX_LEVELS, _reset };
|
||||
@@ -6,6 +6,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
const themehead = require('./themehead'); // light/dark theme head script (2026-11-01)
|
||||
let DATA_DIR = null;
|
||||
const SITE = 'https://instantadpay.com';
|
||||
const AUTHOR = 'Marty Bostick';
|
||||
@@ -69,7 +70,8 @@ const D = {
|
||||
const row = r => ({ slug: r.slug, title: r.title, excerpt: r.excerpt || '', body: r.body || '', cover: r.cover || '', tags: r.tags ? String(r.tags).split(',').filter(Boolean) : [], status: r.status, author: r.author || AUTHOR, created: Number(r.created), updated: Number(r.updated), publishedAt: r.published_at ? Number(r.published_at) : null, views: Number(r.views) || 0 });
|
||||
const impl = () => db.enabled() ? D : J;
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; if (!db.enabled()) J.load(); }
|
||||
let EXTRA_PAGES = () => []; // sitemap entries that follow a switch (the /bixpay guide while bixpayLive, 2026-10-29)
|
||||
function init(opts) { DATA_DIR = opts.dataDir; if (typeof opts.extraPages === 'function') EXTRA_PAGES = opts.extraPages; if (!db.enabled()) J.load(); }
|
||||
async function listAll() { return (await impl().all()).sort((a, b) => (b.publishedAt || b.created) - (a.publishedAt || a.created)); }
|
||||
async function listPublished() { return (await listAll()).filter(p => p.status === 'published' && (p.publishedAt || 0) <= Date.now()); }
|
||||
async function get(slug) { return impl().get(slugify(slug)); }
|
||||
@@ -96,19 +98,19 @@ async function bumpViews(slug) { try { await impl().bumpViews(slug); } catch (e)
|
||||
function head(o) {
|
||||
const url = SITE + o.path;
|
||||
const img = o.image ? (o.image.startsWith('http') ? o.image : SITE + o.image) : SITE + '/banners/iap-hero-1200x630.png';
|
||||
return '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
return '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">'
|
||||
+ '<title>' + esc(o.title) + '</title><meta name="description" content="' + esc(o.desc) + '"><link rel="canonical" href="' + esc(url) + '">'
|
||||
+ '<meta name="robots" content="index,follow,max-image-preview:large"><meta name="theme-color" content="#043b2f">'
|
||||
+ '<meta property="og:type" content="' + (o.article ? 'article' : 'website') + '"><meta property="og:site_name" content="InstantAdPay"><meta property="og:title" content="' + esc(o.title) + '"><meta property="og:description" content="' + esc(o.desc) + '"><meta property="og:url" content="' + esc(url) + '"><meta property="og:image" content="' + esc(img) + '">'
|
||||
+ (o.article ? '<meta property="article:published_time" content="' + new Date(o.article.publishedAt || o.article.created).toISOString() + '"><meta property="article:modified_time" content="' + new Date(o.article.updated).toISOString() + '"><meta property="article:author" content="' + esc(AUTHOR) + '">' + (o.article.tags || []).map(t => '<meta property="article:tag" content="' + esc(t) + '">').join('') : '')
|
||||
+ '<meta name="twitter:card" content="summary_large_image"><meta name="twitter:title" content="' + esc(o.title) + '"><meta name="twitter:description" content="' + esc(o.desc) + '"><meta name="twitter:image" content="' + esc(img) + '">'
|
||||
+ '<link rel="alternate" type="application/rss+xml" title="InstantAdPay blog" href="' + SITE + '/blog/feed.xml"><link rel="icon" type="image/png" href="/logo-icon.png">'
|
||||
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap"><link rel="stylesheet" href="/assets/site.css?v=20260912b">'
|
||||
+ '<style>.bl{max-width:760px}.bl h1{font-size:clamp(30px,4.6vw,44px);line-height:1.12;margin:10px 0 12px}.bl .meta{color:var(--muted);font-size:14px;margin:0 0 22px}.bl .cover{width:100%;border-radius:14px;border:1px solid var(--line);margin:0 0 26px;display:block}.bl article{font-size:17.5px;line-height:1.7}.bl article p{margin:0 0 18px;max-width:68ch}.bl article h2{font-size:26px;margin:36px 0 12px}.bl article h3{font-size:20px;margin:28px 0 10px}.bl article ul,.bl article ol{margin:0 0 18px 22px;max-width:66ch}.bl article li{margin:6px 0}.bl article blockquote{border-left:4px solid var(--mint);margin:0 0 18px;padding:8px 18px;color:var(--muted);font-style:italic}.bl article img{max-width:100%;border-radius:12px;border:1px solid var(--line)}.bl article a{color:var(--mint)}.bl article pre{background:rgba(4,8,7,.6);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;font-size:14px}.bl article table{border-collapse:collapse;width:100%;font-size:15px}.bl article th,.bl article td{border-bottom:1px solid var(--line);padding:8px 10px;text-align:left}.tags a{display:inline-block;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--mint);border:1px solid rgba(67,232,195,.4);border-radius:999px;padding:3px 10px;margin:0 6px 6px 0;text-decoration:none}.post-card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px 22px;margin:0 0 14px;color:inherit;text-decoration:none}.post-card:hover{border-color:var(--mint)}.post-card h2{font-size:22px;margin:0 0 6px}.post-card p{margin:0;color:var(--muted);font-size:15px;max-width:70ch}.post-card .meta{margin:8px 0 0;font-size:13px}.author{display:flex;gap:14px;align-items:center;border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:36px 0 0;background:var(--panel)}.author img{width:56px;height:56px;border-radius:50%;object-fit:cover}.author b{display:block}.author span{color:var(--muted);font-size:14px}.share a{margin-right:14px;font-size:14px}.pager{display:flex;justify-content:space-between;margin:26px 0}.related{margin-top:40px}.related h3{margin-bottom:10px}</style>'
|
||||
+ '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<style>.bl{max-width:760px}.bl h1{font-size:clamp(30px,4.6vw,44px);line-height:1.12;margin:10px 0 12px}.bl .meta{color:var(--muted);font-size:14px;margin:0 0 22px}.bl .cover{width:100%;border-radius:14px;border:1px solid var(--line);margin:0 0 26px;display:block}.bl article{font-size:17.5px;line-height:1.7}.bl article p{margin:0 0 18px;max-width:68ch}.bl article h2{font-size:26px;margin:36px 0 12px}.bl article h3{font-size:20px;margin:28px 0 10px}.bl article ul,.bl article ol{margin:0 0 18px 22px;max-width:66ch}.bl article li{margin:6px 0}.bl article blockquote{border-left:4px solid var(--mint);margin:0 0 18px;padding:8px 18px;color:var(--muted);font-style:italic}.bl article img{max-width:100%;border-radius:12px;border:1px solid var(--line)}.bl article a{color:var(--mint)}.bl article pre{background:var(--ground-soft);border:1px solid var(--line);border-radius:10px;padding:14px;overflow:auto;font-size:14px}.bl article table{border-collapse:collapse;width:100%;font-size:15px}.bl article th,.bl article td{border-bottom:1px solid var(--line);padding:8px 10px;text-align:left}.tags a{display:inline-block;font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:var(--mint);border:1px solid var(--mint-line);border-radius:999px;padding:3px 10px;margin:0 6px 6px 0;text-decoration:none}.post-card{display:block;background:var(--panel);border:1px solid var(--line);border-radius:14px;padding:20px 22px;margin:0 0 14px;color:inherit;text-decoration:none}.post-card:hover{border-color:var(--mint)}.post-card h2{font-size:22px;margin:0 0 6px}.post-card p{margin:0;color:var(--muted);font-size:15px;max-width:70ch}.post-card .meta{margin:8px 0 0;font-size:13px}.author{display:flex;gap:14px;align-items:center;border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:36px 0 0;background:var(--panel)}.author img{width:56px;height:56px;border-radius:50%;object-fit:cover}.author b{display:block}.author span{color:var(--muted);font-size:14px}.share a{margin-right:14px;font-size:14px}.pager{display:flex;justify-content:space-between;margin:26px 0}.related{margin-top:40px}.related h3{margin-bottom:10px}</style>'
|
||||
+ '</head><body><div class="wrap bl">';
|
||||
}
|
||||
function tail() {
|
||||
return '</div><script src="/assets/common.js?v=20260914a"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||
return '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
||||
}
|
||||
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
|
||||
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
|
||||
@@ -152,7 +154,7 @@ function rss(posts) {
|
||||
return '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><title>InstantAdPay blog</title><link>' + SITE + '/blog</link><description>Coaching and teaching articles from Marty Bostick.</description>' + items + '</channel></rss>';
|
||||
}
|
||||
function sitemap(posts) {
|
||||
const pages = ['/', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday'];
|
||||
const pages = ['/', '/facts', '/blog', '/whats-new', '/leaderboard', '/ledger', '/contract', '/plays', '/wallets', '/earning', '/partners', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation'].concat(EXTRA_PAGES() || []);
|
||||
const u = pages.map(p => '<url><loc>' + SITE + p + '</loc><changefreq>weekly</changefreq></url>').join('')
|
||||
+ posts.map(p => '<url><loc>' + SITE + '/blog/' + p.slug + '</loc><lastmod>' + new Date(p.updated).toISOString().slice(0, 10) + '</lastmod><changefreq>monthly</changefreq></url>').join('');
|
||||
return '<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + u + '</urlset>';
|
||||
|
||||
@@ -77,13 +77,19 @@ function getConfig() {
|
||||
function reloadConfig() { cfg = null; return getConfig(); }
|
||||
|
||||
// ---- JSON-RPC with fallback rotation ----
|
||||
// RPC call counter (2026-10-06, Marty: measure 24 h of Polygon traffic before choosing a paid endpoint): counts every request
|
||||
// this module sends, by method, and writes DATA_DIR/rpc-count.json every 5 minutes. Read-only bookkeeping; no behaviour change.
|
||||
const RPC_COUNT = { since: Date.now(), m: {} };
|
||||
const rpcCount = method => { RPC_COUNT.m[method] = (RPC_COUNT.m[method] || 0) + 1; };
|
||||
setInterval(() => { try { fs.writeFileSync(path.join(DATA_DIR, 'rpc-count.json'), JSON.stringify(Object.assign({ at: Date.now() }, RPC_COUNT))); } catch (e) {} }, 300000).unref();
|
||||
let rpcIdx = 0;
|
||||
function rpcOnce(url, method, params) {
|
||||
function rpcOnce(url, method, params, timeoutMs) {
|
||||
rpcCount(method);
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({ jsonrpc: '2.0', id: 1, method, params });
|
||||
const u = new URL(url);
|
||||
const req = https.request({ hostname: u.hostname, path: u.pathname + u.search, method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: 15000 },
|
||||
headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) }, timeout: timeoutMs || 15000 },
|
||||
res => { let d = ''; res.on('data', c => d += c); res.on('end', () => {
|
||||
try { const j = JSON.parse(d); if (j.error) reject(new Error(j.error.message)); else resolve(j.result); }
|
||||
catch (e) { reject(e); } }); });
|
||||
@@ -91,20 +97,28 @@ function rpcOnce(url, method, params) {
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
async function rpc(method, params) {
|
||||
// Circuit breaker (2026-10-12, ported from RM Circle): a provider that fails or hangs is benched for RPC_BENCH_MS so the next
|
||||
// calls skip it instead of each paying the full timeout in turn (a dead node at the sticky index was stalling every member
|
||||
// lookup, which members felt as slow sign-ins). eth_call reads use a 4 s timeout; logs/blocks keep 15 s. Failures are logged.
|
||||
// bench only for provider-health failures (timeouts, connection errors, rate limits, 5xx). A deterministic JSON-RPC reply such as
|
||||
// "invalid block range" or "query returned more than N results" is about the request, so the next provider is tried without benching.
|
||||
const benchable = e => /timeout|timed out|abort|ECONN|EAI_AGAIN|ENOTFOUND|EPIPE|socket|hang up|429|too many|rate.?limit|temporar|internal error|service unavailable|50[234]/i.test(String(e && e.message || e));
|
||||
const RPC_BENCH_MS = 10 * 60 * 1000; const rpcBenched = new Map(); // url -> benched until (ms)
|
||||
const ETH_CALL_TIMEOUT_MS = 4000;
|
||||
async function rpc(method, params, timeoutMs) {
|
||||
const urls = getConfig().rpcs;
|
||||
let last;
|
||||
// 3 rounds over the RPC pool with backoff — the public Amoy nodes routinely
|
||||
// return transient "Temporary internal error. Please retry" on eth_call, and a
|
||||
// single miss was silently surfacing as 0 credits / chainReadError on the
|
||||
// dashboard. Retry so a real read isn't lost to a momentary node hiccup.
|
||||
for (let round = 0; round < 3; round++) {
|
||||
for (let i = 0; i < urls.length; i++) {
|
||||
const url = urls[(rpcIdx + i) % urls.length];
|
||||
try { const r = await rpcOnce(url, method, params); rpcIdx = (rpcIdx + i) % urls.length; return r; }
|
||||
catch (e) { last = e; }
|
||||
// two passes: healthy providers first (round-robin from the last good one), benched ones only as a last resort; a short
|
||||
// backoff before the second pass covers the public nodes' transient "Temporary internal error" replies.
|
||||
for (let round = 0; round < 2; round++) {
|
||||
const now = Date.now(); const order = [], benched = [];
|
||||
for (let i = 0; i < urls.length; i++) { const url = urls[(rpcIdx + i) % urls.length]; ((rpcBenched.get(url) || 0) > now ? benched : order).push(url); }
|
||||
order.push(...benched);
|
||||
for (const url of order) {
|
||||
try { const r = await rpcOnce(url, method, params, timeoutMs); rpcIdx = urls.indexOf(url); rpcBenched.delete(url); return r; }
|
||||
catch (e) { last = e; const bench = benchable(e); if (bench) rpcBenched.set(url, Date.now() + RPC_BENCH_MS); console.warn('rpc', method, 'failed on', url, '->', String(e && e.message || e).slice(0, 80), bench ? '(benched 10 min)' : '(request error, next provider)'); }
|
||||
}
|
||||
if (round < 2) await new Promise(r => setTimeout(r, 400 * (round + 1)));
|
||||
if (round < 1) await new Promise(r => setTimeout(r, 400));
|
||||
}
|
||||
throw last || new Error('all RPCs failed');
|
||||
}
|
||||
@@ -125,7 +139,7 @@ function decodeString(data, wordIdx) {
|
||||
}
|
||||
async function call(sel, args) {
|
||||
const data = sel + (args || []).map(a => pad(a)).join('');
|
||||
return rpc('eth_call', [{ to: getConfig().contract, data }, 'latest']);
|
||||
return rpc('eth_call', [{ to: getConfig().contract, data }, 'latest'], ETH_CALL_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
// ---- reads ----
|
||||
@@ -135,7 +149,16 @@ async function memberIdByAccount(addr) {
|
||||
}
|
||||
async function memberCount() { return toNum(word(await call(SEL.memberCount), 0)); }
|
||||
async function productCount() { return toNum(word(await call(SEL.productCount), 0)); }
|
||||
// member reads are cached 15 s (2026-10-20): dashboards ask for the same members many times a minute and every read is
|
||||
// an RPC round trip; sponsor never changes and a buyer count up to 15 s old is fine for display
|
||||
const memberCache = new Map();
|
||||
async function member(id) {
|
||||
const hit = memberCache.get(Number(id)); if (hit && Date.now() - hit.at < 15000) return hit.v;
|
||||
const v = await memberRead(id); memberCache.set(Number(id), { at: Date.now(), v });
|
||||
if (memberCache.size > 5000) memberCache.clear();
|
||||
return v;
|
||||
}
|
||||
async function memberRead(id) {
|
||||
const r = await call(SEL.members, [id]);
|
||||
return { account: toAddr(word(r, 0)), sponsorId: toNum(word(r, 1)), buyerCount: toNum(word(r, 2)),
|
||||
activated: toNum(word(r, 3)) === 1, countedAsBuyer: toNum(word(r, 4)) === 1 };
|
||||
@@ -148,15 +171,16 @@ async function product(id) {
|
||||
async function quoteWei(id) { try { return toBig(word(await call(SEL.quoteWei, [id]), 0)); } catch (e) { return null; } }
|
||||
async function creditBalance(id, type) { return Number(toBig(word(await call(SEL.creditBalance, [id, type || 0]), 0))); }
|
||||
async function catalog() {
|
||||
// products and quotes are read side by side, not one after another (2026-10-19: 15 sequential reads took ~6 s
|
||||
// and every dashboard waited on them)
|
||||
const n = await productCount();
|
||||
const out = [];
|
||||
for (let i = 1; i <= n; i++) {
|
||||
const p = await product(i);
|
||||
if (!p.exists || !p.active) continue;
|
||||
const q = await quoteWei(i);
|
||||
out.push(Object.assign(p, { costWei: q === null ? null : q.toString() }));
|
||||
}
|
||||
return out;
|
||||
const ids = Array.from({ length: n }, (_, k) => k + 1);
|
||||
const rows = await Promise.all(ids.map(async i => {
|
||||
const [p, q] = await Promise.all([product(i), quoteWei(i)]);
|
||||
if (!p.exists || !p.active) return null;
|
||||
return Object.assign(p, { costWei: q === null ? null : q.toString() });
|
||||
}));
|
||||
return rows.filter(Boolean);
|
||||
}
|
||||
|
||||
// ---- event decode ----
|
||||
@@ -228,7 +252,7 @@ async function tail() {
|
||||
const ev = decodeLog(lg);
|
||||
if (!ev) continue;
|
||||
ev.ts = Date.now(); // indexed-at time: powers honest time-series charts
|
||||
state.events.push(ev);
|
||||
state.events.push(ev); memberCache.clear(); // a new chain event can change any member: drop the 15 s read cache
|
||||
tally(ev);
|
||||
if (onEvent) { try { onEvent(ev); } catch (e) { console.error('chain onEvent', e.message); } }
|
||||
}
|
||||
|
||||
@@ -4,15 +4,29 @@
|
||||
//
|
||||
// HOUSE RULE: whenever a site feature changes, update BOTH the CANNED
|
||||
// answers and FACTS below in the same commit.
|
||||
//
|
||||
// KNOWLEDGE BASE (2026-10-20, kb.js): CANNED below and kb-seed.js SEED the knowledge base, which is
|
||||
// the one source the assistant answers from. Each CANNED regex becomes its entry's instant-answer
|
||||
// pattern (same order, first match wins), and for everything else the best-matching entries go into
|
||||
// the system prompt. Admin > Knowledge base edits entries; an edited entry is no longer refreshed from
|
||||
// the code. If the KB store fails, the in-code CANNED list still answers.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const kb = require('./kb');
|
||||
const kbSeed = require('./kb-seed');
|
||||
|
||||
let DATA_DIR = null;
|
||||
let chain = null;
|
||||
let HERO_SALE = null; // () => gamepass.cfg().heroes + names (server.js): the bonus-hero fact follows heroSales (2026-11-05)
|
||||
let PASS_TIERS = null; // () => the live pass tiers (server.js, from gamepass.cfg): the tier fact follows the sovTiers switch
|
||||
const MODEL = process.env.OPENROUTER_MODEL || 'deepseek/deepseek-v4-flash:nitro';
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; chain = opts.chain; }
|
||||
function init(opts) {
|
||||
if (opts && typeof opts.gameLive === 'function') GAME_LIVE = opts.gameLive;
|
||||
if (opts && typeof opts.refuelOn === 'function') REFUEL_ON = opts.refuelOn;
|
||||
if (opts && typeof opts.bixLive === 'function') BIX_LIVE = opts.bixLive; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : null; HERO_SALE = typeof opts.heroSale === 'function' ? opts.heroSale : null; return kb.init({ dataDir: DATA_DIR, seeds: seeds() }); }
|
||||
function key() {
|
||||
if (process.env.OPENROUTER_API_KEY) return process.env.OPENROUTER_API_KEY.trim();
|
||||
try { return fs.readFileSync(path.join(DATA_DIR, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; }
|
||||
@@ -20,31 +34,159 @@ function key() {
|
||||
function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-09-18'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-11-14'; // 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 = [
|
||||
{ re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
|
||||
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
|
||||
{ id: 'network-signin', title: 'One sign-in for InstantAdPay and LinkSpin', q: ['Do I have to sign in again on LinkSpin?', 'Why was I signed in on LinkSpin without a code?', 'Is it one sign-in for both sites?'], tags: ['sign in', 'network sign-in', 'linkspin', 'code', 'single sign-on'],
|
||||
re: /(((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password).{0,40}(linkspin|both sites|other site)|(linkspin|both sites|other site).{0,40}((sign(ed)?|log(ged)?) ?-?(in|on)\b(?! ?-?ads?\b)|\bcodes?\b|password)|single sign|sso|one sign.?in|network sign.?in)/i,
|
||||
a: 'One sign-in covers both sites. While you are signed in on InstantAdPay, any link inside your account that opens LinkSpin (the Engine Room, Refuel and the other LinkSpin links) lands you there signed in, with no code. It works the other way too, and if you open the sign-in screen on either site while you are signed in on the other, it signs you in by itself. Both sites use the same email. The one exception: if your account on the other site is not set up yet (for example you joined minutes ago, or it is waiting for your first visit), you get the usual email code that one time, with your email already filled in. Signing out signs you out of that site only, and it stays signed out there until you sign in again or follow a link from the other site. A session still lasts 4 hours on each site. This sign-in never moves money: buying, payouts and wallet actions work exactly as before.' },
|
||||
// Stack POL (2026-11-09): stackpol.com, every POL payout across the network on one page; members opt in to a page in Promo tools
|
||||
// Earners Corner (2026-11-10): earnerscorner.com, the network's forum; sign-in is the InstantAdPay account (DiscourseConnect)
|
||||
{ id: 'earners-corner', title: 'Earners Corner forum', q: ['What is Earners Corner?', 'Is there a forum?', 'How do I sign in to the forum?'], tags: ['earners corner', 'forum', 'earnerscorner', 'community', 'discussion'],
|
||||
re: /\b(earners ?corner|earnerscorner(\.com)?|forum)\b/i,
|
||||
a: 'Earners Corner (https://earnerscorner.com) is our forum for people who earn online: business opportunities, paid to click, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing and tools, with its own section for InstantAdPay, LinkSpin, the games and Stack POL. Anyone can read it. To post, tap Log In there and sign in with your InstantAdPay account, no new password. A new account\'s first post is reviewed before it shows, and referral links belong in the Promote Your Program category. Members with an on-chain position can post links from day one. It also has an assistant that answers questions about the network and finds related threads.' },
|
||||
{ id: 'stack-pol', title: 'Stack POL', q: ['What is Stack POL?', 'How do I get my Stack POL page?', 'What is stackpol.com?'], tags: ['stack pol', 'stackpol', 'payouts', 'ledger', 'promo tools', 'stack pol pro', 'pro'],
|
||||
re: /\b(stack ?pol|stackpol(\.com)?)\b/i,
|
||||
a: 'Stack POL (https://stackpol.com) adds up every POL payout in the network: InstantAdPay and LinkSpin referral payments and the rewards from every game that pays POL. It shows the network total, one page per program, and a public ledger of the latest payouts with the username and a Polygonscan link for every payment. It refreshes every 5 minutes. Every member who has been paid has a page by default at stackpol.com/your-username (Promo tools > Stack POL shows the link and the switch "Show my Stack POL page"). It appears at stackpol.com/your-username within 5 minutes and carries your referral link on every program card. Link a wallet so your payouts can be added up. Switch it off any time. Stack POL Pro is a one-time upgrade: your page then shows your own LinkSpin Banner Spins in its ad spots and your spin links, a purple QR code that opens your page, and blog articles opened from your page show your banners and use your referral links on every button. Any ad package of $10 or more unlocks it automatically, one time, yours for good: Pro switches on when that package settles on chain, and you keep every credit of the package. Credits never unlock it. Pro owners also get the Stack POL Pro badge. The totals are what members were paid, not a promise of what anyone will earn.' },
|
||||
// Shards of Valor bonus heroes (2026-11-05, Marty approved): sold one time. The prices and whether they are on sale live in settings, so
|
||||
// this answer names neither; heroesFact() gives the AI the live state.
|
||||
{ id: 'sov-bonus-heroes', title: 'Shards of Valor bonus heroes', q: ['What are the bonus heroes in Shards of Valor?', 'How do I get Kestrel, Valda, Morag or Roland?', 'Is the hero a subscription?'], tags: ['shards of valor', 'heroes', 'bonus heroes', 'kestrel', 'valda', 'morag', 'roland', 'party'],
|
||||
re: /\b(bonus heroe?s?|kestrel|valda|morag|roland|paladin|barbarian|druid hero|archer hero|hero bundle)\b/i,
|
||||
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Kestrel is free for every player: she joins for good once a hero in your party reaches level 20, and she is not sold. Valda, Morag and Roland are each a one-time purchase, yours for good, with no subscription, and there is a bundle of those three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
|
||||
{ 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'],
|
||||
re: SUPPORT_RE, handoff: true,
|
||||
a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' },
|
||||
// BixPay Visa card (2026-10-29, docs/BIXPAY-INTEGRATION.md). Sits ahead of the Level 4 entry because that one also matches "3%".
|
||||
// While site config bixpayLive is off, answer() swaps every bixpay-* hit for BIX_SOON_ANSWER. Never BIX's marketing claims (user
|
||||
// counts, spend per day, valuations) as facts; the only fee we state is 3% per purchase, no load fee, see BIX's terms for the rest.
|
||||
{ id: 'bixpay-link', title: 'Where to put my BixPay partner link', q: ['Where do I put my BixPay partner link?', 'How do I add my BIX link?', 'Which BixPay link do I paste, referral or partner?'], tags: ['bixpay', 'bix', 'partner link', 'profile', 'ib portal'],
|
||||
re: /(bix|bixpay).*(partner link|my link|referral link|ib ?portal|paste|where do i (put|add|enter)|profile)|(partner link|ib ?portal).*(bix|bixpay)/i,
|
||||
a: 'Members > Profile > BixPay card. Paste your PARTNER link there: in your BIX portal (bix.ibportal.io) open Profile and copy the link in the second box, the one labelled Partner. It looks like https://bix.ibportal.io/auth/register?e=...&a=1. The first box, the Bix referral link (it ends in appId=3), only makes a card customer, so the field refuses it and asks for the Partner one. Once saved, your Wallet card, your promo kit, the /bixpay guide opened from your links and the line in your payout emails all carry your link, and LinkSpin will read the same one.' },
|
||||
{ id: 'bixpay-credit', title: 'Who gets the BixPay credit', q: ['Who gets credit when someone signs up for BixPay through my page?', 'Whose BixPay link is on my pages?', 'What does "Using: the network link" mean?'], tags: ['bixpay', 'bix', 'credit', 'sponsor', 'network link'],
|
||||
re: /(bix|bixpay).*(credit|whose|who gets|sponsor.s link|network link|using:|my sponsor|upline)|(whose|who gets).*(bix|bixpay)/i,
|
||||
a: 'The BixPay link on your pages is yours when you have saved your partner link in Profile. If you have not, it is the first sponsor up your line (up to ten levels) who has one, and if nobody has, it is the network link. Every BixPay card says which one is in play: "Using: your link", "Using: @name’s link" or "Using: the network link". Sign-ups are credited inside the BIX portal to whoever owns that link, directs and levels included; InstantAdPay does not count or pay BixPay sign-ups itself. Add your own link in Members > Profile > BixPay card so the credit is yours.' },
|
||||
{ id: 'bixpay-load', title: 'Loading the BixPay card from POL', q: ['How do I load my BixPay card from POL?', 'Can I send POL to BixPay?', 'How do I fund the BixPay card?'], tags: ['bixpay', 'bix', 'fund', 'load', 'usdt', 'usdc', 'polygon', 'cash app'],
|
||||
re: /(bix|bixpay).*(load|fund|top ?up|deposit|send pol|from pol|usdt|usdc|swap|cash ?app)|(load|fund|top ?up).*(bix|bixpay)/i,
|
||||
a: 'The BixPay card spends USDT or USDC, so the step is POL to USDT or USDC first. Three ways: (1) swap your POL for USDT or USDC on any exchange or on-ramp you already use, then send it to your BixPay wallet on the Polygon network (open the BIX app, Wallet > Receive, pick USDT or USDC, and use the Polygon address); (2) in the US, Cash App can send crypto straight to the BixPay wallet; (3) BIX has said an in-app swap is coming, and we will add it here when it ships. Once the USDT or USDC is in the wallet, tap TOPUP on the card. No load fee; 3% per purchase; see BIX’s terms for other charges. The full walk-through with screenshots is at https://instantadpay.com/bixpay.' },
|
||||
{ id: 'bixpay-card', title: 'How to get the BixPay card', q: ['How do I get the BixPay card?', 'How do I sign up for BixPay?', 'Is BixPay available in my state?'], tags: ['bixpay', 'bix', 'visa card', 'virtual card', 'sign up', 'states'],
|
||||
re: /(bix|bixpay).*(get|sign ?up|join|order|apply|virtual|plastic|metal|state|country|available|how much|cost|price|\$9)|(get|sign ?up for|order).*(bix|bixpay)/i,
|
||||
a: 'Open the BixPay card in your Wallet tab (Members > Wallet) and tap Get your BixPay card. That opens a partner sign-up link, so you join as a partner and the card and the referral plan come with it: 1) register in the BIX portal ON THE PAGE THE LINK OPENS (if you are reading this inside Gmail or Telegram, open the page in Chrome or Safari first; do not install the app first and do not use the portal’s own Sign Up menu, or your sponsor is lost and BIX shows the referrer as N/A), 2) download the BIX app and create your wallet, 3) in the app open Settings > Scan QR and scan the code in your portal profile to link the two, 4) Cards > Create Card for the $9.99 virtual Visa (plastic, metal and gold cards cost more). KYC is required for the card. In the US it is open in 31 states so far; not in your state yet? You can still get the wallet and build. Elsewhere availability varies by country. Guide: https://instantadpay.com/bixpay.' },
|
||||
{ id: 'bixpay', title: 'What BixPay is', q: ['What is BixPay?', 'What is the BIX card?', 'Can I spend my POL with a Visa card?'], tags: ['bixpay', 'bix', 'visa', 'card', 'spend pol', 'wallet'],
|
||||
re: /(bix|bixpay|bix card|visa card|debit card|spend (my )?(pol|crypto|earnings)|crypto card)/i,
|
||||
a: 'BixPay is a self-custody wallet with a Visa card, made by BIX, a separate company. You send USDT or USDC to it on Polygon, load the card, and spend wherever Visa is accepted, including Apple Pay and Google Pay. Virtual cards from $9.99. 3% per purchase, no load fee; see BIX’s terms for other charges. InstantAdPay is not the card issuer; members who join BixPay as partners get their own partner link, and anyone who gets a card through their pages is credited to them in the BIX portal, up to ten levels deep. Where to find it: Members > Wallet (the card), Members > Profile (your partner link), Promo tools > BixPay (posts and banners), and the guide at https://instantadpay.com/bixpay. Crypto assets can lose value.' },
|
||||
{ id: 'level4-override', title: 'The Level 4 override (3%)', q: ['What is the Level 4 override?', 'Do I earn from my fourth level?', 'How does the 3% override work?'], tags: ['override', 'level 4', 'fourth level', 'commission', 'payouts'],
|
||||
re: /(level ?(4|four)|4th level|fourth level|override|3 ?%|three percent)/i,
|
||||
a: 'The Level 4 override is 3% of every package bought four levels below you, paid by the company on top of the three levels the contract pays. It goes to the buyer’s 4th sponsor up if that member has 5 or more qualifying buyers (direct referrals who bought $20 or more, the same bar as level 3). If they do not have 5 yet, it moves up the line to the next member who does, up to 25 steps, and each purchase pays one override to one person. It is paid weekly in POL from a company wallet, every Monday after 9 AM Central for the Monday to Sunday week before, through the contract’s award function, so every payment has a Polygon link, and it shows in your Earnings as "Level 4 override". Weekly totals under 0.01 POL carry over to the next week. It counts purchases from the start date on, not earlier ones. It comes from the platform’s 20% share, so the 50/20/10 split does not change. What you earn depends on real purchases in your line; nothing is guaranteed.' },
|
||||
{ id: 'game-pass', title: 'Game Pass and daily POL caps', q: ['What is the Game Pass?', 'Why did I hit the daily POL cap in the games?', 'Does a boss reward carry over to the next day?'], tags: ['games', 'game pass', 'daily cap', 'tournament'],
|
||||
re: /(game ?pass|pass tournament|daily (pol )?cap|pol cap|cap(ped|s)? (on|in|for) (the )?games?|hit (the|my|today.s) (free )?cap|carr(y|ied) (over|forward))/i,
|
||||
a: 'The Game Pass is $5 for 7 days and covers every game in the network on your InstantAdPay account (linked positions included). Since Nov 2 free play is a taste and the Pass is where the games pay: higher daily POL caps across every game (1.50 POL a day on repeatable rewards instead of 0.30, and 5 POL a day in all instead of 2), a seat in the weekly Pass Tournament (POL prizes from 5% of pass sales, settled Mondays, top 3 posted to Game Achievements), extra plays or a perk in each game, and the gold Game Pass badge with your name. Per game: PolHunter 5 hunts a day at the full 0.05 to 1 POL draw instead of one small free hunt (0.02 to 0.10), plus the weekly prizes, the Mystery Hunt Box and 2 Ad Detective cases; Gem Kingdom one free continue a day; Spooky Doors one extra door a day; ClutterHunt 2 bonus hints a day; SpellWheel daily streak 0.30 POL instead of 0.15 plus 1 free hint a day; PolyBreak daily gem limit 1.5 POL instead of 0.5 plus an extra paddle every round; POL Miner daily crystal limit 1.5 POL instead of 0.5 plus one free supply crate every day; PolyWarriors a 4th daily mission and defense pays 25 Circuits instead of 15; Drip Runner a free shield at the start of every run; Road Agent 2 patrols a day and 25% more scrap. The full list is on the Game Pass card. Caps are account-wide and reset at midnight Central. There is also a free allowance: an account with no pass receives at most 2 POL of game rewards in total, across every game, ever; after that the games keep paying only while a pass is active, and one-time progress rewards earned in the meantime are held and paid once it is. When your allowance is used up, the game you are playing and your Overview tell you, with the amount being held for you. A one-time progress reward (a boss, a chapter, a sector) is never lost: whatever is over the day\u2019s total carries to the next day until it is paid in full; repeatable daily play over the daily cap is simply not paid that day. The Pass never changes how much any reward pays, so it is more game, not more payback. Get it in Members > Games > Game Pass: every pass is paid by a NEW package purchase of $5 or more. Tap Get the Pass, then buy the package; the pass starts the moment that purchase settles on chain. Your sponsor and team are paid from that package as usual, and you keep every credit of the package for your ads. Credits you already hold (earned or purchased) never buy a pass, and a package bought before you tapped Get the Pass does not count. Buying again while a pass is active adds 7 days.' },
|
||||
// game POL to any linked wallet (Marty, 2026-10-27, "build all three"): sits ahead of the per-game entries so "my Gem Kingdom POL never came" lands here
|
||||
{ id: 'game-pol-wallet', title: 'Getting your game POL (link your wallet)', q: ['Why was my game POL not sent?', 'It says POL is waiting for my wallet', 'Do I need to switch on payouts to get game POL?'], tags: ['games', 'game pol', 'link wallet', 'waiting for your wallet', 'not sent'],
|
||||
re: /(pol (is )?waiting for (my |your |a )?wallet|link (my |your |a )?wallet to (receive|get)|(game|games|gem ?kingdom|drip ?runner|clutter ?hunt|spooky ?doors|road ?agent|poly ?break|spell ?wheel|poly ?warriors?)\b[^.?!]{0,60}\bpol\b[^.?!]{0,40}\b(not (been )?(paid|sent)|never (paid|sent|arrived|came)|stuck|waiting|pending|switch on|activat\w*)|(switch on|turn on|activate) payouts?[^.?!]{0,40}\b(game|games)\b[^.?!]{0,20}\bpol\b)/i,
|
||||
a: 'Game POL is paid to the wallet linked to your InstantAdPay account. Linking is one free signature on your Wallet tab (https://instantadpay.com/my#wallet): it is not a transaction and it cannot move funds. Once your wallet is linked, every game sends your POL automatically, usually within the hour, including everything you earned before you linked it (each game still pays once your balance reaches the payout line shown in that game). You do not need to switch on payouts for game POL: a linked wallet is paid even before it is activated, so a member waiting in the holding tank for a sponsor still gets their game POL. If a game already has a different wallet on file for you, it keeps paying that one; open Help if that needs changing.' },
|
||||
{ id: 'road-agent', title: 'Road Agent (night-highway shooter)', q: ['What is Road Agent?', 'How do fuel stops work in Road Agent?'], tags: ['games', 'road agent', 'fuel stop'],
|
||||
re: /(road ?agent|night.?highway|fuel stop|weapons truck)/i,
|
||||
a: 'Road Agent is the network’s night-highway shooter, live since October 15 for every member: Games tab > Road Agent > Play, or roadagent.app with your InstantAdPay email. First clear of each sector pays POL to the wallet on your InstantAdPay account, plus a daily patrol reward. Fuel comes from a sponsor visit (a fuel stop), which is a normal verified visit, so advertisers’ visits campaigns get traffic from the game automatically.' },
|
||||
{ id: 'presentation', title: 'The InstantAdPay presentation video', q: ['Where is the presentation video?', 'How do I share the presentation with my link?', 'What is the Build Wide video?'], tags: ['presentation', 'video', 'share', 'captions', 'build wide'],
|
||||
re: /(presentation|build ?wide (video|presentation)|narrated (video|presentation)|share the (video|presentation)|\?v=wide|wide angle)/i,
|
||||
a: 'The InstantAdPay presentation is a narrated video of about six minutes at https://instantadpay.com/presentation, with captions in English, Italian, French, Spanish, German and Portuguese (pick the language under the video). It covers what the platform is, how far your ads reach, how one $20 purchase pays $10, $4 and $2 up three levels in the same transaction, why two and then five qualifying buyers unlock levels 2 and 3, Qualified Start, the Pipeline, LinkSpin and your first week. Members share it from Members > Promo tools > Share the presentation: the link carries your username (instantadpay.com/presentation?ref=<username>), sets you as the sponsor exactly like your invite link, and the page shows you as the person who shared it with a Join button. There is also a short Build Wide video, the first card under Promo tools > Videos, with its own front door ?v=wide on your invite link (the page opens on that video). The examples are illustrations, not promises of income.' },
|
||||
{ id: 'passivedrip', title: 'PassiveDrip earning site', q: ['What is PassiveDrip?', 'Is there a faucet or paid to click?', 'When do coins turn into POL?'], tags: ['passivedrip', 'faucet', 'ptc', 'coins', 'earn'],
|
||||
re: /(passive ?drip|faucet|paid.to.click|\bptc\b|daily bonus|coins? (to|into) pol|2,?000 coins)/i,
|
||||
a: 'PassiveDrip (https://passivedrip.com) is our earning site, listed under More ways to earn on your Earn tab. Claim the faucet, view paid-to-click ads, complete offers and roll the daily bonus for coins. When your balance reaches 2,000 coins ($1) it is paid out automatically in POL to your wallet on Polygon. Open it from the Earn tab with one tap: it signs you in with your InstantAdPay account, no new password. Add your Polygon wallet there so payouts can reach you. What you earn depends on what you do there; nothing is guaranteed.' },
|
||||
{ id: 'spellwheel', title: 'SpellWheel word game', q: ['What is SpellWheel?', 'Is there a daily word puzzle?'], tags: ['games', 'spellwheel', 'word game', 'daily puzzle'],
|
||||
re: /(spell ?wheel|letter wheel|word (game|puzzle)|crossword|daily puzzle)/i,
|
||||
a: 'SpellWheel (https://spellwheel.com, also in Members > Games) is a word game: swipe the letters on the wheel to fill the crossword grid, travel through six cozy places, and solve a new daily puzzle that everyone gets at the same time. Guests play the first place. Signing in with your InstantAdPay account opens the second and saves your progress. The Mountain Lodge and the three places after it, plus the POL for the daily puzzle and streaks, are for Game Pass holders. POL is paid for first clears only: a small taste in the first two places, and the full table from the third place on for pass holders, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. Nothing here is a promise of income.' },
|
||||
{ id: 'warpwares', title: 'Warp & Wares season game', q: ['What is Warp & Wares?', 'How does Warp & Wares pay?', 'What is a sponsor dock?'], tags: ['games', 'warp and wares', 'trade wars', 'season', 'sponsor dock', 'turns'],
|
||||
re: /(warp ?(and|&) ?wares|warpwares|trade ?wars|sponsor docks?|bonus turns|trading season)/i,
|
||||
a: 'Warp & Wares (also in Members > Games) is the network\u2019s 30-day season game in the Trade Wars style. One shared galaxy of 1,200 sectors; every captain gets the same 200 turns a day (reset at midnight Central, never banked) to warp between sectors, buy ore, grain and parts where they are cheap and sell where they are not, haggle, leave fighters and mines to hold sectors, found a base and run a team of up to five with a shared vault. One tap signs you in with your InstantAdPay account. Credits stay in the game; POL is paid for fixed outcomes from a published season budget: the holders of the six landmark sectors and the top traders at each weekly tick (Sundays 9 AM Central), one-time milestones (first base, first garrison, first 100,000 credits traded), and the season-close leaderboard and titles. POL collects in your Warp & Wares balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab). Sponsor markets: docking at one opens a short verified sponsor visit on InstantAdPay and pays bonus turns, the only turns past the daily 200; that is gameplay only, never POL. When the season ends the galaxy resets and the next one starts. Nothing here is a promise of income.' },
|
||||
{ id: 'polminer', title: 'POL Miner mining game', q: ['What is POL Miner?', 'How do Polygon crystals work in POL Miner?', 'What is a supply crate?'], tags: ['games', 'polminer', 'mining', 'polygon crystal', 'supply crate'],
|
||||
re: /(pol ?miner|mining game|digging game|polygon crystals?|pink crystals?|drill boss(es)?|supply crates?)/i,
|
||||
a: 'POL Miner (https://polminer.com, also in Members > Games) is a free dig-down mining game. Dig through the layers of dirt and rock, haul ore up to sell for coins, upgrade your pick, lamp, cart and thruster, and beat a drill boss every 30 m to open the way deeper. The rare glowing pink Polygon crystals pay a random amount of POL the first time you dig each one out, each drill boss pays POL the first time you beat it, and so do your first trips to 50, 100, 150 and 200 m. Coins are for upgrades only and never turn into POL. You can play as a guest right away; sign in with your InstantAdPay account in the game and what you earned as a guest is collected. POL collects in your POL Miner balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab) once it reaches the payout amount. Low on lamp power or coins? Park on the SUPPLY pad: a short sponsor visit opens a supply crate with a full lamp and coins.' },
|
||||
{ id: 'turkeydrop', title: 'Turkey Drop Thanksgiving game', q: ['What is Turkey Drop?', 'How does Turkey Drop pay?', 'What is back on the air in Turkey Drop?'], tags: ['games', 'turkey drop', 'thanksgiving', 'back on the air', 'seasonal'],
|
||||
re: /(turkey ?drop|turkeydropgame|\bwfwl\b|back on the air|catch(ing)? (the )?turkeys)/i,
|
||||
a: 'Turkey Drop (https://turkeydropgame.com, also in Members > Games) is the network’s Thanksgiving game, open Nov 2 through Nov 30 (Central time); its card shows in Members > Games only during the season. The WFWL 98.7 radio helicopter is dropping turkeys over the mall in a 70s cartoon world: swing your net and catch them before they splat. Too many splats and the station pulls you off the air. One tap signs you in with your InstantAdPay account. Score milestones pay POL the first time you reach each one, and the top 3 on the weekly leaderboard win a POL prize. POL collects in your Turkey Drop balance and is sent automatically to the wallet linked to your InstantAdPay account (one free signature on the Wallet tab). Pulled off the air? A short sponsor visit puts you back on the air with an extra life; that is gameplay only, never POL. Nothing here is a promise of income.' },
|
||||
{ id: 'polybreak', title: 'PolyBreak brick breaker', q: ['What is PolyBreak?', 'How do I get another paddle?'], tags: ['games', 'polybreak', 'brick breaker', 'gem'],
|
||||
re: /(poly ?break|brick ?breaker|breakout|arkanoid|purple gem|polygon gem|one more paddle|\bcapsules?\b)/i,
|
||||
a: 'PolyBreak (https://polybreak.app, also in Members > Games) is a free brick breaker in the Amiga arcade style: break a wall of glass jewel bricks with the ball and paddle, catch falling capsules (wider paddle, split ball, lasers, slow ball, catch, a break gate that skips the round, an extra paddle), and catch the purple Polygon gem when it drifts down. Sign in with your InstantAdPay account in one tap. Your first clear of each round pays POL into your PolyBreak game balance, and each gem catch pays a small random amount of POL; the balance is sent to the wallet on your InstantAdPay account automatically at the payout line shown in the game. Out of paddles? A short visit to a member\u2019s page gives you one more paddle on the same round. Share your PolyBreak link from the game: when people you invite play, you earn a share too. Nothing here is a promise of income.' },
|
||||
{ id: 'polywarriors', title: 'PolyWarriors fighting game and NFT warriors', q: ['What is PolyWarriors?', 'How do I get a mint pass?', 'How does fusing warriors work?'], tags: ['games', 'polywarriors', 'nft', 'mint pass', 'duel'],
|
||||
re: /(poly ?warriors?|warrior|mint pass|\bfus(e|ion)\b|arena|duel|cyberpunk|\bnft\b)/i,
|
||||
a: 'PolyWarriors (https://www.polywarriors.com, also in Members > Games) is a free cyberpunk turn-based fighting game, open since Oct 12. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit), and challenge other members to duels that play out while you are away. Your first win over each rival pays POL to the wallet on your InstantAdPay account. Your first warrior mints to your wallet as an NFT on Polygon, free; after that each $5 ad package you buy on InstantAdPay earns a mint pass. Fuse three warriors of the same rarity into one rarer warrior, and trade warriors with other members on the marketplace, settled in POL. Sign in with your InstantAdPay account in one tap. Nothing here is a promise of income.' },
|
||||
{ id: 'clutterhunt', title: 'ClutterHunt hidden-object game', q: ['What is ClutterHunt?', 'How do hints work in ClutterHunt?'], tags: ['games', 'clutterhunt', 'hidden object', 'hints'],
|
||||
re: /(clutter ?hunt|hidden.object|haunted manor)/i,
|
||||
a: 'ClutterHunt (https://clutterhunt.com, also in Members > Games) is a free hidden-object game: search cozy, cluttered rooms for 12 hidden objects plus one sponsored find. This season is the Harvest Farmhouse (Nov 1 to 30: the Farmhouse Kitchen, the Pantry, the Harvest Dining Room, the Barn Loft, the Front Porch and the Cozy Parlor); the Haunted Manor closed with Halloween, and new rooms move in every season, and objects move every time you play. You get 2 free hints a round; after that, a short visit to a member’s page earns another. Sign in with your InstantAdPay account right in the game to save your stars and earn POL: each room pays POL for your first clear and your first 3-star clear every season (Expert rooms pay more), collected in your ClutterHunt balance and sent to the wallet on your InstantAdPay account automatically.' },
|
||||
{ id: 'spooky-doors', title: 'Spooky Doors Halloween game', q: ['What is Spooky Doors?', 'How does the candy ladder pay?', 'How do I buy a costume?'], tags: ['games', 'spooky doors', 'halloween', 'candy', 'costume'],
|
||||
re: /(spooky ?doors?|trick.or.treat|hallowe.?en|costume|candy ladder|\bcandy\b|\bknock)/i,
|
||||
a: 'Spooky Doors (https://spookydoors.com) was the network’s Halloween game. The season ran Oct 4 through Halloween night and closed at midnight Central at the end of Oct 31, so the game and its Games tab card are off for now and the doors no longer pay. The Candy Crunch contest ended with the season: the top 10 candy collectors share 27 POL (10, 6, 4, then 1 each), paid from the game’s wallet after admin sign-off, and a winner without a linked wallet is paid once one is linked on InstantAdPay. Candy ladder POL you earned but had not received (0.10 POL or more) also pays out once your InstantAdPay wallet is linked. Costumes and door packs are no longer sold. Keep an eye on Members > Games for the next seasonal game: Turkey Drop opens Nov 2.' },
|
||||
{ id: 'games-tab', title: 'Games tab and Drip Runner', q: ['Which games pay POL?', 'What is Drip Runner?', 'How do game refuels work?'], tags: ['games', 'drip runner', 'game refuel', 'games tab'],
|
||||
re: /(drip ?runner|games? (tab|page|hub)|play (a |the )?game|games? (that )?pay|(?<!(monthly|my|your|the|a) )refuels?(?!(ing)? ?(day|streak|bonus|window|kit|card|guide)))/i, // 2026-10-24: questions about the Monthly Refuel streak go to the 'refuel' entry, not here
|
||||
a: 'Members > Games lists the network\u2019s games; one tap signs you in. Drip Runner is a runner game: tap to hop, collect gold drips, dodge the bots, clear chapters. The first clear of each chapter drips a little POL into your game balance, which is sent to your wallet once it reaches the payout line shown in the game. When a run ends you can refuel instead of restarting: a short verified visit to a member\u2019s page (or a member video when you have visited them all), up to 20 refuels a day, separate from your regular Earn visits. Refuels are paid for by advertisers, and a share of that funds the POL pool every drip is paid from, so drips depend on the pool and are small. Share your link from the game lobby: when people on your team refuel, a share of what their refuels add to the pool goes to your game balance. Nothing here is a promise of income. The Games tab also has PolHunter, Gem Kingdom (match-3, POL for first clears of stages and bosses), ClutterHunt (hidden objects), SpellWheel (word puzzle), PolyWarriors (cyberpunk fighting, open Oct 12), PolyBreak (brick breaker, opens Oct 13) and Spooky Doors during Halloween; Road Agent opens Thursday Oct 15. The public list of every game, open now and opening next, is https://instantadpay.com/games (add ?ref=yourusername to keep your referral).' },
|
||||
{ id: 'gem-kingdom', title: 'Gem Kingdom match-3 and Crowns', q: ['What is Gem Kingdom?', 'How do I buy Crowns?', 'What do the bosses pay?'], tags: ['games', 'gem kingdom', 'crowns', 'match-3'],
|
||||
re: /(gem ?kingdom|crowns?\b|match.?3|goblin king|ice queen|bog witch|ember dragon|stronghold)/i,
|
||||
a: 'Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon\u2019s Peak, the Sunken Reef and the Shadow Citadel, where the Shadow King waits), earn stars, and rebuild your Stronghold and forge weapons. Chapters 1 and 2 are open to everyone; Chapter 3 needs a free InstantAdPay account; Chapters 4 to 6 need the Royal Charter, a one-time $5 (500 purchased credits, paid credits only), which a Kingdom Pass or an active Game Pass also covers. It pays POL for first clears only: a small taste through chapters 1 to 3 (about 1.2 POL in all), and for Charter holders the real ladder in chapters 4 to 6 (the Ember Dragon 3 POL, the Kraken 5, the Shadow King 7.5), never more in total than the player has paid in. Replays pay nothing, and once the Shadow King is beaten the game pays nothing more until new chapters are added. Rewards go into your game balance and are sent to the wallet on your InstantAdPay account on Polygon once it reaches 0.25 POL. They come from a reward pool funded by a share of Crown purchases, so they pay while the pool has funds (a clear the pool cannot cover pays nothing). Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game\u2019s Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. After a defeat you can also take a free revive by making a short verified visit to a member’s page. In the shop, Specials has a one-time Hero Bundle ($5: a forge weapon, a building level and 60 Crowns), the Kingdom Pass ($10 for 30 days: 10 Crowns a day, a 25-Crown chest each week and the Royal hero looks, no auto-renew) and Hero looks (Halloween looks for 40 Crowns each through Oct 31, yours to keep). Looks are cosmetic only.' },
|
||||
{ id: 'viral-links', title: 'Viral links: ?ref= on any page', q: ['Can any page be my referral link?', 'Do blog links credit me?'], tags: ['referral', 'viral links', 'ref', 'blog'],
|
||||
re: /(viral link|any page.{0,30}(link|referr)|blog.{0,40}(referral|my link|credit)|(referral|invite|my) link.{0,30}(blog|article|any page)|\?ref=|ref=)/i,
|
||||
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
||||
{ re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i,
|
||||
a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
|
||||
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed. A counted refuel of $50 or more (either site) also earns you one free Downline Banners spot (downlinebanners.com, the network banner board), paid by the company and placed for your main wallet, so link a wallet to receive it.' },
|
||||
{ id: 'downline-banners', title: 'Downline Banners (network banner board)', q: ['What is Downline Banners?', 'How do I use my LinkSpin Banner Spin on Downline Banners?', 'How do I sign in to Downline Banners?'], tags: ['downline banners', 'banner board', 'spot', 'banner spin'],
|
||||
re: /(downline ?banners|banner (board|spot)|banner line)/i,
|
||||
a: 'Downline Banners (https://downlinebanners.com) is the Crypto Team Build Network banner board on Polygon. A $5 spot (paid in POL) buys 300 guaranteed views on the board and a place in one global line; when later spots sell, the contract pays the 10 spots above them and the buyer\u2019s sponsor in the same transaction. Nothing is promised: you are paid only when spots sell after yours. Signed in on InstantAdPay? Open its My Spots page and you arrive signed in as your linked wallet, and your share link uses your InstantAdPay username. In My Spots, the "Use a LinkSpin Banner Spin" button puts one of your 468x60 Banner Spins on a spot in two taps, with click tracking under a Downline Banners source on LinkSpin. A $50+ Monthly Refuel earns one free spot. To promote it: Promo tools > Network sites > Downline Banners (or downlinebanners.com/promote) has your links, creatives in every common size, lines, headlines, an email and posts, all carrying your username.' },
|
||||
{ id: 'viral-banner-blitz', title: 'Viral Banner Blitz (network banner loop)', q: ['What is Viral Banner Blitz?', 'How do I post on Viral Banner Blitz?'], tags: ['viral banner blitz', 'vbb', 'banner loop', '125x125'],
|
||||
re: /(viral ?banner ?blitz|vbb|banner loop)/i,
|
||||
a: 'Viral Banner Blitz (https://viralbannerblitz.com) is the network’s shared loop of 125x125 banners. InstantAdPay and LinkSpin members get one free post credit each day they sign in there (Sign in with InstantAdPay works). Real, verified visitors move the loop; a banner that rides out the end has cycled and earns network ad views, which are advertising, not cash. Weekly leaderboards count the visitors you send and the traffic sources they come from, with a prize pot paid in POL to the top three on each board. Your link is viralbannerblitz.com/?ref=your-username. Promo tools > Network sites > Viral Banner Blitz (or viralbannerblitz.com/promote) has your links, creatives, lines, headlines, an email and posts.' },
|
||||
{ id: 'network-sites-kits', title: 'Promo tools: Network sites', q: ['Where are the Downline Banners and Viral Banner Blitz banners?', 'How do I promote the other network sites?'], tags: ['network sites', 'promo kit', 'promote', 'creatives'],
|
||||
re: /(network sites|promo kit|promote (downline|viral|the other|network))/i,
|
||||
a: 'Members > Promo tools > Network sites shows the promo kits of Downline Banners and Viral Banner Blitz with your InstantAdPay username already in every link: your personal links, creatives in 125x125, 468x60, 728x90, 300x250, 160x600, 1200x630 and 1080x1080 (download, copy the URL or copy ready HTML that links to you), 5 short lines, 3 headlines, an email and 2 social posts. Your username works as your sponsor link on those sites even if you never visited them. Each site keeps its own kit, so the copy here is always the current one; the same kit is on each site’s Promote page. Each link also has a tracked version that goes through LinkSpin first (so the network can see which site sent the visit) and then opens the same page with your username; use either one.' },
|
||||
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
|
||||
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
||||
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
||||
{ id: 'five-dollar-friday', title: 'Five Dollar Friday bonus', q: ['What is Five Dollar Friday?', 'What happens on Friday?'], tags: ['five dollar friday', 'bonus credits', 'promotion'],
|
||||
re: /(five dollar friday|5 dollar friday|\$5 friday|friday (bonus|promo|deal|special)|what happens on friday)/i,
|
||||
a: 'Five Dollar Friday: every Friday (Central time), any ad package from $5 up earns +20% bonus credits, added the moment the purchase settles and labelled in your credit log. The page instantadpay.com/friday shows whether it is live right now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack pays its sponsor line in the same on-chain transaction, so when the whole network buys on the same day every line gets paid at once. Since 2026-10-23 a $5+ Friday package also gives you a free 7-day Game Pass (once per Friday, all the games); if that package is the one starting a pass you already ordered, it does not add a second week. Five Fridays in a row earn the Five Fridays badge. Buy under My account > Buy packages.' },
|
||||
// 2026-10-23 conversion pixel (LinkSpin counts, IAP shows): Campaigns > Conversion tracking
|
||||
// 2026-11-07 conversion linkage (reporting only)
|
||||
{ id: 'network-conversions', title: 'Sign-ups and purchases on your click', q: ['I sent someone and they joined, why do I not see a conversion?', 'Do sign-ups on InstantAdPay show in my LinkSpin reports?', 'Does the landing tag track InstantAdPay purchases?'], tags: ['conversion tracking', 'lsclk', 'landing tag', 'reports', 'join', 'purchase'],
|
||||
re: /((sign.?ups?|joins?|purchases?|sales?|conversions?).{0,40}(show|count|track|see|report).{0,30}(linkspin|reports?|landing tag|bridge|on my click)|(bridge|landing) page.{0,40}(click id|lsclk|track|count)|landing tag.{0,40}(instantadpay|purchases?|sign.?ups?|joins?))/i,
|
||||
a: 'People you send to InstantAdPay or LinkSpin count with no goal and no pixel, as long as the click reaches the join page. With the LinkSpin landing tag on your page, your links to either site carry the click id, also inside a redirect link of your own. A spin link or Banner Spin pointed straight at either site carries it too. We keep the click 30 days and store it on the account at sign-up, then their sign-up, wallet link and each package they buy within 30 days of the click count on your click: a sign-up and a wallet once per click, each package on its own with its USD price. See them on Campaigns > Conversion tracking and in LinkSpin under Reports, Conversions, next to your goals. Your own account is never counted, a button that only runs a script cannot carry the click, and people who joined before 2026-11-07 cannot be matched afterwards. This is reporting only: it never changes who a sponsor is or what anyone is paid.' },
|
||||
{ id: 'conversion-tracking', title: 'Conversion tracking (goal pixel)', q: ['How do I track conversions?', 'Can I see which ad brought a sign-up or sale?', 'Where do I put the goal pixel?', 'What is the landing tag?', 'How do I set up conversion tracking on WordPress?'], tags: ['conversion tracking', 'goal pixel', 'landing tag', 'cost per goal', 'aweber', 'getresponse', 'wordpress', 'setup guide'],
|
||||
re: /(conver(sion|t)s?.{0,20}(track|pixel|goal)|track(ing)?.{0,30}(conversions?|sign.?ups?|sales|subscribers|leads)|goal pixel|landing tag|tracking pixel|cost per (goal|lead|sale|sign.?up|conversion)|thank.?you page|lsclk)/i,
|
||||
a: 'Conversion tracking shows which of your ads bring subscribers and sales, not just clicks. It lives in your dashboard under Campaigns > Conversion tracking (https://instantadpay.com/my#campaigns). Three steps: 1) add a goal, like subscriber or sale (a default value is optional); 2) put the landing tag on the page your ad points to; 3) put the goal pixel on your thank-you page. Every click on your ad carries a click id (lsclk=...), and LinkSpin, our sister site, matches each goal to the click: first by the click id still in the address, then the id the landing tag stored, then LinkSpin\'s cookie, and last a 24-hour match on the same connection and browser (the panel says how sure each kind is). Each goal counts once per click, only within 30 days of a real click on your ad, and each campaign shows its goals and its cost per goal (30 days) in credits: the credits that campaign spent in the same 30 days, divided by its goals. Using Aweber or GetResponse? Set the form\'s thank-you (success) page to a page on YOUR site that carries the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL). If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. The Send a test conversion button fires your real pixel in test mode (Last test updates); to check your real thank-you page, add &test=1 to its pixel and open it once. Tests and your own clicks (on your ads, and on your LinkSpin spin links and Banner Spins) never count in your numbers; the card says how many of your own clicks were kept as tests. The step-by-step guide, with copy-paste examples for plain HTML, WordPress, page builders and autoresponder thank-you pages, how to read the report and a troubleshooting checklist: https://instantadpay.com/conversion-tracking' },
|
||||
// 2026-10-23 (Marty: "they need to pay for the slot now to get a place in line"): 6 member slots, then a prepaid line
|
||||
{ id: 'login-ads', title: 'Login ads: slots and the paid line', q: ['How do login ads work?', 'All login ad slots are taken, what now?', 'Can I reserve a login ad slot?', 'Can I cancel my login ad reservation?'], tags: ['login ad', 'login slot', 'reserve', 'queue', 'line', 'refund'],
|
||||
re: /(log ?in.?ads?|sign.?in ads?|log ?in (ad )?(slots?|sponsor)|(reserve|reservation|queue|place in line|waiting list).{0,40}log ?in|log ?in.{0,40}(slots?|reserve|reservation|queue|place in line|waiting list)|reserve (a |the )?(next )?slot)/i,
|
||||
a: 'A login ad is your page shown full screen to members right after they sign in, on the dashboard and in the connected games. A slot is a flat buy: 1,000 purchased credits for 30 days of unlimited sign-in impressions, paid once up front and never charged per day. Earned credits cannot pay for it. Up to 6 member slots run at once, because they all share the same sign-ins. When all 6 are taken you can reserve the next slot in Members > Campaigns: you pay the same price now, and your place in line is first paid, first served. Your 30 days only start when your turn comes, and the form shows your place and an estimated start date in Central time. That date is an estimate, because a slot can end early if its owner archives it. When your ad starts you get a notice on site and an email. Until it starts you can edit the link, image or headline for free, or cancel it and get every credit back. Once it has started, normal slot rules apply. A freed slot always goes to the line first, so a paused slot can only be resumed when a slot is open with nobody waiting.' },
|
||||
// 2026-09-18: sessions were shortened to 4h on purpose. Members WILL ask why they keep being
|
||||
// signed out, and the honest answer reads far better than letting it look like a fault.
|
||||
{ re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
||||
{ id: 'session-4h', title: 'Why am I signed out after 4 hours?', q: ['Why do I keep getting logged out?', 'Why do I have to sign in again?', 'My session expired'], tags: ['session', 'sign in', 'logged out', 'login'],
|
||||
re: /(logged out|log(ged)? me out|signed (me |us )?out|keep.{0,20}(logging|signing) in|session (expired|timed? out)|why.{0,25}(log ?in|sign ?in) again|have to log ?in again|stay logged in)/i,
|
||||
a: 'That is deliberate, not a fault. To keep resources optimised we do not keep anyone signed in longer than 4 hours. After that your session ends and you sign in again with a fresh code - nothing about your account, your credits or your line is affected. You will see the login sponsor ad on the way back in, and that is part of what keeps the free side of the platform paid for.' },
|
||||
{ re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
||||
{ id: 'one-account', title: 'One account per person', q: ['Can I open a second account?', 'Can my wife have an account?', 'Can I refer myself?'], tags: ['account', 'second account', 'duplicate', 'terms', 'qualified start'],
|
||||
re: /(second account|another account|two accounts|multiple accounts|more than one account|duplicate account|new account with|refer myself|self.?refer|sign up (my )?(wife|husband|partner|spouse|kids?|family))/i,
|
||||
a: 'One account per person, and that is in the Terms (https://instantadpay.com/terms). A second account under another email, name or wallet is not allowed, and neither is referring yourself through one. The one sanctioned way to hold more than one position is Qualified Start: extra wallets linked inside your single account, on the Buy packages tab, where they are visible as yours. A family member who genuinely wants to join can join under your link with their own email. Duplicate accounts can be merged or closed and any credits or prizes earned through them are forfeited; payments the contract already made cannot be reversed.' },
|
||||
{ re: /(pyramid|ponzi|scam|scheme)/i,
|
||||
{ id: 'pyramid', title: 'Is this a pyramid or a scam?', q: ['Is this a pyramid scheme?', 'Is this a ponzi or a scam?'], tags: ['pyramid', 'scam', 'legit', 'ponzi'],
|
||||
re: /(pyramid|ponzi|scam|scheme)/i,
|
||||
a: 'Fair question. A pyramid pays for recruiting with no product; here every payment is for real ad delivery, bought by real advertisers, and the whole money flow is public. Check the code and every payout yourself at https://instantadpay.com/contract and https://instantadpay.com/ledger.' },
|
||||
{ re: /(withdraw|cash ?out|payout request|minimum payout)/i,
|
||||
{ id: 'withdraw', title: 'Withdrawals and cash out', q: ['How do I withdraw?', 'What is the minimum payout?', 'How do I cash out?'], tags: ['withdraw', 'cash out', 'payout'],
|
||||
re: /(withdraw|cash ?out|payout request|minimum payout)/i,
|
||||
a: 'There are no withdrawals here, ever. The contract pays your share straight to your own wallet in the same transaction as the purchase. Nothing to request, nothing to wait on.' },
|
||||
// "how much do I earn" used to fall through to the PRICE answer below, because that one
|
||||
// matches "how much do" and this one only caught "how much earn" (Marty, 2026-09-17).
|
||||
{ re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
|
||||
{ id: 'split', title: 'How much do I earn: the split', q: ['How much do I earn?', 'What commission do I get?', 'What is the split on a package?'], tags: ['earn', 'commission', 'split', 'percent', 'levels'],
|
||||
re: /(how (much|do i) earn|how much (do|can|will|would|could|might) (i|we|you|they) (earn|make|get)|what (do|would|will) i (earn|make|get paid)|commission|percent|split)/i,
|
||||
a: 'Every package splits the same way: 50 percent to the direct sponsor, 20 percent to level 2, 10 percent to level 3, 20 percent to the platform. Those numbers are constants in the contract and cannot be changed. The package ladder is on the home page. No income is promised; nobody earns unless real ad buying happens.' },
|
||||
{ re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
|
||||
{ id: 'network-rate', title: 'Network views and partner visits cost less than views here', q: ['Do network views use my credits?', 'How much do Network Ad Space views cost?', 'Why are network views cheaper?'], tags: ['network views', 'network ad space', 'syndication', 'passivedrip', 'partner visits', 'credits', 'rate'],
|
||||
re: /((network (views?|ad space)|syndicat\w*|partner (sites?|visits?)).{0,60}(credits?|charge[ds]?|cost|spend|balance|budget|free|pay|rate|cheap)|(credits?|charge[ds]?|cost|spend|balance|budget|pay|rate).{0,60}(network (views?|ad space)|syndicat\w*|partner (sites?|visits?)))/i,
|
||||
a: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs less: for a banner, 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. Text ads go further still: since November 12, 10 network views of a text ad cost what 1 view here does. So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/4 rate)" or, for text ads, "Network views (1/10 rate)" lines in Credit activity.' },
|
||||
{ id: 'balance-rule', title: 'Why my balance went down', q: ['Why did my balance go down?', 'Where did my credits go?', 'What does In live campaigns mean?'], tags: ['balance', 'credits', 'campaigns', 'credit activity'],
|
||||
re: /(balance (went|going|keeps going) down|credits? (disappear|missing|gone|dropping|went down|ticking)|why (is|did) my (balance|credits)|in campaigns|set aside|reserved credits|available to spend)/i,
|
||||
a: 'One rule: your balance is what is NOT committed to a live campaign. When you start a campaign its whole budget is set aside right then (earned credits first, then purchased), so your Available number drops once and then sits still while the ad runs. The budget spends down inside that campaign in Members > Campaigns, where you can see delivered views, network views and what is left. The dashboard shows Purchased available, Earned available and In live campaigns as three separate numbers; a paused campaign keeps its unspent budget set aside so it can resume. Nothing is lost when a balance reads low while a campaign is live. Purchased credits live on the blockchain; if we ever refund or credit purchased money it shows under Purchased as "credited to you" and spends like a purchase, login ads included. Earned credits fund every format except login ads. Two formats are flat buys paid in full when booked: featured links (sold by the day) and verified-visit packs. Adding credits to a featured link does nothing, so its row offers Extend run instead, which books more days at the daily rate; a visit pack offers Buy more visits. Every credit that comes in or goes out is listed with its reason under Members > Campaigns > Credit activity (also linked from Earn credits): sign-in bonus, daily claim, video watched, verified visit, campaign buys, views delivered per day, grants and refunds. Check it before assuming credits went missing.' },
|
||||
{ re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i,
|
||||
{ id: 'payment-trace', title: 'Why someone was not paid: trace a payment', q: ['Why did my sponsor not get paid?', 'I missed a payment', 'How do I trace a payment?'], tags: ['payment trace', 'missed payment', 'earnings', 'pass-up'],
|
||||
re: /(why (didn'?t|did not|hasn'?t|has not) (my sponsor|i|he|she|they|.{1,30}) (get|got|been) paid|didn'?t get paid|not get paid|missed (a |the )?(payment|commission)|trace (a )?payment|payment trace|who got paid)/i,
|
||||
a: 'Every purchase and every share is on the chain, and you can read it yourself: open Members > Earnings > Trace a payment, enter the member number or username (yourself, anyone up to 3 levels below you, or your own uplines), and each purchase they were part of is laid out level by level: who was paid, who was skipped and why. The three usual answers: the person had not unlocked that level when the purchase settled (level 2 needs 2 qualifying $20+ buyers, level 3 needs 5, and qualification never applies backwards); the buyer used Qualified Start, so the purchase came from a linked wallet whose sponsor is the buyer\'s own main position, which means level 1 went to the buyer themselves; or the person\'s payouts were not switched on. Skipped shares pass up to the next qualified person, never to nobody.' },
|
||||
{ re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i,
|
||||
{ id: 'walk-up', title: 'Unactivated sponsor: the walk-up rule', q: ['What if my sponsor has not switched on payouts?', 'Why did my purchase go to the company position?'], tags: ['sponsor', 'walk up', 'payouts', 'activation'],
|
||||
re: /(sponsor (never|hasn'?t|has not|didn'?t|did not|won'?t|hasnt|didnt) (switch|turn|activat|link)|(payouts?|wallet) (not |aren'?t |isn'?t |never )?(switched|turned|set) on|unactivated sponsor|not activated sponsor|routed past|walk(ed|s)? up|goes? to the company|company position)/i,
|
||||
a: 'Your purchase never waits on your sponsor. If the person who referred you has not linked a wallet and switched on payouts when you buy, the site walks up your sponsor line to the first person who is activated with payouts on and the purchase goes through under them; if nobody in the line is ready it goes under the company position. You see a one-line note on the Buy tab and carry on. For the sponsor it is permanent: the contract locks a buyer to whoever was paid at the first purchase, so that referral moves to the upline who was paid and they cannot earn from that wallet later. They get a message saying so, and the upline gets one too. Two minutes on the Wallet tab prevents it.' },
|
||||
// PIF + the holding tank. Asked together often ("should I pif someone from the tank"),
|
||||
// and the honest answer is that the order matters: you cannot PIF someone still in the
|
||||
@@ -53,72 +195,196 @@ const CANNED = [
|
||||
// ("should I fund their first package", "can I buy it for them"). It needs BOTH a
|
||||
// paying verb AND an explicit for-someone-else phrase, so ordinary pricing questions
|
||||
// like "which package should I buy" are not stolen (Marty, 2026-09-17).
|
||||
{ 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. 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.' },
|
||||
{ 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.' },
|
||||
{ re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
|
||||
{ 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: 'who-invited', title: 'Who invited you? (naming your sponsor)', q: ['How do I add the person who invited me?', 'I joined without a link, can I name my sponsor?', 'What is the Who invited you card?'], tags: ['who invited you', 'invited', 'holding tank', 'no sponsor', 'sponsor link'],
|
||||
re: /(who invited|invited (me|by)|joined without a (link|sponsor)|forgot (the|my|to use).{0,12}(link|sponsor)|(add|name|set|enter|pick|choose) (my |a )?sponsor|nobody invited)/i,
|
||||
a: 'If you joined without a sponsor link, your Overview shows a Who invited you? card. Type the username of the person who invited you, confirm it, and they become your sponsor, here and on LinkSpin, and they get a notice. Do it before you switch on payouts or buy, because your sponsor locks on the contract at that point. It has to be a real member: not you, not someone in your own line, and not someone who has not switched on payouts with nobody above them who has (ask them to switch on first). Once you have a sponsor or a member number the card goes away. Nobody invited you? Tap Nobody invited me and stay in the holding tank; a small link on the Overview brings the card back while you are still there. Nothing on the site waits for your answer. New sign-ups cannot be adopted by hand for their first 24 hours, so you have a day to tell us before a member can pick you up.' },
|
||||
{ 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. If someone invited you, type their username on the Who invited you? card on your Overview and this ends right away. The contract locks your sponsor for good the first time you switch on payouts or buy, so switching on payouts on its own waits until a real member picks you up. Buying is never held: you can buy a package any time, and with no sponsor it goes through under the company position. 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. If you already have a sponsor on LinkSpin with the same email or wallet, you are placed under them right away.' },
|
||||
{ id: 'tank-activate-link', title: 'Switch on payouts after you were picked up (one-tap link)', q: ['I got a Switch on payouts link from my new sponsor', 'How do I switch on payouts after I was adopted?'], tags: ['holding tank', 'switch on payouts', 'adopted', 'one tap', 'reminder'],
|
||||
re: /((switch on|turn on|activate) payouts? (link|email|reminder)|activate=1|(picked (me )?up|adopted( me)?).*(switch on|activate)|one.?tap.*(payouts|activate)|reminder.*switch on payouts)/i,
|
||||
a: 'When a member picks you up from the holding tank (or the site assigns you to one after 24 hours), the chat and the email you get both carry a Switch on payouts link: instantadpay.com/my?activate=1#wallet. Tap it, sign in if asked, and your wallet opens with your new sponsor already filled in. It is one free transaction, no package needed, and it locks that sponsor in as yours on the contract. No wallet linked yet? The same link asks you to link one first (one free signature) and then carries on. On a phone without a wallet browser, the wallet picker opens and hands you to your wallet app to confirm. Nobody, not even the site, can switch payouts on for you: it has to come from your own wallet. If you have not done it 24 hours after you were picked up you get one reminder email (and your sponsor gets a note to give you a nudge), and one last reminder at 72 hours. They stop as soon as your payouts are on or you buy a package.' },
|
||||
{ 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 once they have been here 24 hours. A new sign-up shows an Opens in badge until then, with no Adopt button, so they have a day to tell us who invited them (the 24-hour safety net for wallet-linked members still runs on its own clock). 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 up to 10 people from the tank at one time (counting the ones who have not switched on payouts yet) 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 10 people held from the tank who have not switched on payouts yet, 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.' },
|
||||
{ re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i,
|
||||
{ id: 'free-member', title: 'What free members earn', q: ['What do free members get?', 'Do I have to buy anything?', 'Credits or POL?'], tags: ['free member', 'credits', 'pol', 'activation'],
|
||||
re: /(free member|without (a )?wallet|do i (have to|need to) buy|earn (in )?credits|credits (vs|versus|or) pol|earn pol|get paid in)/i,
|
||||
a: 'Free members earn ad credits: view ads, watch videos, make verified visits, read inbox ads, sign in daily. Credits buy your own ads and are never cashed out. POL, the real crypto, is paid to your wallet by the contract when your referrals buy packages, once you are activated: the $20 starter package (2,000 credits to advertise with) and payouts switched on from the Wallet tab. Your own $20 purchase also makes you count as a qualifying buyer for your sponsor, and two or five such buyers in your own line open levels 2 and 3 for you.' },
|
||||
{ re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
|
||||
{ id: 'join', title: 'How to join; do I need a wallet?', q: ['How do I join?', 'Do I need a wallet?', 'Do I need crypto experience?'], tags: ['join', 'sign up', 'wallet', 'email'],
|
||||
re: /(need (a )?wallet|crypto experience|metamask|how (do i|to) join|sign ?up|register)/i,
|
||||
a: 'Join free with just your email at https://instantadpay.com/my, no wallet and no password needed. Your wallet only comes out when you buy a package or switch on payouts, and the site walks you through it.' },
|
||||
{ re: /(referral link|invite link|share link|refer)/i,
|
||||
{ id: 'referral-link', title: 'My referral and invite links', q: ['Where is my referral link?', 'How do I invite people?'], tags: ['referral', 'invite link', 'promo tools', 'angles'],
|
||||
re: /(referral link|invite link|share link|refer)/i,
|
||||
a: 'You get your share link the moment you sign in, free members included. Open Members > Promo tools: the "Your links" block at the top lists your invite link plus five angle versions (Instant, Ad spend, Free, Ledger, Two), each with a note on who it is for and Copy and Share buttons. They are the same link with a code on the end, so every join and purchase credits you; only the first page the person sees changes. One tip: switch on payouts (one free wallet step in Members) before your people start buying, because the contract locks each buyer to their sponsor at their first purchase.' },
|
||||
{ re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i,
|
||||
a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' },
|
||||
{ re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
|
||||
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, and an Objection handling bank with the truth plus a ready-to-send reply. Everything is personalized with your invite link.' },
|
||||
{ re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||
{ id: 'banner-image', title: 'Banner image link and sizes', q: ['Why was my banner image refused?', 'What banner sizes are there?', 'How do I upload a banner?'], tags: ['banner', 'image', 'sizes', 'campaign'],
|
||||
re: /(banner (image|url|link|size|creative|file)|image (url|link|field)|broken (banner|image)|upload (a |my |the )?(banner|image|creative)|(png|jpg|jpeg) link|which sizes?)/i,
|
||||
a: 'The image field on a banner campaign needs a direct link to the picture itself, one that ends in .png, .jpg, .gif, .webp or .svg, or an upload. A web page link (your join page, an image-hosting page) is refused, because it would show a broken banner. Easiest source: Promo tools > Banners, pick the size you want and tap Copy image URL. Game and BixPay banner links in Promo tools are short (for example https://instantadpay.link/b/turkeydrop/728x90.png) so they fit the image fields on exchanges and safelists that cut long links. Sizes are the standard ad sizes (728x90, 300x250, 160x600, 320x50 and more); the campaign form asks for the size too. Banner and text ads also run out on the wider network.' },
|
||||
{ id: 'themes', title: 'Light and dark themes', q: ['Is there a light mode?', 'How do I switch themes?'], tags: ['theme', 'dark mode', 'light mode', 'appearance', 'accessibility'],
|
||||
re: /(dark ?mode|light ?mode|dark theme|light theme|night mode|themes?|appearance|too bright|too dark|high contrast)/i,
|
||||
a: 'InstantAdPay has light and dark themes (added 2026-11-02). In the member area use the Light, Dark or Auto control in the header, or the Appearance card on your Profile. Dark is the original look, Light is a bright green-grey workspace with the same layout, and Auto follows your device setting and switches with it. Your choice is saved on your account, so it follows you to any device once you sign in, and it applies to the public pages and your wall too. Nothing changes until you pick one. Both themes pass the accessibility contrast standard for text.' },
|
||||
{ id: 'promo-tools', title: 'Promo tools', q: ['What is in Promo tools?', 'Where are the email swipes and banners?'], tags: ['promo tools', 'social posts', 'swipes', 'banners', 'objections'],
|
||||
re: /(promo tools?|social posts?|email swipes?|banner kit|download banners?|promo banners?|text a friend|objection|share buttons?)/i,
|
||||
a: 'Promo tools (Members > Promo tools) has pill menus for each kit: Social posts (X, Facebook, LinkedIn, Telegram or WhatsApp, with post and share buttons), Text a friend (SMS-sized messages with Text it, WhatsApp, Telegram and Copy), Email swipes (short, standard, long, follow-up), Banners (every standard ad size plus square, story and Telegram sizes, download or copy URL), your Banner wall link, an Objection handling bank with the truth plus a ready-to-send reply, and a Games tab with a kit for every network game plus the EnjoyBestGames arcade (enjoybestgames.com, hundreds of free games; only the featured Polygon games pay, and your ?r= link cookies visitors as your referral for 30 days). Everything is personalized with your invite link.' },
|
||||
{ id: 'trust-drain', title: 'Trust Wallet "drain your wallet" warning', q: ['Trust Wallet says this transaction will drain my wallet', 'My wallet blocked the purchase'], tags: ['trust wallet', 'drain', 'wallet warning', 'walletconnect'],
|
||||
re: /(drain (my|your) wallet|stop and go back|trust wallet.*(warn|block|red)|wallet (warning|blocked))/i,
|
||||
a: 'That red "this transaction will drain your wallet" screen is the wallet\'s own safety rule, not a problem with the purchase: Trust Wallet blocks any transaction that spends most of the POL in the wallet. Ways through: buy a smaller package first, add some POL so the purchase is well under half the balance, or connect a different wallet (MetaMask, Phantom, SafePal have no such block). Extra POL always stays yours. If the next try says WalletConnect disconnected, open Wallet, tap Disconnect, then Connect again. Phantom, SafePal and MetaMask do not have the hard block.' },
|
||||
{ re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
|
||||
{ id: 'prohibited-content', title: 'What content is not allowed?', q: ['What content is not allowed?', 'Can I put a link in my bio?', 'Can I advertise a casino or CBD?'], tags: ['prohibited content', 'rules', 'bio links', 'gambling', 'adult', 'link farm'],
|
||||
re: /(not allowed|prohibited|forbidden|banned (content|words|niches?)|content (rules|policy)|what (content|ads|niches?) (is|are) (not )?(allowed|ok|accepted)|can i (post|promote|advertise|run) .*(casino|gambling|betting|adult|porn|cbd|weed|pharma|guns?)|link ?farm|backlinks?|links? in (the |my |your )?bio|bio (link|url)|why was my (bio|profile|link) (refused|rejected|blocked))/i,
|
||||
a: 'Not allowed anywhere on InstantAdPay (ads, campaigns, line banners, wall offers, bios and social links): gambling, casinos, betting, lotteries and sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing and counterfeit goods; misleading financial promises. The bio is text only: no links and no domain names, links go in the social fields in Profile. Your bio, avatar and social links show on your public wall once you have bought a package; free accounts show only their name and the line’s ads there. Accounts created just to place links in profile fields (link farming) are removed without notice, with their profile text. The full list is in the Terms, section 8: https://instantadpay.com/terms#prohibited' },
|
||||
{ id: 'wall', title: 'Your banner wall and its three positions', q: ['How does my wall work?', 'How do I own wall positions 2 and 3?'], tags: ['wall', 'banner wall', 'positions'],
|
||||
re: /(wall (page|slots?|positions?)|banner wall|my wall|three (ads|slots) on (my|the) wall)/i,
|
||||
a: 'Your wall (instantadpay.com/wall/yourname) shows three ads. Position 1 is always your line banner. Positions 2 and 3 show your upline (or InstantAdPay) until you earn them: 2 qualifying buyers ($20 or more) make position 2 yours, 5 make position 3 yours, so a fully qualified member owns the whole page with their own links and offers. Set them in Profile > Your wall; an unlocked slot you leave empty keeps showing your upline until you fill it.' },
|
||||
{ re: /(solo ad|inbox ad|inbox)/i,
|
||||
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members — give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
|
||||
{ re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i,
|
||||
{ id: 'solo-ads', title: 'Solo ads and the inbox', q: ['What is a solo ad?', 'How do inbox reads pay?'], tags: ['solo ad', 'inbox', 'campaigns'],
|
||||
re: /(solo ad|inbox ad|inbox)/i,
|
||||
a: 'Solo ads are full-message ads delivered straight into member inboxes on-site. Compose one under Campaigns (pick "Solo ad"): subject line, a rich-text message with a real editor (bold, headings, lists, links), an attached image or video if you want one, and a call-to-action button with your own label. You pay 5 credits per guaranteed delivery, 10 deliveries minimum. On the reading side, your Inbox section collects solos from other members: give one a real read (10 seconds on the open message) and claim 2 credits, up to 5 rewarded reads a day. You never receive your own solo.' },
|
||||
{ id: 'sponsor', title: 'Who is my sponsor; wrong sponsor', q: ['I joined under the wrong sponsor', 'Who is my sponsor?', 'Can I change my sponsor?'], tags: ['sponsor', 'invite link', 'last touch'],
|
||||
re: /(wrong sponsor|who is my sponsor|which sponsor|sponsor (cookie|link|credit)|clicked (someone|another|two).*link|last (link|click)|first (link|click|touch)|change (my )?sponsor)/i,
|
||||
a: 'The invite link you opened most recently sets your sponsor, and the join page shows it: "Personal invitation from @name". It locks the moment you create your account, so opening someone else\'s link afterwards changes nothing, and your first purchase binds you to that same sponsor on the contract. If you have not joined yet and the page shows the wrong name, open the right person\'s link and it updates. If you already joined under the wrong sponsor by mistake, message support before your first purchase and the admin can move you.' },
|
||||
{ re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
|
||||
{ id: 'sponsor-chat', title: 'Sponsor Chat', q: ['How do I message my sponsor?', 'Can I chat with my team?'], tags: ['chat', 'sponsor', 'messages'],
|
||||
re: /(chat|message (my )?(sponsor|upline|team|downline)|talk to (my )?sponsor|contact (my )?sponsor|ask (my )?sponsor|reach (my )?sponsor)/i,
|
||||
a: 'Yes, Members has a two-way Sponsor Chat. You can message your direct sponsor for help (from Overview or the chat button), and sponsors can message anyone in their line. If they are online you chat live; if not, your message waits in their on-site inbox and they get an email. Sponsors can set themselves unavailable in Profile (you can still leave a note, they just reply later) and mute a member if needed. It is separate from the once-a-day team broadcast.' },
|
||||
{ re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
|
||||
{ id: 'earn-credits', title: 'Earning credits: the daily set, videos, visits', q: ['How do I earn credits?', 'How does the daily ad set work?', 'How much is the daily claim?'], tags: ['earn credits', 'daily set', 'claim streak', 'videos', 'visits'],
|
||||
re: /((view|watch|see).{0,12}ads?|earn.{0,12}credits?|daily (set|ads|views))/i,
|
||||
a: 'In the Earn credits section of Members, each ad in the daily set opens full screen in its own tab, showing the advertiser\'s real site. A countdown runs while you watch (it pauses if you leave the tab), then you pass a quick click-the-icon check and the view counts. Finish the set, claim your daily credits (5 on day one, 7 on day two, 10 from day three, 25 on every 7th day in a row), then keep going with videos (up to 8 a day), verified visits (up to 20 a day) and inbox reads (up to 5 rewarded a day). A separate sign-in bonus pays 5 credits on your first sign-in each day, rising by one per consecutive day up to 10. Earned credits fund every campaign format except login ads. You never see your own ads, and viewer rewards are credits, never cash.' },
|
||||
{ re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
|
||||
{ id: 'featured', title: 'Featured links', q: ['How do featured links work?', 'How do I extend a featured run?'], tags: ['featured links', 'campaigns', 'extend run'],
|
||||
re: /(featured (link|strip|ad|run)|extend run|book (a )?featured)/i,
|
||||
a: 'Featured links run in the strip at the top of every member\'s Overview. Book one under Campaigns for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead; at most 10 links share any day. It is a flat buy, paid in full when booked, and the row shows days left and "runs through" a date. To keep it going use Extend run on the row, which books more days at the same rate; adding credits does not add days. Views (one per viewer per hour) and clicks are counted on the row.' },
|
||||
{ re: /(verified visit|visit pack|buy visits|visits campaign)/i,
|
||||
{ id: 'verified-visits', title: 'Verified-visit packs', q: ['How do verified visits work?', 'How do I buy visits?'], tags: ['verified visits', 'visit pack', 'campaigns'],
|
||||
re: /(verified visit|visit pack|buy visits|visits campaign)/i,
|
||||
a: 'A verified-visit pack sends real members to your site: each one opens it in a new tab, stays at least 8 seconds and passes a check, and no member counts twice. It costs 3 credits per visit, minimum 20 visits, paid in full when you create it, then it fills over time (each member can do at most 20 visits a day). The row shows "N of M visits delivered" and Buy more visits adds to the pack. Members earn 1 credit per verified visit.' },
|
||||
{ re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
|
||||
{ id: 'overview-video', title: 'What is InstantAdPay? The four-minute overview', q: ['What is InstantAdPay?', 'How does this work?', 'Is there an overview video?'], tags: ['overview', 'video', 'what is'],
|
||||
re: /(overview video|four.minute|4.minute|what is (this|instantadpay)|explain (the )?platform|how does (this|it) work)/i,
|
||||
a: 'The quickest answer is the four-minute overview video: it is the first card on Members > Training and on the home page at https://instantadpay.com/#overview-video. It covers what the platform is, what free members get, the campaign formats, how the contract splits every purchase, wallet and payouts, Qualified Start, the payment trace and the tools for building a line.' },
|
||||
{ re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i,
|
||||
a: 'Five packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' },
|
||||
{ re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
|
||||
{ id: 'packages', title: 'Packages and prices', q: ['How much are the packages?', 'Which package should I buy?', 'What do I get for my money?'], tags: ['packages', 'price', 'credits', 'qualification'],
|
||||
re: /(\b(price|prices|pricing|costs?)\b|how much (is|are|does|do)|package (price|cost|size)|which package|what packages|what do i get|what am i buying|should i (buy|get|start with|go with)|worth (buying|getting|it to buy))/i,
|
||||
a: 'Seven packages, priced in dollars and settled in POL at the live rate when you buy: Micro $5 for 500 credits, Starter $10 for 1,000, Activation $20 for 2,000, Builder $50 for 5,500, Growth $100 for 12,000, Leader $250 for 32,500, Elite $500 for 70,000. One credit is one cent of ad delivery in any format. Packages of $20 or more count toward qualification, and every purchase is split by the contract in the same transaction: 50 percent to your sponsor, 20 to level 2, 10 to level 3, 20 to the platform. The live POL prices are on the home page and the Buy packages tab.' },
|
||||
{ id: 'credits', title: 'What ad credits are', q: ['What is a credit worth?', 'What are ad credits?'], tags: ['credits', 'ad formats', 'impressions'],
|
||||
re: /(what (is|are) (a |an )?(ad )?credits?|credits? (worth|value|mean)|one credit|impression|cpm)/i,
|
||||
a: 'Packages mint ad credits on-chain, and every new member also gets a small batch of welcome credits just for joining. One credit is one cent of ad delivery: banners and text ads (also syndicated to the wider network), full-screen login ads, watch-to-earn video ads, solo ads into member inboxes, featured links in the strip on every Overview, and verified-visit packs, all managed from Members > Campaigns. Only your campaigns can spend your credits.' },
|
||||
{ re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
||||
{ id: 'pol-only', title: 'Which coin and network: POL on Polygon', q: ['Which crypto do you use?', 'What network is this on?', 'Do you accept other coins?'], tags: ['pol', 'polygon', 'crypto', 'network'],
|
||||
re: /(which|what) (crypto|coin|token|currency|chain|network)|paid in what|get paid in|supported (crypto|coins|wallets)|do you (support|accept)/i,
|
||||
a: 'One coin, one network: POL, the native coin of Polygon. You pay for packages in POL and every payout arrives as POL in your own Polygon wallet, in the same transaction. No other coins, tokens or chains are used. Any Polygon wallet works (MetaMask, SafePal, Phantom, Coinbase Wallet), and you can buy POL with a card from Buy packages if you have never held crypto.' },
|
||||
{ re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
||||
{ id: 'wallets', title: 'Which wallet, and buying POL with a card', q: ['Which wallet should I use?', 'How do I buy POL with a card?', 'I have never owned crypto'], tags: ['wallet', 'metamask', 'safepal', 'phantom', 'moonpay', 'buy pol'],
|
||||
re: /(which wallet|what wallet|best wallet|recommended wallet|set ?up (a )?wallet|buy (pol|crypto|polygon)|get (pol|crypto)|moonpay|card to crypto|no crypto|never (had|held|owned) crypto)/i,
|
||||
a: 'Preferred wallets: MetaMask (recommended, and the one for Qualified Start extra accounts), Phantom (turn Polygon on first: Settings, Active Networks), SafePal or Coinbase Wallet. Trust Wallet works but blocks a purchase that spends most of the POL in it, so keep about double the package cost there. To buy POL with a card: connect your wallet, open Buy packages, tap "Buy POL with a card". MoonPay opens with POL on Polygon and your own address filled in; pay by card, Apple Pay or Google Pay (first time needs an ID check, minimum order around $30), the POL lands in your wallet in minutes, then buy the package. The full step-by-step guide is in Training: Wallets and buying POL (https://instantadpay.com/wallets, members only).' },
|
||||
{ re: /(safe|trust|rug|run away|company disappear)/i,
|
||||
{ id: 'safe', title: 'Is it safe? What if the company disappears?', q: ['Is this safe?', 'Can you run away with the money?', 'What if the company disappears?'], tags: ['safe', 'contract', 'trust', 'custody'],
|
||||
re: /(safe|trust|rug|run away|company disappear)/i,
|
||||
a: 'The money never touches us. An immutable contract splits every purchase in the same transaction, holds zero balance, and has no pause switch or upgrade path. Read the plain-language review and the verified source at https://instantadpay.com/contract.' }
|
||||
];
|
||||
|
||||
// CANNED + the FAQ seeds, in the shape kb.js stores (order keeps the first-match-wins sequence)
|
||||
function seeds() {
|
||||
return CANNED.map((c, i) => ({ id: 'c-' + c.id, title: c.title, questions: c.q || [], answer: c.a, tags: c.tags || [], pattern: c.re.source,
|
||||
handoff: !!c.handoff, order: (i + 1) * 10, source: 'canned' })).concat(kbSeed.FAQ);
|
||||
}
|
||||
|
||||
// ---- facts for the AI fallback ----
|
||||
function systemPrompt() {
|
||||
// PASS TIERS (2026-10-22): the passes above the weekly Game Pass (Explorer, Champion, Sovereign, Legend; names from gamepass.js
|
||||
// TIER_DEFS). While sovTiers is off the assistant only says they are coming soon; once on, it quotes the live prices and contents.
|
||||
// BONUS HEROES (2026-11-05): sold one time; while heroSales is off the assistant says they are coming soon, once on it quotes the live prices
|
||||
function heroesFact() {
|
||||
let h = null; try { h = HERO_SALE ? HERO_SALE() : null; } catch (e) { h = null; }
|
||||
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Kestrel is FREE for every player once a hero in the party reaches level 20 (since 2026-11-14) and is NOT sold; anyone who bought her before keeps her. Valda, Morag and Roland are sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
|
||||
if (!h || !h.sale) return '- BONUS HEROES (COMING SOON, not on sale yet): ' + base + ' Never quote their prices or a launch date while they are not on sale.\n';
|
||||
const each = (h.rows || []).map(r => r.name + (r.freeAt ? ' free at level ' + r.freeAt + ' (not sold)' : r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
|
||||
return '- BONUS HEROES (ON SALE, Members > Games > Game Pass card at https://instantadpay.com/my#games): ' + each + (h.bundle && h.bundle.names.length ? '; the bundle ' + h.bundle.names.join(', ') + ' $' + h.bundle.usd : '') + '. ' + base + ' The bundle is heroes only (no level cap change).\n';
|
||||
}
|
||||
function passTiersFact() {
|
||||
let t = null; try { t = PASS_TIERS ? PASS_TIERS() : null; } catch (e) { t = null; }
|
||||
const soon = '- MORE GAME PASSES: monthly and yearly passes for Shards of Valor are COMING SOON and are not on sale yet. If someone asks about them (or about an Explorer, Champion, Sovereign or Legend pass, or a monthly or yearly pass), say they are coming soon and that the $5 weekly Game Pass is the pass on sale today. Never quote their prices, contents or a launch date.\n';
|
||||
if (!t || !t.on) return soon;
|
||||
const rows = (t.rows || []).filter(r => r.sale);
|
||||
if (!rows.length) return soon;
|
||||
return '- GAME PASS TIERS (on sale, Members > Games > Game Pass at https://instantadpay.com/my#games): beside the $5 weekly Game Pass, ' + rows.map(r => r.name + ' $' + r.usd + ' for ' + r.days + ' days (' + 'paid by the $' + r.usd + ' package, and the member keeps that package’s ad credits): ' + r.perks.join('; ')).join(' | ')
|
||||
+ '. Each higher pass includes everything below it. Every pass is a Game Pass in every network game with the SAME daily POL caps (1.50 / 5 POL): a higher pass never pays more POL. Passes run side by side, each with its own end date; no auto-renew; buying again adds the pass length from its end date (or from now if it ended). Every pass is paid by a NEW package purchase of at least its price, made after tapping Get on that pass (since 2026-10-25 every pass price IS a one-click package amount: $5, $20, $50, $100, $250, so the right package is exactly the price); the pass starts when it settles, the sponsor and team are paid from the package as usual, and the member keeps the package credits for ads. Credits already held never buy a pass. Nothing earned in a game is taken away when a pass ends.\n';
|
||||
}
|
||||
// SYNDICATED RATE (Marty, 2026-10-27, approved 4:1) follows ads rates().synRateDivisor; the canned answer quotes 1/4, so
|
||||
// the fast path rewrites it when the admin picks another N, and the AI fact always states the live N.
|
||||
const SYN_N = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisor()) || 1)); } catch (e) { return 4; } };
|
||||
// text ads have their own N since 2026-11-12 (Marty: 1/10); the canned answer quotes 4 and 10
|
||||
const SYN_T = () => { try { return Math.max(1, Math.floor(Number(require('./ads').synRateDivisorText()) || 1)); } catch (e) { return 10; } };
|
||||
const netRateAnswer = n => n === 1 ? 'Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery uses credits at the same rate as views and visits here.'
|
||||
: 'Views and visits here on InstantAdPay use credits at the normal rate. Your banner and text ads also run on Network Ad Space, and visit packs also get visits from partner sites like PassiveDrip. That delivery costs 1/' + n + ' of the rate: ' + n + ' network views of a banner cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack.' + (SYN_T() !== n ? ' Text ads: ' + SYN_T() + ' network views cost what 1 view here does.' : '') + ' So your budget goes further, and every credit still buys real delivery. You see network views and partner visits in Members > Campaigns, and network charges show as "Network views (1/' + n + ' rate)" lines in Credit activity.';
|
||||
function synFact() { const n = SYN_N(); return '- NETWORK RATE (live, Marty 2026-10-27): delivery ON instantadpay.com is charged at the normal rate. Network Ad Space impressions of BANNER ads cost 1/' + n + ' of the on-site rate (' + n + ' network views = the price of 1 view here; credit log line "Network views (1/' + n + ' rate)"); TEXT ads have their own network rate since 2026-11-12 (Marty): 1/' + SYN_T() + ' of the on-site text rate (' + SYN_T() + ' network views = the price of 1 view here, so 1 credit = ' + (10 * SYN_T()) + ' network text views at the default 1 credit per 10 views; credit log line "Network views (1/' + SYN_T() + ' rate)"), going forward only; and PassiveDrip partner visits use up 1 visit of a pack per ' + n + ' partner visits. The budget is the limit, burns follow what was charged, nothing charged before 2026-10-27 changed. AdRevLinks popups and DripOffers clicks are not charged. Game refuels and Spooky Doors are charged as normal visits.' + String.fromCharCode(10); }
|
||||
// the refuel fact follows the refuelStreak switch: while it is off the assistant says it is not live yet (2026-10-24)
|
||||
let REFUEL_ON = () => false;
|
||||
// POL Miner (2026-10-28) follows site config gamesLive: until 'polminer' is in it the assistant only says it is coming soon
|
||||
let GAME_LIVE = () => false;
|
||||
// BixPay (2026-10-29) follows site config bixpayLive: until it is on the assistant only says the card is coming soon
|
||||
let BIX_LIVE = () => false;
|
||||
const bixLive = () => { try { return !!BIX_LIVE(); } catch (e) { return false; } };
|
||||
const isBixId = id => /^(c-)?bixpay(-[a-z]+)?$/.test(String(id || ''));
|
||||
const BIX_SOON_ANSWER = 'A BixPay Visa card for spending POL is coming to InstantAdPay soon: a self-custody wallet with a Visa card, made by BIX, a separate company. It is not switched on here yet. When it is, it shows up on your Wallet tab, with a partner-link field in your Profile and a guide at instantadpay.com/bixpay, and the release notes will say so.';
|
||||
function bixFact() { return bixLive()
|
||||
? '- BIXPAY VISA CARD (LIVE, 2026-10-29): BixPay = a self-custody wallet + Visa card made by BIX, a SEPARATE company (not InstantAdPay). The member sends USDT or USDC to the BixPay wallet on Polygon, loads the card, spends wherever Visa is accepted incl. Apple Pay and Google Pay. Virtual card $9.99 (plastic, metal and gold cost more). The ONLY fee we state: 3% per purchase, no load fee; for anything else say "see BIX’s terms". US: open in 31 states so far; not in your state yet = you can still get the wallet and build; elsewhere availability varies by country; KYC required for the card. Funding POL -> card: (1) swap POL to USDT/USDC on any exchange or on-ramp, send on Polygon (app: Wallet > Receive > USDT or USDC > Polygon address); (2) US: Cash App can send crypto straight to the BixPay wallet; (3) an in-app swap is announced by BIX but NOT live: never say members can swap POL inside the app today. Sign-up steps: partner link -> register in the BIX portal (bix.ibportal.io) -> download the BIX app -> Settings > Scan QR to link app and portal -> Cards > Create Card ($9.99 virtual). Partner plan, plain words: BIX puts half of the 3% fee and of card sales into its partner plan, paid over ten levels (15% level 1, 10% level 2, 2.5% each on levels 3 to 10) plus a 5% pool; sign-ups and commissions are tracked and paid by BIX in the BIX portal, never by InstantAdPay; any worked example is hypothetical, not typical, and never a promise. Disputes: BIX accepts a dispute up to 120 days after a transaction posts; they can take 30 to 60 business days. WHERE: Members > Wallet (the card with Get your BixPay card + How it works), Members > Profile > BixPay card (the member pastes their PARTNER link from BIX portal > Profile > Partner, the second box; the referral link with appId=3 is refused), Promo tools > BixPay tab (3 posts, an email swipe, 4 text-only banners, all carrying the member’s link, plus the tab’s click count), the public guide https://instantadpay.com/bixpay (add ?ref=<username> and the page carries that member’s link), one sentence in payout emails. WHOSE LINK: the member’s own partner link, else the first sponsor up the chain (10 levels) with one, else the network link; every card says which ("Using: your link / @name’s link / the network link"). Compliance: InstantAdPay is not the card issuer and earns a referral commission when someone signs up through a partner link; crypto assets can lose value. NEVER repeat BIX marketing claims (user counts, cards issued, spend per day, valuations, "bigger than X") as facts; if asked, say those are BIX’s own claims and we have not verified them.\n'
|
||||
: '- BIXPAY VISA CARD: COMING SOON, not switched on yet. If asked about BixPay, BIX, a crypto Visa card or spending POL with a card, say it is coming to the Wallet tab soon and nothing is live yet; never quote its fees, steps, links or the partner plan until it is on.\n'; }
|
||||
// Warp & Wares (2026-10-29, the 30-day season game) follows gamesLive the same way; its season window is WW_SEASON_START / WW_SEASON_END (Central, end exclusive)
|
||||
const WW_END = /^\d{4}-\d{2}-\d{2}$/.test(String(process.env.WW_SEASON_END || '')) ? process.env.WW_SEASON_END : '2026-12-30';
|
||||
const wwDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const wwOver = () => wwDay() >= WW_END;
|
||||
const wwLive = () => { try { return !!GAME_LIVE('warpwares') && !wwOver(); } catch (e) { return false; } };
|
||||
const WARPWARES_SOON_ANSWER = 'Warp & Wares, a 30-day space trading season game in the Trade Wars style, is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it opens.';
|
||||
const WARPWARES_OVER_ANSWER = 'The Warp & Wares season is over; the next one is announced on the Games tab and in the release notes. The other games are on your Games tab (Members > Games).';
|
||||
const wwAnswer = () => wwOver() ? WARPWARES_OVER_ANSWER : WARPWARES_SOON_ANSWER;
|
||||
function warpwaresFact() { return wwLive() ? '- WARP & WARES (30-day season game, Members > Games): a Trade Wars-style trading and territory game in one shared galaxy of 1,200 sectors. Every captain gets 200 turns a day (reset midnight Central, never banked): warp, trade ore/grain/parts between markets, haggle, hold sectors with fighters and mines, found a base (six levels on build clocks), teams of five with a shared vault and elected leader. One-tap sign-in with the InstantAdPay account. PAYS POL from a published season budget: landmark holders and top traders at each weekly tick (Sundays 9 AM Central), one-time milestones (first base, first garrison, first 100,000 credits traded), the season-close leaderboard and titles. POL collects in the game balance and is paid automatically to the wallet linked on InstantAdPay. SPONSOR DOCK: docking at a sponsor market opens a short verified sponsor visit (charged to the advertiser like any game refuel visit, visit kind dock) and pays BONUS TURNS, the only turns past 200; gameplay only, never POL. Credits never turn into POL. Season Pass through the Game Pass: a hull step up, a second base slot, a named ship, a team banner, gold badges; never turns, fighters or prizes. Never state amounts, caps, totals or a season budget.\n' : wwOver() ? '- WARP & WARES: the season has ENDED; say the season is over and point to the Games tab for the next one.\n' : '- WARP & WARES: COMING SOON, not open yet. Never send members to the game address; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
|
||||
const POLMINER_SOON_ANSWER ='POL Miner, a dig-down mining game where rare Polygon crystals pay POL, is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it launches.';
|
||||
const pmLive = () => { try { return !!GAME_LIVE('polminer'); } catch (e) { return false; } };
|
||||
// Turkey Drop (2026-10-28, the Thanksgiving season game) follows gamesLive the same way, and its season (Nov 2 to 30, Central) ends it
|
||||
const TD_END = '2026-12-01'; // Central day, exclusive (server.js TD_SEASON)
|
||||
const tdDay = () => new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const tdOver = () => tdDay() >= TD_END;
|
||||
const tdLive = () => { try { return !!GAME_LIVE('turkeydrop') && !tdOver(); } catch (e) { return false; } };
|
||||
const TURKEYDROP_SOON_ANSWER = 'Turkey Drop is coming soon to the InstantAdPay games. It is not open yet; it will show up on your Games tab (Members > Games) and in the release notes when it opens.';
|
||||
const TURKEYDROP_OVER_ANSWER = 'Turkey Drop was the network’s Thanksgiving game, open Nov 2 through Nov 30, and its season is over. The other games are on your Games tab (Members > Games).';
|
||||
const tdAnswer = () => tdOver() ? TURKEYDROP_OVER_ANSWER : TURKEYDROP_SOON_ANSWER;
|
||||
const TD_PASS_PERK = ' Turkey Drop one free “back on the air” extra life every day;';
|
||||
const gpWithTd = a => tdLive() ? String(a).replace('plus one free supply crate every day;', 'plus one free supply crate every day;' + TD_PASS_PERK) : a; // the Game Pass answer names the perk only while Turkey Drop is live
|
||||
// Shards of Valor (2026-11-06, Marty): open for testing from the Games tab once 'shardsofvalor' is in gamesLive; no POL until a launch date
|
||||
function sovTestFact() { return GAME_LIVE && GAME_LIVE('shardsofvalor') ? '- SHARDS OF VALOR (OPEN TESTING since Nov 6, https://shardsofvalor.com, Members > Games > Shards of Valor > Play): a pixel adventure RPG for many players at once; lead three heroes across the islands, help the townspeople, fight in the dungeons and recover the eight Shards of Valor. It is in open testing: anyone can play it now, but it is NOT live and pays NO POL until a launch date is set; there is no launch date yet. ALL TESTING PROGRESS IS WIPED AT LAUNCH (heroes, levels, gold and items start fresh), because this phase is only for finding bugs. Never promise a date or a payout. Ask testers to report bugs through Support.\n' : ''; }
|
||||
function turkeydropFact() { return tdLive() ? '- TURKEY DROP (Thanksgiving season game, https://turkeydropgame.com, Members > Games; open Nov 2 through Nov 30 Central, its Games card shows a "Limited time, ends Nov 30" ribbon and is gone after): a free 70s-cartoon arcade game. The WFWL 98.7 radio helicopter drops turkeys over the mall; the player swings a net to catch them before they splat; too many splats and the station pulls them off the air. One-tap sign-in with the InstantAdPay account. PAYS POL: the first time a player reaches each score milestone, plus a weekly top-3 leaderboard POL prize. POL collects in the Turkey Drop balance and is paid automatically to the wallet linked on InstantAdPay. BACK ON THE AIR: after being pulled off the air, a short verified sponsor visit (charged to the advertiser like any game refuel visit) gives one extra life; gameplay only, never POL. Game Pass perk: one free back-on-the-air extra life every day. Never state amounts, caps, totals or a season budget.\n' : tdOver() ? '- TURKEY DROP: the Thanksgiving season game (Nov 2 to 30) has ENDED; say the season is over and point to the other games.\n' : '- TURKEY DROP: COMING SOON, not open yet. Never send members to turkeydropgame.com; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
|
||||
function polminerFact() { return pmLive() ? '- POL MINER (https://polminer.com, Members > Games): a free dig-down mining game. Dig, sell ore for coins, upgrade pick/lamp/cart/thruster, beat a drill boss every 30 m. Pink Polygon crystals pay a random POL amount the first time each one is dug out; each boss pays POL on its first win per account; first trips to 50/100/150/200 m pay POL. Coins never turn into POL. Guests can play and collect at sign-in. POL is paid automatically to the wallet linked on InstantAdPay. The SUPPLY pad opens a sponsored supply crate (full lamp + coins, never POL) after a short sponsor visit.\n' : '- POL MINER: COMING SOON, not open yet. Never send members to polminer.com; say it is coming soon to the Games tab.\n'; }
|
||||
function refuelFact() { return "- DOWNLINE BANNERS (LIVE 2026-11-13, https://downlinebanners.com, contract verified on Polygonscan): network banner board; a $5 spot in POL = 300 guaranteed views + a place in one line; the contract pays the 10 spots above and the buyer's sponsor when later spots sell; nothing promised. InstantAdPay sign-in carries members in as their linked wallet; share links use the InstantAdPay username; My Spots has a 'Use a LinkSpin Banner Spin' button. A counted Monthly Refuel of $50+ (either site) earns one free spot for the member's main wallet, paid by the company (no wallet linked = no spot).\n" + (REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'); }
|
||||
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
|
||||
function systemPrompt(kbBlock) {
|
||||
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
||||
|
||||
FACTS:
|
||||
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
||||
- LEVEL 4 OVERRIDE (LIVE 2026-10-26, first payout Monday 2026-11-02): company-paid, off-chain decision, on-chain payment. 3% of every package purchase (the POL actually paid) goes to the buyer's 4th upline on the contract sponsor chain if that member's contract buyerCount is 5 or more (qualifying buyer = direct referral with a $20+ purchase, same bar as level 3); otherwise it hunts up to the next qualified upline, max 25 hops; the company account (#1) or no qualified upline = company keeps it; exactly one recipient per purchase. Paid weekly in POL every Monday after 9 AM Central for the previous Monday to Sunday Central week, from a company payer wallet via the contract's award(memberId), shown in Earnings as 'Level 4 override' with a Polygon link and announced by email and an on-site notice. Under 0.01 POL carries to the next week. Purchases from the start date only, no back pay. Funded from the platform's 20%; the contract split 50/20/10 is unchanged. Never promise amounts.
|
||||
- NETWORK SIGN-IN (built 2026-11-12): one sign-in for InstantAdPay and LinkSpin, same email on both. A member signed in on one site who follows a link from inside their account to the other (Engine Room, Refuel, Back to InstantAdPay) arrives signed in with no email code; opening the other site's sign-in screen while signed in here also signs them in by itself (one quiet try per browser every 30 minutes). Exception: when the account on the receiving site does not exist yet or is still a waiting account (never signed in), they get the normal email code once, email prefilled. Sign-out is per site and switches the automatic sign-in off on that site for 12 hours (a deliberate link from the other site still works). Sessions are ordinary member sessions (4 hours), the admin portal is never shared, and the sign-in grants nothing extra: purchases, payouts and wallet actions still need the wallet. If it fails, the email code always works.
|
||||
- EARNERS CORNER (LIVE 2026-11-10, https://earnerscorner.com): the network's own forum (Discourse) for people who earn online: business opportunities, PTC, traffic exchanges and mailers, crypto earning and wallets, affiliate marketing, tools, plus an Our Network section. Read is open to everyone; posting needs signing in with the InstantAdPay account (no separate forum password). New accounts' first posts are reviewed; links unlock with trust and are open from day one for members with an on-chain position; referral links only in Promote Your Program; AI spam detection; a forum assistant answers network questions from the same official knowledge and links threads.
|
||||
- STACK POL (LIVE 2026-11-09, https://stackpol.com): one site that adds up every POL payout in the network (InstantAdPay and LinkSpin TierPaid referral payments plus every game's payouts), refreshed every 5 minutes, with per-program pages (/earn/<program>), a public ledger showing each payout's username and Polygonscan link, and a blog. Members get a public page at stackpol.com/<username> by switching on 'Show my Stack POL page' in Promo tools > Stack POL; it is ON by default for every paid member (since 2026-11-09) and off only when they switch it off. It never holds money. STACK POL PRO (2026-11-09): one-time unlock, NEW MONEY only: ANY package of $10 or more bought by the member's own position unlocks it automatically (since 2026-11-09 evening, no order step); credits never count; it never uses up a package that also fulfils a Game Pass or hero order. Pro pages show the member's own LinkSpin Banner Spins in the ad spots (network zones otherwise), their spin links, a purple QR code to the page, a 'Want a personalized page like this?' button, and articles opened from the page (?ref=<username>) use the member's referral on every call to action. Pro owners get the Stack POL Pro badge. Totals are past payouts, never a promise of earnings.
|
||||
${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${warpwaresFact()}${bixFact()}${turkeydropFact()}${sovTestFact()}- ROAD AGENT (LIVE 2026-10-15, https://roadagent.app): a night-highway shooter open to every member. Open the Games tab and tap Play on the Road Agent card, or go to roadagent.app and sign in with the InstantAdPay email. Drive the four-lane highway, shoot the hostiles (thug sedans, switchblades, gunner vans), spare the civilians, pull into the weapons truck for oil slicks, smoke and missiles. Clearing a sector for the first time pays POL to the wallet on the member's InstantAdPay account, plus a daily patrol reward; scrap buys garage upgrades. Fuel = a sponsor visit: before a run the player visits an advertiser's page (a FUEL STOP), which is a normal verified visit with the dwell timer and human check, charged to the advertiser like any visit; advertisers' existing visits campaigns are already in the rotation, nothing to set up; to get more traffic from the game, top up the visits campaign. Clickable Pause, Sound and Music buttons sit under the game (P / M / N keys also work), and the Run tab has an Invite a friend card with the member's roadagent.app/?ref=<username> link.
|
||||
- HELP DESK (LIVE 2026-10-16): members open Help in the dashboard (/my#help) to send Marty a support ticket (pick a category, a subject, the message, up to 2 screenshots), see each ticket's status (Open, Waiting on you, Closed) and read and answer his replies; a badge shows when he has replied, and replies also arrive by email. Anyone signed out or locked out uses the public form at https://instantadpay.com/support (name, email, category, subject, message) and gets an email with the ticket number (like IAP-1042) and a private link to view and reply, no sign-in needed. support@instantadpay.com also reaches Marty. Replying to a closed ticket opens it again. In this chat, "Send this to support" turns the conversation into a ticket. Only Marty answers, so replies are not instant; never promise a response time.
|
||||
- PRESENTATION (2026-10-15): instantadpay.com/presentation is a public page (no sign-in) with the narrated InstantAdPay presentation, about six minutes, Marty's voice, captions in 6 languages (English, Italiano, Français, Español, Deutsch, Português) chosen with pills under the player. Sixteen parts: the platform, ad reach, the nine games that pay POL, the $20 split ($10 / $4 / $2 / $4 platform, same transaction), three rules, packages, the 2-then-5 unlock, pass-up, wide versus narrow ($800 vs $36, an illustration), Qualified Start, the Pipeline, LinkSpin (pre-launch Nov 1), one wallet across the network, the first week, and 'the target is five'. Share link: Members > Promo tools > 'Share the presentation' copies instantadpay.com/presentation?ref=<username>; ?ref sets the same 30-day sponsor cookie as the invite link, the page shows 'Shared with you by @name' with avatar and a Join button to /join/<username>. It is in the site menu as 'Presentation'. BUILD WIDE VIDEO: first card in Promo tools > Videos ('Build wide: watch the payments flow'), matched link ?v=wide.
|
||||
- WIRED WEDNESDAY: every Wednesday, Central time (midnight to midnight), any ad package of $20 or more (Activation and up; no $10 pack exists) earns +25% bonus credits wired into the buyer's balance the moment the purchase settles, purchased-grade (usable on every format incl. login ads), credit log label "Wired Wednesday". First one: Wednesday 2026-09-30. Page: instantadpay.com/wednesday. Credits buy ad delivery, never money.
|
||||
- CONVERSION LINKAGE (LIVE 2026-11-07, reporting only: it never changes sponsors, payouts, credits or anything on chain): a LinkSpin click id (lsclk or lsid in the address) arriving on any InstantAdPay page is kept 30 days in a first-party cookie (last click wins) and travels with the code request, and is stored with the account at sign-up, in-game sign-in included when the game passes it on. InstantAdPay then reports sign-up, wallet link and each package purchase (value = the USD price on the chain event, linked positions included) to LinkSpin, which counts join and wallet once per click and each purchase on its own, for the click's owner. The landing tag adds the click id to links to instantadpay.com, linkspin.app and the share domains, also inside a member's own redirect link; a spin link or Banner Spin pointed straight at those sites carries it with no goal needed. 30 days from the click to the event, same as goals. The first account on a click owns it. The click owner's own account and own clicks are never counted. People who joined before 2026-11-07 cannot be matched afterwards. Shown on the Conversion tracking card (with goals, 30 days) and in LinkSpin under Reports, Conversions.
|
||||
- CONVERSION TRACKING (LIVE 2026-10-23): Campaigns > Conversion tracking in /my#campaigns. Every click on a member's ad (through /api/ads/click) gets a click id added to the target address as lsclk=<id>; the advertiser adds a goal (name like subscriber or sale, optional default value), puts the LinkSpin landing tag (t.js) on the page the ad points to and the goal pixel (cv.gif image, or the cv.js script) on the thank-you page. LinkSpin (sister site, same email) counts the goals; matching order: click id in the address (url, surest), the id the landing tag stored (stored), LinkSpin's cookie (cookie), a 24-hour match on hashed IP plus browser (soft, least sure). Each goal counts once per click, only within 30 days of a real click, only for the pixel owner's own ads; the advertiser's own clicks (signed in, or from a browser they sign in from; their linked positions share their email so count as them too) and the Send a test conversion button count as tests, never in the numbers; the card shows 'N from your own clicks, kept as tests'. SEND A TEST CONVERSION (2026-10-26) loads the member's real LinkSpin pixel in test mode from their browser (falls back to the signed partner call if the browser blocks it), so Last test updates. Each campaign row shows goals and COST PER GOAL (30 DAYS) in credits (2026-10-26: the credits the campaign spent in the last 30 days, from the credit activity log, divided by its goals in the same 30 days; a campaign started inside the window uses its spend since start; never quote it in dollars). Autoresponder tip: set the Aweber or GetResponse thank-you (success) page to a page on the member's own site carrying the goal pixel (Aweber: Thank You Page: custom page; GetResponse: Thank-you page: custom URL); if they cannot, the cookie or the 24-hour match can still count it, less surely. Privacy: the click id is random and nothing personal is sent. SETUP GUIDE (public, 2026-10-24): https://instantadpay.com/conversion-tracking (LinkSpin's copy: https://linkspin.app/conversion-tracking): why track, the flow, the 4 steps (goal, landing tag, goal pixel, test), copy-paste examples (plain HTML, WordPress footer plugin + Custom HTML block, page builders, Aweber/GetResponse custom thank-you page), the page check (add &test=1 to the pixel address, open the thank-you page, Last test updates, then remove it), what to do without code on the thank-you page, how to read the report and a troubleshooting checklist (same domain for landing and thank-you page, goal pixel only on the thank-you page, the script version is surest). Send members there for any setup question.
|
||||
- FIVE DOLLAR FRIDAY: every Friday, Central time, any ad package of $5 or more earns +20% bonus credits, credited the moment the purchase settles (credit log shows the label). First one: Friday 2026-09-25. Since 2026-10-23 the same $5+ Friday package also gives a FREE 7-day Game Pass automatically (once per member per Friday; not a second week when that package itself fulfils a pass order; the Game Pass badge posts the first time). Five Fridays in a row = the Five Fridays badge. The point: the whole network buys on the same day, every pack pays its sponsor line in the same transaction, so every line gets paid at once. No income promises.
|
||||
- SESSIONS LAST 4 HOURS. Sign-ins expire after 4 hours and the member signs in again with a fresh 6-digit code. This is intentional and we say so plainly: it keeps resources optimised, and the login sponsor ad shown on the way back in is part of what pays for the free side. Nothing is lost on expiry - credits, line and account are untouched. Never describe it as a bug, an error, or something to report.
|
||||
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
||||
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
||||
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
|
||||
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com.
|
||||
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two for an angle-matched headline. New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
|
||||
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
|
||||
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. The Games tab (2026-10-31) also carries the EnjoyBestGames arcade kit: enjoybestgames.com is an engagement site with hundreds of free HTML5 games; the featured row Games that pay Polygon is the network's own games and the only ones that pay; the member link enjoybestgames.com/?r=username sets a 30-day cookie so every featured game and the site strip credit that member on InstantAdPay; share image, 4 posts and the 11 banner sizes are in the kit. The Network sites tab (2026-11-14) shows the Downline Banners and Viral Banner Blitz promo kits, read live from each site: the member's links (their InstantAdPay username is their sponsor link there too, even if they never visited), creatives in 7 sizes per angle, 5 lines, 3 headlines, an email and 2 posts; the same kits are on downlinebanners.com/promote and viralbannerblitz.com/promote. Viral Banner Blitz: a shared loop of 125x125 banners, one free post credit a day for InstantAdPay/LinkSpin members, verified visitors move the loop, a banner that cycles earns network ad views (advertising, not cash), weekly leaderboards with a POL prize pot.
|
||||
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
|
||||
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
|
||||
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
|
||||
- LINE BANNER (free, set in Profile): every member can set a destination URL (must allow framing) plus an optional banner image. It is shown to their next THREE levels of new members during welcome tours (position 1 for directs, 2, 3 below), and on their public BANNER WALL at /wall/<username> — a shareable page showing their line ladder with their join link. Free viral traffic that compounds as the team grows; no credits spent.
|
||||
- Ad packages: Micro $5/500 credits, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
|
||||
- Ad packages: Micro $5/500 credits, Starter $10/1,000, Activation $20/2,000, Builder $50/5,500, Growth $100/12,000, Leader $250/32,500, Elite $500/70,000. Dollar-priced, settled in POL (Polygon) at the live Chainlink rate. 1 credit = 1 cent of ad delivery.
|
||||
- Live formats: display banners (per impression), text ads (per impression), full-screen LOGIN ADS (per day: right after a member signs in they land on a sponsor interstitial — they click "Open Ad", the advertiser's page opens in a NEW tab, a countdown runs on the interstitial, and at zero a "Go to dashboard" button appears. Just a CTA link is enough; an optional banner image can be the clickable creative. No framing requirement since it opens in its own tab), WATCH-TO-EARN VIDEO ADS (advertiser uploads an MP4/WebM or gives a direct https .mp4/.webm link and picks a required watch length — 10s/30s/60s — which sets the per-view price; viewers watch in an escape-proof player under Earn credits > Watch videos, the watch time is enforced on the server clock, and they earn credits per completed watch; you never see your own videos), and solo ads. Banner ads also require a size (standard IAB sizes like 728x90, 300x250). Video watching is capped at 8 a day per member and pays 1, 2 or 4 credits for a 10, 30 or 60 second watch. FEATURED LINKS (live): a headline + link in the Featured strip at the top of every member's Overview, booked for 1, 2 or 7 days at 40 credits a day, up to 7 days ahead, at most 10 links sharing any day; flat buy paid when booked; the row shows days left and 'runs through <date>', counts views (one per viewer per hour) and clicks, and offers Extend run. VERIFIED-VISIT PACKS (live): 3 credits per visit, minimum 20 visits, paid up front; each visit is a distinct member who opens the site in a new tab, stays 8 seconds and passes a check, at most 20 visits per member per day; the row shows 'N of M visits delivered' and Buy more visits adds to the pack; the visitor earns 1 credit.
|
||||
- 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.
|
||||
- PROHIBITED CONTENT (2026-10-30, Terms section 8, /terms#prohibited): gambling, casinos, betting, lotteries, sweepstakes; adult or sexual content; drugs and prescription pharmaceuticals; weapons; hate or harassment; malware, phishing, counterfeit goods; misleading financial promises. Refused at save time in bios, social links, line banners, wall offers and every campaign field. A bio may not contain a URL or a domain (links go in the social fields). Profile text, avatar and social links appear on the public wall ONLY for members who have bought a package; a free account's wall shows the name, the line's ads and the join button. Link-farm accounts (created to plant links in profile fields) are removed without notice with their profile text.
|
||||
- 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/<username>) 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.
|
||||
- BTC4HITS (2026-11-11): members of the closed BTC4Hits rotator site with a deliverable email were imported as waiting accounts (no wallet, no password, nothing mailed), with their BTC4Hits sponsor when that sponsor was also imported or already a member; the rest join the holding tank when they first sign in. They sign in here with the same email (code sign-in), or on LinkSpin at linkspin.app/from/btc4hits, where their active rotators became spin links. Pro status and old BTC4Hits commissions do not carry over.
|
||||
- HOLDING TANK (Members > My line > Holding tank card): free members who joined with no sponsor wait there; new sign-ups cannot be adopted by hand for 24 hours from sign-up (they show an Opens in badge and no Adopt button); a member who has switched on payouts AND bought their own $20+ package can Adopt one (first come, max 10 held at one time, counting those not yet switched on payouts, 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.
|
||||
- WHO INVITED YOU (2026-11-07, Marty approved): a member with no sponsor and no member number sees a Who invited you? card on their Overview. They type a username, confirm in an in-page box, and that member becomes their sponsor (it follows to LinkSpin, lifts the activation hold, and the sponsor gets a new-referral email and notice). Refused: themselves, a username that does not exist, someone in their own line, a member who cannot take new members, a member with no payouts on and nobody above them on the contract, and anyone who already has a sponsor or a member number. Nobody invited me hides the card (a small Overview link brings it back while they are in the tank) and changes nothing else. It never blocks the site. It is not an adoption: no 7-day window and it does not count toward the two.
|
||||
- SIGN-UP GRACE (2026-11-07): for 24 hours from sign-up nobody can adopt a member by hand. The 24-hour auto-assign is unchanged and runs from the wallet link, so a member who links a wallet in their first hour is matched about 24 hours after linking, with at most a short hand-adoption window first. Members back in the tank later have no grace.
|
||||
- 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 on its own yet (a PURCHASE is NEVER held, Marty 2026-10-27: with no sponsor anywhere a buy goes ahead under the catch position #1); 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 10 people held from the tank who have not switched on payouts yet, 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. ONE-TAP SWITCH ON PAYOUTS (2026-10-27): every tank assignment (manual adoption or the 24-hour auto-assign) sends the member a chat and an email with a Switch on payouts link, https://instantadpay.com/my?activate=1#wallet; it opens the Wallet tab and starts the normal Activate payouts flow with the new sponsor prefilled (after sign-in, and after linking a wallet if none is linked yet). It never starts while the hold applies or when no sponsor resolves. The site cannot activate for anyone: activation is one free transaction from the member's own wallet. Not activated 24 hours after the assignment: one reminder email to the member with the same link and one notice to the sponsor ("@x hasn't switched on payouts yet; a nudge from you helps"); at 72 hours one last email to the member only; both stop once the member switches on payouts or buys.
|
||||
- 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.
|
||||
@@ -130,15 +396,21 @@ FACTS:
|
||||
- LINKED POSITIONS AND BADGES (2026-09-14): qualifying buyers on a member's linked positions count toward their achievement badges (Spark/Surge/Circuit/Nexus) and light their chip on their sponsor's line, and a badge once earned never regresses. CONTRACT RULE: levels 2 and 3 are paid to the MAIN wallet only when that wallet's own count of qualifying buyers reaches 2 and 5; buyers registered under a linked position count for that position, not the main wallet. Qualified Start positions buy UNDER the main wallet, so those buys raise the main count; a member whose old wallet was swapped out (its buyers stay with the old position) needs new $20+ buyers under the current main wallet before level 2 pays it. The contract still pays levels 2 and 3 to each position based on that position's OWN qualifying buyers, so the Qualifying buyers tile shows the main position's count with the linked positions' count underneath.
|
||||
- CREDITS VS POL (2026-09-15, Marty's stance): EVERY member earns CREDITS (viewing, videos, visits, inbox, sign-in bonus, badge bonuses); credits are ad delivery, not money. POL is paid by the contract to a member's wallet when referrals buy packages. ALWAYS describe activation as 'the $20 starter package plus payouts switched on' and lead every earning answer with it; do NOT volunteer that level 1 can pay without a purchase. If someone asks point-blank whether a purchase is required for level-1 payouts, answer truthfully in one sentence: the contract pays level 1 to any member whose payouts are switched on, and the $20 package is what makes them a qualifying buyer for their sponsor, funds their own ads, and unlocks badges, tools, the holding tank and wall positions. A $20+ purchase by a referral makes that referral a qualifying buyer for their sponsor; 2 and 5 open levels 2 and 3. Never claim the payout itself is gated by a purchase.
|
||||
- PIPELINE (live since 2026-09-15): a follow-up board on the dashboard, tab 'Pipeline' between My line and Buy packages, with its own training video on the Training tab. Columns: Talking to, Joined, Wallet linked, Payouts on, Bought, Building, Later. Prospects (from the My line prospect list) and directs are placed automatically from what they have actually done (coaching rung, on-chain buys); nobody drags cards. The sponsor adds a note, a follow-up date and a tag (hot, later, no response, not interested); a 'Follow up today' strip lists due cards; stalled cards (quiet 3+ days) are flagged; each card carries the message for its exact stage with 'Open chat with this message' (member chat) or copy.
|
||||
- LEADER TOOLS (since 2026-10-16): a 'Leader tools' section on the Training tab with the Leader's Guide (a downloadable PDF: building wide, how width unlocks levels 2 and 3, network reach, Qualified Start, LinkSpin, the wallet as your key, the first week), the narrated presentation to share, and the Build wide video. My line and Pipeline each have a Leader tools card with a direct 'Download the Leader's Guide (PDF)' button and 'Open Leader tools'.
|
||||
- UNACTIVATED SPONSOR = WALK UP, NEVER HOLD (2026-09-16, Marty): if a buyer's sponsor has not linked a wallet or switched on payouts, the purchase is NOT held. The site walks the sponsor line upward to the first upline who is activated with payouts on and the buy goes through under them (on-chain sponsorship for that buyer is then theirs, permanently); if nobody in the line is activated it goes under the company catch position (#1). The buyer sees a one-line notice and proceeds; once the position exists on the chain the skipped sponsor gets a blunt email + on-site message (they lost this referral for good, how to switch on payouts) and the upline who was paid gets a message that the referral is theirs permanently with a nudge to coach the one who missed it; the referral MOVES to whoever got paid (the account's stored sponsor is re-pointed when the position is created on-chain), so the buyer leaves the skipped sponsor's My line for good; the skipped sponsor can never earn from that wallet. Only a transient chain error ('rpc') still pauses a buy ("try again in a minute").
|
||||
- CHASING UNICORNS (2026-11-12): a promo tool at instantadpay.com/chasing-unicorns (Members > Promo tools > 'Chasing Unicorns: the scam-spotting game', copy your own link, which ends in ?ref=<your username> so a join counts for you). It is a clearly labeled training simulation: a fake 'UnicornYield Pro' dashboard (ticking balance, countdown, fake cash-out popups, VIP upgrade, connect-wallet airdrop) where every button reveals one of 8 scam red flags and scores the visitor's 'scam radar'; then it shows what chasing scams costs and how InstantAdPay works instead, with a free join button. Nothing on the fake dashboard is real or touches any account. Made for people still waiting on a payout from another site.
|
||||
- YOUR DIRECTS' DETAILS (2026-11-12): in Members > My line > 'Your line', each person who joined through your link shows their email (with a copy button), where they came from (the referring site and the link's source tag, e.g. 'from mailer.gold/mailergold'; 'no referring site' when the browser hid it; accurate source tags start 2026-11-12, older sign-ups mostly read 'no referring site') and how they joined (your invite link, your bridge page, a link version, a game, came over from LinkSpin, moved over from BTC4Hits). The same email + origin show in the Activity drop-down and the three-level downline card for your directs. Levels 2 and 3 never show emails: they belong to their own sponsor's direct relationship. The search box also matches email and source.
|
||||
- FIND A MEMBER (2026-11-12): every member list on My line (Your line, the three-level downline, the Holding tank) has a search box at the top of its sort/filter bar. Type part of a name, username (with or without @), email or member number and the list narrows as you type, starting on page 1; it works together with the sort and the filter chips. Emails only show (and match) for your own level 1.
|
||||
- DRILL DOWN FROM THE OVERVIEW (2026-09-15): every name chip in 'Your line at a glance' on the Overview is clickable; it jumps to My line with that person's Activity panel already open and the row highlighted.
|
||||
- VISIT PACKS ARE PAID UP FRONT (2026-09-15, Michael's question): a verified-visits campaign charges the whole pack when it is created (3 credits per visit, so 1,000 visits = 3,000 credits) and then delivers over time as members complete verified visits (each member can do at most 20 a day, so packs fill gradually: tens per day at today's size). The Campaigns row shows 'paid up front' and 'N of M visits delivered'; the credits are not being consumed again, they were reserved once. Same for featured-day bookings: a featured link is a flat buy (featuredPerDay credits per day, whole run charged when booked), its row shows 'paid up front', the day count and 'runs through <date>', and it ends on its last day ('run ended'). FEATURED CANNOT TAKE ADDED CREDITS (2026-09-16, Hugh and Michael both tried): the row offers 'Extend run' which books more days after the current run (or from today if it ended) and charges them right away; there is no 'Buy more views' on a featured row any more. Visit packs offer 'Buy more visits' (charged now, adds to the pack). Credits added to a campaign are set aside immediately (Available drops at once) and whatever is unspent returns to Available when the campaign ends.
|
||||
- BANNER CREATIVE MUST BE AN IMAGE LINK (2026-09-16): the New campaign image field needs a direct image URL (ends in .png/.jpg/.gif/.webp/.svg) or an upload; a web-page link (a join page, an imgbb/ibb.co page) is refused with a message. Easiest source: Promo tools > Banners > Copy image URL. A campaign created with a page link before this check served a broken banner and was repaired by admin.
|
||||
- PAYMENT TRACE (2026-09-16): Members > Earnings > "Trace a payment": enter a member number or @username (yourself, anyone up to 3 levels below you, or your own 3 uplines) and every purchase they were part of is listed tier by tier — who was paid at level 1/2/3 (50/20/10%), who was skipped and why ("not qualified: had N of 2 qualifying buyers then"), the platform's 20%, and a verify link to the transaction. Use it to answer "why didn't my sponsor / why didn't I get paid on X's purchase" — the usual answers are (a) the sponsor had not unlocked that level when the purchase settled (qualification never applies backwards), (b) the buyer used Qualified Start, so the purchase came from a linked wallet whose on-chain sponsor is the buyer's own main position (level 1 goes to the buyer themselves), (c) the sponsor's payouts were not switched on. Admins see the same trace under the member card in Admin > Members.
|
||||
- GAME PASS (2026-10-16, Members > Games > Game Pass): $5 for 7 days, one pass per account covering ALL the network games (linked positions share it). PAYMENT (changed 2026-10-22): every pass is paid by a NEW on-chain package purchase of at least the pass price ($5 for the weekly pass), bought from one of the member's own positions AFTER tapping Get the Pass. The pass starts the moment that purchase settles. The sponsor and team are paid from that package exactly like any package, and the member keeps every credit of the package for ads. Credits (earned or purchased, old balances included) NEVER buy a pass, and a package bought before tapping Get the Pass does not count; if someone asks why, say the pass is paid by a fresh package so the team that brought them in is paid too. Passes bought before this change keep running. Buying again while active extends by 7 days. ACCOUNT-WIDE DAILY POL CAPS across the games, reset at midnight Central: free 0.30 POL/day on repeatable daily-play rewards and 2.0 POL/day for everything; Pass 1.50 and 5.0. FREE ALLOWANCE (2026-11-02, Marty: the games are a loss leader but the giveaway has a ceiling): an account with no pass receives at most 2 POL of game rewards EVER across all games combined; after that, one-time progress rewards wait as deferred and are paid once a pass is active, and repeatable daily rewards are not paid. Since 2026-11-03 the games say so the moment it happens ("You have used your free 2 POL in the games. Get the Game Pass to keep earning." plus the POL being held) and the Overview shows a Get the Game Pass card. Say it plainly: play free as long as you like, the free POL is a taste, the Game Pass is how the games keep paying. Caps apply only from the announced start date (capsStartDate); until then the games' own caps stand. A one-time PROGRESS reward (stage, boss, chapter, sector, room) over the day's total is DEFERRED and carried to the next day, never lost (a 10 POL Gem Kingdom boss still pays 10 POL, over a few days); repeatable DAILY-play POL over the daily cap is dropped for that day. Reward AMOUNTS never change with the pass: say 'free play pays; the Pass plays more', NEVER 'earn more' or 'pays for itself' (max repeatable per pass week is 10.5 POL, under the $5). Pass perks per game: PolHunter 5 missions/day and Ad Detective twice; Gem Kingdom a free continue a day; SpellWheel streak 0.30 and a free hint; PolyWarriors +1 mission, defense 25 Circuits, Pass mark; Road Agent 2 patrols and +25% scrap; ClutterHunt 2 free hints; PolyBreak gem cap 1.5 and an extra paddle; Drip Runner a starting shield; Spooky Doors +1 door while the season runs. WEEKLY PASS TOURNAMENT: pass holders ranked by plays reported across the games Monday to Sunday Central; prize pool = 5% of that week's pass sales in POL (50/30/20 to the top 3), settled Mondays 9 AM Central, top 3 posted to the Game Achievements Telegram topic, prizes paid in POL by the games to the winner's InstantAdPay wallet. Members see the card, state and expiry in Members > Games (deep link /my#games?pass=1); an Overview nudge appears once a day after a game reports a free-cap hit. PER-GAME PERKS (live 2026-10-22, also listed on the Game Pass card): PolHunter 5 missions/day instead of 3 + 2 Ad Detective cases/day; Gem Kingdom 1 free continue/day; Spooky Doors +1 door/day; ClutterHunt 2 bonus hints/day; SpellWheel streak 0.30 POL instead of 0.15 + 1 free hint/day; PolyBreak gem limit 1.5 POL/day instead of 0.5 + extra paddle every round; PolyWarriors 4th daily mission + defense 25 Circuits instead of 15; Drip Runner free shield every run; Road Agent 2 patrols/day + 25% more scrap. Buying a pass unlocks the gold Game Pass achievement badge (Members > Overview badges, share or post to Telegram). New free caps started 2026-10-26 (moved up from the announced 10-29).
|
||||
- PLATFORM FACTS (2026-10-06): instantadpay.com/facts (footer link 'Platform facts') and instantadpay.com/llms.txt are the verified reference for how InstantAdPay works: contract 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 on Polygon; split 50% L1 / 20% L2 (needs 2 referred $20+ buyers) / 10% L3 (needs 5) / 10% platform wallet A / 10% platform wallet B, unqualified shares pass up (25 steps) then go to wallet A; purchased credits are on-chain (engine burns them in batches), earned credits are in the site database; credits are not transferable or cashable; POL payments are final, platform may return credits when a campaign fails because of a platform problem. When someone asks how the platform, payouts, credits or refunds work, answer from these facts and link /facts.
|
||||
- CREDIT ACTIVITY LEDGER (2026-09-16): Members > Campaigns has a 'Credit activity' list (last 40 lines, newest first; also linked from the Earn credits pane) showing every real credit movement with a reason: welcome credits, sign-in bonus with streak, daily claim, inbox reads, video watches, verified visits, milestone and leaderboard bonuses, partner codes, admin/team grants, AI Copy Engine charges and refunds, flat buys (featured runs, extensions, visit packs, more visits), login-ad days, and metered delivery rolled up as one line per campaign per day ('Ad views: NAME', 'Inbox deliveries: NAME', 'Video views: NAME'); lines marked '(purchased credits)' spent on-chain purchased credits rather than the earned pool. Reservations (credits set aside for a live campaign) are NOT ledger lines; they show as 'in live campaigns'. Earned credits are spent before purchased ones, so an earn followed by a buy appears as two lines. The ledger starts 2026-09-16; nothing earlier is listed.
|
||||
- PAYMENT + MISSED-PAYMENT NOTICES (2026-09-15): every payout that lands (who bought, level, share in POL and dollars, transaction link) and every missed payout is delivered BOTH by email and as an on-site inbox message from the company account, shown in the login pop-up and the Messages card, so it is waiting when the member signs in. MISSED-PAYOUT detail: when a level-2 or level-3 share passes a member by because that level is not open on their account, the member gets an email the same minute: who bought, the POL and dollar amount they missed, how many qualifying buyers they have versus the 2 or 5 needed, and the two ways to close the gap (bring buyers, or Qualified Start). Qualified members whose wallet rejected a transfer get a different email telling them to link a regular wallet. MISSED PAYOUTS ARE ALSO PUBLIC (2026-09-16): the team's Telegram payments feed posts, by username, who was passed over on a purchase, why (not qualified yet with N of 2 buyers, or payouts not switched on), the amount, and who received it instead; the same for a sale that routed past an unactivated sponsor. Nothing about the contract changed; it is visibility.
|
||||
- LAUNCH WEEK SWIPES (2026-09-15): the founding-week checklist page (/launch) ends with four promoter emails members send to their OWN lists, one a day toward Monday's opening, with the member's invite link and the FOUNDER code (500 credits for anyone who joins before Mon 2026-09-21 9 AM Central) filled in, each with a Copy button. These are swipes for members, not emails the site sends.
|
||||
- LOGIN ADS ARE A SLOT (2026-09-19): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. At most 3 member slots run at once because every slot shares the same sign-ins; when all 3 are taken the buy is refused until one ends. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
|
||||
- LOGIN ADS ARE A SLOT (2026-09-19, updated 2026-10-18 and 2026-10-23): 1,000 purchased credits buys 30 days on the sign-in screen, paid up front, never metered. Purchased credits only: credited purchased credits first, the rest from the position's on-chain package credits; earned (viewing) credits never pay for a login slot. At most 6 member slots run at once (raised from 3 on 2026-10-23) because every slot shares the same sign-ins; when all 6 are taken the member can RESERVE THE NEXT SLOT (since 2026-10-23): they pay the full slot price right then (same purchased-credits-only rule, balance drops at once, credit log 'Login slot reserved (queue #N)'), the ad waits in a paid line, first paid first served, and its 30 days do not start until its turn. Members > Campaigns shows their place in line and an ESTIMATED start date in Central time, worked out from the live slots' end dates and the reservations ahead; it is only an estimate because a slot ends early if its owner archives it. The oldest reservation starts automatically the moment a slot frees (a slot expires, or its owner pauses it to end or archive it; also checked every minute), and the owner gets an on-site notice and an email. Before it starts the owner can edit the link, image or headline for free, or cancel for a FULL refund (credited back as purchased credits, credit log 'Login slot reservation cancelled: refund'); after it starts normal slot rules apply. A freed slot goes to the line first: a paused slot can only be resumed while live slots plus reservations leave a place open, otherwise the owner is told the line is ahead of them. The admin can see the line and cancel-and-refund a reservation. A slot cannot be topped up (it is a flat 30-day buy with unlimited sign-in impressions). Since 2026-10-18 the login ad shows after a fresh sign-in on the dashboard AND after a fresh email sign-in inside the connected games (Drip Runner, Gem Kingdom, ClutterHunt, PolyBreak, SpellWheel, PolyWarriors), before the player continues to the game; a remembered game session does not show it. House login ads only show when no member slot is running. Featured links count views (one per viewer per hour) as well as clicks.
|
||||
- AD VIEWER OPEN-IN-TAB (2026-09-19): the earn viewer shows the advertiser's page inside a frame; a link in its bar opens the same site in a new tab for sites that refuse to load framed or where signing up is easier in a full tab. The view still credits from the frame's countdown and check.
|
||||
- (2026-09-14 hold rule REPLACED on 2026-09-16 by the walk-up rule above: a purchase is never held for an unactivated sponsor; only a transient chain read error pauses a buy.)
|
||||
- NO-PAYOUT POSITIONS (2026-09-14): admin can list member ids (Settings > No-payout positions) whose wallets must never be paid again (e.g. a compromised key). Those positions stay linked for history and counting only: the buy-from picker disables them, a purchase from them is refused, and invite links that would place a new member under them (or under their upline chain) route to the fallback sponsor instead. The contract itself cannot change a member's wallet.
|
||||
@@ -148,11 +420,11 @@ FACTS:
|
||||
- GETTING STARTED CARD (2026-09-14): the top of every new member's Overview shows four steps (username, link wallet, switch on payouts, first package) with the current one explained and one button that opens the right tab and highlights the control (Wallet tab > Link wallet; then Activate payouts). Encouragement only: it can be hidden, and members who only want to view ads and earn credits are never blocked. It disappears once all four are done.
|
||||
- LEADERBOARD + REFERRAL CONTEST (2026-09-14): instantadpay.com/leaderboard ranks members by ad packages sold to people they directly sponsor (dollar value, read from the chain; a member's own linked positions and second accounts never count). Periods: this week (Monday to Sunday, Central time), this month, all time. Weekly and monthly winners are recorded automatically at rollover, announced in Telegram, and the credit prizes set by the admin (a ladder: 1st 1,000 / 2nd 500 / 3rd 250 weekly, 5,000 / 2,500 / 1,000 monthly by default) are granted automatically to those positions; the prize text is shown on the page and on the Overview's Leaderboard card, which also shows the member's own rank. Prizes are credits or packages, never cash.
|
||||
- WHAT'S NEW / ROADMAP (2026-09-14): instantadpay.com/whats-new lists release notes (what shipped, dated, tagged new/improved/fixed) and the roadmap (planned / building, with rough ETAs). The Overview has a "What's new" card with the latest three notes and what is being built; a dot marks notes since the member's last look. Written by the admin in Admin > Releases.
|
||||
- HOLDING TANK ALERTS: when new members land in the tank, a note at the top of every member's Overview names them (usernames) and a post goes to the team's Telegram payments topic; adopt from My line > Holding tank (your own $20 package required).
|
||||
- HOLDING TANK ALERTS: 24 hours after a new member joins (when they can be adopted), a note at the top of every member's Overview names them (usernames) and a post goes to the team's Telegram payments topic; adopt from My line > Holding tank (your own $20 package required).
|
||||
- LEGACY WELCOME (former Faucet Wave / Tier One Ads members): they join through instantadpay.com/from/faucetwave or instantadpay.com/from/tieroneads and, if their email is on the legacy list, welcome-back credits are added automatically at signup (former advertisers 500, former earners 150; once per person; credits, not POL). They land in the holding tank like any member who joins without a sponsor. SOCIALPIX GATE (2026-09-20): socialpix.club no longer takes ad posts; its visitors are sent to instantadpay.com/from/socialpix (advertiser copy by default, ?seg=earn for the earner copy). No welcome-back credits for SocialPix arrivals; they join free by email and land in the holding tank.
|
||||
- PROMO CODES: partner site owners get a reusable code; a member redeems it on a join link (?promo=CODE) or in the Overview box "Have a promo code?" and receives free ad credits (amount set per code by the admin, one use per account; codes can cap uses or expire). Credits, not POL.
|
||||
- DORMANT-LEAD RESCUE: a FREE referral (no wallet, no purchase) with no message from their sponsor for 10 days triggers a warning email + dashboard flag to the sponsor ("unreached, tank in N days"); at 14 days (warning at least 4 days old) the lead moves to the holding tank and the sponsor is told. Sponsor resets the clock with a chat, a Nudge, or the "Contacted them" button (for phone/text contact). Leads whose sponsor link resolves to nobody go to the tank after a day. Nothing on-chain moves; anyone bound by a purchase never moves.
|
||||
- PIF (pay it forward) button: on a free direct or an adopted member who has linked a wallet, the sponsor taps PIF, enters an amount (suggested: the $20 package plus fees), and their OWN wallet app opens with the member's address prefilled; the POL goes wallet to wallet. The site never touches the funds; it only logs the transaction and tells the recipient with a Polygonscan link. The gift is theirs; nothing forces a purchase. You cannot PIF someone still in the holding tank: adopt them first, they link a wallet, then the button appears.
|
||||
- PIF (pay it forward) button: on a free direct or an adopted member who has linked a wallet, the sponsor taps PIF, enters an amount (suggested: the $20 package plus fees), and their OWN wallet app opens with the member's address prefilled; the POL goes wallet to wallet. The site never touches the funds; it only logs the transaction and tells the recipient with a Polygonscan link. The gift is theirs; nothing forces a purchase. Before every PIF the member confirms a plain warning: the funds go wallet to wallet in good faith, InstantAdPay never holds or moves them and cannot reverse or recover them, and the member should only send what they are willing to give. You cannot PIF someone still in the holding tank: adopt them first, they link a wallet, then the button appears.
|
||||
- PIF RISK (Marty, 2026-09-17, say this EVERY time PIF comes up, never sell PIF as a tactic): tell the member to make contact and get an explicit commitment BEFORE sending anything. The transfer is wallet to wallet and irreversible, there is no refund or chargeback and support cannot claw it back. The recipient may go quiet, spend it on something else or never sign in again, and none of that breaks any rule. A tank member joined with nobody working with them and may never have engaged, so an unanswered PIF is the easiest money on the site to lose. Honest arithmetic: if they buy $20 the sponsor gets 50 percent back so a gift that works costs about half, and a gift to someone who never answers costs all of it. Never gift money they need, never borrow to do it. If a member asks "should I PIF someone from the tank", the answer starts with talk to them first, not with the mechanics.
|
||||
- FOUNDING WEEK / PRE-LAUNCH (Training > Founding week checklist, /launch, members only): eight items read live from the account: username, wallet linked, payouts on, level 2 qualified (2 buyers of $20+, or Qualified Start with 2 linked positions), the leader play = level 3 (5 qualifying buyers, up to 5 linked positions; then buy from the main wallet), line banner, links + play chosen (self-marked), first two placed. Reason: unqualified levels pass up, so leaders qualify BEFORE their teams' teams buy. Countdown shows when admin sets launchAt. Never call the site 'pre-launch' publicly: it is live and paying.
|
||||
- COUNTRY TARGETING (2026-09-11): New campaign form has "Show to" tier checkboxes (Tier 1 = US, CA, GB, AU, NZ, IE, DE, FR, NL, SE, NO, DK, FI, CH, AT, BE by default; Tier 2 = rest of Western/Central Europe, JP, KR, SG, HK, TW, IL, Gulf, ZA, BR, MX, AR, CL, CO, etc.; Tier 3 = everyone else; lists editable in Admin > Settings geoTier1/geoTier2). Country comes from the viewer's IP (DB-IP lite). Applies to on-site delivery of every format; a narrowed banner/text ad is NOT sent to the partner network (which is worldwide). Unknown country never matches a narrowed campaign. Campaign rows show 'tier 1+2' chips and top viewer countries.
|
||||
@@ -162,34 +434,51 @@ FACTS:
|
||||
- Onsite SOLO ADS are live: a solo ad is a full message (subject + up to 2000 characters of formatted text + your link) delivered into members' on-site Inbox (Members > Inbox). The composer in Campaigns > Solo ad has a rich-text editor (bold, headings, lists, links), lets you ATTACH one image (PNG/JPG/WebP/GIF, up to 3MB) or one video (MP4/WebM, up to 25MB), and adds a call-to-action button with a custom label that opens the target URL. Cost 5 credits per guaranteed delivery, minimum 10 deliveries (50 credits). Each member receives a given solo at most once, and never the sender's own. Readers earn 2 credits per real read (10-second dwell on the open message, up to 5 rewarded reads/day) — claimed right from the message. Compose one in Campaigns > Solo ad.
|
||||
- Campaign target URLs are checked the moment they are submitted: the page must be reachable and must ALLOW framing (no X-Frame-Options deny/sameorigin, no blocking CSP frame-ancestors), because surf views show the real site full screen. Frame-blocking or dead URLs are rejected with the exact reason; the fix is a landing page that allows framing. Login-ad targets skip the frame check (they are click-through only).
|
||||
- SPONSOR CHAT (Members): a two-way, one-to-one chat. A member can start a conversation with their DIRECT sponsor; a sponsor can message anyone in their downline. Presence-aware — when both are online it is live, otherwise a message waits in the recipient's on-site inbox and sends an email. Each member has an availability toggle in Profile (default on; turning it off stops live chats but people can still leave a note) and can mute a specific person. This is separate from the once-a-day sponsor BROADCAST to the whole downline.
|
||||
- PASSIVEDRIP (LIVE on the Earn tab for every member since 2026-10-03): https://passivedrip.com, an EARNING SITE (never call it a game): faucet claims, paid-to-click ad views, offers (offer walls) and a daily bonus roll earn coins; at 2,000 coins ($1) the balance is paid out AUTOMATICALLY in POL on Polygon to the wallet saved on PassiveDrip. The Earn tab card (More ways to earn: PassiveDrip) opens it with ONE TAP using the InstantAdPay account (no new password; it offers the member's InstantAdPay wallet to save). No income is promised.
|
||||
- POLYBREAK (opens 2026-10-13, https://polybreak.app, in Members > Games): a free Arkanoid-style brick breaker. Eight hand-built rounds that then repeat with tougher silver bricks; colored bricks break in one hit, silver takes more hits each round, gold never breaks. Capsules: S slow, C catch, L laser, E enlarge, D disrupt (three balls), B break (a gate in the right wall skips the round), P extra paddle. One-tap sign-in with the InstantAdPay account; guests can play and their first clears are paid once they sign in. PAYS POL: the first clear of each round (replays pay nothing) and catches of the purple Polygon gem (a small random amount each time, the gem appears every so often during play), into the PolyBreak game balance, sent automatically to the wallet on the member's InstantAdPay account at the payout line shown in the game; rewards are paid from the game's pool, funded by a share of the one-more-paddle visits. ONE MORE PADDLE: when the last paddle is lost, a verified visit to a member's page (or a member video) continues the round with one paddle; it uses the daily refuel allowance shared with the other games. REFERRALS: each player's share link polybreak.app/r/<username>; a sponsor earns a share of the pool income from the paddle visits of players they invited. Never state a maximum or total a player can earn and never promise income.
|
||||
- POLYWARRIORS (LIVE 2026-10-12, https://www.polywarriors.com, in Members > Games): a free cyberpunk turn-based fighting game. Recruit warriors that are each born with their own traits and rarity (Common, Rare, Epic, Legendary); fight through 24 arena rivals (a 12-rival district ladder, then a 12-rival elite circuit); challenge other members to async duels that play out while they are away. The FIRST win over each rival pays POL to the wallet on the member's InstantAdPay account (replays pay nothing). The first warrior mints to the member's wallet as an NFT on Polygon for free; after that every $5 ad package bought on InstantAdPay earns a mint pass. Fusion: three warriors of the same rarity fuse into one rarer warrior (the three are consumed). Marketplace: warriors trade between members, settled in POL. One-tap sign-in with the InstantAdPay account; guests can try fights but earn nothing until they sign in. A 40-second trailer and a promo kit are in Promo tools > Games > PolyWarriors. Never state a maximum or total a player can earn and never promise income.
|
||||
- SPELLWHEEL (LIVE 2026-10-10, https://spellwheel.com, in Members > Games): a letter-wheel word game: swipe letters on the wheel to fill the crossword grid, travel through six cozy places (chapters: the Lantern Library, the Harbor Market, the Mountain Lodge, the Desert Caravan, the Snowy Cabin, the Glass Conservatory), and solve a new daily puzzle shared by everyone. LADDER since 2026-11-02: guests play the first place only and earn nothing (their clears carry over as progress at sign-in, never as POL); a free InstantAdPay account plays the first two places; the Mountain Lodge and beyond need an active Game Pass (the game answers "for Game Pass holders" with a link to the pass). POL, first clears only: levels 0.01/0.01/0.03/0.03/0.05/0.05 and a completed place 0.1/0.1/0.5/0.5/1/1 by chapter; from the third place on, and for the daily puzzle (0.03) and the 7-day streak, only pass holders are paid; a player who has cleared every place earns nothing more until new places ship. Collected in the SpellWheel balance and sent automatically to the wallet on the member's InstantAdPay account. One-tap sign-in with the InstantAdPay account. Never state totals or promise income.
|
||||
- CLUTTERHUNT (LIVE 2026-10-03, https://clutterhunt.com, in Members > Games): a free hidden-object game. Search cozy, cluttered rooms for 12 hidden objects plus one sponsored find (a sealed letter with a sponsor's name; tapping it shows their ad). Rooms change with the seasons: the Haunted Manor (Attic, Library, Witch's Kitchen, Wizard's Study, Moonlit Greenhouse, Wine Cellar) through Oct 31, then new seasonal rooms. Objects move every round. Stars: finish under 3 minutes, use at most 1 hint, at most 6 wrong taps. 2 free hints a round; after that a short verified visit to a member's page earns a hint (shares the daily refuel allowance). Sign in with the InstantAdPay account right inside the game to save stars. PAYS POL since 2026-10-04: fixed rewards per room each season for the first clear and the first 3-star clear (more for Expert rooms, which unlock after all six rooms), collected in the ClutterHunt balance and sent automatically to the wallet on the member's InstantAdPay account once it reaches the payout amount. Players who cleared rooms before 10-04 can replay each room once to collect. NEVER state a maximum or total a player can earn (Marty's rule) and never promise earnings. HARVEST FARMHOUSE season 2026-11-01 to 11-30 (six new rooms: Farmhouse Kitchen, Pantry, Harvest Dining Room, Barn Loft, Front Porch, Cozy Parlor); the Haunted Manor closed 2026-11-01. Rewards unchanged: first clear 0.05 POL per room per season, +0.05 for three stars, Expert 0.15 and +0.10 for three stars, from the season pool while it lasts.
|
||||
- SPOOKY DOORS (Halloween season game, 2026-10-02): https://spookydoors.com, open 2026-10-04 through Halloween night (closes at midnight Central at the end of Oct 31); its Games tab card shows only during the season, with a "Limited time, ends Oct 31" ribbon. Members sign in with one tap from Members > Games. Walk the street, collect candy, avoid black cats and bats, knock on doors. Each door is a verified visit to a member's page or ad (a member video once every page has been visited), the advertiser is charged as for any visit, the player gets candy not credits; 15 doors per Central day, separate from the 20 Earn-tab visits and the 20 Drip Runner refuels. A treat is 10 candy; about 1 door in 5 is a trick (a ghost or skeleton you tap 5 times quickly; beat it for a 3 candy bonus, miss it for half the treat). If no paid ad is left for that player, the door shows a house ad for one of our own programs: a smaller treat (5 candy), and it still counts toward the 15 doors. CANDY LADDER pays POL once per rung: 100 candy 0.1 POL, 250 0.25, 500 0.5, 1,000 1, 2,000 2 (Halloween 2026 badge at 500), paid from a season pool funded by a share of door ad spend and costume sales, only while the pool covers it; the game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. COSTUMES bought with ad credits like Gem Kingdom Crowns: witch free, vampire 300 credits (longer trick timer), bedsheet ghost 300 (black cats ignore you), Lucky caramel apple 500 (+2 candy per treat); no cash value. Top 20 by candy on the season leaderboard. DOOR PACKS: creating a verified-visits campaign, the advertiser picks Everywhere (3 credits per visit, as before), Behind Spooky Doors (4 credits per door) or Golden Spooky Door (6 credits per door; the player gets +2 bonus candy). Paid up front like any visit pack. Door packs are served first on doors (Golden Doors before door packs), each player sees a pack at most once per Central day, they never run on the Earn tab or refuels during the season, and from Nov 1 any doors left run as normal visits; the campaign shows doors opened and unique players. Never promise earnings or call it income. CLOSED 2026-11-01: the season is over, the card is hidden, doors and shop are off; Candy Crunch top 10 share 27 POL (10/6/4/1x7) paid after admin approval, unlinked winners paid once they link a wallet; unpaid ladder POL (0.10+) pays once a wallet is linked; next seasonal game is Turkey Drop (opens 2026-11-02).
|
||||
- GEM KINGDOM (LIVE in the Games tab since 2026-10-02): Gem Kingdom (https://gemkingdom.app) is a free fantasy match-3: match gems so three heroes battle monsters across six chapters (Goblin Woods, the Frozen Pass, the Haunted Swamp, Dragon's Peak, the Sunken Reef, the Shadow Citadel), earn stars, and rebuild your Stronghold and forge weapons. LADDER since 2026-11-02 (Marty: the game funds itself): Chapters 1-2 open to everyone (guests included); Chapter 3 needs a free InstantAdPay account; Chapters 4-6 need the ROYAL CHARTER, $5 one time = 500 PURCHASED credits (paid credits only, never earned viewing credits), bought in the game's Specials; a Kingdom Pass or an active Game Pass counts as a Charter; anyone who had already spent $5+ of purchased credits in the game has it. It pays POL for FIRST clears only: chapters 1-3 are a taste (stages 0.01/0.01/0.02, bosses 0.1/0.2/0.5, about 1.2 POL in all); chapters 4-6 pay Charter holders only (stages 0.08/0.12/0.15, bosses 3/5/7.5 for the Ember Dragon, Kraken and Shadow King, about 19 POL for the full ladder) and a player's chapter 4-6 total never exceeds what they paid in. Replays pay nothing; after the Shadow King nothing more is paid until a new chapter ships. The game balance is sent to the member's InstantAdPay wallet on Polygon at 0.25 POL. Rewards come from a pool funded by a share of Crown purchases and pay only while the pool has funds; never promise earnings or call it income. No referral bonus on game clears. Crowns, its upgrade currency, are bought with your InstantAdPay ad credits: tap Buy in the game's Crown Shop, confirm on InstantAdPay (top up with a pack if you are short), and you land back in the game with the Crowns added. Crowns buy buildings, weapons, battle boosts and a revive after a defeat. Sign in with your InstantAdPay account to save progress, earn badges and appear in the Game Achievements posts in the Crypto Team Build group. Never promise an amount beyond the posted rewards. (2026-10-03) FREE REVIVE: after a defeat, a short verified visit to a member's page (InstantAdPay verified-visit flow inside the game, shares the 20-a-day refuel allowance with Drip Runner) revives the party once per battle; a revived win earns at most 2 stars. SPECIALS in the Crown shop: Hero Bundle (one time, $5 = 500 credits: a tier-1 forge weapon, one building level, 60 Crowns), Kingdom Pass ($10 = 1,000 credits for 30 days: 10 Crowns a day credited on the first visit each Central day, a 25-Crown chest every 7 days, the three Royal hero looks; no auto-renew, buying again adds 30 days), Hero looks (cosmetic only: Halloween looks Pumpkin Knight, Moon Witch, Scarecrow Ranger for 40 Crowns each, sold through Oct 31 and kept forever; Royal looks with the Pass). Only the purchased-credit part of a purchase funds the POL reward pool.
|
||||
- GAME POL TO ANY LINKED WALLET (2026-10-27, Marty): game POL (Drip Runner, Gem Kingdom, ClutterHunt, Spooky Doors, Road Agent, PolyBreak, SpellWheel, PolyWarriors) is paid to the wallet LINKED to the member's InstantAdPay account (one free signature on the Wallet tab, https://instantadpay.com/my#wallet). Activation is NOT needed: a linked wallet that has not switched on payouts (for example a holding-tank member waiting for a sponsor) is paid too. InstantAdPay hands the linked wallet to every game where the member has a balance (hourly, and on every sign-in to a game), and the game sends the POL on its own sweep once the balance reaches that game's payout line, including everything earned before the link. A game that already holds a different wallet keeps paying that one (it is never replaced automatically). Players with no linked wallet get at most three reminders ("X POL is waiting for your wallet": link your wallet, one free signature, and it's sent automatically, including everything you've earned so far), and in the games the reward screen says "Link your wallet to receive this POL" with the same link. Never tell a member to switch on payouts to get game POL.
|
||||
- GAME TIERS (2026-11-02, Marty: every game funds itself; rolling out game by game, no announcements): guests get a first slice and earn nothing; a free InstantAdPay account gets a small taste of POL; the full content and the full rewards need a purchase (the $5 Game Pass, or a one-time unlock where the content is finite). Done so far: GEM KINGDOM (Royal Charter, see its own line), POLHUNTER (a free account hunts ONE code a day drawn on 0.02 to 0.10 POL; Game Pass holders hunt five a day at the full 0.05 to 1 POL draw and alone qualify for the weekly prizes and the Mystery Hunt Box; advertiser-funded finds pay the advertiser's amount on every tier), SPELLWHEEL (guests the first place, a free account the first two, the Mountain Lodge and beyond plus daily-puzzle and streak POL for Game Pass holders; see its own line). ALL OTHER GAMES since the evening of 2026-11-02: guests play but earn no POL (guest progress carries over at sign-in, guest POL does not); a free account earns 25% of each one-time progress reward (chapters, rounds, sectors, rungs, bosses, depth marks) and keeps the existing free daily limits on repeatable rewards; Game Pass holders earn 100%. Specifics: CLUTTERHUNT guests room 1, a free account rooms 1 and 2 at a quarter, Game Pass rooms 3 to 6 and Expert; POL MINER guests dig the Dirt (to 10 m), a free account to 24 m, Game Pass from the Gravel down; POLYWARRIORS the full table needs a PAID warrior mint or the Game Pass (the free first mint does not count), free accounts earn a quarter and cannot place for weekly prizes; TURKEY DROP weekly top-3 prizes go to Game Pass holders from the week of Nov 9 (the week of Nov 2 settles as announced); Drip Runner, PolyBreak, Road Agent and Spooky Doors follow the general rule. Nothing already paid changed.
|
||||
- GAMES TAB (2026-10-01): Members > Games (/my#games) shows one card per network game (as of 2026-10-15: PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Road Agent, Spooky Doors during Halloween; all pay POL to the member's InstantAdPay wallet), with their own progress and a Play button that signs them in with one tap; new games appear there as they launch (PolHunter is one card). DRIP RUNNER (https://driprunner.app, LIVE for every member since 2026-10-01): tap-to-hop runner; gold drips, magenta bots, orange firewalls from chapter 2; each chapter has a drip goal for one run; the FIRST clear of a chapter pays a small POL drip (amount set by the admin, shown in the game) into the game balance, replays pay nothing; the balance is sent on Polygon to the member's InstantAdPay wallet once it reaches the payout line shown in the game. REFUELS: a run that ends can be refuelled with a verified visit to a member's page (once every page has been visited: a member video, a page seen more than 7 days ago again, or one of the network's own programs, so a game visit is never empty; since 2026-10-28 for every game's refuel, paddle, continue, hint and supply crate), up to 20 a day, separate from the 20 Earn-tab visits; the advertiser is charged as for any visit, the player gets fuel not credits. The POL pool is funded ONLY by a share of refuel ad spend plus POL spent in the hangar, so drips depend on refuels and can be zero when the pool is empty; say so honestly. HANGAR: Drip Magnet and Courier Mk II cost drips (game currency); Shield Core and Slow Field cost POL from the game balance, which returns to the pool. GUESTS can try a run without signing in; their clears pay once they sign in. REFERRALS: each player's share link /r/<username>; when members whose InstantAdPay sponsor is that player refuel, a share (10 percent by default) of each refuel's pool income goes to the sponsor's game balance. Telegram posts achievement badges (chapters, unlocks, refuel milestones, payouts). Never promise amounts or income. The public list of every game, open now and opening next, is https://instantadpay.com/games (shareable; add ?ref=<username> to keep the referral).
|
||||
- Every purchase is split by an immutable smart contract in the same transaction: 50% direct sponsor, 20% level 2, 10% level 3, 20% platform. No withdrawals exist; money lands in members' own wallets instantly.
|
||||
- Qualification: level 1 open to all; 2 buyers of $20+ unlock level 2; 5 unlock level 3. Unqualified shares pass up the sponsor line, checking up to 25 positions, else the platform receives them. Qualification cannot be bought and never expires.
|
||||
- Every member gets a share link immediately (site code, /join/<code>); the contract locks a buyer to their sponsor at the buyer's FIRST purchase, so members should switch on payouts before their referrals buy.
|
||||
- Transparency: live ledger at /ledger streams every chain event, and EVERY transaction row carries a clickable "verify" link — to the public block explorer when the chain has one, or to the built-in transaction viewer at /tx/<hash> (block, time, from/to, value, gas, decoded events, read live from the node). Plain-language contract review at /contract; the verified source is public.
|
||||
- The contract cannot be paused, upgraded, or drained. The operator can only manage the ad catalog ($1-$500 bounds, 24h price timelock) and rotate keys.
|
||||
|
||||
PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#wallet, /my#profile. Public: /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
|
||||
PAGES (the ONLY addresses that exist; never invent others): home https://instantadpay.com, member dashboard https://instantadpay.com/my with tabs as hashes: /my#overview, /my#line (My line, holding tank, prospects), /my#pipeline, /my#buy (Buy packages, Qualified Start, Buy POL with a card), /my#campaigns (New campaign, campaign rows, Credit activity), /my#earn (Watch ads, Watch videos, Verified visits, Inbox), /my#earnings (Trace a payment, payouts, referrals, purchases), /my#promo (Your links, Social posts, Text a friend, Email swipes, Banners, Wall, Objections, Videos, Toolkit), /my#training, /my#games (PolHunter, Drip Runner, Gem Kingdom, ClutterHunt, SpellWheel, PolyWarriors, PolyBreak, Spooky Doors in season), /games (public list of every game), /my#wallet, /my#profile, /my#help (Help: support tickets). Public: /support (contact form for anyone signed out or locked out; support@instantadpay.com also works), /join/<username> (invite page, ?v=angle), /wall/<username>, /b/<username>/<badge>, /handout/<username>, /ledger, /tx/<hash>, /contract, /leaderboard, /whats-new, /blog, /plays, /wallets (members), /launch (members), /partners, /earning, /shorts, /terms, /privacy, /disclaimer, /from/faucetwave, /from/tieroneads and /from/socialpix.
|
||||
|
||||
RULES:
|
||||
- 1 to 4 sentences, plain text, no markdown, include full URLs when pointing at a page, and only URLs from the PAGES list above.
|
||||
- Never send someone to a warning, notice, guide, document or page section that is not named above. Saying "read the full warning on your training page" invents something that does not exist and the member will go looking for it. If the answer is not on a page in the PAGES list, give the answer here or say you are not sure and point to /contract, the ledger, or their sponsor.
|
||||
- Plain ASCII only: a normal hyphen, never a non-breaking hyphen, and no smart quotes.
|
||||
- NEVER promise or estimate income. This is an advertising service with a referral program, never an investment. Be honest about risk: crypto transactions are irreversible, nobody earns unless real ad purchases happen.
|
||||
- No em dashes. If you do not know, say so and point to /contract or the ledger.`;
|
||||
- No em dashes. If you do not know, say so and point to /contract or the ledger.
|
||||
- Anything about one person's own account (a missing payout, a sign-in that will not work, a charge, a bug) you cannot look up: say so and point them to Help at https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out.` + (kbBlock ? '\n\n' + kbBlock : '');
|
||||
}
|
||||
|
||||
function askAI(message, historyText) {
|
||||
// OPENROUTER_URL overrides the endpoint (local tests point it at a mock); production uses openrouter.ai
|
||||
function endpoint() {
|
||||
try { return new URL(process.env.OPENROUTER_URL || 'https://openrouter.ai/api/v1/chat/completions'); } catch (e) { return new URL('https://openrouter.ai/api/v1/chat/completions'); }
|
||||
}
|
||||
function askAI(message, historyText, kbBlock) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({
|
||||
model: MODEL,
|
||||
reasoning: { enabled: false }, // 2026-10-16: deepseek-v4-flash now thinks by default and spent the whole max_tokens on it (empty answers)
|
||||
max_tokens: 300,
|
||||
messages: [
|
||||
{ role: 'system', content: systemPrompt() },
|
||||
{ role: 'system', content: systemPrompt(kbBlock) },
|
||||
...(historyText ? [{ role: 'user', content: 'Earlier context: ' + historyText.slice(0, 800) }] : []),
|
||||
{ role: 'user', content: String(message).slice(0, 600) }
|
||||
]
|
||||
});
|
||||
const req = https.request({ hostname: 'openrouter.ai', path: '/api/v1/chat/completions', method: 'POST',
|
||||
const ep = endpoint();
|
||||
const req = (ep.protocol === 'http:' ? http : https).request({ hostname: ep.hostname, port: ep.port || undefined, path: ep.pathname + ep.search, method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body) }, timeout: 30000 },
|
||||
res => {
|
||||
@@ -215,22 +504,46 @@ function askAI(message, historyText) {
|
||||
});
|
||||
}
|
||||
|
||||
async function answer(message, historyText) {
|
||||
const UNSURE_RE = /(not sure|do not know|don't know|cannot help|can't help|unable to help|no way for me|i (can|could) not (see|check|look)|contact support|reach support|support (ticket|desk)|\/support\b|my#help)/i;
|
||||
// every reply leaves without em dashes (Marty's voice rule; the model slips one in now and then, 2026-10-20)
|
||||
async function answer(message, historyText) { const r = await answerRaw(message, historyText); if (r && typeof r.reply === 'string') r.reply = r.reply.replace(/\s*\u2014\s*/g, ', '); return r; }
|
||||
async function answerRaw(message, historyText) {
|
||||
const msg = String(message || '').trim();
|
||||
if (!msg) return { error: 'Say something first.' };
|
||||
for (const c of CANNED) if (c.re.test(msg)) return { reply: c.a, canned: true };
|
||||
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it.' };
|
||||
// fast path: the knowledge base's instant answers (seeded from CANNED); the in-code list only if the KB store is down
|
||||
let hit = null, kbOk = true;
|
||||
try { hit = await kb.fastPath(msg); } catch (e) { kbOk = false; console.error('kb fast path', e.message); }
|
||||
if (hit && hit.id === 'refuel' && !REFUEL_ON()) return { reply: REFUEL_OFF_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'polminer' || hit.id === 'c-polminer') && !pmLive()) return { reply: POLMINER_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'turkeydrop' || hit.id === 'c-turkeydrop') && !tdLive()) return { reply: tdAnswer(), canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'game-pass' || hit.id === 'c-game-pass')) return Object.assign({ reply: gpWithTd(hit.answer), canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'turkeydrop' && !tdLive() ? { reply: tdAnswer(), canned: true } : c.id === 'game-pass' ? { reply: gpWithTd(c.a), canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
if (hit && (hit.id === 'warpwares' || hit.id === 'c-warpwares') && !wwLive()) return { reply: wwAnswer(), canned: true, kb: hit.id };
|
||||
if (hit && isBixId(hit.id) && !bixLive()) return { reply: BIX_SOON_ANSWER, canned: true, kb: hit.id };
|
||||
if (hit && (hit.id === 'network-rate' || hit.id === 'c-network-rate') && (SYN_N() !== 4 || SYN_T() !== 10)) return { reply: netRateAnswer(SYN_N()), canned: true, kb: hit.id };
|
||||
if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, hit.handoff ? { handoff: true } : {});
|
||||
if (!kbOk) for (const c of CANNED) if (c.re.test(msg)) return c.id === 'refuel' && !REFUEL_ON() ? { reply: REFUEL_OFF_ANSWER, canned: true } : c.id === 'polminer' && !pmLive() ? { reply: POLMINER_SOON_ANSWER, canned: true } : c.id === 'warpwares' && !wwLive() ? { reply: wwAnswer(), canned: true } : isBixId(c.id) && !bixLive() ? { reply: BIX_SOON_ANSWER, canned: true } : c.id === 'network-rate' && SYN_N() !== 4 ? { reply: netRateAnswer(SYN_N()), canned: true } : Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {});
|
||||
// retrieval: the closest entries ride along in the system prompt (a short follow-up borrows words from the chat so far)
|
||||
let kbBlock = '', kbIds = [];
|
||||
try {
|
||||
const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg;
|
||||
const hits = await kb.context(query, 5);
|
||||
const hitsOk = hits.filter(h => (pmLive() || !/^(c-)?polminer$/.test(String(h.entry && h.entry.id))) && (wwLive() || !/^(c-)?warpwares$/.test(String(h.entry && h.entry.id))) && (bixLive() || !isBixId(h.entry && h.entry.id)) && (tdLive() || !/^(c-)?turkeydrop$/.test(String(h.entry && h.entry.id)))); // not live yet: keep its answer out of the prompt
|
||||
kbBlock = kb.promptBlock(hitsOk); kbIds = hitsOk.map(h => h.entry.id);
|
||||
} catch (e) { console.error('kb search', e.message); }
|
||||
if (!enabled()) return { reply: 'Good question. The quick answers I have cover packages, payouts, qualification, and joining; for anything deeper, the plain-language contract review at https://instantadpay.com/contract covers most of it, or tap "Send this to support" and Marty will answer.', handoff: true };
|
||||
// One retry: the usual failure is a single provider dropping the request, and asking
|
||||
// again almost always lands. Only after both fail do we admit defeat.
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try { return { reply: await askAI(msg, historyText) }; }
|
||||
// handoff: the answer admits it cannot help, so the widget offers "Send this to support" (help desk, 2026-10-16)
|
||||
try { const reply = await askAI(msg, historyText, kbBlock); return Object.assign({ reply }, kbIds.length ? { kb: kbIds } : {}, UNSURE_RE.test(reply) ? { handoff: true } : {}); }
|
||||
catch (e) {
|
||||
console.error('chat AI failed (attempt ' + (attempt + 1) + ')', e.message);
|
||||
if (attempt === 0) await new Promise(r => setTimeout(r, 700));
|
||||
}
|
||||
}
|
||||
// Never a dead end: say plainly that it was us, and offer a person.
|
||||
return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, the plain-language contract review at https://instantadpay.com/contract and the live ledger at https://instantadpay.com/ledger cover most of the deep questions, and your sponsor can be reached from Members > My line.' };
|
||||
return { reply: 'That one did not come back to me just now, and that is our side, not your question. Ask me again in a moment and it should go through. If it is urgent, tap "Send this to support" and Marty will answer, or reach your sponsor from Members > My line.', handoff: true };
|
||||
}
|
||||
|
||||
module.exports = { init, answer, enabled, KNOWLEDGE_DATE };
|
||||
module.exports = { init, answer, enabled, KNOWLEDGE_DATE, CANNED, seeds, systemPrompt };
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
const walletnudge = require('./walletnudge'); // POL waiting in the games with no wallet linked
|
||||
|
||||
let DATA_DIR = null, chain = null, accounts = null, mailer = null;
|
||||
const DAY = 86400000;
|
||||
@@ -55,12 +56,16 @@ async function member(id) {
|
||||
const STALL_DAYS = 3;
|
||||
async function describe(acct, now = Date.now()) {
|
||||
const mm = await member(acct.memberId);
|
||||
// unknown = the member is on chain but the read failed just now (member() swallows RPC errors and caches null for a
|
||||
// minute); rungFor would call them "payouts on, no purchase" and the coach would mail a buyer the first-package nudge
|
||||
// (2026-10-31 on LinkSpin: Marty, 4 purchases and 7 buyers, got "See a payout land"). Callers that mail must skip unknown.
|
||||
const unknown = !!(acct.memberId && !mm);
|
||||
const rung = rungFor(acct, mm);
|
||||
const last = Math.max(acct.created || 0, acct.lastSeen || 0);
|
||||
const quietDays = Math.floor((now - last) / DAY);
|
||||
const stalled = rung < 6 && quietDays >= STALL_DAYS;
|
||||
const stalled = !unknown && rung < 6 && quietDays >= STALL_DAYS;
|
||||
const R = RUNGS[rung];
|
||||
return { rung, label: R.label, next: R.next, say: R.say, quietDays, stalled, buyerCount: mm ? mm.buyerCount : 0,
|
||||
return { rung, label: R.label, next: R.next, say: R.say, quietDays, stalled, unknown, buyerCount: mm ? mm.buyerCount : 0,
|
||||
counted: !!(mm && mm.countedAsBuyer), joined: acct.created, lastSeen: acct.lastSeen || 0, onchainSponsorId: mm ? mm.sponsorId : null };
|
||||
}
|
||||
// coaching view for a sponsor: every direct, ladder rung, stalled flag, what to say
|
||||
@@ -77,7 +82,10 @@ async function coachView(email) {
|
||||
// no sponsor (or a different one) is in this line on the site but pays this member nothing.
|
||||
c.bound = c.onchainSponsorId == null ? null : (myId > 0 && c.onchainSponsorId === myId);
|
||||
c.free = !d.memberId; // still free: can be released to the holding tank (pay it forward)
|
||||
c.address = (!d.memberId && d.address) ? d.address : null; // linked wallet of a free direct: the PIF gift target
|
||||
// PIF gift target: a direct with a linked wallet who has NOT bought a package yet (rung < 3). Switching payouts on
|
||||
// no longer hides the button (Marty 2026-10-07: a prospect with payouts on still needed his first $20).
|
||||
c.address = (d.address && c.rung < 3) ? d.address : null;
|
||||
c.polWaiting = d.address ? 0 : walletnudge.waitingFor(d.email); // earned in the games, stuck behind a missing wallet
|
||||
out.push(Object.assign({ email: d.email, name: d.username ? '@' + d.username : (d.memberId ? 'member #' + d.memberId : d.email.replace(/^(.).*(@.*)$/, '$1***$2')), memberId: d.memberId || 0 }, c));
|
||||
}
|
||||
// most actionable first: stalled lowest rung, then quiet days
|
||||
@@ -176,6 +184,8 @@ function clickSource(referer) {
|
||||
} catch (e) { return 'unknown'; }
|
||||
}
|
||||
async function recordClick(campaignId, referer) { try { await impl().addClick(Number(campaignId), clickSource(referer), Date.now()); } catch (e) {} }
|
||||
// clicks on these campaigns since a moment (the Engine Room's clicks-this-week dial, 2026-10-24)
|
||||
async function clicksSince(campaignIds, since) { if (!campaignIds.length) return 0; const rows = await impl().clicksFor(campaignIds.map(Number)); return rows.filter(r => Number(r.ts) >= since).length; }
|
||||
async function clickSources(campaignIds) {
|
||||
const rows = await impl().clicksFor(campaignIds.map(Number));
|
||||
const out = {};
|
||||
@@ -189,7 +199,7 @@ async function linkStats(email) {
|
||||
const now = Date.now();
|
||||
const views = await impl().views(tokens, 0);
|
||||
const joined = await accounts.listByReferrer(tokens);
|
||||
const ANG = ['', 'instant', 'adspend', 'free', 'ledger', 'two', 'page']; // page = a viral link (any page + ?ref=)
|
||||
const ANG = ['', 'instant', 'adspend', 'free', 'ledger', 'two', 'wide', 'page']; // page = a viral link (any page + ?ref=)
|
||||
const rows = {};
|
||||
for (const k of ANG) rows[k] = { angle: k || 'plain', views30: 0, views: 0, joins: 0, buyers: 0 };
|
||||
const src = {};
|
||||
@@ -205,6 +215,103 @@ async function linkStats(email) {
|
||||
return { angles: Object.values(rows), sources, totalViews: views.length, totalJoins: joined.length };
|
||||
}
|
||||
|
||||
// ---- the weekly member email (Marty, 2026-09-14; reformatted 2026-10-01 because one long text block was hard to read):
|
||||
// one section per topic, each with a heading, the number that matters up front and ONE button. Sent as HTML with a
|
||||
// plain-text twin built from the same sections.
|
||||
const SITE = 'https://instantadpay.com';
|
||||
const escH = v => String(v == null ? '' : v).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||
const n0 = v => Number(v || 0).toLocaleString('en-US');
|
||||
async function weeklyDigest(acct, view, lbWeek, tankN, now) {
|
||||
const name = acct.username ? '@' + acct.username : 'there';
|
||||
const S = []; // { title, big, bigLabel, lines[], rows[[label, value]], quotes[{to, text}], button{label, url} }
|
||||
// credits: they sit on positions and each campaign pays from one, so the pooled total alone misleads
|
||||
// members with linked positions (Jim Watts, 2026-09-27: "561 unspent" but a top-up allowed 19)
|
||||
try {
|
||||
const ids = [acct.memberId, ...(await accounts.positions(acct.email)).map(p => p.memberId)].filter(Boolean);
|
||||
const bal = await X.ads.balances(ids, acct.email);
|
||||
if (bal.available > 0) {
|
||||
const onPos = (bal.per || []).filter(p => p.avail > 0).sort((a, b) => b.avail - a.avail);
|
||||
const loose = (bal.credited || 0) + (bal.earned || 0);
|
||||
const sec = { title: 'Ad credits ready to use', big: n0(bal.available), bigLabel: 'credits not running yet', lines: [], button: { label: 'Start a campaign', url: SITE + '/my#campaigns' } };
|
||||
if (onPos.length > 1) {
|
||||
sec.rows = onPos.map(p => ['Position #' + p.memberId, n0(p.avail)]);
|
||||
if (loose) sec.rows.push(['Any position can use', n0(loose)]);
|
||||
sec.lines.push('Each campaign spends from one position. Start from #' + onPos[0].memberId + ' to use the most credits at once.');
|
||||
}
|
||||
sec.lines.push('Point the campaign at your invite link so the views bring people to you.');
|
||||
S.push(sec);
|
||||
} else if (bal.inCampaigns > 0) S.push({ title: 'Ad credits', big: n0(bal.inCampaigns), bigLabel: 'credits working in live campaigns', lines: ['Everything you have is running. Nice.'] });
|
||||
} catch (e) {}
|
||||
// streak
|
||||
try {
|
||||
const st = await X.ads.viewStatus(acct.email);
|
||||
if (st.streakDay > 1) S.push({ title: 'Daily claim streak', big: 'Day ' + st.streakDay, bigLabel: 'of your streak. Today’s claim pays ' + n0(st.claimCredits) + ' credits.', lines: ['Miss a day and the streak starts over.'], button: { label: 'Claim today', url: SITE + '/my#earn' } });
|
||||
else S.push({ title: 'Free daily credits', lines: ['View five ads and claim once a day. The claim grows 5, 7, 10 credits, then 25 on every seventh day in a row.'], button: { label: 'Start today', url: SITE + '/my#earn' } });
|
||||
} catch (e) {}
|
||||
// contest
|
||||
let first = false;
|
||||
if (lbWeek && lbWeek.top) {
|
||||
const me = lbWeek.top.find(r => r.name === '@' + acct.username) || null;
|
||||
let mine = me; if (!mine) { try { mine = (await X.lb().view('week', acct.email)).me; } catch (e) {} }
|
||||
first = !!(lbWeek.top.length && lbWeek.top[0].name === '@' + acct.username);
|
||||
const sec = { title: 'This week’s referral contest', lines: [], button: { label: 'See the leaderboard', url: SITE + '/leaderboard' } };
|
||||
if (lbWeek.prize) sec.intro = 'Prizes: ' + lbWeek.prize + '.';
|
||||
if (lbWeek.top.length) sec.rows = lbWeek.top.slice(0, 3).map(r => [r.rank + '. ' + r.name, r.sales + ' sold']);
|
||||
else sec.lines.push('No sales yet. The first one takes the top spot.');
|
||||
if (mine) { sec.big = '#' + mine.rank; sec.bigLabel = 'is your place, with ' + mine.sales + ' sold'; }
|
||||
else sec.lines.push('You are not on the board yet. One $20 package bought by someone you sponsor puts you there.');
|
||||
S.push(sec);
|
||||
}
|
||||
// tank
|
||||
if (tankN > 0 && acct.memberId) S.push({ title: 'Holding tank', big: n0(tankN), bigLabel: 'member' + (tankN === 1 ? '' : 's') + ' waiting for a sponsor', lines: ['Adopt one from My line and they join your team.'], button: { label: 'Adopt a member', url: SITE + '/my#line' } });
|
||||
// line (sponsors only)
|
||||
if (view.directs.length) {
|
||||
const week = view.directs.filter(d => now - d.joined < 7 * DAY).length;
|
||||
const sec = { title: 'Your team', rows: [['Direct members', n0(view.directs.length)], ['Joined this week', n0(week)], ['Gone quiet', n0(view.stalled)]], lines: [], button: { label: 'Open My line', url: SITE + '/my#line' } };
|
||||
const q = view.directs.filter(d => d.stalled).slice(0, 3).map(d => ({ to: d.name, text: d.say.replace('{{name}}', d.name.replace(/^@/, '')) }));
|
||||
if (q.length) { sec.lines.push('A quick message gets most people moving again. Copy these:'); sec.quotes = q; }
|
||||
S.push(sec);
|
||||
}
|
||||
const subject = first ? 'You are #1 this week on InstantAdPay' : 'Your week on InstantAdPay: credits, streak, contest';
|
||||
const tip = { text: 'Short on time? The twenty-minute day: claim your set, message one person on your team, check the tank, start one new conversation.', link: SITE + '/blog/the-twenty-minute-day' };
|
||||
const legal = 'No income is guaranteed. Credits are advertising, not money.';
|
||||
|
||||
// plain text twin
|
||||
const T = ['Hi ' + name + ', here is your week on InstantAdPay.', ''];
|
||||
for (const s of S) {
|
||||
T.push(s.title.toUpperCase());
|
||||
if (s.big) T.push(s.big + ' ' + s.bigLabel);
|
||||
if (s.intro) T.push(s.intro);
|
||||
for (const r of s.rows || []) T.push(' ' + r[0] + ': ' + r[1]);
|
||||
for (const l of s.lines) T.push(l);
|
||||
for (const q of s.quotes || []) T.push(' To ' + q.to + ': "' + q.text + '"');
|
||||
if (s.button) T.push(s.button.label + ': ' + s.button.url);
|
||||
T.push('');
|
||||
}
|
||||
T.push(tip.text + ' ' + tip.link, '', 'InstantAdPay · ' + SITE + '/my', legal);
|
||||
|
||||
// html
|
||||
const btn = b => '<a href="' + escH(b.url) + '" style="display:inline-block;background:#1e3a8a;color:#ffffff;text-decoration:none;font-weight:600;font-size:15px;padding:11px 20px;border-radius:8px">' + escH(b.label) + '</a>';
|
||||
const card = s => '<tr><td style="padding:0 0 14px"><table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#ffffff;border:1px solid #e3e6ee;border-radius:12px"><tr><td style="padding:18px 20px">'
|
||||
+ '<div style="font-size:12px;letter-spacing:.06em;text-transform:uppercase;color:#6b7280;font-weight:700;margin:0 0 6px">' + escH(s.title) + '</div>'
|
||||
+ (s.big ? '<div style="margin:0 0 10px"><span style="font-size:30px;font-weight:800;color:#111827">' + escH(s.big) + '</span> <span style="font-size:15px;color:#4b5563">' + escH(s.bigLabel) + '</span></div>' : '')
|
||||
+ (s.intro ? '<p style="margin:0 0 8px;font-size:15px;line-height:1.5;color:#374151">' + escH(s.intro) + '</p>' : '')
|
||||
+ (s.rows ? '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin:0 0 10px;font-size:15px">' + s.rows.map(r => '<tr><td style="padding:5px 0;border-bottom:1px solid #f0f1f5;color:#374151">' + escH(r[0]) + '</td><td align="right" style="padding:5px 0;border-bottom:1px solid #f0f1f5;color:#111827;font-weight:700">' + escH(r[1]) + '</td></tr>').join('') + '</table>' : '')
|
||||
+ s.lines.map(l => '<p style="margin:0 0 10px;font-size:15px;line-height:1.5;color:#374151">' + escH(l) + '</p>').join('')
|
||||
+ (s.quotes || []).map(q => '<div style="margin:0 0 10px;padding:10px 12px;background:#f5f6fa;border-radius:8px;font-size:14px;line-height:1.5;color:#374151"><b style="color:#111827">To ' + escH(q.to) + '</b><br>' + escH(q.text) + '</div>').join('')
|
||||
+ (s.button ? '<div style="margin:6px 0 0">' + btn(s.button) + '</div>' : '')
|
||||
+ '</td></tr></table></td></tr>';
|
||||
const html = '<!doctype html><html><body style="margin:0;padding:0;background:#f3f4f8">'
|
||||
+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f3f4f8"><tr><td align="center" style="padding:20px 12px">'
|
||||
+ '<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="max-width:560px;font-family:-apple-system,Segoe UI,Roboto,Arial,sans-serif">'
|
||||
+ '<tr><td style="padding:4px 4px 16px"><div style="font-size:20px;font-weight:800;color:#111827">Your week on InstantAdPay</div><div style="font-size:15px;color:#4b5563;margin-top:4px">Hi ' + escH(name) + ', here is where things stand.</div></td></tr>'
|
||||
+ S.map(card).join('')
|
||||
+ '<tr><td style="padding:2px 4px 14px;font-size:14px;line-height:1.5;color:#4b5563">' + escH(tip.text) + ' <a href="' + escH(tip.link) + '" style="color:#1e3a8a">Read how</a></td></tr>'
|
||||
+ '<tr><td style="padding:0 4px 8px;font-size:12px;color:#9ca3af">InstantAdPay · <a href="' + SITE + '/my" style="color:#9ca3af">' + 'instantadpay.com/my</a><br>' + escH(legal) + '</td></tr>'
|
||||
+ '</table></td></tr></table></body></html>';
|
||||
return { subject, text: T.join('\n'), html, sections: S };
|
||||
}
|
||||
|
||||
// ---- automatic nudges to stalled members + weekly digest to sponsors ----
|
||||
let ticking = false;
|
||||
const NUDGE_GAP = 5 * DAY;
|
||||
@@ -217,6 +324,7 @@ async function nudgeTick() {
|
||||
const all = await accounts.listAll(5000);
|
||||
for (const acct of all) {
|
||||
if (!acct.email || !acct.created || now - acct.created < STALL_DAYS * DAY) continue;
|
||||
if (X.adminEmail && String(acct.email).toLowerCase() === String(X.adminEmail).toLowerCase()) continue; // the site owner is never coached (2026-10-31)
|
||||
const c = await describe(acct, now);
|
||||
if (!c.stalled) continue;
|
||||
const R = RUNGS[c.rung]; if (!R.mail) continue;
|
||||
@@ -232,7 +340,7 @@ async function nudgeTick() {
|
||||
// weekly member email (Marty, 2026-09-14, modelled on the mailer.gold weekly): credits sitting unspent,
|
||||
// the streak, the contest standings with the member's own rank, the tank, and the line for sponsors
|
||||
let lbWeek = null; try { lbWeek = X.lb ? await X.lb().view('week') : null; } catch (e) {}
|
||||
let tankN = 0; try { tankN = X.tank ? (await X.tank.waiting()).length : 0; } catch (e) {}
|
||||
let tankN = 0; try { tankN = X.tank ? (await X.tank.adoptable()).length : 0; } catch (e) {}
|
||||
for (const acct of all) {
|
||||
if (!acct.email) continue;
|
||||
const lastD = await impl().lastDigest(acct.email);
|
||||
@@ -242,48 +350,8 @@ async function nudgeTick() {
|
||||
// audience: sponsors with directs (as before) unless the admin switched the weekly on for every member
|
||||
const everyone = X.siteConfig && String(X.siteConfig().memberWeeklyEmail || '0') === '1';
|
||||
if (!everyone && !view.directs.length) { await impl().setDigest(acct.email, now); continue; }
|
||||
const name = acct.username ? '@' + acct.username : 'there';
|
||||
const parts = ['Hi ' + name + ', your week on InstantAdPay:'];
|
||||
// credits
|
||||
try {
|
||||
const ids = [acct.memberId, ...(await accounts.positions(acct.email)).map(p => p.memberId)].filter(Boolean);
|
||||
const bal = await X.ads.balances(ids, acct.email);
|
||||
if (bal.available > 0) {
|
||||
// credits sit on positions and each campaign pays from one, so a pooled total alone misleads
|
||||
// members with linked positions (Jim Watts, 2026-09-27: "561 unspent" but a top-up allowed 19)
|
||||
const onPos = (bal.per || []).filter(p => p.avail > 0).sort((a, b) => b.avail - a.avail);
|
||||
const loose = (bal.credited || 0) + (bal.earned || 0);
|
||||
let where = '';
|
||||
if (onPos.length > 1) where = ' They are spread across your positions: ' + onPos.map(p => '#' + p.memberId + ' has ' + p.avail.toLocaleString()).join(', ') + (loose ? ', plus ' + loose.toLocaleString() + ' that any position can use' : '') + '. Each campaign pays from one position, so start a new campaign from #' + onPos[0].memberId + ' to use the most in one go.';
|
||||
parts.push('- You have ' + bal.available.toLocaleString() + ' ad credits sitting unspent. That is ' + bal.available.toLocaleString() + ' cents of delivery doing nothing.' + where + ' Campaigns > New campaign, point it at your invite link: https://instantadpay.com/my#campaigns');
|
||||
}
|
||||
else if (bal.inCampaigns > 0) parts.push('- All ' + bal.inCampaigns.toLocaleString() + ' of your credits are working in live campaigns. Good.');
|
||||
} catch (e) {}
|
||||
// streak
|
||||
try {
|
||||
const st = await X.ads.viewStatus(acct.email);
|
||||
if (st.streakDay > 1) parts.push('- Your claim streak is on day ' + st.streakDay + '. Today\'s claim pays ' + (st.claimCredits || 0) + ' credits; miss a day and it restarts at 5.');
|
||||
else parts.push('- Five ads and a claim a day is the free way in: 5, 7, 10, then 25 credits every seventh day in a row: https://instantadpay.com/my#earn');
|
||||
} catch (e) {}
|
||||
// contest
|
||||
if (lbWeek && lbWeek.top) {
|
||||
const me = lbWeek.top.find(r => r.name === '@' + acct.username) || null;
|
||||
let mine = me; if (!mine) { try { mine = (await X.lb().view('week', acct.email)).me; } catch (e) {} }
|
||||
parts.push('- Referral contest this week (' + (lbWeek.prize || 'credits to the top 3') + '): ' + (lbWeek.top.length ? lbWeek.top.slice(0, 3).map(r => r.rank + '. ' + r.name + ' (' + r.sales + ' sold)').join(', ') : 'no sales yet, first sale takes the top spot') + '.'
|
||||
+ (mine ? ' You are #' + mine.rank + ' with ' + mine.sales + ' sold.' : ' You are not on the board yet; one $20 package bought by someone you sponsor puts you there.') + ' https://instantadpay.com/leaderboard');
|
||||
}
|
||||
// tank
|
||||
if (tankN > 0 && acct.memberId) parts.push('- ' + tankN + ' member' + (tankN === 1 ? ' is' : 's are') + ' waiting for a sponsor in the holding tank. Adopt one from My line: https://instantadpay.com/my#line');
|
||||
// line (sponsors only)
|
||||
if (view.directs.length) {
|
||||
const week = view.directs.filter(d => now - d.joined < 7 * DAY).length;
|
||||
parts.push('- Your line: ' + view.directs.length + ' direct' + (view.directs.length === 1 ? '' : 's') + ', ' + week + ' joined this week, ' + view.stalled + ' gone quiet.');
|
||||
const actions = view.directs.filter(d => d.stalled).slice(0, 3).map(d => ' Message ' + d.name + ': "' + d.say.replace('{{name}}', d.name.replace(/^@/, '')) + '"');
|
||||
if (actions.length) parts.push(actions.join('\n'));
|
||||
}
|
||||
parts.push('\nTwenty minutes, in order: the set, one message to your line, the tank, one conversation outward. https://instantadpay.com/blog/the-twenty-minute-day\n\nInstantAdPay · https://instantadpay.com/my\nNo income is guaranteed. Credits are advertising, not money.');
|
||||
const subject = lbWeek && lbWeek.top && lbWeek.top.length && lbWeek.top[0].name === '@' + acct.username ? 'You are #1 this week on InstantAdPay' : 'Your week on InstantAdPay: credits, streak, contest';
|
||||
try { await mailer.send(acct.email, subject, parts.join('\n')); digests += 1; } catch (e) { console.error('digest', acct.email, e.message); }
|
||||
const { subject, text, html } = await weeklyDigest(acct, view, lbWeek, tankN, now);
|
||||
try { await mailer.send(acct.email, subject, text, html); digests += 1; } catch (e) { console.error('digest', acct.email, e.message); }
|
||||
await impl().setDigest(acct.email, now);
|
||||
if (digests >= 30) break;
|
||||
}
|
||||
@@ -297,4 +365,4 @@ function init(opts) { X = arguments[0] || {};
|
||||
J.load();
|
||||
}
|
||||
async function viewsSince(since) { return impl().viewsSince(since); }
|
||||
module.exports = { init, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, refHost, viewsSince };
|
||||
module.exports = { init, weeklyDigest, RUNGS, rungFor, describe, coachView, prospects, saveProspect, removeProspect, STATUSES, recordView, linkStats, nudgeTick, recordClick, clickSources, clicksSince, refHost, viewsSince };
|
||||
|
||||
@@ -121,6 +121,7 @@ async function bootstrap() {
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN height INT NULL'); // banner size (IAB) → also NAS height
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_ad_id INT NULL'); // syndicated NAS sponsorads.ID
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN nas_served INT NOT NULL DEFAULT 0'); // NAS impressions already reconciled into spend
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN syn_imps INT NOT NULL DEFAULT 0'); // syndicated delivery counted off-site (IAP: PassiveDrip visits; LinkSpin: partner-zone views), charged at 1/synRateDivisor
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN drip_id INT NULL'); // syndicated DripOffers campaigns.id (2026-09-18)
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN expires BIGINT NULL'); // featured rotation end time
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN starts BIGINT NULL'); // featured run start (booked day); any type: scheduled start
|
||||
@@ -131,12 +132,24 @@ async function bootstrap() {
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN house TINYINT NOT NULL DEFAULT 0'); // admin house ad: free, never charged
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN daily_cap INT NULL'); // optional credits/day pacing (banner + text)
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN geo VARCHAR(16) NULL'); // country tiers the campaign shows to ('1,2'); NULL = everyone
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN placement VARCHAR(8) NULL'); // visits packs: NULL/'all' everywhere, 'doors' / 'golden' = Spooky Doors only until rates.sdSeasonEnd (2026-10-02)
|
||||
await q(`CREATE TABLE IF NOT EXISTS camp_geo (
|
||||
campaign_id INT NOT NULL, cc CHAR(2) NOT NULL, n INT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (campaign_id, cc)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // on-site serves per viewer country
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN day_spent INT NOT NULL DEFAULT 0');
|
||||
await alterSafe("ALTER TABLE campaigns ADD COLUMN day_key CHAR(10) NULL");
|
||||
// prepaid login-ad line (2026-10-23): status 'queued' = paid and waiting for a slot (never serves), 'cancelled' = refunded
|
||||
// before it started; queued_at orders the line (first paid, first served). status is VARCHAR(12), so no change there.
|
||||
await alterSafe('ALTER TABLE campaigns ADD COLUMN queued_at BIGINT NULL');
|
||||
// short lease locks shared by every app copy (two run for ~30 s on each deploy): one conditional UPDATE takes a lock
|
||||
// (holder IS NULL OR lease_until < now), the holder clears it, and an expired lease can be taken over after a crash
|
||||
await q(`CREATE TABLE IF NOT EXISTS app_locks (
|
||||
name VARCHAR(40) PRIMARY KEY,
|
||||
holder VARCHAR(60) NULL,
|
||||
lease_until BIGINT NOT NULL DEFAULT 0
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
await q("INSERT IGNORE INTO app_locks (name, holder, lease_until) VALUES ('login_queue', NULL, 0)");
|
||||
// linked positions: extra wallets owned by one email account (Qualified Start).
|
||||
// Each is its own on-chain member sponsored by the account's main member.
|
||||
await q(`CREATE TABLE IF NOT EXISTS positions (
|
||||
@@ -159,7 +172,8 @@ async function bootstrap() {
|
||||
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN paid INT NOT NULL DEFAULT 0'); // credits paid so far (the drip)
|
||||
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN last_day CHAR(10) NULL'); // Central day of the last installment
|
||||
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN expires BIGINT NOT NULL DEFAULT 0'); // unclaimed installments stop here; 0 = pre-drip row
|
||||
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN ref VARCHAR(80) NULL'); // site the ?promo= link was opened from
|
||||
await alterSafe0('ALTER TABLE promo_redemptions ADD COLUMN ref VARCHAR(80) NULL');
|
||||
await alterSafe0("ALTER TABLE visit_seen ADD COLUMN kind VARCHAR(8) NOT NULL DEFAULT 'earn'"); // 'refuel' = a Drip Runner refuel (own daily cap, 2026-09-30) // site the ?promo= link was opened from
|
||||
await q('UPDATE promo_redemptions SET paid=credits WHERE expires=0 AND paid<credits'); // pre-drip redemptions were paid in full at once
|
||||
await q(`CREATE TABLE IF NOT EXISTS page_hits (
|
||||
day CHAR(10) NOT NULL, host VARCHAR(80) NOT NULL, path VARCHAR(40) NOT NULL, n INT NOT NULL DEFAULT 0,
|
||||
@@ -216,6 +230,17 @@ async function bootstrap() {
|
||||
ts BIGINT NOT NULL,
|
||||
INDEX (campaign_id, ts)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
// repeat door visits after the cooldown (Spooky Doors, 2026-10-02); visit_seen keeps its one-row-per-campaign rule
|
||||
await q(`CREATE TABLE IF NOT EXISTS visit_repeat (
|
||||
id BIGINT AUTO_INCREMENT PRIMARY KEY,
|
||||
campaign_id INT NOT NULL,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
day CHAR(10) NOT NULL,
|
||||
ts BIGINT NOT NULL,
|
||||
kind VARCHAR(8) NOT NULL DEFAULT 'door',
|
||||
INDEX (email, day, kind),
|
||||
INDEX (email, campaign_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
await q(`CREATE TABLE IF NOT EXISTS visit_seen (
|
||||
campaign_id INT NOT NULL,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
@@ -319,6 +344,50 @@ async function bootstrap() {
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_via VARCHAR(20) NULL'); // ?v= angle the lead came in on
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN joined_ref VARCHAR(80) NULL'); // referring domain of the first join-page visit
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN wall_offers VARCHAR(2000) NULL'); // JSON [{title,bannerUrl,targetUrl}] for wall positions 2-3 (unlock at 2 / 5 qualifying buyers)
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN profile_quarantined TINYINT NOT NULL DEFAULT 0'); // 2026-10-30 link-farm rule: first profile save of a new free account carried a link (spamscan.js)
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN bix_partner_link VARCHAR(300) NULL'); // BixPay partner link (bixpay.js, 2026-10-29); column name checked against MySQL 8 reserved words
|
||||
await alterSafe('ALTER TABLE accounts ADD COLUMN theme VARCHAR(8) NULL'); // 2026-11-01 appearance: auto | light | dark (same column as LinkSpin)
|
||||
// help desk (2026-10-16, tickets.js): one shared desk for IAP and, later, LinkSpin; email_message_id threads inbound mail
|
||||
await q(`CREATE TABLE IF NOT EXISTS tickets (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
ref VARCHAR(20) NOT NULL UNIQUE,
|
||||
platform VARCHAR(12) NOT NULL DEFAULT 'iap',
|
||||
source VARCHAR(12) NOT NULL DEFAULT 'form',
|
||||
email VARCHAR(190) NOT NULL,
|
||||
name VARCHAR(80) NULL,
|
||||
username VARCHAR(30) NULL,
|
||||
subject VARCHAR(160) NOT NULL,
|
||||
category VARCHAR(40) NOT NULL,
|
||||
status VARCHAR(20) NOT NULL DEFAULT 'open',
|
||||
priority VARCHAR(8) NOT NULL DEFAULT 'normal',
|
||||
created BIGINT NOT NULL,
|
||||
updated BIGINT NOT NULL,
|
||||
last_member_at BIGINT NULL,
|
||||
last_admin_at BIGINT NULL,
|
||||
admin_unread TINYINT NOT NULL DEFAULT 0,
|
||||
member_unread TINYINT NOT NULL DEFAULT 0,
|
||||
INDEX (email), INDEX (status, updated), INDEX (platform, updated)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
await q(`CREATE TABLE IF NOT EXISTS ticket_messages (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
ticket_id INT NOT NULL,
|
||||
author VARCHAR(8) NOT NULL,
|
||||
body TEXT NOT NULL,
|
||||
internal TINYINT NOT NULL DEFAULT 0,
|
||||
attachments VARCHAR(400) NULL,
|
||||
created BIGINT NOT NULL,
|
||||
email_message_id VARCHAR(250) NULL,
|
||||
via VARCHAR(12) NOT NULL DEFAULT 'web',
|
||||
INDEX (ticket_id), INDEX (email_message_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
// help desk translations (2026-10-16): the English of a member message written in another language
|
||||
await q(`CREATE TABLE IF NOT EXISTS ticket_translations (
|
||||
message_id INT PRIMARY KEY,
|
||||
ticket_id INT NOT NULL,
|
||||
lang VARCHAR(8) NOT NULL,
|
||||
body_en TEXT NOT NULL,
|
||||
INDEX (ticket_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
}
|
||||
|
||||
// one-time import: only when the tables are empty and JSON files exist
|
||||
@@ -360,4 +429,24 @@ async function importJsonOnce() {
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, q: (...a) => q(...a) };
|
||||
// A named lock that holds across every app copy (MySQL GET_LOCK on one dedicated connection), for read-modify-write of a
|
||||
// record two copies might touch at once (the refuel streak, 2026-10-24). Without a database: a per-process queue.
|
||||
const localLocks = new Map();
|
||||
async function withLock(name, fn, secs) {
|
||||
const key = String(name).slice(0, 60);
|
||||
if (!enabled() || !pool) {
|
||||
const prev = localLocks.get(key) || Promise.resolve();
|
||||
let release; const mine = new Promise(r => { release = r; });
|
||||
const tail = prev.then(() => mine); localLocks.set(key, tail);
|
||||
await prev;
|
||||
try { return await fn(); } finally { release(); if (localLocks.get(key) === tail) localLocks.delete(key); }
|
||||
}
|
||||
const conn = await pool.getConnection();
|
||||
try {
|
||||
const [[row]] = await conn.query('SELECT GET_LOCK(?, ?) AS ok', [key, Number(secs) || 10]);
|
||||
if (!row || Number(row.ok) !== 1) throw new Error('lock busy: ' + key);
|
||||
try { return await fn(); } finally { try { await conn.query('SELECT RELEASE_LOCK(?)', [key]); } catch (e) {} }
|
||||
} finally { conn.release(); }
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, q: (...a) => q(...a), withLock };
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
// discord-relay.cjs — mirror a Telegram group post into the Crypto Team Build Discord (relaunch 2026-10-09).
|
||||
// Drop-in for every app that posts with the shared CTB Rewards bot. Call mirror() right where the app calls
|
||||
// Telegram; it is fire-and-forget, never throws, and does nothing unless the DISCORD_WEBHOOK_* env is set.
|
||||
// mirror({ chatId, threadId, text, photo, buttons })
|
||||
// chatId the Telegram chat the post goes to. Only the community group is mirrored; DMs / alert chats are skipped.
|
||||
// threadId forum topic: achievements (661565) -> #achievements, payments (632242) -> #payment-proofs,
|
||||
// no topic (General) -> #achievements. Override with DISCORD_TOPIC_ACH / DISCORD_TOPIC_PAY.
|
||||
// text Telegram HTML (converted to Discord markdown; user text is escaped so names with _ don't italicise)
|
||||
// photo Buffer (uploaded) or a public image URL (embedded), optional
|
||||
// buttons Telegram inline_keyboard (url buttons become links under the text), optional
|
||||
// Env: DISCORD_WEBHOOK_ACHIEVEMENTS, DISCORD_WEBHOOK_PAYMENT_PROOFS, DISCORD_WEBHOOK_PROMOS, DISCORD_WEBHOOK_ANNOUNCEMENTS,
|
||||
// DISCORD_WEBHOOK_OPS; DISCORD_TG_GROUP (default -1001258691510); DISCORD_RELAY=off to disable.
|
||||
// The same post twice within 15 minutes (e.g. a badge sent to a topic AND to General) is mirrored once.
|
||||
'use strict';
|
||||
const crypto = require('node:crypto');
|
||||
|
||||
const GROUP = () => String(process.env.DISCORD_TG_GROUP || '-1001258691510');
|
||||
const TOPIC_ACH = () => String(process.env.DISCORD_TOPIC_ACH || '661565');
|
||||
const TOPIC_PAY = () => String(process.env.DISCORD_TOPIC_PAY || '632242');
|
||||
const HOOKS = { achievements: 'DISCORD_WEBHOOK_ACHIEVEMENTS', 'payment-proofs': 'DISCORD_WEBHOOK_PAYMENT_PROOFS', promos: 'DISCORD_WEBHOOK_PROMOS', announcements: 'DISCORD_WEBHOOK_ANNOUNCEMENTS', ops: 'DISCORD_WEBHOOK_OPS' };
|
||||
function hookFor(feed) { const v = String(process.env[HOOKS[feed]] || ''); return v.startsWith('https://discord.com/api/webhooks/') ? v : ''; }
|
||||
function feedFor(threadId) { const t = String(threadId == null ? '' : threadId); if (t === TOPIC_PAY()) return 'payment-proofs'; if (t === TOPIC_ACH()) return 'achievements'; return 'achievements'; }
|
||||
|
||||
// ---- Telegram HTML -> Discord markdown ----
|
||||
const ENT = { '&': '&', '<': '<', '>': '>', '"': '"', ''': "'", ''': "'", ' ': ' ' };
|
||||
const unesc = s => s.replace(/&(amp|lt|gt|quot|#39|apos|nbsp);/g, m => ENT[m] || m);
|
||||
const escMd = s => s.replace(/([\\*_~`|])/g, '\\$1').replace(/^(\s*)([>#-])/gm, '$1\\$2');
|
||||
const WRAP = { b: '**', strong: '**', i: '*', em: '*', u: '__', ins: '__', s: '~~', strike: '~~', del: '~~', code: '`', 'tg-spoiler': '||', spoiler: '||' };
|
||||
function htmlToMd(html) {
|
||||
const re = /<\/?([a-zA-Z-]+)(?:\s+[^>]*)?\/?>/g; const stack = []; let out = '', last = 0, inCode = 0, m;
|
||||
const emit = t => { if (!t) return; const u = unesc(t); out += inCode ? u : escMd(u); };
|
||||
const close = mk => { const ws = (/\s+$/.exec(out) || [''])[0]; out = out.slice(0, out.length - ws.length) + mk + ws; };
|
||||
while ((m = re.exec(html))) {
|
||||
emit(html.slice(last, m.index)); last = re.lastIndex; const raw = m[0], tag = m[1].toLowerCase();
|
||||
if (tag === 'br') { out += '\n'; continue; }
|
||||
if (!raw.startsWith('</')) {
|
||||
if (tag === 'a') { const h = /href=(?:"([^"]*)"|'([^']*)')/i.exec(raw); stack.push({ tag, href: h ? (h[1] || h[2]) : '', start: out.length }); }
|
||||
else if (tag === 'pre') { out += '```\n'; inCode++; stack.push({ tag, start: out.length }); }
|
||||
else if (WRAP[tag]) { if (tag === 'code') inCode++; out += WRAP[tag]; stack.push({ tag, start: out.length }); }
|
||||
} else {
|
||||
let i = stack.length - 1; while (i >= 0 && stack[i].tag !== tag) i--; if (i < 0) continue;
|
||||
const o = stack[i]; stack.length = i;
|
||||
if (tag === 'a') { const inner = out.slice(o.start); out = out.slice(0, o.start) + (o.href ? '[' + inner + '](' + o.href + ')' : inner); }
|
||||
else if (tag === 'pre') { out += '\n```'; inCode--; }
|
||||
else if (WRAP[tag]) { if (tag === 'code') inCode--; close(WRAP[tag]); }
|
||||
}
|
||||
}
|
||||
emit(html.slice(last)); return out.replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
// ---- sending: one queue per webhook, 1.2 s apart, 429 honoured ----
|
||||
const queues = new Map(); const seen = new Map();
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
function content(text, buttons) {
|
||||
let c = htmlToMd(String(text || ''));
|
||||
const links = []; try { for (const row of (buttons && buttons.inline_keyboard) || []) for (const b of row) if (b && b.url) links.push('[' + String(b.text || 'Open').replace(/[\[\]]/g, '') + '](<' + b.url + '>)'); } catch (e) {}
|
||||
if (links.length) c += '\n\n' + links.join(' · ');
|
||||
return c.length > 1990 ? c.slice(0, 1989) + '…' : c;
|
||||
}
|
||||
async function post(url, msg, attempt) {
|
||||
const payload = { content: content(msg.text, msg.buttons), allowed_mentions: { parse: [] } };
|
||||
let body, headers = {};
|
||||
if (msg.photo && typeof msg.photo !== 'string') {
|
||||
payload.attachments = [{ id: 0, filename: 'card.jpg' }];
|
||||
const fd = new FormData(); fd.append('payload_json', JSON.stringify(payload)); fd.append('files[0]', new Blob([msg.photo]), 'card.jpg'); body = fd;
|
||||
} else {
|
||||
if (typeof msg.photo === 'string' && msg.photo) payload.embeds = [{ image: { url: msg.photo } }]; else payload.flags = 1 << 2;
|
||||
body = JSON.stringify(payload); headers['Content-Type'] = 'application/json';
|
||||
}
|
||||
const r = await fetch(url + '?wait=true', { method: 'POST', headers, body, signal: AbortSignal.timeout(20000) });
|
||||
if (r.status === 429 && (attempt || 0) < 2) { const j = await r.json().catch(() => ({})); await sleep((Number(j.retry_after) || 2) * 1000 + 250); return post(url, msg, (attempt || 0) + 1); }
|
||||
if (!r.ok) console.error('[discord-relay] post failed http=' + r.status + ' ' + (await r.text().catch(() => '')).slice(0, 160));
|
||||
}
|
||||
function mirror(msg) {
|
||||
try {
|
||||
if (String(process.env.DISCORD_RELAY || 'on').toLowerCase() === 'off') return;
|
||||
if (!msg || String(msg.chatId || '') !== GROUP()) return;
|
||||
const feed = msg.feed || feedFor(msg.threadId); const url = hookFor(feed); if (!url) return;
|
||||
const key = crypto.createHash('sha1').update(feed + '\n' + String(msg.text || '') + '\n' + (Buffer.isBuffer(msg.photo) ? msg.photo.length : String(msg.photo || ''))).digest('hex');
|
||||
const now = Date.now(); for (const [k, t] of seen) if (now - t > 15 * 60000) seen.delete(k);
|
||||
if (seen.has(key)) return; seen.set(key, now);
|
||||
const prev = queues.get(url) || Promise.resolve();
|
||||
queues.set(url, prev.then(() => post(url, msg, 0)).catch(e => console.error('[discord-relay]', e && e.message)).then(() => sleep(1200)));
|
||||
} catch (e) { console.error('[discord-relay]', e && e.message); }
|
||||
}
|
||||
module.exports = { mirror, htmlToMd, feedFor };
|
||||
@@ -0,0 +1,99 @@
|
||||
# BixPay card integration (DRAFT for Marty, 2026-10-29)
|
||||
|
||||
Scope: InstantAdPay first, LinkSpin second, CTB when it launches. Nothing here is built yet.
|
||||
|
||||
## What we know about BIX (verified 2026-10-29)
|
||||
- BIX = self-custody wallet + Visa card spent from USDT/USDC. Funding networks include Polygon, so a member can swap POL
|
||||
to USDT in the BIX app and load the card with no bridge. No load fee; up to 3% per purchase, 1% FX.
|
||||
- Cards: virtual $9.99, plastic $100, metal $250, gold $25,000. US = Visa Signature (29 states); elsewhere Visa Platinum.
|
||||
- Partner plan: 50% of net fees and card sales -> 45% over 10 levels (15 / 10 / 2.5 x 8) + 5% pool.
|
||||
- Partner link format: `https://bix.ibportal.io/auth/register?e=<43-char token>&a=1` (opaque token, not derivable from the
|
||||
IB ID). The referral link (`&appId=3`) makes a card customer only; the PARTNER link makes a partner. We use the partner link.
|
||||
- Company fallback link: Marty's partner link (IB12143793).
|
||||
|
||||
## 1. The profile field (one identity, follows the member)
|
||||
- InstantAdPay Profile tab, new section **"BixPay card"**: one input, `bixPartnerLink`.
|
||||
- Accepts a full partner link. Validation: host `bix.ibportal.io`, path `/auth/register`, `e=` present, `a=1`; strip `appId`
|
||||
if pasted (the customer link) and tell the member "That's the card-customer link. Paste the Partner link from your BIX
|
||||
portal profile instead." Max 300 chars. Saved on the IAP account; LinkSpin and CTB read it through the existing partner
|
||||
API (the same way wallet and sponsor already flow), and LinkSpin's own Profile shows it read-only with "Edit on InstantAdPay".
|
||||
- Member sees under the field: "Where to find it: BIX portal > Profile > Partner (the second box). Copy the link."
|
||||
- Admin: the field shows on the member card; a count of members with a link set on the admin Overview.
|
||||
|
||||
## 2. The link each visitor gets (sponsor follows)
|
||||
`bixLinkFor(member)` =
|
||||
1. the member's own `bixPartnerLink`, else
|
||||
2. walk the sponsor chain up to 10 levels, first sponsor with a link, else
|
||||
3. the company link (site config `bixCompanyLink`, default Marty's partner link).
|
||||
The card promo always shows WHOSE link is in play: "Your link" / "Your sponsor @name's link" / "Network link". That nudges
|
||||
members to add their own, and sponsors to get their teams signed up.
|
||||
For public pages (games' landing pages, /join/<user>), the referrer whose `?ref` is on the page resolves the same way.
|
||||
|
||||
## 3. Where members see it
|
||||
### Wallet tab (primary)
|
||||
Card: **"Spend your POL anywhere with a BixPay Visa card"**
|
||||
"BixPay is a self-custody wallet with a Visa card. Send USDT or USDC to it on Polygon, load the card, and spend it wherever
|
||||
Visa is accepted, including Apple Pay and Google Pay. Virtual cards from $9.99."
|
||||
(No in-app swap: Marty confirmed 2026-10-29 he swaps POL to USDT/USDC on an exchange, then sends it to BixPay. The guide
|
||||
gets a "turn your POL into USDT" step: any exchange or on-ramp, then send on Polygon. Add the swap line only once BIX
|
||||
ships it; the founder said "in the next three months" on 10-17.)
|
||||
Buttons: **Get your BixPay card** (partner link) · **How it works** (opens the guide).
|
||||
Small line: "Using: your link / @sponsor's link / the network link. Add yours in Profile."
|
||||
### Overview
|
||||
A one-line announcement card the first week ("New: a Visa card for your POL"), dismissable like the other cards.
|
||||
### Payout emails + game "link your wallet" nudges
|
||||
One sentence after the amount: "Want to spend it? A BixPay Visa card turns POL into everyday purchases: <link>."
|
||||
(Payout emails already carry the member's identity, so the link resolves per member.)
|
||||
### Promo tools > new tab "BixPay"
|
||||
- The member's link with Copy/Share.
|
||||
- 3 posts (short, friendly, the "spend your crypto" angle), an email swipe, and 4 banners we make (no BIX logo until
|
||||
Marty confirms brand rules; text-only "crypto Visa card" creative is safe).
|
||||
- Every asset carries the member's resolved link.
|
||||
### Guide page /bixpay (public, SEO)
|
||||
What it is, the fee table, the funding path (POL -> USDT on Polygon -> card), the sign-up steps with screenshots, the
|
||||
partner plan in plain words, and the compliance box. CTA carries the viewer's resolved link.
|
||||
### Chatbot
|
||||
Canned answers: what BixPay is, how to get the card, how to load it from POL, where to put my partner link, who gets the
|
||||
credit. Facts in the system prompt with KNOWLEDGE_DATE.
|
||||
|
||||
## 4. Copy (Marty's voice, no em dashes)
|
||||
- Wallet card title: "Spend your POL anywhere with a BixPay Visa card"
|
||||
- Body: see above.
|
||||
- Profile field label: "Your BixPay partner link"
|
||||
- Profile help: "Join BixPay as a partner, then paste your Partner link here. Members and visitors who get a card through
|
||||
your pages are credited to you in your BIX portal, up to ten levels deep."
|
||||
- Email line: "Want to spend it? A BixPay Visa card turns POL into everyday purchases."
|
||||
- Post 1 (short): "I spend my crypto with a Visa card now. BixPay keeps the keys with you, loads from USDT or USDC with no
|
||||
load fee, and works with Apple Pay. Virtual card from $9.99: {L}"
|
||||
- Fees line everywhere: "3% per purchase, no load fee. See BIX's terms for other charges."
|
||||
- US line on the Wallet card and guide: "Available in 31 US states so far. Not in your state yet? You can still get the
|
||||
wallet and build."
|
||||
- Guide: a "Funding your card" section with three paths: (1) swap POL to USDT or USDC on any exchange, send on Polygon;
|
||||
(2) Cash App (US): send crypto straight to the BixPay wallet; (3) the BIX in-app swap, once it ships.
|
||||
- Post 2 (friendly): "Earning crypto is one thing. Spending it without jumping through hoops is another. BixPay fixed that
|
||||
for me: a self-custody wallet and a Visa card in one app. Here's where I got mine: {L}"
|
||||
- Post 3 (partner angle): "BixPay pays partners on every card and on card spending, ten levels deep. If you're building a
|
||||
team anyway, this fits right in: {L}"
|
||||
|
||||
## 5. Compliance box (shown on the Wallet card's "How it works" and the guide)
|
||||
"BixPay is a separate company. BIX issues the wallet and the card through its banking partners and sets its own fees,
|
||||
limits, eligibility and terms. InstantAdPay is not the card issuer and earns a referral commission when you sign up
|
||||
through a partner link. Card availability varies by country. Crypto assets can lose value."
|
||||
|
||||
## 6. Tracking
|
||||
- Click counts per surface (wallet card, email, promo tools, guide) in the admin Traffic tab; per-member click counts on
|
||||
the Promo tools BixPay tab. No sign-up credit on our side: the BIX portal shows each partner their directs and levels.
|
||||
- If BIX ever offers a postback, add a "BixPay sign-ups" stat next to the click counts.
|
||||
|
||||
## 7. Rollout
|
||||
1. IAP: field + resolver + Wallet card + guide + chatbot + promo tab (gated by site config `bixpayLive`).
|
||||
2. LinkSpin: read-only field + Wallet/Credits card + promo entry, same resolver through the partner API.
|
||||
3. CTB: same card and field in ctb-next, same identity.
|
||||
4. Announcement (release note + member email + Telegram) after Marty's copy approval.
|
||||
|
||||
## Open questions for Marty / BIX upline
|
||||
- Does a partner sign-up also get the card, or does the member need the app invitation too? (If both: show "Join as a
|
||||
partner" and "Just want the card?" buttons, each with the member's own link type.)
|
||||
- BIX name/logo use in our promo material.
|
||||
- The pool's "50/50 rule".
|
||||
- Any updated BIX materials.
|
||||
@@ -0,0 +1,38 @@
|
||||
# BixPay opportunity call, 2026-10-17 (Zoom replay notes, made 2026-10-29)
|
||||
|
||||
"$iNVU - Live Opportunity Call", 47 min. Host "Bass"; main speaker David Emenite (22-year network marketer; his own company
|
||||
is a trading opportunity, "tap to trade"); BIX founder "Nick" (28, Germany, says he owns "one of the largest Forex brokers
|
||||
on the planet"; BIX started "a couple of months ago"); leaders Tracy Fischer, Lisa, Alan Jones, Gary. The $iNVU / trading
|
||||
company parts are NOT BIX. Transcript: D:/tmp/bix-zoom/transcript.txt; slides D:/tmp/bix-zoom/frames.
|
||||
|
||||
## Plan mechanics (as presented; matches the BIX commission PDF)
|
||||
- The only fee claimed: 3% per transaction. "No top-up fees, no hidden fees." (A third-party review lists 1% FX, $0.75
|
||||
under $50, ATM $1 + 0.6%, so present 3% as THE fee and point to BIX's terms for the rest.)
|
||||
- 50% of the 3% goes into the plan; paid over 10 levels: L1 15%, L2 10%, L3-L10 2.5% each; the other 5% = BIX pool,
|
||||
1 share per 10,000 cards in your network. Worked example: $1,000 spent -> $30 fee -> $15 into the plan.
|
||||
- Card sales pay too: slide "EARN A 50% REFERRAL BONUS ON EVERY CARD PURCHASE" (virtual $9.99, plastic $100, metal $250,
|
||||
24K gold $25,000; shipping to 179 countries). The optional $9.99/month rewards membership is also commissionable.
|
||||
- Upcoming banking (SEPA IBAN, ACH, SWIFT, fiat on/off-ramp): instant 0%, SEPA/ACH 1%, "up to 50% included in the
|
||||
compensation plan". Nick: IBANs and the in-app SWAP "in the next three months", i.e. NOT live on 10-17.
|
||||
- Shareholder: 500,000 cards in your network "on a 50/50 rule" = shareholder of BIX (Nick). Network contest: first to
|
||||
10,000 cards gets a $100,000 bonus. The 50/50 rule is still not defined on the call.
|
||||
- US: "open in 31 states" (review on 10-24: 29), rest "first part of 2027". Wallet works everywhere; you can build from a
|
||||
closed state. KYC required for the card; problems go to BIX support.
|
||||
- Funding tip (Tracy/Bass): Cash App can send crypto straight to the BixPay wallet (about 20 transactions a month, up to
|
||||
$5,000 a week); they used Coinbase before. Card works in Apple Wallet.
|
||||
- Usage data quoted: average customer spends $1,400-1,500 a month (industry figure); Bass's back office shows $20-80 a
|
||||
week per user so far.
|
||||
|
||||
## Claims to treat as marketing, not facts
|
||||
300,000 downloads / 300,000 cards active, $3M spent per day, live since August with global launch ~6 weeks before the
|
||||
call, "5 million users in one year, 80 million in three, bigger than Revolut", "worth a couple hundred million, $100B in
|
||||
three years", "$1 to $1 million per day" spend limit, $2.6T daily payments, founder "a billionaire".
|
||||
|
||||
## What it changes in our integration draft (BIXPAY-INTEGRATION.md)
|
||||
1. Don't promise an in-app swap yet. Copy becomes "load it with USDT or USDC on Polygon" until Marty confirms Swap works
|
||||
in his app; add a short "how to turn POL into USDT" step (any exchange or the BIX swap once live).
|
||||
2. Fees line: "3% per purchase, no load fee; see BIX's terms for other charges."
|
||||
3. Lead with the $9.99 virtual card: it pays the referrer on the sale and on every swipe after.
|
||||
4. US members: add "available in 31 states; not in your state yet? You can still build and get the wallet."
|
||||
5. Add the Cash App funding path to the guide for non-crypto members (US).
|
||||
6. Events in the call (Houston 10-20, Tampa 10-21, Bangkok 11-28) are the leaders' own, not ours.
|
||||
@@ -0,0 +1,72 @@
|
||||
# Release note draft: the Game Pass (not sent)
|
||||
|
||||
Status: DRAFT for Marty's review. Nothing below has been posted, emailed or published. Dates are placeholders until the caps start
|
||||
date is set in Admin > Settings (`capsStartDate`) and `gamePassEnabled` is switched on.
|
||||
|
||||
## Short version (Telegram / feed)
|
||||
|
||||
The games now have a Game Pass: $5 for 7 days, all nine games on one account. Free play keeps paying real POL every day. The Pass
|
||||
plays more: higher daily caps across every game, a seat in the weekly Pass Tournament with POL prizes, extra plays or a perk in each
|
||||
game, and the Pass badge. Members > Games > Game Pass. From [DATE] the daily POL caps are account-wide: free play 0.30 POL a day on
|
||||
repeatable rewards and 2 POL a day in all; with the Pass 1.50 and 5. One-time rewards you earn over the cap are never lost; they pay
|
||||
over the next days.
|
||||
|
||||
## Release note (Admin > Releases, member-facing)
|
||||
|
||||
**The Game Pass: more game across all nine games**
|
||||
|
||||
Every member earns real POL in our games, and that does not change. What is new:
|
||||
|
||||
- **The Game Pass.** $5 for 7 days, one pass for your whole account (linked positions share it), covering PolHunter, Gem Kingdom,
|
||||
SpellWheel, PolyWarriors, Road Agent, ClutterHunt, PolyBreak, Drip Runner and Spooky Doors while its season runs.
|
||||
- **What it does.** Higher daily POL caps in every game (1.50 POL a day on repeatable play instead of 0.30, and 5 POL a day in all
|
||||
instead of 2), a place in the weekly **Pass Tournament**, extra plays or a perk in each game (more PolHunter missions, a free
|
||||
continue in Gem Kingdom, a free hint in SpellWheel and ClutterHunt, an extra patrol in Road Agent, a starting shield in Drip
|
||||
Runner, an extra paddle in PolyBreak, an extra mission in PolyWarriors, an extra door in Spooky Doors), and the Pass badge.
|
||||
- **How to get it.** Members > Games > Game Pass. Tap Get the Pass, then buy a new package of $5 or more. The pass starts the
|
||||
moment that purchase settles. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your
|
||||
ads. Credits you already hold never buy a pass. Buying again while a pass is active adds 7 days.
|
||||
- **Account-wide daily caps, from [DATE].** Until now each game had its own daily limit. From [DATE] the limit is one number for
|
||||
your whole account across all the games, reset at midnight Central: free play 0.30 POL a day on repeatable rewards (finds, daily
|
||||
puzzles, patrols, gems, drips) and 2 POL a day for everything; with the Pass 1.50 and 5. A one-time reward (a boss, a chapter, a
|
||||
sector, a room) never changes and is never lost: whatever is over the day's total carries to the next day until it is paid in
|
||||
full. A 10 POL boss still pays 10 POL, over a few days.
|
||||
- **The weekly Pass Tournament.** Monday to Sunday, Central time, pass holders are ranked by their plays across all the games. The
|
||||
prize pool is 5% of that week's pass sales, paid in POL to the top three (50 / 30 / 20) and posted in Game Achievements on
|
||||
Monday morning.
|
||||
|
||||
The Pass does not change what any reward pays. Free play pays; the Pass plays more.
|
||||
|
||||
## Announcement timing
|
||||
|
||||
- One week before `capsStartDate`: post the short version, publish this note, switch `gamePassEnabled` on so members can buy
|
||||
ahead of the caps.
|
||||
- On `capsStartDate`: the caps enforce themselves at midnight Central; nothing to deploy.
|
||||
- First Monday 9 AM Central after launch: the first tournament settles and posts by itself (only while `gamePassEnabled` is on).
|
||||
|
||||
## Wording rules (chatbot, posts, pages)
|
||||
|
||||
Never "earn more", "pays for itself", "income". Always "free play pays; the Pass plays more". Reward amounts never change with the
|
||||
Pass. Caps are per account, per Central day. Deferred progress rewards are "paid over the next days", never "lost".
|
||||
|
||||
## Update draft, 2026-10-22: how the Game Pass is paid (not sent)
|
||||
|
||||
Status: DRAFT for Marty's review. Nothing has been posted, emailed or published.
|
||||
|
||||
**Short version (Telegram / feed)**
|
||||
|
||||
A change to how the Game Pass is paid: from today every pass is paid by a new package purchase. Tap Get the Pass in Members >
|
||||
Games, buy a package of $5 or more, and the pass starts the moment it settles. Your sponsor and team are paid from that package,
|
||||
and you keep all of its credits for your ads. Credits you already hold no longer buy a pass. Passes you already have keep running.
|
||||
|
||||
**Release note (Admin > Releases)**
|
||||
|
||||
**The Game Pass is now paid with a new package**
|
||||
|
||||
- Tap Get the Pass (or Get on any pass) in Members > Games. Then buy a package of at least the pass price: $5 for the weekly Game
|
||||
Pass.
|
||||
- The pass starts the moment that purchase settles on chain. A package bought before you tapped Get does not count.
|
||||
- Your sponsor and team are paid from that package exactly like any other package, and every credit of the package stays yours for
|
||||
your ads.
|
||||
- Credits you already hold, earned or purchased, no longer buy a pass.
|
||||
- Any pass you already have keeps running to its end date.
|
||||
@@ -0,0 +1,379 @@
|
||||
# Game Pass: draft spec (2026-10-16)
|
||||
|
||||
> **PAYMENT RULE CHANGED 2026-10-22 (Marty): every pass is paid by a FRESH on-chain package purchase; no pass is ever bought with
|
||||
> credits again.** See "Payment: the package rail" at the end. Older sections below that mention credits describe the rule as it was.
|
||||
|
||||
Marty's direction (10-16): a $5 weekly Game Pass that covers all nine games and raises the daily POL cap; a tighter
|
||||
free cap so nobody farms the games all day for free. Pass = "more game", never pitched as payback. Free play keeps
|
||||
paying real POL (the "paid before they ever pay" funnel in the presentation, deck and guide).
|
||||
|
||||
## 1. What the games pay today (live settings, 7-day earnings to 2026-10-16)
|
||||
|
||||
Two kinds of POL rewards exist in every game:
|
||||
|
||||
- **Progress rewards**: one-time per account (first clear of a stage, boss, sector, rival, chapter, room). Finite.
|
||||
- **Daily play rewards**: repeatable every day (finds, daily puzzle, patrol, gems, drips). This is the "all day" risk.
|
||||
|
||||
| Game | Progress rewards (one-time, POL) | Daily play rewards (repeatable) | Game cap/day | Players (7d) | Median / p90 / max per player-day | POL out / week |
|
||||
|---|---|---|---|---|---|---|
|
||||
| PolHunter | none | finds 0.05-1.00 (skewed small), 3 missions/day | 40 | 38 | 0.48 / 0.97 / 4.04 | **102.1** |
|
||||
| Gem Kingdom | stages 0.02-0.15; bosses 0.25 / 0.5 / 2 / 5 / 7.5 / **10** | none | 40 | 25 | 0.46 / 11.35 / **25.49** | **101.4** |
|
||||
| SpellWheel | levels 0.02-0.05; chapters 0.25-1 | daily puzzle 0.03, streak 0.15 | 20 | 102 | 0.04 / 0.16 / 1.50 | 17.6 |
|
||||
| Spooky Doors (to Oct 31) | ladder 0.1 / 0.25 / 0.5 / 1 / 2 | none | 25 | 11 | 0.85 / 1.00 / 2.00 | 10.7 |
|
||||
| PolyWarriors | rivals 0.02-0.10, ladder 0.5, elite 0.12-0.5, elite clear 2 | none (PvP pays Circuits) | 20 | 10 | 0.18 / 1.09 / 4.94 | 8.8 |
|
||||
| ClutterHunt | per room: clear 0.05, 3-star 0.05, expert 0.15, expert stars 0.10 | none | 20 | 13 | 0.20 / 0.95 / 1.05 | 6.4 |
|
||||
| PolyBreak | rounds 0.02 / 0.03 / 0.05 | gems 0.01-0.15, up to 0.5/day | 5 | 39 | 0.02 / 0.06 / 0.12 | 1.3 |
|
||||
| Drip Runner | chapters | drips 0.05, items | 5 | 15 | 0.05 / 0.15 / 0.25 | 1.2 |
|
||||
| Road Agent | sectors 0.05-1.00 (3.60 total) | patrol 0.03/day | 25 | 5 | 0.08 / 0.16 / 0.16 | 0.5 |
|
||||
| **All games** | | | | | | **~250 POL/week (~$23 at 9c)** |
|
||||
|
||||
PolHunter and Gem Kingdom are 81% of the burn. PolHunter is repeatable play (and every find is a delivered sponsor
|
||||
visit, so that burn delivers advertiser inventory). Gem Kingdom's burn is its boss amounts: one player took 25.5 POL in
|
||||
a single day. No other game pays more than 2 POL for any single reward.
|
||||
|
||||
## 2. The pass
|
||||
|
||||
- **$5, 7 days, all nine games.** One pass per account; buying while active extends by 7 days.
|
||||
- (Superseded 2026-10-22, see "Payment: the package rail".) Paid with **purchased-grade credits only** (500 credits = the $5 package), through the existing game-purchase path
|
||||
(`ads.gamePurchase` with `purchasedOnly`, the same rule as PolyWarriors mint passes). A $5 package bought while a pass
|
||||
order waits fulfils it (the `pwpasses` pattern). Earned credits never buy a pass, or no money enters and the pass is
|
||||
just a free cap increase.
|
||||
- Money flow is the normal on-chain split of the $5 package: $2.50 sponsor, $1.00 level 2, $0.50 level 3, $1.00 company.
|
||||
The company's $1 is what funds the extra POL; the games' 30% pool-share rule is an allowance, not cash.
|
||||
|
||||
## 3. Caps (account-wide, across all nine games)
|
||||
|
||||
| | Free | Pass |
|
||||
|---|---|---|
|
||||
| Daily play rewards (repeatable) | **0.30 POL/day** | **1.50 POL/day** |
|
||||
| Everything (progress + daily), paced | **2.0 POL/day** | **5.0 POL/day** |
|
||||
| Progress rewards | unchanged amounts for everyone; excess over the daily total **carries to the next day** (never lost) | same |
|
||||
|
||||
Why these numbers:
|
||||
- Free 0.30/day sits under PolHunter's median (0.48) and SpellWheel's p90 (0.16 stays free). The regular PolHunter
|
||||
hunter is the natural pass buyer; the casual SpellWheel player never notices.
|
||||
- Pass 1.50/day is above today's p90 for every game, so a pass holder keeps everything they earn today and more.
|
||||
Max repeatable per pass week = 10.5 POL (~$0.98), so the pass can never pay for itself and multi-accounting can't win.
|
||||
- The paced total cap stops the Gem Kingdom spike (25 POL in a day) without changing any reward amount: a 10 POL boss
|
||||
still pays 10 POL, over a few days.
|
||||
- Company per pass: $1.00 in, at most $0.98 out if a holder maxes the repeatable cap every day. Realistic use (about
|
||||
half) nets about $0.50 a pass. Progress rewards were payable to free players already, so the pass adds no cost there.
|
||||
|
||||
**DECIDED (Marty, 2026-10-16): Gem Kingdom's bosses stay at 5 / 7.5 / 10 POL.** "We need one that pays out bigger like
|
||||
that anyway." The paced total cap spreads a big boss payout over a few days; the amounts do not change.
|
||||
|
||||
## 3a. API contract (both sides build to this)
|
||||
|
||||
> **Built 2026-10-16 (IAP side). Clarifications and additions to this contract, none of them breaking:**
|
||||
>
|
||||
> 1. **Where the endpoints live.** `GET /api/partner/player` exists today on each GAME (IAP reads the player's card line from it).
|
||||
> The pass and caps version below is served by **IAP** (`https://instantadpay.com/api/partner/player`), so a game CALLS it; nothing
|
||||
> changes on the game's own endpoint. Same for `polgrant`, `polgrant/void` and `tournament/*`: all on IAP.
|
||||
> 2. **Signature, spelled out.** Each game signs with the shared secret it already holds (its `*_SSO_SECRET`; PolHunter uses
|
||||
> `HUNT_SSO_SECRET`). 10-minute window on `ts` (ms).
|
||||
> - `GET /api/partner/player?game=<slug>&m=<memberId>&e=<email>&ts=<ms>&sig=<hex>` with
|
||||
> `sig = HMAC-SHA256(secret, 'player:' + who + ':' + ts)`, `who` = memberId when > 0, else the lowercased email (the same string
|
||||
> the games already compute for IAP's calls to them, with `game` added so IAP knows which secret to check).
|
||||
> - `POST` endpoints: JSON body that includes `game: <slug>`, headers `X-Game-Ts: <ms>` and
|
||||
> `X-Game-Sig: HMAC-SHA256(secret, ts + '\n' + rawBody)` hex (sign the exact bytes you send).
|
||||
> - `GET /api/partner/tournament/pending?game=<slug>&ts&sig` with `who = 'tournament'`.
|
||||
> 3. **`email` is accepted beside `memberId`.** Players who have not linked a wallet have `memberId: 0` in every hand-off token; send
|
||||
> `email` too (the token has it) and IAP resolves the account by email. A linked position's member id resolves to the owner's
|
||||
> account: the pass and the caps are per ACCOUNT.
|
||||
> 4. **Extra fields in answers** (additive): `polgrant` also returns `carried` (POL paid from an earlier day's deferral, already
|
||||
> inside `allowed`), `capHit` (`'daily'|'total'|null`), `enforced` (false before `capsStartDate`), `repeat` (true when the ref was
|
||||
> already answered), `voided`. `caps` also has `enforced`, `pass` and `pending` (POL deferred for this game, not yet paid).
|
||||
> `player` also returns `memberId, username, wallet, suspended, gamePassEnabled`. A suspended account gets `allowed: 0,
|
||||
> suspended: true` and nothing is recorded (a cleared account can replay the ref).
|
||||
> 5. **Carry-forward counts against the later day's total cap** (that is what "paced" means): a 10 POL boss on a 2 POL/day free
|
||||
> account pays 1.7-2.0 a day until done, paid before that day's new grants. Carry-forward only happens on a LATER Central day
|
||||
> than the deferral and only to the same game; the reply that carries it says `carried`.
|
||||
> 6. **`void` reverses only that ref's own share** (its `allowed` on its day and whatever of its deferral is still queued). POL it
|
||||
> already caused to be carried on a later day belongs to that later day and stays. The ref remains answered as voided.
|
||||
> 7. **Hand-off tokens carry the flag** as `gamePass: { active, until }` (not `pass`, which the in-game sign-in flow already uses for
|
||||
> its session token). Apply perks from it at sign-in; refresh from `player`/`polgrant` answers.
|
||||
> 8. **Tournament prize payout seam.** IAP records the winners and POL amounts; a game faucet (Road Agent pattern) pays them:
|
||||
> `GET /api/partner/tournament/pending` answers `{ ok, rows: [{ week, place, email, memberId, wallet, pol, ... }] }` (the same
|
||||
> list is also under `pending`, the admin pane's name) for the rows still unpaid, and the paying game calls
|
||||
> `POST /api/partner/tournament/paid { game, week, place, tx }` so the row leaves the list. PolHunter's faucet pays them
|
||||
> (`polhunter/lib/tournament.js`, see "Games: as built"); Admin > Game Pass shows the unpaid rows meanwhile.
|
||||
> 9. **Not deviations, just dev conveniences (non-production only):** `devDay: 'YYYY-MM-DD'` on `polgrant`/`player`/`buy` fakes the
|
||||
> Central day; `POST /api/dev/gamepass-purchase` fakes a package event; `devPaid: true` on `buy` skipped the credit charge (retired 2026-10-22: there is no charge any more; the dev purchase event takes `minedAt`, `now` and `tx`).
|
||||
|
||||
IAP is the single source of truth for the pass and for the account-wide caps. Every game already signs partner calls
|
||||
with its shared secret (the `/api/partner/player` pattern); the new calls use the same auth.
|
||||
|
||||
- `GET /api/partner/player?...` (existing) additionally returns `pass: { active: bool, until: ms|null }` and
|
||||
`caps: { daily: n, total: n, used: { daily: n, total: n }, day: 'YYYY-MM-DD' }` (Central day).
|
||||
- `POST /api/partner/polgrant` body `{ memberId, game, kind: 'daily'|'progress', pol, ref }` (ref = the game's own
|
||||
idempotency key, e.g. `sector:3`, `find:<id>`). Response `{ allowed: n, deferred: n, pass: bool, day }`.
|
||||
- `kind: 'daily'`: `allowed = min(pol, dailyCapRemaining, totalCapRemaining)`, the rest is DROPPED (never deferred).
|
||||
- `kind: 'progress'`: `allowed = min(pol, totalCapRemaining)`, the rest is DEFERRED: IAP stores it and the game's
|
||||
next call (any kind) on a later day gets it added to `allowed` first (carry-forward). Nothing is ever lost.
|
||||
- Same `ref` twice = same answer (idempotent). Fail closed: if the game cannot reach IAP it grants nothing and retries
|
||||
the same ref later.
|
||||
- `POST /api/partner/polgrant/void` `{ memberId, game, ref }` when a game decides not to pay after all (rare).
|
||||
- Settings on IAP (Admin > Settings, no deploy): `gamePassEnabled`, `gamePassPriceCredits` (500), `gamePassDays` (7),
|
||||
`capFreeDaily` 0.30, `capFreeTotal` 2.0, `capPassDaily` 1.50, `capPassTotal` 5.0, `capsStartDate` (the free caps apply
|
||||
only from this Central date; before it, the games' own caps stand, so the change can be announced a week ahead),
|
||||
`passTournamentPct` 5.
|
||||
- Pass purchase (superseded 2026-10-22: Buy only opens an order, a fresh package fulfils it): `POST /api/my/gamepass/buy` spends 500 purchased-grade credits (`ads.gamePurchase` with
|
||||
`purchasedOnly`); a $5 package bought while a pass order waits fulfils it (the `pwpasses` pattern). Buying while active
|
||||
extends `until` by 7 days. The Games tab shows the card, the state, and the expiry.
|
||||
- Games get the pass flag at the sign-in hand-off and on every `polgrant` response; apply perks locally.
|
||||
|
||||
## 4. Pass perks per game (more game, not more payback)
|
||||
|
||||
| Game | Pass perk (besides the higher caps) |
|
||||
|---|---|
|
||||
| PolHunter | 5 missions/day instead of 3; Ad Detective twice a day. Finds still require the sponsor visit. |
|
||||
| Gem Kingdom | one free continue per day (small, so Crowns sales are not undercut) |
|
||||
| SpellWheel | streak bonus 0.15 -> 0.30; one free hint a day |
|
||||
| PolyWarriors | +1 daily mission; defense pay 15 -> 25 Circuits; Pass mark on the warrior card |
|
||||
| Road Agent | 2 patrols/day; +25% scrap. Fuel stays a sponsor visit. |
|
||||
| ClutterHunt | 2 free hints a day |
|
||||
| PolyBreak | gem cap 0.5 -> 1.5/day; one extra paddle per round |
|
||||
| Drip Runner | a shield at the start of every run |
|
||||
| Spooky Doors | +1 door a day while the season runs |
|
||||
| All games | **Weekly Pass Tournament**: cross-game leaderboard (finds, clears, wins), prizes from 5% of pass sales (25c per pass) in POL; Pass badge; gold profile frame |
|
||||
|
||||
Ad-visit mechanics (fuel, Crowns, hints, refuels) stay as they are. Those verified visits are what advertisers pay for.
|
||||
|
||||
## 5. Build outline
|
||||
|
||||
1. **IAP (central):** durable `gamepass` map {email: {until, history}}; `GET /api/partner/player` returns `pass:{active, until}`;
|
||||
new `POST /api/partner/polgrant` {member, game, kind: progress|daily, pol} -> {allowed, deferred} enforcing the
|
||||
account-wide caps (fail closed when IAP is unreachable; games retry); Games tab card "Game Pass: $5 for 7 days, all
|
||||
games"; buy flow via purchased credits or the $5 package; admin: passes sold, POL out per pass, cap hits.
|
||||
2. **Each game:** read the pass flag at the sign-in hand-off; call `polgrant` before every POL grant (replaces each game's
|
||||
own `dailyCapPol` for the account-wide rule; keep the local cap as a backstop); pace deferred progress rewards (queue,
|
||||
pays out next day); apply its perk; show "Pass" state and a "Get the Pass" nudge when the free cap is hit.
|
||||
3. **Tournament:** weekly job on IAP ranks pass holders across games, pays prizes from the games' wallets, posts to the
|
||||
Game Achievements topic.
|
||||
4. **Chatbot, release note, presentation games slide, and the guide's games section**: say "free play pays; the Pass
|
||||
plays more" (never "earn more").
|
||||
5. **QA:** iap-qa plus a scripted run per game: free cap hit -> nudge; pass bought -> cap raised; progress reward over
|
||||
the cap -> paid the next day; pass expiry -> back to free caps.
|
||||
|
||||
## 6. Rollout
|
||||
|
||||
- Announce one week ahead (the free cap change affects today's PolHunter regulars). First week: pass at $5 with a
|
||||
launch tournament; watch passes sold, POL out per pass, free-tier burn, verified visits delivered.
|
||||
- Review after 14 days against: company net per pass >= $0.40, free burn under 150 POL/week, no drop in visit deliveries.
|
||||
|
||||
## Built (IAP side, 2026-10-16)
|
||||
|
||||
Everything below is on IAP, behind `gamePassEnabled` (default off). The caps are recorded from day one and ENFORCED only from
|
||||
`capsStartDate`, so the change can be announced a week ahead and Admin can read what the caps would have done meanwhile.
|
||||
|
||||
**Files**
|
||||
- `gamepass.js` (new): pass store, waiting orders, cap ledger (`DATA_DIR/gamepass-ledger.json`, refs kept 90 days), tournament,
|
||||
admin stats, prune. Durable persisted maps `gamepass`, `gporders`, `gpprizes` (added to the DURABLE set in server.js so a deploy
|
||||
never wipes them).
|
||||
- `server.js`: settings defaults, init + hourly tournament tick + 6-hourly prune, purchase-event fulfilment (inside the
|
||||
`marks.claim` block, so two app copies never double-fulfil), partner helpers (`GP_SECRETS`, `gpPartnerCheck`, `gpResolve`,
|
||||
`gpDevNow`), `polUsdLive()` (catalog rate, 10-minute cache), `gpClaim` (the `gamePass` claim on every sign-in hand-off token,
|
||||
including PolHunter's), and the endpoints below.
|
||||
- `public/my.html` + `public/assets/my.js`: the Game Pass card at the top of Members > Games (state, caps line, Buy/Extend with
|
||||
`IAP.confirmBox`, waiting state with a Buy-a-package button), deep link `/my#games?pass=1` (setPane now strips a `?query` from
|
||||
the hash and highlights the card), the Overview nudge card `gpNudge` (shown once a day per browser after a game reports a free-cap
|
||||
hit, never to pass holders). Asset tag bumped to `my.js?v=20261016a`.
|
||||
- `public/admin.html` + `public/assets/admin.js`: Admin > Game Pass pane (passes sold week/total, active, POL out per pass week,
|
||||
free/pass cap hits, deferred queue, tournament last run + unpaid prizes, "Settle last week now", comp a pass). Tag
|
||||
`admin.js?v=20261016gp`.
|
||||
- `chatbot.js`: canned answer + FACTS line, `KNOWLEDGE_DATE` 2026-10-16.
|
||||
- `qa/gamepass.mjs` (new, `bash qa/run.sh gamepass`), `qa/walk.mjs` (Games tab card on/off + admin pane), `qa/run.sh`.
|
||||
- `docs/GAME-PASS-RELEASE.md`: the member-facing release note draft (not sent).
|
||||
|
||||
**Settings** (Admin > Settings > Site settings; all read live, no deploy): `gamePassEnabled` ('0'), `gamePassPriceCredits` (500),
|
||||
`gamePassDays` (7), `capFreeDaily` (0.30), `capFreeTotal` (2.0), `capPassDaily` (1.50), `capPassTotal` (5.0), `capsStartDate` ('',
|
||||
Central YYYY-MM-DD), `passTournamentPct` (5), `telegramGamesTopicId` ('661565'), `telegramGamesChatId` ('' = the shared echo chat).
|
||||
|
||||
**Endpoints**
|
||||
- Members: `GET /api/my/gamepass` -> `{ enabled, active, until, price, days, usd, waiting, bought, caps, capsStart, lastCapHit,
|
||||
tournament }`; `POST /api/my/gamepass/buy` -> `{ ok, active, until }` or `{ needPay: true, payUrl: '/my?from=gamepass#buy',
|
||||
order, price, need }`. Spends `gamePassPriceCredits` purchased-grade credits through `ads.gamePurchase(purchasedOnly)` with the
|
||||
credit-log label "Game Pass (7 days)"; short = waiting order, fulfilled by the next $5+ package purchase event.
|
||||
- Games (signed, see 3a): `GET /api/partner/player`, `POST /api/partner/polgrant`, `POST /api/partner/polgrant/void`,
|
||||
`GET /api/partner/tournament/pending`, `POST /api/partner/tournament/paid`.
|
||||
- Admin: `GET /api/admin/gamepass/stats`, `POST /api/admin/gamepass/comp { email, why }`,
|
||||
`POST /api/admin/gamepass/tournament/run { week?, force? }`.
|
||||
|
||||
**Tournament job**: hourly tick; once Monday 9 AM Central has passed and the closed week (Mon 00:00 to Mon 00:00 Central) has no
|
||||
row, exactly one app copy (`marks.claim('gamepass-tournament:<week>')`) ranks the week's pass holders by grants reported through
|
||||
`polgrant` (progress and daily weigh the same, one point per ref with pol > 0), pool = `passTournamentPct` of the week's pass sales
|
||||
in USD at the live catalog POL rate, split 50/30/20, rows recorded in `gpprizes` as pending, top 3 posted to the Game Achievements
|
||||
topic (`telegramGamesTopicId`, only when enabled), winners get an inbox notice (kind `notice`). Comps (`/comp`) are passes, not
|
||||
sales. If the POL rate is unavailable the tick retries next hour.
|
||||
|
||||
**Known limits / follow-ups**
|
||||
- The cap ledger is a JSON file on the volume (like the other IAP side stores), not a MySQL table: during the ~30 s deploy overlap
|
||||
two app copies each hold their own copy and the last save wins. A grant answered by the copy that is about to stop could be
|
||||
re-answered fresh by the other on retry. Move `refs`/`days` into MySQL if the games report drift.
|
||||
- `qa/gamepass.mjs` stubs the credit charge (`devPaid`) for the "buy -> active" step: `ads.gamePurchase(purchasedOnly)` needs a
|
||||
position with on-chain package credits, which a local copy without RPC cannot have. The "short -> waiting order -> package fulfils
|
||||
it" step runs the real path. The purchasedOnly charge itself is the live PolyWarriors mint path.
|
||||
- Prize POL is not sent by IAP (see 3a item 8): PolHunter's faucet pays the pending rows every 10 minutes behind `GAMEPASS=on`;
|
||||
the Games pane lists whatever is still unpaid.
|
||||
- Settings pass through `/api/admin/site` like every other site setting (that endpoint accepts any key; the defaults above make the
|
||||
Game Pass keys show in the Site settings form).
|
||||
|
||||
## Pass tiers: Explorer, Champion, Sovereign, Legend (IAP side, 2026-10-18; restructured 2026-10-22)
|
||||
|
||||
Spec: `ultima-rpg/docs/IAP-PASSES-SPEC.md`. Marty approved the safe form on 2026-10-18 (never more POL) and Dallas's new structure
|
||||
on 2026-10-22 (plus Sovereign and the yearly Legend). On 2026-10-25 Marty set every tier price to an InstantAdPay one-click
|
||||
package amount ($5, $10, $20, $50, $100, $250, $500), so the cheapest qualifying package is exactly the pass price and the pass
|
||||
comes with that package's ad credits (was $19.99 / $39.99 / $99.99 / $249.99). The weekly pass is unchanged. Everything above weekly stays
|
||||
switched off for members (`sovTiers` 0) until Marty flips it.
|
||||
|
||||
| Tier | Name | Price | Length | In Shards of Valor (each includes everything below) |
|
||||
|---|---|---|---|---|
|
||||
| `weekly` | Game Pass | 500 credits ($5) | 7 days | the Game Pass in all nine games, the Sunless Vault, weapons unlocked |
|
||||
| `explorer` | Explorer | 2000 ($20, the Activation package) | 30 days | weapons, gear, 2 DLC islands |
|
||||
| `champion` | Champion | 5000 ($50, the Builder package) | 30 days | weapons, gear, 4 DLC islands of your choice, level cap 30 |
|
||||
| `sovereign` | Sovereign | 10000 ($100, the Growth package) | 30 days | weapons, gear, all DLC islands, level cap 40 |
|
||||
| `legend` | Legend | 25000 ($250, the Leader package) | 365 days | weapons, gear, all DLC islands, every bonus hero while active, level cap 40 |
|
||||
|
||||
**Bonus heroes (2026-11-05, Marty approved).** Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin are
|
||||
SOLD ONE TIME (no subscription, no expiry), not by a tier: $20 each (2000 cents, the Activation package) and a $50 bundle (5000, the
|
||||
Builder package) of Valda, Morag and Roland by default. Paid like a pass: POST /api/my/heroes/buy { hero } opens a waiting order (kind
|
||||
hero); a fresh package of at least the price from one of the member's own positions fulfils it in `onEvent` (one package, one order, the
|
||||
highest-priced it covers). Owned heroes live on the passes record (`heroes`, `heroBundle`) and never in `bought`, so they never feed the
|
||||
Pass Tournament pool. Settings: `heroSales` (sale switch, OFF), `heroPrice<Name>Cents` (0 = free for every account), `heroBundlePriceCents`,
|
||||
`heroBundleHeroes`, `heroBundleCap` (empty: no cap change; not approved). Shards of Valor reads `heroes`, `heroBundle`, `heroSale` (and
|
||||
`heroBundleCap` only when set) on the sign-in hand-off. Admin > Game Pass has a hero test on the admin's own account. QA: qa/sov-heroes-store.cjs.
|
||||
|
||||
- **One table**: `gamepass.js` `TIER_DEFS` holds the rank, wire key, display name, settings stem, default price/length and the
|
||||
member-card list for every tier. Rename a tier there (the card, admin pane, charge label and chatbot all read it).
|
||||
- **Rank**: weekly < explorer < champion < sovereign < legend. Every tier is a Game Pass holder everywhere with exactly the pass
|
||||
caps; `polgrant` keeps answering `pass: true` (a boolean).
|
||||
- **Store**: `record.tiers = { weekly: { until }, explorer: { until }, champion: { until }, sovereign: { until }, legend: { until } }`,
|
||||
the legacy `until` mirrors the weekly tier, bought rows carry `tier` (missing = weekly), waiting orders carry `tier` (missing =
|
||||
weekly). Lazy migration: a record without `tiers` reads its `until` as the weekly tier.
|
||||
- **Wire**: `flag()` = `{ active, until, tier, tiers }` (`tier` = highest active, `until` = that tier's end; `tiers` has all five
|
||||
keys). The hand-off token carries `gamePass: { active, until, tier }`; `GET /api/partner/player` carries
|
||||
`pass: { active, until, tier, tiers }`, so Shards of Valor sees `sovereign` / `legend`.
|
||||
- **Buy**: `POST /api/my/gamepass/buy { tier }` (missing = weekly). Every tier above weekly needs `sovTiers` on (and the weekly pass
|
||||
on); while off, nobody sees or buys them on /my, the admin included (2026-10-25: the member card shows every account the
|
||||
member view). The admin tests them in Admin > Game Pass > Tier test and preview (`GET /api/admin/gamepass/preview`, `POST
|
||||
/api/admin/gamepass/test-buy | test-cancel | test-comp { tier }`, always the signed-in admin's own account). Short of purchased credits: a
|
||||
waiting order per tier; a package of at least the tier price fulfils the highest-priced order it covers (one pass per purchase,
|
||||
each tx once). Copy names the package that pays for the pass, which since 2026-10-25 is exactly the price: $20 (Explorer), $50
|
||||
(Champion), $100 (Sovereign), $250 (Legend); the card says the pass comes with that package's ad credits.
|
||||
- **Renew / expiry**: no auto-renew, no proration. Buying again extends that tier from `max(now, until)` by its length (Legend: 365
|
||||
days). Tiers run side by side; when a higher one ends the next one shows through. Admin comp takes a tier;
|
||||
`POST /api/admin/gamepass/revoke { email, tier, why }` ends one tier now (support refunds only, credits are not returned by it).
|
||||
- **Tournament**: any tier holds a seat; only weekly sales feed the pool unless `passTournamentTierSales` is `1` (then every tier's
|
||||
sales do).
|
||||
- **Settings** (defaults): `sovTiers` 0; kill switches `gamePassExplorerEnabled` / `gamePassChampionEnabled` /
|
||||
`gamePassSovereignEnabled` / `gamePassLegendEnabled` 1 (a `0` stops one tier); `gamePassExplorerPriceCredits` 2000,
|
||||
`gamePassChampionPriceCredits` 5000, `gamePassSovereignPriceCredits` 10000, `gamePassLegendPriceCredits` 25000;
|
||||
`gamePassExplorerDays` / `gamePassChampionDays` / `gamePassSovereignDays` 30, `gamePassLegendDays` 365;
|
||||
`passTournamentTierSales` 0. A value saved in the site settings file wins over these defaults.
|
||||
- **Chatbot**: while `sovTiers` is off the assistant only says more passes are coming soon (no prices, no contents, no date); once
|
||||
on, its fact lists each tier on sale with the live price, length and contents.
|
||||
- **Member UI**: the Games tab card shows the tiers side by side (end dates in Central time); `/my#passes` opens it (the
|
||||
Shards of Valor Buy button). **Admin**: Game Pass pane "By pass tier" table, comp per tier, end-a-tier button.
|
||||
- **Tests**: `bash qa/run.sh sov-passes` (store unit checks + a local copy where the admin buys Explorer and Sovereign through the
|
||||
real `ads.gamePurchase(purchasedOnly)` path with credits seeded by `qa/sov-passes-stub.cjs`, and a Legend order is fulfilled by
|
||||
a $250 package).
|
||||
|
||||
## Games: as built (2026-10-16, local commits only, nothing deployed)
|
||||
|
||||
Everything is behind `GAMEPASS=on` (env, default off = today's behaviour, so the games can be deployed before launch). `IAP_URL` is
|
||||
read where it already existed (default `https://instantadpay.com`). No reward amount changed anywhere; every game's local
|
||||
`dailyCapPol` / pool / hidden ceiling still stands in FRONT of the IAP call as a backstop and none was raised.
|
||||
|
||||
**The shared client `polgrant.js`** (byte-identical copy in every repo, md5 `f3c00b90…116a`; change one, copy to the rest):
|
||||
`spooky-doors/server/`, `road-agent/server/`, `match3-game/server/`, `seek-game/`, `spellwheel/`, `polybreak/`, `cyber-battle/game/`,
|
||||
`polhunter/lib/`, `drip-runner/lib/`.
|
||||
- `grant({ memberId, email, kind, pol, ref })` -> `POST /api/partner/polgrant` `{ game, memberId, email, kind, pol, ref }`, headers
|
||||
`X-Game-Ts` + `X-Game-Sig` (plus an informational `X-Game`), 6 s timeout. Returns `{ allowed, deferred, carried, pass, day, capHit,
|
||||
enforced, repeat, suspended, retry: false }` or `{ allowed: 0, retry: true, error }` on ANY non-200 / non-JSON / network error
|
||||
(fail closed; a 404 "no such member" is also a retry, so the games only call it for signed-in IAP members).
|
||||
- `email` always rides along (wallet-less members have `memberId: 0`; Drip Runner maps its negative `emailId` to 0). `whoOf()` = the
|
||||
member id when > 0, else the lowercased email; the pass cache and the retry queue key on it.
|
||||
- `voidGrant`, `fetchPass` (`GET /api/partner/player`, cached 10 min, fail-soft), `passOf` / `rememberPass` (hand-off claim
|
||||
`gamePass: { active, until }` + every answer), `view()` for the lobby, `note(resp, kind, nominal)` = the player-facing line.
|
||||
- Retry queue `polgrantq` in each game's store: `enqueue` dedupes per (who, ref); `retry(pay)` every 5 min, 48 h then `stuck` +
|
||||
`notify('gpstuck')` once (each game routes it to its faucet alert path); `queued()` keeps a waiting ref from being re-asked.
|
||||
- Carry-forward collection (SD-pattern games): `carrySweep()` on the existing tick, once a Central day per account with `gpOwed > 0`,
|
||||
a zero-POL `progress` call with ref `carry:<YYYY-MM-DD>`; IAP folds the carry into `allowed` (`carried`). `gpOwed` is bookkeeping
|
||||
(`+= deferred`, `-= carried`); the money truth is IAP's. **IAP accepts `pol: 0`** (verified by the integration test below).
|
||||
- `tournamentPending()` reads `rows` from `GET /api/partner/tournament/pending`; `tournamentPaid(row, tx)` posts
|
||||
`{ game, id?, week, place, memberId, email, tx }` (PolHunter only).
|
||||
|
||||
**Per game**
|
||||
|
||||
| Game | Files | Refs (kind) | Pass perk | Tests |
|
||||
|---|---|---|---|---|
|
||||
| Spooky Doors (`spooky-doors`) | server/pol.js (quote/settleGrant/grantGated/payQueued/carrySweep), server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `rung:<n>` (progress) | +1 door/day while the season runs | sim 63/63, gamepass 37/37, e2e 200 pass / 3 pre-existing timing fails |
|
||||
| Road Agent (`road-agent`) | server/pol.js, server/game.js, server/server.js, server/social.js, src/main.js, test/gamepass.mjs | `sector:<n>` (progress); `patrol:<day>`, `patrol:<day>:2` (daily) | 2 patrols/day, +25% scrap | sim pass, gamepass 22/22, e2e pass |
|
||||
| Gem Kingdom (`match3-game`) | server/pol.js, server/server.js (`/api/continue/free`), src/world.js, src/battle.js, src/game.js, test/gamepass.cjs | `stage:<n>` (progress, bosses included) | one free continue/day, no sponsor visit | kingdom.test pass, gamepass 26/26, vite build ok |
|
||||
| ClutterHunt (`seek-game`) | pol.js, server.js, public/game.js, public/index.html (`game.js?v=20261016gp`), test/gamepass.js | `<season>:<room>:<clear or stars or xclear or xstars>` (progress) | 2 bonus hints banked once per Central day | gamepass 23/23 |
|
||||
| SpellWheel (`spellwheel`) | pol.js (`streakPassPol: 0.30`), server.js, public/play.js, public/play.html (`play.js?v=7`), test/gamepass.js | `level:<ch>:<n>`, `chapter:<ch>` (progress); `daily:<day>`, `streak:<day>` (daily) | streak 0.15 -> 0.30, 1 free hint/day | gamepass 25/25 |
|
||||
| PolyBreak (`polybreak`) | pol.js (`gemDailyPassPol: 1.5`), server.js, public/play.js, public/play.html (`play.js?v=6`), test/gamepass.js | `round:<n>` (progress); `gem:<run>:<id>` (daily) | gem ceiling 0.5 -> 1.5/day; +1 paddle per round | gamepass 27/27, run.js 70/70 |
|
||||
| PolyWarriors (`cyber-battle/game`) | pol.js, server.js (DEF_PAY_PASS 25), missions.js (3 + pass), public/game.js, public/game.html (`game.js?v=30`), test/gamepass.js | `rival:<id>`, `ladder`, `elite` (progress) | +1 daily mission (4), held defense 15 -> 25 Circuits, Pass row on the profile (card.js untouched) | gamepass 26/26 |
|
||||
| Drip Runner (`drip-runner`) | lib/ledger.js (chapterDripGated), lib/game.js, server.js, public/play.js, public/play.html (`play.js?v=20261016gp`), test/gamepass.js | `chapter:<n>` (progress; the only POL it pays) | a shield at every run start | gamepass 28/28, run.js pass |
|
||||
| PolHunter (`polhunter`) | lib/rewards.js (status `capped` / `gp-wait`), lib/detective.js, lib/faucet.js (`HUNT_DRY_RUN`), lib/tournament.js (new), server.js, public/app.js, public/app.html (`app.js?v=22`), test/gamepass.js | `find:<missionId>:<day>`, `detective:<boxId>` (daily) | 5 missions/day (+2), 2 Ad Detective cases/day | gamepass 42/42, run.js pass |
|
||||
|
||||
Game commits (local, not pushed): spooky-doors f54ef0c, road-agent d345bbf, match3-game 972dd71, seek-game 9751329, spellwheel b582b72,
|
||||
polybreak e9c3a54, cyber-battle/game fa76d30, drip-runner a7b1fd9, polhunter 7391fd7 + 08486e1. Spooky Doors, Road Agent and Gem
|
||||
Kingdom are Vite builds (hashed assets, no `?v=` bump).
|
||||
|
||||
**Decisions taken on the games side (flip if wanted)**
|
||||
1. Advertiser-funded PolHunter missions (`mission.paid`) are NOT gated: the advertiser paid for that completion. Gate them in
|
||||
polhunter/server.js (`gp.on() && !m.paid`) if the cap should cover them too.
|
||||
2. A 0-allowed daily reward is still "done": a capped find counts as today's find (status `capped`, never reaches the faucet); a capped
|
||||
gem/patrol/daily puzzle is recorded as handled with `pol: 0`. The player sees the cap line with the Pass link.
|
||||
3. Fail closed, visibly: IAP unreachable = the reward is recorded (SD pattern: nothing written until IAP answers, ref queued; PolHunter:
|
||||
a `gp-wait` row settled by the queue), the player sees "Your reward is recorded and pays as soon as InstantAdPay confirms it."
|
||||
4. Perks read the cached flag (hand-off claim -> every grant answer -> `fetchPass` every 10 min); a pass bought mid-session shows
|
||||
within 10 minutes or on the next grant.
|
||||
5. Deferred progress rewards: the ledger row is written with `pol: allowed` (0 included) so the achievement is marked done; carry comes
|
||||
back through `carry:<day>` or any later grant.
|
||||
6. Not built: a per-game admin view of the queue (PolHunter's admin state shows queue + stuck counts and the tournament payer).
|
||||
|
||||
**Pass Tournament payer (PolHunter `lib/tournament.js`)**: every 10 min behind `GAMEPASS=on`, only with the faucet wallet configured.
|
||||
Per pending row: a durable claim in `tourney-claims` BEFORE sending (`id:<id>` or `wk:<week>:<place>`), the tx hash written the
|
||||
moment the chain has it, then `POST /api/partner/tournament/paid`. A claimed row with a hash is only re-reported, never re-sent; a
|
||||
claim without a hash is retried after 10 min; a send failure releases the claim, leaves the row pending on IAP and alerts
|
||||
(`tourneyfail`); low balance alerts once a day. `HUNT_DRY_RUN=on` records `wouldPay` and sends nothing. **Trap:** a claim written
|
||||
during a dry run is permanent (`c.dry` rows are skipped forever), so a prize row seen while `HUNT_DRY_RUN=on` is never paid after the
|
||||
flag is turned off unless `tourney-claims.json` on the PolHunter volume is cleared. Prizes bypass the per-find daily cap and the
|
||||
payout threshold. Admin: `/api/admin/state` -> `tournament` and `gamepass` blocks.
|
||||
|
||||
**Integration test (both sides, local)**: `bash qa/run.sh gamepass-games` (qa/gamepass-games.cjs) boots IAP like qa/gamepass.mjs and
|
||||
drives the REAL `spooky-doors/server/polgrant.js` and `polhunter/lib/tournament.js` against it (needs the sibling game repos under
|
||||
`../..`): fetchPass free/pass, daily within/over cap, progress deferral, the `carry:<day>` zero-POL call on the next Central day
|
||||
(`carried` > 0, idempotent repeat), void, bad secret and IAP-down -> `{ allowed: 0, retry: true }`, the retry queue, and the
|
||||
tournament payer in dry run and live (mocked faucet.send) until IAP's pending list is empty. 2026-10-16: 44/44 after the `rows`
|
||||
fix on the pending endpoint (the games read `rows`; IAP answered only `pending`).
|
||||
|
||||
## Payment: the package rail (2026-10-22, Marty)
|
||||
|
||||
**Why.** A pass paid from a credit balance brings in no new money and pays nobody upline: credits come from packages whose POL was
|
||||
already split on chain ($2.50 sponsor, $1 level 2, $0.50 level 3, $1 company on a $5 package). Today's pass buyer paid from an old
|
||||
balance. From now on every pass is a fresh package purchase, so the sponsor and team are paid exactly like any package.
|
||||
|
||||
**Rule.**
|
||||
- `POST /api/my/gamepass/buy { tier }` never charges anything. It opens a waiting order for that tier (or returns the one already
|
||||
open) and answers `{ needPay: true, order, orderTs, package, payUrl, message }`. The card sends the member to Buy credits.
|
||||
- The order is fulfilled only by an on-chain `Purchase` event (`gamepass.onEvent`, inside the `marks.claim` block, so one app copy
|
||||
acts) that meets ALL of:
|
||||
- the buyer id is one of this account's own positions: the main member id (`accounts.byMemberId`) or a linked position
|
||||
(`accounts.positionByMember`);
|
||||
- `priceCents` is at least the tier price (setting `gamePass*PriceCredits`, now read as cents; the copy names the package that
|
||||
covers it: $5, $20, $50, $100, $250);
|
||||
- the purchase was mined AFTER the order was opened: block time from `eth_getBlockByNumber` (server.js `blockTime` dep), with a
|
||||
30 s clock grace; if the block cannot be read after 3 tries the indexed-at time is used (never earlier than the block);
|
||||
- the tx has never paid a pass or an order before (checked across every order and every bought row, every account).
|
||||
- One pass per purchase: the highest-priced waiting order the package covers. The member keeps every credit of the package.
|
||||
- Bought row: `{ via: 'package', tier, tx, cents, order, buyerId, usd: <pass price>, packageUsd }`. `buyerId` marks the new rail.
|
||||
- Existing passes are untouched (never revoked). On 2026-10-22 production held two sales: one `via: 'credits'` (500 credits,
|
||||
campaign 513) and one `via: 'package'` fulfilled under the old rule (tx 0xdbfb77c7...). No order was left waiting.
|
||||
- Admin > Game Pass > **Pass sales**: every sale with how it was paid ("package", "credit-paid (old rule)", "package (old rule)"),
|
||||
pass value, package value and the package tx; the header splits the counts. Stats field `passes.pay` and `sales`.
|
||||
- Tests: `qa/gamepass.mjs` (order, package mined before the order refused, too small refused, another member refused, fresh package
|
||||
fulfils, replayed tx refused, extend while active); `qa/sov-passes-store.cjs` and `qa/sov-passes-local.mjs` updated the same way.
|
||||
- Not changed: the caps, the tiers, the tournament (pool = pass price of each sale), the hand-off claims.
|
||||
@@ -0,0 +1,61 @@
|
||||
# InstantAdPay reviewer kit: Jamie (@cryptojaime)
|
||||
|
||||
*Plain-text copy of the shareable page. Code minted 2026-09-29: CRYPTOJAIME, 500 credits, no cap, no expiry, one redemption per account. Jamie is member #166, sponsor martbost, wallet linked, payouts on.*
|
||||
|
||||
## Your code and link
|
||||
|
||||
- Code: **CRYPTOJAIME**
|
||||
- Join link with the code built in: https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
|
||||
- Existing members type CRYPTOJAIME into "Have a promo code?" on their Overview.
|
||||
- Hook variants: add `&v=instant`, `&v=free`, `&v=ledger`, `&v=adspend` or `&v=two`.
|
||||
|
||||
## What the code does
|
||||
|
||||
500 credits per redemption (a credit is one cent of ad delivery, so $5 of advertising). Paid as a drip: 100 the day they redeem, then 100 on each day they finish the five-view daily ad set, five installments in all, 30 days to collect. One redemption per account, no cap on uses, never expires. Earned-grade credits: they run ads, never cash, cannot be withdrawn.
|
||||
|
||||
## What Jamie earns
|
||||
|
||||
Every redeemer is his direct referral. 50% of every package a direct buys (first and every one after), 20% at level 2 once two directs have bought a $20+ package, 10% at level 3 at five. Platform keeps 20%. Unqualified levels pass up.
|
||||
|
||||
| Package | Price | Credits | Direct sponsor gets |
|
||||
|---|---|---|---|
|
||||
| Micro | $5 | 500 | $2.50 |
|
||||
| Activation (qualifying buy) | $20 | 2,000 | $10 |
|
||||
| Builder | $50 | 5,500 | $25 |
|
||||
| Growth | $100 | 12,000 | $50 |
|
||||
| Leader | $250 | 32,500 | $125 |
|
||||
|
||||
## Paste-ready copy
|
||||
|
||||
**Video description / pinned comment**
|
||||
|
||||
InstantAdPay is the ad platform I have been reviewing: join free by email, earn credits by viewing ads, run your own campaign for nothing, and every ad package that sells is split by a smart contract on Polygon the moment it sells. No balances held, no payday, every payout public.
|
||||
|
||||
Use my code CRYPTOJAIME for 500 free ad credits, or just join through my link (the code is built in):
|
||||
https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
|
||||
|
||||
Honest note: this is advertising, not investing. Members earn from the ad packages people in their line buy, nothing else. No income is promised, results depend on effort, and crypto involves risk.
|
||||
|
||||
**Short post / comment reply**
|
||||
|
||||
Free to join, ad credits for viewing ads, and packages that pay your sponsor instantly on-chain. Code CRYPTOJAIME gets you 500 free credits: https://instantadpay.com/join/cryptojaime?promo=CRYPTOJAIME
|
||||
|
||||
**DM to someone who already joined**
|
||||
|
||||
Glad you are in. Quick tip: open your Overview, find "Have a promo code?" and enter CRYPTOJAIME. That adds 500 free ad credits, 100 today and 100 more each day you finish your five ad views. Then link a wallet and switch on payouts so anything your own people buy pays you instantly.
|
||||
|
||||
## Creatives
|
||||
|
||||
Full banner kit, posts, swipes and objection answers: dashboard > Promo tools. Direct files:
|
||||
https://instantadpay.com/banners/iap-hero-1200x630.png
|
||||
https://instantadpay.com/banners/iap-advertise-earn-1200x630.jpg
|
||||
https://instantadpay.com/banners/iap-wired-wednesday-1200x630.jpg
|
||||
https://instantadpay.com/banners/iap-five-dollar-friday-1200x630.jpg
|
||||
|
||||
Pages to link: /ledger, /earning, /blog, /partners, /wednesday, /friday.
|
||||
|
||||
## The honest part
|
||||
|
||||
InstantAdPay sells advertising. Members earn from the ad packages people in their line buy, and nothing else. No earn-without-referring option, on purpose. No income guaranteed, results depend on effort, crypto involves risk of loss. Credits are ad delivery, never cash.
|
||||
|
||||
Contact: Marty Bostick, marty@marketingwithmarty.com, t.me/cryptoteambuild
|
||||
@@ -0,0 +1,191 @@
|
||||
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
|
||||
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
|
||||
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
|
||||
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
|
||||
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
|
||||
//
|
||||
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
|
||||
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
|
||||
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
|
||||
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
|
||||
// listing a folder). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
|
||||
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
|
||||
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
|
||||
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
|
||||
|
||||
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
|
||||
const cache = new Map(); // name -> { body: string, at: ms }
|
||||
const pending = new Map(); // name -> body string | null (delete)
|
||||
let flushing = false, timer = null;
|
||||
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
|
||||
|
||||
function nameOf(p) {
|
||||
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
|
||||
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
|
||||
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
|
||||
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
|
||||
return rel;
|
||||
}
|
||||
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
|
||||
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
|
||||
|
||||
function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); }
|
||||
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
|
||||
|
||||
async function flush() {
|
||||
if (!pool || flushing || !pending.size) return;
|
||||
flushing = true;
|
||||
try {
|
||||
for (const [name, body] of [...pending]) {
|
||||
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
|
||||
if (!writer) { pending.delete(name); stats.refused++; continue; }
|
||||
const c = await pool.getConnection();
|
||||
try {
|
||||
await c.beginTransaction();
|
||||
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
|
||||
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
|
||||
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
|
||||
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
|
||||
await c.commit();
|
||||
if (pending.get(name) === body) pending.delete(name);
|
||||
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
|
||||
finally { c.release(); }
|
||||
}
|
||||
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
|
||||
}
|
||||
|
||||
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
|
||||
function install(dataDir) {
|
||||
if (ROOT) return; ROOT = path.resolve(dataDir);
|
||||
fs.readFileSync = function (p, o) {
|
||||
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) throw enoent(p);
|
||||
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
|
||||
};
|
||||
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
|
||||
fs.writeFileSync = function (p, data, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
|
||||
const flag = o && typeof o === 'object' ? o.flag : null;
|
||||
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
|
||||
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
|
||||
};
|
||||
fs.appendFileSync = function (p, data) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
|
||||
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
|
||||
};
|
||||
fs.renameSync = function (a, b) {
|
||||
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
|
||||
if (!nb && !na) return O.renameSync.apply(fs, arguments);
|
||||
let body;
|
||||
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
|
||||
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
|
||||
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
|
||||
};
|
||||
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
|
||||
fs.statSync = function (p, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
|
||||
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
|
||||
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
|
||||
};
|
||||
}
|
||||
|
||||
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
|
||||
// must not run on an empty copy.
|
||||
async function init(opts) {
|
||||
const url = String(process.env.DOCSTORE_URL || '').trim();
|
||||
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
|
||||
const mysql = require('mysql2/promise');
|
||||
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
|
||||
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
|
||||
for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) });
|
||||
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
|
||||
// first boot for any document: import its file, then set the file aside
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
|
||||
for (const p of walk(ROOT)) {
|
||||
const n = nameOf(p); if (!n || cache.has(n)) continue;
|
||||
const body = O.readFileSync.call(fs, p, 'utf8');
|
||||
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
|
||||
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
|
||||
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
|
||||
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
|
||||
O.renameSync.call(fs, p, p + '.imported-' + stamp);
|
||||
}
|
||||
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
|
||||
ready = true;
|
||||
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
|
||||
const shut = () => { flush().catch(() => {}).finally(() => {}); };
|
||||
process.once('beforeExit', shut);
|
||||
return true;
|
||||
}
|
||||
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
|
||||
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
|
||||
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
|
||||
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
|
||||
async function openSplit(sp) {
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
|
||||
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
|
||||
}
|
||||
async function insertMany(table, items, key, ts) {
|
||||
for (let i = 0; i < items.length; i += 500) {
|
||||
const part = items.slice(i, i + 500);
|
||||
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
|
||||
}
|
||||
}
|
||||
// first boot: the array still inside the document moves to its table, then the document is saved without it
|
||||
async function migrateSplit(sp) {
|
||||
const d = cache.get(sp.doc); if (!d) return;
|
||||
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
|
||||
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
|
||||
await insertMany(sp.table, arr, sp.key, sp.ts);
|
||||
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
|
||||
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
|
||||
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
|
||||
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
|
||||
obj[sp.field] = []; const body = JSON.stringify(obj);
|
||||
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
|
||||
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
|
||||
}
|
||||
function rows(table) { return ROWS.get(table) || null; }
|
||||
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
|
||||
async function runRows() {
|
||||
rowBusy = true;
|
||||
try {
|
||||
while (rowQ.length && writer) {
|
||||
const op = rowQ[0];
|
||||
try {
|
||||
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
|
||||
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
|
||||
rowQ.shift();
|
||||
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
|
||||
}
|
||||
} finally { rowBusy = false; }
|
||||
}
|
||||
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
|
||||
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
|
||||
function isOn() { return ready && !!pool; }
|
||||
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
|
||||
async function claim(key) {
|
||||
if (!pool) return true;
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
|
||||
return r.affectedRows === 1;
|
||||
}
|
||||
|
||||
// SIGTERM during a deploy: write what is pending, then exit
|
||||
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
||||
@@ -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; } };
|
||||
@@ -22,7 +22,7 @@
|
||||
{
|
||||
"hours": 192,
|
||||
"subject": "The one thing nobody tells you about ad platforms..",
|
||||
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $250, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
|
||||
"body": "This might be the most important email I send you about InstantAdPay.\n\nBecause there is a detail in how this works that most people do not notice until it is too late.\n\nIt is not about the ad credits, the formats, or even the commission structure.\n\nIt is about timing.\n\nHere is how it works. Your invite link is already live. If someone clicks it, signs up, and buys their first ad package, any package from $5 to $500, you receive 50 percent of that payment. The smart contract pays you in the same transaction. No holding tank, no withdrawal minimum, no waiting.\n\nThat is the upside everyone talks about.\n\nHere is what nobody mentions.\n\nThe moment a person buys their first package through any link, they are locked to that sponsor permanently. Every future package they buy pays that sponsor's line.\n\nSo if someone you know (a friend, a subscriber, a group contact) joins InstantAdPay through someone else's link and buys their first package there, they are locked to that other person for good.\n\n{{paid:You already bought, so your own placement is settled. Your link is live and paying.|If you have not bought yet, your link is still live. It still pays you 50 percent from anyone who clicks it today and buys.}}\n\nBut it will not capture the people you know unless you send it to them.\n\nOne person this week. Just put {{link}} where they will see it. That is all it takes.\n\n{{sponsor}} got their link from somewhere too. Same deal. Now it is your turn to pass it forward.\n\nMarty\n\n{{footer}}"
|
||||
},
|
||||
{
|
||||
"hours": 264,
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// Email typo check for NEW addresses (2026-10-22, after SendGrid bounces to gmai.com / outlook.comz).
|
||||
// Same file lives in InstantAdPay and LinkSpin. Catches:
|
||||
// 1. near-misses of the big mailbox providers (gmai.com, gmial.com, hotmial.com, yaho.com) -> "Did you mean ...?"
|
||||
// 2. mistyped endings (.con, .cmo, .comz, .nett) -> "Did you mean ...?"
|
||||
// 3. domains that cannot receive mail at all (no MX and no A/AAAA record)
|
||||
// A DNS timeout or server error never blocks anyone (fails open). Only call it where an address enters for the
|
||||
// first time - existing accounts must always be able to sign in with the address they already have.
|
||||
const dns = require('dns').promises;
|
||||
|
||||
const POPULAR = ['gmail.com', 'googlemail.com', 'yahoo.com', 'ymail.com', 'hotmail.com', 'outlook.com', 'live.com',
|
||||
'msn.com', 'icloud.com', 'me.com', 'mac.com', 'aol.com', 'protonmail.com', 'proton.me', 'mail.com', 'gmx.com',
|
||||
'gmx.de', 'yandex.com', 'yandex.ru', 'zoho.com', 'comcast.net', 'att.net', 'verizon.net', 'sbcglobal.net',
|
||||
'bellsouth.net', 'cox.net', 'charter.net', 'yahoo.co.uk', 'hotmail.co.uk', 'btinternet.com', 'yahoo.fr',
|
||||
'hotmail.fr', 'orange.fr', 'web.de', 't-online.de', 'libero.it', 'yahoo.com.br', 'outlook.com.br', 'rediffmail.com',
|
||||
'qq.com', '163.com', 'naver.com', 'seznam.cz', 'wp.pl', 'mail.ru'];
|
||||
const POP = new Set(POPULAR);
|
||||
// endings that are typos of .com/.net/.org (real TLDs like .co, .cm, .om are deliberately NOT here)
|
||||
const BAD_TLD = { con: 'com', cmo: 'com', comm: 'com', comz: 'com', coom: 'com', cpm: 'com', vom: 'com', xom: 'com',
|
||||
ocm: 'com', cmon: 'com', 'com.com': 'com', nett: 'net', nte: 'net', ent: 'net', ogr: 'org', orgg: 'org', rog: 'org' };
|
||||
|
||||
// optimal string alignment distance (Damerau-Levenshtein with adjacent swaps), capped
|
||||
function dist(a, b) {
|
||||
if (Math.abs(a.length - b.length) > 2) return 9;
|
||||
const d = [];
|
||||
for (let i = 0; i <= a.length; i++) { d[i] = [i]; }
|
||||
for (let j = 0; j <= b.length; j++) d[0][j] = j;
|
||||
for (let i = 1; i <= a.length; i++) {
|
||||
for (let j = 1; j <= b.length; j++) {
|
||||
const c = a[i - 1] === b[j - 1] ? 0 : 1;
|
||||
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + c);
|
||||
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
||||
}
|
||||
}
|
||||
return d[a.length][b.length];
|
||||
}
|
||||
|
||||
// providers that only ever use ONE domain, so gmail.co / gmail.cm / icloud.net are always typos.
|
||||
// (outlook, hotmail, yahoo, live have real national domains like hotmail.it, so they are not listed.)
|
||||
const SINGLE = { gmail: 'gmail.com', googlemail: 'googlemail.com', icloud: 'icloud.com', aol: 'aol.com',
|
||||
protonmail: 'protonmail.com', ymail: 'ymail.com' };
|
||||
const split = d => { const i = d.indexOf('.'); return i < 0 ? [d, ''] : [d.slice(0, i), d.slice(i + 1)]; };
|
||||
|
||||
function suggestDomain(domain) {
|
||||
if (POP.has(domain)) return null;
|
||||
const labels = domain.split('.');
|
||||
const two = labels.slice(-2).join('.'), last = labels[labels.length - 1];
|
||||
let d = domain;
|
||||
if (BAD_TLD[two]) d = labels.slice(0, -2).concat(BAD_TLD[two]).join('.');
|
||||
else if (BAD_TLD[last]) d = labels.slice(0, -1).concat(BAD_TLD[last]).join('.');
|
||||
if (POP.has(d)) return d;
|
||||
const near = nearestPopular(d);
|
||||
if (near) return near;
|
||||
return d !== domain ? d : null; // ending fixed but not a known provider: still suggest the fixed ending
|
||||
}
|
||||
|
||||
function nearestPopular(domain) {
|
||||
const [name, suffix] = split(domain);
|
||||
if (SINGLE[name] && domain !== SINGLE[name]) return SINGLE[name];
|
||||
let best = null, bestD = 9;
|
||||
for (const p of POPULAR) {
|
||||
const [pn, ps] = split(p);
|
||||
if (ps !== suffix) continue; // only compare names that share the same ending
|
||||
const dd = dist(name, pn);
|
||||
if (dd < bestD) { best = p; bestD = dd; }
|
||||
}
|
||||
// 1 edit always counts; 2 edits only for longer names, so short real domains are left alone
|
||||
return (bestD === 1 || (bestD === 2 && name.length >= 6)) ? best : null;
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms) {
|
||||
return Promise.race([promise, new Promise((_, rej) => setTimeout(() => rej(Object.assign(new Error('timeout'), { code: 'ETIMEOUT' })), ms))]);
|
||||
}
|
||||
|
||||
// true = has somewhere to deliver, false = definitely cannot receive mail, null = could not tell (fail open)
|
||||
async function domainReceives(domain) {
|
||||
const gone = c => c === 'ENOTFOUND' || c === 'ENODATA' || c === 'ESERVFAIL_NXDOMAIN';
|
||||
try {
|
||||
const mx = await withTimeout(dns.resolveMx(domain), 3000);
|
||||
if (mx && mx.length && !(mx.length === 1 && mx[0].exchange === '')) return true; // RFC 7505 null MX = no mail
|
||||
if (mx && mx.length) return false;
|
||||
} catch (e) { if (!gone(e.code)) return null; }
|
||||
try { await withTimeout(dns.resolve4(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
|
||||
try { await withTimeout(dns.resolve6(domain), 3000); return true; } catch (e) { if (!gone(e.code)) return null; }
|
||||
return false;
|
||||
}
|
||||
|
||||
// -> null when the address is fine, or { error, suggestion } to show the person
|
||||
async function emailIssue(email) {
|
||||
const e = String(email || '').trim().toLowerCase();
|
||||
const at = e.lastIndexOf('@');
|
||||
if (at < 1) return null; // the caller's own format check handles this
|
||||
const local = e.slice(0, at), domain = e.slice(at + 1);
|
||||
const fix = suggestDomain(domain);
|
||||
if (fix && fix !== domain) {
|
||||
const suggestion = local + '@' + fix;
|
||||
return { error: 'Did you mean ' + suggestion + '? Please check the email address.', suggestion };
|
||||
}
|
||||
if (POP.has(domain)) return null;
|
||||
const ok = await domainReceives(domain);
|
||||
if (ok === false) return { error: 'The email domain "' + domain + '" cannot receive mail. Please check the address.', suggestion: null };
|
||||
return null;
|
||||
}
|
||||
|
||||
module.exports = { emailIssue, suggestDomain, domainReceives };
|
||||
@@ -0,0 +1,158 @@
|
||||
// The Engine Room (Fuel Your Offers stage 4, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
|
||||
// LinkSpin. Each site gathers its OWN facts (facts shape below) and answers the other's signed /api/partner/engine call
|
||||
// with them; build() turns both sites' facts + the refuel streak (InstantAdPay is its source of truth) + the member's goal
|
||||
// into one plain dashboard: three dials, the streak panel, warning lights, six part lights and one "next move".
|
||||
//
|
||||
// facts (per site): { site: 'iap'|'linkspin', ok, credits: { available, inCampaigns }, campaigns: [{ id, name, type, status,
|
||||
// budget, delivered, clicks, created }], clicksWeek, loginFree, buyUrl, adsUrl,
|
||||
// LinkSpin only: goalsMonth, goalsCount, conv30, parts: { bannerSpin, spinLink, page, testing } each { state, note } }
|
||||
// Everything is credits and counts. Nothing here is money or a promise.
|
||||
'use strict';
|
||||
const DAY = 86400000;
|
||||
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : Number(v) || 0);
|
||||
const LINKS = {
|
||||
iapBuy: 'https://instantadpay.com/my#buy', iapCampaigns: 'https://instantadpay.com/my#campaigns', iapTracking: 'https://instantadpay.com/my#conversions',
|
||||
lsBuy: 'https://linkspin.app/credits#buy', lsAds: 'https://linkspin.app/ads', lsLinks: 'https://linkspin.app/links', lsBanner: 'https://linkspin.app/links#b', lsPages: 'https://linkspin.app/pages', lsConv: 'https://linkspin.app/conversions',
|
||||
};
|
||||
// 2026-10-25 (Marty: "the flow from InstantAdPay to LinkSpin is confusing"): every link points at the screen on the site the
|
||||
// member is ON when that site can do the job (buy, campaigns, conversion goals: InstantAdPay's Campaigns > Conversion
|
||||
// tracking card writes the same LinkSpin goals). Only LinkSpin-only tools (Banner Spin, spin links, pages) cross over, and
|
||||
// engine-room.js tags those links with ?from=<site>&task=<key> so LinkSpin shows an arrival strip with the first step.
|
||||
const linksFor = site => site === 'linkspin'
|
||||
? { buy: LINKS.lsBuy, campaigns: LINKS.lsAds, tracking: LINKS.lsConv }
|
||||
: { buy: LINKS.iapBuy, campaigns: LINKS.iapCampaigns, tracking: LINKS.iapTracking };
|
||||
const ACTIVE = new Set(['active', 'paused']);
|
||||
|
||||
// credits a day across recent campaigns: what each delivered over the days it has run (30 at most), summed
|
||||
function burnPerDay(camps, now) {
|
||||
let b = 0;
|
||||
for (const c of camps) {
|
||||
const age = Math.max(1, Math.min(30, (now - n0(c.created)) / DAY));
|
||||
if (c.status !== 'active' && now - n0(c.created) > 30 * DAY) continue;
|
||||
b += n0(c.delivered) / age;
|
||||
}
|
||||
return b;
|
||||
}
|
||||
function part(state, label, note, link, key) { return { state, label, note, link, key }; }
|
||||
|
||||
function build(o) {
|
||||
const now = o.now || Date.now();
|
||||
const rf = o.refuel || { on: false };
|
||||
if (!rf.on) return { on: false };
|
||||
const sites = [o.iap, o.ls].filter(f => f && f.ok);
|
||||
const camps = sites.flatMap(f => (f.campaigns || []).map(c => Object.assign({ site: f.site }, c)));
|
||||
const recent = camps.filter(c => ACTIVE.has(c.status) || now - n0(c.created) <= 30 * DAY || c.status === 'out');
|
||||
const locked = !rf.started;
|
||||
const here = o.site === 'linkspin' ? 'linkspin' : 'iap', L = linksFor(here);
|
||||
// ---- dial 1: fuel left vs this cycle's refuel ----
|
||||
const left = sites.reduce((s, f) => s + n0(f.credits && f.credits.available) + n0(f.credits && f.credits.inCampaigns), 0);
|
||||
const cy = rf.cycle || null;
|
||||
const refuelCredits = cy ? ['iap', 'linkspin'].reduce((s, k) => s + (cy[k] && cy[k].refueled ? n0(cy[k].credits) + n0(cy[k].bonus) : 0), 0) : 0;
|
||||
const burn = burnPerDay(recent, now);
|
||||
const daysLeft = burn > 0 ? Math.floor(left / burn) : null;
|
||||
const fuel = { left: Math.round(left), refuelCredits: Math.round(refuelCredits), pct: refuelCredits > 0 ? Math.max(0, Math.min(100, Math.round(left / refuelCredits * 100))) : null,
|
||||
burnPerDay: Math.round(burn), daysLeft, label: 'Fuel left' };
|
||||
// ---- dial 2: clicks this week, and per 1,000 credits on recent campaigns ----
|
||||
const clicksWeek = sites.reduce((s, f) => s + n0(f.clicksWeek), 0), clicksPrev = sites.reduce((s, f) => s + n0(f.clicksPrevWeek), 0);
|
||||
const del = recent.reduce((s, c) => s + n0(c.delivered), 0), clk = recent.reduce((s, c) => s + n0(c.clicks), 0);
|
||||
// the dial reads this week against last week: half way = the same as last week
|
||||
const clicks = { week: clicksWeek, prevWeek: clicksPrev, pct: clicksPrev > 0 ? Math.min(100, Math.round(clicksWeek / (2 * clicksPrev) * 100)) : null, per1000: del >= 100 ? Math.round(clk / del * 1000 * 10) / 10 : null, label: 'Clicks this week' };
|
||||
// ---- dial 3: goals this month (conversion pixel, LinkSpin keeps it for both sites) vs the member's own goal ----
|
||||
const lsF = o.ls && o.ls.ok ? o.ls : null;
|
||||
const goalTarget = Math.max(0, Math.round(n0(o.goal))) || null;
|
||||
const goals = { month: lsF ? n0(lsF.goalsMonth) : null, target: goalTarget, pct: goalTarget && lsF ? Math.min(100, Math.round(n0(lsF.goalsMonth) / goalTarget * 100)) : null, tracking: lsF ? n0(lsF.goalsCount) > 0 : null, label: 'Goals this month' };
|
||||
// ---- warning lights ----
|
||||
const low = camps.filter(c => c.status === 'active' && n0(c.budget) > 0 && n0(c.delivered) >= n0(c.budget) * 0.8);
|
||||
const out = camps.filter(c => c.status === 'out' && now - n0(c.created) <= 60 * DAY);
|
||||
const running = camps.filter(c => c.status === 'active');
|
||||
const refuelSoon = rf.active && rf.daysToRefuel != null && rf.daysToRefuel <= 5;
|
||||
const loginFree = sites.filter(f => n0(f.loginFree) > 0).map(f => f.site);
|
||||
const warnings = [
|
||||
{ key: 'low', on: low.length > 0, label: 'Ads at 80%', note: low.length ? low.length + ' ad' + (low.length === 1 ? ' is' : 's are') + ' past 80% of budget' : 'none running low' },
|
||||
{ key: 'out', on: out.length > 0, label: 'Ads out', note: out.length ? out.length + ' ad' + (out.length === 1 ? '' : 's') + ' finished delivering' + (running.length ? '' : ', nothing running now') : 'none out' },
|
||||
{ key: 'refuel', on: !!refuelSoon, label: 'Refuel day coming', note: rf.active ? (rf.windowOpen ? 'window open: refuel day ' + rf.refuelDayLabel : 'refuel day ' + rf.refuelDayLabel) : 'no refuel day yet' },
|
||||
{ key: 'login', on: loginFree.length > 0, label: 'Login slot open', note: loginFree.length ? 'a login-ad slot is free on ' + loginFree.map(s => s === 'iap' ? 'InstantAdPay' : 'LinkSpin').join(' and ') : 'all login slots taken' },
|
||||
];
|
||||
// ---- the six parts ----
|
||||
const P = (lsF && lsF.parts) || {};
|
||||
const pFuel = !camps.length ? part('grey', 'Fuel', 'no ads yet', L.campaigns, 'ads')
|
||||
: out.length && !running.length ? part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads')
|
||||
: low.length || (daysLeft != null && daysLeft < 5) ? part('amber', 'Fuel', daysLeft != null && daysLeft < 5 ? 'about ' + daysLeft + ' days left at your burn' : 'an ad is running low', L.buy, 'refuel')
|
||||
: running.length ? part('green', 'Fuel', running.length + ' ad' + (running.length === 1 ? '' : 's') + ' running', L.campaigns, 'ads') : part('amber', 'Fuel', 'nothing running', L.campaigns, 'ads');
|
||||
const pick = (k, label, link, key) => { const x = P[k]; return x ? part(x.state, label, x.note, link, key) : part('grey', label, lsF ? 'not set up' : 'LinkSpin did not answer', link, key); };
|
||||
const parts = [pFuel, pick('bannerSpin', 'Banner spin', LINKS.lsBanner, 'bannerspin'), pick('spinLink', 'Spin link', LINKS.lsLinks, 'spinlink'), pick('page', 'Page', LINKS.lsPages, 'page'), pick('testing', 'Testing', LINKS.lsLinks, 'testing'),
|
||||
lsF ? (n0(lsF.goalsCount) === 0 ? part('grey', 'Conversion tracking', 'no goal set', L.tracking, 'conversions') : n0(lsF.conv30) === 0 ? part('amber', 'Conversion tracking', 'no conversions tracked yet', L.tracking, 'conversions') : part('green', 'Conversion tracking', n0(lsF.conv30) + ' in 30 days', L.tracking, 'conversions'))
|
||||
: part('grey', 'Conversion tracking', 'LinkSpin did not answer', L.tracking, 'conversions')];
|
||||
// ---- one next move ----
|
||||
const per1000 = c => n0(c.delivered) >= 200 ? n0(c.clicks) / n0(c.delivered) * 1000 : null;
|
||||
const ranked = running.filter(c => per1000(c) != null).sort((a, b) => per1000(b) - per1000(a));
|
||||
const linkFor = c => c.site === 'linkspin' ? LINKS.lsAds : LINKS.iapCampaigns;
|
||||
const availAll = sites.reduce((s, f) => s + n0(f.credits && f.credits.available), 0);
|
||||
let next;
|
||||
const mIap = rf.minUsd ? rf.minUsd.iap : 20, mLs = rf.minUsd ? rf.minUsd.linkspin : 25;
|
||||
const firstWhy = here === 'linkspin' ? 'A package of $' + mLs + ' or more here (or $' + mIap + '+ on InstantAdPay) starts the streak and lights this room.' : 'A package of $' + mIap + ' or more here (or $' + mLs + '+ on LinkSpin) starts the streak and lights this room.';
|
||||
if (locked) next = { key: 'start', label: 'Refuel to start your engine', why: firstWhy, link: L.buy, guide: '/refuel' };
|
||||
else if (rf.windowOpen) next = { key: 'refuel', label: 'Refuel now', why: 'Your refuel window is open: +' + rf.next.single + '% on one site, +' + rf.next.both + '% on each with both. A $' + (here === 'linkspin' ? mLs : mIap) + '+ package here counts.', link: L.buy, guide: '/refuel' };
|
||||
else if (out.length && !running.length && availAll >= 100) next = { key: 'relaunch', label: 'Relaunch an ad', why: 'Nothing is running and you have ' + Math.round(availAll).toLocaleString('en-US') + ' credits free.', link: linkFor(out[0]) };
|
||||
else if (daysLeft != null && daysLeft < 5) next = { key: 'pitstop', label: 'Top up' + (rf.pitStop && (rf.pitStop.iap || rf.pitStop.linkspin) ? ' (Pit Stop +' + rf.pitStop.pct + '%)' : ''), why: 'About ' + daysLeft + ' days of fuel left at your current burn.', link: L.buy };
|
||||
else if (low.length) { const best = low.slice().sort((a, b) => (per1000(b) || 0) - (per1000(a) || 0))[0]; next = { key: 'topup', label: 'Top up the winner', why: '"' + (best.name || 'your ad') + '" is past 80% of its budget.', link: linkFor(best) }; }
|
||||
else if (parts[5].state === 'grey') next = { key: 'tracking', label: 'Set up conversion tracking', why: here === 'linkspin' ? 'Count signups and sales back to the ad that sent them. Step 1: add a goal, then paste its two snippets on your pages.' : 'Count signups and sales back to the ad that sent them. Step 1: add a goal under Campaigns > Conversion tracking, then paste its two snippets on your pages.', link: parts[5].link, guide: '/conversion-tracking' };
|
||||
else if (parts[1].state === 'grey') next = { key: 'bannerspin', label: 'Make a Banner Spin', why: 'Test up to 5 banners in one ad slot and let the winner show.' + (here === 'linkspin' ? '' : ' Banner Spin is a LinkSpin tool: the same email signs you in there.'), link: LINKS.lsBanner };
|
||||
else if (parts[4].state !== 'green') next = { key: 'testing', label: 'Test A against B', why: 'Add a second page to your spin link so the rotation can pick a winner.' + (here === 'linkspin' ? '' : ' Spin links live on LinkSpin: the same email signs you in there.'), link: LINKS.lsLinks };
|
||||
else if (ranked.length >= 2 && per1000(ranked[0]) > per1000(ranked[ranked.length - 1]) * 1.5) { const worst = ranked[ranked.length - 1]; next = { key: 'cut', label: 'Cut the loser', why: '"' + (worst.name || 'an ad') + '" brings the fewest clicks per 1,000 credits. Pause it and move the credits to "' + (ranked[0].name || 'your best ad') + '".', link: linkFor(worst) }; }
|
||||
else next = { key: 'cruise', label: 'Keep it running', why: 'Every part is lit. Check again on your refuel day.', link: L.campaigns };
|
||||
return {
|
||||
on: true, locked, fuel, clicks, goals,
|
||||
streak: { active: !!rf.active, months: rf.streak || 0, best: rf.best || 0, refuelDay: rf.refuelDayLabel || null, graceEnd: rf.graceLabel || null, windowOpen: !!rf.windowOpen, next: rf.next || null, pitStop: rf.pitStop || null, freeMiss: rf.freeMiss || null, both: !!(cy && cy.both), note: streakNote(rf, cy) },
|
||||
warnings, parts, next, site: here, sites: { iap: !!(o.iap && o.iap.ok), linkspin: !!(o.ls && o.ls.ok) }, at: now,
|
||||
};
|
||||
}
|
||||
|
||||
// this site's own facts for one member. d: { site, adminMember, ads, coach, now?, bannerspin?, rotator?, pages?, convtrack? }
|
||||
const monthStartCT = now => { const day = new Date(now).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); const [y, m] = day.split('-').map(Number);
|
||||
for (const off of [5, 6]) { const ts = Date.UTC(y, m - 1, 1, off); const t = new Date(ts); if (t.toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }) === day.slice(0, 8) + '01' && Number(t.toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })) % 24 === 0) return ts; } return Date.UTC(y, m - 1, 1, 6); };
|
||||
async function facts(d, email) {
|
||||
const now = d.now || Date.now(); const e = String(email || '').toLowerCase();
|
||||
const out = { site: d.site, ok: true, credits: { available: 0, inCampaigns: 0 }, campaigns: [], clicksWeek: 0, loginFree: 0 };
|
||||
try { const v = await d.adminMember.view(e); if (v && v.credits) out.credits = { available: n0(v.credits.available), inCampaigns: n0(v.credits.inCampaigns) }; } catch (er) {}
|
||||
let list = []; try { list = (await d.ads.listCampaigns(e)).filter(c => !c.house && c.type !== 'game'); } catch (er) {}
|
||||
out.campaigns = list.map(c => ({ id: c.id, name: c.name || null, type: c.type, status: c.status, budget: n0(c.budget), delivered: n0(c.spent), clicks: n0(c.clicks), created: n0(c.created) }));
|
||||
try { out.clicksWeek = await d.coach.clicksSince(list.map(c => c.id), now - 7 * DAY); out.clicksPrevWeek = Math.max(0, (await d.coach.clicksSince(list.map(c => c.id), now - 14 * DAY)) - out.clicksWeek); } catch (er) {}
|
||||
try { out.loginFree = n0((await d.ads.loginSlots()).free); } catch (er) {}
|
||||
if (d.site === 'linkspin') {
|
||||
const since30 = now - 30 * DAY;
|
||||
try { out.goalsCount = d.convtrack.goalsOf(e).length; out.goalsMonth = d.convtrack.countSince(e, monthStartCT(now)); out.conv30 = d.convtrack.countSince(e, since30); } catch (er) { out.goalsCount = 0; out.goalsMonth = 0; out.conv30 = 0; }
|
||||
const parts = {};
|
||||
let spins = [], rots = [], pgs = [];
|
||||
try { spins = await d.bannerspin.list(e); } catch (er) {}
|
||||
try { rots = await d.rotator.list(e); } catch (er) {}
|
||||
try { pgs = await d.pages.list(e); } catch (er) {}
|
||||
const liveB = s => s.banners.filter(b => b.active && !b.adminOff);
|
||||
if (!spins.length) parts.bannerSpin = { state: 'grey', note: 'not set up' };
|
||||
else { const seen = spins.filter(s => !s.paused && s.imps30 > 0); parts.bannerSpin = seen.length ? { state: 'green', note: seen.reduce((n, s) => n + s.imps30, 0).toLocaleString('en-US') + ' views in 30 days' } : { state: 'amber', note: 'no views yet' }; }
|
||||
if (!rots.length) parts.spinLink = { state: 'grey', note: 'not set up' };
|
||||
else { const w = rots.reduce((n, r) => n + n0(r.hits7), 0); parts.spinLink = w > 0 ? { state: 'green', note: w.toLocaleString('en-US') + ' clicks this week' } : { state: 'amber', note: 'no clicks this week' }; }
|
||||
const pub = pgs.filter(p => p.status === 'published');
|
||||
parts.page = !pgs.length ? { state: 'grey', note: 'not set up' } : !pub.length ? { state: 'amber', note: 'draft only, not published' } : pub.some(p => n0(p.views) > 0) ? { state: 'green', note: pub.length + ' published' } : { state: 'amber', note: 'published, no views yet' };
|
||||
const rotTest = rots.some(r => !r.paused && r.destinations.filter(x => x.active).length >= 2);
|
||||
const rotTraffic = rots.some(r => !r.paused && r.destinations.filter(x => x.active && x.hits7 > 0).length >= 2);
|
||||
const bsTest = spins.some(s => !s.paused && liveB(s).length >= 2);
|
||||
const bsTraffic = spins.some(s => !s.paused && liveB(s).filter(b => b.imps30 > 0).length >= 2);
|
||||
parts.testing = rotTraffic || bsTraffic ? { state: 'green', note: 'two or more versions getting traffic' } : rotTest || bsTest ? { state: 'amber', note: 'two versions set up, waiting for traffic' } : (rots.length || spins.length) ? { state: 'amber', note: 'only one version: add a second to test' } : { state: 'grey', note: 'not set up' };
|
||||
out.parts = parts;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// the streak panel's one line about the next refuel (2026-10-24): once BOTH sites are refueled this cycle it says so,
|
||||
// and only a cycle with one site done asks for the other one, by name
|
||||
function streakNote(rf, cy) {
|
||||
const nx = rf && rf.next; if (!rf || !rf.active || !nx) return '';
|
||||
if (rf.windowOpen) return 'Window open: next refuel +' + nx.single + '% (+' + nx.both + '% on each with both).';
|
||||
const iapDone = !!(cy && cy.iap && cy.iap.refueled), lsDone = !!(cy && cy.linkspin && cy.linkspin.refueled);
|
||||
if ((cy && cy.both) || (iapDone && lsDone)) return 'Both engines fueled this cycle: +' + (nx.secondEngine || (cy.iap && cy.iap.pct) || 0) + '% on each.';
|
||||
if (nx.secondEngine) return 'Refuel ' + (iapDone ? 'LinkSpin' : 'InstantAdPay') + ' this cycle for +' + nx.secondEngine + '% on both.';
|
||||
return '';
|
||||
}
|
||||
|
||||
module.exports = { streakNote, build, facts, burnPerDay, monthStartCT, LINKS };
|
||||
@@ -0,0 +1,55 @@
|
||||
// Earners Corner forum sign-in (Marty 2026-11-10): earnerscorner.com runs Discourse with DiscourseConnect, and InstantAdPay is the
|
||||
// identity provider, so every forum name is a real InstantAdPay account (no separate forum sign-ups to farm). Discourse sends
|
||||
// /forum/sso?sso=<base64 payload>&sig=<hex HMAC-SHA256>; we check the signature, make sure the visitor is signed in here, and send
|
||||
// back a signed payload with the member's email, username and groups. Secret: env FORUM_SSO_SECRET (the same value is set in
|
||||
// Discourse as discourse_connect_secret). Groups: network_members (paying member: an on-chain position) and wallet_linked; in
|
||||
// Discourse those groups grant the trust level that may post links, so link spam needs a real member behind it.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
|
||||
const SECRET = () => String(process.env.FORUM_SSO_SECRET || '').trim();
|
||||
const FORUM_URL = () => String(process.env.FORUM_URL || 'https://earnerscorner.com').replace(/\/+$/, '');
|
||||
const sign = s => crypto.createHmac('sha256', SECRET()).update(s).digest('hex');
|
||||
|
||||
// -> { nonce, returnUrl } or { error }
|
||||
function verify(sso, sig) {
|
||||
if (SECRET().length < 32) return { error: 'The forum sign-in is not connected yet.' };
|
||||
sso = String(sso || ''); sig = String(sig || '').toLowerCase();
|
||||
if (!sso || !/^[0-9a-f]{64}$/.test(sig)) return { error: 'That forum sign-in link is incomplete.' };
|
||||
const want = Buffer.from(sign(sso), 'hex'), got = Buffer.from(sig, 'hex');
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'That forum sign-in link is not valid.' };
|
||||
const q = new URLSearchParams(Buffer.from(sso, 'base64').toString('utf8'));
|
||||
const nonce = q.get('nonce'), returnUrl = q.get('return_sso_url') || '';
|
||||
if (!nonce) return { error: 'That forum sign-in link is incomplete.' };
|
||||
if (!returnUrl.startsWith(FORUM_URL() + '/')) return { error: 'That forum sign-in link points somewhere else.' };
|
||||
return { nonce, returnUrl };
|
||||
}
|
||||
|
||||
// the signed redirect back to the forum for this account
|
||||
function redirectFor(v, acct, site) {
|
||||
const email = String(acct.email || '').toLowerCase();
|
||||
const groups = [];
|
||||
if (Number(acct.memberId) > 0) groups.push('network_members');
|
||||
if (acct.address) groups.push('wallet_linked');
|
||||
const p = new URLSearchParams({ nonce: v.nonce, email, external_id: email, require_activation: 'false', suppress_welcome_message: 'false' });
|
||||
if (acct.username) { p.set('username', acct.username); p.set('name', acct.username); }
|
||||
if (acct.avatarUrl) p.set('avatar_url', /^https?:/.test(acct.avatarUrl) ? acct.avatarUrl : site + acct.avatarUrl);
|
||||
// no website on sign-in (Marty 2026-11-14): Discourse holds a new user who "entered profile information without reading" for
|
||||
// approval, and the stackpol.com link we filled in put every new member in the review queue. Members add their own.
|
||||
if (groups.length) p.set('add_groups', groups.join(','));
|
||||
const remove = ['network_members', 'wallet_linked'].filter(g => !groups.includes(g)); if (remove.length) p.set('remove_groups', remove.join(','));
|
||||
const out = Buffer.from(p.toString()).toString('base64');
|
||||
return v.returnUrl + (v.returnUrl.includes('?') ? '&' : '?') + 'sso=' + encodeURIComponent(out) + '&sig=' + sign(out);
|
||||
}
|
||||
|
||||
// server-to-server: the forum's reward service asks "is this email an activated member, and where are payouts sent?" The request is
|
||||
// signed with the same shared secret: header x-forum-sig = hex HMAC-SHA256 of "<email>.<unix seconds>", x-forum-ts = those seconds,
|
||||
// valid for 5 minutes.
|
||||
function verifyServer(email, ts, sig) {
|
||||
if (SECRET().length < 32) return false;
|
||||
const t = Number(ts); if (!(t > 0) || Math.abs(Date.now() / 1000 - t) > 300) return false;
|
||||
const want = Buffer.from(sign(String(email || '').toLowerCase() + '.' + t), 'hex'), got = Buffer.from(String(sig || ''), 'hex');
|
||||
return want.length === got.length && crypto.timingSafeEqual(want, got);
|
||||
}
|
||||
|
||||
module.exports = { verify, verifyServer, redirectFor, sign, SECRET, FORUM_URL };
|
||||
@@ -30,7 +30,8 @@ function norm(e) { return String(e || '').trim().toLowerCase(); }
|
||||
function ipOf(req) { return String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim().replace(/^::ffff:/, '').slice(0, 45); }
|
||||
function uaOf(req) { return String(req.headers['user-agent'] || '').slice(0, 200); }
|
||||
function cookies(req) { const out = {}; String(req.headers.cookie || '').split(';').forEach(p => { const i = p.indexOf('='); if (i > 0) out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); }); return out; }
|
||||
function deviceOf(req) { const d = cookies(req)['iap.dev'] || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }
|
||||
// in-game sign-in (2026-10-03): a cross-site request carries no iap.dev cookie, so the game sends its own browser id
|
||||
function deviceOf(req) { const d = cookies(req)['iap.dev'] || (req && req.gameDev) || ''; return /^[a-f0-9]{32}$/.test(d) ? d : ''; }
|
||||
function newDeviceId() { return crypto.randomBytes(16).toString('hex'); }
|
||||
function deviceCookie(id, isProd) { return 'iap.dev=' + id + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + (400 * 86400) + (isProd ? '; Secure' : ''); }
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
// purchase indexes and labelled in the credit log. The day's wave is shown live (landing strip,
|
||||
// Overview card, /api/friday), posted to Telegram at every ten packs and wrapped up at midnight,
|
||||
// and five Fridays in a row earn the Five Fridays badge. Thursday 6 PM CT: an on-site notice and
|
||||
// an email to active members (drip unsubscribes honoured). Friday 9 AM CT: the Telegram kickoff.
|
||||
// an email to active members (drip unsubscribes honoured). Friday 5 AM CT: the Telegram kickoff.
|
||||
//
|
||||
// Settings (siteConfig): fridayPromo '1'|'0', fridayBonusPct (20), fridayStart 'YYYY-MM-DD' (first
|
||||
// Friday, 2026-09-25). Everything reads the chain index, never a marketing counter.
|
||||
@@ -29,6 +29,7 @@ function cfg() {
|
||||
return {
|
||||
on: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
||||
pct: Math.max(0, Number(c.fridayBonusPct) || 20),
|
||||
kickHour: Math.min(23, Math.max(0, Number(c.fridayKickHour == null ? 5 : c.fridayKickHour) || 0)), // Central hour of the Telegram kickoff (Marty 2026-10-07: 5 AM, was 9)
|
||||
start: String(c.fridayStart || '2026-09-25'),
|
||||
};
|
||||
}
|
||||
@@ -102,7 +103,7 @@ function earnedBadge(memberId) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// scheduled moments, checked every few minutes: Thursday 18:00 CT notice + email, Friday 09:00 CT kickoff,
|
||||
// scheduled moments, checked every few minutes: Thursday 18:00 CT notice + email, Friday kickoff at kickHour (5 AM CT),
|
||||
// Saturday 00:xx CT wrap-up of the Friday that just ended
|
||||
async function tick() {
|
||||
const c = cfg(); if (!c.on) return;
|
||||
@@ -111,12 +112,12 @@ async function tick() {
|
||||
if (wd === 'Thu' && h >= 18 && next && !S.sent['thu:' + next] && await claimOnce('fri:thu:' + next)) {
|
||||
S.sent['thu:' + next] = now; save();
|
||||
const subject = 'Tomorrow is Five Dollar Friday';
|
||||
const text = 'Tomorrow is Five Dollar Friday on InstantAdPay.\n\nAny ad package of $5 or more bought on Friday (Central time) earns +' + c.pct + '% bonus credits, added the moment the purchase settles. Your $5 pays your sponsor line the second it clears, and your line’s $5s pay you. Friday is when we all push at once.\n\nLine up your pack: https://instantadpay.com/my#buy\nWatch the wave on the live ledger: https://instantadpay.com/ledger';
|
||||
const text = 'Tomorrow is Five Dollar Friday on InstantAdPay.\n\nAny ad package of $5 or more bought on Friday (Central time) earns +' + c.pct + '% bonus credits, added the moment the purchase settles. Your $5 pays your sponsor line the second it clears, and your line’s $5s pay you. Friday is when we all push at once.\n\nGame Pass too: the same Friday purchase gives you a free 7-day Game Pass for every game in the network (once per Friday, added automatically), and the $5 pack lands as 600 credits that you keep for your ads.\n\nLine up your pack: https://instantadpay.com/my#buy\nWatch the wave on the live ledger: https://instantadpay.com/ledger';
|
||||
await broadcast(subject, text);
|
||||
}
|
||||
if (wd === 'Fri' && h >= 9 && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
|
||||
if (wd === 'Fri' && h >= c.kickHour && day >= c.start && !S.sent['kick:' + day] && await claimOnce('fri:kick:' + day)) {
|
||||
S.sent['kick:' + day] = now; save();
|
||||
X.telegram('\u{1F4B5} <b>It’s Five Dollar Friday.</b> Any ad package from $5 up earns <b>+' + c.pct + '% credits</b> today, and every pack pays its sponsor line in the same transaction. Buy yours, then watch the ledger fill up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
X.telegram('\u{1F4B5} <b>It’s Five Dollar Friday.</b> Any ad package from $5 up earns <b>+' + c.pct + '% credits</b> today, and every pack pays its sponsor line in the same transaction. Game Pass day too: the same purchase gives you a free 7-day Game Pass for every game (once per Friday, automatic), and the $5 pack lands as 600 credits you keep for ads. Buy yours, then watch the ledger fill up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
if (wd === 'Sat' && h < 3) {
|
||||
const fri = dayOf(now - 86400000);
|
||||
|
||||
@@ -0,0 +1,712 @@
|
||||
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (POL Miner 2026-10-28, Turkey Drop for its Nov season), and the account-wide POL cap service the games call
|
||||
// before every POL grant. IAP is the single source of truth for both; the games keep their own caps only as a backstop.
|
||||
// Spec: docs/GAME-PASS.md (section 3a is the contract the games build against).
|
||||
//
|
||||
// What lives here:
|
||||
// - the pass store email -> { until, bought: [{ ts, via, tx | credits, usd }], lastCapHit } (durable persisted map 'gamepass')
|
||||
// - pass orders order -> { status, email, ts, tx } (every pass is paid by a FRESH package purchase: see buy() / onEvent())
|
||||
// - the cap ledger per member per Central day: used daily/total, deferred queue per game, every answered (game, ref) kept 90 days
|
||||
// - the weekly Pass Tournament: ranks pass holders by grants reported through polgrant, records POL prizes for the games to pay
|
||||
// - admin stats
|
||||
//
|
||||
// Not to be confused with the in-game SIGN-IN pass (server.js gamePassMint/gamePassOpen): that is a session token the games keep
|
||||
// in localStorage. This module is the paid Game Pass product. Fields on the wire are `pass: { active, until }` (3a).
|
||||
//
|
||||
// Pass tiers (2026-10-18, ultima-rpg docs/IAP-PASSES-SPEC.md; Marty approved the "safe" form): beside the $5 weekly pass, the
|
||||
// monthly Explorer ($20) and Champion ($40) passes. They sell islands and looks in Shards of Valor, NEVER power and NEVER more
|
||||
// POL: every tier gets exactly the weekly pass caps (flag().active is true for any tier, so polgrant answers pass: true and
|
||||
// nothing else changes). Tiers run side by side, each with its own expiry: record.tiers = { weekly: { until }, explorer: { until },
|
||||
// champion: { until } }; the legacy `until` keeps mirroring the weekly tier (lazy migration: a record with no `tiers` reads its
|
||||
// `until` as the weekly tier). flag().tier = the highest active tier. Explorer/Champion sales sit behind the site switch
|
||||
// `sovTiers` (default off; while it is off the admin tests them from Admin > Game Pass, never on the member card). No proration, no auto-renew: buying again
|
||||
// extends that tier from max(now, until).
|
||||
// 2026-10-22 (Marty): every pass rides the package rail so sponsors get paid. Buying a pass never spends a credit balance any more
|
||||
// (today's buyer paid from an old balance, so no new money came in and nobody upline was paid). A pass click opens an order; the
|
||||
// order is fulfilled ONLY by an on-chain package Purchase of at least the tier price, mined after the order was opened, bought by
|
||||
// one of that member's own positions (main or linked), each purchase tx used once. The member keeps that package's credits for ads.
|
||||
// Bought rows: via 'package' (with tx and cents). The two rows from before this change are via 'credits' and 'package' and stay.
|
||||
// 2026-10-22 (Dallas's structure, Marty approved): Explorer $19.99 and Champion $39.99 (30 days), plus Sovereign $99.99 (30 days)
|
||||
// and Legend $249.99 (365 days, the yearly pass), all in TIER_DEFS below and all behind the same sovTiers switch. The weekly
|
||||
// pass is unchanged ($5 / 7 days / the same caps). Rank weekly < explorer < champion < sovereign < legend.
|
||||
// 2026-10-25 (Marty): every tier price equals an InstantAdPay one-click package, so the cheapest qualifying package is exactly
|
||||
// the pass price (no silent overpay): Explorer $20 (was 19.99), Champion $50 (was 39.99), Sovereign $100 (was 99.99), Legend
|
||||
// $250 (was 249.99); weekly $5 unchanged. The pass comes with that package's ad credits.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const TZ = 'America/Chicago';
|
||||
const GAMES = ['polhunter', 'gemkingdom', 'spellwheel', 'spookydoors', 'polywarriors', 'clutterhunt', 'polybreak', 'driprunner', 'roadagent', 'shardsofvalor', 'polminer', 'warpwares', 'turkeydrop'];
|
||||
const NAMES = { polhunter: 'PolHunter', gemkingdom: 'Gem Kingdom', spellwheel: 'SpellWheel', spookydoors: 'Spooky Doors', polywarriors: 'PolyWarriors', clutterhunt: 'ClutterHunt', polybreak: 'PolyBreak', driprunner: 'Drip Runner', roadagent: 'Road Agent', shardsofvalor: 'Shards of Valor', polminer: 'POL Miner', warpwares: 'Warp & Wares', turkeydrop: 'Turkey Drop' };
|
||||
const SHARES = [0.5, 0.3, 0.2]; // tournament prize split, places 1-3
|
||||
const KEEP_DAYS = 90; // answered refs and day rows are kept this long (idempotency window)
|
||||
// THE pass table (2026-10-22, Dallas's structure, Marty approved): lowest to highest, a higher tier includes everything below.
|
||||
// Rename a tier here (name) and nowhere else: the member card, the admin pane, the charge label and the chatbot read it from here.
|
||||
// key = the wire value the games read (flag().tier / tiers); set = the Admin > Settings stem (gamePass<set>Enabled /
|
||||
// PriceCredits / Days; weekly keeps its original gamePassPriceCredits / gamePassDays); price = the pass price in cents (100 = $1;
|
||||
// the setting keeps its old 'PriceCredits' name): the package that pays for a pass must cost at least this much;
|
||||
// perks = what the member card lists. Every tier is a Game Pass holder everywhere with the SAME caps (no extra POL).
|
||||
const TIER_DEFS = [
|
||||
{ key: 'weekly', name: 'Game Pass', set: '', price: 500, days: 7,
|
||||
perks: ['Higher daily POL caps in every game', 'A seat in the weekly Pass Tournament', 'Extra plays and a perk in each game', 'Shards of Valor: the Sunless Vault and weapons unlocked'] },
|
||||
{ key: 'explorer', name: 'Explorer', set: 'Explorer', price: 2000, days: 30,
|
||||
perks: ['Everything in the Game Pass, in every game', 'Shards of Valor: weapons and gear unlocked', 'Shards of Valor: 2 bonus islands'] },
|
||||
{ key: 'champion', name: 'Champion', set: 'Champion', price: 5000, days: 30,
|
||||
perks: ['Everything in Explorer', 'Shards of Valor: 4 bonus islands of your choice', 'Shards of Valor: level cap 30'] }, // 2026-11-05: the Druid moved to the one-time bonus heroes
|
||||
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
|
||||
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: level cap 40'] }, // 2026-11-05: the Necromancer was dropped
|
||||
{ key: 'legend', name: 'Legend', set: 'Legend', price: 25000, days: 365,
|
||||
perks: ['Everything in Sovereign, for a full year', 'Shards of Valor: every bonus island', 'Shards of Valor: every bonus hero while Legend is active (Kestrel, Valda, Morag, Roland), and every new hero as it ships', 'Shards of Valor: level cap 40'] }, // new heroes as a Legend perk: Marty 2026-10-30 (Dallas's $100/year idea folded in here)
|
||||
];
|
||||
const TIERS = TIER_DEFS.map(d => d.key); // lowest to highest
|
||||
const TIER_NAMES = Object.fromEntries(TIER_DEFS.map(d => [d.key, d.name]));
|
||||
const TIER_DEF = Object.fromEntries(TIER_DEFS.map(d => [d.key, d]));
|
||||
const tierOk = t => TIERS.includes(t);
|
||||
const rowTier = b => (b && tierOk(b.tier)) ? b.tier : 'weekly'; // bought rows before 2026-10-18 have no tier: weekly
|
||||
const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
||||
// Bonus heroes for Shards of Valor (Marty approved 2026-11-05, Dallas's request): SOLD ONE TIME, no subscription, owned for good. Paid
|
||||
// exactly like a pass: no credits, no direct POL; buying opens a waiting order, fulfilled by a FRESH package of at least the price
|
||||
// bought by one of the member's own positions, so the sponsor line is paid as usual (onEvent). $20 each = the Activation package; the
|
||||
// $50 bundle (the Builder package) is a settings list, default Valda + Morag + Roland (Dallas 13:26; Marty approved a $50 bundle of
|
||||
// three). Settings (Admin > Settings, no deploy): heroSales (sale switch, default OFF), heroPrice<Set>Cents per hero (0 = free for
|
||||
// every account, granted like a base hero), heroBundlePriceCents, heroBundleHeroes, heroBundleCap (a level the bundle would raise the
|
||||
// cap to; UNSET = no cap change, Marty has not approved one). key = the wire value Shards of Valor reads (classes.json paid buy).
|
||||
// 2026-11-14 (Marty approved, "Yes make it free"; Dallas: "The Archer should be free to everyone at level 20"): Kestrel is FREE for every
|
||||
// player once a hero in their party reaches level 20 (the game decides, Shards of Valor classes.json freeAt) and is NOT SOLD here any more
|
||||
// (freeAt): no buy, not in any bundle, waiting Kestrel orders are cancelled unpaid. A member who bought her keeps her (record.heroes.kestrel);
|
||||
// nothing refunded. Valda, Morag and Roland, the $50 bundle and every price are unchanged.
|
||||
const HERO_DEFS = [
|
||||
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, freeAt: 20, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
|
||||
{ key: 'valda', set: 'Valda', name: 'Valda the Barbarian', price: 2000, blurb: 'A berserker: hits harder the more she is hurt, light on armour.' },
|
||||
{ key: 'morag', set: 'Morag', name: 'Morag the Druid', price: 2000, blurb: 'A healer of the wild: heals the whole party.' },
|
||||
{ key: 'roland', set: 'Roland', name: 'Roland the Paladin', price: 2000, blurb: 'A holy knight: sword and shield, heals one hero at a time.' },
|
||||
];
|
||||
const HERO_KEYS = HERO_DEFS.map(d => d.key);
|
||||
const HERO_DEF = Object.fromEntries(HERO_DEFS.map(d => [d.key, d]));
|
||||
const HERO_SOLD = HERO_DEFS.filter(d => !d.freeAt).map(d => d.key); // free at a level in the game (Kestrel at 20): never sold, never in a bundle
|
||||
const HERO_BUNDLE_DEFAULT = 'valda,morag,roland';
|
||||
|
||||
let R = null; // deps from server.js
|
||||
let passes, orders, prizes, stackpro; // stackpro: Stack POL Pro owners, email -> { ts, tx, cents, order } (2026-11-09). durable persisted maps (server.js open-tokens store, DURABLE set)
|
||||
let L = null; // the cap ledger: { members: { email: { days: {}, deferred: {}, weeks: {} } }, refs: { 'game:ref': {...} } }
|
||||
let saveTimer = null;
|
||||
|
||||
// ---- Central time (no tz lib; same arithmetic as leaderboard.js) ----
|
||||
function ctParts(ts) {
|
||||
const s = new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour12: false, year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', weekday: 'short' });
|
||||
const m = /(\w{3}), (\d{2})\/(\d{2})\/(\d{4}), (\d{2}):(\d{2})/.exec(s);
|
||||
return { wd: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].indexOf(m[1]), y: +m[4], mo: +m[2], d: +m[3], h: +m[5] % 24, mi: +m[6] };
|
||||
}
|
||||
function ctMidnight(ts) { const p = ctParts(ts); const guess = Date.UTC(p.y, p.mo - 1, p.d, 5, 0, 0); const q = ctParts(guess); return (q.h === 0 && q.d === p.d) ? guess : guess + 3600000; }
|
||||
function weekStart(ts) { const p = ctParts(ts); const mid = ctMidnight(ts); return mid - ((p.wd + 6) % 7) * 86400000; }
|
||||
const dayKey = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekKey = ts => dayKey(weekStart(ts));
|
||||
const dayLabel = key => new Date(key + 'T12:00:00Z').toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' });
|
||||
|
||||
// ---- settings (Admin > Settings, no deploy) ----
|
||||
function cfg() {
|
||||
const sc = R.siteConfig();
|
||||
const n = (k, d) => { const raw = sc[k]; if (raw === undefined || raw === null || String(raw).trim() === '') return d; const v = Number(raw); return Number.isFinite(v) ? v : d; };
|
||||
const start = String(sc.capsStartDate || '').trim();
|
||||
const on = k => ['1', 'true', 'on', 'yes'].includes(String(sc[k]).trim().toLowerCase());
|
||||
const offExplicit = k => ['0', 'false', 'off', 'no'].includes(String(sc[k]).trim().toLowerCase());
|
||||
const price = Math.max(1, Math.round(n('gamePassPriceCredits', 500))), days = Math.max(1, Math.round(n('gamePassDays', 7)));
|
||||
return {
|
||||
enabled: on('gamePassEnabled'),
|
||||
price, days,
|
||||
// per tier: price in purchased-grade credits (100 = $1), length, and whether it is on sale. Every tier above weekly needs the
|
||||
// master switch sovTiers AND the weekly pass switched on; its own gamePass<Set>Enabled is a kill switch (missing = on).
|
||||
tierSales: on('sovTiers'),
|
||||
tiers: Object.fromEntries(TIER_DEFS.map(d => [d.key, d.key === 'weekly' ? { price, days, sale: on('gamePassEnabled') }
|
||||
: { price: Math.max(1, Math.round(n('gamePass' + d.set + 'PriceCredits', d.price))), days: Math.max(1, Math.round(n('gamePass' + d.set + 'Days', d.days))),
|
||||
sale: on('gamePassEnabled') && on('sovTiers') && !offExplicit('gamePass' + d.set + 'Enabled') }])),
|
||||
tournamentTierSales: on('passTournamentTierSales'), // off: only weekly pass sales feed the Pass Tournament pool (exactly as before tiers)
|
||||
free: { daily: Math.max(0, n('capFreeDaily', 0.30)), total: Math.max(0, n('capFreeTotal', 2.0)) },
|
||||
// the free allowance (Marty 2026-11-02, "cap these so that if the user wants to keep playing they spend a tiny amount"):
|
||||
// the most game POL an account EVER receives while it holds no pass, across every game. After that, progress rewards
|
||||
// wait as deferred until a pass is active and repeatable rewards are dropped. 2 POL default; admin key capFreeLifetime.
|
||||
freeLifetime: Math.max(0, n('capFreeLifetime', 2.0)),
|
||||
pass: { daily: Math.max(0, n('capPassDaily', 1.50)), total: Math.max(0, n('capPassTotal', 5.0)) },
|
||||
start: /^\d{4}-\d{2}-\d{2}$/.test(start) ? start : '',
|
||||
pct: Math.max(0, n('passTournamentPct', 5)),
|
||||
gamesChat: String(sc.telegramGamesChatId || sc.telegramEchoChatId || '').trim(),
|
||||
gamesTopic: String(sc.telegramGamesTopicId || '').trim(),
|
||||
heroes: (() => {
|
||||
const price = Object.fromEntries(HERO_DEFS.map(d => [d.key, Math.max(0, Math.round(n('heroPrice' + d.set + 'Cents', d.price)))]));
|
||||
const raw = sc.heroBundleHeroes == null || String(sc.heroBundleHeroes).trim() === '' ? HERO_BUNDLE_DEFAULT : String(sc.heroBundleHeroes);
|
||||
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_SOLD.includes(k) && price[k] > 0))];
|
||||
const capRaw = String(sc.heroBundleCap == null ? '' : sc.heroBundleCap).trim(), cap = capRaw === '' ? NaN : Number(capRaw);
|
||||
return { sale: on('heroSales'), price, free: HERO_KEYS.filter(k => price[k] === 0), bundle: { heroes: list.length >= 2 ? list : [], price: Math.max(1, Math.round(n('heroBundlePriceCents', 5000))) },
|
||||
cap: Number.isInteger(cap) && cap > 0 ? cap : null };
|
||||
})(),
|
||||
};
|
||||
}
|
||||
const enforcedOn = (c, day) => !!(c.start && day >= c.start);
|
||||
|
||||
// ---- ledger file ----
|
||||
const FILE = () => path.join(R.dataDir, 'gamepass-ledger.json');
|
||||
function load() { try { L = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { L = null; } if (!L || typeof L !== 'object') L = { members: {}, refs: {} }; L.members = L.members || {}; L.refs = L.refs || {}; }
|
||||
function save() { saveTimer = null; try { fs.writeFileSync(FILE(), JSON.stringify(L)); } catch (e) { console.error('gamepass ledger save', e.message); } }
|
||||
function touch() { if (!saveTimer) saveTimer = setTimeout(save, 500); }
|
||||
function member(e) { return (L.members[e] = L.members[e] || { days: {}, deferred: {}, weeks: {} }); }
|
||||
function dayRow(M, day) {
|
||||
return (M.days[day] = M.days[day] || { daily: 0, total: 0, carried: 0, dropped: 0, deferredOut: 0, grants: 0, hits: { daily: 0, total: 0 },
|
||||
tier: { free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 } },
|
||||
would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 } }); // would = what the caps would have done before capsStartDate
|
||||
}
|
||||
|
||||
function init(deps) {
|
||||
R = deps;
|
||||
passes = R.persistedMap('gamepass');
|
||||
orders = R.persistedMap('gporders');
|
||||
prizes = R.persistedMap('gpprizes');
|
||||
stackpro = R.persistedMap('stackpro');
|
||||
load();
|
||||
}
|
||||
|
||||
// ---- the pass ----
|
||||
function rec(e) { return passes.get(e) || null; }
|
||||
// per-tier expiry (ms, 0 = never held). A record from before tiers has no `tiers`: its legacy `until` is the weekly tier
|
||||
// (lazy migration, idempotent: every write stores `tiers` and mirrors tiers.weekly into `until`).
|
||||
function tiersOf(p) {
|
||||
const out = {}; const T = (p && p.tiers) || {};
|
||||
for (const k of TIERS) out[k] = Number(T[k] && T[k].until) || 0;
|
||||
if (p && !p.tiers) out.weekly = Number(p.until) || 0;
|
||||
return out;
|
||||
}
|
||||
function topTier(T, t) { for (let i = TIERS.length - 1; i >= 0; i--) if (T[TIERS[i]] > t) return TIERS[i]; return null; }
|
||||
// { active, until, tier, tiers }: active = any tier on (every tier is a Game Pass holder everywhere, same caps); tier = the
|
||||
// highest active tier; until = that tier's end. With nothing active, until is the last end the account ever had (as before
|
||||
// tiers) or null. tiers = each tier's end while it is active, else null.
|
||||
function flag(email, now) {
|
||||
const p = rec(String(email || '').toLowerCase()); const t = now || Date.now(); const T = tiersOf(p); const tier = topTier(T, t);
|
||||
const tiers = {}; for (const k of TIERS) tiers[k] = T[k] > t ? T[k] : null;
|
||||
const last = Math.max(...TIERS.map(k => T[k]));
|
||||
return { active: !!tier, until: tier ? T[tier] : (last || null), tier, tiers };
|
||||
}
|
||||
function writeTiers(cur, T, extra) {
|
||||
const tiers = {}; for (const k of TIERS) if (T[k]) tiers[k] = { until: T[k] };
|
||||
return Object.assign({}, cur, { until: T.weekly || 0, tiers }, extra || {});
|
||||
}
|
||||
function extend(e, via, extra, now, tier) {
|
||||
tier = tierOk(tier) ? tier : 'weekly';
|
||||
const c = cfg(); const tc = c.tiers[tier]; const t = now || Date.now(); const cur = passes.get(e) || { until: 0, bought: [] };
|
||||
const T = tiersOf(cur);
|
||||
const until = Math.max(t, T[tier]) + tc.days * 86400000; T[tier] = until; // renewing early loses nothing: from max(now, until)
|
||||
const bought = [Object.assign({ ts: t, via, tier, usd: tc.price / 100, days: tc.days }, extra || {})].concat(cur.bought || []).slice(0, 200);
|
||||
passes.set(e, writeTiers(cur, T, { bought, ts: t }));
|
||||
return { until, days: tc.days, tier };
|
||||
}
|
||||
function waitingOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind !== 'hero' && o.kind !== 'stackpro') out.push(Object.assign({ order: k }, o, { tier: tierOk(o.tier) ? o.tier : 'weekly' })); return out; }
|
||||
function waitingOrder(e, tier) { return waitingOrders(e).find(o => o.tier === (tier || 'weekly')) || null; }
|
||||
// the admin's tier test: drop a waiting order that was opened for testing, so a later real package never fulfils it by surprise
|
||||
function cancelOrder(email, tier) {
|
||||
const e = String(email || '').toLowerCase(); const w = waitingOrder(e, tier || 'weekly'); if (!w) return { ok: true, none: true };
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, tier: w.tier };
|
||||
}
|
||||
function comp(email, why, tier, now) { // support comp: counts as no sale
|
||||
const e = String(email || '').toLowerCase(); const x = extend(e, 'admin', { note: why || 'support', usd: 0 }, now, tier);
|
||||
return { active: true, until: x.until, days: x.days, tier: x.tier };
|
||||
}
|
||||
// support refund (never automatic): that tier ends now; the record keeps what it was
|
||||
function revoke(email, tier, why, now) {
|
||||
const e = String(email || '').toLowerCase(); if (!tierOk(tier)) return { error: 'unknown tier' };
|
||||
const t = now || Date.now(); const p = passes.get(e); const T = tiersOf(p);
|
||||
if (!p || !(T[tier] > t)) return { error: 'No active ' + TIER_NAMES[tier] + ' pass on this account.' };
|
||||
const was = T[tier]; T[tier] = t;
|
||||
passes.set(e, writeTiers(p, T, { revokes: [{ ts: t, tier, why: String(why || 'support').slice(0, 80), was }].concat(p.revokes || []).slice(0, 50) }));
|
||||
return { ok: true, tier, was, until: t };
|
||||
}
|
||||
// on sale for this viewer: the tier's own switch, or the admin portal's tier test (Admin > Game Pass) while sovTiers is off
|
||||
const tierOpen = (c, tier, preview) => !!(c.tiers[tier].sale || (preview && tier !== 'weekly'));
|
||||
const PACKAGE_USD = [5, 10, 20, 50, 100, 250, 500]; // copy only: the package that covers a price
|
||||
const packageFor = usd => PACKAGE_USD.find(x => x >= usd) || usd;
|
||||
|
||||
// GET /api/my/gamepass: exactly what a member sees, for EVERY account, the admin's included (2026-10-25, Marty: no admin-only
|
||||
// tier UI on the member card). opts.preview = the admin portal's tier test (GET /api/admin/gamepass/preview): every tier, each
|
||||
// one open to the admin's own account while sovTiers is off.
|
||||
function view(email, now, opts) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const f = flag(e, t); const p = rec(e); const w = waitingOrder(e, 'weekly');
|
||||
const admin = !!(opts && opts.preview); const T = tiersOf(p);
|
||||
const caps = capsFor(e, t);
|
||||
// the tier rows this member sees: weekly always; a higher tier while on sale, in the admin preview, or to a current holder (holders
|
||||
// keep their pass when a sale is switched off, they just cannot buy more)
|
||||
const passRows = TIERS.filter(k => k === 'weekly' || c.tiers[k].sale || admin || T[k] > t).map(k => {
|
||||
const tc = c.tiers[k]; return { tier: k, name: TIER_NAMES[k], perks: TIER_DEF[k].perks, price: tc.price, usd: tc.price / 100, days: tc.days, package: packageFor(tc.price / 100),
|
||||
active: T[k] > t, until: T[k] > t ? T[k] : null, waiting: !!waitingOrder(e, k), sale: !!tc.sale, open: k === 'weekly' ? c.enabled : tierOpen(c, k, admin) };
|
||||
});
|
||||
const tiered = passRows.some(r => r.tier !== 'weekly');
|
||||
return { enabled: c.enabled, active: f.active, until: f.until, tier: f.tier, price: c.price, days: c.days, usd: c.price / 100,
|
||||
waiting: !!w, waitingSince: w ? w.ts : null, bought: p ? (p.bought || []).length : 0,
|
||||
caps, capsStart: c.start || null, lastCapHit: p && p.lastCapHit && (t - p.lastCapHit.ts) < 2 * 86400000 ? p.lastCapHit : null,
|
||||
tournament: { pct: c.pct, shares: SHARES, next: nextTournamentAt(t) },
|
||||
show: c.enabled || tiered, passes: passRows, tierPreview: tiered && admin && !c.tierSales,
|
||||
heroes: heroView(e, t, opts) }; // bonus heroes (2026-11-05): sold one time, shown while heroSales is on, to an owner, or in the admin test
|
||||
}
|
||||
|
||||
// POST /api/my/gamepass/buy { tier }. tier missing = weekly (exactly the pass as it was before tiers). opts.preview = the admin
|
||||
// portal's tier test (POST /api/admin/gamepass/test-buy, the admin's own account only): a tier that is not on sale still opens an order.
|
||||
// A pass is ALWAYS paid by a fresh package purchase (2026-10-22, Marty: the pass rides the package rail so sponsors get paid). This never
|
||||
// spends credits: it opens (or reuses) a waiting order for that tier and sends the member to buy a package of at least the tier price.
|
||||
// The order is fulfilled by onEvent() below; the member keeps every credit of that package for ads.
|
||||
function buy(email, now, tier, opts) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now();
|
||||
tier = (tier === undefined || tier === null || tier === '') ? 'weekly' : String(tier).toLowerCase();
|
||||
if (!tierOk(tier)) return { error: 'There is no such pass.' };
|
||||
const tc = c.tiers[tier]; const name = TIER_NAMES[tier];
|
||||
if (tier === 'weekly') { if (!c.enabled) return { error: 'The Game Pass is not open yet.' }; }
|
||||
else if (!tierOpen(c, tier, !!(opts && opts.preview))) return { error: 'The ' + name + ' pass is not open yet.' };
|
||||
let w = waitingOrder(e, tier); const reused = !!w;
|
||||
if (!w) { const k = 'gp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, tier }); w = Object.assign({ order: k }, orders.get(k)); }
|
||||
const pkg = packageFor(tc.price / 100);
|
||||
if (!reused) console.log('gamepass order opened', tier, e, w.order, 'needs a package of', tc.price, 'cents');
|
||||
return { ok: false, needPay: true, tier, payUrl: tier === 'weekly' ? '/my?from=gamepass#buy' : '/my?from=gamepass&tier=' + tier + '#buy', order: w.order, orderTs: w.ts, reused,
|
||||
price: tc.price, usd: tc.price / 100, package: pkg,
|
||||
message: (tier === 'weekly' ? 'Your Game Pass' : 'Your ' + name + ' pass') + ' starts the moment your next package of $' + pkg + ' or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
|
||||
}
|
||||
|
||||
// Stack POL Pro (Marty 2026-11-09): a one-time unlock for the member's stackpol.com page (their LinkSpin Banner Spins and spin links
|
||||
// on the page, the shareable stack card). Like a pass or a hero it is NEW MONEY only: "Get Pro" opens a waiting order, and the next
|
||||
// package purchase of $10 or more by one of the member's own positions fulfils it (onEvent). Never credits, never direct POL; the
|
||||
// member keeps every credit of the package and the sponsor line is paid on chain as usual. Owned for good once paid.
|
||||
const STACK_PRO_CENTS = 1000;
|
||||
function stackOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'stackpro') out.push(Object.assign({ order: k }, o)); return out; }
|
||||
function stackPro(email) { const e = String(email || '').toLowerCase(); return stackpro.get(e) || null; }
|
||||
function stackProView(email) { const e = String(email || '').toLowerCase(); const own = stackpro.get(e) || null; const w = stackOrders(e)[0] || null; return { pro: !!own, since: own ? own.ts : null, waiting: !!w, order: w ? w.order : null, usd: STACK_PRO_CENTS / 100 }; }
|
||||
function buyStackPro(email, now) {
|
||||
const e = String(email || '').toLowerCase(); const t = now || Date.now();
|
||||
if (stackpro.get(e)) return { ok: true, pro: true };
|
||||
let w = stackOrders(e)[0]; const reused = !!w;
|
||||
if (!w) { const k = 'sp-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', email: e, ts: t, kind: 'stackpro' }); w = Object.assign({ order: k }, orders.get(k)); console.log('stack pro order opened', e, k); }
|
||||
return { ok: false, needPay: true, payUrl: '/my?from=stackpro#buy', order: w.order, orderTs: w.ts, reused, usd: STACK_PRO_CENTS / 100, package: packageFor(STACK_PRO_CENTS / 100),
|
||||
message: 'Stack POL Pro switches on the moment your next package of $10 or more settles on chain. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
|
||||
}
|
||||
function cancelStackOrder(email) { const e = String(email || '').toLowerCase(); const w = stackOrders(e)[0]; if (!w) return { ok: true }; orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order }; }
|
||||
function compStackPro(email, on, note) { const e = String(email || '').toLowerCase(); if (on) stackpro.set(e, { ts: Date.now(), via: 'comp', note: String(note || '').slice(0, 120) }); else stackpro.delete(e); return { ok: true, pro: !!on }; }
|
||||
// a package bought WITHOUT a Pro order first, granted by the admin (Marty 2026-11-09, Orlando's $10 package): recorded as a
|
||||
// package sale with its tx so it counts as new money, and the tx is marked used like any fulfilment
|
||||
function grantStackProForPackage(email, tx, cents, buyerId, note) {
|
||||
const e = String(email || '').toLowerCase(); if (!e) return { error: 'No account.' };
|
||||
if (stackpro.get(e)) return { ok: true, already: true };
|
||||
stackpro.set(e, { ts: Date.now(), via: 'package', tx, cents, buyerId, note: String(note || 'admin grant: package bought without a Pro order').slice(0, 120) });
|
||||
console.log('stack pro granted for package', e, tx, cents, 'cents');
|
||||
return { ok: true, pro: true };
|
||||
}
|
||||
// Marty 2026-11-09 (evening): "Any $10 package or higher unlocks it". No Get Pro step: the member's own package purchase of $10 or more,
|
||||
// on chain, switches Pro on for good. Still new money only (credits never reach onEvent). Only packages from the Pro launch on count
|
||||
// (a reindex of older history never hands it out). A Pro order left waiting from the first version is closed as paid by the same tx.
|
||||
const PRO_START = Date.parse('2026-11-09T21:30:00Z');
|
||||
function proFromPackage(e, ev, cents) {
|
||||
if (cents < STACK_PRO_CENTS || stackpro.get(e)) return false;
|
||||
const t = (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()); if (t < PRO_START) return false;
|
||||
stackpro.set(e, { ts: t, via: 'package', tx: ev.tx, cents, buyerId: Number(ev.buyerId) || 0 });
|
||||
for (const o of stackOrders(e)) orders.set(o.order, Object.assign({}, orders.get(o.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), buyerId: Number(ev.buyerId) || 0 }));
|
||||
console.log('stack pro unlocked by package', e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents');
|
||||
return true;
|
||||
}
|
||||
function stackProOwners() { return [...stackpro.keys()]; }
|
||||
|
||||
// A package purchase landing on chain fulfils one of this account's waiting orders: the highest-priced one the package covers.
|
||||
// Rules (2026-10-22): the buyer must be one of this account's own positions (main member id or a linked position); the purchase must
|
||||
// be mined AFTER the order was opened (block time, ORDER_SKEW_MS for clock drift); one pass per purchase of $5 or more; each tx used
|
||||
// once across every account and order. Credit balances never fulfil an order.
|
||||
const ORDER_SKEW_MS = 30000;
|
||||
function txUsed(tx) {
|
||||
if (!tx) return false;
|
||||
for (const [, o] of orders) if (o && o.tx === tx) return true;
|
||||
for (const [, p] of passes) if (p && (p.bought || []).some(b => b.tx && b.tx === tx)) return true;
|
||||
return false;
|
||||
}
|
||||
async function ownerOf(ev) { // the account behind the buying position
|
||||
if (ev.devEmail && !R.isProd) return String(ev.devEmail).toLowerCase();
|
||||
const id = Number(ev.buyerId) || 0; if (!id) return null;
|
||||
let a = await R.accounts.byMemberId(id);
|
||||
if (!a && R.accounts.positionByMember) { const pos = await R.accounts.positionByMember(id); if (pos && pos.email) a = { email: pos.email }; }
|
||||
return a && a.email ? String(a.email).toLowerCase() : null;
|
||||
}
|
||||
async function minedAt(ev) { // block time in ms; the indexed-at time only when the block cannot be read (it is never earlier than the block)
|
||||
if (ev.devMinedAt && !R.isProd) return Number(ev.devMinedAt);
|
||||
if (ev.block && R.blockTime) {
|
||||
for (let i = 0; i < 3; i++) { try { const s = await R.blockTime(ev.block); if (s > 0) return s * 1000; } catch (e) {} await new Promise(r => setTimeout(r, 1500)); }
|
||||
console.warn('gamepass: block time unavailable for', ev.block, '- using the indexed-at time');
|
||||
}
|
||||
return Number(ev.ts) || Date.now();
|
||||
}
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase' || (ev.priceCents || 0) < 500) return null;
|
||||
const c = cfg(); const cents = ev.priceCents || 0;
|
||||
if (!TIERS.some(k => cents >= c.tiers[k].price) && !heroOrderPrices(c).some(x => cents >= x) && cents < STACK_PRO_CENTS) return null;
|
||||
const e = await ownerOf(ev); if (!e) return null;
|
||||
const pro = proFromPackage(e, ev, cents); // any $10+ package unlocks Stack POL Pro; it rides along, never takes the package from an order
|
||||
const withPro = r => pro ? Object.assign(r || {}, { stackPro: true, email: e }) : r;
|
||||
if (!waitingOrders(e).length && !heroOrders(e).length) return withPro(null);
|
||||
if (txUsed(ev.tx)) return withPro(null); // each purchase counts once, everywhere
|
||||
const at = await minedAt(ev);
|
||||
// one package fulfils ONE order, pass or bonus hero (2026-11-05): the highest-priced one it covers, then the oldest
|
||||
const all = waitingOrders(e).map(o => Object.assign({ price: c.tiers[o.tier].price }, o)).concat(heroOrders(e).filter(o => heroOrderOpen(e, o.hero)).map(o => Object.assign({ price: heroOrderPrice(c, o.hero) }, o))).concat(stackpro.get(e) ? [] : stackOrders(e).map(o => Object.assign({ price: STACK_PRO_CENTS }, o)));
|
||||
const w = all.filter(o => cents >= o.price && at + ORDER_SKEW_MS >= o.ts).sort((x, y) => y.price - x.price || x.ts - y.ts)[0];
|
||||
if (!w) { console.log('gamepass: package', String(ev.tx).slice(0, 12), 'by', e, 'fulfils no order (bought before the order or too small)'); return withPro(null); }
|
||||
if (w.kind === 'stackpro') {
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
|
||||
stackpro.set(e, { ts: (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), via: 'package', tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0 });
|
||||
console.log('stack pro fulfilled by package', e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents');
|
||||
return { order: w.order, stackPro: true, email: e };
|
||||
}
|
||||
if (w.kind === 'hero') {
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
|
||||
const g = grantHeroes(e, w.hero, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: heroOrderPrice(c, w.hero) / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()));
|
||||
console.log('bonus heroes fulfilled by package', w.hero, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents:', g.heroes.join(','));
|
||||
return withPro({ order: w.order, hero: w.hero, heroes: g.heroes });
|
||||
}
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'paid', tx: ev.tx, cents, paidAt: Date.now(), minedAt: at, buyerId: Number(ev.buyerId) || 0 }));
|
||||
const x = extend(e, 'package', { tx: ev.tx, cents, order: w.order, buyerId: Number(ev.buyerId) || 0, usd: c.tiers[w.tier].price / 100, packageUsd: cents / 100 }, (ev.devNow && !R.isProd) ? Number(ev.devNow) : (ev.ts || Date.now()), w.tier);
|
||||
console.log('gamepass fulfilled by package', w.tier, e, 'tx', String(ev.tx).slice(0, 12), cents, 'cents, until', new Date(x.until).toISOString());
|
||||
return withPro({ order: w.order, until: x.until, tier: w.tier });
|
||||
}
|
||||
|
||||
// ---- bonus heroes (2026-11-05) ----
|
||||
// owned for good: record.heroes = { kestrel: { ts, via, tx, order, cents, usd, bundle? } }, record.heroBundle = { ts, via, heroes, tx, order }
|
||||
// (in the passes map, the same durable record as the passes). A hero is never in `bought`, so hero sales never feed the Pass Tournament pool.
|
||||
function heroOrders(e) {
|
||||
const out = [];
|
||||
for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') {
|
||||
if (HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt) { orders.set(k, Object.assign({}, o, { status: 'cancelled', cancelledAt: Date.now(), why: 'free at level ' + HERO_DEF[o.hero].freeAt + ' in the game' })); continue; } // never paid: she is free now
|
||||
out.push(Object.assign({ order: k }, o));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function heroOrder(e, key) { return heroOrders(e).find(o => o.hero === key) || null; }
|
||||
const heroOrderPrice = (c, key) => key === 'bundle' ? c.heroes.bundle.price : (c.heroes.price[key] || 0);
|
||||
const heroOrderPrices = c => [c.heroes.bundle.price].concat(HERO_SOLD.map(k => c.heroes.price[k]).filter(x => x > 0));
|
||||
// a waiting hero order still worth fulfilling: nothing in it is owned yet (a bundle also needs its list set)
|
||||
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_SOLD.includes(key) && !own.has(key); }
|
||||
// -> { owned: bought, comped and free heroes; bought: on the record; bundle: bought as the bundle }
|
||||
function heroesOwned(email) {
|
||||
const p = rec(String(email || '').toLowerCase()), c = cfg(), H = (p && p.heroes) || {};
|
||||
return { owned: HERO_KEYS.filter(k => H[k] || c.heroes.free.includes(k)), bought: HERO_KEYS.filter(k => H[k]), bundle: !!(p && p.heroBundle) };
|
||||
}
|
||||
// the hand-off claim for Shards of Valor (server.js sovMint): what this member owns, and the current sale (the game keeps it, so a free
|
||||
// hero opens for guests too)
|
||||
function heroClaim(email) {
|
||||
const c = cfg(), h = heroesOwned(email), out = { heroes: h.owned, heroBundle: h.bundle, heroSale: { free: c.heroes.free, bundle: c.heroes.bundle.heroes, each: (c.heroes.price.valda || 2000) / 100, bundlePrice: c.heroes.bundle.price / 100 } };
|
||||
if (h.bundle && c.heroes.cap) out.heroBundleCap = c.heroes.cap; // only once Marty sets heroBundleCap (unset today: heroes only)
|
||||
return out;
|
||||
}
|
||||
function grantHeroes(e, key, via, extra, now) {
|
||||
const t = now || Date.now(), c = cfg(), cur = passes.get(e) || { until: 0, bought: [] }, H = Object.assign({}, cur.heroes || {});
|
||||
const list = key === 'bundle' ? c.heroes.bundle.heroes.slice() : [key], got = [];
|
||||
for (const k of list) if (!H[k]) { H[k] = Object.assign({ ts: t, via }, extra || {}, key === 'bundle' ? { bundle: true } : {}); got.push(k); }
|
||||
const upd = { heroes: H }; if (key === 'bundle') upd.heroBundle = Object.assign({ ts: t, via, heroes: list }, extra || {});
|
||||
passes.set(e, Object.assign({}, cur, upd));
|
||||
// never a second charge for a hero you have: drop waiting orders that are now owned (in full or in part)
|
||||
for (const o of heroOrders(e)) if (!heroOrderOpen(e, o.hero)) orders.set(o.order, Object.assign({}, orders.get(o.order), { status: 'cancelled', cancelledAt: t, why: 'already owned' }));
|
||||
return { heroes: got, owned: heroesOwned(e).owned };
|
||||
}
|
||||
// the member card part: every hero, its price and state, and the bundle. open = on sale (heroSales) or the admin portal's test (opts.preview)
|
||||
function heroView(email, now, opts) {
|
||||
const e = String(email || '').toLowerCase(), c = cfg(), h = heroesOwned(e), own = new Set(h.owned), preview = !!(opts && opts.preview), open = c.heroes.sale || preview;
|
||||
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key], fa = d.freeAt || null; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, freeAt: fa, owned: own.has(d.key), waiting: !fa && !!heroOrder(e, d.key), open: !fa && open && price > 0 && !own.has(d.key) }; });
|
||||
const B = c.heroes.bundle, bOwn = B.heroes.filter(k => own.has(k));
|
||||
const bundle = B.heroes.length ? { key: 'bundle', names: B.heroes.map(k => HERO_DEF[k].name), heroes: B.heroes, price: B.price, usd: B.price / 100, package: packageFor(B.price / 100), owned: bOwn.length === B.heroes.length, some: bOwn.length > 0, waiting: !!heroOrder(e, 'bundle'), open: open && !bOwn.length } : null;
|
||||
return { sale: c.heroes.sale, preview: preview && !c.heroes.sale, show: c.heroes.sale || preview || h.bought.length > 0, items, bundle, owned: h.owned, bundleOwned: h.bundle };
|
||||
}
|
||||
// POST /api/my/heroes/buy { hero: kestrel | valda | morag | roland | bundle }: opens (or reuses) a waiting order; a fresh package of at
|
||||
// least the price fulfils it (onEvent). Never spends credits. Refuses a hero already owned, a free one, and a bundle when any of its
|
||||
// heroes is already owned (the rest one at a time costs less).
|
||||
function buyHero(email, now, key, opts) {
|
||||
const e = String(email || '').toLowerCase(), c = cfg(), t = now || Date.now(); key = String(key || '').toLowerCase();
|
||||
if (key !== 'bundle' && !HERO_KEYS.includes(key)) return { error: 'There is no such hero.' };
|
||||
if (!(c.heroes.sale || (opts && opts.preview))) return { error: 'Bonus heroes are not on sale yet.' };
|
||||
const own = new Set(heroesOwned(e).owned);
|
||||
if (key === 'bundle') {
|
||||
const B = c.heroes.bundle; if (!B.heroes.length) return { error: 'There is no hero bundle right now.' };
|
||||
const have = B.heroes.filter(k => own.has(k)); if (have.length) return { error: 'You already have ' + have.map(k => HERO_DEF[k].name).join(' and ') + ', so the bundle is not for you: get the others one at a time.' };
|
||||
} else {
|
||||
if (HERO_DEF[key].freeAt) return { error: HERO_DEF[key].name + ' is free for every player at level ' + HERO_DEF[key].freeAt + ' in Shards of Valor, so she is not for sale.' };
|
||||
if (c.heroes.price[key] === 0) return { error: HERO_DEF[key].name + ' is free for everyone.' };
|
||||
if (own.has(key)) return { error: 'You already have ' + HERO_DEF[key].name + '. Heroes are yours for good.' };
|
||||
}
|
||||
let w = heroOrder(e, key); const reused = !!w;
|
||||
if (!w) { const k = 'hero-' + t.toString(36) + '-' + Math.random().toString(36).slice(2, 8); orders.set(k, { status: 'waiting', kind: 'hero', hero: key, email: e, ts: t }); w = Object.assign({ order: k }, orders.get(k)); }
|
||||
const price = heroOrderPrice(c, key), pkg = packageFor(price / 100);
|
||||
const name = key === 'bundle' ? 'The hero bundle (' + c.heroes.bundle.heroes.map(k => HERO_DEF[k].name).join(', ') + ')' : HERO_DEF[key].name;
|
||||
if (!reused) console.log('bonus hero order opened', key, e, w.order, 'needs a package of', price, 'cents');
|
||||
return { ok: false, needPay: true, hero: key, payUrl: '/my?from=heroes&hero=' + key + '#buy', order: w.order, orderTs: w.ts, reused, price, usd: price / 100, package: pkg,
|
||||
message: name + ' joins you in Shards of Valor the moment your next package of $' + pkg + ' or more settles on chain. One time, yours for good. Your sponsor and team are paid from it as usual, and you keep every credit of the package for your ads.' };
|
||||
}
|
||||
function cancelHeroOrder(email, key) {
|
||||
const e = String(email || '').toLowerCase(), w = heroOrder(e, String(key || '').toLowerCase()); if (!w) return { ok: true, none: true };
|
||||
orders.set(w.order, Object.assign({}, orders.get(w.order), { status: 'cancelled', cancelledAt: Date.now() })); return { ok: true, order: w.order, hero: w.hero };
|
||||
}
|
||||
function compHero(email, key, why) { // support or the admin test: counts as no sale
|
||||
const e = String(email || '').toLowerCase(); key = String(key || '').toLowerCase(); if (key !== 'bundle' && !HERO_KEYS.includes(key)) return { error: 'There is no such hero.' };
|
||||
return Object.assign({ ok: true }, grantHeroes(e, key, 'admin', { note: String(why || 'support').slice(0, 80), usd: 0 }));
|
||||
}
|
||||
function revokeHero(email, key, why) { // support only (an admin test, a mistaken comp); never automatic
|
||||
const e = String(email || '').toLowerCase(); key = String(key || '').toLowerCase(); const p = passes.get(e); const H = Object.assign({}, (p && p.heroes) || {});
|
||||
const keys = key === 'all' ? Object.keys(H) : [key]; if (!p || !keys.some(k => H[k])) return { error: 'This account does not own that hero.' };
|
||||
const gone = []; for (const k of keys) if (H[k]) { gone.push(Object.assign({}, H[k], { hero: k, revokedAt: Date.now(), why: String(why || 'support').slice(0, 80) })); delete H[k]; }
|
||||
const upd = { heroes: H, heroRevokes: gone.concat(p.heroRevokes || []).slice(0, 50) };
|
||||
if (p.heroBundle && !(p.heroBundle.heroes || []).every(k => H[k])) upd.heroBundle = null;
|
||||
passes.set(e, Object.assign({}, p, upd)); return { ok: true, revoked: gone.map(g => g.hero) };
|
||||
}
|
||||
function heroStats() {
|
||||
const c = cfg(); const out = { sale: c.heroes.sale, sold: Object.fromEntries(HERO_KEYS.map(k => [k, 0])), bundles: 0, comped: 0, usd: 0, waiting: 0 };
|
||||
for (const [, p] of passes) {
|
||||
if (!p) continue;
|
||||
for (const [k, h] of Object.entries(p.heroes || {})) { if (!(k in out.sold)) continue; if (h.via === 'admin') { out.comped += 1; continue; } out.sold[k] += 1; if (!h.bundle) out.usd += Number(h.usd) || 0; }
|
||||
if (p.heroBundle && p.heroBundle.via !== 'admin') { out.bundles += 1; out.usd += Number(p.heroBundle.usd) || 0; }
|
||||
}
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero' && !(HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt)) out.waiting += 1;
|
||||
out.usd = Math.round(out.usd * 100) / 100; return out;
|
||||
}
|
||||
|
||||
// ---- the caps ----
|
||||
function capsFor(email, now, game) {
|
||||
const e = String(email || '').toLowerCase(); const c = cfg(); const t = now || Date.now(); const day = dayKey(t); const pass = flag(e, t).active;
|
||||
const lim = pass ? c.pass : c.free; const M = L.members[e]; const D = M && M.days[day];
|
||||
const used = { daily: r6(D ? D.daily : 0), total: r6(D ? D.total : 0) };
|
||||
const out = { daily: lim.daily, total: lim.total, used, day, enforced: enforcedOn(c, day), pass };
|
||||
out.lifetime = { cap: c.freeLifetime, used: r6(M && M.freeTotal != null ? M.freeTotal : (M ? Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0) : 0)) }; // the free allowance, what has been used of it
|
||||
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
|
||||
out.lifetime.done = !pass && out.lifetime.used + 1e-9 >= out.lifetime.cap; // the free allowance is used up (only a pass pays from here)
|
||||
out.lifetime.waiting = M ? r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0)) : 0;
|
||||
return out;
|
||||
}
|
||||
|
||||
// quest-site check (Zealy, 2026-11-05): has this account earned any game reward, and how much in total
|
||||
function activity(email) {
|
||||
const M = L.members[String(email || '').toLowerCase()]; if (!M) return { grants: 0, pol: 0 };
|
||||
return Object.values(M.days).reduce((o, d) => ({ grants: o.grants + (d.grants || 0), pol: r6(o.pol + (d.total || 0)) }), { grants: 0, pol: 0 });
|
||||
}
|
||||
|
||||
// POST /api/partner/polgrant. Returns { allowed, deferred, pass, day } (+ carried, capHit, enforced, repeat).
|
||||
function grant(o) {
|
||||
const e = String(o.email || '').toLowerCase(); const game = String(o.game || '').toLowerCase(); const kind = o.kind === 'progress' ? 'progress' : 'daily';
|
||||
const pol = r6(o.pol); const ref = String(o.ref || '').slice(0, 120); const t = o.now || Date.now(); const day = dayKey(t);
|
||||
if (!e || !GAMES.includes(game) || !ref || !(pol >= 0)) return { error: 'memberId/email, game, kind, pol and ref are required' };
|
||||
const key = game + ':' + ref;
|
||||
const prev = L.refs[key];
|
||||
if (prev) return { allowed: prev.allowed, deferred: prev.deferred, pass: prev.pass, day: prev.day, carried: prev.carried || 0, capHit: prev.capHit || null, enforced: !!prev.enforced, repeat: true, voided: !!prev.voided };
|
||||
const c = cfg(); const pass = flag(e, t).active; const lim = pass ? c.pass : c.free; const enforced = enforcedOn(c, day);
|
||||
const M = member(e); const D = dayRow(M, day); const tier = D.tier[pass ? 'pass' : 'free'];
|
||||
let totalRem = Math.max(0, r6(lim.total - D.total)), dailyRem = Math.max(0, r6(lim.daily - D.daily));
|
||||
// the free allowance: a running total of what this account received while it held no pass (seeded once from the day rows
|
||||
// still on file); once it reaches freeLifetime, a free account's room for today is zero, carry included
|
||||
if (M.freeTotal == null) M.freeTotal = r6(Object.values(M.days).reduce((n, d) => n + ((d.tier && d.tier.free && d.tier.free.allowed) || 0), 0));
|
||||
let lifetimeHit = false;
|
||||
if (!pass && enforced) { const room = Math.max(0, r6(c.freeLifetime - M.freeTotal)); if (room < totalRem) totalRem = room; lifetimeHit = room < pol; } // hit = the allowance, not the day, is what trims this grant
|
||||
// carry-forward: progress POL deferred on an EARLIER day for this game is paid first, inside today's total cap
|
||||
let carried = 0; const q = M.deferred[game] || [];
|
||||
for (const d of q) {
|
||||
if (d.day >= day || d.left <= 0) continue;
|
||||
const take = enforced ? Math.min(d.left, Math.max(0, r6(totalRem - carried))) : d.left;
|
||||
if (take <= 0) break;
|
||||
d.left = r6(d.left - take); carried = r6(carried + take); d.paid = (d.paid || []).concat([{ day, pol: take, ref }]).slice(-20);
|
||||
}
|
||||
M.deferred[game] = q.filter(d => d.left > 0);
|
||||
if (carried) { D.total = r6(D.total + carried); D.carried = r6(D.carried + carried); tier.allowed = r6(tier.allowed + carried); totalRem = Math.max(0, r6(totalRem - carried)); }
|
||||
// the new grant
|
||||
let allowed = pol, deferred = 0, dropped = 0, capHit = null;
|
||||
const wouldAllowed = kind === 'daily' ? Math.min(pol, dailyRem, totalRem) : Math.min(pol, totalRem);
|
||||
const wouldHit = wouldAllowed < pol ? (kind === 'daily' && dailyRem <= totalRem ? 'daily' : 'total') : null;
|
||||
if (enforced) {
|
||||
allowed = r6(wouldAllowed); capHit = wouldHit;
|
||||
if (kind === 'daily') { dropped = r6(pol - allowed); if (dropped) D.dropped = r6(D.dropped + dropped); }
|
||||
else { deferred = r6(pol - allowed); if (deferred) { q.push({ ref, pol, left: deferred, ts: t, day }); M.deferred[game] = q; D.deferredOut = r6(D.deferredOut + deferred); } }
|
||||
if (capHit) { D.hits[capHit] += 1; tier[capHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1; }
|
||||
} else if (wouldHit) { // before capsStartDate: everything is allowed, but Admin sees what the caps would have done
|
||||
D.would[kind === 'daily' ? 'dropped' : 'deferred'] = r6(D.would[kind === 'daily' ? 'dropped' : 'deferred'] + (pol - wouldAllowed));
|
||||
D.would[wouldHit === 'daily' ? 'hitsDaily' : 'hitsTotal'] += 1;
|
||||
}
|
||||
if (kind === 'daily') D.daily = r6(D.daily + allowed);
|
||||
D.total = r6(D.total + allowed); tier.allowed = r6(tier.allowed + allowed); D.grants += 1;
|
||||
if (!pass) M.freeTotal = r6((M.freeTotal || 0) + allowed + carried); // counts toward the free allowance only while no pass is held
|
||||
// tournament activity: one point per reported grant (progress and daily weigh the same)
|
||||
if (pol > 0) { const wk = weekKey(t); M.weeks[wk] = M.weeks[wk] || {}; M.weeks[wk][game] = (M.weeks[wk][game] || 0) + 1; }
|
||||
if (capHit) { const p = passes.get(e) || { until: 0, bought: [] }; passes.set(e, Object.assign({}, p, { lastCapHit: { ts: t, day, game, kind: capHit, pass, lifetime: !!lifetimeHit } })); }
|
||||
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed, lifetimeHit };
|
||||
L.refs[key] = out; touch();
|
||||
// waiting = every game's progress POL deferred for this account (it pays once a pass is active, inside the pass cap); the games
|
||||
// show it in the allowance note (Marty 2026-11-03: tell members at the cap to get the Pass, and what is waiting for them)
|
||||
const waiting = r6(Object.values(M.deferred).reduce((n, q) => n + (q || []).reduce((m, x) => m + (x.left || 0), 0), 0));
|
||||
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false, lifetimeHit, freeUsed: r6(M.freeTotal || 0), freeLifetime: c.freeLifetime, waiting };
|
||||
}
|
||||
|
||||
// POST /api/partner/polgrant/void: the game decided not to pay after all. Reverses this ref's own share (the carry it triggered
|
||||
// belongs to earlier refs and stays). The ref stays answered, as voided, so a replay is still idempotent.
|
||||
function voidGrant(o) {
|
||||
const game = String(o.game || '').toLowerCase(); const ref = String(o.ref || '').slice(0, 120); const key = game + ':' + ref;
|
||||
const prev = L.refs[key]; if (!prev) return { ok: true, unknown: true };
|
||||
if (prev.voided) return { ok: true, voided: true, repeat: true };
|
||||
const M = member(prev.email); const D = dayRow(M, prev.day);
|
||||
const own = r6(prev.own || 0);
|
||||
D.total = Math.max(0, r6(D.total - own)); if (prev.kind === 'daily') D.daily = Math.max(0, r6(D.daily - own));
|
||||
const tier = D.tier[prev.pass ? 'pass' : 'free']; tier.allowed = Math.max(0, r6(tier.allowed - own));
|
||||
let removed = 0; const q = M.deferred[game] || []; for (const d of q) if (d.ref === ref) { removed = r6(removed + d.left); d.left = 0; } M.deferred[game] = q.filter(d => d.left > 0);
|
||||
if (removed) D.deferredOut = Math.max(0, r6(D.deferredOut - removed));
|
||||
const wk = weekKey(prev.ts || Date.now()); if (M.weeks[wk] && M.weeks[wk][game]) M.weeks[wk][game] -= 1;
|
||||
Object.assign(prev, { voided: true, allowed: 0, deferred: 0, carried: 0, voidedAt: Date.now(), reversed: { allowed: own, deferred: removed } }); touch();
|
||||
return { ok: true, voided: true, reversed: { allowed: own, deferred: removed } };
|
||||
}
|
||||
|
||||
// ---- the weekly Pass Tournament (Monday 9 AM Central, the week that just closed) ----
|
||||
function nextTournamentAt(now) { const t = now || Date.now(); const ws = weekStart(t); const thisMon = ws + 9 * 3600000; return t < thisMon ? thisMon : ws + 7 * 86400000 + 9 * 3600000; }
|
||||
function holdersIn(start, end) { // any tier holds a Pass Tournament seat (every tier above weekly includes everything Weekly gives)
|
||||
const out = [];
|
||||
for (const [e, p] of passes) { if (!p || !(Math.max(...TIERS.map(k => tiersOf(p)[k])) > start)) continue; if ((p.bought || []).some(b => b.ts < end)) out.push(e); }
|
||||
return out;
|
||||
}
|
||||
const isSale = b => b && b.via !== 'admin'; // comps are passes, not sales
|
||||
// the pool counts weekly pass sales only, unless passTournamentTierSales adds the sales of every tier above weekly (default off: the pool exactly as before tiers)
|
||||
function salesIn(start, end, withTiers) { let n = 0, usd = 0; for (const [, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b) && b.ts >= start && b.ts < end && (withTiers || rowTier(b) === 'weekly')) { n += 1; usd += Number(b.usd) || 0; } return { n, usd: Math.round(usd * 100) / 100 }; }
|
||||
function scoresFor(wk, emails) {
|
||||
return emails.map(e => { const M = L.members[e]; const g = (M && M.weeks[wk]) || {}; const score = Object.values(g).reduce((n, x) => n + x, 0); const first = ((passes.get(e) || {}).bought || []).reduce((m, b) => Math.min(m, b.ts), Infinity);
|
||||
return { email: e, score, games: g, first }; }).filter(x => x.score > 0).sort((a, b) => b.score - a.score || a.first - b.first || (a.email < b.email ? -1 : 1));
|
||||
}
|
||||
async function runTournament(startTs, opts) {
|
||||
const c = cfg(); const start = weekStart(startTs); const end = start + 7 * 86400000; const wk = dayKey(start);
|
||||
if (prizes.get(wk) && !(opts && opts.force)) return prizes.get(wk);
|
||||
const polUsd = await R.polUsd().catch(() => 0);
|
||||
if (!(polUsd > 0)) return { error: 'POL rate unavailable; the tournament for the week of ' + wk + ' will be settled on the next hourly pass.' };
|
||||
const sales = salesIn(start, end, c.tournamentTierSales); const poolUsd = Math.round(sales.usd * c.pct) / 100;
|
||||
const poolPol = r6(poolUsd / polUsd);
|
||||
const ranked = scoresFor(wk, holdersIn(start, end));
|
||||
const winners = [];
|
||||
for (let i = 0; i < Math.min(3, ranked.length); i++) {
|
||||
const x = ranked[i]; let a = null; try { a = await R.accounts.byEmail(x.email); } catch (e) {}
|
||||
winners.push({ place: i + 1, email: x.email, username: (a && a.username) || null, memberId: (a && a.memberId) || 0, wallet: (a && a.address) || null, score: x.score, games: x.games, pol: r6(poolPol * SHARES[i]), usd: Math.round(poolUsd * SHARES[i] * 100) / 100, status: 'pending', tx: null });
|
||||
}
|
||||
const row = { week: wk, label: 'week of ' + dayLabel(wk), start, end, sales: sales.n, salesUsd: sales.usd, pct: c.pct, poolUsd, polUsd, poolPol, holders: holdersIn(start, end).length, ranked: ranked.length, winners,
|
||||
unallocatedPol: r6(poolPol - winners.reduce((n, w) => n + w.pol, 0)), ranAt: Date.now(), posted: false };
|
||||
prizes.set(wk, row);
|
||||
console.log('gamepass tournament', wk, 'sales', sales.n, 'pool', poolPol, 'POL', 'winners', winners.length);
|
||||
if (winners.length && c.enabled) {
|
||||
const medal = ['\u{1F947}', '\u{1F948}', '\u{1F949}'];
|
||||
const lines = winners.map(w => medal[w.place - 1] + ' ' + (w.username ? '@' + w.username : 'member #' + (w.memberId || '?')) + ' · ' + w.score + ' plays · ' + w.pol.toFixed(2) + ' POL');
|
||||
const html = '\u{1F3AE} <b>Game Pass Tournament</b> · ' + row.label + '\n' + lines.join('\n') + '\n' + sales.n + ' pass' + (sales.n === 1 ? '' : 'es') + ' sold · prize pool ' + poolPol.toFixed(2) + ' POL (' + c.pct + '% of pass sales)\n'
|
||||
+ 'Prizes are paid in POL by the games to the winners’ InstantAdPay wallets. Get the Pass: https://instantadpay.com/my#games?pass=1';
|
||||
try { await R.telegram(html); row.posted = true; prizes.set(wk, row); } catch (e) { console.error('gamepass tournament post', e.message); }
|
||||
for (const w of winners) { try { await R.notify(w.email, 'Game Pass Tournament: you placed #' + w.place, '<p>You finished <b>#' + w.place + '</b> in the Game Pass Tournament for the ' + row.label + ' with ' + w.score + ' plays across the games. Your prize of <b>' + w.pol.toFixed(2) + ' POL</b> is paid to the wallet on your InstantAdPay account by the games this week.</p>'); } catch (e) {} }
|
||||
}
|
||||
return row;
|
||||
}
|
||||
// hourly: once Monday 9 AM Central has passed and the closed week has no row yet, exactly one app copy settles it (marks.claim)
|
||||
async function tournamentTick(now) {
|
||||
const t = now || Date.now(); const c = cfg(); if (!c.enabled) return null;
|
||||
const ws = weekStart(t); if (t < ws + 9 * 3600000) return null; // not yet 9 AM Monday for the week that just closed
|
||||
const prev = ws - 7 * 86400000; const wk = dayKey(prev);
|
||||
if (prizes.get(wk)) return null;
|
||||
if (!holdersIn(prev, ws).length && !salesIn(prev, ws, c.tournamentTierSales).n) { prizes.set(wk, { week: wk, label: 'week of ' + dayLabel(wk), start: prev, end: ws, sales: 0, salesUsd: 0, poolPol: 0, winners: [], ranAt: Date.now(), empty: true }); return null; }
|
||||
if (!(await R.marks.claim('gamepass-tournament:' + wk))) return null;
|
||||
return runTournament(prev);
|
||||
}
|
||||
// GET /api/partner/tournament/pending: prize rows the games still have to pay (the Road Agent faucet pattern)
|
||||
function pending() { const out = []; for (const [, row] of prizes) for (const w of row.winners || []) if (w.status === 'pending') out.push({ week: row.week, label: row.label, place: w.place, email: w.email, username: w.username, memberId: w.memberId, wallet: w.wallet, pol: w.pol, usd: w.usd, score: w.score }); return out.sort((a, b) => a.week < b.week ? -1 : a.week > b.week ? 1 : a.place - b.place); }
|
||||
function markPaid(week, place, tx, by) {
|
||||
const row = prizes.get(String(week)); if (!row) return { error: 'no such week' };
|
||||
const w = (row.winners || []).find(x => x.place === Number(place)); if (!w) return { error: 'no such place' };
|
||||
if (w.status === 'paid') return { ok: true, repeat: true, tx: w.tx };
|
||||
Object.assign(w, { status: 'paid', tx: String(tx || '').slice(0, 80), paidAt: Date.now(), paidBy: by || null }); prizes.set(String(week), row);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
// ---- admin ----
|
||||
function monthStart(ts) { const p = ctParts(ts); return ctMidnight(Date.UTC(p.y, p.mo - 1, 1, 17)); } // the 1st of the Central month, 00:00 Central
|
||||
// per tier: active = accounts whose HIGHEST active tier is this one (each account counted once); sales by Central week / month /
|
||||
// all time (comps are not sales); renewals30d = purchases in the last 30 days by accounts that held this tier before; expiring7d =
|
||||
// this tier ends within the next 7 Central days (today included); waitingOrders = orders waiting for a package.
|
||||
function tierStats(t) {
|
||||
const ws = weekStart(t), ms = monthStart(t), d30 = t - 30 * 86400000;
|
||||
const soon = ctMidnight(ctMidnight(t) + 7 * 86400000 + 3 * 3600000); // Central midnight that ends day 7 (DST-safe)
|
||||
const out = {}; for (const k of TIERS) out[k] = { name: TIER_NAMES[k], active: 0, soldWeek: 0, usdWeek: 0, soldMonth: 0, usdMonth: 0, soldTotal: 0, usdTotal: 0, renewals30d: 0, expiring7d: 0, comped: 0, waitingOrders: 0 };
|
||||
for (const [, p] of passes) {
|
||||
if (!p) continue; const T = tiersOf(p); const top = topTier(T, t); if (top) out[top].active += 1;
|
||||
for (const k of TIERS) if (T[k] > t && T[k] <= soon) out[k].expiring7d += 1;
|
||||
const rows = p.bought || [];
|
||||
for (const b of rows) {
|
||||
const k = rowTier(b); const o = out[k]; if (!isSale(b)) { o.comped += 1; continue; }
|
||||
const usd = Number(b.usd) || 0; o.soldTotal += 1; o.usdTotal += usd;
|
||||
if (b.ts >= ws) { o.soldWeek += 1; o.usdWeek += usd; }
|
||||
if (b.ts >= ms) { o.soldMonth += 1; o.usdMonth += usd; }
|
||||
if (b.ts >= d30 && rows.some(x => x !== b && rowTier(x) === k && x.ts < b.ts)) o.renewals30d += 1;
|
||||
}
|
||||
}
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind !== 'hero' && o.kind !== 'stackpro') out[tierOk(o.tier) ? o.tier : 'weekly'].waitingOrders += 1;
|
||||
for (const k of TIERS) for (const f of ['usdWeek', 'usdMonth', 'usdTotal']) out[k][f] = Math.round(out[k][f] * 100) / 100;
|
||||
return out;
|
||||
}
|
||||
// every sale row, newest first, labelled by how it was paid. Rows from the new package rail carry buyerId (2026-10-22); the two
|
||||
// rows from before (one paid with a credit balance, one fulfilled by a package under the old rule) are labelled as such.
|
||||
function payLabel(b) {
|
||||
if (b.via === 'credits') return 'credit-paid (old rule)';
|
||||
if (b.via === 'package') return ('buyerId' in b) ? 'package' : 'package (old rule)';
|
||||
return String(b.via || '?');
|
||||
}
|
||||
function salesList(limit) {
|
||||
const out = [];
|
||||
for (const [e, p] of passes) for (const b of (p && p.bought) || []) if (isSale(b)) out.push({ ts: b.ts, email: e, tier: rowTier(b), name: TIER_NAMES[rowTier(b)], via: b.via, label: payLabel(b),
|
||||
tx: b.tx || null, usd: Number(b.usd) || 0, packageUsd: b.packageUsd || (b.cents ? b.cents / 100 : null), credits: b.credits || null, buyerId: b.buyerId || null });
|
||||
return out.sort((a, b) => b.ts - a.ts).slice(0, limit || 50);
|
||||
}
|
||||
function payMix() {
|
||||
const m = { credit: { n: 0, usd: 0 }, packageOld: { n: 0, usd: 0 }, package: { n: 0, usd: 0, packageUsd: 0 } };
|
||||
for (const [, p] of passes) for (const b of (p && p.bought) || []) {
|
||||
if (!isSale(b)) continue; const usd = Number(b.usd) || 0;
|
||||
const k = b.via === 'credits' ? 'credit' : (b.via === 'package' && !('buyerId' in b)) ? 'packageOld' : 'package';
|
||||
m[k].n += 1; m[k].usd = Math.round((m[k].usd + usd) * 100) / 100;
|
||||
if (k === 'package') m.package.packageUsd = Math.round((m.package.packageUsd + (Number(b.packageUsd) || (b.cents ? b.cents / 100 : 0))) * 100) / 100;
|
||||
}
|
||||
return m;
|
||||
}
|
||||
function adminStats(now) {
|
||||
const t = now || Date.now(); const c = cfg(); const ws = weekStart(t); const day = dayKey(t); const wkFrom = dayKey(ws);
|
||||
let active = 0, soldTotal = 0, usdTotal = 0, soldWeek = 0, usdWeek = 0, waiting = 0, comped = 0;
|
||||
for (const [, p] of passes) { if (!p) continue; if (topTier(tiersOf(p), t)) active += 1; for (const b of p.bought || []) { if (!isSale(b)) { comped += 1; continue; } soldTotal += 1; usdTotal += Number(b.usd) || 0; if (b.ts >= ws) { soldWeek += 1; usdWeek += Number(b.usd) || 0; } } }
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind !== 'hero' && o.kind !== 'stackpro') waiting += 1;
|
||||
const wk = { pass: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, free: { allowed: 0, hitsDaily: 0, hitsTotal: 0 }, carried: 0, dropped: 0, deferredOut: 0, grants: 0, would: { dropped: 0, deferred: 0, hitsDaily: 0, hitsTotal: 0 }, players: 0 };
|
||||
const today = { allowed: 0, grants: 0, players: 0 };
|
||||
let qEntries = 0, qPol = 0, qMembers = 0; const byGame = {};
|
||||
for (const [e, M] of Object.entries(L.members)) {
|
||||
let inWeek = false;
|
||||
for (const [d, D] of Object.entries(M.days)) {
|
||||
if (d < wkFrom) continue; inWeek = true;
|
||||
for (const k of ['pass', 'free']) { wk[k].allowed = r6(wk[k].allowed + D.tier[k].allowed); wk[k].hitsDaily += D.tier[k].hitsDaily; wk[k].hitsTotal += D.tier[k].hitsTotal; }
|
||||
wk.carried = r6(wk.carried + D.carried); wk.dropped = r6(wk.dropped + D.dropped); wk.deferredOut = r6(wk.deferredOut + D.deferredOut); wk.grants += D.grants;
|
||||
for (const k of ['dropped', 'deferred']) wk.would[k] = r6(wk.would[k] + D.would[k]); wk.would.hitsDaily += D.would.hitsDaily; wk.would.hitsTotal += D.would.hitsTotal;
|
||||
if (d === day) { today.allowed = r6(today.allowed + D.total); today.grants += D.grants; today.players += 1; }
|
||||
}
|
||||
if (inWeek) wk.players += 1;
|
||||
let mine = 0; for (const [g, q] of Object.entries(M.deferred)) for (const x of q) { qEntries += 1; qPol = r6(qPol + x.left); mine += 1; byGame[g] = r6((byGame[g] || 0) + x.left); }
|
||||
if (mine) qMembers += 1;
|
||||
const W = M.weeks[wkFrom] || {}; for (const [g, n] of Object.entries(W)) { byGame['plays:' + g] = (byGame['plays:' + g] || 0) + n; }
|
||||
void e;
|
||||
}
|
||||
const rows = [...prizes.values()].sort((a, b) => a.week < b.week ? 1 : -1);
|
||||
return { enabled: c.enabled, tierSales: c.tierSales, settings: { price: c.price, days: c.days, tiers: c.tiers, tournamentTierSales: c.tournamentTierSales, free: c.free, pass: c.pass, capsStart: c.start || null, pct: c.pct, enforced: enforcedOn(c, day) },
|
||||
week: { start: ws, label: 'week of ' + dayLabel(wkFrom), day },
|
||||
tiers: tierStats(t), month: { start: monthStart(t), label: dayLabel(dayKey(monthStart(t))) + ' to date' },
|
||||
passes: { soldWeek, soldTotal, usdWeek: Math.round(usdWeek * 100) / 100, usdTotal: Math.round(usdTotal * 100) / 100, active, comped, waitingOrders: waiting, pay: payMix() },
|
||||
sales: salesList(50),
|
||||
pol: { week: { pass: wk.pass.allowed, free: wk.free.allowed, carried: wk.carried, dropped: wk.dropped, deferredOut: wk.deferredOut, grants: wk.grants, players: wk.players, perPass: soldWeek ? r6(wk.pass.allowed / soldWeek) : 0 }, today },
|
||||
capHits: { week: { free: { daily: wk.free.hitsDaily, total: wk.free.hitsTotal }, pass: { daily: wk.pass.hitsDaily, total: wk.pass.hitsTotal } }, would: wk.would },
|
||||
deferredQueue: { entries: qEntries, pol: qPol, members: qMembers, byGame },
|
||||
tournament: { lastRun: rows[0] ? rows[0].ranAt : null, last: rows[0] || null, next: nextTournamentAt(t), pending: pending().length, history: rows.slice(0, 8) } };
|
||||
}
|
||||
|
||||
// ---- housekeeping: answered refs and day rows older than KEEP_DAYS, week tallies older than 10 weeks ----
|
||||
function prune(now) {
|
||||
const t = now || Date.now(); const cut = t - KEEP_DAYS * 86400000; const cutDay = dayKey(cut); const cutWeek = dayKey(weekStart(t - 70 * 86400000)); let n = 0;
|
||||
for (const [k, r] of Object.entries(L.refs)) if ((r.ts || 0) < cut) { delete L.refs[k]; n++; }
|
||||
for (const [e, M] of Object.entries(L.members)) {
|
||||
for (const d of Object.keys(M.days)) if (d < cutDay) { delete M.days[d]; n++; }
|
||||
for (const w of Object.keys(M.weeks)) if (w < cutWeek) { delete M.weeks[w]; n++; }
|
||||
if (!Object.keys(M.days).length && !Object.keys(M.weeks).length && !Object.values(M.deferred).some(q => q.length)) delete L.members[e];
|
||||
}
|
||||
for (const [k, o] of orders) if (o.status === 'waiting' && t - o.ts > 30 * 86400000) orders.delete(k); // a pass order nobody paid for in a month is forgotten
|
||||
if (n) touch();
|
||||
return n;
|
||||
}
|
||||
|
||||
module.exports = { STACK_PRO_CENTS, stackPro, stackProView, buyStackPro, cancelStackOrder, compStackPro, stackProOwners, grantStackProForPackage, init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, HERO_DEFS, HERO_KEYS, heroesOwned, heroClaim, heroView, buyHero, cancelHeroOrder, compHero, revokeHero, heroStats, flag, activity, view, buy, cancelOrder, comp, revoke, onEvent, capsFor, grant, voidGrant, tournamentTick, runTournament, pending, markPaid, adminStats, prune, weekStart, dayKey,
|
||||
_ledger: () => L };
|
||||
@@ -0,0 +1,101 @@
|
||||
// Game figures for the daily snapshot (Marty 2026-10-08: one card for the whole ecosystem, games as their own block).
|
||||
// Two live sources, no estimates:
|
||||
// players sent in — counted here every time InstantAdPay hands a member into a game (/api/my/<game>), per UTC hour,
|
||||
// so "last 24 h" is exact and survives restarts (DATA_DIR/game-handoffs.json)
|
||||
// payouts + POL — read from Polygon: outgoing transfers from each game's payout wallet in the last 24 h (Etherscan v2,
|
||||
// the same query the hourly wallet watcher on core uses). Our own wallets and the fee wallets are skipped.
|
||||
// Env: GAME_WALLETS = "slug:0x…,slug:0x…" (set from the /root/.<game>-address files on core), ETHERSCAN_KEY.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null;
|
||||
const NAMES = { spookydoors: 'Spooky Doors', gemkingdom: 'Gem Kingdom', clutterhunt: 'ClutterHunt', driprunner: 'Drip Runner', polywarriors: 'PolyWarriors', spellwheel: 'SpellWheel', roadagent: 'Road Agent', polhunter: 'PolHunter', passivedrip: 'PassiveDrip', polybreak: 'PolyBreak', polminer: 'POL Miner', warpwares: 'Warp & Wares', turkeydrop: 'Turkey Drop', shardsofvalor: 'Shards of Valor' };
|
||||
const wallets = () => Object.fromEntries(String(process.env.GAME_WALLETS || '').split(',').map(x => x.trim()).filter(Boolean).map(x => { const [k, a] = x.split(':'); return [String(k).toLowerCase(), String(a || '').toLowerCase()]; }).filter(([k, a]) => k && /^0x[0-9a-f]{40}$/.test(a)));
|
||||
const KEY = () => String(process.env.ETHERSCAN_KEY || '').trim();
|
||||
// money never flows to these from a game wallet as a payout: Marty's fee wallets, the other game wallets
|
||||
const SKIP = () => new Set(['0x7627fc78876948ac9d95c1c9eb061e7d6d647b70', '0x8b7d33849a2c4d92c985be31e46dc564ba901ad2', '0xcbe203312e0ea3b542da7a2e7f0a8a09db948f75'].concat(Object.values(wallets())));
|
||||
const FILE = () => path.join(R.dataDir, 'game-handoffs.json');
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { return {}; } }
|
||||
function init(deps) { R = deps; }
|
||||
const hourKey = t => new Date(t || Date.now()).toISOString().slice(0, 13);
|
||||
// a member was handed into a game: one tick in this hour's bucket (buckets older than 3 days are dropped)
|
||||
function handoff(slug) {
|
||||
try {
|
||||
const h = load(), k = hourKey(); h[k] = h[k] || {}; h[k][slug] = (h[k][slug] || 0) + 1;
|
||||
const cut = hourKey(Date.now() - 3 * 86400000); for (const key of Object.keys(h)) if (key < cut) delete h[key];
|
||||
fs.writeFileSync(FILE(), JSON.stringify(h));
|
||||
} catch (e) { /* counting must never break a hand-off */ }
|
||||
}
|
||||
function sentIn(since) { const h = load(), out = {}; const k0 = hourKey(since); for (const [k, m] of Object.entries(h)) if (k >= k0) for (const [slug, c] of Object.entries(m)) out[slug] = (out[slug] || 0) + c; return out; }
|
||||
// outgoing payouts from one game wallet since `since` (ms): { count, wei }
|
||||
async function payoutsFor(addr, since) {
|
||||
const out = { count: 0, wei: 0n }; if (!KEY()) return out;
|
||||
const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=0&endblock=99999999&sort=desc&page=1&offset=500&apikey=' + KEY();
|
||||
const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json(); const rows = Array.isArray(j.result) ? j.result : [];
|
||||
const skip = SKIP(), sinceS = Math.floor(since / 1000);
|
||||
for (const x of rows) {
|
||||
if (Number(x.timeStamp) < sinceS) break; // sorted newest first
|
||||
if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue;
|
||||
if (skip.has(String(x.to).toLowerCase())) continue;
|
||||
out.count++; out.wei += BigInt(x.value);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// everything the card needs: per game and totals, last 24 h
|
||||
async function gather(since) {
|
||||
const W = wallets(), sent = sentIn(since), games = [];
|
||||
const slugs = new Set([...Object.keys(W), ...Object.keys(sent)]);
|
||||
for (const slug of slugs) {
|
||||
const g = { slug, name: NAMES[slug] || slug, sentIn: sent[slug] || 0, payouts: 0, wei: 0n, error: null };
|
||||
if (W[slug]) { try { const p = await payoutsFor(W[slug], since); g.payouts = p.count; g.wei = p.wei; } catch (e) { g.error = e.message; } }
|
||||
games.push(g);
|
||||
}
|
||||
games.sort((a, b) => (b.sentIn - a.sentIn) || (Number(b.wei - a.wei)));
|
||||
const totals = games.reduce((t, g) => ({ sentIn: t.sentIn + g.sentIn, payouts: t.payouts + g.payouts, wei: t.wei + g.wei }), { sentIn: 0, payouts: 0, wei: 0n });
|
||||
return { games, totals, chainChecked: !!KEY() && Object.keys(W).length > 0 };
|
||||
}
|
||||
// ---- all-time running total of game payouts, for the admin P&L (Marty 2026-10-18) ----
|
||||
// Every outgoing POL send from each game wallet to a player, from the wallet's first transaction.
|
||||
// Kept in DATA_DIR/game-payouts-alltime.json per wallet { block, count, wei, players[] } and topped up
|
||||
// incrementally (only blocks after the last one seen), so after the first scan a refresh is one call per game.
|
||||
const AT_FILE = () => path.join(R.dataDir, 'game-payouts-alltime.json');
|
||||
let atState = null, atAt = 0, atBusy = null;
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
function atLoad() { if (!atState) { try { atState = JSON.parse(fs.readFileSync(AT_FILE(), 'utf8')); } catch (e) { atState = {}; } } return atState; }
|
||||
function atSave() { try { fs.writeFileSync(AT_FILE() + '.tmp', JSON.stringify(atState)); fs.renameSync(AT_FILE() + '.tmp', AT_FILE()); } catch (e) {} }
|
||||
async function atScan(slug, addr) {
|
||||
const st = atLoad(); let w = st[slug];
|
||||
if (!w || w.addr !== addr) w = st[slug] = { addr, block: 0, count: 0, wei: '0', players: [] };
|
||||
const skip = SKIP(), players = new Set(w.players); let wei = BigInt(w.wei), count = w.count, maxBlock = w.block; // committed only when the scan finishes, so a failed page never double-counts
|
||||
for (let page = 1; page <= 10; page++) { // Etherscan caps page*offset at 10,000; the next refresh carries on from the last block
|
||||
const url = 'https://api.etherscan.io/v2/api?chainid=137&module=account&action=txlist&address=' + addr + '&startblock=' + (w.block + 1) + '&endblock=99999999&sort=asc&page=' + page + '&offset=1000&apikey=' + KEY();
|
||||
const r = await fetch(url, { signal: AbortSignal.timeout(20000) }); const j = await r.json();
|
||||
if (!Array.isArray(j.result)) { if (/no transactions/i.test(String(j.message || ''))) break; throw new Error(String(j.result || j.message || 'etherscan')); }
|
||||
for (const x of j.result) {
|
||||
const b = Number(x.blockNumber); if (b > maxBlock) maxBlock = b;
|
||||
if (x.isError !== '0' || String(x.from).toLowerCase() !== addr || !x.value || x.value === '0') continue;
|
||||
const to = String(x.to).toLowerCase(); if (skip.has(to)) continue;
|
||||
count++; wei += BigInt(x.value); players.add(to);
|
||||
}
|
||||
if (j.result.length < 1000) break;
|
||||
await sleep(400);
|
||||
}
|
||||
w.block = maxBlock; w.count = count; w.wei = wei.toString(); w.players = [...players]; delete w.error;
|
||||
}
|
||||
async function atRefresh() {
|
||||
const W = wallets();
|
||||
for (const [slug, addr] of Object.entries(W)) { try { await atScan(slug, addr); } catch (e) { (atLoad()[slug] || {}).error = e.message; } await sleep(400); }
|
||||
atSave(); atAt = Date.now();
|
||||
}
|
||||
// { games: [{ slug, name, count, wei, players }], totals, at }; refreshed at most every 10 minutes, never blocks the page past 25 s
|
||||
async function allTime() {
|
||||
if (!KEY()) return { error: 'ETHERSCAN_KEY not set' };
|
||||
if (Date.now() - atAt > 600000 && !atBusy) atBusy = atRefresh().finally(() => { atBusy = null; });
|
||||
if (atBusy && !atAt) await Promise.race([atBusy, sleep(25000)]);
|
||||
const st = atLoad(), W = wallets(), games = [];
|
||||
for (const slug of Object.keys(W)) { const w = st[slug]; if (!w) continue; games.push({ slug, name: NAMES[slug] || slug, count: w.count, wei: w.wei, players: w.players.length, error: w.error || null }); }
|
||||
games.sort((a, b) => (BigInt(b.wei) > BigInt(a.wei) ? 1 : -1));
|
||||
return { games, at: atAt || null, scanning: !!atBusy };
|
||||
}
|
||||
module.exports = { init, handoff, gather, allTime, NAMES };
|
||||
@@ -0,0 +1,362 @@
|
||||
// Network hub sync (2026-11-12, Marty 2026-11-06: one membership from any door; the hub is the single identity).
|
||||
// Everything here sleeps unless HUB_ENABLED is on: server.js does not even init this module without it, so no file is
|
||||
// written, no route answers and no hook is wired. The InstantAdPay <-> LinkSpin direct sync (lssync.js / lsinbound.js)
|
||||
// keeps running exactly as before either way.
|
||||
//
|
||||
// Inbound (POST /api/hub/events, signed by the hub with HUB_SECRET: X-Hub-Ts + X-Hub-Sig = hex HMAC-SHA256(ts + newline +
|
||||
// raw body), 5-minute window). The hub only moves its cursor after a 2xx and may send an event twice:
|
||||
// member.joined someone joined at another door: /v1/resolve the person (and, climbing, any sponsor not here yet) and
|
||||
// hand the rows to lsinbound.receive, the same waiting-account path LinkSpin-first members take, with
|
||||
// joinedVia 'hub' and joinedRef 'hub:<door>'. First-platform rule as there: an account that already
|
||||
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
|
||||
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
|
||||
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
|
||||
// sponsor.changed ignored on purpose (2026-11-14): lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the
|
||||
// hub view does not expose, and someone the InstantAdPay contract holds never moves anyway.
|
||||
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
|
||||
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
|
||||
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
|
||||
// anything else ignored.
|
||||
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
|
||||
// in the log so one bad row cannot hold every later event back.
|
||||
//
|
||||
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
|
||||
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
|
||||
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
|
||||
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), all still one way:
|
||||
// - any later change to a member's username or sponsor goes to /v1/join again (names them; a sponsor only lands where the
|
||||
// hub has none), old members included, not only accounts made since the flag went on;
|
||||
// - a DELIBERATE sponsor change (sponsorfollow: adopt, rescue, release, expire->expiry, admin) goes to /v1/sponsor-change;
|
||||
// - every MemberActivated on the InstantAdPay contract goes to /v1/contract-bind (contract 'iap', the sponsor by wallet),
|
||||
// by email when the wallet belongs to an account here, else by wallet alone.
|
||||
// - every paid Purchase goes to /v1/contract-spend (2026-11-14, rule 2: the contract with money spent decides the network
|
||||
// sponsor when two contracts hold different ones).
|
||||
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
|
||||
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
|
||||
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
|
||||
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']);
|
||||
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expire', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
|
||||
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
|
||||
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||
const SITE = () => String(process.env.HUB_SITE || 'iap').trim().toLowerCase();
|
||||
const on = () => enabled() && !!URL_() && SECRET().length >= 32;
|
||||
const norm = v => String(v || '').trim().toLowerCase();
|
||||
const FILE = () => path.join(R.dataDir, 'hubsync.json');
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||
if (!st || typeof st !== 'object') st = {};
|
||||
st.since = Number(st.since) || Date.now(); // only accounts made after the flag first went on are reported as joins
|
||||
st.done = st.done || {}; st.tries = st.tries || {}; st.outbox = st.outbox || []; st.reported = st.reported || {};
|
||||
st.disagree = st.disagree || {}; st.log = st.log || [];
|
||||
st.stats = Object.assign({ batches: 0, events: 0, applied: 0, skipped: 0, ignored: 0, gaveUp: 0, sent: 0, refused: 0, sendErrors: 0 }, st.stats || {});
|
||||
return st;
|
||||
}
|
||||
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('hubsync save', e.message); } }
|
||||
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
||||
// deps: { dataDir, accounts, lsinbound }
|
||||
function init(deps) { R = deps; load(); save(); }
|
||||
|
||||
const sign = (ts, raw) => crypto.createHmac('sha256', SECRET()).update(String(ts) + '\n' + raw).digest('hex');
|
||||
function verify(headers, raw) {
|
||||
if (SECRET().length < 32) return false;
|
||||
const ts = String(headers['x-hub-ts'] || ''), sig = String(headers['x-hub-sig'] || '');
|
||||
if (!/^\d{10,16}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return false;
|
||||
const want = sign(ts, raw);
|
||||
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||
}
|
||||
async function hubPost(p, body, timeout) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
async function resolve(q) {
|
||||
const r = await hubPost('/v1/resolve', q);
|
||||
if (r.status !== 200) throw new Error('hub resolve ' + r.status);
|
||||
return (r.body && r.body.person) || null;
|
||||
}
|
||||
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
|
||||
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the InstantAdPay CONTRACT holds for them when it holds them
|
||||
// (person.locks.iap), never the plain network sponsor, which may come from another contract where they spent money
|
||||
const CONTRACT = 'iap';
|
||||
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; if (l) return (l.sponsor && l.sponsor.email) || null; return (p && p.sponsor && p.sponsor.email) || null; };
|
||||
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: sponsorFor(p), joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
|
||||
|
||||
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
|
||||
async function compare(email, hubSponsorEmail, how) {
|
||||
const sp = await R.accounts.sponsorOf(email); const here = sp ? norm(sp.email) : null; const there = norm(hubSponsorEmail) || null;
|
||||
const s = load();
|
||||
if (here === there) { delete s.disagree[email]; return; }
|
||||
s.disagree[email] = { at: Date.now(), iap: here, hub: there, how };
|
||||
}
|
||||
|
||||
async function memberJoined(ev) {
|
||||
if (norm(ev.data && ev.data.site) === SITE()) return 'own';
|
||||
const first = await resolve({ id: ev.personId });
|
||||
if (!first || !first.email) return first ? 'no-email' : 'unknown'; // the hub must give this site seeEmails
|
||||
if (first.blocked) return 'blocked';
|
||||
const email = norm(first.email); const A = R.accounts;
|
||||
const existing = await A.byEmail(email);
|
||||
const rows = [rowOf(first)]; const doors = { [email]: doorOf(first) }; const seen = new Set([email]);
|
||||
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
|
||||
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
|
||||
let p = first;
|
||||
for (let i = 0; i < MAX_UP && sponsorFor(p); i++) {
|
||||
const se = norm(sponsorFor(p)); if (seen.has(se) || await A.byEmail(se)) break;
|
||||
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
|
||||
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
|
||||
}
|
||||
const sum = await R.lsinbound.receive(rows, { via: 'hub', refOf: e => 'hub:' + (doors[e] || 'network') });
|
||||
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
||||
await compare(email, rows[0].sponsorEmail, 'hub-join');
|
||||
note({ type: 'joined', email, door: doors[email], created: sum ? sum.created : 0, existed: !!existing });
|
||||
return 'applied';
|
||||
}
|
||||
async function walletConnected(ev) {
|
||||
const p = await resolve({ id: ev.personId });
|
||||
if (!p || !p.email || !p.wallet || p.blocked) return 'skip';
|
||||
const a = await R.accounts.byEmail(p.email);
|
||||
if (!a) return 'not-here'; // member.joined makes the account; a wallet alone does not
|
||||
if (!R.accounts.isUnclaimedShell(a) || a.address) return 'kept'; // claimed accounts link their own wallet here
|
||||
const sum = await R.lsinbound.receive([rowOf(p)], { via: 'hub', refOf: () => 'hub:' + doorOf(p) });
|
||||
if (sum && sum.errors) throw new Error('lsinbound errors ' + sum.errors);
|
||||
return 'applied';
|
||||
}
|
||||
async function apply(ev) {
|
||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||
if (ev.type === 'wallet.connected') return walletConnected(ev);
|
||||
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
|
||||
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
|
||||
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
|
||||
return 'ignored';
|
||||
}
|
||||
function prune() {
|
||||
const s = load(); const seqs = Object.keys(s.done).map(Number).sort((a, b) => a - b);
|
||||
for (const q of seqs.slice(0, Math.max(0, seqs.length - KEEP_DONE))) delete s.done[q];
|
||||
}
|
||||
async function handle(events) {
|
||||
const s = load(); s.stats.batches++; let failed = null;
|
||||
for (const ev of Array.isArray(events) ? events : []) {
|
||||
const seq = Number(ev && ev.seq); if (!seq) continue;
|
||||
if (s.done[seq]) { s.stats.skipped++; continue; } // delivered twice: already applied
|
||||
s.stats.events++;
|
||||
try {
|
||||
const r = await apply(ev);
|
||||
s.done[seq] = Date.now(); delete s.tries[seq];
|
||||
if (r === 'applied') s.stats.applied++; else s.stats.ignored++;
|
||||
} catch (e) {
|
||||
s.tries[seq] = (s.tries[seq] || 0) + 1;
|
||||
console.error('hubsync event', seq, ev.type, e.message);
|
||||
if (s.tries[seq] >= EVENT_TRIES) { s.done[seq] = Date.now(); delete s.tries[seq]; s.stats.gaveUp++; note({ type: 'gave-up', seq, event: ev.type, error: String(e.message).slice(0, 160) }); continue; }
|
||||
failed = e; break; // answer 503: the hub sends this one (and everything after it) again
|
||||
}
|
||||
}
|
||||
prune(); save();
|
||||
return failed ? { status: 503, body: { error: 'retry' } } : { status: 200, body: { ok: true } };
|
||||
}
|
||||
// the POST /api/hub/events handler: { status, body }. Batches run one at a time.
|
||||
function receive(headers, raw) {
|
||||
if (!R || !enabled()) return Promise.resolve({ status: 404, body: { error: 'not found' } });
|
||||
if (!verify(headers, raw)) return Promise.resolve({ status: 401, body: { error: 'unauthorized' } });
|
||||
let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return Promise.resolve({ status: 400, body: { error: 'bad json' } }); }
|
||||
const run = chain_.then(() => handle(b.events)); chain_ = run.catch(() => {}); return run;
|
||||
}
|
||||
|
||||
// ---------- outbound ----------
|
||||
function enqueue(kind, email) {
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
}
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
|
||||
// accounts.onChange: a new account made here, or a later username / sponsor change on any account, goes to /v1/join;
|
||||
// a deliberate sponsor change also goes to /v1/sponsor-change
|
||||
function touch(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
(async () => {
|
||||
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
|
||||
if (!a || SHELL_ORIGINS.has(a.joinedVia)) return;
|
||||
const sp = await R.accounts.sponsorOf(e); const spE = sp ? norm(sp.email) : '';
|
||||
const key = (a.username || '') + '|' + spE;
|
||||
const rep = s.reported[e];
|
||||
if (!rep) { s.reported[e] = { u: a.username || null, k: key }; enqueue('join', e); } // new here, or an older member's first change since the flag
|
||||
else if (rep.k !== key) { rep.u = a.username || null; rep.k = key; enqueue('join', e); }
|
||||
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
|
||||
if (rec && DELIBERATE.has(rec.by) && norm(rec.sponsorEmail) === spE && Number(rec.at) > 0 && s.reported[e].sc !== Number(rec.at)) {
|
||||
s.reported[e].sc = Number(rec.at); enqueue('sponsor', e);
|
||||
}
|
||||
save();
|
||||
})().catch(err => console.error('hubsync touch', err.message));
|
||||
}
|
||||
// chain.onEvent (once across copies): a payout switch-on on the InstantAdPay contract goes to /v1/contract-bind
|
||||
function onChain(ev) {
|
||||
if (ev && ev.type === 'Purchase') return onPurchase(ev);
|
||||
if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return;
|
||||
(async () => {
|
||||
let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {}
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'bind', email: norm(ev.account), wallet: norm(ev.account), sponsorWallet: spW, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onChain', err.message));
|
||||
}
|
||||
// chain.onEvent: money paid into the InstantAdPay contract (Purchase with POL in) goes to /v1/contract-spend (Marty 2026-11-14,
|
||||
// rule 2: when two contracts hold different sponsors, the one with money spent decides the network sponsor). Keyed by the
|
||||
// buyer's position wallet, the same key as its bind, so the bind is always sent first; the tx hash makes a resend count once.
|
||||
// A 404 (bind not there yet, or a linked extra position the hub does not know) is retried like any other miss.
|
||||
function onPurchase(ev) {
|
||||
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
|
||||
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } // nothing paid in: not a spend
|
||||
(async () => {
|
||||
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'spend', email: w, wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onPurchase', err.message));
|
||||
}
|
||||
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
|
||||
function wallet(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
(async () => {
|
||||
const a = await R.accounts.byEmail(email);
|
||||
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
|
||||
})().catch(err => console.error('hubsync wallet', err.message));
|
||||
}
|
||||
// sponsorfollow / tank.js label a window expiry 'expire'; the hub (and its DELIBERATE list) calls it 'expiry' (fixed 2026-11-15:
|
||||
// before, IAP window-expiry moves never reached the hub as a sponsor change)
|
||||
const HUB_BY = { expire: 'expiry' };
|
||||
const hubBy = by => HUB_BY[by] || by;
|
||||
const ROUTE = { join: '/v1/join', wallet: '/v1/wallet', sponsor: '/v1/sponsor-change', bind: '/v1/contract-bind', spend: '/v1/contract-spend' };
|
||||
async function bodyFor(item) {
|
||||
if (item.kind === 'spend') {
|
||||
let owner = null; try { owner = (await R.accounts.byAddress(item.wallet)) || (R.accounts.positionOwner ? await R.accounts.positionOwner(item.wallet) : null); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, cents: item.cents, tx: item.tx || undefined, at: item.paidAt };
|
||||
}
|
||||
if (item.kind === 'bind') {
|
||||
let owner = null; try { owner = await R.accounts.byAddress(item.wallet); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, sponsorRef: item.sponsorWallet || '' };
|
||||
}
|
||||
const a = await R.accounts.byEmail(item.email); if (!a) return null;
|
||||
if (item.kind === 'sponsor') {
|
||||
const sp = await R.accounts.sponsorOf(a.email); const rec = R.follow && R.follow.get ? R.follow.get(a.email) : null;
|
||||
if (!rec || !DELIBERATE.has(rec.by) || norm(rec.sponsorEmail) !== (sp ? norm(sp.email) : '')) return null; // superseded since
|
||||
return { email: a.email, sponsorEmail: sp ? sp.email : null, by: hubBy(rec.by) };
|
||||
}
|
||||
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
|
||||
const sp = await R.accounts.sponsorOf(a.email);
|
||||
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
|
||||
}
|
||||
async function flush(force) { // force (tests, admin): ignore the backoff wait
|
||||
if (!R || !on() || sending) return { skipped: true };
|
||||
sending = true; const s = load(); const now = Date.now(); const held = new Set(); let sent = 0;
|
||||
try {
|
||||
for (const item of s.outbox.slice()) {
|
||||
if (held.has(item.email)) continue; // keep each member's calls in order (join before wallet)
|
||||
if (item.next > now && !force) { held.add(item.email); continue; }
|
||||
const drop = (why, code) => { s.outbox.splice(s.outbox.indexOf(item), 1); if (why) note({ type: 'out-' + why, kind: item.kind, email: item.email, code: code || null }); };
|
||||
let r = null;
|
||||
try {
|
||||
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
|
||||
r = await hubPost(ROUTE[item.kind] || '/v1/wallet', body);
|
||||
} catch (e) { r = { status: 0, body: { error: e.message } }; }
|
||||
const code = (r.body && r.body.error) || null;
|
||||
if (r.status >= 200 && r.status < 300) {
|
||||
drop(null); s.stats.sent++; sent++;
|
||||
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
|
||||
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked') || (item.kind === 'sponsor' && r.status === 404)) {
|
||||
drop('refused', code); s.stats.refused++;
|
||||
} else {
|
||||
item.tries++; s.stats.sendErrors++;
|
||||
if (item.tries >= OUT_TRIES) drop('gave-up', code || String(r.status));
|
||||
else { item.next = now + Math.min(3600000, 30000 * Math.pow(2, item.tries)); held.add(item.email); }
|
||||
}
|
||||
save();
|
||||
}
|
||||
} finally { sending = false; }
|
||||
return { sent, waiting: s.outbox.length };
|
||||
}
|
||||
// password sign-ups do not fire accounts.onChange until they pick a username: every 10 minutes, any account made here since
|
||||
// the flag went on that the hub has not heard about yet is queued
|
||||
async function reconcile() {
|
||||
if (!R || !on()) return { skipped: true };
|
||||
const s = load(); let queued = 0;
|
||||
for (const a of await R.accounts.listAll(1e6)) {
|
||||
const e = norm(a.email);
|
||||
if (!e || s.reported[e] || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) continue;
|
||||
s.reported[e] = { u: a.username || null }; s.outbox.push({ kind: 'join', email: e, at: Date.now(), tries: 0, next: 0 }); queued++;
|
||||
}
|
||||
if (queued) { save(); kick(); }
|
||||
return { queued };
|
||||
}
|
||||
function start() {
|
||||
if (interval) return;
|
||||
interval = setInterval(() => flush().catch(e => console.error('hubsync flush', e.message)), 30000);
|
||||
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
|
||||
for (const t of [interval, rec]) if (t.unref) t.unref();
|
||||
}
|
||||
// ---------- rule 3: the holding tank asks the hub (Marty 2026-11-14) ----------
|
||||
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for. tank.js asks
|
||||
// through its hooks (networkHeld, networkLocked, network); server.js wires them only with HUB_ENABLED, so with the flag off
|
||||
// the tank works exactly as before. One /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10
|
||||
// minutes. CONSERVATIVE when the hub cannot be reached: the last answer stands for up to 1 hour, after that the person is
|
||||
// held ('unknown', not offered, not moved to the tank, not auto-assigned) until the hub answers again. A held tank for a
|
||||
// while is the safe side; offering someone a contract already holds is not. After a failed call the hub is left alone
|
||||
// for 2 minutes (page views must not each wait for a timeout).
|
||||
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
|
||||
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
|
||||
async function refreshHeld(emails, timeout) {
|
||||
const run = heldBusy.then(async () => {
|
||||
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
|
||||
if (!miss.length || now < heldDownUntil) return;
|
||||
try {
|
||||
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
|
||||
const part = miss.slice(i, i + HELD_CHUNK);
|
||||
const r = await hubPost('/v1/locked', { emails: part, detail: true, ids: true }, timeout || 5000); // ids: hub id + door per row (a hub without it ignores the flag)
|
||||
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
|
||||
if (held.size > 60000) held.clear();
|
||||
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
|
||||
}
|
||||
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
|
||||
});
|
||||
heldBusy = run.catch(() => {}); return run;
|
||||
}
|
||||
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
|
||||
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' for the ones the tank must not offer
|
||||
async function heldAmong(accts, opts) {
|
||||
const out = new Map(); if (!R || !on()) return out;
|
||||
const emails = [...new Set((accts || []).map(a => norm(a && a.email)).filter(Boolean))]; if (!emails.length) return out;
|
||||
await refreshHeld(emails, opts && opts.timeout);
|
||||
const now = Date.now(); for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
|
||||
return out;
|
||||
}
|
||||
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
|
||||
async function lockedAnywhere(email) {
|
||||
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
|
||||
return w === 'locked' || w === 'unknown' ? w : null;
|
||||
}
|
||||
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
|
||||
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
|
||||
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
|
||||
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
|
||||
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
|
||||
async function hubSponsor(email) {
|
||||
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
|
||||
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
|
||||
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
|
||||
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, InstantAdPay contract' : 'network hub' } : null;
|
||||
}
|
||||
|
||||
// the hub id and first door of a person the tank cache holds (5xYourTeam draft pool, 2026-11-15): { id, door } | null. Read-only, no call.
|
||||
function hubInfo(email) { const c = held.get(norm(email)); return c && c.row && c.row.id ? { id: c.row.id, door: c.row.door || null } : null; }
|
||||
function adminView() {
|
||||
const s = load();
|
||||
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
|
||||
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
||||
}
|
||||
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
||||
@@ -0,0 +1,72 @@
|
||||
// Email intake for the help desk (2026-10-16): SendGrid Inbound Parse posts every message sent to the support hosts
|
||||
// (support@help.instantadpay.com, reply+<ref>@help.instantadpay.com, anything @linkspin.app) here as multipart/form-data.
|
||||
// We turn it into a new ticket or a reply on an existing one (tickets.ingestEmail), after dropping robots: bounces,
|
||||
// auto-replies, bulk mail and our own messages, so two autoresponders can never ping-pong. The URL carries a secret key
|
||||
// (env SUPPORT_INBOUND_KEY); SendGrid retries anything that is not 2xx, so the route always answers 200 once the key passes.
|
||||
'use strict';
|
||||
let tickets = null, accounts = null;
|
||||
function init(d) { tickets = d.tickets; accounts = d.accounts || null; }
|
||||
const key = () => String(process.env.SUPPORT_INBOUND_KEY || '').trim();
|
||||
|
||||
// a small multipart reader: text fields only, files skipped (attachments are not kept yet)
|
||||
function parseMultipart(buf, contentType) {
|
||||
const m = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType || ''); if (!m) return {};
|
||||
const boundary = Buffer.from('--' + (m[1] || m[2]).trim());
|
||||
const out = {}; let pos = buf.indexOf(boundary);
|
||||
while (pos >= 0) {
|
||||
const next = buf.indexOf(boundary, pos + boundary.length); if (next < 0) break;
|
||||
const part = buf.slice(pos + boundary.length + 2, next - 2); // skip CRLF after the boundary and before the next
|
||||
const sep = part.indexOf('\r\n\r\n');
|
||||
if (sep > 0) {
|
||||
const head = part.slice(0, sep).toString('utf8');
|
||||
const nm = /name="([^"]+)"/i.exec(head);
|
||||
if (nm && !/filename=/i.test(head)) out[nm[1]] = part.slice(sep + 4).toString('utf8');
|
||||
}
|
||||
pos = next;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const header = (raw, name) => { const m = new RegExp('^' + name + ':\\s*([^\\r\\n]*(?:\\r?\\n[ \\t][^\\r\\n]*)*)', 'im').exec(raw || ''); return m ? m[1].replace(/\r?\n[ \t]+/g, ' ').trim() : ''; };
|
||||
const addrOf = s => { const m = /<([^>]+)>/.exec(s || ''); return String(m ? m[1] : s || '').trim().toLowerCase(); };
|
||||
const nameOf = s => { const m = /^\s*"?([^"<]*?)"?\s*</.exec(s || ''); return m ? m[1].trim() : ''; };
|
||||
const ROBOT_FROM = /(mailer-daemon|postmaster|no-?reply|do-?not-?reply|bounce|notifications?@)/i;
|
||||
|
||||
// keep what the person wrote, not the quoted history under it
|
||||
function stripQuoted(text) {
|
||||
let t = String(text || '').replace(/\r\n/g, '\n');
|
||||
const cuts = [/^On .{3,200}wrote:\s*$/m, /^-{2,}\s*Original Message\s*-{2,}/im, /^From:\s.+\n(?:Sent|Date):\s/m, /^_{10,}\s*$/m];
|
||||
for (const re of cuts) { const m = re.exec(t); if (m) t = t.slice(0, m.index); }
|
||||
return t.split('\n').filter(l => !/^\s*>/.test(l)).join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
const htmlToText = h => String(h || '').replace(/<(br|\/p|\/div)[^>]*>/gi, '\n').replace(/<[^>]+>/g, '').replace(/ /g, ' ').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
const perSender = new Map(); // sender -> [timestamps], at most 20 messages an hour become tickets or replies
|
||||
function flood(addr) { const now = Date.now(); const a = (perSender.get(addr) || []).filter(t => now - t < 3600000); a.push(now); perSender.set(addr, a); return a.length > 20; }
|
||||
|
||||
// returns a short outcome string for the log
|
||||
async function handle(buf, contentType) {
|
||||
const f = parseMultipart(buf, contentType);
|
||||
const raw = f.headers || '';
|
||||
const from = addrOf(f.from); if (!from || !/@/.test(from)) return 'no sender';
|
||||
let rcpts = []; try { rcpts = (JSON.parse(f.envelope || '{}').to || []).map(addrOf); } catch (e) {}
|
||||
if (!rcpts.length) rcpts = String(f.to || '').split(',').map(addrOf);
|
||||
const auto = header(raw, 'Auto-Submitted'), prec = header(raw, 'Precedence');
|
||||
if ((auto && !/^no$/i.test(auto)) || /bulk|junk|list/i.test(prec) || header(raw, 'X-Autoreply') || header(raw, 'X-Autorespond') || ROBOT_FROM.test(from)) return 'robot dropped: ' + from;
|
||||
if (/@(instantadpay\.com|help\.instantadpay\.com|linkspin\.app)$/.test(from)) return 'own address dropped';
|
||||
if (flood(from)) return 'flood dropped: ' + from;
|
||||
// support@instantadpay.com is forwarded by NameSilo to iap-support@linkspin.app (its forwarder will not deliver to our own
|
||||
// help. subdomain), so that one address means an InstantAdPay ticket even though it arrives on the LinkSpin host
|
||||
const iapAlias = r => /^iap-support@linkspin\.app$/.test(r);
|
||||
const platform = rcpts.some(r => /@linkspin\.app$/.test(r) && !iapAlias(r)) ? 'linkspin' : 'iap';
|
||||
let subject = String(f.subject || '').replace(/\s+/g, ' ').trim();
|
||||
const plus = rcpts.map(r => /^reply\+((?:iap|ls)-\d{4,9})@/.exec(r)).find(Boolean); // the reply-to we put on ticket mail
|
||||
if (plus) { const ref = plus[1].toUpperCase(); if (!subject.toUpperCase().includes(ref)) subject = '[' + ref + '] ' + subject; }
|
||||
const body = stripQuoted(f.text || htmlToText(f.html)) || '(empty message)';
|
||||
const r = await tickets.ingestEmail({ from, name: nameOf(f.from), subject, text: body, platform, confirm: true,
|
||||
// new tickets only from member emails (Marty 2026-10-24); LinkSpin-first members are InstantAdPay accounts too (lsinbound)
|
||||
canOpen: accounts ? async addr => { try { return !!(await accounts.byEmail(addr)); } catch (e) { return true; } } : null,
|
||||
messageId: header(raw, 'Message-ID'), inReplyTo: header(raw, 'In-Reply-To'), references: header(raw, 'References') });
|
||||
if (r && r.error) return 'refused: ' + r.error;
|
||||
return (r.created ? 'new ticket ' : 'reply on ') + (r.ticket && r.ticket.ref) + ' from ' + from;
|
||||
}
|
||||
module.exports = { init, key, handle, stripQuoted, parseMultipart };
|
||||
@@ -0,0 +1,76 @@
|
||||
// Knowledge-base seeds that are not CANNED fast-path answers (kb.js): the public FAQ on the home page,
|
||||
// the Platform Facts page (/facts), the wallets guide's Common questions, and support replies worth
|
||||
// keeping. An entry here that nobody has edited in Admin > Knowledge base is refreshed when its text
|
||||
// changes in this file; edit it in the admin pane and it becomes the admin's own.
|
||||
// House rules: plain words, no em dashes, never a promise of income.
|
||||
const FAQ = [
|
||||
{ id: 'f-coinbase', title: 'Can I use my regular Coinbase account?', source: 'ticket',
|
||||
questions: ['Can I use my regular Coinbase account?', 'Can I use Coinbase?', 'Can I connect my Coinbase exchange account?', 'How do I connect Coinbase?', 'Can I pay from my exchange account?'],
|
||||
tags: ['coinbase', 'exchange account', 'connect coinbase', 'wallet', 'safepal'],
|
||||
answer: 'Your regular Coinbase account won\'t connect here. Coinbase is an exchange: they hold the crypto for you, which works for buying and selling. InstantAdPay runs on a smart contract on Polygon, and to buy a package or receive payouts you sign that contract yourself, which only a wallet you control can do. You don\'t need Coinbase Wallet; we recommend SafePal (free, phone app or desktop browser extension). Install it, write down your recovery phrase, add Polygon (POL) and copy your address, send POL from Coinbase choosing the Polygon network (send a small test first), then open instantadpay.com in SafePal\'s browser (or the browser with the extension), sign in with your email and tap Link wallet (one free signature). You only need a wallet to buy a package or receive payouts.' },
|
||||
{ id: 'f-how-fast', title: 'How fast do I really get paid?', source: 'faq',
|
||||
questions: ['How fast do I get paid?', 'When does my commission arrive?', 'Is there an approval step for payouts?'],
|
||||
tags: ['payout', 'speed', 'same transaction', 'ledger'],
|
||||
answer: 'Payouts happen inside the very transaction that pays for the package. There is no approval step and nobody holding funds. Your share lands in your own wallet the moment your referral\'s purchase confirms, and the public ledger at https://instantadpay.com/ledger lets you watch each one go through.' },
|
||||
{ id: 'f-what-buying', title: 'What am I actually buying?', source: 'faq',
|
||||
questions: ['What am I actually buying?', 'What is the product?', 'Do bigger packages give bonus credits?'],
|
||||
tags: ['product', 'ad delivery', 'credits', 'packages'],
|
||||
answer: 'You are buying ad delivery. Credits are one cent of delivery each, recorded on-chain when you buy. The $5 package mints 500 credits, and the bigger packages mint bonus credits on top, up to 70,000 on the $500 package. Earnings only come from referring people who also buy real ad delivery, and the contract splits every purchase automatically. Nothing is a promise of income.' },
|
||||
{ id: 'f-refunds', title: 'Refunds', source: 'faq',
|
||||
questions: ['Can I get a refund?', 'Is my purchase refundable?', 'Can a POL payment be reversed or charged back?', 'What happens if my campaign fails to deliver?'],
|
||||
tags: ['refund', 'chargeback', 'reverse payment', 'final'],
|
||||
answer: 'Payments are on-chain and final: a POL payment cannot be reversed, charged back or refunded to a wallet. Unused credits stay in your balance until you spend them. If a campaign fails to deliver because of a platform problem, the platform may return the affected credits to your balance, labeled as returned purchased credits.' },
|
||||
{ id: 'f-credits-transfer', title: 'Can credits be transferred or turned into POL?', source: 'faq',
|
||||
questions: ['Can I transfer credits to another member?', 'Can I give my credits to a friend?', 'Can I sell my credits or exchange them for POL?', 'Are credits a token?'],
|
||||
tags: ['credits', 'transfer', 'cash value', 'token'],
|
||||
answer: 'No. Credits are advertising credit, not currency. They cannot be transferred between members and cannot be exchanged back into POL or cash. Purchased credits are recorded on-chain and burned as your campaigns spend them; earned credits (welcome, viewing, visits, promo codes) are kept by the site and labeled separately.' },
|
||||
{ id: 'f-price-feed', title: 'How the POL price of a package is set', source: 'faq',
|
||||
questions: ['How is the POL price calculated?', 'Why did the POL amount change?', 'What price feed do you use?'],
|
||||
tags: ['price', 'chainlink', 'pol price', 'rate'],
|
||||
answer: 'Prices are set in US dollars and paid in POL. The contract converts the dollar price to POL at the moment of purchase using the Chainlink POL/USD price feed on Polygon, so the POL amount moves with the market. If the feed goes quiet, the contract uses the last fresh price for up to 24 hours, then pauses new sales until the feed recovers. Any package price change waits 24 hours before it takes effect.' },
|
||||
{ id: 'f-contract', title: 'The contract address and network', source: 'faq',
|
||||
questions: ['What is the contract address?', 'Which network is the contract on?', 'Is the contract verified?', 'Can the split be changed?'],
|
||||
tags: ['contract', 'address', 'polygonscan', 'verified', 'polygon'],
|
||||
answer: 'InstantAdPay runs on Polygon mainnet (chain id 137). The contract is 0xBE1ECA72AFF47d13D8E907e523F55eB9e2d365E0 and its source is verified and public. The percentages and qualification rules are constants in the code, there is no function that changes them, and the contract holds no member funds. The plain-language review is at https://instantadpay.com/contract and the reference facts at https://instantadpay.com/facts.' },
|
||||
{ id: 'f-platform-share', title: 'Where the platform share goes', source: 'faq',
|
||||
questions: ['Where does the 20 percent platform share go?', 'What are the platform wallets?', 'What happens to a share nobody qualifies for?'],
|
||||
tags: ['platform', 'platform wallets', 'fees', 'pass-up'],
|
||||
answer: 'The 20 percent platform share is two fixed 10 percent fees to platform wallet A (0x7627fc78876948ac9d95c1c9eb061e7d6d647b70) and B (0x8b7d33849a2c4d92c985be31e46dc564ba901ad2). Platform income pays for operations, development, marketing and the game rewards. If nobody within 25 steps qualifies for a level, that share goes to wallet A, and every pass-up is recorded on-chain with the reason. Overpayment is returned to the buyer in the same transaction.' },
|
||||
{ id: 'f-active-viewing', title: 'Why the video or timer paused', source: 'faq',
|
||||
questions: ['Why did my video ad pause?', 'Why did the countdown stop?', 'Why was my view not counted?'],
|
||||
tags: ['video', 'timer', 'countdown', 'paused', 'anti-fraud'],
|
||||
answer: 'Viewing is active only: video ads pause when you switch tabs or the window loses focus, and viewing and visit timers only count while the page is in front. The server also checks the elapsed time, so a view cannot be credited early. Keep the tab in front until the countdown finishes and pass the quick check.' },
|
||||
{ id: 'f-game-rewards', title: 'Where game POL rewards come from', source: 'faq',
|
||||
questions: ['Where do the game rewards come from?', 'Are game rewards guaranteed?', 'Why did a game reward not pay?'],
|
||||
tags: ['games', 'rewards', 'pool', 'pol'],
|
||||
answer: 'The network games pay small POL rewards for gameplay milestones from game wallets and reward pools the company tops up from platform income (some games also fund a pool from in-game sales). Rewards are per action, paid while the pool covers them, and never guaranteed. You sign in to every game with your InstantAdPay account, so your sponsor carries across them.' },
|
||||
{ id: 'f-not-investment', title: 'What InstantAdPay is not', source: 'faq',
|
||||
questions: ['Is this an investment?', 'Is there guaranteed income?', 'Does InstantAdPay hold my money?'],
|
||||
tags: ['investment', 'income', 'guarantee', 'custody', 'disclaimer'],
|
||||
answer: 'InstantAdPay is an advertising platform with a referral program, not an investment, token sale or security. Credits are not a token and have no cash value. It does not hold member money: payments are split by the contract in the same transaction. And it is not a guarantee of income: referral payouts happen only when real advertising is bought in your line.' },
|
||||
{ id: 'f-how-much-pol', title: 'How much POL do I need?', source: 'faq',
|
||||
questions: ['How much POL do I need?', 'How much POL for fees?', 'What does a package cost in POL?'],
|
||||
tags: ['pol', 'fees', 'gas', 'buy packages'],
|
||||
answer: 'The Buy packages tab shows the live POL cost of each package. Have that plus 2 or 3 POL for network fees; there is no other cost. Trust Wallet users should keep about double, because Trust blocks a purchase that spends most of the wallet.' },
|
||||
{ id: 'f-moonpay-declined', title: 'MoonPay declined my card', source: 'faq',
|
||||
questions: ['Why did MoonPay decline my card?', 'My card was refused buying POL', 'MoonPay will not take my payment'],
|
||||
tags: ['moonpay', 'card', 'declined', 'buy pol'],
|
||||
answer: 'Some banks block crypto purchases. Try a different card, Apple Pay or Google Pay, or buy POL on an exchange and withdraw it to your own wallet on the Polygon network. MoonPay is an independent provider with its own fees, limits and a first-time ID check.' },
|
||||
{ id: 'f-same-wallet-positions', title: 'One wallet, one position', source: 'faq',
|
||||
questions: ['Can I use the same wallet for more than one position?', 'How do I add positions for Qualified Start?'],
|
||||
tags: ['wallet', 'position', 'qualified start', 'metamask'],
|
||||
answer: 'One address is one position on the contract. For Qualified Start, add extra accounts inside MetaMask, each with its own address, and link them on the Buy packages tab. The three Qualified Start videos in Training walk through it.' },
|
||||
{ id: 'f-exchange-withdraw', title: 'Sending POL from an exchange', source: 'faq',
|
||||
questions: ['How do I send POL from Binance or Kraken?', 'Which network do I pick when withdrawing from an exchange?', 'I sent POL on the wrong network'],
|
||||
tags: ['exchange', 'withdraw', 'network', 'polygon', 'binance', 'kraken'],
|
||||
answer: 'Coinbase, Kraken, Binance and most exchanges sell POL. Withdraw it to your own wallet address and pick the Polygon network on the withdrawal screen, never MATIC on Ethereum or another chain. Sending on the wrong network can lose the funds, so send a small test first.' },
|
||||
{ id: 'f-recovery-phrase', title: 'Recovery phrase and scam safety', source: 'faq',
|
||||
questions: ['Someone asked for my recovery phrase', 'Will support ever ask for my private key?', 'Someone messaged me asking for money'],
|
||||
tags: ['recovery phrase', 'private key', 'scam', 'security'],
|
||||
answer: 'Never share your recovery phrase or private key with anyone. Nobody from InstantAdPay will ever ask for them, and nobody from InstantAdPay will message you first asking for money or wallet access. If someone does, do not reply, and tell support through Help at https://instantadpay.com/my#help.' },
|
||||
{ id: 'f-conv-thankyou', title: 'Conversion tracking with Aweber or GetResponse', source: 'faq',
|
||||
questions: ['How do I track sign-ups from my ads?', 'Where do I put the goal pixel?', 'How do I use conversion tracking with Aweber?', 'How do I use conversion tracking with GetResponse?', 'My autoresponder thank-you page is not mine, can I still track?'],
|
||||
tags: ['conversion tracking', 'goal pixel', 'landing tag', 'aweber', 'getresponse', 'thank you page', 'autoresponder'],
|
||||
answer: 'Open Campaigns > Conversion tracking, add a goal (like subscriber), then copy its two snippets: the landing tag goes on the page your ad points to, the goal pixel on your thank-you page. Set your autoresponder\'s thank-you (success) page to a page on YOUR site that carries the goal pixel. Aweber: in your sign-up form settings, choose \'Thank You Page: custom page\' and paste your page\'s address. GetResponse: in the form or landing page settings, pick \'Thank-you page: custom URL\' and paste your page\'s address. If you cannot change it, the pixel can still count through the cookie or the 24-hour match, just less surely. Use Send a test conversion to check the pixel; tests never count in your numbers.' },
|
||||
];
|
||||
module.exports = { FAQ };
|
||||
@@ -0,0 +1,280 @@
|
||||
// Knowledge base behind the site assistant (Marty's support-desk plan, 2026-10-20).
|
||||
// The chatbot answers from maintained entries, and good support replies become entries.
|
||||
//
|
||||
// An entry: { id, title, questions[], answer, tags[], pattern, handoff, order, source, ticketRef,
|
||||
// updated, created, edited, deleted, seedHash }
|
||||
// pattern optional regex (case-insensitive). Entries with one are the instant CANNED fast path:
|
||||
// the first pattern that matches (lowest order) is the reply, no AI call. The CANNED list
|
||||
// in chatbot.js seeds these, so there is ONE source: edit the answer here and the fast
|
||||
// path serves the new text.
|
||||
// source canned | faq | ticket | admin
|
||||
//
|
||||
// Retrieval: BM25 over title, question variants and tags, plus the answer text at a low weight, with
|
||||
// word bigrams so phrase overlap counts more than scattered words. No embeddings, no external calls.
|
||||
// The top hits go into the AI system prompt as "Knowledge base" context (chatbot.js).
|
||||
//
|
||||
// Seeds stay in step with the code: an entry that came from a seed and was never edited in the admin
|
||||
// pane is refreshed when the seed text changes; an edited one is left alone; a deleted seed stays
|
||||
// deleted (tombstone row), and a seed dropped from the code is retired unless an admin edited it.
|
||||
//
|
||||
// Dual store like the other modules: MySQL table kb_entries when DATABASE_URL is set, else
|
||||
// DATA_DIR/kb.json (local dev and the QA harness).
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const db = require('./db');
|
||||
|
||||
let DATA_DIR = null, SEEDS = [], ready = null;
|
||||
let cache = null, cacheAt = 0, index = null;
|
||||
const TTL = 30000; // two app copies run during a deploy, and MySQL is shared: re-read now and then
|
||||
|
||||
// ---------------------------------------------------------------- text + scoring (pure, unit-tested)
|
||||
const STOP = new Set(('a an and are as at be been being but by can could do does did doing for from has have having how i if in into is it its '
|
||||
+ 'me my of on or our ours so than that the their them then there these they this those to too us was we were what when where which who whom why '
|
||||
+ 'will with would you your yours im ive id am just also any about please hi hello hey thanks thank ok okay really very much some there here '
|
||||
+ 'should shall may might must anyone someone something thing things want wanted like know tell').split(' '));
|
||||
const SYN = { paid: 'pay', payment: 'pay', payments: 'pay', paying: 'pay', withdrawal: 'withdraw', withdrawals: 'withdraw', cashout: 'withdraw',
|
||||
signup: 'join', register: 'join', registration: 'join', joining: 'join', joined: 'join', login: 'log', logged: 'log', logout: 'log', signin: 'log',
|
||||
wallets: 'wallet', email: 'email', mail: 'email', pol: 'pol', matic: 'pol', prices: 'price', pricing: 'price', cost: 'price', costs: 'price',
|
||||
ads: 'ad', advert: 'ad', adverts: 'ad', advertising: 'ad', referrals: 'referral', refer: 'referral', referring: 'referral', referred: 'referral' };
|
||||
function stem(w) {
|
||||
if (SYN[w]) return SYN[w];
|
||||
if (w.length > 6 && w.endsWith('able')) return w.slice(0, -4);
|
||||
if (w.length > 5 && w.endsWith('ing')) return w.slice(0, -3);
|
||||
if (w.length > 4 && w.endsWith('ies')) return w.slice(0, -3) + 'y';
|
||||
if (w.length > 4 && w.endsWith('ed') && !w.endsWith('eed')) return w.slice(0, -2);
|
||||
if (w.length > 3 && w.endsWith('s') && !w.endsWith('ss') && !w.endsWith('us')) return w.slice(0, -1);
|
||||
return w;
|
||||
}
|
||||
function words(text) {
|
||||
return String(text || '').toLowerCase().replace(/['’]/g, '').replace(/[^a-z0-9$]+/g, ' ').split(' ')
|
||||
.filter(w => w && !STOP.has(w) && (w.length > 1 || /\d/.test(w))).map(stem);
|
||||
}
|
||||
// unigrams + bigrams of the content words: "coinbase account" scores as a phrase, not two loose words
|
||||
function terms(text) {
|
||||
const w = words(text), out = w.slice();
|
||||
for (let i = 0; i + 1 < w.length; i++) out.push(w[i] + '_' + w[i + 1]);
|
||||
return out;
|
||||
}
|
||||
const FIELDS = { title: 2.0, questions: 2.5, tags: 2.0, answer: 0.35 };
|
||||
const K1 = 1.2, B = 0.75;
|
||||
function fieldText(e, f) {
|
||||
if (f === 'questions') return (e.questions || []).join(' . ');
|
||||
if (f === 'tags') return (e.tags || []).join(' . ');
|
||||
return e[f] || '';
|
||||
}
|
||||
function buildIndex(entries) {
|
||||
const docs = entries.map(e => {
|
||||
const d = { e, f: {} };
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const t = terms(fieldText(e, f)), tf = new Map();
|
||||
for (const x of t) tf.set(x, (tf.get(x) || 0) + 1);
|
||||
d.f[f] = { tf, len: t.length };
|
||||
}
|
||||
return d;
|
||||
});
|
||||
const df = new Map(), avg = {};
|
||||
for (const f of Object.keys(FIELDS)) avg[f] = docs.reduce((s, d) => s + d.f[f].len, 0) / Math.max(1, docs.length) || 1;
|
||||
for (const d of docs) {
|
||||
const seen = new Set();
|
||||
for (const f of Object.keys(FIELDS)) for (const t of d.f[f].tf.keys()) seen.add(t);
|
||||
for (const t of seen) df.set(t, (df.get(t) || 0) + 1);
|
||||
}
|
||||
return { docs, df, avg, n: docs.length };
|
||||
}
|
||||
function rank(idx, query, k) {
|
||||
if (!idx || !idx.n) return [];
|
||||
const qt = [...new Set(terms(query))];
|
||||
if (!qt.length) return [];
|
||||
const out = [];
|
||||
for (const d of idx.docs) {
|
||||
let s = 0;
|
||||
for (const t of qt) {
|
||||
const n = idx.df.get(t); if (!n) continue;
|
||||
const idf = Math.log(1 + (idx.n - n + 0.5) / (n + 0.5)) * (t.includes('_') ? 1.5 : 1);
|
||||
for (const f of Object.keys(FIELDS)) {
|
||||
const tf = d.f[f].tf.get(t); if (!tf) continue;
|
||||
s += FIELDS[f] * idf * (tf * (K1 + 1)) / (tf + K1 * (1 - B + B * d.f[f].len / idx.avg[f]));
|
||||
}
|
||||
}
|
||||
if (s > 0) out.push({ entry: d.e, score: Math.round(s * 100) / 100 });
|
||||
}
|
||||
out.sort((a, b) => b.score - a.score);
|
||||
return out.slice(0, k || 5);
|
||||
}
|
||||
// keep hits that are close to the best one, and only when the best is a real match
|
||||
const MIN_SCORE = 3;
|
||||
function relevant(hits) {
|
||||
if (!hits.length || hits[0].score < MIN_SCORE) return [];
|
||||
const floor = Math.max(MIN_SCORE, hits[0].score * 0.3);
|
||||
return hits.filter(h => h.score >= floor);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- store
|
||||
const row = r => ({ id: r.id, title: r.title, questions: parse(r.questions, []), answer: r.answer, tags: parse(r.tags, []), pattern: r.pattern || '',
|
||||
handoff: !!r.handoff, order: r.ord == null ? null : Number(r.ord), source: r.source, ticketRef: r.ticket_ref || '', seedHash: r.seed_hash || '',
|
||||
edited: !!r.edited, deleted: !!r.deleted, created: Number(r.created), updated: Number(r.updated) });
|
||||
function parse(s, d) { try { const v = JSON.parse(s || ''); return Array.isArray(v) ? v : d; } catch (e) { return d; } }
|
||||
const D = {
|
||||
async ensure() {
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS kb_entries (
|
||||
id VARCHAR(64) PRIMARY KEY,
|
||||
title VARCHAR(200) NOT NULL,
|
||||
questions TEXT NULL,
|
||||
answer TEXT NOT NULL,
|
||||
tags VARCHAR(800) NULL,
|
||||
pattern TEXT NULL,
|
||||
handoff TINYINT NOT NULL DEFAULT 0,
|
||||
ord INT NULL,
|
||||
source VARCHAR(16) NOT NULL DEFAULT 'admin',
|
||||
ticket_ref VARCHAR(20) NULL,
|
||||
seed_hash CHAR(40) NULL,
|
||||
edited TINYINT NOT NULL DEFAULT 0,
|
||||
deleted TINYINT NOT NULL DEFAULT 0,
|
||||
created BIGINT NOT NULL,
|
||||
updated BIGINT NOT NULL,
|
||||
INDEX (deleted, updated)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
},
|
||||
async all() { return (await db.q('SELECT * FROM kb_entries')).map(row); },
|
||||
async put(e) {
|
||||
await db.q(`INSERT INTO kb_entries (id,title,questions,answer,tags,pattern,handoff,ord,source,ticket_ref,seed_hash,edited,deleted,created,updated)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE title=VALUES(title), questions=VALUES(questions), answer=VALUES(answer), tags=VALUES(tags),
|
||||
pattern=VALUES(pattern), handoff=VALUES(handoff), ord=VALUES(ord), source=VALUES(source), ticket_ref=VALUES(ticket_ref), seed_hash=VALUES(seed_hash),
|
||||
edited=VALUES(edited), deleted=VALUES(deleted), updated=VALUES(updated)`,
|
||||
[e.id, e.title, JSON.stringify(e.questions || []), e.answer, JSON.stringify(e.tags || []), e.pattern || null, e.handoff ? 1 : 0, e.order == null ? null : e.order,
|
||||
e.source, e.ticketRef || null, e.seedHash || null, e.edited ? 1 : 0, e.deleted ? 1 : 0, e.created, e.updated]);
|
||||
}
|
||||
};
|
||||
const J = {
|
||||
file: () => path.join(DATA_DIR, 'kb.json'),
|
||||
async ensure() {},
|
||||
async all() { try { const d = JSON.parse(fs.readFileSync(J.file(), 'utf8')); return Array.isArray(d.entries) ? d.entries : []; } catch (e) { return []; } },
|
||||
async put(e) {
|
||||
const all = await J.all(), i = all.findIndex(x => x.id === e.id);
|
||||
if (i >= 0) all[i] = e; else all.push(e);
|
||||
const tmp = J.file() + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify({ entries: all }));
|
||||
fs.renameSync(tmp, J.file());
|
||||
}
|
||||
};
|
||||
const store = () => db.enabled() ? D : J;
|
||||
|
||||
// ---------------------------------------------------------------- seeds
|
||||
const SEED_FIELDS = ['title', 'questions', 'answer', 'tags', 'pattern', 'handoff', 'order', 'source'];
|
||||
const seedHash = s => crypto.createHash('sha1').update(JSON.stringify(SEED_FIELDS.map(f => s[f] == null ? null : s[f]))).digest('hex');
|
||||
function seedEntry(s) {
|
||||
return { id: s.id, title: s.title, questions: s.questions || [], answer: s.answer, tags: s.tags || [], pattern: s.pattern || '', handoff: !!s.handoff,
|
||||
order: s.order == null ? null : s.order, source: s.source || 'faq' };
|
||||
}
|
||||
async function syncSeeds() {
|
||||
const all = await store().all(), byId = new Map(all.map(e => [e.id, e])), now = Date.now();
|
||||
const seedIds = new Set(SEEDS.map(s => s.id));
|
||||
let added = 0, refreshed = 0, retired = 0;
|
||||
for (const s of SEEDS) {
|
||||
const h = seedHash(seedEntry(s)), cur = byId.get(s.id);
|
||||
if (!cur) { await store().put(Object.assign(seedEntry(s), { ticketRef: '', seedHash: h, edited: false, deleted: false, created: now, updated: now })); added++; }
|
||||
else if (!cur.deleted && !cur.edited && cur.seedHash !== h) { await store().put(Object.assign({}, cur, seedEntry(s), { seedHash: h, updated: now })); refreshed++; }
|
||||
}
|
||||
// a seed taken out of the code goes with it, unless an admin has made the entry their own (guard: a broken seed list retires nothing)
|
||||
if (SEEDS.length >= 10) for (const e of all) if (e.seedHash && !e.edited && !e.deleted && !seedIds.has(e.id)) { await store().put(Object.assign({}, e, { deleted: true, updated: now })); retired++; }
|
||||
if (added || refreshed || retired) console.log('kb: seeds synced, ' + added + ' added, ' + refreshed + ' refreshed, ' + retired + ' retired');
|
||||
}
|
||||
|
||||
function init(opts) {
|
||||
DATA_DIR = opts.dataDir; SEEDS = opts.seeds || []; cache = null; index = null;
|
||||
ready = (async () => { await store().ensure(); await syncSeeds(); })().catch(e => { console.error('kb init', e.message); });
|
||||
return ready;
|
||||
}
|
||||
async function load(force) {
|
||||
if (ready) await ready;
|
||||
if (!force && cache && Date.now() - cacheAt < TTL) return cache;
|
||||
const all = await store().all();
|
||||
cache = all.filter(e => !e.deleted); cacheAt = Date.now(); index = buildIndex(cache); rx.clear();
|
||||
return cache;
|
||||
}
|
||||
const rx = new Map();
|
||||
function compiled(src) {
|
||||
if (!rx.has(src)) { let r = null; try { r = new RegExp(src, 'i'); } catch (e) {} rx.set(src, r); }
|
||||
return rx.get(src);
|
||||
}
|
||||
const byOrder = (a, b) => (a.order == null ? 1e9 : a.order) - (b.order == null ? 1e9 : b.order) || a.updated - b.updated;
|
||||
|
||||
// ---------------------------------------------------------------- the chatbot side
|
||||
async function fastPath(msg) {
|
||||
const list = (await load()).filter(e => e.pattern).sort(byOrder);
|
||||
for (const e of list) { const r = compiled(e.pattern); if (r && r.test(msg)) return e; }
|
||||
return null;
|
||||
}
|
||||
async function search(query, k) { await load(); return rank(index, query, k || 5); }
|
||||
async function context(query, k) { return relevant(await search(query, k || 5)); }
|
||||
const HELP = 'Help (https://instantadpay.com/my#help, or https://instantadpay.com/support when signed out)';
|
||||
function promptBlock(hits) {
|
||||
const unsure = 'say "I\'m not sure, ask support" and point to ' + HELP + '.';
|
||||
if (!hits.length) return 'KNOWLEDGE BASE: no entry matches this question. If the FACTS above do not answer it either, ' + unsure + ' Do not guess.';
|
||||
return 'KNOWLEDGE BASE (maintained answers, most relevant first). Answer from these when one fits: keep its facts, numbers and links exactly, in your own short words. '
|
||||
+ 'If none of them and none of the FACTS answer the question, ' + unsure + ' Never guess.\n'
|
||||
+ hits.map((h, i) => '[' + (i + 1) + '] ' + h.entry.title + '\nAsked as: ' + (h.entry.questions || []).slice(0, 4).join(' | ') + '\nAnswer: ' + h.entry.answer).join('\n\n');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the admin side
|
||||
const clean = s => String(s == null ? '' : s).replace(/\s*[—―]\s*/g, ', ').replace(/(\d)\s*–\s*(\d)/g, '$1-$2').replace(/\s*–\s*/g, ', ').replace(/\r\n/g, '\n').trim(); // house rule: no em dashes in member-facing text
|
||||
function validate(o, cur) {
|
||||
o = o || {};
|
||||
const questions = (Array.isArray(o.questions) ? o.questions : String(o.questions || '').split('\n')).map(clean).filter(Boolean).map(q => q.slice(0, 300)).slice(0, 15);
|
||||
const tags = (Array.isArray(o.tags) ? o.tags : String(o.tags || '').split(',')).map(t => clean(t).toLowerCase().slice(0, 40)).filter(Boolean).slice(0, 15);
|
||||
const answer = clean(o.answer).slice(0, 4000);
|
||||
const title = (clean(o.title) || questions[0] || '').slice(0, 200);
|
||||
const pattern = String(o.pattern == null ? (cur ? cur.pattern : '') : o.pattern).trim().slice(0, 2000);
|
||||
if (!title) return { error: 'Give the entry a title or at least one question.' };
|
||||
if (!answer) return { error: 'The answer is empty.' };
|
||||
if (pattern) { try { new RegExp(pattern, 'i'); } catch (e) { return { error: 'The instant-answer pattern is not a valid regular expression: ' + e.message }; } }
|
||||
const order = o.order === '' || o.order == null ? (cur ? cur.order : null) : Number(o.order);
|
||||
return { title, questions, tags, answer, pattern, handoff: o.handoff == null ? !!(cur && cur.handoff) : !!o.handoff, order: Number.isFinite(order) ? Math.round(order) : null };
|
||||
}
|
||||
async function list(q) {
|
||||
const all = (await load(true)).slice();
|
||||
if (!q) return all.sort((a, b) => b.updated - a.updated);
|
||||
const ranked = rank(index, q, 50).map(h => Object.assign({ score: h.score }, h.entry));
|
||||
const lc = String(q).toLowerCase(), seen = new Set(ranked.map(e => e.id));
|
||||
const plain = all.filter(e => !seen.has(e.id) && (e.id.includes(lc) || (e.title + ' ' + e.answer + ' ' + (e.ticketRef || '')).toLowerCase().includes(lc)));
|
||||
return ranked.concat(plain);
|
||||
}
|
||||
async function get(id) { return (await load(true)).find(e => e.id === String(id)) || null; }
|
||||
async function create(o) {
|
||||
const v = validate(o); if (v.error) return v;
|
||||
const now = Date.now(), id = 'kb-' + now.toString(36) + crypto.randomBytes(2).toString('hex');
|
||||
const src = ['ticket', 'admin'].includes(o.source) ? o.source : 'admin';
|
||||
const e = Object.assign(v, { id, source: src, ticketRef: String(o.ticketRef || '').slice(0, 20), seedHash: '', edited: true, deleted: false, created: now, updated: now });
|
||||
await store().put(e); await load(true);
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function update(id, o) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
const v = validate(o, cur); if (v.error) return v;
|
||||
const e = Object.assign({}, cur, v, { edited: true, updated: Date.now() });
|
||||
await store().put(e); await load(true);
|
||||
return { ok: true, entry: e };
|
||||
}
|
||||
async function remove(id) {
|
||||
const cur = await get(id); if (!cur) return { error: 'Entry not found.' };
|
||||
await store().put(Object.assign({}, cur, { deleted: true, updated: Date.now() })); await load(true);
|
||||
return { ok: true };
|
||||
}
|
||||
// newest change made by a person (admin pane or a saved ticket reply), as a Central-time day. The chatbot-sync
|
||||
// guard compares it with release-note dates. Seed refreshes do not count: those follow chatbot.js, whose
|
||||
// KNOWLEDGE_DATE already speaks for the code.
|
||||
const ctDay = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
async function stamp() {
|
||||
const all = await load();
|
||||
const max = all.reduce((m, e) => e.edited ? Math.max(m, e.updated || 0) : m, 0);
|
||||
return { updated: max ? ctDay(max) : '', count: all.length };
|
||||
}
|
||||
async function test(question) {
|
||||
const fast = await fastPath(String(question || ''));
|
||||
const hits = await search(String(question || ''), 8), used = new Set(relevant(hits).map(h => h.entry.id));
|
||||
return { fast: fast ? { id: fast.id, title: fast.title } : null, ranked: hits.map(h => ({ id: h.entry.id, title: h.entry.title, score: h.score, used: used.has(h.entry.id) })) };
|
||||
}
|
||||
|
||||
module.exports = { init, load, fastPath, search, context, promptBlock, list, get, create, update, remove, stamp, test,
|
||||
_pure: { words, terms, buildIndex, rank, relevant, validate, seedHash, MIN_SCORE } };
|
||||
@@ -0,0 +1,218 @@
|
||||
// The Refuel Kit (Fuel Your Offers stage 3, Marty approved the build 2026-10-24). The SAME file ships in InstantAdPay and
|
||||
// LinkSpin; each site keeps ITS OWN program's kits (InstantAdPay art promotes InstantAdPay, LinkSpin art promotes
|
||||
// LinkSpin, never mixed).
|
||||
//
|
||||
// A kit is one month's members-only banner set: { month 'YYYY-MM', theme, released, sizes 728x90 300x250 468x60 160x600
|
||||
// 1200x630 } with one base image per size, stored as data in DATA_DIR/kits/ (kits.json + <month>/<size>.<ext>).
|
||||
// Admin uploads the base art and previews the personalization; nothing here generates art (real art is Marty's).
|
||||
//
|
||||
// Who gets which kit: a counted refuel (the streak in refuel.js, InstantAdPay is the source of truth) unlocks the kit
|
||||
// of the Central-time month it landed in. The entitlement arrives as { months: { 'YYYY-MM': streakMonthAtUnlock } }
|
||||
// from opts.entitled(email). Kits stay usable after their month; missing a refuel only stops NEW kits.
|
||||
// streak month 3+ at unlock an animated GIF version of each banner size
|
||||
// streak month 6+ at unlock a "custom banners" credit for BannerKitAI: the entitlement and a note only, no integration
|
||||
//
|
||||
// Personalized on the server per member: their @username and a QR code to their own link are drawn onto each banner
|
||||
// with ffmpeg (the badge renderer's approach). Rendered files are cached in DATA_DIR/kits/out/<hash>.<ext> and served
|
||||
// publicly at /kitimg/<hash>.<ext> (ad networks and IAP banner campaigns load them by URL); the hash is an HMAC of
|
||||
// member + kit + size + variant + base-art version, so it cannot be guessed and changes when the art changes.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const SIZES = { '728x90': [728, 90], '300x250': [300, 250], '468x60': [468, 60], '160x600': [160, 600], '1200x630': [1200, 630] };
|
||||
const ORDER = ['728x90', '300x250', '468x60', '160x600', '1200x630'];
|
||||
// where the QR and the name go on each size: q = QR box (x, y, side), t = name (x expr, y expr, font px)
|
||||
const LAYOUT = {
|
||||
'728x90': { q: ['W-84', 6, 78], t: ['W-96-tw', 'H-30', 18] },
|
||||
'468x60': { q: ['W-58', 4, 52], t: ['W-68-tw', 'H-24', 14] },
|
||||
'300x250': { q: ['W-82', 'H-82', 76], t: ['8', 'H-30', 16] },
|
||||
'160x600': { q: ['(W-120)/2', 'H-128', 120], t: ['(W-tw)/2', 'H-160', 16] },
|
||||
'1200x630': { q: ['W-212', 'H-212', 182], t: ['32', 'H-66', 34] },
|
||||
};
|
||||
let X = {}, DIR = null, OUT = null, FILE = null, SALT = null;
|
||||
const MONTH_RE = /^\d{4}-(0[1-9]|1[0-2])$/;
|
||||
const norm = e => String(e || '').trim().toLowerCase();
|
||||
|
||||
function init(opts) {
|
||||
X = opts || {}; DIR = path.join(X.dataDir, 'kits'); OUT = path.join(DIR, 'out'); FILE = path.join(DIR, 'kits.json');
|
||||
try { fs.mkdirSync(OUT, { recursive: true }); } catch (e) {}
|
||||
const sf = path.join(DIR, 'salt'); try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (e) {}
|
||||
if (!SALT) { SALT = crypto.randomBytes(16).toString('hex'); try { fs.writeFileSync(sf, SALT, { flag: 'wx' }); } catch (e) { try { SALT = fs.readFileSync(sf, 'utf8').trim(); } catch (er) {} } }
|
||||
}
|
||||
const program = () => X.program === 'linkspin' ? 'linkspin' : 'iap';
|
||||
const brand = () => program() === 'linkspin' ? 'LinkSpin' : 'InstantAdPay';
|
||||
function load() { try { const s = JSON.parse(fs.readFileSync(FILE, 'utf8')); s.kits = s.kits || {}; s.credits = s.credits || {}; return s; } catch (e) { return { kits: {}, credits: {} }; } }
|
||||
function save(s) { const tmp = FILE + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(s, null, 1)); fs.renameSync(tmp, FILE); }
|
||||
const ctMonth = ts => new Date(ts || Date.now()).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }).slice(0, 7);
|
||||
const monthLabel = m => new Date(Date.UTC(Number(m.slice(0, 4)), Number(m.slice(5, 7)) - 1, 15)).toLocaleDateString('en-US', { month: 'long', year: 'numeric', timeZone: 'UTC' });
|
||||
|
||||
// ---- admin: the kits ---------------------------------------------------------------------------------
|
||||
function baseFile(month, size) {
|
||||
const d = path.join(DIR, month);
|
||||
for (const ext of ['png', 'jpg', 'gif']) { const f = path.join(d, size + '.' + ext); if (fs.existsSync(f)) return f; }
|
||||
return null;
|
||||
}
|
||||
function kitView(k) {
|
||||
const sizes = ORDER.map(s => { const f = baseFile(k.month, s); return { size: s, ready: !!f, v: f ? Math.round(fs.statSync(f).mtimeMs) : 0 }; });
|
||||
return { month: k.month, label: monthLabel(k.month), theme: k.theme || '', released: !!k.released, program: program(), sizes, complete: sizes.every(x => x.ready), updated: k.updated || 0 };
|
||||
}
|
||||
function listKits() { const s = load(); return Object.values(s.kits).sort((a, b) => b.month.localeCompare(a.month)).map(kitView); }
|
||||
function saveKit(b) {
|
||||
const month = String(b.month || ''); if (!MONTH_RE.test(month)) return { error: 'Month as YYYY-MM.' };
|
||||
const s = load(); const k = s.kits[month] || { month, theme: '', released: false, created: Date.now() };
|
||||
if (b.theme != null) k.theme = String(b.theme).trim().slice(0, 80);
|
||||
if (b.released != null) {
|
||||
if (b.released && !kitView(k).complete) return { error: 'Upload all five sizes before releasing the kit.' };
|
||||
k.released = !!b.released;
|
||||
}
|
||||
if (b.remove) { delete s.kits[month]; save(s); return { ok: true, removed: true }; }
|
||||
k.updated = Date.now(); s.kits[month] = k; save(s);
|
||||
return { ok: true, kit: kitView(k) };
|
||||
}
|
||||
const MAGIC = { png: b => b[0] === 0x89 && b[1] === 0x50, jpg: b => b[0] === 0xff && b[1] === 0xd8, gif: b => b.slice(0, 3).toString() === 'GIF' };
|
||||
function uploadBase(month, size, buf, mime) {
|
||||
if (!MONTH_RE.test(String(month))) return { error: 'Month as YYYY-MM.' };
|
||||
if (!SIZES[size]) return { error: 'Size must be one of ' + ORDER.join(', ') + '.' };
|
||||
const ext = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif' }[String(mime || '').split(';')[0].trim()];
|
||||
if (!ext || !buf || buf.length < 32 || !MAGIC[ext](buf)) return { error: 'Use a PNG, JPG or GIF file.' };
|
||||
const d = path.join(DIR, month); fs.mkdirSync(d, { recursive: true });
|
||||
for (const e of ['png', 'jpg', 'gif']) { try { fs.unlinkSync(path.join(d, size + '.' + e)); } catch (er) {} }
|
||||
fs.writeFileSync(path.join(d, size + '.' + ext), buf);
|
||||
const s = load(); if (!s.kits[month]) s.kits[month] = { month, theme: '', released: false, created: Date.now() }; s.kits[month].updated = Date.now(); save(s);
|
||||
return { ok: true, kit: kitView(s.kits[month]) };
|
||||
}
|
||||
// placeholder art for tests and previews: the program's existing banners from public/banners (no paid image APIs)
|
||||
function usePlaceholder(month) {
|
||||
const pre = program() === 'linkspin' ? 'linkspin-' : 'iap-';
|
||||
const pick = { '728x90': [pre + '728x90.png'], '300x250': [pre + '300x250.png'], '468x60': [pre + '468x60.png'], '160x600': [pre + '160x600.png'],
|
||||
'1200x630': program() === 'linkspin' ? ['linkspin-og-1200x630.png'] : ['iap-hero-1200x630.png', 'iap-advertise-earn-1200x630.jpg'] };
|
||||
const done = [];
|
||||
for (const size of ORDER) {
|
||||
const f = pick[size].map(n => path.join(X.publicDir, 'banners', n)).find(p => fs.existsSync(p)); if (!f) continue;
|
||||
const buf = fs.readFileSync(f); const r = uploadBase(month, size, buf, /\.jpg$/.test(f) ? 'image/jpeg' : 'image/png'); if (r.ok) done.push(size);
|
||||
}
|
||||
return { ok: true, sizes: done, kit: kitView(load().kits[month] || { month }) };
|
||||
}
|
||||
|
||||
// ---- the renderer ---------------------------------------------------------------------------------------
|
||||
let FONT;
|
||||
function font() {
|
||||
if (FONT !== undefined) return FONT;
|
||||
FONT = process.env.BADGE_FONT || null; if (FONT) return FONT;
|
||||
const walk = d => { let ents = []; try { ents = fs.readdirSync(d, { withFileTypes: true }); } catch (e) { return null; } for (const e of ents) { const f = path.join(d, e.name); if (e.isDirectory()) { const r = walk(f); if (r) return r; } else if (/bold\.ttf$/i.test(e.name) || /DejaVuSans-Bold\.ttf$/.test(e.name)) return f; } return null; };
|
||||
for (const d of ['/usr/share/fonts', '/usr/local/share/fonts']) { const r = walk(d); if (r) { FONT = r; break; } }
|
||||
if (!FONT && process.platform === 'win32' && fs.existsSync('C:/Windows/Fonts/arialbd.ttf')) FONT = 'C:/Windows/Fonts/arialbd.ttf';
|
||||
return FONT;
|
||||
}
|
||||
const ffText = t => String(t).replace(/\\/g, '\\\\').replace(/'/g, "\\'").replace(/:/g, '\\:').replace(/%/g, '%%');
|
||||
function run(args, cwd) {
|
||||
return new Promise(resolve => {
|
||||
const p = spawn(X.ffmpeg || 'ffmpeg', args, { stdio: ['ignore', 'pipe', 'pipe'], cwd });
|
||||
const out = []; let err = '';
|
||||
p.stdout.on('data', c => out.push(c)); p.stderr.on('data', c => { err += c; });
|
||||
p.on('error', e => resolve({ code: -1, err: e.message })); p.on('close', code => resolve({ code, out: Buffer.concat(out), err }));
|
||||
});
|
||||
}
|
||||
// one personalized banner: base scaled to the exact size, QR (white quiet zone) and @name on a dark box
|
||||
async function renderStill(base, size, name, link, stage, outFile) {
|
||||
const [W, H] = SIZES[size]; const L = LAYOUT[size]; const F = font();
|
||||
if (!F) return { error: 'No font for the renderer.' };
|
||||
const qr = X.qrcode || require('qrcode'); // opts.qrcode: a test copy without node_modules
|
||||
const qrFile = outFile + '.qr.png';
|
||||
await qr.toFile(qrFile, link, { margin: 1, width: L.q[2], errorCorrectionLevel: 'M', color: { dark: '#000000', light: '#ffffff' } });
|
||||
const winPath = /:/.test(F); const fontFile = winPath ? path.basename(F) : F;
|
||||
const ex = v => String(v).replace(/W/g, String(W)).replace(/H/g, String(H));
|
||||
const tx = String(L.t[0]).replace(/W/g, String(W)).replace(/tw/g, 'text_w'); const ty = ex(L.t[1]);
|
||||
const showName = stage !== 0, showQr = stage === undefined || stage === 2;
|
||||
const chain = ['[0:v]scale=' + W + ':' + H + ':flags=lanczos,setsar=1[b]'];
|
||||
let last = 'b';
|
||||
if (showQr) { chain.push('[1:v]scale=' + L.q[2] + ':' + L.q[2] + '[q]'); chain.push('[' + last + '][q]overlay=x=' + ex(L.q[0]) + ':y=' + ex(L.q[1]) + '[o]'); last = 'o'; }
|
||||
if (showName && name) { chain.push('[' + last + ']drawtext=fontfile=' + fontFile + ":text='" + ffText(name) + "':fontcolor=white:fontsize=" + L.t[2] + ':box=1:boxcolor=0x0b1418@0.72:boxborderw=6:x=' + tx + ':y=' + ty + '[n]'); last = 'n'; }
|
||||
const args = ['-v', 'error', '-y', '-i', path.resolve(base), '-i', path.resolve(qrFile), '-filter_complex', chain.join(';'), '-map', '[' + last + ']', '-frames:v', '1'];
|
||||
if (/\.jpg$/.test(outFile)) args.push('-q:v', '3');
|
||||
args.push(path.resolve(outFile));
|
||||
const r = await run(args, winPath ? path.dirname(F) : undefined);
|
||||
try { fs.unlinkSync(qrFile); } catch (e) {}
|
||||
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'Render failed: ' + String(r.err || '').slice(0, 200) };
|
||||
return { ok: true };
|
||||
}
|
||||
// the animated version (streak month 3+): the banner, then the name, then the name and the QR, looping
|
||||
async function renderGif(base, size, name, link, outFile) {
|
||||
const frames = [0, 1, 2].map(i => outFile + '.f' + i + '.png');
|
||||
for (let i = 0; i < 3; i++) { const r = await renderStill(base, size, name, link, i, frames[i]); if (r.error) return r; }
|
||||
const list = outFile + '.txt';
|
||||
fs.writeFileSync(list, frames.map((f, i) => "file '" + path.resolve(f).replace(/\\/g, '/') + "'\nduration " + (i === 2 ? 3 : 1)).join('\n') + "\nfile '" + path.resolve(frames[2]).replace(/\\/g, '/') + "'\n");
|
||||
const r = await run(['-v', 'error', '-y', '-f', 'concat', '-safe', '0', '-i', list, '-filter_complex', 'split[a][b];[a]palettegen=max_colors=96[p];[b][p]paletteuse=dither=bayer', '-loop', '0', path.resolve(outFile)]);
|
||||
for (const f of frames.concat(list)) { try { fs.unlinkSync(f); } catch (e) {} }
|
||||
if (r.code !== 0 || !fs.existsSync(outFile)) return { error: 'GIF render failed: ' + String(r.err || '').slice(0, 200) };
|
||||
return { ok: true };
|
||||
}
|
||||
const hashOf = (email, month, size, variant, v) => crypto.createHmac('sha256', SALT).update([norm(email), program(), month, size, variant, v].join('|')).digest('hex').slice(0, 28);
|
||||
function indexFile() { return path.join(OUT, 'index.json'); }
|
||||
function noteIndex(h, meta) { let ix = {}; try { ix = JSON.parse(fs.readFileSync(indexFile(), 'utf8')); } catch (e) {} ix[h] = meta; const tmp = indexFile() + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(ix)); fs.renameSync(tmp, indexFile()); }
|
||||
// render (or reuse) one personalized file; returns { url, file, size, variant, w, h, bytes }
|
||||
async function personal(who, month, size, variant) {
|
||||
const base = baseFile(month, size); if (!base) return { error: 'That kit has no ' + size + ' art yet.' };
|
||||
const v = Math.round(fs.statSync(base).mtimeMs);
|
||||
const ext = variant === 'gif' ? 'gif' : size === '1200x630' ? 'jpg' : 'png';
|
||||
const h = hashOf(who.email, month, size, variant, v + '|' + who.name + '|' + who.link);
|
||||
const out = path.join(OUT, h + '.' + ext);
|
||||
if (!fs.existsSync(out)) {
|
||||
const tmp = path.join(OUT, h + '.' + process.pid + '.' + Date.now() + '.' + ext);
|
||||
let r; try { r = variant === 'gif' ? await renderGif(base, size, who.name, who.link, tmp) : await renderStill(base, size, who.name, who.link, undefined, tmp); } catch (e) { r = { error: 'The banner renderer is not available: ' + e.message }; }
|
||||
if (r.error) return r;
|
||||
try { fs.renameSync(tmp, out); } catch (e) { try { fs.unlinkSync(tmp); } catch (er) {} }
|
||||
noteIndex(h, { email: norm(who.email), month, size, variant, ts: Date.now() });
|
||||
}
|
||||
const [w, hh] = SIZES[size];
|
||||
return { ok: true, url: '/kitimg/' + h + '.' + ext, abs: String(X.siteUrl || '').replace(/\/+$/, '') + '/kitimg/' + h + '.' + ext, file: out, size, variant, w, h: hh, bytes: fs.statSync(out).size, ext };
|
||||
}
|
||||
// public serving: only files already rendered for an entitled member
|
||||
function servePath(name) { const m = /^([a-f0-9]{28})\.(png|jpg|gif)$/.exec(String(name || '')); if (!m) return null; const f = path.join(OUT, m[0]); return fs.existsSync(f) ? { file: f, mime: { png: 'image/png', jpg: 'image/jpeg', gif: 'image/gif' }[m[2]] } : null; }
|
||||
|
||||
// ---- the member ------------------------------------------------------------------------------------------
|
||||
async function whoOf(email) {
|
||||
const w = await X.linkFor(norm(email)); if (!w || !w.link) return null;
|
||||
return { email: norm(email), name: w.username ? '@' + w.username : '', link: w.link };
|
||||
}
|
||||
async function myKits(email) {
|
||||
const ent = (await X.entitled(norm(email)).catch(() => null)) || null;
|
||||
if (!ent || !ent.on) return { on: false };
|
||||
const s = load(); const months = ent.months || {};
|
||||
const nowMonth = String(ent.today || '').slice(0, 7) || ctMonth(); // a kit released early still waits for its month
|
||||
const kits = Object.values(s.kits).filter(k => k.released && k.month <= nowMonth).sort((a, b) => b.month.localeCompare(a.month)).slice(0, 12).map(k => {
|
||||
const streakAt = months[k.month] || 0; const unlocked = streakAt > 0;
|
||||
return Object.assign(kitView(k), { unlocked, streakAt, gif: unlocked && streakAt >= 3, custom: unlocked && streakAt >= 6 });
|
||||
});
|
||||
// the BannerKitAI "custom banners" credit: an entitlement on record, nothing more yet
|
||||
const customMonths = Object.entries(months).filter(([, k]) => k >= 6).map(([m]) => m);
|
||||
if (customMonths.length) {
|
||||
const e = norm(email); const have = s.credits[e] || {}; let changed = false;
|
||||
for (const m of customMonths) if (!have[m]) { have[m] = { ts: Date.now(), used: false }; changed = true; }
|
||||
if (changed) { s.credits[e] = have; save(s); }
|
||||
}
|
||||
const credits = Object.entries((s.credits[norm(email)] || {})).map(([m, c]) => ({ month: m, used: !!c.used }));
|
||||
const cur = nowMonth; const who = await whoOf(email).catch(() => null);
|
||||
return { on: true, program: program(), brand: brand(), link: who ? who.link : null, name: who ? who.name : null, current: cur, currentLabel: monthLabel(cur), unlockedCurrent: !!months[cur],
|
||||
kits, customCredits: credits, customNote: credits.length ? 'Custom banners made for your own offer with BannerKitAI are coming. Your credit is saved on your account and will be honored when it opens.' : null,
|
||||
nextRefuel: ent.nextRefuel || null };
|
||||
}
|
||||
async function renderFor(email, month, size, variant) {
|
||||
const mk = await myKits(email); if (!mk.on) return { error: 'The Refuel Kit is not switched on.' };
|
||||
const k = mk.kits.find(x => x.month === month); if (!k) return { error: 'No such kit.' };
|
||||
if (!k.unlocked) return { error: 'Your next counted refuel unlocks this kit.' };
|
||||
if (!SIZES[size]) return { error: 'No such size.' };
|
||||
if (variant === 'gif' && !k.gif) return { error: 'The animated version comes with a 3-month streak.' };
|
||||
const who = await whoOf(email); if (!who) return { error: 'Set a username first, so your banners carry your own link.' };
|
||||
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
|
||||
}
|
||||
async function preview(month, size, username, variant) {
|
||||
const link = String(X.siteUrl || '').replace(/\/+$/, '') + '/join/' + (username || 'yourname');
|
||||
const who = { email: 'preview@' + program(), name: '@' + (username || 'yourname'), link };
|
||||
return personal(who, month, size, variant === 'gif' ? 'gif' : 'still');
|
||||
}
|
||||
|
||||
module.exports = { init, SIZES, ORDER, LAYOUT, listKits, saveKit, uploadBase, usePlaceholder, myKits, renderFor, preview, servePath, ctMonth, monthLabel, font };
|
||||
@@ -5,6 +5,7 @@
|
||||
// rollover (checked hourly), announced to Telegram, and credit prizes are granted automatically.
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const themehead = require('./themehead'); // light/dark theme head script (2026-11-01)
|
||||
let R = null; // { chain, accounts, ads, dataDir, siteConfig, notify(text), pushFeed(ev) }
|
||||
const TZ = 'America/Chicago';
|
||||
let cache = { at: 0, rows: null };
|
||||
@@ -131,9 +132,9 @@ async function renderPage() {
|
||||
+ (v.top.length ? v.top.map(r => '<tr><td>' + r.rank + '</td><td><b>' + esc(r.name) + '</b></td><td>' + r.sales + '</td><td>$' + r.usd.toLocaleString() + '</td><td>' + r.buyers + '</td><td>' + r.joins + '</td></tr>').join('') : '<tr><td colspan="6" class="muted">No sales yet in this period.</td></tr>') + '</table>';
|
||||
const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' });
|
||||
const desc = 'Who is selling the most ad packages on InstantAdPay this week and this month. Weekly and monthly referral contest standings, read from the chain.';
|
||||
let h = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | InstantAdPay</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="https://instantadpay.com/leaderboard"><meta property="og:title" content="InstantAdPay leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="https://instantadpay.com/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap"><link rel="stylesheet" href="/assets/site.css?v=20260913a">'
|
||||
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:#ffd15c;font-weight:800}.prize{border-left:4px solid var(--mint);background:rgba(67,232,195,.07);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
|
||||
let h = '<!doctype html><html lang="en"' + themehead.htmlAttr('dark') + '><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Leaderboard | InstantAdPay</title><meta name="description" content="' + esc(desc) + '"><link rel="canonical" href="https://instantadpay.com/leaderboard"><meta property="og:title" content="InstantAdPay leaderboard"><meta property="og:description" content="' + esc(desc) + '"><meta property="og:image" content="https://instantadpay.com/banners/iap-hero-1200x630.png"><meta name="twitter:card" content="summary_large_image">'
|
||||
+ '<link rel="icon" type="image/png" href="/logo-icon.png"><link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">' + themehead.tag() + '<link rel="stylesheet" href="/assets/site.css?v=20261112ln">'
|
||||
+ '<style>.lbw{max-width:860px}.lb{width:100%;border-collapse:collapse;margin:8px 0 26px;font-variant-numeric:tabular-nums}.lb th{text-align:left;color:var(--muted);font-size:11px;letter-spacing:.08em;text-transform:uppercase;padding:8px 10px;border-bottom:1px solid var(--line)}.lb td{padding:10px;border-bottom:1px solid var(--line)}.lb tr:first-child + tr td:first-child{color:var(--gold);font-weight:800}.prize{border-left:4px solid var(--mint);background:var(--mint-soft);padding:12px 16px;border-radius:0 12px 12px 0;margin:0 0 18px}.win{background:var(--panel);border:1px solid var(--line);border-radius:12px;padding:12px 16px;margin:0 0 10px}</style></head><body><div class="wrap lbw">'
|
||||
+ '<section class="hero" style="padding:56px 0 8px"><p class="eyebrow">Referral contest</p><h1>Leaderboard: <em>who is selling</em>.</h1><p class="lead">Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.</p></section>';
|
||||
h += '<h2 style="font-size:24px;margin:0 0 4px">' + week.label + ' <span class="muted small">' + fmtD(week.start) + ' to Sunday</span></h2>' + (week.prize ? '<div class="prize"><b>Weekly prizes:</b> ' + esc(week.prize) + '</div>' : '') + table(week);
|
||||
h += '<h2 style="font-size:24px;margin:0 0 4px">' + month.label + '</h2>' + (month.prize ? '<div class="prize"><b>Monthly prizes:</b> ' + esc(month.prize) + '</div>' : '') + table(month);
|
||||
@@ -141,7 +142,7 @@ async function renderPage() {
|
||||
const w = winners();
|
||||
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
||||
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
||||
h += '</div><script src="/assets/common.js?v=20260914a"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
return h;
|
||||
}
|
||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||
|
||||
@@ -16,7 +16,8 @@ const path = require('path');
|
||||
|
||||
let FILE = null;
|
||||
const DIRS = ['in', 'out'];
|
||||
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt'];
|
||||
// 'outside': a wallet that is not one of ours above, e.g. Marty funding a game wallet from his own Tangem
|
||||
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt', 'outside'];
|
||||
// assets we can actually value; anything else is recorded but valued only by the usd field
|
||||
const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
|
||||
// WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through
|
||||
@@ -28,9 +29,18 @@ const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
|
||||
// transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances
|
||||
// from other owned positions into the Tangem receiver. Touches the balance ONLY and
|
||||
// must never show up as revenue, or the P&L reports his savings as earnings.
|
||||
const KINDS = ['revenue', 'draw', 'transfer'];
|
||||
// cost a real cost of running the network (2026-10-04, Marty: top up game wallets as needed and record each top-up so
|
||||
// the P&L balances; "show what I spent in advertising versus income" at tax time). Every cost has a category.
|
||||
const KINDS = ['revenue', 'draw', 'transfer', 'cost'];
|
||||
// tax-friendly cost categories: advertising + rewards are both "advertising and promotion" on the tax summary
|
||||
// games (2026-10-05, Marty): game wallet top-ups are a marketing cost for InstantAdPay, booked apart from paid traffic
|
||||
const CATS = { advertising: 'Advertising (paid traffic, ad networks)', games: 'Game marketing (game wallet top-ups)', rewards: 'Player rewards (game and earning-site payouts)', software: 'Software and hosting', other: 'Other costs' };
|
||||
|
||||
function init(opts) { FILE = path.join(opts.dataDir, 'ledger.json'); }
|
||||
function init(opts) {
|
||||
FILE = path.join(opts.dataDir, 'ledger.json');
|
||||
// one-time move (2026-10-05): earlier game wallet top-ups, booked by the wallet watcher as Player rewards, become Game marketing
|
||||
try { const d = load(); let n = 0; for (const e of d.entries) if (e.kind === 'cost' && e.category === 'rewards' && /^Player rewards funding: /.test(e.note || '')) { e.category = 'games'; e.note = e.note.replace(/^Player rewards funding: /, 'Game marketing: '); n++; } if (n) { save(d); console.log('ledger: moved', n, 'game wallet top-ups to Game marketing'); } } catch (e) { console.error('ledger migrate', e.message); }
|
||||
}
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } }
|
||||
function save(d) {
|
||||
const tmp = FILE + '.tmp';
|
||||
@@ -65,6 +75,8 @@ function put(input) {
|
||||
tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '',
|
||||
ts: Date.now(),
|
||||
};
|
||||
if (e.kind === 'cost') e.category = CATS[input.category] ? input.category : 'other';
|
||||
if (e.tx && d.entries.some(x => x.tx === e.tx && x.id !== e.id)) return { error: 'That transaction is already recorded.', duplicate: true };
|
||||
const i = d.entries.findIndex(x => x.id === e.id);
|
||||
if (i >= 0) d.entries[i] = e; else d.entries.push(e);
|
||||
save(d);
|
||||
@@ -86,12 +98,13 @@ function totals(wallet) {
|
||||
const rows = load().entries.filter(e => !wallet || e.wallet === wallet);
|
||||
const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length,
|
||||
// revenue and draws are the P&L numbers; transfers move the balance and nothing else
|
||||
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0 };
|
||||
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0, costPol: 0, costUsd: 0 };
|
||||
for (const e of rows) {
|
||||
const pol = e.asset === 'POL' ? e.amount : 0;
|
||||
if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; }
|
||||
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; }
|
||||
else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; }
|
||||
else if (e.kind === 'cost') { t.costPol += (e.dir === 'out' ? pol : -pol); t.costUsd += (e.dir === 'out' ? e.usd : -e.usd); }
|
||||
else t.transferPol += (e.dir === 'in' ? pol : -pol);
|
||||
}
|
||||
for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6;
|
||||
@@ -108,4 +121,4 @@ function reconcile(earnedPol, actualPol, wallet) {
|
||||
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
|
||||
}
|
||||
|
||||
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS };
|
||||
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS, CATS, entriesFor: year => load().entries.filter(e => String(e.date || '').startsWith(String(year))) };
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Login-ad showings per day per surface (Marty, 2026-10-18). The sign-in interstitial now runs on
|
||||
// the dashboard AND inside the games' sign-in kit; before raising the 3-slot cap he wants a week of
|
||||
// combined numbers. One row per Central day, surface ('dashboard' or a game slug) and kind:
|
||||
// 'member' (a member's slot was shown), 'house' (the house login ad), 'none' (a sign-in with no
|
||||
// login ad to show). MySQL table login_shows when the DB is on, else DATA_DIR/login-shows.json.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const db = require('./db');
|
||||
let DATA_DIR = null, J = null, ready = null;
|
||||
const ctDay = t => new Date(t === undefined ? Date.now() : t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const FILE = () => path.join(DATA_DIR, 'login-shows.json');
|
||||
|
||||
function init(opts) { DATA_DIR = opts.dataDir; }
|
||||
function ensure() {
|
||||
if (!ready) ready = db.q(`CREATE TABLE IF NOT EXISTS login_shows (
|
||||
day VARCHAR(10) NOT NULL, surface VARCHAR(40) NOT NULL, kind VARCHAR(10) NOT NULL, n INT NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (day, surface, kind)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`).catch(e => { ready = null; throw e; });
|
||||
return ready;
|
||||
}
|
||||
function load() { if (J) return J; try { J = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { J = {}; } return J; }
|
||||
|
||||
// surface: 'dashboard' | game slug; ad: what ads.serve returned (null = nothing to show)
|
||||
async function record(surface, ad) {
|
||||
const s = String(surface || 'dashboard').toLowerCase().replace(/[^a-z0-9_-]/g, '').slice(0, 40) || 'dashboard';
|
||||
const kind = !ad ? 'none' : ad.house ? 'house' : 'member';
|
||||
const d = ctDay();
|
||||
try {
|
||||
if (db.enabled()) {
|
||||
await ensure();
|
||||
await db.q('INSERT INTO login_shows (day,surface,kind,n) VALUES (?,?,?,1) ON DUPLICATE KEY UPDATE n=n+1', [d, s, kind]);
|
||||
} else {
|
||||
const k = d + '|' + s + '|' + kind, st = load();
|
||||
st[k] = (st[k] || 0) + 1;
|
||||
fs.writeFileSync(FILE(), JSON.stringify(st));
|
||||
}
|
||||
} catch (e) { console.error('login shows', e.message); }
|
||||
}
|
||||
// last `days` Central days, newest first: { day, dashboard: {member,house,none}, games: {member,house,none}, byGame: {slug: shown} }
|
||||
async function report(days) {
|
||||
days = Math.max(1, Math.min(90, Number(days) || 14));
|
||||
const since = ctDay(Date.now() - (days - 1) * 86400000);
|
||||
let rows = [];
|
||||
if (db.enabled()) {
|
||||
await ensure();
|
||||
rows = (await db.q('SELECT day, surface, kind, n FROM login_shows WHERE day>=?', [since])).map(r => ({ day: String(r.day), surface: r.surface, kind: r.kind, n: Number(r.n) }));
|
||||
} else {
|
||||
for (const [k, n] of Object.entries(load())) { const [day, surface, kind] = k.split('|'); if (day >= since) rows.push({ day, surface, kind, n }); }
|
||||
}
|
||||
const out = {};
|
||||
const blank = () => ({ member: 0, house: 0, none: 0 });
|
||||
for (let i = 0; i < days; i++) { const d = ctDay(Date.now() - i * 86400000); out[d] = { day: d, dashboard: blank(), games: blank(), byGame: {} }; }
|
||||
for (const r of rows) {
|
||||
const o = out[r.day]; if (!o || !['member', 'house', 'none'].includes(r.kind)) continue;
|
||||
if (r.surface === 'dashboard') o.dashboard[r.kind] += r.n;
|
||||
else { o.games[r.kind] += r.n; if (r.kind !== 'none') o.byGame[r.surface] = (o.byGame[r.surface] || 0) + r.n; }
|
||||
}
|
||||
return Object.values(out).sort((a, b) => (a.day < b.day ? 1 : -1));
|
||||
}
|
||||
module.exports = { init, record, report };
|
||||
@@ -0,0 +1,176 @@
|
||||
// Conversion tracking, InstantAdPay half (Marty approved 2026-10-23). LinkSpin owns goals and conversions;
|
||||
// this module does three things:
|
||||
// record(click) every click through /api/ads/click/:id gets an id ('i' + 11 hex) that rides on the target URL as
|
||||
// ?lsclk=<id>, and the click row is stored here (MySQL ad_clicks, or a capped JSON file locally)
|
||||
// flush loop unpushed rows go to LinkSpin POST /api/partner/clicks every ~3 s, 500 per request, signed exactly
|
||||
// like lssync.js (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET). A row is marked pushed only
|
||||
// after LinkSpin answers ok, so a failure keeps it for the next try (backoff up to 5 minutes).
|
||||
// LinkSpin upserts by id, so two app copies pushing the same rows during a deploy is harmless.
|
||||
// conv(email,..) the member's goals and summary through POST /api/partner/conv (op summary/create/update/remove/test),
|
||||
// summary cached 60 s per email.
|
||||
// owners (2026-10-26) the soft keys members sign in from ride on the click push, so LinkSpin keeps a member's own
|
||||
// clicks (ads here, spin links and Banner Spins there) as tests, never counted
|
||||
// No LS_SYNC_SECRET (or shorter than 32 chars): clicks still get ids and rows, nothing is sent.
|
||||
// The raw IP is never stored: only the soft key 's:' + sha256(ip + '|' + ua) first 20 hex, same on both sites.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
|
||||
const stats = { pushed: 0, lastAt: null, lastError: null, errors: 0 };
|
||||
const cache = new Map(); // email -> { at, data }
|
||||
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
const on = () => SECRET().length >= 32;
|
||||
const useDb = () => !!(R && R.db && R.db.enabled());
|
||||
const JCAP = 5000;
|
||||
const JFILE = () => path.join(R.dataDir, 'adclicks.json');
|
||||
|
||||
function init(deps) {
|
||||
R = deps;
|
||||
if (useDb()) ensureTable().catch(e => console.error('lsconv table', e.message));
|
||||
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 3000); if (timer.unref) timer.unref(); }
|
||||
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
}
|
||||
// column names checked against MySQL 8 reserved words (none of id, campaign_id, owner_email, cname, ctype, sk, country,
|
||||
// device, placement, target, spent, is_self, ts, pushed is reserved)
|
||||
async function ensureTable() {
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS ad_clicks (
|
||||
id VARCHAR(16) PRIMARY KEY,
|
||||
campaign_id INT NOT NULL,
|
||||
owner_email VARCHAR(190) NOT NULL,
|
||||
cname VARCHAR(80) NULL,
|
||||
ctype VARCHAR(12) NULL,
|
||||
sk VARCHAR(24) NULL,
|
||||
country VARCHAR(4) NULL,
|
||||
device VARCHAR(8) NULL,
|
||||
placement VARCHAR(80) NULL,
|
||||
target VARCHAR(500) NULL,
|
||||
spent INT NOT NULL DEFAULT 0,
|
||||
is_self TINYINT NOT NULL DEFAULT 0,
|
||||
ts BIGINT NOT NULL,
|
||||
pushed TINYINT NOT NULL DEFAULT 0,
|
||||
INDEX (pushed, ts),
|
||||
INDEX (campaign_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
}
|
||||
|
||||
// ---- helpers (pure) ----
|
||||
const newId = () => 'i' + crypto.randomBytes(6).toString('hex').slice(0, 11);
|
||||
const softKey = (ip, ua) => 's:' + crypto.createHash('sha256').update(String(ip || '') + '|' + String(ua || '')).digest('hex').slice(0, 20);
|
||||
const deviceOf = ua => /Mobi|Android|iPhone|iPad|iPod|Opera Mini|IEMobile/i.test(String(ua || '')) ? 'mobile' : 'desktop';
|
||||
function placementOf(referer) {
|
||||
try { const u = new URL(String(referer || '')); if (!/^https?:$/.test(u.protocol)) return null; return (u.host.replace(/^www\./, '') + u.pathname.replace(/\/+$/, '')).replace(/[^\w.\-\/:]/g, '').slice(0, 80) || null; }
|
||||
catch (e) { return null; }
|
||||
}
|
||||
// append lsclk=<id> without touching anything already in the URL (string insert keeps the original encoding of every
|
||||
// existing param); an existing lsclk is never replaced; a URL that does not parse goes out unchanged
|
||||
function withClickId(target, id) {
|
||||
const t = String(target || '');
|
||||
let u; try { u = new URL(t); } catch (e) { return t; }
|
||||
if (!/^https?:$/.test(u.protocol) || u.searchParams.has('lsclk')) return t;
|
||||
const hashAt = t.indexOf('#'); const base = hashAt >= 0 ? t.slice(0, hashAt) : t; const hash = hashAt >= 0 ? t.slice(hashAt) : '';
|
||||
const sep = base.includes('?') ? (/[?&]$/.test(base) ? '' : '&') : '?';
|
||||
return base + sep + 'lsclk=' + encodeURIComponent(id) + hash;
|
||||
}
|
||||
|
||||
// ---- own-click tests (Marty approved 2026-10-26) ----
|
||||
// A member's own click is a test on LinkSpin, on every click type. LinkSpin knows the soft keys its members sign in from;
|
||||
// InstantAdPay members may never sign in there, so the soft keys of their InstantAdPay sessions ride along with the click
|
||||
// push as owners: [{ owner, sk, ts }] (no raw IP, same hash as the click rows). Queued at most once per 6 h per
|
||||
// email + soft key; a failed push puts them back. Also checked here so an own click is flagged self=1 at the source.
|
||||
const OWN_MS = 31 * 86400e3, ownSeen = new Map(); let ownQueue = new Map();
|
||||
function noteSession(email, ip, ua) {
|
||||
const e = String(email || '').trim().toLowerCase(); if (!e || e.length > 190) return false;
|
||||
const sk = softKey(ip, ua); const k = e + '|' + sk; const now = Date.now();
|
||||
if (now - (ownSeen.get(k) || 0) < 6 * 3600e3) return false;
|
||||
ownSeen.set(k, now); if (ownSeen.size > 50000) ownSeen.delete(ownSeen.keys().next().value);
|
||||
if (on()) { ownQueue.set(k, { owner: e, sk, ts: now }); if (ownQueue.size > 5000) ownQueue.delete(ownQueue.keys().next().value); }
|
||||
return true;
|
||||
}
|
||||
function isOwnerSk(owner, sk) { const t = ownSeen.get(String(owner || '').toLowerCase() + '|' + sk); return !!(t && Date.now() - t <= OWN_MS); }
|
||||
function takeOwners() { const out = [...ownQueue.values()].slice(0, 2000); for (const o of out) ownQueue.delete(o.owner + '|' + o.sk); return out; }
|
||||
function requeueOwners(list) { for (const o of list || []) if (!ownQueue.has(o.owner + '|' + o.sk)) ownQueue.set(o.owner + '|' + o.sk, o); }
|
||||
|
||||
// ---- storage ----
|
||||
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!Array.isArray(jstate.rows)) throw 0; } catch (e) { jstate = { rows: [] }; } return jstate; }
|
||||
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 500); }
|
||||
function jcap() { const st = jload(); if (st.rows.length <= JCAP) return; let drop = st.rows.length - JCAP; st.rows = st.rows.filter(r => !(drop > 0 && r.pushed && drop--)); if (st.rows.length > JCAP) st.rows = st.rows.slice(-JCAP); }
|
||||
|
||||
// c = the campaign (ads.campaignById shape); returns the stored row
|
||||
async function record(c, req, opts) {
|
||||
const o = opts || {};
|
||||
const ip = o.ip || String(req.headers['x-forwarded-for'] || req.socket.remoteAddress || '').split(',')[0].trim();
|
||||
const ua = String(req.headers['user-agent'] || '');
|
||||
const row = { id: newId(), camp: Number(c.id), cname: String(c.name || c.title || '').slice(0, 80) || null, type: String(c.type || '').slice(0, 12) || null,
|
||||
owner: String(c.owner || '').toLowerCase(), ts: Date.now(), sk: softKey(ip, ua), c: o.country ? String(o.country).slice(0, 4) : null, dv: deviceOf(ua),
|
||||
pl: placementOf(req.headers.referer), target: String(o.target || c.targetUrl || '').slice(0, 500), spent: Math.max(0, Math.round(Number(c.spent || 0) + Number(c.accrued || 0))), self: o.self ? 1 : 0 };
|
||||
if (useDb()) {
|
||||
await R.db.q('INSERT INTO ad_clicks (id, campaign_id, owner_email, cname, ctype, sk, country, device, placement, target, spent, is_self, ts, pushed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,0)',
|
||||
[row.id, row.camp, row.owner, row.cname, row.type, row.sk, row.c, row.dv, row.pl, row.target, row.spent, row.self, row.ts]);
|
||||
} else { const st = jload(); st.rows.push(Object.assign({ pushed: 0 }, row)); jcap(); jsave(); }
|
||||
return row;
|
||||
}
|
||||
const fromDb = r => ({ id: r.id, camp: Number(r.campaign_id), cname: r.cname, type: r.ctype, owner: r.owner_email, ts: Number(r.ts), sk: r.sk, c: r.country, dv: r.device, pl: r.placement, target: r.target, spent: Number(r.spent) || 0, self: Number(r.is_self) ? 1 : 0 });
|
||||
async function unpushed(n) {
|
||||
if (useDb()) return (await R.db.q('SELECT * FROM ad_clicks WHERE pushed=0 ORDER BY ts LIMIT ?', [n])).map(fromDb);
|
||||
return jload().rows.filter(r => !r.pushed).slice(0, n).map(r => { const x = Object.assign({}, r); delete x.pushed; return x; });
|
||||
}
|
||||
async function markPushed(ids) {
|
||||
if (!ids.length) return;
|
||||
if (useDb()) { await R.db.q('UPDATE ad_clicks SET pushed=1 WHERE id IN (?)', [ids]); return; }
|
||||
const set = new Set(ids); for (const r of jload().rows) if (set.has(r.id)) r.pushed = 1; jsave();
|
||||
}
|
||||
async function prune() { // click rows only matter for the 30-day window; keep 120 days for questions
|
||||
const cut = Date.now() - 120 * 86400e3;
|
||||
if (useDb()) await R.db.q('DELETE FROM ad_clicks WHERE pushed=1 AND ts<?', [cut]);
|
||||
else { const st = jload(); const n = st.rows.length; st.rows = st.rows.filter(r => !(r.pushed && r.ts < cut)); if (st.rows.length !== n) jsave(); }
|
||||
}
|
||||
|
||||
// ---- LinkSpin calls ----
|
||||
async function signedPost(pth, body, timeoutMs) {
|
||||
const raw = JSON.stringify(body || {}); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(URL_() + pth, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(timeoutMs || 15000) });
|
||||
const txt = await r.text(); let j = null; try { j = JSON.parse(txt); } catch (e) {}
|
||||
if (!r.ok) { const e = new Error((j && j.error) || ('linkspin ' + r.status)); e.status = r.status; e.plain = !!(j && j.error); throw e; }
|
||||
return j || {};
|
||||
}
|
||||
async function flush() {
|
||||
if (!on() || flushing || Date.now() < nextAt) return { skipped: true };
|
||||
flushing = true; let sent = 0;
|
||||
try {
|
||||
for (let round = 0; round < 20; round++) { // drain a backlog, 500 at a time; owners (own soft keys) ride on the first request
|
||||
const rows = await unpushed(500); const owners = round === 0 ? takeOwners() : [];
|
||||
if (!rows.length && !owners.length) break;
|
||||
let res; try { res = await signedPost('/api/partner/clicks', { clicks: rows, owners }, 20000); } catch (e) { requeueOwners(owners); throw e; }
|
||||
if (!res || res.ok !== true) { requeueOwners(owners); throw new Error('linkspin answered without ok'); }
|
||||
if (rows.length) { await markPushed(rows.map(r => r.id)); sent += rows.length; stats.pushed += rows.length; stats.lastAt = Date.now(); }
|
||||
if (owners.length) stats.owners = (stats.owners || 0) + owners.length;
|
||||
if (rows.length < 500) break;
|
||||
}
|
||||
fails = 0; nextAt = 0; return { sent };
|
||||
} catch (e) {
|
||||
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 3000 * Math.pow(2, Math.min(fails, 7)));
|
||||
if (fails <= 3 || fails % 20 === 0) console.error('lsconv push', e.message);
|
||||
return { error: e.message, sent };
|
||||
} finally { flushing = false; }
|
||||
}
|
||||
// op summary is cached 60 s per email; any write clears that email's cache
|
||||
async function summary(email, fresh) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
const hit = cache.get(e); if (!fresh && hit && Date.now() - hit.at < 60000) return hit.data;
|
||||
const data = await signedPost('/api/partner/conv', { op: 'summary', email: e, days: 30 }, 8000);
|
||||
cache.set(e, { at: Date.now(), data }); if (cache.size > 2000) cache.delete(cache.keys().next().value);
|
||||
return data;
|
||||
}
|
||||
async function goalOp(email, op, fields) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
if (!['create', 'update', 'remove', 'test'].includes(op)) throw new Error('Unknown action.');
|
||||
const body = Object.assign({ op, email: e }, fields || {});
|
||||
const out = await signedPost('/api/partner/conv', body, 10000);
|
||||
cache.delete(e); return out;
|
||||
}
|
||||
function adminView() { return { on: on(), url: URL_(), pushed: stats.pushed, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
|
||||
module.exports = { signedPost, init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
|
||||
@@ -0,0 +1,195 @@
|
||||
// Inbound registry rows from LinkSpin (2026-10-15, the reverse of lssync.js). Marty: someone whose FIRST contact is a
|
||||
// LinkSpin member's link is placed right on LinkSpin, but InstantAdPay never heard of them, so a later InstantAdPay join
|
||||
// without that link landed under another sponsor or the company. LinkSpin's iapsync.js now posts its rows here
|
||||
// (POST /api/partner/registry, HMAC LS_SYNC_SECRET over ts + newline + raw body; see server.js).
|
||||
//
|
||||
// Per row {email, username, wallet, sponsorEmail, joinedAt, profile}:
|
||||
// - FIRST-PLATFORM RULE: an email that already has an InstantAdPay account keeps its sponsor. Only EMPTY fields are
|
||||
// filled: username (if free and allowed here), wallet (if no other account or linked position holds it), profile.
|
||||
// A conflict is skipped and logged, never forced.
|
||||
// - A new email becomes a waiting (shell) account, joinedVia 'linkspin', under its LinkSpin sponsor's InstantAdPay
|
||||
// account. A sponsor not on InstantAdPay yet gets a shell too, from rows received in this or an earlier batch,
|
||||
// climbing at most 25 levels (as LinkSpin's carry.js does). A sponsor whose row has not arrived is remembered
|
||||
// (pending) and bound when it does, as long as the shell is still unclaimed and still has no sponsor.
|
||||
// - Nothing here sends mail or notices, touches the chain or runs the sign-up anti-fraud checks (there is no request:
|
||||
// no IP, no device). The checks run when the owner claims the shell at their first sign-in (server.js), and until
|
||||
// then accounts.listAll leaves unclaimed shells out of every sweep that mails, counts or adopts members.
|
||||
// - Loop guard: each email is muted in lssync while its row is applied, then lssync records the result as already
|
||||
// pushed when it equals what LinkSpin sent, so it is not bounced back (see lssync.release). No-op rows change nothing.
|
||||
// - SPONSOR FOLLOW (2026-10-22, sponsorfollow.js): a row that carries a DELIBERATE change made on LinkSpin (sponsorSetBy
|
||||
// adopt / rescue / release / expire / admin) is the one exception to the first-platform rule: it is applied, a clear
|
||||
// back to the tank included, when the member is not bound on InstantAdPay's contract (no memberId, not on chain), the
|
||||
// change is newer than our own deliberate change, and the two sides agreed before it (or we have no sponsor). Bound,
|
||||
// diverged and race cases change nothing here and are logged for Admin > Members > Sponsor check. Applied quietly.
|
||||
// - NETWORK TANK: a row's `tank` (LinkSpin's own adoptions of the person) is kept as remote state, so our waiting list
|
||||
// hides someone adopted on LinkSpin and the two-adoptions limit counts both sites.
|
||||
'use strict';
|
||||
const SF = require('./sponsorfollow');
|
||||
const prohibited = require('./prohibited'); // 2026-10-30: policy applied on ingest
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, st = null, chain_ = Promise.resolve();
|
||||
const MAX_UP = 25;
|
||||
const FILE = () => path.join(R.dataDir, 'lsinbound.json');
|
||||
const norm = v => String(v || '').trim().toLowerCase();
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
function load() {
|
||||
if (st) return st;
|
||||
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = null; }
|
||||
if (!st || typeof st !== 'object') st = {};
|
||||
st.rows = st.rows || {}; st.pending = st.pending || {}; st.log = st.log || [];
|
||||
st.stats = Object.assign({ batches: 0, received: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, errors: 0 }, st.stats || {});
|
||||
return st;
|
||||
}
|
||||
function save() { try { const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(load())); fs.renameSync(tmp, FILE()); } catch (e) { console.error('lsinbound save', e.message); } }
|
||||
function note(ev) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, ev)); if (s.log.length > 300) s.log = s.log.slice(-300); }
|
||||
function init(deps) { R = deps; load(); } // { dataDir, accounts, lssync, follow (sponsorfollow glue), store (sponsorfollow store) }
|
||||
|
||||
function clean(x) {
|
||||
if (!x || typeof x !== 'object') return null;
|
||||
const email = norm(x.email); if (!EMAIL_RE.test(email) || email.length > 190) return null;
|
||||
const username = norm(x.username).replace(/^@/, '') || null;
|
||||
const wallet = /^0x[0-9a-f]{40}$/.test(norm(x.wallet)) ? norm(x.wallet) : null;
|
||||
let sponsorEmail = norm(x.sponsorEmail); if (!EMAIL_RE.test(sponsorEmail) || sponsorEmail === email) sponsorEmail = null;
|
||||
const profile = x.profile && typeof x.profile === 'object' ? x.profile : null;
|
||||
const out = { email, username, wallet, sponsorEmail, joinedAt: Number(x.joinedAt) || null, profile };
|
||||
if (SF.isDeliberate(x.sponsorSetBy) && Number(x.sponsorSetAt) > 0) { // a deliberate change on LinkSpin (sponsorfollow.js)
|
||||
out.sponsorSetAt = Number(x.sponsorSetAt); out.sponsorSetBy = String(x.sponsorSetBy);
|
||||
const pv = norm(x.sponsorPrevEmail); out.sponsorPrevEmail = EMAIL_RE.test(pv) ? pv : null;
|
||||
out.sponsorSetOrigin = norm(x.sponsorSetOrigin).replace(/[^a-z]/g, '').slice(0, 20) || 'linkspin';
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(x, 'tank')) out.tank = SF.cleanTank(x.tank); // null = LinkSpin has no adoption of them now
|
||||
return out;
|
||||
}
|
||||
const tokenOf = a => a.username || a.code;
|
||||
// released / rescued / expired back to the tank on purpose here: an ordinary row must not refill the sponsor (sponsorfollow.js)
|
||||
const emptiedOnPurpose = email => { const pv = R.store && R.store.get(email); return !!(pv && SF.isDeliberate(pv.by) && !pv.sponsorEmail); };
|
||||
function conflict(sum, email, kind, detail) { sum.conflicts++; note({ type: 'conflict', email, kind, detail: String(detail || '').slice(0, 120) }); }
|
||||
|
||||
// would binding `email` under `sp` close a loop (sp already sits below email)?
|
||||
async function wouldCycle(email, sp) {
|
||||
let cur = sp; const seen = new Set();
|
||||
for (let i = 0; cur && i < 60; i++) {
|
||||
if (cur.email === email) return true; if (seen.has(cur.email)) return true; seen.add(cur.email);
|
||||
cur = await R.accounts.sponsorOf(cur.email);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
// the sponsor's InstantAdPay account, building their shell (and theirs, upward) from known rows when needed
|
||||
async function sponsorAccount(spEmail, depth, ctx) {
|
||||
const sp = await R.accounts.byEmail(spEmail); if (sp) return sp;
|
||||
if (depth >= MAX_UP || !load().rows[spEmail] || ctx.done.has(spEmail)) return null;
|
||||
return place(spEmail, depth + 1, ctx);
|
||||
}
|
||||
// fill only what is empty; returns true when something was written
|
||||
async function fill(a, r, sum) {
|
||||
let wrote = false; const A = R.accounts;
|
||||
if (r.username && !a.username) {
|
||||
const other = await A.byUsername(r.username);
|
||||
if (other && other.email !== a.email) conflict(sum, a.email, 'username-taken', r.username);
|
||||
else { const x = await A.setUsername(a.email, r.username); if (x && x.error) conflict(sum, a.email, 'username', r.username + ': ' + x.error); else { sum.filled++; wrote = true; } }
|
||||
}
|
||||
if (r.wallet) {
|
||||
if (!a.address) {
|
||||
const other = await A.byAddress(r.wallet);
|
||||
if (other && other.email !== a.email) conflict(sum, a.email, 'wallet-taken', r.wallet);
|
||||
else { const x = await A.linkWallet(a.email, r.wallet); if (x && x.error) conflict(sum, a.email, 'wallet', r.wallet + ': ' + x.error); else { sum.filled++; wrote = true; } }
|
||||
} else if (norm(a.address) !== r.wallet) conflict(sum, a.email, 'wallet-differs', r.wallet); // InstantAdPay's wallet stands
|
||||
}
|
||||
if (r.profile && A.setProfile) { // same rules as LinkSpin's side: https only, known socials, fills only what is empty
|
||||
const pf = r.profile, ok = v => /^https:[/][/][^ ]+$/i.test(v) && v.length <= 300;
|
||||
// prohibited-content policy on ingest (2026-10-30): a bio with a link or a prohibited term, or a social carrying one, is dropped, not stored
|
||||
const cp = prohibited.cleanProfile(pf, 'InstantAdPay'); if (cp.dropped.length) console.log('lsinbound profile dropped', String(a.email).replace(/^(.).*(@.*)$/, '$1***$2'), cp.dropped.join(','));
|
||||
const av = String(pf.avatarUrl || '').trim(); const bio = cp.bio || ''; let soc = null;
|
||||
if (cp.socials) { const c = {}; for (const k of ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']) { const v = String(cp.socials[k] || '').trim(); if (ok(v)) c[k] = v; } if (Object.keys(c).length) soc = JSON.stringify(c); }
|
||||
const upd = [!a.avatarUrl && ok(av) ? av : undefined, !a.bio && bio ? bio : undefined, !a.socials && soc ? soc : undefined];
|
||||
if (upd.some(v => v !== undefined)) { const x = await A.setProfile(a.email, upd[0], upd[1], upd[2]); if (!(x && x.error)) { sum.filled++; wrote = true; } }
|
||||
}
|
||||
return wrote;
|
||||
}
|
||||
async function place(email, depth, ctx) {
|
||||
const s = load(); const r = s.rows[email]; const A = R.accounts;
|
||||
if (ctx.done.has(email)) return A.byEmail(email);
|
||||
ctx.done.add(email); R.lssync.mute(email);
|
||||
let a = await A.byEmail(email); let wrote = false;
|
||||
if (!r) return a;
|
||||
const inc = SF.incomingOf(r);
|
||||
if (a && inc && R.follow) {
|
||||
// a deliberate sponsor change made on LinkSpin: the follow rule decides (never on a member bound here)
|
||||
const d = await R.follow.applyIncoming(email, r, { sponsorAccount: em => sponsorAccount(em, depth, ctx) });
|
||||
if (d.apply) { ctx.sum.followed++; wrote = true; delete s.pending[email]; note({ type: 'follow', email, by: r.sponsorSetBy, sponsor: r.sponsorEmail || null, action: d.action }); }
|
||||
else if (d.action !== 'same' && d.action !== 'ordinary') { ctx.sum.followKept++; note({ type: 'follow-kept', email, by: r.sponsorSetBy, action: d.action, detail: String(d.reason || '').slice(0, 120) }); }
|
||||
a = await A.byEmail(email);
|
||||
} else if (!a) {
|
||||
let tok = '';
|
||||
if (r.sponsorEmail) {
|
||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||
if (sp) tok = tokenOf(sp); else { s.pending[email] = r.sponsorEmail; ctx.sum.pendingSponsor++; }
|
||||
}
|
||||
const x = await A.ensure(email, tok, ctx.via || 'linkspin', ctx.refOf ? ctx.refOf(email) : 'linkspin'); // hubsync.js passes its own via (2026-11-12)
|
||||
if (!x || x.error) { conflict(ctx.sum, email, 'create', x && x.error); return null; }
|
||||
a = x.account;
|
||||
if (x.created) { ctx.sum.created++; wrote = true; note({ type: 'shell', email, sponsor: tok || null, pending: tok ? null : (r.sponsorEmail || null) }); }
|
||||
// a new waiting account built from a deliberate change carries the same record, so its row does not echo back
|
||||
if (x.created && inc && R.store && (!r.sponsorEmail || tok)) R.store.record(email, { at: inc.at, by: inc.by, sponsorEmail: inc.sponsorEmail, prevEmail: inc.prevEmail, origin: inc.origin || 'linkspin' });
|
||||
} else if (A.isUnclaimedShell(a) && !a.sponsorRef && r.sponsorEmail && !emptiedOnPurpose(email)) {
|
||||
// our own waiting account, still without a sponsor: this row (or a later one) names one
|
||||
const sp = await sponsorAccount(r.sponsorEmail, depth, ctx);
|
||||
if (sp && sp.email !== email && !(await wouldCycle(email, sp))) { await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++; wrote = true; }
|
||||
else if (!sp) s.pending[email] = r.sponsorEmail;
|
||||
}
|
||||
if (await fill(a, r, ctx.sum)) wrote = true;
|
||||
if (!wrote) ctx.sum.noop++;
|
||||
return A.byEmail(email);
|
||||
}
|
||||
// shells waiting for a sponsor whose row has now arrived (or whose account now exists)
|
||||
async function resolvePending(ctx) {
|
||||
const s = load(); const A = R.accounts;
|
||||
for (const [email, spEmail] of Object.entries(s.pending)) {
|
||||
const a = await A.byEmail(email);
|
||||
if (!a || !A.isUnclaimedShell(a) || a.sponsorRef || emptiedOnPurpose(email)) { delete s.pending[email]; continue; } // claimed, bound or emptied on purpose meanwhile: leave it
|
||||
const sp = await sponsorAccount(spEmail, 0, ctx); if (!sp) continue;
|
||||
if (sp.email === email || await wouldCycle(email, sp)) { delete s.pending[email]; conflict(ctx.sum, email, 'sponsor-cycle', spEmail); continue; }
|
||||
R.lssync.mute(email); ctx.done.add(email);
|
||||
await A.setSponsorRef(email, tokenOf(sp)); delete s.pending[email]; ctx.sum.sponsored++;
|
||||
note({ type: 'sponsored', email, sponsor: tokenOf(sp) });
|
||||
}
|
||||
}
|
||||
async function handle(rows, opts) {
|
||||
const s = load(); s.stats.batches++;
|
||||
const sum = { rows: 0, noop: 0, created: 0, filled: 0, sponsored: 0, conflicts: 0, pendingSponsor: 0, errors: 0, followed: 0, followKept: 0, tank: 0 };
|
||||
const ctx = { sum, done: new Set(), via: opts && opts.via, refOf: opts && opts.refOf }; const batch = [];
|
||||
for (const x of rows || []) { const r = clean(x); if (!r) continue; sum.rows++; s.rows[r.email] = r; batch.push(r); }
|
||||
if (R.store) for (const r of batch) if (Object.prototype.hasOwnProperty.call(r, 'tank')) { R.store.setRemote(r.email, r.tank); sum.tank++; } // network tank
|
||||
try {
|
||||
for (const r of batch) {
|
||||
try { await place(r.email, 0, ctx); }
|
||||
catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), email: r.email, error: String(e.message).slice(0, 160) }; console.error('lsinbound', r.email, e.message); }
|
||||
}
|
||||
try { await resolvePending(ctx); } catch (e) { sum.errors++; s.stats.lastError = { at: Date.now(), error: 'pending: ' + String(e.message).slice(0, 160) }; }
|
||||
} finally {
|
||||
for (const email of ctx.done) await R.lssync.release(email, s.rows[email]); // loop guard: equal results are not echoed
|
||||
}
|
||||
s.stats.received += sum.rows; for (const k of ['noop', 'created', 'filled', 'sponsored', 'conflicts', 'errors', 'followed', 'followKept']) s.stats[k] = (s.stats[k] || 0) + sum[k];
|
||||
s.last = Object.assign({ at: Date.now() }, sum); save();
|
||||
return Object.assign({ proto: SF.PROTO }, sum); // proto 2: this side understands sponsor follow + network tank facts
|
||||
}
|
||||
// batches are applied one at a time (two overlapping posts must not both create the same sponsor shell)
|
||||
// opts (hubsync.js only): { via, refOf(email) } names where a new waiting account came from; LinkSpin's posts pass none
|
||||
function receive(rows, opts) { const run = chain_.then(() => handle(rows, opts)); chain_ = run.catch(() => {}); return run; }
|
||||
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() });
|
||||
}
|
||||
// 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 };
|
||||
@@ -0,0 +1,151 @@
|
||||
// Conversion linkage, InstantAdPay half (Marty 2026-11-07, "Yes ship these"). REPORTING ONLY: this module never reads or changes a
|
||||
// sponsor, a payout, credits or anything on chain. LinkSpin owns the counting; this keeps the click and tells it what happened.
|
||||
// the click arrives as ?lsclk= or ?lsid= on any page: a first-party cookie iap.lsclk, 30 days, last click wins (the same life
|
||||
// and last-touch rule as the sponsor cookie), plus the page's own copy sent with the code request, because the
|
||||
// cookie is refused inside a traffic-exchange frame and never crosses browsers (the 2026-09-29 sponsor lesson)
|
||||
// the account kept in its own table, ls_account_clicks, keyed by email: remembered when the code is requested, bound when the
|
||||
// account is created (or a waiting LinkSpin shell is claimed). Its own table on purpose: accounts is not touched
|
||||
// the events sign-up, wallet link, each package Purchase on the chain, by an account with a bound click. One row each in
|
||||
// ls_events; its primary key is the idempotency key (join:<hash>, wallet:<hash>, purchase:<tx>:<log index>), so two
|
||||
// app copies during a deploy can both try and only one row exists
|
||||
// the delivery a loop in the background posts unsent rows to LinkSpin (POST /api/partner/conv op events, signed like lsconv), 100
|
||||
// at a time, every ~5 s with backoff to 5 minutes. A row is marked sent only after LinkSpin answers, and LinkSpin
|
||||
// dedupes by the same key, so a row sent by both copies, or twice, counts once
|
||||
// Nothing here runs in the chain event handler's path or in a sign-up's path beyond one local write: LinkSpin down, slow or
|
||||
// blocked changes nothing except that rows wait. No LS_SYNC_SECRET: rows wait too.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const lsconv = require('./lsconv');
|
||||
|
||||
let R = null, timer = null, flushing = false, fails = 0, nextAt = 0, jstate = null, saveT = null;
|
||||
const stats = { sent: 0, lastAt: null, lastError: null, errors: 0 };
|
||||
const DAY = 86400000, WINDOW = 30 * DAY;
|
||||
const useDb = () => !!(R && R.db && R.db.enabled());
|
||||
const JFILE = () => path.join(R.dataDir, 'lsreport.json');
|
||||
const norm = e => String(e || '').trim().toLowerCase();
|
||||
const isId = v => /^(?:[a-f0-9]{10}|[aik][a-f0-9]{11})$/.test(String(v || ''));
|
||||
const hash = email => crypto.createHash('sha256').update(norm(email)).digest('hex').slice(0, 24);
|
||||
// the id in a page address, or '' (lsclk first: it is the id the landing tag and ad clicks carry)
|
||||
const fromUrl = u => { const v = u.searchParams.get('lsclk') || u.searchParams.get('lsid') || ''; return isId(v) ? v : ''; };
|
||||
const pick = (...vals) => { for (const v of vals) if (isId(v)) return String(v); return ''; };
|
||||
const COOKIE = 'iap.lsclk';
|
||||
const cookieHeader = (id, isProd) => COOKIE + '=' + id + '; Path=/; Max-Age=' + (30 * 86400) + '; ' + (isProd ? 'SameSite=None; Secure' : 'SameSite=Lax');
|
||||
|
||||
function init(deps) {
|
||||
R = deps;
|
||||
if (useDb()) ensureTables().catch(e => console.error('lsreport tables', e.message));
|
||||
if (!deps.noTimers) {
|
||||
if (!timer) { timer = setInterval(() => { flush().catch(() => {}); }, 5000); if (timer.unref) timer.unref(); }
|
||||
setInterval(() => prune().catch(() => {}), 6 * 3600 * 1000).unref();
|
||||
}
|
||||
}
|
||||
// column names checked against MySQL 8 reserved words (none of email, click_id, ts, bound, k, ev, cents, ev_ts, tx, sk, pushed, outcome is reserved)
|
||||
async function ensureTables() {
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS ls_account_clicks (
|
||||
email VARCHAR(190) PRIMARY KEY,
|
||||
click_id VARCHAR(16) NOT NULL,
|
||||
ts BIGINT NOT NULL,
|
||||
bound TINYINT NOT NULL DEFAULT 0
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
await R.db.q(`CREATE TABLE IF NOT EXISTS ls_events (
|
||||
k VARCHAR(120) PRIMARY KEY,
|
||||
ev VARCHAR(10) NOT NULL,
|
||||
email VARCHAR(190) NOT NULL,
|
||||
click_id VARCHAR(16) NOT NULL,
|
||||
cents INT NOT NULL DEFAULT 0,
|
||||
ev_ts BIGINT NOT NULL,
|
||||
tx VARCHAR(80) NULL,
|
||||
sk VARCHAR(24) NULL,
|
||||
pushed TINYINT NOT NULL DEFAULT 0,
|
||||
outcome VARCHAR(12) NULL,
|
||||
INDEX (pushed, ev_ts)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`);
|
||||
}
|
||||
|
||||
// ---- JSON store (local runs) ----
|
||||
function jload() { if (jstate) return jstate; try { jstate = JSON.parse(fs.readFileSync(JFILE(), 'utf8')); if (!jstate.clicks || !Array.isArray(jstate.events)) throw 0; } catch (e) { jstate = { clicks: {}, events: [] }; } return jstate; }
|
||||
function jsave() { if (saveT) return; saveT = setTimeout(() => { saveT = null; try { fs.writeFileSync(JFILE(), JSON.stringify(jload())); } catch (e) {} }, 300); if (saveT.unref) saveT.unref(); }
|
||||
|
||||
// ---- the click on the account ----
|
||||
async function clickOf(email) {
|
||||
const e = norm(email);
|
||||
if (useDb()) { const r = (await R.db.q('SELECT click_id, ts, bound FROM ls_account_clicks WHERE email=?', [e]))[0]; return r ? { click: r.click_id, ts: Number(r.ts), bound: Number(r.bound) ? 1 : 0 } : null; }
|
||||
return jload().clicks[e] || null;
|
||||
}
|
||||
// at the code request: the click travels with the email, so verifying in another browser still finds it. Last click wins until bound.
|
||||
async function remember(email, click) {
|
||||
const e = norm(email); if (!e || e.length > 190 || !isId(click)) return false;
|
||||
const now = Date.now();
|
||||
if (useDb()) { await R.db.q('INSERT INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0) ON DUPLICATE KEY UPDATE click_id=IF(bound=0,VALUES(click_id),click_id), ts=IF(bound=0,VALUES(ts),ts)', [e, click, now]); return true; }
|
||||
const st = jload(); if (st.clicks[e] && st.clicks[e].bound) return false; st.clicks[e] = { click, ts: now, bound: 0 }; jsave(); return true;
|
||||
}
|
||||
// the account now exists: bind the click (this request's, else the remembered one), once, and queue the join
|
||||
async function signup(email, click, sk) {
|
||||
const e = norm(email); if (!e || e.length > 190) return false;
|
||||
const row = await clickOf(e); if (row && row.bound) return false;
|
||||
const c = isId(click) ? click : (row && Date.now() - row.ts <= WINDOW ? row.click : ''); if (!c) return false;
|
||||
const now = Date.now();
|
||||
if (useDb()) {
|
||||
await R.db.q('INSERT IGNORE INTO ls_account_clicks (email, click_id, ts, bound) VALUES (?,?,?,0)', [e, c, now]);
|
||||
const u = await R.db.q('UPDATE ls_account_clicks SET click_id=?, ts=?, bound=1 WHERE email=? AND bound=0', [c, now, e]);
|
||||
if (!(u && u.affectedRows === 1)) return false;
|
||||
} else { const st = jload(); st.clicks[e] = { click: c, ts: now, bound: 1 }; jsave(); }
|
||||
await enqueue({ k: 'join:' + hash(e), ev: 'join', email: e, click: c, cents: 0, ts: now, sk: /^s:[a-f0-9]{20}$/.test(String(sk || '')) ? sk : null });
|
||||
return true;
|
||||
}
|
||||
async function wallet(email) {
|
||||
const e = norm(email); const row = await clickOf(e); if (!row || !row.bound) return false;
|
||||
return enqueue({ k: 'wallet:' + hash(e), ev: 'wallet', email: e, click: row.click, cents: 0, ts: Date.now() });
|
||||
}
|
||||
// a Purchase chain event, already resolved to its account. Value = the USD price on the event. Linked positions sit on the same
|
||||
// account, so they count as that account's purchases. Past the click window nothing is queued: LinkSpin would refuse it anyway
|
||||
// (the bind is never earlier than the click, so more than 30 days after the bind is more than 30 days after the click).
|
||||
async function purchase(ev, email) {
|
||||
const e = norm(email); const cents = Number(ev && ev.priceCents) || 0; if (!e || cents <= 0 || !ev.tx) return false;
|
||||
const row = await clickOf(e); if (!row || !row.bound) return false;
|
||||
const ts = Number(ev.ts) || Date.now();
|
||||
if (ts < row.ts - 60000 || ts - row.ts > WINDOW) return false; // before the sign-up, or past the window
|
||||
return enqueue({ k: ('purchase:' + ev.tx + ':' + ev.li).slice(0, 120), ev: 'purchase', email: e, click: row.click, cents, ts, tx: String(ev.tx).slice(0, 80) });
|
||||
}
|
||||
async function enqueue(x) {
|
||||
if (useDb()) { const r = await R.db.q('INSERT IGNORE INTO ls_events (k, ev, email, click_id, cents, ev_ts, tx, sk, pushed) VALUES (?,?,?,?,?,?,?,?,0)', [x.k, x.ev, x.email, x.click, x.cents, x.ts, x.tx || null, x.sk || null]); return !!(r && r.affectedRows === 1); }
|
||||
const st = jload(); if (st.events.some(r => r.k === x.k)) return false; st.events.push(Object.assign({ pushed: 0 }, x)); if (st.events.length > 5000) st.events = st.events.slice(-4000); jsave(); return true;
|
||||
}
|
||||
|
||||
// ---- delivery ----
|
||||
async function unsent(n) {
|
||||
if (useDb()) return (await R.db.q('SELECT k, ev, email, click_id, cents, ev_ts, tx, sk FROM ls_events WHERE pushed=0 ORDER BY ev_ts LIMIT ?', [n])).map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click_id, cents: Number(r.cents) || 0, ts: Number(r.ev_ts), tx: r.tx, sk: r.sk }));
|
||||
return jload().events.filter(r => !r.pushed).slice(0, n);
|
||||
}
|
||||
async function markSent(k, outcome) {
|
||||
if (useDb()) { await R.db.q('UPDATE ls_events SET pushed=1, outcome=? WHERE k=?', [String(outcome || '').slice(0, 12) || null, k]); return; }
|
||||
const r = jload().events.find(x => x.k === k); if (r) { r.pushed = 1; r.outcome = outcome; jsave(); }
|
||||
}
|
||||
async function flush() {
|
||||
if (!lsconv.on() || flushing || Date.now() < nextAt) return { skipped: true };
|
||||
flushing = true; let sent = 0;
|
||||
try {
|
||||
for (let round = 0; round < 10; round++) {
|
||||
const rows = await unsent(100); if (!rows.length) break;
|
||||
const res = await lsconv.signedPost('/api/partner/conv', { op: 'events', events: rows.map(r => ({ k: r.k, ev: r.ev, email: r.email, click: r.click, value: r.cents / 100, ts: r.ts, tx: r.tx || undefined, sk: r.sk || undefined })) }, 15000);
|
||||
if (!res || res.ok !== true || !Array.isArray(res.results)) throw new Error('linkspin answered without results');
|
||||
for (const a of res.results) { await markSent(a.k, a.result); sent++; stats.sent++; }
|
||||
stats.lastAt = Date.now();
|
||||
if (rows.length < 100) break;
|
||||
}
|
||||
fails = 0; nextAt = 0; return { sent };
|
||||
} catch (e) {
|
||||
fails++; stats.errors++; stats.lastError = e.message; nextAt = Date.now() + Math.min(300000, 5000 * Math.pow(2, Math.min(fails, 6)));
|
||||
if (fails <= 3 || fails % 20 === 0) console.error('lsreport push', e.message);
|
||||
return { error: e.message, sent };
|
||||
} finally { flushing = false; }
|
||||
}
|
||||
async function prune() {
|
||||
const now = Date.now(); const old = now - 60 * DAY, stale = now - 31 * DAY;
|
||||
if (useDb()) { await R.db.q('DELETE FROM ls_events WHERE ev_ts<?', [old]); await R.db.q('DELETE FROM ls_account_clicks WHERE (bound=0 AND ts<?) OR ts<?', [stale, old]); return; }
|
||||
const st = jload(); st.events = st.events.filter(r => r.ts >= old); for (const k of Object.keys(st.clicks)) { const c = st.clicks[k]; if (c.ts < old || (!c.bound && c.ts < stale)) delete st.clicks[k]; } jsave();
|
||||
}
|
||||
function adminView() { return { on: lsconv.on(), sent: stats.sent, lastAt: stats.lastAt, errors: stats.errors, lastError: stats.lastError, fails, nextAt: nextAt || null }; }
|
||||
module.exports = { init, ensureTables, fromUrl, pick, cookieHeader, COOKIE, isId, remember, signup, wallet, purchase, clickOf, flush, prune, adminView };
|
||||
@@ -0,0 +1,123 @@
|
||||
// LinkSpin registry sync (Marty 2026-10-08: "members in InstantAdPay synchronized with those waiting inside LinkSpin").
|
||||
// Two paths, same signed POST to LinkSpin /api/partner/registry (HMAC-SHA256 of ts + newline + raw body, LS_SYNC_SECRET):
|
||||
// touch(email) right after an account changes (created, named, wallet linked, sponsor bound): that row goes within ~3 s
|
||||
// tick() every 2 minutes: every account is hashed (username, wallet, sponsor, joined) against the last pushed
|
||||
// hash in DATA_DIR/lssync.json and only changed rows go, 100 per request. Catches anything touch() missed.
|
||||
// LinkSpin upserts the rows and creates shell accounts with their sponsor line, so a new InstantAdPay member is already
|
||||
// "waiting" on LinkSpin before they ever sign in there. Nothing here moves money; the registry is identity + line only.
|
||||
//
|
||||
// Sponsor follow (2026-10-22, sponsorfollow.js): a row also carries sponsorSetAt / sponsorSetBy / sponsorPrevEmail /
|
||||
// sponsorSetOrigin while the account's sponsor is the result of a deliberate change (tank adoption, rescue, release,
|
||||
// window expiry, admin edit), and `tank` (this site's own adoptions of the person: count + the open one, or null).
|
||||
// Rows without those facts hash exactly as before, so nothing is resent on deploy. Until LinkSpin answers proto 2 the
|
||||
// hash of a row carrying the new facts is not recorded, so it is sent again once LinkSpin runs the new code.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const SF = require('./sponsorfollow');
|
||||
const prohibited = require('./prohibited'); // 2026-10-30: a profile that fails the policy never leaves this site
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let R = null, state = null, pending = new Map(), timer = null, ticking = false;
|
||||
const muted = new Set(); // emails lsinbound.js is writing right now: their rows came FROM LinkSpin, hold them until it decides
|
||||
const URL_ = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.LS_SYNC_SECRET || '').trim();
|
||||
const on = () => SECRET().length >= 32;
|
||||
const FILE = () => path.join(R.dataDir, 'lssync.json');
|
||||
function load() { if (state) return state; try { state = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { state = { hashes: {}, pushed: 0, last: null, errors: 0 }; } return state; }
|
||||
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) {} }
|
||||
|
||||
function init(deps) { R = deps; load(); }
|
||||
async function rowFor(acct, byRef, tankMap) {
|
||||
const ref = String(acct.sponsorRef || '').toLowerCase(); let sponsorEmail = null;
|
||||
if (ref) { const sp = byRef ? byRef.get(ref) : (await R.accounts.byUsername(ref) || await R.accounts.byCode(ref)); if (sp && sp.email !== acct.email) sponsorEmail = sp.email; }
|
||||
const row = { email: acct.email, username: acct.username || null, wallet: acct.address || null, sponsorEmail, joinedAt: Number(acct.created) || null, memberId: acct.memberId || null, profile: profileOf(acct) };
|
||||
if (acct.joinedVia === 'btc4hits') row.origin = 'btc4hits'; // BTC4Hits import (2026-11-11): LinkSpin words its holding-tank mail for them
|
||||
if (R.follow) Object.assign(row, SF.rowFields(R.follow.get(acct.email), sponsorEmail) || {});
|
||||
const T = R.tank && R.tank();
|
||||
if (T) { try { row.tank = (tankMap ? tankMap.get(String(acct.email).toLowerCase()) : await T.summaryFor(acct.email)) || null; } catch (e) {} }
|
||||
return row;
|
||||
}
|
||||
const carriesNew = r => !!(r.sponsorSetBy || r.tank);
|
||||
// the member's profile travels too (Marty 2026-10-11: no re-typing on LinkSpin; they can change it there later). Avatar as an
|
||||
// absolute https URL so the other property can show it; socials as the parsed {platform: url} object.
|
||||
const PUBLIC = () => String(process.env.PUBLIC_URL || 'https://instantadpay.com').replace(/\/+$/, '');
|
||||
function profileOf(a) {
|
||||
if (a.profileQuarantined) return null; // quarantined (link planted on a brand-new free account): stays here, unseen, until Marty decides
|
||||
const cp = prohibited.cleanProfile({ avatarUrl: a.avatarUrl, bio: a.bio, socials: a.socials }, 'InstantAdPay'); // policy applied on the way out too
|
||||
const socials = cp.socials;
|
||||
const av = String(a.avatarUrl || '').trim();
|
||||
const avatarUrl = !av ? null : /^https:\/\//i.test(av) ? av : av.startsWith('/') ? PUBLIC() + av : null;
|
||||
const bio = cp.bio;
|
||||
// the BixPay partner link travels too (2026-10-29): LinkSpin shows it read-only ("Edit on InstantAdPay") and resolves the
|
||||
// same way; only set when there is one, so rows without it keep the hash they had
|
||||
const bixPartnerLink = String(a.bixPartnerLink || '').trim() || null;
|
||||
if (!avatarUrl && !bio && !bixPartnerLink && !(socials && Object.keys(socials).length)) return null;
|
||||
const out = { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
|
||||
if (bixPartnerLink) out.bixPartnerLink = bixPartnerLink;
|
||||
return out;
|
||||
}
|
||||
const hashOf = r => crypto.createHash('sha1').update([r.username || '', r.wallet || '', r.sponsorEmail || '', r.joinedAt || '', r.memberId || '', r.profile ? JSON.stringify(r.profile) : ''].join('|') + SF.hashExtra(r)).digest('hex').slice(0, 16);
|
||||
|
||||
async function post(rows) {
|
||||
const raw = JSON.stringify({ rows }); const ts = String(Date.now());
|
||||
const sig = crypto.createHmac('sha256', SECRET()).update(ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(URL_() + '/api/partner/registry', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-LS-Ts': ts, 'X-LS-Sig': sig }, body: raw, signal: AbortSignal.timeout(20000) });
|
||||
if (!r.ok) throw new Error('linkspin ' + r.status + ' ' + (await r.text()).slice(0, 120));
|
||||
return r.json();
|
||||
}
|
||||
async function push(rows) {
|
||||
const st = load(); let sent = 0;
|
||||
for (let i = 0; i < rows.length; i += 100) {
|
||||
const chunk = rows.slice(i, i + 100); const res = await post(chunk); sent += chunk.length;
|
||||
const peerNew = Number(res && res.proto) >= SF.PROTO; if (R.follow) R.follow.setPeer(peerNew ? SF.PROTO : 1);
|
||||
for (const r of chunk) { if (peerNew || !carriesNew(r)) st.hashes[r.email] = hashOf(r); } // an old LinkSpin ignored the new facts: send again later
|
||||
}
|
||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
||||
}
|
||||
// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed
|
||||
// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would
|
||||
// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone.
|
||||
const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a);
|
||||
// an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one)
|
||||
function touch(email) {
|
||||
if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now());
|
||||
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
|
||||
}
|
||||
// the reconcile pass: only rows whose hash changed since the last push
|
||||
async function tick(force) {
|
||||
if (!on() || ticking) return { skipped: true };
|
||||
ticking = true;
|
||||
try {
|
||||
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
||||
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const sent = rows.length ? await push(rows) : 0;
|
||||
return { accounts: all.length, changed: rows.length, sent };
|
||||
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
||||
finally { ticking = false; }
|
||||
}
|
||||
// Reverse-sync loop guard (2026-10-15, see lsinbound.js): while a LinkSpin row is being applied its email is muted; afterwards,
|
||||
// if the account now says exactly what LinkSpin sent (username, wallet, sponsor), its hash is recorded as already pushed, so
|
||||
// it is never sent back. When InstantAdPay's facts differ (its sponsor binding stood, a wallet was skipped) the row goes
|
||||
// back once; LinkSpin only fills empty fields, so that changes nothing there and its own hash stops a resend.
|
||||
function mute(email) { muted.add(String(email || '').toLowerCase()); }
|
||||
async function release(email, sent) {
|
||||
const e = String(email || '').toLowerCase(); muted.delete(e); let same = false;
|
||||
try {
|
||||
const a = await R.accounts.byEmail(e);
|
||||
if (a && sent) {
|
||||
const r = await rowFor(a); const n = v => String(v || '').toLowerCase();
|
||||
// a deliberate change from LinkSpin counts as the same only when we now carry that same record (applied, not refused)
|
||||
const sameFollow = !sent.sponsorSetBy || (Number(r.sponsorSetAt) === Number(sent.sponsorSetAt) && String(r.sponsorSetBy) === String(sent.sponsorSetBy));
|
||||
if (n(r.username) === n(sent.username) && n(r.wallet) === n(sent.wallet) && n(r.sponsorEmail) === n(sent.sponsorEmail) && sameFollow) { load().hashes[e] = hashOf(r); save(); same = true; }
|
||||
}
|
||||
} catch (err) {}
|
||||
if (pending.has(e) && !timer) { pending.delete(e); touch(e); } // a touch that queued while muted goes now (the hash check drops it when same)
|
||||
return same;
|
||||
}
|
||||
// does LinkSpin know this email? (its row was pushed and recorded) - used by the link-farm admin list, never for a cascade
|
||||
function knows(email) { const st = load(); return Object.prototype.hasOwnProperty.call(st.hashes || {}, String(email || '').toLowerCase()); }
|
||||
function adminView() { const st = load(); return { on: on(), url: URL_(), tracked: Object.keys(st.hashes).length, pushed: st.pushed, last: st.last, errors: st.errors, pendingTouches: pending.size }; }
|
||||
module.exports = { init, touch, tick, adminView, on, mute, release, knows };
|
||||
@@ -15,14 +15,38 @@ function key() {
|
||||
}
|
||||
function hasKey() { return !!key(); }
|
||||
|
||||
function send(to, subject, text) {
|
||||
// Opt-out rule (2026-10-15, Spamhaus DBL listing): every email except sign-in
|
||||
// codes and mail to the admin is skipped for anyone who unsubscribed, carries
|
||||
// the signed unsubscribe link (appended unless the body already has one) and
|
||||
// RFC 8058 one-click List-Unsubscribe headers. New senders inherit this.
|
||||
function isAdmin(to) { const a = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase(); return !!a && String(to).trim().toLowerCase() === a; }
|
||||
|
||||
async function send(to, subject, text, html, opts) { // html optional (2026-10-01): sent alongside the plain text, never instead of it
|
||||
const transactional = !!(opts && opts.transactional) || isAdmin(to);
|
||||
let unsub = '';
|
||||
if (!transactional) {
|
||||
const drip = require('./drip');
|
||||
try { if (await drip.isUnsubscribed(to)) return false; } catch (e) { console.error('mailer opt-out check', e.message); }
|
||||
try { unsub = drip.unsubUrl(to); } catch (e) { console.error('mailer unsub link', e.message); }
|
||||
}
|
||||
if (unsub && !String(text).includes('/unsubscribe?')) text = text + '\n\n--\nStop these emails: ' + unsub;
|
||||
if (unsub && html && !String(html).includes('/unsubscribe?')) {
|
||||
const foot = '<p style="font-size:12px;color:#888;margin-top:24px">Stop these emails: <a href="' + unsub + '" style="color:#888">unsubscribe</a></p>';
|
||||
html = /<\/body>/i.test(html) ? html.replace(/<\/body>/i, foot + '</body>') : html + foot;
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
const body = JSON.stringify({
|
||||
const content = [{ type: 'text/plain', value: text }];
|
||||
if (html) content.push({ type: 'text/html', value: html });
|
||||
const msg = {
|
||||
personalizations: [{ to: [{ email: to }] }],
|
||||
from: FROM,
|
||||
subject,
|
||||
content: [{ type: 'text/plain', value: text }]
|
||||
});
|
||||
content
|
||||
};
|
||||
if (unsub) msg.headers = { 'List-Unsubscribe': '<' + unsub + '>', 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click' };
|
||||
if (opts && opts.replyTo) msg.reply_to = { email: String(opts.replyTo) }; // help desk: replies thread back into the ticket
|
||||
if (opts && opts.headers) msg.headers = Object.assign(msg.headers || {}, opts.headers);
|
||||
const body = JSON.stringify(msg);
|
||||
const req = https.request({ hostname: 'api.sendgrid.com', path: '/v3/mail/send', method: 'POST',
|
||||
headers: { Authorization: 'Bearer ' + key(), 'Content-Type': 'application/json',
|
||||
'Content-Length': Buffer.byteLength(body) }, timeout: 15000 },
|
||||
@@ -41,7 +65,7 @@ function sendCode(to, code) {
|
||||
return send(to, code + ' is your InstantAdPay sign-in code',
|
||||
'Your sign-in code is: ' + code + '\n\n'
|
||||
+ 'It works for 15 minutes. If you did not request it, ignore this email.\n\n'
|
||||
+ 'InstantAdPay\nAdvertise and earn instantly. Locked in code, not promises.\nhttps://instantadpay.com');
|
||||
+ 'InstantAdPay\nAdvertise and earn instantly. Locked in code, not promises.\nhttps://instantadpay.com', null, { transactional: true });
|
||||
}
|
||||
|
||||
module.exports = { init, hasKey, send, sendCode };
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
// 1,000-member milestone drop (Marty, 2026-10-10): when the account count reaches the target, every member whose wallet is
|
||||
// ACTIVATED on chain (payouts switched on: the account's address maps to an on-chain member record with the activated
|
||||
// flag, and that member id is not on the no-payout list) receives `milestonePol` POL from a dedicated hot wallet, and is
|
||||
// told. Everyone else is told they missed it and how to be in the next one: link a wallet (no wallet yet) or switch on
|
||||
// payouts (wallet linked, not activated).
|
||||
//
|
||||
// Snapshot first, then pay: eligibility is frozen the moment the count crosses the target, so nothing linked afterwards
|
||||
// counts. Payments go one at a time from IAP_MILESTONE_KEY over the site's own RPC list (chain.getConfig().rpcs), each
|
||||
// row carrying its tx hash; a row is never sent twice (status due -> sent -> paid | failed). Notices are in-app
|
||||
// (kind 'notice') plus email: the paid email is transactional (everyone paid gets it), the missed-it email respects the
|
||||
// newsletter opt-in like every other nudge. One Telegram proof post at the start and one at the end (mirrored to Discord
|
||||
// by telegramSend), never one per payment. The total lands in the P&L as a rewards cost against Receiver A.
|
||||
//
|
||||
// Modes (site config milestoneMode): off | dry | armed. dry = snapshot and show, send nothing. State: DATA_DIR/milestone-1000.json.
|
||||
'use strict';
|
||||
const fs = require('fs'), path = require('path');
|
||||
let R = {}, DATA_DIR = '.', ethers = null, paying = false;
|
||||
const FILE = () => path.join(DATA_DIR, 'milestone-1000.json');
|
||||
const blank = () => ({ v: 1, status: 'idle', target: 1000, pol: 1, snapshotAt: 0, countAt: 0, rows: [], others: { noWallet: [], notActivated: [], suspended: 0 }, notified: { paidStart: 0, paidEnd: 0, missed: 0 }, log: [] });
|
||||
const load = () => { try { return Object.assign(blank(), JSON.parse(fs.readFileSync(FILE(), 'utf8'))); } catch (e) { return blank(); } };
|
||||
const save = s => { const f = FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(s)); fs.renameSync(f + '.tmp', f); };
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const logLine = (S, t) => { S.log.push({ at: Date.now(), t: String(t).slice(0, 300) }); if (S.log.length > 400) S.log = S.log.slice(-400); };
|
||||
const r4 = n => Math.round(Number(n) * 1e4) / 1e4;
|
||||
|
||||
function init(opts) { R = opts || {}; DATA_DIR = R.dataDir || '.'; }
|
||||
const cfg = () => { const sc = (R.siteConfig && R.siteConfig()) || {}; return { mode: ['off', 'dry', 'armed'].includes(sc.milestoneMode) ? sc.milestoneMode : 'off', target: Number(sc.milestoneTarget) || 1000, pol: Number(sc.milestonePol) > 0 ? Number(sc.milestonePol) : 1 }; };
|
||||
const keyOk = () => /^0x[0-9a-fA-F]{64}$/.test(String(process.env.IAP_MILESTONE_KEY || '').trim());
|
||||
function wallet() {
|
||||
if (!keyOk()) return null; if (!ethers) ethers = require('ethers');
|
||||
const c = R.chain.getConfig(); const rpcs = (c.rpcs || []).filter(Boolean); if (!rpcs.length) return null;
|
||||
const provider = new ethers.JsonRpcProvider(rpcs[0], Number(c.chainId) || 137);
|
||||
return { w: new ethers.Wallet(String(process.env.IAP_MILESTONE_KEY).trim(), provider), provider, explorer: c.explorer || 'https://polygonscan.com', chainId: Number(c.chainId) || 137 };
|
||||
}
|
||||
async function balance() { const W = wallet(); if (!W) return null; try { return Number(ethers.formatEther(await W.provider.getBalance(W.w.address))); } catch (e) { return null; } }
|
||||
const address = () => { const W = wallet(); return W ? W.w.address : null; };
|
||||
|
||||
// how many accounts exist right now (the number Marty watches on the admin Overview)
|
||||
async function accountCount() { const all = await R.accounts.listAll(100000); return all.length; }
|
||||
|
||||
// freeze the eligibility list: activated on chain, not on the no-payout list, not suspended
|
||||
async function snapshot(force) {
|
||||
const S = load(); const C = cfg();
|
||||
if (S.status !== 'idle' && !force) return S;
|
||||
const all = await R.accounts.listAll(100000); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set();
|
||||
const rows = [], noWallet = [], notActivated = []; let suspended = 0; const seenAddr = new Set();
|
||||
for (const a of all) {
|
||||
if (a.suspended) { suspended++; continue; }
|
||||
const addr = String(a.address || '').toLowerCase();
|
||||
if (!/^0x[0-9a-f]{40}$/.test(addr)) { noWallet.push(a.email); continue; }
|
||||
if (seenAddr.has(addr)) { notActivated.push(a.email); continue; } // the same wallet on a second account never pays twice
|
||||
let id = 0, activated = false, err = null;
|
||||
for (let t = 0; t < 3 && !err; t++) { try { id = await R.chain.memberIdByAccount(addr); if (id) { const m = await R.chain.member(id); activated = !!(m && m.activated); } break; } catch (e) { if (t === 2) err = String(e.message || e).slice(0, 120); } }
|
||||
if (err) { rows.push({ email: a.email, username: a.username || null, address: addr, memberId: 0, status: 'check', error: err, pol: C.pol }); continue; }
|
||||
if (!id || !activated || bad.has(Number(id))) { notActivated.push(a.email); continue; }
|
||||
seenAddr.add(addr);
|
||||
rows.push({ email: a.email, username: a.username || null, address: addr, memberId: id, flags: Array.isArray(a.flags) && a.flags.length ? a.flags : undefined, status: 'due', pol: C.pol, tx: null });
|
||||
}
|
||||
Object.assign(S, { status: 'snapshot', target: C.target, pol: C.pol, snapshotAt: Date.now(), countAt: all.length, rows, others: { noWallet, notActivated, suspended } });
|
||||
logLine(S, 'snapshot: ' + all.length + ' accounts, ' + rows.filter(r => r.status === 'due').length + ' eligible, ' + rows.filter(r => r.status === 'check').length + ' unchecked (rpc), ' + notActivated.length + ' wallet not activated, ' + noWallet.length + ' no wallet');
|
||||
save(S); return S;
|
||||
}
|
||||
// re-check rows the snapshot could not read from the chain (rpc trouble); they join as due or move to the missed list
|
||||
async function recheck() {
|
||||
const S = load(); const bad = R.noPayoutSet ? R.noPayoutSet() : new Set(); let fixed = 0;
|
||||
for (const r of S.rows.filter(x => x.status === 'check')) {
|
||||
try { const id = await R.chain.memberIdByAccount(r.address); const m = id ? await R.chain.member(id) : null;
|
||||
if (id && m && m.activated && !bad.has(Number(id))) { r.memberId = id; r.status = 'due'; delete r.error; } else { r.status = 'skip'; S.others.notActivated.push(r.email); } fixed++; } catch (e) { r.error = String(e.message || e).slice(0, 120); }
|
||||
}
|
||||
if (fixed) logLine(S, 'recheck: ' + fixed + ' rows resolved'); save(S); return S;
|
||||
}
|
||||
|
||||
const link = () => (R.site || 'https://instantadpay.com') + '/my#wallet';
|
||||
function paidCopy(r, S, W) {
|
||||
const subject = '1,000 members. We just sent you ' + S.pol + ' POL.';
|
||||
const tx = W.explorer + '/tx/' + r.tx;
|
||||
const p1 = 'InstantAdPay passed 1,000 members today. To mark it, every member whose wallet was activated with payouts on at that moment received ' + S.pol + ' POL, sent straight to the wallet on your account.';
|
||||
const p2 = 'Yours is on chain: ' + tx;
|
||||
const p3 = 'Thank you for building with us. The next milestone will do the same, so keep that wallet on your account.';
|
||||
return { subject, text: [p1, '', p2, '', p3].join('\n'), html: '<p>' + esc(p1) + '</p><p><a href="' + esc(tx) + '">Your payment on Polygonscan</a></p><p>' + esc(p3) + '</p>' };
|
||||
}
|
||||
function missedCopy(kind, S) {
|
||||
const subject = 'You missed the 1,000-member POL drop. Here is how to be in the next one.';
|
||||
const p1 = 'InstantAdPay passed 1,000 members today, and every member whose wallet was activated with payouts on received ' + S.pol + ' POL on the spot.';
|
||||
const p2 = kind === 'noWallet' ? 'Your account had no wallet linked, so there was nowhere to send yours.' : 'Your account had a wallet linked, but payouts were not switched on, so the drop could not reach you.';
|
||||
const p3 = kind === 'noWallet' ? 'Link a wallet on your Wallet tab (one free signature, it cannot move funds), then switch on payouts. The next milestone pays everyone who has done both.' : 'Switch on payouts from your Wallet tab. It is one small transaction that activates your position, and from then on every payout, sponsor commission and milestone reaches you automatically.';
|
||||
return { subject, text: [p1, '', p2, '', p3, '', link()].join('\n'), html: '<p>' + esc(p1) + '</p><p>' + esc(p2) + '</p><p>' + esc(p3) + '</p><p><a href="' + esc(link()) + '"><b>Open your Wallet tab</b></a></p>' };
|
||||
}
|
||||
|
||||
// pay every due row, one at a time; safe to call again (rows already sent or paid are never resent)
|
||||
async function pay() {
|
||||
if (paying) return { error: 'already paying' }; paying = true;
|
||||
try {
|
||||
const S = load(); const C = cfg(); if (!['snapshot', 'paying'].includes(S.status)) return { error: 'nothing to pay (status ' + S.status + ')' };
|
||||
if (C.mode !== 'armed') return { error: 'mode is ' + C.mode + ', not armed' };
|
||||
const W = wallet(); if (!W) return { error: 'no milestone wallet key (IAP_MILESTONE_KEY)' };
|
||||
const due = S.rows.filter(r => r.status === 'due'); if (!due.length) { return finish(S, W); }
|
||||
if (S.status === 'snapshot') {
|
||||
const need = r4(due.length * S.pol) + 0.05, have = await balance(); // the snapshot is frozen; the announcement waits for the funding
|
||||
if (have == null || have < need) { if (!S.waitLogged || Date.now() - S.waitLogged > 1800000) { logLine(S, 'waiting for funds: wallet holds ' + have + ' POL, needs ' + need); S.waitLogged = Date.now(); save(S); } return { waiting: 'funds', have, need }; }
|
||||
S.status = 'paying'; S.payStart = Date.now(); save(S);
|
||||
await post('\u{1F389} <b>InstantAdPay just passed ' + S.target.toLocaleString() + ' members.</b>\nTo mark it, ' + due.length + ' members whose wallets are activated with payouts on are each receiving <b>' + S.pol + ' POL</b> right now, straight to the wallet on their account. Not activated yet? Switch on payouts on your Wallet tab and you are in the next one.\n' + (R.site || 'https://instantadpay.com') + '/my#wallet');
|
||||
S.notified.paidStart = Date.now(); save(S); }
|
||||
let bal = await balance(); if (bal == null) return { error: 'could not read the wallet balance' };
|
||||
for (const r of S.rows) {
|
||||
if (r.status !== 'due') continue;
|
||||
if (bal < Number(r.pol) + 0.01) { logLine(S, 'paused: balance ' + bal + ' POL below the next payment'); save(S); return { paused: 'low balance', balance: bal }; }
|
||||
try {
|
||||
const tx = await W.w.sendTransaction({ to: r.address, value: ethers.parseEther(String(r.pol)) });
|
||||
r.status = 'sent'; r.tx = tx.hash; r.sentAt = Date.now(); save(S);
|
||||
let rc = null; try { rc = await tx.wait(1, 120000); } catch (e) { if (!(e && e.code === 'TIMEOUT')) throw e; }
|
||||
if (rc && rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); bal -= Number(r.pol); save(S); notifyPaid(r, S, W).catch(() => {}); }
|
||||
else if (rc) { r.status = 'failed'; r.error = 'reverted'; save(S); }
|
||||
// a timeout leaves the row 'sent' with its hash; settle() picks it up on the next tick
|
||||
} catch (e) {
|
||||
const msg = String(e && (e.shortMessage || e.message) || e);
|
||||
if (/insufficient funds/i.test(msg)) { r.status = 'due'; logLine(S, 'paused: insufficient funds'); save(S); return { paused: 'insufficient funds' }; }
|
||||
r.status = 'due'; r.error = msg.slice(0, 160); logLine(S, 'send error for ' + r.email + ': ' + msg.slice(0, 120)); save(S);
|
||||
return { paused: 'rpc', error: msg.slice(0, 160) }; // leave the rest for the next tick rather than hammer a failing node
|
||||
}
|
||||
}
|
||||
return finish(S, W);
|
||||
} finally { paying = false; }
|
||||
}
|
||||
// rows left 'sent' by a receipt timeout: read the receipt now
|
||||
async function settle() {
|
||||
const S = load(); const W = wallet(); if (!W) return; let n = 0;
|
||||
for (const r of S.rows.filter(x => x.status === 'sent' && x.tx)) {
|
||||
try { const rc = await W.provider.getTransactionReceipt(r.tx); if (!rc) continue; if (rc.status === 1) { r.status = 'paid'; r.paidAt = Date.now(); notifyPaid(r, S, W).catch(() => {}); } else { r.status = 'failed'; r.error = 'reverted'; } n++; } catch (e) {}
|
||||
}
|
||||
if (n) save(S); return n;
|
||||
}
|
||||
async function finish(S, W) {
|
||||
S = load(); if (S.rows.some(r => r.status === 'due' || r.status === 'sent')) return { pending: true };
|
||||
if (S.status === 'done') return { done: true };
|
||||
const paid = S.rows.filter(r => r.status === 'paid'), failed = S.rows.filter(r => r.status === 'failed'); const total = r4(paid.reduce((n, r) => n + Number(r.pol), 0));
|
||||
S.status = 'done'; S.doneAt = Date.now(); logLine(S, 'done: ' + paid.length + ' paid (' + total + ' POL), ' + failed.length + ' failed'); save(S);
|
||||
await post('✅ <b>' + S.target.toLocaleString() + '-member drop complete.</b> ' + paid.length + ' activated members received ' + S.pol + ' POL each, ' + total + ' POL in all, every payment on chain from ' + W.explorer + '/address/' + W.w.address + '. Missed it? Switch on payouts on your Wallet tab: the next milestone pays everyone who has.');
|
||||
S = load(); S.notified.paidEnd = Date.now(); save(S);
|
||||
if (R.ledger && total > 0) { try { R.ledger.put({ dir: 'out', amount: total, note: S.target.toLocaleString() + '-member milestone: ' + S.pol + ' POL to ' + paid.length + ' activated members', kind: 'cost', category: 'rewards', wallet: 'feeA', asset: 'POL' }); } catch (e) {} }
|
||||
notifyMissed().catch(e => console.error('milestone missed-notify', e.message));
|
||||
return { done: true, paid: paid.length, total };
|
||||
}
|
||||
async function post(html) { try { if (R.telegram) await R.telegram(html); } catch (e) {} }
|
||||
async function notifyPaid(r, S, W) {
|
||||
if (r.notified) return; const c = paidCopy(r, S, W);
|
||||
try { if (R.message) await R.message(r.email, c.subject, c.html); } catch (e) {}
|
||||
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey()) await R.mailer.send(r.email, c.subject, c.text, c.html); } catch (e) {}
|
||||
const S2 = load(); const row = S2.rows.find(x => x.email === r.email); if (row) { row.notified = Date.now(); save(S2); }
|
||||
}
|
||||
// the missed-it nudge for everyone not paid: in-app notice always, email only with the newsletter opt-in (like every nudge)
|
||||
async function notifyMissed() {
|
||||
const S = load(); if (S.notified.missed) return { done: true }; let n = 0;
|
||||
for (const kind of ['noWallet', 'notActivated']) {
|
||||
const c = missedCopy(kind, S);
|
||||
for (const email of S.others[kind] || []) {
|
||||
try { if (R.message) await R.message(email, c.subject, c.html); n++; } catch (e) {}
|
||||
try { if (R.mailer && R.mailer.hasKey && R.mailer.hasKey() && R.optedIn && await R.optedIn(email)) await R.mailer.send(email, c.subject, c.text, c.html); } catch (e) {}
|
||||
}
|
||||
}
|
||||
const S2 = load(); S2.notified.missed = Date.now(); logLine(S2, 'missed-it notices: ' + n); save(S2); return { sent: n };
|
||||
}
|
||||
|
||||
// every 2 minutes: watch the count while armed or dry, and keep paying/settling once a snapshot exists
|
||||
async function tick() {
|
||||
const C = cfg(); if (C.mode === 'off') return;
|
||||
let S = load();
|
||||
if (S.status === 'idle') { const n = await accountCount(); if (n < C.target) return { waiting: n }; S = await snapshot(); if (C.mode === 'dry') return { dry: true, eligible: S.rows.filter(r => r.status === 'due').length }; }
|
||||
if (S.rows.some(r => r.status === 'check')) await recheck();
|
||||
if (C.mode !== 'armed') return { dry: true };
|
||||
await settle();
|
||||
return pay();
|
||||
}
|
||||
async function view() {
|
||||
const S = load(); const C = cfg(); const W = wallet();
|
||||
const by = s => S.rows.filter(r => r.status === s).length;
|
||||
return { mode: C.mode, target: C.target, pol: C.pol, status: S.status, snapshotAt: S.snapshotAt, countAt: S.countAt, countNow: await accountCount().catch(() => null),
|
||||
wallet: W ? W.w.address : null, balance: await balance(), keyPresent: keyOk(),
|
||||
eligible: S.rows.filter(r => ['due', 'sent', 'paid', 'failed'].includes(r.status)).length, due: by('due'), sent: by('sent'), paid: by('paid'), failed: by('failed'), unchecked: by('check'),
|
||||
needPol: r4(S.rows.filter(r => r.status === 'due').length * S.pol), missed: { noWallet: (S.others.noWallet || []).length, notActivated: (S.others.notActivated || []).length, suspended: S.others.suspended || 0 },
|
||||
notified: S.notified, rows: S.rows.map(r => ({ email: r.email, username: r.username, memberId: r.memberId, status: r.status, tx: r.tx || null, error: r.error || null, flags: r.flags || null })), log: S.log.slice(-40) };
|
||||
}
|
||||
function reset() { const S = blank(); save(S); return S; } // only while nothing was paid: the admin route checks
|
||||
module.exports = { init, tick, snapshot, recheck, pay, settle, notifyMissed, view, reset, address, balance, cfg };
|
||||
@@ -133,4 +133,15 @@ async function topUp(nasAdId, addImpressions, days) {
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, impressionsPerCredit, nasKind };
|
||||
// restart a STOPPED ad (deactivate zeroed `remaining`) with `addImpressions` more, re-basing `assigned` on the TRUE served
|
||||
// count we recorded at the stop. A plain topUp would leave assigned - remaining = the whole old allocation, so the
|
||||
// undelivered part would read back as served (the same trap as deactivate, one step later).
|
||||
async function restart(nasAdId, trueServed, addImpressions, days) {
|
||||
if (!enabled()) return { skipped: 'flag-off' };
|
||||
const add = Math.max(0, Math.floor(Number(addImpressions) || 0)), base = Math.max(0, Math.floor(Number(trueServed) || 0));
|
||||
await q(`UPDATE sponsorads SET assigned=?, remaining=?, approved=1, EDate=DATE_ADD(NOW(), INTERVAL ? DAY) WHERE ID=?`,
|
||||
[base + add, add, Number(days || 30), Number(nasAdId)]);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
module.exports = { setClickUrl, enabled, pushCampaign, readServed, deactivate, topUp, restart, impressionsPerCredit, nasKind };
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
|
||||
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
|
||||
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
|
||||
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, Stack POL).
|
||||
const FALLBACK = [
|
||||
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
|
||||
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
|
||||
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
||||
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
||||
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
||||
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
||||
];
|
||||
const TTL = 10 * 60 * 1000;
|
||||
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
|
||||
let inflight = null;
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||
function clean(list) {
|
||||
if (!Array.isArray(list)) return null;
|
||||
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
|
||||
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
|
||||
return ok.length ? ok : null;
|
||||
}
|
||||
function refresh() {
|
||||
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
|
||||
.then(r => (r.ok ? r.json() : null))
|
||||
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
|
||||
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
|
||||
.finally(() => { clearTimeout(t); inflight = null; });
|
||||
return inflight;
|
||||
}
|
||||
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
|
||||
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
|
||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
function selfId(req, l) {
|
||||
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
|
||||
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
|
||||
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
|
||||
}
|
||||
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
|
||||
function tracked(id, from, extra) {
|
||||
const code = CODES[id]; if (!code || !from) return '';
|
||||
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
|
||||
return linksBase() + '/r/' + code + '?' + q.toString();
|
||||
}
|
||||
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
|
||||
// GET /api/network-sites: public, cacheable, the same answer on every page
|
||||
function handle(req, res) {
|
||||
const l = list();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(JSON.stringify(withGo(l, selfId(req, l))));
|
||||
}
|
||||
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
|
||||
@@ -0,0 +1,230 @@
|
||||
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
|
||||
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
|
||||
//
|
||||
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
|
||||
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
|
||||
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
|
||||
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
|
||||
// P mints a token bound to R, the state and the email, and sends the browser
|
||||
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
|
||||
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
|
||||
// (so nobody can push their own token into someone else's browser), and spends
|
||||
// the nonce (a second use is refused). The email must already be a member
|
||||
// here; then R makes an ordinary session and redirects to the relative path.
|
||||
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
|
||||
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
|
||||
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
|
||||
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
|
||||
// bots and non-page fetches never bounce.
|
||||
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
|
||||
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
|
||||
//
|
||||
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
|
||||
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
|
||||
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
|
||||
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
|
||||
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
|
||||
'use strict';
|
||||
const crypto = require('crypto');
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
const TTL = 60 * 1000; // token life
|
||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||
const STATE_AGE = 300; // seconds: the state cookie
|
||||
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
||||
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15)
|
||||
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||
|
||||
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
|
||||
|
||||
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||||
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
|
||||
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
|
||||
|
||||
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
|
||||
function safePath(to, dflt) {
|
||||
const d = dflt == null ? '/' : dflt;
|
||||
const s = String(to == null ? '' : to);
|
||||
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
|
||||
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
|
||||
}
|
||||
|
||||
function mint(o) {
|
||||
const now = o.now || Date.now();
|
||||
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
|
||||
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
|
||||
if (o.name) t.name = String(o.name).slice(0, 40);
|
||||
const body = b64u(JSON.stringify(t));
|
||||
return 'v1.' + body + '.' + b64u(mac(body));
|
||||
}
|
||||
|
||||
// -> { ok, email, to, n, exp } or { error: reason }
|
||||
function verify(tok, o) {
|
||||
if (!enabled()) return { error: 'off' };
|
||||
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
|
||||
if (!m) return { error: 'malformed' };
|
||||
const want = mac(m[1]), got = unb64u(m[2]);
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
|
||||
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
|
||||
const now = (o && o.now) || Date.now();
|
||||
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
|
||||
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
|
||||
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
|
||||
const st = String((o && o.st) || '');
|
||||
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
|
||||
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
|
||||
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
|
||||
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
|
||||
}
|
||||
|
||||
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
|
||||
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
|
||||
const used = new Map(); let fileLoaded = false, tableReady = null;
|
||||
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
|
||||
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
|
||||
function loadFile() {
|
||||
if (fileLoaded) return; fileLoaded = true;
|
||||
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
|
||||
}
|
||||
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
|
||||
async function spend(n, exp) {
|
||||
const now = Date.now(); loadFile(); prune(now);
|
||||
if (used.has(n)) return false;
|
||||
used.set(n, Number(exp) + SKEW); saveFile();
|
||||
const db = C && C.db;
|
||||
if (db && db.enabled && db.enabled()) {
|
||||
try {
|
||||
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
|
||||
await tableReady;
|
||||
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
|
||||
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
|
||||
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// crawlers, link previews and headless browsers never bounce
|
||||
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
|
||||
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
|
||||
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
|
||||
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
|
||||
|
||||
function cookies(req) {
|
||||
const out = {};
|
||||
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
|
||||
return out;
|
||||
}
|
||||
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
|
||||
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
|
||||
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
|
||||
|
||||
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
|
||||
|
||||
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
|
||||
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
|
||||
|
||||
// -> true when the request was one of ours and has been answered
|
||||
async function handle(req, res, u) {
|
||||
if (!C || req.method !== 'GET') return false;
|
||||
const p = u.pathname;
|
||||
const peerName = NAMES[C.peer] || C.peer;
|
||||
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
|
||||
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
|
||||
if (goTo && (goTo === C.peer || walletBase(goTo))) {
|
||||
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const plain = base + to;
|
||||
if (!enabled() || isBot(req)) return go(res, plain);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) return go(res, plain);
|
||||
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
|
||||
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
|
||||
}
|
||||
if (p === '/sso/start') {
|
||||
const to = safePath(u.searchParams.get('to'), C.defaultPath);
|
||||
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
|
||||
const via = String(u.searchParams.get('via') || '');
|
||||
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
|
||||
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (s && (s.email || s.address)) return go(res, to); // already signed in here
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||
}
|
||||
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||
const clear = [ck('nsso.back', '', 0, true)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
}
|
||||
if (p === '/sso/check') {
|
||||
const st = String(u.searchParams.get('st') || '');
|
||||
const to = safePath(u.searchParams.get('to'), '/');
|
||||
const r = String(u.searchParams.get('r') || '');
|
||||
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
|
||||
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
|
||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) {
|
||||
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
|
||||
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
|
||||
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
|
||||
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
|
||||
}
|
||||
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||
}
|
||||
let w = null;
|
||||
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||
log('token issued', s.email, 'for ' + forName);
|
||||
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
|
||||
}
|
||||
if (p === '/sso/in') {
|
||||
const c = cookies(req);
|
||||
const set = [ck('nsso.st', '', 0, true)];
|
||||
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
|
||||
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
|
||||
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
|
||||
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
|
||||
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
|
||||
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
|
||||
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
|
||||
return go(res, C.signinPath(v.to), set);
|
||||
}
|
||||
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
|
||||
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
|
||||
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
|
||||
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
|
||||
}
|
||||
if (p === '/api/sso/status') {
|
||||
const c = cookies(req); const set = [];
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
const signedIn = !!(s && (s.email || s.address));
|
||||
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
|
||||
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
|
||||
return sendJson(res, out, set);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||
|
||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
@@ -0,0 +1,366 @@
|
||||
// Level-4 override (Marty, decided 2026-10-17, approved to build for real 2026-10-23; design in memory iap-level4-override):
|
||||
// 3% of every purchase goes to the buyer's 4th upline on the CONTRACT sponsor chain when that member has 5+ qualifying
|
||||
// buyers (the contract's own buyerCount, the same bar as level 3); an unqualified 4th upline is skipped and the hunt
|
||||
// climbs (cap 25 hops, mirroring the contract's HOP_CAP). Exactly one recipient per purchase, so it never costs more than
|
||||
// 3%; company ids (overrideHouseIds) keep it. Funded off-chain from the company's 20% and paid weekly with the contract's
|
||||
// award(toMemberId) from a pre-funded payer wallet, purchases from overrideGoLive forward only (no back-pay).
|
||||
//
|
||||
// MODES (site setting overrideMode):
|
||||
// 'off' nothing at all.
|
||||
// 'dryrun' (default) the Monday who-would-be-paid report to Marty's private Telegram. No money moves.
|
||||
// 'live' pays, but ONLY when overrideGoLive is set AND a payer key is present (env OVERRIDE_PAYER_KEY or
|
||||
// OVERRIDE_PAYER_KEY_FILE). Missing either one: it reports as a dry run and says why it did not pay.
|
||||
//
|
||||
// MONEY SAFETY (why each piece exists):
|
||||
// - Every "do this once" is a claim that only one running copy of the app can win: an exclusive file create on the
|
||||
// shared volume (fs 'wx'), plus a row in event_marks when MySQL is on. A deploy runs two copies for ~30 s (the
|
||||
// 2026-09-25 double Friday bonus); a claim that cannot be checked counts as LOST (fail closed), never as won.
|
||||
// - A week's plan (who gets how much) is computed once, written to the volume and never recomputed, so a later read
|
||||
// of buyer counts cannot change an amount that is already being paid.
|
||||
// - A payout row is marked 'sending' on disk BEFORE the transaction is sent and gets its tx hash the moment the node
|
||||
// accepts it. A row whose answer was lost is 'review': it is never sent again automatically. The chain index can
|
||||
// settle it (an AwardPaid from the payer wallet to that member for that exact amount), or the admin does.
|
||||
// - Amounts under the dust minimum (overrideDustPol, default 0.01 POL) and pre-flight failures (award() would revert,
|
||||
// no gas spent) are carried to the next week's plan.
|
||||
// - Hard cap per week (overridePayCapPol, default 100 POL): a plan over the cap is held whole, nothing is sent.
|
||||
// - The wallet must hold the week's total plus gas for every send, or nothing is sent and Marty is told.
|
||||
// - Weeks are paid in order; a week that is held or needs review stops the later weeks until it is resolved.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
let ethersLib = null; try { ethersLib = require('ethers'); } catch (e) { /* optional: the payer stays off without it */ }
|
||||
|
||||
const PCT = 3, MIN_BUYERS = 5, HOP_CAP = 25, LEVEL = 4;
|
||||
const GAS_LIMIT = 150000n; // award(): reentrancy guard + member read + capped-gas send + event, ~60k; generous headroom
|
||||
const WEI = 10n ** 18n;
|
||||
|
||||
// ---- Central-time week math (pure, shared by every instance) ----
|
||||
const CT = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
|
||||
const CT_HOUR = new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', weekday: 'short', hour: '2-digit', hourCycle: 'h23' });
|
||||
function weekOf(ts) { // the Monday (YYYY-MM-DD, Central) of the week holding ts
|
||||
const parts = Object.fromEntries(CT.formatToParts(new Date(ts)).map(p => [p.type, p.value]));
|
||||
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[parts.weekday];
|
||||
return new Date(Date.UTC(+parts.year, +parts.month - 1, +parts.day - back)).toISOString().slice(0, 10);
|
||||
}
|
||||
const ctMidnight = day => { // ms at 00:00 America/Chicago on YYYY-MM-DD (CDT = UTC-5, CST = UTC-6)
|
||||
for (const off of [5, 6]) { const t = Date.parse(day + 'T0' + off + ':00:00Z'); if (new Intl.DateTimeFormat('en-US', { timeZone: 'America/Chicago', hour: '2-digit', hourCycle: 'h23' }).format(new Date(t)) === '00') return t; }
|
||||
return Date.parse(day + 'T05:00:00Z');
|
||||
};
|
||||
const addDays = (day, n) => new Date(Date.parse(day + 'T12:00:00Z') + n * 86400000).toISOString().slice(0, 10);
|
||||
const weekBounds = monday => ({ from: ctMidnight(monday), to: ctMidnight(addDays(monday, 7)) });
|
||||
// the week may be settled from 9 AM Central on the Monday after it
|
||||
const payableAt = monday => ctMidnight(addDays(monday, 7)) + 9 * 3600000;
|
||||
const polStr = wei => { const w = BigInt(wei); const s = (w * 10000n / WEI).toString().padStart(5, '0'); return s.slice(0, -4) + '.' + s.slice(-4); };
|
||||
const toWei = pol => { const [a, b = ''] = String(pol).trim().split('.'); return BigInt(a || '0') * WEI + BigInt((b + '0'.repeat(18)).slice(0, 18) || '0'); };
|
||||
|
||||
function create() {
|
||||
let DATA_DIR = null, chain = null, siteConfig = () => ({}), notify = null, db = null, now = () => Date.now();
|
||||
let BRAND = 'InstantAdPay', SITE_URL = 'https://instantadpay.com', HOUSE_DEFAULT = '1', payerOverride = null;
|
||||
const lastError = { at: 0, msg: '' };
|
||||
|
||||
function init(o) {
|
||||
DATA_DIR = o.dataDir; chain = o.chain; siteConfig = o.siteConfig || siteConfig; notify = o.notify || null; db = o.db || null;
|
||||
if (o.brand) BRAND = o.brand; if (o.siteUrl) SITE_URL = o.siteUrl; if (o.houseDefault) HOUSE_DEFAULT = String(o.houseDefault);
|
||||
if (o.payer) payerOverride = o.payer; // tests: a fake signer, never the real chain
|
||||
if (o.now) now = o.now;
|
||||
}
|
||||
const cfg = () => {
|
||||
const s = siteConfig();
|
||||
const num = (v, d) => { const n = Number(v); return v === undefined || v === '' || !isFinite(n) ? d : n; };
|
||||
return { mode: String(s.overrideMode || 'dryrun'), house: String(s.overrideHouseIds || HOUSE_DEFAULT).split(',').map(x => Number(x.trim())).filter(Boolean),
|
||||
goLive: Number(s.overrideGoLive || 0), dustWei: toWei(Math.max(0, num(s.overrideDustPol, 0.01)).toFixed(18)), capWei: toWei(Math.max(0, num(s.overridePayCapPol, 100)).toFixed(18)) };
|
||||
};
|
||||
|
||||
// ---- the payer wallet (OVERRIDE_PAYER_KEY; never logged, never returned) ----
|
||||
function keyHex() {
|
||||
let k = String(process.env.OVERRIDE_PAYER_KEY || '').trim();
|
||||
if (!k && process.env.OVERRIDE_PAYER_KEY_FILE) { try { k = fs.readFileSync(process.env.OVERRIDE_PAYER_KEY_FILE, 'utf8').trim(); } catch (e) {} }
|
||||
if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
|
||||
return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
|
||||
}
|
||||
let realPayer = null;
|
||||
function payer() {
|
||||
if (payerOverride) return payerOverride;
|
||||
const k = keyHex(); if (!k || !ethersLib) return null;
|
||||
if (realPayer) return realPayer;
|
||||
const c = chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc]; let idx = 0;
|
||||
const wallet = () => new ethersLib.Wallet(k, new ethersLib.JsonRpcProvider(urls[idx % urls.length], Number(c.chainId), { staticNetwork: true }));
|
||||
const ctr = w => new ethersLib.Contract(chain.getConfig().contract, ['function award(uint32 toMemberId) payable'], w);
|
||||
const address = new ethersLib.Wallet(k).address;
|
||||
realPayer = {
|
||||
address,
|
||||
balance: async () => { try { return await wallet().provider.getBalance(address); } catch (e) { idx++; throw e; } },
|
||||
fees: async () => { const g = await chain.suggestedFees(); return { maxPriorityFeePerGas: BigInt(g.maxPriorityFeePerGas), maxFeePerGas: BigInt(g.maxFeePerGas) }; },
|
||||
// a revert here (unknown member, a wallet that refuses POL) costs nothing and sends nothing
|
||||
preflight: async (id, wei) => { await ctr(wallet()).award.staticCall(Number(id), { value: BigInt(wei) }); },
|
||||
send: async (id, wei, fees) => { const tx = await ctr(wallet()).award(Number(id), Object.assign({ value: BigInt(wei), gasLimit: GAS_LIMIT }, fees)); return { hash: tx.hash, wait: () => tx.wait(1) }; }
|
||||
};
|
||||
return realPayer;
|
||||
}
|
||||
function liveState() {
|
||||
const c = cfg(), why = [];
|
||||
if (c.mode !== 'live') why.push('overrideMode is ' + c.mode + ', not live');
|
||||
if (!c.goLive) why.push('overrideGoLive is not set');
|
||||
if (!payerOverride && !keyHex()) why.push('no payer key (OVERRIDE_PAYER_KEY)');
|
||||
if (!payerOverride && !ethersLib) why.push('ethers is not installed');
|
||||
return { ready: !why.length, why };
|
||||
}
|
||||
|
||||
// ---- one-time claims, fail closed ----
|
||||
const dir = (...p) => path.join(DATA_DIR, 'override', ...p);
|
||||
const mkdirp = d => { try { fs.mkdirSync(d, { recursive: true }); } catch (e) {} };
|
||||
const safe = k => String(k).replace(/[^a-zA-Z0-9_.:-]/g, '_').replace(/:/g, '__').slice(0, 150);
|
||||
async function claim(key) {
|
||||
if (db && db.enabled && db.enabled()) {
|
||||
try { const r = await db.q('INSERT IGNORE INTO event_marks (k, ts) VALUES (?, ?)', ['ov:' + String(key).slice(0, 150), now()]); if (!(r && r.affectedRows === 1)) return false; }
|
||||
catch (e) { lastError.at = now(); lastError.msg = 'claim ' + key + ': ' + e.message; return false; }
|
||||
}
|
||||
mkdirp(dir('claims'));
|
||||
try { fs.closeSync(fs.openSync(dir('claims', safe(key)), 'wx')); return true; }
|
||||
catch (e) { if (e.code !== 'EEXIST') { lastError.at = now(); lastError.msg = 'claim file ' + key + ': ' + e.message; } return false; }
|
||||
}
|
||||
const claimed = key => fs.existsSync(dir('claims', safe(key)));
|
||||
|
||||
// ---- payout store: one small JSON file per week header and per (week, member) row, each with a single writer ----
|
||||
const readJ = f => { try { return JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { return null; } };
|
||||
const writeJ = (f, o) => { mkdirp(path.dirname(f)); const tmp = f + '.' + process.pid + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(o)); fs.renameSync(tmp, f); };
|
||||
const getWeek = wk => readJ(dir('weeks', wk, 'week.json'));
|
||||
const putWeek = (wk, patch) => { const cur = getWeek(wk) || { week: wk }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'week.json'), o); return o; };
|
||||
const getRow = (wk, id) => readJ(dir('weeks', wk, 'm' + id + '.json'));
|
||||
const putRow = (wk, id, patch) => { const cur = getRow(wk, id) || { week: wk, memberId: id }; const o = Object.assign(cur, patch, { updated: now() }); writeJ(dir('weeks', wk, 'm' + id + '.json'), o); return o; };
|
||||
const rowsOf = wk => { try { return fs.readdirSync(dir('weeks', wk)).filter(f => /^m\d+\.json$/.test(f)).map(f => readJ(dir('weeks', wk, f))).filter(Boolean).sort((a, b) => a.memberId - b.memberId); } catch (e) { return []; } };
|
||||
const plannedWeeks = () => { try { return fs.readdirSync(dir('weeks')).filter(w => /^\d{4}-\d{2}-\d{2}$/.test(w)).sort(); } catch (e) { return []; } };
|
||||
|
||||
// ---- who gets the override on one purchase ----
|
||||
const memo = new Map();
|
||||
async function mem(id) {
|
||||
const c = memo.get(id); if (c && now() - c.t < 600000) return c.v;
|
||||
const m = await chain.member(id); const v = { sponsorId: m.sponsorId || 0, buyerCount: m.buyerCount || 0 };
|
||||
memo.set(id, { t: now(), v }); return v;
|
||||
}
|
||||
// { recipientId, hops, skipped: [{id, buyers}] } or { recipientId: 0, reason }
|
||||
async function recipientFor(buyerId) {
|
||||
const ups = []; let cur = buyerId;
|
||||
for (let i = 0; i < LEVEL - 1 + HOP_CAP; i++) { const s = (await mem(cur)).sponsorId; if (!s || s === cur) break; ups.push(s); cur = s; }
|
||||
if (ups.length < LEVEL) return { recipientId: 0, reason: 'line shorter than ' + LEVEL + ' levels' };
|
||||
const skipped = [], house = cfg().house;
|
||||
for (let i = LEVEL - 1; i < ups.length && i < LEVEL - 1 + HOP_CAP; i++) {
|
||||
const id = ups[i];
|
||||
if (house.includes(id)) return { recipientId: 0, reason: 'reached the company account #' + id, skipped };
|
||||
const b = (await mem(id)).buyerCount;
|
||||
if (b >= MIN_BUYERS) return { recipientId: id, hops: i - (LEVEL - 1), skipped };
|
||||
skipped.push({ id, buyers: b });
|
||||
}
|
||||
return { recipientId: 0, reason: 'no qualified upline within ' + HOP_CAP + ' hops', skipped };
|
||||
}
|
||||
|
||||
// every Purchase in the full-history index (chain.recentEvents keeps the whole history in memory; the file is the fallback)
|
||||
function purchases() {
|
||||
try { if (chain && chain.recentEvents) return chain.recentEvents(1e9).filter(e => e.type === 'Purchase'); } catch (e) {}
|
||||
try { return (JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'chain-index.json'), 'utf8')).events || []).filter(e => e.type === 'Purchase'); } catch (e) { return []; }
|
||||
}
|
||||
// purchases in [from, to) (and from overrideGoLive on): one row per purchase + totals per recipient
|
||||
async function report(from, to) {
|
||||
const c = cfg(); const rows = [], per = {};
|
||||
for (const p of purchases()) {
|
||||
if (p.ts < from || p.ts >= to || (c.goLive && p.ts < c.goLive)) continue;
|
||||
const wei = BigInt(p.paidWei || '0') * BigInt(PCT) / 100n, usd = Math.round((p.priceCents || 0) * PCT) / 10000; // dollars: price cents x 3% / 100
|
||||
const r = await recipientFor(p.buyerId).catch(e => ({ recipientId: 0, reason: 'read failed: ' + e.message, readFailed: true }));
|
||||
rows.push({ tx: p.tx, ts: p.ts, buyerId: p.buyerId, priceCents: p.priceCents, overrideWei: wei.toString(), overrideUsd: usd, recipientId: r.recipientId, hops: r.hops || 0, skipped: r.skipped || [], reason: r.reason || '', readFailed: !!r.readFailed });
|
||||
if (r.recipientId) { const o = per[r.recipientId] = per[r.recipientId] || { recipientId: r.recipientId, purchases: 0, wei: 0n, usdCents: 0 }; o.purchases++; o.wei += wei; o.usdCents += (p.priceCents || 0) * PCT / 100; }
|
||||
}
|
||||
const recipients = Object.values(per).map(o => ({ recipientId: o.recipientId, purchases: o.purchases, wei: o.wei.toString(), pol: Number(o.wei) / 1e18, usd: Math.round(o.usdCents) / 100 })).sort((a, b) => b.usd - a.usd || a.recipientId - b.recipientId);
|
||||
const paidUsd = recipients.reduce((n, o) => n + o.usd, 0), keptUsd = rows.filter(x => !x.recipientId).reduce((n, x) => n + x.overrideUsd, 0);
|
||||
return { mode: c.mode, from, to, purchases: rows.length, readFailures: rows.filter(x => x.readFailed).length, recipients,
|
||||
totals: { wouldPayUsd: Math.round(paidUsd * 100) / 100, wouldPayPol: recipients.reduce((n, o) => n + o.pol, 0), companyKeepsUsd: Math.round(keptUsd * 100) / 100, salesUsd: rows.reduce((n, x) => n + x.priceCents, 0) / 100 }, rows };
|
||||
}
|
||||
// last full week, or the week containing `day`
|
||||
async function week(day) {
|
||||
const monday = day ? weekOf(Date.parse(day + 'T12:00:00Z')) : weekOf(now() - 7 * 86400000);
|
||||
const b = weekBounds(monday);
|
||||
return Object.assign(await report(b.from, b.to), { week: monday, status: weekStatus(monday) });
|
||||
}
|
||||
|
||||
// ---- planning: freeze who gets how much for one closed week (single writer via claim) ----
|
||||
// carried rows from earlier weeks roll into this plan; under-dust totals are carried again
|
||||
async function plan(wk) {
|
||||
if (getWeek(wk)) return getWeek(wk);
|
||||
const b = weekBounds(wk);
|
||||
if (now() < b.to) return null; // not closed yet
|
||||
const r = await report(b.from, b.to);
|
||||
if (r.readFailures) { lastError.at = now(); lastError.msg = 'week ' + wk + ': ' + r.readFailures + ' sponsor reads failed, plan postponed'; return null; } // never plan on a partial read
|
||||
if (!await claim('plan:' + wk)) return getWeek(wk); // another copy is planning (or did)
|
||||
putWeek(wk, { state: 'planning', created: now(), from: b.from, to: b.to, purchases: r.purchases, salesUsd: r.totals.salesUsd, companyKeepsUsd: r.totals.companyKeepsUsd });
|
||||
const per = {};
|
||||
for (const o of r.recipients) per[o.recipientId] = { wei: BigInt(o.wei), usd: o.usd, purchases: o.purchases, carriedIn: 0n, carriedFrom: [] };
|
||||
for (const w of plannedWeeks().filter(w => w < wk)) for (const row of rowsOf(w)) {
|
||||
if (row.state !== 'carried') continue;
|
||||
const o = per[row.memberId] = per[row.memberId] || { wei: 0n, usd: 0, purchases: 0, carriedIn: 0n, carriedFrom: [] };
|
||||
o.wei += BigInt(row.amountWei); o.usd = Math.round((o.usd + (row.usd || 0)) * 100) / 100; o.carriedIn += BigInt(row.amountWei); o.carriedFrom.push(w);
|
||||
putRow(w, row.memberId, { state: 'rolled', rolledInto: wk });
|
||||
}
|
||||
const dust = cfg().dustWei; let total = 0n, n = 0;
|
||||
for (const [id, o] of Object.entries(per)) {
|
||||
const st = o.wei < dust ? 'carried' : 'pending'; if (st === 'pending') { total += o.wei; n++; }
|
||||
putRow(wk, Number(id), { amountWei: o.wei.toString(), usd: o.usd, purchases: o.purchases, carriedInWei: o.carriedIn.toString(), carriedFrom: o.carriedFrom, state: st, note: st === 'carried' ? 'under the ' + polStr(dust) + ' POL minimum, carried to next week' : '' });
|
||||
}
|
||||
return putWeek(wk, { state: n ? 'planned' : 'paid', totalWei: total.toString(), recipients: n, planned: now() });
|
||||
}
|
||||
|
||||
// settle rows whose send answer was lost, from the chain index only (AwardPaid from the payer to that member, that amount)
|
||||
function reconcile(wk, pay) {
|
||||
if (!pay || !chain.recentEvents) return;
|
||||
const b = weekBounds(wk), used = overrideTxs(true);
|
||||
for (const row of rowsOf(wk)) {
|
||||
if (row.state !== 'review' && row.state !== 'sent') continue;
|
||||
const hit = chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && e.toId === row.memberId && String(e.amountWei) === String(row.amountWei)
|
||||
&& String(e.from || '').toLowerCase() === String(pay.address).toLowerCase() && e.ts >= b.to
|
||||
&& (row.txHash ? String(e.tx).toLowerCase() === String(row.txHash).toLowerCase() : !used.has(String(e.tx).toLowerCase())));
|
||||
if (hit) putRow(wk, row.memberId, { state: 'paid', txHash: hit.tx, note: 'confirmed from the chain index' });
|
||||
}
|
||||
}
|
||||
// admin decision for a stuck row: 'carry' (you checked the payer wallet and nothing went out) or 'paid' with the tx,
|
||||
// which must be an AwardPaid in the chain index from the payer wallet to that member for that exact amount
|
||||
async function resolve(wk, memberId, action, tx) {
|
||||
const r = getRow(wk, Number(memberId)); if (!r) return { error: 'no such row' };
|
||||
if (!['review', 'failed', 'sending', 'sent'].includes(r.state)) return { error: 'row is ' + r.state + ', nothing to resolve' };
|
||||
if (action === 'carry') { putRow(wk, r.memberId, { state: 'carried', note: 'admin: nothing went out, carried to next week (was ' + r.state + ')' }); return finishWeek(wk); }
|
||||
if (action === 'paid') {
|
||||
const p = (payerOverride || keyHex()) ? payer() : null;
|
||||
const hit = p && chain.recentEvents(1e9).find(e => e.type === 'AwardPaid' && String(e.tx).toLowerCase() === String(tx || '').toLowerCase());
|
||||
if (!hit || hit.toId !== r.memberId || String(hit.amountWei) !== String(r.amountWei) || String(hit.from).toLowerCase() !== String(p.address).toLowerCase()) return { error: 'that tx is not an AwardPaid from the payer wallet to #' + r.memberId + ' for ' + polStr(r.amountWei) + ' POL in the chain index' };
|
||||
putRow(wk, r.memberId, { state: 'paid', txHash: hit.tx, note: 'admin: confirmed tx' }); return finishWeek(wk);
|
||||
}
|
||||
return { error: 'action must be carry or paid' };
|
||||
}
|
||||
|
||||
// ---- paying one planned week (live only) ----
|
||||
async function pay(wk) {
|
||||
const live = liveState(); if (!live.ready) return { week: wk, paid: 0, why: live.why };
|
||||
let w = getWeek(wk); if (!w) return { week: wk, why: ['not planned'] };
|
||||
if (w.state === 'planning') return { week: wk, why: ['plan is being written (or a plan write stopped halfway: needs review if this lasts)'] };
|
||||
const p = payer(); reconcile(wk, p);
|
||||
let rows = rowsOf(wk).filter(r => r.state === 'pending');
|
||||
if (!rows.length) return finishWeek(wk);
|
||||
const c = cfg(); const total = rows.reduce((n, r) => n + BigInt(r.amountWei), 0n);
|
||||
if (total > c.capWei) { putWeek(wk, { state: 'held', heldWhy: 'over the weekly cap: ' + polStr(total) + ' POL planned, cap ' + polStr(c.capWei) + ' POL' }); await alertOnce(wk, 'cap', '⛔ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPlanned ' + polStr(total) + ' POL is over the weekly cap of ' + polStr(c.capWei) + ' POL. Nothing was sent. Raise overridePayCapPol or review the plan, then press Pay this week now in admin.'); return { week: wk, held: 'cap' }; }
|
||||
let fees, bal;
|
||||
try { fees = await p.fees(); bal = BigInt(await p.balance()); } catch (e) { lastError.at = now(); lastError.msg = 'payer read: ' + e.message; return { week: wk, why: ['payer read failed: ' + e.message] }; }
|
||||
const gas = BigInt(rows.length) * GAS_LIMIT * fees.maxFeePerGas;
|
||||
if (bal < total + gas) { putWeek(wk, { state: 'held', heldWhy: 'payer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL, needs ' + polStr(total + gas) + ' (payouts ' + polStr(total) + ' + gas ' + polStr(gas) + ')' }); await alertOnce(wk, 'balance', '⚠️ <b>Level-4 override HELD</b> · ' + BRAND + ' · week of ' + wk + '\nPayer wallet ' + p.address + ' holds ' + polStr(bal) + ' POL; this week needs ' + polStr(total + gas) + ' POL (' + polStr(total) + ' payouts + up to ' + polStr(gas) + ' gas). Nothing was sent. Fund it and it pays on the next check (or press Pay this week now).'); return { week: wk, held: 'balance' }; }
|
||||
putWeek(wk, { state: 'paying', heldWhy: '' });
|
||||
let sent = 0;
|
||||
for (const r0 of rows) {
|
||||
if (!await claim('pay:' + wk + ':' + r0.memberId)) continue; // another copy owns this row
|
||||
const r = getRow(wk, r0.memberId); if (!r || r.state !== 'pending') continue;
|
||||
try { await p.preflight(r.memberId, r.amountWei); }
|
||||
catch (e) { putRow(wk, r.memberId, { state: 'carried', note: 'award() would revert (' + String(e.reason || e.shortMessage || e.message).slice(0, 100) + '); nothing sent, carried to next week' }); continue; }
|
||||
putRow(wk, r.memberId, { state: 'sending', sendingAt: now() }); // on disk BEFORE the send
|
||||
let tx;
|
||||
try { tx = await p.send(r.memberId, r.amountWei, fees); }
|
||||
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'send error, may or may not have gone out: ' + String(e.shortMessage || e.message).slice(0, 140) }); continue; }
|
||||
putRow(wk, r.memberId, { state: 'sent', txHash: tx.hash });
|
||||
console.log('override: week ' + wk + ' #' + r.memberId + ' ' + polStr(r.amountWei) + ' POL tx ' + tx.hash);
|
||||
try { const rc = await tx.wait(); if (rc && Number(rc.status) === 1) { putRow(wk, r.memberId, { state: 'paid', paidAt: now() }); sent++; } else putRow(wk, r.memberId, { state: 'failed', note: 'reverted on chain (no POL moved except gas); needs review' }); }
|
||||
catch (e) { putRow(wk, r.memberId, { state: 'review', note: 'sent, receipt not confirmed: ' + String(e.message).slice(0, 120) }); }
|
||||
}
|
||||
return Object.assign(await finishWeek(wk), { sentNow: sent });
|
||||
}
|
||||
async function finishWeek(wk) {
|
||||
// a send that stopped halfway (no answer in 15 minutes) is never retried: it becomes review
|
||||
for (const r of rowsOf(wk)) {
|
||||
if (r.state === 'sending' && now() - (r.sendingAt || r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'the app stopped during the send; it may or may not have gone out' });
|
||||
if (r.state === 'sent' && now() - (r.updated || 0) > 15 * 60000) putRow(wk, r.memberId, { state: 'review', note: 'sent, no receipt and not in the chain index after 15 minutes' });
|
||||
}
|
||||
reconcile(wk, (payerOverride || keyHex()) ? payer() : null);
|
||||
const rows = rowsOf(wk); const open = rows.filter(r => ['pending', 'sending', 'sent', 'review', 'failed'].includes(r.state));
|
||||
if (open.length) {
|
||||
const stuck = open.filter(r => r.state === 'review' || r.state === 'failed'); // in-flight rows of another copy are not stuck
|
||||
if (stuck.length) await alertOnce(wk, 'review', '\u{1F50E} <b>Level-4 override needs review</b> · ' + BRAND + ' · week of ' + wk + '\n' + stuck.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL: ' + r.state + (r.txHash ? ' ' + txLink(r.txHash) : '') + ' ' + (r.note || '')).join('\n') + '\nNothing is re-sent automatically. Check the payer wallet on the explorer, then resolve it in admin.');
|
||||
return { week: wk, state: (getWeek(wk) || {}).state, open: open.length };
|
||||
}
|
||||
const w = putWeek(wk, { state: 'paid', done: now() });
|
||||
await summaryPaid(wk);
|
||||
return { week: wk, state: w.state };
|
||||
}
|
||||
const txLink = h => { const c = chain.getConfig(); return (c.explorer ? c.explorer.replace(/\/+$/, '') : 'https://polygonscan.com') + '/tx/' + h; };
|
||||
async function alertOnce(wk, kind, text) { if (!notify) return; if (!await claim('tg:' + wk + ':' + kind)) return; await notify(text, null).catch(() => {}); }
|
||||
async function summaryPaid(wk) {
|
||||
if (!notify || !await claim('tg:' + wk + ':paid')) return;
|
||||
const w = getWeek(wk) || {}, rows = rowsOf(wk), paid = rows.filter(r => r.state === 'paid'), carried = rows.filter(r => r.state === 'carried');
|
||||
const tot = paid.reduce((n, r) => n + BigInt(r.amountWei), 0n), usd = paid.reduce((n, r) => n + (r.usd || 0), 0);
|
||||
await notify('\u{1F4B8} <b>Level-4 override PAID</b> · ' + BRAND + ' · week of ' + wk + '\n' + (w.purchases || 0) + ' purchases, $' + Number(w.salesUsd || 0).toFixed(2) + ' sales\n'
|
||||
+ 'Paid ' + polStr(tot) + ' POL (about $' + usd.toFixed(2) + ' at purchase prices) to ' + paid.length + ' member' + (paid.length === 1 ? '' : 's') + '; company keeps $' + Number(w.companyKeepsUsd || 0).toFixed(2) + ' of the 3%.\n'
|
||||
+ (paid.map(r => '#' + r.memberId + ': ' + polStr(r.amountWei) + ' POL ($' + (r.usd || 0).toFixed(2) + ') <a href="' + txLink(r.txHash) + '">tx</a>').join('\n') || 'Nobody qualified this week.')
|
||||
+ (carried.length ? '\nCarried to next week (under the minimum or the wallet refused): ' + carried.map(r => '#' + r.memberId + ' ' + polStr(r.amountWei) + ' POL').join(', ') : '')
|
||||
+ '\nDetails: ' + SITE_URL + '/api/admin/override?week=' + wk, null).catch(() => {});
|
||||
}
|
||||
|
||||
// weeks the live payer is responsible for: from the go-live week to the last closed one, in order
|
||||
function dueWeeks(force) {
|
||||
const c = cfg(); if (!c.goLive) return [];
|
||||
const out = []; let wk = weekOf(c.goLive);
|
||||
while (true) { const b = weekBounds(wk); if (now() < b.to) break; if (!force && now() < payableAt(wk)) break; out.push(wk); wk = addDays(wk, 7); if (out.length > 520) break; }
|
||||
return out;
|
||||
}
|
||||
// settle every due week in order; stop at the first one that is not fully paid
|
||||
async function payDue(opts) {
|
||||
const o = opts || {}; const results = [];
|
||||
if (!liveState().ready) return { ready: false, why: liveState().why, results };
|
||||
for (const wk of dueWeeks(o.force)) {
|
||||
if (o.week && wk > o.week) break;
|
||||
let w = getWeek(wk);
|
||||
if (!w) w = await plan(wk);
|
||||
if (!w) { results.push({ week: wk, why: ['not planned yet: ' + (lastError.msg || 'waiting')] }); break; }
|
||||
if (w.state === 'paid') { await summaryPaid(wk); results.push({ week: wk, state: 'paid' }); continue; }
|
||||
const r = await pay(wk); results.push(r);
|
||||
if ((getWeek(wk) || {}).state !== 'paid') break;
|
||||
}
|
||||
return { ready: true, results };
|
||||
}
|
||||
|
||||
function weekStatus(wk) {
|
||||
const w = getWeek(wk); if (!w) return { week: wk, state: claimed('plan:' + wk) ? 'planning' : 'not planned' };
|
||||
const rows = rowsOf(wk);
|
||||
return { week: wk, state: w.state, heldWhy: w.heldWhy || '', totalWei: w.totalWei, totalPol: w.totalWei ? polStr(w.totalWei) : '0',
|
||||
rows: rows.map(r => ({ memberId: r.memberId, pol: polStr(r.amountWei), amountWei: r.amountWei, usd: r.usd, purchases: r.purchases, state: r.state, txHash: r.txHash || '', tx: r.txHash ? txLink(r.txHash) : '', note: r.note || '', carriedFrom: r.carriedFrom || [], rolledInto: r.rolledInto || '' })) };
|
||||
}
|
||||
async function payerStatus() {
|
||||
const c = cfg(), live = liveState(); const out = { mode: c.mode, ready: live.ready, why: live.why, goLive: c.goLive || 0, capPol: polStr(c.capWei), dustPol: polStr(c.dustWei), house: c.house, keyPresent: !!(payerOverride || keyHex()), lastError: lastError.msg ? lastError : null };
|
||||
const p = (payerOverride || keyHex()) ? payer() : null;
|
||||
if (p) { out.address = p.address; try { out.balancePol = polStr(await p.balance()); } catch (e) { out.balanceError = e.message; } }
|
||||
return out;
|
||||
}
|
||||
// AwardPaid txs this payer made (for the Earnings label and the payout email): tx -> { week, memberId }
|
||||
let txCache = { at: 0, map: new Map() };
|
||||
function overrideTxs(fresh) {
|
||||
if (!fresh && now() - txCache.at < 30000) return txCache.map;
|
||||
const m = new Map(); for (const wk of plannedWeeks()) for (const r of rowsOf(wk)) if (r.txHash) m.set(String(r.txHash).toLowerCase(), { week: wk, memberId: r.memberId });
|
||||
txCache = { at: now(), map: m }; return m;
|
||||
}
|
||||
const txInfo = tx => { return overrideTxs(true).get(String(tx || '').toLowerCase()) || null; };
|
||||
|
||||
// ---- the scheduler: every 30 minutes ----
|
||||
async function tick() {
|
||||
const c = cfg(); if (c.mode === 'off') return;
|
||||
const live = liveState();
|
||||
if (live.ready) { try { await payDue(); } catch (e) { lastError.at = now(); lastError.msg = 'payDue: ' + e.message; console.error('override pay', e.message); } return; }
|
||||
// dry run (or 'live' that is not ready): the Monday report, once per week across every copy of the app
|
||||
const parts = Object.fromEntries(CT_HOUR.formatToParts(new Date(now())).map(p => [p.type, p.value]));
|
||||
if (parts.weekday !== 'Mon' || Number(parts.hour) < 9 || !notify) return;
|
||||
const r = await week(); if (r.readFailures) return; // try again in 30 minutes rather than report a partial week
|
||||
if (!await claim('tg:' + r.week + ':dry')) return;
|
||||
let st = {}; try { st = JSON.parse(fs.readFileSync(path.join(DATA_DIR, 'override-dryrun.json'), 'utf8')); } catch (e) {}
|
||||
st.lastWeek = r.week; st.reports = Object.assign(st.reports || {}, { [r.week]: { totals: r.totals, recipients: r.recipients, purchases: r.purchases } });
|
||||
try { fs.writeFileSync(path.join(DATA_DIR, 'override-dryrun.json'), JSON.stringify(st)); } catch (e) {}
|
||||
const top = r.recipients.slice(0, 8).map(o => '#' + o.recipientId + ': $' + o.usd.toFixed(2) + ' (' + o.pol.toFixed(2) + ' POL, ' + o.purchases + ' buys)').join('\n');
|
||||
await notify('\u{1F4CA} <b>Level-4 override, DRY RUN</b> · ' + BRAND + ' · week of ' + r.week + '\n' + r.purchases + ' purchases, $' + r.totals.salesUsd.toFixed(2) + ' sales\n'
|
||||
+ 'Would pay $' + r.totals.wouldPayUsd.toFixed(2) + ' (' + r.totals.wouldPayPol.toFixed(2) + ' POL) to ' + r.recipients.length + ' members; company keeps $' + r.totals.companyKeepsUsd.toFixed(2) + ' of the 3%.\n'
|
||||
+ (top || 'Nobody qualified this week.') + '\nNo money moved' + (c.mode === 'live' ? ' (live switch is on but not paying: ' + live.why.join('; ') + ')' : '') + '. Details: ' + SITE_URL + '/api/admin/override?week=' + r.week, null).catch(() => {});
|
||||
}
|
||||
|
||||
return { init, report, week, recipientFor, tick, plan, pay, payDue, resolve, dueWeeks, weekStatus, payerStatus, liveState, overrideTxs, txInfo, claim, cfg };
|
||||
}
|
||||
|
||||
const main = create();
|
||||
module.exports = Object.assign(main, { create, weekOf, ctMidnight, weekBounds, payableAt, polStr, toWei, PCT, MIN_BUYERS, HOP_CAP, LEVEL, GAS_LIMIT });
|
||||
@@ -0,0 +1,77 @@
|
||||
// PassiveDrip PTC bridge (2026-09-30). Every InstantAdPay verified-visit campaign is listed on PassiveDrip's
|
||||
// paid-to-click page under the house account; PassiveDrip members view it for coins, and the visits they deliver
|
||||
// count against the campaign here exactly like visits delivered in our own viewer.
|
||||
//
|
||||
// Loop (every PD_SYNC_MIN minutes, 90 s after boot):
|
||||
// 1. POST <bridge>?a=ptc_sync {campaigns:[{id, title, desc, url, visitsLeft}]} (HMAC-signed) -> PD upserts rows by
|
||||
// our campaign id, pauses any row we no longer list, keeps ONE live row per target URL.
|
||||
// 2. GET <bridge>?a=ptc_served -> [{iapId, received}] (cumulative visits PD delivered per campaign). Delivery is READ
|
||||
// from PD, never derived: the delta since our last read is applied through ads.applyExternalVisits, which bumps
|
||||
// imps and closes the pack when the ordered count is reached. Our last-read counters live in DATA_DIR/pdsync.json.
|
||||
// SYNDICATED RATE (Marty 2026-10-27, 4:1): N = ads.synRateDivisor() partner visits use up ONE visit of the pack
|
||||
// (floor(now/N) - floor(prev/N) on the cumulative count, so fractions carry exactly); every partner visit is still
|
||||
// counted in the campaign's syn_imps for the member's stats, and PD is offered (visits left) x N.
|
||||
//
|
||||
// FEATURE-FLAGGED: inert unless PD_BRIDGE_URL and PD_BRIDGE_SECRET are set. Geo-restricted campaigns are not sent
|
||||
// (PassiveDrip's audience is worldwide).
|
||||
'use strict';
|
||||
const fs = require('fs'), path = require('path'), http = require('http'), https = require('https'), crypto = require('crypto');
|
||||
|
||||
let X = null, FILE = null, S = { served: {}, last: null }, running = false;
|
||||
function enabled() { return !!(process.env.PD_BRIDGE_URL && process.env.PD_BRIDGE_SECRET); }
|
||||
const synN = () => { try { return (X && X.ads && X.ads.synRateDivisor) ? X.ads.synRateDivisor() : 1; } catch (e) { return 1; } };
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'pdsync.json'); try { S = Object.assign(S, JSON.parse(fs.readFileSync(FILE, 'utf8'))); } catch (e) {} }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
|
||||
function bridge(action, method, body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const raw = body ? JSON.stringify(body) : '';
|
||||
const ts = Math.floor(Date.now() / 1000);
|
||||
const sig = crypto.createHmac('sha256', process.env.PD_BRIDGE_SECRET.trim()).update(ts + '\n' + method + '\n' + action + '\n' + raw).digest('hex');
|
||||
const u = new URL(process.env.PD_BRIDGE_URL.trim()); u.searchParams.set('a', action);
|
||||
const req = (u.protocol === 'http:' ? http : https).request(u, { method, headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(raw), 'X-PD-Ts': String(ts), 'X-PD-Sig': sig, 'User-Agent': 'instantadpay-pdsync' }, timeout: 25000 }, res => {
|
||||
let d = ''; res.on('data', c => d += c); res.on('end', () => { try { const j = JSON.parse(d); if (res.statusCode !== 200 || j.error) return reject(new Error('bridge ' + action + ': HTTP ' + res.statusCode + ' ' + (j.error || d.slice(0, 120)))); resolve(j); } catch (e) { reject(new Error('bridge ' + action + ': bad response ' + d.slice(0, 120))); } });
|
||||
});
|
||||
req.on('error', reject); req.on('timeout', () => req.destroy(new Error('bridge timeout'))); req.end(raw);
|
||||
});
|
||||
}
|
||||
|
||||
// what PassiveDrip should list: every active, worldwide visits campaign with visits still to deliver
|
||||
// (Spooky Doors door packs and Golden Doors stay behind the doors while the season runs: doorOnly)
|
||||
async function listing() {
|
||||
const all = await X.ads.adminList(2000);
|
||||
return all.filter(c => c.type === 'visits' && c.status === 'active' && !c.doorOnly && !c.geo && !(c.starts && c.starts > Date.now()) && /^https?:\/\//.test(c.targetUrl || ''))
|
||||
.map(c => ({ id: c.id, title: String(c.name || c.title || 'Sponsor').slice(0, 64), desc: String((c.title && String(c.title).toLowerCase() !== String(c.name || '').toLowerCase()) ? c.title : '').slice(0, 128), url: c.targetUrl, visitsLeft: Math.max(0, Number(c.body || 0) - Number(c.imps || 0)) * synN() }))
|
||||
.filter(c => c.visitsLeft > 0);
|
||||
}
|
||||
|
||||
async function sync() {
|
||||
if (!enabled() || running) return { skipped: true };
|
||||
running = true;
|
||||
const t = { at: Date.now(), pushed: 0, applied: 0, closed: 0, note: '' };
|
||||
try {
|
||||
const camps = await listing(); t.pushed = camps.length;
|
||||
const r = await bridge('ptc_sync', 'POST', { campaigns: camps });
|
||||
t.pdLive = r.live; t.pdPaused = r.paused;
|
||||
const served = await bridge('ptc_served', 'GET');
|
||||
for (const row of (served.rows || [])) {
|
||||
const id = String(row.iapId); const now = Number(row.received) || 0; const prev = Number(S.served[id] || 0);
|
||||
if (now <= prev) { if (now < prev) S.served[id] = now; continue; } // PD's counter reset (row recreated): re-baseline, never charge backwards
|
||||
if (process.env.PD_SYNC_APPLY === '0') { S.served[id] = now; t.ignored = (t.ignored || 0) + (now - prev); continue; } // staging bridge: test views are read and baselined, never counted as delivery
|
||||
const N = synN(); const units = Math.floor(now / N) - Math.floor(prev / N); // pack visits these partner visits use up
|
||||
try { const res = await X.ads.applyExternalVisits(Number(id), units, 'PassiveDrip', now - prev); S.served[id] = now; t.applied += res.applied || 0; if (res.closed) t.closed++; }
|
||||
catch (e) { console.error('pdsync apply', id, e.message); } // one bad row never stops the others; its delta is retried next sync
|
||||
}
|
||||
save();
|
||||
} catch (e) { t.note = String(e.message).slice(0, 160); console.error('pdsync', e.message); }
|
||||
finally { S.last = t; save(); running = false; }
|
||||
return t;
|
||||
}
|
||||
function status() { return { enabled: enabled(), bridge: enabled() ? process.env.PD_BRIDGE_URL.replace(/\?.*$/, '') : null, last: S.last, tracked: Object.keys(S.served).length }; }
|
||||
// the member's own PassiveDrip line for the Games card (2026-10-01): bridge action 'member', read only
|
||||
async function member(memberId, email) {
|
||||
if (!enabled()) return null;
|
||||
const j = await bridge('member', 'POST', { memberId: Number(memberId) || 0, email: String(email || '').toLowerCase() });
|
||||
return j && j.ok ? j : null;
|
||||
}
|
||||
module.exports = { enabled, init, sync, status, listing, member };
|
||||
@@ -0,0 +1,108 @@
|
||||
// Prohibited-content policy, one module shared by InstantAdPay and LinkSpin (keep the two copies identical).
|
||||
// 2026-10-30: an SEO backlink farm opened 106 free accounts, each with a casino or local-business bio and a
|
||||
// website link, and Google indexed that text under our domains through the public walls. Rules (Marty):
|
||||
// - profile fields are not a free backlink: a bio may not carry a URL or a domain-looking token;
|
||||
// - gambling, adult, pharma, weapons and link-selling terms are refused in every member-set text field
|
||||
// (bio, social links, line banner, wall offers, campaign names, headlines, copy and target URLs);
|
||||
// - case-insensitive and Unicode aware (NFC, lower-cased, letter/number boundaries, so "Essex" never hits "sex").
|
||||
// Pure functions, no state, no dependencies.
|
||||
'use strict';
|
||||
|
||||
// One entry per term or phrase; spaces match any run of whitespace. Grouped for the Terms page and the admin.
|
||||
const LIST = {
|
||||
gambling: ['casino', 'casinos', 'cassino', 'cassinos', 'slots', 'slot gacor', 'betting', 'sportsbook', 'sportsbooks', 'bookmaker', 'bookmakers', 'bookie',
|
||||
'lottery', 'lotteries', 'lotto', 'poker', 'baccarat', 'roulette', 'blackjack', 'jackpot', 'togel', 'judi', 'judi online', 'apostas', 'apuestas',
|
||||
'nổ hũ', 'cá cược', 'đổi thưởng', 'xổ số', 'kèo', 'nhà cái', 'soi kèo', 'game bài', 'tài xỉu', 'bắn cá'],
|
||||
adult: ['porn', 'porno', 'pornography', 'sex', 'sexy', 'escort', 'escorts', 'erotic', 'erotica', 'xxx', 'onlyfans', 'nude', 'nudes', 'hentai', 'cam girl', 'cam girls', 'sex cam', 'hookup', 'hookups'],
|
||||
pharma: ['viagra', 'cialis', 'levitra', 'pharmacy', 'pharmacies', 'prescription', 'prescriptions', 'steroids', 'anabolic', 'cannabis', 'marijuana', 'weed', 'cbd', 'kratom', 'opioid', 'opioids',
|
||||
'xanax', 'adderall', 'tramadol', 'oxycodone', 'ketamine', 'cocaine', 'mdma', 'psilocybin', 'vape', 'vaping'],
|
||||
weapons: ['firearm', 'firearms', 'guns', 'gun shop', 'gun store', 'ammunition', 'ammo', 'rifle', 'rifles', 'pistol', 'pistols', 'handgun', 'handguns', 'silencer', 'suppressor', 'explosives'],
|
||||
linkfarm: ['backlink', 'backlinks', 'seo service', 'seo services', 'seo agency', 'link building', 'link-building', 'guest post', 'guest posts', 'guest posting', 'pbn', 'buy links', 'sell links', 'dofollow']
|
||||
};
|
||||
const ALL = Object.values(LIST).reduce((a, b) => a.concat(b), []);
|
||||
|
||||
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const ZW = /[-]/g; // zero-width joiners hide nothing
|
||||
const strip = s => String(s == null ? '' : s).normalize('NFC').replace(ZW, '');
|
||||
const norm = s => strip(s).toLowerCase();
|
||||
// Boundary = anything that is not a letter or a number (works for every script, unlike \b).
|
||||
const TERM_RE = new RegExp('(?<![\\p{L}\\p{N}])(?:' + ALL.map(t => esc(norm(t)).replace(/\s+/g, '\\s+')).join('|') + ')(?![\\p{L}\\p{N}])', 'u');
|
||||
|
||||
// Common gTLDs plus the ccTLDs link farms actually use. A short two-letter list keeps "Mr.Li" style text out of it.
|
||||
const TLDS = 'com|net|org|info|biz|io|co|app|xyz|me|tv|us|uk|vn|de|fr|ru|in|id|br|es|it|nl|ca|au|eu|ch|at|be|pt|pl|cz|se|no|fi|dk|ie|nz|za|ng|ke|eg|tr|ua|il|ae|sa|pk|bd|lk|np|kh|la|mm|my|sg|ph|th|jp|kr|cn|tw|hk|mx|ar|cl|pe|to|ly|cc|gg|ai|pw|ws|tk|ml|ga|cf|gq|su|'
|
||||
+ 'site|online|store|shop|club|top|pro|live|link|page|dev|fun|vip|one|tech|space|website|cloud|digital|agency|company|email|news|blog|life|world|today|zone|guru|ninja|game|games|team|network|money|cash|gold|bid|trade|win|bet|casino|poker|mobi|name|tel|travel|jobs|pics|photo|video|press|media|art|design|studio|capital|finance|exchange|solutions|services|systems|tools|works|center|group|global|international|institute|academy|school|education|university|church|community|social|chat|dating|love|wiki|review|reviews|directory|guide|help|support|rocks|ventures|holdings|partners|limited|ltd|llc|inc|asia|africa|london|nyc|tokyo|berlin|paris|best|buzz|click|host|hosting|lol|monster|wtf|ooo|icu|sbs|cfd|cyou|rest|bar|cam|surf|run|fit|health|care|dog|cat|pet|pets|wine|beer|vodka|bio|eco|green|energy|solar|car|cars|auto|bike|tires|taxi|limo|rent|rentals|house|homes|realty|estate|land|city|town|place|map|earth|fund|loans|credit|insure|legal|law|lawyer|attorney|tax|accountant|consulting|marketing|promo|sale|deals|discount|coupons|gift|gifts|toys|baby|kids|mom|family|wedding|party|events|tickets|show|theater|film|movie|music|band|dance|yoga|golf|football|soccer|hockey|tennis|racing';
|
||||
// Schemes and www. are matched in any case; a bare domain token (or an email address) only with its TLD in lower case, so a
|
||||
// missed space after a period ("ads.One day") is not mistaken for a link while real spam domains (typed lower case) are caught.
|
||||
const SCHEME_RE = /(?:https?:\/\/|ftp:\/\/|(?<![\p{L}\p{N}])www\.)/iu;
|
||||
const DOMAIN_RE = new RegExp('(?<![\\p{L}\\p{N}])[\\p{L}\\p{N}-]{1,63}(?:\\.[\\p{L}\\p{N}-]{1,63})*\\.(?:' + TLDS + ')(?![\\p{L}\\p{N}])', 'u');
|
||||
|
||||
// The matching prohibited term, or null.
|
||||
function match(text) { const m = TERM_RE.exec(norm(text)); return m ? m[0].replace(/\s+/g, ' ') : null; }
|
||||
// True when the text carries a URL or a domain-looking token (http(s)://, www., word.tld).
|
||||
function hasUrl(text) { const t = strip(text); return SCHEME_RE.test(t) || DOMAIN_RE.test(t); }
|
||||
|
||||
const BIO_LINK_MSG = 'Links go in the social fields, not the bio.';
|
||||
const blockedMsg = site => 'That content is not allowed on ' + (site || 'InstantAdPay/LinkSpin') + ' profiles (see Terms).';
|
||||
const blockedAdMsg = site => 'That content is not allowed on ' + (site || 'InstantAdPay/LinkSpin') + ' (see Terms, Prohibited content).';
|
||||
|
||||
// Bio rule: no links, no prohibited terms. Returns { ok: true } or { error, reason }.
|
||||
function checkBio(bio, site) {
|
||||
const t = String(bio || '');
|
||||
if (!t.trim()) return { ok: true };
|
||||
if (hasUrl(t)) return { error: BIO_LINK_MSG, reason: 'url' };
|
||||
const term = match(t);
|
||||
if (term) return { error: blockedMsg(site), reason: 'term:' + term };
|
||||
return { ok: true };
|
||||
}
|
||||
// Any other member-set text (social URL, banner target, campaign name, headline, copy): prohibited terms only.
|
||||
// Pass profile: true for profile fields (the message names profiles), else the ad message is used.
|
||||
function checkText(text, site, opts) {
|
||||
const term = match(text);
|
||||
if (!term) return { ok: true };
|
||||
return { error: (opts && opts.profile) ? blockedMsg(site) : blockedAdMsg(site), reason: 'term:' + term };
|
||||
}
|
||||
// Several fields at once: { name: value, ... } -> first failure, with the field named in `field`.
|
||||
function checkFields(fields, site, opts) {
|
||||
for (const k of Object.keys(fields || {})) {
|
||||
const v = fields[k]; if (v == null || v === '') continue;
|
||||
const r = checkText(Array.isArray(v) ? v.join(' ') : String(v), site, opts);
|
||||
if (r.error) return Object.assign({ field: k }, r);
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
// Profile ingest (registry sync from the other property, or a saved profile replayed): the parts of a profile that may be
|
||||
// stored. A bio with a link or a prohibited term is dropped (null); a social URL carrying a prohibited term is dropped.
|
||||
function cleanProfile(pf, site) {
|
||||
const out = { avatarUrl: null, bio: null, socials: null, dropped: [] };
|
||||
if (!pf || typeof pf !== 'object') return out;
|
||||
const av = String(pf.avatarUrl || '').trim(); if (/^https:\/\/[^\s]+$/i.test(av) && av.length <= 300) out.avatarUrl = av;
|
||||
const bio = String(pf.bio || '').trim().slice(0, 600);
|
||||
if (bio) { const r = checkBio(bio, site); if (r.ok) out.bio = bio; else out.dropped.push('bio:' + r.reason); }
|
||||
const src = pf.socials && typeof pf.socials === 'object' ? pf.socials : (typeof pf.socials === 'string' ? safeJson(pf.socials) : null);
|
||||
if (src) {
|
||||
const c = {};
|
||||
for (const k of Object.keys(src)) {
|
||||
const v = String(src[k] || '').trim(); if (!v) continue;
|
||||
const r = checkText(v, site, { profile: true }); if (r.ok) c[k] = v; else out.dropped.push('socials.' + k + ':' + r.reason);
|
||||
}
|
||||
if (Object.keys(c).length) out.socials = c;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function safeJson(s) { try { const o = JSON.parse(s); return o && typeof o === 'object' ? o : null; } catch (e) { return null; } }
|
||||
// Terms-page wording, one line per group (kept here so both sites say the same thing).
|
||||
const POLICY = [
|
||||
'gambling, casinos, betting, lotteries and sweepstakes',
|
||||
'adult or sexual content',
|
||||
'drugs and prescription pharmaceuticals',
|
||||
'weapons',
|
||||
'hate or harassment',
|
||||
'malware, phishing and counterfeit goods',
|
||||
'misleading financial promises',
|
||||
'accounts created to place links in profile fields (link farming), which are removed without notice together with their profile text'
|
||||
];
|
||||
// One log line per refusal, with the email masked (never the text itself at full length).
|
||||
function logRefusal(where, email, r) {
|
||||
try { console.log('prohibited-content refused', where, String(email || '-').replace(/^(.).*(@.*)$/, '$1***$2'), r && r.field ? 'field=' + r.field : '', r && r.reason ? r.reason : ''); } catch (e) {}
|
||||
}
|
||||
module.exports = { LIST, ALL, POLICY, match, hasUrl, checkBio, checkText, checkFields, cleanProfile, logRefusal, BIO_LINK_MSG, blockedMsg, blockedAdMsg };
|
||||
@@ -1,12 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<html lang="en" data-theme-base="dark">
|
||||
<head>
|
||||
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
||||
<meta name="robots" content="noindex,nofollow">
|
||||
<title>Admin | InstantAdPay</title>
|
||||
<!--theme-head--><script>(function(){var A=0,h=document.documentElement,b=h.getAttribute("data-theme-base")||"dark",m=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;function g(){try{v=localStorage.getItem("iap.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);window.IAPTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("iap.theme",c);else localStorage.removeItem("iap.theme")}catch(e){}ap();if(!quiet)try{dispatchEvent(new CustomEvent("iap-theme",{detail:g()}))}catch(e){}}}})()</script><!--/theme-head-->
|
||||
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Sora:wght@600;700;800&display=swap">
|
||||
<link rel="icon" type="image/png" href="/logo-icon.png">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20260910h">
|
||||
<link rel="stylesheet" href="/assets/site.css?v=20261112ln">
|
||||
<style>
|
||||
.adm-table{width:100%;table-layout:auto}
|
||||
.adm-table th{cursor:pointer;user-select:none;white-space:nowrap}
|
||||
@@ -24,10 +25,10 @@
|
||||
.adm-table .act{white-space:nowrap}
|
||||
.adm-table .act button{margin-right:6px}
|
||||
.st{display:inline-block;border-radius:999px;padding:2px 9px;font-size:11.5px;font-weight:700;letter-spacing:.04em;text-transform:uppercase}
|
||||
.st.active{background:rgba(67,232,195,.14);color:var(--mint)}
|
||||
.st.paused{background:rgba(255,178,56,.14);color:var(--amber)}
|
||||
.st.out{background:rgba(255,255,255,.08);color:var(--muted)}
|
||||
.house-tag{display:inline-block;border:1px solid rgba(157,125,255,.5);color:var(--violet);border-radius:6px;padding:1px 6px;font-size:10.5px;font-weight:700;margin-left:6px;vertical-align:middle}
|
||||
.st.active{background:var(--mint-soft-2);color:var(--mint)}
|
||||
.st.paused{background:var(--amber-soft);color:var(--amber)}
|
||||
.st.out{background:var(--muted-soft);color:var(--muted)}
|
||||
.house-tag{display:inline-block;border:1px solid var(--violet-line);color:var(--violet);border-radius:6px;padding:1px 6px;font-size:10.5px;font-weight:700;margin-left:6px;vertical-align:middle}
|
||||
.adm-form p{margin:0 0 10px}
|
||||
.adm-form label.small{display:block;margin-bottom:4px}
|
||||
.trunc{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;display:inline-block;vertical-align:bottom}
|
||||
@@ -35,7 +36,7 @@
|
||||
.ph-chips{display:inline-flex;gap:6px;flex-wrap:wrap;margin-left:6px;vertical-align:middle}
|
||||
.ph-chips .chip-t{padding:2px 10px;font-size:11.5px;font-family:var(--mono);text-transform:none;letter-spacing:0;cursor:pointer;background:transparent}
|
||||
.drip-steps{display:grid;gap:12px}
|
||||
.drip-step{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:rgba(4,8,7,.4)}
|
||||
.drip-step{border:1px solid var(--line);border-radius:12px;padding:14px 16px;background:var(--ground-soft)}
|
||||
.drip-step .ds-head{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-bottom:8px}
|
||||
.drip-step .ds-n{font-family:var(--mono);font-size:12px;color:var(--mint);letter-spacing:.08em}
|
||||
.drip-step .ds-when{display:flex;align-items:center;gap:6px;font-size:13px;color:var(--muted)}
|
||||
@@ -61,6 +62,14 @@
|
||||
.kv-row .k{font-family:var(--mono);font-size:12.5px;overflow-wrap:anywhere}
|
||||
.kv-row input[type=checkbox]{width:auto;justify-self:start}
|
||||
@media(max-width:700px){.kv-row{grid-template-columns:1fr}}
|
||||
.gpt-note{margin:0 0 10px;padding:8px 12px;border-radius:8px;background:#fde68a;color:#7c2d12;font-size:13px}
|
||||
.gpt-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px}
|
||||
.gpt-tier{border:1px dashed var(--line-strong);border-radius:12px;padding:12px 14px;display:flex;flex-direction:column;gap:4px}
|
||||
.gpt-tier.on{border-style:solid;border-color:var(--gold,#e2b04a);box-shadow:0 0 0 1px var(--gold,#e2b04a) inset}
|
||||
.gpt-tier h4{margin:0;font-size:16px;display:flex;gap:6px;align-items:center;flex-wrap:wrap}
|
||||
.gpt-tier .gpt-price{margin:0;font-size:18px;font-weight:700}
|
||||
.gpt-tier ul{margin:4px 0;padding-left:18px;font-size:13px}
|
||||
.gpt-tier .gpt-acts{display:flex;gap:6px;flex-wrap:wrap;margin-top:auto;padding-top:6px}
|
||||
</style>
|
||||
</head>
|
||||
<body class="bo-body">
|
||||
@@ -96,11 +105,14 @@
|
||||
<button data-pane="house" type="button"><svg viewBox="0 0 24 24"><path d="M3 11l14-5v12L3 13v-2z"/><path d="M17 8a4 4 0 0 1 0 8M7 13v5a2 2 0 0 0 4 0v-3"/></svg>House ads</button>
|
||||
<button data-pane="campaigns" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h16M4 18h10"/></svg>All campaigns</button>
|
||||
<button data-pane="members" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="7" r="3.2"/><circle cx="5" cy="17" r="2.6"/><circle cx="19" cy="17" r="2.6"/><path d="M12 10v3M12 13l-5 2M12 13l5 2"/></svg>Members</button>
|
||||
<button data-pane="support" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="8.5"/><path d="M9.6 9.4a2.5 2.5 0 0 1 4.8.9c0 1.7-2.4 2.1-2.4 3.7"/><path d="M12 17v.5"/></svg>Support<span class="pill" id="supBadge" hidden></span></button>
|
||||
<button data-pane="kb" type="button"><svg viewBox="0 0 24 24"><path d="M4 5.5A2.5 2.5 0 0 1 6.5 3H20v15H6.5A2.5 2.5 0 0 0 4 20.5z"/><path d="M4 20.5A2.5 2.5 0 0 0 6.5 21H20v-3"/><path d="M9 8h7M9 11.5h5"/></svg>Knowledge base</button>
|
||||
<button data-pane="reports" type="button"><svg viewBox="0 0 24 24"><path d="M12 3l9 16H3z"/><path d="M12 10v4M12 17v.5"/></svg>Reports<span class="pill" id="repBadge" hidden></span></button>
|
||||
<button data-pane="traffic" type="button"><svg viewBox="0 0 24 24"><path d="M3 17l6-6 4 4 8-8"/><path d="M14 7h7v7"/></svg>Traffic</button>
|
||||
<button data-pane="blog" type="button"><svg viewBox="0 0 24 24"><path d="M4 4h12l4 4v12H4z"/><path d="M8 12h8M8 16h8M8 8h4"/></svg>Blog</button>
|
||||
<button data-pane="releases" type="button"><svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h7"/><circle cx="18" cy="17" r="3"/></svg>Releases</button>
|
||||
<button data-pane="pnl" type="button"><svg viewBox="0 0 24 24"><path d="M4 19V5M4 19h16"/><path d="M8 15l3-4 3 2 5-6"/></svg>P&L</button>
|
||||
<button data-pane="gamepass" type="button"><svg viewBox="0 0 24 24"><rect x="2.5" y="7" width="19" height="11" rx="5.5"/><path d="M7 11v3M5.5 12.5h3"/><circle cx="15.5" cy="11.5" r="1.1"/><circle cx="18" cy="13.5" r="1.1"/></svg>Game Pass</button>
|
||||
<button data-pane="settings" type="button"><svg viewBox="0 0 24 24"><circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/></svg>Settings</button>
|
||||
</nav>
|
||||
<div class="bo-links">
|
||||
@@ -120,6 +132,7 @@
|
||||
<button id="boBurger" aria-label="Menu" type="button">☰</button>
|
||||
<h2 id="boTitle" style="margin:0">Overview</h2>
|
||||
<span class="small muted" id="chainLine"></span>
|
||||
<span class="seg theme-seg" id="boTheme" role="group" aria-label="Theme"><button type="button" data-theme="light" title="Light theme">Light</button><button type="button" data-theme="dark" title="Dark theme">Dark</button><button type="button" data-theme="auto" title="Follow the device">Auto</button></span>
|
||||
</header>
|
||||
<main class="bo-content">
|
||||
|
||||
@@ -130,6 +143,7 @@
|
||||
<div class="statx c-violet"><div><div class="nv" id="ovActive">0</div><div class="lb">Active campaigns</div><span class="chip flat" id="ovCampSub"></span></div></div>
|
||||
<div class="statx c-amber"><div><div class="nv" id="ovReports">0</div><div class="lb">Open reports</div><span class="chip flat" id="ovBurnSub"></span></div></div>
|
||||
<div class="statx"><div><div class="nv" id="ovDrips">0</div><div class="lb">Follow-ups in flight</div><span class="chip flat" id="ovDripSub"></span></div></div>
|
||||
<div class="statx c-cyan"><div><div class="nv" id="ovBix">0</div><div class="lb">BixPay partner links</div><span class="chip flat" id="ovBixSub"></span></div></div>
|
||||
</div>
|
||||
<div class="grid c2" style="margin-top:16px">
|
||||
<div class="card">
|
||||
@@ -206,6 +220,7 @@
|
||||
<div id="hVisitsRow" hidden>
|
||||
<p><input id="hVisitTitle" maxlength="80" placeholder="Headline (what members see before visiting)" style="width:100%"></p>
|
||||
<p><input id="hVisitCount" type="number" min="20" placeholder="How many verified visits?" style="width:100%"></p>
|
||||
<p><select id="hVisitPlace" style="width:100%"><option value="all">Everywhere (Earn tab, refuels, Spooky Doors)</option><option value="doors">Behind Spooky Doors (doors only, in season)</option><option value="golden">Golden Spooky Door (doors only, bonus candy)</option></select></p>
|
||||
<p class="small muted" id="hVisitHint"></p>
|
||||
</div>
|
||||
<p id="hErr" class="small" style="color:var(--bad)" hidden></p>
|
||||
@@ -228,6 +243,11 @@
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-campaigns" hidden>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Login-ad line</h3><span class="sub" id="lqSub">paid reservations waiting for a slot</span></div>
|
||||
<p class="small muted" style="margin:0 0 10px">When every member slot is taken, a member can pay now to reserve the next one. The oldest paid reservation starts the moment a slot frees (on expiry, on a pause, and on a one-minute check), before any paused slot can come back. Estimated starts assume every live slot runs its full term. Cancel gives the full price back as purchased credits.</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="lqTable"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>All campaigns</h3><span class="sub" id="campSub">newest first</span></div>
|
||||
<p style="margin:0 0 10px"><input id="campFilter" placeholder="Filter by owner, name, type or status" style="width:100%"></p>
|
||||
@@ -250,6 +270,7 @@
|
||||
<button type="button" class="btn small sec" data-mcact="sponsor">Set sponsor</button>
|
||||
<button type="button" class="btn small sec" data-mcact="wallet">Swap main wallet</button>
|
||||
<button type="button" class="btn small sec" data-mcact="credits">Grant credits</button>
|
||||
<button type="button" class="btn small sec" data-mcact="message">Message (inbox + email)</button>
|
||||
<a class="btn small sec" id="mcWall" href="#" target="_blank" rel="noopener">Public wall</a>
|
||||
<button type="button" class="btn small sec" data-mcact="delete" style="margin-left:auto">Delete account</button>
|
||||
</div>
|
||||
@@ -261,6 +282,13 @@
|
||||
<p class="small muted" style="margin:12px 0 6px">Adoptions (newest first)</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="tankAdopt"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Sponsor check: InstantAdPay and LinkSpin</h3><span class="sub" id="scSub">members on both sites whose sponsor differs</span></div>
|
||||
<p class="small muted">Deliberate changes (a tank adoption, a rescue, a release, the end of an adoption window, an admin edit) follow to the other site until the member is bound on that site's contract. Everything else keeps the first sponsor. To settle a difference, pick the side whose sponsor is right: it is applied on the other site, unless the member is already bound there.</p>
|
||||
<p><button class="btn small" id="scRun" type="button">Run the check</button></p>
|
||||
<div class="tablewrap"><table class="adm-table" id="scTable"></table></div>
|
||||
<details style="margin-top:10px"><summary class="small muted">Recent sponsor follow activity on both sites</summary><div class="tablewrap"><table class="adm-table" id="scLog"></table></div></details>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Members</h3><span class="sub" id="memSub">newest first</span></div>
|
||||
<p style="margin:0 0 10px"><div class="card" id="fraudBox" style="margin-bottom:12px"><p class="small muted">Loading duplicate signals…</p></div>
|
||||
@@ -268,6 +296,55 @@
|
||||
<p class="small muted">Sponsor = the token the account joined under (username, share code, or member #). Editing it re-points free referrals and future purchases. On-chain sponsorship is permanent once activated.</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="memTable"></table></div>
|
||||
</div>
|
||||
<div class="card" id="spamCard">
|
||||
<div class="card-head"><h3>Link-farm list</h3><span class="sub" id="spamSub">daily scan at 06:30 Central</span></div>
|
||||
<p class="small muted">Free accounts (no package, no wallet) that carry a link plus a farm signal: a prohibited term in the profile, a sign-in that ended within 15 minutes of the sign-up, or no sponsor. Nothing is deleted on its own. Delete uses the normal member delete (on-chain members are refused) and never touches LinkSpin; the "also on LinkSpin" column is there so you can decide. Allow keeps an email off this list for good.</p>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0 0 10px"><button class="btn small" id="spamRun" type="button">Scan now</button><button class="btn small sec" id="spamDelete" type="button">Delete selected</button><span class="small muted" id="spamAllow"></span></p>
|
||||
<div class="tablewrap"><table class="adm-table" id="spamTable"></table></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-support" hidden>
|
||||
<div id="spList">
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Support desk</h3><span class="sub" id="spSub">tickets from Help, /support and the chatbot</span></div>
|
||||
<div class="chips" id="spStatus" style="margin-top:4px"></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
|
||||
<select id="spPlatform" class="small"><option value="">All platforms</option><option value="iap">InstantAdPay</option><option value="linkspin">LinkSpin</option></select>
|
||||
<select id="spCategory" class="small"></select>
|
||||
<input id="spQ" class="small" placeholder="Search ref, email, name, subject" style="flex:1;min-width:200px">
|
||||
</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="spTable"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Saved replies</h3><span class="sub">insert them from any ticket's reply box</span></div>
|
||||
<div id="spTpls"></div>
|
||||
<p style="display:flex;gap:10px;flex-wrap:wrap;margin:10px 0 0"><button type="button" class="btn small sec" id="spTplAdd">+ Add a saved reply</button><button type="button" class="btn small" id="spTplSave">Save saved replies</button></p>
|
||||
</div>
|
||||
<p class="small muted">New tickets and member replies ping your private Telegram chat (site setting supportTelegramChat) and email ADMIN_EMAIL, at most one ping per ticket every 10 minutes. Your replies email the requester and, for members, land in their Help tab as a quiet inbox notice.</p>
|
||||
</div>
|
||||
<div id="spView" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-kb" hidden>
|
||||
<div id="kbList">
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Knowledge base</h3><span class="sub" id="kbSub">what the chat assistant answers from</span></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:10px 0">
|
||||
<input id="kbQ" class="small" placeholder="Search title, questions, answer, tags" style="flex:1;min-width:200px">
|
||||
<select id="kbSrc" class="small"><option value="">All sources</option><option value="canned">From the code</option><option value="faq">FAQ</option><option value="ticket">From tickets</option><option value="admin">Added here</option></select>
|
||||
<button type="button" class="btn small" id="kbNew">+ New entry</button>
|
||||
</p>
|
||||
<div class="tablewrap"><table class="adm-table" id="kbTable"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Try a question</h3><span class="sub">which entry answers it, and what the AI is given</span></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;margin:0"><input id="kbTry" class="small" placeholder="Ask it the way a member would" style="flex:1;min-width:200px"><button type="button" class="btn small sec" id="kbTryGo">Test</button></p>
|
||||
<div id="kbTryOut" class="small"></div>
|
||||
</div>
|
||||
<p class="small muted">Instant answers (a pattern is set) reply on their own with no AI call. For every other question the closest entries go to the AI as its knowledge base, and when nothing fits it says it is not sure and points to support. In a ticket, "Save as KB entry" under your reply turns it into a draft here. Entries from the code follow chatbot.js and kb-seed.js until you edit them.</p>
|
||||
</div>
|
||||
<div id="kbEdit" class="card" hidden></div>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-reports" hidden>
|
||||
@@ -288,6 +365,11 @@
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-traffic" hidden>
|
||||
<div class="card"><div class="card-head"><h3>Games to members</h3><span class="sub" id="stSub">the $5 welcome offer after a game win</span></div><div class="tablewrap"><table class="adm-table" id="trfStarter"></table></div></div>
|
||||
<div class="card"><div class="card-head"><h3>Login-ad showings</h3><span class="sub" id="lsSub">sign-in interstitials per day, dashboard vs games</span></div><div class="tablewrap"><table class="adm-table" id="trfLogin"></table></div></div>
|
||||
<div class="card" id="trfBixCard"><div class="card-head"><h3>BixPay clicks</h3><span class="sub" id="bixSub">taps on "Get your BixPay card" by surface (the range picked below)</span></div>
|
||||
<p class="muted small" style="margin:0 0 10px">Every BixPay button and banner goes through /go/bixpay, which counts the tap and opens the member's resolved partner link (own, else a sponsor's, else the network link). Sign-ups are not counted here: the BIX portal shows each partner their directs and levels.</p>
|
||||
<div class="grid c2"><div class="tablewrap"><table class="adm-table" id="trfBix"></table></div><div class="tablewrap"><table class="adm-table" id="trfBixMembers"></table></div></div></div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Where visitors come from</h3><span class="sub" id="trfSub"></span></div>
|
||||
<div class="chips" id="trfRange" style="margin:0 0 10px"><button type="button" class="chip-t" data-days="7">7 days</button><button type="button" class="chip-t on" data-days="30">30 days</button><button type="button" class="chip-t" data-days="90">90 days</button><button type="button" class="chip-t" data-days="365">Year</button></div>
|
||||
@@ -411,7 +493,7 @@
|
||||
<label class="small">Closing (after the notes, e.g. your sign-off)<textarea id="updClosing" rows="2" style="width:100%" placeholder="See you Monday. Marty"></textarea></label>
|
||||
<label class="small">Audience<select id="updAudience"></select></label>
|
||||
<div style="display:flex;gap:8px;flex-wrap:wrap"><button type="button" class="btn small sec" id="updSaveDraft">Save draft</button><button type="button" class="btn small sec" id="updPreview">Preview</button><button type="button" class="btn small sec" id="updTest">Send test to me</button><button type="button" class="btn small" id="updSend">Send</button></div>
|
||||
<pre id="updPre" class="small" hidden style="white-space:pre-wrap;background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:10px;padding:10px;max-height:320px;overflow:auto"></pre>
|
||||
<pre id="updPre" class="small" hidden style="white-space:pre-wrap;background:var(--ink-faint);border:1px solid var(--line);border-radius:10px;padding:10px;max-height:320px;overflow:auto"></pre>
|
||||
</div>
|
||||
<div>
|
||||
<div class="small muted" style="margin:0 0 6px">Release notes to include (newest first; notes since your last send are pre-ticked)</div>
|
||||
@@ -435,9 +517,11 @@
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlSplit"></table></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>PolHunter payouts</h3><span class="sub">all time, its own faucet</span></div>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div>
|
||||
<p class="small muted" style="margin:10px 0 0">Marketing spend, paid in POL from the PolHunter wallet. None of it passes through the ad contract, so it is not in the lines above.</p>
|
||||
<div class="card-head"><h3>Game payouts</h3><span class="sub">all time, running total</span></div>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlGames"></table></div>
|
||||
<p class="small muted" style="margin:10px 0 0">Marketing spend: every POL send from each game's own payout wallet to a player, read from Polygon since the wallet's first transaction. Top-ups, moves between our wallets and returns to the fee wallets are left out. None of it passes through the ad contract, so it is not in the lines to the left.</p>
|
||||
<details style="margin-top:10px"><summary class="small">PolHunter detail (its own ledger)</summary>
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlHunt"></table></div></details>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Wallets</h3><span class="sub">live balances</span></div>
|
||||
@@ -452,8 +536,9 @@
|
||||
<div class="tablewrap"><table class="adm-table" id="pnlLedger"></table></div>
|
||||
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-top:12px">
|
||||
<select id="ldDir"><option value="in">Money in</option><option value="out">Money out</option></select>
|
||||
<select id="ldKind"><option value="revenue">Revenue</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select>
|
||||
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option></select>
|
||||
<select id="ldKind"><option value="revenue">Revenue</option><option value="cost">Cost</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select>
|
||||
<select id="ldCat" hidden><option value="advertising">Advertising</option><option value="games">Game marketing</option><option value="rewards">Player rewards</option><option value="software">Software and hosting</option><option value="other">Other cost</option></select>
|
||||
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option><option value="outside">Outside wallet</option></select>
|
||||
<input type="number" id="ldAmount" min="0" step="0.0001" placeholder="Amount in POL">
|
||||
<input type="number" id="ldUsd" min="0" step="0.01" placeholder="USD (optional)">
|
||||
<input type="date" id="ldDate">
|
||||
@@ -463,13 +548,70 @@
|
||||
<button class="btn small" type="button" id="ldAdd">Add line</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Tax summary</h3><span class="sub">income versus advertising and other costs, for one year</span></div>
|
||||
<p class="small muted" style="margin:0 0 10px">Income is the platform's share of every package sale, valued at that sale's own dollar price, plus outside revenue. Sales to your own positions are left out. Costs are the ledger's Cost lines; game wallet top-ups are recorded there automatically as Player rewards. Draws and transfers are your money, not expenses, so they are listed apart.</p>
|
||||
<p><select id="taxYear"></select> <button class="btn small" type="button" id="taxRun">Show</button> <button class="btn small sec" type="button" id="taxCsv" hidden>Copy CSV for your accountant</button></p>
|
||||
<div id="taxOut" class="small"></div>
|
||||
<textarea id="taxCsvText" hidden rows="6" style="width:100%;margin-top:8px" readonly></textarea>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Automatic credit burner</h3><span class="sub">settles pending campaign spend on-chain from the engine wallet</span></div>
|
||||
<p class="small" id="burnerLine">…</p>
|
||||
<p><button class="btn small sec" type="button" id="burnerRun">Run now</button></p>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Level 4 override</h3><span class="sub">3% of each purchase to the qualified 4th upline, paid weekly from the payer wallet</span></div>
|
||||
<p class="small" id="ovPayer">…</p>
|
||||
<div id="ovWeeks" class="small"></div>
|
||||
<p><select id="ovWeek"></select> <button class="btn small sec" type="button" id="ovShow">Show week</button> <button class="btn small" type="button" id="ovPay" hidden>Pay this week now</button></p>
|
||||
<div id="ovOut" class="small"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="pane" id="pane-gamepass" hidden>
|
||||
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));margin-top:0" id="gpStats"><p class="small muted">…</p></div>
|
||||
<div class="grid c2" style="margin-top:16px">
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>This week</h3><span class="sub" id="gpWeekSub"></span></div>
|
||||
<div id="gpWeek" class="small">…</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Pass Tournament</h3><span class="sub" id="gpTourSub"></span></div>
|
||||
<div id="gpTour" class="small">…</div>
|
||||
<p style="margin:12px 0 0;display:flex;gap:8px;flex-wrap:wrap"><button class="btn small sec" id="gpTourRun" type="button">Settle last week now</button></p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>By pass tier</h3><span class="sub" id="gpTiersSub"></span></div>
|
||||
<div id="gpTiers" class="small">…</div>
|
||||
</div>
|
||||
<div class="card" id="gpTestCard">
|
||||
<div class="card-head"><h3>Tier test and preview</h3><span class="sub" id="gpTestSub">admin only · your own account</span></div>
|
||||
<div id="gpTest" class="small">…</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Pass sales</h3><span class="sub" id="gpSalesSub"></span></div>
|
||||
<div id="gpSales" class="small">…</div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Comp a pass</h3><span class="sub">support: one pass period, recorded as no sale</span></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0"><input id="gpCompEmail" placeholder="member email" style="max-width:260px"><select id="gpCompTier"><option value="weekly">Game Pass (weekly)</option><option value="explorer">Explorer (monthly)</option><option value="champion">Champion (monthly)</option><option value="sovereign">Sovereign (monthly)</option><option value="legend">Legend (yearly)</option></select><input id="gpCompWhy" placeholder="why" style="max-width:220px"><button class="btn small" id="gpComp" type="button">Give one pass period</button><button class="btn small sec" id="gpRevoke" type="button">End this tier now (refund)</button></p>
|
||||
</div>
|
||||
<p class="small muted">Every pass is paid by a new package purchase of at least its price (since 2026-10-22; credits never buy a pass). The *PriceCredits settings are the pass price in cents. Settings live in Settings › Site settings: gamePassEnabled (1/0), gamePassPriceCredits, gamePassDays, capFreeDaily, capFreeTotal, capPassDaily, capPassTotal, capsStartDate (Central YYYY-MM-DD; empty = caps recorded, not enforced), passTournamentPct, telegramGamesTopicId. Tiers above weekly: sovTiers (1/0, the sale switch for all of them; off = members never see them and the admin tests them in Tier test and preview above, never on the member card), gamePassExplorerEnabled / gamePassChampionEnabled / gamePassSovereignEnabled / gamePassLegendEnabled (0 stops one tier), gamePassExplorerPriceCredits (2000), gamePassChampionPriceCredits (5000), gamePassSovereignPriceCredits (10000), gamePassLegendPriceCredits (25000); since 2026-10-25 every tier price equals a one-click package ($5, $20, $50, $100, $250), gamePassExplorerDays / gamePassChampionDays / gamePassSovereignDays (30), gamePassLegendDays (365), passTournamentTierSales (1 = their sales feed the tournament pool; default 0). Prize POL is paid by the games from their faucets (GET /api/partner/tournament/pending), not from here.</p>
|
||||
</div>
|
||||
|
||||
<div class="pane" id="pane-settings" hidden>
|
||||
<div class="card" id="kitCard">
|
||||
<div class="card-head"><h3>Refuel Kit</h3><span class="sub" id="kitSub">monthly members-only banners: unlocked by a counted refuel (needs refuelStreak on)</span></div>
|
||||
<p class="small muted">Five base images per month for this site's own program: 728x90, 300x250, 468x60, 160x600, 1200x630. Each member's @name and a QR to their own link are drawn on top: keep the right end clear on 728x90 and 468x60 (QR) with room for the name left of it, the bottom-right corner on 300x250 and 1200x630, and the bottom 170 px on 160x600. No income claims in any banner. Release on the 1st; a member unlocks the month's kit with their next counted refuel.</p>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center"><input id="kitMonth" placeholder="YYYY-MM" style="max-width:110px"><input id="kitTheme" placeholder="Theme (e.g. Harvest)" style="max-width:240px">
|
||||
<button class="btn small" id="kitSave" type="button">Save kit</button><button class="btn small sec" id="kitPlaceholder" type="button">Use placeholder art (public/banners)</button></p>
|
||||
<div id="kitSizes"></div>
|
||||
<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin-top:10px">Preview <select id="kitPrevSize"></select><input id="kitPrevName" placeholder="username" style="max-width:160px"><label class="small"><input type="checkbox" id="kitPrevGif" style="width:auto"> animated</label><button class="btn small sec" id="kitPreview" type="button">Preview</button></p>
|
||||
<div id="kitPrevBox"></div>
|
||||
<div id="kitList" class="small"></div>
|
||||
<div id="kitBox"></div>
|
||||
</div>
|
||||
<div class="card">
|
||||
<div class="card-head"><h3>Follow-up emails</h3><span class="sub" id="dripSub">sent to every new free member, hours after sign-up</span></div>
|
||||
<p class="small muted">One card per email. Placeholders fill in per reader: click a chip to drop it where your cursor is.
|
||||
@@ -510,7 +652,8 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20260923b"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/admin.js?v=20260923b"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// Admin > Knowledge base (2026-10-20, kb.js on the server): list, search, add, edit and delete the
|
||||
// entries the chat assistant answers from, try a question against them, and take a support reply
|
||||
// straight into a new entry (admin.js calls IAPKB.compose from a ticket's "Save as KB entry").
|
||||
(function () {
|
||||
const $ = IAP.$;
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
async function api(path, body, method) {
|
||||
const opts = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
|
||||
if (body !== undefined) { opts.headers['Content-Type'] = 'application/json'; opts.body = JSON.stringify(body); }
|
||||
const r = await (await fetch(path, opts)).json();
|
||||
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||
return r;
|
||||
}
|
||||
const ctDay = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', year: 'numeric' }) : '';
|
||||
const SRC = { canned: 'from the code', faq: 'FAQ', ticket: 'from a ticket', admin: 'added here' };
|
||||
let entries = [], filter = { q: '', src: '' }, wired = false;
|
||||
|
||||
function wire() {
|
||||
if (wired) return; wired = true;
|
||||
let t = null;
|
||||
$('kbQ').addEventListener('input', () => { clearTimeout(t); t = setTimeout(() => { filter.q = $('kbQ').value.trim(); load().catch(e => IAP.status(e.message, 'bad')); }, 300); });
|
||||
$('kbSrc').addEventListener('change', () => { filter.src = $('kbSrc').value; draw(); });
|
||||
$('kbNew').addEventListener('click', () => compose({}));
|
||||
$('kbTable').addEventListener('click', e => { const tr = e.target.closest('[data-kbid]'); if (tr) edit(tr.dataset.kbid).catch(err => IAP.status(err.message, 'bad')); });
|
||||
const go = async () => {
|
||||
const q = $('kbTry').value.trim(); if (!q) return $('kbTry').focus();
|
||||
const r = await api('/api/admin/kb/test', { question: q });
|
||||
$('kbTryOut').innerHTML = (r.fast ? '<p style="margin:6px 0"><b>Instant answer:</b> ' + esc(r.fast.title) + ' <span class="mono muted">' + esc(r.fast.id) + '</span> (no AI call)</p>' : '<p style="margin:6px 0">No instant answer, so this goes to the AI with:</p>')
|
||||
+ (r.ranked.length ? '<ol style="margin:4px 0 0 18px;padding:0">' + r.ranked.map(h => '<li' + (h.used ? '' : ' class="muted"') + '><a href="#" data-kbopen="' + esc(h.id) + '">' + esc(h.title) + '</a> <span class="mono">' + h.score + '</span>' + (h.used ? ' <b>used</b>' : '') + '</li>').join('') + '</ol>'
|
||||
: '<p class="muted" style="margin:4px 0">No entry matches, so the assistant is told to say it is not sure and point to support.</p>');
|
||||
};
|
||||
$('kbTryGo').addEventListener('click', () => go().catch(e => IAP.status(e.message, 'bad')));
|
||||
$('kbTry').addEventListener('keydown', e => { if (e.key === 'Enter') go().catch(err => IAP.status(err.message, 'bad')); });
|
||||
$('kbTryOut').addEventListener('click', e => { const a = e.target.closest('[data-kbopen]'); if (a) { e.preventDefault(); edit(a.dataset.kbopen).catch(err => IAP.status(err.message, 'bad')); } });
|
||||
}
|
||||
|
||||
async function load() {
|
||||
wire();
|
||||
$('kbEdit').hidden = true; $('kbList').hidden = false;
|
||||
const r = await api('/api/admin/kb' + (filter.q ? '?q=' + encodeURIComponent(filter.q) : ''));
|
||||
entries = r.entries || [];
|
||||
$('kbSub').textContent = (r.stamp ? r.stamp.count : entries.length) + ' entries' + (r.stamp && r.stamp.updated ? ' · last change ' + r.stamp.updated : '');
|
||||
draw();
|
||||
}
|
||||
function draw() {
|
||||
const rows = entries.filter(e => !filter.src || e.source === filter.src);
|
||||
$('kbTable').innerHTML = '<tr><th>Entry</th><th>Asked as</th><th>Source</th><th>Updated</th></tr>'
|
||||
+ (rows.length ? rows.map(e => '<tr data-kbid="' + esc(e.id) + '" style="cursor:pointer"><td><b>' + esc(e.title) + '</b>' + (e.score != null ? ' <span class="small muted mono">' + e.score + '</span>' : '')
|
||||
+ '<div class="small muted">' + esc(String(e.answer).slice(0, 140)) + (String(e.answer).length > 140 ? '…' : '') + '</div>'
|
||||
+ ((e.tags || []).length ? '<div class="small" style="margin-top:3px">' + e.tags.map(t => '<span class="house-tag" style="margin:0 4px 0 0">' + esc(t) + '</span>').join('') + '</div>' : '') + '</td>'
|
||||
+ '<td class="small">' + (e.questions || []).slice(0, 3).map(esc).join('<br>') + ((e.questions || []).length > 3 ? '<br><span class="muted">+' + (e.questions.length - 3) + ' more</span>' : '') + '</td>'
|
||||
+ '<td class="small">' + esc(SRC[e.source] || e.source) + (e.pattern ? '<div class="muted">instant</div>' : '') + (e.ticketRef ? '<div class="mono muted">' + esc(e.ticketRef) + '</div>' : '') + (e.edited && e.source !== 'admin' && e.source !== 'ticket' ? '<div class="muted">edited</div>' : '') + '</td>'
|
||||
+ '<td class="small muted" style="white-space:nowrap">' + esc(ctDay(e.updated)) + '</td></tr>').join('')
|
||||
: '<tr><td colspan="4" class="muted">No entries here.</td></tr>');
|
||||
}
|
||||
|
||||
async function edit(id) { const r = await api('/api/admin/kb/' + encodeURIComponent(id)); compose(r.entry); }
|
||||
// e: an existing entry (has id), or a prefill for a new one ({ title, questions, answer, tags, source, ticketRef })
|
||||
function compose(e) {
|
||||
wire();
|
||||
e = e || {};
|
||||
const isNew = !e.id;
|
||||
$('kbList').hidden = true; $('kbEdit').hidden = false;
|
||||
$('kbEdit').innerHTML = '<div class="card-head"><h3>' + (isNew ? 'New entry' : 'Edit entry') + '</h3><span class="sub mono">' + (isNew ? (e.ticketRef ? 'from ' + esc(e.ticketRef) : '') : esc(e.id) + ' · ' + esc(SRC[e.source] || e.source) + (e.ticketRef ? ' · ' + esc(e.ticketRef) : '') + ' · updated ' + esc(ctDay(e.updated))) + '</span></div>'
|
||||
+ (e.source === 'ticket' && isNew ? '<p class="small" style="margin:0 0 10px;color:var(--amber,#ffb238)">Taken from a support reply. Take out names, emails, member numbers and anything about this one account before saving: entries are shown to the assistant for every member who asks something similar.</p>' : '')
|
||||
+ (!isNew && (e.source === 'canned' || e.source === 'faq') && !e.edited ? '<p class="small muted" style="margin:0 0 10px">This entry comes from the code (chatbot.js or kb-seed.js) and follows it when the code changes. Saving it here makes it yours: later code changes to this entry are not applied.</p>' : '')
|
||||
+ '<div style="display:grid;gap:10px">'
|
||||
+ '<label class="small">Title<input id="kbTitle" maxlength="200" style="width:100%" value="' + esc(e.title || '') + '" placeholder="Can I use my regular Coinbase account?"></label>'
|
||||
+ '<label class="small">Question variants, one per line (how members actually ask it)<textarea id="kbQs" rows="4" style="width:100%">' + esc((e.questions || []).join('\n')) + '</textarea></label>'
|
||||
+ '<label class="small">Answer (plain words, no em dashes, never a promise of income; full https links)<textarea id="kbAns" rows="8" maxlength="4000" style="width:100%">' + esc(e.answer || '') + '</textarea></label>'
|
||||
+ '<label class="small">Tags, comma separated<input id="kbTags" style="width:100%" value="' + esc((e.tags || []).join(', ')) + '" placeholder="coinbase, exchange account, wallet"></label>'
|
||||
+ '<label class="small"><input type="checkbox" id="kbHandoff"' + (e.handoff ? ' checked' : '') + '> Offer "Send this to support" under this answer</label>'
|
||||
+ '<details' + (e.pattern ? ' open' : '') + '><summary class="small">Instant answer (advanced)</summary>'
|
||||
+ '<p class="small muted" style="margin:6px 0">A regular expression (case-insensitive). When a question matches it, this answer is sent as is, with no AI call. The lowest order number wins when several match; the code seeds use 10, 20, 30 and so on. Leave it empty to answer through the AI only.</p>'
|
||||
+ '<div style="display:grid;grid-template-columns:1fr 110px;gap:8px"><input id="kbPat" class="mono small" value="' + esc(e.pattern || '') + '" placeholder="(coinbase account|regular coinbase)"><input id="kbOrd" class="small" type="number" value="' + (e.order == null ? '' : esc(e.order)) + '" placeholder="order"></div></details>'
|
||||
+ '</div>'
|
||||
+ '<p style="display:flex;gap:10px;flex-wrap:wrap;margin:14px 0 0"><button type="button" class="btn small" id="kbSave">' + (isNew ? 'Add entry' : 'Save') + '</button><button type="button" class="btn small sec" id="kbCancel">Cancel</button>'
|
||||
+ (isNew ? '' : '<button type="button" class="btn small sec" id="kbDel" style="margin-left:auto">Delete</button>') + '</p>';
|
||||
$('kbCancel').addEventListener('click', () => { load().catch(err => IAP.status(err.message, 'bad')); });
|
||||
$('kbSave').addEventListener('click', async () => {
|
||||
const b = $('kbSave'); if (b.disabled) return; b.disabled = true;
|
||||
try {
|
||||
const body = { title: $('kbTitle').value, questions: $('kbQs').value.split('\n'), answer: $('kbAns').value, tags: $('kbTags').value.split(','),
|
||||
handoff: $('kbHandoff').checked, pattern: $('kbPat').value, order: $('kbOrd').value, source: e.source, ticketRef: e.ticketRef };
|
||||
if (isNew) await api('/api/admin/kb', body); else await api('/api/admin/kb/' + encodeURIComponent(e.id), body, 'PUT');
|
||||
IAP.status(isNew ? 'Entry added. The assistant uses it from the next question.' : 'Entry saved.', 'ok');
|
||||
await load();
|
||||
} catch (err) { IAP.status(err.message, 'bad'); } finally { b.disabled = false; }
|
||||
});
|
||||
if ($('kbDel')) $('kbDel').addEventListener('click', async () => {
|
||||
if (!(await IAP.confirmBox('Delete "' + (e.title || e.id) + '"? The assistant stops using it right away.', { ok: 'Delete', cancel: 'Keep it' }))) return;
|
||||
try { await api('/api/admin/kb/' + encodeURIComponent(e.id), undefined, 'DELETE'); IAP.status('Entry deleted.', 'ok'); await load(); } catch (err) { IAP.status(err.message, 'bad'); }
|
||||
});
|
||||
$('kbTitle').focus();
|
||||
}
|
||||
|
||||
// a support reply, tidied into a draft: the greeting and sign-off go, the member's words become the question
|
||||
function fromTicket(t, question, reply) {
|
||||
const q = String(question || '').replace(/^[\s\S]*?\bMe: /, '').split(/\nAssistant: /)[0].replace(/\s+/g, ' ').trim().slice(0, 300);
|
||||
const a = String(reply || '').replace(/^\s*(hi|hello|hey|dear|good (morning|afternoon|evening))\b[^\n]*\n+/i, '')
|
||||
.replace(/\n+\s*(thanks|thank you|cheers|best|regards|kind regards|talk soon|marty)\b[\s\S]{0,80}$/i, '').trim();
|
||||
const title = String(t.subject || '').replace(/^Chat:\s*/i, '').trim().slice(0, 200) || q.slice(0, 120);
|
||||
const tags = String(t.category || '').toLowerCase().split(/\s*&\s*|\s*,\s*/).filter(x => x && x !== 'other');
|
||||
return { title, questions: q ? [q] : [], answer: a, tags, source: 'ticket', ticketRef: t.ref };
|
||||
}
|
||||
|
||||
window.IAPKB = { load: () => load(), compose, fromTicket };
|
||||
})();
|
||||
@@ -0,0 +1,40 @@
|
||||
// Admin > Settings > Refuel Kit (2026-10-24). The SAME file ships in InstantAdPay and LinkSpin. Upload one month's base art
|
||||
// (five sizes, this site's own program), preview the personalization (@name + QR to the member's link), then release it.
|
||||
// Keep the QR corner and the name strip clear in the art (see the layout note on the card).
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
if (!$('kitBox')) return;
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const say = m => { $('kitSub').textContent = m; };
|
||||
const api = async (url, opt) => { const r = await fetch(url, Object.assign({ cache: 'no-store' }, opt || {})); const j = await r.json().catch(() => ({})); if (!r.ok || j.error) throw new Error(j.error || ('HTTP ' + r.status)); return j; };
|
||||
const post = (url, body) => api(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
|
||||
const nextMonth = () => { const d = new Date(); const ct = new Date(d.toLocaleString('en-US', { timeZone: 'America/Chicago' })); ct.setDate(1); ct.setMonth(ct.getMonth() + 1); return ct.getFullYear() + '-' + String(ct.getMonth() + 1).padStart(2, '0'); };
|
||||
let sizes = [];
|
||||
async function load() {
|
||||
try {
|
||||
const d = await api('/api/admin/kits'); sizes = d.sizes;
|
||||
if (!$('kitMonth').value) $('kitMonth').value = nextMonth();
|
||||
$('kitList').innerHTML = d.kits.length ? d.kits.map(k => '<div style="border:1px solid var(--line,#ccd);border-radius:8px;padding:10px;margin:8px 0">'
|
||||
+ '<b>' + esc(k.label) + '</b> ' + (k.theme ? '· ' + esc(k.theme) + ' ' : '') + '<span class="small muted">(' + esc(k.month) + ')</span> '
|
||||
+ (k.released ? '<span class="badge">released</span>' : '<span class="badge amber">draft</span>') + '<div class="small" style="margin:6px 0">'
|
||||
+ k.sizes.map(s => s.size + ': ' + (s.ready ? 'ready' : '<b>missing</b>')).join(' · ') + '</div>'
|
||||
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small sec" type="button" data-kedit="' + esc(k.month) + '" data-theme="' + esc(k.theme) + '">Edit</button>'
|
||||
+ '<button class="btn small' + (k.released ? ' sec' : '') + '" type="button" data-krel="' + esc(k.month) + '" data-on="' + (k.released ? '0' : '1') + '"' + (!k.complete && !k.released ? ' disabled title="upload all five sizes first"' : '') + '>' + (k.released ? 'Unrelease' : 'Release to members') + '</button></div></div>').join('') : '<p class="small muted">No kits yet.</p>';
|
||||
$('kitList').querySelectorAll('[data-kedit]').forEach(b => b.addEventListener('click', () => { $('kitMonth').value = b.dataset.kedit; $('kitTheme').value = b.dataset.theme; say('editing ' + b.dataset.kedit); }));
|
||||
$('kitList').querySelectorAll('[data-krel]').forEach(b => b.addEventListener('click', async () => { try { await post('/api/admin/kits', { month: b.dataset.krel, released: b.dataset.on === '1' }); load(); } catch (e) { say(e.message); } }));
|
||||
$('kitSizes').innerHTML = sizes.map(s => '<label class="small" style="display:block;margin:4px 0">' + s + ' <input type="file" accept="image/png,image/jpeg,image/gif" data-ksize="' + s + '"></label>').join('');
|
||||
$('kitSizes').querySelectorAll('[data-ksize]').forEach(inp => inp.addEventListener('change', async () => {
|
||||
const f = inp.files && inp.files[0]; if (!f) return; const m = $('kitMonth').value.trim();
|
||||
try { await api('/api/admin/kits/upload?month=' + encodeURIComponent(m) + '&size=' + inp.dataset.ksize, { method: 'POST', headers: { 'Content-Type': f.type }, body: f }); say(inp.dataset.ksize + ' uploaded for ' + m); load(); } catch (e) { say(e.message); }
|
||||
}));
|
||||
$('kitPrevSize').innerHTML = sizes.map(s => '<option>' + s + '</option>').join('');
|
||||
} catch (e) { say('Could not load: ' + e.message); }
|
||||
}
|
||||
$('kitSave').addEventListener('click', async () => { try { await post('/api/admin/kits', { month: $('kitMonth').value.trim(), theme: $('kitTheme').value }); say('saved'); load(); } catch (e) { say(e.message); } });
|
||||
$('kitPlaceholder').addEventListener('click', async () => { try { const r = await post('/api/admin/kits/placeholder', { month: $('kitMonth').value.trim() }); say('placeholder art: ' + r.sizes.join(', ')); load(); } catch (e) { say(e.message); } });
|
||||
$('kitPreview').addEventListener('click', () => {
|
||||
const q = 'month=' + encodeURIComponent($('kitMonth').value.trim()) + '&size=' + encodeURIComponent($('kitPrevSize').value) + '&username=' + encodeURIComponent($('kitPrevName').value || 'yourname') + ($('kitPrevGif').checked ? '&variant=gif' : '') + '&t=' + Date.now();
|
||||
$('kitPrevBox').innerHTML = '<img alt="preview" style="max-width:100%;border:1px solid var(--line-strong)" src="/api/admin/kits/preview?' + q + '">';
|
||||
});
|
||||
load();
|
||||
})();
|
||||
@@ -0,0 +1,64 @@
|
||||
// Admin > Members > Sponsor check (2026-10-22). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
// Lists members on both sites whose sponsor differs (or is set on one side only), with when and how each side's sponsor
|
||||
// was set and whether each side is bound on its contract. "Use X's sponsor" applies X's sponsor on the OTHER site; the
|
||||
// server refuses when the member is already bound there. Nothing runs until the admin presses "Run the check".
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
if (!$('scRun')) return;
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const day = ts => ts ? new Date(Number(ts)).toLocaleString([], { year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||
const HOW = { adopt: 'adopted from the tank', rescue: 'rescued to the tank', release: 'released to the tank', expire: 'adoption window ended', admin: 'admin edit', invited: 'the member named who invited them' };
|
||||
const NAME = { instantadpay: 'InstantAdPay', linkspin: 'LinkSpin' };
|
||||
function side(f) {
|
||||
if (!f) return '<span class="muted">no account</span>';
|
||||
const sp = f.sponsorEmail ? esc(f.sponsorName || f.sponsorEmail) + '<br><span class="small muted">' + esc(f.sponsorEmail) + '</span>' : f.deadLink ? '<span class="badge amber">dead link: ' + esc(f.sponsorRef) + '</span>' : '<span class="muted">none (in the tank)</span>';
|
||||
const how = [];
|
||||
if (f.prov) how.push('<b>' + esc(HOW[f.prov.by] || f.prov.by) + '</b> ' + esc(day(f.prov.at)) + (f.prov.origin ? ' on ' + esc(NAME[f.prov.origin] || f.prov.origin) : '') + (f.prov.prevEmail ? ', before: ' + esc(f.prov.prevEmail) : ''));
|
||||
else how.push('no deliberate change on record; account made ' + esc(day(f.created)) + (f.joinedVia ? ' via ' + esc(f.joinedVia) : '') + (f.joinedRef ? ' (' + esc(f.joinedRef) + ')' : ''));
|
||||
for (const a of (f.adoptions || []).slice(-3)) how.push('tank: ' + esc(a.status) + ' by ' + esc(a.adopter) + ' ' + esc(day(a.ts)));
|
||||
if (f.remoteTank && f.remoteTank.open) how.push('adopted on the other site by ' + esc(f.remoteTank.adopterEmail));
|
||||
if (f.pending) how.push('<span class="badge amber">follow waiting: ' + esc(f.pending.why || '') + '</span>');
|
||||
for (const l of (f.log || []).filter(x => x.conflict).slice(0, 2)) how.push('<span class="badge amber">' + esc(l.action) + '</span> ' + esc(l.reason || '') + ' ' + esc(day(l.ts)));
|
||||
const bound = f.bound ? '<span class="badge">bound on chain' + (f.memberId ? ': member #' + f.memberId : '') + (f.activation ? ', on-chain sponsor #' + f.activation.sponsorId + ', block ' + f.activation.block : '') + '</span>' : '<span class="muted small">not bound on chain' + (f.wallet ? ' (wallet linked)' : '') + '</span>';
|
||||
return sp + '<div class="small" style="margin-top:4px">' + how.join('<br>') + '</div><div style="margin-top:4px">' + bound + '</div>';
|
||||
}
|
||||
let last = null;
|
||||
async function run() {
|
||||
$('scRun').disabled = true; $('scSub').textContent = 'checking both sites...';
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/sponsor-check', { cache: 'no-store' })).json();
|
||||
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||
last = r;
|
||||
if (r.peerError) { $('scSub').textContent = 'could not read the other site: ' + r.peerError; $('scTable').innerHTML = ''; return; }
|
||||
const differ = r.rows.filter(x => x.kind === 'differ').length;
|
||||
$('scSub').textContent = r.shared + ' on both sites, ' + r.same + ' match, ' + differ + ' differ, ' + (r.rows.length - differ) + ' set on one side only (' + day(r.at) + ')';
|
||||
$('scTable').innerHTML = '<tr><th>Member</th><th>InstantAdPay sponsor</th><th>LinkSpin sponsor</th><th>Settle it</th></tr>' + (r.rows.length ? r.rows.map(x => {
|
||||
const iapBound = !!(x.iap && x.iap.bound), lsBound = !!(x.ls && x.ls.bound);
|
||||
return '<tr><td>' + esc(x.username ? '@' + x.username : '') + '<br><span class="small muted">' + esc(x.email) + '</span><br><span class="small muted">' + esc(x.kind === 'differ' ? 'different sponsors' : x.kind === 'iap-only' ? 'sponsor on InstantAdPay only' : 'sponsor on LinkSpin only') + '</span></td>'
|
||||
+ '<td>' + side(x.iap) + '</td><td>' + side(x.ls) + '</td><td class="act">'
|
||||
+ '<button class="btn small sec" data-scuse="instantadpay" data-email="' + esc(x.email) + '"' + (lsBound ? ' disabled title="bound on the LinkSpin contract: its sponsor there cannot change"' : '') + '>Use InstantAdPay\'s sponsor</button><br>'
|
||||
+ '<button class="btn small sec" style="margin-top:6px" data-scuse="linkspin" data-email="' + esc(x.email) + '"' + (iapBound ? ' disabled title="bound on the InstantAdPay contract: its sponsor there cannot change"' : '') + '>Use LinkSpin\'s sponsor</button></td></tr>';
|
||||
}).join('') : '<tr><td colspan="4" class="muted">Every shared member has the same sponsor on both sites.</td></tr>');
|
||||
const logs = [].concat((r.follow && r.follow.recent) || []).map(l => Object.assign({ where: r.here }, l)).concat(((r.peerFollow && r.peerFollow.recent) || []).map(l => Object.assign({ where: r.here === 'linkspin' ? 'instantadpay' : 'linkspin' }, l))).sort((a, b) => b.ts - a.ts).slice(0, 60);
|
||||
$('scLog').innerHTML = '<tr><th>When</th><th>Site</th><th>Member</th><th>What</th><th>From</th><th>To</th><th>Why</th></tr>' + (logs.length ? logs.map(l => '<tr><td class="when">' + esc(day(l.ts)) + '</td><td>' + esc(NAME[l.where] || l.where) + '</td><td class="small">' + esc(l.email || '') + '</td><td>' + (l.conflict ? '<span class="badge amber">' + esc(l.action) + '</span>' : esc(l.action)) + (l.by ? ' <span class="small muted">' + esc(HOW[l.by] || l.by) + '</span>' : '') + '</td><td class="small">' + esc(l.from || '-') + '</td><td class="small">' + esc(l.to || '(tank)') + '</td><td class="small muted">' + esc(l.reason || '') + '</td></tr>').join('') : '<tr><td colspan="7" class="muted">nothing yet</td></tr>');
|
||||
} catch (e) { $('scSub').textContent = e.message; say(e.message, 'bad'); }
|
||||
finally { $('scRun').disabled = false; }
|
||||
}
|
||||
$('scRun').addEventListener('click', run);
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-scuse]'); if (!b || b.disabled) return;
|
||||
const use = b.dataset.scuse, email = b.dataset.email; const row = last && last.rows.find(x => x.email === email); if (!row) return;
|
||||
const from = use === 'instantadpay' ? row.iap : row.ls; const target = use === 'instantadpay' ? 'LinkSpin' : 'InstantAdPay';
|
||||
const who = from && from.sponsorEmail ? (from.sponsorName || from.sponsorEmail) : 'no sponsor (back to the holding tank)';
|
||||
let ok = false;
|
||||
try { ok = await IAP.confirmBox('Set ' + email + "'s sponsor on " + target + ' to ' + who + '? The other site keeps what it has. This is refused if the member is already bound on the ' + target + ' contract.', { title: 'Use ' + NAME[use] + "'s sponsor", ok: 'Apply on ' + target, cancel: 'Cancel' }); } catch (err) { ok = false; }
|
||||
if (!ok) return;
|
||||
b.disabled = true;
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/sponsor-check/resolve', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email, use }) })).json();
|
||||
if (r.error) throw new Error(r.error === 'auth' ? 'Session expired. Sign in again.' : r.error);
|
||||
say('Done: ' + email + ' now has ' + who + ' on ' + target + '.', 'ok'); await run();
|
||||
} catch (err) { say(err.message, 'bad'); b.disabled = false; }
|
||||
});
|
||||
})();
|
||||
@@ -44,16 +44,18 @@
|
||||
});
|
||||
|
||||
// ── panes ──
|
||||
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', settings: 'Settings' };
|
||||
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, settings: loadSettings };
|
||||
const TITLES = { overview: 'Overview', house: 'House ads', campaigns: 'All campaigns', members: 'Members', support: 'Support', kb: 'Knowledge base', reports: 'Reports', traffic: 'Traffic', blog: 'Blog', releases: 'Releases and roadmap', pnl: 'Profit and loss', gamepass: 'Game Pass', settings: 'Settings' };
|
||||
const loaders = { overview: loadOverview, house: loadHouse, campaigns: loadCampaigns, members: loadMembers, support: loadSupport, kb: () => window.IAPKB.load(), reports: loadReports, traffic: loadTraffic, blog: loadBlog, releases: loadReleases, pnl: loadPnl, gamepass: loadGamePass, settings: loadSettings };
|
||||
function setPane(name) {
|
||||
const paneQ = String(name || '').split('?')[1] || ''; name = String(name || '').split('?')[0]; // #support?t=IAP-1042 opens that ticket (links in the Telegram ping and admin email)
|
||||
if (!TITLES[name]) name = 'overview';
|
||||
document.querySelectorAll('.pane').forEach(p => { p.hidden = p.id !== 'pane-' + name; });
|
||||
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.classList.toggle('on', b.dataset.pane === name));
|
||||
$('boTitle').textContent = TITLES[name];
|
||||
if (location.hash.slice(1) !== name) history.replaceState(null, '', '#' + name);
|
||||
const keepQ = name === 'support' && paneQ ? '?' + paneQ : '';
|
||||
if (location.hash.slice(1) !== name + keepQ) history.replaceState(null, '', '#' + name + keepQ);
|
||||
$('adminArea').classList.remove('side-open');
|
||||
loaders[name]().catch(e => IAP.status(e.message, 'bad'));
|
||||
return loaders[name](paneQ).catch(e => IAP.status(e.message, 'bad'));
|
||||
}
|
||||
document.querySelectorAll('.bo-menu [data-pane]').forEach(b => b.addEventListener('click', () => setPane(b.dataset.pane)));
|
||||
document.addEventListener('click', e => { const g = e.target.closest('[data-goto]'); if (g) setPane(g.dataset.goto); });
|
||||
@@ -72,6 +74,7 @@
|
||||
$('chainLine').textContent = c.chainName + (c.rehearsal ? ' · rehearsal' : '');
|
||||
} catch (e) {}
|
||||
setPane(location.hash.slice(1) || 'overview');
|
||||
supportBadge();
|
||||
}
|
||||
|
||||
// ── overview ──
|
||||
@@ -88,6 +91,7 @@
|
||||
const f = o.followups || {};
|
||||
$('ovDrips').textContent = f.active || 0;
|
||||
$('ovDripSub').textContent = (f.done || 0) + ' finished · ' + (f.unsubscribed || 0) + ' unsubscribed';
|
||||
if ($('ovBix')) { $('ovBix').textContent = Number(o.bixLinks || 0).toLocaleString(); $('ovBixSub').textContent = o.bixpayLive ? 'members with their own link · live' : 'members with their own link · bixpayLive is off'; } // BixPay (2026-10-29)
|
||||
const bt = Object.entries(o.byType || {}).sort((a, b) => b[1] - a[1]);
|
||||
$('ovByType').innerHTML = bt.length ? bt.map(([t, n]) => '<div style="display:flex;justify-content:space-between;padding:4px 0;border-bottom:1px solid var(--line)"><span>' + esc(t) + '</span><b>' + n + '</b></div>').join('') : 'No campaigns yet.';
|
||||
const ch = o.chain || {};
|
||||
@@ -154,9 +158,9 @@
|
||||
ctaLabel: t === 'video' ? $('hVideoCta').value : $('hSoloCta').value,
|
||||
videoUrl: $('hVideoUrl').value, watchSecs: Number($('hWatchSecs').value),
|
||||
videoW: hVidDims ? hVidDims.w : null, videoH: hVidDims ? hVidDims.h : null,
|
||||
days, startDay: Number($('hFeatStart').value) || 0, count,
|
||||
days, startDay: Number($('hFeatStart').value) || 0, count, placement: t === 'visits' && $('hVisitPlace') ? $('hVisitPlace').value : undefined,
|
||||
budget: t === 'featured' ? days * (rates.featuredPerDay || 40)
|
||||
: t === 'visits' ? count * (rates.visitCostPerVisit || 3)
|
||||
: t === 'visits' ? count * (($('hVisitPlace') && $('hVisitPlace').value === 'golden') ? (rates.goldenDoorCost || 6) : ($('hVisitPlace') && $('hVisitPlace').value === 'doors') ? (rates.doorPackCost || 4) : (rates.visitCostPerVisit || 3))
|
||||
: (Number($('hBudget').value) || 0) };
|
||||
try {
|
||||
await api('/api/admin/campaigns', body);
|
||||
@@ -253,10 +257,31 @@
|
||||
// ── all campaigns ──
|
||||
let allCamps = [];
|
||||
async function loadCampaigns() {
|
||||
loadLoginLine().catch(e => IAP.status(e.message, 'bad'));
|
||||
const r = await api('/api/admin/campaigns');
|
||||
allCamps = r.campaigns || [];
|
||||
drawCamps();
|
||||
}
|
||||
// prepaid login-ad line (2026-10-23): paid reservations waiting for a slot, oldest paid first. Dates in Central time.
|
||||
const lqWhen = ts => ts ? esc(ctWhen(ts)) : '<span class="muted">unknown</span>'; // ctWhen (below) prints Central time
|
||||
async function loadLoginLine() {
|
||||
const d = await api('/api/admin/login-queue');
|
||||
$('lqSub').textContent = d.used + ' of ' + d.max + ' member slots live · ' + d.queued + ' paid reservation' + (d.queued === 1 ? '' : 's') + ' in line · ' + d.free + ' open';
|
||||
$('lqTable').innerHTML = '<tr><th>Place</th><th>ID</th><th>Owner</th><th>Campaign</th><th>Paid</th><th>Queued at</th><th>Estimated start</th><th></th></tr>'
|
||||
+ (d.queue.length ? d.queue.map(c => '<tr><td><b>#' + c.place + '</b></td><td>#' + c.id + '</td><td><span class="trunc" title="' + esc(c.owner) + '">' + esc(c.owner) + '</span></td>'
|
||||
+ '<td>' + esc(c.name) + '<div><a class="small trunc" href="' + esc(c.targetUrl) + '" target="_blank" rel="noopener">' + esc(c.targetUrl) + '</a></div></td>'
|
||||
+ '<td class="mono small">' + Number(c.paid || 0).toLocaleString() + '</td><td class="small muted">' + lqWhen(c.queuedAt) + '</td><td class="small">' + lqWhen(c.estStart) + '</td>'
|
||||
+ '<td class="act"><button class="btn small sec" data-lqcancel="' + c.id + '" data-lqowner="' + esc(c.owner) + '" data-lqpaid="' + Number(c.paid || 0) + '">Cancel + refund</button></td></tr>').join('')
|
||||
: '<tr><td colspan="8" class="muted">Nobody is waiting. When every slot is taken, members can pay now to reserve the next one.</td></tr>');
|
||||
}
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-lqcancel]'); if (!b) return;
|
||||
const ok = await IAP.confirmBox('Cancel reservation #' + b.dataset.lqcancel + ' for ' + b.dataset.lqowner + '? The full ' + Number(b.dataset.lqpaid || 0).toLocaleString() + ' credits go back to them as purchased credits, and everyone behind moves up one place.', { title: 'Cancel and refund', ok: 'Cancel and refund', cancel: 'Keep it' });
|
||||
if (!ok) return;
|
||||
b.disabled = true;
|
||||
try { const r = await api('/api/admin/login-queue/' + b.dataset.lqcancel + '/cancel', {}); IAP.status('Reservation #' + r.id + ' cancelled, ' + Number(r.refunded || 0).toLocaleString() + ' credits refunded.', 'ok'); await loadCampaigns(); }
|
||||
catch (err) { IAP.status(err.message, 'bad'); b.disabled = false; }
|
||||
});
|
||||
function drawCamps() {
|
||||
const q = ($('campFilter').value || '').trim().toLowerCase();
|
||||
const list = allCamps.filter(c => !q || [c.owner, c.name, c.type, c.status, c.targetUrl, String(c.id)].join(' ').toLowerCase().includes(q));
|
||||
@@ -270,12 +295,18 @@
|
||||
async function loadTank() {
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/tank')).json(); if (r.error) return;
|
||||
$('tankAdmSub').textContent = r.waiting.length + ' waiting · cap ' + r.cap + ' open per adopter · ' + r.ttlDays + '-day window';
|
||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>');
|
||||
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
||||
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.opensAt > Date.now() ? ' <span class="badge amber" title="New sign-up: hand adoption opens 24 hours after they joined">Opens ' + when(w.opensAt) + '</span>' : '') + (w.ready ? ' <span class="badge" style="background:var(--ok-soft);border-color:var(--ok);color:var(--ok)">Ready to activate · ' + left(w) + '</span>' : '');
|
||||
$('tankWait').innerHTML = '<tr><th>Waiting</th><th>Email</th><th>Joined</th><th>Last sign-in</th></tr>' + (r.waiting.length ? r.waiting.map(w => '<tr><td>' + esc(w.name) + rb(w) + '</td><td>' + esc(w.email) + '</td><td class="when">' + when(w.joined) + '</td><td class="when">' + (w.lastSeen ? when(w.lastSeen) : '<span class="muted">never</span>') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">empty</td></tr>')
|
||||
+ ((r.aligned || []).length ? '<tr><th colspan="4">Aligned to their network sponsor (LinkSpin) instead of the tank</th></tr>' + r.aligned.slice(0, 15).map(x => '<tr><td>' + esc(x.email) + '</td><td>' + esc(x.toName || x.to) + '</td><td class="when">' + when(x.at) + '</td><td class="muted">' + esc(x.via || '') + '</td></tr>').join('') : '');
|
||||
$('tankAdopt').innerHTML = '<tr><th>Member</th><th>Adopted by</th><th>When</th><th>Window ends</th><th>Status</th></tr>' + (r.adoptions.length ? r.adoptions.map(a => '<tr><td>' + esc(a.adopteeName) + '</td><td>' + esc(a.adopterName) + '</td><td class="when">' + when(a.ts) + '</td><td class="when">' + (a.status === 'released' || a.status === 'invited' ? '' : when(a.expires)) + '</td><td>' + esc(a.status) + '</td></tr>').join('') : '<tr><td colspan="5" class="muted">none yet</td></tr>');
|
||||
} catch (e) {}
|
||||
}
|
||||
async function loadMembers() {
|
||||
loadSpamScan().catch(() => {});
|
||||
loadTank(); loadFraud();
|
||||
const r = await api('/api/admin/members');
|
||||
allMembers = r.members || [];
|
||||
@@ -294,6 +325,31 @@
|
||||
+ '<td class="act"><button class="btn small sec" data-mcopen="' + esc(a.email) + '">Open</button> <button class="btn small sec" data-susp="' + esc(a.email) + '" data-on="' + (a.suspended ? '1' : '0') + '">' + (a.suspended ? 'Unsuspend' : 'Suspend') + '</button> <button class="btn small sec" data-spon="' + esc(a.email) + '" data-cur="' + esc(a.sponsorRef || '') + '">Sponsor</button></td></tr>').join('');
|
||||
}
|
||||
$('memFilter').addEventListener('input', drawMembers);
|
||||
// Link-farm list (2026-10-30): the daily scan's candidates; Delete selected = one DELETE /api/admin/member per email (on-chain refused); Allow = spamScanAllow
|
||||
async function loadSpamScan() {
|
||||
let v; try { v = await api('/api/admin/spamscan'); } catch (e) { return; }
|
||||
const last = v.last || {}; const rows = last.candidates || [];
|
||||
$('spamSub').textContent = last.at ? (rows.length + ' candidate' + (rows.length === 1 ? '' : 's') + ' \u00B7 scanned ' + when(last.at) + (last.manual ? ' (manual)' : '') + ' \u00B7 ' + (last.scanned || 0) + ' accounts, ' + (last.skipped || 0) + ' allowlisted') : 'no scan yet (daily at 06:30 Central)';
|
||||
$('spamAllow').textContent = 'Allowlist: ' + ((v.allow || []).join(', ') || 'empty');
|
||||
$('spamTable').innerHTML = '<tr><th></th><th>Account</th><th>Joined</th><th>Sponsor</th><th>First link</th><th>Why</th><th>Also on ' + esc(v.otherSite || 'the other site') + '</th><th></th></tr>'
|
||||
+ (rows.length ? rows.map(c => '<tr><td><input type="checkbox" data-spamsel="' + esc(c.email) + '"></td><td>' + (c.username ? '<b>@' + esc(c.username) + '</b><br>' : '') + '<span class="small">' + esc(c.email) + '</span>' + (c.quarantined ? ' <span class="badge amber">quarantined</span>' : '') + '</td>'
|
||||
+ '<td class="small muted when">' + when(c.created) + '</td><td class="small">' + esc(c.sponsorName || 'none') + '</td><td class="small mono" style="max-width:260px;overflow:hidden;text-overflow:ellipsis" title="' + esc((c.links || []).join(' ')) + '">' + esc(c.firstLink || '') + '</td>'
|
||||
+ '<td class="small">' + esc((c.reasons || []).join(', ')) + '</td><td class="small">' + (c.alsoOn === true ? 'yes' : c.alsoOn === false ? 'no' : 'unknown') + '</td>'
|
||||
+ '<td class="act"><button class="btn small sec" data-mcopen="' + esc(c.email) + '">Open</button> <button class="btn small sec" data-spamallow="' + esc(c.email) + '">Allow</button></td></tr>').join('') : '<tr><td colspan="8" class="muted small">Nothing to review.</td></tr>');
|
||||
}
|
||||
$('spamRun').addEventListener('click', busy($('spamRun'), async () => { await api('/api/admin/spamscan/run', {}); await loadSpamScan(); IAP.status('Scan done.', 'ok'); }));
|
||||
$('spamDelete').addEventListener('click', busy($('spamDelete'), async () => {
|
||||
const sel = [...document.querySelectorAll('[data-spamsel]:checked')].map(x => x.dataset.spamsel);
|
||||
if (!sel.length) { IAP.status('Tick the accounts to delete first.', 'bad'); return; }
|
||||
if (!await IAP.confirmBox('Delete ' + sel.length + ' account' + (sel.length === 1 ? '' : 's') + ' with their profile text? On-chain members are refused. LinkSpin is not touched.', { title: 'Delete selected', ok: 'Delete', cancel: 'Cancel' })) return;
|
||||
let ok = 0, bad = 0; for (const e of sel) { try { await api('/api/admin/member?email=' + encodeURIComponent(e), undefined, 'DELETE'); ok++; } catch (err) { bad++; } }
|
||||
IAP.status(ok + ' deleted' + (bad ? ', ' + bad + ' refused' : '') + '.', bad ? 'bad' : 'ok');
|
||||
await api('/api/admin/spamscan/run', {}).catch(() => {}); await loadSpamScan(); loadMembers().catch(() => {});
|
||||
}));
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-spamallow]'); if (!b) return;
|
||||
try { await api('/api/admin/spamscan/allow', { email: b.dataset.spamallow }); IAP.status('Allowed ' + b.dataset.spamallow + '.', 'ok'); await api('/api/admin/spamscan/run', {}).catch(() => {}); loadSpamScan(); } catch (err) { IAP.status(err.message, 'bad'); }
|
||||
});
|
||||
document.addEventListener('click', async e => {
|
||||
const b = e.target.closest('[data-susp]'); if (!b) return;
|
||||
const on = b.dataset.on === '1';
|
||||
@@ -374,7 +430,7 @@
|
||||
mcCur = d; const a = d.account; $('memHits').hidden = true;
|
||||
$('memCard').hidden = false; document.querySelectorAll('#pane-members > .card').forEach(c => { if (c.id !== 'memCard' && c.id !== 'memSearchCard') c.hidden = true; });
|
||||
$('mcName').textContent = (a.username ? '@' + a.username : a.email) + (a.memberId ? ' · member #' + a.memberId : ' · free member');
|
||||
$('mcSub').textContent = 'joined ' + when(a.created) + ' · last seen ' + ago(a.lastSeen);
|
||||
$('mcSub').textContent = 'joined ' + when(a.created) + ' · last seen ' + ago(a.lastSeen) + (a.profileQuarantined ? ' · PROFILE QUARANTINED (link planted on a brand-new free account; not shown publicly)' : '');
|
||||
$('mcWall').hidden = !a.username; if (a.username) $('mcWall').href = '/wall/' + a.username;
|
||||
const ch = d.chain, cr = d.credits, t = d.totals;
|
||||
const level = ch && !ch.readError ? (ch.buyerCount >= 5 ? 'level 3 (5+ buyers)' : ch.buyerCount >= 2 ? 'level 2 (2 buyers)' : 'level 1') : '';
|
||||
@@ -390,11 +446,13 @@
|
||||
? ' <span class="small" style="color:var(--mint)">payouts ON</span>'
|
||||
: ' <span class="small" style="color:var(--bad)">payouts OFF</span>')
|
||||
: '<span class="muted">none linked</span>'],
|
||||
['PolyWarriors mint passes', d.pwPasses ? '<b>' + (d.pwPasses.n || 0) + '</b> unused <span class="muted small">(earned ' + (d.pwPasses.earned || 0) + ', used ' + (d.pwPasses.used || 0) + ')</span>' : '<span class="muted">none</span>'],
|
||||
['Extra positions', d.positions.length ? d.positions.map(p => '<span class="mono small">' + esc(p.address.slice(0, 8) + '…' + p.address.slice(-6)) + '</span>' + (p.memberId ? ' = #' + p.memberId : ' (unregistered)')).join('<br>') : '<span class="muted">none</span>'],
|
||||
['Sponsor (site)', d.upline.length ? memLink(d.upline[0].email, d.upline[0].name) + ' <span class="muted small">token ' + esc(a.sponsorRef || '') + '</span>' : (a.sponsorRef ? '<span class="muted">unresolved: ' + esc(a.sponsorRef) + '</span>' : '<span class="muted">none (company)</span>')],
|
||||
['Upline chain', d.upline.length > 1 ? d.upline.map(u => memLink(u.email, u.name)).join(' → ') : '<span class="muted">-</span>'],
|
||||
['Joined via', esc(a.joinedVia || 'join page') + (a.joinedRef ? ' from ' + esc(a.joinedRef) : '')],
|
||||
['Line banner', a.lineTargetUrl ? '<a href="' + esc(a.lineTargetUrl) + '" target="_blank" rel="noopener">' + esc(a.lineTargetUrl.slice(0, 50)) + '</a>' : '<span class="muted">not set</span>'],
|
||||
['BixPay partner link', a.bixPartnerLink ? '<span class="mono small" style="overflow-wrap:anywhere">' + esc(a.bixPartnerLink) + '</span>' : '<span class="muted">not set (pages use a sponsor’s link or the network link)</span>'],
|
||||
['Chat', a.chatAvailable ? 'available' : 'switched off']]) + '</div>';
|
||||
h += '<div><h4 style="margin:0 0 6px">On-chain and money</h4>' + kv([
|
||||
// Say WHICH of the two "not registered" states this is, and what it costs them, so the row
|
||||
@@ -428,7 +486,7 @@
|
||||
h += '<div><h4 style="margin:0 0 6px">Payouts received</h4><div class="tablewrap"><table class="adm-table"><tr><th>When</th><th>From</th><th>Tier</th><th>Amount</th></tr>'
|
||||
+ (d.received.length ? d.received.map(r => '<tr><td class="small">' + when(r.ts) + '</td><td>#' + r.buyerId + (d.names[r.buyerId] ? ' @' + esc(d.names[r.buyerId]) : '') + '</td><td>' + r.tier + '</td><td>' + polOf(r.amountWei) + ' POL</td></tr>').join('') : '<tr><td colspan="4" class="muted">Nothing received yet.</td></tr>') + '</table></div></div></div>';
|
||||
h += '<h4 style="margin:18px 0 6px">Campaigns (' + d.campaigns.length + ')</h4><div class="tablewrap"><table class="adm-table"><tr><th>#</th><th>Type</th><th>Status</th><th>Budget</th><th>Spent</th><th>Views</th><th>Clicks</th><th>Created</th></tr>'
|
||||
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + Number(c.views || 0).toLocaleString() + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
|
||||
+ (d.campaigns.length ? d.campaigns.map(c => '<tr><td>' + c.id + '</td><td>' + esc(c.type) + '</td><td>' + esc(c.status) + '</td><td>' + Number(c.budget || 0).toLocaleString() + '</td><td>' + Number(c.spent || 0).toLocaleString() + '</td><td>' + (c.pack ? Number(c.views || 0).toLocaleString() + ' <span class="muted small">of ' + Number(c.pack).toLocaleString() + ' visits</span>' : Number(c.views || 0).toLocaleString()) + '</td><td>' + Number(c.clicks || 0).toLocaleString() + '</td><td class="small muted">' + when(c.created) + '</td></tr>').join('') : '<tr><td colspan="8" class="muted">No campaigns.</td></tr>') + '</table></div>';
|
||||
$('mcBody').innerHTML = h;
|
||||
if (location.hash !== '#members') history.replaceState(null, '', '#members');
|
||||
loadTrace(d);
|
||||
@@ -445,11 +503,11 @@
|
||||
let h = '<h4 style="margin:18px 0 6px">Payment trace</h4><p class="small muted" style="margin:0 0 6px">' + r.buyersNow + ' qualifying buyer' + (r.buyersNow === 1 ? '' : 's') + ' · every purchase this member was part of, newest first.</p>';
|
||||
if (!r.purchases.length) h += '<p class="small muted">No purchases involving them yet.</p>';
|
||||
for (const p of r.purchases) {
|
||||
h += '<div style="border:1px solid rgba(255,255,255,.1);border-radius:8px;padding:8px 10px;margin:0 0 6px"><div class="small"><b>' + when(p.ts) + '</b> · ' + nm(p.buyerId) + ' bought $' + (p.priceCents / 100).toFixed(0) + ' (' + polOf(p.paidWei) + ' POL)' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + ' · <span class="muted">' + esc(p.tx.slice(0, 12)) + '…</span></div>';
|
||||
h += '<div style="border:1px solid var(--line);border-radius:8px;padding:8px 10px;margin:0 0 6px"><div class="small"><b>' + when(p.ts) + '</b> · ' + nm(p.buyerId) + ' bought $' + (p.priceCents / 100).toFixed(0) + ' (' + polOf(p.paidWei) + ' POL)' + (p.sponsorId ? ' · sponsor ' + nm(p.sponsorId) : '') + ' · <span class="muted">' + esc(p.tx.slice(0, 12)) + '…</span></div>';
|
||||
for (const t of p.tiers) {
|
||||
let line = '<b>L' + t.tier + ' ' + t.pct + '%</b>: ';
|
||||
for (const x of t.skipped) line += '<span style="color:#f0a742">' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' buyers then' : esc(x.reason)) + ')</span> → ';
|
||||
line += t.paidTo ? '<span style="color:' + (t.paidTo === mid ? '#3ecf7a' : 'inherit') + '">' + nm(t.paidTo) + ' ' + polOf(t.amountWei) + ' POL</span>' : '<span class="muted">no catcher → company</span>';
|
||||
for (const x of t.skipped) line += '<span style="color:var(--warn)">' + nm(x.id) + ' skipped (' + (x.reason === 'unqualified' ? 'had ' + x.buyersThen + ' of ' + (t.tier === 2 ? 2 : 5) + ' buyers then' : esc(x.reason)) + ')</span> → ';
|
||||
line += t.paidTo ? '<span style="color:' + (t.paidTo === mid ? 'var(--ok)' : 'inherit') + '">' + nm(t.paidTo) + ' ' + polOf(t.amountWei) + ' POL</span>' : '<span class="muted">no catcher → company</span>';
|
||||
h += '<div class="small" style="margin-top:3px">' + line + '</div>';
|
||||
}
|
||||
h += '<div class="small muted" style="margin-top:3px">platform ' + polOf(p.adminWei) + ' POL</div></div>';
|
||||
@@ -486,6 +544,14 @@
|
||||
if (act === 'sponsor') { const v = await IAP.ask({ title: 'Sponsor for ' + (a.username ? '@' + a.username : a.email), text: 'Username, share code or member #. Blank = no sponsor (company). Re-points free referrals and future purchases; on-chain sponsorship never changes.', value: a.sponsorRef || '', ok: 'Save' }); if (v === null || v === undefined) return; body = { sponsorRef: v }; }
|
||||
if (act === 'wallet') { const v = await IAP.ask({ title: 'Main wallet for ' + a.email, text: 'Paste the 0x address that should be their main wallet (the one that paid, if a purchase came from an unlinked account). The member number is re-read from the chain. Blank = unlink.', value: a.address || '', ok: 'Swap' }); if (v === null || v === undefined) return; if (!await IAP.confirmBox('Swap the main wallet for ' + a.email + ' to ' + (v.trim() || 'nothing') + '?', { title: 'Sure?', ok: 'Swap it', cancel: 'Cancel' })) return; body = { address: v }; }
|
||||
if (act === 'credits') { const v = await IAP.ask({ title: 'Grant credits to ' + (a.username ? '@' + a.username : a.email), text: 'Whole number of earned-pool credits (1 credit = 1 cent of delivery). They can spend them on campaigns right away.', type: 'number', value: '', placeholder: '250', ok: 'Grant' }); if (!v) return; const note = await IAP.ask({ title: 'Reason (kept in the server log)', value: '', placeholder: 'e.g. refund for broken banner', ok: 'Grant' }); body = { grantCredits: v, note: note || '' }; }
|
||||
// message the member (Marty 2026-11-12): lands in their member inbox AND emails them (opt-outs honoured by the mailer)
|
||||
if (act === 'message') {
|
||||
const who = a.username ? '@' + a.username : a.email;
|
||||
const subject = await IAP.ask({ title: 'Message ' + who, text: 'Subject line. The message goes to their member inbox and is emailed to them (unless they unsubscribed from email).', value: '', placeholder: 'A quick note from Marty', ok: 'Next' }); if (!subject) return;
|
||||
const text = await IAP.ask({ title: subject, text: 'Your message. Plain text; blank lines start new paragraphs.', type: 'textarea', value: '', ok: 'Send' }); if (!text || !text.trim()) return;
|
||||
const r = await api('/api/admin/member/message', { email: a.email, subject, text }, 'POST');
|
||||
IAP.status('Sent to ' + who + "'s inbox" + (r.emailed ? ' and emailed.' : r.emailSkipped ? '. Email skipped: ' + r.emailSkipped + '.' : '.'), r.emailed ? 'ok' : 'warn'); return;
|
||||
}
|
||||
if (act === 'delete') {
|
||||
if (a.memberId) { IAP.status('Registered members cannot be deleted; their position is on-chain.', 'bad'); return; }
|
||||
if (!await IAP.confirmBox('Delete the free account ' + a.email + '? Their sign-in, referrals link and credits go away. There is no undo.', { title: 'Delete account', ok: 'Delete', cancel: 'Keep it' })) return;
|
||||
@@ -535,8 +601,14 @@
|
||||
try {
|
||||
const d = await api('/api/admin/updates');
|
||||
$('updSub').textContent = (d.mailer ? '' : 'mailer not configured · ') + (d.lastSentAt ? 'last send ' + new Date(d.lastSentAt).toLocaleString() : 'nothing sent yet') + (d.running ? ' · sending now' : '');
|
||||
$('updAudience').innerHTML = Object.entries(d.audiences).map(([k, v]) => '<option value="' + k + '">' + esc(v) + ' (' + (d.counts[k] || 0) + ')</option>').join('');
|
||||
$('updNotes').innerHTML = d.notes.length ? d.notes.map(n => '<label class="small" style="display:flex;gap:8px;align-items:flex-start"><input type="checkbox" value="' + esc(n.id) + '"' + (n.fresh ? ' checked' : '') + '><span>' + esc(n.title) + ' <span class="muted">' + esc(n.date) + '</span></span></label>').join('') : '<span class="muted small">No release notes yet.</span>';
|
||||
const keep = $('updAudience').value;
|
||||
$('updAudience').innerHTML = Object.entries(d.audiences).map(([k, v]) => '<option value="' + k + '">' + esc(v) + (d.counts ? ' (' + (d.counts[k] || 0) + ')' : ' (counting…)') + '</option>').join('');
|
||||
if (keep) $('updAudience').value = keep;
|
||||
if (!d.counts) setTimeout(() => loadUpdates().catch(() => {}), 15000); // the counts are being worked out in the background
|
||||
// a re-render (the background count refresh) must keep whatever is ticked; only the first render pre-ticks fresh notes,
|
||||
// and a saved draft decides for itself (Marty, 2026-09-28: a test send carried every note because a refresh re-ticked them)
|
||||
const wasTicked = new Set([...$('updNotes').querySelectorAll('input:checked')].map(i => i.value)), rendered = $('updNotes').querySelector('input') !== null;
|
||||
$('updNotes').innerHTML = d.notes.length ? d.notes.map(n => '<label class="small" style="display:flex;gap:8px;align-items:flex-start"><input type="checkbox" value="' + esc(n.id) + '"' + ((rendered || updDraftLoaded) ? (wasTicked.has(n.id) ? ' checked' : '') : (n.fresh && !d.draft ? ' checked' : '')) + '><span>' + esc(n.title) + ' <span class="muted">' + esc(n.date) + '</span></span></label>').join('') : '<span class="muted small">No release notes yet.</span>';
|
||||
$('updLog').innerHTML = '<tr><th>When</th><th>Subject</th><th>Audience</th><th>Sent</th></tr>' + (d.sends.length ? d.sends.map(x => '<tr><td class="small">' + new Date(x.ts).toLocaleString() + '</td><td>' + esc(x.subject) + '</td><td class="small">' + esc(d.audiences[x.audience] || x.audience) + '</td><td class="small">' + x.sent + ' of ' + x.total + (x.skipped ? ' · ' + x.skipped + ' opted out' : '') + (x.failed ? ' · ' + x.failed + ' failed' : '') + (x.unknown ? ' · ' + x.unknown + ' unchecked (Sendy gave no answer)' : '') + (x.status === 'running' ? ' · running' : '') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted small">None yet.</td></tr>');
|
||||
if (d.draft && !updDraftLoaded) { updDraftLoaded = true; $('updSubject').value = d.draft.subject || ''; $('updIntro').value = d.draft.intro || ''; $('updClosing').value = d.draft.closing || ''; if (d.draft.audience) $('updAudience').value = d.draft.audience; $('updNotes').querySelectorAll('input').forEach(i => { i.checked = (d.draft.noteIds || []).includes(i.value); }); $('updSub').textContent += ' · draft loaded (saved ' + new Date(d.draft.savedAt).toLocaleString() + ')'; }
|
||||
if (d.running) setTimeout(loadUpdates, 4000);
|
||||
@@ -549,7 +621,7 @@
|
||||
$('updPreview').addEventListener('click', busy($('updPreview'), async () => { const r = await api('/api/admin/updates/preview', updInput()); $('updPre').hidden = false; $('updPre').textContent = 'Subject: ' + r.subject + '\n\n' + r.text; }));
|
||||
$('updTest').addEventListener('click', busy($('updTest'), async () => { const r = await api('/api/admin/updates/send', Object.assign(updInput(), { test: true })); IAP.status('Test sent to ' + r.to + '.', 'ok'); }));
|
||||
$('updSend').addEventListener('click', busy($('updSend'), async () => {
|
||||
const inp = updInput(); if (!inp.noteIds.length) { IAP.status('Pick at least one note.', 'bad'); return; }
|
||||
const inp = updInput(); if (!inp.noteIds.length && !String(inp.intro || '').trim()) { IAP.status('Write an intro or pick at least one note.', 'bad'); return; }
|
||||
const opt = $('updAudience').selectedOptions[0].textContent;
|
||||
if (!(await IAP.confirmBox('Send this update to ' + opt + '? One email per member, opt-outs skipped.', { title: 'Send member update', ok: 'Send now', cancel: 'Not yet' }))) return;
|
||||
const r = await api('/api/admin/updates/send', inp); IAP.status('Sending to ' + r.total + ' members in the background.', 'ok'); loadUpdates();
|
||||
@@ -587,10 +659,11 @@
|
||||
const r = await api('/api/admin/promos', { code: $('pcCode').value, credits: $('pcCredits').value, partner: $('pcPartner').value, maxUses: $('pcMax').value, expires: $('pcExpires').value || null, active: true });
|
||||
msg.textContent = 'Saved ' + r.code.code + ': ' + r.code.credits + ' credits.'; msg.style.color = 'var(--mint)';
|
||||
$('pcCode').value = ''; $('pcCredits').value = ''; $('pcPartner').value = ''; loadPromos();
|
||||
} catch (e) { msg.textContent = e.message; msg.style.color = '#ff8a8a'; }
|
||||
} catch (e) { msg.textContent = e.message; msg.style.color = 'var(--bad)'; }
|
||||
});
|
||||
async function loadTraffic() {
|
||||
loadPromos().catch(e => IAP.status(e.message, 'bad'));
|
||||
loadLoginShows().catch(e => IAP.status(e.message, 'bad'));
|
||||
const d = await (await fetch('/api/admin/traffic?days=' + trfDays)).json();
|
||||
if (d.error) throw new Error(d.error);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
@@ -601,10 +674,33 @@
|
||||
const pct = (num, den) => den ? (100 * num / den).toFixed(num && 100 * num / den < 10 ? 1 : 0) + '%' : '<span class="muted">-</span>';
|
||||
$('trfSources').innerHTML = '<tr><th>Source</th><th>Page<br>views</th><th>Join-page<br>views</th><th>Signups</th><th>Visit →<br>signup</th><th>Registered</th><th>Signup →<br>registered</th><th>$20+<br>buyers</th><th>Signup →<br>buyer</th></tr>'
|
||||
+ (d.sources.length ? d.sources.map(s => '<tr><td>' + esc(s.source) + '</td><td>' + n(s.hits) + '</td><td>' + n(s.joinViews) + '</td><td>' + n(s.signups) + '</td><td>' + pct(s.signups, s.hits + s.joinViews) + '</td><td>' + n(s.registered) + '</td><td>' + pct(s.registered, s.signups) + '</td><td>' + n(s.buyers) + '</td><td>' + pct(s.buyers, s.signups) + '</td></tr>').join('') : '<tr><td colspan="9" class="muted">Nothing recorded in this range yet.</td></tr>');
|
||||
// games to members (2026-10-05): card taps that reached InstantAdPay, first packages bought, dollars, per game (all time)
|
||||
if (d.starter) { const st = d.starter, rows = Object.values(st.games);
|
||||
$('stSub').textContent = (st.settings.on ? 'on' : 'off') + ' · welcome bonus ' + st.settings.bonus + ' credits · ' + st.granted + ' granted';
|
||||
$('trfStarter').innerHTML = '<tr><th>Game</th><th>Offer taps</th><th>First packages</th><th>Package $</th><th>Tap → buy</th></tr>' + rows.map(g => '<tr><td>' + esc(g.name) + '</td><td>' + n(g.visits) + '</td><td>' + n(g.buyers) + '</td><td>$' + g.usd.toFixed(2) + '</td><td>' + pct(g.buyers, g.visits) + '</td></tr>').join(''); }
|
||||
$('trfPaths').innerHTML = '<tr><th>Page</th><th>Views</th></tr>' + (d.paths.length ? d.paths.map(p => '<tr><td>' + esc(p.path) + '</td><td>' + n(p.hits) + '</td></tr>').join('') : '<tr><td colspan="2" class="muted">No page views yet.</td></tr>');
|
||||
// BixPay clicks by surface + per member (2026-10-29)
|
||||
if (d.bixpay && $('trfBix')) { const bx = d.bixpay, LBL = { wallet: 'Wallet tab card', overview: 'Overview card', email: 'Payout emails', nudge: 'Game wallet nudges', promo: 'Promo tools (members’ posts and banners)', guide: '/bixpay guide', chat: 'Chatbot', other: 'Other' };
|
||||
$('bixSub').textContent = 'last ' + bx.days + ' days: ' + n(bx.total) + ' clicks · all time ' + n(bx.allTime) + (bx.live ? '' : ' · bixpayLive is OFF');
|
||||
const rows = Object.entries(bx.bySurface).sort((a, b) => b[1] - a[1]);
|
||||
$('trfBix').innerHTML = '<tr><th>Surface</th><th>Clicks</th></tr>' + (rows.length ? rows.map(([s, c]) => '<tr><td>' + esc(LBL[s] || s) + '</td><td>' + n(c) + '</td></tr>').join('') : '<tr><td colspan="2" class="muted">No BixPay clicks in this range yet.</td></tr>');
|
||||
$('trfBixMembers').innerHTML = '<tr><th>Member</th><th>All clicks</th><th>Via promo kit</th><th>Last</th></tr>' + (bx.members.length ? bx.members.map(m => '<tr><td>' + esc(m.name || m.email) + '</td><td>' + n(m.total) + '</td><td>' + n(m.promo) + '</td><td class="small muted">' + (m.last ? ago(m.last) : '') + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">No member clicks yet.</td></tr>'); }
|
||||
$('trfAngles').innerHTML = '<tr><th>Angle</th><th>Join-page<br>views</th><th>Signups</th><th>View →<br>signup</th></tr>' + (d.angles.length ? d.angles.map(a => '<tr><td>' + esc(a.angle) + '</td><td>' + n(a.views) + '</td><td>' + n(a.signups) + '</td><td>' + pct(a.signups, a.views) + '</td></tr>').join('') : '<tr><td colspan="4" class="muted">No angle data yet.</td></tr>');
|
||||
$('trfDaily').innerHTML = '<tr><th>Day</th><th>Page views</th><th>Signups</th></tr>' + (d.daily.length ? d.daily.slice().reverse().map(x => '<tr><td>' + esc(x.day) + '</td><td>' + n(x.hits) + '</td><td>' + n(x.signups) + '</td></tr>').join('') : '<tr><td colspan="3" class="muted">Nothing yet.</td></tr>');
|
||||
}
|
||||
// login-ad showings per Central day (2026-10-18): the dashboard gate vs the games' sign-in kit, member slot vs house ad,
|
||||
// and sign-ins that had no login ad to show. A week of these decides whether the 3-slot cap goes up.
|
||||
async function loadLoginShows() {
|
||||
const d = await (await fetch('/api/admin/login-shows?days=14')).json();
|
||||
if (d.error) throw new Error(d.error);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const n = v => Number(v || 0).toLocaleString(), shown = x => x.member + x.house;
|
||||
const week = d.days.slice(0, 7).reduce((a, x) => { a.dash += shown(x.dashboard); a.games += shown(x.games); return a; }, { dash: 0, games: 0 });
|
||||
$('lsSub').textContent = 'last 7 days: ' + n(week.dash + week.games) + ' shown (' + n(week.dash) + ' dashboard, ' + n(week.games) + ' games) · slots ' + d.slots.used + ' of ' + d.slots.max + ' taken';
|
||||
$('trfLogin').innerHTML = '<tr><th>Day (CT)</th><th>Dashboard<br>shown</th><th>Games<br>shown</th><th>Total<br>shown</th><th>Of which<br>house ad</th><th>Sign-ins with<br>no login ad</th><th>By game</th></tr>'
|
||||
+ d.days.map(x => '<tr><td>' + esc(x.day) + '</td><td>' + n(shown(x.dashboard)) + '</td><td>' + n(shown(x.games)) + '</td><td><b>' + n(shown(x.dashboard) + shown(x.games)) + '</b></td><td>' + n(x.dashboard.house + x.games.house) + '</td><td>' + n(x.dashboard.none + x.games.none) + '</td><td class="small">'
|
||||
+ (Object.keys(x.byGame).length ? Object.entries(x.byGame).map(([g, v]) => esc(g) + ' ' + n(v)).join(', ') : '<span class="muted">-</span>') + '</td></tr>').join('');
|
||||
}
|
||||
// ── blog: coaching articles, public at /blog (Marty, 2026-09-12) ──
|
||||
let blCur = null; // slug being edited, or null for a new one
|
||||
function blCount() {
|
||||
@@ -702,6 +798,7 @@
|
||||
}
|
||||
|
||||
async function loadPnl() {
|
||||
loadOverride().catch(() => {}); // its own request: does not wait for the chain reads below
|
||||
const r = await api('/api/admin/pnl?days=' + pnlDays);
|
||||
const px = r.polUsd || 0;
|
||||
const platUsd = (Number(BigInt(r.platformWei || '0') / 10n ** 14n) / 10000) * px;
|
||||
@@ -734,6 +831,22 @@
|
||||
+ '<tr><td class="muted small">Hunters paid</td><td class="mono">' + Number(t.hunters || 0) + '</td><td class="muted small">today ' + Number(t.today || 0).toFixed(3) + ' POL</td></tr>';
|
||||
}
|
||||
}
|
||||
// every game's payouts, all time, running total (Marty, 2026-10-18). PassiveDrip is a drip
|
||||
// program rather than a game, so it sits under the total instead of inside it.
|
||||
const ga = r.gamesAll, gaEl = $('pnlGames');
|
||||
if (gaEl) {
|
||||
if (!ga || ga.error || !Array.isArray(ga.games) || !ga.games.length) gaEl.innerHTML = '<tr><td colspan="4" class="muted small">' + (ga && ga.scanning ? 'Reading the game wallets from Polygon for the first time. Refresh in a minute.' : 'Game payout figures unavailable' + (ga && ga.error ? ' (' + esc(ga.error) + ')' : '') + '.') + '</td></tr>';
|
||||
else {
|
||||
const wp = w => Number(BigInt(w) / 10n ** 12n) / 1e6, games = ga.games.filter(g => g.slug !== 'passivedrip'), pd = ga.games.find(g => g.slug === 'passivedrip');
|
||||
const row = (name, w, n, pl, cls) => '<tr' + (cls ? ' class="' + cls + '"' : '') + '><td>' + name + '</td><td class="mono">' + wp(w).toFixed(4) + '</td><td class="mono">$' + (wp(w) * px).toFixed(2) + '</td><td class="mono small">' + Number(n).toLocaleString() + ' to ' + Number(pl).toLocaleString() + '</td></tr>';
|
||||
const tw = games.reduce((t, g) => t + BigInt(g.wei), 0n), tn = games.reduce((t, g) => t + g.count, 0);
|
||||
gaEl.innerHTML = '<tr><th>Game</th><th>POL</th><th>USD now</th><th>Payouts to players</th></tr>'
|
||||
+ games.map(g => row(esc(g.name) + (g.error ? ' <span class="chip flat">stale</span>' : ''), g.wei, g.count, g.players)).join('')
|
||||
+ '<tr><td><b>All game payouts</b></td><td class="mono"><b>' + wp(tw).toFixed(4) + '</b></td><td class="mono"><b>$' + (wp(tw) * px).toFixed(2) + '</b></td><td class="mono small">' + tn.toLocaleString() + ' payouts</td></tr>'
|
||||
+ (pd ? row('<span class="muted">PassiveDrip (not a game)</span>', pd.wei, pd.count, pd.players) : '')
|
||||
+ '<tr><td colspan="4" class="muted small">Read ' + (ga.at ? new Date(ga.at).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', minute: '2-digit', month: 'short', day: 'numeric' }) + ' CT' : 'just now') + (ga.scanning ? ', refreshing' : '') + '. Updates every 10 minutes.</td></tr>';
|
||||
}
|
||||
}
|
||||
$('pnlSplit').innerHTML ='<tr><th>Line</th><th>POL</th><th>USD now</th></tr>'
|
||||
+ [['Level 1 (50%)', r.byTier[1]], ['Level 2 (20%)', r.byTier[2]], ['Level 3 (10%)', r.byTier[3]], ['Platform (20% + pass-ups)', r.platformWei]].map(x => '<tr><td>' + x[0] + '</td><td class="mono">' + pol(x[1]) + '</td><td class="mono">' + usdOf(x[1], px) + '</td></tr>').join('');
|
||||
const W = r.wallets || {}, B = r.balances || {};
|
||||
@@ -747,15 +860,16 @@
|
||||
// The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that
|
||||
// makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody
|
||||
// wrote down (Marty, 2026-09-23).
|
||||
const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer' };
|
||||
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter' };
|
||||
const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' };
|
||||
const LD_CAT = { advertising: 'Advertising', games: 'Game marketing', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' };
|
||||
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' };
|
||||
const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 });
|
||||
function renderLedger(r) {
|
||||
const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {};
|
||||
if ($('pnlLedger')) {
|
||||
$('pnlLedger').innerHTML = '<tr><th>Date</th><th>Wallet</th><th>Kind</th><th>POL</th><th>What for</th><th></th></tr>'
|
||||
+ (rows.length ? rows.map(e => '<tr><td>' + e.date + '</td><td>' + (LD_WALLET[e.wallet] || e.wallet) + '</td>'
|
||||
+ '<td>' + (LD_KIND[e.kind] || e.kind) + '</td>'
|
||||
+ '<td>' + (LD_KIND[e.kind] || e.kind) + (e.kind === 'cost' ? ' <span class="muted">(' + (LD_CAT[e.category] || e.category || 'other') + ')</span>' : '') + '</td>'
|
||||
+ '<td' + (e.dir === 'out' ? ' style="color:var(--bad)"' : '') + '>' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount)
|
||||
+ (e.usd ? ' <span class="muted">($' + Number(e.usd).toFixed(2) + ')</span>' : '') + '</td>'
|
||||
+ '<td>' + esc(e.note || '') + '</td>'
|
||||
@@ -782,7 +896,7 @@
|
||||
}
|
||||
}
|
||||
if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => {
|
||||
const body = { dir: $('ldDir').value, kind: $('ldKind').value, wallet: $('ldWallet').value,
|
||||
const body = { dir: $('ldDir').value, kind: $('ldKind').value, category: $('ldCat') ? $('ldCat').value : '', wallet: $('ldWallet').value,
|
||||
amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0,
|
||||
date: $('ldDate').value, note: $('ldNote').value };
|
||||
try {
|
||||
@@ -798,6 +912,29 @@
|
||||
});
|
||||
document.querySelectorAll('#pnlPeriods [data-days]').forEach(b => b.addEventListener('click', () => { pnlDays = Number(b.dataset.days); document.querySelectorAll('#pnlPeriods [data-days]').forEach(x => x.classList.toggle('on', x === b)); loadPnl().catch(e => IAP.status(e.message, 'bad')); }));
|
||||
if ($('pnlFixedSave')) $('pnlFixedSave').addEventListener('click', async () => { try { await api('/api/admin/site', { pnlFixedMonthlyUsd: Number($('pnlFixed').value) || 0 }, 'PATCH'); IAP.status('Saved.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
||||
// Level 4 override (2026-10-23): week status from /api/admin/override; the pay button exists only while the live payer is ready
|
||||
const OV_STATE = { 'not planned': 'not planned', planning: 'planning', planned: 'pending', paying: 'paying', held: 'held', paid: 'paid' };
|
||||
async function loadOverride(week) {
|
||||
if (!$('ovPayer')) return;
|
||||
let r; try { r = await (await fetch('/api/admin/override' + (week ? '?week=' + encodeURIComponent(week) : ''), { cache: 'no-store' })).json(); } catch (e) { $('ovPayer').textContent = 'Could not read the override: ' + e.message; return; }
|
||||
const pz = r.payer || {};
|
||||
$('ovPayer').textContent = 'Mode: ' + (pz.mode || '?') + (pz.ready ? ' · PAYING automatically each Monday after 9 AM CT' : ' · not paying (' + (pz.why || []).join('; ') + ')')
|
||||
+ (pz.address ? ' · payer wallet ' + pz.address + ' holds ' + (pz.balancePol || '?') + ' POL' : '') + ' · weekly cap ' + (pz.capPol || '?') + ' POL · minimum ' + (pz.dustPol || '?') + ' POL'
|
||||
+ (pz.goLive ? ' · purchases from ' + new Date(pz.goLive).toLocaleString('en-US', { timeZone: 'America/Chicago' }) + ' CT' : '') + (pz.lastError ? ' · last error: ' + pz.lastError.msg : '');
|
||||
$('ovPay').hidden = !pz.ready;
|
||||
const sel = $('ovWeek'); if (!sel.options.length) { const now = new Date(); for (let i = 0; i < 10; i++) { const d = new Date(now.getTime() - i * 7 * 86400000); const v = d.toISOString().slice(0, 10); sel.innerHTML += '<option value="' + v + '">week containing ' + v + '</option>'; } sel.selectedIndex = 1; }
|
||||
$('ovWeeks').innerHTML = (r.dueWeeks || []).length ? '<table><tr><th>Week of</th><th>Status</th><th>Total</th></tr>' + r.dueWeeks.map(w => '<tr><td>' + esc(w.week) + '</td><td>' + esc(OV_STATE[w.state] || w.state) + (w.heldWhy ? ' <span class="muted">(' + esc(w.heldWhy) + ')</span>' : '') + '</td><td class="mono">' + esc(w.totalPol || '0') + ' POL</td></tr>').join('') + '</table>' : '';
|
||||
const st = r.status || {}; const t = r.totals || {};
|
||||
$('ovOut').innerHTML = '<p>Week of ' + esc(r.week || '') + ': ' + (r.purchases || 0) + ' purchases, $' + Number(t.salesUsd || 0).toFixed(2) + ' sales. Override due: $' + Number(t.wouldPayUsd || 0).toFixed(2) + ' (' + Number(t.wouldPayPol || 0).toFixed(4) + ' POL) to ' + (r.recipients || []).length + ' members; company keeps $' + Number(t.companyKeepsUsd || 0).toFixed(2) + '. Payout status: <b>' + esc(OV_STATE[st.state] || st.state || '?') + '</b>' + (st.heldWhy ? ' (' + esc(st.heldWhy) + ')' : '') + '.</p>'
|
||||
+ ((st.rows || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Status</th><th></th></tr>' + st.rows.map(x => '<tr><td>#' + x.memberId + '</td><td class="mono">' + esc(x.pol) + '</td><td class="mono">$' + Number(x.usd || 0).toFixed(2) + '</td><td>' + esc(x.state) + (x.note ? ' <span class="muted">' + esc(x.note) + '</span>' : '') + '</td><td>' + (x.tx ? '<a target="_blank" rel="noopener" href="' + esc(x.tx) + '">tx</a>' : '') + '</td></tr>').join('') + '</table>'
|
||||
: (r.recipients || []).length ? '<table><tr><th>Member</th><th>POL</th><th>USD</th><th>Buys</th></tr>' + r.recipients.map(x => '<tr><td>#' + x.recipientId + '</td><td class="mono">' + Number(x.pol).toFixed(4) + '</td><td class="mono">$' + Number(x.usd).toFixed(2) + '</td><td>' + x.purchases + '</td></tr>').join('') + '</table>' : '');
|
||||
}
|
||||
if ($('ovShow')) $('ovShow').addEventListener('click', () => loadOverride($('ovWeek').value));
|
||||
if ($('ovPay')) $('ovPay').addEventListener('click', async () => {
|
||||
const wk = $('ovWeek').value;
|
||||
if (!await IAP.confirmBox('This sends real POL from the payer wallet for every closed week up to the week containing ' + wk + ' that is not paid yet. Each member is paid once; anything already paid is skipped.', { title: 'Pay the override now?', ok: 'Pay now' })) return;
|
||||
try { const r = await api('/api/admin/override/pay', { week: wk }); IAP.status('Override: ' + (r.results || []).map(x => x.week + ' ' + (x.state || x.held || (x.why || []).join(', '))).join(' · '), 'ok'); loadOverride(wk); } catch (e) { IAP.status(e.message, 'bad'); }
|
||||
});
|
||||
if ($('burnerRun')) $('burnerRun').addEventListener('click', async () => { try { const r = await api('/api/admin/burner/run', {}); IAP.status('Burner ran: ' + (r.burned || 0) + ' burned.', 'ok'); loadPnl(); } catch (e) { IAP.status(e.message, 'bad'); } });
|
||||
async function loadAudit() {
|
||||
if (!$('audTable')) return;
|
||||
@@ -810,6 +947,107 @@
|
||||
} catch (e) { $('audSub').textContent = e.message; }
|
||||
}
|
||||
if ($('audRun')) $('audRun').addEventListener('click', busy($('audRun'), loadAudit));
|
||||
// ── help desk (2026-10-16): one shared desk (IAP now, LinkSpin later); newest activity first ──
|
||||
const SP_STATUS = { open: 'Open', waiting_on_member: 'Waiting on member', closed: 'Closed' };
|
||||
const SP_AUTHOR = { member: 'Member', admin: 'You', system: 'System' };
|
||||
const ctWhen = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
|
||||
const spLink = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '<a href="$1" target="_blank" rel="noopener nofollow">$1</a>');
|
||||
let spFilter = { status: 'open', platform: '', category: '', q: '' }, spTemplates = [], spCats = [];
|
||||
async function supportBadge() {
|
||||
try { const c = await api('/api/admin/support/counts'); $('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : c.open; return c; } catch (e) { return null; }
|
||||
}
|
||||
async function loadSupport(q) {
|
||||
const ref = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(q || '') || [])[1];
|
||||
if (ref) return openTicket(ref);
|
||||
$('spView').hidden = true; $('spList').hidden = false;
|
||||
const qs = new URLSearchParams(Object.entries(spFilter).filter(([, v]) => v)).toString();
|
||||
const [r, tp] = await Promise.all([api('/api/admin/support' + (qs ? '?' + qs : '')), spTemplates.length ? Promise.resolve({ templates: spTemplates }) : api('/api/admin/support/templates')]);
|
||||
spTemplates = tp.templates || []; spCats = r.categories || spCats;
|
||||
const c = r.counts || {};
|
||||
$('supBadge').hidden = !c.open; $('supBadge').textContent = c.open > 99 ? '99+' : (c.open || '');
|
||||
$('spSub').textContent = (c.open || 0) + ' open · ' + (c.waiting_on_member || 0) + ' waiting on member · ' + (c.unread || 0) + ' unread';
|
||||
const chip = (v, label, n) => '<button type="button" class="chip-t' + (spFilter.status === v ? ' on' : '') + '" data-spst="' + v + '">' + label + (n != null ? ' (' + n + ')' : '') + '</button>';
|
||||
$('spStatus').innerHTML = chip('open', 'Open', c.open || 0) + chip('waiting_on_member', 'Waiting on member', c.waiting_on_member || 0) + chip('closed', 'Closed', c.closed || 0) + chip('', 'All');
|
||||
if (!$('spCategory').options.length) $('spCategory').innerHTML = '<option value="">All categories</option>' + spCats.map(x => '<option>' + esc(x) + '</option>').join('');
|
||||
$('spTable').innerHTML = '<tr><th>Ticket</th><th>Subject</th><th>From</th><th>Category</th><th>Status</th><th>Last activity</th></tr>'
|
||||
+ (r.tickets.length ? r.tickets.map(t => '<tr data-spref="' + esc(t.ref) + '" style="cursor:pointer"><td class="mono small">' + (t.adminUnread ? '<b style="color:var(--amber,#ffb238)">●</b> ' : '') + esc(t.ref)
|
||||
+ (t.platform !== 'iap' ? ' <span class="small muted">' + esc(t.platform) + '</span>' : '') + (t.priority === 'high' ? ' <b style="color:var(--bad)">high</b>' : '') + '</td>'
|
||||
+ '<td>' + (t.adminUnread ? '<b>' + esc(t.subject) + '</b>' : esc(t.subject)) + '<div class="small muted">' + esc(t.source) + '</div></td>'
|
||||
+ '<td class="small">' + esc(t.name || '') + '<div class="muted">' + esc(t.email) + (t.username ? ' · @' + esc(t.username) : '') + '</div></td>'
|
||||
+ '<td class="small">' + esc(t.category) + '</td><td class="small">' + esc(SP_STATUS[t.status] || t.status) + '</td><td class="small muted" style="white-space:nowrap">' + esc(ctWhen(t.updated)) + '</td></tr>').join('')
|
||||
: '<tr><td colspan="6" class="muted">No tickets here.</td></tr>');
|
||||
drawTemplates();
|
||||
}
|
||||
$('spStatus').addEventListener('click', e => { const b = e.target.closest('[data-spst]'); if (!b) return; spFilter.status = b.dataset.spst; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
||||
$('spPlatform').addEventListener('change', () => { spFilter.platform = $('spPlatform').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
||||
$('spCategory').addEventListener('change', () => { spFilter.category = $('spCategory').value; loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
||||
let spQT = null; $('spQ').addEventListener('input', () => { clearTimeout(spQT); spQT = setTimeout(() => { spFilter.q = $('spQ').value.trim(); loadSupport('').catch(err => IAP.status(err.message, 'bad')); }, 350); });
|
||||
$('spTable').addEventListener('click', e => { const tr = e.target.closest('[data-spref]'); if (tr) { history.replaceState(null, '', '#support?t=' + tr.dataset.spref); openTicket(tr.dataset.spref).catch(err => IAP.status(err.message, 'bad')); } });
|
||||
async function openTicket(ref) {
|
||||
const v = await api('/api/admin/support/' + encodeURIComponent(ref));
|
||||
if (!spTemplates.length) { try { spTemplates = (await api('/api/admin/support/templates')).templates || []; } catch (e) {} }
|
||||
if (!spCats.length) spCats = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
|
||||
drawTicket(v); supportBadge();
|
||||
}
|
||||
function drawTicket(v) {
|
||||
const t = v.ticket, rq = v.requester || {};
|
||||
$('spList').hidden = true; $('spView').hidden = false;
|
||||
const sel = (id, opts, cur) => '<select id="' + id + '" class="small">' + opts.map(o => '<option value="' + esc(o[0]) + '"' + (o[0] === cur ? ' selected' : '') + '>' + esc(o[1]) + '</option>').join('') + '</select>';
|
||||
const stOpts = Object.entries(SP_STATUS);
|
||||
$('spView').innerHTML = '<p style="margin:0 0 10px"><a href="#support" id="spBack">‹ All tickets</a></p>'
|
||||
+ '<div class="card"><div class="card-head" style="flex-wrap:wrap;gap:8px"><h3 style="margin:0">' + esc(t.subject) + '</h3><span class="sub mono">' + esc(t.ref) + ' · ' + esc(t.platform) + ' · via ' + esc(t.source) + ' · opened ' + esc(ctWhen(t.created)) + '</span></div>'
|
||||
+ '<div style="display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin:6px 0 0"><label class="small muted">Status ' + sel('spSt', stOpts, t.status) + '</label>'
|
||||
+ '<label class="small muted">Priority ' + sel('spPr', [['normal', 'Normal'], ['high', 'High']], t.priority) + '</label>'
|
||||
+ '<label class="small muted">Category ' + sel('spCat', spCats.map(c => [c, c]), t.category) + '</label></div></div>'
|
||||
+ '<div class="card"><div class="card-head"><h3>Requester</h3><span class="sub">' + (rq.member ? 'member account' : 'no account with this email') + '</span></div>'
|
||||
+ kv([['Name', esc(t.name || '(not given)')], ['Email', esc(t.email)]].concat(rq.member ? [
|
||||
['Account', (rq.username ? '@' + esc(rq.username) : '(no username yet)') + (rq.memberId ? ' · member #' + rq.memberId : ' · free member') + ' · <a href="#" id="spMember" data-email="' + esc(rq.email) + '">open member card</a>'],
|
||||
['Wallet linked', rq.wallet ? 'yes' : 'no'], ['Joined', esc(ctWhen(rq.created))], ['Last seen', esc(ctWhen(rq.lastSeen) || 'never')]] : []).concat([['Private link', '<span class="mono small" style="word-break:break-all">' + esc(v.link) + '</span>']]))
|
||||
+ '</div>'
|
||||
+ '<div class="card"><div class="card-head"><h3>Thread</h3><span class="sub">' + v.messages.length + ' message' + (v.messages.length === 1 ? '' : 's') + '</span></div>'
|
||||
+ v.messages.map(m => '<div style="border:1px solid ' + (m.internal ? 'var(--gold-line)' : m.author === 'admin' ? 'var(--mint-line)' : 'var(--line)') + ';background:' + (m.internal ? 'var(--gold-soft)' : m.author === 'admin' ? 'var(--mint-faint)' : 'transparent') + ';border-radius:12px;padding:10px 14px;margin:8px 0">'
|
||||
+ '<div class="small muted" style="display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap"><b>' + esc(SP_AUTHOR[m.author] || m.author) + (m.internal ? ' · internal note' : '') + (m.via && m.via !== 'web' ? ' · via ' + esc(m.via) : '') + '</b><span>' + esc(ctWhen(m.created)) + '</span></div>'
|
||||
+ '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:6px">' + spLink(m.body) + '</div>'
|
||||
+ (m.author === 'admin' && !m.internal && t.platform !== 'linkspin' && window.IAPKB ? '<p style="margin:8px 0 0"><button type="button" class="btn small sec" data-kbsave="' + m.id + '">Save as KB entry</button></p>' : '')
|
||||
+ (m.bodyEn ? '<div style="white-space:pre-wrap;word-wrap:break-word;margin-top:8px;padding:8px 10px;border-left:3px solid var(--mint);background:var(--mint-soft);border-radius:6px"><span class="small muted">🌐 ' + esc(m.langName || m.lang) + ', in English (your reply goes back in ' + esc(m.langName || m.lang) + ' with your English underneath)</span>\n' + spLink(m.bodyEn) + '</div>' : '')
|
||||
+ ((m.attachments || []).length ? '<div style="display:flex;gap:8px;margin-top:8px;flex-wrap:wrap">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment" style="max-width:180px;max-height:140px;border-radius:8px;border:1px solid var(--line)"></a>').join('') + '</div>' : '') + '</div>').join('')
|
||||
+ '</div>'
|
||||
+ '<div class="card"><div class="card-head"><h3>Reply</h3><span class="sub">emailed to the requester' + (rq.member ? ' and put in their Help tab and inbox' : '') + '</span></div>'
|
||||
+ '<p style="display:flex;gap:8px;flex-wrap:wrap;align-items:center;margin:0 0 8px"><select id="spTpl" class="small"><option value="">Insert a saved reply…</option>' + spTemplates.map((x, i) => '<option value="' + i + '">' + esc(x.name) + '</option>').join('') + '</select></p>'
|
||||
+ '<textarea id="spBody" rows="7" style="width:100%" maxlength="5000" placeholder="Write your reply"></textarea>'
|
||||
+ '<p style="display:flex;gap:14px;flex-wrap:wrap;align-items:center;margin:10px 0 0"><label class="small"><input type="checkbox" id="spInternal"> Internal note (only you see it, nothing is sent)</label>'
|
||||
+ '<label class="small muted">Then set status ' + sel('spAfter', stOpts, 'waiting_on_member') + '</label>'
|
||||
+ '<button type="button" class="btn small" id="spSend">Send reply</button></p></div>';
|
||||
$('spView').querySelectorAll('[data-kbsave]').forEach(b => b.addEventListener('click', async () => { // a good reply becomes a knowledge-base draft (2026-10-20)
|
||||
const i = v.messages.findIndex(x => String(x.id) === b.dataset.kbsave); if (i < 0) return;
|
||||
const asked = v.messages.slice(0, i).reverse().find(x => x.author === 'member' && !x.internal);
|
||||
const draft = window.IAPKB.fromTicket(t, asked ? (asked.bodyEn || asked.body) : t.subject, v.messages[i].body);
|
||||
await setPane('kb'); window.IAPKB.compose(draft);
|
||||
}));
|
||||
$('spBack').addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#support'); loadSupport('').catch(err => IAP.status(err.message, 'bad')); });
|
||||
const patch = async f => { try { drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref), f, 'PATCH')); supportBadge(); IAP.status('Saved.', 'ok'); } catch (e) { IAP.status(e.message, 'bad'); } };
|
||||
$('spSt').addEventListener('change', () => patch({ status: $('spSt').value }));
|
||||
$('spPr').addEventListener('change', () => patch({ priority: $('spPr').value }));
|
||||
$('spCat').addEventListener('change', () => patch({ category: $('spCat').value }));
|
||||
if ($('spMember')) $('spMember').addEventListener('click', async e => { e.preventDefault(); await setPane('members'); openMember(e.target.dataset.email); });
|
||||
$('spTpl').addEventListener('change', () => { const x = spTemplates[Number($('spTpl').value)]; if (x) { const b = $('spBody'); b.value = (b.value ? b.value.replace(/\s+$/, '') + '\n\n' : '') + x.body; b.focus(); } $('spTpl').value = ''; });
|
||||
$('spInternal').addEventListener('change', () => { $('spAfter').value = $('spInternal').checked ? t.status : 'waiting_on_member'; $('spSend').textContent = $('spInternal').checked ? 'Save note' : 'Send reply'; });
|
||||
$('spSend').addEventListener('click', busy($('spSend'), async () => {
|
||||
const internal = $('spInternal').checked;
|
||||
if (!internal && !(await IAP.confirmBox('Send this reply to ' + t.email + '?', { ok: 'Send', cancel: 'Not yet' }))) return;
|
||||
drawTicket(await api('/api/admin/support/' + encodeURIComponent(t.ref) + '/reply', { body: $('spBody').value, internal, status: $('spAfter').value }));
|
||||
supportBadge(); IAP.status(internal ? 'Note saved.' : 'Reply sent.', 'ok');
|
||||
}));
|
||||
}
|
||||
function drawTemplates() {
|
||||
$('spTpls').innerHTML = spTemplates.map((x, i) => '<div class="sp-tpl" style="border:1px solid var(--line);border-radius:10px;padding:10px;margin:0 0 8px"><div style="display:flex;gap:8px"><input class="small" data-tn="' + i + '" value="' + esc(x.name) + '" placeholder="name" style="flex:1"><button type="button" class="btn small sec" data-tdel="' + i + '">Remove</button></div>'
|
||||
+ '<textarea class="small" data-tb="' + i + '" rows="3" style="width:100%;margin-top:6px">' + esc(x.body) + '</textarea></div>').join('') || '<p class="small muted">No saved replies. Add one below.</p>';
|
||||
}
|
||||
const readTemplates = () => [...document.querySelectorAll('#spTpls [data-tn]')].map(el => ({ name: el.value, body: document.querySelector('#spTpls [data-tb="' + el.dataset.tn + '"]').value }));
|
||||
$('spTpls').addEventListener('click', e => { const b = e.target.closest('[data-tdel]'); if (!b) return; spTemplates = readTemplates(); spTemplates.splice(Number(b.dataset.tdel), 1); drawTemplates(); });
|
||||
$('spTplAdd').addEventListener('click', () => { spTemplates = readTemplates(); spTemplates.push({ name: '', body: '' }); drawTemplates(); const n = document.querySelector('#spTpls [data-tn="' + (spTemplates.length - 1) + '"]'); if (n) n.focus(); });
|
||||
$('spTplSave').addEventListener('click', busy($('spTplSave'), async () => { const r = await api('/api/admin/support/templates', { templates: readTemplates() }, 'PUT'); spTemplates = r.templates || []; drawTemplates(); IAP.status('Saved replies saved.', 'ok'); }));
|
||||
|
||||
async function loadReports() {
|
||||
loadAudit();
|
||||
const [r, b] = await Promise.all([api('/api/admin/reports'), api('/api/admin/burns')]);
|
||||
@@ -907,6 +1145,8 @@
|
||||
loginCreditsPerDay: ['Login ad: credits per day', 'flat daily charge while active'],
|
||||
loginDwellSeconds: ['Login ad: seconds shown', 'full-screen interstitial after sign-in'],
|
||||
burnBatchMin: ['On-chain burn batch (credits)', 'accrued spend is burned once it reaches this'],
|
||||
synRateDivisor: ['Network rate divisor (N)', 'Network Ad Space banner views and PassiveDrip visits cost 1/N of the on-site rate; 1 = same rate as on-site; whole numbers'],
|
||||
synRateDivisorText: ['Network rate divisor for TEXT ads (N)', 'Network Ad Space text-ad views cost 1/N of the on-site text rate (10 = 1 credit per 100 network views); whole numbers'],
|
||||
welcomeCredits: ['Welcome credits', 'granted after the welcome tour'],
|
||||
dailyViewTarget: ['Daily view set (ads)', 'ads a member views for the daily claim'],
|
||||
dailyClaimCredits: ['Daily claim (credits)', 'paid when the set is complete'],
|
||||
@@ -916,6 +1156,8 @@
|
||||
videoWatchCapPerDay: ['Video: rewarded watches per day', ''],
|
||||
featuredPerDay: ['Featured link: credits per day', ''], featuredSlotsPerDay: ['Featured link: slots per day', ''], featuredWindowDays: ['Featured link: booking window (days)', ''],
|
||||
featuredDurations: ['Featured link: durations offered (days)', 'comma-separated'],
|
||||
doorPackCost: ['Spooky Doors: door pack, credits per door', 'placement "Behind Spooky Doors"'], goldenDoorCost: ['Spooky Doors: Golden Door, credits per door', 'placement "Golden Spooky Door"'],
|
||||
goldenBonusCandy: ['Spooky Doors: Golden Door bonus candy', 'sent to the game as bonus'], sdSeasonEnd: ['Spooky Doors: season end (Central day, exclusive)', 'from this day door packs run as normal visits (YYYY-MM-DD)'],
|
||||
visitCostPerVisit: ['Verified visit: credits per visit', ''], visitMinPack: ['Verified visit: smallest pack', ''], visitReward: ['Verified visit: viewer reward (credits)', ''], visitDwellSeconds: ['Verified visit: seconds on site', ''], visitCapPerDay: ['Verified visit: rewarded visits per day', ''],
|
||||
videoTiers: ['Video ad tiers', 'watch length → advertiser cost → viewer reward'],
|
||||
milestoneBonus: ['Milestone bonuses (credits)', 'one-time, when a member reaches each step']
|
||||
@@ -929,10 +1171,10 @@
|
||||
else if (typeof v === 'boolean') html.push('<div class="rf"><label>' + esc(label) + '</label><label class="small"><input type="checkbox" data-rk="' + esc(k) + '"' + (v ? ' checked' : '') + ' style="width:auto"> on</label></div>');
|
||||
else if (Array.isArray(v) && v.every(x => typeof x === 'number')) html.push('<div class="rf"><label>' + esc(label) + '</label><input data-rk="' + esc(k) + '" data-kind="numlist" value="' + esc(v.join(', ')) + '">' + (hint ? '<span class="hint">' + esc(hint) + '</span>' : '') + '</div>');
|
||||
else if (Array.isArray(v) && v.every(x => x && typeof x === 'object')) {
|
||||
const cols = [...new Set(v.flatMap(x => Object.keys(x)))];
|
||||
const cols = [...new Set(v.flatMap(x => Object.keys(x)))]; const txt = new Set(cols.filter(c => v.some(x => typeof x[c] === 'string'))); // text columns (doorHouseAds) stay text
|
||||
html.push('<div class="rf wide"><label>' + esc(label) + '</label>' + (hint ? '<span class="hint">' + esc(hint) + '</span>' : '')
|
||||
+ '<table class="tiers" data-rk="' + esc(k) + '" data-kind="table"><tr>' + cols.map(c => '<th>' + esc(c) + '</th>').join('') + '</tr>'
|
||||
+ v.map((row, i) => '<tr>' + cols.map(c => '<td><input type="number" step="any" data-col="' + esc(c) + '" value="' + esc(row[c] == null ? '' : row[c]) + '"></td>').join('') + '</tr>').join('') + '</table></div>');
|
||||
+ v.map((row, i) => '<tr>' + cols.map(c => '<td><input ' + (txt.has(c) ? 'type="text" data-str="1"' : 'type="number" step="any"') + ' data-col="' + esc(c) + '" value="' + esc(row[c] == null ? '' : row[c]) + '"></td>').join('') + '</tr>').join('') + '</table></div>');
|
||||
} else if (v && typeof v === 'object') {
|
||||
html.push('<div class="rf wide"><label>' + esc(label) + '</label>' + (hint ? '<span class="hint">' + esc(hint) + '</span>' : '') + '<div class="sub-grid" data-rk="' + esc(k) + '" data-kind="object">'
|
||||
+ Object.entries(v).map(([sk, sv]) => '<label>' + esc(humanize(sk)) + '<input type="number" step="any" data-sub="' + esc(sk) + '" value="' + esc(sv) + '"></label>').join('') + '</div></div>');
|
||||
@@ -945,7 +1187,7 @@
|
||||
document.querySelectorAll('#ratesForm [data-rk]').forEach(el => {
|
||||
const k = el.dataset.rk, kind = el.dataset.kind;
|
||||
if (kind === 'numlist') out[k] = el.value.split(/[\s,]+/).filter(Boolean).map(Number).filter(n => !isNaN(n));
|
||||
else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = Number(i.value); }); return o; });
|
||||
else if (kind === 'table') out[k] = [...el.querySelectorAll('tr')].slice(1).map(tr => { const o = {}; tr.querySelectorAll('input[data-col]').forEach(i => { o[i.dataset.col] = i.dataset.str ? i.value.trim() : Number(i.value); }); return o; });
|
||||
else if (kind === 'object') { const o = {}; el.querySelectorAll('input[data-sub]').forEach(i => { o[i.dataset.sub] = Number(i.value); }); out[k] = o; }
|
||||
else if (el.type === 'checkbox') out[k] = !!el.checked;
|
||||
else if (el.type === 'number') out[k] = Number(el.value);
|
||||
@@ -994,6 +1236,138 @@
|
||||
catch (e) { $('siteErr').textContent = e.message; $('siteErr').hidden = false; }
|
||||
}));
|
||||
|
||||
// ---- Game Pass (2026-10-16): passes sold, active, POL out per pass week, cap hits, deferred queue, tournament ----
|
||||
async function loadGamePass() {
|
||||
const r = await api('/api/admin/gamepass/stats');
|
||||
const pol = n => Number(n || 0).toFixed(2); const usd = n => '$' + Number(n || 0).toFixed(2);
|
||||
const tile = (v, lb, cls, sub) => '<div class="statx' + (cls ? ' ' + cls : '') + '"><div><div class="nv">' + v + '</div><div class="lb">' + lb + '</div>' + (sub ? '<span class="chip flat">' + sub + '</span>' : '') + '</div></div>';
|
||||
const P = r.passes || {}, W = (r.pol && r.pol.week) || {}, H = (r.capHits && r.capHits.week) || { free: {}, pass: {} }, Q = r.deferredQueue || {}, T = r.tournament || {}, S = r.settings || {};
|
||||
$('gpStats').innerHTML = tile(r.enabled ? 'ON' : 'OFF', 'Game Pass', r.enabled ? 'c-cyan' : '', S.enforced ? 'caps enforced' : S.capsStart ? 'caps from ' + S.capsStart : 'caps recorded only')
|
||||
+ tile(P.soldWeek || 0, 'Passes sold this week', 'c-violet', usd(P.usdWeek) + ' · ' + (P.soldTotal || 0) + ' all time')
|
||||
+ tile(P.active || 0, 'Active passes', 'c-cyan', (P.waitingOrders || 0) + ' waiting for a package')
|
||||
+ tile(pol(W.pass), 'POL to pass holders this week', 'c-amber', (P.soldWeek ? pol(W.perPass) + ' per pass sold' : 'no passes sold yet'))
|
||||
+ tile(pol(W.free), 'POL to free players this week', '', (W.players || 0) + ' players · ' + (W.grants || 0) + ' grants')
|
||||
+ tile((H.free.daily || 0) + (H.free.total || 0), 'Free cap hits this week', 'c-amber', (H.free.daily || 0) + ' daily · ' + (H.free.total || 0) + ' total')
|
||||
+ tile((H.pass.daily || 0) + (H.pass.total || 0), 'Pass cap hits this week', '', (H.pass.daily || 0) + ' daily · ' + (H.pass.total || 0) + ' total')
|
||||
+ tile(Q.entries || 0, 'Deferred queue', 'c-violet', pol(Q.pol) + ' POL · ' + (Q.members || 0) + ' members');
|
||||
$('gpWeekSub').textContent = r.week ? r.week.label + ' · today ' + r.week.day : '';
|
||||
const would = (r.capHits && r.capHits.would) || {};
|
||||
$('gpWeek').innerHTML = '<table class="adm-table">'
|
||||
+ '<tr><td>Carried forward (deferred progress paid on a later day)</td><td class="num">' + pol(W.carried) + ' POL</td></tr>'
|
||||
+ '<tr><td>Dropped (daily play over the daily cap)</td><td class="num">' + pol(W.dropped) + ' POL</td></tr>'
|
||||
+ '<tr><td>Deferred out (progress over the total cap, pays later)</td><td class="num">' + pol(W.deferredOut) + ' POL</td></tr>'
|
||||
+ (S.enforced ? '' : '<tr><td colspan="2" class="muted">Before capsStartDate, what the caps WOULD have done: ' + pol(would.dropped) + ' POL dropped, ' + pol(would.deferred) + ' POL deferred, ' + ((would.hitsDaily || 0) + (would.hitsTotal || 0)) + ' cap hits.</td></tr>')
|
||||
+ '<tr><td>Caps: free ' + S.free.daily + ' / ' + S.free.total + ' · pass ' + S.pass.daily + ' / ' + S.pass.total + ' POL (daily play / everything, per day)</td><td class="num">' + S.price + ' credits · ' + S.days + ' days</td></tr>'
|
||||
+ '</table>'
|
||||
+ (Q.byGame && Object.keys(Q.byGame).length ? '<p class="muted" style="margin:8px 0 0">By game: ' + Object.entries(Q.byGame).filter(([k]) => !k.startsWith('plays:')).map(([k, v]) => esc(k) + ' ' + pol(v) + ' POL queued').concat(Object.entries(Q.byGame).filter(([k]) => k.startsWith('plays:')).map(([k, v]) => esc(k.slice(6)) + ' ' + v + ' plays')).join(' · ') + '</p>' : '');
|
||||
// per tier (2026-10-18): active counts each account once, at its highest tier; Central week / month
|
||||
const TS = r.tiers || {}, TC = S.tiers || {};
|
||||
$('gpTiersSub').textContent = 'Tiers above weekly, sale: ' + (r.tierSales ? 'ON' : 'OFF (admin preview only)') + ' · ' + (r.week ? r.week.label : '') + ' · month ' + (r.month ? r.month.label : '') + ' · tournament pool ' + (S.tournamentTierSales ? 'includes' : 'excludes') + ' tier sales';
|
||||
$('gpTiers').innerHTML = '<table class="adm-table"><tr><th>Tier</th><th>Price</th><th class="num">Active</th><th class="num">Sold week</th><th class="num">Sold month</th><th class="num">All time</th><th class="num">Renewals 30d</th><th class="num">Ending in 7 days</th><th class="num">Comped</th><th class="num">Waiting</th></tr>'
|
||||
+ (Object.keys(TS).length ? Object.keys(TS) : ['weekly', 'explorer', 'champion', 'sovereign', 'legend']).map(k => { const x = TS[k] || {}, c = TC[k] || {}; return '<tr><td style="white-space:nowrap">' + esc(x.name || k) + (c.sale ? '' : '<br><span class="chip flat">not on sale</span>') + '</td><td style="white-space:nowrap">' + (c.price || 0) + ' cr<br>' + (c.days || 0) + ' d</td><td class="num">' + (x.active || 0) + '</td><td class="num">' + (x.soldWeek || 0) + ' · ' + usd(x.usdWeek) + '</td><td class="num">' + (x.soldMonth || 0) + ' · ' + usd(x.usdMonth) + '</td><td class="num">' + (x.soldTotal || 0) + ' · ' + usd(x.usdTotal) + '</td><td class="num">' + (x.renewals30d || 0) + '</td><td class="num">' + (x.expiring7d || 0) + '</td><td class="num">' + (x.comped || 0) + '</td><td class="num">' + (x.waitingOrders || 0) + '</td></tr>'; }).join('')
|
||||
+ '</table><p class="muted" style="margin:8px 0 0">Every tier gets the same pass caps (no extra POL). Each higher tier includes everything below it and adds Shards of Valor content (Legend is yearly).</p>';
|
||||
// pass sales by how they were paid (2026-10-22: every new pass is a fresh package purchase; the old credit-paid rows stay, labelled)
|
||||
const PM = P.pay || {}, SL = r.sales || [];
|
||||
$('gpSalesSub').textContent = (PM.package ? PM.package.n : 0) + ' paid by a new package (' + usd(PM.package && PM.package.usd) + ' pass value, packages ' + usd(PM.package && PM.package.packageUsd) + ')'
|
||||
+ ' · ' + (PM.credit ? PM.credit.n : 0) + ' credit-paid (old rule, ' + usd(PM.credit && PM.credit.usd) + ')' + ' · ' + (PM.packageOld ? PM.packageOld.n : 0) + ' package under the old rule (' + usd(PM.packageOld && PM.packageOld.usd) + ')';
|
||||
const txLink = h => h ? '<a href="/tx/' + esc(h) + '" target="_blank" rel="noopener">' + esc(String(h).slice(0, 10)) + '…</a>' : '';
|
||||
$('gpSales').innerHTML = !SL.length ? '<p class="muted">No pass sold yet.</p>' : '<table class="adm-table"><tr><th>When</th><th>Member</th><th>Pass</th><th>Paid by</th><th class="num">Pass</th><th class="num">Package</th><th>Package tx</th></tr>'
|
||||
+ SL.map(x => '<tr><td style="white-space:nowrap">' + when(x.ts) + '</td><td>' + esc(x.email) + '</td><td>' + esc(x.name || x.tier) + '</td><td>' + esc(x.label) + (x.credits ? ' · ' + x.credits + ' cr' : '') + '</td><td class="num">' + usd(x.usd) + '</td><td class="num">' + (x.packageUsd ? usd(x.packageUsd) : '') + '</td><td>' + txLink(x.tx) + '</td></tr>').join('')
|
||||
+ '</table>';
|
||||
await loadGpTest();
|
||||
$('gpTourSub').textContent = (T.lastRun ? 'last settled ' + when(T.lastRun) : 'never run') + ' · next Monday 9 AM Central (' + when(T.next) + ') · ' + (T.pending || 0) + ' prize' + (T.pending === 1 ? '' : 's') + ' unpaid';
|
||||
const L = T.last;
|
||||
$('gpTour').innerHTML = !L ? '<p class="muted">No week settled yet. The job runs hourly and settles the closed week once Monday 9 AM Central has passed; ' + S.pct + '% of that week\u2019s pass sales becomes the POL prize pool (50 / 30 / 20).</p>'
|
||||
: '<p><b>' + esc(L.label) + '</b>: ' + (L.sales || 0) + ' pass' + (L.sales === 1 ? '' : 'es') + ' sold (' + usd(L.salesUsd) + '), pool ' + pol(L.poolPol) + ' POL at $' + Number(L.polUsd || 0).toFixed(4) + ' per POL, ' + (L.holders || 0) + ' holders, ' + (L.ranked || 0) + ' with plays' + (L.posted ? ' · posted to Telegram' : '') + '</p>'
|
||||
+ (L.winners && L.winners.length ? '<table class="adm-table">' + L.winners.map(w => '<tr><td>#' + w.place + ' ' + esc(w.username ? '@' + w.username : w.email) + '</td><td>' + w.score + ' plays</td><td class="num">' + pol(w.pol) + ' POL</td><td>' + esc(w.status) + (w.tx ? ' · ' + esc(String(w.tx).slice(0, 12)) : '') + '</td></tr>').join('') + '</table>' : '<p class="muted">No pass holder reported any plays that week.</p>')
|
||||
+ ((T.history || []).length > 1 ? '<p class="muted" style="margin:8px 0 0">Earlier: ' + T.history.slice(1).map(h => esc(h.label) + ' (' + (h.sales || 0) + ' sold, ' + pol(h.poolPol) + ' POL)').join(' · ') + '</p>' : '');
|
||||
}
|
||||
// Tier test and preview (2026-10-25, Marty): the member Games card shows the admin exactly what a member sees, so every tier test lives
|
||||
// here. Every action touches ONLY the signed-in admin's own account; a test buy opens the same waiting order a member gets (a fresh
|
||||
// package on /my fulfils it, sponsors paid as usual), a test comp starts the tier at once with no sale recorded.
|
||||
// Shards of Valor bonus heroes (2026-11-05, Marty approved): sold ONE TIME. The same test path as the tiers, on the admin's own account:
|
||||
// a test buy opens the real waiting order (a fresh $20 / $50 package on /my fulfils it), Give grants it at once as comped, Remove takes it back.
|
||||
function heroTestHtml(H) {
|
||||
if (!H || !H.items) return '';
|
||||
const row = (key, name, sub, usd, pkg, owned, waiting, free) => '<div class="gpt-tier' + (owned ? ' on' : '') + '"><h4>' + esc(name) + '</h4><p class="small muted" style="margin:0 0 4px">' + esc(sub) + '</p>'
|
||||
+ '<p class="gpt-price">' + (free ? 'Free for everyone' : '$' + usd + ' <span class="small muted">one time, the $' + pkg + ' package</span>') + '</p>'
|
||||
+ '<p class="small" style="margin:4px 0">' + (owned ? '<b>Your account: owned</b>' : waiting ? '<b>Your account: test order waiting for a $' + pkg + ' package</b>' : 'Your account: not owned') + '</p><div class="gpt-acts">'
|
||||
+ (free || owned ? '' : waiting ? '<a class="btn small" href="/my?from=heroes#buy" target="_blank" rel="noopener">Buy the $' + pkg + ' package on /my</a><button class="btn small sec" type="button" data-ht-cancel="' + key + '">Cancel test order</button>' : '<button class="btn small" type="button" data-ht-buy="' + key + '">Test buy (real order, $' + pkg + ' package)</button>')
|
||||
+ (owned || free ? '' : '<button class="btn small sec" type="button" data-ht-comp="' + key + '">Give my account ' + esc(name.split(' ')[0]) + ' now (test)</button>')
|
||||
+ (owned && !free && key !== 'bundle' ? '<button class="btn small sec" type="button" data-ht-revoke="' + key + '">Remove from my account</button>' : '') + '</div></div>';
|
||||
const B = H.bundle;
|
||||
return '<h3 style="margin:16px 0 6px">Shards of Valor bonus heroes <span class="chip flat">' + (H.sale ? 'on sale: members see them' : 'hidden from members (heroSales off)') + '</span></h3>'
|
||||
+ '<p class="muted" style="margin:0 0 8px">Sold one time, owned for good, paid by a fresh package like a pass (no credits). Prices, the free list and the bundle are settings: heroPrice<Name>Cents (0 = free for everyone), heroBundleHeroes, heroBundlePriceCents. heroBundleCap stays empty (the bundle is heroes only). Members see heroes only once <b>heroSales</b> is on.</p>'
|
||||
+ '<div class="gpt-grid">' + H.items.map(i => row(i.key, i.name, i.blurb, i.usd, i.package, i.owned, i.waiting, i.free)).join('')
|
||||
+ (B ? row('bundle', 'Hero bundle', B.names.join(', '), B.usd, B.package, B.owned, B.waiting, false) : '') + '</div>';
|
||||
}
|
||||
function wireHeroTest(box, g) {
|
||||
const nm = k => k === 'bundle' ? 'the hero bundle' : ((g.heroes.items.find(i => i.key === k) || {}).name || k);
|
||||
box.querySelectorAll('[data-ht-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.htBuy; if (!(await IAP.confirmBox('Open a TEST order for ' + nm(k) + ' on your own account (' + g.email + ')? It is fulfilled when a fresh package of at least its price from one of your positions settles on chain. Members still cannot buy heroes while heroSales is off.', { title: 'Test buy: ' + nm(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
|
||||
const x = await api('/api/admin/heroes/test-buy', { hero: k }); IAP.status('Test order for ' + nm(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
|
||||
})));
|
||||
box.querySelectorAll('[data-ht-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => { const k = b.dataset.htCancel; await api('/api/admin/heroes/test-cancel', { hero: k }); IAP.status('Test order for ' + nm(k) + ' cancelled.', 'ok'); await loadGpTest(); })));
|
||||
box.querySelectorAll('[data-ht-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.htComp; if (!(await IAP.confirmBox('Give your own account ' + nm(k) + ' now, for testing? Recorded as comped (no sale); the game shows it the next time you sign in to it from /my Games.', { title: 'Test ' + nm(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
|
||||
await api('/api/admin/heroes/test-comp', { hero: k }); IAP.status(nm(k) + ' is on your account (test).', 'ok'); await loadGpTest();
|
||||
})));
|
||||
box.querySelectorAll('[data-ht-revoke]').forEach(b => b.addEventListener('click', busy(b, async () => { const k = b.dataset.htRevoke; await api('/api/admin/heroes/test-revoke', { hero: k }); IAP.status(nm(k) + ' removed from your account.', 'ok'); await loadGpTest(); })));
|
||||
}
|
||||
async function loadGpTest() {
|
||||
const box = $('gpTest'); if (!box) return;
|
||||
let g; try { g = await api('/api/admin/gamepass/preview'); } catch (e) { box.innerHTML = '<p class="muted">' + esc(e.message) + '</p>'; return; }
|
||||
const ct = ms => new Date(Number(ms)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric' }) + ' (Central)';
|
||||
const len = d => d >= 365 && d % 365 === 0 ? (d === 365 ? '1 year' : (d / 365) + ' years') : d + ' days';
|
||||
const rows = g.passes || [];
|
||||
$('gpTestSub').textContent = 'TEST / PREVIEW · admin only · acts on your own account: ' + g.email;
|
||||
const card = r => {
|
||||
const sale = r.tier === 'weekly' ? !!g.enabled : !!r.sale;
|
||||
const st = r.active ? '<b>Your account: active until ' + esc(ct(r.until)) + '</b>' : r.waiting ? '<b>Your account: test order waiting for a $' + r.package + ' package</b>' : 'Your account: not active';
|
||||
const acts = (r.waiting ? '<a class="btn small" href="/my?from=gamepass#buy" target="_blank" rel="noopener">Buy the $' + r.package + ' package on /my</a><button class="btn small sec" type="button" data-gpt-cancel="' + esc(r.tier) + '">Cancel test order</button>'
|
||||
: '<button class="btn small" type="button" data-gpt-buy="' + esc(r.tier) + '">Test buy (real order, $' + r.package + ' package)</button>')
|
||||
+ '<button class="btn small sec" type="button" data-gpt-comp="' + esc(r.tier) + '">Give my account ' + esc(r.name) + ' now (test)</button>'
|
||||
+ (r.active ? '<button class="btn small sec" type="button" data-gpt-end="' + esc(r.tier) + '">End my ' + esc(r.name) + ' now</button>' : '');
|
||||
return '<div class="gpt-tier' + (r.active ? ' on' : '') + '"><h4>' + esc(r.name) + ' <span class="chip flat">' + (sale ? 'on sale: members see it' : 'hidden from members') + '</span></h4>'
|
||||
+ '<p class="gpt-price">$' + r.usd + ' <span class="small muted">for ' + len(r.days) + '</span></p>'
|
||||
+ '<ul>' + (r.perks || []).map(x => '<li>' + esc(x) + '</li>').join('') + '</ul>'
|
||||
+ '<p class="small" style="margin:4px 0">' + st + '</p><div class="gpt-acts">' + acts + '</div></div>';
|
||||
};
|
||||
box.innerHTML = '<p class="gpt-note"><b>Test / preview, admin only.</b> ' + (g.tierPreview ? 'The passes above the weekly Game Pass are hidden from members until sovTiers is switched on in Settings (it stays off until the paid tiers launch). ' : '')
|
||||
+ 'These are the tier cards as members will see them. Every button here acts on your own account (' + esc(g.email) + ') and nobody else’s. The member Games card on /my shows you exactly what a member sees: while you hold a test tier it shows that tier the way it would for any member who holds one.</p>'
|
||||
+ '<div class="gpt-grid">' + rows.map(card).join('') + '</div>'
|
||||
+ '<p class="muted" style="margin:10px 0 0"><b>Test buy</b> opens the same waiting order a member gets: a fresh package of at least the price, bought on /my by one of your positions, starts it (sponsors paid as usual). Cancel a test order you will not pay, or a later real package of that size fulfils it. <b>Give my account</b> starts one pass period at once, recorded as comped (no sale); <b>End</b> stops it. '
|
||||
+ 'To test it in game, open <b>Shards of Valor > Passes</b> (key P) after signing in to the game again from /my Games: the game reads your highest tier from InstantAdPay at sign-in.</p>'
|
||||
+ heroTestHtml(g.heroes);
|
||||
const tierName = k => (rows.find(r => r.tier === k) || {}).name || k;
|
||||
wireHeroTest(box, g);
|
||||
box.querySelectorAll('[data-gpt-buy]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.gptBuy; const r = rows.find(x => x.tier === k);
|
||||
if (!(await IAP.confirmBox('Open a TEST order for ' + tierName(k) + ' on your own account (' + g.email + ')? It starts when a fresh $' + r.package + ' or bigger package from one of your positions settles on chain. Members still cannot see or buy this tier.', { title: 'Test buy: ' + tierName(k), ok: 'Open the test order', cancel: 'Not now' }))) return;
|
||||
const x = await api('/api/admin/gamepass/test-buy', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' is waiting for a $' + x.package + ' package on ' + x.email + '.', 'ok'); await loadGpTest();
|
||||
})));
|
||||
box.querySelectorAll('[data-gpt-cancel]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.gptCancel; await api('/api/admin/gamepass/test-cancel', { tier: k }); IAP.status('Test order for ' + tierName(k) + ' cancelled.', 'ok'); await loadGpTest();
|
||||
})));
|
||||
box.querySelectorAll('[data-gpt-comp]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.gptComp;
|
||||
if (!(await IAP.confirmBox('Give your own account (' + g.email + ') one ' + tierName(k) + ' period now, for testing? It is recorded as comped (no sale) and shows in the game the next time you sign in to it.', { title: 'Test ' + tierName(k), ok: 'Give it to me', cancel: 'Not now' }))) return;
|
||||
const x = await api('/api/admin/gamepass/test-comp', { tier: k }); IAP.status(tierName(k) + ' on your account until ' + when(x.until) + ' (test).', 'ok'); await loadGamePass();
|
||||
})));
|
||||
box.querySelectorAll('[data-gpt-end]').forEach(b => b.addEventListener('click', busy(b, async () => {
|
||||
const k = b.dataset.gptEnd;
|
||||
if (!(await IAP.confirmBox('End ' + tierName(k) + ' on your own account now?', { title: 'End test tier', ok: 'End it now', cancel: 'Keep it' }))) return;
|
||||
await api('/api/admin/gamepass/revoke', { email: g.email, tier: k, why: 'admin tier test' }); IAP.status(tierName(k) + ' on your account ended.', 'ok'); await loadGamePass();
|
||||
})));
|
||||
}
|
||||
$('gpTourRun').addEventListener('click', busy($('gpTourRun'), async () => { const r = await api('/api/admin/gamepass/tournament/run', {}); IAP.status('Settled ' + r.label + ': ' + (r.winners || []).length + ' winner(s), pool ' + Number(r.poolPol || 0).toFixed(2) + ' POL.', 'ok'); await loadGamePass(); }));
|
||||
$('gpComp').addEventListener('click', busy($('gpComp'), async () => { const r = await api('/api/admin/gamepass/comp', { email: $('gpCompEmail').value, why: $('gpCompWhy').value, tier: $('gpCompTier').value }); IAP.status((r.tier || 'weekly') + ' pass on ' + r.email + ' until ' + when(r.until) + '.', 'ok'); $('gpCompEmail').value = ''; await loadGamePass(); }));
|
||||
$('gpRevoke').addEventListener('click', busy($('gpRevoke'), async () => {
|
||||
const email = $('gpCompEmail').value.trim(), tier = $('gpCompTier').value; if (!email) { IAP.status('Enter the member email first.', 'bad'); return; }
|
||||
if (!(await IAP.confirmBox('End the ' + tier + ' pass on ' + email + ' now? Use this only for a support refund; it does not return any credits by itself.', { title: 'End a pass tier', ok: 'End it now', cancel: 'Keep it' }))) return;
|
||||
const r = await api('/api/admin/gamepass/revoke', { email, tier, why: $('gpCompWhy').value }); IAP.status(r.tier + ' pass on ' + r.email + ' ended (was until ' + when(r.was) + ').', 'ok'); await loadGamePass();
|
||||
}));
|
||||
|
||||
async function loadSettings() {
|
||||
const [r, s, d] = await Promise.all([api('/api/admin/rates'), api('/api/admin/site'), api('/api/admin/drip')]);
|
||||
ratesObj = r.rates || {}; drawRates();
|
||||
@@ -1005,3 +1379,33 @@
|
||||
|
||||
render();
|
||||
})();
|
||||
// ---- tax summary (2026-10-04) + the cost category picker
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
if ($('ldKind') && $('ldCat')) { const sync = () => { $('ldCat').hidden = $('ldKind').value !== 'cost'; }; $('ldKind').addEventListener('change', sync); sync(); }
|
||||
if (!$('taxYear')) return;
|
||||
const y = new Date().getFullYear(); for (let v = y; v >= 2025; v--) { const o = document.createElement('option'); o.value = v; o.textContent = v; $('taxYear').appendChild(o); }
|
||||
const money = n => '$' + Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
||||
$('taxRun').addEventListener('click', async () => {
|
||||
$('taxOut').textContent = 'Working it out...';
|
||||
try {
|
||||
const r = await (await fetch('/api/admin/tax?year=' + $('taxYear').value, { credentials: 'same-origin' })).json();
|
||||
if (r.error) throw new Error(r.error);
|
||||
const cats = Object.entries(r.expenses.byCategory || {}).map(([k, v]) => '<tr><td>' + (r.expenses.labels[k] || k) + '</td><td class="num">' + money(v) + '</td></tr>').join('');
|
||||
$('taxOut').innerHTML = '<table class="adm-table"><tr><th colspan="2">' + r.year + '</th></tr>'
|
||||
+ '<tr><td><b>Income</b>: platform share of ' + r.income.sales + ' package sales</td><td class="num">' + money(r.income.platformUsd) + '</td></tr>'
|
||||
+ (r.income.outsideUsd ? '<tr><td>Outside revenue</td><td class="num">' + money(r.income.outsideUsd) + '</td></tr>' : '')
|
||||
+ '<tr><td><b>Total income</b></td><td class="num"><b>' + money(r.income.totalUsd) + '</b></td></tr>'
|
||||
+ (cats || '<tr><td>No costs recorded yet</td><td></td></tr>')
|
||||
+ '<tr><td><b>Advertising and promotion</b> (advertising + game marketing + player rewards)</td><td class="num"><b>' + money(r.expenses.advertisingAndPromotionUsd) + '</b></td></tr>'
|
||||
+ '<tr><td><b>Total costs</b></td><td class="num"><b>' + money(r.expenses.totalUsd) + '</b></td></tr>'
|
||||
+ '<tr><td><b>Net</b></td><td class="num"><b>' + money(r.netUsd) + '</b></td></tr></table>'
|
||||
+ '<p class="muted">Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).</p>';
|
||||
$('taxCsvText').value = r.csv; $('taxCsv').hidden = false;
|
||||
} catch (e) { $('taxOut').textContent = 'Could not build the summary: ' + e.message; }
|
||||
});
|
||||
$('taxCsv').addEventListener('click', async () => {
|
||||
try { await navigator.clipboard.writeText($('taxCsvText').value); IAP.status('CSV copied. Paste it into a spreadsheet.', 'good'); }
|
||||
catch (e) { $('taxCsvText').hidden = false; $('taxCsvText').select(); IAP.status('Selected. Copy it with your keyboard.', 'good'); }
|
||||
});
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
// BixPay guide (/bixpay, 2026-10-29): the CTA carries the viewer's resolved partner link (their own when signed in, else the
|
||||
// member whose ?ref brought them here or whose sponsor cookie they carry, else the network link), always through the counted
|
||||
// /go/bixpay link. The server already folded ?ref into the sponsor cookie; the ref is passed along too so the first view resolves.
|
||||
// In-app browsers (Gmail, Telegram, Facebook webviews): BIX's register page runs a Cloudflare check that often fails there, and
|
||||
// the invite token lives only in the URL, so a member who then reopens BIX elsewhere registers with no sponsor (bizventures,
|
||||
// 2026-10-29: referrer N/A). Those viewers get a notice with the link to copy into a real browser.
|
||||
(function () {
|
||||
var cta = document.getElementById('bixCta'), using = document.getElementById('bixUsing'), soon = document.getElementById('bixSoon');
|
||||
var box = document.getElementById('bixInApp'), boxLink = document.getElementById('bixInAppLink'), boxCopy = document.getElementById('bixInAppCopy');
|
||||
if (!cta) return;
|
||||
function inApp() {
|
||||
var u = navigator.userAgent || '';
|
||||
if (/FBAN|FBAV|FB_IAB|Instagram|Line\/|Twitter|Snapchat|GSA\/|Telegram|\bwv\b|WebView/i.test(u)) return true;
|
||||
return /iPhone|iPad|iPod/.test(u) && !/Safari\//.test(u); // an iOS web view: no Safari token
|
||||
}
|
||||
var ref = '';
|
||||
try { ref = new URLSearchParams(location.search).get('ref') || ''; } catch (e) { ref = ''; }
|
||||
fetch('/api/public/bixpay' + (ref ? '?ref=' + encodeURIComponent(ref) : ''), { credentials: 'same-origin' }).then(function (r) { return r.json(); }).then(function (d) {
|
||||
if (!d || !d.live) { if (soon) soon.hidden = false; cta.href = '/my#wallet'; if (using) using.textContent = 'Sign in to your dashboard and open the Wallet tab.'; return; }
|
||||
cta.href = d.go;
|
||||
if (using) using.textContent = d.whose === 'you' ? 'The button opens your own BixPay partner link.' : d.whose === 'sponsor' ? 'The button opens ' + d.name + "'s BixPay partner link." + (d.signedIn ? ' Add yours in Members > Profile.' : '') : 'The button opens the network’s BixPay partner link.' + (d.signedIn ? ' Add yours in Members > Profile.' : '');
|
||||
if (box && inApp()) {
|
||||
box.hidden = false;
|
||||
if (boxLink) boxLink.textContent = d.go;
|
||||
if (boxCopy) boxCopy.addEventListener('click', function () {
|
||||
var done = function () { boxCopy.textContent = 'Copied'; setTimeout(function () { boxCopy.textContent = 'Copy link'; }, 2000); };
|
||||
var select = function () { try { var r = document.createRange(); r.selectNodeContents(boxLink); var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); boxCopy.textContent = 'Selected: copy it'; } catch (e) {} }; // no native dialogs
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(d.go).then(done, select);
|
||||
else select();
|
||||
});
|
||||
}
|
||||
}).catch(function () {});
|
||||
})();
|
||||
|
After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 25 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 100 KiB |
|
After Width: | Height: | Size: 20 KiB |
|
After Width: | Height: | Size: 74 KiB |
|
After Width: | Height: | Size: 15 KiB |
@@ -11,7 +11,7 @@
|
||||
share.querySelectorAll('a').forEach(a => { a.href = a.href.replace(encodeURIComponent('https://instantadpay.com' + location.pathname), encodeURIComponent(link)); });
|
||||
const bar = document.createElement('div');
|
||||
bar.id = 'viralBar';
|
||||
bar.style.cssText = 'margin-top:18px;padding:12px 14px;border:1px solid var(--line);border-radius:12px;background:var(--card, rgba(255,255,255,.03));display:flex;gap:10px;align-items:center;flex-wrap:wrap';
|
||||
bar.style.cssText = 'margin-top:18px;padding:12px 14px;border:1px solid var(--line);border-radius:12px;background:var(--ink-faint);display:flex;gap:10px;align-items:center;flex-wrap:wrap';
|
||||
bar.innerHTML = '<div style="flex:1;min-width:220px"><div class="eyebrow" style="margin:0 0 4px">Your link for this article</div><div class="mono small" style="overflow-wrap:anywhere">' + link.replace(/[&<>]/g, '') + '</div><div class="muted small" style="margin-top:4px">Share this and anyone who joins from it is yours, same as your invite link.</div></div><button class="btn small" type="button">Copy link</button>';
|
||||
bar.querySelector('button').onclick = async () => { try { await navigator.clipboard.writeText(link); IAP.status('Link copied.', 'ok'); } catch (e) { IAP.status('Copy failed.', 'bad'); } };
|
||||
share.parentNode.insertBefore(bar, share);
|
||||
|
||||
|
After Width: | Height: | Size: 212 KiB |
@@ -0,0 +1,122 @@
|
||||
// Chasing Unicorns (Marty, 2026-11-12): a promo-tool lead magnet. A fake earnings dashboard where every button, tile and popup
|
||||
// is one of the classic scam warning signs; clicking one reveals it and scores the visitor's "scam radar", and the ending
|
||||
// contrasts the unicorn with how InstantAdPay works. Shared as /chasing-unicorns?ref=<username> (the viral ?ref= link sets the
|
||||
// sponsor cookie server-side). Nothing here touches an account: it is all made up on the page.
|
||||
(function () {
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var usd = function (n) { return '$' + n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); };
|
||||
var calm = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||||
|
||||
var FLAGS = {
|
||||
daily: { name: 'A fixed daily return', short: 'Guaranteed % a day on your deposit',
|
||||
h: 'Nobody pays a fixed 3% a day.', p: 'That is over 4 million percent a year, compounded. No business earns that. The only way to pay a fixed daily return is with the next person\'s deposit.',
|
||||
tell: 'Your "interest" is a line of code adding to a number. Watch it: it goes up even though nothing happened.', do: 'Ask what the product is and who buys it. If the answer is "the return", walk away.' },
|
||||
withdraw: { name: 'Withdrawals that never arrive', short: 'Always "processing"',
|
||||
h: 'Withdrawal processing... forever.', p: 'Deposits are instant. Withdrawals need "verification", a "maintenance window", a new minimum. That is how a site with no money buys time.',
|
||||
tell: 'The balance on screen is not money. Money is what lands in your own wallet or bank.', do: 'Withdraw a small amount early. If $20 is a hostage negotiation, you have your answer.' },
|
||||
vip: { name: 'Pay to unlock your own money', short: 'Upgrade or "release fee" first',
|
||||
h: 'Pay $199 to unlock your own $25,000?', p: 'The "upgrade", the "tax", the "release fee", a "small miner fee" or "gas fee". It always sounds minor next to the balance waiting for you. It is the oldest trick: the balance is bait, and the fee is the real product. Some sites are free right up until the countdown ends, then everybody gets the fee at once.',
|
||||
tell: 'If the money were there, they would take the fee out of it. They want new money from you instead.', do: 'Never pay to withdraw. A real balance pays its own fees.' },
|
||||
team: { name: 'The product is recruiting', short: 'Paid mainly for sign-ups',
|
||||
h: '+$500 per sign-up. Paid with what?', p: 'If you earn for bringing people in and nobody is buying anything real, the money for your bonus comes from the people you brought in.',
|
||||
tell: 'A team bonus with no product is your friends\' deposits with your name on them.', do: 'Ask: if nobody new joined tomorrow, where would the money come from?' },
|
||||
clock: { name: 'The clock is always ticking', short: 'Countdowns and "spots left"',
|
||||
h: 'The countdown resets. It always does.', p: 'Urgency is there to stop you thinking and to get you recruiting before you check anything. Watch the timer: when it hits zero, it starts over.',
|
||||
tell: 'A good opportunity is still there after you sleep on it. A bad one needs you not to.', do: 'Wait 48 hours and search the name plus "withdrawal" and "scam" first.' },
|
||||
coin: { name: 'Paid in their own coin', short: 'Tokens you cannot sell anywhere real',
|
||||
h: '48,000 UYP, worth whatever they say.', p: 'A token you can only "sell" back on their own site is Monopoly money with better branding. They print it, they price it, they decide when you can sell.',
|
||||
tell: '"Soon x100" is a promise from the people holding all the supply.', do: 'Check whether it trades anywhere real, with real volume, and who holds most of it.' },
|
||||
keys: { name: 'Anything that touches your keys', short: '"Connect wallet to claim"',
|
||||
h: 'Connect wallet to claim? That is the scam.', p: 'Claim pages ask you to sign an approval that lets them spend your tokens. Some ask for your seed phrase outright. Nobody legit ever needs either.',
|
||||
tell: 'One signature can empty a wallet. The "airdrop" is the bait.', do: 'Never type a seed phrase into a website. Read what a signature approves before you sign it.' },
|
||||
proof: { name: 'Fake social proof', short: 'People "cashing out" every few seconds',
|
||||
h: '"Dave from Denver just withdrew $19,350."', p: 'These popups are a few lines of code picking a random name and a random amount. They are on scam sites because they work on all of us.',
|
||||
tell: 'A popup is not a receipt. A transaction you can look up is.', do: 'Ask for a payment you can verify yourself, on a public ledger, not a screenshot.' }
|
||||
};
|
||||
var ORDER = ['daily', 'withdraw', 'vip', 'team', 'clock', 'coin', 'keys', 'proof'];
|
||||
var seen = [];
|
||||
|
||||
// the visitor's sponsor rides the share link (?ref=), so the join button and the share line keep it
|
||||
var ref = (new URLSearchParams(location.search).get('ref') || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
|
||||
// where the page link was posted (?src=massifly, ?src=leasedadspace...) rides into the join, so a sign-up says which channel
|
||||
var chan = (new URLSearchParams(location.search).get('src') || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 18);
|
||||
var srcTag = chan ? 'unicorns-' + chan : 'chasing-unicorns';
|
||||
$('joinBtn').href = '/join?src=' + srcTag;
|
||||
if (ref) {
|
||||
$('joinBtn').href = '/join/' + ref + '?src=' + srcTag;
|
||||
$('ledgerBtn').href = '/ledger?ref=' + ref;
|
||||
$('shareLink').textContent = 'https://instantadpay.com/chasing-unicorns?ref=' + ref;
|
||||
}
|
||||
|
||||
// radar
|
||||
var dots = $('dots'); ORDER.forEach(function () { dots.appendChild(document.createElement('i')); });
|
||||
function renderRadar() {
|
||||
[].forEach.call(dots.children, function (d, i) { d.className = i < seen.length ? 'on' : ''; });
|
||||
$('score').textContent = seen.length + ' of 8';
|
||||
$('endH').textContent = seen.length === 8 ? 'Scam radar: 8 of 8. You are a unicorn hunter.' : 'Your scam radar: ' + seen.length + ' of 8 red flags spotted';
|
||||
$('flags').innerHTML = ORDER.map(function (k) { var f = FLAGS[k]; return '<li class="' + (seen.indexOf(k) >= 0 ? 'on' : '') + '"><b>' + f.name + '</b><span class="fine">' + f.short + '</span></li>'; }).join('');
|
||||
document.querySelectorAll('[data-flag]').forEach(function (b) { b.classList.toggle('done', seen.indexOf(b.getAttribute('data-flag')) >= 0); });
|
||||
if (seen.length >= 3) $('after').hidden = false;
|
||||
}
|
||||
renderRadar();
|
||||
|
||||
// the reveal card
|
||||
var lastFocus = null;
|
||||
function reveal(k) {
|
||||
var f = FLAGS[k]; if (!f) return;
|
||||
if (seen.indexOf(k) < 0) seen.push(k);
|
||||
renderRadar();
|
||||
$('cardK').textContent = 'Red flag ' + seen.length + ' of 8 spotted: ' + f.name;
|
||||
$('cardH').textContent = f.h; $('cardP').textContent = f.p;
|
||||
$('cardTell').textContent = f.tell; $('cardDo').textContent = 'What to do: ' + f.do;
|
||||
$('cardNext').textContent = seen.length === 8 ? 'See my result' : 'Keep hunting';
|
||||
lastFocus = document.activeElement; $('veil').hidden = false; $('cardNext').focus();
|
||||
}
|
||||
function closeCard(toEnd) {
|
||||
$('veil').hidden = true;
|
||||
if (toEnd || seen.length === 8) $('end').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' });
|
||||
else if (lastFocus) lastFocus.focus();
|
||||
}
|
||||
document.querySelectorAll('[data-flag]').forEach(function (b) { b.addEventListener('click', function () { reveal(b.getAttribute('data-flag')); }); });
|
||||
$('cardNext').addEventListener('click', function () { closeCard(false); });
|
||||
$('cardEnd').addEventListener('click', function () { closeCard(true); });
|
||||
$('veil').addEventListener('click', function (e) { if (e.target === $('veil')) closeCard(false); });
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !$('veil').hidden) closeCard(false); });
|
||||
$('showAll').addEventListener('click', function () { ORDER.forEach(function (k) { if (seen.indexOf(k) < 0) seen.push(k); }); renderRadar(); $('after').scrollIntoView({ behavior: calm ? 'auto' : 'smooth', block: 'start' }); });
|
||||
$('copyShare').addEventListener('click', function () {
|
||||
var t = $('shareLink').textContent, b = $('copyShare');
|
||||
navigator.clipboard.writeText(t).then(function () { b.textContent = 'Copied'; }, function () { var r = document.createRange(); r.selectNodeContents($('shareLink')); var s = getSelection(); s.removeAllRanges(); s.addRange(r); b.textContent = 'Press Ctrl+C'; });
|
||||
});
|
||||
|
||||
// the ticking balance: 3% a day of $25,000, out of thin air
|
||||
var START = 25000, perSec = START * 0.03 / 86400, t0 = performance.now(), midnight = new Date(); midnight.setHours(0, 0, 0, 0);
|
||||
function tick() {
|
||||
var gain = (performance.now() - t0) / 1000 * perSec;
|
||||
$('bal').textContent = usd(START + gain);
|
||||
$('rate').textContent = '+3.00% daily compound interest · +' + usd(gain) + ' since you opened this page';
|
||||
$('today').textContent = usd((Date.now() - midnight.getTime()) / 1000 * perSec);
|
||||
}
|
||||
tick(); setInterval(tick, calm ? 1000 : 100);
|
||||
|
||||
// the countdown that starts over at zero, and spots that never run out
|
||||
var LEN = 600, end = Date.now() + LEN * 1000, spots = 3;
|
||||
setInterval(function () {
|
||||
var left = Math.round((end - Date.now()) / 1000);
|
||||
if (left <= 0) { end = Date.now() + LEN * 1000; left = LEN; spots = 3; }
|
||||
else if (left % 89 === 0 && spots > 1) spots--;
|
||||
$('clock').textContent = String(Math.floor(left / 60)).padStart(2, '0') + ':' + String(left % 60).padStart(2, '0');
|
||||
$('spots').textContent = 'Only ' + spots + ' VIP spot' + (spots === 1 ? '' : 's') + ' left';
|
||||
}, 1000);
|
||||
|
||||
// fake "cash out" popups every few seconds: random made-up names and amounts
|
||||
var who = ['Jessica from Ohio', 'Mike in Texas', 'Priya from London', 'Carlos in Miami', 'Ahmed from Dubai', 'Linda in Phoenix', 'Tom from Sydney', 'Grace in Toronto', 'Dave from Denver', 'Nina in Berlin', 'Kwame from Accra', 'Rosa in Manila'];
|
||||
var what = ['just withdrew', 'just cashed out', 'just earned', 'just got a team bonus of'];
|
||||
function pop() {
|
||||
var n = who[Math.floor(Math.random() * who.length)], amt = Math.round((Math.random() * 40000 + 1500) / 10) * 10;
|
||||
$('pAv').textContent = n.charAt(0);
|
||||
$('pT').innerHTML = n + ' ' + what[Math.floor(Math.random() * what.length)] + ' <b>' + usd(amt) + '</b> ' + (1 + Math.floor(Math.random() * 9)) + ' min ago';
|
||||
$('proof').classList.add('on');
|
||||
setTimeout(function () { $('proof').classList.remove('on'); }, 4500);
|
||||
}
|
||||
setTimeout(function () { pop(); setInterval(pop, 8000); }, 3000);
|
||||
})();
|
||||
@@ -1,4 +1,6 @@
|
||||
// 24/7 assistant widget: floating bubble, slide-up panel, /api/chat.
|
||||
// Hand-off (help desk, 2026-10-16): when the answer cannot help, or they ask for a person, the widget offers
|
||||
// "Send this to support", which files the last few turns as a ticket (members: their Help pane; signed out: their email).
|
||||
(function () {
|
||||
const root = document.createElement('div');
|
||||
root.id = 'iapChat';
|
||||
@@ -7,10 +9,11 @@
|
||||
+ '<div class="ch-head"><b>Ask anything</b><span class="ch-sub">Real answers, around the clock</span>'
|
||||
+ '<button id="iapChatClose" aria-label="Close chat" type="button">×</button></div>'
|
||||
+ '<div class="ch-msgs" id="iapChatMsgs">'
|
||||
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype.</div>'
|
||||
+ '<div class="ch-m bot">Hey. Ask me how the payments work, what the packages buy, or anything else. Straight answers only, no income hype. Need a person instead? Tap <b>Send this to support</b> below, or use the <a href="/support" style="color:inherit;text-decoration:underline">support page</a>.</div>'
|
||||
+ '</div>'
|
||||
+ '<div class="ch-input"><input id="iapChatIn" placeholder="Type your question…" maxlength="600">'
|
||||
+ '<button id="iapChatSend" type="button">Send</button></div>'
|
||||
+ '<div style="text-align:center;font-size:12px;padding:4px 0 8px"><a href="#" id="iapChatHuman" style="color:inherit;opacity:.75">Need a person? Send this to support</a></div>'
|
||||
+ '</div>';
|
||||
document.body.appendChild(root);
|
||||
|
||||
@@ -18,6 +21,7 @@
|
||||
const msgs = $('iapChatMsgs');
|
||||
const input = $('iapChatIn');
|
||||
let history = [];
|
||||
const turns = []; // { who: 'me' | 'bot', text } for the support hand-off
|
||||
|
||||
const add = (text, who) => {
|
||||
const d = document.createElement('div');
|
||||
@@ -29,11 +33,18 @@
|
||||
msgs.scrollTop = msgs.scrollHeight;
|
||||
return d;
|
||||
};
|
||||
function offerHandoff() {
|
||||
if (msgs.querySelector('.ch-handoff')) return;
|
||||
const d = document.createElement('div'); d.className = 'ch-m bot ch-handoff';
|
||||
d.innerHTML = '<button type="button" class="btn small" style="margin:0">Send this to support</button>';
|
||||
d.querySelector('button').addEventListener('click', handoff);
|
||||
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
|
||||
}
|
||||
async function send() {
|
||||
const q = input.value.trim();
|
||||
if (!q) return;
|
||||
input.value = '';
|
||||
add(q, 'me');
|
||||
add(q, 'me'); turns.push({ who: 'me', text: q });
|
||||
const wait = add('…', 'bot');
|
||||
try {
|
||||
const r = await (await fetch('/api/chat', { method: 'POST',
|
||||
@@ -41,12 +52,61 @@
|
||||
body: JSON.stringify({ message: q, history: history.slice(-4).join(' | ') }) })).json();
|
||||
wait.remove();
|
||||
add(r.reply || r.error || 'No answer came back. Try again.', 'bot');
|
||||
if (r.reply) turns.push({ who: 'bot', text: r.reply });
|
||||
history.push('Q: ' + q, 'A: ' + (r.reply || ''));
|
||||
if (r.handoff) offerHandoff();
|
||||
} catch (e) {
|
||||
wait.remove();
|
||||
add('Connection hiccup. Try that again.', 'bot');
|
||||
offerHandoff();
|
||||
}
|
||||
}
|
||||
async function post(body) {
|
||||
const g = window.IAP && IAP.guard;
|
||||
if (g) await g.formSettled();
|
||||
return (await fetch('/api/support/chatbot', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(Object.assign({ transcript: turns.slice(-8), fts: g ? g.FORM_TS : 0, fage: g ? Date.now() - g.FORM_TS : 0 }, body)) })).json();
|
||||
}
|
||||
function done(r) {
|
||||
const old = msgs.querySelector('.ch-handoff'); if (old) old.remove();
|
||||
const f = msgs.querySelector('.ch-hform'); if (f) f.remove();
|
||||
add(r.member ? 'Sent to support as ticket ' + r.ref + '. Marty will reply in Help in your dashboard and by email: ' + location.origin + r.link
|
||||
: 'Sent to support as ticket ' + r.ref + '. We emailed you a private link to follow it, and Marty will reply there: ' + location.origin + r.link, 'bot');
|
||||
}
|
||||
async function handoff(e) {
|
||||
if (e && e.preventDefault) e.preventDefault();
|
||||
if (msgs.querySelector('.ch-hform')) return;
|
||||
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (err) {}
|
||||
if (me && me.signedIn && me.email) {
|
||||
const ok = window.IAP && IAP.confirmBox ? await IAP.confirmBox('Send this chat to support as a ticket? Marty will reply in Help in your dashboard and by email.', { ok: 'Send it', cancel: 'Not now' }) : true;
|
||||
if (!ok) return;
|
||||
try { const r = await post({}); if (r.error) throw new Error(r.error); done(r); } catch (err) { add(err.message || 'Could not send it. Try the Help tab in your dashboard.', 'bot'); }
|
||||
return;
|
||||
}
|
||||
// signed out: an email so Marty can reply, plus the same invisible walls as sign-up
|
||||
const d = document.createElement('div'); d.className = 'ch-m bot ch-hform';
|
||||
d.innerHTML = 'Where should Marty reply?'
|
||||
+ '<input class="hp-field" type="text" tabindex="-1" aria-hidden="true" autocomplete="off" id="iapChatHp">'
|
||||
+ '<input id="iapChatEmail" type="email" placeholder="your email" maxlength="190" autocomplete="email" style="width:100%;margin-top:6px;box-sizing:border-box">'
|
||||
+ '<input id="iapChatNote" placeholder="anything to add (optional)" maxlength="600" style="width:100%;margin-top:6px;box-sizing:border-box">'
|
||||
+ '<div id="iapChatCheck" hidden style="margin-top:6px"></div>'
|
||||
+ '<button type="button" class="btn small" id="iapChatGo" style="margin-top:8px">Send to support</button> <span class="small" id="iapChatErr"></span>';
|
||||
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
|
||||
$('iapChatEmail').focus();
|
||||
$('iapChatGo').addEventListener('click', async () => {
|
||||
const btn = $('iapChatGo'); if (btn.disabled) return; btn.disabled = true; $('iapChatErr').textContent = '';
|
||||
try {
|
||||
let pick = null, r = null;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
r = await post({ email: $('iapChatEmail').value.trim(), note: $('iapChatNote').value.trim(), hp_field_x9: window.IAP && IAP.guard ? IAP.guard.hpValue($('iapChatHp')) : '', pick });
|
||||
if (r.challenge && window.IAP && IAP.guard) { pick = await IAP.guard.iconCheck($('iapChatCheck'), r.challenge, r.error); continue; }
|
||||
break;
|
||||
}
|
||||
if (!r || r.error) throw new Error((r && r.error) || 'Could not send it.');
|
||||
done(r);
|
||||
} catch (err) { $('iapChatErr').textContent = err.message; btn.disabled = false; }
|
||||
});
|
||||
}
|
||||
$('iapChatBtn').addEventListener('click', () => {
|
||||
const p = $('iapChatPanel');
|
||||
p.hidden = !p.hidden;
|
||||
@@ -54,5 +114,6 @@
|
||||
});
|
||||
$('iapChatClose').addEventListener('click', () => { $('iapChatPanel').hidden = true; });
|
||||
$('iapChatSend').addEventListener('click', send);
|
||||
$('iapChatHuman').addEventListener('click', handoff);
|
||||
input.addEventListener('keydown', e => { if (e.key === 'Enter') send(); });
|
||||
})();
|
||||
|
||||
@@ -30,10 +30,12 @@ window.IAP = (function () {
|
||||
+ '<span class="logo-wrap"><a class="logo" href="/"><img src="/logo.png" alt="InstantAdPay" style="height:30px;display:block"></a><span class="byline">Brought to you by the <b>Crypto Team Build Network</b></span></span>'
|
||||
+ '<span class="links">'
|
||||
+ '<a href="/#how" data-p="home">How it works</a>'
|
||||
+ '<a href="/presentation" data-p="presentation">Presentation</a>'
|
||||
+ '<a href="/#packages" data-p="pricing">Ad packages</a>'
|
||||
+ '<a href="/ledger" data-p="ledger">Live ledger</a>'
|
||||
+ '<a href="/leaderboard" data-p="leaderboard">Leaderboard</a>'
|
||||
+ '<a href="/contract" data-p="contract">The contract</a>'
|
||||
+ '<a href="/support" data-p="support">Support</a>'
|
||||
+ '<a href="/my" data-p="my">Members</a>'
|
||||
+ '</span><span id="navWallet" class="muted">…</span></div>';
|
||||
document.body.prepend(nav);
|
||||
@@ -54,10 +56,37 @@ window.IAP = (function () {
|
||||
f.style.cssText = 'border-top:1px solid var(--line);margin-top:48px;padding:26px 22px;text-align:center;color:var(--muted);font-size:13px';
|
||||
f.innerHTML = '<div>© ' + new Date().getFullYear() + ' InstantAdPay</div>'
|
||||
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
||||
+ '<a href="/">How it works</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
|
||||
+ '<a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
|
||||
+ '<a href="/">How it works</a><a href="/presentation">Presentation</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
|
||||
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
|
||||
document.body.appendChild(f);
|
||||
renderNetworkLine(f);
|
||||
}
|
||||
// "Part of the network" (Marty 2026-11-14 trust pack): the list comes from the hub through /api/network-sites, built-in copy if not
|
||||
const NET_FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
|
||||
let netList = null;
|
||||
async function networkSites() {
|
||||
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
|
||||
return netList;
|
||||
}
|
||||
function renderNetworkLine(host) {
|
||||
if (!host || host.querySelector('.netline')) return;
|
||||
const d = document.createElement('div'); d.className = 'netline';
|
||||
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||
host.appendChild(d);
|
||||
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch]);
|
||||
const paint = list => {
|
||||
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
|
||||
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
|
||||
: '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
|
||||
};
|
||||
paint(NET_FALLBACK);
|
||||
networkSites().then(paint);
|
||||
}
|
||||
// pages with their own footer (the members area) get the network line too
|
||||
function decorateFooters() { document.querySelectorAll('footer.bo-pagefoot').forEach(f => { const w = document.createElement('div'); w.style.width = '100%'; f.appendChild(w); renderNetworkLine(w); }); }
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', decorateFooters); else decorateFooters();
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
@@ -91,7 +120,7 @@ window.IAP = (function () {
|
||||
case 'AdminPaid': return '🏛 platform fee settled: ' + pol(ev.amountWei);
|
||||
case 'BuyerCounted': return '⭐ ' + nm(ev.sponsorId) + ' now has ' + ev.newCount + ' qualifying buyer(s)';
|
||||
case 'MemberActivated': return '👤 ' + nm(ev.id) + ' activated a payout wallet';
|
||||
case 'AwardPaid': return '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
|
||||
case 'AwardPaid': return ev.override ? '🏅 Level 4 override' + (ev.overrideWeek ? ' (week of ' + ev.overrideWeek + ')' : '') + ': ' + pol(ev.amountWei) + ' → ' + nm(ev.toId) : '🎁 award: ' + pol(ev.amountWei) + ' → ' + nm(ev.toId);
|
||||
case 'CreditsConsumed': return '📣 ' + nm(ev.memberId) + ' ran ads: −' + ev.amount.toLocaleString() + ' credits';
|
||||
case 'PriceCached': return '🔮 oracle price refreshed';
|
||||
case 'FallbackPriceUsed': return '🔮 cached price bridged an oracle gap';
|
||||
@@ -189,7 +218,7 @@ window.IAP = (function () {
|
||||
await formSettled();
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const r = await (await fetch('/api/auth/email/start', { method: 'POST', headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ email, fts: FORM_TS, hp_field_x9: hpValue(o.honeypot), pick }) })).json();
|
||||
body: JSON.stringify({ email, fts: FORM_TS, fage: Date.now() - FORM_TS, hp_field_x9: hpValue(o.honeypot), pick, ref: o.ref || null, angle: o.angle || null, lsclk: o.lsclk || null }) })).json(); // ref = the join page's own link token, so the sponsor survives a lost cookie
|
||||
if (r.challenge && o.host) { pick = await iconCheck(o.host, r.challenge, r.error); continue; }
|
||||
if (r.error) throw new Error(r.error);
|
||||
return r;
|
||||
@@ -247,7 +276,7 @@ window.IAP = (function () {
|
||||
: '<input id="dlgInput" type="' + (o.type === 'number' ? 'number' : 'text') + '" ' + (o.type === 'number' ? 'inputmode="decimal" min="0" step="any" ' : '') + 'value="' + esc(o.value) + '" placeholder="' + esc(o.placeholder) + '" style="width:100%;margin-top:12px" autocomplete="off">';
|
||||
back.innerHTML = '<div class="modal-card" role="dialog" aria-modal="true">' + (o.title ? '<h3 style="margin:0 0 8px">' + esc(o.title) + '</h3>' : '')
|
||||
+ (o.text ? '<p class="muted small" style="margin:0;white-space:pre-line">' + esc(o.text) + '</p>' : '') + field
|
||||
+ '<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap"><button type="button" class="btn sec small" id="dlgCancel">' + esc(o.cancel || 'Cancel') + '</button><button type="button" class="btn small" id="dlgOk">' + esc(o.ok || 'OK') + '</button></div></div>';
|
||||
+ '<div style="display:flex;gap:10px;justify-content:flex-end;margin-top:16px;flex-wrap:wrap">' + (o.noCancel ? '' : '<button type="button" class="btn sec small" id="dlgCancel">' + esc(o.cancel || 'Cancel') + '</button>') + '<button type="button" class="btn small" id="dlgOk">' + esc(o.ok || 'OK') + '</button></div></div>';
|
||||
document.body.appendChild(back);
|
||||
const inp = back.querySelector('#dlgInput');
|
||||
const done = v => { document.removeEventListener('keydown', onKey); back.remove(); resolve(v); };
|
||||
@@ -255,12 +284,69 @@ window.IAP = (function () {
|
||||
const onKey = e => { if (e.key === 'Escape') { e.preventDefault(); done(o.type === 'none' ? false : null); } else if (e.key === 'Enter' && o.type !== 'textarea') { e.preventDefault(); okv(); } };
|
||||
document.addEventListener('keydown', onKey);
|
||||
back.querySelector('#dlgOk').addEventListener('click', okv);
|
||||
back.querySelector('#dlgCancel').addEventListener('click', () => done(o.type === 'none' ? false : null));
|
||||
if (back.querySelector('#dlgCancel')) back.querySelector('#dlgCancel').addEventListener('click', () => done(o.type === 'none' ? false : null));
|
||||
back.addEventListener('click', e => { if (e.target === back) done(o.type === 'none' ? false : null); });
|
||||
setTimeout(() => { if (inp) { inp.focus(); if (inp.select && o.type !== 'textarea') inp.select(); } else back.querySelector('#dlgOk').focus(); }, 30);
|
||||
});
|
||||
}
|
||||
function ask(o) { return dialog(Object.assign({ type: 'text', value: '', placeholder: '' }, o || {})); }
|
||||
function confirmBox(text, o) { return dialog(Object.assign({ type: 'none', text, ok: 'Yes', cancel: 'No' }, o || {})); }
|
||||
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $ };
|
||||
// ── appearance (2026-11-01): Light / Dark / Auto, mirrored from LinkSpin. The head script (themehead.js) owns window.IAPTheme and
|
||||
// localStorage iap.theme; this paints every .theme-seg on the page (member-area header, Profile pane, admin header), saves a
|
||||
// click to the account when signed in (POST /api/my/profile {theme}), and at sign-in lets the account value win over the local
|
||||
// one (a local choice is pushed up when the account has none yet). Pages without a .theme-seg still get the theme from the head script.
|
||||
const THEME_VALUES = ['light', 'dark', 'auto'];
|
||||
function storedTheme() { try { const v = localStorage.getItem('iap.theme'); return THEME_VALUES.includes(v) ? v : null; } catch (e) { return null; } }
|
||||
function paintTheme() { const c = window.IAPTheme ? IAPTheme.get() : 'dark'; document.querySelectorAll('.theme-seg [data-theme]').forEach(b => { const on = b.dataset.theme === c; b.classList.toggle('on', on); b.setAttribute('aria-pressed', on ? 'true' : 'false'); }); }
|
||||
const saveTheme = v => fetch('/api/my/profile', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ theme: v }) }).catch(() => {});
|
||||
function themeSync(m) { if (!window.IAPTheme) return; const acct = m && m.signedIn && THEME_VALUES.includes(m.theme) ? m.theme : null; const local = storedTheme(); if (acct) { if (acct !== local) IAPTheme.set(acct, true); } else if (m && m.signedIn && local) saveTheme(local); paintTheme(); }
|
||||
// the controls only exist on signed-in surfaces (member-area shell, admin), so a click always tries the save; signed out it is a harmless 401
|
||||
document.addEventListener('click', e => { const b = e.target.closest && e.target.closest('.theme-seg [data-theme]'); if (!b || !window.IAPTheme) return; const v = b.dataset.theme; IAPTheme.set(v); saveTheme(v); });
|
||||
window.addEventListener('iap-theme', paintTheme);
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', paintTheme); else paintTheme();
|
||||
return { getConfig, fmtPol, fmtUsd, status, renderNav, refreshNavWallet, describeEvent, feedRow, adSlot, reportAd, requestCode, launchChecks, launchToggle, ask, confirmBox, $, themeSync, paintTheme,
|
||||
guard: { FORM_TS, iconCheck, hpValue, formSettled } }; // guard: the sign-up walls, reused by the support form and the chatbot hand-off
|
||||
})();
|
||||
// shown inside someone else's frame (traffic exchanges, 2026-10-03): sign-in, join and off-site links open in a new tab,
|
||||
// because browsers refuse our session cookie inside another site's frame
|
||||
(function () {
|
||||
var framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
|
||||
if (!framed) return;
|
||||
// the sponsor this page was opened for (?ref=, /join/<tok>, /wall/<tok>); its cookie was refused in the frame, so the
|
||||
// new tab gets it in the link and the viral-link rule sets it there
|
||||
var ref = ''; try { ref = new URLSearchParams(location.search).get('ref') || (location.pathname.match(/^\/(?:join|wall)\/([^/?#]+)/) || [])[1] || ''; } catch (e) {}
|
||||
ref = String(ref).toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
|
||||
document.addEventListener('click', function (e) {
|
||||
var a = e.target && e.target.closest && e.target.closest('a[href]'); if (!a) return;
|
||||
var h = a.getAttribute('href') || ''; if (h.charAt(0) === '#' || /^javascript:/i.test(h)) return;
|
||||
var sign = a.host === location.host && /^\/(my|join|signin|login|from|admin)(\/|$)/.test(a.pathname);
|
||||
if (sign && ref && a.pathname === '/my' && !/[?&]ref=/.test(a.search)) a.search = (a.search ? a.search + '&' : '?') + 'ref=' + ref;
|
||||
if (sign || a.host !== location.host) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||
}, true);
|
||||
})();
|
||||
// Level 4 override copy (2026-10-23): blocks marked data-when="override-live" stay hidden until the site setting
|
||||
// overrideMode is 'live' and overrideGoLive is set; [data-ov-start] gets the start date in Central time
|
||||
(function () {
|
||||
var els = document.querySelectorAll('[data-when="override-live"]'); if (!els.length || !window.IAP) return;
|
||||
IAP.getConfig().then(function (c) {
|
||||
if (String(c.overrideMode || '') !== 'live' || !Number(c.overrideGoLive)) return;
|
||||
var d = new Date(Number(c.overrideGoLive)).toLocaleDateString('en-US', { timeZone: 'America/Chicago', month: 'long', day: 'numeric', year: 'numeric' });
|
||||
document.querySelectorAll('[data-ov-start]').forEach(function (e) { e.textContent = d; });
|
||||
els.forEach(function (e) { e.hidden = false; });
|
||||
}).catch(function () {});
|
||||
})();
|
||||
|
||||
// Network links (2026-11-13): a click on a link to LinkSpin goes through /go/linkspin, which signs a signed-in member in over there and is a
|
||||
// plain redirect for everyone else. Rewritten at click time only, so links people copy to share stay clean. data-nogo opts a link out.
|
||||
(function () {
|
||||
if (window.__netlinks) return; window.__netlinks = 1;
|
||||
const HOSTS = ['linkspin.app', 'www.linkspin.app'];
|
||||
document.addEventListener('click', e => {
|
||||
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
|
||||
const a = e.target && e.target.closest ? e.target.closest('a[href]') : null;
|
||||
if (!a || a.hasAttribute('download') || a.hasAttribute('data-nogo')) return;
|
||||
let u; try { u = new URL(a.href); } catch (x) { return; }
|
||||
if (u.protocol !== 'https:' || !HOSTS.includes(u.hostname)) return;
|
||||
a.href = '/go/linkspin?to=' + encodeURIComponent(u.pathname + u.search + u.hash);
|
||||
}, true);
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// Conversion tracking guide (/conversion-tracking, 2026-10-24): the Copy buttons on the code examples. Copies the text of
|
||||
// the <pre> in the same box (placeholders included). Frame handling (traffic exchanges) is common.js's, like every page.
|
||||
(function () {
|
||||
function flash(b, t) { var o = b.getAttribute('data-label') || b.textContent; b.setAttribute('data-label', o); b.textContent = t; setTimeout(function () { b.textContent = o; }, 1600); }
|
||||
document.querySelectorAll('[data-copy]').forEach(function (b) {
|
||||
b.addEventListener('click', function () {
|
||||
var box = b.closest('.cg-code'); var pre = box && box.querySelector('pre'); if (!pre) return;
|
||||
var text = pre.textContent;
|
||||
var done = function () { flash(b, 'Copied'); };
|
||||
var fallback = function () {
|
||||
try { var r = document.createRange(); r.selectNodeContents(pre); var s = window.getSelection(); s.removeAllRanges(); s.addRange(r); var ok = document.execCommand && document.execCommand('copy'); flash(b, ok ? 'Copied' : 'Selected'); }
|
||||
catch (e) { flash(b, 'Select and copy'); }
|
||||
};
|
||||
try { if (navigator.clipboard && navigator.clipboard.writeText) navigator.clipboard.writeText(text).then(done, fallback); else fallback(); } catch (e) { fallback(); }
|
||||
});
|
||||
});
|
||||
})();
|
||||
|
After Width: | Height: | Size: 72 KiB |
@@ -0,0 +1,81 @@
|
||||
/* Spooky Doors door: one verified visit (a member's page or ad), then back to the street with a signed receipt. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var q = new URLSearchParams(location.search); var tok = q.get('t') || '';
|
||||
var nonce = '', tokRet = '', game = 'spookydoors'; try { var claims = JSON.parse(atob(tok.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'))); nonce = claims.nonce || ''; tokRet = claims.ret || ''; if (claims.game === 'roadagent') game = 'roadagent'; } catch (e) {}
|
||||
// Road Agent (2026-10-07) uses the same door as a fuel stop; the words change, the round trip does not
|
||||
var RA = game === 'roadagent';
|
||||
var W = RA ? { back: 'Back to the highway', unit: 'Fuel stop', name: 'Road Agent', home: 'https://roadagent.app/play', open: 'Open this page from a fuel stop in Road Agent.', waiting: 'Pulling into the fuel stop…', treat: ' has fuel for you.', treatSomeone: 'Visit counted. Fuel loaded.', house: 'A house ad: a smaller fuel bonus while the sponsors’ ads are resting. Stay on this page.', capTitle: 'That is tonight’s fuel stops', cap: 'You have used every fuel stop for today. Your scrap is safe, and the pumps open again at midnight Central.', none: 'This stop is closed: there are no sponsor pages or videos left for you right now. No fuel here, and this stop does not count. Head back and try again later.', noneTitle: 'Pumps are closed' }
|
||||
: { back: 'Back to the street', unit: 'Door', name: 'Spooky Doors', home: 'https://spookydoors.com/play', open: 'Open this page by knocking on a door in Spooky Doors.', waiting: 'Someone is coming to the door…', treat: ' has a treat for you.', treatSomeone: 'Visit counted. Someone has a treat for you.', house: 'A house ad: a smaller treat while the street’s ads are resting. Stay on this page.', capTitle: 'That is tonight’s doors', cap: 'You have knocked on every door for today. Your candy is safe, and the doors open again at midnight Central.', none: 'The lights are out at this house: there are no member pages or videos left for you right now. No candy here, and this door does not count. Head back and try the next house.', noneTitle: 'Nobody’s home' };
|
||||
if (RA) { document.body.classList.add('ra'); var bb0 = document.getElementById('sdBrand'); if (bb0) bb0.textContent = W.name; var t0 = document.getElementById('sdTitle'); if (t0) t0.textContent = W.waiting; document.title = 'Fuel stop · Road Agent verified visit'; var kk = document.querySelector('#sdFrame h1'); if (kk) { kk.textContent = 'Fuel stop'; kk.nextElementSibling.textContent = 'Pulling in...'; } }
|
||||
// every dead end on this page keeps a way back to the street
|
||||
var gameHome = tokRet ? tokRet.split('?')[0] : W.home;
|
||||
var dwell = 8, left = 8, timer = null;
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
|
||||
function msg(title, text, backUrl, auto) {
|
||||
$('sdFrame').innerHTML = '<div class="dr-msg"><div class="in"><h1>' + esc(title) + '</h1><p>' + esc(text) + '</p></div></div>';
|
||||
$('sdDone').hidden = true; $('sdCheck').hidden = true; $('sdRow').hidden = true;
|
||||
var b = $('sdBack'); b.hidden = false; var to = backUrl || gameHome; b.textContent = W.back; b.onclick = function () { location.href = to; };
|
||||
if (auto && backUrl) setTimeout(function () { location.href = backUrl; }, 2500);
|
||||
}
|
||||
function api(p, body) { return fetch(p, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {}).then(function (r) { return r.json(); }); }
|
||||
function ring() { $('sdN').textContent = left; $('sdRing').style.setProperty('--p', ((dwell - left) / dwell * 100) + '%'); }
|
||||
function tick() {
|
||||
if (document.hidden) return; // the timer only runs while the page is in front
|
||||
var vid = document.getElementById('sdVideo'); if (vid && (vid.paused || vid.ended && left > 1)) return; // a video must actually be playing
|
||||
left--; if (left > 0) return ring();
|
||||
clearInterval(timer); ring(); $('sdHint').textContent = 'One quick check to count the visit:';
|
||||
challenge();
|
||||
}
|
||||
function challenge() {
|
||||
api('/api/door/challenge?n=' + encodeURIComponent(nonce)).then(function (c) {
|
||||
if (c.early) { setTimeout(challenge, (c.wait || 1) * 1000 + 300); return; }
|
||||
if (c.error) { $('sdHint').textContent = c.error; return; }
|
||||
$('sdPrompt').textContent = 'Tap the ' + c.prompt + ':'; var w = $('sdOpts'); w.innerHTML = '';
|
||||
c.options.forEach(function (em, i) { var b = document.createElement('button'); b.type = 'button'; b.textContent = em; b.setAttribute('aria-label', 'Option ' + (i + 1)); b.addEventListener('click', function () { answer(i); }); w.appendChild(b); });
|
||||
$('sdCheck').hidden = false;
|
||||
});
|
||||
}
|
||||
function answer(i) {
|
||||
api('/api/door/done', { n: nonce, answer: i }).then(function (r) {
|
||||
if (r.error) {
|
||||
if (r.retry) return challenge();
|
||||
if (r.cap && r.ret) return msg(W.capTitle, W.cap, r.ret, true);
|
||||
$('sdHint').textContent = r.error; $('sdCheck').hidden = true; var bb = $('sdBack'); bb.hidden = false; bb.onclick = function () { location.href = gameHome; }; return;
|
||||
}
|
||||
$('sdCheck').hidden = true; $('sdHint').textContent = r.golden ? 'Visit counted. Golden Door! ' + (r.host ? '@' + r.host + ' has' : 'Someone has') + ' a treat for you, plus ' + (r.bonus || 0) + ' bonus candy.' : r.house ? 'Visit counted. A smaller treat from ' + (r.program || 'the house') + ' is on its way.' : r.host ? 'Visit counted. @' + r.host + W.treat : W.treatSomeone;
|
||||
var b = $('sdDone'); b.disabled = false; b.textContent = W.back; b.onclick = function () { location.href = r.ret; };
|
||||
setTimeout(function () { location.href = r.ret; }, 1200);
|
||||
});
|
||||
}
|
||||
if (!tok) return msg(RA ? 'No fuel stop here' : 'No door here', W.open);
|
||||
api('/api/door/open?t=' + encodeURIComponent(tok)).then(function (r) {
|
||||
if (r.error) return msg('Door link problem', r.error);
|
||||
if (r.done) { location.href = r.ret; return; }
|
||||
if (r.none) return r.why === 'cap'
|
||||
? msg(W.capTitle, W.cap + ' Your regular InstantAdPay visits are not affected.', r.ret, true)
|
||||
: msg(W.noneTitle, W.none, r.ret, true);
|
||||
dwell = r.dwell || 8; left = Math.max(1, dwell - (r.elapsed || 0));
|
||||
if (r.doors && r.doors.cap) { var ch = $('sdDoors'); ch.textContent = W.unit + ' ' + Math.min(r.doors.cap, (r.doors.used || 0) + 1) + ' of ' + r.doors.cap; ch.hidden = false; }
|
||||
var who = r.house ? 'House ad' : r.host ? '@' + r.host + (RA ? '’s stop' : '’s door') : (RA ? 'A sponsor’s stop' : 'A member’s door');
|
||||
if (r.golden) { document.body.classList.add('gold'); $('sdGold').hidden = false; who = 'Golden Door! ' + who; } // gold variant: bonus candy on this one
|
||||
if (r.mode === 'video') { // no member pages left: a member video ad instead
|
||||
$('sdTitle').textContent = who + ': ' + (r.title || 'member video'); $('sdUrl').textContent = 'video ad';
|
||||
$('sdHint').textContent = 'You have visited every member page running right now, so this ' + (RA ? 'stop' : 'door') + ' is a short member video. Keep it playing.';
|
||||
var v = document.createElement('video'); v.id = 'sdVideo'; v.src = r.video.url; v.autoplay = true; v.muted = true; v.playsInline = true; v.setAttribute('playsinline', ''); v.loop = true; v.controls = false;
|
||||
v.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000';
|
||||
$('sdFrame').innerHTML = ''; $('sdFrame').appendChild(v);
|
||||
var un = document.createElement('button'); un.type = 'button'; un.textContent = 'Tap for sound'; un.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:2;padding:8px 12px;border-radius:8px;border:0;background:rgba(0,0,0,.6);color:#fff;font:600 12px system-ui';
|
||||
un.onclick = function () { v.muted = false; v.play().catch(function () {}); un.remove(); }; $('sdFrame').appendChild(un);
|
||||
v.play().catch(function () { $('sdHint').textContent = 'Tap the video to start it. The timer runs while it plays.'; v.onclick = function () { v.play(); }; });
|
||||
ring(); timer = setInterval(tick, 1000); return;
|
||||
}
|
||||
$('sdTitle').textContent = who + ': ' + (r.title || 'member site'); try { $('sdUrl').textContent = new URL(r.target).hostname; } catch (e) {}
|
||||
if (r.house) $('sdHint').textContent = W.house;
|
||||
if (r.golden) $('sdHint').textContent = 'A Golden Door: this one comes with ' + (r.bonus || 0) + ' bonus candy. Stay on this page; the timer only runs while it is in front.';
|
||||
var f = document.createElement('iframe'); f.src = r.target; f.setAttribute('referrerpolicy', 'no-referrer'); f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups'); $('sdFrame').innerHTML = ''; $('sdFrame').appendChild(f);
|
||||
var o = $('sdOpen'); o.href = r.target; o.hidden = false;
|
||||
ring(); timer = setInterval(tick, 1000);
|
||||
}).catch(function () { msg(RA ? 'Could not open the fuel stop' : 'Could not open the door', RA ? 'Check your connection and go back to the highway.' : 'Check your connection and go back to the street.'); });
|
||||
})();
|
||||
@@ -0,0 +1,82 @@
|
||||
// The Engine Room (2026-10-24). The SAME file ships in InstantAdPay (Members > Engine Room) and LinkSpin (Ads screen panel).
|
||||
// Plain dials, real numbers, colour only for warnings. Renders into #erRoot from /api/my/engine; hidden while the
|
||||
// refuelStreak switch is off. Unlocked by the first counted refuel, greyed "Refuel to start your engine" until then.
|
||||
(function () {
|
||||
const root = document.getElementById('erRoot'); if (!root) return;
|
||||
const host = document.getElementById(root.dataset.host || 'erPanel');
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||
// a link on this site becomes a plain path; a link to the other site carries ?from=<this site>&task=<job> so the other
|
||||
// site opens with an arrival strip naming the job and its first step (2026-10-25, Marty lost the thread on LinkSpin)
|
||||
const TASK = { tracking: 'conversions', start: 'refuel', refuel: 'refuel', pitstop: 'refuel', bannerspin: 'bannerspin', testing: 'testing', relaunch: 'ads', topup: 'ads', cut: 'ads', cruise: 'ads' };
|
||||
let FROM = 'iap';
|
||||
const siteOf = u => /linkspin/i.test(u.host) ? 'linkspin' : 'iap'; // which site a link belongs to, by its host (also right on a local copy)
|
||||
// a link to the other site goes through this site's /go/<other> hop (network sign-in, 2026-11-12): the member arrives signed in
|
||||
const go = (url, task) => { try { const u = new URL(url); if (u.host === location.host || siteOf(u) === FROM) return u.pathname + u.search + u.hash; if (task) { u.searchParams.set('from', FROM); u.searchParams.set('task', task); } return '/go/' + (FROM === 'iap' ? 'linkspin' : 'iap') + '?to=' + encodeURIComponent(u.pathname + u.search + u.hash); } catch (e) { return url; } };
|
||||
// "Refuel LinkSpin this cycle..." gets a way there (2026-10-25): the other site's buy screen, tagged for its arrival strip
|
||||
const otherBuy = note => { const m = /^Refuel (LinkSpin|InstantAdPay) /.exec(note || ''); if (!m) return '';
|
||||
const url = m[1] === 'LinkSpin' ? 'https://linkspin.app/credits#refuel' : 'https://instantadpay.com/my#buy';
|
||||
return ' <a href="' + esc(go(url, 'refuel')) + '">Refuel ' + m[1] + (ext(url) ? ' ↗' : '') + '</a>'; };
|
||||
const ext = url => { try { const u = new URL(url); return u.host !== location.host && siteOf(u) !== FROM; } catch (e) { return false; } };
|
||||
const css = '.er{display:grid;gap:14px}.er-locked{opacity:.45;filter:grayscale(1);pointer-events:none}.er-dials{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,180px),1fr));gap:12px}'
|
||||
+ '.er-dial{border:1px solid rgba(127,127,127,.3);border-radius:10px;padding:10px 12px;text-align:center;min-width:0}.er-dial svg{width:100%;max-width:200px;height:auto;display:block;margin:0 auto}'
|
||||
+ '.er-dial .v{font-size:22px;font-weight:700;margin-top:-6px}.er-dial .c{font-size:12px;opacity:.8}.er-row{display:flex;flex-wrap:wrap;gap:8px}'
|
||||
+ '.er-light{display:flex;gap:6px;align-items:center;border:1px solid rgba(127,127,127,.3);border-radius:999px;padding:4px 10px;font-size:12.5px}.er-dot{width:10px;height:10px;border-radius:50%;background:rgba(127,127,127,.45);flex:none}'
|
||||
+ '.er-dot.on{background:var(--warn,#e8a317)}.er-dot.green{background:var(--ok,#2fa36b)}.er-dot.amber{background:var(--warn,#e8a317)}.er-dot.grey{background:rgba(127,127,127,.45)}.er-parts{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,210px),1fr));gap:8px}'
|
||||
+ '.er-part{border:1px solid rgba(127,127,127,.3);border-radius:8px;padding:8px 10px;font-size:13px;display:grid;gap:3px;min-width:0}.er-part b{display:flex;flex-wrap:wrap;gap:2px 6px;align-items:center}.er-next{border:1px solid rgba(127,127,127,.4);border-radius:10px;padding:12px;display:flex;gap:12px;align-items:center;flex-wrap:wrap}'
|
||||
+ '.er-next .w{flex:1 1 220px;font-size:13px}.er-h{font-size:12px;letter-spacing:.06em;text-transform:uppercase;opacity:.75;margin:0}.er-streak{font-size:13.5px;line-height:1.5}.er-goal{display:flex;gap:6px;align-items:center;justify-content:center;margin-top:6px;font-size:12px}.er-goal input{width:70px}';
|
||||
if (!document.getElementById('erCss')) { const st = document.createElement('style'); st.id = 'erCss'; st.textContent = css; document.head.appendChild(st); }
|
||||
// a plain 180-degree dial; pct null = no reading
|
||||
function dial(pct, value, caption, aria, warn) {
|
||||
const p = pct == null ? 0 : Math.max(0, Math.min(100, pct));
|
||||
const a = Math.PI * (1 - p / 100); const x = 100 + 80 * Math.cos(a), y = 100 - 80 * Math.sin(a);
|
||||
const col = warn ? 'var(--warn,#e8a317)' : 'currentColor';
|
||||
return '<div class="er-dial" role="img" aria-label="' + esc(aria) + '"><svg viewBox="0 0 200 112" aria-hidden="true"><path d="M20 100 A80 80 0 0 1 180 100" fill="none" stroke="rgba(127,127,127,.3)" stroke-width="14" stroke-linecap="round"/>'
|
||||
+ (pct == null ? '' : '<path d="M20 100 A80 80 0 0 1 ' + x.toFixed(1) + ' ' + y.toFixed(1) + '" fill="none" stroke="' + col + '" stroke-width="14" stroke-linecap="round"/>') + '</svg>'
|
||||
+ '<div class="v">' + esc(value) + '</div><div class="c">' + caption + '</div></div>';
|
||||
}
|
||||
function view(d) {
|
||||
const f = d.fuel, c = d.clicks, g = d.goals, s = d.streak;
|
||||
const fuelCap = (f.refuelCredits ? n(f.left) + ' of ' + n(f.refuelCredits) + ' credits this cycle' : n(f.left) + ' credits on both sites') + (f.daysLeft != null ? '<br>about ' + n(f.daysLeft) + ' days at your burn (' + n(f.burnPerDay) + ' a day)' : '');
|
||||
const fuelAria = 'Fuel left: ' + n(f.left) + ' credits' + (f.pct != null ? ', ' + f.pct + ' percent of this cycle’s refuel' : '') + (f.daysLeft != null ? ', about ' + f.daysLeft + ' days at your current burn' : '');
|
||||
const clickCap = (c.prevWeek ? 'last week: ' + n(c.prevWeek) + ' (half way = the same)<br>' : '') + (c.per1000 != null ? n(c.per1000) + ' clicks per 1,000 credits' : 'clicks per 1,000 credits: not enough delivery yet') + '<br>all ads, both sites';
|
||||
const goalCap = (g.month == null ? 'LinkSpin did not answer' : g.tracking ? (g.target ? 'goal: ' + n(g.target) + ' this month' : 'set a goal for the month') : 'set up conversion tracking') + '<span class="er-goal"><label>goal <input type="number" min="0" max="100000" data-er-goal value="' + (g.target || '') + '" aria-label="Your goal for this month"></label><button class="btn small sec" type="button" data-er-save>Save</button></span>';
|
||||
const dials = '<div class="er-dials">'
|
||||
+ dial(f.pct, f.pct != null ? f.pct + '%' : n(f.left), 'Fuel left<br>' + fuelCap, fuelAria, f.daysLeft != null && f.daysLeft < 5)
|
||||
+ dial(c.pct, n(c.week), 'Clicks this week<br>' + clickCap, 'Clicks this week: ' + n(c.week) + (c.prevWeek ? ', last week ' + n(c.prevWeek) : '') + (c.per1000 != null ? ', ' + c.per1000 + ' per 1,000 credits' : ''), false)
|
||||
+ dial(g.pct, g.month == null ? '?' : n(g.month), 'Goals this month<br>' + goalCap, 'Goals this month: ' + (g.month == null ? 'unknown' : g.month) + (g.target ? ' of ' + g.target : ''), false) + '</div>';
|
||||
const streak = '<div class="er-streak"><p class="er-h">Streak</p>' + (s.active ? '<b>' + s.months + ' month' + (s.months === 1 ? '' : 's') + '</b>' + (s.both ? ', both engines this cycle' : '') + '. Refuel day <b>' + esc(s.refuelDay) + '</b>, grace to ' + esc(s.graceEnd) + ' (Central).'
|
||||
+ (typeof s.note === 'string' ? (s.note ? ' ' + esc(s.note) + otherBuy(s.note) : '') : s.next ? (s.windowOpen ? ' Window open: next refuel +' + s.next.single + '% (+' + s.next.both + '% on each with both).' : s.both ? ' Both engines fueled this cycle.' : s.next.secondEngine ? ' Refuel the other site this cycle for +' + s.next.secondEngine + '% on both.' : '') : '') // s.note from engine.js (2026-10-24: no 'refuel the other site' once both are done)
|
||||
+ (s.pitStop ? ' Pit Stop: +' + s.pitStop.pct + '% ' + (s.pitStop.iap || s.pitStop.linkspin ? 'available' : 'used') + ' this cycle.' : '') + (s.best > s.months ? ' Best: ' + s.best + '.' : '') : 'Not started.') + '</div>';
|
||||
const warns = '<div><p class="er-h">Warning lights</p><div class="er-row">' + d.warnings.map(w => '<span class="er-light" title="' + esc(w.note) + '"><span class="er-dot' + (w.on ? ' on' : '') + '" aria-hidden="true"></span>' + esc(w.label) + ': ' + (w.on ? '<b>on</b>' : 'off') + '<span class="sr" style="position:absolute;left:-9999px"> (' + esc(w.note) + ')</span></span>').join('') + '</div></div>';
|
||||
const parts = '<div><p class="er-h">The six parts</p><div class="er-parts">' + d.parts.map(p => '<div class="er-part"><b><span class="er-dot ' + p.state + '" aria-hidden="true"></span>' + esc(p.label) + ' <span style="font-weight:400;opacity:.75">(' + (p.state === 'green' ? 'working' : p.state === 'amber' ? 'needs attention' : 'not started') + ')</span></b><span>' + esc(p.note) + '</span>'
|
||||
+ (p.state !== 'green' && p.link ? '<a href="' + esc(go(p.link, p.key)) + '">' + (p.state === 'grey' ? 'Set it up' : 'Fix it') + (ext(p.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') + ' ↗' : '') + '</a>' : '') + '</div>').join('') + '</div></div>';
|
||||
const nextLink = go(d.next.link, TASK[d.next.key]);
|
||||
const next = '<div class="er-next"><div class="w"><p class="er-h">Next move</p><b>' + esc(d.next.label) + '</b><br>' + esc(d.next.why)
|
||||
+ (d.next.guide ? '<br><a href="' + esc(d.next.guide) + '" target="_blank" rel="noopener" style="font-size:12.5px">' + (d.next.key === 'tracking' ? 'Step-by-step setup guide' : 'How the Refuel streak works') + '</a>' : '') + '</div>'
|
||||
+ '<a class="btn' + (d.locked ? '' : ' pri') + '" href="' + esc(nextLink) + '">' + esc(d.next.label) + (ext(d.next.link) ? ' on ' + (FROM === 'iap' ? 'LinkSpin' : 'InstantAdPay') : '') + '</a></div>';
|
||||
const how = d.next.guide === '/refuel' ? '' : '<p style="margin:0;font-size:12.5px"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
|
||||
if (d.locked) return '<div class="er">' + next + how + '<div class="er-locked" aria-hidden="true">' + dials + warns + parts + '</div></div>';
|
||||
return '<div class="er">' + next + dials + streak + how + warns + parts + '<p class="small muted" style="margin:0;font-size:12px;opacity:.75">Numbers cover InstantAdPay and LinkSpin together' + (d.sites && (!d.sites.iap || !d.sites.linkspin) ? ' (one site did not answer just now)' : '') + '. Credits buy ad delivery only.</p></div>';
|
||||
}
|
||||
async function load(fresh) {
|
||||
try {
|
||||
const d = await (await fetch('/api/my/engine' + (fresh ? '?fresh=1' : ''), { cache: 'no-store' })).json();
|
||||
window.FUEL = window.FUEL || {}; window.FUEL.engine = d;
|
||||
if (!d || !d.on) { if (host) host.hidden = true; return; }
|
||||
if (host) host.hidden = false;
|
||||
if (d.error) { root.innerHTML = '<p class="small muted">' + esc(d.error) + '</p>'; return; }
|
||||
FROM = d.site === 'linkspin' ? 'linkspin' : 'iap';
|
||||
root.innerHTML = view(d);
|
||||
const save = root.querySelector('[data-er-save]');
|
||||
if (save) save.addEventListener('click', async () => {
|
||||
const v = root.querySelector('[data-er-goal]').value; save.disabled = true;
|
||||
try { const r = await (await fetch('/api/my/engine/goal', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ goal: Number(v) || 0 }) })).json(); if (r.error) throw new Error(r.error); load(true); }
|
||||
catch (e) { save.disabled = false; save.textContent = 'Try again'; }
|
||||
});
|
||||
} catch (e) { if (host) host.hidden = true; }
|
||||
}
|
||||
window.ENGINE_ROOM = { load };
|
||||
load(); setInterval(() => { if (!document.hidden) load(); }, 120000);
|
||||
window.addEventListener('cr:signedin', () => load(true)); // LinkSpin's in-shell sign-in: the panel loaded signed out
|
||||
})();
|
||||
@@ -0,0 +1,113 @@
|
||||
// Fuel Your Offers (2026-10-24): the Refuel card on the Overview. Hidden while the refuelStreak switch is off
|
||||
// (/api/my/refuel answers { on:false }). Everything here is ad credits, never cash.
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const n = v => Number(v || 0).toLocaleString('en-US');
|
||||
const goBuy = () => { const m = document.querySelector('.bo-menu [data-pane="buy"]'); if (m) m.click(); else location.hash = '#buy'; };
|
||||
window.FUEL = window.FUEL || {};
|
||||
const HOW = '<p class="small" style="margin:8px 0 0"><a href="/refuel" target="_blank" rel="noopener">How the Refuel streak works</a></p>'; // the member guide (2026-10-24)
|
||||
|
||||
function siteLine(name, s, minUsd) {
|
||||
if (s && s.refueled) return '<li><b>' + name + '</b>: refueled ' + esc(s.dayLabel ? 'on ' + s.dayLabel : '') + ', +' + s.pct + '% (' + n(s.bonus) + ' bonus credits)</li>';
|
||||
return '<li><b>' + name + '</b>: not yet this cycle (a $' + minUsd + '+ package counts)</li>';
|
||||
}
|
||||
function cardHtml(v) {
|
||||
const head = '<div class="card-head"><h3>⛽ Monthly Refuel</h3><span class="sub">' + (v.active ? 'streak: ' + v.streak + ' month' + (v.streak === 1 ? '' : 's') : 'not started') + '</span></div>';
|
||||
if (!v.active) {
|
||||
const lapsed = v.started ? '<p>Your last streak ended' + (v.misses && v.misses[0] ? ' after ' + esc(v.misses[0].day) : '') + '. Your next package of $' + v.minUsd.iap + '+ here (or $' + v.minUsd.linkspin + '+ on LinkSpin) starts it again at month 1.</p>' : '';
|
||||
return head + (lapsed || '<p>Refuel your ads every month and the bonus grows. A package of <b>$' + v.minUsd.iap + ' or more</b> here, or $' + v.minUsd.linkspin + ' or more on LinkSpin, starts your streak and sets your own refuel day.</p>')
|
||||
+ '<p class="small">Month 1 <b>+' + v.ladder.single[0] + '%</b> bonus ad credits, month 2 +' + v.ladder.single[1] + '%, month 3 +' + v.ladder.single[2] + '%, month 4 and up +' + v.ladder.single[3] + '%. Refuel both InstantAdPay and LinkSpin in the same cycle and each gets +' + v.ladder.both.join('%, +') + '%. It stacks on Five Dollar Friday and Wired Wednesday.</p>'
|
||||
+ '<button class="btn" type="button" data-fuel-buy>Start my streak</button>' + HOW;
|
||||
}
|
||||
const c = v.cycle || {};
|
||||
const when = v.windowOpen
|
||||
? '<p><b>Your refuel window is open.</b> Refuel day: <b>' + esc(v.refuelDayLabel) + '</b>, grace to ' + esc(v.graceLabel) + ' (Central time). Your next refuel earns <b>+' + v.next.single + '%</b>, or +' + v.next.both + '% on each site when you refuel both.</p>'
|
||||
: '<p>Next refuel day: <b>' + esc(v.refuelDayLabel) + '</b> (Central time). The window opens ' + esc(v.opensLabel) + ' and the grace runs to ' + esc(v.graceLabel) + '.</p>';
|
||||
const sites = c.month ? '<p class="small" style="margin-bottom:2px">This cycle (month ' + c.month + (c.both ? ', both engines' : '') + '):</p><ul class="small" style="margin-top:0">' + siteLine('InstantAdPay', c.iap, v.minUsd.iap) + siteLine('LinkSpin', c.linkspin, v.minUsd.linkspin) + '</ul>' : '';
|
||||
let twin = '';
|
||||
if (!v.windowOpen && c.month && !c.both) twin = '<p class="small">Refuel ' + (c.iap && c.iap.refueled ? 'LinkSpin ($' + v.minUsd.linkspin + '+)' : 'InstantAdPay ($' + v.minUsd.iap + '+)') + ' before ' + esc(v.opensLabel) + ' and both sites move to <b>+' + v.next.secondEngine + '%</b>; the one you already refueled is topped up to match.'
|
||||
// the second engine is on the other site: a direct way there (2026-10-25), landing on LinkSpin's Refuel panel with an arrival strip
|
||||
+ (c.iap && c.iap.refueled ? ' <a href="/go/linkspin?to=%2Fcredits%3Ffrom%3Diap%26task%3Drefuel%23refuel" target="_blank" rel="noopener">Refuel LinkSpin ↗</a> (same email signs you in)' : '') + '</p>';
|
||||
let pit = '';
|
||||
if (v.pitStop) {
|
||||
const here = v.pitStop.iap ? 'available here (+' + v.pitStop.pct + '% on a $' + v.minUsd.iap + '+ top-up, once this cycle)' : v.pitStop.usedIap ? 'used here this cycle' : null;
|
||||
if (here) pit = '<p class="small"><b>Pit Stop:</b> ' + here + '. It keeps your ads running between refuel days; it does not count as your refuel.</p>';
|
||||
}
|
||||
const miss = '<p class="small muted">' + (v.freeMiss.available ? 'You have one free miss this year: if a grace passes, your streak is kept once.' : 'Your free miss for this year is used.') + (v.best > v.streak ? ' Best streak: ' + v.best + ' months.' : '') + '</p>';
|
||||
return head + when + sites + twin + pit + miss + '<button class="btn" type="button" data-fuel-buy>' + (v.windowOpen ? 'Refuel now' : 'Buy a package') + '</button>' + HOW;
|
||||
}
|
||||
async function loadRefuelCard() {
|
||||
const card = $('rfCard'); if (!card) return;
|
||||
try {
|
||||
const v = await (await fetch('/api/my/refuel', { cache: 'no-store' })).json();
|
||||
window.FUEL.refuel = v;
|
||||
if (!v || !v.on) { card.hidden = true; return; }
|
||||
card.innerHTML = cardHtml(v); card.hidden = false;
|
||||
card.querySelectorAll('[data-fuel-buy]').forEach(b => b.addEventListener('click', goBuy));
|
||||
} catch (e) { card.hidden = true; }
|
||||
}
|
||||
window.FUEL.loadRefuelCard = loadRefuelCard;
|
||||
loadRefuelCard(); setInterval(loadRefuelCard, 300000);
|
||||
|
||||
// ---- the Refuel Kit (Promo tools): this month's members-only banners, with your @name and a QR to your link ----
|
||||
const say = (m, k) => { try { IAP.status(m, k); } catch (e) {} };
|
||||
const IAP_SIZES = ['728x90', '300x250', '468x60', '160x600'];
|
||||
let kitData = null;
|
||||
async function render(month, size, variant) {
|
||||
const r = await (await fetch('/api/my/kits/render', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ month, size, variant }) })).json();
|
||||
if (r.error) throw new Error(r.error);
|
||||
return r;
|
||||
}
|
||||
// prefill the banner form under Campaigns with the kit image and the member's own link
|
||||
function useInCampaign(r, month) {
|
||||
const m = document.querySelector('.bo-menu [data-pane="campaigns"]'); if (m) m.click();
|
||||
setTimeout(() => {
|
||||
const set = (id, v, ev) => { const el = $(id); if (!el) return; el.value = v; el.dispatchEvent(new Event(ev || 'input', { bubbles: true })); };
|
||||
set('cType', 'banner', 'change'); set('cSize', r.size, 'change');
|
||||
set('cName', 'Refuel Kit ' + month + ' ' + r.size); set('cImage', r.abs); if (kitData && kitData.link) set('cTarget', kitData.link);
|
||||
const el = $('cName'); if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
say('Banner form filled with your kit banner and your link. Set a budget and launch.', 'ok');
|
||||
}, 250);
|
||||
}
|
||||
function kitHtml(k, d) {
|
||||
const head = '<div class="card-head"><h3>Refuel Kit: ' + esc(k.label) + (k.theme ? ' · ' + esc(k.theme) : '') + '</h3><span class="sub">' + (k.unlocked ? 'yours' : 'locked') + '</span></div>';
|
||||
if (!k.unlocked) return head + '<p class="small">Members-only banners for ' + esc(k.label) + '. Your next counted refuel unlocks them: a package of $20+ here, or $25+ on LinkSpin' + (d.nextRefuel ? ' (your refuel day: ' + esc(d.nextRefuel) + ')' : '') + '.</p>';
|
||||
return head + '<p class="small">Five banners with your ' + esc(d.name || 'name') + ' and a QR code to your own link drawn on each one. They stay yours after the month ends.' + (k.gif ? ' Your streak also unlocks the animated version.' : '') + '</p>'
|
||||
+ '<div class="kit-grid" style="display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,240px),1fr));gap:12px">'
|
||||
+ k.sizes.filter(s => s.ready).map(s => '<div class="kit-cell" data-month="' + esc(k.month) + '" data-size="' + s.size + '" style="border:1px solid var(--line,#2a4650);border-radius:8px;padding:8px;min-width:0">'
|
||||
+ '<div class="small muted">' + s.size + (s.size === '1200x630' ? ' (social posts)' : '') + '</div><div class="kit-img" style="margin:6px 0;min-height:30px"></div>'
|
||||
+ '<div style="display:flex;gap:6px;flex-wrap:wrap"><button class="btn small" type="button" data-kit="make">Make mine</button>'
|
||||
+ (k.gif && s.size !== '1200x630' ? '<button class="btn small sec" type="button" data-kit="gif">Animated</button>' : '') + '</div></div>').join('')
|
||||
+ '</div>';
|
||||
}
|
||||
function cellReady(cell, r, month) {
|
||||
const box = cell.querySelector('.kit-img');
|
||||
box.innerHTML = '<img src="' + esc(r.url) + '" alt="Your ' + esc(r.size) + ' Refuel Kit banner" style="max-width:100%;height:auto;display:block">'
|
||||
+ '<div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:6px"><a class="btn small sec" href="' + esc(r.url) + '" download>Download</a>'
|
||||
+ '<button class="btn small sec" type="button" data-kit="copy">Copy image link</button>'
|
||||
+ (IAP_SIZES.includes(r.size) ? '<button class="btn small" type="button" data-kit="use">Use in an IAP banner campaign</button>' : '') + '</div>';
|
||||
box.querySelector('[data-kit="copy"]').addEventListener('click', () => { try { navigator.clipboard.writeText(r.abs); say('Image link copied.', 'ok'); } catch (e) { say(r.abs); } });
|
||||
const u = box.querySelector('[data-kit="use"]'); if (u) u.addEventListener('click', () => useInCampaign(r, month));
|
||||
}
|
||||
async function loadKitCard() {
|
||||
const card = $('rkCard'); if (!card) return;
|
||||
try {
|
||||
const d = await (await fetch('/api/my/kits', { cache: 'no-store' })).json();
|
||||
kitData = d;
|
||||
if (!d || !d.on || !d.kits || !d.kits.length) { card.hidden = true; return; }
|
||||
card.innerHTML = d.kits.slice(0, 3).map(k => '<div class="rk-kit" style="margin-bottom:14px">' + kitHtml(k, d) + '</div>').join('')
|
||||
+ (d.customNote ? '<p class="small"><b>Custom banners credit:</b> ' + esc(d.customNote) + '</p>' : '')
|
||||
+ '<p class="small muted">Ad credits buy delivery only. No banner may promise income.</p>';
|
||||
card.hidden = false;
|
||||
card.querySelectorAll('.kit-cell button[data-kit]').forEach(b => b.addEventListener('click', async () => {
|
||||
const cell = b.closest('.kit-cell'); b.disabled = true; const was = b.textContent; b.textContent = 'Drawing your banner...';
|
||||
try { cellReady(cell, await render(cell.dataset.month, cell.dataset.size, b.dataset.kit === 'gif' ? 'gif' : 'still'), cell.dataset.month); }
|
||||
catch (e) { say(e.message, 'err'); }
|
||||
b.disabled = false; b.textContent = was;
|
||||
}));
|
||||
} catch (e) { card.hidden = true; }
|
||||
}
|
||||
window.FUEL.loadKitCard = loadKitCard;
|
||||
loadKitCard();
|
||||
})();
|
||||
@@ -0,0 +1,235 @@
|
||||
/* InstantAdPay in-game sign-in kit (2026-10-03). Served by instantadpay.com, loaded by each game's own /signin page,
|
||||
so a player signs in (or opens a free InstantAdPay account) without leaving the game. Talks to /api/game/auth/*
|
||||
from the player's browser; the game only ever receives its normal hand-off token, which it opens at /auth.
|
||||
Host page sets theme through CSS variables on .iapsi (--si-*). Usage:
|
||||
IAPSignin.mount(el, { game: 'driprunner', ref: 'skycash', oneTap: 'https://instantadpay.com/api/my/driprunner' });
|
||||
IAPSignin.enter('wallet'); // nudge: opens InstantAdPay in a new tab, already signed in
|
||||
After a fresh sign-in (never on a remembered pass) the kit shows the InstantAdPay login ad before the hand-off,
|
||||
same as the dashboard: sponsor card, Open Ad (a counted click), 10 s countdown, then Continue. Any ad error,
|
||||
or no ad to show, goes straight to the game. mount option loginAd: false switches it off (2026-10-18). */
|
||||
(function () {
|
||||
var IAP = 'https://instantadpay.com';
|
||||
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
|
||||
var PASS_KEY = 'iap.gamepass', DEV_KEY = 'iap.gdev';
|
||||
function ls(k, v) { try { if (v === undefined) return localStorage.getItem(k); if (v === null) localStorage.removeItem(k); else localStorage.setItem(k, v); } catch (e) { return null; } }
|
||||
function devId() { var d = ls(DEV_KEY); if (!/^[a-f0-9]{32}$/.test(d || '')) { d = ''; var a = new Uint8Array(16); (window.crypto || window.msCrypto).getRandomValues(a); for (var i = 0; i < 16; i++) d += ('0' + a[i].toString(16)).slice(-2); ls(DEV_KEY, d); } return d; }
|
||||
function getPass() { try { var p = JSON.parse(ls(PASS_KEY) || 'null'); return p && p.p && p.exp > Date.now() ? p : null; } catch (e) { return null; } }
|
||||
// the one-tap link carries the inviter's ref too, so a new player who taps it still gets their sponsor (2026-10-05)
|
||||
function oneTapUrl(opt) { var u = String(opt.oneTap || ''), r = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20); if (!r || /[?&]ref=/.test(u)) return u; return u + (u.indexOf('?') < 0 ? '?' : '&') + 'ref=' + encodeURIComponent(r); }
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function post(path, body) {
|
||||
return fetch(IAP + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), credentials: 'omit' })
|
||||
.then(function (r) { return r.json().catch(function () { return {}; }).then(function (j) { j._status = r.status; return j; }); })
|
||||
.catch(function () { return { _status: 0, error: 'Could not reach InstantAdPay. Check your connection and try again.' }; });
|
||||
}
|
||||
var CSS = '.iapsi{--a:var(--si-accent,#7c5cff);--ai:var(--si-accent-ink,#fff);--ink:var(--si-ink,#f2efff);--mu:var(--si-muted,#b7b0d6);--fl:var(--si-field,rgba(255,255,255,.06));--ln:var(--si-line,rgba(255,255,255,.18));color:var(--ink);font-family:var(--si-font,system-ui,sans-serif);display:grid;gap:14px}'
|
||||
+ '.iapsi h2{margin:0;font-size:22px;line-height:1.2}.iapsi p{margin:0;color:var(--mu);font-size:14.5px;line-height:1.5}.iapsi b{color:var(--ink)}'
|
||||
+ '.iapsi label.f{display:grid;gap:6px;font-size:13px;color:var(--mu)}.iapsi input.t{font:inherit;font-size:17px;padding:12px 14px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);color:var(--ink);width:100%;box-sizing:border-box}'
|
||||
+ '.iapsi input.t:focus{outline:2px solid var(--a);outline-offset:1px}.iapsi input.code{letter-spacing:.4em;text-align:center;font-size:22px}'
|
||||
+ '.iapsi .go{font:inherit;font-weight:700;font-size:16px;padding:13px 16px;border:0;border-radius:12px;background:var(--a);color:var(--ai);cursor:pointer;width:100%}.iapsi .go[disabled]{opacity:.55;cursor:default}'
|
||||
+ '.iapsi .lk{background:none;border:0;padding:0;font:inherit;font-size:13.5px;color:var(--mu);text-decoration:underline;cursor:pointer}.iapsi .lk[disabled]{opacity:.5;cursor:default;text-decoration:none}'
|
||||
+ '.iapsi form{display:grid;gap:12px;margin:0}.iapsi .row{display:flex;gap:14px;flex-wrap:wrap;justify-content:space-between}.iapsi label.ck{display:flex!important;gap:10px;align-items:flex-start;font-size:13px;color:var(--mu);margin:0}.iapsi .ck input{margin:3px 0 0;width:auto!important;flex:0 0 auto;height:auto;padding:0}.iapsi .ck span{flex:1}.iapsi .err:empty{display:none}'
|
||||
+ '.iapsi .err{color:var(--si-bad,#ff8a8a);font-size:14px;min-height:1px}.iapsi .fine{font-size:12px;color:var(--mu)}.iapsi .fine a{color:var(--mu)}'
|
||||
+ '.iapsi .hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}.iapsi .chal{display:flex;gap:8px;flex-wrap:wrap}.iapsi .chal button{font-size:26px;width:52px;height:52px;border-radius:12px;border:1px solid var(--ln);background:var(--fl);cursor:pointer}'
|
||||
// login-ad gate (full screen, above the game page)
|
||||
+ '.iapla{position:fixed;inset:0;z-index:2147483000;display:flex;flex-direction:column;background:var(--si-ground,#0d0b1a);color:var(--si-ink,#f2efff);font-family:var(--si-font,system-ui,sans-serif)}'
|
||||
+ '.iapla-bar{display:flex;align-items:center;gap:10px 14px;flex-wrap:wrap;padding:10px 16px;background:var(--si-panel,#17142b);border-bottom:1px solid var(--si-line,rgba(255,255,255,.18))}'
|
||||
+ '.iapla-brand{font-weight:800;font-size:15px;white-space:nowrap}.iapla-brand em{color:var(--si-accent,#7c5cff);font-style:normal}.iapla-note{flex:1;min-width:140px;font-size:13px;color:var(--si-muted,#b7b0d6)}'
|
||||
+ '.iapla-timer{font-weight:700;font-size:14px;border:1px solid var(--si-line,rgba(255,255,255,.3));border-radius:999px;padding:4px 12px;white-space:nowrap}.iapla-timer.done{color:var(--si-accent,#7c5cff);border-color:var(--si-accent,#7c5cff)}'
|
||||
+ '.iapla-btn{font:inherit;font-weight:700;font-size:14px;padding:9px 14px;border:0;border-radius:10px;background:var(--si-accent,#7c5cff);color:var(--si-accent-ink,#fff);cursor:pointer;text-decoration:none;white-space:nowrap}'
|
||||
+ '.iapla-btn.sec{background:transparent;color:var(--si-ink,#f2efff);border:1px solid var(--si-line,rgba(255,255,255,.3))}.iapla-btn[disabled]{opacity:.55;cursor:default}.iapla-btn.big{font-size:17px;padding:13px 22px}'
|
||||
+ '.iapla-frame{flex:1;border:0;width:100%;background:#fff;min-height:0}.iapla-body{flex:1;display:grid;place-items:center;padding:24px 16px;overflow:auto}'
|
||||
+ '.iapla-card{max-width:560px;text-align:center;display:grid;gap:16px;justify-items:center}.iapla-card p{margin:0;font-size:14px;line-height:1.5;color:var(--si-muted,#b7b0d6)}'
|
||||
+ '.iapla-eye{font-size:12px;letter-spacing:.12em;text-transform:uppercase}.iapla-card img{max-width:100%;max-height:50vh;border-radius:12px;border:1px solid var(--si-line,rgba(255,255,255,.18))}'
|
||||
+ '.iapla-link{display:inline-block;font-size:20px;font-weight:700;color:var(--si-ink,#f2efff);background:var(--si-field,rgba(255,255,255,.06));border:1px solid var(--si-line,rgba(255,255,255,.18));border-radius:14px;padding:18px 22px}'
|
||||
+ '.iapla [hidden]{display:none!important}';
|
||||
function styleOnce() { if (document.getElementById('iapsiCss')) return; var s = document.createElement('style'); s.id = 'iapsiCss'; s.textContent = CSS; document.head.appendChild(s); }
|
||||
|
||||
// the login ad after a fresh sign-in. `then` (the hand-off) always runs exactly once: when the gate is done,
|
||||
// when there is no ad, or on any error or a slow answer, so an ad can never hold a player out of the game.
|
||||
function loginAd(game, then) {
|
||||
var over = false; function go() { if (over) return; over = true; try { then(); } catch (e) {} }
|
||||
var ctl = null; try { ctl = new AbortController(); } catch (e) {}
|
||||
var slow = setTimeout(function () { if (ctl) try { ctl.abort(); } catch (e) {} go(); }, 7000);
|
||||
fetch(IAP + '/api/game/ads/login?game=' + encodeURIComponent(game || ''), { credentials: 'omit', signal: ctl ? ctl.signal : undefined })
|
||||
.then(function (r) { return r.ok ? r.json() : {}; })
|
||||
.then(function (j) { clearTimeout(slow); if (over) return; var ad = j && j.ad; if (!ad || !ad.targetUrl) return go(); gate(ad, go); })
|
||||
.catch(function () { clearTimeout(slow); go(); });
|
||||
}
|
||||
function gate(ad, go) {
|
||||
var abs = function (u) { return /^https?:/i.test(u) ? u : IAP + u; };
|
||||
var click = abs(ad.targetUrl), site = ad.siteUrl || click, framed = !!ad.frameable, started = false, t = null;
|
||||
var g = document.createElement('div'); g.className = 'iapla'; g.setAttribute('role', 'dialog'); g.setAttribute('aria-label', 'Login sponsor');
|
||||
g.innerHTML = '<div class="iapla-bar"><span class="iapla-brand">Instant<em>AdPay</em></span>'
|
||||
+ '<span class="iapla-note" data-st>Login ad sponsor. Tap "Open Ad" to begin.</span>'
|
||||
+ '<span class="iapla-timer" data-tm hidden></span>'
|
||||
+ '<a class="iapla-btn sec" data-tab target="_blank" rel="noopener" hidden>Open site in a new tab \u2197</a>'
|
||||
+ '<button class="iapla-btn" type="button" data-go hidden>Continue to the game</button></div>'
|
||||
+ '<iframe class="iapla-frame" data-fr hidden sandbox="allow-scripts allow-same-origin allow-forms allow-popups" referrerpolicy="no-referrer" title="Sponsor site"></iframe>'
|
||||
+ '<div class="iapla-body" data-bd><div class="iapla-card"><p class="iapla-eye">Today\'s login sponsor</p>'
|
||||
+ (ad.imageUrl ? '<img src="' + esc(ad.imageUrl) + '" alt="sponsor ad">' : '<span class="iapla-link">' + esc(ad.title || 'Visit today\'s sponsor') + '</span>')
|
||||
+ '<button class="iapla-btn big" type="button" data-open>Open Ad</button>'
|
||||
+ '<p>' + (framed ? 'The sponsor\'s page opens right here under this bar. When the timer hits zero, your Continue button appears beside it.'
|
||||
: 'This sponsor\'s site opens in a new tab. The timer counts down here; come back when it hits zero to continue to the game.') + '</p></div></div>';
|
||||
var q = function (k) { return g.querySelector('[data-' + k + ']'); };
|
||||
var st = q('st'), tm = q('tm'), tab = q('tab'), btn = q('go'), fr = q('fr'), bd = q('bd'), open = q('open');
|
||||
function finish() { clearInterval(t); document.removeEventListener('securitypolicyviolation', csp); try { g.remove(); } catch (e) {} go(); }
|
||||
// a game page whose CSP refuses the frame: offer the sponsor in a new tab instead (the timer keeps running)
|
||||
function csp(ev) {
|
||||
if (!started || !framed || !/frame|child|default/.test(String(ev.violatedDirective || ev.effectiveDirective || ''))) return;
|
||||
var b = String(ev.blockedURI || '');
|
||||
fr.hidden = true; bd.hidden = true; tab.hidden = false;
|
||||
tab.href = (!b || b.indexOf(IAP) === 0) ? click : site; // blocked before our click relay ran: the tab is the counted click
|
||||
st.textContent = 'This game cannot show the sponsor here. Open it in a new tab; the timer runs here.';
|
||||
}
|
||||
document.addEventListener('securitypolicyviolation', csp);
|
||||
open.addEventListener('click', function () {
|
||||
if (started) return; started = true; open.disabled = true;
|
||||
if (framed) {
|
||||
fr.src = click; // the click relay counts it, then redirects inside the frame
|
||||
fr.hidden = false; bd.hidden = true; tab.href = site; tab.hidden = false;
|
||||
st.textContent = 'Today\'s sponsor. Have a look; your Continue button appears when the timer ends.';
|
||||
} else {
|
||||
try { window.open(click, '_blank'); } catch (e) {} // the click relay counts it
|
||||
st.textContent = 'The sponsor opened in a new tab. View it and come back; the timer runs here.';
|
||||
}
|
||||
var left = Math.max(1, Number(ad.dwell) || 10);
|
||||
tm.hidden = false; tm.textContent = 'Time remaining: ' + left + 's';
|
||||
t = setInterval(function () {
|
||||
left -= 1;
|
||||
if (left > 0) { tm.textContent = 'Time remaining: ' + left + 's'; return; }
|
||||
clearInterval(t); tm.textContent = 'Time is up'; tm.className = 'iapla-timer done';
|
||||
st.textContent = 'Thanks for the look. Your game is ready.'; btn.hidden = false;
|
||||
try { btn.focus(); } catch (e) {}
|
||||
}, 1000);
|
||||
});
|
||||
btn.addEventListener('click', finish);
|
||||
document.body.appendChild(g);
|
||||
}
|
||||
|
||||
function mount(el, opt) {
|
||||
styleOnce(); opt = opt || {};
|
||||
var game = opt.game, ref = String(opt.ref || '').toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 40), src = String(opt.src || '').toLowerCase().replace(/[^a-z0-9_.-]/g, '').slice(0, 30);
|
||||
var fts = Date.now(), email = '', newsletter = true, resendAt = 0, timer = null;
|
||||
var onToken = opt.onToken || function (t) { location.href = '/auth?t=' + encodeURIComponent(t); };
|
||||
el.classList.add('iapsi');
|
||||
function err(m) { var e = el.querySelector('.err'); if (e) e.textContent = m || ''; }
|
||||
function busy(on) { var b = el.querySelector('.go'); if (b) { b.disabled = !!on; if (on) b.dataset.l = b.textContent, b.textContent = 'One moment…'; else if (b.dataset.l) b.textContent = b.dataset.l; } }
|
||||
function done(r) {
|
||||
if (r.pass) { var prev = getPass(); ls(PASS_KEY, JSON.stringify({ p: r.pass, exp: Date.now() + 29 * 86400000, email: email || (prev && prev.email) || '', name: r.username || (prev && prev.name) || '' })); }
|
||||
if (r.needUsername) return stepName(r);
|
||||
if (r.token) { // a fresh sign-in: the login ad first (fails open to the hand-off)
|
||||
if (opt.loginAd === false) return onToken(r.token);
|
||||
el.innerHTML = '<h2>You are in</h2><p>One moment\u2026</p>';
|
||||
try { return loginAd(game, function () { onToken(r.token); }); } catch (e) { return onToken(r.token); }
|
||||
}
|
||||
err('Something went wrong. Try again.');
|
||||
}
|
||||
function stepEmail(msg) {
|
||||
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2>'
|
||||
+ '<p>Use your email. We send you a 6-digit code, no password. New here? This also opens your free <b>InstantAdPay</b> account, the home of every game in the network.</p>'
|
||||
+ '<form novalidate><label class="f">Email<input class="t" type="email" name="email" autocomplete="email" inputmode="email" required value="' + esc(email) + '"></label>'
|
||||
+ '<input class="hp" type="text" name="hp_field_x9" tabindex="-1" autocomplete="off" aria-hidden="true">'
|
||||
+ '<label class="ck"><input type="checkbox" name="nl"' + (newsletter ? ' checked' : '') + '><span>Keep me posted with the InstantAdPay newsletter (tips and updates). You can unsubscribe anytime.</span></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Send my code</button></form>'
|
||||
+ (opt.oneTap ? '<div class="row"><a class="lk" href="' + esc(oneTapUrl(opt)) + '">Already signed in to InstantAdPay here? One tap</a></div>' : '')
|
||||
+ '<p class="fine">By continuing you agree to the InstantAdPay <a href="' + IAP + '/terms" target="_blank" rel="noopener">Terms</a> and <a href="' + IAP + '/privacy" target="_blank" rel="noopener">Privacy</a> policy.</p>';
|
||||
var f = el.querySelector('form'); if (msg) err(msg);
|
||||
f.addEventListener('submit', function (ev) { ev.preventDefault(); send(null); });
|
||||
setTimeout(function () { var i = f.email; if (i && !email) try { i.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
function send(pick) {
|
||||
var f = el.querySelector('form');
|
||||
if (f && f.email) { email = String(f.email.value || '').trim(); newsletter = !!(f.nl && f.nl.checked); }
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(email)) return err('Enter the email you use (or want to use) for InstantAdPay.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/start', { game: game, email: email, ref: ref, src: src, fts: fts, fage: Date.now() - fts, hp_field_x9: (f && f.hp_field_x9 && f.hp_field_x9.value) || '', pick: pick || '', dev: devId() }).then(function (r) {
|
||||
busy(false);
|
||||
if (r.challenge) return stepChallenge(r.challenge, r.error);
|
||||
if (r.ok) { resendAt = Date.now() + 60000; return stepCode(r.devCode); }
|
||||
if (/already sent/i.test(r.error || '')) { resendAt = Date.now() + 60000; return stepCode(null, r.error); }
|
||||
err(r.error || 'Could not send the code. Try again.');
|
||||
});
|
||||
}
|
||||
function stepChallenge(ch, msg) {
|
||||
el.innerHTML = '<h2>Quick check</h2><p>' + esc(msg || 'Before we send your code:') + ' Tap the <b>' + esc(ch.prompt) + '</b>.</p><div class="chal">'
|
||||
+ ch.options.map(function (o) { return '<button type="button" data-o="' + esc(o) + '">' + esc(o) + '</button>'; }).join('') + '</div><div class="err" role="alert"></div>'
|
||||
+ '<button class="lk" type="button" data-back>Use a different email</button>';
|
||||
el.querySelectorAll('[data-o]').forEach(function (b) { b.addEventListener('click', function () { send(b.getAttribute('data-o')); }); });
|
||||
el.querySelector('[data-back]').addEventListener('click', function () { stepEmail(); });
|
||||
}
|
||||
function stepCode(devCode, msg) {
|
||||
el.innerHTML = '<h2>Check your email</h2><p>We sent a 6-digit code to <b>' + esc(email) + '</b>. It can take a minute. Not there? Check spam or promotions.</p>'
|
||||
+ '<form novalidate><label class="f">Code<input class="t code" name="code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" pattern="[0-9]*" value="' + esc(devCode || '') + '"></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Sign in</button></form>'
|
||||
+ '<div class="row"><button class="lk" type="button" data-again>Send a new code</button><button class="lk" type="button" data-back>Use a different email</button></div>';
|
||||
var f = el.querySelector('form'), again = el.querySelector('[data-again]'); if (msg) err(msg);
|
||||
clearInterval(timer);
|
||||
function tick() { var s = Math.ceil((resendAt - Date.now()) / 1000); again.disabled = s > 0; again.textContent = s > 0 ? 'Send a new code (' + s + 's)' : 'Send a new code'; if (s <= 0) clearInterval(timer); }
|
||||
tick(); timer = setInterval(tick, 1000);
|
||||
again.addEventListener('click', function () { clearInterval(timer); send(null); });
|
||||
el.querySelector('[data-back]').addEventListener('click', function () { clearInterval(timer); stepEmail(); });
|
||||
f.code.addEventListener('input', function () { f.code.value = f.code.value.replace(/\D/g, '').slice(0, 6); if (f.code.value.length === 6) f.requestSubmit ? f.requestSubmit() : verify(); });
|
||||
f.addEventListener('submit', function (ev) { ev.preventDefault(); verify(); });
|
||||
setTimeout(function () { try { f.code.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
function verify() {
|
||||
var f = el.querySelector('form'); var code = String((f && f.code && f.code.value) || '').trim();
|
||||
if (!/^\d{6}$/.test(code)) return err('Enter the 6 digits from the email.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/verify', { game: game, email: email, code: code, ref: ref, src: src, newsletter: newsletter, dev: devId() }).then(function (r) {
|
||||
busy(false);
|
||||
if (r.ok) { clearInterval(timer); return done(r); }
|
||||
if (/expired|too many/i.test(r.error || '')) { clearInterval(timer); return stepEmail(r.error); }
|
||||
err(r.error || 'That did not work. Try again.');
|
||||
});
|
||||
}
|
||||
function stepName(r) {
|
||||
el.innerHTML = '<h2>Pick your username</h2><p>This is your name in every game, on the leaderboards and in your invite link. Choose carefully: it cannot be changed later.</p>'
|
||||
+ '<form novalidate><label class="f">Username<input class="t" name="u" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="20" placeholder="3 to 20 letters, numbers or _"></label>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="submit">Save and play</button></form>';
|
||||
var f = el.querySelector('form');
|
||||
f.u.addEventListener('input', function () { f.u.value = f.u.value.replace(/[^A-Za-z0-9_]/g, '').slice(0, 20); });
|
||||
f.addEventListener('submit', function (ev) {
|
||||
ev.preventDefault(); var name = f.u.value.trim();
|
||||
if (!/^[A-Za-z0-9_]{3,20}$/.test(name)) return err('Usernames are 3 to 20 letters, numbers, or underscores.');
|
||||
if (/^\d+$/.test(name)) return err('Usernames need at least one letter.');
|
||||
var pass = getPass(); if (!pass) return stepEmail('Your sign-in expired. Start again with your email.');
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/username', { game: game, pass: pass.p, username: name }).then(function (x) { busy(false); if (x.ok) return done(x); err(x.error || 'That name did not work. Try another.'); });
|
||||
});
|
||||
setTimeout(function () { try { f.u.focus(); } catch (e) {} }, 50);
|
||||
}
|
||||
// signed in on this device before (the 29-day pass): one tap, no code (Dallas 2026-10-19: "only a name and login with
|
||||
// InstantAdPay, it should take care of the rest"). Remembered sign-ins skip the login ad, as before.
|
||||
function stepResume(saved) {
|
||||
var who = saved.name ? '@' + saved.name : (saved.email || 'your InstantAdPay account');
|
||||
el.innerHTML = '<h2>' + esc(opt.title || 'Sign in to play') + '</h2><p>You are signed in on this device as <b>' + esc(who) + '</b>.</p>'
|
||||
+ '<div class="err" role="alert"></div><button class="go" type="button" data-go>Continue as ' + esc(who) + '</button>'
|
||||
+ '<div class="row"><button class="lk" type="button" data-other>Use a different account</button></div>';
|
||||
el.querySelector('[data-go]').addEventListener('click', function () {
|
||||
err(''); busy(true);
|
||||
post('/api/game/auth/resume', { game: game, pass: saved.p }).then(function (x) {
|
||||
busy(false);
|
||||
if (x.ok && x.pass) ls(PASS_KEY, JSON.stringify({ p: x.pass, exp: Date.now() + 29 * 86400000, email: saved.email || '', name: x.username || saved.name || '' }));
|
||||
if (x.ok && x.needUsername) return stepName(x);
|
||||
if (x.ok && x.token) return onToken(x.token);
|
||||
ls(PASS_KEY, null); stepEmail(x.error || 'Your sign-in expired. Start again with your email.');
|
||||
});
|
||||
});
|
||||
el.querySelector('[data-other]').addEventListener('click', function () { ls(PASS_KEY, null); stepEmail(); });
|
||||
}
|
||||
var saved = opt.resume === false ? null : getPass();
|
||||
if (saved) stepResume(saved); else stepEmail();
|
||||
}
|
||||
|
||||
// nudge: open InstantAdPay in a new tab already signed in (the pass posts in a form, never in a URL)
|
||||
function enter(to) {
|
||||
var pass = getPass();
|
||||
if (!pass) { window.open(IAP + '/my' + (to ? '#' + to : ''), '_blank', 'noopener'); return; }
|
||||
var f = document.createElement('form'); f.method = 'POST'; f.action = IAP + '/api/game/enter'; f.target = '_blank'; f.style.display = 'none';
|
||||
[['p', pass.p], ['to', to || 'overview']].forEach(function (kv) { var i = document.createElement('input'); i.type = 'hidden'; i.name = kv[0]; i.value = kv[1]; f.appendChild(i); });
|
||||
document.body.appendChild(f); f.submit(); setTimeout(function () { f.remove(); }, 1000);
|
||||
}
|
||||
window.IAPSignin = { mount: mount, enter: enter, hasPass: function () { return !!getPass(); }, forget: function () { ls(PASS_KEY, null); }, origin: IAP };
|
||||
})();
|
||||
@@ -0,0 +1,36 @@
|
||||
/* InstantAdPay "More games" strip (2026-10-03). Served by instantadpay.com and loaded by every network game, so the list
|
||||
of games lives in one place (/api/public/games: live games, Spooky Doors only while its season runs). Each card goes
|
||||
through /g/<slug>?from=<this game>, which counts the hop and lands a signed-in member straight in the game.
|
||||
Theme with CSS variables on the container (--gs-*). Usage:
|
||||
IAPGames.strip(el, { current: 'driprunner', title: 'More games' }); */
|
||||
(function () {
|
||||
var IAP = 'https://instantadpay.com';
|
||||
try { var me = document.currentScript && document.currentScript.src; if (me) IAP = new URL(me).origin; } catch (e) {}
|
||||
var CSS = '.iapgs{--ink:var(--gs-ink,#f2efff);--mu:var(--gs-muted,#b7b0d6);--card:var(--gs-card,rgba(255,255,255,.06));--ln:var(--gs-line,rgba(255,255,255,.16));--hot:var(--gs-hot,#ff8a1f);color:var(--ink);font-family:var(--gs-font,inherit);text-align:left}'
|
||||
+ '.iapgs .gs-h{font-size:12px;font-weight:800;letter-spacing:.14em;text-transform:uppercase;color:var(--mu);margin:0 0 8px}'
|
||||
+ '.iapgs .gs-row{display:grid;grid-auto-flow:column;grid-auto-columns:minmax(150px,1fr);gap:10px;overflow-x:auto;scroll-snap-type:x mandatory;padding-bottom:4px;-webkit-overflow-scrolling:touch}'
|
||||
+ '.iapgs a.gs-c{scroll-snap-align:start;display:flex;flex-direction:column;text-decoration:none;color:var(--ink);background:var(--card);border:1px solid var(--ln);border-radius:12px;overflow:hidden;min-width:0}'
|
||||
+ '.iapgs a.gs-c:hover,.iapgs a.gs-c:focus-visible{border-color:var(--ink)}'
|
||||
+ '.iapgs .gs-c img{display:block;width:100%;aspect-ratio:1200/630;object-fit:cover;background:#000}'
|
||||
+ '.iapgs .gs-t{padding:8px 10px 10px;display:grid;gap:3px}.iapgs .gs-t b{font-size:14px;line-height:1.2}'
|
||||
+ '.iapgs .gs-t small{font-size:12px;line-height:1.35;color:var(--mu)}.iapgs .gs-t em{font-style:normal;font-size:10.5px;font-weight:800;letter-spacing:.06em;text-transform:uppercase;color:var(--mu)}'
|
||||
+ '.iapgs .gs-t em.hot{color:var(--hot)}';
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
var cache = null;
|
||||
function list() { if (!cache) cache = fetch(IAP + '/api/public/games', { credentials: 'omit' }).then(function (r) { return r.json(); }).then(function (j) { return (j && j.games) || []; }).catch(function () { cache = null; return []; }); return cache; }
|
||||
function strip(el, opt) {
|
||||
if (!el) return Promise.resolve(0); opt = opt || {};
|
||||
if (!document.getElementById('iapgsCss')) { var s = document.createElement('style'); s.id = 'iapgsCss'; s.textContent = CSS; document.head.appendChild(s); }
|
||||
return list().then(function (games) {
|
||||
var g = games.filter(function (x) { return x.slug !== opt.current; });
|
||||
if (!g.length) { el.hidden = true; return 0; }
|
||||
el.classList.add('iapgs'); el.hidden = false;
|
||||
el.innerHTML = '<p class="gs-h">' + esc(opt.title || 'More games') + '</p><div class="gs-row">' + g.map(function (x) {
|
||||
return '<a class="gs-c" href="' + IAP + '/g/' + x.slug + '?from=' + encodeURIComponent(opt.current || '') + '"><img src="' + esc(x.art) + '" alt="" loading="lazy" style="object-position:' + esc(x.artPos || 'center') + '">'
|
||||
+ '<span class="gs-t"><em' + (x.seasonal ? ' class="hot"' : '') + '>' + esc(x.tag) + '</em><b>' + esc(x.name) + '</b><small>' + esc(x.line) + '</small></span></a>';
|
||||
}).join('') + '</div>';
|
||||
return g.length;
|
||||
});
|
||||
}
|
||||
window.IAPGames = { strip: strip, list: list, origin: IAP };
|
||||
})();
|
||||
@@ -0,0 +1,34 @@
|
||||
// Public games page (2026-10-10): every game in the network, live ones first, then the ones with an opening date.
|
||||
// Data: /api/public/games/all. Play links go to each game's own site (the game signs the visitor in with InstantAdPay).
|
||||
// A ?ref=<username> on this page is kept by the site's viral-link handling and carried onto the Join button.
|
||||
(function () {
|
||||
var esc = function (s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]; }); };
|
||||
var ref = ''; try { ref = new URLSearchParams(location.search).get('ref') || ''; } catch (e) {}
|
||||
if (ref) { var j = document.getElementById('gJoin'); if (j) j.href = '/join/' + encodeURIComponent(ref); } // the sponsored join page itself (bare /join used to 404, Diann 2026-10-11)
|
||||
function card(g) {
|
||||
var soon = !g.live && g.opens;
|
||||
var ribbon = g.season ? '<span class="ribbon">Limited time · ends ' + esc(g.season.ends) + '</span>' : soon ? '<span class="ribbon soon">' + esc(g.opens) + '</span>' : '';
|
||||
var play = g.live && g.open ? '<a class="btn" href="' + esc(g.open) + '" target="_blank" rel="noopener">Play</a>' : '<span class="btn" aria-disabled="true">' + esc(g.opens || 'Opens soon') + '</span>';
|
||||
var site = g.host ? '<span class="host">' + esc(g.host) + '</span>' : '';
|
||||
var art = g.video ? '<video controls playsinline preload="none" poster="' + esc(g.poster || g.art || '') + '" src="' + esc(g.video) + '" style="width:100%;height:100%;object-fit:cover;display:block;background:#000"></video>' : (g.art ? '<img src="' + esc(g.art) + '" alt="" loading="lazy"' + (g.artPos ? ' style="object-position:' + esc(g.artPos) + ' center"' : '') + '>' : '');
|
||||
return '<div class="gcard"><div class="art">' + art + ribbon + '</div>' +
|
||||
'<div class="body"><span class="tag">' + esc(g.tag || '') + '</span><h3>' + esc(g.name) + '</h3><p>' + esc(g.blurb || '') + '</p>' +
|
||||
(g.pays ? '<div class="pays">Pays: <b>' + esc(g.pays) + '</b></div>' : '') +
|
||||
'<div class="row">' + play + site + '</div></div></div>';
|
||||
}
|
||||
fetch('/api/public/games/all').then(function (r) { return r.json(); }).then(function (d) {
|
||||
var games = (d && d.games) || [];
|
||||
var live = games.filter(function (g) { return g.live; }), soon = games.filter(function (g) { return !g.live; });
|
||||
var L = document.getElementById('gLive'), S = document.getElementById('gSoon');
|
||||
if (!games.length) { document.getElementById('gEmpty').hidden = false; return; }
|
||||
if (live.length) L.innerHTML = '<h2 class="gsec">Open now · ' + live.length + ' game' + (live.length === 1 ? '' : 's') + '</h2><div class="ggrid">' + live.map(card).join('') + '</div>';
|
||||
if (soon.length) S.innerHTML = '<h2 class="gsec">Opening next</h2><div class="ggrid">' + soon.map(card).join('') + '</div>';
|
||||
}).catch(function () { document.getElementById('gEmpty').hidden = false; });
|
||||
// featured warriors from the PolyWarriors market (2026-10-10): the rarest listings, with the forged art
|
||||
fetch('/api/public/pw-featured').then(function (r) { return r.json(); }).then(function (d) {
|
||||
var f = (d && d.featured) || []; if (!f.length) return; var S = document.getElementById('gSoon'); var host = document.createElement('div'); host.id = 'gFeatured';
|
||||
host.innerHTML = '<h2 class="gsec">From the PolyWarriors market <small style="letter-spacing:0;text-transform:none;font-size:11px"> <a href="' + esc(d.market) + '" target="_blank" rel="noopener">open the market</a></small></h2><div class="fgrid">' + f.map(function (x) {
|
||||
return '<a class="fcard" href="' + esc(x.url) + '" target="_blank" rel="noopener" style="--rc:' + esc(x.color) + '"><div class="fpic"><img src="' + esc(x.image) + '" alt="" loading="lazy"><span class="ftag">' + esc(x.rarity) + '</span>' + (x.forSale ? '<span class="fsale">For sale</span>' : '') + '</div><div class="fb"><b>' + esc(x.name) + ' #' + String(x.serial).padStart(4, '0') + '</b>' + (x.forge ? '<small>Forged ' + esc(x.forge.grade) + ' ' + esc(x.forge.score) + '</small>' : '') + (x.forSale ? '<span class="fp">' + esc(x.price) + ' POL</span>' : '') + '</div></a>'; }).join('') + '</div>';
|
||||
S.parentNode.insertBefore(host, S.nextSibling);
|
||||
}).catch(function () {});
|
||||
})();
|
||||
|
After Width: | Height: | Size: 145 KiB |
|
After Width: | Height: | Size: 109 KiB |
@@ -16,7 +16,8 @@
|
||||
const { products } = await (await fetch('/api/catalog')).json();
|
||||
const wrap = document.getElementById('tiles');
|
||||
wrap.innerHTML = '';
|
||||
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
|
||||
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
|
||||
products.sort((a, b) => a.priceCents - b.priceCents);
|
||||
for (const p of products) {
|
||||
const bonus = p.creditAmount - p.priceCents; // credits above 1cr/cent = bulk bonus
|
||||
const div = document.createElement('div');
|
||||
@@ -44,7 +45,7 @@
|
||||
IAP.status('Confirm the purchase in your wallet…');
|
||||
// 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();
|
||||
const spNow = await (await fetch('/api/sponsor?intent=buy')).json(); // intent=buy: never held (Marty 2026-10-27)
|
||||
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');
|
||||
@@ -62,6 +63,15 @@
|
||||
} catch (e) {}
|
||||
}
|
||||
loadFriday();
|
||||
// Wired Wednesday strip: the live wave on Wednesdays, the next date otherwise
|
||||
async function loadWednesday() {
|
||||
try { const f = await (await fetch('/api/wednesday')).json(); const el = document.getElementById('wwStrip'); if (!f.on || !el) return; el.hidden = false;
|
||||
el.innerHTML = f.live && f.today
|
||||
? '<b>⚡ It’s Wired Wednesday.</b> ' + f.today.packs + ' pack' + (f.today.packs === 1 ? '' : 's') + ' bought so far today, ' + Number(f.today.bonusCredits || 0).toLocaleString() + ' bonus credits wired in. Any pack from $' + f.minUsd + ' earns +' + f.pct + '% credits the second it settles, until midnight Central. <a href="/my">Get yours</a>'
|
||||
: '<b>⚡ Wired Wednesday:</b> every Wednesday, any ad package from $' + f.minUsd + ' up earns +' + f.pct + '% bonus credits, wired into your balance the second it settles. Next one: ' + (f.nextLabel || 'soon') + '. <a href="/wednesday">How it works</a>';
|
||||
} catch (e) {}
|
||||
}
|
||||
loadWednesday();
|
||||
async function loadStats() {
|
||||
try {
|
||||
const s = await (await fetch('/api/stats')).json();
|
||||
@@ -144,7 +154,7 @@
|
||||
setB($id('dcB3'), l3open, qualifies ? (5 - d) + ' more buyer(s)' : 'needs $20+ buyers');
|
||||
$id('dcQualNote').textContent = qualifies
|
||||
? 'Buyers of $20 or more count toward your qualification. 2 unlock level 2, 5 unlock level 3.'
|
||||
: 'Heads up: $5 packages pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
|
||||
: 'Heads up: packages under $20 pay your level 1 but do not qualify buyers, so levels 2 and 3 stay locked in this scenario.';
|
||||
};
|
||||
['dcDirects', 'dcPkg', 'dcSpread'].forEach(x => $id(x).addEventListener('input', recalc));
|
||||
recalc();
|
||||
|
||||
@@ -15,6 +15,9 @@
|
||||
cta: 'Claim your welcome-back credits', sub: 'Free account by email. Use the email you had on ' + brand + ': the credits are tied to it.', video: false };
|
||||
const ANGLES = {
|
||||
'fw-adv': LEG('Faucet Wave', 'adv'), 'fw-earn': LEG('Faucet Wave', 'earn'), 't1-adv': LEG('Tier One Ads', 'adv'), 't1-earn': LEG('Tier One Ads', 'earn'),
|
||||
play: { eyebrow: 'If you have time to play', h: 'If you have time to play a game, <em>you have time to build a business.</em>', lead: 'You play games on your phone anyway. These free games pay real Polygon to your wallet, on chain, where anyone can check it. That is the trust tool: people believe what they see paid.',
|
||||
points: ['A whole collection of free games on one page: a brick breaker, a word puzzle, match three, a cyberpunk battler, a runner and more.', 'First clears and wins pay real Polygon to the wallet on your InstantAdPay account, and every payout is a public transaction anyone can check.', 'Share your games link instead of just playing. When a friend plays, gets paid and joins, they join your team.'],
|
||||
cta: 'Join free and get your own games link', sub: 'Free account by email. No password, no wallet today. Your games link and invite link are live the moment you are in.', games: true },
|
||||
instant: { eyebrow: 'Same-transaction payouts', h: 'Paid before the page <em>reloads.</em>', lead: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay that is not a metaphor. A smart contract on Polygon splits every ad package the moment it sells.',
|
||||
points: ['A verified contract splits every package in the same transaction it sells: 50 percent to the sponsor, 20 and 10 up the line, 20 to the platform.', 'It lands in your own wallet in seconds. There is no balance to withdraw because nothing is ever held.', 'Every payment is public on Polygonscan, so you can check the claim before you spend a dollar.'],
|
||||
cta: 'See a payout land in seconds', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' },
|
||||
@@ -29,7 +32,11 @@
|
||||
cta: 'Check the ledger yourself, then decide', sub: 'Free account by email. The public ledger and the verified contract are one click from your dashboard.' },
|
||||
two: { eyebrow: 'The referral side, exactly as coded', h: 'Two buyers open <em>level two.</em>', lead: 'Every direct buyer pays you 50 percent from their first package. Two qualifying buyers open level two, five open level three. Written as constants in a verified contract.',
|
||||
points: ['Every direct buyer pays you 50 percent from their very first package.', 'Two qualifying buyers open level two at 20 percent. Five open level three at 10 percent. Constants in a verified contract.', 'Until a level opens, its share climbs to the next qualified member above, so the plan rewards the people who build.'],
|
||||
cta: 'Start your line. Two buyers is the target.', sub: 'Free account by email. Your invite link and the team-building plays are waiting inside.' }
|
||||
cta: 'Start your line. Two buyers is the target.', sub: 'Free account by email. Your invite link and the team-building plays are waiting inside.' },
|
||||
// Build Wide (2026-10-15): the buildwide promo video, vertical on phones and 16:9 on wider screens
|
||||
wide: { eyebrow: 'Build wide', h: 'Width unlocks <em>depth.</em>', lead: 'Watch the fifty percent land, then the deeper levels open.', file: 'buildwide', portraitOnPhones: true,
|
||||
points: ['Every direct buyer pays you 50 percent of their package, in the same transaction it sells.', 'Two direct buyers of $20 or more open level two at 20 percent. Five open level three at 10 percent.', 'A level you have not opened yet passes its share up the line. Going wide first is what opens the deeper levels.'],
|
||||
cta: 'Start wide. Join free.', sub: 'Free account by email. No password, no wallet today. Your invite link is live the moment you are in.' }
|
||||
};
|
||||
// ?name=First personalises the page (site-owner links, Marty 2026-09-12): letters, spaces, hyphens,
|
||||
// apostrophes only, 30 chars. On the company placement links it says the top spot is reserved.
|
||||
@@ -48,9 +55,24 @@
|
||||
// the matching hook video + this angle's three points replace the worked example
|
||||
const VID = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
|
||||
const vid = $('jnVideo');
|
||||
if (a.video === false) vid.hidden = true; else { vid.src = VID + v + '.mp4'; vid.poster = VID + v + '.jpg'; }
|
||||
if (a.video === false) vid.hidden = true;
|
||||
else {
|
||||
const file = a.file || v; // a hook whose uploaded video carries another name (wide -> promo/buildwide.*)
|
||||
const tall = a.portraitOnPhones && window.matchMedia && window.matchMedia('(max-width: 640px)').matches;
|
||||
vid.src = VID + file + (tall ? '-portrait' : '') + '.mp4'; vid.poster = VID + file + (tall ? '-portrait' : '') + '.jpg';
|
||||
if (tall) { vid.style.aspectRatio = '9/16'; vid.style.maxWidth = '380px'; vid.style.margin = '0 auto'; vid.style.maxHeight = '78vh'; }
|
||||
}
|
||||
$('jnPoints').innerHTML = (a.points || []).map(t => '<li>' + t.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])) + '</li>').join('');
|
||||
$('jnMock').hidden = true; $('jnAngle').hidden = false; $('jnPoints').hidden = false;
|
||||
// play angle (2026-10-13): a big button to the public games page, carrying this page's invite token as ?ref
|
||||
if (a.games && !document.getElementById('jnGames')) {
|
||||
const tok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
|
||||
const g = document.createElement('p'); g.id = 'jnGames'; g.style.cssText = 'margin:14px 0 4px;text-align:center';
|
||||
const btn = document.createElement('a'); btn.className = 'btn'; btn.href = '/games' + (tok && !/^(company|top)$/i.test(tok) ? '?ref=' + encodeURIComponent(tok) : '');
|
||||
btn.target = '_blank'; btn.rel = 'noopener'; btn.textContent = 'Play the free games'; btn.style.cssText = 'display:inline-block;font-size:1.1em;padding:14px 28px';
|
||||
const note = document.createElement('div'); note.className = 'small muted'; note.style.marginTop = '8px'; note.textContent = 'Opens the games page. Play free, then join below to get paid and get your own link.';
|
||||
g.appendChild(btn); g.appendChild(note); vid.after(g);
|
||||
}
|
||||
}
|
||||
|
||||
async function api(path, body) {
|
||||
@@ -62,7 +84,8 @@
|
||||
function busy(btn, fn) {
|
||||
return async () => { if (btn.disabled) return; btn.disabled = true; err(''); try { await fn(); } catch (e) { err(e.message || 'Something went wrong.'); } finally { btn.disabled = false; } };
|
||||
}
|
||||
const codeOpts = () => ({ honeypot: $('jnWebsite'), host: $('jnCheck') });
|
||||
const pageClick = (() => { const q = new URLSearchParams(location.search); return q.get('lsclk') || q.get('lsid') || ''; })(); // the LinkSpin click in this page's address: travels with the requests, the cookie may be refused in a frame (reporting only)
|
||||
const codeOpts = () => ({ honeypot: $('jnWebsite'), host: $('jnCheck'), ref: linkTok, angle: v || '', lsclk: pageClick }); // the page's own token rides with the code request (cookie may be blocked in a frame)
|
||||
const send = busy($('jnSend'), async () => {
|
||||
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
|
||||
$('jnCodeRow').hidden = false; $('jnVerify').hidden = false; $('jnSend').hidden = true; $('jnResend').hidden = false;
|
||||
@@ -72,14 +95,18 @@
|
||||
IAP.status(r.sent ? 'Code sent. Check your inbox (and spam, the first time).' : 'Dev mode: code filled in.', 'ok');
|
||||
$('jnCode').focus();
|
||||
});
|
||||
$('jnSend').addEventListener('click', send);
|
||||
// framed: the code would arrive but the sign-in cookie would be refused, so the sign-up continues in a full window
|
||||
// with the email filled in (the link carries the invite token, so the sponsor holds)
|
||||
let framed = false; try { framed = window.top !== window.self; } catch (e) { framed = true; }
|
||||
$('jnSend').addEventListener('click', framed ? () => { const t = new URL(location.href); const em = ($('jnEmail').value || '').trim(); if (em) t.searchParams.set('email', em); window.open(t.toString(), '_blank', 'noopener'); IAP.status('Opened InstantAdPay in a new tab. Finish joining there.', 'ok'); } : send);
|
||||
try { const em = new URLSearchParams(location.search).get('email'); if (em && $('jnEmail') && !$('jnEmail').value) $('jnEmail').value = em.slice(0, 120); } catch (e) {}
|
||||
$('jnResend').addEventListener('click', busy($('jnResend'), async () => {
|
||||
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
|
||||
if (r.devCode) $('jnCode').value = r.devCode;
|
||||
IAP.status('Fresh code sent.', 'ok');
|
||||
}));
|
||||
$('jnVerify').addEventListener('click', busy($('jnVerify'), async () => {
|
||||
await api('/api/auth/email/verify', { email: $('jnEmail').value, code: $('jnCode').value, newsletter: !!$('jnNews').checked, followups: !!$('jnNews').checked });
|
||||
await api('/api/auth/email/verify', { email: $('jnEmail').value, code: $('jnCode').value, newsletter: !!$('jnNews').checked, followups: !!$('jnNews').checked, ref: linkTok, lsclk: pageClick });
|
||||
IAP.status('You are in. Taking you to your dashboard…', 'ok');
|
||||
location.href = '/my?welcome=1'; // dashboard runs the username step + welcome tour on arrival
|
||||
}));
|
||||
@@ -89,6 +116,11 @@
|
||||
// sponsor line (the link opened most recently sets the sponsor; it locks at account creation)
|
||||
let sponsorName = '';
|
||||
const linkTok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
|
||||
// Shown inside another site (a traffic-exchange frame)? Browsers refuse our cookies there, so the invitation
|
||||
// could be lost. Offer the full window; the link carries the token, so the top-level visit sets the cookie.
|
||||
try { if (window.top !== window.self) { const n = document.createElement('p'); n.className = 'small'; n.style.cssText = 'margin:0 0 10px;padding:10px 12px;border:1px solid var(--line-strong);border-radius:10px;background:var(--mint-soft)';
|
||||
n.innerHTML = '<b>Viewing this inside another site?</b> <a href="' + location.href.replace(/"/g, '') + '" target="_top" rel="noopener">Open InstantAdPay in a full window</a> so your invitation stays attached to your account.';
|
||||
const row = $('jnEmail') && $('jnEmail').closest('p'); if (row) row.parentNode.insertBefore(n, row); } } catch (e) {}
|
||||
fetch('/api/sponsor' + (linkTok ? '?ref=' + encodeURIComponent(linkTok) : '')).then(r => r.json()).then(sp => {
|
||||
if (sp && sp.invited && sp.name) {
|
||||
sponsorName = sp.name;
|
||||
@@ -99,10 +131,10 @@
|
||||
}
|
||||
}).catch(() => {});
|
||||
// package ladder (dollar constants + live POL quote)
|
||||
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
|
||||
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader', 6: 'Starter', 7: 'Elite' };
|
||||
fetch('/api/catalog').then(r => r.json()).then(c => {
|
||||
const wrap = $('jnLadder'); if (!wrap || !c.products) return;
|
||||
wrap.innerHTML = c.products.filter(p => p.active !== false).map(p =>
|
||||
wrap.innerHTML = c.products.filter(p => p.active !== false).sort((a, b) => a.priceCents - b.priceCents).map(p =>
|
||||
'<div class="jn-pk"><div class="n">' + (NAMES[p.id] || 'Package ' + p.id) + '</div><div class="p">' + IAP.fmtUsd(p.priceCents) + '</div><div class="c">' + Number(p.creditAmount).toLocaleString() + ' credits</div>'
|
||||
+ (p.costWei ? '<div class="small muted">' + IAP.fmtPol(p.costWei) + ' POL now</div>' : '') + '</div>').join('');
|
||||
}).catch(() => {});
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// partner kit pages (/partners/<slug>): copy buttons + toast (2026-09-29)
|
||||
(function(){
|
||||
var toast=document.getElementById('toast'),tm;
|
||||
function say(t){toast.textContent=t;toast.classList.add('on');clearTimeout(tm);tm=setTimeout(function(){toast.classList.remove('on')},1400)}
|
||||
function copy(text,btn){
|
||||
function fallback(){var r=document.createRange();var el=btn.previousElementSibling||btn.parentElement;r.selectNodeContents(el);var s=getSelection();s.removeAllRanges();s.addRange(r);say('Select and copy')}
|
||||
try{navigator.clipboard.writeText(text).then(function(){say('Copied')},fallback)}catch(e){fallback()}
|
||||
}
|
||||
document.querySelectorAll('[data-copy]').forEach(function(b){b.addEventListener('click',function(){copy(b.getAttribute('data-copy'),b)})});
|
||||
document.querySelectorAll('[data-copy-el]').forEach(function(b){b.addEventListener('click',function(){var el=document.getElementById(b.getAttribute('data-copy-el'));copy(el.textContent,b)})});
|
||||
})();
|
||||
@@ -0,0 +1,71 @@
|
||||
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
|
||||
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on Downline Banners or Viral Banner Blitz shows here
|
||||
// at once. Usernames are network-wide: the member's InstantAdPay username is their sponsor link on those sites even if they never
|
||||
// visited them. Nothing is stored here.
|
||||
window.IAPNetKits = (function () {
|
||||
const SITES = [
|
||||
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
|
||||
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' }
|
||||
];
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const $ = id => document.getElementById(id);
|
||||
let user = '', cur = '', cache = {}, txt = [];
|
||||
try { cur = localStorage.getItem('iap.netkit') || ''; } catch (e) {}
|
||||
if (!SITES.some(s => s.key === cur)) cur = SITES[0].key;
|
||||
function setUser(u) { if (u && u !== user) { user = u; cache = {}; } }
|
||||
async function copy(t, btn) {
|
||||
try { await navigator.clipboard.writeText(t); } catch (e) { const a = document.createElement('textarea'); a.value = t; document.body.appendChild(a); a.select(); try { document.execCommand('copy'); } catch (e2) {} a.remove(); }
|
||||
if (window.IAP && IAP.status) IAP.status('Copied.', 'ok');
|
||||
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1300); }
|
||||
}
|
||||
const cb = (t, label, cls) => { txt.push(t); return '<button type="button" class="btn small ' + (cls == null ? 'sec' : cls) + '" data-nkc="' + (txt.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
|
||||
function pick() {
|
||||
const p = $('nkPick'); if (!p) return;
|
||||
p.innerHTML = SITES.map(s => '<button type="button" class="chip-t' + (s.key === cur ? ' on' : '') + '" data-nk="' + s.key + '">' + esc(s.name) + '</button>').join('');
|
||||
p.querySelectorAll('[data-nk]').forEach(b => b.addEventListener('click', () => { cur = b.dataset.nk; try { localStorage.setItem('iap.netkit', cur); } catch (e) {} pick(); show(); }));
|
||||
}
|
||||
function render(site, k) {
|
||||
txt = [];
|
||||
const by = {}; const angles = [];
|
||||
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
|
||||
let h = '<p class="muted small" style="margin:0 0 12px">' + esc(site.blurb) + '</p>';
|
||||
// tracked links (2026-11-14): the site's LinkSpin network link, credited here to InstantAdPay as the site that sent the visit
|
||||
const strip = (label, url, cls) => '<div class="promo-strip" style="padding:0 0 12px"><div><span class="eyebrow" style="margin:0 0 4px">' + esc(label) + '</span><div class="mono small" style="overflow-wrap:anywhere">' + esc(url) + '</div></div><span>' + cb(url, 'Copy link', cls) + '</span></div>';
|
||||
const fromHere = u => String(u).replace(/([?&]src=)[a-z0-9]+/i, '$1iap');
|
||||
h += k.links.map(l => strip(l.label, l.url, '') + (l.tracked ? strip(l.label + ', tracked', fromHere(l.tracked), 'sec') : '')).join('');
|
||||
if (k.links.some(l => l.tracked)) h += '<p class="muted small" style="margin:0 0 12px">A tracked link goes through LinkSpin first, so the network can see the visit came from InstantAdPay, then opens the same page with your username. Use either one.</p>';
|
||||
h += '<div class="card-head" style="margin-top:6px"><h3>Creatives</h3><span class="sub">every HTML snippet already links to you</span></div>';
|
||||
angles.forEach(a => {
|
||||
h += '<details class="promo-block nk-set"' + (a === angles[0] ? ' open' : '') + '><summary class="pb-head" style="cursor:pointer"><span class="lab"><b>' + esc(a.angleLabel) + '</b></span> <span class="muted small">' + by[a.angle].length + ' sizes</span></summary><div class="nk-grid">'
|
||||
+ by[a.angle].map(c => '<figure class="nk-fig"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(c.url) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy" style="max-width:' + Math.min(c.w, c.w > 600 ? 420 : c.w) + 'px"></a>'
|
||||
+ '<figcaption class="small"><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + '×' + c.h + '</span></figcaption><div class="pb-actions"><a class="btn small sec" href="' + esc(c.url) + '" target="_blank" rel="noopener" download>Download</a> ' + cb(c.url, 'Copy URL') + ' ' + cb(c.html, 'Copy HTML') + '</div></figure>').join('')
|
||||
+ '</div></details>';
|
||||
});
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Short lines</h3><span class="sub">chats, comments, text ads, signatures</span></div>'
|
||||
+ k.lines.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Headlines</h3></div>' + k.headlines.map(t => '<div class="promo-block"><div class="pb-text"><b>' + esc(t) + '</b></div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Email</h3><span class="sub">plain text, paste it into any mailer</span></div><div class="promo-block"><div class="pb-head"><span class="lab">Subject:</span> ' + esc(k.email.subject) + '</div><div class="pb-text">' + esc(k.email.body) + '</div><div class="pb-actions">' + cb(k.email.subject, 'Copy subject') + ' ' + cb(k.email.body, 'Copy email', '') + '</div></div>';
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Social posts</h3></div>' + k.posts.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t, 'Copy post') + '</div></div>').join('');
|
||||
if (k.note) h += '<p class="muted small" style="margin:12px 0 0">' + esc(k.note) + '</p>';
|
||||
if (k.promotePage) h += '<p class="small" style="margin:8px 0 0">The same kit is on <a href="' + esc(k.promotePage + '?u=' + encodeURIComponent(user)) + '" target="_blank" rel="noopener">' + esc(k.name) + ' › Promote</a>.</p>';
|
||||
return h;
|
||||
}
|
||||
async function show() {
|
||||
const box = $('nkBody'); if (!box) return;
|
||||
const site = SITES.find(s => s.key === cur);
|
||||
if (!user) { box.innerHTML = '<p class="muted">Pick a username first: it becomes your link on every network site.</p>'; return; }
|
||||
box.innerHTML = '<p class="muted small">Loading the ' + esc(site.name) + ' kit...</p>';
|
||||
try {
|
||||
if (!cache[cur]) {
|
||||
const r = await fetch(site.feed + '?u=' + encodeURIComponent(user), { cache: 'no-store' });
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
cache[cur] = await r.json();
|
||||
}
|
||||
if (cur !== site.key) return;
|
||||
box.innerHTML = render(site, cache[cur]);
|
||||
box.querySelectorAll('[data-nkc]').forEach(b => b.addEventListener('click', () => copy(txt[Number(b.dataset.nkc)], b)));
|
||||
} catch (e) { box.innerHTML = '<p class="muted">Could not load the ' + esc(site.name) + ' kit right now. Try again in a minute.</p>'; }
|
||||
}
|
||||
function load(u) { if (u) setUser(u); pick(); show(); }
|
||||
return { load, setUser, SITES };
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
// "Part of the network" footer line for pages that do not load common.js (Marty 2026-11-14 trust pack): company line + the network
|
||||
// list from the hub (/api/network-sites, built-in copy if it does not answer). The current site comes from data-site on this tag.
|
||||
(function () {
|
||||
var me = (document.currentScript && document.currentScript.getAttribute('data-site')) || 'iap';
|
||||
var FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(function (a) { return { id: a[0], name: a[1], url: a[2] }; });
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function run() {
|
||||
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
|
||||
var hasLegal = !!f.querySelector('a[href="/terms"]'); // decided once, before this line adds its own links
|
||||
var host = f.querySelector('.wrap') || f;
|
||||
var box = document.createElement('div'); box.className = 'netline';
|
||||
box.style.cssText = 'flex-basis:100%;width:100%;margin-top:10px;display:flex;gap:6px 14px;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||
host.appendChild(box);
|
||||
var paint = function (list) {
|
||||
box.innerHTML = (hasLegal ? '' : '<span style="flex-basis:100%"><a href="/terms">Terms</a> · <a href="/disclaimer">Earnings Disclaimer</a> · <a href="/privacy">Privacy</a> · <a href="/contract">Contract</a> · <a href="/ledger">Ledger</a> · <a href="/support">Support</a></span>') + '<span style="flex-basis:100%">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
|
||||
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
||||
}).join('');
|
||||
};
|
||||
paint(FALLBACK);
|
||||
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) paint(l); }).catch(function () {});
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
})();
|
||||
@@ -0,0 +1,30 @@
|
||||
// Network sign-in, the sign-in page side (2026-11-12). The SAME file ships in InstantAdPay and LinkSpin (see networksso.js).
|
||||
// On a sign-in screen with no session: ask /api/sso/status once; { check: true } means bounce once through the other site,
|
||||
// which signs the member in here if they are signed in there (the server allows one try per browser per 30 minutes and none
|
||||
// after a sign-out). { hint } means they came from the other site but need the email code here the first time: fill it in.
|
||||
(function () {
|
||||
if (window.__netsso) return; window.__netsso = 1;
|
||||
const BOXES = '#mcEmail,#jnEmail,#siEmail';
|
||||
function fill(email, peer) {
|
||||
let n = 0;
|
||||
const t = setInterval(() => {
|
||||
const el = document.querySelector(BOXES);
|
||||
if (el && el.offsetParent !== null) {
|
||||
clearInterval(t);
|
||||
if (!el.value) el.value = email;
|
||||
if (!document.getElementById('nssoNote')) {
|
||||
const p = document.createElement('p'); p.id = 'nssoNote'; p.className = 'muted small'; p.setAttribute('role', 'note'); p.style.margin = '6px 0';
|
||||
p.textContent = 'Welcome over from ' + peer + '. The first time here, send yourself a code with the same email to finish signing in. After that, ' + peer + ' signs you in here.';
|
||||
(el.closest('label') || el).insertAdjacentElement('afterend', p);
|
||||
}
|
||||
try { el.focus(); } catch (e) {}
|
||||
} else if (++n > 60) clearInterval(t);
|
||||
}, 250);
|
||||
}
|
||||
fetch('/api/sso/status', { credentials: 'same-origin', headers: { Accept: 'application/json' }, cache: 'no-store' })
|
||||
.then(r => r.json()).then(d => {
|
||||
if (!d) return;
|
||||
if (d.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search + location.hash)); return; }
|
||||
if (d.hint) fill(String(d.hint), String(d.peer || 'the other site'));
|
||||
}).catch(() => {});
|
||||
})();
|
||||
@@ -0,0 +1,17 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 420" role="img" aria-label="PassiveDrip">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#1b1446"/><stop offset="1" stop-color="#4c1d95"/></linearGradient>
|
||||
<radialGradient id="coin" cx=".35" cy=".3" r=".8"><stop offset="0" stop-color="#c4a6ff"/><stop offset=".6" stop-color="#8247e5"/><stop offset="1" stop-color="#4b1fa8"/></radialGradient>
|
||||
<linearGradient id="drop" x1="0" y1="0" x2="0" y2="1"><stop offset="0" stop-color="#9fd8ff"/><stop offset="1" stop-color="#3b82f6"/></linearGradient>
|
||||
</defs>
|
||||
<rect width="800" height="420" fill="url(#bg)"/>
|
||||
<g opacity=".18" fill="#ffffff"><circle cx="90" cy="70" r="3"/><circle cx="700" cy="60" r="4"/><circle cx="640" cy="350" r="3"/><circle cx="160" cy="360" r="4"/><circle cx="420" cy="40" r="2"/></g>
|
||||
<path d="M400 60 C400 60 340 140 340 180 a60 60 0 0 0 120 0 C460 140 400 60 400 60 Z" fill="url(#drop)"/>
|
||||
<g transform="translate(400 300)">
|
||||
<ellipse cx="0" cy="34" rx="92" ry="16" fill="#000" opacity=".25"/>
|
||||
<circle r="78" fill="url(#coin)" stroke="#d8c7ff" stroke-width="5"/>
|
||||
<path d="M-28 -24 l28 -16 l28 16 v32 l-28 16 l-28 -16 Z" fill="none" stroke="#ffffff" stroke-width="8" stroke-linejoin="round"/>
|
||||
</g>
|
||||
<text x="40" y="220" font-family="Arial, Helvetica, sans-serif" font-size="44" font-weight="800" fill="#ffffff">PassiveDrip</text>
|
||||
<text x="42" y="256" font-family="Arial, Helvetica, sans-serif" font-size="20" fill="#d8c7ff">Faucet + games, paid in POL</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.5 KiB |
@@ -0,0 +1,64 @@
|
||||
// /presentation (2026-10-15): the narrated Build Wide presentation, caption language pills, and a
|
||||
// sponsor card for whoever shared the link. Public, no sign-in. Works framed (traffic exchanges):
|
||||
// join and sign-in open in a new tab and every internal link carries the sharer's ?ref, because a
|
||||
// cross-site frame usually cannot keep the sponsor cookie.
|
||||
(async function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
const esc = t => String(t || '').replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const framed = (() => { try { return window.top !== window.self; } catch (e) { return true; } })();
|
||||
const ref = String(new URLSearchParams(location.search).get('ref') || '').trim().toLowerCase().replace(/[^a-z0-9_]/g, '').slice(0, 20);
|
||||
try { await IAP.renderNav('presentation'); } catch (e) {}
|
||||
|
||||
// ---- caption pills: Off + one per track; a non-English browser starts in its own language
|
||||
const v = $('prVideo'), bar = $('prCaps');
|
||||
const NAMES = { en: 'English', it: 'Italiano', fr: 'Français', es: 'Español', de: 'Deutsch', pt: 'Português' };
|
||||
const tracks = () => [...(v.textTracks || [])].filter(t => t.kind === 'captions' || t.kind === 'subtitles');
|
||||
function show(lang) {
|
||||
tracks().forEach(t => { t.mode = lang && String(t.language).toLowerCase() === lang ? 'showing' : 'disabled'; });
|
||||
bar.querySelectorAll('button').forEach(b => b.setAttribute('aria-pressed', b.dataset.lang === (lang || '') ? 'true' : 'false'));
|
||||
try { localStorage.setItem('iap.capLang', lang || 'off'); } catch (e) {}
|
||||
}
|
||||
if (v && bar) {
|
||||
bar.innerHTML = '<span class="lab">Captions</span>' + ['', 'en', 'it', 'fr', 'es', 'de', 'pt'].map(l => '<button type="button" data-lang="' + l + '" aria-pressed="false">' + (l ? NAMES[l] : 'Off') + '</button>').join('');
|
||||
bar.querySelectorAll('button').forEach(b => b.addEventListener('click', () => show(b.dataset.lang)));
|
||||
let start = '';
|
||||
try { start = localStorage.getItem('iap.capLang') || ''; } catch (e) {}
|
||||
if (!start) { const nav = String(navigator.language || '').slice(0, 2).toLowerCase(); start = NAMES[nav] && nav !== 'en' ? nav : 'off'; }
|
||||
show(start === 'off' ? '' : start);
|
||||
}
|
||||
|
||||
// ---- links: join / sign-in open a new tab when framed; internal links carry ?ref
|
||||
function decorate(root) {
|
||||
root.querySelectorAll('a[href]').forEach(a => {
|
||||
const h = a.getAttribute('href');
|
||||
if (!h || !h.startsWith('/') || h.startsWith('//') || h.startsWith('/api/')) return;
|
||||
if (framed && /^\/(my|join)(\/|$|\?|#)/.test(h)) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||
if (ref && !/^\/join\//.test(h) && !/[?&]ref=/.test(h)) { const [p, hash] = h.split('#'); a.setAttribute('href', p + (p.includes('?') ? '&' : '?') + 'ref=' + ref + (hash ? '#' + hash : '')); }
|
||||
});
|
||||
}
|
||||
|
||||
// ---- sponsor card: the link's owner (?ref) first, then the visitor's sponsor cookie
|
||||
try {
|
||||
const sp = await (await fetch('/api/sponsor' + (ref ? '?ref=' + encodeURIComponent(ref) : ''))).json();
|
||||
const tok = ref || (sp && sp.ref) || '';
|
||||
if (sp && sp.name && tok && !sp.own) {
|
||||
$('prHead').innerHTML = 'Shared with you by <b>' + esc(sp.name) + '</b>';
|
||||
// /api/sponsor caps the bio at 220 characters, so a capped bio ends mid-word: trim it back to a word and add an ellipsis
|
||||
const bio = sp.bio && sp.bio.length >= 220 ? sp.bio.slice(0, sp.bio.lastIndexOf(' ')).replace(/[\s,;:.—-]+$/, '') + '…' : sp.bio;
|
||||
$('prText').textContent = bio ? bio : 'They can help you get set up in a few minutes, and they will be your sponsor on every platform in the network.';
|
||||
$('prJoin').textContent = 'Join with ' + sp.name;
|
||||
$('prJoin').href = '/join/' + encodeURIComponent(tok) + '?v=wide';
|
||||
$('prIni').textContent = String(sp.name).replace(/^@/, '').slice(0, 1).toUpperCase() || '?';
|
||||
if (sp.avatarUrl && /^https:\/\//.test(sp.avatarUrl)) { const im = $('prImg'); im.src = sp.avatarUrl; im.alt = sp.name; im.hidden = false; $('prIni').hidden = true; im.onerror = () => { im.hidden = true; $('prIni').hidden = false; }; }
|
||||
} else if (sp && sp.own) {
|
||||
$('prHead').textContent = 'This is your presentation link';
|
||||
$('prText').textContent = 'Anyone who opens it sees you here, with a Join button that puts them on your line. Copy it from Promo tools.';
|
||||
$('prJoin').textContent = 'Open Promo tools'; $('prJoin').href = '/my#promo';
|
||||
} else {
|
||||
$('prJoin').href = '/join';
|
||||
}
|
||||
} catch (e) {}
|
||||
if (framed) { $('prJoin').target = '_blank'; $('prJoin').rel = 'noopener'; }
|
||||
decorate(document);
|
||||
setTimeout(() => decorate(document), 1500); // the nav's sign-in link arrives after /api/me
|
||||
})();
|
||||
@@ -8,9 +8,12 @@ window.IAPPromo = (function () {
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const status = (m, c) => (window.IAP && IAP.status) ? IAP.status(m, c) : console.log(m);
|
||||
const angleLink = (link, angle) => angle ? link + '?v=' + angle : link;
|
||||
// the public games page carrying the member's referral (any public page + ?ref sets the sponsor)
|
||||
const gamesLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/games?ref=$1');
|
||||
// The Five Dollar Friday bridge page with the member's referral: /friday?ref=<username>. Any
|
||||
// public page plus ?ref sets the same sponsor cookie as the invite link (viral links, 2026-09-21).
|
||||
const fridayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/friday?ref=$1');
|
||||
const wednesdayLink = link => link.replace(/\/join\/([^/?#]+).*$/, '/wednesday?ref=$1');
|
||||
|
||||
// ── social posts ──
|
||||
const POSTS = [
|
||||
@@ -19,12 +22,15 @@ window.IAPPromo = (function () {
|
||||
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Five Dollar Friday', text: 'Quick one for the group: Five Dollar Friday on InstantAdPay. Any ad package from $5 up earns 20% bonus credits today (Central time, until midnight). The page shows whether it is live right now: {{FRIDAY}}' },
|
||||
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: every Friday, any ad package from $5 earns +20% bonus credits, and every pack pays its sponsor line in the same on-chain transaction. The whole network buys on the same day. Join free and line yours up: {{LINK}}' },
|
||||
{ net: 'Telegram', label: 'Telegram or WhatsApp · Five Dollar Friday', text: 'Reminder for the group: tomorrow is Five Dollar Friday on InstantAdPay. Any pack from $5 up earns +20% credits, and your pack pays your sponsor line the second it settles. Everyone pushes on the same day, and every line gets paid at once. Free to join: {{LINK}}' },
|
||||
{ net: 'X', label: 'X · Wired Wednesday', text: 'Wired Wednesday on InstantAdPay: any ad package from $20 up earns 25% bonus credits, wired into your balance the second the purchase settles and good for any ad format. Every Wednesday, Central time. Free to join: {{WEDNESDAY}}' },
|
||||
{ net: 'Facebook', label: 'Facebook · Wired Wednesday', text: 'Wednesdays on InstantAdPay are different. Buy any ad package from $20 up and 25% extra credits are wired into your balance the second the purchase settles, ready to run on any format, banners, text, video, solo ads, even login ads. No code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction. Midnight to midnight Central. Free to join by email: {{WEDNESDAY}}' },
|
||||
{ net: 'Telegram', label: 'Telegram or WhatsApp group · Wired Wednesday', text: 'Quick one for the group: Wired Wednesday on InstantAdPay. Any ad package from $20 up earns 25% bonus credits today, wired in the second it settles (Central time, until midnight). The page shows whether it is live right now: {{WEDNESDAY}}' },
|
||||
{ net: 'X', label: 'X · instant payout', text: 'No withdraw button. A smart contract on Polygon splits every ad package the second it sells: 50% to the sponsor, 20% to level 2, 10% to level 3. Lands in your own wallet. Watch the ledger move: {{LINK:instant}}' },
|
||||
{ net: 'X', label: 'X · advertiser', text: 'Marketers: you were buying traffic anyway. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Packages from $5. Join free: {{LINK:adspend}}' },
|
||||
{ net: 'X', label: 'X · free join', text: 'Join free. View a few ads, earn credits, run your first campaign for zero dollars. Seven ad formats, real dwell-timed attention, every payout public on Polygon. {{LINK:free}}' },
|
||||
{ net: 'Facebook', label: 'Facebook · story post', text: 'I got tired of "your commission is pending." So I joined a platform where there is no pending. A smart contract on the Polygon blockchain splits every ad package the moment it sells: half to the sponsor, then levels two and three, then the platform. It lands in your own wallet in seconds. No approval queue, no withdrawal button, no 15th of the month.\n\nYou are buying real advertising: banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits. Members earn credits for their attention, so the ads actually get seen.\n\nJoin free, look around, and check the public ledger before you spend a dollar: {{LINK:instant}}\n\nNo income promises. It is advertising, not investing, and crypto carries risk.' },
|
||||
{ net: 'Facebook', label: 'Facebook · skeptic angle', text: 'Every online program I ever joined asked me to trust a back office. This one does not. Every payout is a public transaction on Polygon you can look up yourself, with the wallet addresses and amounts right there. The split is written in a verified smart contract nobody can quietly edit.\n\nFree to join with just an email. The wallet comes out only if you buy a package or switch on payouts. Packages run $5 to $250, and every one of them is ad delivery you can watch running.\n\nTake the tour: {{LINK:ledger}}' },
|
||||
{ net: 'LinkedIn', label: 'LinkedIn · professional', text: 'An experiment in transparent affiliate payouts: InstantAdPay sells advertising packages ($5 to $250) whose sponsor commissions are settled by a verified smart contract on Polygon in the same transaction as the purchase. 50 / 20 / 10 across three levels, 20 percent to the platform, every payment public on the chain.\n\nWhat I find interesting is not the commission. It is that "pending payout" stops being a concept. If you buy traffic for a living and want to see how same-transaction settlement works in practice, the tour is free: {{LINK:adspend}}' },
|
||||
{ net: 'Facebook', label: 'Facebook · skeptic angle', text: 'Every online program I ever joined asked me to trust a back office. This one does not. Every payout is a public transaction on Polygon you can look up yourself, with the wallet addresses and amounts right there. The split is written in a verified smart contract nobody can quietly edit.\n\nFree to join with just an email. The wallet comes out only if you buy a package or switch on payouts. Packages run $5 to $500, and every one of them is ad delivery you can watch running.\n\nTake the tour: {{LINK:ledger}}' },
|
||||
{ net: 'LinkedIn', label: 'LinkedIn · professional', text: 'An experiment in transparent affiliate payouts: InstantAdPay sells advertising packages ($5 to $500) whose sponsor commissions are settled by a verified smart contract on Polygon in the same transaction as the purchase. 50 / 20 / 10 across three levels, 20 percent to the platform, every payment public on the chain.\n\nWhat I find interesting is not the commission. It is that "pending payout" stops being a concept. If you buy traffic for a living and want to see how same-transaction settlement works in practice, the tour is free: {{LINK:adspend}}' },
|
||||
{ net: 'Telegram', label: 'Telegram or WhatsApp group', text: 'Quick one for the group. Ad platform on Polygon where every package splits to sponsor wallets the second it sells. No withdrawals, no pending. Free to join by email, packages from $5, seven ad formats, and you earn credits for viewing. Tour here: {{LINK:instant}}' },
|
||||
{ net: 'Telegram', label: 'Telegram or WhatsApp group · free angle', text: 'If you want to test an ad network without spending anything: join free, view a handful of ads, earn credits, run your first campaign on the house. Payouts are on the public Polygon ledger. {{LINK:free}}' }
|
||||
];
|
||||
@@ -32,6 +38,7 @@ window.IAPPromo = (function () {
|
||||
// ── text a friend (SMS-sized) ──
|
||||
const TEXTS = [
|
||||
{ angle: 'friday', title: '"Five Dollar Friday"', text: 'Heads up: Fridays on InstantAdPay any ad package from $5 up gets 20% bonus credits, Central time. Page tells you if it is live right now: {{FRIDAY}}' },
|
||||
{ angle: 'wednesday', title: '"Wired Wednesday"', text: 'Heads up: Wednesdays on InstantAdPay any ad package from $20 up gets 25% bonus credits wired in the second it settles, Central time. Page tells you if it is live right now: {{WEDNESDAY}}' },
|
||||
{ angle: '', title: '"Thought of you"', text: 'Hey, found an ad platform where the commission lands in your wallet the second someone buys. No pending, no withdraw button. Free to look: {{LINK}}' },
|
||||
{ angle: 'instant', title: '"Before the page reloads"', text: 'Random thought. What if your commission showed up before the thank-you page finished loading? That is literally how this works: {{LINK:instant}}' },
|
||||
{ angle: 'adspend', title: '"You buy ads anyway"', text: 'You already buy traffic. This one pays your line every time someone in it buys ads, same transaction, on Polygon. Two-minute look: {{LINK:adspend}}' },
|
||||
@@ -42,9 +49,10 @@ window.IAPPromo = (function () {
|
||||
// ── email swipes ──
|
||||
const SWIPES = [
|
||||
{ tier: 'Five Dollar Friday', subject: 'Tomorrow is Five Dollar Friday', body: 'Quick heads-up.\n\nTomorrow is Five Dollar Friday on InstantAdPay. Any ad package from $5 up, bought on Friday (Central time), earns +20% bonus credits the moment it settles.\n\nHere is why it matters: every pack pays its sponsor line in the same transaction, on the Polygon blockchain. When the whole network buys on the same day, every line gets paid at once, and you can watch it happen on the public ledger.\n\nIt is free to join. Line up your pack tonight so you are ready when Friday starts:\n{{LINK}}\n\nAdvertising with a referral program. Not an investment, no income guaranteed.' },
|
||||
{ tier: 'Wired Wednesday', subject: 'Tomorrow is Wired Wednesday', body: 'Quick heads-up.\n\nTomorrow is Wired Wednesday on InstantAdPay. Any ad package from $20 up, bought on Wednesday (Central time), earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included. Nothing to set up, nothing to claim.\n\nAnd like every pack, it pays the sponsor line in the same transaction on the Polygon blockchain, public on the ledger.\n\nIf you have been meaning to get a pack, tomorrow is the day: {{WEDNESDAY}}\n\nNo income promises. Advertising, not investing.' },
|
||||
{ tier: 'Short', subject: 'Paid the second it sells', body: 'Quick one.\n\nI joined an ad platform where every package splits to sponsor wallets in the same transaction as the sale. No pending payouts, no withdraw button. It is on the Polygon blockchain, and every payment is public.\n\nJoin free, look at the ledger, decide later: {{LINK:instant}}\n\nNo income promises. Advertising, not investing.' },
|
||||
{ tier: 'Standard', subject: 'Your wallet gets paid instantly', body: 'You know the usual drill. Someone buys on your link, you wait for a payout. Maybe days. Maybe an approval hold. Maybe a "your account is under review."\n\nInstantAdPay does not work like that.\n\nA smart contract on the Polygon blockchain handles every purchase the second it happens. 50% to the sponsor. 20% to the next level. 10% to the one after that. 20% to the platform. Each split lands directly in your own wallet. No withdrawal button. No "request payout." No approval queue.\n\nThe money just shows up.\n\nYou can watch every transaction on the public ledger. Real time. Anyone can verify it.\n\nFree to join. Packages from $5 to $250. No income promises. It is advertising, not investing.\n\n{{LINK}}' },
|
||||
{ tier: 'Long', subject: 'The ad network with no pending payouts', body: 'Let me tell you what you are actually looking at, because "crypto ad platform" can mean anything.\n\nInstantAdPay sells advertising. Five packages, $5 to $250. A package mints ad credits, and one credit is one cent of delivery across seven formats: display banners, text ads, full-screen login ads, solo ads delivered into member inboxes, video ads, featured links, and verified visits. Members earn credits for their attention, with a timer that pauses when they look away, so your ad is seen by a person, not a script.\n\nNow the part that made me join.\n\nWhen anyone in your line buys a package, a verified smart contract on Polygon splits the payment in that same transaction: 50 percent to their direct sponsor, 20 percent to level two, 10 percent to level three, 20 percent to the platform. It lands in real wallets in seconds. There is no balance to withdraw because nothing is ever held.\n\nEvery one of those payments is public. Open the ledger, click a transaction, read it on Polygonscan.\n\nJoining is free and only needs an email. Your wallet comes out when you buy a package or switch on payouts. If you never spend a dollar, you can still view ads, earn credits, and run a small campaign on those.\n\nHave a look: {{LINK:instant}}\n\nOne honest line: nobody is promising you an income. Results depend on your effort, and crypto carries risk of loss.' },
|
||||
{ tier: 'Standard', subject: 'Your wallet gets paid instantly', body: 'You know the usual drill. Someone buys on your link, you wait for a payout. Maybe days. Maybe an approval hold. Maybe a "your account is under review."\n\nInstantAdPay does not work like that.\n\nA smart contract on the Polygon blockchain handles every purchase the second it happens. 50% to the sponsor. 20% to the next level. 10% to the one after that. 20% to the platform. Each split lands directly in your own wallet. No withdrawal button. No "request payout." No approval queue.\n\nThe money just shows up.\n\nYou can watch every transaction on the public ledger. Real time. Anyone can verify it.\n\nFree to join. Packages from $5 to $500. No income promises. It is advertising, not investing.\n\n{{LINK}}' },
|
||||
{ tier: 'Long', subject: 'The ad network with no pending payouts', body: 'Let me tell you what you are actually looking at, because "crypto ad platform" can mean anything.\n\nInstantAdPay sells advertising. Seven packages, $5 to $500. A package mints ad credits, and one credit is one cent of delivery across seven formats: display banners, text ads, full-screen login ads, solo ads delivered into member inboxes, video ads, featured links, and verified visits. Members earn credits for their attention, with a timer that pauses when they look away, so your ad is seen by a person, not a script.\n\nNow the part that made me join.\n\nWhen anyone in your line buys a package, a verified smart contract on Polygon splits the payment in that same transaction: 50 percent to their direct sponsor, 20 percent to level two, 10 percent to level three, 20 percent to the platform. It lands in real wallets in seconds. There is no balance to withdraw because nothing is ever held.\n\nEvery one of those payments is public. Open the ledger, click a transaction, read it on Polygonscan.\n\nJoining is free and only needs an email. Your wallet comes out when you buy a package or switch on payouts. If you never spend a dollar, you can still view ads, earn credits, and run a small campaign on those.\n\nHave a look: {{LINK:instant}}\n\nOne honest line: nobody is promising you an income. Results depend on your effort, and crypto carries risk of loss.' },
|
||||
{ tier: 'Follow-up', subject: 'Did you see the ledger?', body: 'Following up on the ad platform I sent over.\n\nIf you only look at one thing, look at the live ledger. Every purchase and every payout, with real wallet addresses, in the order they happened. That is the whole pitch: nothing to take on faith.\n\n{{LINK:ledger}}\n\nIf it is not for you, no worries at all.' }
|
||||
];
|
||||
|
||||
@@ -53,7 +61,7 @@ window.IAPPromo = (function () {
|
||||
{ q: 'Which crypto do I get paid in?', truth: 'One coin, one network: POL, the native coin of Polygon. Packages are dollar-priced and settled in POL at the live Chainlink rate; every payout is sent as POL to the recipient\'s own Polygon wallet in the same transaction. No tokens, no other chains, no stablecoins.', say: 'You get paid in POL, which is Polygon\'s own coin, straight into your wallet the moment a package in your line sells. Any Polygon wallet works, MetaMask, SafePal, Phantom, and if you have never held crypto you can buy POL with a card inside the member area. {{LINK}}' },
|
||||
{ q: 'Is this a pyramid scheme?', truth: 'You are buying advertising that actually runs: a credit is one cent of delivery across seven live formats, and members earn credits for dwell-timed attention. Sponsor payments are referral commissions written as constants in a verified contract, paid only when a real package sells. Nobody has to recruit to use the ads, and joining costs nothing.', say: 'Fair question. Here is the test I use: is there a real product that people would buy with no referral involved? Here the product is ad delivery, seven formats, one cent per credit, and you can watch your campaign serving. The sponsor split is a referral commission on those sales, fixed in a public contract. Join free and run the ads with zero referrals if you like. {{LINK:free}}' },
|
||||
{ q: 'I do not have a crypto wallet. I am not technical.', truth: 'Joining needs only an email and a 6-digit code. The wallet comes out only when someone buys a package or switches on payouts, and the site walks them through it. A card on-ramp (MoonPay) delivers POL straight to their own wallet. Email first, wallet second.', say: 'You do not need one to join. It is email only, no password even. The wallet shows up later, only if you decide to buy a package or want payouts, and the site walks you through it step by step. Start here and look around first: {{LINK}}' },
|
||||
{ q: 'What am I actually buying?', truth: 'Ad credits minted on-chain the moment a package is bought: $5 = 500, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500. Credits spend on banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits, with live stats per campaign. Only the buyer\'s campaigns can spend them.', say: 'Advertising. A package mints credits, one credit is one cent of delivery, and you spend them on seven ad formats from your own dashboard with live stats. The $5 package is 500 credits, the $250 package is 32,500. You can see the formats before you spend anything: {{LINK:adspend}}' },
|
||||
{ q: 'What am I actually buying?', truth: 'Ad credits minted on-chain the moment a package is bought: $5 = 500, $10 = 1,000, $20 = 2,000, $50 = 5,500, $100 = 12,000, $250 = 32,500, $500 = 70,000. Credits spend on banners, text ads, login ads, solo ads to member inboxes, video ads, featured links and verified visits, with live stats per campaign. Only the buyer\'s campaigns can spend them.', say: 'Advertising. A package mints credits, one credit is one cent of delivery, and you spend them on seven ad formats from your own dashboard with live stats. The $5 package is 500 credits, the $500 package is 70,000. You can see the formats before you spend anything: {{LINK:adspend}}' },
|
||||
{ q: 'Who holds my money?', truth: 'Nobody. A purchase is one Polygon transaction that splits to the sponsor line and the platform wallets immediately. The site never holds balances, and the contract source is verified on Polygonscan and Sourcify. Overpayment refunds itself in the same transaction.', say: 'That is the part I like most: nobody holds it. The purchase is a single blockchain transaction that pays the sponsor line and the platform in the same moment. There is no balance sitting anywhere waiting for a withdrawal. The contract code is public and verified, and every payment is on the ledger: {{LINK:ledger}}' },
|
||||
{ q: 'What if POL drops?', truth: 'Packages are priced in dollars and settled in POL at the live Chainlink rate at the moment of purchase. Payouts arrive as POL in the recipient\'s own wallet immediately, so what they do with it is their call. This is advertising, not an investment, and POL is volatile like any crypto asset.', say: 'Packages are dollar priced, so $20 is $20 worth of POL at that moment. Payouts land in your wallet right away, and it is your money from that second. Crypto does move, so treat it as advertising you bought, not an investment. {{LINK}}' },
|
||||
{ q: 'Why would anyone buy ads here?', truth: 'The members are marketers who already buy traffic. Viewers earn credits only after a server-timed dwell, so impressions are real people. Solo ads reach member inboxes with a guaranteed delivery count, verified visits are one unique member per visit, and banner and text ads also syndicate to a partner ad network.', say: 'Because the people on it are marketers, and they get paid to actually look. Every view is dwell-timed on the server, solo ads land in real inboxes with a guaranteed count, and verified visits are one real person each. You can watch your own campaign serve: {{LINK:adspend}}' },
|
||||
@@ -62,7 +70,7 @@ window.IAPPromo = (function () {
|
||||
];
|
||||
|
||||
function fillLink(text, link) {
|
||||
return text.replace(/\{\{FRIDAY\}\}/g, fridayLink(link)).replace(/\{\{LINK(?::([a-z]+))?\}\}/g, (m, a) => angleLink(link, a));
|
||||
return text.replace(/\{\{GAMES\}\}/g, gamesLink(link)).replace(/\{\{FRIDAY\}\}/g, fridayLink(link)).replace(/\{\{WEDNESDAY\}\}/g, wednesdayLink(link)).replace(/\{\{LINK(?::([a-z]+))?\}\}/g, (m, a) => angleLink(link, a));
|
||||
}
|
||||
function copyBtn(text, label) {
|
||||
const b = document.createElement('button');
|
||||
@@ -94,6 +102,8 @@ window.IAPPromo = (function () {
|
||||
// hook videos: one per angle; the matched link continues the same hook on the join page
|
||||
const VID_BASE = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
|
||||
const VIDEOS = [
|
||||
{ angle: 'wide', file: 'buildwide', title: 'Build wide: watch the payments flow', hook: 'Width unlocks depth. Watch fifty percent land, then the deeper levels open.', caption: 'Here is the one move every leader starts with: go wide. Each person you bring in who buys advertising pays you fifty percent the moment they buy. Two buyers open your second level, five open the third. Watch the payments flow, then join free: {{LINK:wide}}' },
|
||||
{ angle: 'play', title: 'If you have time to play', hook: 'If you have time to play a game on your phone, you have time to build a business.', caption: 'If you have time to play a game on your phone, you have time to build a business. These free games pay real Polygon to your wallet, on chain, where anyone can check it. Share your games link instead of just playing. Watch it and play free: {{LINK:play}}' },
|
||||
{ angle: 'instant', title: 'Paid before the page reloads', hook: 'What if your commission landed before the thank-you page finished loading?', caption: 'What if your commission landed before the thank-you page finished loading? On InstantAdPay a smart contract splits every ad package the second it sells, straight to wallets, on a public ledger. Free to join by email: {{LINK:instant}}' },
|
||||
{ angle: 'adspend', title: 'You were buying traffic anyway', hook: 'Every ad dollar you have ever spent went one direction. Out.', caption: 'Every ad dollar you have ever spent went one direction. Out. Here the ad spend in your line pays you back in the same transaction. Seven formats, packages from $5, free to join: {{LINK:adspend}}' },
|
||||
{ angle: 'free', title: 'Watch first, spend never', hook: 'You can run your first ad campaign here for exactly zero dollars.', caption: 'Run your first ad campaign for exactly zero dollars. Join free by email, earn credits by viewing ads, launch a real campaign, and watch real payouts land on a public ledger before you spend a cent: {{LINK:free}}' },
|
||||
@@ -103,10 +113,12 @@ window.IAPPromo = (function () {
|
||||
// the six front doors: the plain invite link plus one page per hook angle
|
||||
const ANGLES = [
|
||||
{ angle: '', name: 'General', hook: 'The whole picture', use: 'What InstantAdPay is, the payment split, join free. Use it when you have not said anything specific yet.' },
|
||||
{ angle: 'play', name: 'Play', hook: 'If you have time to play', use: 'For people who play games on their phone. The page shows the games video and a Play the free games button with your referral, then the free sign-up.' },
|
||||
{ angle: 'instant', name: 'Instant', hook: 'Paid before the page reloads', use: 'For anyone burned by pending commissions. The page opens on the on-chain payout that lands in seconds.' },
|
||||
{ angle: 'adspend', name: 'Ad spend', hook: 'You buy ads anyway', use: 'For marketers who already pay for traffic. Frames it as advertising that also pays your line when they buy.' },
|
||||
{ angle: 'free', name: 'Free', hook: 'Costs nothing to try', use: 'For skeptics and beginners. Join free, earn credits by viewing, run a first campaign without spending.' },
|
||||
{ angle: 'ledger', name: 'Ledger', hook: 'No back office, no payday', use: 'For people who have waited on a payout. Every payment is public on Polygonscan and nothing is ever held.' },
|
||||
{ angle: 'wide', name: 'Wide', hook: 'Width unlocks depth', use: 'For team builders and anyone weighing the plan. The page opens on the Build Wide video: fifty percent landing, then levels two and three opening at two and five buyers.' },
|
||||
{ angle: 'two', name: 'Two', hook: 'Two buyers open level two', use: 'For team builders. The 2-then-5 qualification ladder and how a line stacks under you.' }
|
||||
];
|
||||
function fill(link, me) {
|
||||
@@ -135,7 +147,8 @@ window.IAPPromo = (function () {
|
||||
+ (navigator.share ? '<button class="btn small sec" type="button">Share</button>' : '') + '</div></div>'; // Share = the phone's share sheet; desktops have none, so no button
|
||||
const [copyBtn, shareBtn] = row.querySelectorAll('button');
|
||||
copyBtn.onclick = async () => { try { await navigator.clipboard.writeText(url); status((a.name === 'General' ? 'Invite' : a.name) + ' link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
if (shareBtn) shareBtn.onclick = async () => { try { await navigator.share({ title: 'InstantAdPay', text: a.hook, url }); } catch (e) { if (!(e && e.name === 'AbortError')) status('Could not open the share sheet.', 'bad'); } };
|
||||
// the share sheet gets one ready message with the link inside it: some apps (Telegram among them) keep only the text field
|
||||
if (shareBtn) shareBtn.onclick = async () => { try { await navigator.share({ title: 'InstantAdPay', text: (a.angle ? a.hook + ': ' : 'Have a look: ') + url }); } catch (e) { if (!(e && e.name === 'AbortError')) status('Could not open the share sheet.', 'bad'); } };
|
||||
al.appendChild(row);
|
||||
}
|
||||
}
|
||||
@@ -184,15 +197,15 @@ window.IAPPromo = (function () {
|
||||
if (vw && vw.dataset.filled !== link) {
|
||||
vw.dataset.filled = link; vw.innerHTML = '';
|
||||
for (const v of VIDEOS) {
|
||||
const mlink = angleLink(link, v.angle);
|
||||
const mlink = v.games ? gamesLink(link) : angleLink(link, v.angle);
|
||||
const card = document.createElement('div'); card.className = 'pv';
|
||||
card.innerHTML = '<div class="pv-head"><span class="pb-net">' + esc(v.angle) + ' angle</span> <b>' + esc(v.title) + '</b><div class="muted small">' + esc(v.hook) + '</div></div>'
|
||||
+ '<video src="' + VID_BASE + v.angle + '.mp4" poster="' + VID_BASE + v.angle + '.jpg" preload="none" controls playsinline style="width:100%;max-width:640px;border-radius:12px;background:#000;margin:10px 0"></video>'
|
||||
+ '<video src="' + VID_BASE + (v.file || v.angle) + '.mp4" poster="' + VID_BASE + (v.file || v.angle) + '.jpg" preload="none" controls playsinline style="width:100%;max-width:640px;border-radius:12px;background:#000;margin:10px 0"></video>'
|
||||
+ '<p class="small"><span class="muted">Matched link:</span> <span class="mono" style="overflow-wrap:anywhere">' + esc(mlink) + '</span></p>';
|
||||
const row = document.createElement('p'); row.className = 'pb-actions';
|
||||
row.appendChild(copyBtn(mlink, 'Copy matched link'));
|
||||
row.appendChild(linkBtn(VID_BASE + v.angle + '.mp4', 'Download 16:9'));
|
||||
row.appendChild(linkBtn(VID_BASE + v.angle + '-portrait.mp4', 'Download 9:16'));
|
||||
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '.mp4', 'Download 16:9'));
|
||||
row.appendChild(linkBtn(VID_BASE + (v.file || v.angle) + '-portrait.mp4', 'Download 9:16'));
|
||||
card.appendChild(row);
|
||||
const cap = fillLink(v.caption, link);
|
||||
const extras = [
|
||||
@@ -267,6 +280,157 @@ window.IAPPromo = (function () {
|
||||
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img src="' + src + '" alt="' + s + '" style="max-width:100%;height:auto;border-radius:8px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); bg.appendChild(d); }
|
||||
}
|
||||
// Games (2026-10-06, Marty: one tab for every game instead of a pill each). A picker drives one panel: games with their own
|
||||
// kit (PolHunter, Spooky Doors) show it; the rest get link, share image and posts. Every game gets the 10 standard banners
|
||||
// from banners.adrotate.xyz, each embed linked to the member (PolHunter takes ?r=, the other games ?ref=).
|
||||
const gms = $('promo-games');
|
||||
if (gms && token && gms.dataset.filled !== token) {
|
||||
gms.dataset.filled = token;
|
||||
const enc = encodeURIComponent;
|
||||
// short image host (2026-11-03, Michael Camire via Marty): /b/<slug>/<file> on the share domain serves the game-banners CDN files in
|
||||
// place; the ~105-character CDN URLs were cut off by exchange and safelist image fields. 728x90.png expands to <slug>-728x90.png.
|
||||
const CDN = ((typeof SHARE_DOMAIN === 'string' && SHARE_DOMAIN) ? 'https://' + SHARE_DOMAIN : location.origin) + '/b/';
|
||||
const preLaunch = (y, m, d) => Date.now() < Date.UTC(y, m - 1, d, 5); // before midnight Central on that day
|
||||
const GAMES = [
|
||||
// the public games page (2026-10-10, Marty: "make sure that's in the promo tools for everyone"): every game on one page, with the member's referral on the Join button
|
||||
{ slug: 'allgames', name: 'All games (one page)', link: 'https://instantadpay.com/games?ref=', img: 'https://instantadpay.com/banners/iap-games-1200x630.jpg', sub: 'every game in the network on one public page, open now and opening next',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Every game in the InstantAdPay network on one page: a word puzzle, a hidden-object hunt, a match-3, a runner, a scavenger hunt, a cyberpunk battler, a brick breaker, a mining game. Free to play, and they pay POL to the wallet on your account. {L}' },
|
||||
{ name: 'Friendly post', text: 'If you like small games that actually pay something, this is the page I send people. Every one is free, and they all pay POL on Polygon for first clears, levels, bosses and daily puzzles. Pick one: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {L}' }] },
|
||||
// EnjoyBestGames arcade (2026-10-31, Marty): the engagement site. Hundreds of free HTML5 games draw the crowd; the featured
|
||||
// "Games that pay Polygon" row is the only part that pays, and every game link there carries the member's ref through the
|
||||
// ?r= cookie (30 days). The site's own images live on the game-banners CDN like the other kits.
|
||||
{ slug: 'enjoybestgames', name: 'EnjoyBestGames arcade', link: 'https://enjoybestgames.com/?r=', img: CDN + 'enjoybestgames/og-enjoybestgames.jpg', sub: 'free arcade, the Polygon games pay',
|
||||
note: 'EnjoyBestGames is an engagement site: hundreds of free HTML5 games people already search for. The featured row, Games that pay Polygon, is our network games, and those are the only ones that pay. The rest are there to draw the crowd and keep them on the site. Your link sets a 30-day cookie, so anyone who plays a featured game or clicks the strip lands on InstantAdPay as your referral.',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Free games site I keep open on my phone: hundreds of HTML5 games, nothing to install. The featured row is the games that pay Polygon to your wallet when you clear levels and bosses. Play free: {L}' },
|
||||
{ name: 'Friendly post', text: 'If you like casual games, bookmark this one. EnjoyBestGames has hundreds of free games in every genre, and a featured row of games that actually pay POL on Polygon for first clears and daily puzzles. Start with any of them: {L}' },
|
||||
{ name: 'Casual gamer angle', text: 'Puzzle, racing, arcade, word games, match-3. All free, all in the browser. And the Games that pay Polygon row does what it says. {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'Hundreds of free games, and the Polygon ones pay: {L}' }] },
|
||||
// Warp & Wares (2026-10-29, the 30-day season game): shows once 'warpwares' is in the public games list (gamesLive, in season)
|
||||
{ slug: 'warpwares', name: 'Warp & Wares', link: 'https://warpwares.saasy.top/?ref=', img: 'https://warpwares.saasy.top/og-warpwares.jpg', sub: 'space trading season that pays Polygon',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Warp & Wares is a free 30-day space trading season. One shared galaxy, 200 turns a day for everyone: buy low, sell high, hold your sectors, build a base, run a team. The weekly territory and trader prizes pay Polygon, and the season leaderboard pays at the close. {L}' },
|
||||
{ name: 'Friendly post', text: 'If you ever played Trade Wars on a BBS, this is that feeling again, on your phone. Warp & Wares: 30 days, 1,200 sectors, three goods, a team of five, and prizes in Polygon at published positions. Free to play: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'New season game in the network: Warp & Wares. 200 turns a day, trade and hold territory, weekly Polygon prizes. Free: {L}' }] },
|
||||
// Turkey Drop (2026-10-28, the Thanksgiving season game): shows only while it is in the public games list (gamesLive, through Nov 30) and from Nov 2
|
||||
{ slug: 'turkeydrop', name: 'Turkey Drop', link: 'https://turkeydropgame.com/?ref=', img: CDN + 'turkeydrop/og-turkeydrop.jpg', sub: 'Thanksgiving game that pays Polygon, through Nov 30',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Turkey Drop is a free Thanksgiving game. The radio station helicopter is dropping turkeys over the mall, and you swing the net to catch them before they splat. Score milestones pay Polygon the first time you reach them, and the top 3 each week win a Polygon prize. Here through Nov 30: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'Thanksgiving game in the network: Turkey Drop. Catch the turkeys before they splat, score milestones pay Polygon. Free, through Nov 30: {L}' }] },
|
||||
// POL Miner (2026-10-28): shows once 'polminer' is in gamesLive (the public games list), like PolyBreak
|
||||
{ slug: 'polminer', name: 'POL Miner', link: 'https://polminer.com/?ref=', img: CDN + 'polminer/og-polminer.jpg', sub: 'mining game that pays Polygon',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'POL Miner is a free mining game. Dig down through the layers, haul ore up to sell, upgrade your pick, lamp and cart, and beat a drill boss every 30 m. The rare pink Polygon crystals pay Polygon to the wallet on your InstantAdPay account. {L}' },
|
||||
{ name: 'Friendly post', text: 'This one is easy to lose an hour in. POL Miner is free, it plays fine on a phone, and you sign in with your InstantAdPay account. Each pink Polygon crystal you dig out pays Polygon, and so does each drill boss the first time you beat it. Give it a dig: {L}' },
|
||||
{ name: 'Crystal angle', text: 'Somewhere under the gravel there is a pink glow. In POL Miner the rare Polygon crystals pay Polygon when you dig them out. Free to play: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: POL Miner. Free mining game, the pink Polygon crystals pay Polygon: {L}' }] },
|
||||
{ slug: 'polybreak', name: 'PolyBreak', link: 'https://polybreak.app/?ref=', img: CDN + 'polybreak/og-polybreak.jpg', sub: 'brick breaker that pays Polygon',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'PolyBreak is a free brick breaker in the old Amiga arcade style. Smash a wall of glass jewel bricks, grab the capsules, and catch the purple Polygon gem when it drops. Your first clear of each round pays Polygon to the wallet on your InstantAdPay account. {L}' },
|
||||
{ name: 'Friendly post', text: 'I grew up on brick breakers, so this one got me. PolyBreak is free, it plays great on a phone, and it signs in with your InstantAdPay account. First round clears pay Polygon, and so does every purple gem you catch. Out of paddles? Visit a member\'s page and you get one more. Give it a try: {L}' },
|
||||
{ name: 'Gem angle', text: 'Keep one eye on the bricks and one eye on the top of the screen. Every so often a purple Polygon gem drifts down in PolyBreak. Catch it with your paddle and it pays Polygon to your wallet. Free to play: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyBreak. Free brick breaker, pays Polygon for first round clears and gem catches: {L}' }] },
|
||||
{ slug: 'polywarriors', name: 'PolyWarriors', link: 'https://www.polywarriors.com/?ref=', img: 'https://www.polywarriors.com/og-polywarriors.jpg', sub: 'cyberpunk battler with NFT warrior cards',
|
||||
// launch trailer (2026-10-12, Marty approved): 16:9 + 9:16 cuts and a poster on Spaces; the caption carries the member's link
|
||||
video: { base: 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/', file: 'polywarriors-trailer.mp4', portrait: 'polywarriors-trailer-portrait.mp4', poster: 'polywarriors-trailer.jpg', best: 'landscape for Facebook, X and YouTube; vertical for Shorts, Reels and TikTok',
|
||||
cap: 'PolyWarriors just opened: a free cyberpunk fighting game. Recruit warriors born with their own traits and rarity, beat 24 arena rivals, duel other members. First wins pay Polygon to your wallet and your first warrior mints free as an NFT. {L} #PolyWarriors #Polygon #NFT #gaming' },
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'PolyWarriors is a free cyberpunk battler. Recruit warriors that are each born with their own traits and rarity, fight through 24 arena rivals, and challenge other members in duels that play out while you are away. Your first win over each rival pays Polygon to the wallet on your InstantAdPay account, and your first warrior mints to your wallet as an NFT, free. {L}' },
|
||||
{ name: 'Friendly post', text: 'I have been playing PolyWarriors, a turn-based fighting game with a cyberpunk look. Every warrior is one of a kind, you can mint yours, fuse three of a kind into something rarer, and battle other members. Free to play, and it pays Polygon for first wins: {L}' },
|
||||
{ name: 'Collector angle', text: 'Every PolyWarriors warrior is born with its own traits, rarity and serial, minted on Polygon when you forge it. Rares, Epics and Legendaries trade between members on the marketplace. Your first mint is free; after that every $5 ad package on InstantAdPay earns a mint pass. Start here: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'New game in the network: PolyWarriors. Free cyberpunk battler, pays Polygon for first wins, your first warrior mints free: {L}' }] },
|
||||
{ slug: 'gemkingdom', name: 'Gem Kingdom', link: 'https://gemkingdom.app/?ref=', img: 'https://gemkingdom.app/fantasy/og-gemkingdom.jpg', sub: 'fantasy match-3 with boss battles',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Gem Kingdom is a fantasy match-3 you can start playing free. Lead three heroes, beat the Goblin King’s bosses and rebuild your village. A one-time $5 Royal Charter opens the last three chapters and their POL rewards. Play here: {L}' },
|
||||
{ name: 'Friendly post', text: 'Looking for a game to unwind with? Gem Kingdom is match-3 with a story: forge weapons, collect stars and climb the leaderboard. Free in your browser: {L}' }] },
|
||||
{ slug: 'roadagent', name: 'Road Agent', link: 'https://roadagent.app/?ref=', img: 'https://roadagent.app/og-roadagent.jpg', sub: 'night highway shooter',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Road Agent is a free night-highway shooter in the old arcade spirit. Shoot the hostiles, spare the civilians, pull into the weapons truck. Every sector you clear for the first time pays POL.' + (preLaunch(2026, 10, 15) ? ' Opens Thursday Oct 15.' : '') + ' {L}' },
|
||||
{ name: 'Friendly post', text: 'I have been playing Road Agent, a top-down highway shooter with a twist: clear a sector and it pays POL. No wallet needed to start, just your InstantAdPay email. Free in your browser: {L}' }] },
|
||||
{ slug: 'driprunner', name: 'Drip Runner', link: 'https://driprunner.app/?ref=', img: 'https://driprunner.app/og-driprunner.jpg', sub: 'quick runner game',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'Drip Runner is a quick free runner game. Hop the network, dodge the drones, clear chapters and refuel for POL rewards. Play in your browser: {L}' },
|
||||
{ name: 'Friendly post', text: 'Got two minutes? Drip Runner is a fast little runner game I keep coming back to. See how far you get: {L}' }] },
|
||||
{ slug: 'clutterhunt', name: 'ClutterHunt', link: 'https://clutterhunt.com/?ref=', img: CDN + 'clutterhunt/og-harvest-farmhouse.jpg', sub: 'hidden-object game, Harvest Farmhouse rooms through Nov 30',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'ClutterHunt is a free hidden-object game, and the Harvest Farmhouse just opened: six new rooms through Nov 30, a clock running, and everything moves each time you play. First clears pay POL. Can you three-star Expert? {L}' },
|
||||
{ name: 'Friendly post', text: 'If you like spot-the-object puzzles, try ClutterHunt. New farmhouse rooms this month, free in your browser, with POL rewards for clearing rooms: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'ClutterHunt has six new Harvest Farmhouse rooms through Nov 30. Free hidden-object game, first clears pay POL: {L}' }] },
|
||||
{ slug: 'spellwheel', name: 'SpellWheel', link: 'https://spellwheel.com/?ref=', img: 'https://spellwheel.com/og-spellwheel.jpg', sub: 'letter-wheel word game',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'SpellWheel is a free word game. Swipe the letters on the wheel to fill the grid, one place at a time.' + (preLaunch(2026, 10, 10) ? ' Opens Saturday Oct 10.' : '') + ' {L}' },
|
||||
{ name: 'Friendly post', text: 'Word game fans, this one is for you. SpellWheel: swipe letters, fill the grid, and earn POL rewards as you clear levels. Free in your browser: {L}' }] },
|
||||
{ slug: 'spookydoors', name: 'Spooky Doors', link: 'https://spookydoors.com/?ref=', kit: 'promo-spookydoors', seasonal: true },
|
||||
{ slug: 'polhunter', name: 'PolHunter', link: 'https://polhunter.com/?r=', kit: 'promo-polhunter' }];
|
||||
const SIZES = [['728x90', 'Leaderboard'], ['468x60', 'Banner'], ['320x50', 'Mobile banner'], ['300x250', 'Medium rectangle'], ['336x280', 'Large rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Wide skyscraper'], ['120x600', 'Skyscraper'], ['300x600', 'Half page'], ['600x300', 'Traffic exchange / splash page']];
|
||||
const avail = { spookydoors: false, roadagent: !preLaunch(2026, 10, 15), polybreak: false, polminer: false, warpwares: false, turkeydrop: false }; // Warp & Wares: in the public games list (its season window applies there) // PolyBreak joins once it is in gamesLive (public games list) // seasonal: the Spooky Doors kit says whether its season is showing; Road Agent joins the list on its launch day
|
||||
const list = () => GAMES.filter(g => avail[g.slug] !== false);
|
||||
let cur = null; try { cur = localStorage.getItem('iap.gmGame'); } catch (e) {}
|
||||
const draw = () => {
|
||||
const L = list(); const g = L.find(x => x.slug === cur) || L[0]; cur = g.slug;
|
||||
try { localStorage.setItem('iap.gmGame', cur); } catch (e) {}
|
||||
$('gmPick').innerHTML = L.map(x => '<button class="chip-t' + (x === g ? ' on' : '') + '" type="button" data-gm="' + x.slug + '">' + esc(x.name) + '</button>').join('');
|
||||
const link = g.link + enc(token);
|
||||
GAMES.forEach(x => { if (x.kit && $(x.kit)) $(x.kit).hidden = x !== g; });
|
||||
$('gmGeneric').hidden = !!g.kit;
|
||||
if (!g.kit) {
|
||||
$('gmTitle').textContent = g.name; $('gmSub').textContent = g.sub || '';
|
||||
const gn = $('gmNote'); if (gn) { gn.textContent = g.note || ''; gn.hidden = !g.note; }
|
||||
$('gmLink').textContent = link;
|
||||
$('gmLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const posts = g.posts.map(p => ({ name: p.name, text: p.text.replace('{L}', link) })), hook = posts[0].text.replace(link, '').trim();
|
||||
const sh = $('gmShare'); sh.innerHTML = '';
|
||||
[linkBtn('https://x.com/intent/tweet?text=' + enc(posts[0].text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(posts[0].text), 'WhatsApp')].forEach(b => sh.appendChild(b));
|
||||
const gi = $('gmImg'); gi.hidden = true; gi.onload = () => { if (gi.dataset.want === g.img) gi.hidden = false; }; gi.onerror = () => { gi.hidden = true; }; gi.dataset.want = g.img; gi.src = g.img; // hidden until the new game's image loads (no stale picture) $('gmImg').alt = g.name; $('gmImgOpen').href = g.img;
|
||||
$('gmImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(g.img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const gv = $('gmVideo'); if (gv) { gv.innerHTML = ''; gv.hidden = !g.video;
|
||||
if (g.video) { const v = g.video, cap = v.cap.replace('{L}', link); const d = document.createElement('div'); d.className = 'promo-block';
|
||||
d.innerHTML = '<div class="pb-head"><span class="lab">Trailer</span> <span class="muted small">Best on: ' + esc(v.best) + '</span></div><video controls playsinline preload="none" poster="' + v.base + v.poster + '" src="' + v.base + v.file + '" style="width:100%;max-width:480px;border-radius:12px;display:block;margin:8px auto;background:#000"></video><div class="pb-text">' + esc(cap) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions';
|
||||
row.appendChild(linkBtn(v.base + v.file, 'Download 16:9')); if (v.portrait) row.appendChild(linkBtn(v.base + v.portrait, 'Download vertical')); row.appendChild(linkBtn(v.base + v.poster, 'Poster image')); row.appendChild(copyBtn(cap, 'Copy caption'));
|
||||
[linkBtn('https://x.com/intent/tweet?text=' + enc(cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(link), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(cap.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(cap), 'WhatsApp')].forEach(b => row.appendChild(b));
|
||||
d.appendChild(row); gv.appendChild(d); } }
|
||||
const pp = $('gmPosts'); pp.innerHTML = '';
|
||||
for (const p of posts) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(link) + '&text=' + enc(p.text.replace(link, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
|
||||
}
|
||||
const grid = $('gbGrid'); grid.innerHTML = '';
|
||||
for (const [s, n] of SIZES) { const w = s.split('x')[0], h = s.split('x')[1], src = CDN + g.slug + '/' + s + '.png';
|
||||
const code = '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="' + g.name + '"></a>';
|
||||
const d = document.createElement('div'); d.className = 'promo-block'; d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(n) + '</span></div><div style="overflow:auto;margin:8px 0"><img loading="lazy" src="' + src + '" alt="' + esc(g.name) + ' ' + s + '" style="max-width:100%;height:auto;border-radius:6px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(copyBtn(src, 'Copy image URL')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); grid.appendChild(d); }
|
||||
};
|
||||
window.__gmAvail = (slug, on) => { avail[slug] = !!on; draw(); };
|
||||
fetch('/api/public/games').then(r => r.json()).then(d => { for (const sl of ['polybreak', 'polminer', 'warpwares', 'turkeydrop']) if ((d.games || []).some(g => g.slug === sl && (sl === 'turkeydrop' || g.live)) && !(sl === 'turkeydrop' && preLaunch(2026, 11, 2))) window.__gmAvail(sl, true); }).catch(() => {});
|
||||
$('gmPick').addEventListener('click', e => { const b = e.target.closest('[data-gm]'); if (!b) return; cur = b.dataset.gm; draw(); });
|
||||
draw();
|
||||
}
|
||||
// Spooky Doors (Halloween season, 2026-10-02): the member's game link, the share image and two short posts. Shown on the
|
||||
// season window the Games card uses (the server decides; the admin gets a preview before the start), hidden after it.
|
||||
const sdp = $('promo-spookydoors');
|
||||
if (sdp && token && sdp.dataset.filled !== token) {
|
||||
sdp.dataset.filled = token;
|
||||
fetch('/api/my/spookydoors/promo').then(r => r.json()).then(s => {
|
||||
// the Games tab's picker lists Spooky Doors only while its season shows (the server decides)
|
||||
if (!s || !s.show) { sdp.hidden = true; if (window.__gmAvail) window.__gmAvail('spookydoors', false); return; }
|
||||
if (window.__gmAvail) window.__gmAvail('spookydoors', true);
|
||||
const enc = encodeURIComponent, sl = String(s.base || 'https://spookydoors.com') + '/?ref=' + enc(token), img = s.image || 'https://spookydoors.com/og-spookydoors.jpg';
|
||||
const day = (d, back) => { const t = new Date(d + 'T12:00:00Z'); if (back) t.setUTCDate(t.getUTCDate() - 1); return t.toLocaleDateString('en-US', { month: 'short', day: 'numeric', timeZone: 'UTC' }); };
|
||||
const ends = s.season && s.season.end ? day(s.season.end, true) : 'Oct 31';
|
||||
$('sdpSub').textContent = s.preview && s.season ? 'preview: members see this card from ' + day(s.season.start) + ' to ' + ends : 'our Halloween game, limited time, ends ' + ends;
|
||||
$('sdpLink').textContent = sl;
|
||||
$('sdpCopy').onclick = async () => { try { await navigator.clipboard.writeText(sl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
$('sdpImg').onerror = () => { $('sdpImg').hidden = true; }; $('sdpImg').src = img; $('sdpImgOpen').href = img;
|
||||
$('sdpImgCopy').onclick = async () => { try { await navigator.clipboard.writeText(img); status('Image URL copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const SD_POSTS = [
|
||||
{ name: 'Short post', text: 'Trick or treat! \u{1F383} Spooky Doors is a free Halloween game: walk the street, dodge the black cats and bats, knock on doors and fill your candy bucket. Only until Halloween night. Play here: ' + sl },
|
||||
{ name: 'Friendly post', text: 'Something fun for October: I have been playing Spooky Doors, a little Halloween game where every door you knock on opens somebody\u2019s page. Pick a costume and see how much candy you can collect before ' + ends + '. ' + sl },
|
||||
];
|
||||
const pp = $('sdpPosts'); pp.innerHTML = '';
|
||||
for (const p of SD_POSTS) pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>', [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(sl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(sl) + '&text=' + enc(p.text.replace(sl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(p.text), 'WhatsApp')]));
|
||||
}).catch(() => {});
|
||||
}
|
||||
// objections
|
||||
const ob = $('promoObjections');
|
||||
if (ob && ob.dataset.filled !== link) {
|
||||
@@ -285,5 +449,53 @@ window.IAPPromo = (function () {
|
||||
}
|
||||
}
|
||||
|
||||
return { fill, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS };
|
||||
// ── BixPay partner kit (2026-10-29, docs/BIXPAY-INTEGRATION.md). me.bix from /api/me. The three posts are Marty's approved
|
||||
// copy. {L} = the member's TRACKED link (/go/bixpay?s=promo&m=<member>: counted here, then the resolved partner link), so every
|
||||
// asset carries the member's link and the Promo tab can show its clicks. Banners: text only, no BIX logo (brand rules unconfirmed).
|
||||
const BIX_POSTS = [
|
||||
{ name: 'Short post', net: 'X', text: 'I spend my crypto with a Visa card now. BixPay keeps the keys with you, loads from USDT or USDC with no load fee, and works with Apple Pay. Virtual card from $9.99: {L}' },
|
||||
{ name: 'Friendly post', net: 'Facebook', text: 'Earning crypto is one thing. Spending it without jumping through hoops is another. BixPay fixed that for me: a self-custody wallet and a Visa card in one app. Here\'s where I got mine: {L}' },
|
||||
{ name: 'Partner angle', net: 'LinkedIn', text: 'BixPay pays partners on every card and on card spending, ten levels deep. If you\'re building a team anyway, this fits right in: {L}' }
|
||||
];
|
||||
const BIX_SWIPE = { subject: 'A Visa card for the crypto you already earn', body: 'Hey,\n\nQuick one, because this solved something for me.\n\nI earn crypto in a few places, and for a long time the awkward part was spending it. Exchange, bank, waiting, fees. BixPay took that out of the loop: it is a self-custody wallet with a Visa card in one app. You send USDT or USDC to it on Polygon, load the card, and pay wherever Visa is accepted, Apple Pay and Google Pay included.\n\nThe parts I liked:\n- The keys stay with you. It is your wallet, not an account someone else holds.\n- No load fee. 3% per purchase, and BIX\'s terms cover the rest.\n- A virtual card is $9.99 and you can be using it the same day.\n- If you build a team, BixPay pays partners on every card and on card spending, ten levels deep.\n\nUS note: it is open in 31 states so far. If yours is not on the list yet, you can still get the wallet and build.\n\nHere is my link: {L}\n\nBixPay is a separate company. BIX issues the wallet and the card through its banking partners and sets its own fees, limits, eligibility and terms. Crypto assets can lose value.\n\nTalk soon,' };
|
||||
const BIX_CDN = ((typeof SHARE_DOMAIN === 'string' && SHARE_DOMAIN) ? 'https://' + SHARE_DOMAIN : location.origin) + '/b/bixpay/'; // short image host, same files as the game-banners CDN (2026-11-03)
|
||||
const BIX_SIZES = [['728x90', 'Leaderboard'], ['300x250', 'Medium rectangle'], ['468x60', 'Banner'], ['600x300', 'Traffic exchange / splash page']];
|
||||
function fillBix(me) {
|
||||
const b = (me && me.bix) || {}; const sec = $('promo-bixpay'); if (!sec) return;
|
||||
if (!b.live || b.error || !b.go) { sec.hidden = true; return; }
|
||||
const enc = encodeURIComponent, link = b.link, go = b.go.promo;
|
||||
if (sec.dataset.filled === link + '|' + go + '|' + (b.clicks ? b.clicks.total : 0)) return;
|
||||
sec.dataset.filled = link + '|' + go + '|' + (b.clicks ? b.clicks.total : 0);
|
||||
$('bixPromoLink').textContent = link;
|
||||
$('bixPromoUsing').textContent = b.using || '';
|
||||
$('bixPromoSub').textContent = b.whose === 'you' ? 'every link and banner here carries your partner link' : 'add your own partner link in Profile and these switch to yours';
|
||||
$('bixPromoCopy').onclick = async () => { try { await navigator.clipboard.writeText(link); status('Partner link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const sh = $('bixPromoShare'); if (sh) { sh.hidden = !navigator.share; sh.onclick = async () => { try { await navigator.share({ title: 'BixPay', text: 'A Visa card for your crypto: ' + go }); } catch (e) { if (!(e && e.name === 'AbortError')) status('Could not open the share sheet.', 'bad'); } }; }
|
||||
$('bixPromoGo').textContent = go;
|
||||
$('bixPromoGoCopy').onclick = async () => { try { await navigator.clipboard.writeText(go); status('Tracked link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const n = (b.clicks && b.clicks.promo) || 0; $('bixPromoClicks').textContent = n ? 'Clicks so far: ' + n.toLocaleString() + '.' : 'No clicks counted yet.';
|
||||
const pp = $('bixPromoPosts'); pp.innerHTML = '';
|
||||
for (const p of BIX_POSTS) {
|
||||
const text = p.text.replace('{L}', go), lead = text.replace(go, '').trim();
|
||||
const extras = [];
|
||||
if (p.net === 'X') extras.push(linkBtn('https://twitter.com/intent/tweet?text=' + enc(text), 'Post on X'));
|
||||
if (p.net === 'Facebook') extras.push(linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(go), 'Share on Facebook'));
|
||||
if (p.net === 'LinkedIn') extras.push(linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + enc(go), 'Share on LinkedIn'));
|
||||
extras.push(linkBtn('https://t.me/share/url?url=' + enc(go) + '&text=' + enc(lead), 'Telegram'));
|
||||
extras.push(linkBtn('https://wa.me/?text=' + enc(text), 'WhatsApp'));
|
||||
pp.appendChild(block(text, '<span class="pb-net">' + esc(p.name) + '</span>', extras));
|
||||
}
|
||||
const sw = $('bixPromoSwipe'); sw.innerHTML = '';
|
||||
sw.appendChild(block('Subject: ' + BIX_SWIPE.subject + '\n\n' + BIX_SWIPE.body.replace('{L}', go), '<span class="pb-net">Email</span> <b>' + esc(BIX_SWIPE.subject) + '</b>'));
|
||||
const bg = $('bixPromoBanners'); bg.innerHTML = '';
|
||||
for (const [s, nme] of BIX_SIZES) {
|
||||
const w = s.split('x')[0], h = s.split('x')[1], src = BIX_CDN + 'bixpay-' + s + '.png';
|
||||
const code = '<a href="' + go + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="A Visa card for your crypto"></a>';
|
||||
const d = document.createElement('div'); d.className = 'promo-block';
|
||||
d.innerHTML = '<div class="pb-head"><span class="lab">' + s + '</span> <span class="muted small">' + esc(nme) + '</span></div><div style="overflow:auto;margin:8px 0"><img loading="lazy" src="' + src + '" alt="BixPay banner ' + s + '" style="max-width:100%;height:auto;border-radius:6px"></div><div class="pb-text mono small" style="overflow-wrap:anywhere">' + esc(code) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions'; row.appendChild(copyBtn(code, 'Copy embed code')); row.appendChild(copyBtn(src, 'Copy image URL')); row.appendChild(linkBtn(src, 'Open image')); d.appendChild(row); bg.appendChild(d);
|
||||
}
|
||||
}
|
||||
|
||||
return { fill, fillBix, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS, BIX_POSTS, BIX_SWIPE };
|
||||
})();
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
/* Drip Runner refuel: one verified visit, then back to the game with a signed receipt. */
|
||||
(function () {
|
||||
'use strict';
|
||||
var $ = function (id) { return document.getElementById(id); };
|
||||
var q = new URLSearchParams(location.search); var tok = q.get('t') || '';
|
||||
var nonce = '', tokRet = ''; try { var claims = JSON.parse(atob(tok.split('.')[0].replace(/-/g, '+').replace(/_/g, '/'))); nonce = claims.nonce || ''; tokRet = claims.ret || ''; } catch (e) {}
|
||||
// every dead end on this page keeps a way back to the run (Marty, 2026-09-30)
|
||||
var gameHome = tokRet ? tokRet.split('?')[0] : 'https://driprunner.saasy.top/play';
|
||||
var GAME = 'Drip Runner', inGame = false; try { inGame = window.parent !== window; } catch (e) { inGame = true; } // Gem Kingdom shows this page in an overlay (2026-10-03)
|
||||
function setGame(r) { if (!r || !r.game) return; GAME = r.game; var bar = document.querySelector('.rf-bar span'); if (bar) bar.innerHTML = 'InstantAdPay \u00b7 <b>verified visit</b> \u00b7 ' + (r.label || 'refuel') + ' for ' + esc(GAME); }
|
||||
var ret = null, dwell = 8, left = 8, timer = null, done = false;
|
||||
function msg(title, text, backUrl) { $('rfFrame').innerHTML = '<div class="rf-msg" style="background:#0b1020;height:100%"><h1>' + title + '</h1><p>' + text + '</p></div>'; $('rfDone').hidden = true; $('rfCheck').hidden = true; var b = $('rfBack'); b.hidden = false; var to = backUrl || gameHome; b.textContent = backUrl ? 'Back to the game' : 'Back to Drip Runner'; b.onclick = function () { location.href = to; }; }
|
||||
function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); }
|
||||
function api(p, body) { return fetch(p, body ? { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) } : {}).then(function (r) { return r.json(); }); }
|
||||
function ring() { $('rfN').textContent = left; $('rfRing').style.setProperty('--p', ((dwell - left) / dwell * 100) + '%'); }
|
||||
function tick() {
|
||||
if (document.hidden) return; // the timer only runs while the page is in front
|
||||
var vid = document.getElementById('rfVideo'); if (vid && (vid.paused || vid.ended && left > 1)) return; // a video must actually be playing
|
||||
left--; if (left > 0) return ring();
|
||||
clearInterval(timer); ring(); $('rfHint').textContent = 'One quick check to count the visit:';
|
||||
challenge();
|
||||
}
|
||||
function challenge() {
|
||||
api('/api/refuel/challenge?n=' + encodeURIComponent(nonce)).then(function (c) {
|
||||
if (c.early) { setTimeout(challenge, (c.wait || 1) * 1000 + 300); return; }
|
||||
if (c.error) { $('rfHint').textContent = c.error; return; }
|
||||
$('rfPrompt').textContent = 'Tap the ' + c.prompt + ':'; var w = $('rfOpts'); w.innerHTML = '';
|
||||
c.options.forEach(function (em, i) { var b = document.createElement('button'); b.type = 'button'; b.textContent = em; b.addEventListener('click', function () { answer(i); }); w.appendChild(b); });
|
||||
$('rfCheck').hidden = false;
|
||||
});
|
||||
}
|
||||
function answer(i) {
|
||||
api('/api/refuel/done', { n: nonce, answer: i }).then(function (r) {
|
||||
if (r.error) { if (r.retry) return challenge(); $('rfHint').textContent = r.error; $('rfCheck').hidden = true; return; }
|
||||
done = true; $('rfCheck').hidden = true; var gk = GAME === 'Gem Kingdom', ch = GAME === 'ClutterHunt', sw = GAME === 'SpellWheel', ww = GAME === 'Warp & Wares', td = GAME === 'Turkey Drop';
|
||||
$('rfHint').textContent = gk ? 'Visit counted. Your heroes are back on their feet.' : (ch || sw) ? 'Visit counted. Your hint is ready.' : ww ? 'Visit counted. Your bonus turns are waiting on the bridge.' : td ? 'Visit counted. WFWL is back on the air.' : 'Visit counted. Your tank is full.';
|
||||
if (gk && inGame) { try { window.parent.postMessage({ gkContinue: nonce, ok: true }, '*'); } catch (e) {} }
|
||||
var b = $('rfDone'); b.disabled = false; b.textContent = gk ? 'Back to the battle' : ch ? 'Back to the room' : sw ? 'Back to the puzzle' : ww ? 'Back to the bridge' : td ? 'Back on the air' : 'Back to the run'; b.onclick = function () { location.href = r.ret; };
|
||||
setTimeout(function () { location.href = r.ret; }, 1200);
|
||||
});
|
||||
}
|
||||
if (!tok) return msg('No refuel link', 'Open this page from the game’s Refuel button.');
|
||||
api('/api/refuel/open?t=' + encodeURIComponent(tok)).then(function (r) {
|
||||
setGame(r);
|
||||
if (r.error) return msg('Refuel link problem', esc(r.error));
|
||||
if (r.done) { location.href = r.ret; return; }
|
||||
if (r.none) return msg(r.why === 'cap' ? 'That is today’s refuels' : 'No sponsor pages right now', r.why === 'cap' ? 'You have used today’s refuels. Your run and progress are saved, and refuels reopen at midnight Central. Your regular InstantAdPay visits are not affected.' : 'You have used every sponsor page and video running right now. Try again later: new ones start all the time.', r.ret + '&none=1');
|
||||
ret = r.ret; dwell = r.dwell || 8; left = Math.max(1, dwell - (r.elapsed || 0));
|
||||
if (r.mode === 'video') { // no sponsor pages left: a member video ad instead
|
||||
$('rfTitle').textContent = r.title || 'Member video'; $('rfUrl').textContent = 'video ad';
|
||||
$('rfHint').textContent = 'You have visited every sponsor page running right now, so this refuel is a short member video. Keep it playing.';
|
||||
var v = document.createElement('video'); v.id = 'rfVideo'; v.src = r.video.url; v.autoplay = true; v.muted = true; v.playsInline = true; v.setAttribute('playsinline', ''); v.loop = true; v.controls = false;
|
||||
v.style.cssText = 'position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#000';
|
||||
$('rfFrame').innerHTML = ''; $('rfFrame').appendChild(v);
|
||||
var un = document.createElement('button'); un.type = 'button'; un.textContent = 'Tap for sound'; un.style.cssText = 'position:absolute;right:10px;bottom:10px;z-index:2;padding:8px 12px;border-radius:8px;border:0;background:rgba(0,0,0,.6);color:#fff;font:600 12px system-ui';
|
||||
un.onclick = function () { v.muted = false; v.play().catch(function () {}); un.remove(); }; $('rfFrame').appendChild(un);
|
||||
v.play().catch(function () { $('rfHint').textContent = 'Tap the video to start it. The timer runs while it plays.'; v.onclick = function () { v.play(); }; });
|
||||
ring(); timer = setInterval(tick, 1000); return;
|
||||
}
|
||||
$('rfTitle').textContent = r.title || 'Member site'; try { $('rfUrl').textContent = new URL(r.target).hostname; } catch (e) {}
|
||||
var f = document.createElement('iframe'); f.src = r.target; f.setAttribute('referrerpolicy', 'no-referrer'); f.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms allow-popups'); $('rfFrame').innerHTML = ''; $('rfFrame').appendChild(f);
|
||||
var o = $('rfOpen'); o.href = r.target; o.hidden = false;
|
||||
ring(); timer = setInterval(tick, 1000);
|
||||
}).catch(function () { msg('Could not load the visit', 'Check your connection and go back to the game.'); });
|
||||
})();
|
||||
@@ -13,6 +13,20 @@
|
||||
--mono:"Consolas","JetBrains Mono",monospace;
|
||||
--disp:"Sora","Segoe UI",system-ui,sans-serif;
|
||||
--radius:18px;
|
||||
/* 2026-11-01 theme tokens (mirrored from LinkSpin): every surface, text, border and soft fill that used to be a literal
|
||||
in this file, the page inline styles and the UI-drawing scripts. Light values live in :root[data-theme="light"] at
|
||||
the end of this file; themehead.js sets data-theme on <html> before the first paint. */
|
||||
--mint-deep:#1fb894; --mint-pale:#8ffbe3;
|
||||
--mint-faint:rgba(67,232,195,.06); --mint-soft-2:rgba(67,232,195,.16); --mint-line:rgba(67,232,195,.38); --mint-line-2:rgba(67,232,195,.6);
|
||||
--ok:#22c55e; --ok-ink:#04140a; --ok-soft:rgba(34,197,94,.15); --warn:#f0a742; --bad-soft:rgba(255,143,125,.12);
|
||||
--gold:#ffd15c; --gold-2:#f2c94c; --gold-ink:#1a1206; --gold-soft:rgba(242,201,76,.14); --gold-faint:rgba(242,201,76,.04); --gold-line:rgba(242,201,76,.55);
|
||||
--amber-soft:rgba(255,178,56,.12); --amber-line:rgba(255,178,56,.4); --amber-ink:#1a1206;
|
||||
--cyan-soft:rgba(84,204,255,.1); --cyan-line:rgba(84,204,255,.3); --violet-soft:rgba(157,125,255,.12); --violet-line:rgba(157,125,255,.32);
|
||||
--muted-soft:rgba(139,166,156,.12); --muted-line:rgba(139,166,156,.4); --ink-faint:rgba(255,255,255,.04); --line-soft:rgba(84,150,128,.08);
|
||||
--ground-soft:rgba(4,8,7,.5); --field-bg:rgba(4,8,7,.65); --nav-bg:rgba(4,8,7,.75); --side-bg:rgba(10,18,15,.92); --pill-bg:rgba(16,28,24,.7);
|
||||
--panel-grad:linear-gradient(165deg,rgba(24,36,31,.6),rgba(13,19,17,.66)); --panel-grad-deep:linear-gradient(170deg,#0e1c17,#080f0c); --plate-grad:linear-gradient(160deg,#12241e,#0a1411);
|
||||
--sh-lg:0 30px 80px rgba(0,0,0,.6),0 0 60px rgba(67,232,195,.08);
|
||||
color-scheme:dark;
|
||||
}
|
||||
*{box-sizing:border-box}
|
||||
[hidden]{display:none!important} /* beats any display: set by a class (chat panel bug) */
|
||||
@@ -26,7 +40,7 @@ a:hover{text-decoration:underline}
|
||||
.wrap{max-width:1100px;margin:0 auto;padding:0 22px}
|
||||
h1,h2,h3{font-family:var(--disp);letter-spacing:-.015em}
|
||||
/* ── nav: capsule pill ─────────────────────────────── */
|
||||
nav{position:sticky;top:0;z-index:10;background:rgba(4,8,7,.7);backdrop-filter:blur(16px);
|
||||
nav{position:sticky;top:0;z-index:10;background:var(--nav-bg);backdrop-filter:blur(16px);
|
||||
-webkit-backdrop-filter:blur(16px);border-bottom:1px solid var(--line)}
|
||||
nav .wrap{display:flex;align-items:center;gap:20px;min-height:66px;flex-wrap:wrap;padding-top:8px;padding-bottom:8px}
|
||||
.logo{font-family:var(--disp);font-weight:800;font-size:20px;color:var(--ink)}
|
||||
@@ -36,13 +50,13 @@ nav .wrap{display:flex;align-items:center;gap:20px;min-height:66px;flex-wrap:wra
|
||||
.byline b{color:var(--ink);font-weight:600}
|
||||
.bo-side .byline{padding:4px 8px 10px;white-space:normal}
|
||||
@media (max-width:560px){nav .byline{font-size:9.5px}}
|
||||
nav .links{display:flex;gap:4px;flex:1;flex-wrap:wrap;background:rgba(16,28,24,.7);border:1px solid var(--line);
|
||||
nav .links{display:flex;gap:4px;flex:1;flex-wrap:wrap;background:var(--pill-bg);border:1px solid var(--line);
|
||||
border-radius:999px;padding:5px 8px;width:fit-content;flex:0 1 auto;margin:0 auto}
|
||||
nav .links a{color:var(--muted);font-size:13.5px;font-weight:600;padding:7px 14px;border-radius:999px}
|
||||
nav .links a:hover{color:var(--ink);text-decoration:none}
|
||||
nav .links a.active{color:var(--mint);background:rgba(67,232,195,.1)}
|
||||
nav .links a.active{color:var(--mint);background:var(--mint-soft)}
|
||||
#navWallet{font-size:13px;margin-left:auto}
|
||||
.rehearsal{background:rgba(67,232,195,.07);border-bottom:1px solid var(--line);color:var(--muted);
|
||||
.rehearsal{background:var(--mint-faint);border-bottom:1px solid var(--line);color:var(--muted);
|
||||
text-align:center;font-size:12.5px;padding:7px 12px}
|
||||
.rehearsal b{color:var(--mint)}
|
||||
/* ── buttons ───────────────────────────────────────── */
|
||||
@@ -50,14 +64,14 @@ nav .links a.active{color:var(--mint);background:rgba(67,232,195,.1)}
|
||||
padding:13px 26px;font-weight:700;font-size:15px;cursor:pointer;font-family:var(--disp);
|
||||
box-shadow:0 4px 30px rgba(67,232,195,.35);transition:transform .16s ease,box-shadow .16s ease,background .16s ease}
|
||||
.btn:hover{transform:translateY(-2px);background:var(--mint-hi);box-shadow:0 8px 44px rgba(67,232,195,.5);text-decoration:none}
|
||||
.btn.sec{background:transparent;color:var(--mint);border:1px solid rgba(67,232,195,.6);box-shadow:none}
|
||||
.btn.sec:hover{background:rgba(67,232,195,.08);box-shadow:0 4px 26px rgba(67,232,195,.2)}
|
||||
.btn.sec{background:transparent;color:var(--mint);border:1px solid var(--mint-line-2);box-shadow:none}
|
||||
.btn.sec:hover{background:var(--mint-soft);box-shadow:0 4px 26px rgba(67,232,195,.2)}
|
||||
.btn.small{padding:8px 17px;font-size:13px}
|
||||
/* a third, quieter button for actions that are not the main move (Archive). NOT ".ghost": that is
|
||||
the giant footer wordmark and it sets color:transparent, which made the Archive button invisible
|
||||
(Marty, 2026-09-23). */
|
||||
.btn.quiet{background:transparent;color:var(--muted);border:1px solid var(--line-strong);box-shadow:none}
|
||||
.btn.quiet:hover{background:rgba(139,166,156,.1);color:var(--ink);border-color:var(--muted);box-shadow:none}
|
||||
.btn.quiet:hover{background:var(--muted-soft);color:var(--ink);border-color:var(--muted);box-shadow:none}
|
||||
/* the member's campaign actions sat flush against each other on desktop; the mobile rule already
|
||||
had a gap, this gives the wide layout the same room */
|
||||
/* Campaign actions (Marty, 2026-09-23): the column is narrow, so these stack. Left-aligned pills
|
||||
@@ -68,6 +82,13 @@ nav .links a.active{color:var(--mint);background:rgba(67,232,195,.1)}
|
||||
text-align:center;line-height:1.25;white-space:normal}
|
||||
.camp-table td.act .btn:last-child{margin-bottom:0}
|
||||
.btn:disabled{opacity:.45;cursor:default;transform:none;box-shadow:none}
|
||||
/* ── segmented control + the Light / Dark / Auto theme switch (2026-11-01): member-area header, Profile pane, admin header ── */
|
||||
.seg{display:inline-flex;border:1px solid var(--line-strong);border-radius:999px;overflow:hidden;background:var(--pill-bg);vertical-align:middle}
|
||||
.seg button{background:transparent;border:0;border-right:1px solid var(--line-strong);padding:6px 12px;font:700 12px var(--disp);color:var(--muted);cursor:pointer;line-height:1.2}
|
||||
.seg button:last-child{border-right:0} .seg button:hover{color:var(--ink)} .seg button.on{background:var(--mint);color:var(--mint-ink)}
|
||||
.theme-seg button{min-width:0}
|
||||
.bo-top .theme-seg{margin-left:auto;flex:none} .bo-top .bo-rehearsal:not([hidden]) + .theme-seg{margin-left:0}
|
||||
@media (max-width:560px){.bo-top .theme-seg button{padding:6px 9px;font-size:11px}}
|
||||
/* ── hero: centered, light-trail set-piece ─────────── */
|
||||
.hero{position:relative;text-align:center;padding:120px 0 84px;overflow:visible}
|
||||
.hero h1{font-size:clamp(36px,5.4vw,62px);font-weight:700;line-height:1.08;margin:0 auto 18px;max-width:820px;text-wrap:balance}
|
||||
@@ -99,7 +120,7 @@ section{padding:64px 0 8px}
|
||||
.cmp{width:100%;border-collapse:separate;border-spacing:0;font-size:15px;background:var(--panel);border:1px solid var(--line);border-radius:var(--radius);overflow:hidden}
|
||||
.cmp th,.cmp td{padding:13px 16px;border-bottom:1px solid var(--line);vertical-align:top;text-align:left}
|
||||
.cmp th{font-family:var(--disp);font-size:13px;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
.cmp th:last-child,.cmp td:last-child{color:var(--ink);background:rgba(67,232,195,.06)}
|
||||
.cmp th:last-child,.cmp td:last-child{color:var(--ink);background:var(--mint-faint)}
|
||||
.cmp td:first-child{font-weight:700;white-space:nowrap}
|
||||
.cmp td:nth-child(2){color:var(--muted)}
|
||||
.cmp tr:last-child td{border-bottom:0}
|
||||
@@ -113,11 +134,11 @@ h3{font-size:16.5px;margin:0 0 8px;font-weight:700}
|
||||
/* icon-plate feature cards */
|
||||
.plates{display:grid;gap:16px;grid-template-columns:1fr}
|
||||
@media(min-width:760px){.plates{grid-template-columns:1fr 1fr 1fr}}
|
||||
.platecard{background:linear-gradient(170deg,rgba(22,38,32,.6),rgba(10,18,15,.7));border:1px solid var(--line);
|
||||
.platecard{background:var(--panel-grad);border:1px solid var(--line);
|
||||
border-radius:var(--radius);padding:26px 22px;text-align:center;transition:border-color .2s ease,transform .2s ease}
|
||||
.platecard:hover{border-color:var(--line-strong);transform:translateY(-4px)}
|
||||
.plate{width:88px;height:88px;margin:0 auto 18px;border-radius:22px;display:grid;place-items:center;
|
||||
background:linear-gradient(160deg,#12241e,#0a1411);border:1px solid var(--line-strong);
|
||||
background:var(--plate-grad);border:1px solid var(--line-strong);
|
||||
box-shadow:0 0 34px rgba(67,232,195,.15),inset 0 1px 0 rgba(143,251,227,.15)}
|
||||
.plate svg{width:38px;height:38px;stroke:var(--mint);fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
|
||||
.platecard p{color:var(--muted);font-size:14px;margin:0}
|
||||
@@ -129,15 +150,15 @@ h3{font-size:16.5px;margin:0 0 8px;font-weight:700}
|
||||
.flankitem .plate svg{width:24px;height:24px}
|
||||
.flankitem p{color:var(--muted);font-size:13.5px;margin:0}
|
||||
/* ledger mockup frame */
|
||||
.mockup{background:linear-gradient(170deg,#0e1c17,#080f0c);border:1px solid var(--line-strong);border-radius:20px;
|
||||
box-shadow:0 30px 80px rgba(0,0,0,.6),0 0 60px rgba(67,232,195,.08);overflow:hidden}
|
||||
.mockup{background:var(--panel-grad-deep);border:1px solid var(--line-strong);border-radius:20px;
|
||||
box-shadow:var(--sh-lg);overflow:hidden}
|
||||
.mockup .bar{display:flex;gap:6px;align-items:center;padding:11px 14px;border-bottom:1px solid var(--line)}
|
||||
.mockup .bar i{width:9px;height:9px;border-radius:50%;background:#1e3a31;display:inline-block}
|
||||
.mockup .bar .addr{font-family:var(--mono);font-size:11px;color:var(--muted);margin-left:8px;background:rgba(4,8,7,.6);
|
||||
.mockup .bar i{width:9px;height:9px;border-radius:50%;background:var(--line-strong);display:inline-block}
|
||||
.mockup .bar .addr{font-family:var(--mono);font-size:11px;color:var(--muted);margin-left:8px;background:var(--ground-soft);
|
||||
border-radius:999px;padding:3px 12px}
|
||||
.mockup .body{padding:6px 0}
|
||||
.mockup .mrow{display:flex;justify-content:space-between;gap:10px;padding:9px 16px;font-family:var(--mono);
|
||||
font-size:12px;border-bottom:1px solid rgba(84,150,128,.08)}
|
||||
font-size:12px;border-bottom:1px solid var(--line-soft)}
|
||||
.mockup .mrow span:last-child{color:var(--mint)}
|
||||
.mockup .mrow.dim span:last-child{color:var(--muted)}
|
||||
/* 2-col story block: iso illustration + checklist */
|
||||
@@ -147,24 +168,24 @@ h3{font-size:16.5px;margin:0 0 8px;font-weight:700}
|
||||
.checks li{padding:7px 0 7px 30px;position:relative;color:var(--muted);font-size:14.5px}
|
||||
.checks li::before{content:"✓";position:absolute;left:0;top:6px;width:20px;height:20px;border-radius:50%;
|
||||
background:var(--mint-soft);color:var(--mint);font-size:12px;font-weight:700;display:grid;place-items:center;
|
||||
border:1px solid rgba(67,232,195,.35)}
|
||||
border:1px solid var(--mint-line)}
|
||||
.chips{display:flex;gap:8px;margin:14px 0 4px;flex-wrap:wrap}
|
||||
.chip-t{border:1px solid var(--line-strong);border-radius:999px;padding:5px 16px;font-size:12.5px;color:var(--muted);font-family:var(--disp);font-weight:600}
|
||||
.chip-t.on{background:var(--mint);color:var(--mint-ink);border-color:var(--mint)}
|
||||
.iso{filter:drop-shadow(0 24px 50px rgba(0,0,0,.5))}
|
||||
/* level cycler: light the paying generation */
|
||||
#genViz .edge path{stroke:#22523f;transition:stroke .5s ease}
|
||||
#genViz .node-o{fill:#122e25;stroke:#2f6b55;stroke-width:1.3;transition:stroke .5s ease,fill .5s ease}
|
||||
#genViz .node-d{fill:#3f8f74;transition:fill .5s ease}
|
||||
#genViz[data-lvl="1"] .e1 path,#genViz[data-lvl="2"] .e2 path,#genViz[data-lvl="3"] .e3 path{stroke:#43e8c3}
|
||||
#genViz[data-lvl="1"] .g1 .node-o,#genViz[data-lvl="2"] .g2 .node-o,#genViz[data-lvl="3"] .g3 .node-o{stroke:#43e8c3;fill:#11362b}
|
||||
#genViz[data-lvl="1"] .g1 .node-d,#genViz[data-lvl="2"] .g2 .node-d,#genViz[data-lvl="3"] .g3 .node-d{fill:#43e8c3}
|
||||
#genViz .edge path{stroke:var(--line-strong);transition:stroke .5s ease}
|
||||
#genViz .node-o{fill:var(--panel-solid);stroke:var(--mint-line);stroke-width:1.3;transition:stroke .5s ease,fill .5s ease}
|
||||
#genViz .node-d{fill:var(--mint-deep);transition:fill .5s ease}
|
||||
#genViz[data-lvl="1"] .e1 path,#genViz[data-lvl="2"] .e2 path,#genViz[data-lvl="3"] .e3 path{stroke:var(--mint)}
|
||||
#genViz[data-lvl="1"] .g1 .node-o,#genViz[data-lvl="2"] .g2 .node-o,#genViz[data-lvl="3"] .g3 .node-o{stroke:var(--mint);fill:var(--mint-soft-2)}
|
||||
#genViz[data-lvl="1"] .g1 .node-d,#genViz[data-lvl="2"] .g2 .node-d,#genViz[data-lvl="3"] .g3 .node-d{fill:var(--mint)}
|
||||
.chips button{cursor:pointer;background:transparent;font:inherit}
|
||||
.chips button.chip-t{border:1px solid var(--line-strong);color:var(--muted)}
|
||||
.chips button.chip-t.on{background:var(--mint);color:var(--mint-ink);border-color:var(--mint)}
|
||||
/* pricing tiles: mint discipline */
|
||||
.tiles{display:grid;gap:16px;grid-template-columns:repeat(auto-fit,minmax(185px,1fr));align-items:stretch}
|
||||
.tile{position:relative;background:linear-gradient(170deg,rgba(22,38,32,.55),rgba(10,18,15,.65));border:1px solid var(--line);
|
||||
.tile{position:relative;background:var(--panel-grad);border:1px solid var(--line);
|
||||
border-radius:var(--radius);padding:26px 18px;text-align:center;display:flex;flex-direction:column;gap:6px;
|
||||
transition:transform .2s ease,border-color .2s ease}
|
||||
.tile:hover{transform:translateY(-5px);border-color:var(--line-strong)}
|
||||
@@ -173,7 +194,7 @@ h3{font-size:16.5px;margin:0 0 8px;font-weight:700}
|
||||
.tile .cr{color:var(--mint);font-weight:700;font-size:14.5px}
|
||||
.tile .bonus{font-size:12px;color:var(--mint-hi)}
|
||||
.tile .pol{font-family:var(--mono);font-size:12px;color:var(--muted);flex:1}
|
||||
.tile.hot{border:1px solid rgba(67,232,195,.65);box-shadow:0 0 44px rgba(67,232,195,.14)}
|
||||
.tile.hot{border:1px solid var(--mint-line-2);box-shadow:0 0 44px rgba(67,232,195,.14)}
|
||||
.tile.hot::before{content:"MOST POPULAR";position:absolute;top:-11px;left:50%;transform:translateX(-50%);
|
||||
background:var(--mint);color:var(--mint-ink);font-family:var(--disp);font-size:10px;font-weight:800;
|
||||
letter-spacing:.12em;border-radius:999px;padding:4px 14px}
|
||||
@@ -181,14 +202,14 @@ h3{font-size:16.5px;margin:0 0 8px;font-weight:700}
|
||||
.split{display:flex;gap:8px;margin:18px 0}
|
||||
.split div{border-radius:12px;padding:16px 6px;text-align:center;font-size:13px;font-weight:700;font-family:var(--disp);
|
||||
border:1px solid var(--line-strong);color:var(--mint)}
|
||||
.split .s50{flex:5;background:rgba(67,232,195,.16);box-shadow:0 0 30px rgba(67,232,195,.12)}
|
||||
.split .s20{flex:2;background:rgba(67,232,195,.09)}
|
||||
.split .s10{flex:1;background:rgba(67,232,195,.05)}
|
||||
.split .sa{flex:2;background:rgba(139,166,156,.08);color:var(--muted)}
|
||||
.split .s50{flex:5;background:var(--mint-soft-2);box-shadow:0 0 30px rgba(67,232,195,.12)}
|
||||
.split .s20{flex:2;background:var(--mint-soft)}
|
||||
.split .s10{flex:1;background:var(--mint-faint)}
|
||||
.split .sa{flex:2;background:var(--muted-soft);color:var(--muted)}
|
||||
section[id]{scroll-margin-top:84px} /* anchored menu targets clear the sticky nav */
|
||||
/* ticker */
|
||||
.ticker{overflow:hidden;contain:layout paint;border-top:1px solid var(--line);border-bottom:1px solid var(--line);
|
||||
background:rgba(67,232,195,.04);white-space:nowrap;padding:10px 0;
|
||||
background:var(--mint-faint);white-space:nowrap;padding:10px 0;
|
||||
-webkit-mask-image:linear-gradient(90deg,transparent,#000 6%,#000 94%,transparent);
|
||||
mask-image:linear-gradient(90deg,transparent,#000 6%,#000 94%,transparent)}
|
||||
.ticker .inner{display:inline-block;font-family:var(--mono);font-size:12.5px;padding-left:100%;animation:tick 120s linear infinite}
|
||||
@@ -216,32 +237,32 @@ tr:last-child td{border-bottom:0}
|
||||
.feed .t-TierPaid{color:var(--mint)}
|
||||
.feed .t-AdminPaid{color:var(--muted)}
|
||||
.feed .tx a{color:var(--muted);font-size:12px}
|
||||
.badge{display:inline-block;background:var(--mint-soft);color:var(--mint);border:1px solid rgba(67,232,195,.35);
|
||||
.badge{display:inline-block;background:var(--mint-soft);color:var(--mint);border:1px solid var(--mint-line);
|
||||
border-radius:999px;padding:3px 13px;font-size:12px;font-weight:700}
|
||||
.spend-banner{background:linear-gradient(160deg,rgba(242,201,76,.14),rgba(242,201,76,.04));border-color:rgba(242,201,76,.55);text-align:center;padding:22px 20px}
|
||||
.spend-banner .lbl{font-family:var(--disp);font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:#f2c94c}
|
||||
.spend-banner .big{font-family:var(--disp);font-size:clamp(40px,6vw,64px);font-weight:800;color:#f2c94c;line-height:1.05;margin:6px 0 4px;font-variant-numeric:tabular-nums}
|
||||
.spend-banner{background:linear-gradient(160deg,var(--gold-soft),var(--gold-faint));border-color:var(--gold-line);text-align:center;padding:22px 20px}
|
||||
.spend-banner .lbl{font-family:var(--disp);font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:var(--gold-2)}
|
||||
.spend-banner .big{font-family:var(--disp);font-size:clamp(40px,6vw,64px);font-weight:800;color:var(--gold-2);line-height:1.05;margin:6px 0 4px;font-variant-numeric:tabular-nums}
|
||||
.spend-banner .big .unit{font-size:20px;font-weight:700;color:var(--ink)}
|
||||
.spend-banner .sub{color:var(--ink);font-size:15px}
|
||||
.spend-banner .rates{display:flex;gap:8px 18px;flex-wrap:wrap;justify-content:center;margin-top:12px;font-size:12.5px;color:var(--muted)}
|
||||
.spend-banner .rates b{color:var(--ink)}
|
||||
.boot-spin{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;min-height:60vh}
|
||||
.boot-spin .ring{width:46px;height:46px;border-radius:50%;border:4px solid rgba(67,232,195,.18);border-top-color:var(--mint);animation:bootspin .9s linear infinite}
|
||||
.boot-spin .ring{width:46px;height:46px;border-radius:50%;border:4px solid var(--mint-soft-2);border-top-color:var(--mint);animation:bootspin .9s linear infinite}
|
||||
@keyframes bootspin{to{transform:rotate(360deg)}}
|
||||
.bo-top{flex-wrap:wrap}
|
||||
.ad-strip{flex:1 1 100%;font-size:13.5px;padding:8px 0 2px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.ad-strip a{color:var(--ink)}
|
||||
.ad-strip b{color:var(--mint)}
|
||||
.ad-foot{text-align:center}
|
||||
.pv{border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:0 0 16px;background:rgba(4,8,7,.35)}
|
||||
.pv{border:1px solid var(--line);border-radius:14px;padding:16px 18px;margin:0 0 16px;background:var(--ground-soft)}
|
||||
.pv-head b{display:block;font-size:18px;margin:4px 0 2px}
|
||||
.done-big{display:flex;flex-direction:column;align-items:center;gap:6px;padding:26px 16px;text-align:center}
|
||||
.done-big .tick{width:84px;height:84px;border-radius:50%;display:grid;place-items:center;font-size:48px;font-weight:800;color:var(--mint-ink);background:var(--mint);box-shadow:0 0 0 10px rgba(67,232,195,.15),0 10px 30px rgba(67,232,195,.35)}
|
||||
.done-big b{font-family:var(--disp);font-size:22px;margin-top:8px}
|
||||
.badge.amber{background:rgba(139,166,156,.1);border-color:rgba(139,166,156,.4);color:var(--muted)}
|
||||
.badge.amber{background:var(--muted-soft);border-color:var(--muted-line);color:var(--muted)}
|
||||
/* faq */
|
||||
details{border:1px solid var(--line);border-radius:14px;margin:0 0 10px;background:var(--panel)}
|
||||
details[open]{border-color:rgba(67,232,195,.45)}
|
||||
details[open]{border-color:var(--mint-line)}
|
||||
summary{cursor:pointer;padding:16px 20px;font-weight:700;font-family:var(--disp);font-size:15px;list-style:none}
|
||||
summary::before{content:"+";color:var(--mint);font-weight:800;margin-right:12px}
|
||||
details[open] summary::before{content:"−"}
|
||||
@@ -249,7 +270,7 @@ details p{margin:0;padding:0 20px 18px 42px;color:var(--muted);font-size:14.5px}
|
||||
/* closing cta card */
|
||||
.closer{position:relative;display:grid;gap:26px;align-items:center;grid-template-columns:1fr;
|
||||
padding:44px 36px;border-radius:24px;overflow:hidden;margin:80px 0 0;
|
||||
background:linear-gradient(160deg,#0d1d17,#060c0a);border:1px solid var(--line-strong)}
|
||||
background:var(--panel-grad-deep);border:1px solid var(--line-strong)}
|
||||
@media(min-width:880px){.closer{grid-template-columns:1.2fr .8fr}}
|
||||
.closer::before{content:"";position:absolute;width:460px;height:460px;right:-140px;top:-260px;border-radius:50%;
|
||||
background:radial-gradient(circle,rgba(67,232,195,.2),transparent 65%);pointer-events:none}
|
||||
@@ -266,7 +287,7 @@ footer{border-top:1px solid var(--line);margin-top:90px;padding:34px 0 0;color:v
|
||||
box-shadow:0 12px 40px rgba(0,0,0,.55)}
|
||||
#status.ok{border-color:var(--mint)}
|
||||
#status.bad{border-color:var(--bad)}
|
||||
input,select,textarea{background:rgba(4,8,7,.65);border:1px solid var(--line-strong);color:var(--ink);border-radius:11px;
|
||||
input,select,textarea{background:var(--field-bg);border:1px solid var(--line-strong);color:var(--ink);border-radius:11px;
|
||||
padding:11px 14px;font-size:14.5px;font-family:inherit}
|
||||
input[type=range]{padding:0;border:0;background:transparent;accent-color:var(--mint);height:28px;vertical-align:middle}
|
||||
input:focus,select:focus,textarea:focus{border-color:var(--mint)}
|
||||
@@ -277,18 +298,18 @@ textarea{resize:vertical;font:inherit}
|
||||
.bo-body{background:var(--ground)}
|
||||
.bo{display:grid;grid-template-columns:236px 1fr;min-height:100vh}
|
||||
.bo-side{position:sticky;top:0;height:100vh;overflow-y:auto;scrollbar-width:none;-ms-overflow-style:none;display:flex;flex-direction:column;gap:22px;
|
||||
padding:22px 16px;background:rgba(10,18,15,.92);border-right:1px solid var(--line)}
|
||||
padding:22px 16px;background:var(--side-bg);border-right:1px solid var(--line)}
|
||||
.bo-side .logo{font-size:19px;padding:0 8px}
|
||||
.bo-menu{display:flex;flex-direction:column;gap:4px}
|
||||
.bo-menu button{display:flex;align-items:center;gap:11px;background:transparent;border:0;color:var(--muted);
|
||||
font:600 14px var(--disp);padding:11px 12px;border-radius:11px;cursor:pointer;text-align:left;
|
||||
border-left:3px solid transparent}
|
||||
.bo-menu a{display:flex;align-items:center;gap:11px;color:var(--muted);font:600 14px var(--disp);padding:11px 12px;border-radius:11px;text-align:left;border-left:3px solid transparent;text-decoration:none}
|
||||
.bo-menu a:hover{color:var(--ink);background:rgba(67,232,195,.05)}
|
||||
.bo-menu a:hover{color:var(--ink);background:var(--mint-faint)}
|
||||
.bo-menu a svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex:0 0 auto}
|
||||
.bo-menu button svg{width:18px;height:18px;stroke:currentColor;fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;flex:0 0 auto}
|
||||
.bo-menu button:hover{color:var(--ink);background:rgba(67,232,195,.05)}
|
||||
.bo-menu button.on{color:var(--mint);background:rgba(67,232,195,.09);border-left-color:var(--mint)}
|
||||
.bo-menu button:hover{color:var(--ink);background:var(--mint-faint)}
|
||||
.bo-menu button.on{color:var(--mint);background:var(--mint-soft);border-left-color:var(--mint)}
|
||||
.bo-links{display:flex;flex-direction:column;gap:2px;padding:14px 12px;border-top:1px solid var(--line)}
|
||||
.bo-cap{font-family:var(--mono);font-size:10.5px;letter-spacing:.18em;text-transform:uppercase;color:var(--muted);margin-bottom:6px}
|
||||
.bo-links a{color:var(--muted);font-size:13.5px;padding:5px 0}
|
||||
@@ -300,7 +321,7 @@ textarea{resize:vertical;font:inherit}
|
||||
.bo-pagefoot a{color:var(--muted)}
|
||||
.bo-pagefoot a:hover{color:var(--ink);text-decoration:none}
|
||||
.bo-top{display:flex;align-items:center;gap:16px;padding:16px 26px;border-bottom:1px solid var(--line);
|
||||
background:rgba(6,10,8,.75);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);position:sticky;top:0;z-index:5}
|
||||
background:var(--nav-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);position:sticky;top:0;z-index:5}
|
||||
.bo-top h2{font-size:20px}
|
||||
#boBurger{display:none;background:transparent;border:1px solid var(--line-strong);color:var(--ink);
|
||||
border-radius:9px;font-size:17px;padding:5px 11px;cursor:pointer}
|
||||
@@ -339,11 +360,11 @@ textarea{resize:vertical;font:inherit}
|
||||
.feat-day .fd-occ{font-family:var(--mono);font-size:11px;color:var(--muted)}
|
||||
.feat-day.open2 .fd-occ{color:var(--mint)}
|
||||
/* ── featured rotation strip ── */
|
||||
.feat-top{max-width:760px;margin:16px auto;border:1px solid rgba(255,177,56,.5)}
|
||||
.feat-top{max-width:760px;margin:16px auto;border:1px solid var(--amber-line)}
|
||||
.feat-strip{display:flex;justify-content:center;margin-top:10px}
|
||||
.feat-strip a{max-width:728px;width:100%;display:flex;justify-content:space-between;gap:10px;padding:11px 14px;border-radius:10px;
|
||||
background:var(--panel);border:1px solid #ffb238;color:var(--ink);text-decoration:none;font-weight:600}
|
||||
.feat-strip a:hover{border-color:#ffd15c;box-shadow:0 0 0 1px rgba(255,177,56,.4)}
|
||||
background:var(--panel);border:1px solid var(--amber);color:var(--ink);text-decoration:none;font-weight:600}
|
||||
.feat-strip a:hover{border-color:var(--gold);box-shadow:0 0 0 1px var(--amber-line)}
|
||||
.feat-strip .by{font-size:12px;color:var(--muted);font-weight:500;white-space:nowrap}
|
||||
.feat-strip .by{font-size:12px;color:var(--muted);font-weight:500;white-space:nowrap}
|
||||
/* ── achievement badges ── */
|
||||
@@ -352,22 +373,22 @@ textarea{resize:vertical;font:inherit}
|
||||
.badge-a .badge-img{width:150px;height:150px;border-radius:14px;object-fit:cover;border:1px solid var(--line-strong)}
|
||||
.badge-a.locked .badge-img{filter:grayscale(.85) brightness(.5);opacity:.7}
|
||||
.badge-a .medal{width:76px;height:76px;border-radius:50%;display:grid;place-items:center;position:relative;
|
||||
background:radial-gradient(circle at 50% 35%,rgba(67,232,195,.28),rgba(9,26,19,.9));
|
||||
background:radial-gradient(circle at 50% 35%,var(--mint-soft-2),var(--panel-solid));
|
||||
border:2px solid var(--mint);box-shadow:0 0 18px rgba(67,232,195,.3)}
|
||||
.badge-a.locked .medal{background:rgba(139,166,156,.08);border-color:var(--line-strong);box-shadow:none;filter:grayscale(1);opacity:.5}
|
||||
.badge-a.locked .medal{background:var(--muted-soft);border-color:var(--line-strong);box-shadow:none;filter:grayscale(1);opacity:.5}
|
||||
.badge-a .medal svg{width:38px;height:38px;stroke:var(--mint);fill:none;stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round}
|
||||
.badge-a.locked .medal svg{stroke:var(--muted)}
|
||||
.badge-a .bl{font-size:12px;font-weight:700;line-height:1.2}
|
||||
.badge-a .bs{font-size:10.5px;color:var(--muted)}
|
||||
.badge-a .share{font-size:11px;color:var(--mint);cursor:pointer;background:none;border:0;padding:0;text-decoration:underline}
|
||||
/* ── "Your next move": milestone stepper card ── */
|
||||
.next-card{position:relative;overflow:hidden;border-color:rgba(67,232,195,.28)}
|
||||
.next-card{position:relative;overflow:hidden;border-color:var(--mint-line)}
|
||||
.next-card::before{content:"";position:absolute;inset:0;pointer-events:none;background:
|
||||
radial-gradient(420px 150px at 10% 0%,rgba(67,232,195,.12),transparent 70%),
|
||||
radial-gradient(360px 130px at 90% 100%,rgba(157,125,255,.09),transparent 70%)}
|
||||
.nc-head{display:flex;gap:14px;align-items:flex-start;position:relative}
|
||||
.nc-head .pl{flex:0 0 auto;width:44px;height:44px;border-radius:12px;display:grid;place-items:center;
|
||||
background:rgba(67,232,195,.12);border:1px solid rgba(67,232,195,.35)}
|
||||
background:var(--mint-soft-2);border:1px solid var(--mint-line)}
|
||||
.nc-head .pl svg{width:20px;height:20px;stroke:var(--mint);fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
|
||||
.nc-steps{display:flex;margin-top:20px;position:relative;flex-wrap:wrap;row-gap:14px}
|
||||
.nc-step{flex:1;min-width:88px;display:flex;flex-direction:column;align-items:center;gap:7px;
|
||||
@@ -388,20 +409,20 @@ textarea{resize:vertical;font:inherit}
|
||||
.statx{display:flex;gap:14px;align-items:flex-start;background:var(--panel);border:1px solid var(--line);
|
||||
border-radius:var(--radius);padding:18px;position:relative;overflow:hidden}
|
||||
.statx .pl{flex:0 0 auto;width:46px;height:46px;border-radius:13px;display:grid;place-items:center;
|
||||
background:rgba(67,232,195,.1);border:1px solid rgba(67,232,195,.3)}
|
||||
background:var(--mint-soft);border:1px solid var(--mint-line)}
|
||||
.statx .pl svg{width:22px;height:22px;stroke:var(--mint);fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
|
||||
.statx.c-cyan .pl{background:rgba(84,204,255,.1);border-color:rgba(84,204,255,.3)}
|
||||
.statx.c-cyan .pl{background:var(--cyan-soft);border-color:var(--cyan-line)}
|
||||
.statx.c-cyan .pl svg{stroke:var(--cyan)}
|
||||
.statx.c-violet .pl{background:rgba(157,125,255,.12);border-color:rgba(157,125,255,.32)}
|
||||
.statx.c-violet .pl{background:var(--violet-soft);border-color:var(--violet-line)}
|
||||
.statx.c-violet .pl svg{stroke:var(--violet)}
|
||||
.statx.c-amber .pl{background:rgba(255,178,56,.1);border-color:rgba(255,178,56,.3)}
|
||||
.statx.c-amber .pl{background:var(--amber-soft);border-color:var(--amber-line)}
|
||||
.statx.c-amber .pl svg{stroke:var(--amber)}
|
||||
.statx .nv{font-family:var(--disp);font-size:26px;font-weight:800;font-variant-numeric:tabular-nums;line-height:1.1}
|
||||
.statx .lb{font-size:12px;color:var(--muted);text-transform:uppercase;letter-spacing:.08em;margin-top:2px}
|
||||
.chip{display:inline-block;margin-top:7px;font-size:11.5px;font-weight:700;border-radius:999px;padding:2px 10px;
|
||||
background:rgba(67,232,195,.1);color:var(--mint)}
|
||||
.chip.flat{background:rgba(139,166,156,.12);color:var(--muted)}
|
||||
.chip.warm{background:rgba(255,178,56,.12);color:var(--amber)}
|
||||
background:var(--mint-soft);color:var(--mint)}
|
||||
.chip.flat{background:var(--muted-soft);color:var(--muted)}
|
||||
.chip.warm{background:var(--amber-soft);color:var(--amber)}
|
||||
.card-head{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
||||
.card-head .sub{font-size:12px;color:var(--muted)}
|
||||
/* dismiss on the announcement cards at the top of the Overview (Marty, 2026-09-22):
|
||||
@@ -409,16 +430,16 @@ textarea{resize:vertical;font:inherit}
|
||||
.card-x{flex:none;align-self:center;margin:-4px -6px 0 2px;width:28px;height:28px;border-radius:50%;
|
||||
border:1px solid var(--line);background:transparent;color:var(--muted);font-size:19px;line-height:1;
|
||||
cursor:pointer;display:grid;place-items:center;padding:0}
|
||||
.card-x:hover{border-color:var(--line-strong);color:var(--ink);background:rgba(139,166,156,.1)}
|
||||
.card-x:hover{border-color:var(--line-strong);color:var(--ink);background:var(--muted-soft)}
|
||||
/* bar chart (divs, real data) */
|
||||
.barchart{display:flex;align-items:flex-end;gap:6px;height:120px;margin-top:14px}
|
||||
.barchart .bar{flex:1;min-width:6px;background:linear-gradient(180deg,var(--mint),rgba(67,232,195,.25));
|
||||
.barchart .bar{flex:1;min-width:6px;background:linear-gradient(180deg,var(--mint),var(--mint-line));
|
||||
border-radius:5px 5px 2px 2px;position:relative;transition:height .5s ease}
|
||||
.barchart .bar.alt{background:linear-gradient(180deg,var(--violet),rgba(157,125,255,.25))}
|
||||
.barchart .bar.alt{background:linear-gradient(180deg,var(--violet),var(--violet-line))}
|
||||
.barchart .bar:hover::after{content:attr(data-v);position:absolute;bottom:calc(100% + 4px);left:50%;
|
||||
transform:translateX(-50%);background:var(--panel-solid);border:1px solid var(--line-strong);border-radius:7px;
|
||||
padding:2px 8px;font-family:var(--mono);font-size:11px;white-space:nowrap;z-index:3}
|
||||
.barchart .bar.empty{background:rgba(139,166,156,.15);height:4px!important}
|
||||
.barchart .bar.empty{background:var(--muted-soft);height:4px!important}
|
||||
.chart-x{display:flex;gap:6px;margin-top:6px}
|
||||
.chart-x span{flex:1;text-align:center;font-family:var(--mono);font-size:10px;color:var(--muted);overflow:hidden;white-space:nowrap}
|
||||
/* donut + ring (SVG) */
|
||||
@@ -485,10 +506,26 @@ textarea{resize:vertical;font:inherit}
|
||||
.lin-row .sp{display:block;font-size:11.5px;color:var(--muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .lin-row .em{min-width:0}
|
||||
.lin-row .dt{font-size:12px;color:var(--muted);text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
|
||||
.lin-row .chat-msg-btn{justify-self:end}
|
||||
.lin-row .sp.wrap{white-space:normal;line-height:1.7}
|
||||
/* list toolbar: sort + filter chips shared by the tank, roster and downline (2026-09-29) */
|
||||
.lst-bar{display:flex;flex-wrap:wrap;align-items:center;gap:6px 10px;margin:4px 0 10px;padding:8px 10px;border:1px solid var(--line);border-radius:12px;background:var(--ink-faint)}
|
||||
.lst-q{flex:1 1 100%;min-width:0;background:var(--panel);color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:6px 10px;font-size:13px}
|
||||
.lst-sort{font-size:12px;color:var(--muted);display:inline-flex;align-items:center;gap:6px}
|
||||
.lst-sort select{background:var(--panel);color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:4px 8px;font-size:12.5px}
|
||||
.lst-dir{background:transparent;color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;padding:4px 9px;font-size:12px;cursor:pointer;white-space:nowrap}
|
||||
.lst-chips{display:flex;flex-wrap:wrap;gap:6px}
|
||||
.lst-chip{font-size:12px;color:var(--muted);background:transparent;border:1px solid var(--line);border-radius:999px;padding:3px 10px;cursor:pointer;white-space:nowrap}
|
||||
.lst-chip.on{border-color:var(--mint);color:var(--ink);background:var(--mint-soft)}
|
||||
.lst-n{margin-left:auto;font-size:12px;color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
.roster-em{color:var(--mint);word-break:break-all;margin-top:2px}
|
||||
.lst-copy{background:transparent;color:var(--muted);border:1px solid var(--line);border-radius:6px;padding:0 6px;font-size:11px;cursor:pointer;margin-left:4px}
|
||||
.lchip{display:inline-block;font-size:11.5px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:1px 8px;white-space:nowrap;vertical-align:middle}
|
||||
.lchip.on{border-color:var(--mint-line);color:var(--ink)} .lchip.warn{border-color:var(--gold-line);color:var(--gold)}
|
||||
.roster td:nth-child(3){white-space:normal;line-height:1.8}
|
||||
.lin-row .lin-act-btn{justify-self:end;white-space:nowrap}
|
||||
.lin-act{display:flex;flex-wrap:wrap;gap:6px;align-items:center;padding:8px 10px 10px;margin:-1px 0 6px;border-bottom:1px solid var(--line);background:rgba(255,255,255,.025);border-radius:0 0 10px 10px}
|
||||
.lin-chip{font-size:12px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:3px 10px;white-space:nowrap} .lin-chip b{font-weight:600;color:var(--ink);margin-right:5px} .lin-chip.on{border-color:rgba(67,232,195,.45);color:var(--ink)} .lin-chip.warn{border-color:rgba(255,209,92,.5)}
|
||||
.lin-verdict{margin-left:auto;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#ffd15c} .lin-verdict.on{color:var(--mint)}
|
||||
.lin-act{display:flex;flex-wrap:wrap;gap:6px;align-items:center;padding:8px 10px 10px;margin:-1px 0 6px;border-bottom:1px solid var(--line);background:var(--ink-faint);border-radius:0 0 10px 10px}
|
||||
.lin-chip{font-size:12px;color:var(--muted);border:1px solid var(--line);border-radius:999px;padding:3px 10px;white-space:nowrap} .lin-chip b{font-weight:600;color:var(--ink);margin-right:5px} .lin-chip.on{border-color:var(--mint-line);color:var(--ink)} .lin-chip.warn{border-color:var(--gold-line)}
|
||||
.lin-verdict{margin-left:auto;font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--gold)} .lin-verdict.on{color:var(--mint)}
|
||||
@media (max-width:560px){.lin-chip{white-space:normal}.lin-act{padding:8px 4px 10px}}
|
||||
@media (max-width:560px){.lin-row{grid-template-columns:1fr auto;gap:2px 10px}
|
||||
.lin-row .em{grid-column:1/2}.lin-row .dt{grid-column:1/2;text-align:left}.lin-row .chat-msg-btn{grid-row:1/3;grid-column:2}
|
||||
@@ -498,7 +535,7 @@ textarea{resize:vertical;font:inherit}
|
||||
.ed-bar button{background:var(--panel);color:var(--ink);border:1px solid var(--line-strong);border-radius:8px;
|
||||
padding:5px 11px;font-size:12.5px;cursor:pointer}
|
||||
.ed-bar button:hover,.ed-bar button:focus-visible{border-color:var(--mint);outline:none}
|
||||
.ed-body{background:rgba(4,8,7,.65);border:1px solid var(--line-strong);border-radius:11px;
|
||||
.ed-body{background:var(--field-bg);border:1px solid var(--line-strong);border-radius:11px;
|
||||
min-height:180px;padding:12px 14px;outline:none;overflow-wrap:anywhere}
|
||||
.ed-body:focus{border-color:var(--mint)}
|
||||
.ed-body:empty::before{content:attr(data-ph);color:var(--muted)}
|
||||
@@ -518,11 +555,11 @@ textarea.ed-body{width:100%;min-height:180px;resize:vertical}
|
||||
.subtab.on{color:var(--mint);border-bottom-color:var(--mint)}
|
||||
.subtab .pill{position:static}
|
||||
/* ── solo-ads inbox ── */
|
||||
.bo-menu .pill{margin-left:auto;background:var(--amber);color:#1a1206;font-size:11px;font-weight:800;
|
||||
.bo-menu .pill{margin-left:auto;background:var(--amber);color:var(--amber-ink);font-size:11px;font-weight:800;
|
||||
border-radius:999px;padding:1px 8px;line-height:1.5}
|
||||
.ib-row{display:flex;gap:10px;align-items:baseline;padding:11px 6px;border-bottom:1px solid var(--line);
|
||||
cursor:pointer;flex-wrap:wrap}
|
||||
.ib-row:hover{background:rgba(67,232,195,.05)}
|
||||
.ib-row:hover{background:var(--mint-faint)}
|
||||
.ib-row .sub{font-weight:700;flex:1;min-width:160px;overflow-wrap:anywhere}
|
||||
.ib-row.unread .sub{color:var(--mint)}
|
||||
.ib-row .from,.ib-row .when{font-size:12px;color:var(--muted);white-space:nowrap}
|
||||
@@ -543,9 +580,9 @@ textarea.ed-body{width:100%;min-height:180px;resize:vertical}
|
||||
#pane-earn .card h3::before,#pane-earnings .card h3::before{background:var(--violet)}
|
||||
#pane-promo .card h3::before{background:var(--cyan)}
|
||||
#pane-wallet .card h3::before,#pane-profile .card h3::before{background:var(--mint)}
|
||||
.bo .card{background:linear-gradient(165deg,rgba(24,36,31,.6),rgba(13,19,17,.66))}
|
||||
#pane-line .qualbar,#nextCard{border-left:3px solid rgba(67,232,195,.4)}
|
||||
.promo-block{background:rgba(4,8,7,.55);border:1px solid var(--line);border-radius:12px;
|
||||
.bo .card{background:var(--panel-grad)}
|
||||
#pane-line .qualbar,#nextCard{border-left:3px solid var(--mint-line)}
|
||||
.promo-block{background:var(--ground-soft);border:1px solid var(--line);border-radius:12px;
|
||||
padding:14px 16px;margin:0 0 12px;font-size:13.5px;line-height:1.6;white-space:pre-wrap}
|
||||
.promo-block .btn{margin-top:10px}
|
||||
/* back-office polish: pane transitions, quick actions */
|
||||
@@ -554,19 +591,19 @@ textarea.ed-body{width:100%;min-height:180px;resize:vertical}
|
||||
@keyframes panein{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
|
||||
}
|
||||
.qa{display:flex;flex-direction:column;gap:8px}
|
||||
.qa button{display:flex;align-items:center;gap:10px;background:rgba(67,232,195,.05);border:1px solid var(--line);
|
||||
.qa button{display:flex;align-items:center;gap:10px;background:var(--mint-faint);border:1px solid var(--line);
|
||||
color:var(--ink);font:600 14px var(--disp);padding:11px 14px;border-radius:11px;cursor:pointer;text-align:left;
|
||||
transition:border-color .15s ease,background .15s ease}
|
||||
.qa button:hover{border-color:var(--mint);background:rgba(67,232,195,.1)}
|
||||
.qa button:hover{border-color:var(--mint);background:var(--mint-soft)}
|
||||
/* member sub-navigation */
|
||||
.subnav{display:flex;gap:6px;flex-wrap:wrap;background:rgba(16,28,24,.7);border:1px solid var(--line);
|
||||
.subnav{display:flex;gap:6px;flex-wrap:wrap;background:var(--pill-bg);border:1px solid var(--line);
|
||||
border-radius:999px;padding:6px 8px;width:fit-content;margin:0 0 22px}
|
||||
.subnav button{background:transparent;border:0;color:var(--muted);font:600 13.5px var(--disp);
|
||||
padding:8px 16px;border-radius:999px;cursor:pointer}
|
||||
.subnav button:hover{color:var(--ink)}
|
||||
.subnav button.on{color:var(--mint-ink);background:var(--mint)}
|
||||
/* member dashboard: qualification progress + roster */
|
||||
.qualbar{position:relative;height:12px;border-radius:999px;background:rgba(4,8,7,.7);border:1px solid var(--line-strong);
|
||||
.qualbar{position:relative;height:12px;border-radius:999px;background:var(--ground-soft);border:1px solid var(--line-strong);
|
||||
margin:26px 0 30px;max-width:520px}
|
||||
.qualbar #qualFill{height:100%;border-radius:999px;background:linear-gradient(90deg,var(--mint),var(--mint-hi));
|
||||
box-shadow:0 0 18px rgba(67,232,195,.4);width:0;transition:width .6s ease}
|
||||
@@ -592,8 +629,8 @@ img{max-width:100%}
|
||||
font-size:22px;cursor:pointer;line-height:1}
|
||||
.ch-msgs{padding:14px;overflow-y:auto;max-height:340px;display:flex;flex-direction:column;gap:10px}
|
||||
.ch-m{border-radius:12px;padding:9px 13px;font-size:13.5px;line-height:1.5;max-width:86%}
|
||||
.ch-m.bot{background:rgba(67,232,195,.08);border:1px solid rgba(67,232,195,.2);align-self:flex-start}
|
||||
.ch-m.me{background:rgba(130,148,196,.12);border:1px solid var(--line);align-self:flex-end}
|
||||
.ch-m.bot{background:var(--mint-soft);border:1px solid var(--mint-line);align-self:flex-start}
|
||||
.ch-m.me{background:var(--muted-soft);border:1px solid var(--line);align-self:flex-end}
|
||||
.ch-m a{word-break:break-all}
|
||||
.ch-input{display:flex;gap:8px;padding:11px;border-top:1px solid var(--line)}
|
||||
.ch-input input{flex:1;min-width:0}
|
||||
@@ -601,7 +638,7 @@ img{max-width:100%}
|
||||
font-weight:700;cursor:pointer;font-family:var(--disp)}
|
||||
@media(prefers-reduced-motion:no-preference){
|
||||
.feed .row:first-child{animation:landed .9s ease}
|
||||
@keyframes landed{from{background:rgba(67,232,195,.3)}to{background:var(--mint-soft)}}
|
||||
@keyframes landed{from{background:var(--mint-soft-2)}to{background:var(--mint-soft)}}
|
||||
}
|
||||
|
||||
/* ── Sponsor chat: FAB, slide-in drawer, threads, bubbles, presence ── */
|
||||
@@ -655,12 +692,12 @@ img{max-width:100%}
|
||||
.lt-nodes{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.lt-node{background:var(--panel);border:1px solid var(--line-strong);border-radius:10px;padding:6px 12px;font-size:13px;font-weight:600;white-space:nowrap}
|
||||
.lt-node.deep{color:var(--muted)}
|
||||
.lt-node.qualified{border-color:#ffb238;color:#ffd15c;box-shadow:0 0 0 1px rgba(255,177,56,.35)}
|
||||
.lt-node.qualified{border-color:var(--amber);color:var(--gold);box-shadow:0 0 0 1px var(--amber-line)}
|
||||
.lt-node.open{border-style:dashed;color:var(--muted);background:transparent}
|
||||
.lt-node .lt-n{display:inline-block;font-style:normal;font-size:10px;line-height:16px;min-width:16px;text-align:center;border-radius:8px;background:rgba(255,177,56,.18);color:#ffd15c;margin-left:6px;padding:0 4px;font-variant-numeric:tabular-nums}
|
||||
.lt-node .lt-n{display:inline-block;font-style:normal;font-size:10px;line-height:16px;min-width:16px;text-align:center;border-radius:8px;background:var(--amber-soft);color:var(--gold);margin-left:6px;padding:0 4px;font-variant-numeric:tabular-nums}
|
||||
|
||||
.sh-report{display:block;text-align:center;margin-top:10px;color:rgba(255,255,255,.45);font-size:12px}
|
||||
.sh-report:hover{color:rgba(255,255,255,.8)}
|
||||
.sh-report{display:block;text-align:center;margin-top:10px;color:var(--muted);font-size:12px}
|
||||
.sh-report:hover{color:var(--ink)}
|
||||
|
||||
/* ── promo tools (2026-09-09) ── */
|
||||
.promo-strip{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap;padding:16px 20px}
|
||||
@@ -691,7 +728,7 @@ img{max-width:100%}
|
||||
.promo-bv{display:flex;gap:12px;align-items:center;flex-wrap:wrap;margin-top:16px;padding:14px 16px;border:1px dashed var(--line-strong);border-radius:12px}
|
||||
.promo-bv b{font-family:var(--disp)}
|
||||
.obj-wrap{display:flex;flex-direction:column;gap:8px}
|
||||
.obj{border:1px solid var(--line);border-radius:12px;background:rgba(4,8,7,.4)}
|
||||
.obj{border:1px solid var(--line);border-radius:12px;background:var(--ground-soft)}
|
||||
.obj summary{cursor:pointer;padding:12px 16px;font-family:var(--disp);font-weight:700;font-size:15px;list-style:none;display:flex;justify-content:space-between;gap:10px}
|
||||
.obj summary::after{content:"+";color:var(--mint);font-weight:800}
|
||||
.obj[open] summary::after{content:"–"}
|
||||
@@ -713,12 +750,12 @@ img{max-width:100%}
|
||||
.wo-slot img{max-width:100%;border-radius:8px}
|
||||
|
||||
/* getting-started stepper on the Overview (Jim could not find the wallet step, 2026-09-14) */
|
||||
.gs{border-color:rgba(67,232,195,.45)}
|
||||
.gs{border-color:var(--mint-line)}
|
||||
.gs-steps{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px;margin:4px 0 12px}
|
||||
.gs-step{display:flex;gap:10px;align-items:center;border:1px solid var(--line);border-radius:12px;padding:10px 12px;color:var(--muted);font-size:14px}
|
||||
.gs-step .n{flex:0 0 26px;width:26px;height:26px;border-radius:50%;display:inline-flex;align-items:center;justify-content:center;font-weight:700;border:1px solid var(--line);font-size:13px}
|
||||
.gs-step.done{color:var(--ink)} .gs-step.done .n{background:var(--mint);color:var(--mint-ink);border-color:var(--mint)}
|
||||
.gs-step.now{color:var(--ink);border-color:var(--mint);background:rgba(67,232,195,.07)} .gs-step.now .n{border-color:var(--mint);color:var(--mint)}
|
||||
.gs-step.now{color:var(--ink);border-color:var(--mint);background:var(--mint-faint)} .gs-step.now .n{border-color:var(--mint);color:var(--mint)}
|
||||
.gs-now{display:flex;gap:14px;align-items:center;flex-wrap:wrap;border-top:1px solid var(--line);padding-top:12px}
|
||||
.gs-now p{margin:0;flex:1;min-width:240px;max-width:60ch} .gs-now p b{display:block;font-family:var(--disp);font-size:16px;margin-bottom:2px}
|
||||
@keyframes gsPulse{0%{box-shadow:0 0 0 0 rgba(67,232,195,.7)}70%{box-shadow:0 0 0 14px rgba(67,232,195,0)}100%{box-shadow:0 0 0 0 rgba(67,232,195,0)}}
|
||||
@@ -727,16 +764,16 @@ img{max-width:100%}
|
||||
/* promo toolkit tiers */
|
||||
.tk-tiers{display:grid;grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:10px}
|
||||
.tk-tier{border:1px solid var(--line);border-radius:12px;padding:12px 14px;font-size:13.5px;color:var(--muted)}
|
||||
.tk-tier.reached{border-color:rgba(67,232,195,.5);color:var(--ink)} .tk-tier.current{background:rgba(67,232,195,.07)}
|
||||
.tk-tier.reached{border-color:var(--mint-line);color:var(--ink)} .tk-tier.current{background:var(--mint-faint)}
|
||||
.tk-tier b{display:block;font-family:var(--disp);font-size:15px;color:var(--ink)} .tk-tier .need{font-size:12px;margin:2px 0 8px;color:var(--muted)}
|
||||
.tk-tier ul{margin:0;padding-left:16px} .tk-tier li{margin:3px 0} .tk-tier li.soon{opacity:.65} .tk-tier li.soon::after{content:' (coming)';font-size:11px;color:var(--muted)}
|
||||
.tk-tier .lock{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#ffd15c}
|
||||
.tk-tier .lock{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:var(--gold)}
|
||||
.tk-hist{border-top:1px solid var(--line);padding:8px 0;font-size:13px} .tk-hist .muted{font-size:12px}
|
||||
.tk-sec{margin-top:18px;padding-top:14px;border-top:1px solid var(--line)} .tk-grid{display:flex;gap:8px;flex-wrap:wrap}
|
||||
.tk-vids{display:grid;grid-template-columns:repeat(auto-fill,minmax(210px,1fr));gap:8px} .tk-vid{border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:13px} .tk-vid b{display:block;font-weight:600;margin-bottom:4px} .tk-vid .st{font-size:12px;color:var(--muted)}
|
||||
.tk-bar{height:8px;border-radius:99px;background:rgba(255,255,255,.08);overflow:hidden;margin:6px 0 4px} .tk-bar i{display:block;height:100%;border-radius:99px;background:linear-gradient(90deg,#1fb894,#43e8c3);transition:width .6s ease;min-width:4px}
|
||||
.tk-bar{height:8px;border-radius:99px;background:var(--muted-soft);overflow:hidden;margin:6px 0 4px} .tk-bar i{display:block;height:100%;border-radius:99px;background:linear-gradient(90deg,var(--mint-deep),var(--mint));transition:width .6s ease;min-width:4px}
|
||||
.tk-table{width:100%;border-collapse:collapse;font-size:13px} .tk-table th,.tk-table td{text-align:left;padding:6px 8px;border-bottom:1px solid var(--line)} .tk-table th{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--muted)} .tk-table td.n{font-variant-numeric:tabular-nums;text-align:right} .tk-table th.n{text-align:right} .tk-table tr.best td{color:var(--mint)}
|
||||
.tk-team{border:1px solid var(--line);border-radius:10px;padding:8px 12px;margin:6px 0;font-size:13px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:space-between} .tk-team .who b{font-weight:600} .tk-team .who span{color:var(--muted);font-size:12px} .tk-team.stalled{border-color:rgba(255,209,92,.45)}
|
||||
.tk-team{border:1px solid var(--line);border-radius:10px;padding:8px 12px;margin:6px 0;font-size:13px;display:flex;gap:10px;flex-wrap:wrap;align-items:center;justify-content:space-between} .tk-team .who b{font-weight:600} .tk-team .who span{color:var(--muted);font-size:12px} .tk-team.stalled{border-color:var(--gold-line)}
|
||||
.tk-nudge{width:100%;margin:8px 0 0;padding:8px 12px;border:1px dashed var(--line);border-radius:10px;font-size:13px}
|
||||
/* click sources stack one per line so the Clicks column stays narrow (Marty, 2026-09-15) */
|
||||
.clk-src span{display:block;white-space:nowrap} .camp-table td{white-space:normal} .camp-table td:first-child{max-width:260px}
|
||||
@@ -759,11 +796,11 @@ img{max-width:100%}
|
||||
|
||||
/* Pipeline board (Marty, 2026-09-15): columns scroll sideways inside their own box, never the page */
|
||||
.pipe-board{display:flex;gap:10px;overflow-x:auto;padding:4px 2px 10px;scroll-snap-type:x proximity}
|
||||
.pipe-col{flex:0 0 220px;scroll-snap-align:start;background:rgba(4,8,7,.45);border:1px solid var(--line);border-radius:12px;padding:10px;min-height:120px}
|
||||
.pipe-col{flex:0 0 220px;scroll-snap-align:start;background:var(--ground-soft);border:1px solid var(--line);border-radius:12px;padding:10px;min-height:120px}
|
||||
.pipe-col h4{margin:0 0 2px;font-size:13px;letter-spacing:.06em;text-transform:uppercase;color:var(--mint);display:flex;justify-content:space-between;gap:8px}
|
||||
.pipe-col h4 span{color:var(--muted);font-variant-numeric:tabular-nums}
|
||||
.pipe-col .hint{font-size:11.5px;color:var(--muted);margin:0 0 8px;line-height:1.35}
|
||||
.pipe-card{background:rgba(255,255,255,.04);border:1px solid var(--line);border-radius:10px;padding:8px 10px;margin:0 0 8px;cursor:pointer;transition:border-color .15s}
|
||||
.pipe-card{background:var(--ink-faint);border:1px solid var(--line);border-radius:10px;padding:8px 10px;margin:0 0 8px;cursor:pointer;transition:border-color .15s}
|
||||
.pipe-card:hover,.pipe-card:focus-visible{border-color:var(--mint);outline:none}
|
||||
.pipe-card.on{border-color:var(--gold,#e6c15a)}
|
||||
.pipe-card .nm{font-weight:700;font-size:14px;display:flex;justify-content:space-between;gap:6px;align-items:baseline}
|
||||
@@ -778,7 +815,7 @@ img{max-width:100%}
|
||||
.lt-node.lt-go{cursor:pointer;transition:border-color .15s,transform .15s} .lt-node.lt-go:hover,.lt-node.lt-go:focus-visible{border-color:var(--mint);transform:translateY(-1px);outline:none}
|
||||
.lin-row.lin-focus{box-shadow:0 0 0 2px var(--mint);border-radius:10px}
|
||||
/* paged lists: 25 rows, then a control bar that reads as a control, not more list (Marty, 2026-09-19) */
|
||||
.pgr{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin:12px 0 4px;padding:10px 12px;border:1px solid var(--line-strong);border-radius:12px;background:rgba(67,232,195,.07)}
|
||||
.pgr{display:flex;align-items:center;justify-content:space-between;gap:10px;flex-wrap:wrap;margin:12px 0 4px;padding:10px 12px;border:1px solid var(--line-strong);border-radius:12px;background:var(--mint-faint)}
|
||||
.pgr-n{color:var(--ink);font-size:13px} .pgr-n b{color:var(--mint);font-variant-numeric:tabular-nums}
|
||||
.pgr-b{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
|
||||
.pgr-pg{font-size:11px;color:var(--muted);letter-spacing:.06em;text-transform:uppercase;white-space:nowrap}
|
||||
@@ -788,13 +825,42 @@ img{max-width:100%}
|
||||
#chatThreads .pgr{margin:8px 10px}
|
||||
|
||||
/* Five Dollar Friday strip (landing) */
|
||||
.fdf{margin:18px auto 0;max-width:760px;padding:12px 16px;border-radius:12px;background:rgba(67,232,195,.08);border:1px solid rgba(67,232,195,.35);color:var(--ink,#eafffa);font-size:14px;line-height:1.5;text-align:center}
|
||||
.fdf a{color:#43e8c3;font-weight:600}
|
||||
.fdf{margin:18px auto 0;max-width:760px;padding:12px 16px;border-radius:12px;background:var(--mint-soft);border:1px solid var(--mint-line);color:var(--ink);font-size:14px;line-height:1.5;text-align:center}
|
||||
.fdf a{color:var(--mint);font-weight:600}
|
||||
|
||||
/* My line: section pills, sticky under the top bar (Marty, 2026-09-26) */
|
||||
.line-jump{position:sticky;top:var(--jumpTop,64px);z-index:4;margin:0 0 14px;padding:10px 0;flex-wrap:nowrap;overflow-x:auto;scrollbar-width:none;
|
||||
background:rgba(6,10,8,.88);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--line)}
|
||||
background:var(--nav-bg);backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);border-bottom:1px solid var(--line)}
|
||||
.line-jump::-webkit-scrollbar{display:none}
|
||||
.line-jump .chip-t{flex:none;white-space:nowrap}
|
||||
#pane-line > .card[data-jump]{scroll-margin-top:calc(var(--jumpTop,64px) + 64px)}
|
||||
.tablewrap > .pgr{margin-top:10px}
|
||||
|
||||
/* a game return bar sits at the bottom: lift the status toast above it (Marty 2026-10-08: the bar hid the purchase result) */
|
||||
body.hasback #status{bottom:92px}
|
||||
|
||||
/* ── Light theme (2026-11-01, mirrored from LinkSpin): light mint-grey ground, white panels, dark ink, the mint family
|
||||
darkened to a teal that reads as text on white (every pair below clears WCAG AA 4.5:1, measured by qa/theme-contrast.mjs).
|
||||
themehead.js resolves auto | light | dark to data-theme on <html> before the first paint; nothing stored keeps dark. ── */
|
||||
:root[data-theme="light"]{
|
||||
--ground:#E8F0EC; --ground2:#F2F7F4; --panel:#FFFFFF; --panel-solid:#FFFFFF;
|
||||
--line:#C9D8D1; --line-strong:#A6BBB1; --line-soft:#DDE7E2; --ink:#0B1A14; --muted:#50665C;
|
||||
--mint:#0A6B56; --mint-hi:#075744; --mint-deep:#064A3A; --mint-ink:#FFFFFF; --mint-pale:#075744;
|
||||
--mint-faint:#EDF6F2; --mint-soft:#DDF0E8; --mint-soft-2:#C6E6DA; --mint-line:#8FC9B6; --mint-line-2:#3E9E85;
|
||||
--cyan:#0A6F8C; --violet:#5B3FD6; --amber:#8A5200; --bad:#B42318; --bad-soft:#FDE8E6;
|
||||
--ok:#0B7A52; --ok-ink:#FFFFFF; --ok-soft:#E3F6EC; --warn:#9A4A00;
|
||||
--gold:#7A5200; --gold-2:#7F5C00; --gold-ink:#FFFFFF; --gold-soft:#FFF4D1; --gold-faint:#FFFBEB; --gold-line:#E6C25E;
|
||||
--amber-soft:#FFF1D6; --amber-line:#E8C27A; --amber-ink:#FFFFFF;
|
||||
--cyan-soft:#DDF1F8; --cyan-line:#9FD3E6; --violet-soft:#EEE9FF; --violet-line:#C4B5FF;
|
||||
--muted-soft:rgba(80,102,92,.12); --muted-line:rgba(80,102,92,.45); --ink-faint:rgba(11,26,20,.05);
|
||||
--ground-soft:#F2F7F4; --field-bg:#FFFFFF; --nav-bg:rgba(242,247,244,.88); --side-bg:rgba(242,247,244,.97); --pill-bg:rgba(255,255,255,.85);
|
||||
--panel-grad:linear-gradient(180deg,#FFFFFF,#F5FAF7); --panel-grad-deep:linear-gradient(180deg,#F2F7F4,#E2ECE7); --plate-grad:linear-gradient(160deg,#FFFFFF,#E6F1EC);
|
||||
--sh-lg:0 0 0 1px rgba(11,26,20,.04),0 14px 34px -20px rgba(11,26,20,.35);
|
||||
color-scheme:light;
|
||||
}
|
||||
:root[data-theme="light"] body::before{opacity:.7}
|
||||
:root[data-theme="light"] .ghost{background:linear-gradient(180deg,rgba(10,107,86,.22),transparent 78%);-webkit-background-clip:text;background-clip:text}
|
||||
:root[data-theme="light"] .btn{box-shadow:0 4px 18px rgba(10,107,86,.22)} :root[data-theme="light"] .btn:hover{box-shadow:0 8px 26px rgba(10,107,86,.3)}
|
||||
:root[data-theme="light"] .mockup,:root[data-theme="light"] .modal-card,:root[data-theme="light"] #status,:root[data-theme="light"] #iapChatPanel,:root[data-theme="light"] .chat-drawer{box-shadow:0 18px 50px -20px rgba(11,26,20,.35)}
|
||||
:root[data-theme="light"] .bo.side-open .bo-side{box-shadow:0 0 60px rgba(11,26,20,.25)}
|
||||
:root[data-theme="light"] .plate{box-shadow:0 0 24px rgba(10,107,86,.12),inset 0 1px 0 rgba(255,255,255,.8)}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// Help desk front end (2026-10-16): the public /support form, the private ticket link page (/support/t/<token>)
|
||||
// and the member Help pane (/my#help). Server side: tickets.js + the /api/support, /api/my/support routes.
|
||||
// Times show in US Central, like the rest of the site's support copy.
|
||||
window.IAPSupport = (function () {
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const CATS = ['Account & sign-in', 'Wallet & payouts', 'Buying packages', 'Ads & campaigns', 'Earning credits & games', 'Team & referrals', 'Other'];
|
||||
const STATUS = { open: 'Open', waiting_on_member: 'Waiting on you', closed: 'Closed' };
|
||||
const when = ts => ts ? new Date(Number(ts)).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
|
||||
const linkify = s => esc(s).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)\]])/g, '<a href="$1" target="_blank" rel="noopener nofollow">$1</a>');
|
||||
async function call(path, body, method) {
|
||||
const o = { method: method || (body === undefined ? 'GET' : 'POST'), headers: {} };
|
||||
if (body !== undefined) { o.headers['Content-Type'] = 'application/json'; o.body = JSON.stringify(body); }
|
||||
const r = await (await fetch(path, o)).json();
|
||||
if (r.error && !r.challenge) { const e = new Error(r.error); e.data = r; throw e; }
|
||||
return r;
|
||||
}
|
||||
(function css() {
|
||||
if (document.getElementById('supCss')) return;
|
||||
const st = document.createElement('style'); st.id = 'supCss';
|
||||
st.textContent = '.sup-form label{display:block;font-size:13px;color:var(--muted);margin:12px 0 4px}.sup-form input,.sup-form select,.sup-form textarea{width:100%;box-sizing:border-box}'
|
||||
+ '.sup-row{display:flex;gap:10px;align-items:center;justify-content:space-between;padding:12px 4px;border-bottom:1px solid var(--line);cursor:pointer}.sup-row:last-child{border-bottom:0}.sup-row:hover{background:var(--mint-faint)}'
|
||||
+ '.sup-row .sr-main{min-width:0;flex:1}.sup-row .sr-sub{font-weight:700;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.sup-row .sr-meta{font-size:12px;color:var(--muted)}'
|
||||
+ '.sup-st{font-size:11.5px;font-weight:700;border-radius:999px;padding:2px 10px;border:1px solid var(--line-strong);white-space:nowrap}.sup-st.open{color:var(--mint);border-color:var(--mint-line-2)}.sup-st.waiting_on_member{color:var(--gold-2);border-color:var(--gold-line)}.sup-st.closed{color:var(--muted)}'
|
||||
+ '.sup-dot{display:inline-block;width:8px;height:8px;border-radius:50%;background:var(--amber,#ffb238);margin-right:6px;vertical-align:1px}'
|
||||
+ '.sup-msg{border:1px solid var(--line);border-radius:12px;padding:12px 14px;margin:10px 0;background:var(--ground-soft)}.sup-msg.admin{border-color:var(--mint-line);background:var(--mint-faint)}.sup-msg.system{opacity:.8}'
|
||||
+ '.sup-msg .sm-head{font-size:12px;color:var(--muted);margin:0 0 6px;display:flex;justify-content:space-between;gap:8px;flex-wrap:wrap}.sup-msg .sm-body{white-space:pre-wrap;word-wrap:break-word;font-size:15px;line-height:1.5}'
|
||||
+ '.sup-att{display:flex;gap:8px;margin-top:8px;flex-wrap:wrap}.sup-att img{max-width:160px;max-height:120px;border-radius:8px;border:1px solid var(--line)}'
|
||||
+ '.sup-actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:12px}';
|
||||
document.head.appendChild(st);
|
||||
})();
|
||||
const catOptions = sel => CATS.map(c => '<option' + (c === sel ? ' selected' : '') + '>' + esc(c) + '</option>').join('');
|
||||
const AUTHOR = { member: 'You', admin: 'Marty, InstantAdPay support', system: 'InstantAdPay' };
|
||||
function threadHtml(v) {
|
||||
const t = v.ticket;
|
||||
return '<div class="card-head" style="flex-wrap:wrap;gap:8px"><h3 style="margin:0">' + esc(t.subject) + '</h3><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>'
|
||||
+ '<p class="small muted" style="margin:4px 0 6px">' + esc(t.ref) + ' · ' + esc(t.category) + ' · opened ' + esc(when(t.created)) + '</p>'
|
||||
+ v.messages.map(m => '<div class="sup-msg ' + esc(m.author) + '"><div class="sm-head"><b>' + esc(AUTHOR[m.author] || m.author) + '</b><span>' + esc(when(m.created)) + '</span></div>'
|
||||
+ '<div class="sm-body">' + linkify(m.body) + '</div>'
|
||||
+ ((m.attachments || []).length ? '<div class="sup-att">' + m.attachments.map(a => '<a href="' + esc(a) + '" target="_blank" rel="noopener"><img src="' + esc(a) + '" alt="attachment"></a>').join('') + '</div>' : '') + '</div>').join('')
|
||||
+ (t.status === 'closed' ? '<p class="small muted" style="margin:14px 0 0">This ticket is closed. Write below and it opens again.</p>' : '');
|
||||
}
|
||||
function replyBox(id, withAttach) {
|
||||
return '<div class="sup-form"><label for="' + id + 'Body">Your reply</label><textarea id="' + id + 'Body" rows="4" maxlength="5000" placeholder="Add more detail or answer Marty here"></textarea>'
|
||||
+ (withAttach ? attachRow(id) : '')
|
||||
+ '<div class="sup-actions"><button class="btn small" type="button" id="' + id + 'Send">Send reply</button><span class="small muted" id="' + id + 'Msg"></span></div></div>';
|
||||
}
|
||||
// up to 2 screenshots per message, through the member upload path (signed-in only)
|
||||
const attachRow = id => '<label for="' + id + 'File">Screenshots (optional, up to 2 images)</label><input type="file" id="' + id + 'File" accept="image/png,image/jpeg,image/webp,image/gif" multiple><div class="sup-att" id="' + id + 'Att"></div>';
|
||||
function wireAttach(id) {
|
||||
const list = []; const inp = document.getElementById(id + 'File'); if (!inp) return () => [];
|
||||
const draw = () => { document.getElementById(id + 'Att').innerHTML = list.map(u => '<img src="' + esc(u) + '" alt="screenshot">').join(''); };
|
||||
inp.addEventListener('change', async () => {
|
||||
for (const f of [...inp.files]) {
|
||||
if (list.length >= 2) { IAP.status('Two images per message at most.', 'bad'); break; }
|
||||
try { const r = await (await fetch('/api/my/upload', { method: 'POST', headers: { 'Content-Type': f.type }, body: f })).json(); if (r.error) throw new Error(r.error); if (r.type !== 'image') throw new Error('Images only, please.'); list.push(r.url); draw(); }
|
||||
catch (e) { IAP.status(e.message || 'Upload failed.', 'bad'); }
|
||||
}
|
||||
inp.value = '';
|
||||
});
|
||||
return () => list.slice(); // read at send time
|
||||
}
|
||||
|
||||
// ── member Help pane ──
|
||||
let helpState = { open: null };
|
||||
async function badge() {
|
||||
try { const r = await call('/api/my/support'); const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; } return r; } catch (e) { return null; }
|
||||
}
|
||||
async function help(paneQ) {
|
||||
const host = document.getElementById('helpBody'); if (!host) return;
|
||||
const want = (/(?:^|&)t=((?:IAP|LS)-\d+)/.exec(paneQ || '') || [])[1];
|
||||
if (want) return openMine(want);
|
||||
helpState.open = null;
|
||||
host.innerHTML = '<div class="card"><p class="muted small">Loading your tickets…</p></div>';
|
||||
let r; try { r = await call('/api/my/support'); } catch (e) { host.innerHTML = '<div class="card"><p class="small">Could not load your tickets. ' + esc(e.message) + '</p></div>'; return; }
|
||||
const b = document.getElementById('helpBadge'); if (b) { b.hidden = !r.unread; b.textContent = r.unread > 9 ? '9+' : r.unread; }
|
||||
host.innerHTML = '<div class="card"><div class="card-head"><h3>Help and support</h3><button class="btn small" type="button" id="helpNewBtn">New ticket</button></div>'
|
||||
+ '<p class="muted small" style="margin:6px 0 0">Stuck on something? Send Marty a ticket. He reads every one and replies here, and you get an email when he does. The quickest answers to common questions are in Training and the chat bubble.</p></div>'
|
||||
+ '<div class="card" id="helpNew" hidden></div>'
|
||||
+ '<div class="card"><div class="card-head"><h3>Your tickets</h3><span class="sub">' + r.tickets.length + '</span></div>'
|
||||
+ (r.tickets.length ? r.tickets.map(t => '<div class="sup-row" data-ref="' + esc(t.ref) + '"><div class="sr-main"><div class="sr-sub">' + (t.unread ? '<span class="sup-dot" title="New reply"></span>' : '') + esc(t.subject) + '</div>'
|
||||
+ '<div class="sr-meta">' + esc(t.ref) + ' · ' + esc(t.category) + ' · updated ' + esc(when(t.updated)) + '</div></div><span class="sup-st ' + esc(t.status) + '">' + esc(STATUS[t.status] || t.status) + '</span></div>').join('')
|
||||
: '<p class="muted small" id="helpEmpty">No tickets yet. When you send one, it shows up here with Marty\'s replies.</p>') + '</div>';
|
||||
host.querySelectorAll('.sup-row').forEach(el => el.addEventListener('click', () => { history.replaceState(null, '', '#help?t=' + el.dataset.ref); openMine(el.dataset.ref); }));
|
||||
document.getElementById('helpNewBtn').addEventListener('click', () => newForm());
|
||||
if (/(?:^|&)new=1/.test(paneQ || '')) newForm();
|
||||
}
|
||||
function newForm() {
|
||||
const box = document.getElementById('helpNew'); if (!box) return;
|
||||
box.hidden = false;
|
||||
box.innerHTML = '<h3 style="margin:0 0 4px">New ticket</h3><div class="sup-form">'
|
||||
+ '<label for="hnCat">What is it about?</label><select id="hnCat">' + catOptions('') + '</select>'
|
||||
+ '<label for="hnSubject">Subject</label><input id="hnSubject" maxlength="140" placeholder="A few words, like: my payout did not arrive">'
|
||||
+ '<label for="hnBody">Message</label><textarea id="hnBody" rows="6" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
|
||||
+ attachRow('hn')
|
||||
+ '<div class="sup-actions"><button class="btn small" type="button" id="hnSend">Send to support</button><button class="btn small sec" type="button" id="hnCancel">Cancel</button><span class="small muted" id="hnMsg"></span></div></div>';
|
||||
const atts = wireAttach('hn');
|
||||
document.getElementById('hnCancel').addEventListener('click', () => { box.hidden = true; box.innerHTML = ''; });
|
||||
const send = document.getElementById('hnSend');
|
||||
send.addEventListener('click', async () => {
|
||||
if (send.disabled) return; send.disabled = true;
|
||||
try {
|
||||
const r = await call('/api/my/support', { category: document.getElementById('hnCat').value, subject: document.getElementById('hnSubject').value, body: document.getElementById('hnBody').value, attachments: atts() });
|
||||
IAP.status('Sent. Your ticket is ' + r.ref + '. Marty will reply here and by email.', 'ok');
|
||||
history.replaceState(null, '', '#help?t=' + r.ref); openMine(r.ref);
|
||||
} catch (e) { document.getElementById('hnMsg').textContent = e.message; }
|
||||
finally { send.disabled = false; }
|
||||
});
|
||||
document.getElementById('hnSubject').focus();
|
||||
}
|
||||
async function openMine(ref) {
|
||||
const host = document.getElementById('helpBody'); if (!host) return;
|
||||
helpState.open = ref;
|
||||
host.innerHTML = '<div class="card"><p class="muted small">Loading…</p></div>';
|
||||
let v; try { v = await call('/api/my/support/' + encodeURIComponent(ref)); } catch (e) { host.innerHTML = '<div class="card"><p class="small">' + esc(e.message) + '</p><p><a href="#help" id="helpBack">Back to your tickets</a></p></div>'; wireBack(); return; }
|
||||
drawMine(v);
|
||||
badge();
|
||||
}
|
||||
const wireBack = () => { const a = document.getElementById('helpBack'); if (a) a.addEventListener('click', e => { e.preventDefault(); history.replaceState(null, '', '#help'); help(''); }); };
|
||||
function drawMine(v) {
|
||||
const host = document.getElementById('helpBody');
|
||||
host.innerHTML = '<p style="margin:0 0 10px"><a href="#help" id="helpBack">‹ All your tickets</a></p><div class="card">' + threadHtml(v) + '</div><div class="card">' + replyBox('hr', true) + '</div>';
|
||||
wireBack();
|
||||
const atts = wireAttach('hr');
|
||||
const btn = document.getElementById('hrSend');
|
||||
btn.addEventListener('click', async () => {
|
||||
if (btn.disabled) return; btn.disabled = true;
|
||||
try { const nv = await call('/api/my/support/' + encodeURIComponent(v.ticket.ref) + '/reply', { body: document.getElementById('hrBody').value, attachments: atts() }); drawMine(nv); IAP.status('Reply sent.', 'ok'); }
|
||||
catch (e) { document.getElementById('hrMsg').textContent = e.message; }
|
||||
finally { btn.disabled = false; }
|
||||
});
|
||||
}
|
||||
|
||||
// ── public /support page and the private ticket link ──
|
||||
async function page() {
|
||||
const host = document.getElementById('supMain'); if (!host) return;
|
||||
const m = /^\/support\/t\/([A-Za-z0-9_.-]{20,80})$/.exec(location.pathname);
|
||||
if (m) return tokenPage(host, m[1]);
|
||||
let me = null; try { me = await (await fetch('/api/me')).json(); } catch (e) {}
|
||||
const signedIn = !!(me && me.signedIn && me.email);
|
||||
host.innerHTML = (signedIn ? '<div class="card" style="border-color:var(--mint-line)"><p class="small" style="margin:0">You are signed in as <b>' + esc(me.username ? '@' + me.username : me.email) + '</b>. Your tickets and Marty\'s replies live in <a href="/my#help">Help in your dashboard</a>, which is the easiest place to follow up. This form works too and files the ticket under your account.</p></div>' : '')
|
||||
+ '<div class="card"><form class="sup-form" id="supForm" novalidate autocomplete="on">'
|
||||
+ '<input class="hp-field" type="text" name="website_url" id="supHp" tabindex="-1" aria-hidden="true" autocomplete="off">'
|
||||
+ (signedIn ? '' : '<label for="supName">Your name</label><input id="supName" maxlength="80" autocomplete="name">'
|
||||
+ '<label for="supEmail">Your email (replies go here)</label><input id="supEmail" type="email" maxlength="190" autocomplete="email" required>')
|
||||
+ '<label for="supCat">What is it about?</label><select id="supCat">' + catOptions('') + '</select>'
|
||||
+ '<label for="supSubject">Subject</label><input id="supSubject" maxlength="140" placeholder="A few words, like: my sign-in code does not arrive">'
|
||||
+ '<label for="supBody">Message</label><textarea id="supBody" rows="7" maxlength="5000" placeholder="What happened, what you expected, and anything you already tried. Never send your recovery phrase or private key."></textarea>'
|
||||
+ '<div id="supCheck" hidden style="margin-top:12px"></div>'
|
||||
+ '<div class="sup-actions"><button class="btn" type="submit" id="supSend">Send to support</button><span class="small muted" id="supMsg"></span></div>'
|
||||
+ '</form></div>';
|
||||
const f = document.getElementById('supForm');
|
||||
f.addEventListener('submit', async e => {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById('supSend'); if (btn.disabled) return; btn.disabled = true;
|
||||
const msg = document.getElementById('supMsg'); msg.textContent = 'Sending…';
|
||||
const val = id => { const el = document.getElementById(id); return el ? el.value : ''; };
|
||||
try {
|
||||
const g = IAP.guard; await g.formSettled();
|
||||
let pick = null, r = null;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
r = await call('/api/support', { name: val('supName'), email: val('supEmail'), category: val('supCat'), subject: val('supSubject'), body: val('supBody'),
|
||||
fts: g.FORM_TS, fage: Date.now() - g.FORM_TS, hp_field_x9: g.hpValue(document.getElementById('supHp')), pick });
|
||||
if (r.challenge) { msg.textContent = ''; pick = await g.iconCheck(document.getElementById('supCheck'), r.challenge, r.error); continue; }
|
||||
break;
|
||||
}
|
||||
if (!r || !r.ok) throw new Error('Could not verify. Refresh the page and try again.');
|
||||
host.innerHTML = '<div class="card"><h3 style="margin:0 0 6px">Got it. Your ticket is ' + esc(r.ref) + '.</h3>'
|
||||
+ '<p class="muted small">Marty reads every ticket and replies as soon as he can. ' + (r.member ? 'His reply shows up in Help in your dashboard and in your email.' : 'We just emailed you a private link to this ticket, so you can check on it or add more detail without signing in. If it does not arrive, look in spam or promotions.') + '</p>'
|
||||
+ '<p class="sup-actions">' + (r.member ? '<a class="btn small" href="/my#help?t=' + esc(r.ref) + '">Open it in Help</a>' : '<a class="btn small" href="/support/t/' + esc(r.token) + '">View your ticket</a>') + '<a class="btn small sec" href="/">Back to InstantAdPay</a></p></div>';
|
||||
window.scrollTo(0, 0);
|
||||
} catch (err) { msg.textContent = err.message; }
|
||||
finally { btn.disabled = false; }
|
||||
});
|
||||
}
|
||||
async function tokenPage(host, tok) {
|
||||
const h = document.querySelector('.sectionhead h2'); if (h) h.innerHTML = 'Your support <em>ticket</em>';
|
||||
host.innerHTML = '<div class="card"><p class="muted small">Loading your ticket…</p></div>';
|
||||
let v; try { v = await call('/api/support/t/' + encodeURIComponent(tok)); } catch (e) { host.innerHTML = '<div class="card"><p>' + esc(e.message) + '</p><p><a class="btn small" href="/support">Send a new ticket</a></p></div>'; return; }
|
||||
const draw = v2 => {
|
||||
host.innerHTML = '<div class="card">' + threadHtml(v2) + '</div><div class="card">' + replyBox('tk', false)
|
||||
+ '<p class="small muted" style="margin:10px 0 0">Keep this link private: anyone with it can read and answer this ticket. Members can also follow up from <a href="/my#help">Help in the dashboard</a>, where screenshots can be attached.</p></div>';
|
||||
const btn = document.getElementById('tkSend');
|
||||
btn.addEventListener('click', async () => {
|
||||
if (btn.disabled) return; btn.disabled = true;
|
||||
try { const nv = await call('/api/support/t/' + encodeURIComponent(tok) + '/reply', { body: document.getElementById('tkBody').value }); draw(nv); IAP.status('Reply sent. Marty will see it.', 'ok'); }
|
||||
catch (e) { document.getElementById('tkMsg').textContent = e.message; }
|
||||
finally { btn.disabled = false; }
|
||||
});
|
||||
};
|
||||
draw(v);
|
||||
}
|
||||
return { help, badge, page, CATS, STATUS, when, esc, linkify };
|
||||
})();
|
||||
if (document.getElementById('supMain')) IAPSupport.page();
|
||||
@@ -7,6 +7,8 @@
|
||||
const token = location.pathname.split('/').pop();
|
||||
const framed = window.self !== window.top; // shown inside the dashboard's in-page ad overlay
|
||||
let left = 5, timer = null, credited = false, asking = false;
|
||||
// 'active' = visible and (focused, or the ad frame itself holds focus, or a touch device where hasFocus() is unreliable)
|
||||
const tabActive = () => document.visibilityState === 'visible' && (document.hasFocus() || !!(document.activeElement && document.activeElement.tagName === 'IFRAME') || (window.matchMedia && window.matchMedia('(pointer: coarse)').matches));
|
||||
const setMsg = t => { $('vMsg').textContent = t; };
|
||||
async function j(url, body) {
|
||||
const r = await fetch(url, body
|
||||
@@ -18,7 +20,7 @@
|
||||
if (credited || asking) return;
|
||||
// In the in-page overlay the iframe often doesn't hold focus even though it's
|
||||
// fully on screen, so gate on tab visibility only when framed.
|
||||
if (document.visibilityState !== 'visible' || (!framed && !document.hasFocus())) {
|
||||
if (document.visibilityState !== 'visible' || (!framed && !tabActive())) {
|
||||
$('vTimer').classList.add('paused');
|
||||
$('vTimer').textContent = 'paused';
|
||||
setMsg(framed ? 'Keep this ad on screen to finish the countdown.' : 'Come back to this tab to keep the countdown moving.');
|
||||
|
||||
@@ -17,9 +17,11 @@
|
||||
title.innerHTML = safeName;
|
||||
if (hostEl) hostEl.innerHTML = safeName;
|
||||
IAP.$('bioHead').hidden = false;
|
||||
if (w.avatarUrl) { const av = IAP.$('bioAvatar'); av.src = w.avatarUrl; av.hidden = false; }
|
||||
// profile fields (avatar, bio, socials, intro video) are rendered only when the server says the member has bought (w.bought);
|
||||
// a free member's wall shows the name, the line's ads and the join call, nothing from the profile (2026-10-30)
|
||||
if (w.bought && w.avatarUrl) { const av = IAP.$('bioAvatar'); av.src = w.avatarUrl; av.hidden = false; }
|
||||
if (w.badge) { const bb = IAP.$('bioBadge'); if (bb) { bb.src = w.badge.img; bb.title = w.badge.label + ' badge'; bb.hidden = false; } }
|
||||
IAP.$('bioText').textContent = w.bio || 'Building a team on InstantAdPay — join through this page and you\'re in my line.';
|
||||
IAP.$('bioText').textContent = (w.bought && w.bio) || 'Building a team on InstantAdPay. Join through this page and you are in my line.';
|
||||
if (w.qrUrl) IAP.$('bioQr').src = w.qrUrl;
|
||||
// social links
|
||||
const SOC = { facebook: 'Facebook', twitter: 'X', youtube: 'YouTube', instagram: 'Instagram', tiktok: 'TikTok', telegram: 'Telegram', linkedin: 'LinkedIn', website: 'Website' };
|
||||
@@ -36,14 +38,15 @@
|
||||
website: svg('<circle cx="12" cy="12" r="9"/><path d="M3 12h18M12 3c3 3.5 3 14.5 0 18M12 3c-3 3.5-3 14.5 0 18"/>')
|
||||
};
|
||||
const sc = IAP.$('bioSocials');
|
||||
if (sc && w.socials && typeof w.socials === 'object') {
|
||||
if (sc && w.bought && w.socials && typeof w.socials === 'object') {
|
||||
// paid placement: Google wants these marked sponsored (plus ugc), never a plain dofollow (2026-10-30)
|
||||
const links = Object.keys(SOC).filter(k => w.socials[k]).map(k =>
|
||||
'<a href="' + String(w.socials[k]).replace(/"/g, '%22') + '" target="_blank" rel="noopener nofollow me">' + (ICON[k] || '') + '<span>' + SOC[k] + '</span></a>');
|
||||
'<a href="' + String(w.socials[k]).replace(/"/g, '%22') + '" target="_blank" rel="sponsored ugc noopener">' + (ICON[k] || '') + '<span>' + SOC[k] + '</span></a>');
|
||||
sc.innerHTML = links.join('');
|
||||
}
|
||||
// intro video under the bio: YouTube / Vimeo embed, or a direct file
|
||||
const bv = IAP.$('bioVideo');
|
||||
const vurl = w.socials && typeof w.socials === 'object' ? String(w.socials.video || '') : '';
|
||||
const vurl = w.bought && w.socials && typeof w.socials === 'object' ? String(w.socials.video || '') : '';
|
||||
if (bv && vurl) {
|
||||
let yt = /(?:youtube\.com\/(?:watch\?(?:.*&)?v=|shorts\/|embed\/)|youtu\.be\/)([A-Za-z0-9_-]{6,})/.exec(vurl);
|
||||
let vm = /vimeo\.com\/(?:video\/)?(\d+)/.exec(vurl);
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
/* /wednesday status strip. External file on purpose: the site's CSP blocks inline scripts. */
|
||||
(function () {
|
||||
var el = document.getElementById('wwState');
|
||||
if (!el) return;
|
||||
function n(x) { return Number(x || 0).toLocaleString('en-US'); }
|
||||
// the minute (Central) when the next Wednesday starts, found by scanning rather than assumed,
|
||||
// so a daylight-saving change cannot put the countdown an hour out
|
||||
function startsAt(dayKey) {
|
||||
var now = Date.now();
|
||||
for (var m = 0; m < 8 * 1440; m++) {
|
||||
var t = now + m * 60000;
|
||||
var d = new Date(t).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
if (d === dayKey) return t;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function render(f) {
|
||||
if (!f || !f.on) { el.innerHTML = '<span class="fr-tag">Paused</span><span>Wired Wednesday is not running right now. Join free and you will hear when it is back.</span>'; return; }
|
||||
if (f.live) {
|
||||
var t = f.today || {};
|
||||
el.className = 'fr-state live';
|
||||
el.innerHTML = '<span class="fr-tag">Live now</span><span><b>It is Wired Wednesday.</b> Bonus runs until midnight Central.</span>'
|
||||
+ '<span><span class="fr-num">' + n(t.packs) + '</span> pack' + (t.packs === 1 ? '' : 's') + ' so far today</span>'
|
||||
+ '<span><span class="fr-num">' + n(t.bonusCredits) + '</span> bonus credits wired in</span>';
|
||||
return;
|
||||
}
|
||||
var at = f.nextWednesday ? startsAt(f.nextWednesday) : null;
|
||||
var left = at ? Math.max(0, at - Date.now()) : 0;
|
||||
var hrs = Math.floor(left / 3600000), mins = Math.floor((left % 3600000) / 60000), days = Math.floor(hrs / 24);
|
||||
var when = at ? (days >= 1 ? days + ' day' + (days === 1 ? '' : 's') + ' ' + (hrs % 24) + 'h' : hrs + 'h ' + mins + 'm') : '';
|
||||
el.className = 'fr-state';
|
||||
el.innerHTML = '<span class="fr-tag">Next</span><span><b>Next Wired Wednesday: ' + (f.nextLabel || f.nextWednesday || 'soon') + '.</b> Starts at midnight Central' + (when ? ', in ' + when : '') + '.</span>'
|
||||
+ '<span>Join now so your account is ready before it starts.</span>';
|
||||
}
|
||||
fetch('/api/wednesday').then(function (r) { return r.ok ? r.json() : null; }).catch(function () { return null; }).then(render);
|
||||
})();
|
||||
@@ -45,32 +45,32 @@
|
||||
'-webkit-backdrop-filter:blur(3px);backdrop-filter:blur(3px);';
|
||||
|
||||
var card = document.createElement('div');
|
||||
card.style.cssText = 'position:relative;width:100%;max-width:470px;background:#0b1512;color:#eef7f3;' +
|
||||
'border:1px solid rgba(67,232,195,.28);border-radius:18px;padding:26px 24px 22px;' +
|
||||
card.style.cssText = 'position:relative;width:100%;max-width:470px;background:var(--panel-solid);color:var(--ink);' +
|
||||
'border:1px solid var(--mint-line);border-radius:18px;padding:26px 24px 22px;' +
|
||||
'box-shadow:0 26px 70px rgba(0,0,0,.6);font-size:15px;line-height:1.55;';
|
||||
|
||||
var html =
|
||||
'<button type="button" class="iap-w-x" aria-label="Close" style="position:absolute;top:10px;right:12px;' +
|
||||
'background:none;border:0;color:#8ba69c;font-size:26px;line-height:1;cursor:pointer;padding:4px 8px;">×</button>' +
|
||||
'<div style="letter-spacing:2px;text-transform:uppercase;font-size:11px;font-weight:700;color:#43e8c3;">InstantAdPay</div>' +
|
||||
'<h2 style="margin:8px 0 12px;font-size:25px;line-height:1.25;color:#fff;">The ad spend in your line pays you, in the same transaction.</h2>' +
|
||||
'<p style="margin:0 0 14px;color:#c8d6e2;">You buy advertising you were going to buy anyway. When someone in your line buys a package, the contract splits it and your share lands in your wallet before the page reloads. No back office, no payday to wait for.</p>' +
|
||||
'<ul style="margin:0 0 16px;padding-left:18px;color:#c8d6e2;">' +
|
||||
'background:none;border:0;color:var(--muted);font-size:26px;line-height:1;cursor:pointer;padding:4px 8px;">×</button>' +
|
||||
'<div style="letter-spacing:2px;text-transform:uppercase;font-size:11px;font-weight:700;color:var(--mint);">InstantAdPay</div>' +
|
||||
'<h2 style="margin:8px 0 12px;font-size:25px;line-height:1.25;color:var(--ink);">The ad spend in your line pays you, in the same transaction.</h2>' +
|
||||
'<p style="margin:0 0 14px;color:var(--ink);">You buy advertising you were going to buy anyway. When someone in your line buys a package, the contract splits it and your share lands in your wallet before the page reloads. No back office, no payday to wait for.</p>' +
|
||||
'<ul style="margin:0 0 16px;padding-left:18px;color:var(--ink);">' +
|
||||
'<li style="margin-bottom:5px;">Every payout is on the public ledger, and you can read it yourself.</li>' +
|
||||
'<li style="margin-bottom:5px;">Free members earn ad credits by viewing ads, videos and visits.</li>' +
|
||||
'<li>Credits buy your own advertising. They are delivery, not a balance to hoard.</li>' +
|
||||
'</ul>';
|
||||
|
||||
if (fri) {
|
||||
html += '<div style="margin:0 0 16px;padding:12px 14px;border:1px solid rgba(255,178,56,.38);' +
|
||||
'background:rgba(255,178,56,.08);border-radius:12px;color:#eef7f3;">' +
|
||||
'<div style="font-weight:800;color:#ffb238;font-size:12px;letter-spacing:1.4px;text-transform:uppercase;margin-bottom:4px;">' + fri.tag + '</div>' +
|
||||
html += '<div style="margin:0 0 16px;padding:12px 14px;border:1px solid var(--amber-line);' +
|
||||
'background:var(--amber-soft);border-radius:12px;color:var(--ink);">' +
|
||||
'<div style="font-weight:800;color:var(--amber);font-size:12px;letter-spacing:1.4px;text-transform:uppercase;margin-bottom:4px;">' + fri.tag + '</div>' +
|
||||
'<div>' + fri.text + '</div></div>';
|
||||
}
|
||||
|
||||
html += '<div style="display:flex;gap:9px;flex-wrap:wrap;">' +
|
||||
'<a class="iap-w-go" href="/my#buy" style="flex:1 1 auto;text-align:center;text-decoration:none;background:linear-gradient(180deg,#5ff0cf,#43e8c3);color:#04120e;font-weight:800;padding:12px 16px;border-radius:11px;">See the packages</a>' +
|
||||
'<a class="iap-w-go" href="/ledger" style="flex:0 1 auto;text-align:center;text-decoration:none;border:1px solid rgba(67,232,195,.4);color:#43e8c3;font-weight:700;padding:12px 16px;border-radius:11px;">Live ledger</a>' +
|
||||
'<a class="iap-w-go" href="/ledger" style="flex:0 1 auto;text-align:center;text-decoration:none;border:1px solid var(--mint-line-2);color:var(--mint);font-weight:700;padding:12px 16px;border-radius:11px;">Live ledger</a>' +
|
||||
'</div>';
|
||||
|
||||
card.innerHTML = html;
|
||||
|
||||
|
After Width: | Height: | Size: 276 KiB |
|
After Width: | Height: | Size: 247 KiB |
|
After Width: | Height: | Size: 238 KiB |
|
After Width: | Height: | Size: 226 KiB |
|
After Width: | Height: | Size: 207 KiB |