Files
martbost 7c8f204f5a Light and dark themes as token sets (Marty 2026-11-01: a member asked for both, for vision-impaired readers and people who struggle with bright or dark screens)
cr.css and pub.css gain :root[data-theme="dark"]: deep navy workspace (#0B1424 ground, #142338 panels, #1B2D47 panel-2), near-white ink, readable muted, quiet lines, the blue accent and signal orange retuned so text on them and they on the ground clear WCAG AA 4.5:1 (accent-ink/sig-ink/ok-ink/bad-ink/on-ink tokens carry the text colour for each fill), soft fills as dark tints, flatter darker shadows; the chrome rail, topbar and strip stay as they are. site.css (the sapphire pages) gains :root[data-theme="light"]: light ground, white panels, dark ink, the same blue family darkened to read on white, the chrome headline gradient turned blue steel so it still shows.

Audit of stray literals: every raw hex/rgba that encoded a surface, text, border or soft fill in the five stylesheets now reads a token (new tokens: field-bg, btn-bg, btn-blue, panel-grad(-hi/-deep), ph-a/b, hl, grid-dot, bg-glow, row-hover, panel-glass, sh-lg, note-*, violet-*, *-line, chrome-hi/warm, mint-faint/soft-2/line/line-2/deep/pale, gold-*, amber-*, cyan-*, muted-soft, ink-faint, ground-soft, nav-bg, side-bg, pill-bg, glow). tools.css maps every site.css token onto a Control Room token (its hard-coded --ink and --mint-ink are gone), admin.css loses its white/slate literals. Stage and pipeline palettes get a lifted dark variant; .stg text mixes the stage colour with ink so 10.5px pills pass in both themes. Light-side tuning for AA: muted #596984, ok #0B7A52, warn #B23A0A, sig-2 #B8420A, and the orange primary button carries navy text (white on #FF6A1A was 2.9:1).

Scripts that draw UI read tokens: my.js charts take their colours from getComputedStyle at draw time (CH proxy), donut caption and rank/wallet/ready badges use var(--muted)/var(--gold)/var(--ok); admin.js, credits-screen.js, engine-room.js, common.js (wordmark stroke) and cr-shell.js (arrival strip) likewise. Left as literals on purpose: brand gradients on the orange primary buttons, glows and drop shadows, overlays (modal backdrops, the full-screen ad viewer), video/QR/banner-preview backings that must stay black or white, print styles, var() fallbacks, and the categorical stage colours themselves.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-01 10:44:20 -06:00

228 lines
24 KiB
JavaScript

// LinkSpin Credits (2026-10-07): the buy screen inside the Control Room. Package picker from the catalog, the POL
// quote, connect/link a wallet, the on-chain purchase (ported from the classic /my#buy flow: sponsor hold, balance
// pre-flight, Trust Wallet heads-up), switch-on-payouts without buying, card on-ramp, purchases from the chain.
(function () {
const $ = id => document.getElementById(id); const esc = CR.esc, fmt = CR.fmt;
// wallet.js reports through IAP.status (the classic dashboard's status bar): route it to the shell's toast
if (window.IAP) IAP.status = (m, kind) => CR.toast(m, kind === 'bad');
CR.mount({ active: 'credits', title: 'Credits', sub: 'loading' });
const pol = wei => { try { return (Number(BigInt(String(wei || '0')) / 10000000000000000n) / 100).toFixed(2); } catch (e) { return '0.00'; } };
const usd = c => '$' + (Number(c || 0) / 100).toLocaleString(undefined, { maximumFractionDigits: 2 });
const NAMES = { 1000: 'Door', 2500: 'Most chosen', 5000: 'Builder', 10000: 'Growth', 25000: 'Leader', 50000: 'Network' };
let CFG = null, ME = null, CAT = [], SEL = null, CAMP = null, DASH = null, POS = null, FROM = 'main';
const short = a => String(a || '').slice(0, 6) + '…' + String(a || '').slice(-4);
// Qualified Start (2026-10-18, ported from the classic Buy pane): extra wallets on this account, each its own position
// under the main member. Testers could not buy from a second wallet here: the only control was a disconnect that
// snapped back to the main wallet, and the buy insisted on the main wallet.
const posList = () => (POS && Array.isArray(POS.positions)) ? POS.positions : [];
const fromPos = () => FROM !== 'main' && posList().some(x => String(x.address).toLowerCase() === FROM) ? FROM : null;
function paintTiles() {
const avail = CAMP ? CAMP.availableCredits : 0, inLive = CAMP ? CAMP.inCampaigns : 0;
const addr = ME && ME.address, on = !!(ME && ME.memberId);
const bc = DASH ? (DASH.buyerCount || 0) : 0;
$('tiles').innerHTML = [
CR.tile({ k: 'Credits available', v: fmt(avail), hi: true, note: CAMP ? 'earned ' + fmt(CAMP.earnedCredits) + ' · purchased ' + fmt(CAMP.purchasedCredits) : '' }),
CR.tile({ k: 'Working in live ads', v: fmt(inLive), note: CAMP ? (CAMP.campaigns || []).filter(c => c.status === 'live').length + ' live' : '' }),
CR.tile({ k: 'Wallet', v: addr ? addr.slice(0, 6) + '…' + addr.slice(-4) : 'not linked', note: on ? 'payouts on · member #' + ME.memberId : (addr ? 'payouts off' : 'needed to buy or be paid') }),
CR.tile({ k: 'Qualification', v: bc + ' of ' + (bc >= 5 ? 5 : bc >= 2 ? 5 : 2), note: bc >= 5 ? 'levels 2 and 3 open' : bc >= 2 ? 'level 2 open · 5 opens level 3' : 'buyers to open level 2' })
].join('');
}
// the Monthly Refuel threshold in cents once fuel.js has the member's refuel view (2026-10-25); 0 while the switch is off
const rfMin = () => { const v = window.FUEL && window.FUEL.refuel; return v && v.on && v.minUsd ? Math.round(Number(v.minUsd.linkspin) * 100) : 0; };
window.LSCredits = { repaint: () => { if (CAT && CAT.length) paintPkgs(); } };
function paintPkgs() {
const live = CAT.filter(p => p.active !== false && p.exists !== false);
if (!live.length) { $('pkgs').innerHTML = '<div class="muted">No packages are on sale right now.</div>'; return; }
if (!SEL) SEL = (live.find(p => p.priceCents === 2500) || live[0]).id;
$('pkgs').innerHTML = live.map(p => '<button type="button" class="pk' + (p.id === SEL ? ' on' : '') + '" data-id="' + p.id + '"><span class="k">' + esc(NAMES[p.priceCents] || 'Package') + '</span><span class="price">' + usd(p.priceCents) + '</span><span class="cr">' + fmt(p.creditAmount) + ' credits</span>'
+ (p.priceCents >= 2500 ? '<span class="tag ok">qualifies</span>' : '<span class="tag">does not qualify</span>')
+ (rfMin() && p.priceCents >= rfMin() ? '<span class="tag ok" title="A package this size counts as your monthly refuel (or a Pit Stop when this cycle is already refueled here)">counts for Refuel</span>' : '') + '</button>').join('');
$('pkgs').querySelectorAll('.pk').forEach(b => b.addEventListener('click', () => { SEL = Number(b.dataset.id); paintPkgs(); paintQuote(); paintGoes(); }));
}
const sel = () => CAT.find(p => p.id === SEL);
function paintQuote() {
const p = sel(); if (!p) return;
if (p.costWei) { $('payPol').textContent = pol(p.costWei) + ' POL'; $('payUsd').textContent = '≈ ' + usd(p.priceCents) + ' + gas'; }
else { $('payPol').textContent = 'paused'; $('payUsd').textContent = 'price feed is catching up'; }
const rate = (p.costWei && p.priceCents) ? (p.priceCents / 100) / (Number(BigInt(p.costWei) / 1000000000000n) / 1e6) : 0;
$('rateLine').textContent = rate ? 'rate ' + rate.toFixed(4) + ' USD/POL · live from the oracle' : '';
const addr = ME && ME.address;
$('buyBtn').disabled = !p.costWei;
const fp = fromPos(), n = fp ? posList().findIndex(x => String(x.address).toLowerCase() === fp) + 2 : 0;
$('buyBtn').textContent = addr ? 'Buy ' + usd(p.priceCents) + ' package' + (fp ? ' from position ' + n : '') : 'Connect a wallet to buy';
}
// "Buy from": the main wallet or one of the positions. Always shown once a main wallet is linked (Michael 2026-10-18:
// the instructions say "pick it under Buy from" and the menu did not exist until a position was added)
function paintFrom() {
const list = posList(), main = POS && POS.main;
if (!fromPos()) FROM = 'main';
$('fromWrap').hidden = !(ME && ME.address);
if (!(ME && ME.address)) return;
$('buyFrom').innerHTML = '<option value="main">Main wallet ' + (ME && ME.address ? short(ME.address) : '') + (ME && ME.memberId ? ' · #' + ME.memberId : '') + (main && main.noPayout ? ' · linkage only' : '') + '</option>'
+ list.map((x, i) => '<option value="' + esc(String(x.address).toLowerCase()) + '"' + (x.noPayout ? ' disabled' : '') + '>Position ' + (i + 2) + ' ' + short(x.address) + (x.memberId ? ' · #' + x.memberId : ' · not registered yet') + (x.noPayout ? ' · linkage only' : x.counted ? ' · counted' : '') + '</option>').join('');
$('buyFrom').value = FROM;
$('fromHint').textContent = fromPos() ? 'Your wallet app must be on this position\'s account when you confirm. Its first package registers it under you.' : (list.length ? 'Your wallet app must be on this account when you confirm.' : 'Your main wallet. Positions you add with "Add a position wallet" on this screen appear in this list.');
}
function paintGoes() {
const p = sel(); if (!p) return;
const d = p.priceCents / 100; const spName = ME && ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : 'your sponsor';
$('goesTitle').textContent = 'Where ' + usd(p.priceCents) + ' goes';
$('goesRows').innerHTML = [
['Level 1 · ' + esc(spName), '$' + (d * 0.5).toFixed(2)],
['Level 2 · upline <span class="tag" title="paid if qualified, else passes up">if qualified</span>', '$' + (d * 0.2).toFixed(2)],
['Level 3 · upline <span class="tag" title="paid if qualified, else passes up">if qualified</span>', '$' + (d * 0.1).toFixed(2)],
['Platform, two wallets', '$' + (d * 0.2).toFixed(2)]
].map(([k, v]) => '<div class="row"><span>' + k + '</span><span class="mono" style="font-weight:700">' + v + '</span></div>').join('')
+ '<p class="muted" style="margin:10px 0 0;font-size:11.5px">A pass-up goes to the next qualified member above, else to the platform. Nothing is ever held for later.</p>';
}
function paintWallet() {
const addr = ME && ME.address, on = !!(ME && ME.memberId);
$('walletMeta').textContent = addr ? (on ? 'payouts on' : 'linked · payouts off') : 'none linked';
$('walletBox').innerHTML = addr
? '<div class="code" style="display:block">' + esc(addr) + '</div>'
+ (on ? '<div class="ok"><span class="dot"></span>Payouts on. Every package your people buy pays this wallet in the same transaction.</div>'
: ME.tankHold ? '<div class="ink2" id="tankHoldNote" style="font-size:13px;color:var(--ok)">' + esc(tankHoldText(ME.tankHold)) + '</div>' // held for an adopter: no activate button
: '<div class="ink2" style="font-size:13px">Linked, but payouts are off until this wallet is on the contract. Buying a package does that. So does the free activation below (gas only).</div><div class="acts"><button class="btn blue" type="button" id="activateBtn">Switch on payouts (free)</button></div>')
+ '<div class="acts"><a class="btn sm" href="' + esc((CFG && CFG.explorer) || 'https://polygonscan.com') + '/address/' + esc(addr) + '" target="_blank" rel="noopener">Open on the explorer</a><button class="btn sm" type="button" id="switchBtn">Switch account</button><button class="btn sm" type="button" id="dropBtn">Disconnect</button></div>'
+ posBlock()
: '<div class="ink2" style="font-size:13px">Link the wallet that should receive your payouts. One free signature, no transaction. SafePal is the recommended wallet; MetaMask, Phantom and any WalletConnect wallet work too.</div><div class="acts"><button class="btn blue" type="button" id="linkBtn">Link a wallet</button><a class="btn sm" href="/wallets" target="_blank" rel="noopener">Wallet guide</a></div>';
const lb = $('linkBtn'); if (lb) lb.addEventListener('click', () => guard(lb, linkWallet));
const ab = $('activateBtn'); if (ab) ab.addEventListener('click', () => guard(ab, activate));
const sb = $('switchBtn'); if (sb) sb.addEventListener('click', () => guard(sb, switchAccount));
const db = $('dropBtn'); if (db) db.addEventListener('click', () => guard(db, async () => { await IAPWallet.disconnect(); CR.toast('Disconnected. Your linked wallet stays on your account. The next purchase or Add a position wallet opens the account picker.'); }));
const pb = $('addPosBtn'); if (pb) pb.addEventListener('click', () => guard(pb, addPosition));
}
function posBlock() {
const list = posList(); const max = 5;
return '<div style="border-top:1px solid var(--line);padding-top:10px;display:grid;gap:8px"><div style="font:700 10.5px var(--mono);letter-spacing:.1em;text-transform:uppercase;color:var(--muted)">Extra positions · Qualified Start</div>'
+ list.map((x, i) => '<div class="row" style="padding:4px 0"><span>Position ' + (i + 2) + ' <span class="mono">' + esc(short(x.address)) + '</span></span><span class="mono muted" style="font-size:11.5px">' + (x.memberId ? '#' + x.memberId + (x.noPayout ? ' · linkage only' : x.counted ? ' · counted' : '') : 'buy to register') + '</span></div>').join('')
+ '<div class="ink2" style="font-size:12.5px">Own another wallet? Add it as a position, then pick it under <b>Buy from</b> and buy a package marked qualifies. Each position that buys counts as a qualifying buyer for you, its credits pool with yours, and you stay signed in as you.</div>'
+ (list.length < max ? '<div class="acts"><button class="btn blue sm" type="button" id="addPosBtn">Add a position wallet</button><span class="muted" style="font-size:11.5px">' + list.length + ' of ' + max + ' used</span></div>' : '<div class="muted" style="font-size:11.5px">All ' + max + ' positions are linked.</div>')
+ '</div>';
}
// pick a different account in the wallet (MetaMask's account picker; a fresh session for WalletConnect) and say what it is
async function switchAccount() {
const a = String(await IAPWallet.pickAccount() || '').toLowerCase(); if (!a) return;
const i = posList().findIndex(x => String(x.address).toLowerCase() === a);
if (ME && a === String(ME.address || '').toLowerCase()) { FROM = 'main'; CR.toast('Connected as ' + short(a) + ', your main wallet.'); }
else if (i >= 0) { FROM = a; CR.toast('Connected as ' + short(a) + ', position ' + (i + 2) + '. It is selected under Buy from.'); }
else CR.toast('Connected as ' + short(a) + '. That account is not on LinkSpin yet. To buy from it, use Add a position wallet.');
paintFrom(); paintQuote();
}
// every Add-a-position attempt is reported to the server log, so support can see where it stopped (never blocks the flow)
function posReport(stage, detail) { try { fetch('/api/my/position-attempt', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ stage, detail: String(detail || '').slice(0, 300), ua: navigator.userAgent.slice(0, 160), wallet: !!window.ethereum, mm: !!(window.ethereum && window.ethereum.isMetaMask) }), keepalive: true }).catch(() => {}); } catch (e) {} }
async function addPosition() {
posReport('click', '');
const me = await CR.me(true);
if (!me.address) throw new Error('Link your main wallet first, then add positions under it.');
if (!me.memberId) throw new Error('Switch on payouts for your main wallet first. Positions register under your member number.');
const ok = await CR.dialog({ title: 'Add a position wallet', html: '<div class="ink2" style="display:grid;gap:8px"><div>Your wallet asks which account to connect. Choose <b>only the new account</b> (not ' + esc(short(me.address)) + '), then sign once. No transaction, no cost.</div><div>No second account yet? MetaMask: account menu, Add account. SafePal or Trust: create or switch wallet. Phone with WalletConnect: pick the other wallet app in the list.</div></div>', ok: 'Ready', no: 'Cancel' });
if (!ok) { posReport('cancelled', ''); return; }
CR.toast('Pick the new account in your wallet, then sign once…');
posReport('start', '');
// the wallet can sit silent (a request already waiting in MetaMask, its window behind the browser, or only one
// account to offer): after 20 s say what to check instead of looking like nothing happened (Michael 2026-10-18)
const tip = setTimeout(() => { posReport('no-answer-20s', ''); CR.dialog({ title: 'Waiting on your wallet', text: 'Your wallet has not answered yet. Open MetaMask (the fox icon in the browser toolbar): a request may be waiting there, or its window may be behind this one. You also need a second account in MetaMask: Accounts, then Add account. Pick only that new account and sign once.', ok: 'OK' }).catch(() => {}); }, 20000);
let r;
try { r = await IAPWallet.signIn({ asPosition: true, pick: true }); }
catch (e) { posReport('error', (e && e.message) || String(e)); throw e; }
finally { clearTimeout(tip); }
posReport('added', r && r.address);
FROM = String(r.address || '').toLowerCase();
CR.toast('Position added: ' + short(r.address) + '. It is selected under Buy from. Pick a qualifying package and buy.');
await load();
}
function paintBuys(E) {
const buys = E && Array.isArray(E.purchases) ? E.purchases : [];
$('buysMeta').textContent = buys.length + (buys.length === 1 ? ' purchase' : ' purchases') + ' · every row links to the transaction';
$('buyRows').innerHTML = buys.length ? buys.slice(0, 50).map(x => {
const ts = Number(x.ts || x.time || 0); const when = ts ? new Date(ts * (ts > 1e12 ? 1 : 1000)).toLocaleString() : '';
const pkg = (x.priceCents ? usd(x.priceCents) : (x.package || x.product || ('#' + (x.productId || '')))) + (x.position ? ' · Position ' + x.position : ''); // bought from a linked position (2026-10-18)
const paid = x.amountWei || x.valueWei || x.paidWei ? pol(x.amountWei || x.valueWei || x.paidWei) + ' POL' : '';
const tx = x.tx || x.hash || '';
return '<div class="rw"><span class="mono muted" style="font-size:12px">' + esc(when) + '</span><span class="num">' + esc(String(pkg)) + '</span><span class="mono">' + esc(paid) + '</span><span>' + (tx ? '<a class="mono" href="' + esc((CFG && CFG.explorer) || 'https://polygonscan.com') + '/tx/' + esc(tx) + '" target="_blank" rel="noopener">' + esc(tx.slice(0, 10)) + '…' + esc(tx.slice(-6)) + '</a>' : '') + '</span></div>';
}).join('') : '<div class="rw" style="grid-template-columns:1fr"><span class="muted">Nothing yet. Your first package shows here with its transaction, what you paid in POL, and who in your line was paid.</span></div>';
}
async function guard(btn, fn) { if (btn.disabled) return; btn.disabled = true; try { await fn(); } catch (e) { CR.toast((e && e.message) || 'Something went wrong.', true); } finally { btn.disabled = false; } }
// holding tank (2026-10-27): no sponsor yet, so the free Switch on payouts waits for an adopter (24 hours at most).
// A purchase is never held: buying goes ahead as before.
const holdLeft = ms => { const m = Math.max(1, Math.round(ms / 60000)); const h = Math.floor(m / 60); return h ? h + ' h ' + (m % 60) + ' min' : m + ' min'; };
function tankHoldText(h) {
let t = "You're being matched with a sponsor. Payouts switch on as soon as someone picks you up (within 24 hours).";
if (h && h.until) { const ms = h.until - Date.now(); t += ms > 0 ? ' Time left: ' + holdLeft(ms) + '.' : ' Any minute now.'; }
return t;
}
// a named sponsor that cannot be paid right now: hold the transaction and say why (never credit the company by default)
function holdText(sp) {
if (sp.sponsorBlocked === 'tankHold') return tankHoldText(sp.tankHold); // the free activation only (intent=activate), never a buy
const who = sp.sponsorName ? ('@' + String(sp.sponsorName).replace(/^@/, '')) : 'your sponsor';
if (sp.sponsorBlocked === 'claim' && sp.claim) return (sp.claim.nobody ? 'Nobody above you on LinkSpin has a wallet yet, so there is no one for the contract to pay. ' : who + ' has not linked a wallet on LinkSpin yet. ') + 'Your first purchase waits until ' + (sp.claim.deadline ? new Date(sp.claim.deadline).toLocaleDateString() : 'they do') + ', then it goes ahead with the nearest member above who has one. Nothing was charged.';
if (sp.sponsorBlocked === 'notActivated') return who + ' has not switched on payouts yet, so this purchase would credit the company instead of them. Ask them to switch on payouts first (one free transaction).';
if (sp.sponsorBlocked === 'rpc') return 'Could not confirm your sponsor on the chain just now. Try again in a minute; nothing was charged.';
return 'Your sponsor link could not be matched to a member. Send a ticket from Help (/help) before buying so ' + who + ' gets credit.';
}
async function linkWallet() { CR.toast('Check your wallet for the free link signature…'); await IAPWallet.signIn(); CR.toast('Wallet linked. Earnings pay there from now on.'); await load(); }
async function activate() {
const sp = await CR.get('/api/sponsor?intent=activate'); if (sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; if (sp.sponsorBlocked === 'tankHold') { ME.tankHold = sp.tankHold || {}; paintWallet(); } return; }
CR.toast('Confirm the free activation in your wallet…');
const r = await IAPWallet.activate(sp.sponsorId || 0);
if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
CR.toast('Payouts are on. Your invite link is live.'); await load();
}
async function buy() {
const p = sel(); if (!p || !p.costWei) return;
$('holdBox').hidden = true;
let me = await CR.me(true);
// which wallet buys: the main one, or a position picked under "Buy from" (it registers under the main member id
// on its first buy, so its sponsor is always this member)
const fp = fromPos(), row = fp ? posList().find(x => String(x.address).toLowerCase() === fp) : (POS && POS.main);
if (fp && !me.memberId) throw new Error('Switch on payouts for your main wallet first, so this position can register under you.');
if (fp && p.priceCents < 2500 && !(await CR.dialog({ title: 'This package does not qualify', text: 'A ' + usd(p.priceCents) + ' package from a position adds credits but does not count toward your qualification. Pick a package marked qualifies to count this position.', ok: 'Buy anyway', no: 'Pick another' }))) return;
if (row && row.noPayout) throw new Error('This ' + (fp ? 'position' : 'wallet') + ' is kept for linkage only. A purchase from it would pay a retired wallet. Buy from another one.');
if (!fp && !me.address) { CR.toast('Link your wallet first: one quick signature…'); await IAPWallet.signIn(); me = await CR.me(true); }
const want = fp || String(me.address || '').toLowerCase(); if (!want) throw new Error('No wallet linked.');
// never buy from a wallet other than the one chosen: a stray wallet would register a brand-new member
await IAPWallet.connect();
let cur = String(await IAPWallet.activeAddress() || '').toLowerCase();
if (cur !== want) { CR.toast('Pick ' + short(want) + ' in your wallet\'s account picker…'); cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); }
if (cur !== want) throw new Error('Your wallet connected as ' + short(cur) + ' but you are buying from ' + short(want) + '. Switch accounts in the wallet app (or change Buy from) and try again.');
const sp = fp ? { sponsorId: me.memberId } : await CR.get('/api/sponsor?intent=buy');
if (!fp && !me.memberId && sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; }
try { // pre-flight: the POL has to be there; Trust Wallet refuses transactions that spend most of a balance
const need = BigInt(p.costWei) + BigInt(p.costWei) / 50n;
const bal = await IAPWallet.balance(want);
if (bal < need) { CR.toast('That wallet holds ' + pol(bal.toString()) + ' POL, but this package needs about ' + pol(need.toString()) + ' POL plus a little for gas. Top it up and try again.', true); return; }
const pct = Number(need * 100n / bal);
if (/trust/i.test(IAPWallet.walletName() || '') && pct > 55) {
const ok = await CR.dialog({ title: 'Heads up for Trust Wallet', text: 'This purchase uses about ' + pct + '% of the POL in your wallet, and Trust Wallet refuses transactions that spend most of a balance. Add some POL first, or continue and see if it lets it through.', ok: 'Continue' });
if (!ok) return;
}
} catch (e) { /* balance read failed: let the wallet decide */ }
CR.toast('Confirm the purchase in your wallet…');
const r = await IAPWallet.buy(Number(p.id), sp.sponsorId || 0, p.costWei);
if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Nothing was charged beyond gas.');
CR.toast(fp ? 'Settled on-chain. That position now counts toward your qualification, and its credits pool with yours.' : 'Settled on-chain. Your credits are in Ads now.');
await load();
}
$('buyBtn').addEventListener('click', () => guard($('buyBtn'), buy));
$('buyFrom').addEventListener('change', () => { FROM = $('buyFrom').value || 'main'; paintFrom(); paintQuote(); });
async function load() {
try { [CFG, ME] = await Promise.all([CR.get('/api/config'), CR.me(true)]); } catch (e) { CR.sub('could not load'); return; }
let cat = null, E = null;
try { [cat, CAMP, DASH, E] = await Promise.all([CR.get('/api/catalog'), CR.get('/api/my/campaigns'), CR.get('/api/my/dashboard'), CR.get('/api/my/activity')]); } catch (e) {}
try { POS = ME.address ? await CR.get('/api/my/positions') : null; } catch (e) { POS = null; }
CAT = (cat && cat.products) || [];
CR.sub((CAMP ? fmt(CAMP.availableCredits) + ' free to spend · ' + fmt(CAMP.inCampaigns) + ' in live ads' : '') + (CAT[0] && CAT[0].costWei ? '' : ' · price feed catching up'));
paintTiles(); paintPkgs(); paintFrom(); paintQuote(); paintGoes(); paintWallet(); paintBuys(E);
const spName = ME.sponsorName ? ('@' + String(ME.sponsorName).replace(/^@/, '')) : null;
$('sponsorLine').innerHTML = spName
? 'Your sponsor <b>' + esc(spName) + '</b> is placed on the contract. The moment you confirm, half of the package lands in their wallet and the rest splits as shown. Credits appear in Ads right away.'
: 'No sponsor is recorded on your account. Your purchase still works; the sponsor share goes to the platform position. If someone invited you, open their invite link first.';
if (ME.sponsorBlocked) { $('holdBox').textContent = holdText(ME); $('holdBox').hidden = false; }
}
CR.requireSession(load);
})();