Compare commits
253 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 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 |
@@ -399,10 +399,14 @@ 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) {} };
|
||||
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 +432,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 +464,18 @@ 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)); 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).
|
||||
const isUnclaimedShell = a => !!a && a.joinedVia === 'linkspin' && !a.lastSeen && !a.memberId;
|
||||
async function listAll(limit = 500, opts) { const all = await impl().listAll(limit); return opts && opts.shells ? all : all.filter(a => !isUnclaimedShell(a)); }
|
||||
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,11 +499,11 @@ 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, 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) => { const r = await impl().setProfile(String(e || '').toLowerCase(), a, bio, socials); if (!(r && r.error)) changed(String(e || '').toLowerCase()); return r; }, // profile edits reach LinkSpin too
|
||||
touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()),
|
||||
adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null),
|
||||
positionByAddress: a => impl().positionByAddress(normAddr(a)),
|
||||
|
||||
@@ -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 } , 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;
|
||||
|
||||
@@ -108,7 +108,7 @@ function head(o) {
|
||||
+ '</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=20261023ov"></script><script src="/assets/blog-page.js?v=20260921a"></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 +152,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'];
|
||||
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,27 @@
|
||||
//
|
||||
// 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 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; DATA_DIR = opts.dataDir; chain = opts.chain; PASS_TIERS = typeof opts.passTiers === 'function' ? opts.passTiers : 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 +32,105 @@ 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-10-28'; // 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,
|
||||
{ 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.' },
|
||||
{ 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 all ten games on your InstantAdPay account (linked positions included). Free play keeps paying real POL every day; the Pass plays more: 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 missions a day instead of 3 plus 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. 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 free 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. Sign in with your InstantAdPay account right in the game to save progress: clearing levels, finishing a place and solving the daily puzzle each pay POL, collected in your SpellWheel balance and sent to the wallet on your InstantAdPay account automatically. 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: '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 Haunted Manor (six rooms) through Oct 31, then 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) is the network\u2019s Halloween game. It opens on Oct 4 and closes at midnight Central at the end of Halloween night (Oct 31), and it shows in Members > Games only during the season; one tap signs you in with your InstantAdPay account. Walk the street, grab loose candy, hop the black cats and bats, and knock on doors. Every door is a short verified visit to a member\u2019s page or ad (a member video once you have visited them all), up to 15 doors a day, separate from your Earn visits and Drip Runner refuels. Most doors give a treat of 10 candy; about one door in five plays a trick, and beating it with quick taps adds a small bonus. Candy climbs a ladder that pays POL once per rung (100 candy 0.1 POL, 250 candy 0.25, 500 candy 0.5, 1,000 candy 1, 2,000 candy 2), from a season pool funded by a share of door ad spend and costume sales, so rungs pay only while the pool covers them. POL goes to the wallet on your InstantAdPay account once your game balance reaches 0.25 POL. The witch costume is free; the vampire (300 credits), bedsheet ghost (300) and Lucky caramel apple (500) are bought with your ad credits in the game\u2019s costume shop. Advertisers can also put a verified-visits pack behind the doors: when you create a verified-visits campaign, pick Everywhere (3 credits a visit), Behind Spooky Doors (4 credits a door) or Golden Spooky Door (6 credits a door, and the player gets a little bonus candy). Door packs show only in Spooky Doors until the season ends, then any doors left run as normal visits. Nothing here is a promise of income.' },
|
||||
{ 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. It pays POL for first clears only: a little for each stage the first time you clear it, and more for each chapter boss (the Ember Dragon 5 POL, the Kraken 7.5, the Shadow King 10). Replays pay nothing. 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.' },
|
||||
{ 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 ten 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
|
||||
{ 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 a quarter of the rate', 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 a quarter of the rate: 4 network views cost what 1 view here does, and 4 partner visits use up 1 visit of your pack. 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)" 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 +139,139 @@ 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: 'tank-hold', title: 'Matched with a sponsor (activation on hold)', q: ['Why can I not switch on payouts?', 'It says I am being matched with a sponsor'], tags: ['holding tank', 'switch on payouts', 'matched with a sponsor', 'ready to activate'],
|
||||
re: /(being matched|matched with a sponsor|(can.?t|cannot|unable to) (i )?(switch on|turn on|activate) (my )?payouts|activate (button|payouts) (is )?(gone|missing|hidden)|ready to activate)/i,
|
||||
a: 'You joined without a sponsor, so you are in the holding tank. The contract locks your sponsor for good the first time you switch on payouts or buy, so 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. To adopt you need payouts switched on and your own $20 or larger package bought; then open Members > My line > Holding tank. You can hold 2 open adoptions at a time and each one runs for 7 days, and if that person never links a wallet or buys they drop back into the tank. Adopting sets you as their sponsor, opens a chat and emails them, and their first purchase binds to you on the chain. You can also release one of your own free referrals into the tank for somebody else to work with, though not one you adopted less than 3 days ago. A member can be adopted twice in their lifetime at most, so an adoption you drop still costs them one of those chances. Members who have linked a wallet show a Ready to activate badge with the hours left and sit at the top of the list: their payouts are on hold until someone adopts them, and after 24 hours the site assigns them to the next eligible adopter in turn (own $20 package, fewer than 2 open adoptions, signed in within the last 7 days). Adopters take turns, so the one assigned least recently goes first.' },
|
||||
{ id: 'qualification', title: 'Qualification, levels 2 and 3, credits vs POL', q: ['How do I unlock level 2?', 'How does qualification work?', 'What is a pass-up?'], tags: ['qualification', 'level 2', 'level 3', 'pass-up', 'qualified start'],
|
||||
re: /(qualif|unlock level|level 2|level 3|pass.?up)/i,
|
||||
a: 'Two different things are earned here. CREDITS: every member, free ones included, earns ad credits by viewing ads, videos, visits and the daily sign-in; credits buy your own ads and are never withdrawn. POL: real crypto paid to your wallet when your referrals buy packages, once you are activated: the $20 starter package plus payouts switched on from your wallet. Level 1 pays 50 percent of the packages your direct referrals buy, from the day you are activated. Bring 2 buyers of $20 or more and level 2 unlocks; 5 unlock level 3. When a level is not qualified, its share climbs the sponsor line, checking up to 25 positions, and pays the first qualified person. Qualification never expires and cannot be bought. Qualified Start: you may link extra wallets of your own as positions under your account (Buy packages > Qualified Start); each one that buys a $20+ package counts as a qualifying buyer, its credits pool with yours, and 50% of its purchase comes back to your main wallet. Your own money, your own wallets, a faster start, never an income promise.' },
|
||||
{ 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,
|
||||
{ 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. 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,
|
||||
{ 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, 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: '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: '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.
|
||||
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 all ten games 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; } };
|
||||
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 cost what 1 view here does, and ' + n + ' partner visits use up 1 visit of your pack. 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/text 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)"), 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;
|
||||
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; } };
|
||||
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 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.
|
||||
${passTiersFact()}${refuelFact()}${synFact()}${polminerFact()}- 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 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.
|
||||
- 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.
|
||||
- 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).
|
||||
- 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.
|
||||
- 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.
|
||||
- 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 2 open adoptions, signed in within 7 days, not suspended; least recently auto-assigned first); the adopter gets a chat + email and Telegram shows the pickup marked (auto-assigned). If nobody is eligible they stay on hold and the admin is alerted; never the company. Someone whose same email or wallet already has a sponsor on LinkSpin is placed under that sponsor instead (not one they were released or rescued from). A member who arrived through a sponsor link is never held. Once they have a sponsor the hold lifts by itself. 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 +283,18 @@ 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").
|
||||
- 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 NINE 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. 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.
|
||||
@@ -152,7 +308,7 @@ FACTS:
|
||||
- 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 +318,50 @@ 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 free letter-wheel word game: swipe letters on the wheel to fill the crossword grid, travel through six cozy places (chapters), and solve a new daily puzzle shared by everyone. Pays POL for clearing levels, finishing a place and solving the daily puzzle, 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.
|
||||
- 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.
|
||||
- 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. It pays POL for FIRST clears only (stages 0.02 to 0.15 POL rising by chapter; bosses 0.25, 0.5, 2, 5, 7.5 and 10 POL for the Goblin King, Ice Queen, Bog Witch, Ember Dragon, Kraken and Shadow King); replays pay nothing. 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.
|
||||
- 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 (a member video once every page has been visited), 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 +387,41 @@ 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 === 'network-rate' || hit.id === 'c-network-rate') && SYN_N() !== 4) 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 === '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 = pmLive() ? hits : hits.filter(h => !/^(c-)?polminer$/.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;
|
||||
@@ -77,7 +78,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 +180,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 +195,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 +211,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;
|
||||
@@ -242,48 +345,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 +360,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,47 @@ 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)
|
||||
// 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 +426,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,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,370 @@
|
||||
# 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, the Druid hero, level cap 30 |
|
||||
| `sovereign` | Sovereign | 10000 ($100, the Growth package) | 30 days | weapons, gear, all DLC islands, the Necromancer hero, level cap 40 |
|
||||
| `legend` | Legend | 25000 ($250, the Leader package) | 365 days | weapons, gear, all DLC islands, every hero including the Archer, level cap 40 |
|
||||
|
||||
- **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
|
||||
@@ -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 };
|
||||
@@ -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' : ''); }
|
||||
|
||||
|
||||
@@ -1,152 +1,153 @@
|
||||
// Five Dollar Friday (Marty, 2026-09-20). Every Friday, Central time, any ad package of $5 or more
|
||||
// earns +20% bonus credits (purchased-grade, so they run login ads too), credited the moment the
|
||||
// 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.
|
||||
//
|
||||
// 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.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let X = {}, FILE = null, S = null;
|
||||
const TZ = 'America/Chicago';
|
||||
const dayOf = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekdayOf = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, weekday: 'short' });
|
||||
const hourOf = ts => Number(new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false }));
|
||||
const isFriday = ts => weekdayOf(ts) === 'Fri';
|
||||
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'friday.json'); S = load(); }
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { granted: {}, posts: {}, badges: {}, sent: {} }; } }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
// shared across instances when the app is wired with marks (server.js); true when nobody else has it
|
||||
async function claimOnce(key) { try { return X.marks ? await X.marks.claim(key) : true; } catch (e) { return true; } }
|
||||
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
return {
|
||||
on: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
||||
pct: Math.max(0, Number(c.fridayBonusPct) || 20),
|
||||
start: String(c.fridayStart || '2026-09-25'),
|
||||
};
|
||||
}
|
||||
// the next Friday on or after today (Central), as a day key and a label
|
||||
function nextFriday(now) {
|
||||
const t0 = now || Date.now();
|
||||
for (let d = 0; d < 8; d++) { const ts = t0 + d * 86400000; if (isFriday(ts) && dayOf(ts) >= cfg().start) return dayOf(ts); }
|
||||
return null;
|
||||
}
|
||||
function labelOf(dayKey) { const [y, m, d] = dayKey.split('-').map(Number); return new Date(Date.UTC(y, m - 1, d, 12)).toLocaleDateString('en-US', { month: 'long', day: 'numeric', timeZone: 'UTC' }); }
|
||||
// is the promo live right now (a Friday on or after the start, switched on)
|
||||
function liveNow(now) { const c = cfg(); const t = now || Date.now(); return c.on && isFriday(t) && dayOf(t) >= c.start; }
|
||||
function counts(dayKey) { return purchasesOn(dayKey).length; }
|
||||
|
||||
// every $5+ purchase on a given Central day, from the chain index
|
||||
function purchasesOn(dayKey) {
|
||||
const out = [];
|
||||
try { for (const ev of X.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.priceCents >= 500 && dayOf(ev.ts) === dayKey) out.push(ev); } catch (e) {}
|
||||
return out;
|
||||
}
|
||||
function paidOn(dayKey) {
|
||||
let wei = 0n, n = 0;
|
||||
try { for (const ev of X.chain.recentEvents(1e9)) if ((ev.type === 'TierPaid' || ev.type === 'AwardPaid') && dayOf(ev.ts) === dayKey) { wei += BigInt(ev.amountWei); n++; } } catch (e) {}
|
||||
return { pol: Number(wei / 10n ** 14n) / 10000, n };
|
||||
}
|
||||
function stats(dayKey) {
|
||||
const day = dayKey || dayOf(Date.now());
|
||||
const p = purchasesOn(day); const paid = paidOn(day);
|
||||
const usd = p.reduce((s, e) => s + e.priceCents, 0) / 100;
|
||||
const buyers = new Set(p.map(e => e.buyerId)).size;
|
||||
const bonus = Object.values(S.granted || {}).filter(g => g.day === day).reduce((s, g) => s + g.bonus, 0);
|
||||
return { day, packs: p.length, usd, buyers, polPaid: paid.pol, payouts: paid.n, bonusCredits: bonus };
|
||||
}
|
||||
// public view
|
||||
function view() {
|
||||
const c = cfg(); const now = Date.now(); const live = liveNow(now); const next = nextFriday(now);
|
||||
return { on: c.on, pct: c.pct, live, today: live ? stats(dayOf(now)) : null, nextFriday: next, nextLabel: next ? labelOf(next) : null, start: c.start };
|
||||
}
|
||||
|
||||
// the bonus: once per purchase tx, on a Friday on or after the start
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
|
||||
if (S.granted[ev.tx]) return null;
|
||||
const c = cfg(); const bonus = Math.round((Number(ev.creditAmount) || 0) * c.pct / 100);
|
||||
if (bonus <= 0) return null;
|
||||
const a = await X.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
|
||||
const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, '');
|
||||
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: 'Five Dollar Friday: +' + c.pct + '% on your ' + usd + ' package', ref: 'fdf:' + String(ev.tx).slice(0, 30) } });
|
||||
S.granted[ev.tx] = { day: dayOf(ev.ts), memberId: ev.buyerId, bonus, at: Date.now() }; save();
|
||||
try { await X.notify(ev.buyerId, 'Five Dollar Friday: +' + bonus + ' bonus credits', 'Your ' + usd + ' package landed on a Five Dollar Friday, so ' + bonus + ' bonus credits (+' + c.pct + '%) were added to your balance. Every pack bought on a Friday gets this. See your balance: https://instantadpay.com/my#campaigns', 'notice'); } catch (e) {}
|
||||
// the wave, every ten packs
|
||||
const st = stats(dayOf(ev.ts));
|
||||
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
|
||||
S.posts[st.day + ':' + st.packs] = Date.now(); save();
|
||||
X.telegram('\u{1F4B5} <b>Five Dollar Friday</b> · <b>' + st.packs + ' packs</b> so far today from ' + st.buyers + ' buyers, <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members in the same transactions.\nEvery $5+ pack today earns +' + c.pct + '% credits: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
return bonus;
|
||||
}
|
||||
|
||||
// five Fridays in a row (the most recent five promo Fridays that have happened), any $5+ pack each
|
||||
function fridayStreak(memberId) {
|
||||
const c = cfg(); const now = Date.now(); const days = [];
|
||||
for (let d = 0; d < 7 * 8 && days.length < 5; d++) { const ts = now - d * 86400000; const k = dayOf(ts); if (isFriday(ts) && k >= c.start && (k < dayOf(now) || liveNow(now))) days.push(k); }
|
||||
let streak = 0;
|
||||
for (const k of days) { if (purchasesOn(k).some(e => e.buyerId === Number(memberId))) streak++; else break; }
|
||||
return streak;
|
||||
}
|
||||
function earnedBadge(memberId) {
|
||||
if (S.badges[memberId]) return true;
|
||||
if (fridayStreak(memberId) >= 5) { S.badges[memberId] = Date.now(); save(); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
// scheduled moments, checked every few minutes: Thursday 18:00 CT notice + email, Friday 09:00 CT kickoff,
|
||||
// Saturday 00:xx CT wrap-up of the Friday that just ended
|
||||
async function tick() {
|
||||
const c = cfg(); if (!c.on) return;
|
||||
const now = Date.now(); const day = dayOf(now); const wd = weekdayOf(now); const h = hourOf(now);
|
||||
const next = nextFriday(now);
|
||||
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';
|
||||
await broadcast(subject, text);
|
||||
}
|
||||
if (wd === 'Fri' && h >= 9 && 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(() => {});
|
||||
}
|
||||
if (wd === 'Sat' && h < 3) {
|
||||
const fri = dayOf(now - 86400000);
|
||||
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
|
||||
S.sent['wrap:' + fri] = now; save();
|
||||
const st = stats(fri); const top = await topLines(fri);
|
||||
X.telegram('\u{1F3C1} <b>Five Dollar Friday wrap-up</b> (' + labelOf(fri) + ')\n<b>' + st.packs + ' packs</b> from ' + st.buyers + ' buyers · $' + st.usd.toFixed(0) + ' in ad packages · <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members · ' + st.bonusCredits.toLocaleString() + ' bonus credits handed out'
|
||||
+ (top.length ? '\nBiggest lines today: ' + top.map(t => t.who + ' (' + t.packs + ')').join(', ') : '') + '\nNext one is a week away. Line it up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
// most packs bought by a sponsor's directs on a day (the line that pushed hardest)
|
||||
async function topLines(dayKey) {
|
||||
const by = new Map();
|
||||
for (const ev of purchasesOn(dayKey)) { let sp = 0; try { const m = await X.chain.member(ev.buyerId); sp = m && m.sponsorId ? Number(m.sponsorId) : 0; } catch (e) {} if (!sp) continue; by.set(sp, (by.get(sp) || 0) + 1); }
|
||||
const rows = [...by.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
||||
const out = []; for (const [id, packs] of rows) { let who = '#' + id; try { const a = await X.accounts.byMemberId(id); if (a && a.username) who = '@' + a.username; } catch (e) {} out.push({ memberId: id, who, packs }); }
|
||||
return out;
|
||||
}
|
||||
// on-site notice + email to every active member (quiet 45+ days skipped, drip unsubscribes honoured)
|
||||
async function broadcast(subject, text) {
|
||||
let all = []; try { all = await X.accounts.listAll(5000); } catch (e) { return; }
|
||||
const now = Date.now(); let n = 0;
|
||||
for (const a of all) {
|
||||
if (!a.email) continue;
|
||||
if (now - (a.lastSeen || a.created || 0) > 45 * 86400000) continue;
|
||||
try { await X.notify(a.memberId, subject, text, 'notice'); } catch (e) {}
|
||||
try { if (X.mailer && X.mailer.hasKey() && !(X.drip && await X.drip.isUnsubscribed(a.email))) { await X.mailer.send(a.email, subject, text + '\n\nInstantAdPay'); n++; } } catch (e) {}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, view, stats, onEvent, tick, fridayStreak, earnedBadge, liveNow, nextFriday, isFriday, labelOf, topLines };
|
||||
// Five Dollar Friday (Marty, 2026-09-20). Every Friday, Central time, any ad package of $5 or more
|
||||
// earns +20% bonus credits (purchased-grade, so they run login ads too), credited the moment the
|
||||
// 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 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.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let X = {}, FILE = null, S = null;
|
||||
const TZ = 'America/Chicago';
|
||||
const dayOf = ts => new Date(ts).toLocaleDateString('en-CA', { timeZone: TZ });
|
||||
const weekdayOf = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, weekday: 'short' });
|
||||
const hourOf = ts => Number(new Date(ts).toLocaleString('en-US', { timeZone: TZ, hour: 'numeric', hour12: false }));
|
||||
const isFriday = ts => weekdayOf(ts) === 'Fri';
|
||||
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'friday.json'); S = load(); }
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { granted: {}, posts: {}, badges: {}, sent: {} }; } }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
// shared across instances when the app is wired with marks (server.js); true when nobody else has it
|
||||
async function claimOnce(key) { try { return X.marks ? await X.marks.claim(key) : true; } catch (e) { return true; } }
|
||||
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
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'),
|
||||
};
|
||||
}
|
||||
// the next Friday on or after today (Central), as a day key and a label
|
||||
function nextFriday(now) {
|
||||
const t0 = now || Date.now();
|
||||
for (let d = 0; d < 8; d++) { const ts = t0 + d * 86400000; if (isFriday(ts) && dayOf(ts) >= cfg().start) return dayOf(ts); }
|
||||
return null;
|
||||
}
|
||||
function labelOf(dayKey) { const [y, m, d] = dayKey.split('-').map(Number); return new Date(Date.UTC(y, m - 1, d, 12)).toLocaleDateString('en-US', { month: 'long', day: 'numeric', timeZone: 'UTC' }); }
|
||||
// is the promo live right now (a Friday on or after the start, switched on)
|
||||
function liveNow(now) { const c = cfg(); const t = now || Date.now(); return c.on && isFriday(t) && dayOf(t) >= c.start; }
|
||||
function counts(dayKey) { return purchasesOn(dayKey).length; }
|
||||
|
||||
// every $5+ purchase on a given Central day, from the chain index
|
||||
function purchasesOn(dayKey) {
|
||||
const out = [];
|
||||
try { for (const ev of X.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.priceCents >= 500 && dayOf(ev.ts) === dayKey) out.push(ev); } catch (e) {}
|
||||
return out;
|
||||
}
|
||||
function paidOn(dayKey) {
|
||||
let wei = 0n, n = 0;
|
||||
try { for (const ev of X.chain.recentEvents(1e9)) if ((ev.type === 'TierPaid' || ev.type === 'AwardPaid') && dayOf(ev.ts) === dayKey) { wei += BigInt(ev.amountWei); n++; } } catch (e) {}
|
||||
return { pol: Number(wei / 10n ** 14n) / 10000, n };
|
||||
}
|
||||
function stats(dayKey) {
|
||||
const day = dayKey || dayOf(Date.now());
|
||||
const p = purchasesOn(day); const paid = paidOn(day);
|
||||
const usd = p.reduce((s, e) => s + e.priceCents, 0) / 100;
|
||||
const buyers = new Set(p.map(e => e.buyerId)).size;
|
||||
const bonus = Object.values(S.granted || {}).filter(g => g.day === day).reduce((s, g) => s + g.bonus, 0);
|
||||
return { day, packs: p.length, usd, buyers, polPaid: paid.pol, payouts: paid.n, bonusCredits: bonus };
|
||||
}
|
||||
// public view
|
||||
function view() {
|
||||
const c = cfg(); const now = Date.now(); const live = liveNow(now); const next = nextFriday(now);
|
||||
return { on: c.on, pct: c.pct, live, today: live ? stats(dayOf(now)) : null, nextFriday: next, nextLabel: next ? labelOf(next) : null, start: c.start };
|
||||
}
|
||||
|
||||
// the bonus: once per purchase tx, on a Friday on or after the start
|
||||
async function onEvent(ev) {
|
||||
if (!ev || ev.type !== 'Purchase' || !liveNow(ev.ts) || ev.priceCents < 500) return null;
|
||||
if (S.granted[ev.tx]) return null;
|
||||
const c = cfg(); const bonus = Math.round((Number(ev.creditAmount) || 0) * c.pct / 100);
|
||||
if (bonus <= 0) return null;
|
||||
const a = await X.accounts.byMemberId(ev.buyerId); if (!a || !a.email) return null;
|
||||
const usd = ('$' + (ev.priceCents / 100).toFixed(2)).replace(/\.00$/, '');
|
||||
await X.ads.addEarned(a.email, bonus, { purchased: true, log: { kind: 'bonus', note: 'Five Dollar Friday: +' + c.pct + '% on your ' + usd + ' package', ref: 'fdf:' + String(ev.tx).slice(0, 30) } });
|
||||
S.granted[ev.tx] = { day: dayOf(ev.ts), memberId: ev.buyerId, bonus, at: Date.now() }; save();
|
||||
try { await X.notify(ev.buyerId, 'Five Dollar Friday: +' + bonus + ' bonus credits', 'Your ' + usd + ' package landed on a Five Dollar Friday, so ' + bonus + ' bonus credits (+' + c.pct + '%) were added to your balance. Every pack bought on a Friday gets this. See your balance: https://instantadpay.com/my#campaigns', 'notice'); } catch (e) {}
|
||||
// the wave, every ten packs
|
||||
const st = stats(dayOf(ev.ts));
|
||||
if (st.packs > 0 && st.packs % 10 === 0 && !S.posts[st.day + ':' + st.packs]) {
|
||||
S.posts[st.day + ':' + st.packs] = Date.now(); save();
|
||||
X.telegram('\u{1F4B5} <b>Five Dollar Friday</b> · <b>' + st.packs + ' packs</b> so far today from ' + st.buyers + ' buyers, <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members in the same transactions.\nEvery $5+ pack today earns +' + c.pct + '% credits: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
return bonus;
|
||||
}
|
||||
|
||||
// five Fridays in a row (the most recent five promo Fridays that have happened), any $5+ pack each
|
||||
function fridayStreak(memberId) {
|
||||
const c = cfg(); const now = Date.now(); const days = [];
|
||||
for (let d = 0; d < 7 * 8 && days.length < 5; d++) { const ts = now - d * 86400000; const k = dayOf(ts); if (isFriday(ts) && k >= c.start && (k < dayOf(now) || liveNow(now))) days.push(k); }
|
||||
let streak = 0;
|
||||
for (const k of days) { if (purchasesOn(k).some(e => e.buyerId === Number(memberId))) streak++; else break; }
|
||||
return streak;
|
||||
}
|
||||
function earnedBadge(memberId) {
|
||||
if (S.badges[memberId]) return true;
|
||||
if (fridayStreak(memberId) >= 5) { S.badges[memberId] = Date.now(); save(); return true; }
|
||||
return false;
|
||||
}
|
||||
|
||||
// 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;
|
||||
const now = Date.now(); const day = dayOf(now); const wd = weekdayOf(now); const h = hourOf(now);
|
||||
const next = nextFriday(now);
|
||||
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';
|
||||
await broadcast(subject, text);
|
||||
}
|
||||
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(() => {});
|
||||
}
|
||||
if (wd === 'Sat' && h < 3) {
|
||||
const fri = dayOf(now - 86400000);
|
||||
if (isFriday(now - 86400000) && fri >= c.start && !S.sent['wrap:' + fri] && await claimOnce('fri:wrap:' + fri)) {
|
||||
S.sent['wrap:' + fri] = now; save();
|
||||
const st = stats(fri); const top = await topLines(fri);
|
||||
X.telegram('\u{1F3C1} <b>Five Dollar Friday wrap-up</b> (' + labelOf(fri) + ')\n<b>' + st.packs + ' packs</b> from ' + st.buyers + ' buyers · $' + st.usd.toFixed(0) + ' in ad packages · <b>' + st.polPaid.toFixed(2) + ' POL</b> paid to members · ' + st.bonusCredits.toLocaleString() + ' bonus credits handed out'
|
||||
+ (top.length ? '\nBiggest lines today: ' + top.map(t => t.who + ' (' + t.packs + ')').join(', ') : '') + '\nNext one is a week away. Line it up: https://instantadpay.com/my#buy').catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
// most packs bought by a sponsor's directs on a day (the line that pushed hardest)
|
||||
async function topLines(dayKey) {
|
||||
const by = new Map();
|
||||
for (const ev of purchasesOn(dayKey)) { let sp = 0; try { const m = await X.chain.member(ev.buyerId); sp = m && m.sponsorId ? Number(m.sponsorId) : 0; } catch (e) {} if (!sp) continue; by.set(sp, (by.get(sp) || 0) + 1); }
|
||||
const rows = [...by.entries()].sort((a, b) => b[1] - a[1]).slice(0, 3);
|
||||
const out = []; for (const [id, packs] of rows) { let who = '#' + id; try { const a = await X.accounts.byMemberId(id); if (a && a.username) who = '@' + a.username; } catch (e) {} out.push({ memberId: id, who, packs }); }
|
||||
return out;
|
||||
}
|
||||
// on-site notice + email to every active member (quiet 45+ days skipped, drip unsubscribes honoured)
|
||||
async function broadcast(subject, text) {
|
||||
let all = []; try { all = await X.accounts.listAll(5000); } catch (e) { return; }
|
||||
const now = Date.now(); let n = 0;
|
||||
for (const a of all) {
|
||||
if (!a.email) continue;
|
||||
if (now - (a.lastSeen || a.created || 0) > 45 * 86400000) continue;
|
||||
try { await X.notify(a.memberId, subject, text, 'notice'); } catch (e) {}
|
||||
try { if (X.mailer && X.mailer.hasKey() && !(X.drip && await X.drip.isUnsubscribed(a.email))) { await X.mailer.send(a.email, subject, text + '\n\nInstantAdPay'); n++; } } catch (e) {}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
module.exports = { init, cfg, view, stats, onEvent, tick, fridayStreak, earnedBadge, liveNow, nextFriday, isFriday, labelOf, topLines };
|
||||
|
||||
@@ -0,0 +1,506 @@
|
||||
// Game Pass (2026-10-16): the $5 weekly pass across all the network games (ten with POL Miner, 2026-10-28), 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'];
|
||||
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' };
|
||||
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: the Druid hero', 'Shards of Valor: level cap 30'] },
|
||||
{ key: 'sovereign', name: 'Sovereign', set: 'Sovereign', price: 10000, days: 30,
|
||||
perks: ['Everything in Champion', 'Shards of Valor: every bonus island', 'Shards of Valor: the Necromancer hero', 'Shards of Valor: level cap 40'] },
|
||||
{ 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 hero, the Archer included', 'Shards of Valor: level cap 40'] },
|
||||
];
|
||||
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;
|
||||
|
||||
let R = null; // deps from server.js
|
||||
let passes, orders, prizes; // 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)) },
|
||||
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(),
|
||||
};
|
||||
}
|
||||
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');
|
||||
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) 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 };
|
||||
}
|
||||
|
||||
// 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.' };
|
||||
}
|
||||
|
||||
// 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)) return null;
|
||||
const e = await ownerOf(ev); if (!e) return null;
|
||||
if (!waitingOrders(e).length) return null;
|
||||
if (txUsed(ev.tx)) return null; // each purchase counts once, everywhere
|
||||
const at = await minedAt(ev);
|
||||
const w = waitingOrders(e).filter(o => cents >= c.tiers[o.tier].price && at + ORDER_SKEW_MS >= o.ts)
|
||||
.sort((x, y) => c.tiers[y.tier].price - c.tiers[x.tier].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 null; }
|
||||
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 { order: w.order, until: x.until, tier: w.tier };
|
||||
}
|
||||
|
||||
// ---- 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 };
|
||||
if (game && M) out.pending = r6((M.deferred[game] || []).reduce((n, x) => n + x.left, 0));
|
||||
return out;
|
||||
}
|
||||
|
||||
// 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));
|
||||
// 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;
|
||||
// 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 } })); }
|
||||
const out = { allowed: r6(carried + allowed), deferred, pass, day, carried, capHit, enforced, kind, pol, email: e, ts: t, own: allowed };
|
||||
L.refs[key] = out; touch();
|
||||
return { allowed: out.allowed, deferred, pass, day, carried, capHit, enforced, repeat: false };
|
||||
}
|
||||
|
||||
// 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') 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') 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 = { init, cfg, GAMES, NAMES, TIERS, TIER_NAMES, TIER_DEFS, flag, 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', 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,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 };
|
||||
@@ -141,7 +141,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=20261023ov"></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 = { init, record, flush, summary, goalOp, withClickId, softKey, placementOf, deviceOf, newId, adminView, on, noteSession, isOwnerSk };
|
||||
@@ -0,0 +1,191 @@
|
||||
// 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 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;
|
||||
const av = String(pf.avatarUrl || '').trim(); const bio = String(pf.bio || '').trim().slice(0, 600); let soc = null;
|
||||
if (pf.socials && typeof pf.socials === 'object') { const c = {}; for (const k of ['facebook', 'twitter', 'youtube', 'instagram', 'tiktok', 'telegram', 'linkedin', 'website', 'video']) { const v = String(pf.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, 'linkspin', 'linkspin');
|
||||
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) {
|
||||
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() }; 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)
|
||||
function receive(rows) { const run = chain_.then(() => handle(rows)); 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,108 @@
|
||||
// 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 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 (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) {
|
||||
let socials = null; try { socials = a.socials ? (typeof a.socials === 'string' ? JSON.parse(a.socials) : a.socials) : null; } catch (e) { socials = null; }
|
||||
const av = String(a.avatarUrl || '').trim();
|
||||
const avatarUrl = !av ? null : /^https:\/\//i.test(av) ? av : av.startsWith('/') ? PUBLIC() + av : null;
|
||||
const bio = String(a.bio || '').trim().slice(0, 600) || null;
|
||||
if (!avatarUrl && !bio && !(socials && Object.keys(socials).length)) return null;
|
||||
return { avatarUrl, bio, socials: socials && Object.keys(socials).length ? socials : null };
|
||||
}
|
||||
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;
|
||||
}
|
||||
// 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) { 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)) 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;
|
||||
}
|
||||
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 };
|
||||
@@ -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,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 @@
|
||||
// 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 #ccd" 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' };
|
||||
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; }
|
||||
});
|
||||
})();
|
||||
@@ -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(); });
|
||||
})();
|
||||
|
||||
@@ -1,266 +1,297 @@
|
||||
// Shared page runtime: site config, nav, formatting. Zero dependencies.
|
||||
window.IAP = (function () {
|
||||
let config = null;
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
async function getConfig() {
|
||||
if (!config) config = await (await fetch('/api/config')).json();
|
||||
return config;
|
||||
}
|
||||
// POL amounts display with two decimals (rounded half-up), e.g. 523.39
|
||||
function fmtPol(wei) {
|
||||
const cents = (BigInt(wei) + 5000000000000000n) / 10000000000000000n; // wei -> hundredths of a POL
|
||||
const s = cents.toString().padStart(3, '0');
|
||||
return s.slice(0, -2) + '.' + s.slice(-2);
|
||||
}
|
||||
const fmtUsd = cents => '$' + (cents / 100).toFixed(2);
|
||||
|
||||
function status(msg, cls) {
|
||||
let el = $('status');
|
||||
if (!el) { el = document.createElement('div'); el.id = 'status'; document.body.appendChild(el); }
|
||||
el.textContent = msg; el.className = cls || ''; el.hidden = false;
|
||||
clearTimeout(status._t);
|
||||
if (cls === 'ok') status._t = setTimeout(() => { el.hidden = true; }, 6000);
|
||||
}
|
||||
|
||||
async function renderNav(active) {
|
||||
const c = await getConfig();
|
||||
const nav = document.createElement('nav');
|
||||
nav.innerHTML = '<div class="wrap">'
|
||||
+ '<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="/#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="/my" data-p="my">Members</a>'
|
||||
+ '</span><span id="navWallet" class="muted">…</span></div>';
|
||||
document.body.prepend(nav);
|
||||
if (c.rehearsal) {
|
||||
const b = document.createElement('div');
|
||||
b.className = 'rehearsal';
|
||||
b.innerHTML = '<b>Testnet rehearsal</b>: running on ' + c.chainName + '. Purchases use valueless test POL while we prove every payout in public.';
|
||||
document.body.prepend(b);
|
||||
}
|
||||
const a = nav.querySelector('[data-p="' + active + '"]');
|
||||
if (a) a.className = 'active';
|
||||
refreshNavWallet();
|
||||
renderFooter();
|
||||
}
|
||||
function renderFooter() {
|
||||
if (document.getElementById('iapFooter')) return;
|
||||
const f = document.createElement('footer'); f.id = 'iapFooter';
|
||||
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>';
|
||||
document.body.appendChild(f);
|
||||
}
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
const el = $('navWallet');
|
||||
if (!el) return;
|
||||
if (me.signedIn) {
|
||||
// identity order: username, then email, then wallet
|
||||
const who = me.username
|
||||
? '<b>@' + String(me.username).replace(/[&<>]/g, '') + '</b>'
|
||||
: (me.email ? String(me.email).replace(/[&<>]/g, '')
|
||||
: (me.address ? '<span class="mono">' + me.address.slice(0, 6) + '…' + me.address.slice(-4) + '</span>' : 'signed in'));
|
||||
el.innerHTML = (me.memberId ? '<span class="badge">member #' + me.memberId + '</span> ' : '') + who;
|
||||
} else {
|
||||
el.innerHTML = '<a href="/my">Sign in</a>';
|
||||
}
|
||||
return me;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
function describeEvent(ev, c) {
|
||||
const pol = w => fmtPol(w) + ' POL';
|
||||
// real people, not numbers: use usernames when the site knows them
|
||||
const nm = id => (ev.names && ev.names[id])
|
||||
? String(ev.names[id]).replace(/[&<>]/g, '')
|
||||
: 'member #' + id;
|
||||
switch (ev.type) {
|
||||
case 'Purchase': return '🧾 ' + nm(ev.buyerId) + ' bought package #' + ev.productId
|
||||
+ ' (' + fmtUsd(ev.priceCents) + ') for ' + pol(ev.paidWei) + ' → +' + ev.creditAmount.toLocaleString() + ' credits';
|
||||
case 'TierPaid': return '💸 level ' + ev.tier + ' payout → ' + nm(ev.recipientId) + ': ' + pol(ev.amountWei)
|
||||
+ (ev.hops ? ' (passed up ' + ev.hops + ')' : '');
|
||||
case 'PassedUp': return '↷ level ' + ev.tier + ' passed over ' + nm(ev.skippedId) + ' (' + ev.reason + ')';
|
||||
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 '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';
|
||||
default: return '· ' + ev.type;
|
||||
}
|
||||
}
|
||||
function feedRow(ev, c) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'row t-' + ev.type;
|
||||
const when = ev.ts ? new Date(ev.ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||
div.innerHTML = (when ? '<span class="when" title="' + new Date(ev.ts).toLocaleString() + '">' + when + '</span>' : '') + '<span>' + describeEvent(ev, c) + '</span>'
|
||||
+ (c.explorer
|
||||
? '<span class="tx"><a target="_blank" rel="noopener" href="' + c.explorer + '/tx/' + ev.tx + '">verify ↗</a></span>'
|
||||
: '<span class="tx"><a href="/tx/' + ev.tx + '">verify ↗</a></span>'); // built-in viewer when the chain has no public explorer
|
||||
return div;
|
||||
}
|
||||
// Render one served ad into #<elId>. Silent if no inventory.
|
||||
// report an ad (auto-approved ads need a member-facing flag → admin notified)
|
||||
// 2026-09-16: was a native prompt() with 'broken' pre-filled, so a stray tap on OK filed a
|
||||
// "broken" report with no note (campaign #27). Now the site dialog, no default, reason validated.
|
||||
const REPORT_REASONS = ['broken', 'inappropriate', 'spam', 'scam', 'other'];
|
||||
async function reportAd(campaignId) {
|
||||
if (!campaignId) return;
|
||||
const raw = await ask({ title: 'Report this ad', text: 'What is wrong with it? Type one: broken, inappropriate, spam, scam, or other.', placeholder: 'e.g. broken', ok: 'Next' });
|
||||
if (raw === null) return;
|
||||
const reason = String(raw || '').trim().toLowerCase();
|
||||
if (!REPORT_REASONS.includes(reason)) { status('Pick one of: broken, inappropriate, spam, scam, or other.', 'bad'); return; }
|
||||
const note = await ask({ title: 'Report: ' + reason, text: 'Tell the admin what you saw, so it can be fixed. Optional, but it helps.', type: 'textarea', ok: 'Send report' });
|
||||
if (note === null) return;
|
||||
fetch('/api/report-ad', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ campaignId, reason, note: String(note || '').slice(0, 500) }) })
|
||||
.then(() => status('Thanks — this ad was reported to the admin for review.', 'ok'))
|
||||
.catch(() => status('Could not send the report. Try again.', 'bad'));
|
||||
}
|
||||
const reportTag = ad => ' <a class="ad-report small muted" href="#" data-cid="' + ad.id + '" style="margin-left:8px">⚠ report</a>';
|
||||
function wireReport(el) {
|
||||
const rl = el.querySelector('.ad-report');
|
||||
if (rl) rl.addEventListener('click', e => { e.preventDefault(); reportAd(Number(rl.dataset.cid)); });
|
||||
}
|
||||
async function adSlot(type, elId, opts) {
|
||||
try {
|
||||
const q = '/api/ads/slot?type=' + type + (opts && opts.width ? '&w=' + opts.width + '&h=' + opts.height : '');
|
||||
const { ad } = await (await fetch(q)).json();
|
||||
const el = $(elId);
|
||||
if (!ad || !el) return;
|
||||
el.hidden = false;
|
||||
if (ad.imageUrl) {
|
||||
el.style.textAlign = 'center';
|
||||
el.innerHTML = '<a href="' + ad.targetUrl + '" target="_blank" rel="noopener nofollow">'
|
||||
+ '<img src="' + ad.imageUrl + '" alt="advertisement" style="max-width:min(100%,728px);height:auto;display:block;margin:0 auto;border-radius:8px"></a>'
|
||||
+ '<div class="small muted">member ad' + reportTag(ad) + '</div>';
|
||||
} else {
|
||||
el.innerHTML = '<a href="' + ad.targetUrl + '" target="_blank" rel="noopener nofollow"><b>' + ad.title + '</b>'
|
||||
+ (ad.body ? ' · ' + ad.body : '') + '</a> <span class="small muted">member ad' + reportTag(ad) + '</span>';
|
||||
}
|
||||
wireReport(el);
|
||||
el.hidden = false;
|
||||
} catch (e) {}
|
||||
}
|
||||
// ── sign-up code request with the invisible guard fields (form age + honeypot)
|
||||
// and the icon check the server asks for only after an IP trips a limit ──
|
||||
const FORM_TS = Date.now();
|
||||
function iconCheck(host, ch, note) {
|
||||
return new Promise(resolve => {
|
||||
host.hidden = false;
|
||||
host.innerHTML = '<div class="small" style="margin:0 0 8px">' + (note ? esc(note) + ' ' : '') + 'Tap the <b>' + esc(ch.prompt) + '</b>.</div>'
|
||||
+ '<div class="icon-check">' + ch.options.map(o => '<button type="button" class="ic-btn">' + esc(o) + '</button>').join('') + '</div>';
|
||||
host.querySelectorAll('.ic-btn').forEach(b => b.addEventListener('click', () => { host.innerHTML = ''; host.hidden = true; resolve(b.textContent); }, { once: true }));
|
||||
});
|
||||
}
|
||||
// honeypot fields (join + sign-in): read-only until a trusted focus, so browser autofill and
|
||||
// password managers leave them alone; a value that appeared without a trusted event is ignored
|
||||
function armHoneypots() {
|
||||
document.querySelectorAll('.hp-field').forEach(el => {
|
||||
if (el.dataset.armed) return; el.dataset.armed = '1'; el.readOnly = true;
|
||||
const touch = e => { if (e.isTrusted) { el.readOnly = false; el.dataset.touched = '1'; } };
|
||||
el.addEventListener('focus', touch); el.addEventListener('input', touch); el.addEventListener('keydown', touch);
|
||||
});
|
||||
}
|
||||
armHoneypots(); document.addEventListener('DOMContentLoaded', armHoneypots);
|
||||
const hpValue = el => (el && el.dataset.touched === '1') ? (el.value || '') : '';
|
||||
// The server refuses a code request that arrives within a couple of seconds of the page loading,
|
||||
// because a script fills a form instantly and a person does not. A returning member whose email
|
||||
// is already autofilled has nothing to type, taps straight away, and gets told off for being
|
||||
// quick (Marty, 2026-09-23). So the page waits out the remainder itself: the person sees the
|
||||
// normal sending state, and anything posting at the endpoint without a page behind it still
|
||||
// fails the same check.
|
||||
const MIN_FORM_MS = 2400; // the server wants 2000; leave headroom for clock skew in transit
|
||||
function formSettled() {
|
||||
const left = MIN_FORM_MS - (Date.now() - FORM_TS);
|
||||
return left > 0 ? new Promise(r => setTimeout(r, left)) : Promise.resolve();
|
||||
}
|
||||
async function requestCode(email, opts) {
|
||||
const o = opts || {};
|
||||
let pick = null;
|
||||
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();
|
||||
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;
|
||||
}
|
||||
throw new Error('Could not verify. Refresh the page and try again.');
|
||||
}
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
// ── founding-week checklist, read from the live account. Shared by /launch and
|
||||
// the dashboard mark. Two items are the member's own call and persist locally.
|
||||
const LAUNCH_KEY = 'iap.launch.manual';
|
||||
const manualSet = () => { try { return new Set(JSON.parse(localStorage.getItem(LAUNCH_KEY) || '[]')); } catch (e) { return new Set(); } };
|
||||
function launchToggle(key) { const s = manualSet(); if (s.has(key)) s.delete(key); else s.add(key); try { localStorage.setItem(LAUNCH_KEY, JSON.stringify([...s])); } catch (e) {} }
|
||||
function launchChecks(me) {
|
||||
const m = me || {}, man = manualSet();
|
||||
const bc = Number(m.buyerCount || 0), refs = (m.referrals || []).length;
|
||||
return [
|
||||
{ key: 'username', title: 'Pick your username', done: !!m.username, href: '/my#profile', cta: 'Profile',
|
||||
how: 'Profile tab. It becomes your invite link and your public page, and it is permanent.',
|
||||
why: 'Every link, banner and video you hand out this week carries it. Change it later and the links you already sent die.' },
|
||||
{ key: 'wallet', title: 'Link your wallet', done: !!m.address, href: '/my#wallet', cta: 'Wallet',
|
||||
how: 'Wallet tab, Connect, sign the free message. MetaMask recommended. Never held crypto? The wallet guide in Training walks through buying POL with a card.',
|
||||
why: 'Payouts go to this address. No wallet, nowhere to pay you.' },
|
||||
{ key: 'payouts', title: 'Switch on payouts', done: !!m.memberId, href: '/my#wallet', cta: 'Wallet',
|
||||
how: 'Wallet tab, one small transaction. It registers your address with the contract.',
|
||||
why: 'The contract binds each buyer to their sponsor at their first purchase. If payouts are off when your first person buys, that commission is not yours.' },
|
||||
{ key: 'level2', title: 'Qualify: open level 2', done: bc >= 2, href: '/my#buy', cta: 'Buy packages',
|
||||
how: 'Two of your people buy a $20 or more package. Or use Qualified Start: add two positions from extra wallets in your own MetaMask and buy a $20 package from each (about $23 of POL in each wallet).',
|
||||
why: 'Until you have two qualifying buyers, every level 2 payment from your team climbs past you.',
|
||||
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 2.' },
|
||||
{ key: 'level3', title: 'The leader play: open all three levels', done: bc >= 5, href: '/my#buy', cta: 'Qualified Start',
|
||||
how: 'Five qualifying buyers, real or Qualified Start, up to five linked positions. Once qualified, buy from your main wallet so your sponsor is paid in full.',
|
||||
why: 'A leader whose team goes three deep this week collects level 3 from day one instead of watching those 10% payments pass upward. Optional for members, the play for leaders.',
|
||||
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 5.' },
|
||||
{ key: 'banner', title: 'Upload your line banner', done: !!m.lineBannerUrl, href: '/my#profile', cta: 'Profile',
|
||||
how: 'Profile tab, line banner. It shows on the welcome tour to everyone in your next three levels.',
|
||||
why: 'Your first advertising to your own team, free, and it is live the moment they join.' },
|
||||
{ key: 'links', title: 'Copy your links and pick a play', done: man.has('links'), manual: true,
|
||||
how: 'Promo tools, Your links: the invite link and the five angle links, plus the matching hook videos. Then read the plays page and choose one.',
|
||||
why: 'On launch day you send links, not explanations. Having them ready is the whole difference between a launch and a scramble.' },
|
||||
{ key: 'two', title: 'Place your first two', done: refs >= 2, href: '/my#line', cta: 'My line',
|
||||
how: 'Two people you have actually talked to, joined through your link, walked through items 1 to 3 on their own accounts.',
|
||||
why: 'Your first two are the shape of your whole line. Choose them, do not wait for them.',
|
||||
note: 'Joined through you so far: <b>' + refs + '</b>.' }
|
||||
];
|
||||
}
|
||||
// In-page dialogs instead of window.prompt / confirm. Mobile Safari shows a red "Suppress dialogs"
|
||||
// option on the second native pop-up in a row and, once tapped, swallows every later prompt on the
|
||||
// site until reload. ask() resolves the typed value (null on cancel); confirmBox() resolves true/false.
|
||||
function dialog(o) {
|
||||
return new Promise(resolve => {
|
||||
const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200';
|
||||
const field = o.type === 'none' ? '' : o.type === 'textarea'
|
||||
? '<textarea id="dlgInput" rows="5" style="width:100%;margin-top:12px">' + esc(o.value) + '</textarea>'
|
||||
: '<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>';
|
||||
document.body.appendChild(back);
|
||||
const inp = back.querySelector('#dlgInput');
|
||||
const done = v => { document.removeEventListener('keydown', onKey); back.remove(); resolve(v); };
|
||||
const okv = () => done(o.type === 'none' ? true : (inp ? inp.value : ''));
|
||||
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));
|
||||
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, $ };
|
||||
})();
|
||||
// Shared page runtime: site config, nav, formatting. Zero dependencies.
|
||||
window.IAP = (function () {
|
||||
let config = null;
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
async function getConfig() {
|
||||
if (!config) config = await (await fetch('/api/config')).json();
|
||||
return config;
|
||||
}
|
||||
// POL amounts display with two decimals (rounded half-up), e.g. 523.39
|
||||
function fmtPol(wei) {
|
||||
const cents = (BigInt(wei) + 5000000000000000n) / 10000000000000000n; // wei -> hundredths of a POL
|
||||
const s = cents.toString().padStart(3, '0');
|
||||
return s.slice(0, -2) + '.' + s.slice(-2);
|
||||
}
|
||||
const fmtUsd = cents => '$' + (cents / 100).toFixed(2);
|
||||
|
||||
function status(msg, cls) {
|
||||
let el = $('status');
|
||||
if (!el) { el = document.createElement('div'); el.id = 'status'; document.body.appendChild(el); }
|
||||
el.textContent = msg; el.className = cls || ''; el.hidden = false;
|
||||
clearTimeout(status._t);
|
||||
if (cls === 'ok') status._t = setTimeout(() => { el.hidden = true; }, 6000);
|
||||
}
|
||||
|
||||
async function renderNav(active) {
|
||||
const c = await getConfig();
|
||||
const nav = document.createElement('nav');
|
||||
nav.innerHTML = '<div class="wrap">'
|
||||
+ '<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);
|
||||
if (c.rehearsal) {
|
||||
const b = document.createElement('div');
|
||||
b.className = 'rehearsal';
|
||||
b.innerHTML = '<b>Testnet rehearsal</b>: running on ' + c.chainName + '. Purchases use valueless test POL while we prove every payout in public.';
|
||||
document.body.prepend(b);
|
||||
}
|
||||
const a = nav.querySelector('[data-p="' + active + '"]');
|
||||
if (a) a.className = 'active';
|
||||
refreshNavWallet();
|
||||
renderFooter();
|
||||
}
|
||||
function renderFooter() {
|
||||
if (document.getElementById('iapFooter')) return;
|
||||
const f = document.createElement('footer'); f.id = 'iapFooter';
|
||||
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="/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="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
|
||||
document.body.appendChild(f);
|
||||
}
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
const el = $('navWallet');
|
||||
if (!el) return;
|
||||
if (me.signedIn) {
|
||||
// identity order: username, then email, then wallet
|
||||
const who = me.username
|
||||
? '<b>@' + String(me.username).replace(/[&<>]/g, '') + '</b>'
|
||||
: (me.email ? String(me.email).replace(/[&<>]/g, '')
|
||||
: (me.address ? '<span class="mono">' + me.address.slice(0, 6) + '…' + me.address.slice(-4) + '</span>' : 'signed in'));
|
||||
el.innerHTML = (me.memberId ? '<span class="badge">member #' + me.memberId + '</span> ' : '') + who;
|
||||
} else {
|
||||
el.innerHTML = '<a href="/my">Sign in</a>';
|
||||
}
|
||||
return me;
|
||||
} catch (e) { return null; }
|
||||
}
|
||||
function describeEvent(ev, c) {
|
||||
const pol = w => fmtPol(w) + ' POL';
|
||||
// real people, not numbers: use usernames when the site knows them
|
||||
const nm = id => (ev.names && ev.names[id])
|
||||
? String(ev.names[id]).replace(/[&<>]/g, '')
|
||||
: 'member #' + id;
|
||||
switch (ev.type) {
|
||||
case 'Purchase': return '🧾 ' + nm(ev.buyerId) + ' bought package #' + ev.productId
|
||||
+ ' (' + fmtUsd(ev.priceCents) + ') for ' + pol(ev.paidWei) + ' → +' + ev.creditAmount.toLocaleString() + ' credits';
|
||||
case 'TierPaid': return '💸 level ' + ev.tier + ' payout → ' + nm(ev.recipientId) + ': ' + pol(ev.amountWei)
|
||||
+ (ev.hops ? ' (passed up ' + ev.hops + ')' : '');
|
||||
case 'PassedUp': return '↷ level ' + ev.tier + ' passed over ' + nm(ev.skippedId) + ' (' + ev.reason + ')';
|
||||
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 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';
|
||||
default: return '· ' + ev.type;
|
||||
}
|
||||
}
|
||||
function feedRow(ev, c) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'row t-' + ev.type;
|
||||
const when = ev.ts ? new Date(ev.ts).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) : '';
|
||||
div.innerHTML = (when ? '<span class="when" title="' + new Date(ev.ts).toLocaleString() + '">' + when + '</span>' : '') + '<span>' + describeEvent(ev, c) + '</span>'
|
||||
+ (c.explorer
|
||||
? '<span class="tx"><a target="_blank" rel="noopener" href="' + c.explorer + '/tx/' + ev.tx + '">verify ↗</a></span>'
|
||||
: '<span class="tx"><a href="/tx/' + ev.tx + '">verify ↗</a></span>'); // built-in viewer when the chain has no public explorer
|
||||
return div;
|
||||
}
|
||||
// Render one served ad into #<elId>. Silent if no inventory.
|
||||
// report an ad (auto-approved ads need a member-facing flag → admin notified)
|
||||
// 2026-09-16: was a native prompt() with 'broken' pre-filled, so a stray tap on OK filed a
|
||||
// "broken" report with no note (campaign #27). Now the site dialog, no default, reason validated.
|
||||
const REPORT_REASONS = ['broken', 'inappropriate', 'spam', 'scam', 'other'];
|
||||
async function reportAd(campaignId) {
|
||||
if (!campaignId) return;
|
||||
const raw = await ask({ title: 'Report this ad', text: 'What is wrong with it? Type one: broken, inappropriate, spam, scam, or other.', placeholder: 'e.g. broken', ok: 'Next' });
|
||||
if (raw === null) return;
|
||||
const reason = String(raw || '').trim().toLowerCase();
|
||||
if (!REPORT_REASONS.includes(reason)) { status('Pick one of: broken, inappropriate, spam, scam, or other.', 'bad'); return; }
|
||||
const note = await ask({ title: 'Report: ' + reason, text: 'Tell the admin what you saw, so it can be fixed. Optional, but it helps.', type: 'textarea', ok: 'Send report' });
|
||||
if (note === null) return;
|
||||
fetch('/api/report-ad', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ campaignId, reason, note: String(note || '').slice(0, 500) }) })
|
||||
.then(() => status('Thanks — this ad was reported to the admin for review.', 'ok'))
|
||||
.catch(() => status('Could not send the report. Try again.', 'bad'));
|
||||
}
|
||||
const reportTag = ad => ' <a class="ad-report small muted" href="#" data-cid="' + ad.id + '" style="margin-left:8px">⚠ report</a>';
|
||||
function wireReport(el) {
|
||||
const rl = el.querySelector('.ad-report');
|
||||
if (rl) rl.addEventListener('click', e => { e.preventDefault(); reportAd(Number(rl.dataset.cid)); });
|
||||
}
|
||||
async function adSlot(type, elId, opts) {
|
||||
try {
|
||||
const q = '/api/ads/slot?type=' + type + (opts && opts.width ? '&w=' + opts.width + '&h=' + opts.height : '');
|
||||
const { ad } = await (await fetch(q)).json();
|
||||
const el = $(elId);
|
||||
if (!ad || !el) return;
|
||||
el.hidden = false;
|
||||
if (ad.imageUrl) {
|
||||
el.style.textAlign = 'center';
|
||||
el.innerHTML = '<a href="' + ad.targetUrl + '" target="_blank" rel="noopener nofollow">'
|
||||
+ '<img src="' + ad.imageUrl + '" alt="advertisement" style="max-width:min(100%,728px);height:auto;display:block;margin:0 auto;border-radius:8px"></a>'
|
||||
+ '<div class="small muted">member ad' + reportTag(ad) + '</div>';
|
||||
} else {
|
||||
el.innerHTML = '<a href="' + ad.targetUrl + '" target="_blank" rel="noopener nofollow"><b>' + ad.title + '</b>'
|
||||
+ (ad.body ? ' · ' + ad.body : '') + '</a> <span class="small muted">member ad' + reportTag(ad) + '</span>';
|
||||
}
|
||||
wireReport(el);
|
||||
el.hidden = false;
|
||||
} catch (e) {}
|
||||
}
|
||||
// ── sign-up code request with the invisible guard fields (form age + honeypot)
|
||||
// and the icon check the server asks for only after an IP trips a limit ──
|
||||
const FORM_TS = Date.now();
|
||||
function iconCheck(host, ch, note) {
|
||||
return new Promise(resolve => {
|
||||
host.hidden = false;
|
||||
host.innerHTML = '<div class="small" style="margin:0 0 8px">' + (note ? esc(note) + ' ' : '') + 'Tap the <b>' + esc(ch.prompt) + '</b>.</div>'
|
||||
+ '<div class="icon-check">' + ch.options.map(o => '<button type="button" class="ic-btn">' + esc(o) + '</button>').join('') + '</div>';
|
||||
host.querySelectorAll('.ic-btn').forEach(b => b.addEventListener('click', () => { host.innerHTML = ''; host.hidden = true; resolve(b.textContent); }, { once: true }));
|
||||
});
|
||||
}
|
||||
// honeypot fields (join + sign-in): read-only until a trusted focus, so browser autofill and
|
||||
// password managers leave them alone; a value that appeared without a trusted event is ignored
|
||||
function armHoneypots() {
|
||||
document.querySelectorAll('.hp-field').forEach(el => {
|
||||
if (el.dataset.armed) return; el.dataset.armed = '1'; el.readOnly = true;
|
||||
const touch = e => { if (e.isTrusted) { el.readOnly = false; el.dataset.touched = '1'; } };
|
||||
el.addEventListener('focus', touch); el.addEventListener('input', touch); el.addEventListener('keydown', touch);
|
||||
});
|
||||
}
|
||||
armHoneypots(); document.addEventListener('DOMContentLoaded', armHoneypots);
|
||||
const hpValue = el => (el && el.dataset.touched === '1') ? (el.value || '') : '';
|
||||
// The server refuses a code request that arrives within a couple of seconds of the page loading,
|
||||
// because a script fills a form instantly and a person does not. A returning member whose email
|
||||
// is already autofilled has nothing to type, taps straight away, and gets told off for being
|
||||
// quick (Marty, 2026-09-23). So the page waits out the remainder itself: the person sees the
|
||||
// normal sending state, and anything posting at the endpoint without a page behind it still
|
||||
// fails the same check.
|
||||
const MIN_FORM_MS = 2400; // the server wants 2000; leave headroom for clock skew in transit
|
||||
function formSettled() {
|
||||
const left = MIN_FORM_MS - (Date.now() - FORM_TS);
|
||||
return left > 0 ? new Promise(r => setTimeout(r, left)) : Promise.resolve();
|
||||
}
|
||||
async function requestCode(email, opts) {
|
||||
const o = opts || {};
|
||||
let pick = null;
|
||||
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, fage: Date.now() - FORM_TS, hp_field_x9: hpValue(o.honeypot), pick, ref: o.ref || null, angle: o.angle || 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;
|
||||
}
|
||||
throw new Error('Could not verify. Refresh the page and try again.');
|
||||
}
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
// ── founding-week checklist, read from the live account. Shared by /launch and
|
||||
// the dashboard mark. Two items are the member's own call and persist locally.
|
||||
const LAUNCH_KEY = 'iap.launch.manual';
|
||||
const manualSet = () => { try { return new Set(JSON.parse(localStorage.getItem(LAUNCH_KEY) || '[]')); } catch (e) { return new Set(); } };
|
||||
function launchToggle(key) { const s = manualSet(); if (s.has(key)) s.delete(key); else s.add(key); try { localStorage.setItem(LAUNCH_KEY, JSON.stringify([...s])); } catch (e) {} }
|
||||
function launchChecks(me) {
|
||||
const m = me || {}, man = manualSet();
|
||||
const bc = Number(m.buyerCount || 0), refs = (m.referrals || []).length;
|
||||
return [
|
||||
{ key: 'username', title: 'Pick your username', done: !!m.username, href: '/my#profile', cta: 'Profile',
|
||||
how: 'Profile tab. It becomes your invite link and your public page, and it is permanent.',
|
||||
why: 'Every link, banner and video you hand out this week carries it. Change it later and the links you already sent die.' },
|
||||
{ key: 'wallet', title: 'Link your wallet', done: !!m.address, href: '/my#wallet', cta: 'Wallet',
|
||||
how: 'Wallet tab, Connect, sign the free message. MetaMask recommended. Never held crypto? The wallet guide in Training walks through buying POL with a card.',
|
||||
why: 'Payouts go to this address. No wallet, nowhere to pay you.' },
|
||||
{ key: 'payouts', title: 'Switch on payouts', done: !!m.memberId, href: '/my#wallet', cta: 'Wallet',
|
||||
how: 'Wallet tab, one small transaction. It registers your address with the contract.',
|
||||
why: 'The contract binds each buyer to their sponsor at their first purchase. If payouts are off when your first person buys, that commission is not yours.' },
|
||||
{ key: 'level2', title: 'Qualify: open level 2', done: bc >= 2, href: '/my#buy', cta: 'Buy packages',
|
||||
how: 'Two of your people buy a $20 or more package. Or use Qualified Start: add two positions from extra wallets in your own MetaMask and buy a $20 package from each (about $23 of POL in each wallet).',
|
||||
why: 'Until you have two qualifying buyers, every level 2 payment from your team climbs past you.',
|
||||
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 2.' },
|
||||
{ key: 'level3', title: 'The leader play: open all three levels', done: bc >= 5, href: '/my#buy', cta: 'Qualified Start',
|
||||
how: 'Five qualifying buyers, real or Qualified Start, up to five linked positions. Once qualified, buy from your main wallet so your sponsor is paid in full.',
|
||||
why: 'A leader whose team goes three deep this week collects level 3 from day one instead of watching those 10% payments pass upward. Optional for members, the play for leaders.',
|
||||
note: 'Qualifying buyers so far: <b>' + bc + '</b> of 5.' },
|
||||
{ key: 'banner', title: 'Upload your line banner', done: !!m.lineBannerUrl, href: '/my#profile', cta: 'Profile',
|
||||
how: 'Profile tab, line banner. It shows on the welcome tour to everyone in your next three levels.',
|
||||
why: 'Your first advertising to your own team, free, and it is live the moment they join.' },
|
||||
{ key: 'links', title: 'Copy your links and pick a play', done: man.has('links'), manual: true,
|
||||
how: 'Promo tools, Your links: the invite link and the five angle links, plus the matching hook videos. Then read the plays page and choose one.',
|
||||
why: 'On launch day you send links, not explanations. Having them ready is the whole difference between a launch and a scramble.' },
|
||||
{ key: 'two', title: 'Place your first two', done: refs >= 2, href: '/my#line', cta: 'My line',
|
||||
how: 'Two people you have actually talked to, joined through your link, walked through items 1 to 3 on their own accounts.',
|
||||
why: 'Your first two are the shape of your whole line. Choose them, do not wait for them.',
|
||||
note: 'Joined through you so far: <b>' + refs + '</b>.' }
|
||||
];
|
||||
}
|
||||
// In-page dialogs instead of window.prompt / confirm. Mobile Safari shows a red "Suppress dialogs"
|
||||
// option on the second native pop-up in a row and, once tapped, swallows every later prompt on the
|
||||
// site until reload. ask() resolves the typed value (null on cancel); confirmBox() resolves true/false.
|
||||
function dialog(o) {
|
||||
return new Promise(resolve => {
|
||||
const esc = t => String(t == null ? '' : t).replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));
|
||||
const back = document.createElement('div'); back.className = 'modal-back'; back.style.zIndex = '200';
|
||||
const field = o.type === 'none' ? '' : o.type === 'textarea'
|
||||
? '<textarea id="dlgInput" rows="5" style="width:100%;margin-top:12px">' + esc(o.value) + '</textarea>'
|
||||
: '<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">' + (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); };
|
||||
const okv = () => done(o.type === 'none' ? true : (inp ? inp.value : ''));
|
||||
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);
|
||||
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, $,
|
||||
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 () {});
|
||||
})();
|
||||
|
||||
@@ -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,81 @@
|
||||
// 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)
|
||||
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 u.href; } 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:#e8a317}.er-dot.green{background:#2fa36b}.er-dot.amber{background:#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 ? '#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="https://linkspin.app/credits?from=iap&task=refuel#refuel" 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();
|
||||
|
||||
@@ -1,112 +1,143 @@
|
||||
// Invite / lead-capture page: /join/<token>[?v=<angle>]
|
||||
// Email first (code sign-in creates the account), wallet later inside the
|
||||
// member area. The angle only changes the hook copy; the sponsor cookie was
|
||||
// set by the server when this page was served.
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
const LEG = (brand, seg) => seg === 'adv'
|
||||
? { eyebrow: 'For former ' + brand + ' advertisers', h: 'Your next ad budget <em>pays you back.</em>',
|
||||
lead: brand + ' is closed. The people who bought ads there are exactly who InstantAdPay was built for: real ad packages from $5, seven formats, and every package in your line paid out by a verified contract on Polygon in the same transaction.',
|
||||
points: ['Welcome-back credits land the moment your account exists: enough to run a real banner or text campaign today, on us.', 'Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw your ad.', 'When anyone in your line buys ads, the contract pays you in that same transaction. Public on Polygonscan, nothing held, nothing to withdraw.'],
|
||||
cta: 'Claim your welcome-back credits', sub: 'Free account by email. No password, no wallet today. Use the email you had on ' + brand + ': the credits are tied to it.', video: false }
|
||||
: { eyebrow: 'For former ' + brand + ' members', h: 'Same daily habit. <em>Real payouts on-chain.</em>',
|
||||
lead: 'You viewed ads on ' + brand + '. Here you view ads to earn credits, run your own campaign with them for free, and when anyone in your line buys ads you are paid in POL to your own wallet in the same transaction.',
|
||||
points: ['Welcome-back credits on day one, so your first campaign runs before you have viewed a single ad.', 'Join with just an email. No password, no wallet today. Link a wallet later, only when you want payouts switched on.', 'Every payout is a public transaction on Polygon. Nothing is held, so there is nothing to withdraw and nothing to wait for.'],
|
||||
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'),
|
||||
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.' },
|
||||
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, dwell-timed views, packages from $5.',
|
||||
points: ['Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits.', 'Views are timed on the server, so a real person saw your ad. Banners and text also run across a partner ad network.', 'When anyone in your line buys ads, the contract pays you in that same transaction.'],
|
||||
cta: 'Put your next ad dollar where it pays you back', sub: 'Free account by email. See every format and the live rates before you buy anything.' },
|
||||
free: { eyebrow: 'Costs nothing to try', h: 'Watch first. <em>Spend never.</em>', lead: 'Join free, view a few ads, earn credits, and run your first campaign for zero dollars. Upgrade only if you want more reach.',
|
||||
points: ['Join with just an email. No password, no wallet today.', 'View a few ads each day and earn credits you can spend on your own banner or text campaign.', 'Buy a package only if you want more reach. They start at $5, and every payout on them is public.'],
|
||||
cta: 'Start for free. No card, no wallet.', sub: 'Type your email and we send a 6-digit code. That is the whole signup.' },
|
||||
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and nothing is ever held.',
|
||||
points: ['Every payout is a public transaction on Polygon. Click it, read it, verify it yourself.', 'The contract holds zero balance. It splits and sends in the same transaction, with no pause switch and no upgrade path.', 'No back office means nobody can delay, reverse or review your commission.'],
|
||||
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.' }
|
||||
};
|
||||
// ?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.
|
||||
const who = String(new URLSearchParams(location.search).get('name') || '').replace(/[^A-Za-z\u00C0-\u024F' -]/g, '').trim().slice(0, 30);
|
||||
if (who) {
|
||||
const top = /^\/join\/(company|top)$/i.test(location.pathname);
|
||||
const h = $('jnHello');
|
||||
if (h) { h.textContent = who + (top ? ', your spot directly under the company at the top is reserved for you. Activate with the $20 package to claim it.' : ', this invitation is for you.'); h.hidden = false; }
|
||||
}
|
||||
const v = new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '';
|
||||
const a = v && ANGLES[v];
|
||||
if (a) {
|
||||
document.body.classList.add('squeeze'); // server sets it too; this covers cached HTML
|
||||
$('jnEyebrow').textContent = '· ' + a.eyebrow; $('jnHead').innerHTML = a.h; $('jnLead').textContent = a.lead;
|
||||
if (a.cta) { $('jnCapH').textContent = a.cta; $('jnCapSub').textContent = a.sub || ''; }
|
||||
// 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'; }
|
||||
$('jnPoints').innerHTML = (a.points || []).map(t => '<li>' + t.replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])) + '</li>').join('');
|
||||
$('jnMock').hidden = true; $('jnAngle').hidden = false; $('jnPoints').hidden = false;
|
||||
}
|
||||
|
||||
async function api(path, body) {
|
||||
const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
|
||||
if (r.error) throw new Error(r.error);
|
||||
return r;
|
||||
}
|
||||
const err = m => { const e = $('jnErr'); e.textContent = m || ''; e.hidden = !m; };
|
||||
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 send = busy($('jnSend'), async () => {
|
||||
const r = await IAP.requestCode($('jnEmail').value, codeOpts());
|
||||
$('jnCodeRow').hidden = false; $('jnVerify').hidden = false; $('jnSend').hidden = true; $('jnResend').hidden = false;
|
||||
if (r.devCode) $('jnCode').value = r.devCode;
|
||||
// the last thing they see before the account is created: who they are joining under
|
||||
if (sponsorName) { $('jnUnder').textContent = 'Joining under ' + sponsorName + '. Not who invited you? Open their invite link first, then come back for the code.'; $('jnUnder').hidden = false; }
|
||||
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);
|
||||
$('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 });
|
||||
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
|
||||
}));
|
||||
$('jnEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('jnVerify').hidden ? $('jnSend') : $('jnVerify')).click(); });
|
||||
$('jnCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('jnVerify').click(); });
|
||||
|
||||
// sponsor line (the link opened most recently sets the sponsor; it locks at account creation)
|
||||
let sponsorName = '';
|
||||
const linkTok = (location.pathname.match(/^\/join\/([^/?#]+)/) || [])[1] || '';
|
||||
fetch('/api/sponsor' + (linkTok ? '?ref=' + encodeURIComponent(linkTok) : '')).then(r => r.json()).then(sp => {
|
||||
if (sp && sp.invited && sp.name) {
|
||||
sponsorName = sp.name;
|
||||
$('jnSponName').textContent = sp.name + (sp.own ? ' (this is your own invite page; visitors see your name here)' : '');
|
||||
if (sp.avatarUrl) { $('jnSponImg').src = sp.avatarUrl; $('jnSponImg').hidden = false; }
|
||||
if (sp.cobrand && sp.bio && $('jnSponBio')) { $('jnSponBio').textContent = sp.bio; $('jnSponBio').hidden = false; $('jnSpon').classList.add('cobrand'); }
|
||||
$('jnSpon').hidden = false;
|
||||
}
|
||||
}).catch(() => {});
|
||||
// package ladder (dollar constants + live POL quote)
|
||||
const NAMES = { 1: 'Micro', 2: 'Activation', 3: 'Builder', 4: 'Growth', 5: 'Leader' };
|
||||
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 =>
|
||||
'<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(() => {});
|
||||
fetch('/api/stats').then(r => r.json()).then(s => {
|
||||
if (s && s.onchainMembers) $('jnStats').textContent = s.onchainMembers.toLocaleString() + (s.onchainMembers === 1 ? ' member' : ' members') + ' on-chain so far.';
|
||||
}).catch(() => {});
|
||||
})();
|
||||
// Invite / lead-capture page: /join/<token>[?v=<angle>]
|
||||
// Email first (code sign-in creates the account), wallet later inside the
|
||||
// member area. The angle only changes the hook copy; the sponsor cookie was
|
||||
// set by the server when this page was served.
|
||||
(function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
const LEG = (brand, seg) => seg === 'adv'
|
||||
? { eyebrow: 'For former ' + brand + ' advertisers', h: 'Your next ad budget <em>pays you back.</em>',
|
||||
lead: brand + ' is closed. The people who bought ads there are exactly who InstantAdPay was built for: real ad packages from $5, seven formats, and every package in your line paid out by a verified contract on Polygon in the same transaction.',
|
||||
points: ['Welcome-back credits land the moment your account exists: enough to run a real banner or text campaign today, on us.', 'Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits. Views are timed on the server, so a real person saw your ad.', 'When anyone in your line buys ads, the contract pays you in that same transaction. Public on Polygonscan, nothing held, nothing to withdraw.'],
|
||||
cta: 'Claim your welcome-back credits', sub: 'Free account by email. No password, no wallet today. Use the email you had on ' + brand + ': the credits are tied to it.', video: false }
|
||||
: { eyebrow: 'For former ' + brand + ' members', h: 'Same daily habit. <em>Real payouts on-chain.</em>',
|
||||
lead: 'You viewed ads on ' + brand + '. Here you view ads to earn credits, run your own campaign with them for free, and when anyone in your line buys ads you are paid in POL to your own wallet in the same transaction.',
|
||||
points: ['Welcome-back credits on day one, so your first campaign runs before you have viewed a single ad.', 'Join with just an email. No password, no wallet today. Link a wallet later, only when you want payouts switched on.', 'Every payout is a public transaction on Polygon. Nothing is held, so there is nothing to withdraw and nothing to wait for.'],
|
||||
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.' },
|
||||
adspend: { eyebrow: 'For marketers who buy traffic', h: 'You were buying <em>ads anyway.</em>', lead: 'Every ad dollar you ever spent went one direction: out. Here the ad spend in your line pays you, in the same transaction, on a public ledger. Seven formats, dwell-timed views, packages from $5.',
|
||||
points: ['Seven formats: banners, text ads, login ads, solo ads to member inboxes, video, featured links and verified visits.', 'Views are timed on the server, so a real person saw your ad. Banners and text also run across a partner ad network.', 'When anyone in your line buys ads, the contract pays you in that same transaction.'],
|
||||
cta: 'Put your next ad dollar where it pays you back', sub: 'Free account by email. See every format and the live rates before you buy anything.' },
|
||||
free: { eyebrow: 'Costs nothing to try', h: 'Watch first. <em>Spend never.</em>', lead: 'Join free, view a few ads, earn credits, and run your first campaign for zero dollars. Upgrade only if you want more reach.',
|
||||
points: ['Join with just an email. No password, no wallet today.', 'View a few ads each day and earn credits you can spend on your own banner or text campaign.', 'Buy a package only if you want more reach. They start at $5, and every payout on them is public.'],
|
||||
cta: 'Start for free. No card, no wallet.', sub: 'Type your email and we send a 6-digit code. That is the whole signup.' },
|
||||
ledger: { eyebrow: 'No back office', h: 'No back office. <em>No payday.</em>', lead: 'Your last program paid you on the 15th, if it paid you. Here every payout is a public transaction on Polygon you can read yourself, and nothing is ever held.',
|
||||
points: ['Every payout is a public transaction on Polygon. Click it, read it, verify it yourself.', 'The contract holds zero balance. It splits and sends in the same transaction, with no pause switch and no upgrade path.', 'No back office means nobody can delay, reverse or review your commission.'],
|
||||
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.' },
|
||||
// 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.
|
||||
const who = String(new URLSearchParams(location.search).get('name') || '').replace(/[^A-Za-z\u00C0-\u024F' -]/g, '').trim().slice(0, 30);
|
||||
if (who) {
|
||||
const top = /^\/join\/(company|top)$/i.test(location.pathname);
|
||||
const h = $('jnHello');
|
||||
if (h) { h.textContent = who + (top ? ', your spot directly under the company at the top is reserved for you. Activate with the $20 package to claim it.' : ', this invitation is for you.'); h.hidden = false; }
|
||||
}
|
||||
const v = new URLSearchParams(location.search).get('v') || (document.cookie.match(/(?:^|; )iap\.angle=([^;]+)/) || [])[1] || '';
|
||||
const a = v && ANGLES[v];
|
||||
if (a) {
|
||||
document.body.classList.add('squeeze'); // server sets it too; this covers cached HTML
|
||||
$('jnEyebrow').textContent = '· ' + a.eyebrow; $('jnHead').innerHTML = a.h; $('jnLead').textContent = a.lead;
|
||||
if (a.cta) { $('jnCapH').textContent = a.cta; $('jnCapSub').textContent = a.sub || ''; }
|
||||
// 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 {
|
||||
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) {
|
||||
const r = await (await fetch(path, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) })).json();
|
||||
if (r.error) throw new Error(r.error);
|
||||
return r;
|
||||
}
|
||||
const err = m => { const e = $('jnErr'); e.textContent = m || ''; e.hidden = !m; };
|
||||
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'), ref: linkTok, angle: v || '' }); // 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;
|
||||
if (r.devCode) $('jnCode').value = r.devCode;
|
||||
// the last thing they see before the account is created: who they are joining under
|
||||
if (sponsorName) { $('jnUnder').textContent = 'Joining under ' + sponsorName + '. Not who invited you? Open their invite link first, then come back for the code.'; $('jnUnder').hidden = false; }
|
||||
IAP.status(r.sent ? 'Code sent. Check your inbox (and spam, the first time).' : 'Dev mode: code filled in.', 'ok');
|
||||
$('jnCode').focus();
|
||||
});
|
||||
// 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, ref: linkTok });
|
||||
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
|
||||
}));
|
||||
$('jnEmail').addEventListener('keydown', e => { if (e.key === 'Enter') ($('jnVerify').hidden ? $('jnSend') : $('jnVerify')).click(); });
|
||||
$('jnCode').addEventListener('keydown', e => { if (e.key === 'Enter') $('jnVerify').click(); });
|
||||
|
||||
// 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;
|
||||
$('jnSponName').textContent = sp.name + (sp.own ? ' (this is your own invite page; visitors see your name here)' : '');
|
||||
if (sp.avatarUrl) { $('jnSponImg').src = sp.avatarUrl; $('jnSponImg').hidden = false; }
|
||||
if (sp.cobrand && sp.bio && $('jnSponBio')) { $('jnSponBio').textContent = sp.bio; $('jnSponBio').hidden = false; $('jnSpon').classList.add('cobrand'); }
|
||||
$('jnSpon').hidden = false;
|
||||
}
|
||||
}).catch(() => {});
|
||||
// package ladder (dollar constants + live POL quote)
|
||||
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).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(() => {});
|
||||
fetch('/api/stats').then(r => r.json()).then(s => {
|
||||
if (s && s.onchainMembers) $('jnStats').textContent = s.onchainMembers.toLocaleString() + (s.onchainMembers === 1 ? ' member' : ' members') + ' on-chain so far.';
|
||||
}).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,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
|
||||
})();
|
||||
@@ -1,289 +1,427 @@
|
||||
// Promo tools content + rendering for the member area (Promo tools pane).
|
||||
// Everything is personalized from the member's join link. Angle links carry
|
||||
// ?v=<angle> so they keep working when the matched squeeze pages ship.
|
||||
// Copy rules: no income promises, package prices in dollars are fine, never a
|
||||
// POL figure, no em dashes.
|
||||
window.IAPPromo = (function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
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 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');
|
||||
|
||||
// ── social posts ──
|
||||
const POSTS = [
|
||||
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: any ad package from $5 up earns 20% bonus credits, every Friday, Central time. The pack pays the sponsor line in the same transaction, on a public ledger. Free to join: {{FRIDAY}}' },
|
||||
{ net: 'Facebook', label: 'Facebook · Five Dollar Friday', text: 'Every Friday I point people at this. Any ad package from $5 up gets 20% extra credits on InstantAdPay, added the second the purchase settles, no code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction, so there is no pending anything. It runs midnight to midnight Central. Free to join by email: {{FRIDAY}}' },
|
||||
{ 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 · 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: '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}}' }
|
||||
];
|
||||
|
||||
// ── 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: '', 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}}' },
|
||||
{ angle: 'free', title: '"Costs nothing to try"', text: 'Try this without spending a dollar: join free, view a few ads, earn credits, run your first campaign. {{LINK:free}}' },
|
||||
{ angle: 'ledger', title: '"No back office"', text: 'Remember waiting on payouts that never came? This one has no back office. Every payment is public on the blockchain. Check it yourself: {{LINK:ledger}}' }
|
||||
];
|
||||
|
||||
// ── 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: '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: '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.' }
|
||||
];
|
||||
|
||||
// ── objection bank (truth + say this) ──
|
||||
const OBJECTIONS = [
|
||||
{ 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: '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}}' },
|
||||
{ q: 'I do not know anyone to refer.', truth: 'Referrals are optional. Members can view ads, earn credits and advertise with no line at all. When they do refer, every direct buyer pays them 50 percent from the very first package, and their line banner is shown to their next three levels during welcome tours.', say: 'You do not have to refer anyone. Join free, earn credits by viewing, run ads. If one person ever joins through you and buys a $5 package, half of it hits your wallet in that transaction. That is the whole referral side, and it is optional. {{LINK:free}}' },
|
||||
{ q: 'How much can I make?', truth: 'No income is guaranteed or implied. Sponsor commissions are 50 / 20 / 10 across three levels on packages that actually sell; level 2 needs 2 qualifying buyers ($20 or more) and level 3 needs 5. Results depend on the member\'s effort, and crypto carries risk of loss. Never quote a figure.', say: 'Nobody can tell you that, and I would not trust anyone who did. What I can tell you is exactly how it is split: 50 percent to the direct sponsor, 20 and 10 to the next two levels, paid the moment a package sells, all public. What that adds up to depends entirely on what you build. {{LINK:instant}}' }
|
||||
];
|
||||
|
||||
function fillLink(text, link) {
|
||||
return text.replace(/\{\{FRIDAY\}\}/g, fridayLink(link)).replace(/\{\{LINK(?::([a-z]+))?\}\}/g, (m, a) => angleLink(link, a));
|
||||
}
|
||||
function copyBtn(text, label) {
|
||||
const b = document.createElement('button');
|
||||
b.className = 'btn small sec'; b.type = 'button'; b.textContent = label || 'Copy';
|
||||
b.addEventListener('click', async () => {
|
||||
try { await navigator.clipboard.writeText(text); status('Copied. Paste it anywhere.', 'ok'); }
|
||||
catch (e) { status('Copy failed. Select the text instead.', 'bad'); }
|
||||
});
|
||||
return b;
|
||||
}
|
||||
function block(text, head, extraBtns) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'promo-block';
|
||||
if (head) { const h = document.createElement('div'); h.className = 'pb-head'; h.innerHTML = head; div.appendChild(h); }
|
||||
const pre = document.createElement('div'); pre.className = 'pb-text'; pre.textContent = text; div.appendChild(pre);
|
||||
const row = document.createElement('div'); row.className = 'pb-actions';
|
||||
row.appendChild(copyBtn(text));
|
||||
(extraBtns || []).forEach(b => row.appendChild(b));
|
||||
div.appendChild(row);
|
||||
return div;
|
||||
}
|
||||
function linkBtn(href, label, cls) {
|
||||
const a = document.createElement('a');
|
||||
a.className = 'btn small ' + (cls || 'sec'); a.href = href; a.textContent = label;
|
||||
if (!/^sms:/.test(href)) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||
return a;
|
||||
}
|
||||
|
||||
// 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: '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}}' },
|
||||
{ angle: 'ledger', title: 'No back office. No payday.', hook: 'Your last affiliate program paid you on the fifteenth. If it paid you.', caption: 'Your last affiliate program paid you on the fifteenth. If it paid you. Here the payroll is the blockchain: every payout is a public transaction, nothing is held, nobody can change the split. Open the ledger, then join free: {{LINK:ledger}}' },
|
||||
{ angle: 'two', title: 'Two buyers open level two', hook: 'Two buyers. Then five. That is the whole ladder.', caption: 'Two buyers. Then five. That is the whole ladder. Level 1 pays from your first buyer, two qualifying buyers open level 2, five open level 3, all in the same transaction, straight to your wallet. Free to join: {{LINK:two}}' }
|
||||
];
|
||||
// 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: '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: '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) {
|
||||
const token = (me && (me.username || me.refCode || me.memberId)) || '';
|
||||
// invite strip
|
||||
if ($('promoLink')) $('promoLink').textContent = link;
|
||||
if ($('promoLinkCopy')) $('promoLinkCopy').onclick = async () => {
|
||||
try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); }
|
||||
};
|
||||
// angle links: one row per front door, copy + share
|
||||
const al = $('promoAngles');
|
||||
if (al && al.dataset.filled !== link) {
|
||||
al.dataset.filled = link; al.innerHTML = '';
|
||||
for (const a of ANGLES) {
|
||||
const url = angleLink(link, a.angle);
|
||||
const hasVideo = VIDEOS.some(v => v.angle === a.angle);
|
||||
// one collapsed band per angle, like the banner kit: open the one you want
|
||||
const row = document.createElement('details');
|
||||
row.className = 'angle-row pb-acc';
|
||||
row.innerHTML = '<summary><span><span class="angle-name">' + esc(a.name) + '</span> <span class="angle-hook">' + esc(a.hook) + '</span></span>'
|
||||
+ (hasVideo ? '<span class="angle-tag">video</span>' : '') + '</summary>'
|
||||
+ '<div class="angle-body"><div class="angle-txt">'
|
||||
+ '<div class="muted small">' + esc(a.use) + '</div>'
|
||||
+ '<a class="mono small angle-url" href="' + esc(url) + '" target="_blank" rel="noopener">' + esc(url) + '</a></div>'
|
||||
+ '<div class="angle-btns"><a class="btn small sec" href="' + esc(url) + '" target="_blank" rel="noopener">Open</a><button class="btn small" type="button">Copy</button>'
|
||||
+ (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'); } };
|
||||
al.appendChild(row);
|
||||
}
|
||||
}
|
||||
// posts
|
||||
const posts = $('promoPosts');
|
||||
if (posts && posts.dataset.filled !== link) {
|
||||
posts.dataset.filled = link; posts.innerHTML = '';
|
||||
for (const p of POSTS) {
|
||||
const text = fillLink(p.text, link);
|
||||
const extras = [];
|
||||
if (p.net === 'X') extras.push(linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), 'Post on X'));
|
||||
if (p.net === 'Facebook') extras.push(linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')), 'Share on Facebook'));
|
||||
if (p.net === 'LinkedIn') extras.push(linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(angleLink(link, 'adspend')), 'Share on LinkedIn'));
|
||||
if (p.net === 'Telegram') extras.push(linkBtn('https://t.me/share/url?url=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')) + '&text=' + encodeURIComponent(text.replace(/\s*\{\{LINK[^}]*\}\}\s*$/, '').replace(/https?:\/\/\S+$/, '').trim()), 'Share on Telegram'));
|
||||
posts.appendChild(block(text, '<span class="pb-net">' + esc(p.label) + '</span>', extras));
|
||||
}
|
||||
}
|
||||
// text a friend
|
||||
const texts = $('promoTexts');
|
||||
if (texts && texts.dataset.filled !== link) {
|
||||
texts.dataset.filled = link; texts.innerHTML = '';
|
||||
TEXTS.forEach((t, i) => {
|
||||
const text = fillLink(t.text, link);
|
||||
const enc = encodeURIComponent(text);
|
||||
const tgUrl = angleLink(link, t.angle);
|
||||
const tgLead = text.replace(/https?:\/\/\S+/, '').trim();
|
||||
const extras = [
|
||||
linkBtn('sms:?&body=' + enc, 'Text it', ''),
|
||||
linkBtn('https://wa.me/?text=' + enc, 'WhatsApp'),
|
||||
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(tgUrl) + '&text=' + encodeURIComponent(tgLead), 'Telegram')
|
||||
];
|
||||
texts.appendChild(block(text, '<span class="pb-net">Text ' + (i + 1) + (t.angle ? ' · ' + esc(t.angle) + ' angle' : ' · general') + '</span> <b>' + esc(t.title) + '</b>', extras));
|
||||
});
|
||||
}
|
||||
// swipes
|
||||
const sw = $('promoSwipeWrap');
|
||||
if (sw && sw.dataset.filled !== link) {
|
||||
sw.dataset.filled = link; sw.innerHTML = '';
|
||||
for (const s of SWIPES) {
|
||||
const text = 'Subject: ' + s.subject + '\n\n' + fillLink(s.body, link);
|
||||
sw.appendChild(block(text, '<span class="pb-net">' + esc(s.tier) + '</span> <b>' + esc(s.subject) + '</b>'));
|
||||
}
|
||||
}
|
||||
// hook videos
|
||||
const vw = $('promoVideos');
|
||||
if (vw && vw.dataset.filled !== link) {
|
||||
vw.dataset.filled = link; vw.innerHTML = '';
|
||||
for (const v of VIDEOS) {
|
||||
const mlink = 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>'
|
||||
+ '<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'));
|
||||
card.appendChild(row);
|
||||
const cap = fillLink(v.caption, link);
|
||||
const extras = [
|
||||
linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(cap), 'Post on X'),
|
||||
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(mlink), 'Share on Facebook'),
|
||||
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(mlink) + '&text=' + encodeURIComponent(cap.replace(/https?:\/\/\S+$/, '').trim()), 'Telegram'),
|
||||
linkBtn('https://wa.me/?text=' + encodeURIComponent(cap), 'WhatsApp')
|
||||
];
|
||||
card.appendChild(block(cap, '<span class="lab">Caption</span>', extras));
|
||||
vw.appendChild(card);
|
||||
}
|
||||
}
|
||||
// viral link builder: any page on the site + ?ref=<you> (same cookie as the invite link)
|
||||
const vp = $('viralPage');
|
||||
if (vp && token && vp.dataset.filled !== token) {
|
||||
vp.dataset.filled = token;
|
||||
const origin = 'https://instantadpay.com', enc = encodeURIComponent;
|
||||
const build = path => { if (!path) return ''; let x; try { x = new URL(origin + path); } catch (e) { return ''; } x.searchParams.set('ref', token); return origin + x.pathname + x.search; };
|
||||
const render = () => {
|
||||
const l = build(vp.value);
|
||||
$('viralLink').textContent = l || '…';
|
||||
const sh = $('viralShare'); sh.innerHTML = '';
|
||||
if (!l) return;
|
||||
const title = vp.selectedOptions[0] ? vp.selectedOptions[0].textContent.replace(/^Article: /, '') : 'InstantAdPay';
|
||||
[linkBtn('https://x.com/intent/tweet?url=' + enc(l) + '&text=' + enc(title), 'X'),
|
||||
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(l), 'Facebook'),
|
||||
linkBtn('https://t.me/share/url?url=' + enc(l) + '&text=' + enc(title), 'Telegram'),
|
||||
linkBtn('https://wa.me/?text=' + enc(title + ' ' + l), 'WhatsApp'),
|
||||
linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + enc(l), 'LinkedIn'),
|
||||
linkBtn('mailto:?subject=' + enc(title) + '&body=' + enc(l), 'Email')].forEach(b => sh.appendChild(b));
|
||||
if (navigator.share) { const b = document.createElement('button'); b.className = 'btn small sec'; b.type = 'button'; b.textContent = 'Share'; b.onclick = async () => { try { await navigator.share({ title, url: l }); } catch (e) {} }; sh.appendChild(b); }
|
||||
};
|
||||
fetch('/api/pages').then(r => r.json()).then(r => { vp.innerHTML = (r.pages || []).map(pg => '<option value="' + esc(pg.path) + '">' + esc(pg.title) + '</option>').join(''); render(); }).catch(() => { vp.innerHTML = '<option value="/">Home page</option>'; render(); });
|
||||
vp.onchange = render;
|
||||
$('viralCopy').onclick = async () => { const l = $('viralLink').textContent; if (!/^https:/.test(l)) return; try { await navigator.clipboard.writeText(l); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
}
|
||||
// PolHunter, the feeder program: the member's PolHunter link (their IAP username, so sign-ups land on their line)
|
||||
const phl = $('phLink');
|
||||
if (phl && token && phl.dataset.filled !== token) {
|
||||
phl.dataset.filled = token;
|
||||
const enc = encodeURIComponent, pl = 'https://polhunter.com/?r=' + enc(token);
|
||||
phl.textContent = pl;
|
||||
$('phLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const sh = $('phShare'); sh.innerHTML = '';
|
||||
const hook = 'PolHunter: find a code on one of our sites and a drip of POL lands in your wallet, on chain. Free to start.';
|
||||
[linkBtn('https://x.com/intent/tweet?url=' + enc(pl) + '&text=' + enc(hook), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(hook + ' ' + pl), 'WhatsApp'), linkBtn('mailto:?subject=' + enc('A scavenger hunt that pays in POL') + '&body=' + enc(hook + '\n\n' + pl), 'Email')].forEach(b => sh.appendChild(b));
|
||||
const PH_POSTS = [
|
||||
{ name: 'Short post', text: 'New thing I am playing with: PolHunter. You visit a site, find your code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in your wallet. On chain, with a link to prove it. ' + pl },
|
||||
{ name: 'Story post', text: 'I spent two minutes on a training page tonight, found a little glass coin at the bottom, tapped the code, and 0.26 POL showed up in my wallet a minute later. That is PolHunter. Small drips, real chain, no catch beyond actually visiting the site. Free to start, you just need an InstantAdPay account and a wallet. ' + pl },
|
||||
{ name: 'Telegram or WhatsApp', text: '\u{1F3AF} PolHunter is live. Missions across our sites, one code to find per site, random POL drips paid straight to your wallet. The hiding place moves every day. Start here: ' + pl },
|
||||
{ name: 'Email swipe', subject: 'A scavenger hunt that pays in POL', text: 'Hey,\n\nQuick one. I have been testing something called PolHunter.\n\nYou pick a mission, spend a couple of minutes on the site it names, and your personal code appears somewhere on the page. Tap it to copy, paste it on your board, and a random drip of POL goes to your wallet, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly prizes, and the hiding place moves every day.\n\nIt is free to start. You need an InstantAdPay account (also free) and a wallet, and the site walks you through both.\n\nStart here: ' + pl + '\n\nTell me what your first find pays.' },
|
||||
];
|
||||
// the two spots (photoreal / animated): player, download, caption with the member's link, share buttons
|
||||
const SP = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
|
||||
const SPOTS = [
|
||||
{ id: 'photoreal', name: 'Photoreal: the hunt in the forest', file: 'polhunter-spot-photoreal.mp4', poster: 'polhunter-spot-photoreal-poster.jpg', best: 'Facebook, YouTube Shorts, an older audience', cap: 'Somewhere on one of our sites, a code is waiting. Find it, tap it, paste it on your board, and a drip of Polygon lands in your wallet. On chain, with a link to prove it. Free to play. Start here: ' + pl + ' #PolHunter #Polygon #crypto #scavengerhunt' },
|
||||
{ id: 'animated', name: 'Animated: the explorer and the glass coin', file: 'polhunter-spot-animated.mp4', poster: 'polhunter-spot-animated-poster.jpg', best: 'TikTok, Instagram Reels, a younger crowd', cap: 'A scavenger hunt that pays in Polygon. Pick a mission, find the glass coin, tap it, and the drip lands in your wallet instantly. Three missions a day, badges, weekly prizes. 100% free. ' + pl + ' #PolHunter #Polygon #crypto #gaming' },
|
||||
];
|
||||
const ps = $('phSpots'); if (ps) { ps.innerHTML = '';
|
||||
for (const s of SPOTS) { const d = document.createElement('div'); d.className = 'promo-block';
|
||||
d.innerHTML = '<div class="pb-head"><span class="lab">' + esc(s.name) + '</span> <span class="muted small">Best on: ' + esc(s.best) + '</span></div><video controls playsinline preload="none" poster="' + SP + s.poster + '" src="' + SP + s.file + '" style="width:100%;max-width:300px;border-radius:12px;display:block;margin:8px auto"></video><div class="pb-text">' + esc(s.cap) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions';
|
||||
row.appendChild(linkBtn(SP + s.file, 'Download the video')); row.appendChild(copyBtn(s.cap, 'Copy caption'));
|
||||
[linkBtn('https://x.com/intent/tweet?text=' + enc(s.cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(s.cap.replace(pl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(s.cap), 'WhatsApp')].forEach(b => row.appendChild(b));
|
||||
d.appendChild(row); ps.appendChild(d); }
|
||||
}
|
||||
const pp = $('phPosts'); pp.innerHTML = '';
|
||||
for (const p of PH_POSTS) { const extras = p.subject ? [] : [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(p.text.replace(pl, '').trim()), 'Telegram')]; pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>' + (p.subject ? ' <span class="muted small">Subject: ' + esc(p.subject) + '</span>' : ''), extras)); }
|
||||
const sizes = [['728x90', 'Leaderboard'], ['468x60', 'Mobile leaderboard'], ['300x250', 'Medium rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Skyscraper'], ['1200x630', 'Social card'], ['1080x1080', 'Instagram square']];
|
||||
const bg = $('phBanners'); bg.innerHTML = '';
|
||||
for (const [s, n] of sizes) { const w = s.split('x')[0], h = s.split('x')[1]; const src = 'https://polhunter.com/promo/polhunter-' + s + (Number(w) >= 300 ? '.jpg' : '.png'); const code = '<a href="' + pl + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="PolHunter"></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 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); }
|
||||
}
|
||||
// objections
|
||||
const ob = $('promoObjections');
|
||||
if (ob && ob.dataset.filled !== link) {
|
||||
ob.dataset.filled = link; ob.innerHTML = '';
|
||||
for (const o of OBJECTIONS) {
|
||||
const d = document.createElement('details'); d.className = 'obj';
|
||||
const s = document.createElement('summary'); s.textContent = o.q; d.appendChild(s);
|
||||
const body = document.createElement('div'); body.className = 'obj-body';
|
||||
const t = document.createElement('div'); t.className = 'obj-truth';
|
||||
t.innerHTML = '<span class="lab">The truth</span><p>' + esc(o.truth) + '</p>'; body.appendChild(t);
|
||||
const say = fillLink(o.say, link);
|
||||
const sayEl = block(say, '<span class="lab lab-say">Say this</span>');
|
||||
sayEl.classList.add('obj-say'); body.appendChild(sayEl);
|
||||
d.appendChild(body); ob.appendChild(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { fill, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS };
|
||||
})();
|
||||
// Promo tools content + rendering for the member area (Promo tools pane).
|
||||
// Everything is personalized from the member's join link. Angle links carry
|
||||
// ?v=<angle> so they keep working when the matched squeeze pages ship.
|
||||
// Copy rules: no income promises, package prices in dollars are fine, never a
|
||||
// POL figure, no em dashes.
|
||||
window.IAPPromo = (function () {
|
||||
const $ = id => document.getElementById(id);
|
||||
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 = [
|
||||
{ net: 'X', label: 'X · Five Dollar Friday', text: 'Five Dollar Friday on InstantAdPay: any ad package from $5 up earns 20% bonus credits, every Friday, Central time. The pack pays the sponsor line in the same transaction, on a public ledger. Free to join: {{FRIDAY}}' },
|
||||
{ net: 'Facebook', label: 'Facebook · Five Dollar Friday', text: 'Every Friday I point people at this. Any ad package from $5 up gets 20% extra credits on InstantAdPay, added the second the purchase settles, no code, nothing to claim. And every pack pays the sponsor line in the same blockchain transaction, so there is no pending anything. It runs midnight to midnight Central. Free to join by email: {{FRIDAY}}' },
|
||||
{ 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 $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}}' }
|
||||
];
|
||||
|
||||
// ── 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}}' },
|
||||
{ angle: 'free', title: '"Costs nothing to try"', text: 'Try this without spending a dollar: join free, view a few ads, earn credits, run your first campaign. {{LINK:free}}' },
|
||||
{ angle: 'ledger', title: '"No back office"', text: 'Remember waiting on payouts that never came? This one has no back office. Every payment is public on the blockchain. Check it yourself: {{LINK:ledger}}' }
|
||||
];
|
||||
|
||||
// ── 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 $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.' }
|
||||
];
|
||||
|
||||
// ── objection bank (truth + say this) ──
|
||||
const OBJECTIONS = [
|
||||
{ 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, $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}}' },
|
||||
{ q: 'I do not know anyone to refer.', truth: 'Referrals are optional. Members can view ads, earn credits and advertise with no line at all. When they do refer, every direct buyer pays them 50 percent from the very first package, and their line banner is shown to their next three levels during welcome tours.', say: 'You do not have to refer anyone. Join free, earn credits by viewing, run ads. If one person ever joins through you and buys a $5 package, half of it hits your wallet in that transaction. That is the whole referral side, and it is optional. {{LINK:free}}' },
|
||||
{ q: 'How much can I make?', truth: 'No income is guaranteed or implied. Sponsor commissions are 50 / 20 / 10 across three levels on packages that actually sell; level 2 needs 2 qualifying buyers ($20 or more) and level 3 needs 5. Results depend on the member\'s effort, and crypto carries risk of loss. Never quote a figure.', say: 'Nobody can tell you that, and I would not trust anyone who did. What I can tell you is exactly how it is split: 50 percent to the direct sponsor, 20 and 10 to the next two levels, paid the moment a package sells, all public. What that adds up to depends entirely on what you build. {{LINK:instant}}' }
|
||||
];
|
||||
|
||||
function fillLink(text, link) {
|
||||
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');
|
||||
b.className = 'btn small sec'; b.type = 'button'; b.textContent = label || 'Copy';
|
||||
b.addEventListener('click', async () => {
|
||||
try { await navigator.clipboard.writeText(text); status('Copied. Paste it anywhere.', 'ok'); }
|
||||
catch (e) { status('Copy failed. Select the text instead.', 'bad'); }
|
||||
});
|
||||
return b;
|
||||
}
|
||||
function block(text, head, extraBtns) {
|
||||
const div = document.createElement('div');
|
||||
div.className = 'promo-block';
|
||||
if (head) { const h = document.createElement('div'); h.className = 'pb-head'; h.innerHTML = head; div.appendChild(h); }
|
||||
const pre = document.createElement('div'); pre.className = 'pb-text'; pre.textContent = text; div.appendChild(pre);
|
||||
const row = document.createElement('div'); row.className = 'pb-actions';
|
||||
row.appendChild(copyBtn(text));
|
||||
(extraBtns || []).forEach(b => row.appendChild(b));
|
||||
div.appendChild(row);
|
||||
return div;
|
||||
}
|
||||
function linkBtn(href, label, cls) {
|
||||
const a = document.createElement('a');
|
||||
a.className = 'btn small ' + (cls || 'sec'); a.href = href; a.textContent = label;
|
||||
if (!/^sms:/.test(href)) { a.target = '_blank'; a.rel = 'noopener'; }
|
||||
return a;
|
||||
}
|
||||
|
||||
// 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}}' },
|
||||
{ angle: 'ledger', title: 'No back office. No payday.', hook: 'Your last affiliate program paid you on the fifteenth. If it paid you.', caption: 'Your last affiliate program paid you on the fifteenth. If it paid you. Here the payroll is the blockchain: every payout is a public transaction, nothing is held, nobody can change the split. Open the ledger, then join free: {{LINK:ledger}}' },
|
||||
{ angle: 'two', title: 'Two buyers open level two', hook: 'Two buyers. Then five. That is the whole ladder.', caption: 'Two buyers. Then five. That is the whole ladder. Level 1 pays from your first buyer, two qualifying buyers open level 2, five open level 3, all in the same transaction, straight to your wallet. Free to join: {{LINK:two}}' }
|
||||
];
|
||||
// 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) {
|
||||
const token = (me && (me.username || me.refCode || me.memberId)) || '';
|
||||
// invite strip
|
||||
if ($('promoLink')) $('promoLink').textContent = link;
|
||||
if ($('promoLinkCopy')) $('promoLinkCopy').onclick = async () => {
|
||||
try { await navigator.clipboard.writeText(link); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); }
|
||||
};
|
||||
// angle links: one row per front door, copy + share
|
||||
const al = $('promoAngles');
|
||||
if (al && al.dataset.filled !== link) {
|
||||
al.dataset.filled = link; al.innerHTML = '';
|
||||
for (const a of ANGLES) {
|
||||
const url = angleLink(link, a.angle);
|
||||
const hasVideo = VIDEOS.some(v => v.angle === a.angle);
|
||||
// one collapsed band per angle, like the banner kit: open the one you want
|
||||
const row = document.createElement('details');
|
||||
row.className = 'angle-row pb-acc';
|
||||
row.innerHTML = '<summary><span><span class="angle-name">' + esc(a.name) + '</span> <span class="angle-hook">' + esc(a.hook) + '</span></span>'
|
||||
+ (hasVideo ? '<span class="angle-tag">video</span>' : '') + '</summary>'
|
||||
+ '<div class="angle-body"><div class="angle-txt">'
|
||||
+ '<div class="muted small">' + esc(a.use) + '</div>'
|
||||
+ '<a class="mono small angle-url" href="' + esc(url) + '" target="_blank" rel="noopener">' + esc(url) + '</a></div>'
|
||||
+ '<div class="angle-btns"><a class="btn small sec" href="' + esc(url) + '" target="_blank" rel="noopener">Open</a><button class="btn small" type="button">Copy</button>'
|
||||
+ (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'); } };
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
// posts
|
||||
const posts = $('promoPosts');
|
||||
if (posts && posts.dataset.filled !== link) {
|
||||
posts.dataset.filled = link; posts.innerHTML = '';
|
||||
for (const p of POSTS) {
|
||||
const text = fillLink(p.text, link);
|
||||
const extras = [];
|
||||
if (p.net === 'X') extras.push(linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(text), 'Post on X'));
|
||||
if (p.net === 'Facebook') extras.push(linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')), 'Share on Facebook'));
|
||||
if (p.net === 'LinkedIn') extras.push(linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + encodeURIComponent(angleLink(link, 'adspend')), 'Share on LinkedIn'));
|
||||
if (p.net === 'Telegram') extras.push(linkBtn('https://t.me/share/url?url=' + encodeURIComponent(angleLink(link, (/\{\{LINK:([a-z]+)\}\}/.exec(p.text) || [])[1] || '')) + '&text=' + encodeURIComponent(text.replace(/\s*\{\{LINK[^}]*\}\}\s*$/, '').replace(/https?:\/\/\S+$/, '').trim()), 'Share on Telegram'));
|
||||
posts.appendChild(block(text, '<span class="pb-net">' + esc(p.label) + '</span>', extras));
|
||||
}
|
||||
}
|
||||
// text a friend
|
||||
const texts = $('promoTexts');
|
||||
if (texts && texts.dataset.filled !== link) {
|
||||
texts.dataset.filled = link; texts.innerHTML = '';
|
||||
TEXTS.forEach((t, i) => {
|
||||
const text = fillLink(t.text, link);
|
||||
const enc = encodeURIComponent(text);
|
||||
const tgUrl = angleLink(link, t.angle);
|
||||
const tgLead = text.replace(/https?:\/\/\S+/, '').trim();
|
||||
const extras = [
|
||||
linkBtn('sms:?&body=' + enc, 'Text it', ''),
|
||||
linkBtn('https://wa.me/?text=' + enc, 'WhatsApp'),
|
||||
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(tgUrl) + '&text=' + encodeURIComponent(tgLead), 'Telegram')
|
||||
];
|
||||
texts.appendChild(block(text, '<span class="pb-net">Text ' + (i + 1) + (t.angle ? ' · ' + esc(t.angle) + ' angle' : ' · general') + '</span> <b>' + esc(t.title) + '</b>', extras));
|
||||
});
|
||||
}
|
||||
// swipes
|
||||
const sw = $('promoSwipeWrap');
|
||||
if (sw && sw.dataset.filled !== link) {
|
||||
sw.dataset.filled = link; sw.innerHTML = '';
|
||||
for (const s of SWIPES) {
|
||||
const text = 'Subject: ' + s.subject + '\n\n' + fillLink(s.body, link);
|
||||
sw.appendChild(block(text, '<span class="pb-net">' + esc(s.tier) + '</span> <b>' + esc(s.subject) + '</b>'));
|
||||
}
|
||||
}
|
||||
// hook videos
|
||||
const vw = $('promoVideos');
|
||||
if (vw && vw.dataset.filled !== link) {
|
||||
vw.dataset.filled = link; vw.innerHTML = '';
|
||||
for (const v of VIDEOS) {
|
||||
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.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.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 = [
|
||||
linkBtn('https://twitter.com/intent/tweet?text=' + encodeURIComponent(cap), 'Post on X'),
|
||||
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + encodeURIComponent(mlink), 'Share on Facebook'),
|
||||
linkBtn('https://t.me/share/url?url=' + encodeURIComponent(mlink) + '&text=' + encodeURIComponent(cap.replace(/https?:\/\/\S+$/, '').trim()), 'Telegram'),
|
||||
linkBtn('https://wa.me/?text=' + encodeURIComponent(cap), 'WhatsApp')
|
||||
];
|
||||
card.appendChild(block(cap, '<span class="lab">Caption</span>', extras));
|
||||
vw.appendChild(card);
|
||||
}
|
||||
}
|
||||
// viral link builder: any page on the site + ?ref=<you> (same cookie as the invite link)
|
||||
const vp = $('viralPage');
|
||||
if (vp && token && vp.dataset.filled !== token) {
|
||||
vp.dataset.filled = token;
|
||||
const origin = 'https://instantadpay.com', enc = encodeURIComponent;
|
||||
const build = path => { if (!path) return ''; let x; try { x = new URL(origin + path); } catch (e) { return ''; } x.searchParams.set('ref', token); return origin + x.pathname + x.search; };
|
||||
const render = () => {
|
||||
const l = build(vp.value);
|
||||
$('viralLink').textContent = l || '…';
|
||||
const sh = $('viralShare'); sh.innerHTML = '';
|
||||
if (!l) return;
|
||||
const title = vp.selectedOptions[0] ? vp.selectedOptions[0].textContent.replace(/^Article: /, '') : 'InstantAdPay';
|
||||
[linkBtn('https://x.com/intent/tweet?url=' + enc(l) + '&text=' + enc(title), 'X'),
|
||||
linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(l), 'Facebook'),
|
||||
linkBtn('https://t.me/share/url?url=' + enc(l) + '&text=' + enc(title), 'Telegram'),
|
||||
linkBtn('https://wa.me/?text=' + enc(title + ' ' + l), 'WhatsApp'),
|
||||
linkBtn('https://www.linkedin.com/sharing/share-offsite/?url=' + enc(l), 'LinkedIn'),
|
||||
linkBtn('mailto:?subject=' + enc(title) + '&body=' + enc(l), 'Email')].forEach(b => sh.appendChild(b));
|
||||
if (navigator.share) { const b = document.createElement('button'); b.className = 'btn small sec'; b.type = 'button'; b.textContent = 'Share'; b.onclick = async () => { try { await navigator.share({ title, url: l }); } catch (e) {} }; sh.appendChild(b); }
|
||||
};
|
||||
fetch('/api/pages').then(r => r.json()).then(r => { vp.innerHTML = (r.pages || []).map(pg => '<option value="' + esc(pg.path) + '">' + esc(pg.title) + '</option>').join(''); render(); }).catch(() => { vp.innerHTML = '<option value="/">Home page</option>'; render(); });
|
||||
vp.onchange = render;
|
||||
$('viralCopy').onclick = async () => { const l = $('viralLink').textContent; if (!/^https:/.test(l)) return; try { await navigator.clipboard.writeText(l); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
}
|
||||
// PolHunter, the feeder program: the member's PolHunter link (their IAP username, so sign-ups land on their line)
|
||||
const phl = $('phLink');
|
||||
if (phl && token && phl.dataset.filled !== token) {
|
||||
phl.dataset.filled = token;
|
||||
const enc = encodeURIComponent, pl = 'https://polhunter.com/?r=' + enc(token);
|
||||
phl.textContent = pl;
|
||||
$('phLinkCopy').onclick = async () => { try { await navigator.clipboard.writeText(pl); status('Link copied.', 'ok'); } catch (e) { status('Copy failed.', 'bad'); } };
|
||||
const sh = $('phShare'); sh.innerHTML = '';
|
||||
const hook = 'PolHunter: find a code on one of our sites and a drip of POL lands in your wallet, on chain. Free to start.';
|
||||
[linkBtn('https://x.com/intent/tweet?url=' + enc(pl) + '&text=' + enc(hook), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(hook), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(hook + ' ' + pl), 'WhatsApp'), linkBtn('mailto:?subject=' + enc('A scavenger hunt that pays in POL') + '&body=' + enc(hook + '\n\n' + pl), 'Email')].forEach(b => sh.appendChild(b));
|
||||
const PH_POSTS = [
|
||||
{ name: 'Short post', text: 'New thing I am playing with: PolHunter. You visit a site, find your code on the page, tap it to copy, paste it on your board, and a random drip of POL lands in your wallet. On chain, with a link to prove it. ' + pl },
|
||||
{ name: 'Story post', text: 'I spent two minutes on a training page tonight, found a little glass coin at the bottom, tapped the code, and 0.26 POL showed up in my wallet a minute later. That is PolHunter. Small drips, real chain, no catch beyond actually visiting the site. Free to start, you just need an InstantAdPay account and a wallet. ' + pl },
|
||||
{ name: 'Telegram or WhatsApp', text: '\u{1F3AF} PolHunter is live. Missions across our sites, one code to find per site, random POL drips paid straight to your wallet. The hiding place moves every day. Start here: ' + pl },
|
||||
{ name: 'Email swipe', subject: 'A scavenger hunt that pays in POL', text: 'Hey,\n\nQuick one. I have been testing something called PolHunter.\n\nYou pick a mission, spend a couple of minutes on the site it names, and your personal code appears somewhere on the page. Tap it to copy, paste it on your board, and a random drip of POL goes to your wallet, on chain, with a link to prove it. Three missions a day, a leaderboard with weekly prizes, and the hiding place moves every day.\n\nIt is free to start. You need an InstantAdPay account (also free) and a wallet, and the site walks you through both.\n\nStart here: ' + pl + '\n\nTell me what your first find pays.' },
|
||||
];
|
||||
// the two spots (photoreal / animated): player, download, caption with the member's link, share buttons
|
||||
const SP = 'https://coolify-saasytop.nyc3.digitaloceanspaces.com/promo/';
|
||||
const SPOTS = [
|
||||
{ id: 'photoreal', name: 'Photoreal: the hunt in the forest', file: 'polhunter-spot-photoreal.mp4', poster: 'polhunter-spot-photoreal-poster.jpg', best: 'Facebook, YouTube Shorts, an older audience', cap: 'Somewhere on one of our sites, a code is waiting. Find it, tap it, paste it on your board, and a drip of Polygon lands in your wallet. On chain, with a link to prove it. Free to play. Start here: ' + pl + ' #PolHunter #Polygon #crypto #scavengerhunt' },
|
||||
{ id: 'animated', name: 'Animated: the explorer and the glass coin', file: 'polhunter-spot-animated.mp4', poster: 'polhunter-spot-animated-poster.jpg', best: 'TikTok, Instagram Reels, a younger crowd', cap: 'A scavenger hunt that pays in Polygon. Pick a mission, find the glass coin, tap it, and the drip lands in your wallet instantly. Three missions a day, badges, weekly prizes. 100% free. ' + pl + ' #PolHunter #Polygon #crypto #gaming' },
|
||||
];
|
||||
const ps = $('phSpots'); if (ps) { ps.innerHTML = '';
|
||||
for (const s of SPOTS) { const d = document.createElement('div'); d.className = 'promo-block';
|
||||
d.innerHTML = '<div class="pb-head"><span class="lab">' + esc(s.name) + '</span> <span class="muted small">Best on: ' + esc(s.best) + '</span></div><video controls playsinline preload="none" poster="' + SP + s.poster + '" src="' + SP + s.file + '" style="width:100%;max-width:300px;border-radius:12px;display:block;margin:8px auto"></video><div class="pb-text">' + esc(s.cap) + '</div>';
|
||||
const row = document.createElement('div'); row.className = 'pb-actions';
|
||||
row.appendChild(linkBtn(SP + s.file, 'Download the video')); row.appendChild(copyBtn(s.cap, 'Copy caption'));
|
||||
[linkBtn('https://x.com/intent/tweet?text=' + enc(s.cap), 'X'), linkBtn('https://www.facebook.com/sharer/sharer.php?u=' + enc(pl), 'Facebook'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(s.cap.replace(pl, '').trim()), 'Telegram'), linkBtn('https://wa.me/?text=' + enc(s.cap), 'WhatsApp')].forEach(b => row.appendChild(b));
|
||||
d.appendChild(row); ps.appendChild(d); }
|
||||
}
|
||||
const pp = $('phPosts'); pp.innerHTML = '';
|
||||
for (const p of PH_POSTS) { const extras = p.subject ? [] : [linkBtn('https://x.com/intent/tweet?text=' + enc(p.text), 'X'), linkBtn('https://t.me/share/url?url=' + enc(pl) + '&text=' + enc(p.text.replace(pl, '').trim()), 'Telegram')]; pp.appendChild(block(p.text, '<span class="lab">' + esc(p.name) + '</span>' + (p.subject ? ' <span class="muted small">Subject: ' + esc(p.subject) + '</span>' : ''), extras)); }
|
||||
const sizes = [['728x90', 'Leaderboard'], ['468x60', 'Mobile leaderboard'], ['300x250', 'Medium rectangle'], ['250x250', 'Square'], ['125x125', 'Button'], ['160x600', 'Skyscraper'], ['1200x630', 'Social card'], ['1080x1080', 'Instagram square']];
|
||||
const bg = $('phBanners'); bg.innerHTML = '';
|
||||
for (const [s, n] of sizes) { const w = s.split('x')[0], h = s.split('x')[1]; const src = 'https://polhunter.com/promo/polhunter-' + s + (Number(w) >= 300 ? '.jpg' : '.png'); const code = '<a href="' + pl + '" target="_blank" rel="noopener"><img src="' + src + '" width="' + w + '" height="' + h + '" alt="PolHunter"></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 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, CDN = 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/';
|
||||
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. 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. Eight games, all free, all paying POL on Polygon for first clears, levels and daily puzzles. Pick one: {L}' },
|
||||
{ name: 'Telegram or WhatsApp line', text: 'All the games that pay POL, one page, free to play: {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: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/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: 'https://coolify-saasytop.nyc3.cdn.digitaloceanspaces.com/game-banners/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 free fantasy match-3. Lead three heroes, beat the Goblin King’s bosses and rebuild your village. Boss wins come with 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: 'https://clutterhunt.com/og-clutterhunt.jpg', sub: 'seasonal hidden-object game',
|
||||
posts: [
|
||||
{ name: 'Short post', text: 'ClutterHunt is a free hidden-object game. Six rooms to search, a clock running, and everything moves each time you play. Can you three-star Expert? {L}' },
|
||||
{ name: 'Friendly post', text: 'If you like spot-the-object puzzles, try ClutterHunt. Free in your browser, with POL rewards for clearing rooms: {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 }; // 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 || '';
|
||||
$('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 + '/' + 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']) if ((d.games || []).some(g => g.slug === sl)) 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) {
|
||||
ob.dataset.filled = link; ob.innerHTML = '';
|
||||
for (const o of OBJECTIONS) {
|
||||
const d = document.createElement('details'); d.className = 'obj';
|
||||
const s = document.createElement('summary'); s.textContent = o.q; d.appendChild(s);
|
||||
const body = document.createElement('div'); body.className = 'obj-body';
|
||||
const t = document.createElement('div'); t.className = 'obj-truth';
|
||||
t.innerHTML = '<span class="lab">The truth</span><p>' + esc(o.truth) + '</p>'; body.appendChild(t);
|
||||
const say = fillLink(o.say, link);
|
||||
const sayEl = block(say, '<span class="lab lab-say">Say this</span>');
|
||||
sayEl.classList.add('obj-say'); body.appendChild(sayEl);
|
||||
d.appendChild(body); ob.appendChild(d);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { fill, POSTS, TEXTS, SWIPES, OBJECTIONS, VIDEOS };
|
||||
})();
|
||||
|
||||
@@ -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';
|
||||
$('rfHint').textContent = gk ? 'Visit counted. Your heroes are back on their feet.' : (ch || sw) ? 'Visit counted. Your hint is ready.' : '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' : '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.'); });
|
||||
})();
|
||||
@@ -485,6 +485,19 @@ 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:rgba(255,255,255,.025)}
|
||||
.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}
|
||||
.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:rgba(67,232,195,.45);color:var(--ink)} .lchip.warn{border-color:rgba(255,209,92,.55);color:#ffd15c}
|
||||
.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)}
|
||||
@@ -798,3 +811,6 @@ img{max-width:100%}
|
||||
.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}
|
||||
|
||||
@@ -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:rgba(67,232,195,.04)}'
|
||||
+ '.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:rgba(67,232,195,.5)}.sup-st.waiting_on_member{color:#f2c94c;border-color:rgba(242,201,76,.5)}.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:rgba(4,8,7,.35)}.sup-msg.admin{border-color:rgba(67,232,195,.45);background:rgba(67,232,195,.06)}.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:rgba(67,232,195,.45)"><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.');
|
||||
|
||||
@@ -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);
|
||||
})();
|
||||
|
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 |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 41 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 49 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 66 KiB |
|
After Width: | Height: | Size: 35 KiB |
|
After Width: | Height: | Size: 222 KiB |
|
After Width: | Height: | Size: 157 KiB |
|
After Width: | Height: | Size: 146 KiB |
|
After Width: | Height: | Size: 108 KiB |
|
After Width: | Height: | Size: 316 KiB |
|
After Width: | Height: | Size: 366 KiB |
|
After Width: | Height: | Size: 180 KiB |
|
After Width: | Height: | Size: 267 KiB |
|
After Width: | Height: | Size: 389 KiB |
|
After Width: | Height: | Size: 175 KiB |
|
After Width: | Height: | Size: 154 KiB |
|
After Width: | Height: | Size: 93 KiB |
|
After Width: | Height: | Size: 81 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 56 KiB |
@@ -0,0 +1,453 @@
|
||||
WEBVTT
|
||||
|
||||
1
|
||||
00:00:00.600 --> 00:00:01.850
|
||||
Willkommen.
|
||||
|
||||
2
|
||||
00:00:01.982 --> 00:00:07.294
|
||||
In den nächsten Minuten zeige ich dir, was
|
||||
InstantAdPay ist, wie weit deine Anzeigen
|
||||
reichen,
|
||||
|
||||
3
|
||||
00:00:07.485 --> 00:00:11.253
|
||||
wie der Vergütungsplan das Geld bewegt,
|
||||
und die eine Strategie,
|
||||
|
||||
4
|
||||
00:00:11.293 --> 00:00:14.271
|
||||
die alles freischaltet: in die Breite
|
||||
bauen.
|
||||
|
||||
5
|
||||
00:00:15.520 --> 00:00:19.520
|
||||
InstantAdPay ist eine Werbeplattform, die
|
||||
ihre Mitglieder bezahlt.
|
||||
|
||||
6
|
||||
00:00:19.781 --> 00:00:26.022
|
||||
Mitglieder kaufen Werbe-Credits und
|
||||
schalten Banner, Textanzeigen, ein
|
||||
Vollbild-Spotlight beim
|
||||
|
||||
7
|
||||
00:00:26.062 --> 00:00:29.795
|
||||
Login, Inbox-Nachrichten, Videos und
|
||||
Website-Besuche.
|
||||
|
||||
8
|
||||
00:00:29.928 --> 00:00:30.898
|
||||
Die Aufrufe sind echt.
|
||||
|
||||
9
|
||||
00:00:30.938 --> 00:00:35.600
|
||||
Mitglieder sehen Anzeigen mindestens zehn
|
||||
Sekunden lang, Kampagnen können Länder
|
||||
gezielt ansprechen, und du
|
||||
|
||||
10
|
||||
00:00:35.640 --> 00:00:38.247
|
||||
zahlst nur für Auslieferung, die wirklich
|
||||
stattgefunden hat.
|
||||
|
||||
11
|
||||
00:00:38.322 --> 00:00:42.822
|
||||
Und wenn jemand, den du geworben hast,
|
||||
Werbung kauft, zahlt dich der Smart
|
||||
|
||||
12
|
||||
00:00:42.862 --> 00:00:44.331
|
||||
Contract in derselben Transaktion.
|
||||
|
||||
13
|
||||
00:00:44.464 --> 00:00:45.550
|
||||
Keine Auszahlungsanträge.
|
||||
|
||||
14
|
||||
00:00:45.590 --> 00:00:46.840
|
||||
Kein Warten.
|
||||
|
||||
15
|
||||
00:00:47.900 --> 00:00:50.309
|
||||
Deine Anzeigen bleiben nicht auf einer
|
||||
Seite.
|
||||
|
||||
16
|
||||
00:00:50.663 --> 00:00:54.037
|
||||
Sie laufen in InstantAdPay, wo Mitglieder
|
||||
Anzeigen ansehen, um ihre
|
||||
|
||||
17
|
||||
00:00:54.077 --> 00:00:55.499
|
||||
täglichen Credits zu verdienen.
|
||||
|
||||
18
|
||||
00:00:55.574 --> 00:01:00.491
|
||||
Sie gehen in die Werbezonen des Netzwerks,
|
||||
die im August rund zwei
|
||||
|
||||
19
|
||||
00:01:00.531 --> 00:01:01.908
|
||||
Millionen Impressionen ausgeliefert haben.
|
||||
|
||||
20
|
||||
00:01:02.470 --> 00:01:05.890
|
||||
Und sie reichen über das Netzwerk hinaus,
|
||||
über Offerwalls von Partnern und
|
||||
|
||||
21
|
||||
00:01:05.930 --> 00:01:07.724
|
||||
die eigenen Websites der Mitglieder.
|
||||
|
||||
22
|
||||
00:01:07.799 --> 00:01:09.872
|
||||
Deine Geworbenen kaufen echte Reichweite.
|
||||
|
||||
23
|
||||
00:01:10.063 --> 00:01:15.596
|
||||
Deshalb kommen sie wieder und kaufen
|
||||
erneut, und jedes Mal wirst du wieder
|
||||
bezahlt.
|
||||
|
||||
24
|
||||
00:01:16.850 --> 00:01:18.377
|
||||
Das hier schafft schnell Vertrauen.
|
||||
|
||||
25
|
||||
00:01:18.417 --> 00:01:21.326
|
||||
Neun kostenlose Spiele im Netzwerk zahlen
|
||||
echte POL.
|
||||
|
||||
26
|
||||
00:01:21.459 --> 00:01:26.864
|
||||
Eine neue Person meldet sich mit ihrer
|
||||
E-Mail über deinen Link an, spielt, und
|
||||
sieht POL in
|
||||
|
||||
27
|
||||
00:01:26.904 --> 00:01:28.154
|
||||
ihrer eigenen Wallet ankommen.
|
||||
|
||||
28
|
||||
00:01:28.193 --> 00:01:30.660
|
||||
Sie wird bezahlt, bevor sie überhaupt
|
||||
etwas zahlt.
|
||||
|
||||
29
|
||||
00:01:40.810 --> 00:01:42.372
|
||||
Jetzt: wie sich das Geld bewegt.
|
||||
|
||||
30
|
||||
00:01:42.412 --> 00:01:44.555
|
||||
Nimm ein Paket für $20.
|
||||
|
||||
31
|
||||
00:01:44.688 --> 00:01:49.559
|
||||
Der Smart Contract teilt es in derselben
|
||||
Transaktion auf: $10 an den Sponsor
|
||||
|
||||
32
|
||||
00:01:49.599 --> 00:01:55.201
|
||||
des Käufers, $4 an Ebene 2, $2 an Ebene 3,
|
||||
und $4 an
|
||||
|
||||
33
|
||||
00:01:55.241 --> 00:01:56.304
|
||||
die Plattform.
|
||||
|
||||
34
|
||||
00:01:56.344 --> 00:01:58.266
|
||||
Niemand kann diese Aufteilung ändern.
|
||||
|
||||
35
|
||||
00:01:58.527 --> 00:02:00.426
|
||||
Sie steht im Contract.
|
||||
|
||||
36
|
||||
00:02:12.580 --> 00:02:14.107
|
||||
Drei Regeln zum Merken.
|
||||
|
||||
37
|
||||
00:02:14.147 --> 00:02:18.310
|
||||
Eins: Ebene 1, die 50 %, ist für alle
|
||||
offen.
|
||||
|
||||
38
|
||||
00:02:18.385 --> 00:02:20.853
|
||||
Auszahlungen einzuschalten kostet fast
|
||||
nichts.
|
||||
|
||||
39
|
||||
00:02:20.893 --> 00:02:24.661
|
||||
Zwei: Jeder Kauf zahlt, nicht nur der
|
||||
erste.
|
||||
|
||||
40
|
||||
00:02:24.736 --> 00:02:28.399
|
||||
Drei: Schalte deine Auszahlungen ein,
|
||||
bevor du jemanden einlädst.
|
||||
|
||||
41
|
||||
00:02:28.439 --> 00:02:33.218
|
||||
Ein Kauf wird nie aufgehalten, also wenn
|
||||
deine Auszahlungen nicht an sind, gehen
|
||||
dieser Verkauf und
|
||||
|
||||
42
|
||||
00:02:33.258 --> 00:02:37.304
|
||||
dieser Käufer an den nächsten Sponsor über
|
||||
dir, für immer.
|
||||
|
||||
43
|
||||
00:02:38.550 --> 00:02:41.517
|
||||
Die Pakete reichen von $5 bis $500.
|
||||
|
||||
44
|
||||
00:02:41.963 --> 00:02:46.823
|
||||
Ab $20 wird jemand zum qualifizierenden
|
||||
Käufer, und das ist wichtig für das,
|
||||
|
||||
45
|
||||
00:02:46.863 --> 00:02:48.877
|
||||
was jetzt kommt.
|
||||
|
||||
46
|
||||
00:02:50.130 --> 00:02:52.412
|
||||
Das ist das Herz der Strategie.
|
||||
|
||||
47
|
||||
00:02:52.603 --> 00:02:55.024
|
||||
Ebene 1 ist ab dem ersten Tag offen.
|
||||
|
||||
48
|
||||
00:02:55.157 --> 00:02:58.217
|
||||
Ebene 2 öffnet sich, wenn zwei deiner
|
||||
direkt Geworbenen jeweils für $20
|
||||
|
||||
49
|
||||
00:02:58.257 --> 00:03:00.109
|
||||
oder mehr gekauft haben.
|
||||
|
||||
50
|
||||
00:03:00.242 --> 00:03:02.234
|
||||
Ebene 3 öffnet sich bei fünf.
|
||||
|
||||
51
|
||||
00:03:02.367 --> 00:03:04.475
|
||||
Breite ersetzt also nicht die Tiefe.
|
||||
|
||||
52
|
||||
00:03:04.515 --> 00:03:07.377
|
||||
Breite ist das, was die Tiefe
|
||||
freischaltet.
|
||||
|
||||
53
|
||||
00:03:15.230 --> 00:03:18.394
|
||||
Das passiert, wenn du in die Tiefe baust,
|
||||
ohne in die Breite zu bauen.
|
||||
|
||||
54
|
||||
00:03:18.585 --> 00:03:21.773
|
||||
Angenommen, du hast zwei Käufer und ein
|
||||
tiefes Team darunter.
|
||||
|
||||
55
|
||||
00:03:21.813 --> 00:03:25.418
|
||||
Wenn jemand in deiner Ebene 3 kauft,
|
||||
wartet dieser Anteil nicht auf dich.
|
||||
|
||||
56
|
||||
00:03:25.609 --> 00:03:29.273
|
||||
Er geht an die nächste Person über dir,
|
||||
die fünf Käufer hat.
|
||||
|
||||
57
|
||||
00:03:30.520 --> 00:03:35.066
|
||||
Stell dir zwei Leader vor, und jeder macht
|
||||
einen Kauf für $20.
|
||||
|
||||
58
|
||||
00:03:35.141 --> 00:03:39.524
|
||||
Leader A sponsert zehn, jeder davon
|
||||
sponsert fünf, und jeder
|
||||
|
||||
59
|
||||
00:03:39.564 --> 00:03:41.161
|
||||
von denen sponsert fünf.
|
||||
|
||||
60
|
||||
00:03:41.422 --> 00:03:44.366
|
||||
Das sind $800 aus einem einzigen Kauf pro
|
||||
Person.
|
||||
|
||||
61
|
||||
00:03:44.557 --> 00:03:48.057
|
||||
Leader B sponsert zwei, und jeder davon
|
||||
sponsert zwei.
|
||||
|
||||
62
|
||||
00:03:48.620 --> 00:03:51.866
|
||||
$36, und B's Ebene 3 wird nach oben
|
||||
weitergegeben.
|
||||
|
||||
63
|
||||
00:03:52.057 --> 00:03:55.163
|
||||
Das ist ein Beispiel, kein
|
||||
Einkommensversprechen.
|
||||
|
||||
64
|
||||
00:03:55.354 --> 00:03:58.913
|
||||
Ob jemand kauft, ist seine eigene
|
||||
Entscheidung.
|
||||
|
||||
65
|
||||
00:04:00.160 --> 00:04:02.210
|
||||
Du willst nicht auf deine ersten
|
||||
Geworbenen warten?
|
||||
|
||||
66
|
||||
00:04:02.238 --> 00:04:06.401
|
||||
Qualified Start lässt dich bis zu fünf
|
||||
eigene Wallets als Positionen verknüpfen.
|
||||
|
||||
67
|
||||
00:04:06.534 --> 00:04:10.824
|
||||
Jeder $20-Kauf einer Position zählt als
|
||||
qualifizierender Käufer, und die Hälfte
|
||||
|
||||
68
|
||||
00:04:10.864 --> 00:04:12.937
|
||||
geht direkt zurück an deine Haupt-Wallet.
|
||||
|
||||
69
|
||||
00:04:13.070 --> 00:04:17.082
|
||||
Fünf Positionen: Du gibst $100 aus, $50
|
||||
kommen zurück, du hast 10.000
|
||||
|
||||
70
|
||||
00:04:17.122 --> 00:04:20.936
|
||||
Werbe-Credits, und die Ebenen 2 und 3 sind
|
||||
offen.
|
||||
|
||||
71
|
||||
00:04:22.190 --> 00:04:24.286
|
||||
Du hast echte Werkzeuge zum Aufbauen.
|
||||
|
||||
72
|
||||
00:04:24.988 --> 00:04:29.650
|
||||
Die Pipeline ist dein Follow-up-Board:
|
||||
alle, mit denen du arbeitest, in Spalten,
|
||||
die sich von selbst
|
||||
|
||||
73
|
||||
00:04:29.690 --> 00:04:33.911
|
||||
bewegen, wenn Leute den nächsten Schritt
|
||||
machen, damit du immer weißt, mit wem du
|
||||
|
||||
74
|
||||
00:04:33.951 --> 00:04:35.201
|
||||
als Nächstes sprichst.
|
||||
|
||||
75
|
||||
00:04:35.448 --> 00:04:38.961
|
||||
Dazu bekommst du Coaching für dein Team,
|
||||
und Promo-Tools mit
|
||||
|
||||
76
|
||||
00:04:39.001 --> 00:04:40.412
|
||||
deinem Link schon eingetragen.
|
||||
|
||||
77
|
||||
00:04:42.660 --> 00:04:45.290
|
||||
Es gibt eine zweite Einkommensquelle auf
|
||||
derselben Wallet.
|
||||
|
||||
78
|
||||
00:04:45.423 --> 00:04:51.293
|
||||
LinkSpin gibt deinem Team Werkzeuge, um
|
||||
alles zu bewerben: rotierende Links,
|
||||
echtes Tracking,
|
||||
|
||||
79
|
||||
00:04:51.333 --> 00:04:52.953
|
||||
Seiten und Werbezonen.
|
||||
|
||||
80
|
||||
00:04:53.086 --> 00:04:58.305
|
||||
Es zahlt dieselben 50, 20, 10, mit
|
||||
denselben Freischaltungen.
|
||||
|
||||
81
|
||||
00:04:58.333 --> 00:05:00.418
|
||||
Der Pre-Launch öffnet am 1. November.
|
||||
|
||||
82
|
||||
00:05:01.670 --> 00:05:03.418
|
||||
Deine Wallet ist dein Schlüssel.
|
||||
|
||||
83
|
||||
00:05:03.864 --> 00:05:07.934
|
||||
Jede Plattform im Netzwerk erkennt dich
|
||||
daran, und dein Team folgt dir.
|
||||
|
||||
84
|
||||
00:05:08.195 --> 00:05:11.464
|
||||
Wenn eine neue Plattform startet, sind
|
||||
deine Leute schon unter dir platziert.
|
||||
|
||||
85
|
||||
00:05:11.504 --> 00:05:17.663
|
||||
Ein Sponsor wird nie übergangen, weil er
|
||||
ruhig ist, und ein Kauf wird nie
|
||||
aufgehalten.
|
||||
|
||||
86
|
||||
00:05:18.910 --> 00:05:21.389
|
||||
Deine erste Woche: Schalte die
|
||||
Auszahlungen ein.
|
||||
|
||||
87
|
||||
00:05:21.580 --> 00:05:23.015
|
||||
Finde deine ersten zwei Käufer.
|
||||
|
||||
88
|
||||
00:05:23.055 --> 00:05:23.897
|
||||
Komm auf fünf.
|
||||
|
||||
89
|
||||
00:05:23.937 --> 00:05:25.244
|
||||
Bau weiter in die Breite.
|
||||
|
||||
90
|
||||
00:05:25.377 --> 00:05:28.912
|
||||
Und bring jeder Person, die du dazuholst,
|
||||
denselben Plan bei.
|
||||
|
||||
91
|
||||
00:05:36.760 --> 00:05:38.136
|
||||
Das Ziel ist fünf.
|
||||
|
||||
92
|
||||
00:05:38.397 --> 00:05:43.047
|
||||
Fünf starke Käufer schalten jede Ebene,
|
||||
jeden Meilenstein und jedes Werkzeug frei.
|
||||
|
||||
93
|
||||
00:05:43.401 --> 00:05:44.651
|
||||
Bereit zu starten?
|
||||
|
||||
94
|
||||
00:05:45.607 --> 00:05:48.144
|
||||
Melde dich bei der Person, die dir das
|
||||
geteilt hat.
|
||||
|
||||
95
|
||||
00:05:48.184 --> 00:05:51.615
|
||||
Sie hilft dir, in wenigen Minuten
|
||||
startklar zu sein, und sie wird dein
|
||||
Sponsor
|
||||
|
||||
96
|
||||
00:05:51.655 --> 00:05:53.542
|
||||
auf jeder Plattform im Netzwerk.
|
||||
@@ -0,0 +1,438 @@
|
||||
WEBVTT
|
||||
|
||||
1
|
||||
00:00:00.600 --> 00:00:01.850
|
||||
Welcome.
|
||||
|
||||
2
|
||||
00:00:01.982 --> 00:00:07.294
|
||||
In the next few minutes I'll show you what
|
||||
InstantAdPay is, how far your ads reach,
|
||||
|
||||
3
|
||||
00:00:07.485 --> 00:00:11.253
|
||||
how the pay plan moves money, and the one
|
||||
strategy that
|
||||
|
||||
4
|
||||
00:00:11.293 --> 00:00:14.271
|
||||
unlocks everything: building wide.
|
||||
|
||||
5
|
||||
00:00:15.520 --> 00:00:19.520
|
||||
InstantAdPay is an advertising platform
|
||||
that pays its members.
|
||||
|
||||
6
|
||||
00:00:19.781 --> 00:00:26.022
|
||||
Members buy ad credits and run banners,
|
||||
text ads, a full-screen login spotlight,
|
||||
|
||||
7
|
||||
00:00:26.062 --> 00:00:29.795
|
||||
inbox messages, videos and website visits.
|
||||
|
||||
8
|
||||
00:00:29.928 --> 00:00:30.898
|
||||
The views are real.
|
||||
|
||||
9
|
||||
00:00:30.938 --> 00:00:35.600
|
||||
Members view ads for at least ten seconds,
|
||||
campaigns can target countries, and you're
|
||||
|
||||
10
|
||||
00:00:35.640 --> 00:00:38.247
|
||||
only charged for delivery that actually
|
||||
happened.
|
||||
|
||||
11
|
||||
00:00:38.322 --> 00:00:42.822
|
||||
And when someone you referred buys
|
||||
advertising, the smart contract pays you
|
||||
|
||||
12
|
||||
00:00:42.862 --> 00:00:44.331
|
||||
in the same transaction.
|
||||
|
||||
13
|
||||
00:00:44.464 --> 00:00:45.550
|
||||
No withdrawal requests.
|
||||
|
||||
14
|
||||
00:00:45.590 --> 00:00:46.840
|
||||
No waiting.
|
||||
|
||||
15
|
||||
00:00:47.900 --> 00:00:50.309
|
||||
Your ads don't stay on one site.
|
||||
|
||||
16
|
||||
00:00:50.663 --> 00:00:54.037
|
||||
They run inside InstantAdPay, where
|
||||
members view ads to
|
||||
|
||||
17
|
||||
00:00:54.077 --> 00:00:55.499
|
||||
earn their daily credits.
|
||||
|
||||
18
|
||||
00:00:55.574 --> 00:01:00.491
|
||||
They go out across the network's ad zones,
|
||||
which served about two million ad
|
||||
|
||||
19
|
||||
00:01:00.531 --> 00:01:01.908
|
||||
impressions in August.
|
||||
|
||||
20
|
||||
00:01:02.470 --> 00:01:05.890
|
||||
And they reach beyond the network, through
|
||||
partner offer walls
|
||||
|
||||
21
|
||||
00:01:05.930 --> 00:01:07.724
|
||||
and members' own websites.
|
||||
|
||||
22
|
||||
00:01:07.799 --> 00:01:09.872
|
||||
Your referrals are buying real reach.
|
||||
|
||||
23
|
||||
00:01:10.063 --> 00:01:15.596
|
||||
That's why they come back and buy again,
|
||||
and every time they do, you're paid again.
|
||||
|
||||
24
|
||||
00:01:16.850 --> 00:01:18.377
|
||||
Here's what builds trust fast.
|
||||
|
||||
25
|
||||
00:01:18.417 --> 00:01:21.326
|
||||
Nine free games on the network pay real
|
||||
POL.
|
||||
|
||||
26
|
||||
00:01:21.459 --> 00:01:26.864
|
||||
A new person signs in with email through
|
||||
your link, plays, and watches POL land in
|
||||
|
||||
27
|
||||
00:01:26.904 --> 00:01:28.154
|
||||
their own wallet.
|
||||
|
||||
28
|
||||
00:01:28.193 --> 00:01:30.660
|
||||
They get paid before they ever pay.
|
||||
|
||||
29
|
||||
00:01:40.810 --> 00:01:42.372
|
||||
Now, how the money moves.
|
||||
|
||||
30
|
||||
00:01:42.412 --> 00:01:44.555
|
||||
Take one twenty-dollar package.
|
||||
|
||||
31
|
||||
00:01:44.688 --> 00:01:49.559
|
||||
The smart contract splits it in the same
|
||||
transaction: ten dollars to the buyer's
|
||||
|
||||
32
|
||||
00:01:49.599 --> 00:01:55.201
|
||||
sponsor, four dollars to level two, two
|
||||
dollars to level three, and four dollars
|
||||
|
||||
33
|
||||
00:01:55.241 --> 00:01:56.304
|
||||
to the platform.
|
||||
|
||||
34
|
||||
00:01:56.344 --> 00:01:58.266
|
||||
Nobody can change that split.
|
||||
|
||||
35
|
||||
00:01:58.527 --> 00:02:00.426
|
||||
It's written into the contract.
|
||||
|
||||
36
|
||||
00:02:12.580 --> 00:02:14.107
|
||||
Three rules to remember.
|
||||
|
||||
37
|
||||
00:02:14.147 --> 00:02:18.310
|
||||
One: level one, the fifty percent, is open
|
||||
to everyone.
|
||||
|
||||
38
|
||||
00:02:18.385 --> 00:02:20.853
|
||||
Switching on payouts costs next to
|
||||
nothing.
|
||||
|
||||
39
|
||||
00:02:20.893 --> 00:02:24.661
|
||||
Two: every purchase pays, not just the
|
||||
first one.
|
||||
|
||||
40
|
||||
00:02:24.736 --> 00:02:28.399
|
||||
Three: switch on your payouts before you
|
||||
invite anyone.
|
||||
|
||||
41
|
||||
00:02:28.439 --> 00:02:33.218
|
||||
A purchase is never held up, so if your
|
||||
payouts aren't on, that sale and that
|
||||
|
||||
42
|
||||
00:02:33.258 --> 00:02:37.304
|
||||
buyer move to the next sponsor above you,
|
||||
for good.
|
||||
|
||||
43
|
||||
00:02:38.550 --> 00:02:41.517
|
||||
Packages run from five dollars to five
|
||||
hundred.
|
||||
|
||||
44
|
||||
00:02:41.963 --> 00:02:46.823
|
||||
Twenty dollars or more makes someone a
|
||||
qualifying buyer, and that matters for
|
||||
|
||||
45
|
||||
00:02:46.863 --> 00:02:48.877
|
||||
what comes next.
|
||||
|
||||
46
|
||||
00:02:50.130 --> 00:02:52.412
|
||||
This is the heart of the strategy.
|
||||
|
||||
47
|
||||
00:02:52.603 --> 00:02:55.024
|
||||
Level one is open from day one.
|
||||
|
||||
48
|
||||
00:02:55.157 --> 00:02:58.217
|
||||
Level two opens when two of your personal
|
||||
referrals have each bought
|
||||
|
||||
49
|
||||
00:02:58.257 --> 00:03:00.109
|
||||
twenty dollars or more.
|
||||
|
||||
50
|
||||
00:03:00.242 --> 00:03:02.234
|
||||
Level three opens at five.
|
||||
|
||||
51
|
||||
00:03:02.367 --> 00:03:04.475
|
||||
So width isn't instead of depth.
|
||||
|
||||
52
|
||||
00:03:04.515 --> 00:03:07.377
|
||||
Width is what unlocks depth.
|
||||
|
||||
53
|
||||
00:03:15.230 --> 00:03:18.394
|
||||
Here's what happens if you build deep
|
||||
without building wide.
|
||||
|
||||
54
|
||||
00:03:18.585 --> 00:03:21.773
|
||||
Say you have two buyers and a deep team
|
||||
below them.
|
||||
|
||||
55
|
||||
00:03:21.813 --> 00:03:25.418
|
||||
When someone in your level three buys,
|
||||
that share doesn't wait for you.
|
||||
|
||||
56
|
||||
00:03:25.609 --> 00:03:29.273
|
||||
It passes to the next person above you who
|
||||
has five buyers.
|
||||
|
||||
57
|
||||
00:03:30.520 --> 00:03:35.066
|
||||
Picture two leaders, and everyone makes
|
||||
one twenty-dollar purchase.
|
||||
|
||||
58
|
||||
00:03:35.141 --> 00:03:39.524
|
||||
Leader A sponsors ten, each of them
|
||||
sponsors five, and each
|
||||
|
||||
59
|
||||
00:03:39.564 --> 00:03:41.161
|
||||
of those sponsors five.
|
||||
|
||||
60
|
||||
00:03:41.422 --> 00:03:44.366
|
||||
That's eight hundred dollars from one
|
||||
purchase each.
|
||||
|
||||
61
|
||||
00:03:44.557 --> 00:03:48.057
|
||||
Leader B sponsors two, and each of them
|
||||
sponsors two.
|
||||
|
||||
62
|
||||
00:03:48.620 --> 00:03:51.866
|
||||
Thirty-six dollars, and B's level three
|
||||
passes up.
|
||||
|
||||
63
|
||||
00:03:52.057 --> 00:03:55.163
|
||||
This is an illustration, not a promise of
|
||||
income.
|
||||
|
||||
64
|
||||
00:03:55.354 --> 00:03:58.913
|
||||
Whether anyone buys is their own choice.
|
||||
|
||||
65
|
||||
00:04:00.160 --> 00:04:02.210
|
||||
Don't want to wait for your first
|
||||
referrals?
|
||||
|
||||
66
|
||||
00:04:02.238 --> 00:04:06.401
|
||||
Qualified Start lets you link up to five
|
||||
wallets of your own as positions.
|
||||
|
||||
67
|
||||
00:04:06.534 --> 00:04:10.824
|
||||
Each twenty-dollar position purchase
|
||||
counts as a qualifying buyer, and half of
|
||||
|
||||
68
|
||||
00:04:10.864 --> 00:04:12.937
|
||||
it comes straight back to your main
|
||||
wallet.
|
||||
|
||||
69
|
||||
00:04:13.070 --> 00:04:17.082
|
||||
Five positions: you spend a hundred
|
||||
dollars, fifty comes back, you hold ten
|
||||
|
||||
70
|
||||
00:04:17.122 --> 00:04:20.936
|
||||
thousand ad credits, and levels two and
|
||||
three are open.
|
||||
|
||||
71
|
||||
00:04:22.190 --> 00:04:24.286
|
||||
You'll have real tools to build with.
|
||||
|
||||
72
|
||||
00:04:24.988 --> 00:04:29.650
|
||||
The Pipeline is your follow-up board:
|
||||
everyone you're working with, in columns
|
||||
|
||||
73
|
||||
00:04:29.690 --> 00:04:33.911
|
||||
that move on their own as people take each
|
||||
step, so you always know who
|
||||
|
||||
74
|
||||
00:04:33.951 --> 00:04:35.201
|
||||
to talk to next.
|
||||
|
||||
75
|
||||
00:04:35.448 --> 00:04:38.961
|
||||
You also get coaching for your team, and
|
||||
promo tools with your
|
||||
|
||||
76
|
||||
00:04:39.001 --> 00:04:40.412
|
||||
link already filled in.
|
||||
|
||||
77
|
||||
00:04:42.660 --> 00:04:45.290
|
||||
There's a second income stream on the same
|
||||
wallet.
|
||||
|
||||
78
|
||||
00:04:45.423 --> 00:04:51.293
|
||||
LinkSpin gives your team tools to promote
|
||||
anything: rotating links, real tracking,
|
||||
|
||||
79
|
||||
00:04:51.333 --> 00:04:52.953
|
||||
pages and ad zones.
|
||||
|
||||
80
|
||||
00:04:53.086 --> 00:04:58.305
|
||||
It pays the same fifty, twenty, ten, with
|
||||
the same unlocks.
|
||||
|
||||
81
|
||||
00:04:58.333 --> 00:05:00.418
|
||||
Pre-launch opens November first.
|
||||
|
||||
82
|
||||
00:05:01.670 --> 00:05:03.418
|
||||
Your wallet is your key.
|
||||
|
||||
83
|
||||
00:05:03.864 --> 00:05:07.934
|
||||
Every platform in the network knows you by
|
||||
it, and your team follows you.
|
||||
|
||||
84
|
||||
00:05:08.195 --> 00:05:11.464
|
||||
When a new platform launches, your people
|
||||
are already placed under you.
|
||||
|
||||
85
|
||||
00:05:11.504 --> 00:05:17.663
|
||||
A sponsor is never passed over for being
|
||||
quiet, and a purchase is never held up.
|
||||
|
||||
86
|
||||
00:05:18.910 --> 00:05:21.389
|
||||
Your first week: switch on payouts.
|
||||
|
||||
87
|
||||
00:05:21.580 --> 00:05:23.015
|
||||
Find your first two buyers.
|
||||
|
||||
88
|
||||
00:05:23.055 --> 00:05:23.897
|
||||
Get to five.
|
||||
|
||||
89
|
||||
00:05:23.937 --> 00:05:25.244
|
||||
Keep going wide.
|
||||
|
||||
90
|
||||
00:05:25.377 --> 00:05:28.912
|
||||
And teach the same plan to every person
|
||||
you bring in.
|
||||
|
||||
91
|
||||
00:05:36.760 --> 00:05:38.136
|
||||
The target is five.
|
||||
|
||||
92
|
||||
00:05:38.397 --> 00:05:43.047
|
||||
Five strong buyers unlock every level,
|
||||
every milestone and every tool.
|
||||
|
||||
93
|
||||
00:05:43.401 --> 00:05:44.651
|
||||
Ready to start?
|
||||
|
||||
94
|
||||
00:05:45.607 --> 00:05:48.144
|
||||
Reach out to the person who shared this
|
||||
with you.
|
||||
|
||||
95
|
||||
00:05:48.184 --> 00:05:51.615
|
||||
They'll help you get set up in a few
|
||||
minutes, and they'll be your sponsor on
|
||||
|
||||
96
|
||||
00:05:51.655 --> 00:05:53.542
|
||||
every platform in the network.
|
||||
@@ -0,0 +1,447 @@
|
||||
WEBVTT
|
||||
|
||||
1
|
||||
00:00:00.600 --> 00:00:01.850
|
||||
Bienvenido.
|
||||
|
||||
2
|
||||
00:00:01.982 --> 00:00:07.294
|
||||
En los próximos minutos te mostraré qué es
|
||||
InstantAdPay, hasta dónde llegan tus
|
||||
anuncios, cómo el
|
||||
|
||||
3
|
||||
00:00:07.485 --> 00:00:11.253
|
||||
plan de pagos mueve el dinero, y la única
|
||||
estrategia que
|
||||
|
||||
4
|
||||
00:00:11.293 --> 00:00:14.271
|
||||
lo desbloquea todo: construir a lo ancho.
|
||||
|
||||
5
|
||||
00:00:15.520 --> 00:00:19.520
|
||||
InstantAdPay es una plataforma de
|
||||
publicidad que paga a sus miembros.
|
||||
|
||||
6
|
||||
00:00:19.781 --> 00:00:26.022
|
||||
Los miembros compran créditos
|
||||
publicitarios y publican banners, anuncios
|
||||
de texto, un spotlight a pantalla completa
|
||||
al iniciar sesión, mensajes
|
||||
|
||||
7
|
||||
00:00:26.062 --> 00:00:29.795
|
||||
en la bandeja de entrada, videos y visitas
|
||||
a sitios web.
|
||||
|
||||
8
|
||||
00:00:29.928 --> 00:00:30.898
|
||||
Las vistas son reales.
|
||||
|
||||
9
|
||||
00:00:30.938 --> 00:00:35.600
|
||||
Los miembros ven los anuncios durante al
|
||||
menos diez segundos, las campañas pueden
|
||||
segmentar por países,
|
||||
|
||||
10
|
||||
00:00:35.640 --> 00:00:38.247
|
||||
y solo pagas por la entrega que realmente
|
||||
ocurrió.
|
||||
|
||||
11
|
||||
00:00:38.322 --> 00:00:42.822
|
||||
Y cuando alguien que referiste compra
|
||||
publicidad, el smart contract te paga
|
||||
|
||||
12
|
||||
00:00:42.862 --> 00:00:44.331
|
||||
en la misma transacción.
|
||||
|
||||
13
|
||||
00:00:44.464 --> 00:00:45.550
|
||||
Sin solicitudes de retiro.
|
||||
|
||||
14
|
||||
00:00:45.590 --> 00:00:46.840
|
||||
Sin esperas.
|
||||
|
||||
15
|
||||
00:00:47.900 --> 00:00:50.309
|
||||
Tus anuncios no se quedan en un solo
|
||||
sitio.
|
||||
|
||||
16
|
||||
00:00:50.663 --> 00:00:54.037
|
||||
Se muestran dentro de InstantAdPay, donde
|
||||
los miembros ven anuncios
|
||||
|
||||
17
|
||||
00:00:54.077 --> 00:00:55.499
|
||||
para ganar sus créditos diarios.
|
||||
|
||||
18
|
||||
00:00:55.574 --> 00:01:00.491
|
||||
Salen a las zonas de anuncios de la red,
|
||||
que en agosto sirvieron unos
|
||||
|
||||
19
|
||||
00:01:00.531 --> 00:01:01.908
|
||||
dos millones de impresiones.
|
||||
|
||||
20
|
||||
00:01:02.470 --> 00:01:05.890
|
||||
Y llegan más allá de la red, a través de
|
||||
los offer walls de socios y
|
||||
|
||||
21
|
||||
00:01:05.930 --> 00:01:07.724
|
||||
los propios sitios web de los miembros.
|
||||
|
||||
22
|
||||
00:01:07.799 --> 00:01:09.872
|
||||
Tus referidos compran alcance real.
|
||||
|
||||
23
|
||||
00:01:10.063 --> 00:01:15.596
|
||||
Por eso vuelven y compran otra vez, y cada
|
||||
vez que lo hacen, te pagan otra vez.
|
||||
|
||||
24
|
||||
00:01:16.850 --> 00:01:18.377
|
||||
Esto es lo que genera confianza rápido.
|
||||
|
||||
25
|
||||
00:01:18.417 --> 00:01:21.326
|
||||
Nueve juegos gratis de la red pagan POL
|
||||
real.
|
||||
|
||||
26
|
||||
00:01:21.459 --> 00:01:26.864
|
||||
Una persona nueva inicia sesión con su
|
||||
email a través de tu enlace, juega, y ve
|
||||
llegar POL
|
||||
|
||||
27
|
||||
00:01:26.904 --> 00:01:28.154
|
||||
a su propio wallet.
|
||||
|
||||
28
|
||||
00:01:28.193 --> 00:01:30.660
|
||||
Le pagan antes de que pague nada.
|
||||
|
||||
29
|
||||
00:01:40.810 --> 00:01:42.372
|
||||
Ahora, cómo se mueve el dinero.
|
||||
|
||||
30
|
||||
00:01:42.412 --> 00:01:44.555
|
||||
Toma un paquete de $20.
|
||||
|
||||
31
|
||||
00:01:44.688 --> 00:01:49.559
|
||||
El smart contract lo reparte en la misma
|
||||
transacción: $10 al patrocinador
|
||||
|
||||
32
|
||||
00:01:49.599 --> 00:01:55.201
|
||||
del comprador, $4 al nivel 2, $2 al nivel
|
||||
3, y $4
|
||||
|
||||
33
|
||||
00:01:55.241 --> 00:01:56.304
|
||||
a la plataforma.
|
||||
|
||||
34
|
||||
00:01:56.344 --> 00:01:58.266
|
||||
Nadie puede cambiar ese reparto.
|
||||
|
||||
35
|
||||
00:01:58.527 --> 00:02:00.426
|
||||
Está escrito en el contrato.
|
||||
|
||||
36
|
||||
00:02:12.580 --> 00:02:14.107
|
||||
Tres reglas para recordar.
|
||||
|
||||
37
|
||||
00:02:14.147 --> 00:02:18.310
|
||||
Uno: el nivel 1, el 50%, está abierto para
|
||||
todos.
|
||||
|
||||
38
|
||||
00:02:18.385 --> 00:02:20.853
|
||||
Activar los pagos no cuesta casi nada.
|
||||
|
||||
39
|
||||
00:02:20.893 --> 00:02:24.661
|
||||
Dos: cada compra paga, no solo la primera.
|
||||
|
||||
40
|
||||
00:02:24.736 --> 00:02:28.399
|
||||
Tres: activa tus pagos antes de invitar a
|
||||
nadie.
|
||||
|
||||
41
|
||||
00:02:28.439 --> 00:02:33.218
|
||||
Una compra nunca se detiene, así que si
|
||||
tus pagos no están activos, esa venta y
|
||||
ese
|
||||
|
||||
42
|
||||
00:02:33.258 --> 00:02:37.304
|
||||
comprador pasan al siguiente patrocinador
|
||||
por encima de ti, para siempre.
|
||||
|
||||
43
|
||||
00:02:38.550 --> 00:02:41.517
|
||||
Los paquetes van de $5 a $500.
|
||||
|
||||
44
|
||||
00:02:41.963 --> 00:02:46.823
|
||||
Con $20 o más alguien se convierte en
|
||||
comprador calificado, y eso importa para
|
||||
|
||||
45
|
||||
00:02:46.863 --> 00:02:48.877
|
||||
lo que viene.
|
||||
|
||||
46
|
||||
00:02:50.130 --> 00:02:52.412
|
||||
Este es el corazón de la estrategia.
|
||||
|
||||
47
|
||||
00:02:52.603 --> 00:02:55.024
|
||||
El nivel 1 está abierto desde el primer
|
||||
día.
|
||||
|
||||
48
|
||||
00:02:55.157 --> 00:02:58.217
|
||||
El nivel 2 se abre cuando dos de tus
|
||||
referidos directos han comprado
|
||||
|
||||
49
|
||||
00:02:58.257 --> 00:03:00.109
|
||||
cada uno $20 o más.
|
||||
|
||||
50
|
||||
00:03:00.242 --> 00:03:02.234
|
||||
El nivel 3 se abre con cinco.
|
||||
|
||||
51
|
||||
00:03:02.367 --> 00:03:04.475
|
||||
Así que el ancho no reemplaza a la
|
||||
profundidad.
|
||||
|
||||
52
|
||||
00:03:04.515 --> 00:03:07.377
|
||||
El ancho es lo que desbloquea la
|
||||
profundidad.
|
||||
|
||||
53
|
||||
00:03:15.230 --> 00:03:18.394
|
||||
Esto es lo que pasa si construyes en
|
||||
profundidad sin construir a lo ancho.
|
||||
|
||||
54
|
||||
00:03:18.585 --> 00:03:21.773
|
||||
Digamos que tienes dos compradores y un
|
||||
equipo profundo debajo de ellos.
|
||||
|
||||
55
|
||||
00:03:21.813 --> 00:03:25.418
|
||||
Cuando alguien de tu nivel 3 compra, esa
|
||||
parte no te espera.
|
||||
|
||||
56
|
||||
00:03:25.609 --> 00:03:29.273
|
||||
Pasa a la siguiente persona por encima de
|
||||
ti que tiene cinco compradores.
|
||||
|
||||
57
|
||||
00:03:30.520 --> 00:03:35.066
|
||||
Imagina dos líderes, y cada persona hace
|
||||
una compra de $20.
|
||||
|
||||
58
|
||||
00:03:35.141 --> 00:03:39.524
|
||||
El líder A patrocina a diez, cada uno
|
||||
patrocina a cinco, y cada uno
|
||||
|
||||
59
|
||||
00:03:39.564 --> 00:03:41.161
|
||||
de esos patrocina a cinco.
|
||||
|
||||
60
|
||||
00:03:41.422 --> 00:03:44.366
|
||||
Son $800 de una sola compra por persona.
|
||||
|
||||
61
|
||||
00:03:44.557 --> 00:03:48.057
|
||||
El líder B patrocina a dos, y cada uno
|
||||
patrocina a dos.
|
||||
|
||||
62
|
||||
00:03:48.620 --> 00:03:51.866
|
||||
$36, y el nivel 3 de B pasa hacia arriba.
|
||||
|
||||
63
|
||||
00:03:52.057 --> 00:03:55.163
|
||||
Esto es una ilustración, no una promesa de
|
||||
ingresos.
|
||||
|
||||
64
|
||||
00:03:55.354 --> 00:03:58.913
|
||||
Comprar o no es decisión de cada persona.
|
||||
|
||||
65
|
||||
00:04:00.160 --> 00:04:02.210
|
||||
¿No quieres esperar a tus primeros
|
||||
referidos?
|
||||
|
||||
66
|
||||
00:04:02.238 --> 00:04:06.401
|
||||
Qualified Start te permite vincular hasta
|
||||
cinco wallets propios como posiciones.
|
||||
|
||||
67
|
||||
00:04:06.534 --> 00:04:10.824
|
||||
Cada compra de $20 de una posición cuenta
|
||||
como comprador calificado, y la
|
||||
|
||||
68
|
||||
00:04:10.864 --> 00:04:12.937
|
||||
mitad vuelve directo a tu wallet
|
||||
principal.
|
||||
|
||||
69
|
||||
00:04:13.070 --> 00:04:17.082
|
||||
Cinco posiciones: gastas $100, te vuelven
|
||||
$50, tienes 10.000 créditos publicitarios,
|
||||
|
||||
70
|
||||
00:04:17.122 --> 00:04:20.936
|
||||
y los niveles 2 y 3 quedan abiertos.
|
||||
|
||||
71
|
||||
00:04:22.190 --> 00:04:24.286
|
||||
Tendrás herramientas reales para
|
||||
construir.
|
||||
|
||||
72
|
||||
00:04:24.988 --> 00:04:29.650
|
||||
El Pipeline es tu tablero de seguimiento:
|
||||
todas las personas con las que trabajas,
|
||||
en columnas que
|
||||
|
||||
73
|
||||
00:04:29.690 --> 00:04:33.911
|
||||
avanzan solas a medida que cada uno da su
|
||||
paso, para que siempre sepas con
|
||||
|
||||
74
|
||||
00:04:33.951 --> 00:04:35.201
|
||||
quién hablar después.
|
||||
|
||||
75
|
||||
00:04:35.448 --> 00:04:38.961
|
||||
También tienes coaching para tu equipo, y
|
||||
herramientas promocionales con
|
||||
|
||||
76
|
||||
00:04:39.001 --> 00:04:40.412
|
||||
tu enlace ya incluido.
|
||||
|
||||
77
|
||||
00:04:42.660 --> 00:04:45.290
|
||||
Hay una segunda fuente de ingresos en el
|
||||
mismo wallet.
|
||||
|
||||
78
|
||||
00:04:45.423 --> 00:04:51.293
|
||||
LinkSpin le da a tu equipo herramientas
|
||||
para promocionar cualquier cosa: enlaces
|
||||
rotativos, seguimiento real, páginas
|
||||
|
||||
79
|
||||
00:04:51.333 --> 00:04:52.953
|
||||
y zonas de anuncios.
|
||||
|
||||
80
|
||||
00:04:53.086 --> 00:04:58.305
|
||||
Paga el mismo 50, 20, 10, con los mismos
|
||||
desbloqueos.
|
||||
|
||||
81
|
||||
00:04:58.333 --> 00:05:00.418
|
||||
El prelanzamiento abre el 1 de noviembre.
|
||||
|
||||
82
|
||||
00:05:01.670 --> 00:05:03.418
|
||||
Tu wallet es tu llave.
|
||||
|
||||
83
|
||||
00:05:03.864 --> 00:05:07.934
|
||||
Cada plataforma de la red te reconoce por
|
||||
él, y tu equipo te sigue.
|
||||
|
||||
84
|
||||
00:05:08.195 --> 00:05:11.464
|
||||
Cuando se lanza una nueva plataforma, tu
|
||||
gente ya está colocada debajo de ti.
|
||||
|
||||
85
|
||||
00:05:11.504 --> 00:05:17.663
|
||||
A un patrocinador nunca se le salta por
|
||||
estar callado, y una compra nunca se
|
||||
detiene.
|
||||
|
||||
86
|
||||
00:05:18.910 --> 00:05:21.389
|
||||
Tu primera semana: activa los pagos.
|
||||
|
||||
87
|
||||
00:05:21.580 --> 00:05:23.015
|
||||
Encuentra a tus dos primeros compradores.
|
||||
|
||||
88
|
||||
00:05:23.055 --> 00:05:23.897
|
||||
Llega a cinco.
|
||||
|
||||
89
|
||||
00:05:23.937 --> 00:05:25.244
|
||||
Sigue construyendo a lo ancho.
|
||||
|
||||
90
|
||||
00:05:25.377 --> 00:05:28.912
|
||||
Y enseña el mismo plan a cada persona que
|
||||
traigas.
|
||||
|
||||
91
|
||||
00:05:36.760 --> 00:05:38.136
|
||||
La meta es cinco.
|
||||
|
||||
92
|
||||
00:05:38.397 --> 00:05:43.047
|
||||
Cinco compradores sólidos desbloquean cada
|
||||
nivel, cada hito y cada herramienta.
|
||||
|
||||
93
|
||||
00:05:43.401 --> 00:05:44.651
|
||||
¿Listo para empezar?
|
||||
|
||||
94
|
||||
00:05:45.607 --> 00:05:48.144
|
||||
Contacta a la persona que te compartió
|
||||
este video.
|
||||
|
||||
95
|
||||
00:05:48.184 --> 00:05:51.615
|
||||
Te ayudará a empezar en pocos minutos, y
|
||||
será tu patrocinador en
|
||||
|
||||
96
|
||||
00:05:51.655 --> 00:05:53.542
|
||||
cada plataforma de la red.
|
||||
@@ -0,0 +1,459 @@
|
||||
WEBVTT
|
||||
|
||||
1
|
||||
00:00:00.600 --> 00:00:01.850
|
||||
Bienvenue.
|
||||
|
||||
2
|
||||
00:00:01.982 --> 00:00:07.294
|
||||
Dans les prochaines minutes, je vais vous
|
||||
montrer ce qu'est InstantAdPay, jusqu'où
|
||||
vont vos annonces, comment
|
||||
|
||||
3
|
||||
00:00:07.485 --> 00:00:11.253
|
||||
le plan de rémunération fait circuler
|
||||
l'argent, et la stratégie qui
|
||||
|
||||
4
|
||||
00:00:11.293 --> 00:00:14.271
|
||||
débloque tout : construire en largeur.
|
||||
|
||||
5
|
||||
00:00:15.520 --> 00:00:19.520
|
||||
InstantAdPay est une plateforme
|
||||
publicitaire qui paie ses membres.
|
||||
|
||||
6
|
||||
00:00:19.781 --> 00:00:26.022
|
||||
Les membres achètent des crédits
|
||||
publicitaires et diffusent des bannières,
|
||||
des annonces texte, un spotlight plein
|
||||
écran à la connexion, des messages
|
||||
|
||||
7
|
||||
00:00:26.062 --> 00:00:29.795
|
||||
en boîte de réception, des vidéos et des
|
||||
visites de sites.
|
||||
|
||||
8
|
||||
00:00:29.928 --> 00:00:30.898
|
||||
Les vues sont réelles.
|
||||
|
||||
9
|
||||
00:00:30.938 --> 00:00:35.600
|
||||
Les membres regardent les annonces au
|
||||
moins dix secondes, les campagnes peuvent
|
||||
cibler des pays,
|
||||
|
||||
10
|
||||
00:00:35.640 --> 00:00:38.247
|
||||
et vous ne payez que la diffusion
|
||||
réellement effectuée.
|
||||
|
||||
11
|
||||
00:00:38.322 --> 00:00:42.822
|
||||
Et quand une personne que vous avez
|
||||
parrainée achète de la publicité, le smart
|
||||
contract vous
|
||||
|
||||
12
|
||||
00:00:42.862 --> 00:00:44.331
|
||||
paie dans la même transaction.
|
||||
|
||||
13
|
||||
00:00:44.464 --> 00:00:45.550
|
||||
Aucune demande de retrait.
|
||||
|
||||
14
|
||||
00:00:45.590 --> 00:00:46.840
|
||||
Aucune attente.
|
||||
|
||||
15
|
||||
00:00:47.900 --> 00:00:50.309
|
||||
Vos annonces ne restent pas sur un seul
|
||||
site.
|
||||
|
||||
16
|
||||
00:00:50.663 --> 00:00:54.037
|
||||
Elles tournent dans InstantAdPay, où les
|
||||
membres regardent des annonces pour
|
||||
|
||||
17
|
||||
00:00:54.077 --> 00:00:55.499
|
||||
gagner leurs crédits du jour.
|
||||
|
||||
18
|
||||
00:00:55.574 --> 00:01:00.491
|
||||
Elles sortent dans les zones publicitaires
|
||||
du réseau, qui ont servi environ deux
|
||||
|
||||
19
|
||||
00:01:00.531 --> 00:01:01.908
|
||||
millions d'impressions en août.
|
||||
|
||||
20
|
||||
00:01:02.470 --> 00:01:05.890
|
||||
Et elles vont au-delà du réseau, via les
|
||||
offer walls partenaires et
|
||||
|
||||
21
|
||||
00:01:05.930 --> 00:01:07.724
|
||||
les propres sites des membres.
|
||||
|
||||
22
|
||||
00:01:07.799 --> 00:01:09.872
|
||||
Vos filleuls achètent une vraie
|
||||
visibilité.
|
||||
|
||||
23
|
||||
00:01:10.063 --> 00:01:15.596
|
||||
C'est pour ça qu'ils reviennent et
|
||||
rachètent, et à chaque fois, vous êtes
|
||||
payé à nouveau.
|
||||
|
||||
24
|
||||
00:01:16.850 --> 00:01:18.377
|
||||
Voici ce qui crée la confiance rapidement.
|
||||
|
||||
25
|
||||
00:01:18.417 --> 00:01:21.326
|
||||
Neuf jeux gratuits du réseau paient de
|
||||
vrais POL.
|
||||
|
||||
26
|
||||
00:01:21.459 --> 00:01:26.864
|
||||
Une nouvelle personne se connecte avec son
|
||||
e-mail via votre lien, joue, et voit des
|
||||
POL arriver
|
||||
|
||||
27
|
||||
00:01:26.904 --> 00:01:28.154
|
||||
dans son propre wallet.
|
||||
|
||||
28
|
||||
00:01:28.193 --> 00:01:30.660
|
||||
Elle est payée avant même de payer.
|
||||
|
||||
29
|
||||
00:01:40.810 --> 00:01:42.372
|
||||
Maintenant, comment circule l'argent.
|
||||
|
||||
30
|
||||
00:01:42.412 --> 00:01:44.555
|
||||
Prenons un pack à $20.
|
||||
|
||||
31
|
||||
00:01:44.688 --> 00:01:49.559
|
||||
Le smart contract le répartit dans la même
|
||||
transaction : $10 au parrain
|
||||
|
||||
32
|
||||
00:01:49.599 --> 00:01:55.201
|
||||
de l'acheteur, $4 au niveau 2, $2 au
|
||||
niveau 3, et $4 à
|
||||
|
||||
33
|
||||
00:01:55.241 --> 00:01:56.304
|
||||
la plateforme.
|
||||
|
||||
34
|
||||
00:01:56.344 --> 00:01:58.266
|
||||
Personne ne peut modifier cette
|
||||
répartition.
|
||||
|
||||
35
|
||||
00:01:58.527 --> 00:02:00.426
|
||||
Elle est écrite dans le contrat.
|
||||
|
||||
36
|
||||
00:02:12.580 --> 00:02:14.107
|
||||
Trois règles à retenir.
|
||||
|
||||
37
|
||||
00:02:14.147 --> 00:02:18.310
|
||||
Un : le niveau 1, les 50 %, est ouvert à
|
||||
tous.
|
||||
|
||||
38
|
||||
00:02:18.385 --> 00:02:20.853
|
||||
Activer les paiements ne coûte presque
|
||||
rien.
|
||||
|
||||
39
|
||||
00:02:20.893 --> 00:02:24.661
|
||||
Deux : chaque achat paie, pas seulement le
|
||||
premier.
|
||||
|
||||
40
|
||||
00:02:24.736 --> 00:02:28.399
|
||||
Trois : activez vos paiements avant
|
||||
d'inviter qui que ce soit.
|
||||
|
||||
41
|
||||
00:02:28.439 --> 00:02:33.218
|
||||
Un achat n'est jamais bloqué, donc si vos
|
||||
paiements ne sont pas activés, cette vente
|
||||
et
|
||||
|
||||
42
|
||||
00:02:33.258 --> 00:02:37.304
|
||||
cet acheteur passent au parrain suivant
|
||||
au-dessus de vous, définitivement.
|
||||
|
||||
43
|
||||
00:02:38.550 --> 00:02:41.517
|
||||
Les packs vont de $5 à $500.
|
||||
|
||||
44
|
||||
00:02:41.963 --> 00:02:46.823
|
||||
À partir de $20, on devient acheteur
|
||||
qualifiant, et c'est important pour
|
||||
|
||||
45
|
||||
00:02:46.863 --> 00:02:48.877
|
||||
la suite.
|
||||
|
||||
46
|
||||
00:02:50.130 --> 00:02:52.412
|
||||
C'est le cœur de la stratégie.
|
||||
|
||||
47
|
||||
00:02:52.603 --> 00:02:55.024
|
||||
Le niveau 1 est ouvert dès le premier
|
||||
jour.
|
||||
|
||||
48
|
||||
00:02:55.157 --> 00:02:58.217
|
||||
Le niveau 2 s'ouvre quand deux de vos
|
||||
filleuls directs ont chacun acheté
|
||||
|
||||
49
|
||||
00:02:58.257 --> 00:03:00.109
|
||||
pour $20 ou plus.
|
||||
|
||||
50
|
||||
00:03:00.242 --> 00:03:02.234
|
||||
Le niveau 3 s'ouvre à cinq.
|
||||
|
||||
51
|
||||
00:03:02.367 --> 00:03:04.475
|
||||
La largeur ne remplace donc pas la
|
||||
profondeur.
|
||||
|
||||
52
|
||||
00:03:04.515 --> 00:03:07.377
|
||||
C'est la largeur qui débloque la
|
||||
profondeur.
|
||||
|
||||
53
|
||||
00:03:15.230 --> 00:03:18.394
|
||||
Voici ce qui arrive si vous construisez en
|
||||
profondeur sans construire en largeur.
|
||||
|
||||
54
|
||||
00:03:18.585 --> 00:03:21.773
|
||||
Disons que vous avez deux acheteurs et une
|
||||
équipe profonde en dessous.
|
||||
|
||||
55
|
||||
00:03:21.813 --> 00:03:25.418
|
||||
Quand quelqu'un de votre niveau 3 achète,
|
||||
cette part ne vous attend pas.
|
||||
|
||||
56
|
||||
00:03:25.609 --> 00:03:29.273
|
||||
Elle passe à la prochaine personne
|
||||
au-dessus de vous qui a cinq acheteurs.
|
||||
|
||||
57
|
||||
00:03:30.520 --> 00:03:35.066
|
||||
Imaginez deux leaders, et chacun fait un
|
||||
achat de $20.
|
||||
|
||||
58
|
||||
00:03:35.141 --> 00:03:39.524
|
||||
Le leader A parraine dix personnes,
|
||||
chacune en parraine cinq, et chacune
|
||||
|
||||
59
|
||||
00:03:39.564 --> 00:03:41.161
|
||||
de celles-ci en parraine cinq.
|
||||
|
||||
60
|
||||
00:03:41.422 --> 00:03:44.366
|
||||
Cela fait $800 pour un seul achat chacun.
|
||||
|
||||
61
|
||||
00:03:44.557 --> 00:03:48.057
|
||||
Le leader B en parraine deux, et chacun
|
||||
d'eux en parraine deux.
|
||||
|
||||
62
|
||||
00:03:48.620 --> 00:03:51.866
|
||||
$36, et le niveau 3 de B remonte
|
||||
au-dessus.
|
||||
|
||||
63
|
||||
00:03:52.057 --> 00:03:55.163
|
||||
Ceci est une illustration, pas une
|
||||
promesse de revenus.
|
||||
|
||||
64
|
||||
00:03:55.354 --> 00:03:58.913
|
||||
Acheter ou non reste le libre choix de
|
||||
chacun.
|
||||
|
||||
65
|
||||
00:04:00.160 --> 00:04:02.210
|
||||
Vous ne voulez pas attendre vos premiers
|
||||
filleuls ?
|
||||
|
||||
66
|
||||
00:04:02.238 --> 00:04:06.401
|
||||
Qualified Start vous permet de lier
|
||||
jusqu'à cinq de vos propres wallets comme
|
||||
positions.
|
||||
|
||||
67
|
||||
00:04:06.534 --> 00:04:10.824
|
||||
Chaque achat de $20 d'une position compte
|
||||
comme un acheteur qualifiant, et la
|
||||
|
||||
68
|
||||
00:04:10.864 --> 00:04:12.937
|
||||
moitié revient directement sur votre
|
||||
wallet principal.
|
||||
|
||||
69
|
||||
00:04:13.070 --> 00:04:17.082
|
||||
Cinq positions : vous dépensez $100, $50
|
||||
vous reviennent, vous détenez 10 000
|
||||
|
||||
70
|
||||
00:04:17.122 --> 00:04:20.936
|
||||
crédits publicitaires, et les niveaux 2 et
|
||||
3 sont ouverts.
|
||||
|
||||
71
|
||||
00:04:22.190 --> 00:04:24.286
|
||||
Vous aurez de vrais outils pour
|
||||
construire.
|
||||
|
||||
72
|
||||
00:04:24.988 --> 00:04:29.650
|
||||
La Pipeline est votre tableau de suivi :
|
||||
toutes les personnes avec qui vous
|
||||
travaillez, dans
|
||||
|
||||
73
|
||||
00:04:29.690 --> 00:04:33.911
|
||||
des colonnes qui avancent d'elles-mêmes à
|
||||
chaque étape franchie, pour que vous
|
||||
sachiez toujours à
|
||||
|
||||
74
|
||||
00:04:33.951 --> 00:04:35.201
|
||||
qui parler ensuite.
|
||||
|
||||
75
|
||||
00:04:35.448 --> 00:04:38.961
|
||||
Vous avez aussi du coaching pour votre
|
||||
équipe, et des outils promo
|
||||
|
||||
76
|
||||
00:04:39.001 --> 00:04:40.412
|
||||
avec votre lien déjà intégré.
|
||||
|
||||
77
|
||||
00:04:42.660 --> 00:04:45.290
|
||||
Il y a une deuxième source de revenus sur
|
||||
le même wallet.
|
||||
|
||||
78
|
||||
00:04:45.423 --> 00:04:51.293
|
||||
LinkSpin donne à votre équipe des outils
|
||||
pour promouvoir n'importe quoi : liens
|
||||
rotatifs, vrai suivi,
|
||||
|
||||
79
|
||||
00:04:51.333 --> 00:04:52.953
|
||||
pages et zones publicitaires.
|
||||
|
||||
80
|
||||
00:04:53.086 --> 00:04:58.305
|
||||
Il paie les mêmes 50, 20, 10, avec les
|
||||
mêmes déblocages.
|
||||
|
||||
81
|
||||
00:04:58.333 --> 00:05:00.418
|
||||
La pré-ouverture démarre le 1er novembre.
|
||||
|
||||
82
|
||||
00:05:01.670 --> 00:05:03.418
|
||||
Votre wallet est votre clé.
|
||||
|
||||
83
|
||||
00:05:03.864 --> 00:05:07.934
|
||||
Chaque plateforme du réseau vous reconnaît
|
||||
grâce à lui, et votre équipe vous suit.
|
||||
|
||||
84
|
||||
00:05:08.195 --> 00:05:11.464
|
||||
Quand une nouvelle plateforme est lancée,
|
||||
vos personnes sont déjà placées sous vous.
|
||||
|
||||
85
|
||||
00:05:11.504 --> 00:05:17.663
|
||||
Un parrain n'est jamais écarté parce qu'il
|
||||
est discret, et un achat n'est jamais
|
||||
bloqué.
|
||||
|
||||
86
|
||||
00:05:18.910 --> 00:05:21.389
|
||||
Votre première semaine : activez les
|
||||
paiements.
|
||||
|
||||
87
|
||||
00:05:21.580 --> 00:05:23.015
|
||||
Trouvez vos deux premiers acheteurs.
|
||||
|
||||
88
|
||||
00:05:23.055 --> 00:05:23.897
|
||||
Atteignez cinq.
|
||||
|
||||
89
|
||||
00:05:23.937 --> 00:05:25.244
|
||||
Continuez à construire en largeur.
|
||||
|
||||
90
|
||||
00:05:25.377 --> 00:05:28.912
|
||||
Et enseignez le même plan à chaque
|
||||
personne que vous faites entrer.
|
||||
|
||||
91
|
||||
00:05:36.760 --> 00:05:38.136
|
||||
L'objectif, c'est cinq.
|
||||
|
||||
92
|
||||
00:05:38.397 --> 00:05:43.047
|
||||
Cinq acheteurs solides débloquent chaque
|
||||
niveau, chaque palier et chaque outil.
|
||||
|
||||
93
|
||||
00:05:43.401 --> 00:05:44.651
|
||||
Prêt à commencer ?
|
||||
|
||||
94
|
||||
00:05:45.607 --> 00:05:48.144
|
||||
Contactez la personne qui vous a partagé
|
||||
cette vidéo.
|
||||
|
||||
95
|
||||
00:05:48.184 --> 00:05:51.615
|
||||
Elle vous aidera à démarrer en quelques
|
||||
minutes, et elle sera votre parrain
|
||||
|
||||
96
|
||||
00:05:51.655 --> 00:05:53.542
|
||||
sur chaque plateforme du réseau.
|
||||