Gem Kingdom: sign-in hand-off (/api/my/gemkingdom), Games card (admin preview until gamesLive), Crown shop checkout (/gk/shop: confirm, short -> top-up detour with dashboard banner back, confirm spends credits via ads.gamePurchase, signed receipt redirect + server callback); game purchases skip refill notices and the campaign list
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+3176
-3173
File diff suppressed because it is too large
Load Diff
+1
-1
@@ -1108,7 +1108,7 @@
|
||||
<script src="/assets/common.js?v=20260929b"></script><script src="/assets/welcome.js?v=20260923b"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20260929c"></script>
|
||||
<script src="/assets/my.js?v=20261001c"></script>
|
||||
<script src="/assets/my.js?v=20261001d"></script>
|
||||
<script src="/assets/chat.js?v=20260907l"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,282 +1,282 @@
|
||||
// Campaign refill notices (Marty, 2026-09-22). Two moments in an advertiser's life were silent:
|
||||
// the ad running low, and the ad stopping dead. 70 member campaigns had already delivered their whole
|
||||
// budget and stopped with nobody told, and half of those owners were still holding credits they could
|
||||
// have spent the same minute. This watches for both moments, writes one email and one on-site notice
|
||||
// per owner (never one per campaign), leads with what the ad actually delivered, and puts the bonus
|
||||
// ladder in front of them at the only moment it is persuasive.
|
||||
//
|
||||
// Everything sent is recorded, and every send is then watched for what the owner did next: relaunched
|
||||
// a campaign, topped one up, or bought credits. That is the conversion history, in data/refill.json.
|
||||
//
|
||||
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget
|
||||
// delivered that counts as "running low".
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let X = {}, FILE = null, S = null;
|
||||
const DAY = 86400000;
|
||||
const LOOKBACK = 45 * DAY; // a send older than this stops being watched for a conversion
|
||||
const MAX_PER_TICK = 25; // owners emailed in one pass, so a backfill goes out in batches
|
||||
const IDLE_AFTER = 7 * DAY; // follow-up: an "out" notice this old, still unanswered, with credits idle and nothing running (Marty, 2026-09-30)
|
||||
const IDLE_MIN_CREDITS = 100; // enough to relaunch without buying
|
||||
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'refill.json'); S = load(); }
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { sent: {}, seq: 0 }; } }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
return {
|
||||
on: String(c.refillNotices == null ? '1' : c.refillNotices) === '1',
|
||||
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
|
||||
fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
||||
fridayPct: Number(c.fridayBonusPct) || 20,
|
||||
};
|
||||
}
|
||||
|
||||
const SITE = 'https://instantadpay.com';
|
||||
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : 0);
|
||||
const money = n => Number(n || 0).toLocaleString('en-US');
|
||||
const delivered = c => n0(c.spent) + n0(c.accrued);
|
||||
// video campaigns count watches, not impressions, and the relaunch maths only makes sense with the per-watch price (Marty, 2026-09-30)
|
||||
const unit = c => c.type === 'video' ? 'watches' : 'impressions';
|
||||
function videoNote(c) {
|
||||
if (c.type !== 'video') return '';
|
||||
const secs = Number(c.body) || 0; let cost = 0;
|
||||
try { cost = ((X.ads.rates().videoTiers || []).find(t => t.secs === secs) || {}).cost || 0; } catch (e) {}
|
||||
if (!secs || !cost) return '';
|
||||
return ' (' + secs + '-second video at ' + cost + ' credits a watch: every ' + money(cost * 100) + ' credits buys about 100 more watches)';
|
||||
}
|
||||
const key = (id, state) => id + ':' + state;
|
||||
|
||||
// the five packages and what each dollar buys, so the ladder is never hand-typed
|
||||
const PACKS = [
|
||||
{ price: 5, credits: 500, bonus: 0 },
|
||||
{ price: 20, credits: 2000, bonus: 0 },
|
||||
{ price: 50, credits: 5500, bonus: 10 },
|
||||
{ price: 100, credits: 12000, bonus: 20 },
|
||||
{ price: 250, credits: 32500, bonus: 30 },
|
||||
];
|
||||
|
||||
function ladderText() {
|
||||
const c = cfg();
|
||||
const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : ''));
|
||||
let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n')
|
||||
+ '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.';
|
||||
if (c.fridayOn) s += '\n\nFive Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.';
|
||||
return s;
|
||||
}
|
||||
function ladderHtml() {
|
||||
const c = cfg();
|
||||
const rows = PACKS.map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + p.price + '</b></td><td style="padding:6px 14px 6px 0">' + money(p.credits)
|
||||
+ ' credits</td><td style="padding:6px 0;color:#0E8F72">' + (p.bonus ? p.bonus + '% more per dollar' : '') + '</td></tr>').join('');
|
||||
return '<p><b>Ad packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
|
||||
+ '<p style="color:#556">A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.</p>'
|
||||
+ (c.fridayOn ? '<p><b>Five Dollar Friday:</b> any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.</p>' : '');
|
||||
}
|
||||
|
||||
// what one owner's batch of campaigns says in the body
|
||||
function describe(list) {
|
||||
return list.map(c => {
|
||||
const bits = [money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'];
|
||||
if (n0(c.imps)) bits.push(money(n0(c.imps)) + ' ' + unit(c));
|
||||
if (n0(c.clicks)) bits.push(money(n0(c.clicks)) + ' clicks');
|
||||
return ' "' + (c.name || c.title || ('campaign #' + c.id)) + '" (' + (c.type || 'ad') + '): ' + bits.join(', ') + videoNote(c);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
async function compose(owner, list, state, credits) {
|
||||
const many = list.length > 1;
|
||||
const totalImps = list.reduce((n, c) => n + n0(c.imps), 0);
|
||||
const totalClicks = list.reduce((n, c) => n + n0(c.clicks), 0);
|
||||
const canRelaunch = credits >= 100;
|
||||
const subject = state === 'idle' ? money(Math.round(credits)) + ' credits are sitting idle on your InstantAdPay account'
|
||||
: state === 'out'
|
||||
? (many ? 'Your InstantAdPay ads have finished delivering' : 'Your ad "' + (list[0].name || 'campaign') + '" has finished delivering')
|
||||
: (many ? 'Your InstantAdPay ads are nearly out of credits' : 'Your ad "' + (list[0].name || 'campaign') + '" is nearly out of credits');
|
||||
const opener = state === 'idle'
|
||||
? 'A week ago ' + (many ? 'your ads' : 'your ad "' + (list[0].name || 'campaign') + '"') + ' finished delivering, and nothing has run since. Your credits are still there, and nobody is seeing your link while they sit.'
|
||||
: state === 'out'
|
||||
? (many ? 'Your ' + list.length + ' campaigns have spent their full budget and stopped. They delivered everything you paid for.'
|
||||
: 'That campaign spent its full budget and stopped. It delivered everything you paid for.')
|
||||
: (many ? 'Your ' + list.length + ' campaigns are close to spending their full budget. When they do, they stop.'
|
||||
: 'That campaign is close to spending its full budget. When it does, it stops.');
|
||||
const totals = (totalImps || totalClicks)
|
||||
? 'Between them so far: ' + money(totalImps) + (list.every(c => c.type === 'video') ? ' watches' : ' impressions') + ' and ' + money(totalClicks) + ' clicks.'
|
||||
: '';
|
||||
const next = state === 'idle'
|
||||
? money(Math.round(credits)) + ' credits are ready to run. A banner or text ad takes a minute to set up and starts showing the moment you launch it, no purchase needed: ' + SITE + '/my#campaigns'
|
||||
: canRelaunch
|
||||
? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns'
|
||||
: 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy';
|
||||
const lines = [opener, totals, next, ladderText(),
|
||||
'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.'];
|
||||
const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay';
|
||||
const html = '<p>' + opener + '</p>' + (totals ? '<p>' + totals + '</p>' : '')
|
||||
+ '<p>' + next.replace(/(https:\/\/[^\s]+)/g, '<a href="$1">$1</a>') + '</p>'
|
||||
+ '<p><b>What each one did:</b></p><ul>' + list.map(c => '<li>' + esc(c.name || ('campaign #' + c.id)) + ' (' + esc(c.type || 'ad') + '): '
|
||||
+ money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'
|
||||
+ (n0(c.imps) ? ', ' + money(n0(c.imps)) + ' ' + unit(c) : '') + (n0(c.clicks) ? ', ' + money(n0(c.clicks)) + ' clicks' : '') + esc(videoNote(c)) + '</li>').join('') + '</ul>'
|
||||
+ ladderHtml()
|
||||
+ '<p style="color:#556">Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.</p>';
|
||||
return { subject, text, html };
|
||||
}
|
||||
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
// ---- the pass -------------------------------------------------------------------------------
|
||||
let running = false;
|
||||
async function tick() {
|
||||
if (running || !cfg().on) return { sent: 0 };
|
||||
running = true;
|
||||
try {
|
||||
const c = cfg();
|
||||
const all = await X.ads.adminList(1000);
|
||||
const mine = all.filter(x => !x.house && x.owner);
|
||||
// group the campaigns that need a notice by owner, so one person gets one email
|
||||
const due = new Map(); // owner -> { state -> [campaigns] }
|
||||
for (const cm of mine) {
|
||||
const b = n0(cm.budget); if (b <= 0) continue;
|
||||
let state = null;
|
||||
if (cm.status === 'out') state = 'out';
|
||||
else if (cm.status === 'active' && delivered(cm) >= b * (c.lowPct / 100)) state = 'low';
|
||||
if (!state) continue;
|
||||
if (S.sent[key(cm.id, state)]) continue;
|
||||
if (state === 'low' && S.sent[key(cm.id, 'out')]) continue; // already past it
|
||||
const g = due.get(cm.owner) || {}; (g[state] = g[state] || []).push(cm); due.set(cm.owner, g);
|
||||
}
|
||||
let sent = 0;
|
||||
for (const [owner, byState] of due) {
|
||||
if (sent >= MAX_PER_TICK) break;
|
||||
for (const state of ['out', 'low']) {
|
||||
const list = byState[state]; if (!list || !list.length) continue;
|
||||
const ok = await notify(owner, list, state).catch(e => { console.error('refill notify', owner, e.message); return false; });
|
||||
if (ok) sent++;
|
||||
break; // one state per owner per pass: "out" is the louder message
|
||||
}
|
||||
}
|
||||
await checkConversions();
|
||||
sent += await followUps(all, sent);
|
||||
if (sent) { save(); console.log('refill notices sent:', sent); }
|
||||
return { sent };
|
||||
} finally { running = false; }
|
||||
}
|
||||
|
||||
// Seven days after an "out" notice that went unanswered: if the owner still holds enough credits to relaunch
|
||||
// and has nothing running, one more nudge. Once per out-record; tracked like any other send.
|
||||
async function followUps(all, alreadySent) {
|
||||
S.records = S.records || {};
|
||||
const now = Date.now(); let sent = 0;
|
||||
const due = Object.values(S.records).filter(r => r.state === 'out' && !r.converted && !r.followUp && now - r.ts >= IDLE_AFTER && now - r.ts < LOOKBACK);
|
||||
for (const r of due) {
|
||||
if (alreadySent + sent >= MAX_PER_TICK) break;
|
||||
const running = all.some(c => c.owner === r.owner && !c.house && c.status === 'active');
|
||||
if (running) { r.followUp = 'running'; continue; } // something is live: no nudge, and never revisit this record
|
||||
let credits = 0; try { credits = await X.creditsFor(r.owner); } catch (e) {}
|
||||
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
|
||||
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
|
||||
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; });
|
||||
r.followUp = ok ? S.seq : 'failed';
|
||||
if (ok) sent++;
|
||||
}
|
||||
if (due.length) save();
|
||||
return sent;
|
||||
}
|
||||
|
||||
async function notify(owner, list, state, parentId) {
|
||||
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
|
||||
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
|
||||
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
|
||||
const m = await compose(owner, list, state, credits);
|
||||
// the on-site notice always goes; the email is skipped for anyone who opted out
|
||||
try { await X.message(owner, m.subject, m.html); } catch (e) { console.error('refill inbox', e.message); }
|
||||
if (!stopped && X.mailer.hasKey()) { try { await X.mailer.send(owner, m.subject, m.text); } catch (e) { console.error('refill mail', e.message); } }
|
||||
const rec = {
|
||||
id: ++S.seq, owner, state, ts: Date.now(), emailed: !stopped && X.mailer.hasKey(),
|
||||
campaigns: list.map(c => ({ id: c.id, name: c.name || null, type: c.type || null, budget: Math.round(n0(c.budget)), delivered: Math.round(delivered(c)), imps: n0(c.imps), clicks: n0(c.clicks) })),
|
||||
creditsAtSend: Math.round(credits), memberId: acct.memberId || 0, converted: null, parent: parentId || null,
|
||||
};
|
||||
if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = rec.id;
|
||||
S.records = S.records || {}; S.records[rec.id] = rec;
|
||||
save();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- did anything come of it? ---------------------------------------------------------------
|
||||
// Polled rather than hooked: a relaunch, a top-up and a purchase all show up in state, and polling
|
||||
// cannot miss one because a call site was forgotten.
|
||||
async function checkConversions() {
|
||||
S.records = S.records || {};
|
||||
const open = Object.values(S.records).filter(r => !r.converted && Date.now() - r.ts < LOOKBACK);
|
||||
if (!open.length) return;
|
||||
const all = await X.ads.adminList(1000);
|
||||
const evs = (X.chain.recentEvents(4000) || []).filter(e => e.type === 'Purchase');
|
||||
for (const r of open) {
|
||||
const since = r.ts;
|
||||
// 1. bought credits (any position on the account)
|
||||
let ids = [r.memberId].filter(Boolean);
|
||||
try { const ps = await X.accounts.positions(r.owner); ids = [...new Set([...ids, ...ps.map(p => p.memberId).filter(Boolean)])]; } catch (e) {}
|
||||
const buy = evs.find(e => ids.includes(Number(e.id || e.buyerId)) && norm(e) > since);
|
||||
if (buy) { mark(r, 'purchase', { cents: n0(buy.priceCents), tx: buy.tx || null }); continue; }
|
||||
// 2. put an ad back up. Only two things count: a campaign created after we wrote to them, or one of
|
||||
// the very campaigns we named coming back to life. An unrelated ad that was already running is not a
|
||||
// response to the email, and counting it was inflating the rate to meaninglessness.
|
||||
const fresh = all.find(c => c.owner === r.owner && !c.house && n0(c.created) > since);
|
||||
if (fresh) { mark(r, 'relaunch', { campaignId: fresh.id, name: fresh.name || null }); continue; }
|
||||
// only meaningful for an ad that had actually stopped: a "running low" ad is still active by
|
||||
// definition, so counting that as a response would mark every low notice converted on the spot
|
||||
if (r.state === 'out' || r.state === 'idle') {
|
||||
const revived = all.find(c => c.status === 'active' && r.campaigns.some(x => x.id === c.id) && delivered(c) < n0(c.budget));
|
||||
if (revived) { mark(r, 'resumed', { campaignId: revived.id, name: revived.name || null }); continue; }
|
||||
}
|
||||
const topped = all.find(c => { const was = r.campaigns.find(x => x.id === c.id); return was && n0(c.budget) > was.budget; });
|
||||
if (topped) { mark(r, 'topup', { campaignId: topped.id, added: Math.round(n0(topped.budget) - r.campaigns.find(x => x.id === topped.id).budget) }); }
|
||||
}
|
||||
save();
|
||||
}
|
||||
const norm = e => { let t = n0(e.ts); if (t < 1e12) t *= 1000; return t; };
|
||||
function mark(r, kind, detail) {
|
||||
r.converted = { kind, at: Date.now(), hours: Math.round((Date.now() - r.ts) / 3600000), detail: detail || null };
|
||||
console.log('refill converted:', r.owner, kind, 'after', r.converted.hours + 'h');
|
||||
}
|
||||
|
||||
// ---- what the admin sees --------------------------------------------------------------------
|
||||
function stats() {
|
||||
S.records = S.records || {};
|
||||
const recs = Object.values(S.records).sort((a, b) => b.ts - a.ts);
|
||||
const by = { out: { sent: 0, converted: 0 }, low: { sent: 0, converted: 0 }, idle: { sent: 0, converted: 0 } };
|
||||
const kinds = {};
|
||||
let revenueCents = 0, hours = [];
|
||||
for (const r of recs) {
|
||||
const b = by[r.state] || (by[r.state] = { sent: 0, converted: 0 });
|
||||
b.sent++;
|
||||
if (r.converted) {
|
||||
b.converted++; kinds[r.converted.kind] = (kinds[r.converted.kind] || 0) + 1;
|
||||
hours.push(r.converted.hours);
|
||||
if (r.converted.kind === 'purchase') revenueCents += n0(r.converted.detail && r.converted.detail.cents);
|
||||
}
|
||||
}
|
||||
const conv = recs.length ? Math.round(recs.filter(r => r.converted).length / recs.length * 100) : 0;
|
||||
return {
|
||||
enabled: cfg().on, lowPct: cfg().lowPct,
|
||||
totals: { sent: recs.length, converted: recs.filter(r => r.converted).length, ratePct: conv,
|
||||
purchasesUsd: Math.round(revenueCents / 100), medianHours: hours.length ? hours.sort((a, b) => a - b)[Math.floor(hours.length / 2)] : null },
|
||||
byState: by, byKind: kinds,
|
||||
recent: recs.slice(0, 60).map(r => ({ id: r.id, owner: r.owner, state: r.state, at: r.ts, emailed: r.emailed,
|
||||
credits: r.creditsAtSend, campaigns: r.campaigns.length, imps: r.campaigns.reduce((n, c) => n + c.imps, 0),
|
||||
converted: r.converted })),
|
||||
};
|
||||
}
|
||||
|
||||
// clears conversion verdicts so the corrected rule can re-decide them (used once after the
|
||||
// first run, where "already had another ad running" was wrongly counted as a relaunch)
|
||||
function resetConversions(kinds) {
|
||||
S.records = S.records || {};
|
||||
const want = new Set(kinds && kinds.length ? kinds : ['relaunch']);
|
||||
let n = 0;
|
||||
for (const r of Object.values(S.records)) if (r.converted && want.has(r.converted.kind)) { r.converted = null; n++; }
|
||||
save();
|
||||
return { cleared: n };
|
||||
}
|
||||
|
||||
module.exports = { init, tick, stats, resetConversions, PACKS };
|
||||
// Campaign refill notices (Marty, 2026-09-22). Two moments in an advertiser's life were silent:
|
||||
// the ad running low, and the ad stopping dead. 70 member campaigns had already delivered their whole
|
||||
// budget and stopped with nobody told, and half of those owners were still holding credits they could
|
||||
// have spent the same minute. This watches for both moments, writes one email and one on-site notice
|
||||
// per owner (never one per campaign), leads with what the ad actually delivered, and puts the bonus
|
||||
// ladder in front of them at the only moment it is persuasive.
|
||||
//
|
||||
// Everything sent is recorded, and every send is then watched for what the owner did next: relaunched
|
||||
// a campaign, topped one up, or bought credits. That is the conversion history, in data/refill.json.
|
||||
//
|
||||
// Settings (siteConfig): refillNotices '1'|'0' (default on), refillLowPct (80) the share of budget
|
||||
// delivered that counts as "running low".
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let X = {}, FILE = null, S = null;
|
||||
const DAY = 86400000;
|
||||
const LOOKBACK = 45 * DAY; // a send older than this stops being watched for a conversion
|
||||
const MAX_PER_TICK = 25; // owners emailed in one pass, so a backfill goes out in batches
|
||||
const IDLE_AFTER = 7 * DAY; // follow-up: an "out" notice this old, still unanswered, with credits idle and nothing running (Marty, 2026-09-30)
|
||||
const IDLE_MIN_CREDITS = 100; // enough to relaunch without buying
|
||||
|
||||
function init(opts) { X = opts; FILE = path.join(opts.dataDir, 'refill.json'); S = load(); }
|
||||
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { sent: {}, seq: 0 }; } }
|
||||
function save() { try { fs.writeFileSync(FILE, JSON.stringify(S)); } catch (e) {} }
|
||||
|
||||
function cfg() {
|
||||
const c = (X.siteConfig && X.siteConfig()) || {};
|
||||
return {
|
||||
on: String(c.refillNotices == null ? '1' : c.refillNotices) === '1',
|
||||
lowPct: Math.min(99, Math.max(50, Number(c.refillLowPct) || 80)),
|
||||
fridayOn: String(c.fridayPromo == null ? '1' : c.fridayPromo) === '1',
|
||||
fridayPct: Number(c.fridayBonusPct) || 20,
|
||||
};
|
||||
}
|
||||
|
||||
const SITE = 'https://instantadpay.com';
|
||||
const n0 = v => (typeof v === 'number' && isFinite(v) ? v : 0);
|
||||
const money = n => Number(n || 0).toLocaleString('en-US');
|
||||
const delivered = c => n0(c.spent) + n0(c.accrued);
|
||||
// video campaigns count watches, not impressions, and the relaunch maths only makes sense with the per-watch price (Marty, 2026-09-30)
|
||||
const unit = c => c.type === 'video' ? 'watches' : 'impressions';
|
||||
function videoNote(c) {
|
||||
if (c.type !== 'video') return '';
|
||||
const secs = Number(c.body) || 0; let cost = 0;
|
||||
try { cost = ((X.ads.rates().videoTiers || []).find(t => t.secs === secs) || {}).cost || 0; } catch (e) {}
|
||||
if (!secs || !cost) return '';
|
||||
return ' (' + secs + '-second video at ' + cost + ' credits a watch: every ' + money(cost * 100) + ' credits buys about 100 more watches)';
|
||||
}
|
||||
const key = (id, state) => id + ':' + state;
|
||||
|
||||
// the five packages and what each dollar buys, so the ladder is never hand-typed
|
||||
const PACKS = [
|
||||
{ price: 5, credits: 500, bonus: 0 },
|
||||
{ price: 20, credits: 2000, bonus: 0 },
|
||||
{ price: 50, credits: 5500, bonus: 10 },
|
||||
{ price: 100, credits: 12000, bonus: 20 },
|
||||
{ price: 250, credits: 32500, bonus: 30 },
|
||||
];
|
||||
|
||||
function ladderText() {
|
||||
const c = cfg();
|
||||
const rows = PACKS.map(p => ' $' + p.price + ' -> ' + money(p.credits) + ' credits' + (p.bonus ? ' (' + p.bonus + '% more per dollar)' : ''));
|
||||
let s = 'Ad packages, and what each one adds to your balance:\n\n' + rows.join('\n')
|
||||
+ '\n\nA credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.';
|
||||
if (c.fridayOn) s += '\n\nFive Dollar Friday: any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.';
|
||||
return s;
|
||||
}
|
||||
function ladderHtml() {
|
||||
const c = cfg();
|
||||
const rows = PACKS.map(p => '<tr><td style="padding:6px 14px 6px 0"><b>$' + p.price + '</b></td><td style="padding:6px 14px 6px 0">' + money(p.credits)
|
||||
+ ' credits</td><td style="padding:6px 0;color:#0E8F72">' + (p.bonus ? p.bonus + '% more per dollar' : '') + '</td></tr>').join('');
|
||||
return '<p><b>Ad packages, and what each one adds to your balance:</b></p><table style="border-collapse:collapse">' + rows + '</table>'
|
||||
+ '<p style="color:#556">A credit is one cent of delivery, so the bigger packages are simply more delivery for the same dollar.</p>'
|
||||
+ (c.fridayOn ? '<p><b>Five Dollar Friday:</b> any package from $5 up, bought on a Friday, earns an extra ' + c.fridayPct + '% in credits on top of the above.</p>' : '');
|
||||
}
|
||||
|
||||
// what one owner's batch of campaigns says in the body
|
||||
function describe(list) {
|
||||
return list.map(c => {
|
||||
const bits = [money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'];
|
||||
if (n0(c.imps)) bits.push(money(n0(c.imps)) + ' ' + unit(c));
|
||||
if (n0(c.clicks)) bits.push(money(n0(c.clicks)) + ' clicks');
|
||||
return ' "' + (c.name || c.title || ('campaign #' + c.id)) + '" (' + (c.type || 'ad') + '): ' + bits.join(', ') + videoNote(c);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
async function compose(owner, list, state, credits) {
|
||||
const many = list.length > 1;
|
||||
const totalImps = list.reduce((n, c) => n + n0(c.imps), 0);
|
||||
const totalClicks = list.reduce((n, c) => n + n0(c.clicks), 0);
|
||||
const canRelaunch = credits >= 100;
|
||||
const subject = state === 'idle' ? money(Math.round(credits)) + ' credits are sitting idle on your InstantAdPay account'
|
||||
: state === 'out'
|
||||
? (many ? 'Your InstantAdPay ads have finished delivering' : 'Your ad "' + (list[0].name || 'campaign') + '" has finished delivering')
|
||||
: (many ? 'Your InstantAdPay ads are nearly out of credits' : 'Your ad "' + (list[0].name || 'campaign') + '" is nearly out of credits');
|
||||
const opener = state === 'idle'
|
||||
? 'A week ago ' + (many ? 'your ads' : 'your ad "' + (list[0].name || 'campaign') + '"') + ' finished delivering, and nothing has run since. Your credits are still there, and nobody is seeing your link while they sit.'
|
||||
: state === 'out'
|
||||
? (many ? 'Your ' + list.length + ' campaigns have spent their full budget and stopped. They delivered everything you paid for.'
|
||||
: 'That campaign spent its full budget and stopped. It delivered everything you paid for.')
|
||||
: (many ? 'Your ' + list.length + ' campaigns are close to spending their full budget. When they do, they stop.'
|
||||
: 'That campaign is close to spending its full budget. When it does, it stops.');
|
||||
const totals = (totalImps || totalClicks)
|
||||
? 'Between them so far: ' + money(totalImps) + (list.every(c => c.type === 'video') ? ' watches' : ' impressions') + ' and ' + money(totalClicks) + ' clicks.'
|
||||
: '';
|
||||
const next = state === 'idle'
|
||||
? money(Math.round(credits)) + ' credits are ready to run. A banner or text ad takes a minute to set up and starts showing the moment you launch it, no purchase needed: ' + SITE + '/my#campaigns'
|
||||
: canRelaunch
|
||||
? 'You still have ' + money(Math.round(credits)) + ' credits in your balance, which is enough to put an ad back up right now without buying anything. Open Campaigns and start one: ' + SITE + '/my#campaigns'
|
||||
: 'Your balance is down to ' + money(Math.round(credits)) + ' credits, so the next campaign needs a top-up first: ' + SITE + '/my#buy';
|
||||
const lines = [opener, totals, next, ladderText(),
|
||||
'Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger at ' + SITE + '/ledger.'];
|
||||
const text = lines.filter(Boolean).join('\n\n') + '\n\nWhat each one did:\n' + describe(list) + '\n\nInstantAdPay';
|
||||
const html = '<p>' + opener + '</p>' + (totals ? '<p>' + totals + '</p>' : '')
|
||||
+ '<p>' + next.replace(/(https:\/\/[^\s]+)/g, '<a href="$1">$1</a>') + '</p>'
|
||||
+ '<p><b>What each one did:</b></p><ul>' + list.map(c => '<li>' + esc(c.name || ('campaign #' + c.id)) + ' (' + esc(c.type || 'ad') + '): '
|
||||
+ money(Math.round(delivered(c))) + ' of ' + money(Math.round(n0(c.budget))) + ' credits delivered'
|
||||
+ (n0(c.imps) ? ', ' + money(n0(c.imps)) + ' ' + unit(c) : '') + (n0(c.clicks) ? ', ' + money(n0(c.clicks)) + ' clicks' : '') + esc(videoNote(c)) + '</li>').join('') + '</ul>'
|
||||
+ ladderHtml()
|
||||
+ '<p style="color:#556">Every package pays your sponsor line in the same on-chain transaction, and every payout is on the public ledger.</p>';
|
||||
return { subject, text, html };
|
||||
}
|
||||
const esc = s => String(s == null ? '' : s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
|
||||
// ---- the pass -------------------------------------------------------------------------------
|
||||
let running = false;
|
||||
async function tick() {
|
||||
if (running || !cfg().on) return { sent: 0 };
|
||||
running = true;
|
||||
try {
|
||||
const c = cfg();
|
||||
const all = await X.ads.adminList(1000);
|
||||
const mine = all.filter(x => !x.house && x.owner && x.type !== 'game'); // game purchases are flat buys, not ads that ran out
|
||||
// group the campaigns that need a notice by owner, so one person gets one email
|
||||
const due = new Map(); // owner -> { state -> [campaigns] }
|
||||
for (const cm of mine) {
|
||||
const b = n0(cm.budget); if (b <= 0) continue;
|
||||
let state = null;
|
||||
if (cm.status === 'out') state = 'out';
|
||||
else if (cm.status === 'active' && delivered(cm) >= b * (c.lowPct / 100)) state = 'low';
|
||||
if (!state) continue;
|
||||
if (S.sent[key(cm.id, state)]) continue;
|
||||
if (state === 'low' && S.sent[key(cm.id, 'out')]) continue; // already past it
|
||||
const g = due.get(cm.owner) || {}; (g[state] = g[state] || []).push(cm); due.set(cm.owner, g);
|
||||
}
|
||||
let sent = 0;
|
||||
for (const [owner, byState] of due) {
|
||||
if (sent >= MAX_PER_TICK) break;
|
||||
for (const state of ['out', 'low']) {
|
||||
const list = byState[state]; if (!list || !list.length) continue;
|
||||
const ok = await notify(owner, list, state).catch(e => { console.error('refill notify', owner, e.message); return false; });
|
||||
if (ok) sent++;
|
||||
break; // one state per owner per pass: "out" is the louder message
|
||||
}
|
||||
}
|
||||
await checkConversions();
|
||||
sent += await followUps(all, sent);
|
||||
if (sent) { save(); console.log('refill notices sent:', sent); }
|
||||
return { sent };
|
||||
} finally { running = false; }
|
||||
}
|
||||
|
||||
// Seven days after an "out" notice that went unanswered: if the owner still holds enough credits to relaunch
|
||||
// and has nothing running, one more nudge. Once per out-record; tracked like any other send.
|
||||
async function followUps(all, alreadySent) {
|
||||
S.records = S.records || {};
|
||||
const now = Date.now(); let sent = 0;
|
||||
const due = Object.values(S.records).filter(r => r.state === 'out' && !r.converted && !r.followUp && now - r.ts >= IDLE_AFTER && now - r.ts < LOOKBACK);
|
||||
for (const r of due) {
|
||||
if (alreadySent + sent >= MAX_PER_TICK) break;
|
||||
const running = all.some(c => c.owner === r.owner && !c.house && c.status === 'active');
|
||||
if (running) { r.followUp = 'running'; continue; } // something is live: no nudge, and never revisit this record
|
||||
let credits = 0; try { credits = await X.creditsFor(r.owner); } catch (e) {}
|
||||
if (credits < IDLE_MIN_CREDITS) { r.followUp = 'nocredits'; continue; }
|
||||
const list = r.campaigns.map(x => all.find(c => c.id === x.id) || x);
|
||||
const ok = await notify(r.owner, list, 'idle', r.id).catch(e => { console.error('refill follow-up', r.owner, e.message); return false; });
|
||||
r.followUp = ok ? S.seq : 'failed';
|
||||
if (ok) sent++;
|
||||
}
|
||||
if (due.length) save();
|
||||
return sent;
|
||||
}
|
||||
|
||||
async function notify(owner, list, state, parentId) {
|
||||
const acct = await X.accounts.byEmail(owner); if (!acct) return false;
|
||||
const stopped = X.drip && X.drip.isUnsubscribed ? await X.drip.isUnsubscribed(owner).catch(() => false) : false;
|
||||
let credits = 0; try { credits = await X.creditsFor(owner); } catch (e) {}
|
||||
const m = await compose(owner, list, state, credits);
|
||||
// the on-site notice always goes; the email is skipped for anyone who opted out
|
||||
try { await X.message(owner, m.subject, m.html); } catch (e) { console.error('refill inbox', e.message); }
|
||||
if (!stopped && X.mailer.hasKey()) { try { await X.mailer.send(owner, m.subject, m.text); } catch (e) { console.error('refill mail', e.message); } }
|
||||
const rec = {
|
||||
id: ++S.seq, owner, state, ts: Date.now(), emailed: !stopped && X.mailer.hasKey(),
|
||||
campaigns: list.map(c => ({ id: c.id, name: c.name || null, type: c.type || null, budget: Math.round(n0(c.budget)), delivered: Math.round(delivered(c)), imps: n0(c.imps), clicks: n0(c.clicks) })),
|
||||
creditsAtSend: Math.round(credits), memberId: acct.memberId || 0, converted: null, parent: parentId || null,
|
||||
};
|
||||
if (state !== 'idle') for (const cm of list) S.sent[key(cm.id, state)] = rec.id;
|
||||
S.records = S.records || {}; S.records[rec.id] = rec;
|
||||
save();
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- did anything come of it? ---------------------------------------------------------------
|
||||
// Polled rather than hooked: a relaunch, a top-up and a purchase all show up in state, and polling
|
||||
// cannot miss one because a call site was forgotten.
|
||||
async function checkConversions() {
|
||||
S.records = S.records || {};
|
||||
const open = Object.values(S.records).filter(r => !r.converted && Date.now() - r.ts < LOOKBACK);
|
||||
if (!open.length) return;
|
||||
const all = await X.ads.adminList(1000);
|
||||
const evs = (X.chain.recentEvents(4000) || []).filter(e => e.type === 'Purchase');
|
||||
for (const r of open) {
|
||||
const since = r.ts;
|
||||
// 1. bought credits (any position on the account)
|
||||
let ids = [r.memberId].filter(Boolean);
|
||||
try { const ps = await X.accounts.positions(r.owner); ids = [...new Set([...ids, ...ps.map(p => p.memberId).filter(Boolean)])]; } catch (e) {}
|
||||
const buy = evs.find(e => ids.includes(Number(e.id || e.buyerId)) && norm(e) > since);
|
||||
if (buy) { mark(r, 'purchase', { cents: n0(buy.priceCents), tx: buy.tx || null }); continue; }
|
||||
// 2. put an ad back up. Only two things count: a campaign created after we wrote to them, or one of
|
||||
// the very campaigns we named coming back to life. An unrelated ad that was already running is not a
|
||||
// response to the email, and counting it was inflating the rate to meaninglessness.
|
||||
const fresh = all.find(c => c.owner === r.owner && !c.house && n0(c.created) > since);
|
||||
if (fresh) { mark(r, 'relaunch', { campaignId: fresh.id, name: fresh.name || null }); continue; }
|
||||
// only meaningful for an ad that had actually stopped: a "running low" ad is still active by
|
||||
// definition, so counting that as a response would mark every low notice converted on the spot
|
||||
if (r.state === 'out' || r.state === 'idle') {
|
||||
const revived = all.find(c => c.status === 'active' && r.campaigns.some(x => x.id === c.id) && delivered(c) < n0(c.budget));
|
||||
if (revived) { mark(r, 'resumed', { campaignId: revived.id, name: revived.name || null }); continue; }
|
||||
}
|
||||
const topped = all.find(c => { const was = r.campaigns.find(x => x.id === c.id); return was && n0(c.budget) > was.budget; });
|
||||
if (topped) { mark(r, 'topup', { campaignId: topped.id, added: Math.round(n0(topped.budget) - r.campaigns.find(x => x.id === topped.id).budget) }); }
|
||||
}
|
||||
save();
|
||||
}
|
||||
const norm = e => { let t = n0(e.ts); if (t < 1e12) t *= 1000; return t; };
|
||||
function mark(r, kind, detail) {
|
||||
r.converted = { kind, at: Date.now(), hours: Math.round((Date.now() - r.ts) / 3600000), detail: detail || null };
|
||||
console.log('refill converted:', r.owner, kind, 'after', r.converted.hours + 'h');
|
||||
}
|
||||
|
||||
// ---- what the admin sees --------------------------------------------------------------------
|
||||
function stats() {
|
||||
S.records = S.records || {};
|
||||
const recs = Object.values(S.records).sort((a, b) => b.ts - a.ts);
|
||||
const by = { out: { sent: 0, converted: 0 }, low: { sent: 0, converted: 0 }, idle: { sent: 0, converted: 0 } };
|
||||
const kinds = {};
|
||||
let revenueCents = 0, hours = [];
|
||||
for (const r of recs) {
|
||||
const b = by[r.state] || (by[r.state] = { sent: 0, converted: 0 });
|
||||
b.sent++;
|
||||
if (r.converted) {
|
||||
b.converted++; kinds[r.converted.kind] = (kinds[r.converted.kind] || 0) + 1;
|
||||
hours.push(r.converted.hours);
|
||||
if (r.converted.kind === 'purchase') revenueCents += n0(r.converted.detail && r.converted.detail.cents);
|
||||
}
|
||||
}
|
||||
const conv = recs.length ? Math.round(recs.filter(r => r.converted).length / recs.length * 100) : 0;
|
||||
return {
|
||||
enabled: cfg().on, lowPct: cfg().lowPct,
|
||||
totals: { sent: recs.length, converted: recs.filter(r => r.converted).length, ratePct: conv,
|
||||
purchasesUsd: Math.round(revenueCents / 100), medianHours: hours.length ? hours.sort((a, b) => a - b)[Math.floor(hours.length / 2)] : null },
|
||||
byState: by, byKind: kinds,
|
||||
recent: recs.slice(0, 60).map(r => ({ id: r.id, owner: r.owner, state: r.state, at: r.ts, emailed: r.emailed,
|
||||
credits: r.creditsAtSend, campaigns: r.campaigns.length, imps: r.campaigns.reduce((n, c) => n + c.imps, 0),
|
||||
converted: r.converted })),
|
||||
};
|
||||
}
|
||||
|
||||
// clears conversion verdicts so the corrected rule can re-decide them (used once after the
|
||||
// first run, where "already had another ad running" was wrongly counted as a relaunch)
|
||||
function resetConversions(kinds) {
|
||||
S.records = S.records || {};
|
||||
const want = new Set(kinds && kinds.length ? kinds : ['relaunch']);
|
||||
let n = 0;
|
||||
for (const r of Object.values(S.records)) if (r.converted && want.has(r.converted.kind)) { r.converted = null; n++; }
|
||||
save();
|
||||
return { cleared: n };
|
||||
}
|
||||
|
||||
module.exports = { init, tick, stats, resetConversions, PACKS };
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
# Gem Kingdom on InstantAdPay (2026-10-01): sign-in hand-off, Games card, and the Crown shop checkout with its return trip.
|
||||
P = 'D:/Projects/HighRisk/onchain-ad-membership/site/server.js'
|
||||
J = 'D:/Projects/HighRisk/onchain-ad-membership/site/public/assets/my.js'
|
||||
H = 'D:/Projects/HighRisk/onchain-ad-membership/site/public/my.html'
|
||||
def patch(path, edits):
|
||||
s = open(path, encoding='utf-8').read()
|
||||
for a, b in edits:
|
||||
n = s.count(a)
|
||||
if n != 1: raise SystemExit('%s: anchor count %d: %s' % (path, n, a[:100]))
|
||||
s = s.replace(a, b)
|
||||
open(path, 'w', encoding='utf-8').write(s)
|
||||
|
||||
HELPERS = r"""
|
||||
// -- Gem Kingdom (2026-10-01): sign-in hand-off + the Crown shop checkout. Same token shape as Drip Runner, its own
|
||||
// secret GK_SSO_SECRET (also set on the game). The game mints a 'gk-buy' order; this site shows the member what it
|
||||
// costs, spends the ad credits through ads.gamePurchase (credit log + on-chain burn like any flat buy), then signs a
|
||||
// 'gk-receipt' back: as a redirect to the game AND as a server-to-server callback, so Crowns land even if they never return.
|
||||
const GK_SECRET = () => String(process.env.GK_SSO_SECRET || '').trim();
|
||||
const GK_URL = () => String(process.env.GK_URL || 'https://gemkingdom.app').replace(/\/+$/, '');
|
||||
const gkSign = p => drB64u(crypto.createHmac('sha256', GK_SECRET()).update(p).digest());
|
||||
function gkMint(claims, ttlMs) { const payload = JSON.stringify(Object.assign({ iat: Date.now(), exp: Date.now() + (ttlMs || 300000), nonce: crypto.randomBytes(12).toString('hex') }, claims)); return drB64u(payload) + '.' + gkSign(payload); }
|
||||
function gkOpen(token) {
|
||||
if (GK_SECRET().length < 32) return { error: 'Gem Kingdom is not connected yet.' };
|
||||
const [p, sig] = String(token || '').split('.'); if (!p || !sig) return { error: 'That link is not valid.' };
|
||||
let payload; try { payload = Buffer.from(String(p).replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString('utf8'); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
const want = gkSign(payload); if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { error: 'That link is not valid.' };
|
||||
let c; try { c = JSON.parse(payload); } catch (e) { return { error: 'That link is not valid.' }; }
|
||||
if (!c.exp || Date.now() > c.exp) return { error: 'That order has expired. Go back to Gem Kingdom and open the shop again.' };
|
||||
return { ok: true, claims: c };
|
||||
}
|
||||
const gkOrders = persistedMap('gkorders'); // order -> { status: 'paying'|'paid', email, campaignId, ts }
|
||||
const gkEsc = s => String(s == null ? '' : s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[ch]));
|
||||
function gkPage(res, code, title, inner) {
|
||||
res.writeHead(code, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }));
|
||||
res.end('<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>' + gkEsc(title) + ' | InstantAdPay</title>'
|
||||
+ '<style>body{margin:0;background:radial-gradient(ellipse 80% 50% at 50% 0%,#3B1E6E,#1B1026 70%);color:#3B1A0A;font:16px/1.5 system-ui,-apple-system,Segoe UI,sans-serif;min-height:100vh;display:grid;place-items:center;padding:24px 16px;box-sizing:border-box}'
|
||||
+ '.card{width:100%;max-width:440px;background:linear-gradient(180deg,#F1E2BF,#E3CC98);border-radius:12px;box-shadow:0 0 0 3px #6B4220,0 0 0 8px #3A2214,0 24px 60px rgba(0,0,0,.6);padding:26px 22px;text-align:center}'
|
||||
+ 'h1{font:700 26px/1.2 Georgia,serif;margin:0 0 6px}.sub{color:#5A3416;font-weight:700;margin:0 0 16px}.big{font:700 40px/1 Georgia,serif;color:#9A5A00;margin:8px 0}'
|
||||
+ '.row{display:flex;justify-content:space-between;padding:8px 0;border-bottom:1px solid rgba(90,52,22,.25);font-weight:700}.row span:first-child{color:#6A4422}'
|
||||
+ '.btn{display:block;width:100%;box-sizing:border-box;margin-top:16px;padding:14px;border:0;border-radius:12px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font:700 18px Georgia,serif;text-decoration:none;cursor:pointer;box-shadow:0 4px 0 #6A0E1C}'
|
||||
+ '.btn.blue{background:linear-gradient(180deg,#3B6FE8,#1D3FA8);box-shadow:0 4px 0 #10205A}.alt{display:inline-block;margin-top:14px;color:#5A3416;font-weight:700}.warn{color:#8A2A12;font-weight:800}.fine{font-size:13px;color:#6A4422;margin-top:14px}</style></head>'
|
||||
+ '<body><main class="card">' + inner + '</main></body></html>');
|
||||
}
|
||||
function gkFormBody(req) { return new Promise((ok, no) => { let d = ''; req.on('data', ch => { d += ch; if (d.length > 20000) req.destroy(); }); req.on('end', () => ok(new URLSearchParams(d))); req.on('error', no); }); }
|
||||
const gkCookie = (k, v, maxAge) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + maxAge + (IS_PROD ? '; Secure' : '');
|
||||
async function gkCallback(cbUrl, receipt) {
|
||||
if (!String(cbUrl || '').startsWith(GK_URL() + '/')) return false;
|
||||
try { const r = await fetch(cbUrl, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ t: receipt }), signal: AbortSignal.timeout(8000) }); return r.ok; } catch (e) { console.warn('gemkingdom callback', e.message); return false; }
|
||||
}
|
||||
"""
|
||||
|
||||
ROUTES = r""" // -- Gem Kingdom hand-off (2026-10-01): sign the member across; the game verifies with GK_SSO_SECRET
|
||||
if (p === '/api/my/gemkingdom' && req.method === 'GET') {
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Set-Cookie': gkCookie('iap.return', 'gemkingdom', 1800), 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
if (GK_SECRET().length < 32) return json(res, 503, { error: 'Gem Kingdom is not connected yet.' });
|
||||
const acct = await accounts.byEmail(s.email);
|
||||
const tok = gkMint({ memberId: Number((acct && acct.memberId) || s.memberId || 0), email: String(s.email).toLowerCase(), username: (acct && acct.username) || null, wallet: (acct && acct.address) || null });
|
||||
res.writeHead(302, { Location: GK_URL() + '/auth?t=' + tok, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
// -- the Crown shop checkout: confirm, spend the credits, sign a receipt back to the game
|
||||
if (p === '/gk/shop' && req.method === 'GET') {
|
||||
const t = u.searchParams.get('t') || ''; const r = gkOpen(t);
|
||||
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Back to Gem Kingdom</a>');
|
||||
const c = r.claims; if (c.kind !== 'gk-buy' || !c.order || !(c.credits > 0) || !(c.crowns > 0)) return gkPage(res, 400, 'Order problem', '<h1>That is not a Crown order</h1>');
|
||||
const done = gkOrders.get(c.order);
|
||||
if (done && done.status === 'paid') { const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: c.email, crowns: c.crowns, credits: c.credits, ref: done.campaignId }, 24 * 3600000); res.writeHead(302, { Location: c.ret + '?t=' + rc, 'Cache-Control': 'no-store' }); return res.end(); }
|
||||
const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email) { res.writeHead(302, { Location: '/my', 'Cache-Control': 'no-store', 'Set-Cookie': [gkCookie('iap.gkshop', t, 7200), gkCookie('iap.return', 'gkshop', 1800)] }); return res.end(); }
|
||||
if (String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Different account', '<h1>Different account</h1><p class="sub">This order was started by the Gem Kingdom player ' + gkEsc(c.email) + ', but you are signed in to InstantAdPay as ' + gkEsc(s.email) + '. Sign in with the same account in both places.</p><a class="btn blue" href="' + GK_URL() + '/play">Back to Gem Kingdom</a>');
|
||||
const { ids } = await myMemberIds(s); const bal = await ads.balances(ids, s.email);
|
||||
const free = (bal.earned || 0) + (bal.credited || 0); const best = (bal.per || []).slice().sort((a, b) => b.avail - a.avail)[0] || { avail: 0 };
|
||||
const can = free >= c.credits || best.avail >= c.credits; const usable = Math.max(free, best.avail);
|
||||
const dollars = '$' + (c.credits / 100).toFixed(c.credits % 100 ? 2 : 0);
|
||||
const head = '<p class="sub">Gem Kingdom · Crown Shop</p><h1>' + gkEsc(c.label || 'Crowns') + '</h1><div class="big">' + Number(c.crowns) + ' Crowns</div>'
|
||||
+ '<div class="row"><span>Price</span><span>' + Number(c.credits).toLocaleString('en-US') + ' ad credits (' + dollars + ')</span></div>'
|
||||
+ '<div class="row"><span>Your available credits</span><span>' + Number(bal.available || 0).toLocaleString('en-US') + '</span></div>';
|
||||
if (can) {
|
||||
const csrf = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase());
|
||||
return gkPage(res, 200, 'Confirm your Crowns', head + '<form method="post" action="/gk/shop/confirm"><input type="hidden" name="t" value="' + gkEsc(t) + '"><input type="hidden" name="csrf" value="' + csrf + '"><button class="btn" type="submit">Spend ' + Number(c.credits).toLocaleString('en-US') + ' credits</button></form>'
|
||||
+ '<a class="alt" href="' + GK_URL() + '/play?open=shop">Cancel and go back</a><p class="fine">Crowns are game items. They have no cash value and cannot be withdrawn. The credits come off your ad balance and show in your Credit activity.</p>');
|
||||
}
|
||||
const need = c.credits - usable;
|
||||
return gkPage(res, 200, 'More credits needed', head + '<p class="warn">You need ' + need.toLocaleString('en-US') + ' more credits for this pack' + (bal.available >= c.credits ? ' (some of your credits are already budgeted to live campaigns or spread across positions)' : '') + '.</p>'
|
||||
+ '<a class="btn" href="/gk/shop/topup?t=' + encodeURIComponent(t) + '">Buy a credit package</a><a class="btn blue" href="' + GK_URL() + '/play?open=shop">Pick a smaller pack</a>'
|
||||
+ '<p class="fine">A $5 package comes with 500 credits. After you buy, a banner on your dashboard brings you straight back to finish this order.</p>');
|
||||
}
|
||||
if (p === '/gk/shop/topup' && req.method === 'GET') { // the detour to Buy packages, remembered for the way back
|
||||
const t = u.searchParams.get('t') || ''; if (gkOpen(t).error) { res.writeHead(302, { Location: '/my#buy' }); return res.end(); }
|
||||
res.writeHead(302, { Location: '/my#buy', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', t, 7200) }); return res.end();
|
||||
}
|
||||
if (p === '/gk/shop/resume' && req.method === 'GET') {
|
||||
const t = parseCookies(req)['iap.gkshop']; res.writeHead(302, { Location: t ? '/gk/shop?t=' + encodeURIComponent(t) : GK_URL() + '/play?open=shop', 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.return', '', 0) }); return res.end();
|
||||
}
|
||||
if (p === '/gk/shop/confirm' && req.method === 'POST') {
|
||||
const f = await gkFormBody(req); const t = f.get('t') || ''; const r = gkOpen(t);
|
||||
if (r.error) return gkPage(res, 400, 'Order problem', '<h1>That order did not work</h1><p class="sub">' + gkEsc(r.error) + '</p>');
|
||||
const c = r.claims; const s = await auth.fromRequest(req);
|
||||
if (!s || !s.email || String(s.email).toLowerCase() !== String(c.email).toLowerCase()) return gkPage(res, 403, 'Sign in', '<h1>Please sign in again</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Continue</a>');
|
||||
const want = gkSign('csrf:' + c.order + ':' + String(s.email).toLowerCase()); const got = String(f.get('csrf') || '');
|
||||
if (want.length !== got.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(got))) return gkPage(res, 403, 'Order problem', '<h1>That form expired</h1><a class="btn blue" href="/gk/shop?t=' + encodeURIComponent(t) + '">Try again</a>');
|
||||
const prev = gkOrders.get(c.order);
|
||||
if (prev && (prev.status === 'paid' || (prev.status === 'paying' && Date.now() - prev.ts < 60000))) { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); }
|
||||
gkOrders.set(c.order, { status: 'paying', email: s.email, ts: Date.now() });
|
||||
const { ids } = await myMemberIds(s);
|
||||
const out = await ads.gamePurchase(s.email, ids, c.credits, 'Gem Kingdom: ' + c.crowns + ' Crowns', GK_URL());
|
||||
if (out.error) { gkOrders.delete(c.order); if (out.error === 'short') { res.writeHead(302, { Location: '/gk/shop?t=' + encodeURIComponent(t) }); return res.end(); } return gkPage(res, 500, 'Order problem', '<h1>Something went wrong</h1><p class="sub">' + gkEsc(out.error) + '</p>'); }
|
||||
gkOrders.set(c.order, { status: 'paid', email: s.email, campaignId: out.campaignId, ts: Date.now() });
|
||||
console.log('gemkingdom crowns', s.email, c.crowns, 'for', c.credits, 'credits, campaign', out.campaignId);
|
||||
const rc = gkMint({ kind: 'gk-receipt', order: c.order, email: String(c.email).toLowerCase(), crowns: Number(c.crowns), credits: Number(c.credits), ref: out.campaignId }, 24 * 3600000);
|
||||
gkCallback(c.cb, rc); // the server copy; the redirect below is the fast path
|
||||
const ret = String(c.ret || '').startsWith(GK_URL() + '/') ? c.ret : GK_URL() + '/api/iap/receipt';
|
||||
res.writeHead(302, { Location: ret + '?t=' + rc, 'Cache-Control': 'no-store', 'Set-Cookie': gkCookie('iap.gkshop', '', 0) }); return res.end();
|
||||
}
|
||||
"""
|
||||
|
||||
patch(P, [
|
||||
("// -- the games registry (2026-10-01).", HELPERS + "\n// -- the games registry (2026-10-01)."),
|
||||
(" { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt',",
|
||||
" { slug: 'gemkingdom', name: 'Gem Kingdom', tag: 'Fantasy match-3', blurb: 'Match gems to battle monsters with three heroes, earn stars and rebuild your village. Crowns for instant upgrades come from your ad credits.',\n"
|
||||
" art: GK_URL() + '/fantasy/bg.jpg', play: '/api/my/gemkingdom', cta: 'Play', pays: 'Game rewards; Crowns from ad credits' },\n"
|
||||
" { slug: 'polhunter', name: 'PolHunter', tag: 'Scavenger hunt',"),
|
||||
(" // -- PassiveDrip card on the Earn tab", ROUTES + " // -- PassiveDrip card on the Earn tab"),
|
||||
("returnTo: ['polhunter', 'driprunner', 'passivedrip'].includes(", "returnTo: ['polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop'].includes("),
|
||||
("next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip' })[parseCookies(req)['iap.return']] || null",
|
||||
"next: ({ driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume' })[parseCookies(req)['iap.return']] || null"),
|
||||
])
|
||||
patch(J, [
|
||||
(" if (me.returnTo === 'passivedrip' && !render.toGame) {",
|
||||
" if (me.returnTo === 'gemkingdom' && !render.toGame) { render.toGame = true; location.href = '/api/my/gemkingdom'; return; } // Gem Kingdom sent them here to sign in (2026-10-01)\n"
|
||||
" if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }\n"
|
||||
" if (me.gkShop && !document.getElementById('gkBack')) { const d = document.createElement('a'); d.id = 'gkBack'; d.href = '/gk/shop/resume'; d.textContent = 'Finish your Gem Kingdom Crowns order \\u2192'; d.setAttribute('style', 'position:fixed;left:12px;right:12px;bottom:14px;z-index:9999;display:block;padding:14px 16px;border-radius:14px;background:linear-gradient(180deg,#E8455A,#A8172B);color:#fff;font-weight:800;text-align:center;text-decoration:none;box-shadow:0 10px 30px rgba(0,0,0,.45)'); document.body.appendChild(d); }\n"
|
||||
" if (me.returnTo === 'passivedrip' && !render.toGame) {"),
|
||||
])
|
||||
print('patched')
|
||||
Reference in New Issue
Block a user