ViralAdBlitz v1 (viraladblitz.com rebuild, Marty approved 2026-11-14): the network's text-ad home, local build, not deployed

- Free text ad for network members (InstantAdPay / LinkSpin sign-in or wallet, membership through the hub), one per member
- Member pages viraladblitz.com/<username>: own ad + the first 5 people above in the hub line with a live ad (by place) + 2 Boosted places
- Front page: amber ticker (Boosted starred), Top ads this week by verified clicks, today's numbers, ledger, contract proof
- Verified visitors / views / clicks (ticket + dwell + per-visitor dedupe + per-connection cap + bot filter, owner excluded)
- Boost $5 = 500 guaranteed views through VABShop: keeper-signed EIP-712 line voucher from the hub line, watcher, delivery
  counted per verified view with an audit row each, Network Ad Space text-ad finishing after 30 days (vabnas.js)
- Trust pack: /ledger, /contract, toasts, Telegram card per Boost (once), Terms / Earnings Disclaimer / Privacy (TrustClickz),
  network footer from the hub with tracked links, promo kit (21 creatives) + /promote, LinkSpin zone placeholders, hub report
- Old YFW links via the oldrefs map (admin load route); docstore MySQL documents + row tables
- qa/smoke.mjs 162/162 (stand-in hub, chain, Telegram, NAS; Playwright desktop + phone), qa/chain.mjs 20/20 (real VABShop on anvil)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Marty Bostick
2026-11-14 13:52:03 -06:00
commit 001878bdae
79 changed files with 4813 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
// Admin: status, Boost delivery, member lookup, ad status, the old-link map. The token stays in this tab only (sessionStorage).
(function () {
VAB.renderNav(''); VAB.renderFooter();
const $ = VAB.$, esc = VAB.esc;
let tok = ''; try { tok = sessionStorage.getItem('vab.admin') || ''; } catch (e) {}
const H = () => ({ 'x-admin-token': tok, 'Content-Type': 'application/json' });
const show = (el, o) => { el.textContent = JSON.stringify(o, null, 2); };
async function load() {
if (!tok) return;
const s = await VAB.getJSON('/api/admin/status', { headers: H() }); show($('statusOut'), s);
const b = await VAB.getJSON('/api/admin/boosts', { headers: H() });
$('boostRows').querySelector('tbody').innerHTML = (b.boosts || []).map(x => '<tr><td>' + VAB.when(x.at) + '</td><td>ad #' + esc(x.adId) + '</td><td>' + VAB.n(x.delivered) + ' / ' + VAB.n(x.views) + '</td><td>' + esc(x.status) + '</td><td class="mono small">' + esc(VAB.short(x.buyer)) + '</td></tr>').join('') || '<tr><td class="muted">none</td></tr>';
}
$('tokForm').addEventListener('submit', e => { e.preventDefault(); tok = $('tok').value.trim(); try { sessionStorage.setItem('vab.admin', tok); } catch (x) {} load(); });
$('lookForm').addEventListener('submit', async e => { e.preventDefault(); show($('lookOut'), await VAB.getJSON('/api/admin/member-lookup?q=' + encodeURIComponent($('look').value.trim()), { headers: H() })); });
$('adForm').addEventListener('submit', async e => { e.preventDefault(); const r = await VAB.getJSON('/api/admin/ad', { method: 'POST', headers: H(), body: JSON.stringify({ id: Number($('adId').value), status: $('adStatus').value.trim(), note: $('adNoteIn').value }) }); VAB.status(r.error || 'Saved.', r.error ? 'err' : 'ok'); });
$('oldFile').addEventListener('change', async e => { const f = e.target.files[0]; if (!f) return; const r = await fetch('/api/admin/oldrefs', { method: 'POST', headers: H(), body: await f.text() }); show($('oldOut'), await r.json()); });
load();
})();
+35
View File
@@ -0,0 +1,35 @@
// Boost page: the live POL price for 1..10 Boosts and the Buy button (one-time, never a subscription).
(async function () {
VAB.renderNav('/boost'); VAB.renderFooter(); VAB.wire('other').catch(() => {});
const $ = VAB.$;
const c = await VAB.getConfig().catch(() => ({}));
const b = c.boost || { usd: 5, views: 500, maxQty: 10 };
$('bViews').textContent = VAB.n(b.views); $('bViews2').textContent = VAB.n(b.views); $('bDays').textContent = c.deliverDays || 30;
for (let i = 1; i <= (b.maxQty || 10); i++) { const o = document.createElement('option'); o.value = i; o.textContent = i + (i === 1 ? ' Boost' : ' Boosts'); $('bQty').appendChild(o); }
const live = !!(c.shop && c.shop.live);
const me = await VAB.getJSON('/api/me').catch(() => ({}));
const qty = () => Number($('bQty').value) || 1;
function who() {
if (!live) { $('bWho').textContent = 'Boosts open when the contract goes live. Post your free ad now.'; $('bBuy').disabled = true; return; }
$('bBuy').disabled = false;
$('bWho').textContent = me.signedIn ? 'Signed in as ' + (me.username ? '@' + me.username : VAB.short(me.address)) + '. Pay from this same wallet.' : 'Sign in on My page first, then pay from the same wallet.';
}
async function price() {
const n = qty(); $('bUsd').textContent = '$' + (b.usd * n); $('bViews2').textContent = VAB.n(b.views * n);
if (!live) { $('bPol').textContent = 'paid in POL at the live price'; return; }
const q = await VABBuy.quote(n).catch(() => ({ error: 'x' }));
$('bPol').textContent = q.error ? 'price unavailable right now' : 'about ' + VABBuy.fmtPol(q.wei, 2) + ' POL at today\'s price';
}
who(); await price(); $('bQty').onchange = price; setInterval(price, 60000);
let busy = false;
$('bBuy').onclick = async () => {
if (busy) return; busy = true; $('bBuy').disabled = true;
try {
if (!me.signedIn) { location.href = '/my'; return; }
const before = ((await VAB.getJSON('/api/my')).boosts || []).length;
const r = await VABBuy.run({ qty: qty(), done: async () => (((await VAB.getJSON('/api/my')).boosts || []).length > before) });
VAB.status((r.recorded ? 'Your Boost is live: your ad is starred on the ticker and its views are being delivered. Follow it on My page.' : 'Paid and confirmed. Your Boost shows on My page within a few minutes.') + (r.link ? ' Transaction: ' + r.link : ''), 'ok');
} catch (e) { VAB.status(String(e && e.message || e).slice(0, 400), 'err'); }
finally { busy = false; who(); }
};
})();
+39
View File
@@ -0,0 +1,39 @@
// One-time Boosts through VABShop. The server builds the buy() call for the signed-in member (POST /api/my/order, with a fresh
// line voucher when the member's sponsor line is not on the contract yet); the member's own wallet sends it. The wallet that
// pays must be the member's ViralAdBlitz account. After the transaction confirms the page waits for the watcher to record it.
window.VABBuy = (function () {
const fmtPol = (wei, d) => { const k = d || 4; const s = (BigInt(wei) * 10n ** BigInt(k) / 10n ** 18n).toString().padStart(k + 1, '0'); return s.slice(0, -k) + '.' + s.slice(-k); };
async function quote(qty) { return VAB.getJSON('/api/quote?qty=' + (qty || 1)); }
// o: { qty, done() -> bool (the Boost shows on /api/my), say(msg, cls) }
async function run(o) {
const say = o.say || VAB.status;
const c = await VAB.getConfig();
if (!c.shop || !c.shop.live) throw new Error('Boosts are not open right now.');
const me = await VAB.getJSON('/api/me');
if (!me.signedIn) throw new Error('Sign in on My page first, so the Boost lands on your ad.');
say('Connecting your wallet...');
const addr = String(await VABWallet.activeAddress(await VABWallet.connect()) || '').toLowerCase();
if (!addr) throw new Error('No wallet connected. Tap Boost again and pick SafePal or any other crypto wallet.');
if (addr !== me.address) throw new Error('Your wallet is connected as ' + VAB.short(addr) + ', but your ViralAdBlitz account is ' + VAB.short(me.address) + '. A Boost goes to the wallet that pays, so switch your wallet app to ' + VAB.short(me.address) + ', or sign out and sign in with ' + VAB.short(addr) + '.');
const od = await VAB.post('/api/my/order', { qty: o.qty || 1 });
if (od.error) throw new Error(od.error);
const value = BigInt(od.value);
try { const bal = await VABWallet.balance(addr); if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The Boost needs about ' + fmtPol(value) + ' POL plus a little gas. Add POL on Polygon and try again.'); }
catch (e) { if (/holds/.test(e.message)) throw e; }
say('Confirm the payment in your wallet: about ' + fmtPol(value) + ' POL ($' + od.usd + '). Anything above the exact price comes straight back in the same transaction.');
const hash = await VABWallet.sendTx(od.to, od.data, od.value);
const link = c.explorer ? c.explorer + '/tx/' + hash : '';
say('Payment sent. Waiting for the Polygon network to confirm it...');
const r = await VABWallet.waitTx(hash);
if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : ''));
VAB.post('/api/my/paid', {}).catch(() => {});
say('Confirmed on Polygon. Your Boost shows on My page within about a minute.', 'ok');
for (let i = 0; i < 72; i++) {
await new Promise(res => setTimeout(res, 5000));
if (i % 4 === 3) VAB.post('/api/my/paid', {}).catch(() => {});
try { if (await o.done()) return { hash, link, recorded: true }; } catch (e) {}
}
return { hash, link, recorded: false };
}
return { run, quote, fmtPol };
})();
+129
View File
@@ -0,0 +1,129 @@
// Shared page helpers (VAB namespace, modelled on VBB / Downline Banners common.js): nav, the amber ticker, verified visits,
// ad cards, footer (legal, company line, the network line from the hub), network ad zones and toasts of real events.
window.VAB = (function () {
let cfgP = null, vt = null;
const $ = id => document.getElementById(id);
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const getConfig = () => cfgP || (cfgP = fetch('/api/config').then(r => r.json()));
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
const framed = (() => { try { return window.top !== window.self; } catch (e) { return true; } })();
const n = x => Number(x || 0).toLocaleString('en-US');
function status(msg, cls) { const el = $('status'); if (!el) return; el.hidden = !msg; el.className = 'note ' + (cls || ''); el.textContent = msg || ''; }
async function getJSON(url, opts) { const r = await fetch(url, opts); let j = {}; try { j = await r.json(); } catch (e) {} if (!r.ok && !j.error) j.error = 'Request failed (' + r.status + ')'; j._status = r.status; return j; }
const post = (url, body) => getJSON(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) });
function renderNav(active) {
const nav = document.createElement('nav'); nav.className = 'top';
const links = [['/#board', 'Top ads'], ['/my', 'My page'], ['/boost', 'Boost'], ['/ledger', 'Ledger'], ['/contract', 'Contract'], ['/promote', 'Promote']];
nav.innerHTML = '<div class="wrap"><a class="brand" href="/"><span class="wm">ViralAdBlitz</span><span class="live">LIVE</span></a><div class="links">'
+ links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="on" aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</div>'
+ '<a class="cta" href="/my">Post my free text ad</a></div>';
document.body.prepend(nav);
const tk = document.createElement('div'); tk.className = 'ticker'; tk.id = 'ticker'; tk.setAttribute('aria-label', 'Live ticker of the newest text ads');
tk.innerHTML = '<span class="empty">Loading the wire...</span>'; nav.after(tk);
if (framed) document.querySelectorAll('a[href="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; });
}
// a link through the click relay: placement + the visitor's verified token once their visit has verified
const goHref = (id, p) => '/go/' + id + '?p=' + encodeURIComponent(p || 'site') + (vt ? '&v=' + vt : '');
function decorate() { document.querySelectorAll('a[data-go]').forEach(a => { a.href = goHref(a.dataset.go, a.dataset.p); }); }
function renderTicker(items) {
const el = $('ticker'); if (!el) return;
if (!items || !items.length) { el.innerHTML = '<span class="empty">The wire is quiet. Post the first text ad.</span>'; return; }
const one = items.map(t => '<a data-go="' + t.id + '" data-p="ticker" target="_blank" rel="noopener sponsored" class="' + (t.boosted ? 'star' : '') + '" href="' + goHref(t.id, 'ticker') + '">'
+ (t.boosted ? '<b>★ BOOSTED:</b> ' : '▲ ') + esc(t.headline) + ' · ' + esc(t.owner) + '</a>').join('');
const reps = Math.max(1, Math.ceil(8 / items.length));
el.innerHTML = '<div class="run" style="--tick-s:' + Math.max(30, items.length * reps * 6) + 's">' + one.repeat(reps) + one.repeat(reps) + '</div>';
}
// a newsprint card for a text ad (front board, member page Boosted places)
function paper(t, tag, place) {
return '<article class="paper' + (t.boosted ? ' star' : '') + '"><span class="tag">' + (t.boosted ? '★ BOOSTED' + (tag ? ' · ' : '') : '') + esc(tag || '') + '</span>'
+ '<h3>' + esc(t.headline) + '</h3><p>' + esc(t.line1) + (t.line2 ? ' ' + esc(t.line2) : '') + '</p>'
+ '<a class="visit" data-go="' + t.id + '" data-p="' + esc(place || 'card') + '" target="_blank" rel="noopener sponsored" href="' + goHref(t.id, place) + '">Visit ' + esc(t.host) + ' · ' + esc(t.owner) + '</a></article>';
}
// the page's data and its verified visit: the ads come with a ticket; after visitSeconds of the page being visible the
// visit is sent once, and from then on clicks carry the verified token
async function wire(page, u) {
const src = document.referrer || '';
const d = await getJSON('/api/wire?page=' + encodeURIComponent(page) + (u ? '&u=' + encodeURIComponent(u) : '') + (src ? '&src=' + encodeURIComponent(src) : ''));
renderTicker(d.ticker || []);
if (d.ticket) {
const need = (d.seconds || 6) * 1000; let seen = 0, last = Date.now(), sent = false;
const step = async () => {
const now = Date.now(); if (document.visibilityState === 'visible') seen += now - last; last = now;
if (!sent && seen >= need) {
sent = true; clearInterval(iv);
const r = await post('/api/visit/seen', { ticket: d.ticket, visibleMs: seen }).catch(() => ({}));
if (r.vt) { vt = r.vt; decorate(); }
document.dispatchEvent(new CustomEvent('vab:verified', { detail: r }));
}
};
const iv = setInterval(step, 500);
document.addEventListener('visibilitychange', () => { last = Date.now(); });
}
return d;
}
// network ad zones (LinkSpin zones on Marty's account for viraladblitz.com, the VBB pattern). EMPTY until the zones are created
// on LinkSpin: footer wide 728x90, footer phone 320x50, ledger 468x60, Boost page 300x250, My page 468x60; 404 in server.js.
const ZONES = { footWide: '', footPhone: '', ledger: '', boost: '', my: '' };
function zone(el, key) {
if (!el || el.dataset.zoned || !ZONES[key]) return; el.dataset.zoned = '1'; el.classList.add('net-zone');
const lab = document.createElement('div'); lab.className = 'net-zone-label'; lab.textContent = 'Network';
const s = document.createElement('script'); s.async = true; s.src = 'https://linkspin.app/z.js'; s.setAttribute('data-zone', ZONES[key]);
el.appendChild(lab); el.appendChild(s);
}
function pageZones() {
const p = location.pathname.replace(/\/$/, '') || '/';
if (p === '/admin') return;
const after = (el, key) => { if (!el || !el.parentNode) return; const d = document.createElement('div'); el.parentNode.insertBefore(d, el.nextSibling); zone(d, key); };
if (p === '/ledger') after($('rows') && $('rows').closest('section'), 'ledger');
if (p === '/boost') after(document.querySelector('main section'), 'boost');
if (p === '/my') after($('dash'), 'my');
const za = document.createElement('div'); za.className = 'wrap'; document.body.appendChild(za);
zone(za, window.innerWidth >= 760 ? 'footWide' : 'footPhone');
}
const NET = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['viraladblitz', 'ViralAdBlitz', 'https://viraladblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
function netLine(el) {
if (!el) return;
const paint = list => { el.innerHTML = '<b>Part of the network</b> &middot; One account across the network: ' + list.map(s => (s.id === 'viraladblitz' || /viraladblitz\.com/.test(s.url))
? '<span class="here" aria-current="page">' + esc(s.name) + '</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join(' &middot; '); };
paint(NET);
fetch('/api/network-sites').then(r => r.json()).then(l => { if (Array.isArray(l) && l.length) paint(l.some(s => s.id === 'viraladblitz') ? l : l.concat([NET[4]])); }).catch(() => {});
}
function renderFooter() {
pageZones();
const f = document.createElement('footer'); f.className = 'foot';
f.innerHTML = '<div class="wrap"><p><b>ViralAdBlitz</b>, the network\'s text ad wire</p>'
+ '<p>A Boost buys advertising, not income. Nothing is promised.</p>'
+ '<p><a href="/">Front page</a> &middot; <a href="/my">My page</a> &middot; <a href="/boost">Boost</a> &middot; <a href="/promote">Promote</a></p>'
+ '<p class="legal-links"><a href="/terms">Terms</a> &middot; <a href="/disclaimer">Earnings Disclaimer</a> &middot; <a href="/privacy">Privacy</a> &middot; <a href="/contract">Contract</a> &middot; <a href="/ledger">Ledger</a> &middot; <a href="https://instantadpay.com/support" target="_blank" rel="noopener">Support</a></p>'
+ '<p class="co">TrustClickz &middot; 615 Green Valley Drive, Moody, AL 35004</p><p class="netline"></p></div>';
document.body.appendChild(f);
netLine(f.querySelector('.netline'));
toasts();
}
// live toasts: real new ads and Boosts only, bottom-left, one at a time, never older than 30 minutes
let toastsOn = false;
function toasts() {
if (toastsOn) return; toastsOn = true;
const seen = new Set(); let first = true;
const box = document.createElement('div'); box.className = 'toasts'; box.setAttribute('aria-live', 'polite'); document.body.appendChild(box);
const show = c => {
const el = document.createElement('a'); el.className = 'toast';
if (c.kind === 'boost') { el.href = '/ledger'; el.innerHTML = '<b>' + (c.name ? '@' + esc(c.name) : 'A member') + ' just boosted an ad</b><br><span>' + (c.levels ? (c.levels === 1 ? '1 sponsor' : c.levels + ' sponsors') + ' paid in the same transaction' : 'paid on-chain, split by the contract') + '</span>'; }
else { el.href = '/'; el.innerHTML = '<b>' + (c.name ? '@' + esc(c.name) : 'A member') + ' posted a new text ad</b><br><span>' + esc(c.headline) + '</span>'; }
box.appendChild(el); requestAnimationFrame(() => el.classList.add('in'));
setTimeout(() => { el.classList.remove('in'); setTimeout(() => el.remove(), 400); }, 7000);
};
const tick = async () => {
const d = await getJSON('/api/recent').catch(() => null); const all = (d && d.items) || [];
const fresh = all.filter(c => !seen.has(c.key)); all.forEach(c => seen.add(c.key));
const list = first ? fresh.slice(0, 1) : fresh.reverse(); first = false;
list.slice(0, 3).forEach((c, i) => setTimeout(() => show(c), 1500 + i * 8000));
};
tick(); setInterval(tick, 25000);
}
const polOf = (w, d) => { try { const k = BigInt(w || 0); const v = Number(k / 10n ** 12n) / 1e6; return v.toFixed(d != null ? d : (v >= 100 ? 2 : 4)); } catch (e) { return '0'; } };
const when = t => t ? new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : '';
return { $, esc, getConfig, short, framed, status, getJSON, post, n, renderNav, renderFooter, renderTicker, paper, wire, decorate, goHref, polOf, when };
})();
+20
View File
@@ -0,0 +1,20 @@
// Contract proof page (trust pack): live facts from /api/contract (read from Polygon, cached 5 minutes on the server).
(async function () {
VAB.renderNav('/contract'); VAB.renderFooter(); VAB.wire('other').catch(() => {});
const el = document.getElementById('facts'); const esc = VAB.esc;
let d; try { d = await VAB.getJSON('/api/contract'); } catch (e) { d = {}; }
const ex = d.explorer || 'https://polygonscan.com';
const addr = (a, note) => a ? '<a class="mono" href="' + esc(ex) + '/address/' + esc(a) + '" target="_blank" rel="noopener">' + esc(a) + '</a>' + (note ? '<br><span class="muted small">' + note + '</span>' : '') : '<span class="muted">not read yet</span>';
if (!d.address) { el.innerHTML = '<tbody><tr><td class="muted">The contract is not live yet. Its address, owner and every Boost will show here, read straight from Polygon.</td></tr></tbody>'; return; }
const rows = [
['Contract', addr(d.address, 'VABShop on ' + (d.chainId === 137 ? 'Polygon' : 'chain ' + d.chainId))],
['Source code', 'Verified source on Polygonscan and Sourcify: ' + esc(d.verified && d.verified.polygonscan === 'pending' ? 'pending' : 'done')],
['Owner', addr(d.owner, 'A Tangem hardware wallet. It can pause new sales, set the Boost price for future sales and change the keeper. It cannot move anyone\'s money or change the split.')],
['Company', addr(d.company, 'ViralAdBlitz. Fixed in the contract when it was deployed.')],
['Keeper', addr(d.keeper, 'The site\'s signing key. It only signs a buyer\'s sponsor line from the network hub, once, on their first Boost.')],
['Boost', '$' + esc(d.boost && d.boost.usd) + ' for ' + VAB.n(d.boost && d.boost.views) + ' guaranteed views, paid in POL at the live Chainlink price'],
['Sales', d.live ? (d.paused ? '<b>Paused</b>' : 'Open') + ' · ' + VAB.n(d.orderCount) + ' orders so far' : '<span class="muted">' + esc(d.error || 'not read yet') + '</span>'],
['Held by the contract', d.live ? VAB.polOf(d.balanceWei) + ' POL' + (BigInt(d.totalOwedWei || 0) > 0n ? ' (all of it owed to wallets whose payment bounced, waiting for them to claim)' : ' (nothing is kept: every Boost is paid out in the same transaction)') : '<span class="muted">not read yet</span>']
];
el.innerHTML = '<tbody>' + rows.map(r => '<tr><th>' + r[0] + '</th><td>' + r[1] + '</td></tr>').join('') + '</tbody>';
})();
+23
View File
@@ -0,0 +1,23 @@
// Front page: the ticker, today's numbers, "Top ads this week" by verified clicks, the live ledger and the contract box.
(async function () {
VAB.renderNav('/'); VAB.renderFooter();
const $ = VAB.$, esc = VAB.esc;
const d = await VAB.wire('front').catch(() => ({}));
const t = d.today || {};
$('stViews').textContent = VAB.n(t.views); $('stClicks').textContent = VAB.n(t.vclicks); $('stBoosts').textContent = VAB.n(t.boosts); $('stAds').textContent = VAB.n(t.ads);
const items = (d.board && d.board.items) || [];
$('boardCards').innerHTML = items.length ? items.map(x => VAB.paper(x, 'No. ' + x.rank + ' · ' + VAB.n(x.clicks) + ' verified click' + (x.clicks === 1 ? '' : 's'), 'board')).join('')
: '<p class="muted">No verified clicks yet this week. The first ad clicked by a verified visitor takes No. 1.</p>';
// the ledger: the newest Boost rows and their payouts
const L = await VAB.getJSON('/api/ledger?n=6').catch(() => ({}));
const ex = L.explorer || 'https://polygonscan.com';
const who = (a, nm) => nm ? '@' + esc(nm) : esc(VAB.short(a || ''));
const rows = [];
for (const r of (L.items || [])) {
const link = '<a href="' + esc(ex) + '/tx/' + esc(r.tx) + '" target="_blank" rel="noopener">verify</a>';
rows.push('<tr><td>' + VAB.when(r.at) + '</td><td class="ev">Boost bought</td><td>' + who(r.buyer, r.buyerName) + '</td><td>' + VAB.polOf(r.weiPaid) + '</td><td>' + link + '</td></tr>');
for (const p of r.pays || []) if (p.level > 0) rows.push('<tr><td></td><td>Paid level ' + p.level + (p.failed ? ' (waiting to be claimed)' : '') + '</td><td>' + (p.to ? who(p.to, p.name) : 'sponsor') + '</td><td>' + VAB.polOf(p.wei) + '</td><td>' + link + '</td></tr>');
}
$('ledgerMini').querySelector('tbody').innerHTML = rows.length ? rows.slice(0, 12).join('') : '<tr><td colspan="5" class="muted">No Boosts yet. The first one shows here within a minute of its transaction.</td></tr>';
if (L.contract) { $('cAddr').textContent = 'Polygon · ' + L.contract + ' · read it live'; $('cLink').textContent = 'View the contract proof'; }
})();
+51
View File
@@ -0,0 +1,51 @@
// Promote page renderer (2026-11-14). Draws a promo kit (GET /api/promo-kit) into a container: links, creatives grouped by angle,
// swipe lines, headlines, an email and social posts, each with a copy button. Same file on Downline Banners, Viral Banner Blitz and ViralAdBlitz;
// the page script decides the username and the look comes from the site's own CSS (.card, .btn, .kit-*).
window.KitPage = (function () {
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function copy(text, btn) {
try { await navigator.clipboard.writeText(text); } catch (e) {
const t = document.createElement('textarea'); t.value = text; document.body.appendChild(t); t.select(); try { document.execCommand('copy'); } catch (e2) {} t.remove();
}
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1400); }
}
const TXT = [];
const cb = (text, label, cls) => { TXT.push(text); return '<button type="button" class="btn small ' + (cls || 'sec') + '" data-kc="' + (TXT.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
// on the kit's own site, show creatives from this origin (same files; the copied URL stays absolute)
function local(url, k) { try { const u = new URL(url); return u.hostname === k.site && location.hostname !== k.site ? u.pathname : url; } catch (e) { return url; } }
const row = (label, url, cls) => '<div class="kit-row"><div class="kit-l"><span class="kit-lab">' + esc(label) + '</span><code class="kit-url">' + esc(url) + '</code></div>' + cb(url, 'Copy link', cls) + '</div>';
function render(root, k) {
TXT.length = 0;
const angles = []; const by = {};
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
let h = '';
h += '<div class="card"><h3>Your links</h3>' + (k.username ? '<p class="muted small">Every link, creative and line below carries <b>' + esc(k.username) + '</b>.</p>' : '<p class="muted small">Add your network username above so these links carry it.</p>')
+ k.links.map(l => row(l.label, l.url, '') + (l.tracked ? row(l.label + ', tracked', l.tracked, 'sec') : '')).join('')
+ (k.links.some(l => l.tracked) ? '<p class="muted small">A tracked link goes through LinkSpin first, so the network can see which site sent the visit, then opens the same page with your username. Use either one.</p>' : '') + '</div>';
h += '<div class="card"><h3>Creatives</h3><p class="muted small">Download them, or copy the HTML: it already links to you.</p><div class="kit-tabs" role="tablist">'
+ angles.map((c, i) => '<button type="button" class="kit-tab' + (i ? '' : ' on') + '" data-ka="' + esc(c.angle) + '">' + esc(c.angleLabel) + '</button>').join('') + '</div>';
angles.forEach((a, i) => {
h += '<div class="kit-set" data-ks="' + esc(a.angle) + '"' + (i ? ' hidden' : '') + '>' + by[a.angle].map(c =>
'<figure class="kit-fig kit-' + esc(c.shape) + '"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(local(c.url, k)) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy"></a>'
+ '<figcaption><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + 'x' + c.h + '</span><span class="kit-acts"><a class="btn small sec" href="' + esc(c.url) + '" download>Download</a>' + cb(c.url, 'Copy URL') + cb(c.html, 'Copy HTML') + '</span></figcaption></figure>').join('') + '</div>';
});
h += '</div>';
h += '<div class="card"><h3>Short lines</h3><p class="muted small">For chats, comments, text ads and signatures.</p>' + k.lines.map(t => '<div class="kit-row"><p class="kit-txt">' + esc(t) + '</p>' + cb(t) + '</div>').join('') + '</div>';
h += '<div class="card"><h3>Headlines</h3>' + k.headlines.map(t => '<div class="kit-row"><p class="kit-txt"><b>' + esc(t) + '</b></p>' + cb(t) + '</div>').join('') + '</div>';
h += '<div class="card"><h3>Email</h3><div class="kit-row"><p class="kit-txt"><span class="kit-lab">Subject</span>' + esc(k.email.subject) + '</p>' + cb(k.email.subject, 'Copy subject') + '</div>'
+ '<pre class="kit-pre">' + esc(k.email.body) + '</pre><div class="kit-row" style="justify-content:flex-end">' + cb(k.email.body, 'Copy email') + '</div></div>';
h += '<div class="card"><h3>Social posts</h3>' + k.posts.map(t => '<div class="kit-post"><pre class="kit-pre">' + esc(t) + '</pre><div class="kit-row" style="justify-content:flex-end">' + cb(t, 'Copy post') + '</div></div>').join('') + '</div>';
if (k.note) h += '<p class="muted small kit-note">' + esc(k.note) + '</p>';
root.innerHTML = h;
root.querySelectorAll('[data-kc]').forEach(b => b.addEventListener('click', () => copy(TXT[Number(b.dataset.kc)], b)));
root.querySelectorAll('[data-ka]').forEach(b => b.addEventListener('click', () => {
root.querySelectorAll('[data-ka]').forEach(x => x.classList.toggle('on', x === b));
root.querySelectorAll('[data-ks]').forEach(s => { s.hidden = s.dataset.ks !== b.dataset.ka; });
}));
}
async function load(root, u) {
const r = await fetch('/api/promo-kit' + (u ? '?u=' + encodeURIComponent(u) : ''), { cache: 'no-store' });
const k = await r.json(); render(root, k); return k;
}
return { render, load, copy };
})();
+28
View File
@@ -0,0 +1,28 @@
// Live ledger (trust pack): every Boost with every level paid in the same transaction (and its place in the buyer's line), who was
// passed over, the company share and the Boost's delivery, from /api/ledger, refreshed every 30 seconds.
(function () {
VAB.renderNav('/ledger'); VAB.renderFooter(); VAB.wire('other').catch(() => {});
const esc = VAB.esc;
const pol = w => VAB.polOf(w) + ' POL';
const usd = c => '$' + (Number(c || 0) / 100).toFixed(2);
const who = (a, nm) => nm ? '@' + esc(nm) : '<span class="mono">' + esc(VAB.short(a || '')) + '</span>';
async function load() {
let d; try { d = await VAB.getJSON('/api/ledger?n=100'); } catch (e) { return; } if (!d || !d.items) return;
const ex = d.explorer || 'https://polygonscan.com'; const t = d.totals || {};
document.getElementById('totals').innerHTML = '<div class="stat"><b>' + VAB.n(t.boosts) + '</b><span>Boosts on-chain</span></div>'
+ '<div class="stat"><b>' + pol(t.levelsWei) + '</b><span>paid to sponsor levels, same transaction</span></div>'
+ '<div class="stat"><b>' + usd(t.usdCents) + '</b><span>in Boosts, at the price when bought</span></div>'
+ '<div class="stat"><b>0</b><span>withdrawals needed: every Boost pays out in the same transaction</span></div>';
const body = document.querySelector('#rows tbody');
if (!d.items.length) { body.innerHTML = '<tr><td colspan="4" class="muted">No Boosts yet. The first one shows here within a minute of its transaction.</td></tr>'; return; }
body.innerHTML = d.items.map(r => {
const link = '<a href="' + esc(ex) + '/tx/' + esc(r.tx) + '" target="_blank" rel="noopener">verify</a>';
const pays = (r.pays || []).map(p => p.level === 0 ? 'ViralAdBlitz: ' + pol(p.wei)
: 'Level ' + p.level + ': ' + pol(p.wei) + ' to ' + (p.to ? who(p.to, p.name) : 'sponsor') + (p.depth && p.depth !== p.level ? ' <span class="muted">(place ' + p.depth + ')</span>' : '') + (p.failed ? ' <span class="muted">(bounced, waiting in the contract for them to claim)</span>' : '')).join('<br>');
const over = (r.passedOver || []).length ? '<br><span class="muted small">Passed over (no Boost yet): ' + r.passedOver.map(o => (o.name ? '@' + esc(o.name) : esc(VAB.short(o.who))) + ' at place ' + o.depth).join(', ') + '</span>' : '';
const dv = r.delivery ? '<br><span class="muted small">Views delivered: ' + VAB.n(r.delivery.delivered) + ' of ' + VAB.n(r.delivery.views) + '</span>' : '';
return '<tr><td class="small">' + VAB.when(r.at) + '</td><td><span class="pill on">Boost</span><br>' + who(r.buyer, r.buyerName) + ' bought ' + esc(r.what) + ' for ' + usd(r.usdCents) + (r.ad ? '<br><span class="small">"' + esc(r.ad.headline) + '"</span>' : '') + dv + '</td><td class="small">' + pays + over + '</td><td>' + link + '</td></tr>';
}).join('');
}
load(); setInterval(load, 30000);
})();
+26
View File
@@ -0,0 +1,26 @@
// A member's page (viraladblitz.com/<username>): their own ad, the ads of the first five people above them in the network sponsor
// line who have an ad here (labelled by their place in the line), Boosted places, and "join free under this member".
(async function () {
VAB.renderNav(''); VAB.renderFooter();
const $ = VAB.$, esc = VAB.esc;
const name = decodeURIComponent(location.pathname.replace(/^\/+|\/+$/g, ''));
const d = await VAB.wire('member', name).catch(() => ({}));
const pg = d.page;
if (!pg) { $('own').innerHTML = '<div class="card"><h2>No member by that name</h2><p>Check the link, or <a href="/">see the front page</a>.</p></div>'; $('levels').innerHTML = ''; return; }
document.title = '@' + pg.username + ' recommends | ViralAdBlitz';
$('who').textContent = '@' + pg.username.toUpperCase() + ' RECOMMENDS';
$('teamHead').textContent = 'Also recommended by @' + pg.username + '\'s team';
if (pg.ad) {
const a = pg.ad;
$('own').innerHTML = '<article class="paper big">' + (a.boosted ? '<span class="tag">★ BOOSTED</span>' : '') + '<h1>' + esc(a.headline) + '</h1><p>' + esc(a.line1) + (a.line2 ? ' ' + esc(a.line2) : '') + '</p>'
+ '<div class="row" style="margin-top:4px"><a class="btn-green" data-go="' + a.id + '" data-p="own" target="_blank" rel="noopener sponsored" href="' + VAB.goHref(a.id, 'own') + '">Take a look</a><span class="host mono small" style="color:var(--paper-sub)">' + esc(a.host) + ' · this member\'s own ad</span></div></article>';
} else $('own').innerHTML = '<div class="card"><h2>@' + esc(pg.username) + ' has not posted an ad yet</h2><p>Their team\'s ads are below.</p></div>';
const rows = (pg.line || []).map(x => '<div class="lvl' + (x.boosted ? ' star' : '') + '"><span class="no">LEVEL ' + x.level + '</span><div class="txt"><b>' + esc(x.headline) + '</b><div>' + esc(x.line1) + (x.line2 ? ' ' + esc(x.line2) : '') + ' ' + esc(x.owner) + (x.boosted ? ' · ★ Boosted' : '') + '</div></div>'
+ '<a class="btn-line" data-go="' + x.id + '" data-p="level' + x.level + '" target="_blank" rel="noopener sponsored" href="' + VAB.goHref(x.id, 'level' + x.level) + '">Visit</a></div>');
for (let i = rows.length; i < 5; i++) rows.push('<div class="lvl open"><span class="no">OPEN</span><div class="txt"><b>An open place</b><div>' + (pg.hubOk === false && !i ? 'The network line is loading slowly. Try again in a minute.' : 'When more of this member\'s line posts an ad, it shows here.') + '</div></div></div>');
$('levels').innerHTML = rows.join('');
if ((pg.boosted || []).length) { $('boostedSec').hidden = false; $('boosted').innerHTML = pg.boosted.map(x => VAB.paper(x, '', 'boosted')).join(''); }
$('joinHead').textContent = 'Want your ad on pages like this one?';
$('joinText').textContent = 'Join free under @' + pg.username + '. Your ad goes on your own page and on every page you bring in, five levels down.';
$('joinBtn').href = pg.joinUrl; $('joinBtn').target = '_blank'; $('joinBtn').rel = 'noopener';
})();
+62
View File
@@ -0,0 +1,62 @@
// My page: sign in (network or wallet), post or edit the one free text ad, the member's page link, their line, Boost delivery,
// and what the contract has paid them.
(async function () {
VAB.renderNav('/my'); VAB.renderFooter(); VAB.wire('other').catch(() => {});
const $ = VAB.$, esc = VAB.esc;
const c = await VAB.getConfig().catch(() => ({}));
const me = await VAB.getJSON('/api/me');
if (!me.signedIn) {
// signed in on InstantAdPay already? one quick hop there and back signs you in here too
try { const ss = await VAB.getJSON('/api/sso/status'); if (ss && ss.check) { location.replace('/sso/start?mode=check&via=iap&to=' + encodeURIComponent('/my')); return; } } catch (e) {}
$('signin').hidden = false;
if (!c.sso) { $('viaIap').hidden = true; $('viaLs').hidden = true; }
if (c.joinUrl) $('joinLink').href = c.joinUrl;
$('viaWallet').onclick = async () => {
try { VAB.status('Check your wallet for the sign-in message.'); await VABWallet.signIn(); location.reload(); }
catch (e) { VAB.status(String(e && e.message || e).slice(0, 300), 'err'); }
};
return;
}
$('signout').onclick = async () => { await VAB.post('/api/auth/logout'); location.reload(); };
const counter = (inp, out, max) => { const f = () => { out.textContent = inp.value.length + ' / ' + max; }; inp.addEventListener('input', f); f(); };
const copyText = (t, b) => { try { navigator.clipboard.writeText(t); b.textContent = 'Copied'; setTimeout(() => { b.textContent = 'Copy my link'; }, 1400); } catch (e) {} };
async function load() {
const d = await VAB.getJSON('/api/my'); if (d.error) { VAB.status(d.error, 'err'); return; }
$('dash').hidden = false;
const a = d.ad; const lim = c.ad || { headline: 60, line: 90 };
$('stats').innerHTML = '<div class="stat"><b>' + (d.username ? '@' + esc(d.username) : esc(VAB.short(d.address))) + '</b><span>' + (d.netVerified ? 'network member' : 'not in the network yet') + '</span></div>'
+ '<div class="stat"><b>' + VAB.n(a ? a.views : 0) + '</b><span>verified views of your ad</span></div>'
+ '<div class="stat"><b>' + VAB.n(a ? a.vclicks : 0) + '</b><span>verified clicks</span></div>'
+ '<div class="stat"><b>' + VAB.polOf(d.earned && d.earned.wei) + '</b><span>POL paid to you by the contract</span></div>';
$('pageCard').innerHTML = d.page
? '<h2>Your page</h2><p>Share it anywhere. It shows your ad and the five people above you, and everyone who joins through it shows your ad on their page.</p><p class="mono" style="overflow-wrap:anywhere"><a id="pageLink" href="' + esc(d.page) + '" target="_blank" rel="noopener">' + esc(d.page) + '</a></p><div class="row"><button class="btn-line" type="button" id="copyPage">Copy my link</button><a class="btn-quiet" href="/promote">Promo kit</a></div>'
: '<h2>Your page</h2><p>Your page address uses your network username. Sign in through InstantAdPay or LinkSpin once and it is set.</p>';
if ($('copyPage')) $('copyPage').onclick = () => copyText(d.page, $('copyPage'));
if (!d.netVerified) {
$('adNote').innerHTML = 'Text ads are free for network members. This wallet is not in the network yet: <a href="' + esc(d.joinUrl) + '" target="_blank" rel="noopener">join InstantAdPay free</a>, link this wallet there, then sign in here through InstantAdPay.';
$('adForm').hidden = true;
} else {
$('adForm').hidden = false;
if (a) { $('adHead').textContent = 'Your text ad' + (a.status !== 'live' ? ' (' + a.status + ')' : ''); $('fHead').value = a.headline; $('fL1').value = a.line1; $('fL2').value = a.line2 || ''; $('fLink').value = a.link; $('adSave').textContent = 'Save changes'; }
counter($('fHead'), $('cHead'), lim.headline); counter($('fL1'), $('cL1'), lim.line); counter($('fL2'), $('cL2'), lim.line);
}
$('line').innerHTML = (d.line || []).length ? '<p class="small">The people above you in the network, nearest first. Your page shows the first five who have an ad here.</p>'
+ d.line.map(x => '<div class="kit-row"><span class="mono" style="color:var(--amber);width:84px">PLACE ' + x.depth + '</span><span style="flex:1">' + (x.username ? '@' + esc(x.username) : 'a member') + '</span><span class="pill' + (x.hasAd ? ' on' : '') + '">' + (x.hasAd ? 'ad live' : 'no ad yet') + '</span></div>').join('')
: '<p class="small">' + (d.lineOk === false ? 'The network line could not be read just now. Try again in a minute.' : 'No sponsor line is known for you in the network yet.') + '</p>';
$('boosts').innerHTML = (d.boosts || []).length ? d.boosts.map(b => '<div class="kit-row" style="flex-direction:column;align-items:stretch"><div style="display:flex;justify-content:space-between;gap:10px;flex-wrap:wrap"><span>' + VAB.when(b.at) + ' · ' + VAB.n(b.views) + ' guaranteed views</span><span class="pill' + (b.status === 'delivered' ? ' done' : ' on') + '">' + esc(b.status.replace(/-/g, ' ')) + '</span></div>'
+ '<div class="meter"><i style="width:' + Math.min(100, Math.round(b.delivered / b.views * 100)) + '%"></i></div><span class="small muted">' + VAB.n(b.delivered) + ' of ' + VAB.n(b.views) + ' delivered' + (b.nas ? ' (' + VAB.n(b.nas) + ' through Network Ad Space)' : '') + (b.dueAt && b.status === 'delivering' ? ' · on-site until ' + VAB.when(b.dueAt) : '') + '</span></div>').join('')
: '<p class="small">No Boosts yet. A Boost is $' + (c.boost ? c.boost.usd : 5) + ' once and buys ' + VAB.n(c.boost ? c.boost.views : 500) + ' guaranteed network views for your ad.</p>';
const ex = c.explorer || 'https://polygonscan.com';
$('earned').innerHTML = (d.earned && d.earned.items.length) ? d.earned.items.map(x => '<div class="kit-row"><span class="small">' + VAB.when(x.at) + '</span><span style="flex:1">Level ' + x.level + ' share from ' + (x.buyerName ? '@' + esc(x.buyerName) : 'a Boost') + (x.failed ? ' (waiting in the contract for you to claim)' : '') + '</span><b class="mono">' + VAB.polOf(x.wei) + ' POL</b><a class="small" href="' + esc(ex) + '/tx/' + esc(x.tx) + '" target="_blank" rel="noopener">verify</a></div>').join('')
: '<p class="small">Nothing yet. The contract pays a level share in the same transaction when someone in your team buys a Boost, if you have bought one yourself. Advertising, not income. Nothing is promised.</p>';
}
$('adForm').addEventListener('submit', async e => {
e.preventDefault(); $('adSave').disabled = true; VAB.status('Checking your link...');
const r = await VAB.post('/api/my/ad', { headline: $('fHead').value, line1: $('fL1').value, line2: $('fL2').value, link: $('fLink').value });
$('adSave').disabled = false;
if (r.error) return VAB.status(r.error, 'err');
VAB.status(r.created ? 'Posted. Your ad is live on your page and on your team\'s pages.' : 'Saved. Your ad shows the new text everywhere.', 'ok');
load();
});
await load();
})();
+19
View File
@@ -0,0 +1,19 @@
// Promote page: the promo kit from /api/promo-kit with the member's network username in every link.
// Username: ?u= first, then the signed-in member's, then the last one typed here (this browser only).
(async function () {
VAB.renderNav('/promote'); VAB.renderFooter(); VAB.wire('other').catch(() => {});
const $ = VAB.$; const RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/;
let u = new URLSearchParams(location.search).get('u') || ''; let signed = false;
if (!RE.test(u)) { u = ''; try { const me = await VAB.getJSON('/api/me'); if (me.signedIn) { u = me.username || me.address || ''; signed = true; } } catch (e) {} }
if (!u) { try { u = localStorage.getItem('kit.u') || ''; } catch (e) {} if (!RE.test(u)) u = ''; }
$('whoIn').value = u;
if (signed) $('whoNote').textContent = 'Signed in: your links below use ' + (u.startsWith('0x') ? 'your wallet (no network username found yet)' : '@' + u) + '.';
async function show(name) { try { await KitPage.load($('kit'), name); VAB.status(''); } catch (e) { VAB.status('Could not load the kit. Try again in a moment.', 'err'); } }
$('whoForm').addEventListener('submit', e => {
e.preventDefault(); const v = $('whoIn').value.trim().replace(/^@/, '');
if (v && !RE.test(v)) return VAB.status('That does not look like a username: letters, numbers, dot, dash or underscore.', 'err');
try { localStorage.setItem('kit.u', v); } catch (e2) {}
show(v);
});
show(u);
})();
+2
View File
@@ -0,0 +1,2 @@
// Legal and other plain pages: nav, the ticker (its views count like any page), footer.
(function () { VAB.renderNav(''); VAB.renderFooter(); VAB.wire('other').catch(() => {}); })();
+196
View File
@@ -0,0 +1,196 @@
/* ViralAdBlitz: the stock-ticker newsroom look (mockup approved by Marty 2026-11-14, canvas BRddgcFA8wbTKbHiWc8sjk).
Deep ink-green ground, glowing amber ticker, newsprint cream cards, Playfair Display headlines, IBM Plex Mono figures + IBM Plex Sans text.
Its own look: not DLB ultraviolet, not VBB pop-art, not IAP mint, not LinkSpin. Class names are neutral (no ad/banner words). */
:root{
--bg:#0a1712; --bg2:#07110d; --panel:#0f2219; --line:#1f3a2d; --line2:#3a5a49;
--amber:#ffb000; --amber2:#ffd166; --cream:#f4efe3; --paper-ink:#13201a; --paper-sub:#4b6355; --paper-gold:#7a5a00;
--green:#0b5d3b; --green2:#0e7a4d; --text:#e8efe9; --sub:#b9c8bd; --muted:#8fa89a; --nav:#c9d6cd; --bad:#ff7a6b; --good:#6fe3a6;
--disp:'Playfair Display',Georgia,'Times New Roman',serif; --mono:'IBM Plex Mono',ui-monospace,Menlo,Consolas,monospace; --body:'IBM Plex Sans',system-ui,-apple-system,'Segoe UI',sans-serif;
}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--text);font:16px/1.55 var(--body);min-height:100vh;overflow-x:hidden}
a{color:var(--amber)} a:hover{color:var(--amber2)}
img{max-width:100%}
.wrap{max-width:1180px;margin:0 auto;padding:0 24px}
@media (max-width:600px){.wrap{padding:0 16px}}
.mono{font-family:var(--mono)} .muted{color:var(--muted)} .small{font-size:13.5px} .sub{color:var(--sub)}
h1,h2,h3{font-family:var(--disp);color:var(--cream);line-height:1.08;margin:0}
h1{font-weight:900;font-size:clamp(36px,6.4vw,64px);letter-spacing:-.5px}
h2{font-size:clamp(26px,3.6vw,34px);font-weight:700}
h3{font-size:22px;font-weight:700}
main{padding:40px 0 56px;display:flex;flex-direction:column;gap:44px}
main.wrap{padding-top:40px}
/* top bar */
nav.top{border-bottom:1px solid var(--line);background:var(--bg2)}
nav.top .wrap{display:flex;align-items:center;gap:18px;flex-wrap:wrap;padding-top:14px;padding-bottom:14px}
.brand{display:flex;align-items:baseline;gap:10px;margin-right:auto;text-decoration:none}
.brand .wm{font-family:var(--disp);font-weight:900;font-size:28px;color:var(--cream);letter-spacing:-.5px}
.brand .live{font:600 12px var(--mono);color:var(--amber);border:1px solid var(--amber);padding:2px 6px;letter-spacing:1px}
nav.top .links{display:flex;gap:16px;flex-wrap:wrap;font-size:14px}
nav.top .links a{color:var(--nav);text-decoration:none;padding:4px 0;border-bottom:2px solid transparent}
nav.top .links a:hover,nav.top .links a.on{color:var(--cream);border-bottom-color:var(--amber)}
.cta{background:var(--amber);color:#1a1200;font-weight:600;padding:12px 18px;text-decoration:none;font-size:14px;border:0;cursor:pointer;display:inline-block;font-family:var(--body)}
.cta:hover{background:var(--amber2);color:#1a1200}
@media (max-width:760px){nav.top .links{width:100%;order:3;gap:14px;overflow-x:auto;white-space:nowrap;flex-wrap:nowrap;padding-bottom:2px}.brand .wm{font-size:24px}}
/* the amber ticker */
.ticker{background:#000;border-bottom:2px solid var(--amber);overflow:hidden;white-space:nowrap;font:15px var(--mono);color:var(--amber);position:relative}
.ticker .run{display:inline-block;padding:12px 0;animation:vabtick var(--tick-s,60s) linear infinite;will-change:transform}
.ticker:hover .run{animation-play-state:paused}
.ticker a{color:var(--amber);text-decoration:none;padding:0 26px}
.ticker a:hover{color:var(--amber2);text-decoration:underline}
.ticker a.star{color:#fff}
.ticker a.star b{color:var(--amber)}
.ticker .empty{padding:12px 24px;display:inline-block;color:var(--muted)}
@keyframes vabtick{from{transform:translateX(0)}to{transform:translateX(-50%)}}
@media (prefers-reduced-motion:reduce){.ticker .run{animation:none}.ticker{overflow-x:auto}}
/* hero */
.hero{display:flex;flex-wrap:wrap;gap:40px;align-items:flex-end}
.hero .copy{flex:999 1 560px;min-width:0}
.kicker{margin:0 0 12px;font:600 13px var(--mono);color:var(--amber);letter-spacing:2px;text-transform:uppercase}
.lead{margin:20px 0 0;font-size:19px;line-height:1.55;color:var(--sub);max-width:660px}
.row{display:flex;gap:12px;flex-wrap:wrap;align-items:center;margin-top:20px}
.wirebox{flex:1 1 300px;border:1px solid var(--line);background:var(--panel);padding:20px;display:flex;flex-direction:column;gap:12px}
.wirebox .lab{font:12px var(--mono);color:var(--muted);letter-spacing:1px}
.wirebox .kv{display:flex;justify-content:space-between;border-bottom:1px dashed var(--line);padding-bottom:8px}
.wirebox .kv:last-child{border-bottom:0;padding-bottom:0}
.wirebox .kv b{font-family:var(--mono);color:var(--amber)}
/* section heads */
.shead{display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:8px;border-bottom:3px double var(--line2);padding-bottom:10px;margin-bottom:16px}
.shead .side{font:13px var(--mono);color:var(--muted)}
section{min-width:0}
/* newsprint ad cards */
.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
@media (max-width:900px){.cards{grid-template-columns:repeat(2,minmax(0,1fr))}}
@media (max-width:600px){.cards{grid-template-columns:minmax(0,1fr)}}
.paper{background:var(--cream);color:var(--paper-ink);padding:18px;border-top:6px solid var(--line2);display:flex;flex-direction:column;gap:8px;min-width:0}
.paper.star{border-top-color:var(--amber)}
.paper .tag{font:11px var(--mono);color:var(--paper-sub);letter-spacing:1px;text-transform:uppercase}
.paper.star .tag{color:var(--paper-gold)}
.paper h3{color:var(--paper-ink);font-size:22px;overflow-wrap:anywhere}
.paper p{margin:0;font-size:15px;line-height:1.45;overflow-wrap:anywhere}
.paper .visit{color:var(--green);font-weight:600;font-size:14px;margin-top:auto}
.paper .visit:hover{color:var(--green2)}
.paper .host{font:12px var(--mono);color:var(--paper-sub)}
.paper.big{padding:32px;border-top-width:8px;border-top-color:var(--amber)}
.paper.big h1{color:var(--paper-ink);font-size:clamp(32px,5.2vw,52px);line-height:1.05;overflow-wrap:anywhere}
.paper.big p{font-size:20px;line-height:1.5;max-width:720px}
.btn-green{background:var(--green);color:#fff;font-weight:600;padding:14px 22px;text-decoration:none;font-size:16px;border:0;cursor:pointer;display:inline-block;font-family:var(--body)}
.btn-green:hover{background:var(--green2);color:#fff}
.btn-green:disabled{opacity:.55;cursor:not-allowed}
.btn-line{border:1px solid var(--amber);color:var(--amber);padding:10px 14px;text-decoration:none;font-size:14px;background:transparent;cursor:pointer;display:inline-block;font-family:var(--body)}
.btn-line:hover{background:rgba(255,176,0,.08);color:var(--amber2)}
.btn-quiet{border:1px solid var(--line2);color:var(--sub);padding:10px 14px;background:transparent;cursor:pointer;font-family:var(--body);font-size:14px;text-decoration:none;display:inline-block}
/* member page: the five-level rows */
.levels{display:flex;flex-direction:column;gap:10px}
.lvl{display:flex;gap:16px;align-items:center;border:1px solid var(--line);background:var(--panel);padding:16px 20px;flex-wrap:wrap}
.lvl .no{font:13px var(--mono);color:var(--amber);width:84px;flex:0 0 auto}
.lvl .txt{flex:999 1 400px;min-width:0}
.lvl .txt b{font-family:var(--disp);font-size:20px;color:var(--cream);overflow-wrap:anywhere}
.lvl .txt div{color:var(--sub);font-size:15px;overflow-wrap:anywhere}
.lvl.star{border-color:var(--amber)}
.lvl.open .txt b{color:var(--muted)}
.joinbar{background:var(--panel);border:1px solid var(--amber);padding:24px;display:flex;flex-wrap:wrap;gap:20px;align-items:center}
.joinbar .txt{flex:999 1 480px;min-width:0}
.joinbar b{font-family:var(--disp);font-size:26px;color:var(--cream)}
.joinbar p{margin:8px 0 0;color:var(--sub)}
/* steps, stats, boxes */
.steps{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:16px}
@media (max-width:760px){.steps{grid-template-columns:minmax(0,1fr)}}
.step{border:1px solid var(--line);padding:20px;display:flex;flex-direction:column;gap:8px}
.step .n{font-family:var(--disp);font-size:40px;color:var(--amber);line-height:1}
.step b{font-size:17px} .step span{color:var(--sub)}
.splits{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:10px;font-family:var(--mono)}
@media (max-width:900px){.splits{grid-template-columns:repeat(3,minmax(0,1fr))}}
@media (max-width:420px){.splits{grid-template-columns:repeat(2,minmax(0,1fr))}}
.split{border:1px solid var(--line);padding:16px;display:flex;flex-direction:column;gap:6px;min-width:0}
.split span{color:var(--muted);font-size:12px} .split b{color:var(--amber);font-size:26px} .split i{color:var(--sub);font-size:12px;font-style:normal}
.split.co{border-color:var(--line2);background:var(--panel)} .split.co b{color:var(--cream)}
.stats{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}
@media (max-width:760px){.stats{grid-template-columns:repeat(2,minmax(0,1fr))}}
.stat{border:1px solid var(--line);background:var(--panel);padding:14px;display:flex;flex-direction:column;gap:4px;min-width:0}
.stat b{font:600 22px var(--mono);color:var(--amber);overflow-wrap:anywhere} .stat span{color:var(--sub);font-size:13px}
.box{background:var(--panel);border:1px solid var(--line);padding:24px;display:flex;flex-wrap:wrap;gap:24px;align-items:center}
.box .txt{flex:999 1 480px;min-width:0;display:flex;flex-direction:column;gap:8px}
.box .lab{font:12px var(--mono);color:var(--amber);letter-spacing:1px}
.box .big{font-family:var(--disp);font-size:26px;color:var(--cream);font-weight:700;line-height:1.2}
.box .addr{font:14px var(--mono);color:var(--sub);word-break:break-all}
.card{background:var(--panel);border:1px solid var(--line);padding:22px;min-width:0}
.card h2,.card h3{margin-bottom:10px}
.card p{color:var(--sub)}
.card p:last-child{margin-bottom:0}
.price{flex:1 1 320px;background:var(--cream);color:var(--paper-ink);padding:28px;border-top:8px solid var(--amber);display:flex;flex-direction:column;gap:14px}
.price .lab{font:12px var(--mono);color:var(--paper-gold);letter-spacing:1px}
.price .amt{font-family:var(--disp);font-size:48px;font-weight:900;line-height:1}
.price .pol{font:14px var(--mono);color:var(--paper-sub)}
.price ul{margin:0;padding-left:18px;line-height:1.7;font-size:15px}
.price .qty{display:flex;gap:10px;align-items:center;font-size:14px}
.price select{font:15px var(--mono);padding:8px;border:1px solid var(--paper-sub);background:#fff;color:var(--paper-ink)}
/* tables (ledger) */
.tscroll{overflow-x:auto;-webkit-overflow-scrolling:touch}
table.t{width:100%;border-collapse:collapse;font:14px var(--mono)}
table.t th{padding:10px 8px;border-bottom:1px solid var(--line);color:var(--muted);text-align:left;font-weight:400;white-space:nowrap}
table.t td{padding:10px 8px;border-bottom:1px dashed var(--line);vertical-align:top}
table.t td.ev{color:var(--amber)}
table.facts th{width:30%;color:var(--muted);font-weight:400;text-align:left;vertical-align:top;padding:10px 8px;border-bottom:1px dashed var(--line)}
table.facts td{padding:10px 8px;border-bottom:1px dashed var(--line);overflow-wrap:anywhere}
@media (max-width:600px){table.t{font-size:12.5px}table.facts th{width:38%}}
/* forms */
label.f{display:flex;flex-direction:column;gap:6px;font:13px var(--mono);color:var(--muted)}
.f input,.f textarea{background:var(--bg2);border:1px solid var(--line2);color:var(--text);font:16px var(--body);padding:11px 12px;width:100%;border-radius:0}
.f input:focus,.f textarea:focus{outline:2px solid var(--amber);outline-offset:1px}
.f .cnt{align-self:flex-end;font-size:12px}
.form{display:flex;flex-direction:column;gap:14px;max-width:720px}
.note{border-left:4px solid var(--amber);background:var(--panel);padding:12px 16px;color:var(--sub);overflow-wrap:anywhere}
.note.ok{border-left-color:var(--good);color:var(--text)} .note.err{border-left-color:var(--bad);color:var(--text)}
.pill{display:inline-block;font:11px var(--mono);letter-spacing:1px;text-transform:uppercase;border:1px solid var(--line2);padding:2px 6px;color:var(--sub)}
.pill.on{border-color:var(--amber);color:var(--amber)} .pill.done{border-color:var(--good);color:var(--good)}
.meter{height:8px;background:var(--bg2);border:1px solid var(--line);margin-top:6px} .meter i{display:block;height:100%;background:var(--amber)}
.signin{display:flex;flex-wrap:wrap;gap:12px}
.legal .card h2{font-size:24px}
.legal .card li{color:var(--sub);margin:4px 0}
/* toasts (real events only) */
.toasts{position:fixed;left:24px;bottom:24px;z-index:50;display:flex;flex-direction:column;gap:10px;max-width:min(340px,calc(100vw - 32px))}
.toast{background:var(--cream);color:var(--paper-ink);border-left:6px solid var(--amber);padding:12px 16px;font-size:14px;box-shadow:0 8px 24px rgba(0,0,0,.45);text-decoration:none;opacity:0;transform:translateY(12px);transition:opacity .35s,transform .35s}
.toast.in{opacity:1;transform:none}
.toast span{color:var(--paper-sub)}
@media (max-width:600px){.toasts{left:16px;bottom:16px}}
/* footer */
footer.foot{border-top:1px solid var(--line);padding:28px 0 36px;color:var(--muted);font-size:13px;text-align:center}
footer.foot p{margin:6px 0} footer.foot a{color:var(--nav)} footer.foot a:hover{color:var(--amber)}
footer.foot .netline a{color:var(--amber)} footer.foot .here{color:var(--cream);font-weight:600}
.net-zone{margin:18px auto;text-align:center}
.net-zone-label{font:11px var(--mono);color:var(--muted);margin-bottom:4px;letter-spacing:1px}
/* promote page (kit) */
.kit-who{display:flex;gap:10px;flex-wrap:wrap;margin-top:10px}
.kit-who input{flex:1 1 220px;min-width:0;background:var(--bg2);border:1px solid var(--line2);padding:11px 12px;color:var(--text);font:14px var(--mono)}
.kit-row{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:10px 0;border-top:1px dashed var(--line)}
.kit-row:first-of-type{border-top:0}
.kit-l{flex:1 1 260px;min-width:0;display:flex;flex-direction:column;gap:3px}
.kit-lab{display:block;font:11px var(--mono);color:var(--muted);text-transform:uppercase;letter-spacing:.1em}
.kit-url{font-family:var(--mono);font-size:13.5px;overflow-wrap:anywhere;color:var(--amber)}
.kit-txt{flex:1 1 300px;margin:0;min-width:0;color:var(--sub)}
.kit-pre{white-space:pre-wrap;font-family:var(--body);font-size:14.5px;line-height:1.55;margin:10px 0 0;padding:12px 14px;border:1px solid var(--line);background:var(--bg2);overflow-wrap:anywhere;color:var(--sub)}
.kit-tabs{display:flex;gap:8px;flex-wrap:wrap;margin:6px 0 16px}
.kit-tab{font:600 13px var(--mono);padding:9px 13px;border:1px solid var(--line2);background:transparent;color:var(--sub);cursor:pointer}
.kit-tab.on{border-color:var(--amber);color:var(--amber)}
.kit-set{display:flex;flex-wrap:wrap;gap:18px;align-items:flex-start}
.kit-fig{margin:0;display:flex;flex-direction:column;gap:8px;max-width:100%}
.kit-fig img{display:block;max-width:100%;height:auto}
.kit-social img{width:600px} .kit-square img{width:360px}
.kit-fig figcaption{font-size:13px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}
.kit-acts{display:flex;gap:6px;flex-wrap:wrap;width:100%}
.btn{font:600 13px var(--body);padding:8px 12px;border:1px solid var(--amber);color:var(--amber);background:transparent;cursor:pointer;text-decoration:none;display:inline-block}
.btn.sec{border-color:var(--line2);color:var(--sub)} .btn.small{font-size:12.5px;padding:6px 10px}
+233
View File
@@ -0,0 +1,233 @@
// ViralAdBlitz wallet sign-in: the VBB / Downline Banners wallet.js (same AppKit build, chain guard, dead-session recovery)
// with its buy flow (2026-11-14): sendTx() hard-guards the chain, sets Polygon's fee floor from /api/gas and recovers a dead
// WalletConnect session once; waitTx() polls /api/tx; balance() is the pre-flight check. The page builds the call on the server.
window.VABWallet = (function () {
const pad = v => BigInt(v).toString(16).padStart(64, '0');
const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); };
// Normalize a chainId to a decimal number. eth_chainId is meant to return a
// hex string, but some wallets return a number or a decimal string — compare
// numerically so a wallet's shape never crashes the flow.
const chainNum = v => {
if (v == null) return NaN;
if (typeof v === 'number') return v;
const s = String(v).trim();
return /^0x/i.test(s) ? parseInt(s, 16) : parseInt(s, 10);
};
const APPKIT_URL = 'https://cdn.jsdelivr.net/npm/@reown/appkit-cdn@1.8.23/dist/appkit.js';
let modal = null, akPromise = null, provider = null;
async function initAppKit(c) {
if (modal) return modal;
if (akPromise) return akPromise;
akPromise = (async () => {
const mod = await import(APPKIT_URL);
const { createAppKit, WagmiAdapter, networks } = mod;
const netMap = { 80002: networks.polygonAmoy, 137: networks.polygon, 31337: networks.hardhat || networks.localhost };
const base = netMap[Number(c.chainId)] || networks.polygonAmoy;
// Override the chain's RPC with our clean public endpoint. AppKit's built-in
// networks advertise the WalletConnect RPC proxy
// (rpc.walletconnect.org/v1/?chainId=…&projectId=…) as the chain RPC, and
// wallets reject that query-string URL as "Invalid URL" when adding/switching
// the network — the cause of Trust's "Invalid URL", MetaMask's switch loop,
// and the failed mobile buy (the chain switch never completed).
const rpc = String(c.rpc || '').trim();
const net = rpc ? Object.assign({}, base, { rpcUrls: { default: { http: [rpc] }, public: { http: [rpc] } } }) : base;
// Accept the wallet's usual networks too, so AppKit doesn't trap the user in
// its own "Switch Network" modal — that modal loops on a testnet the wallet
// can't auto-add. We switch to `net` ourselves (wallet_addEthereumChain adds
// + switches in one step) and sendTx hard-guards the chain before signing.
const allNets = [net];
for (const k of ['polygon', 'mainnet']) {
try { const n = networks[k]; if (n && n.id !== net.id) allNets.push(n); } catch (e) {}
}
const projectId = String(c.walletConnectProjectId || '').trim();
const wagmiAdapter = new WagmiAdapter({ networks: allNets, projectId });
modal = createAppKit({
adapters: [wagmiAdapter], networks: allNets, projectId, defaultNetwork: net,
metadata: { name: 'ViralAdBlitz', description: 'The network text ad wire.',
url: location.origin, icons: [location.origin + '/art/icon-192.png'] },
features: { analytics: false, email: false, socials: [] },
// Picker order: wallets without Trust's balance-proportion block go first.
// Trust Wallet is NOT excluded; it just drops out of the featured row into
// "All wallets" (Marty, 2026-09-09: move Trust to the bottom, not off).
featuredWalletIds: [
'0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150', // SafePal (recommended, listed first)
'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96', // MetaMask
'a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393', // Phantom
'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa' // Coinbase Wallet
]
});
return modal;
})();
return akPromise;
}
function currentAddress() { try { return (modal && modal.getAddress && modal.getAddress()) || null; } catch (e) { return null; } }
function waitForConnection(timeoutMs) {
if (currentAddress()) return Promise.resolve(currentAddress());
return new Promise((resolve, reject) => {
let done = false, unsub = null;
const finish = (addr, err) => { if (done) return; done = true; try { unsub && unsub(); } catch (e) {} err ? reject(err) : resolve(addr); };
try { unsub = modal.subscribeAccount(acc => { if (acc && acc.isConnected && acc.address) finish(acc.address); }); } catch (e) {}
const t0 = Date.now();
(function poll() {
if (done) return;
const a = currentAddress();
if (a) return finish(a);
if (Date.now() - t0 > (timeoutMs || 180000)) return finish(null, new Error('Wallet connection timed out. Tap Connect and try again.'));
setTimeout(poll, 400);
})();
});
}
async function resolveProvider() {
for (let i = 0; i < 20; i++) {
try { const p = modal.getWalletProvider ? await Promise.resolve(modal.getWalletProvider()) : null; if (p && p.request) return p; } catch (e) {}
await new Promise(r => setTimeout(r, 300));
}
throw new Error('Could not reach your wallet. Try connecting again.');
}
function eth() { if (!provider) throw new Error('Connect your wallet first.'); return provider; }
const isInjected = () => !!(provider && window.ethereum && (provider === window.ethereum || provider.isMetaMask));
// the account the wallet will actually sign with: for an injected wallet (MetaMask
// extension) that is its active account, which can differ from AppKit's cached one
async function activeAddress(fallback) {
if (isInjected()) { try { const a = await provider.request({ method: 'eth_accounts' }); if (a && a[0]) return a[0]; } catch (e) {} }
return fallback || currentAddress();
}
// Force the wallet's own account picker. Injected wallets stay connected to the
// site, so a plain disconnect/reconnect never shows one: asking for permissions
// again makes MetaMask open its account-selection prompt, and whatever the user
// ticks becomes the active account. WalletConnect wallets fall back to a fresh
// session (the picker + the wallet app's own account choice).
async function pickAccount() {
const c = await VAB.getConfig();
await initAppKit(c);
const inj = window.ethereum;
if (inj && inj.request) {
try {
await inj.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }] });
const accs = await inj.request({ method: 'eth_accounts' });
if (accs && accs[0]) { provider = inj; await ensureChain(c).catch(() => {}); return accs[0]; }
} catch (e) {
if (e && (e.code === 4001 || /reject|denied/i.test(String(e.message || '')))) throw new Error('You closed the account picker. Pick the account you want and try again.');
}
}
return freshConnect(c);
}
// A WalletConnect session can die underneath AppKit's cached "connected"
// state: the wallet app rejects or kills it (Trust does this after its own
// security stop), the phone sleeps, the relay drops. AppKit still reports an
// address, so the next request fails with a "disconnected" style error.
// Detect that, wipe the stale session, and re-open the picker for a fresh one.
const DEAD_RE = /disconnect|not connected|no matching key|session (topic|expired|deleted|not found)|call connect|please call connect|missing or invalid|relay/i;
const isDead = e => DEAD_RE.test(String((e && e.message) || e || ''));
async function freshConnect(c) {
try { VAB.status('Your wallet session dropped. Reconnect in the picker…'); } catch (e) {}
await disconnect();
try { await modal.open(); } catch (e) {}
const addr = await waitForConnection(180000);
try { if (modal && modal.close) await modal.close(); } catch (e) {}
provider = await resolveProvider();
await ensureChain(c).catch(() => {});
return addr;
}
async function connect() {
const c = await VAB.getConfig();
await initAppKit(c);
let addr = currentAddress();
if (!addr) {
// give AppKit a moment to rehydrate an existing session before popping the
// picker — otherwise an already-connected wallet still gets the modal
for (let i = 0; i < 8 && !addr; i++) { await new Promise(r => setTimeout(r, 150)); addr = currentAddress(); }
}
if (!addr) { try { await modal.open(); } catch (e) {} addr = await waitForConnection(180000); }
try { if (modal && modal.close) await modal.close(); } catch (e) {} // dismiss the picker once we're connected
provider = await resolveProvider();
// probe the session: a dead WalletConnect session answers with a disconnect error
try { await provider.request({ method: 'eth_chainId' }); }
catch (e) { if (isDead(e)) return freshConnect(c); }
await ensureChain(c).catch(() => {}); // AppKit already connects on the right network; switch is best-effort
return addr;
}
async function ensureChain(c) {
const want = '0x' + Number(c.chainId).toString(16);
let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) { return; }
if (chainNum(cur) === Number(c.chainId)) return;
try {
await eth().request({ method: 'wallet_switchEthereumChain', params: [{ chainId: want }] });
} catch (e) {
// any failure (not just 4902): try to add the chain — wallet_addEthereumChain
// adds AND switches in one step, which is what unblocks wallets that can't
// otherwise reach a chain they don't already have (e.g. a testnet).
const addParams = { chainId: want, chainName: c.chainName, nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrls: [c.rpc] };
if (c.explorer && /^https?:\/\//i.test(c.explorer)) addParams.blockExplorerUrls = [c.explorer];
try { await eth().request({ method: 'wallet_addEthereumChain', params: [addParams] }); } catch (e2) {}
}
}
// SIWE: challenge -> personal_sign -> verify (server sets the session cookie)
async function signIn(opts) {
const addr = (opts && opts.pick) ? await pickAccount() : await activeAddress(await connect());
const ch = await (await fetch('/api/auth/challenge', { method: 'POST',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr }) })).json();
if (ch.error) throw new Error(ch.error);
// hex-encode the message (Trust and others require hex for personal_sign)
const hexMsg = '0x' + Array.from(new TextEncoder().encode(ch.message)).map(b => b.toString(16).padStart(2, '0')).join('');
const sig = await eth().request({ method: 'personal_sign', params: [hexMsg, addr] });
const r = await (await fetch('/api/auth/verify', { method: 'POST',
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr, signature: sig, asPosition: !!(opts && opts.asPosition) }) })).json();
if (r.error) throw new Error(r.error);
return r;
}
async function sendTx(to, data, valueHex) {
const c = await VAB.getConfig();
const addr = await connect();
const wantNum = Number(c.chainId);
let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum) {
await ensureChain(c);
try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {}
if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum)
throw new Error('Your wallet is on the wrong network. Switch it to ' + (c.chainName || 'Polygon') + ', then try again.');
}
const tx = { from: await activeAddress(addr), to, data };
if (valueHex) tx.value = valueHex;
try { const g = await (await fetch('/api/gas')).json(); if (g && g.maxPriorityFeePerGas && g.maxFeePerGas) { tx.maxPriorityFeePerGas = g.maxPriorityFeePerGas; tx.maxFeePerGas = g.maxFeePerGas; } } catch (e) {}
try { return await eth().request({ method: 'eth_sendTransaction', params: [tx] }); }
catch (e) {
if (!isDead(e)) throw e;
tx.from = await freshConnect(c);
return eth().request({ method: 'eth_sendTransaction', params: [tx] });
}
}
async function waitTx(hash) {
for (let i = 0; i < 120; i++) {
try { const r = await (await fetch('/api/tx/' + hash)).json(); if (r.found) return r; } catch (e) { /* app switch on a phone: keep polling */ }
await new Promise(res => setTimeout(res, 2500));
}
throw new Error('Still waiting for the transaction. Check it on the explorer; your Boost shows once it confirms.');
}
async function balance(addr) {
await connect();
return BigInt(await eth().request({ method: 'eth_getBalance', params: [addr || currentAddress(), 'latest'] }));
}
async function disconnect() {
// AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) —
// never block on it, so the UI can't get stuck "disconnecting".
try { if (modal && modal.disconnect) await Promise.race([modal.disconnect(), new Promise(r => setTimeout(r, 1200))]); } catch (e) {}
provider = null;
try { Object.keys(localStorage).forEach(k => { if (/wc@2|walletconnect|w3m|wcm|reown|wagmi|appkit/i.test(k)) localStorage.removeItem(k); }); } catch (e) {}
}
function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } }
return { connect, signIn, sendTx, waitTx, balance, disconnect, address: currentAddress, activeAddress, pickAccount, walletName };
})();