ViralAdSource app (Marty approved 2026-11-16): free text ads that spread by reshares, each ad with its own family tree

Watershed look from the approved mockup (hero, topo pattern, icons). Network sign-in through the hub, hub membership, activity ping.
Reshare links per member per ad with branch/step tracking; family-tree dashboard (branch, step, reshares, views, clicks, sign-ups, Boosts).
Verified views earn ad credits for the branch's resharer (L3). L2 sign-up pipeline (hub-new, confirmed email, not self device/IP,
throwaway block, daily cap, fraud score) with keeper-signed reward vouchers and a pending-rewards ledger; payouts OFF (REWARD_PAYOUTS).
L1 Boosts through VASShop with signed orders naming the sponsor line and the resharer. Trust pack, chatbot, promo kit, PolHunter embed.
All numbers are PROPOSALS until Marty sets them. qa/e2e.mjs 59/59 on a local anvil chain, chatbot test 108/108.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Marty Bostick
2026-11-16 09:19:34 -06:00
commit edaf98c8f6
103 changed files with 6229 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
// Admin: status, the L2 sign-up checks (release / reject / recheck), the pending-rewards ledger, and (staging only) the test-member switch.
// The token stays in this tab only (sessionStorage).
(function () {
const $ = VAS.$, esc = VAS.esc;
let tok = ''; try { tok = sessionStorage.getItem('vas.admin') || ''; } catch (e) {}
const H = () => ({ 'x-admin-token': tok, 'Content-Type': 'application/json' });
const api = (p, body) => VAS.getJSON(p, body ? { method: 'POST', headers: H(), body: JSON.stringify(body) } : { headers: H() });
async function load() {
if (!tok) return;
const s = await api('/api/admin/status'); $('statusOut').textContent = JSON.stringify(s, null, 2); $('testBox').hidden = !s.testSwitch;
const su = await api('/api/admin/signups');
$('suRows').innerHTML = (su.signups || []).map(x => '<tr><td class="mono">' + esc(x.id) + '</td><td>' + esc(x.status) + '</td><td>' + esc(x.email) + (x.confirmLink ? '<br><a href="' + esc(x.confirmLink) + '">staging confirm link</a>' : '') + '</td><td>' + esc(x.resharer || '')
+ '</td><td style="font-size:12px">' + esc(JSON.stringify(x.checks || {})) + (x.fail.length ? '<br><b>fail:</b> ' + esc(x.fail.join(', ')) : '') + (x.hold.length ? '<br><b>hold:</b> ' + esc(x.hold.join(', ')) : '')
+ '</td><td><button class="btn sm" data-a="release" data-id="' + esc(x.id) + '">Release</button> <button class="btn sm" data-a="reject" data-id="' + esc(x.id) + '">Reject</button> <button class="btn sm" data-a="recheck" data-id="' + esc(x.id) + '">Recheck</button></td></tr>').join('') || '<tr><td colspan="6" class="muted">none</td></tr>';
const rw = await api('/api/admin/rewards');
$('rwRows').innerHTML = (rw.rewards || []).map(r => '<tr><td class="mono">' + esc(r.id) + '</td><td>' + esc(r.toName || r.to) + '</td><td>' + esc(r.kind) + '</td><td>' + esc(r.cents) + '</td><td>' + esc(r.status)
+ '</td><td class="mono" style="font-size:12px">' + (r.voucher ? 'signed, nonce ' + esc(String(r.voucher.nonce).slice(0, 10)) + '...' : esc(r.note || '')) + '</td></tr>').join('') || '<tr><td colspan="6" class="muted">none</td></tr>';
}
document.addEventListener('click', async e => { const b = e.target.closest('button[data-a]'); if (!b) return; const r = await api('/api/admin/signup', { id: b.dataset.id, action: b.dataset.a }); if (r.error) VAS.status(r.error, 'err'); load(); });
$('go').onclick = () => { tok = $('tok').value.trim(); try { sessionStorage.setItem('vas.admin', tok); } catch (x) {} load(); };
$('tGo').onclick = async () => { const r = await api('/api/admin/test-member', { address: $('tAddr').value.trim(), username: $('tName').value.trim() || undefined }); VAS.status(r.error || 'Marked as a test member.', r.error ? 'err' : 'ok'); };
load();
})();
+26
View File
@@ -0,0 +1,26 @@
// An ad through a reshare link (/s/<code>): the ad, whose branch it came through, "Reshare this ad" (the member's own unique link,
// under this one) and "Join free" for people new to the network. The visit counts as a verified view for that branch once seen.
(async function () {
const $ = VAS.$, esc = VAS.esc;
const code = (location.pathname.match(/^\/s\/([a-z0-9]{8})/) || [])[1];
const d = await VAS.wire('share', code).catch(() => ({}));
if (!d.ad) { $('adBox').innerHTML = '<p class="note err">' + esc(d.error || 'That ad is not running right now.') + ' <a href="/#board">See the board</a></p>'; $('reshareBox').hidden = true; return; }
const sh = d.share || {};
document.title = d.ad.headline + ' | ViralAdSource';
$('chain').textContent = sh.step > 0 ? 'Reshared by @' + (sh.resharer || 'a member') + ' · step ' + sh.step + ' from the source' + (sh.owner ? ' (@' + sh.owner + ')' : '')
: 'At the source' + (sh.owner ? ': @' + sh.owner + '\'s ad' : '');
$('adBox').innerHTML = VAS.adCard(d.ad, { big: true, place: 'share', share: sh.code });
VAS.featured($('featured'), d);
const out = (url, note) => {
$('reshareOut').innerHTML = '<div class="sharebox"><span>' + esc(url) + '</span><button class="btn sm" type="button" id="cp">Copy</button></div>' + (note ? '<p class="muted" style="font-size:14px;margin:8px 0 0">' + esc(note) + '</p>' : '');
$('cp').onclick = () => VAS.copy(url, $('cp'));
};
if (d.mine) out(d.mine.url, d.mine.own ? 'This is your own ad: this is its source link.' : 'Your reshare link for this ad.');
$('reshareBtn').onclick = async () => {
const me = await VAS.getJSON('/api/me'); if (!me.signedIn) { location.href = '/my?back=' + encodeURIComponent(location.pathname); return; }
const r = await VAS.post('/api/my/reshare', { adId: d.ad.id, from: sh.code });
if (r.error) return VAS.status(r.error, 'err');
out(r.url, r.own ? 'This is your own ad: share its source link.' : r.created ? 'Your new branch: step ' + r.step + ' from the source. Share this link anywhere.' : 'You already reshared this ad. Here is your link again.');
VAS.status('');
};
})();
+29
View File
@@ -0,0 +1,29 @@
// Boost page: the split (live from the contract, else the proposal), the live POL price, and the Buy button.
(async function () {
const $ = VAS.$;
VAS.wire('other').catch(() => {});
const c = await VAS.getConfig().catch(() => ({})); const sp = c.split || {}; const b = c.boost || {};
const rows = [['Resharer whose branch sold it', VAS.pct(sp.resharerBps)], ['Reward pot (pays sign-up rewards only)', VAS.pct(sp.potBps)]]
.concat((sp.levelBps || []).map((x, i) => ['Sponsor level ' + (i + 1), VAS.pct(x)]));
const used = (sp.resharerBps || 0) + (sp.potBps || 0) + (sp.levelBps || []).reduce((t, x) => t + x, 0);
rows.push(['Company (the rest, plus any level nobody qualifies for)', VAS.pct(10000 - used)]);
$('splitRows').innerHTML = rows.map(r => '<tr><td>' + r[0] + '</td><td class="n">' + r[1] + '</td></tr>').join('') + (sp.live ? '' : '<tr><td colspan="2" class="muted">Proposed numbers, not final.</td></tr>');
const live = !!(c.shop && c.shop.live);
const qty = () => Number($('qty').value) || 1;
async function price() {
if (!live) { $('quote').textContent = 'Boosts open when the contract goes live.'; $('buy').disabled = true; return; }
const q = await VASBuy.quote(qty()).catch(() => ({ error: 'x' }));
$('quote').textContent = q.error ? 'price unavailable right now' : '$' + (b.usd * qty()) + ', about ' + VASBuy.fmtPol(q.wei, 2) + ' POL at today\'s price';
}
price(); $('qty').onchange = price;
$('buy').onclick = async () => {
$('buy').disabled = true;
try {
const me = await VAS.getJSON('/api/me'); if (!me.signedIn) { location.href = '/my'; return; }
const before = ((await VAS.getJSON('/api/my')).boosts || []).length;
const r = await VASBuy.run({ qty: qty(), done: async () => (((await VAS.getJSON('/api/my')).boosts || []).length > before) });
VAS.status((r.recorded ? 'Your Boost is live: your ad is at the top of the reshare board.' : 'Paid and confirmed. Your Boost shows within a few minutes.') + (r.link ? ' Transaction: ' + r.link : ''), 'ok');
} catch (e) { VAS.status(String(e && e.message || e).slice(0, 400), 'err'); }
finally { $('buy').disabled = !live; }
};
})();
+39
View File
@@ -0,0 +1,39 @@
// One-time Boosts through VASShop. The server builds the signed buy() call for the signed-in member (POST /api/my/order: the hub sponsor line + the resharer whose link they came through)
// 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 ViralAdSource account. After the transaction confirms the page waits for the watcher to record it.
window.VASBuy = (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 VAS.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 || VAS.status;
const c = await VAS.getConfig();
if (!c.shop || !c.shop.live) throw new Error('Boosts are not open right now.');
const me = await VAS.getJSON('/api/me');
if (!me.signedIn) throw new Error('Sign in on My ad tree first, so the Boost lands on your ad.');
say('Connecting your wallet...');
const addr = String(await VASWallet.activeAddress(await VASWallet.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 ' + VAS.short(addr) + ', but your ViralAdSource account is ' + VAS.short(me.address) + '. A Boost goes to the wallet that pays, so switch your wallet app to ' + VAS.short(me.address) + ', or sign out and sign in with ' + VAS.short(addr) + '.');
const od = await VAS.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 VASWallet.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 VASWallet.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 VASWallet.waitTx(hash);
if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas. ' + (link ? 'Details: ' + link : ''));
VAS.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) VAS.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 };
})();
+46
View File
@@ -0,0 +1,46 @@
/* Site assistant widget in the ViralAdSource watershed look (vas.css): ink header, rounded white panel, coral send, aqua chips.
The overrides at the end of this file set the look; the shared widget rules above stay as on every network site. */
#scChat{--sc-bg:var(--card,#fff);--sc-ink:var(--ink,#0A1F6B);--sc-sub:var(--sub,#3E4C7A);--sc-head:var(--royal,#0A1F6B);--sc-head-ink:#fff;
--sc-accent:var(--red,#E3141E);--sc-accent-ink:#fff;--sc-me:var(--royal2,#12308F);--sc-me-ink:#fff;--sc-bot:var(--tint,#E1EBFF);--sc-line:var(--line,#C9D6F5);
--sc-chip:var(--gtint,#FFF3CC);--sc-chip-ink:var(--gold-ink,#7A5B00);--sc-gold:var(--gold,#FFC21A);
--sc-font:var(--body,Inter,system-ui,sans-serif);--sc-headfont:var(--head,'Chakra Petch',system-ui,sans-serif);--sc-cut:polygon(0 0,calc(100% - 14px) 0,100% 14px,100% 100%,14px 100%,0 calc(100% - 14px));
position:fixed;right:18px;bottom:18px;z-index:80;font-family:var(--sc-font)}
#scBtn{width:58px;height:58px;border:0;cursor:pointer;background:var(--sc-accent);color:var(--sc-accent-ink);display:flex;align-items:center;justify-content:center;
clip-path:polygon(0 0,calc(100% - 12px) 0,100% 12px,100% 100%,12px 100%,0 calc(100% - 12px));box-shadow:0 6px 18px rgba(6,26,102,.35)}
#scBtn:hover{background:#C70F18}
#scBtn:focus-visible{outline:3px solid var(--sc-gold);outline-offset:3px}
#scChat.open #scBtn{background:var(--sc-head)}
/* the panel sets display:flex, which would beat the hidden attribute: closing must win */
#scPanel[hidden]{display:none}
#scPanel{position:absolute;right:0;bottom:72px;width:370px;max-width:calc(100vw - 32px);height:540px;max-height:calc(100vh - 110px);display:flex;flex-direction:column;
background:var(--sc-bg);color:var(--sc-ink);clip-path:var(--sc-cut);border:1px solid var(--sc-line);box-shadow:0 18px 48px rgba(6,26,102,.3)}
.sc-head{display:flex;align-items:flex-start;gap:10px;padding:14px 16px;background:var(--sc-head);color:var(--sc-head-ink);border-bottom:3px solid var(--sc-gold)}
.sc-head>div{flex:1;min-width:0}
.sc-title{display:block;font-family:var(--sc-headfont);font-size:18px;letter-spacing:.02em}
.sc-sub{display:block;font-size:12.5px;opacity:.8}
#scClose{background:transparent;border:0;color:inherit;font-size:26px;line-height:1;cursor:pointer;padding:0 2px}
.sc-msgs{flex:1;overflow-y:auto;padding:14px;display:flex;flex-direction:column;gap:9px}
.sc-m{max-width:88%;padding:9px 12px;font-size:14.5px;line-height:1.45;word-wrap:break-word;overflow-wrap:anywhere}
.sc-m.bot{align-self:flex-start;background:var(--sc-bot);color:var(--sc-ink);clip-path:polygon(0 0,100% 0,100% 100%,8px 100%,0 calc(100% - 8px))}
.sc-m.me{align-self:flex-end;background:var(--sc-me);color:var(--sc-me-ink);clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,0 100%)}
.sc-m a{color:inherit;text-decoration:underline}
.sc-m.wait{opacity:.6}
.sc-cta{display:inline-block;background:var(--sc-accent);color:var(--sc-accent-ink)!important;text-decoration:none!important;font-weight:700;padding:8px 14px;
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
.sc-handoff{background:transparent!important;padding:0!important}
.sc-topics{display:flex;flex-wrap:wrap;gap:6px;padding:0 14px 8px}
.sc-topics button{background:var(--sc-chip);color:var(--sc-chip-ink);border:1px solid var(--sc-gold);font:600 12.5px var(--sc-font);padding:5px 10px;cursor:pointer}
.sc-input{display:flex;gap:8px;padding:10px 12px;border-top:1px solid var(--sc-line)}
.sc-input input{flex:1;min-width:0;border:1px solid var(--sc-line);padding:10px 12px;font:15px var(--sc-font);color:var(--sc-ink);background:#fff}
.sc-input input:focus{outline:2px solid var(--blue,#1F66FF);outline-offset:-1px}
.sc-input button{background:var(--sc-accent);color:var(--sc-accent-ink);border:0;font:700 14px var(--sc-font);padding:0 16px;cursor:pointer;
clip-path:polygon(0 0,calc(100% - 8px) 0,100% 8px,100% 100%,8px 100%,0 calc(100% - 8px))}
.sc-human{display:block;text-align:center;font-size:12.5px;color:var(--sc-sub);padding:0 0 10px}
@media (max-width:600px){#scChat{right:12px;bottom:12px}#scBtn{width:52px;height:52px}#scPanel{bottom:64px;height:calc(100vh - 100px)}}
/* ViralAdSource watershed look */
#scChat{--sc-ink:#0B2730;--sc-sub:#3D5D65;--sc-head:#0B2730;--sc-accent:#C4371B;--sc-me:#123845;--sc-bot:#EAF6F4;--sc-line:#CFE6E2;--sc-chip:#DDF3EF;--sc-chip-ink:#0B5A57;--sc-gold:#2BA39A;
--sc-font:'IBM Plex Sans',system-ui,sans-serif;--sc-headfont:'Bricolage Grotesque',system-ui,sans-serif;--sc-cut:none}
#scChat #scBtn{clip-path:none;border-radius:50%;box-shadow:0 6px 18px rgba(11,39,48,.35)}
#scChat #scBtn:hover{background:#A8321A}
#scChat #scPanel{clip-path:none;border-radius:18px;overflow:hidden}
#scChat .sc-m.bot,#scChat .sc-m.me{clip-path:none;border-radius:14px}#scChat [class*="sc-"]{clip-path:none}#scChat .sc-chip,#scChat button{border-radius:10px}
+72
View File
@@ -0,0 +1,72 @@
// Site assistant widget (2026-11-15): a round button bottom right, a panel that asks /api/chat. The look is this site's own,
// in /assets/chat.css (colors and fonts from the site's stylesheet). When an answer cannot help, or the visitor asks for a
// person, it offers "Open network support": InstantAdPay's support desk, which already knows the question and the site.
// The SAME file ships in ViralAdBlitz, DownlineHydra, 5xYourTeam, Viral Banner Blitz, Downline Banners and Stack POL.
(function () {
if (window.__siteChat || /^\/admin/.test(location.pathname)) return;
window.__siteChat = 1;
var css = document.createElement('link'); css.rel = 'stylesheet'; css.href = '/assets/chat.css?v=20261115d'; document.head.appendChild(css);
var NAME = 'this site', TOPICS = [];
var root = document.createElement('div'); root.id = 'scChat';
root.innerHTML = '<button id="scBtn" type="button" aria-label="Ask a question" aria-expanded="false">'
+ '<svg viewBox="0 0 24 24" width="26" height="26" aria-hidden="true"><path fill="currentColor" d="M4 4h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H9l-5 4v-4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2zm3 6.5a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01zm5 0a1.5 1.5 0 1 0 0 .01z"/></svg></button>'
+ '<div id="scPanel" role="dialog" aria-label="Questions" hidden>'
+ '<div class="sc-head"><div><b class="sc-title" id="scTitle">Ask a question</b><span class="sc-sub">Straight answers about this site and the network</span></div>'
+ '<button id="scClose" type="button" aria-label="Close">&times;</button></div>'
+ '<div class="sc-msgs" id="scMsgs" aria-live="polite"></div>'
+ '<div class="sc-topics" id="scTopics"></div>'
+ '<form class="sc-input" id="scForm"><input id="scIn" autocomplete="off" maxlength="600" placeholder="Type your question" aria-label="Your question">'
+ '<button type="submit" id="scSend">Send</button></form>'
+ '<a class="sc-human" id="scHuman" href="https://instantadpay.com/support" target="_blank" rel="noopener">Need a person? Open network support</a>'
+ '</div>';
document.body.appendChild(root);
var $ = function (id) { return document.getElementById(id); };
var msgs = $('scMsgs'), input = $('scIn'), panel = $('scPanel'), btn = $('scBtn');
var history = [], greeted = false, support = 'https://instantadpay.com/support';
fetch('/api/chat/config').then(function (r) { return r.json(); }).then(function (c) {
if (c.name) { NAME = c.name; $('scTitle').textContent = 'Ask ' + c.name; }
if (c.support) { support = c.support; $('scHuman').href = c.support; }
TOPICS = c.topics || [];
}).catch(function () {});
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]; }); }
function add(text, who) {
var d = document.createElement('div'); d.className = 'sc-m ' + who;
d.innerHTML = esc(text).replace(/(https?:\/\/[^\s<]+[^\s<.,;:!?)])/g, '<a href="$1" target="_blank" rel="noopener">$1</a>');
msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight; return d;
}
function offer(link) {
var old = msgs.querySelector('.sc-handoff'); if (old) old.remove();
var d = document.createElement('div'); d.className = 'sc-m bot sc-handoff';
var a = document.createElement('a'); a.className = 'sc-cta'; a.href = link || support; a.target = '_blank'; a.rel = 'noopener'; a.textContent = 'Open network support';
d.appendChild(a); msgs.appendChild(d); msgs.scrollTop = msgs.scrollHeight;
}
function open() {
panel.hidden = false; btn.setAttribute('aria-expanded', 'true'); root.className = 'open';
if (!greeted) {
greeted = true;
add('Hi. Ask me how ' + NAME + ' works, what it costs, how payouts work, or about any other site in the network. Straight answers, no income hype.', 'bot');
var t = $('scTopics'); TOPICS.slice(0, 4).forEach(function (q) {
var b = document.createElement('button'); b.type = 'button'; b.textContent = q; b.addEventListener('click', function () { input.value = q; send(); }); t.appendChild(b);
});
}
setTimeout(function () { input.focus(); }, 50);
}
function close() { panel.hidden = true; btn.setAttribute('aria-expanded', 'false'); root.className = ''; }
btn.addEventListener('click', function () { panel.hidden ? open() : close(); });
$('scClose').addEventListener('click', close);
document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && !panel.hidden) close(); });
async function send() {
var q = input.value.trim(); if (!q) return;
input.value = ''; $('scTopics').innerHTML = '';
add(q, 'me'); var wait = add('...', 'bot wait');
try {
var r = await (await fetch('/api/chat', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ message: q, history: history.slice(-6) }) })).json();
wait.remove();
add(r.reply || r.error || 'Something went wrong. Try again in a moment.', 'bot');
history.push(q, r.reply || '');
if (r.handoff) offer(r.support);
} catch (e) { wait.remove(); add('I could not reach the assistant just now. Try again in a moment, or open network support.', 'bot'); offer(); }
}
$('scForm').addEventListener('submit', function (e) { e.preventDefault(); send(); });
})();
+125
View File
@@ -0,0 +1,125 @@
// Shared page helpers (VAS namespace, the network common.js pattern): header, footer (legal, company line, the network line from the
// hub), verified visits, ad cards, toasts of real events, small formatters. The watershed look lives in vas.css.
window.VAS = (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');
const pct = bps => (Number(bps || 0) / 100).toFixed(Number(bps) % 100 ? 1 : 0) + '%';
const usd = c => '$' + (Number(c || 0) / 100).toFixed(2);
function status(msg, cls, id) { const el = $(id || 'status'); if (!el) return; el.hidden = !msg; el.className = 'note ' + (cls || ''); el.textContent = msg || ''; if (msg) el.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); }
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 || {}) });
const MARK = '<svg width="34" height="34" viewBox="0 0 34 34" aria-hidden="true"><circle cx="17" cy="8" r="5" fill="#C4371B"></circle><path d="M17 13 V20 M17 20 L8 29 M17 20 L26 29 M17 20 V30" stroke="#0B2730" stroke-width="2.4" fill="none" stroke-linecap="round"></path></svg>';
function renderNav(active) {
const h = document.createElement('header'); h.className = 'top';
const links = [['/#how', 'How it spreads'], ['/#board', 'Reshare board'], ['/rewards', 'Rewards'], ['/boost', 'Boost'], ['/ledger', 'Ledger'], ['/my', 'My ad tree']];
h.innerHTML = '<a class="skip" href="#main">Skip to content</a><div class="wrap"><a class="brand" href="/" aria-label="ViralAdSource, front page">' + MARK + '<span class="wm">ViralAd<b>Source</b></span></a>'
+ '<nav class="links" aria-label="Main">' + links.map(l => '<a href="' + l[0] + '"' + (l[0] === active ? ' class="on" aria-current="page"' : '') + '>' + l[1] + '</a>').join('') + '</nav>'
+ '<div class="row"><a class="btn sm" id="navSign" href="/my">Sign in</a><a class="btn sm ink" href="/my#post">Post your ad free</a></div></div>';
document.body.prepend(h);
getConfig().then(c => { if (c.staging) { const b = document.createElement('div'); b.className = 'stage-bar'; b.textContent = 'Staging copy for testing. Numbers marked as proposals are not final. No real payouts happen here.'; h.after(b); } }).catch(() => {});
getJSON('/api/me').then(m => { if (m.signedIn) { const a = $('navSign'); if (a) { a.textContent = m.username ? '@' + m.username : short(m.address); } } }).catch(() => {});
if (framed) document.querySelectorAll('a[href^="/my"]').forEach(a => { a.target = '_blank'; a.rel = 'noopener'; });
}
// a link through the click relay: share + placement + the visitor's verified token once their visit has verified
const goHref = (id, p, s) => '/go/' + id + '?p=' + encodeURIComponent(p || 'site') + (s ? '&s=' + s : '') + (vt ? '&v=' + vt : '');
function decorate() { document.querySelectorAll('a[data-go]').forEach(a => { a.href = goHref(a.dataset.go, a.dataset.p, a.dataset.s); }); }
// an ad card. o = { place, share, big, extra (html) }
function adCard(t, o) {
o = o || {};
const tags = [];
if (t.boosted) tags.push('<span class="chip coral">Boosted</span>');
if (t.credit) tags.push('<span class="chip">Featured with credits</span>');
if (t.rank) tags.push('<span class="chip grey">#' + t.rank + '</span>');
return '<article class="ad' + (t.boosted ? ' boosted' : '') + (t.credit ? ' credit' : '') + (o.big ? ' big' : '') + '">'
+ '<div class="tag"><span>' + tags.join(' ') + '</span><span>' + n(t.reshares) + ' reshare' + (t.reshares === 1 ? '' : 's') + '</span></div>'
+ '<h3>' + esc(t.headline) + '</h3><p>' + esc(t.line1) + (t.line2 ? ' ' + esc(t.line2) : '') + '</p>'
+ '<div class="foot"><a class="visit" data-go="' + t.id + '" data-p="' + esc(o.place || 'card') + '"' + (o.share ? ' data-s="' + esc(o.share) + '"' : '') + ' target="_blank" rel="noopener sponsored" href="' + goHref(t.id, o.place, o.share) + '">Visit ' + esc(t.host) + '</a>'
+ '<span class="muted">' + esc(t.owner) + '</span></div>' + (o.extra || '') + '</article>';
}
// the page's data and its verified visit: ads come with a ticket; after visitSeconds of the page being visible the visit is sent once
async function wire(page, s) {
const src = document.referrer || '';
let hunt = /[?&#]ph=/.test(location.search + location.hash); try { hunt = hunt || !!sessionStorage.getItem('ph.token'); } catch (e) {}
const d = await getJSON('/api/wire?page=' + encodeURIComponent(page) + (s ? '&s=' + encodeURIComponent(s) : '') + (src ? '&src=' + encodeURIComponent(src) : '') + (hunt ? '&hunt=1' : ''));
if (d.ticket) {
const need = (d.seconds || 6) * 1000; let seen = 0, last = Date.now(), sent = false;
const iv = setInterval(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('vas:verified', { detail: r })); }
}, 500);
document.addEventListener('visibilitychange', () => { last = Date.now(); });
}
return d;
}
function featured(el, d) { if (!el) return; const f = d.featured || []; el.hidden = !f.length; if (f.length) el.querySelector('.ads').innerHTML = f.map(t => adCard(t, { place: 'credit' })).join(''); }
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'], ['downlinehydra', 'DownlineHydra', 'https://downlinehydra.com'],
['fivex', '5xYourTeam', 'https://5xyourteam.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
const HERE = { id: 'viraladsource', name: 'ViralAdSource', url: 'https://viraladsource.com' };
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 === 'viraladsource'
? '<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.concat([HERE]));
fetch('/api/network-sites').then(r => r.json()).then(l => { if (Array.isArray(l) && l.length) paint(l.some(s => s.id === 'viraladsource') ? l : l.concat([HERE])); }).catch(() => {});
}
function renderFooter() {
const f = document.createElement('footer'); f.className = 'foot';
f.innerHTML = '<div class="wrap"><p><b>ViralAdSource</b>: every ad has a source. Ad credits buy advertising, not income. Nothing is promised.</p>'
+ '<p><a href="/">Front page</a> &middot; <a href="/#how">How it spreads</a> &middot; <a href="/rewards">Rewards</a> &middot; <a href="/my">My ad tree</a> &middot; <a href="/boost">Boost</a> &middot; <a href="/promote">Promote</a></p>'
+ '<p><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?from=viraladsource" target="_blank" rel="noopener">Support</a></p>'
+ '<p>TrustClickz &middot; 615 Green Valley Drive, Moody, AL 35004</p><p class="netline"></p></div>';
document.body.appendChild(f);
netLine(f.querySelector('.netline'));
toasts();
}
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 who = c => c.name ? '@' + esc(c.name) : 'A member';
const show = c => {
const el = document.createElement('a'); el.className = 'toast';
if (c.kind === 'boost') { el.href = '/ledger'; el.innerHTML = '<b>' + who(c) + ' boosted an ad</b><br><span>' + (c.resharer ? 'through @' + esc(c.resharer) + '\'s branch, paid in the same transaction' : 'split on chain by the contract') + '</span>'; }
else if (c.kind === 'reshare') { el.href = '/#board'; el.innerHTML = '<b>' + who(c) + ' reshared an ad</b><br><span>a new branch, step ' + esc(c.step) + ' from the source</span>'; }
else { el.href = '/#board'; el.innerHTML = '<b>' + who(c) + ' posted a new 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' : '';
async function copy(text, btn) { try { await navigator.clipboard.writeText(text); if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1600); } } catch (e) { if (btn) { btn.textContent = 'Select the link above to copy it'; } } }
return { MARK, $, esc, getConfig, short, framed, status, getJSON, post, n, pct, usd, renderNav, renderFooter, adCard, wire, featured, decorate, goHref, polOf, when, copy };
})();
// every page: header, footer and the numbers from /api/config (proposals are labelled as proposals)
(function () {
const boot = () => {
VAS.renderNav(document.body.dataset.nav || ''); VAS.renderFooter();
VAS.getConfig().then(c => {
const sp = c.split || {}, rw = c.reward || {}, cr = c.credits || {}, b = c.boost || {};
const prop = sp.live ? '' : '(proposal)';
const lv = sp.levelBps || []; const lvTxt = lv.length ? (lv.every(x => x === lv[0]) ? lv.length + ' x ' + VAS.pct(lv[0]) : lv.map(VAS.pct).join(' / ')) : 'none';
const tier = (rw.tiers || [])[0] || {};
const V = { cut: VAS.pct(sp.resharerBps), pot: VAS.pct(sp.potBps), levels: lvTxt, signup: VAS.usd(rw.cents), cap: String(rw.dailyCap), lockDays: String(tier.lockDays || 14),
creditsPer: String(cr.per), creditsViews: String(cr.views), boostDays: String(b.days), boostUsd: '$' + b.usd, headline: String((c.ad || {}).headline || 60),
proposalTag: prop, proposalNote: sp.live ? '' : 'The percentages and amounts shown are proposals and are not final yet.',
payoutsNote: rw.payouts ? '' : 'Sign-up reward payouts are switched off for now: verified rewards wait in the pending ledger.' };
document.querySelectorAll('[data-cfg]').forEach(el => { const k = el.dataset.cfg; if (V[k] != null) el.textContent = V[k]; });
}).catch(() => {});
};
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot); else boot();
})();
+17
View File
@@ -0,0 +1,17 @@
// Contract page: live facts from /api/contract (read from Polygon, cached 5 minutes), or the proposed rules before it is deployed.
(async function () {
const el = VAS.$('facts'); const esc = VAS.esc;
const d = await VAS.getJSON('/api/contract').catch(() => ({}));
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>' : '<span class="muted">not deployed yet</span>') + (note ? '<br><span class="muted" style="font-size:13px">' + note + '</span>' : '');
const sp = d.split || {}; const lv = (sp.levelBps || []).map(VAS.pct).join(' / ');
const rows = [
['Contract', addr(d.address, 'VASShop on Polygon' + (d.proposal ? '. Not deployed: the numbers below are proposals.' : ''))],
['Owner', addr(d.owner, 'Marty\'s Tangem hardware wallet. It can pause, set future prices and percentages, and change the keeper. It cannot take the reward pot.')],
['Split of each Boost', 'Resharer ' + VAS.pct(sp.resharerBps) + ' · reward pot ' + VAS.pct(sp.potBps) + ' · sponsor levels ' + esc(lv) + ' · company the rest'],
['Sign-up reward', VAS.usd(d.reward && d.reward.cents) + ' in POL, up to ' + esc(d.reward && d.reward.dailyCap) + ' a day per wallet' + (d.reward && !d.reward.payouts ? ' (payouts switched off for now)' : '')],
['Reward pot', d.live && d.pot ? VAS.polOf(d.pot.balanceWei) + ' POL now · ' + VAS.polOf(d.pot.fundedWei) + ' POL in · ' + VAS.polOf(d.pot.paidWei) + ' POL paid out' : '<span class="muted">' + esc(d.error || 'not deployed yet') + '</span>'],
['Sales', d.live ? (d.paused ? '<b>Paused</b>' : 'Open') + ' · ' + VAS.n(d.orderCount) + ' orders' : '<span class="muted">not open yet</span>']
];
el.innerHTML = rows.map(r => '<tr><th>' + r[0] + '</th><td>' + r[1] + '</td></tr>').join('');
})();
+14
View File
@@ -0,0 +1,14 @@
// Front page: the reshare board, credit-featured ads, today's numbers and the PolHunter embed (hunters' visits never count).
(async function () {
const $ = VAS.$;
const d = await VAS.wire('front').catch(() => ({}));
const t = d.today || {};
$('todayStats').innerHTML = [[t.ads, 'ads running'], [t.reshares, 'reshares today'], [t.views, 'verified views today'], [t.vclicks, 'verified clicks today']]
.map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
const b = d.board || [];
$('boardAds').innerHTML = b.length ? b.map(x => VAS.adCard(x, { place: 'board', extra: '<a class="btn sm" style="margin-top:8px" href="/a/' + x.id + '">Open and reshare</a>' })).join('')
: '<p class="muted">No ads yet. <a href="/my#post">Post the first one free</a>.</p>';
VAS.featured($('featured'), d);
// PolHunter mission embed (the network pattern; the mission is saved inactive until go-live)
const ph = document.createElement('script'); ph.async = true; ph.src = 'https://polhunter.com/embed.js'; ph.setAttribute('data-site', 'viraladsource'); $('phEmbed').appendChild(ph);
})();
+20
View File
@@ -0,0 +1,20 @@
// Join the network free (/join) and confirm the email (/confirm?t=). The join is booked to the reshare link the visitor came through.
(async function () {
const $ = VAS.$;
if ($('joinForm')) {
const f = await VAS.getJSON('/api/join/form');
if (f.via && f.via.resharer) $('viaNote').textContent = 'You came through @' + f.via.resharer + '\'s reshare of "' + f.via.headline + '". One free account for every network site.';
$('joinForm').addEventListener('submit', async e => {
e.preventDefault();
const r = await VAS.post('/api/join', { email: $('email').value.trim(), username: $('username').value.trim(), form: f.form });
if (r.error) return VAS.status(r.error, 'err');
$('joinForm').hidden = true;
VAS.status(r.mailed ? 'Check your inbox: open the link we sent to confirm your email.' : 'Thanks. This is the staging copy, so no email is sent: the confirm link is on the admin page for testing.', 'ok');
});
} else {
const t = new URLSearchParams(location.search).get('t') || '';
const r = await VAS.post('/api/confirm', { t });
if (r.error) return VAS.status(r.error, 'err');
VAS.status('Your email is confirmed. Welcome to the network. Sign in with your network account to post your own ad.', 'ok');
}
})();
+22
View File
@@ -0,0 +1,22 @@
// Live ledger: every Boost with its split (resharer, sponsor levels, pot, company) and every sign-up reward, refreshed every 30 s.
(function () {
const $ = VAS.$, esc = VAS.esc; const pol = w => VAS.polOf(w) + ' POL';
const who = (a, nm) => nm ? '@' + esc(nm) : '<span class="mono">' + esc(VAS.short(a || '')) + '</span>';
async function load() {
const d = await VAS.getJSON('/api/ledger?n=100').catch(() => null); if (!d || !d.items) return;
const ex = d.explorer || 'https://polygonscan.com'; const t = d.totals || {};
$('ledStats').innerHTML = [[VAS.n(t.boosts), 'Boosts on chain'], [pol(t.resharerWei), 'paid to resharers'], [pol(t.potWei), 'added to the reward pot'],
[VAS.n((d.rewards || []).filter(r => r.status === 'paid').length), 'sign-up rewards paid']].map(x => '<div class="stat"><b>' + x[0] + '</b><span>' + x[1] + '</span></div>').join('');
const tx = h => h ? '<a href="' + esc(ex) + '/tx/' + esc(h) + '" target="_blank" rel="noopener">verify</a>' : '';
if (d.items.length) $('rows').innerHTML = d.items.map(r => {
const lv = (r.pays || []).filter(p => p.kind >= 1 && p.kind <= 5).map(p => 'L' + p.kind + ' ' + pol(p.wei) + ' ' + who(p.to, p.name)).join('<br>') || '<span class="muted">none qualified</span>';
const co = (r.pays || []).find(p => p.kind === 0);
return '<tr><td>' + VAS.when(r.at) + '</td><td>' + who(r.buyer, r.buyerName) + '</td><td class="n">' + VAS.usd(r.usdCents) + '<br>' + pol(r.weiPaid) + '</td><td>'
+ (r.resharer ? who(r.resharer.to, r.resharer.name) + '<br>' + pol(r.resharer.wei) : '<span class="muted">none</span>') + '</td><td>' + lv + '</td><td class="n">' + pol(r.potWei) + '</td><td class="n">' + (co ? pol(co.wei) : '') + '</td><td>' + tx(r.tx) + '</td></tr>';
}).join('');
$('payNote').textContent = d.payoutsOn ? '' : 'Payouts are switched off for now: verified rewards wait here as pending until the amounts are confirmed.';
if ((d.rewards || []).length) $('rrows').innerHTML = d.rewards.map(r => '<tr><td>' + VAS.when(r.at) + '</td><td>' + (r.name ? '@' + esc(r.name) : esc(r.to)) + '</td><td>' + (r.kind === 'tier' ? 'tier bonus' : 'new member') + '</td><td class="n">' + VAS.usd(r.cents) + '</td><td><span class="chip' + (r.status === 'paid' ? '' : ' grey') + '">' + esc(r.status) + '</span>'
+ (r.unlockAt && r.unlockAt > Date.now() ? '<br><span class="muted" style="font-size:13px">withdrawable ' + VAS.when(r.unlockAt) + '</span>' : '') + '</td><td>' + tx(r.tx) + '</td></tr>').join('');
}
VAS.wire('other').catch(() => {}); load(); setInterval(load, 30000);
})();
+67
View File
@@ -0,0 +1,67 @@
// My ad tree (the member dashboard): sign in (network account through the hub, or wallet), the free ad with the spin-link picker,
// the ad's family tree (branch, step, reshares under it, views, clicks, sign-ups, Boosts), the ads I reshared, credits and rewards.
(async function () {
const $ = VAS.$, esc = VAS.esc;
VAS.wire('other').catch(() => {});
const c = await VAS.getConfig().catch(() => ({}));
const me = await VAS.getJSON('/api/me');
const back = new URLSearchParams(location.search).get('back');
if (!me.signedIn) {
try { const ss = await VAS.getJSON('/api/sso/status'); if (ss && ss.check) { location.replace('/sso/start?mode=check&to=' + encodeURIComponent(location.pathname + location.search)); return; } } catch (e) {}
$('signin').hidden = false; if (c.joinUrl) $('joinLink').href = c.joinUrl;
$('walletBtn').onclick = async () => {
try { VAS.status('Check your wallet for the sign-in message.', '', 'status'); await VASWallet.signIn(); location.href = back && /^\/s\/[a-z0-9]{8}$/.test(back) ? back : '/my'; }
catch (e) { VAS.status(String(e && e.message || e).slice(0, 300), 'err'); }
};
return;
}
if (back && /^\/s\/[a-z0-9]{8}$/.test(back)) { location.replace(back); return; }
$('dash').hidden = false;
$('logout').onclick = async () => { await VAS.post('/api/auth/logout'); location.reload(); };
$('logoutAll').onclick = async () => { $('logoutAll').disabled = true; await VAS.post('/api/auth/logout-everywhere'); location.reload(); };
// spin-link picker: only the member's own LinkSpin spin links (LinkSpin confirms again on every save)
let spins = null;
$('loadSpins').onclick = async () => {
const box = $('spinList'); box.innerHTML = '<p class="muted" style="margin:0;padding:10px 12px;font-size:14px">Asking LinkSpin for your spin links...</p>';
const r = await VAS.getJSON('/api/my/spins').catch(() => ({ error: 'LinkSpin did not answer. Try again in a minute.' }));
if (r.error) { box.innerHTML = '<p class="note err" style="margin:8px">' + esc(r.error) + '</p>'; return; }
spins = r.spins || [];
if (!r.account) { box.innerHTML = '<p style="margin:0;padding:10px 12px;font-size:14px">No LinkSpin account was found for your network username yet. <a href="https://linkspin.app" target="_blank" rel="noopener">Open LinkSpin</a></p>'; return; }
if (!spins.length) { box.innerHTML = '<p style="margin:0;padding:10px 12px;font-size:14px">You have no spin links yet. Make one on <a href="https://linkspin.app/links" target="_blank" rel="noopener">LinkSpin</a>, then pick it here.</p>'; return; }
box.innerHTML = spins.map((x, i) => '<button type="button" data-i="' + i + '"' + (x.paused || !x.destinations ? ' disabled' : '') + (x.url === $('link').value ? ' class="on"' : '') + '>' + esc(x.name || x.code) + ' <span>' + (x.paused ? 'paused' : x.destinations + ' page' + (x.destinations === 1 ? '' : 's')) + '</span></button>').join('');
box.querySelectorAll('button[data-i]').forEach(b => { b.onclick = () => { const x = spins[Number(b.dataset.i)]; $('link').value = x.url; box.querySelectorAll('button').forEach(y => y.classList.remove('on')); b.classList.add('on'); $('track').checked = false; VAS.status('Spin link picked. Save your ad to use it.', 'ok'); }; });
};
$('adForm').addEventListener('submit', async e => {
e.preventDefault(); $('saveAd').disabled = true;
const r = await VAS.post('/api/my/ad', { headline: $('headline').value, line1: $('line1').value, line2: $('line2').value, link: $('link').value.trim(), track: $('track').checked });
$('saveAd').disabled = false;
if (r.error) return VAS.status(r.error, 'err');
VAS.status(r.created ? 'Your ad is live. Share your source link below: every reshare grows a branch.' : 'Saved.', 'ok'); load();
});
$('copySource').onclick = () => VAS.copy($('sourceUrl').textContent, $('copySource'));
async function load() {
const d = await VAS.getJSON('/api/my'); if (d.error) return VAS.status(d.error, 'err');
$('who').innerHTML = 'Signed in as ' + (d.username ? '@' + esc(d.username) : '<span class="mono">' + esc(VAS.short(d.address)) + '</span>') + (d.netVerified ? ' · network member' : ' · <b>not found in the network yet</b>: sign in with your network account to post and reshare') + (d.test ? ' · <span class="chip gold">staging test member</span>' : '');
const a = d.ad, t = d.tree;
if (a) {
$('adTitle').textContent = 'My ad'; $('headline').value = a.headline; $('line1').value = a.line1; $('line2').value = a.line2 || ''; $('link').value = a.link; $('track').checked = a.track !== false; $('saveAd').textContent = 'Save changes';
$('treeChip').textContent = a.status + (a.boostedUntil && a.boostedUntil > Date.now() ? ' · boosted until ' + VAS.when(a.boostedUntil) : '');
}
if (d.source) { $('sourceBox').hidden = false; $('sourceUrl').textContent = d.source.url; }
const cr = d.credits || {}, rw = d.rewards || {};
$('myStats').innerHTML = [[t ? t.totals.shares : 0, 'reshares of my ad'], [t ? t.totals.reach : 0, 'furthest step'], [a ? a.views : 0, 'verified views'], [a ? a.vclicks : 0, 'verified clicks'], [cr.balance, 'ad credits']].map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
if (t && t.rows && t.rows.length) {
$('treeStats').innerHTML = [[t.root.views, 'views at the source'], [t.totals.views, 'views through branches'], [t.totals.signups, 'sign-ups through branches'], [t.totals.boosts, 'Boosts through branches']].map(x => '<div class="stat"><b>' + VAS.n(x[0]) + '</b><span>' + x[1] + '</span></div>').join('');
$('treeRows').innerHTML = t.rows.map(r => '<tr class="' + (r.step > 1 ? 'sub' : '') + '" style="--d:' + (r.step - 1) + '"><td>' + esc(r.who) + '</td><td class="n">' + r.step + '</td><td class="n">' + VAS.n(r.under) + '</td><td class="n">' + VAS.n(r.views) + '</td><td class="n">' + VAS.n(r.clicks) + '</td><td class="n">' + VAS.n(r.signups) + '</td><td class="n">' + VAS.n(r.boosts) + '</td></tr>').join('');
}
if ((d.reshares || []).length) $('myShares').innerHTML = d.reshares.map(s => '<tr><td>' + esc(s.headline || 'ad #' + s.adId) + (s.owner ? '<br><span class="muted" style="font-size:13px">by @' + esc(s.owner) + '</span>' : '') + (s.live ? '' : ' <span class="chip grey">not running</span>') + '</td><td class="n">' + s.step + '</td><td class="n">' + VAS.n(s.views) + '</td><td class="n">' + VAS.n(s.clicks) + '</td><td class="n">' + VAS.n(s.signups) + '</td><td class="n">' + VAS.n(s.boosts) + '</td><td><button class="btn sm" type="button" data-copy="' + esc(s.url) + '">Copy link</button></td></tr>').join('');
document.querySelectorAll('button[data-copy]').forEach(b => { b.onclick = () => VAS.copy(b.dataset.copy, b); });
let earnedWei = 0n; try { earnedWei = BigInt((d.earned || {}).wei || 0); } catch (e) {}
$('rewardStats').innerHTML = [[VAS.n(cr.balance), 'ad credits to spend'], [VAS.n(cr.nextAt), 'branch views to the next ' + VAS.n(cr.per) + ' credits'], [VAS.usd(rw.pendingCents), 'sign-up rewards pending'], [VAS.polOf(earnedWei.toString()) + ' POL', 'paid to me by the contract']].map(x => '<div class="stat"><b>' + x[0] + '</b><span>' + x[1] + '</span></div>').join('');
$('rewardNote').textContent = rw.payoutsOn ? '' : 'Sign-up reward payouts are switched off for now. Verified rewards wait here as pending until the amounts are confirmed.';
if ((rw.items || []).length) $('rewardRows').innerHTML = rw.items.map(r => '<tr><td>' + VAS.when(r.at) + '</td><td>' + (r.kind === 'tier' ? 'Tier bonus' : 'New member through my link') + '</td><td class="n">' + VAS.usd(r.cents) + '</td><td>' + esc(r.status) + (r.unlockAt && r.unlockAt > Date.now() ? ' (withdrawable ' + VAS.when(r.unlockAt) + ')' : '') + '</td></tr>').join('');
}
load();
})();
+15
View File
@@ -0,0 +1,15 @@
// Promote page: the promo kit from /api/promo-kit with the member's network username in every link.
(async function () {
const $ = VAS.$, esc = VAS.esc;
let u = new URLSearchParams(location.search).get('u') || '';
if (!u) { const me = await VAS.getJSON('/api/me').catch(() => ({})); if (me.signedIn && me.username) u = me.username; }
$('kitUser').value = u;
async function show() {
const k = await VAS.getJSON('/api/promo-kit?u=' + encodeURIComponent($('kitUser').value.trim().replace(/^@/, '')));
$('kit').innerHTML = '<section class="panel"><h2 style="font-size:24px">Your links</h2>' + k.links.map(l => '<p><b>' + esc(l.label) + '</b><br><span class="mono" style="word-break:break-all">' + esc(l.tracked || l.url) + '</span></p>').join('') + '</section>'
+ '<section class="panel" style="margin-top:18px"><h2 style="font-size:24px">Lines to post</h2>' + k.lines.map(x => '<p>' + esc(x) + '</p>').join('') + '<h3>Email</h3><p><b>' + esc(k.email.subject) + '</b></p><p style="white-space:pre-wrap">' + esc(k.email.body) + '</p></section>'
+ (k.creatives.length ? '<section class="panel" style="margin-top:18px"><h2 style="font-size:24px">Creatives</h2><div class="row">' + k.creatives.map(c => '<figure style="margin:0"><img src="' + esc(c.url) + '" width="' + Math.min(c.w, 300) + '" alt="' + esc(c.angleLabel) + '"><figcaption class="muted" style="font-size:13px">' + esc(c.label) + ' ' + c.w + 'x' + c.h + '</figcaption></figure>').join('') + '</div></section>' : '')
+ '<p class="muted">' + esc(k.note) + '</p>';
}
$('kitUser').addEventListener('change', show); show();
})();
+2
View File
@@ -0,0 +1,2 @@
// Static pages: header, footer and the live numbers come from common.js; the visit is a plain verified visit.
VAS.wire('other').catch(() => {});
+115
View File
@@ -0,0 +1,115 @@
/* ViralAdSource "watershed" look (approved mockup 2026-11-16, canvas 2XuFAog3KEiuXbfEvVvTZk): aqua ground, deep ink, coral source,
teal streams. Bricolage Grotesque headlines, IBM Plex Sans body, IBM Plex Mono figures. Distinct from every other network site. */
:root{--aqua:#EAF6F4;--ink:#0B2730;--ink2:#123845;--ink3:#23444D;--muted:#3D5D65;--line:#CFE6E2;--line2:#E3EFED;--teal:#0B5A57;--teal2:#2BA39A;--mint:#8FCFC7;
--mist:#B9DCD7;--coral:#C4371B;--coral2:#FF9479;--paper:#FFFFFF;--pale:#F6FBFA;--chip:#DDF3EF;--warn:#8A4B00;--ok:#0B5A57;--bad:#A3281A;
--h:'Bricolage Grotesque',system-ui,sans-serif;--b:'IBM Plex Sans',system-ui,sans-serif;--m:'IBM Plex Mono',ui-monospace,monospace}
*{box-sizing:border-box}
html{scroll-behavior:smooth}
body{margin:0;background:var(--aqua);color:var(--ink);font-family:var(--b);font-size:17px;line-height:1.55;-webkit-text-size-adjust:100%}
a{color:var(--teal)}a:hover{color:var(--ink)}
img{max-width:100%}
[hidden]{display:none!important}
.wrap{max-width:1240px;margin:0 auto;padding:0 24px}
@media (max-width:600px){.wrap{padding:0 16px}}
h1,h2,h3{font-family:var(--h);letter-spacing:-.01em;margin:0;text-wrap:balance}
h1{font-weight:800;font-size:clamp(38px,6vw,62px);line-height:1.02;letter-spacing:-.02em}
h2{font-weight:800;font-size:clamp(30px,4.2vw,42px);line-height:1.08}
h3{font-family:var(--b);font-weight:600;font-size:21px}
.kicker{margin:0 0 14px;font-family:var(--m);font-size:13px;letter-spacing:.14em;text-transform:uppercase;color:var(--teal)}
.lead{font-size:19px;color:var(--ink3);max-width:600px;margin:20px 0 0}
.muted{color:var(--muted)}.mono{font-family:var(--m)}
.btn{display:inline-flex;align-items:center;justify-content:center;gap:8px;min-height:48px;padding:0 22px;border-radius:12px;border:1.5px solid var(--ink);background:transparent;color:var(--ink);font:600 16px var(--b);text-decoration:none;cursor:pointer}
.btn:hover{background:var(--chip);color:var(--ink)}
.btn.ink{background:var(--ink);color:#fff;border-color:var(--ink)}.btn.ink:hover{background:var(--ink2)}
.btn.coral{background:var(--coral);border-color:var(--coral);color:#fff}.btn.coral:hover{background:#A8321A}
.btn.sm{min-height:40px;padding:0 14px;font-size:14px;border-radius:10px}
.btn[disabled]{opacity:.5;cursor:not-allowed}
.row{display:flex;flex-wrap:wrap;gap:12px;align-items:center}
/* header */
header.top{background:#fff;border-bottom:1px solid var(--line);position:relative;z-index:5}
header.top .wrap{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px 16px;padding-top:14px;padding-bottom:14px}
.brand{display:flex;align-items:center;gap:10px;text-decoration:none;color:var(--ink)}
.brand .wm{font-family:var(--h);font-weight:800;font-size:22px}.brand .wm b{color:var(--coral);font-weight:800}
nav.links{display:flex;flex-wrap:wrap;gap:6px 20px;font-size:15px;font-weight:500}
nav.links a{text-decoration:none;color:var(--ink)}nav.links a.on{color:var(--coral);text-decoration:underline;text-underline-offset:5px}
.stage-bar{background:#FFF4D6;color:#5A3A00;font:500 13px var(--m);text-align:center;padding:6px 12px}
/* hero */
.hero{background:linear-gradient(90deg,var(--aqua) 0%,rgba(234,246,244,.92) 34%,rgba(234,246,244,0) 58%),url(/art/hero.webp) right center/cover no-repeat}
@media (max-width:860px){.hero{background:linear-gradient(180deg,rgba(234,246,244,.95) 0%,rgba(234,246,244,.95) 62%,rgba(234,246,244,.2) 100%),url(/art/hero.webp) center bottom/cover no-repeat}}
.hero .wrap{display:flex;flex-wrap:wrap;gap:40px;align-items:center;padding-top:72px;padding-bottom:72px}
.hero .copy{flex:1 1 460px;min-width:0}.hero .spacer{flex:1 1 380px;min-height:400px}
@media (max-width:860px){.hero .spacer{min-height:220px}}
.hero.slim .wrap{padding-top:48px;padding-bottom:48px}.hero.slim .spacer{min-height:200px}
.topo{background:var(--ink) url(/art/topo.png) repeat;background-size:600px 600px;color:var(--aqua)}
.topo .wrap{padding-top:64px;padding-bottom:64px}
.topo p{color:var(--mist)}
.topo a{color:var(--coral2)}
.cards{display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:20px;margin-top:32px}
.card-ink{background:var(--ink2);border-radius:16px;padding:24px}
.card-ink .step{margin:0;font-family:var(--m);color:var(--coral2);font-size:14px}
.card-ink h3{margin:10px 0 8px;color:#fff}
.card-ink img{display:block;margin-bottom:12px;width:34px;height:34px}
.card-ink.c1{border-top:4px solid var(--coral2)}.card-ink.c2{border-top:4px solid var(--teal2)}.card-ink.c3{border-top:4px solid var(--mint)}
.card-ink.c2 .step,.card-ink.c3 .step{color:var(--mint)}
ol.verify{margin:18px 0 0;padding:0;list-style:none;display:grid;grid-template-columns:repeat(auto-fit,minmax(210px,1fr));gap:14px}
ol.verify li{background:var(--ink2);border-radius:14px;padding:18px}ol.verify b{font-family:var(--m);color:var(--coral2)}ol.verify p{margin:6px 0 0}
section.band{padding:64px 0}
.split{display:flex;flex-wrap:wrap;gap:40px;align-items:flex-start}
.split>*{flex:1 1 380px;min-width:0}
.panel{background:#fff;border:1px solid var(--line);border-radius:20px;padding:22px}
.panel.pale{background:var(--pale);border:2px solid var(--ink)}
ul.ticks{margin:18px 0 0;padding-left:20px;color:var(--ink3);display:flex;flex-direction:column;gap:8px}
.chip{display:inline-block;font-family:var(--m);font-size:13px;padding:4px 10px;border-radius:999px;background:var(--chip);color:var(--teal)}
.chip.coral{background:#FCE3DC;color:var(--coral)}.chip.gold{background:#FFF1C9;color:#6B4A00}.chip.grey{background:#E7EEED;color:var(--muted)}
/* ad cards */
.ads{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:16px;margin-top:22px}
.ad{background:#fff;border:1px solid var(--line);border-radius:16px;padding:18px;display:flex;flex-direction:column;gap:8px;position:relative}
.ad.boosted{border:2px solid var(--coral);box-shadow:0 6px 0 rgba(196,55,27,.12)}
.ad.credit{border:2px dashed var(--teal2)}
.ad .tag{font-family:var(--m);font-size:12px;color:var(--muted);display:flex;gap:8px;flex-wrap:wrap;justify-content:space-between}
.ad h3{font-family:var(--h);font-weight:800;font-size:21px;line-height:1.15}
.ad p{margin:0;color:var(--ink3);font-size:15px}
.ad .foot{display:flex;flex-wrap:wrap;gap:8px;justify-content:space-between;align-items:center;margin-top:auto;padding-top:8px;font-size:14px}
.ad .visit{font-weight:600;color:var(--coral);text-decoration:none}.ad .visit:hover{text-decoration:underline}
.ad.big{padding:26px;border-radius:20px}.ad.big h3{font-size:30px}.ad.big p{font-size:17px}
/* forms */
label.f{display:flex;flex-direction:column;gap:6px;font-weight:600;font-size:14px}
label.f small{font-weight:400;color:var(--muted)}
input[type=text],input[type=email],input[type=url],input[type=number],select,textarea{min-height:46px;padding:0 12px;border:1.5px solid var(--line);border-radius:10px;font:400 16px var(--b);background:#fff;color:var(--ink);width:100%}
input:focus,select:focus,textarea:focus{outline:3px solid rgba(43,163,154,.35);border-color:var(--teal2)}
form.stack{display:flex;flex-direction:column;gap:12px}
.picker{border:1.5px solid var(--ink);border-radius:12px;overflow:hidden}
.picker .ph{padding:10px 12px;background:var(--aqua);font:500 13px var(--m);display:flex;justify-content:space-between;gap:8px}
.picker button{display:flex;width:100%;justify-content:space-between;align-items:center;gap:10px;min-height:48px;padding:0 12px;border:0;border-top:1px solid var(--line);background:#fff;font:400 15px var(--b);text-align:left;cursor:pointer;color:var(--ink)}
.picker button.on{font-weight:600;background:var(--chip)}.picker button span{color:var(--muted);font-size:13px}
.note{margin:12px 0 0;padding:12px 14px;border-radius:12px;background:#fff;border:1px solid var(--line);font-size:15px}
.note.ok{border-color:var(--teal2);background:#E5F6F2}.note.err{border-color:var(--coral);background:#FDECE7;color:var(--bad)}.note.warn{border-color:#E9B949;background:#FFF7DF;color:#5A3A00}
/* tables */
.tbl{overflow-x:auto;margin-top:14px}
table{width:100%;border-collapse:collapse;font-size:15px}
th{text-align:left;color:var(--muted);font-size:13px;font-weight:600;padding:8px 6px;white-space:nowrap}
td{padding:10px 6px;border-top:1px solid var(--line2);vertical-align:top}
td.n{font-family:var(--m);white-space:nowrap}
tr.sub td:first-child{padding-left:calc(6px + var(--d,1) * 18px)}
tr.sub td:first-child::before{content:'\21B3 ';color:var(--teal2)}
/* stats */
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-top:18px}
.stat{background:#fff;border:1px solid var(--line);border-radius:14px;padding:14px}
.stat b{display:block;font:800 28px var(--h)}.stat span{font-size:13px;color:var(--muted)}
.topo .stat{background:var(--ink2);border:0}.topo .stat span{color:var(--mist)}
/* dashboard */
.dash{display:grid;grid-template-columns:repeat(auto-fit,minmax(min(100%,520px),1fr));gap:20px;margin-top:24px}
.sharebox{display:flex;gap:8px;flex-wrap:wrap;align-items:center;background:var(--aqua);border-radius:12px;padding:10px 12px;font:500 14px var(--m);word-break:break-all}
.chain{font:500 13px var(--m);color:var(--muted)}
/* footer */
footer.foot{background:var(--ink);color:var(--mist);font-size:14px;margin-top:0}
footer.foot .wrap{padding-top:36px;padding-bottom:36px;display:flex;flex-direction:column;gap:10px}
footer.foot p{margin:0}footer.foot b{color:var(--aqua)}footer.foot a{color:var(--mist)}footer.foot a:hover{color:#fff}
footer.foot .here{color:var(--coral2);font-weight:600}
.legal main{max-width:820px}.legal h2{font-size:26px;margin-top:28px}.legal p,.legal li{color:var(--ink3)}
/* toasts */
.toasts{position:fixed;left:16px;bottom:16px;z-index:40;display:flex;flex-direction:column;gap:8px;max-width:min(360px,calc(100vw - 32px))}
.toast{display:block;background:var(--ink);color:var(--aqua);border-left:4px solid var(--coral2);border-radius:12px;padding:12px 14px;font-size:14px;text-decoration:none;transform:translateY(20px);opacity:0;transition:.35s}
.toast.in{transform:none;opacity:1}.toast b{color:#fff}.toast span{color:var(--mist)}
.net-zone{margin:20px auto;text-align:center}.net-zone-label{font:500 11px var(--m);color:var(--muted);margin-bottom:4px}
.skip{position:absolute;left:-999px}.skip:focus{left:16px;top:8px;z-index:50;background:#fff;padding:8px}
+233
View File
@@ -0,0 +1,233 @@
// ViralAdSource wallet sign-in: the VBB / Downline Banners / ViralAdBlitz 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.VASWallet = (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: 'ViralAdSource', description: 'Every ad has a source.',
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 VAS.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 { VAS.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 VAS.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 VAS.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 };
})();