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
+5
View File
@@ -0,0 +1,5 @@
node_modules
data
qa/out
.git
.env
+44
View File
@@ -0,0 +1,44 @@
# ViralAdBlitz app env (Coolify). Never commit real values.
DOCSTORE_URL= # mysql://user:pass@host:3306/viraladblitz REQUIRED for launch (files are local prototype only)
SITE_HOST=viraladblitz.com
SESSION_SECRET= # random hex; default = generated into DATA_DIR/.secret
ADMIN_TOKEN= # x-admin-token for /api/admin/* (8+ characters)
NETWORK_SSO_SECRET= # same value as InstantAdPay + LinkSpin; they must also list viraladblitz under wallets
WALLETCONNECT_PROJECT_ID= # Reown id (IAP project); add viraladblitz.com to its allowlist first
NETWORK_SITE_ID=viraladblitz # this site in the network footer list and tracked links (LinkSpin code nwvab)
JOIN_URL= # default https://instantadpay.com/?ref={ref} (where a non-member joins under a page owner)
# Boost (display copy; must match VABShop SKU 1): $5 = 500 guaranteed views, delivered on-site within 30 days, then NAS
BOOST_USD=5
BOOST_VIEWS=500
BOOST_DELIVER_DAYS=30
BOOST_SLOTS=2 # Boosted places on each member page
TICKER_BOOSTS=12 # starred Boosted ads in the ticker
VISIT_SECONDS=6 # page visible this long before views count
VISITS_PER_IP_DAY=3 # browsers counted per connection per 24 h
LINK_PROBE=1 # 0 skips the "link answers" check (local tests only)
CF_PROXIED=0 # 1 only if Cloudflare proxies the domain
NETWORK_LOOKUP_URL= # default InstantAdPay /api/network/member (used only while the hub is unreachable)
# VABShop (../contracts). All empty = inert.
CONTRACT_ADDRESS= # the deployed VABShop
CHAIN_RPC= # server-side Polygon RPC for the watcher (publicnode like VBB)
SHOP_START_BLOCK= # the deploy block
SHOP_CONFIRMATIONS=10
SHOP_POLL_MS=30000
KEEPER_KEY= # private key of the contract's keeper (signs line vouchers). Coolify secret only
VOUCHER_SECONDS=1800
COMPANY_WALLET= # display only; default Tangem 0x7627...7b70 (immutable in the contract)
# Network hub (hubpeople.js lookups are on whenever HUB_URL + HUB_SECRET are set; HUB_ENABLED only switches the Boost report)
HUB_URL= # https://hub.saasy.top
HUB_SECRET= # this site's secret in the hub's HUB_SITES (32+ chars)
HUB_SITE=viraladblitz
HUB_ENABLED=0
# Telegram sale cards (CTB Rewards bot, payments topic; same values as Downline Banners / VBB)
TG_TOKEN=
TG_CHAT=
TG_PAY_TOPIC=
# Network Ad Space finishing of late Boosts (same NAS_DB_* as InstantAdPay / Downline Banners). Empty = off.
NAS_DB_HOST=
NAS_DB_PORT=3306
NAS_DB_USER=
NAS_DB_PASSWORD=
NAS_DB_NAME=
+5
View File
@@ -0,0 +1,5 @@
node_modules/
data/
*.log
qa/out/
.env
+12
View File
@@ -0,0 +1,12 @@
FROM node:22-alpine
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev --no-audit --no-fund
COPY . .
RUN mkdir -p /app/data
ENV NODE_ENV=production
ENV PORT=3000
EXPOSE 3000
# a container that cannot boot is never swapped in (2026-10-08 rule)
HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=4 CMD wget -qO- http://127.0.0.1:3000/health >/dev/null || exit 1
CMD ["node","server.js"]
+33
View File
@@ -0,0 +1,33 @@
# ViralAdBlitz app (viraladblitz.com rebuild)
The network's text-ad home (Marty approved the plan and mockup 2026-11-14; Boost = $5 for 500 guaranteed network views).
Plain Node http server, no framework, the VBB / Downline Banners pattern. Contract: `../contracts` (VABShop).
## What it does
- **Free text ad** (headline 60, two lines of 90, https link, no shorteners) for network members: sign in through InstantAdPay or LinkSpin (networksso.js, audience `viraladblitz`) or by wallet; membership is checked with the network hub (hubpeople.js), InstantAdPay's lookup only while the hub is unreachable. One ad per member, editable.
- **Member page** `viraladblitz.com/<network username>`: the member's ad, then the first 5 people above them in the hub sponsor line who have a live ad here (hubline.js walks up to 20 places; each row is labelled with the person's real place in the line), then 2 Boosted places, then "Join free under @owner" (JOIN_URL, default InstantAdPay `?ref=`).
- **Front page**: amber ticker of the newest ads (Boosted ones starred, on every page), "Top ads this week" by verified clicks, today's numbers, 3 steps, live ledger, contract proof, toasts.
- **Verified visitors** (wire.js, VBB rules): every page load gets a ticket listing the ads the server showed; after `VISIT_SECONDS` visible the browser redeems it. Bots, early sends and more than `VISITS_PER_IP_DAY` browsers per connection are refused. Each shown ad gets one view per visitor per 24 h, never the owner's own. Verified clicks: `/go/<ad>?v=<token>` once per visitor per ad per 24 h, never the owner's own; raw clicks are counted apart. `{clickid}` and `{placement}` in an ad link are filled on every click.
- **Boost** ($5, one-time, never a subscription): order built server side (`POST /api/my/order`), paid from the member's wallet through VABShop. If the buyer's line is not on chain yet, the keeper signs an EIP-712 line voucher with the hub line's wallets (nearest first, up to 20, people without a wallet left out). The watcher (shop.js) records each Purchase once per tx:logIndex.
- **Delivery** (wire.js + vabnas.js): every verified view of a Boosted ad counts toward its guarantee (oldest Boost first) and is kept as an audit row (`vab_bviews`, 120 days). Boosted ads are starred on the ticker and fill the member pages' Boosted places, furthest-behind first. A Boost not delivered on-site within 30 days is finished through **Network Ad Space as a text ad** (pid 1) for exactly the views still owed; NAS impressions count toward the same guarantee. NAS was chosen over LinkSpin zones because NAS serves text ads natively; LinkSpin zones are banner placements.
- **Trust pack** (proof.js): `/ledger` (each Boost with every level paid, its place in the line, who was passed over, delivery), `/contract` (live facts), toasts of real events, one Telegram photo card per Boost (never twice: in-process guard + `docstore.claim`, nothing older than 2 hours), Terms / Earnings Disclaimer / Privacy (TrustClickz, 615 Green Valley Drive, Moody, AL 35004), the network footer from the hub (netsites.js, tracked LinkSpin links, code `nwvab`).
- **Promo kit** (promokit.js): `GET /api/promo-kit?u=`, `/promote`, 21 creatives `public/art/kit/vab-{free,spread,boost}-{tile,strip,leader,box,tower,social,square}.png`.
- **Network ad zones**: placeholders in `public/assets/common.js` ZONES and `ZONE_404` in server.js, ids empty until the LinkSpin zones exist.
- **Hub report** (hubreport.js): each Boost as contract-bind / contract-spend, contract `viraladblitz`, off unless `HUB_ENABLED=1`.
- **Old links**: `/?<old>`, `/splashpg.php?pid=N&r=<old>`, `/lcp.php?pid=N&r=<old>` 301 to `/<network username>` from the oldrefs map (`POST /api/admin/oldrefs`), any other `*.php` to `/`.
- **Data**: docstore.js (MySQL via `DOCSTORE_URL`): document `vab.json` + row tables `vab_ads`, `vab_visits`, `vab_clicks`, `vab_bviews`; `hubreport.json`, `vab-nas.json`, `oldrefs.json` are documents too.
## Run and test
```
npm install
node server.js # prototype mode without DOCSTORE_URL (never launch this way)
node qa/smoke.mjs # 162 checks: stand-in hub, chain, Telegram, NAS; Playwright desktop + phone renders
SKIP_UI=1 node qa/smoke.mjs # HTTP checks only
node qa/chain.mjs # 20 checks against the real VABShop on a local anvil chain (needs ../contracts built)
node tools/pages.mjs # regenerate public/*.html (one source of copy + legal facts)
node tools/art.mjs # regenerate icon, OG image, proof cards, kit creatives (Playwright)
```
Admin: `/admin` with the `ADMIN_TOKEN` (status, Boost delivery, member lookup, ad status, old-link map). Env: `.env.example`.
+63
View File
@@ -0,0 +1,63 @@
// All runtime config comes from env (Coolify sets these). Read once.
// ViralAdBlitz (viraladblitz.com rebuild, Marty approved 2026-11-14): the network's text-ad home. Members post one free text ad;
// each member's page shows their ad plus the ads of the 5 people above them in their network (hub) sponsor line. A Boost ($5,
// one-time, 500 guaranteed network views) is paid in POL through VABShop and split on-chain 10% to each of 5 sponsor levels
// (pass-up to the next person who has boosted) + 50% company. Purchases are inert until CONTRACT_ADDRESS / CHAIN_RPC / KEEPER_KEY are set.
const path = require('path');
let cfg = null;
function get() {
if (cfg) return cfg;
const e = process.env;
const num = (v, d, min, max) => { const n = Number(v); return Number.isFinite(n) && v !== '' && v != null ? Math.min(max, Math.max(min, Math.round(n))) : d; };
const addr = v => /^0x[0-9a-fA-F]{40}$/.test(String(v || '').trim()) ? require('ethers').getAddress(String(v).trim().toLowerCase()) : '';
cfg = {
port: Number(e.PORT || 3000),
isProd: e.NODE_ENV === 'production',
site: e.SITE_HOST || 'viraladblitz.com',
siteName: 'ViralAdBlitz',
siteId: 'viraladblitz', // hub site id, network sign-in audience, netsites id
dataDir: e.DATA_DIR || path.join(__dirname, 'data'),
chainId: Number(e.CHAIN_ID || 137),
chainName: e.CHAIN_NAME || 'Polygon',
publicRpc: e.PUBLIC_RPC || 'https://polygon-bor-rpc.publicnode.com',
walletConnectProjectId: (e.WALLETCONNECT_PROJECT_ID || '').trim(),
// ---- Boost (Marty 2026-11-14: "$5 for 500 guaranteed network views"). The contract's SKU holds the real price; this is the
// display copy and must match it (smoke + chain tests check). One-time, never a subscription.
boost: { sku: num(e.BOOST_SKU, 1, 1, 1000), usd: Number(e.BOOST_USD || 5), views: num(e.BOOST_VIEWS, 500, 1, 1e6), maxQty: 10 },
split: { levels: 5, levelPct: 10, companyPct: 50, maxDepth: 20 }, // VABShop constants (display copy)
deliverDays: num(e.BOOST_DELIVER_DAYS, 30, 1, 365), // on-site delivery window; then Network Ad Space finishes the rest
// the pages
levels: 5, // upline ads on a member's page
lineSearch: num(e.LINE_SEARCH, 20, 5, 50), // hub places walked to find 5 uplines with a live ad
boostSlots: num(e.BOOST_SLOTS, 2, 0, 10), // Boosted places on a member page (the "extra place on the five-level pages")
tickerBoosts: num(e.TICKER_BOOSTS, 12, 0, 50), // starred Boosted ads in the ticker
tickerNewest: num(e.TICKER_NEWEST, 16, 0, 100), // newest ads in the ticker
boardSize: num(e.BOARD_SIZE, 9, 3, 50), // "Top ads this week"
// verified visitors (the VBB rules)
visitSeconds: num(e.VISIT_SECONDS, 6, 2, 60), // page visible this long before views count
visitWindowHours: 24, // one verified view per visitor per ad (and one visit per page) per 24 h
perIpDay: num(e.VISITS_PER_IP_DAY, 3, 1, 100), // distinct browsers counted per connection per 24 h
// text ads
ad: { headline: 60, line: 90 }, // characters
linkProbe: e.LINK_PROBE !== '0', // check the link answers (off in the local smoke test)
explorer: String(e.EXPLORER || (Number(e.CHAIN_ID || 137) === 137 ? 'https://polygonscan.com' : '')).replace(/\/+$/, ''),
// VABShop (../contracts). KEEPER_KEY is read by shop.js only, never kept here.
contractAddress: addr(e.CONTRACT_ADDRESS),
companyWallet: addr(e.COMPANY_WALLET) || '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70', // Tangem (immutable in VABShop)
chainRpc: String(e.CHAIN_RPC || '').trim(),
shopStartBlock: num(e.SHOP_START_BLOCK, 0, 0, 1e12),
shopConfirmations: num(e.SHOP_CONFIRMATIONS, 10, 0, 1000),
shopPollMs: num(e.SHOP_POLL_MS, 30000, 200, 3600000),
voucherSeconds: num(e.VOUCHER_SECONDS, 1800, 60, 86400),
iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''),
lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''),
// where someone who is not in the network yet joins free under the page owner ({ref} = the owner's network username)
joinUrl: String(e.JOIN_URL || 'https://instantadpay.com/?ref={ref}'),
networkLookupUrl: e.NETWORK_LOOKUP_URL !== undefined ? String(e.NETWORK_LOOKUP_URL).trim()
: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, '') + '/api/network/member'
};
return cfg;
}
module.exports = { get, reset: () => { cfg = null; } };
+40
View File
@@ -0,0 +1,40 @@
services:
viraladblitz:
build: .
restart: unless-stopped
environment:
NODE_ENV: production
PORT: 3000
DATA_DIR: /app/data
SITE_HOST: ${SITE_HOST:-viraladblitz.com}
DOCSTORE_URL: ${DOCSTORE_URL:-}
SESSION_SECRET: ${SESSION_SECRET:-}
ADMIN_TOKEN: ${ADMIN_TOKEN:-}
NETWORK_SSO_SECRET: ${NETWORK_SSO_SECRET:-}
WALLETCONNECT_PROJECT_ID: ${WALLETCONNECT_PROJECT_ID:-}
CONTRACT_ADDRESS: ${CONTRACT_ADDRESS:-}
CHAIN_RPC: ${CHAIN_RPC:-}
SHOP_START_BLOCK: ${SHOP_START_BLOCK:-}
KEEPER_KEY: ${KEEPER_KEY:-}
CHAIN_ID: ${CHAIN_ID:-137}
RPC_URLS: ${RPC_URLS:-}
HUB_URL: ${HUB_URL:-}
HUB_SECRET: ${HUB_SECRET:-}
HUB_SITE: ${HUB_SITE:-viraladblitz}
HUB_ENABLED: ${HUB_ENABLED:-0}
TG_TOKEN: ${TG_TOKEN:-}
TG_CHAT: ${TG_CHAT:-}
TG_PAY_TOPIC: ${TG_PAY_TOPIC:-}
NAS_DB_HOST: ${NAS_DB_HOST:-}
NAS_DB_PORT: ${NAS_DB_PORT:-3306}
NAS_DB_USER: ${NAS_DB_USER:-}
NAS_DB_PASSWORD: ${NAS_DB_PASSWORD:-}
NAS_DB_NAME: ${NAS_DB_NAME:-}
NETWORK_SITE_ID: ${NETWORK_SITE_ID:-viraladblitz}
JOIN_URL: ${JOIN_URL:-}
volumes:
- vab-data:/app/data # the session secret file only; all data lives in MySQL (DOCSTORE_URL)
expose:
- "3000" # Coolify's proxy routes the domain here; no host port
volumes:
vab-data:
+191
View File
@@ -0,0 +1,191 @@
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
//
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
// listing a folder). The SAME file ships in InstantAdPay, LinkSpin, Downline Banners and VBB.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
const cache = new Map(); // name -> { body: string, at: ms }
const pending = new Map(); // name -> body string | null (delete)
let flushing = false, timer = null;
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
function nameOf(p) {
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
return rel;
}
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); }
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
async function flush() {
if (!pool || flushing || !pending.size) return;
flushing = true;
try {
for (const [name, body] of [...pending]) {
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
if (!writer) { pending.delete(name); stats.refused++; continue; }
const c = await pool.getConnection();
try {
await c.beginTransaction();
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
await c.commit();
if (pending.get(name) === body) pending.delete(name);
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
finally { c.release(); }
}
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
}
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
function install(dataDir) {
if (ROOT) return; ROOT = path.resolve(dataDir);
fs.readFileSync = function (p, o) {
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
const d = cache.get(n); if (!d) throw enoent(p);
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
};
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
fs.writeFileSync = function (p, data, o) {
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
const flag = o && typeof o === 'object' ? o.flag : null;
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
};
fs.appendFileSync = function (p, data) {
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
};
fs.renameSync = function (a, b) {
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
if (!nb && !na) return O.renameSync.apply(fs, arguments);
let body;
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
};
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
fs.statSync = function (p, o) {
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
};
}
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
// must not run on an empty copy.
async function init(opts) {
const url = String(process.env.DOCSTORE_URL || '').trim();
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
const mysql = require('mysql2/promise');
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) });
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
// first boot for any document: import its file, then set the file aside
const stamp = new Date().toISOString().slice(0, 10);
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
for (const p of walk(ROOT)) {
const n = nameOf(p); if (!n || cache.has(n)) continue;
const body = O.readFileSync.call(fs, p, 'utf8');
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
O.renameSync.call(fs, p, p + '.imported-' + stamp);
}
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
ready = true;
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
const shut = () => { flush().catch(() => {}).finally(() => {}); };
process.once('beforeExit', shut);
return true;
}
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
async function openSplit(sp) {
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
}
async function insertMany(table, items, key, ts) {
for (let i = 0; i < items.length; i += 500) {
const part = items.slice(i, i + 500);
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
}
}
// first boot: the array still inside the document moves to its table, then the document is saved without it
async function migrateSplit(sp) {
const d = cache.get(sp.doc); if (!d) return;
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
await insertMany(sp.table, arr, sp.key, sp.ts);
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
obj[sp.field] = []; const body = JSON.stringify(obj);
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
}
function rows(table) { return ROWS.get(table) || null; }
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
async function runRows() {
rowBusy = true;
try {
while (rowQ.length && writer) {
const op = rowQ[0];
try {
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
rowQ.shift();
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
}
} finally { rowBusy = false; }
}
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
function isOn() { return ready && !!pool; }
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
async function claim(key) {
if (!pool) return true;
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
return r.affectedRows === 1;
}
// SIGTERM during a deploy: write what is pending, then exit
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
+40
View File
@@ -0,0 +1,40 @@
// A member's sponsor line from the network hub (the one source of truth, Marty 2026-11-13/14). Walks hubpeople.sponsorOf()
// up to `max` places, nearest first: [{ depth, id, username, wallet }]. Used two ways:
// - member pages (viraladblitz.com/<username>): the ads of the first 5 people above with a live ad here
// - Boost vouchers: the wallets of the line, bound on chain on the buyer's first Boost (VABShop binds link by link)
// Answers are cached 5 minutes per start person. {ok: false} = the hub did not answer all the way (the line is partial); the
// caller decides (pages fall back to the last good line; vouchers are not signed on a partial line).
'use strict';
const hubpeople = require('./hubpeople');
const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000);
const cache = new Map(); const lastGood = new Map();
async function walk(person, max) {
const line = []; const seen = new Set([person.id]); let p = person;
for (let depth = 1; depth <= max; depth++) {
if (!p.sponsor || !p.sponsor.id) return { ok: true, line };
if (seen.has(p.sponsor.id)) return { ok: true, line, loop: true }; // a loop in the hub data: stop
const r = await hubpeople.sponsorOf(p); if (!r.ok) return { ok: false, line };
if (!r.person) return { ok: true, line };
seen.add(r.person.id);
line.push({ depth, id: r.person.id, username: r.person.username ? String(r.person.username) : null, wallet: hubpeople.wallet(r.person) });
p = r.person;
}
return { ok: true, line };
}
// start = { ref: username } | { wallet }. -> { ok, person, line, stale? }
async function lineOf(start, max) {
const k = JSON.stringify(start) + '|' + max; const hit = cache.get(k);
if (hit && Date.now() - hit.at < TTL()) return hit.v;
const me = start.wallet ? await hubpeople.byWallet(start.wallet) : await hubpeople.byRef(start.ref);
let v;
if (!me.ok) v = { ok: false, person: null, line: [] };
else if (!me.person) v = { ok: true, person: null, line: [] };
else { const w = await walk(me.person, max); v = { ok: w.ok, person: me.person, line: w.line }; }
if (v.ok) { cache.set(k, { at: Date.now(), v }); lastGood.set(k, v); if (cache.size > 20000) cache.clear(); if (lastGood.size > 20000) lastGood.clear(); return v; }
const lg = lastGood.get(k); return lg ? Object.assign({}, lg, { ok: false, stale: true }) : v;
}
module.exports = { lineOf, walk, _reset: () => { cache.clear(); lastGood.clear(); } };
+62
View File
@@ -0,0 +1,62 @@
// Network hub lookups (Marty 2026-11-14: "want everything looped through the hub to verify membership"). The hub is the one
// record per person across the network; this asks it who a username, wallet or hub id is:
// POST /v1/resolve {ref: <username or wallet>} | {wallet} | {id: 'h_...'} -> {person: view or null}
// signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)), the same
// scheme as hubreport.js. This site cannot see emails (seeEmails false): a person is {id, username, wallet, sponsor: {id, username}, blocked, ...}.
// Answers (people and misses) are cached HUB_CACHE_MS (5 minutes). A failed call (timeout, refused, any non-200) is never
// cached: it returns {ok: false} so the caller can fall back, and the hub is skipped for 30 seconds so pages never wait on it.
// On unless HUB_LOOKUP=0; needs HUB_URL and a 32+ character HUB_SECRET (HUB_ENABLED only switches the shadow report).
'use strict';
const crypto = require('crypto');
const DEFAULT_SITE = 'viraladblitz';
const ADDR_RE = /^0x[0-9a-f]{40}$/;
const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000);
const TIMEOUT = () => Number(process.env.HUB_LOOKUP_TIMEOUT_MS || 2500);
const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_LOOKUP || '').trim())
&& !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32;
const cache = new Map(); let downUntil = 0; let lastError = null; const stats = { asked: 0, cached: 0, failed: 0 };
async function call(body) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), TIMEOUT());
try {
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/resolve', { method: 'POST', body: raw, signal: ac.signal,
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || DEFAULT_SITE).trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
if (r.status !== 200) throw new Error('hub answered ' + r.status);
const j = await r.json();
if (!j || typeof j !== 'object' || !('person' in j)) throw new Error('hub answer has no person field');
return j.person && typeof j.person === 'object' ? j.person : null;
} finally { clearTimeout(t); }
}
// {ok: true, person: view | null} when the hub answered; {ok: false} when it is off or unreachable (the caller falls back)
async function resolve(body) {
if (!on() || Date.now() < downUntil) return { ok: false };
const k = JSON.stringify(body); const hit = cache.get(k);
if (hit && Date.now() - hit.at < TTL()) { stats.cached++; return { ok: true, person: hit.person }; }
stats.asked++;
let person;
try { person = await call(body); } catch (e) {
stats.failed++; downUntil = Date.now() + Number(process.env.HUB_DOWN_MS || 30000);
if (!lastError || Date.now() - lastError.at > 600000) console.error('hub lookup failed, falling back:', e.name === 'AbortError' ? 'timeout' : e.message);
lastError = { at: Date.now(), error: e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120) };
return { ok: false };
}
if (cache.size > 20000) cache.clear();
cache.set(k, { at: Date.now(), person });
if (person && person.id) cache.set(JSON.stringify({ id: person.id }), { at: Date.now(), person });
return { ok: true, person };
}
const wallet = p => (p && ADDR_RE.test(String(p.wallet || '').toLowerCase()) ? String(p.wallet).toLowerCase() : null);
// a username or wallet -> person (a blocked person counts as unknown)
async function byRef(ref) { const r = await resolve({ ref: String(ref || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
async function byWallet(w) { const r = await resolve({ wallet: String(w || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
async function byId(id) { if (!/^h_[0-9a-f]{16}$/.test(String(id || ''))) return { ok: true, person: null }; const r = await resolve({ id: String(id) }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; }
// the person's network sponsor as a full person (with wallet), resolved through the hub by hub id. {ok, person: sponsor or null}
async function sponsorOf(p) { if (!p || !p.sponsor || !p.sponsor.id) return { ok: true, person: null }; return byId(p.sponsor.id); }
function view() { return { on: on(), down: Date.now() < downUntil, cached: cache.size, stats, lastError }; }
module.exports = { resolve, byRef, byWallet, byId, sponsorOf, wallet, view, on, _reset: () => { cache.clear(); downUntil = 0; } };
+75
View File
@@ -0,0 +1,75 @@
// Network hub report (the Downline Banners / VBB hubreport.js pattern, 2026-11-14). ViralAdBlitz has no email accounts, so every VABShop Boost
// goes to the hub by wallet:
// the buyer's first purchase: POST /v1/contract-bind { contract: 'viraladblitz', wallet, sponsorRef: <sponsor wallet>, spentCents, tx, at }
// every later purchase: POST /v1/contract-spend { contract: 'viraladblitz', wallet, cents, tx, at }
// signed as HUB_SITE (default viraladblitz) with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)).
// One way only: nothing the hub answers changes anything here. A wallet the hub does not know (404) is kept in `unknown` and asked
// again every 6 hours (the member may link it on InstantAdPay later). Off unless HUB_ENABLED=1 with HUB_URL and a 32+ char HUB_SECRET.
// State lives in hubreport.json (a MySQL document through docstore when DOCSTORE_URL is set).
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const CONTRACT = 'viraladblitz';
const ZERO = '0x0000000000000000000000000000000000000000';
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim())
&& !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32;
const RECHECK = 6 * 3600000;
let R = null, st = null, busy = false;
const FILE = () => path.join(R.dataDir, 'hubreport.json');
function load() {
if (st) return st;
try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = {}; }
st.sent = st.sent || {}; st.bound = st.bound || {}; st.unknown = st.unknown || {}; st.errors = st.errors || {}; st.log = st.log || [];
return st;
}
function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('hubreport save', e.message); } }
function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); }
async function post(route, body) {
const raw = JSON.stringify(body); const ts = String(Date.now());
const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex');
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 15000);
try {
const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + route, { method: 'POST', body: raw, signal: ac.signal,
headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'viraladblitz').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } });
let j = null; try { j = await r.json(); } catch (e) {}
return { status: r.status, body: j };
} finally { clearTimeout(t); }
}
async function tick() {
if (!enabled() || busy) return; busy = true;
try {
const s = load(); const now = Date.now();
const list = R.purchases().slice().sort((a, b) => (a.block || 0) - (b.block || 0) || (a.at || 0) - (b.at || 0));
for (const p of list) {
if (s.sent[p.key]) continue;
const a = p.buyer;
if (s.unknown[a] && now - s.unknown[a].at < RECHECK) continue;
const tx = String(p.key).split(':')[0];
const bind = !s.bound[a];
const body = bind
? { contract: CONTRACT, wallet: a, sponsorRef: p.sponsor && p.sponsor !== ZERO ? p.sponsor : '', spentCents: p.usdCents || 0, tx, at: p.at || now }
: { contract: CONTRACT, wallet: a, cents: p.usdCents || 0, tx, at: p.at || now };
let r; try { r = await post(bind ? '/v1/contract-bind' : '/v1/contract-spend', body); }
catch (e) { s.errors[p.key] = { at: now, error: e.message }; break; } // hub unreachable: try again next tick
if (r.status === 200) { s.sent[p.key] = { at: now, route: bind ? 'bind' : 'spend' }; if (bind) s.bound[a] = now; delete s.unknown[a]; delete s.errors[p.key]; note({ sent: p.key, bind }); }
else if (r.status === 404) { s.unknown[a] = { at: now, sponsor: p.sponsor || null }; note({ unknown: a }); }
else { s.errors[p.key] = { at: now, status: r.status, error: r.body && (r.body.error || r.body.message) }; note({ error: p.key, status: r.status }); if (r.status >= 500) break; }
}
save();
} finally { busy = false; }
}
// deps: { dataDir, purchases: () => [{ key, buyer, sponsor, usdCents, block, at }] }
function init(deps) {
R = deps; if (!enabled()) return; load(); save();
const every = Math.max(200, Number(process.env.HUB_TICK_MS) || 60000);
setTimeout(() => tick().catch(e => console.error('hubreport', e.message)), Math.min(20000, every)).unref();
setInterval(() => tick().catch(e => console.error('hubreport', e.message)), every).unref();
}
function view() { if (!R) return { enabled: false }; const s = load(); return { enabled: enabled(), site: String(process.env.HUB_SITE || 'viraladblitz').trim(), sent: Object.keys(s.sent).length, bound: Object.keys(s.bound).length, unknown: s.unknown, errors: s.errors, log: s.log.slice(-30) }; }
module.exports = { init, tick, view, enabled, CONTRACT };
+61
View File
@@ -0,0 +1,61 @@
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, ViralAdBlitz, Stack POL).
const FALLBACK = [
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
{ id: 'viraladblitz', name: 'ViralAdBlitz', url: 'https://viraladblitz.com' },
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
];
const TTL = 10 * 60 * 1000;
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
let inflight = null;
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
function clean(list) {
if (!Array.isArray(list)) return null;
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
return ok.length ? ok : null;
}
function refresh() {
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
.then(r => (r.ok ? r.json() : null))
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
.finally(() => { clearTimeout(t); inflight = null; });
return inflight;
}
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', viraladblitz: 'nwvab', stackpol: 'nwsp', earnerscorner: 'nwec' };
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
function selfId(req, l) {
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
}
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
function tracked(id, from, extra) {
const code = CODES[id]; if (!code || !from) return '';
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
return linksBase() + '/r/' + code + '?' + q.toString();
}
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
// GET /api/network-sites: public, cacheable, the same answer on every page
function handle(req, res) {
const l = list();
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
res.end(JSON.stringify(withGo(l, selfId(req, l))));
}
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
+212
View File
@@ -0,0 +1,212 @@
// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each
// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes.
//
// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider).
// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st),
// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P.
// 2. P GET /sso/check?st=<state>&to=/path P looks at its OWN member session (never the admin portal). Signed in:
// P mints a token bound to R, the state and the email, and sends the browser
// to R /sso/in?t=<token>. Not signed in: R /sso/in?none=1&to=/path.
// 3. R GET /sso/in?t=<token> R checks signature, audience, expiry (60 s), the state against its cookie
// (so nobody can push their own token into someone else's browser), and spends
// the nonce (a second use is refused). The email must already be a member
// here; then R makes an ordinary session and redirects to the relative path.
// Outbound links: P GET /go/<peer>?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the
// secret not set), it is a plain redirect to the other site, so it is always safe to link through.
// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie
// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link),
// bots and non-page fetches never bounce.
// Token: "v1.<base64url JSON>.<base64url HMAC-SHA256(NETWORK_SSO_SECRET, 'nsso.v1.' + JSON part)>", JSON = { iss, aud, email,
// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it.
//
// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email
// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline
// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet
// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from
// either, and makes a session for that wallet. /sso/start?via=<site> picks which site to ask; old copies ignore the new parameters.
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim();
const enabled = () => SECRET().length >= 32;
const TTL = 60 * 1000; // token life
const SKEW = 30 * 1000; // clock skew allowed between the two servers
const STATE_AGE = 300; // seconds: the state cookie
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz' }; // viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-14); the same line must ship in IAP + LinkSpin
const WALLET_RE = /^0x[0-9a-f]{40}$/;
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
// wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } }
const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64');
const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest();
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || '');
// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters.
function safePath(to, dflt) {
const d = dflt == null ? '/' : dflt;
const s = String(to == null ? '' : to);
if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d;
try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; }
}
function mint(o) {
const now = o.now || Date.now();
const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') };
if (o.wallet) t.wallet = String(o.wallet).toLowerCase();
if (o.name) t.name = String(o.name).slice(0, 40);
const body = b64u(JSON.stringify(t));
return 'v1.' + body + '.' + b64u(mac(body));
}
// -> { ok, email, to, n, exp } or { error: reason }
function verify(tok, o) {
if (!enabled()) return { error: 'off' };
const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || ''));
if (!m) return { error: 'malformed' };
const want = mac(m[1]), got = unb64u(m[2]);
if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' };
let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; }
const now = (o && o.now) || Date.now();
if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' };
if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' };
if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' };
if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' };
const st = String((o && o.st) || '');
if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' };
if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' };
const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null;
return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) };
}
// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it),
// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window).
const used = new Map(); let fileLoaded = false, tableReady = null;
const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null;
function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); }
function loadFile() {
if (fileLoaded) return; fileLoaded = true;
try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {}
}
function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } }
async function spend(n, exp) {
const now = Date.now(); loadFile(); prune(now);
if (used.has(n)) return false;
used.set(n, Number(exp) + SKEW); saveFile();
const db = C && C.db;
if (db && db.enabled && db.enabled()) {
try {
if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; });
await tableReady;
await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]);
if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {});
} catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed
}
return true;
}
// crawlers, link previews and headless browsers never bounce
const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i;
const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); };
// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser)
const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; };
function cookies(req) {
const out = {};
for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } }
return out;
}
const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : '');
const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; };
const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; };
function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); }
// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in)
const offCookie = () => ck('nsso.off', '1', OFF_AGE, true);
// -> true when the request was one of ours and has been answered
async function handle(req, res, u) {
if (!C || req.method !== 'GET') return false;
const p = u.pathname;
const peerName = NAMES[C.peer] || C.peer;
const goTo = p.startsWith('/go/') ? p.slice(4) : '';
const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null);
if (goTo && (goTo === C.peer || walletBase(goTo))) {
const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)();
const to = safePath(u.searchParams.get('to'), '/');
const plain = base + to;
if (!enabled() || isBot(req)) return go(res, plain);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) return go(res, plain);
if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link
return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to));
}
if (p === '/sso/start') {
const to = safePath(u.searchParams.get('to'), C.defaultPath);
const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check';
const via = String(u.searchParams.get('via') || '');
const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider
if (!enabled() || isBot(req) || notPage(req)) return go(res, to);
let s = null; try { s = await C.member(req); } catch (e) {}
if (s && (s.email || s.address)) return go(res, to); // already signed in here
const c = cookies(req);
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
const st = crypto.randomBytes(16).toString('hex');
const set = [ck('nsso.st', st, STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to), set);
}
if (p === '/sso/check') {
const st = String(u.searchParams.get('st') || '');
const to = safePath(u.searchParams.get('to'), '/');
const r = String(u.searchParams.get('r') || '');
const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet
const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud;
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
let s = null; try { s = await C.member(req); } catch (e) {}
if (!s || !s.email) { log('check: not signed in here', null, 'for ' + forName); return go(res, none); }
let w = null;
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
log('token issued', s.email, 'for ' + forName);
return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to }));
}
if (p === '/sso/in') {
const c = cookies(req);
const set = [ck('nsso.st', '', 0, true)];
if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); }
const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] });
if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); }
if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); }
let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; }
if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in
log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email);
set.push(ck('nsso.hint', v.email, HINT_AGE, true));
return go(res, C.signinPath(v.to), set);
}
let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); }
if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); }
set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
log('signed in from ' + (NAMES[v.iss] || peerName), v.email);
return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13)
}
if (p === '/api/sso/status') {
const c = cookies(req); const set = [];
let s = null; try { s = await C.member(req); } catch (e) {}
const signedIn = !!(s && (s.email || s.address));
const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] };
if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); }
return sendJson(res, out, set);
}
return false;
}
module.exports = { init, handle, enabled, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
+240
View File
@@ -0,0 +1,240 @@
{
"name": "viraladblitz",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "viraladblitz",
"version": "0.1.0",
"dependencies": {
"ethers": "^6.13.0",
"mysql2": "^3.11.0"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@adraffy/ens-normalize": {
"version": "1.11.1",
"resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz",
"integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==",
"license": "MIT"
},
"node_modules/@noble/curves": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz",
"integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==",
"license": "MIT",
"dependencies": {
"@noble/hashes": "1.3.2"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@noble/hashes": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz",
"integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==",
"license": "MIT",
"engines": {
"node": ">= 16"
},
"funding": {
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@types/node": {
"version": "22.7.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz",
"integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.2"
}
},
"node_modules/aes-js": {
"version": "4.0.0-beta.5",
"resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz",
"integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==",
"license": "MIT"
},
"node_modules/aws-ssl-profiles": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/ethers": {
"version": "6.17.0",
"resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz",
"integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/ethers-io/"
},
{
"type": "individual",
"url": "https://www.buymeacoffee.com/ricmoo"
}
],
"license": "MIT",
"dependencies": {
"@adraffy/ens-normalize": "1.11.1",
"@noble/curves": "1.2.0",
"@noble/hashes": "1.3.2",
"@types/node": "22.7.5",
"aes-js": "4.0.0-beta.5",
"tslib": "2.7.0",
"ws": "8.21.0"
},
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"license": "MIT",
"dependencies": {
"is-property": "^1.0.2"
}
},
"node_modules/iconv-lite": {
"version": "0.7.3",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz",
"integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==",
"license": "MIT",
"dependencies": {
"safer-buffer": ">= 2.1.2 < 3.0.0"
},
"engines": {
"node": ">=0.10.0"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
"license": "MIT"
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
"node_modules/lru.min": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz",
"integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=1.30.0",
"node": ">=8.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wellwelwel"
}
},
"node_modules/mysql2": {
"version": "3.24.6",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz",
"integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==",
"license": "MIT",
"dependencies": {
"aws-ssl-profiles": "^1.1.2",
"generate-function": "^2.3.1",
"iconv-lite": "^0.7.3",
"long": "^5.3.2",
"lru.min": "^1.1.4",
"named-placeholders": "^1.1.6",
"sql-escaper": "^1.5.1"
},
"engines": {
"node": ">= 8.0"
},
"peerDependencies": {
"@types/node": ">= 8"
}
},
"node_modules/named-placeholders": {
"version": "1.1.6",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
"integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
"license": "MIT",
"dependencies": {
"lru.min": "^1.1.0"
},
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/safer-buffer": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
"license": "MIT"
},
"node_modules/sql-escaper": {
"version": "1.5.2",
"resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz",
"integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=2.0.0",
"node": ">=12.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
}
},
"node_modules/tslib": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz",
"integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==",
"license": "0BSD"
},
"node_modules/undici-types": {
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"license": "MIT"
},
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+20
View File
@@ -0,0 +1,20 @@
{
"name": "viraladblitz",
"version": "0.1.0",
"private": true,
"description": "ViralAdBlitz (viraladblitz.com rebuild): the network's text-ad home. Free text ad for network members, 5-level member pages from the hub sponsor line, one-time $5 Boost (500 guaranteed views) split on-chain 5 levels.",
"main": "server.js",
"scripts": {
"start": "node server.js",
"dev": "node --watch server.js",
"qa": "node qa/smoke.mjs",
"qa:chain": "node qa/chain.mjs"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"ethers": "^6.13.0",
"mysql2": "^3.11.0"
}
}
+100
View File
@@ -0,0 +1,100 @@
// Promo kit (the VBB pattern, 2026-11-14): the ONE place the ViralAdBlitz creatives and swipe copy live. Published as a public
// JSON feed, GET /api/promo-kit?u=<network username or wallet>, read by /promote and by InstantAdPay's promo center ("Network
// sites"). Facts come from config.js (Boost price + guaranteed views, 5 levels). Copy rules: advertising, not income; nothing is
// promised; no em dashes; no earnings caps; wallets = "SafePal or any other crypto wallet".
// Creatives: public/art/kit/vab-<angle>-<shape>.png, rendered by tools/kit-art.mjs (neutral names: no size tokens, no ad words).
'use strict';
const fs = require('fs');
const path = require('path');
const C = require('./config').get();
const netsites = require('./netsites');
const KIT_DIR = path.join(__dirname, 'public', 'art', 'kit');
const SHAPES = { tile: [125, 125, 'Square button'], strip: [468, 60, 'Strip'], leader: [728, 90, 'Leaderboard'], box: [300, 250, 'Box'],
tower: [160, 600, 'Skyscraper'], social: [1200, 630, 'Social share'], square: [1080, 1080, 'Square post'] };
const ANGLES = { free: 'Post a free text ad', spread: 'Your ad on your team\'s pages, 5 levels deep', boost: 'Boost: guaranteed network views' };
function copy() {
const n = x => Number(x || 0).toLocaleString('en-US');
const boost = '$' + C.boost.usd + ' one-time Boost buys ' + n(C.boost.views) + ' guaranteed network views';
return {
lines: [
'InstantAdPay or LinkSpin member? Post a free text ad on ViralAdBlitz. It shows on your page and on your team\'s pages, 5 levels deep. {{LINK}}',
'One text ad: a headline, two lines and your link. Every person you bring in shows it on their page. {{LINK}}',
'ViralAdBlitz: the network\'s text ad wire. Free to join, sign in with your network account. {{LINK}}',
'Want more eyes on your ad? A ' + boost + ', a starred spot on the live ticker and extra places on member pages. No subscription. {{LINK}}',
'Real visitors only: views and clicks count after the page has been seen, bots and repeats do not count. {{LINK}}'
],
headlines: ['Post Your Text Ad Free', 'Your Ad, Five Levels Deep', 'Boost Your Ad Across the Network'],
email: {
subject: 'Your text ad on your whole team\'s pages',
body: [
'Hi,',
'',
'ViralAdBlitz is the network\'s home for text ads: a headline, two lines and your link.',
'',
'If you are an InstantAdPay or LinkSpin member, you can post one text ad free. It shows on your own page, and on the page of everyone you bring in, and everyone they bring in, five levels down.',
'',
'There is a live ticker of the newest ads and a board of the top ads each week, ranked by verified clicks.',
'',
'If you want more people to see it, a ' + boost + '. It is paid in POL with SafePal or any other crypto wallet, once, never a subscription.',
'',
'It is advertising, not income. Nothing is promised.',
'',
'Here is my page:',
'{{LINK}}'
].join('\n')
},
posts: [
'I put my text ad on ViralAdBlitz. It shows on my page and on the pages of everyone I bring in, five levels deep. Free to join for InstantAdPay and LinkSpin members.\n\n{{LINK}}',
'ViralAdBlitz has a live ticker of the newest ads and a weekly board ranked by verified clicks. A ' + boost + '.\n\n{{LINK}}'
]
};
}
const NOTE = 'A Boost buys advertising, not income. Nothing is promised.';
const REF_RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/;
const base = () => 'https://' + C.site;
let files = null;
function creatives() {
if (files) return files;
let names = []; try { names = fs.readdirSync(KIT_DIR).filter(f => /^vab-[a-z]+-[a-z]+\.png$/.test(f)); } catch (e) {}
const out = [];
for (const angle of Object.keys(ANGLES)) for (const shape of Object.keys(SHAPES)) {
const f = 'vab-' + angle + '-' + shape + '.png'; if (!names.includes(f)) continue;
const [w, h, label] = SHAPES[shape];
out.push({ key: angle + '-' + shape, angle, angleLabel: ANGLES[angle], shape, label, w, h, url: base() + '/art/kit/' + f });
}
return (files = out);
}
function kit(u) {
const ref = REF_RE.test(String(u || '')) ? String(u) : '';
// the member's own page is their link (viraladblitz.com/<username>); a wallet falls back to ?ref=
const link = ref && !/^0x/i.test(ref) ? base() + '/' + encodeURIComponent(ref) : base() + '/' + (ref ? '?ref=' + encodeURIComponent(ref) : '');
const q = ref ? '?ref=' + encodeURIComponent(ref) : '';
const fill = s => s.split('{{LINK}}').join(link);
const track = seg => netsites.tracked(C.siteId, C.siteId, { s1: ref, s2: seg });
const t = copy();
return {
v: 1, site: C.site, name: C.siteName, updated: '2026-11-14', username: ref || null,
tagline: 'Your text ad on your whole team\'s pages, five levels deep.',
links: [
{ key: 'page', label: 'Your page', url: link, tracked: track('') },
{ key: 'boost', label: 'Boost', url: base() + '/boost' + q, tracked: track('boost') },
{ key: 'ledger', label: 'Live ledger', url: base() + '/ledger' + q, tracked: track('ledger') }
],
linkTemplate: base() + '/{username}', trackedTemplate: netsites.tracked(C.siteId, C.siteId) + '&s1={username}',
creatives: creatives().map(c => Object.assign({}, c, { html: '<a href="' + link + '" target="_blank" rel="noopener"><img src="' + c.url + '" width="' + c.w + '" height="' + c.h + '" alt="ViralAdBlitz"></a>' })),
lines: t.lines.map(fill), headlines: t.headlines, email: { subject: t.email.subject, body: fill(t.email.body) }, posts: t.posts.map(fill),
note: NOTE, promotePage: base() + '/promote'
};
}
function handle(req, res, u, sendFile) {
if (u.pathname === '/promote' && (req.method === 'GET' || req.method === 'HEAD') && sendFile) { sendFile(res, path.join(__dirname, 'public', 'promote.html')); return true; }
if (u.pathname !== '/api/promo-kit') return false;
const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type' };
if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return true; }
if (req.method !== 'GET' && req.method !== 'HEAD') return false;
res.writeHead(200, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' }, cors));
res.end(JSON.stringify(kit(u.searchParams.get('u')))); return true;
}
module.exports = { kit, handle, creatives, SHAPES, ANGLES, copy };
+138
View File
@@ -0,0 +1,138 @@
// Trust pack (Marty 2026-11-14: "all these sites need to show their live ledger and the contract for proof and trust, and toast
// notifications ... post a Telegram with some kind of image and stats, and payment notifications"). The Downline Banners / VBB pattern.
// - ledger(): every Boost (from the Purchase events shop.js recorded) with its split read from the receipt: each level paid
// (with the person's place in the buyer's line), who was passed over, the company, and Boost delivery (views delivered so far).
// - contract(): live facts for /contract (owner, company, keeper, paused, orders, what it holds), cached 5 minutes.
// - Telegram: one photo card per Boost (a prebuilt ViralAdBlitz proof image, rotated, the buyer, every level paid in that same
// transaction with its POL, this week's numbers and the verify link) in the payments topic (TG_CHAT / TG_PAY_TOPIC, the CTB
// Rewards bot TG_TOKEN, same as Downline Banners and VBB). Once per transaction across app copies (in-process guard +
// docstore.claim), never anything older than 2 hours. Off unless TG_TOKEN and TG_CHAT are set. TG_API (tests) = a stand-in.
'use strict';
const store = require('./store');
const docstore = require('./docstore');
const SPLIT = { levelBps: 1000, levels: 5, denom: 10000 }; // VABShop LEVEL_BPS / LEVELS (constants in the contract)
const CARDS = ['/art/proof/vab-proof-amber.png', '/art/proof/vab-proof-cream.png', '/art/proof/vab-proof-green.png']; // rotated per post
const st = { posted: 0, skipped: 0, failed: 0, lastError: null };
let C = null, shop = null, wire = null, names = null;
const sent = new Set();
const once = k => { if (sent.has(k)) return false; sent.add(k); if (sent.size > 5000) sent.clear(); return true; };
function init(cfg, deps) { C = cfg; shop = deps.shop; wire = deps.wire; names = deps.nameOf || null; }
const on = () => !!(process.env.TG_TOKEN && process.env.TG_CHAT);
const lc = a => String(a || '').toLowerCase();
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : null; }
async function nameOf(addr) { const local = nameLocal(addr); if (local) return local; if (names) { try { const n = await names(lc(addr)); if (n) return n; } catch (e) {} } return null; }
const who = (addr, name) => name ? '@' + name : short(lc(addr));
const pol = wei => { const v = Number(BigInt(wei || 0) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); };
const usd = cents => '$' + (Number(cents || 0) / 100).toFixed(2);
const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' }[c]));
const what = x => (Number(x.qty) > 1 ? x.qty + ' Boosts' : 'a Boost') + ' (' + Number(x.views || 0).toLocaleString('en-US') + ' guaranteed views)';
// the split of one Boost: from the receipt when read, else from the Purchase event (levels paid x 10%, the rest company; who
// got each level is then unknown until the receipt is read)
function split(x) {
if (Array.isArray(x.pays) && x.pays.length) return x.pays;
let paid = 0n; try { paid = BigInt(x.weiPaid || 0); } catch (e) {}
const share = paid * BigInt(SPLIT.levelBps) / BigInt(SPLIT.denom); const out = [];
for (let i = 1; i <= Number(x.levelsPaid || 0); i++) out.push({ level: i, depth: null, to: null, wei: share.toString() });
out.push({ level: 0, depth: 0, to: lc(C.companyWallet), wei: x.companyPaid != null ? String(x.companyPaid) : (paid - share * BigInt(x.levelsPaid || 0)).toString() });
return out;
}
// ---- public ledger ----
function rows() { return Object.entries((store.state() && store.state().purchases) || {}).map(([k, x]) => Object.assign({ key: k, tx: k.split(':')[0] }, x)); }
function ledger(n) {
const lim = Math.min(200, Math.max(1, Number(n) || 50));
const list = rows().map(x => {
const dv = wire ? wire.boostView(x) : null; const a = x.adId ? store.ad(x.adId) : null;
return { kind: 'boost', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), what: what(x), qty: x.qty,
usdCents: x.usdCents, weiPaid: x.weiPaid, ad: a ? { id: a.id, headline: a.headline } : null,
pays: split(x).map(p => ({ level: p.level, depth: p.depth, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })),
passedOver: (x.over || []).map(o => ({ depth: o.depth, name: nameLocal(o.who) || null, who: o.who })),
delivery: dv ? { views: dv.views, delivered: dv.delivered, status: dv.status } : null };
}).sort((a, b) => (b.at || 0) - (a.at || 0));
let wei = 0n, levels = 0n, cents = 0, boosts = 0;
for (const x of rows()) { boosts += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); levels += BigInt(x.weiPaid || 0) - BigInt(x.companyPaid || 0); } catch (e) {} }
return { contract: C.contractAddress || null, explorer: C.explorer, items: list.slice(0, lim), totals: { boosts, orders: list.length, usdCents: cents, weiPaid: wei.toString(), levelsWei: levels.toString() } };
}
// ---- contract facts (cached 5 minutes) ----
let cCache = null;
async function contract() {
if (cCache && Date.now() - cCache.at < 300000) return cCache.v;
const v = { address: C.contractAddress || null, chainId: C.chainId, explorer: C.explorer, split: { levels: 5, levelPct: 10, companyPct: 50, maxDepth: 20 },
boost: { usd: C.boost.usd, views: C.boost.views }, verified: { sourcify: false, polygonscan: 'pending', sourcifyUrl: C.contractAddress ? 'https://repo.sourcify.dev/' + C.chainId + '/' + C.contractAddress : null },
ownerNote: "Marty's Tangem hardware wallet", live: false };
if (shop && shop.watching()) {
const { Interface } = require('ethers');
const I = new Interface(['function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)',
'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)']);
const read = async fn => I.decodeFunctionResult(fn, await shop.rpc('eth_call', [{ to: C.contractAddress, data: I.encodeFunctionData(fn, []) }, 'latest']))[0];
try {
const [owner, company, keeper, paused, totalOwed, orderCount, bal] = await Promise.all(['owner', 'company', 'keeper', 'paused', 'totalOwed', 'orderCount'].map(read)
.concat([shop.rpc('eth_getBalance', [C.contractAddress, 'latest'])]));
Object.assign(v, { owner: lc(owner), company: lc(company), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount), balanceWei: BigInt(bal).toString(), live: true, readAt: Date.now() });
} catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; }
}
cCache = { at: Date.now(), v };
if (v.error) cCache.at = Date.now() - 240000;
return v;
}
// ---- Telegram ----
async function tg(method, body) {
const base = String(process.env.TG_API || 'https://api.telegram.org').replace(/\/+$/, '');
const b = Object.assign({ chat_id: process.env.TG_CHAT, parse_mode: 'HTML' }, body);
if (process.env.TG_PAY_TOPIC) b.message_thread_id = Number(process.env.TG_PAY_TOPIC);
const r = await fetch(base + '/bot' + process.env.TG_TOKEN + '/' + method, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b), signal: AbortSignal.timeout(15000) });
const j = await r.json().catch(() => ({}));
if (!j.ok) { st.failed++; st.lastError = String(j.description || r.status).slice(0, 160); console.error('proof: telegram', method, 'failed', r.status, st.lastError); return false; }
return true;
}
function weekLine() {
const w = wire.weekStats();
return '\u{1F4CA} This week: ' + w.boosts + ' Boost' + (w.boosts === 1 ? '' : 's') + ' · ' + w.adsLive + ' ads live · ' + w.vclicks + ' verified click' + (w.vclicks === 1 ? '' : 's');
}
async function caption(x) {
const lines = ['\u{1F4F0} <b>ViralAdBlitz</b>', '\u{26A1} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' boosted ' + (x.adId && store.ad(x.adId) ? '"' + esc(store.ad(x.adId).headline) + '"' : 'a text ad') + ': ' + esc(what(x)) + ' · ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)'];
const s = split(x); let levels = 0;
for (const p of s) {
if (p.level === 0) { lines.push('\u{1F3E6} ViralAdBlitz: ' + pol(p.wei) + ' POL'); continue; }
levels++;
const where = p.depth && p.depth !== p.level ? ' (place ' + p.depth + ' in the line)' : '';
if (p.failed) lines.push('⚠️ Level ' + p.level + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim');
else lines.push('\u{1F4B8} Level ' + p.level + ' 10%: ' + pol(p.wei) + ' POL → ' + (p.to ? esc(who(p.to, await nameOf(p.to))) : 'sponsor') + where);
}
if (levels === 0) lines.push('Nobody in this line has boosted yet, so the level shares went to ViralAdBlitz.');
if ((x.over || []).length) lines.push(x.over.length === 1 ? '1 person in the line had not boosted yet and was passed over; their share went up the line.' : x.over.length + ' people in the line had not boosted yet and were passed over; their shares went up the line.');
lines.push('Paid by the contract in this same transaction. It keeps nothing and there is nothing to withdraw.');
lines.push(weekLine());
lines.push('· <a href="' + esc(C.explorer) + '/tx/' + esc(x.tx) + '">Verify on Polygonscan</a> · <a href="https://' + esc(C.site) + '/ledger">Live ledger</a>');
return lines.join('\n');
}
let card = 0;
// shop.js calls this once per newly recorded Boost (rec = the stored purchase, tx = its transaction)
function onPurchase(rec, tx) {
const x = Object.assign({ tx }, rec);
(async () => {
try {
const sp = await shop.readSplit(tx, rec.orderId);
if (sp) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId);
if (k) { Object.assign(S.purchases[k], { pays: sp.pays, over: sp.over, bound: sp.bound }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); }
} catch (e) {}
if (!on()) return;
const at = (rec.blockAt ? rec.blockAt * 1000 : rec.at) || Date.now();
if (Date.now() - at > 2 * 3600000) { st.skipped++; return; }
const text = await caption(x);
if (!once('p:' + lc(tx) + ':' + rec.orderId) || !(await docstore.claim('vabtg:' + lc(tx) + ':' + rec.orderId))) return; // never the same Boost twice
const pick = CARDS[card++ % CARDS.length];
const photo = (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + pick;
let ok = await tg('sendPhoto', { photo, caption: text });
if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true });
if (ok) { st.posted++; console.log('proof: posted Boost', String(tx).slice(0, 12)); }
})().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); });
}
function view() { return Object.assign({ telegram: on(), topic: process.env.TG_PAY_TOPIC || null }, st); }
module.exports = { init, ledger, contract, onPurchase, caption, split, view, on, CARDS };
+41
View File
@@ -0,0 +1,41 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Admin | ViralAdBlitz</title>
<meta name="description" content="ViralAdBlitz admin.">
<meta name="robots" content="noindex">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Admin | ViralAdBlitz">
<meta property="og:description" content="ViralAdBlitz admin.">
<meta property="og:url" content="https://viraladblitz.com/admin">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Admin | ViralAdBlitz">
<meta name="twitter:description" content="ViralAdBlitz admin.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero"><div class="copy"><h1>Admin</h1></div></section>
<div class="card"><form class="kit-who" id="tokForm"><input id="tok" type="password" autocomplete="off" placeholder="admin token"><button class="cta" type="submit">Load</button></form></div>
<div class="card"><h3>Status</h3><pre class="kit-pre" id="statusOut">Enter the token.</pre></div>
<div class="card"><h3>Boosts</h3><div class="tscroll"><table class="t" id="boostRows"><tbody></tbody></table></div></div>
<div class="card"><h3>Member lookup</h3><form class="kit-who" id="lookForm"><input id="look" placeholder="wallet, #ad id or username"><button class="cta" type="submit">Look up</button></form><pre class="kit-pre" id="lookOut"></pre></div>
<div class="card"><h3>Ad status</h3><form class="kit-who" id="adForm"><input id="adId" placeholder="ad id"><input id="adStatus" placeholder="live | paused | removed"><input id="adNoteIn" placeholder="note"><button class="cta" type="submit">Set</button></form></div>
<div class="card"><h3>Old site links</h3><p class="small">JSON file {"oldrefs": {"old username": "network username"}} replaces the whole map.</p><input type="file" id="oldFile" accept="application/json"><pre class="kit-pre" id="oldOut"></pre></div>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/admin.js?v=3"></script>
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 55 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.6 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 95 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64"><rect width="64" height="64" fill="#0a1712"/><rect x="0" y="46" width="64" height="6" fill="#ffb000"/><path d="M13 12h9l10 26 10-26h9L37 44h-10z" fill="#f4efe3"/><circle cx="52" cy="14" r="4" fill="#ffb000"/></svg>

After

Width:  |  Height:  |  Size: 298 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 50 KiB

+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 };
})();
+75
View File
@@ -0,0 +1,75 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Boost | ViralAdBlitz</title>
<meta name="description" content="A $5 one-time Boost buys 500 guaranteed network views for your text ad, a starred spot on the live ticker and extra places on member pages. Split on-chain five levels up your line.">
<link rel="canonical" href="https://viraladblitz.com/boost">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Boost | ViralAdBlitz">
<meta property="og:description" content="A $5 one-time Boost buys 500 guaranteed network views for your text ad, a starred spot on the live ticker and extra places on member pages. Split on-chain five levels up your line.">
<meta property="og:url" content="https://viraladblitz.com/boost">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Boost | ViralAdBlitz">
<meta name="twitter:description" content="A $5 one-time Boost buys 500 guaranteed network views for your text ad, a starred spot on the live ticker and extra places on member pages. Split on-chain five levels up your line.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero" style="align-items:stretch">
<div class="copy" style="display:flex;flex-direction:column;gap:14px">
<p class="kicker">One-time, never a subscription</p>
<h1>Boost your text ad across the network</h1>
<p class="lead" style="margin:0">A Boost puts your ad in front of more people: <b id="bViews">500</b> guaranteed network views, a starred spot on the live ticker, and an extra place on the five-level pages. Paid in POL on Polygon.</p>
<p class="small muted" style="margin:0">Views count only from verified visitors: a real browser that keeps the page open and visible for a few seconds, once per visitor per day. If the views are not all delivered on ViralAdBlitz within <span id="bDays">30</span> days, the rest is finished through Network Ad Space.</p>
</div>
<div class="price">
<span class="lab">BOOST PACK</span>
<span class="amt" id="bUsd">$5</span>
<span class="pol" id="bPol">about ... POL at today's price</span>
<ul><li><span id="bViews2">500</span> guaranteed network views</li><li>Starred spot on the live ticker</li><li>Extra place on the five-level pages</li></ul>
<label class="qty">How many <select id="bQty"></select></label>
<button type="button" class="btn-green" id="bBuy">Boost with SafePal or any other crypto wallet</button>
<span class="small" id="bWho" style="color:var(--paper-sub)"></span>
</div>
</section>
<section>
<div class="shead"><h2>Where each Boost goes, in the same transaction</h2></div>
<div class="splits">
<div class="split"><span>LEVEL 1</span><b>10%</b><i>your sponsor</i></div>
<div class="split"><span>LEVEL 2</span><b>10%</b><i>their sponsor</i></div>
<div class="split"><span>LEVEL 3</span><b>10%</b><i>next up</i></div>
<div class="split"><span>LEVEL 4</span><b>10%</b><i>next up</i></div>
<div class="split"><span>LEVEL 5</span><b>10%</b><i>next up</i></div>
<div class="split co"><span>COMPANY</span><b>50%</b><i>runs the network</i></div>
</div>
<p class="sub" style="max-width:820px">Levels follow your sponsor line in the network. Someone in your line who has not bought a Boost is passed over, and their share goes up to the next person who has. The contract looks up to 20 places up the line; a share nobody qualifies for goes to the company. Nothing is held and there is nothing to withdraw. A Boost buys advertising, not income: you are paid only when people in your team buy Boosts, and nothing is promised.</p>
</section>
<section class="box">
<div class="txt"><span class="lab">YOUR LINE IS SET ONCE</span><span class="big">Your sponsor line comes from the network hub.</span><span class="sub">On your first Boost the site signs your line and the contract records it. After that it never changes, so every later Boost pays the same people.</span></div>
</section>
<section style="display:flex;flex-wrap:wrap;gap:32px;align-items:flex-start">
<div style="flex:999 1 460px;min-width:0;display:flex;flex-direction:column;gap:10px">
<h2>Every sale is posted in Telegram</h2>
<p class="sub" style="margin:0">Each Boost posts a card to the network's Telegram with the week's stats and a link to verify the transaction, and every payout gets its own line. The same events show as toasts on the site and rows in the live ledger.</p>
</div>
<div class="card" style="flex:1 1 360px"><span class="small muted">Telegram · payments topic</span><p style="margin:8px 0 0"><b style="font-family:var(--disp);color:var(--cream);font-size:20px">ViralAdBlitz</b><br><span class="mono" style="color:var(--amber)">@member boosted an ad</span><br><span class="mono small">This week: Boosts, ads live, verified clicks</span></p><p class="small">Level payouts in the same transaction. <a href="/ledger">Verify</a></p></div>
</section>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=3"></script>
<script src="/assets/buy.js?v=3"></script>
<script src="/assets/boost.js?v=3"></script>
</body>
</html>
+50
View File
@@ -0,0 +1,50 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Contract Proof | ViralAdBlitz</title>
<meta name="description" content="The ViralAdBlitz Boost contract on Polygon: owner, company, keeper and the fixed five-level split, read live from the chain.">
<link rel="canonical" href="https://viraladblitz.com/contract">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Contract Proof | ViralAdBlitz">
<meta property="og:description" content="The ViralAdBlitz Boost contract on Polygon: owner, company, keeper and the fixed five-level split, read live from the chain.">
<meta property="og:url" content="https://viraladblitz.com/contract">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Contract Proof | ViralAdBlitz">
<meta name="twitter:description" content="The ViralAdBlitz Boost contract on Polygon: owner, company, keeper and the fixed five-level split, read live from the chain.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Read live from Polygon</p><h1>Contract proof</h1><p class="lead">Every Boost is paid to one smart contract on Polygon. It splits the payment in the same transaction. Check every number here yourself.</p></div></section>
<div class="card"><h2>The contract</h2><table class="facts" id="facts"><tbody><tr><td class="muted">Reading the contract...</td></tr></tbody></table></div>
<section>
<div class="shead"><h2>Where each Boost goes</h2></div>
<div class="splits">
<div class="split"><span>LEVEL 1</span><b>10%</b><i>nearest qualified</i></div><div class="split"><span>LEVEL 2</span><b>10%</b><i>next qualified</i></div>
<div class="split"><span>LEVEL 3</span><b>10%</b><i>next qualified</i></div><div class="split"><span>LEVEL 4</span><b>10%</b><i>next qualified</i></div>
<div class="split"><span>LEVEL 5</span><b>10%</b><i>next qualified</i></div><div class="split co"><span>COMPANY</span><b>50%</b><i>plus any share nobody qualifies for</i></div>
</div>
<p class="sub">The percentages are constants in the contract code: nobody can change who gets what share. There is no owner withdraw. The contract keeps nothing: if a payment cannot be delivered, it waits in the contract for that wallet to claim, and nobody else can take it. Anything sent above the price comes back in the same transaction.</p>
</section>
<div class="card"><h2>Check it yourself</h2><ol class="sub">
<li>Open the contract on Polygonscan (link above) and read its verified source code.</li>
<li>Choose <b>Read Contract</b> and compare owner, company and keeper with this page.</li>
<li>Open any Boost in the <a href="/ledger">live ledger</a> and look at its <b>Logs</b>: one Purchase event, one Paid event per level and one for the company, and a PassedOver event for anyone in the line who had not boosted.</li>
</ol></div>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/contract.js?v=3"></script>
</body>
</html>
+39
View File
@@ -0,0 +1,39 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Earnings Disclaimer | ViralAdBlitz</title>
<meta name="description" content="Advertising, not income. Nothing is promised.">
<link rel="canonical" href="https://viraladblitz.com/disclaimer">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Earnings Disclaimer | ViralAdBlitz">
<meta property="og:description" content="Advertising, not income. Nothing is promised.">
<meta property="og:url" content="https://viraladblitz.com/disclaimer">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Earnings Disclaimer | ViralAdBlitz">
<meta name="twitter:description" content="Advertising, not income. Nothing is promised.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap legal">
<section class="hero"><div class="copy"><h1>Earnings Disclaimer</h1><p class="lead">Advertising, not income. Nothing is promised.</p><p class="muted small">Last updated November 14, 2026</p></div></section>
<div class="card"><h2>What you are buying</h2><p>A ViralAdBlitz Boost is advertising for your own text ad: guaranteed views, a ticker spot and member-page places. It is not an investment, a business opportunity, a share of profits or a promise of any payment.</p></div>
<div class="card"><h2>Level shares are not promised</h2><p>The contract pays a level share only when someone in your team chooses to buy a Boost. Nobody is required to buy one, and we do not know or promise whether anyone in your team ever will. Many members receive nothing, and many receive less than they spend. Your results depend on other people's free choices, not on anything we do.</p></div>
<div class="card"><h2>No examples are promises</h2><p>Any number on this site, in the ledger or in a Telegram post shows what really happened in one transaction. It is not a typical result and not a forecast of what you will receive.</p></div>
<div class="card"><h2>Prices and taxes</h2><p>Boosts are priced in US dollars and paid in POL, whose price moves. Anything you receive is in POL and its dollar value can change. You are responsible for any taxes on what you receive where you live.</p></div>
<div class="card"><h2>Who to ask</h2><p>TrustClickz, 615 Green Valley Drive, Moody, AL 35004. <a href="https://instantadpay.com/support" target="_blank" rel="noopener">Network support</a>.</p></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/static.js?v=3"></script>
</body>
</html>
+73
View File
@@ -0,0 +1,73 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>ViralAdBlitz | Your text ad on your whole team's pages, five levels deep</title>
<meta name="description" content="The network's text ad wire. Post one free text ad: it shows on your page and on the page of everyone you bring in, five levels down. Live ticker, top ads by verified clicks, a $5 one-time Boost.">
<link rel="canonical" href="https://viraladblitz.com/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="ViralAdBlitz | Your text ad on your whole team's pages, five levels deep">
<meta property="og:description" content="The network's text ad wire. Post one free text ad: it shows on your page and on the page of everyone you bring in, five levels down. Live ticker, top ads by verified clicks, a $5 one-time Boost.">
<meta property="og:url" content="https://viraladblitz.com/">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="ViralAdBlitz | Your text ad on your whole team's pages, five levels deep">
<meta name="twitter:description" content="The network's text ad wire. Post one free text ad: it shows on your page and on the page of everyone you bring in, five levels down. Live ticker, top ads by verified clicks, a $5 one-time Boost.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebSite","name":"ViralAdBlitz","url":"https://viraladblitz.com/"},{"@type":"Organization","name":"ViralAdBlitz","url":"https://viraladblitz.com/","logo":"https://viraladblitz.com/art/icon-192.png"}]}</script>
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero">
<div class="copy">
<p class="kicker">The network's text ad wire</p>
<h1>Your ad runs on your whole team's pages. Five levels deep.</h1>
<p class="lead">Write one text ad: a headline, two lines and your link. It shows on your page and on the page of everyone you bring in, and everyone they bring in, five levels down. Free to join for network members.</p>
<div class="row"><a class="cta" href="/my">Post my free text ad</a><a class="btn-line" href="/boost">How a Boost works</a></div>
</div>
<div class="wirebox" aria-label="Today on the wire">
<span class="lab">TODAY ON THE WIRE</span>
<div class="kv"><span>Ad views</span><b id="stViews">0</b></div>
<div class="kv"><span>Verified clicks</span><b id="stClicks">0</b></div>
<div class="kv"><span>Boosts sold</span><b id="stBoosts">0</b></div>
<div class="kv"><span>Ads live</span><b id="stAds">0</b></div>
</div>
</section>
<section id="board">
<div class="shead"><h2>Top ads this week</h2><span class="side">ranked by verified clicks</span></div>
<div class="cards" id="boardCards"><p class="muted">Loading the board...</p></div>
</section>
<section class="steps" aria-label="How it works">
<div class="step"><span class="n">1</span><b>Post one free text ad</b><span>Sign in with your InstantAdPay or LinkSpin account. A headline, two lines and your link.</span></div>
<div class="step"><span class="n">2</span><b>Share your page</b><span>Your page shows your ad and the five people above you. Every visit shows six ads.</span></div>
<div class="step"><span class="n">3</span><b>Your ad spreads down</b><span>Everyone you bring in shows your ad on their page, five levels deep.</span></div>
</section>
<section id="ledger">
<div class="shead"><h2>Live ledger</h2><span class="side">every Boost and every payout, straight from the chain</span></div>
<div class="tscroll"><table class="t" id="ledgerMini"><thead><tr><th>TIME CT</th><th>EVENT</th><th>MEMBER</th><th>POL</th><th>TX</th></tr></thead><tbody><tr><td colspan="5" class="muted">Loading the ledger...</td></tr></tbody></table></div>
<p class="small"><a href="/ledger">Open the full ledger</a></p>
</section>
<section class="box" id="contract">
<div class="txt"><span class="lab">CONTRACT PROOF</span><span class="big">Paid in the same transaction. Nothing held, nothing to withdraw.</span><span class="addr" id="cAddr">Polygon · the contract address shows here once it is live</span></div>
<a class="btn-line" id="cLink" href="/contract">Check the contract</a>
</section>
<p class="muted small">A Boost buys advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/front.js?v=3"></script>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Live Ledger | ViralAdBlitz</title>
<meta name="description" content="Every ViralAdBlitz Boost and every level payout, read from the Polygon contract, with a link to verify each transaction.">
<link rel="canonical" href="https://viraladblitz.com/ledger">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Live Ledger | ViralAdBlitz">
<meta property="og:description" content="Every ViralAdBlitz Boost and every level payout, read from the Polygon contract, with a link to verify each transaction.">
<meta property="og:url" content="https://viraladblitz.com/ledger">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Live Ledger | ViralAdBlitz">
<meta name="twitter:description" content="Every ViralAdBlitz Boost and every level payout, read from the Polygon contract, with a link to verify each transaction.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Straight from the chain</p><h1>Live ledger</h1><p class="lead">Every Boost and every payout. Each row links to its transaction on Polygonscan, so you can check it yourself.</p></div></section>
<div class="stats" id="totals"></div>
<section>
<div class="tscroll"><table class="t" id="rows"><thead><tr><th>TIME CT</th><th>BOOST</th><th>PAID IN THE SAME TRANSACTION</th><th>TX</th></tr></thead><tbody><tr><td colspan="4" class="muted">Loading the ledger...</td></tr></tbody></table></div>
</section>
<p class="muted small">Levels follow the buyer's sponsor line. Someone who has not bought a Boost is passed over and their share goes up to the next person who has. Advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/ledger.js?v=3"></script>
</body>
</html>
+49
View File
@@ -0,0 +1,49 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>A member's page | ViralAdBlitz</title>
<meta name="description" content="Text ads recommended by a ViralAdBlitz member and the five people above them in the network.">
<link rel="canonical" href="https://viraladblitz.com/">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="A member's page | ViralAdBlitz">
<meta property="og:description" content="Text ads recommended by a ViralAdBlitz member and the five people above them in the network.">
<meta property="og:url" content="https://viraladblitz.com/">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="A member's page | ViralAdBlitz">
<meta name="twitter:description" content="Text ads recommended by a ViralAdBlitz member and the five people above them in the network.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<p class="kicker" id="who">RECOMMENDED</p>
<div id="own"><p class="muted">Loading...</p></div>
<section>
<div class="shead"><h2 id="teamHead">Also recommended by the team</h2><span class="side">the five people above them in the network</span></div>
<div class="levels" id="levels"></div>
</section>
<section id="boostedSec" hidden>
<div class="shead"><h2>Boosted across the network</h2><span class="side">members who boosted their ad</span></div>
<div class="cards" id="boosted"></div>
</section>
<section class="joinbar" id="join">
<div class="txt"><b id="joinHead">Want your ad on pages like this one?</b><p id="joinText">Join free. Your ad goes on your own page and on every page you bring in, five levels down.</p></div>
<div class="row" style="margin:0"><a class="cta" id="joinBtn" href="/my">Join free</a><a class="btn-line" href="/my">I am a member: sign in</a></div>
</section>
<p class="muted small">Advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/member.js?v=3"></script>
</body>
</html>
+64
View File
@@ -0,0 +1,64 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>My page | ViralAdBlitz</title>
<meta name="description" content="Post or edit your free text ad, share your page, and follow your Boost.">
<meta name="robots" content="noindex">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="My page | ViralAdBlitz">
<meta property="og:description" content="Post or edit your free text ad, share your page, and follow your Boost.">
<meta property="og:url" content="https://viraladblitz.com/my">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="My page | ViralAdBlitz">
<meta name="twitter:description" content="Post or edit your free text ad, share your page, and follow your Boost.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Your desk</p><h1>My page</h1><p class="lead">One free text ad for network members. Share your page and your ad spreads five levels down.</p></div></section>
<section id="signin" hidden>
<div class="card">
<h2>Sign in</h2>
<p>Sign in with your network account. Your username and your sponsor line come with you.</p>
<div class="signin"><a class="cta" id="viaIap" href="/sso/start?mode=go&amp;via=iap&amp;to=%2Fmy">Sign in with InstantAdPay</a><a class="cta" id="viaLs" href="/sso/start?mode=go&amp;via=linkspin&amp;to=%2Fmy">Sign in with LinkSpin</a><button class="btn-line" id="viaWallet" type="button">Sign in with your wallet</button></div>
<p class="small muted">Wallet sign-in works with SafePal or any other crypto wallet. It is a free signature that cannot move funds.</p>
<p class="small">Not in the network yet? <a id="joinLink" href="https://instantadpay.com/" target="_blank" rel="noopener">Join InstantAdPay free</a>, then come back and sign in through it.</p>
</div>
</section>
<section id="dash" hidden>
<div class="stats" id="stats"></div>
<div class="card" id="pageCard" style="margin-top:16px"></div>
<div class="card" id="adCard" style="margin-top:16px">
<h2 id="adHead">Your text ad</h2>
<p class="small" id="adNote">A headline, two lines and your https link. No link shorteners.</p>
<form class="form" id="adForm">
<label class="f">Headline <input id="fHead" maxlength="60" autocomplete="off" required><span class="cnt" id="cHead"></span></label>
<label class="f">First line <input id="fL1" maxlength="90" autocomplete="off" required><span class="cnt" id="cL1"></span></label>
<label class="f">Second line (optional) <input id="fL2" maxlength="90" autocomplete="off"><span class="cnt" id="cL2"></span></label>
<label class="f">Your link <input id="fLink" maxlength="600" autocomplete="off" inputmode="url" placeholder="https://" required></label>
<div class="row" style="margin:0"><button class="btn-green" id="adSave" type="submit">Post my free text ad</button><span class="small muted">Tracking codes work: {clickid} and {placement} are filled on every click.</span></div>
</form>
</div>
<div class="card" id="lineCard" style="margin-top:16px"><h2>Your line</h2><div id="line"></div></div>
<div class="card" id="boostCard" style="margin-top:16px"><h2>Your Boosts</h2><div id="boosts"></div><div class="row"><a class="cta" href="/boost">Boost my ad</a></div></div>
<div class="card" id="earnCard" style="margin-top:16px"><h2>Paid to you</h2><div id="earned"></div></div>
<div class="row"><button class="btn-quiet" id="signout" type="button">Sign out</button></div>
</section>
<div id="status" class="note" hidden></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/wallet.js?v=3"></script>
<script src="/assets/my.js?v=3"></script>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Privacy Policy | ViralAdBlitz</title>
<meta name="description" content="What ViralAdBlitz keeps about you, why, and for how long.">
<link rel="canonical" href="https://viraladblitz.com/privacy">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Privacy Policy | ViralAdBlitz">
<meta property="og:description" content="What ViralAdBlitz keeps about you, why, and for how long.">
<meta property="og:url" content="https://viraladblitz.com/privacy">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Privacy Policy | ViralAdBlitz">
<meta name="twitter:description" content="What ViralAdBlitz keeps about you, why, and for how long.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap legal">
<section class="hero"><div class="copy"><h1>Privacy Policy</h1><p class="lead">What ViralAdBlitz keeps about you, why, and for how long.</p><p class="muted small">Last updated November 14, 2026</p></div></section>
<div class="card"><h2>Who we are</h2><p>ViralAdBlitz is run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004.</p></div>
<div class="card"><h2>What we keep</h2><ul><li>Your wallet address and network username, and your text ad (it is public: that is its purpose).</li><li>Your network record from the network hub: your hub id and your sponsor line. ViralAdBlitz does not store your email. When you sign in through InstantAdPay or LinkSpin, your email is used once to check your network membership and is not kept.</li><li>Your Boosts, which are public on the Polygon blockchain, and how many of their views have been delivered.</li><li>For counting real views and clicks: a one-way code made from your internet address and browser type (never the address itself), the page, and the site that sent you. Visit and click records are kept 15 days; the records of each view counted toward a Boost are kept 120 days so delivery can be checked.</li></ul></div>
<div class="card"><h2>Cookies</h2><p>A sign-in cookie (7 days), a cookie that remembers whose page you came from (30 days), and short-lived cookies for signing in through the network. No advertising or tracking cookies of our own.</p></div>
<div class="card"><h2>Who else sees data</h2><ul><li>The Polygon blockchain: every Boost and payment is public there, by its nature.</li><li>The network hub, which keeps one record per person across the network sites (username, wallet, sponsor).</li><li>Our Telegram payments topic: each Boost is posted with the buyer's username (or a shortened wallet) and the amounts paid.</li><li>Services the pages load: Google Fonts, WalletConnect (Reown) when you connect a wallet, LinkSpin network ad zones, and Network Ad Space for finishing Boost views.</li></ul><p>We do not sell personal data.</p></div>
<div class="card"><h2>Your choices</h2><p>You can edit your ad at any time, or ask us to remove it and your account here. Records on the blockchain cannot be removed by anyone.</p></div>
<div class="card"><h2>Contact</h2><p>Questions, problems or a request about your data: <a href="https://instantadpay.com/support" target="_blank" rel="noopener">network support</a>, or write to TrustClickz, 615 Green Valley Drive, Moody, AL 35004.</p></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/static.js?v=3"></script>
</body>
</html>
+40
View File
@@ -0,0 +1,40 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Promote | ViralAdBlitz</title>
<meta name="description" content="Your ViralAdBlitz links, creatives in every common size, and copy you can paste anywhere.">
<link rel="canonical" href="https://viraladblitz.com/promote">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Promote | ViralAdBlitz">
<meta property="og:description" content="Your ViralAdBlitz links, creatives in every common size, and copy you can paste anywhere.">
<meta property="og:url" content="https://viraladblitz.com/promote">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Promote | ViralAdBlitz">
<meta name="twitter:description" content="Your ViralAdBlitz links, creatives in every common size, and copy you can paste anywhere.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Share the wire</p><h1>Promote ViralAdBlitz</h1><p class="lead">Your links, creatives in every common size, and copy you can paste anywhere. Everything carries your network username.</p></div></section>
<div class="card" id="whoCard"><h3>Your network username</h3>
<p class="small" id="whoNote">Your InstantAdPay or LinkSpin username works here. Sign in on <a href="/my">My page</a> and it fills in by itself.</p>
<form class="kit-who" id="whoForm"><input id="whoIn" autocomplete="off" spellcheck="false" maxlength="42" placeholder="your username"><button class="cta" type="submit">Use it</button></form></div>
<div id="status" class="note" hidden></div>
<div id="kit" style="display:flex;flex-direction:column;gap:16px"><p class="muted">Loading the kit...</p></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/kitpage.js?v=3"></script>
<script src="/assets/promote.js?v=3"></script>
</body>
</html>
+48
View File
@@ -0,0 +1,48 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>Terms and Conditions | ViralAdBlitz</title>
<meta name="description" content="The rules for using ViralAdBlitz, in plain English.">
<link rel="canonical" href="https://viraladblitz.com/terms">
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="Terms and Conditions | ViralAdBlitz">
<meta property="og:description" content="The rules for using ViralAdBlitz, in plain English.">
<meta property="og:url" content="https://viraladblitz.com/terms">
<meta property="og:image" content="https://viraladblitz.com/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Terms and Conditions | ViralAdBlitz">
<meta name="twitter:description" content="The rules for using ViralAdBlitz, in plain English.">
<meta name="twitter:image" content="https://viraladblitz.com/art/og-share.png">
<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">
<link rel="stylesheet" href="/assets/vab.css?v=3">
</head>
<body>
<main class="wrap legal">
<section class="hero"><div class="copy"><h1>Terms and Conditions</h1><p class="lead">The rules for using ViralAdBlitz, in plain English.</p><p class="muted small">Last updated November 14, 2026</p></div></section>
<div class="card"><h2>Who we are</h2><p>ViralAdBlitz (viraladblitz.com) is run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. It is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, Stack POL and Earners Corner. By using ViralAdBlitz you agree to these terms.</p></div>
<div class="card"><h2>What ViralAdBlitz is</h2><p>ViralAdBlitz is the network's home for text ads. A network member posts one text ad: a headline, two lines and a link. Each member has a page that shows their own ad and the ads of the five people above them in their network sponsor line, so an ad appears on the pages of the people its owner brings in, five levels down. The front page shows a live ticker of the newest ads and a weekly board of the top ads by verified clicks.</p></div>
<div class="card"><h2>Your free text ad</h2><p>One text ad is free for each network member (InstantAdPay or LinkSpin, checked with the network hub). You can edit it at any time. There is nothing to pay to post it.</p></div>
<div class="card"><h2>What a Boost is</h2><p>A Boost is a single, one-time purchase of $5 for your text ad. It buys 500 guaranteed network views, a starred spot on the live ticker while the views are delivered, and an extra place on member pages. You can buy more than one; each adds its own 500 views.</p><p>A view counts only from a verified visitor: a real browser that keeps a ViralAdBlitz page open and visible for a few seconds, once per visitor per ad each day, never your own views, never bots. Views are delivered on ViralAdBlitz pages first. If a Boost's views are not all delivered within 30 days, the rest is delivered through Network Ad Space, a network ad site, as a text ad with the same headline, lines and link.</p><p>Boosts are paid in POL on Polygon at the live Chainlink POL/USD price the contract reads when you buy. Anything you send above the price comes back to you in the same transaction. Nothing renews and nothing is ever billed again. There are no subscriptions.</p><p>What you buy is advertising for your own text ad. It is not income, an investment or a share of anything.</p></div>
<div class="card"><h2>How a payment is split</h2><p>The ViralAdBlitz contract splits each Boost in the same transaction it is paid: 10% to each of five levels up the buyer's sponsor line and 50% to ViralAdBlitz.</p><p>Only someone who has bought at least one Boost can receive a level share. Someone in the line who has not is passed over, and the share goes up to the next person who has. The contract looks up to 20 places up the line for five such people; a share nobody qualifies for goes to ViralAdBlitz.</p><p>Your sponsor line comes from the network hub. On your first Boost the site signs it and the contract records it link by link. A link already recorded is never changed, so every later Boost pays along the same line. Members of the line without a wallet in the network cannot receive payments and are left out of the recorded line.</p><p>The split is fixed in the contract code and there is no owner withdraw. The contract keeps nothing: each share goes straight to the person's wallet in the buyer's transaction. If a payment cannot be delivered, it waits in the contract for that wallet to claim, and nobody else can take it.</p></div>
<div class="card"><h2>Nothing is promised</h2><p>We do not promise or guarantee any income, payout or result. A level share is paid only when someone in your team chooses to buy a Boost. Read the <a href="/disclaimer">Earnings Disclaimer</a>.</p></div>
<div class="card"><h2>No refunds</h2><p>Payments are made on the blockchain and are final once confirmed. We cannot reverse, cancel or refund them. Check the amount before you confirm in your wallet. If your ad is removed for breaking these terms, the views left on its Boosts are not delivered or refunded.</p></div>
<div class="card"><h2>Crypto risk</h2><ul><li>The price of POL moves. The dollar value of a payment can be higher or lower later than when it was paid.</li><li>You are responsible for your wallet and its recovery phrase. Nobody, including us, can recover a lost wallet or reverse a payment sent from it.</li><li>Blockchain transactions are final. Each one costs a small network fee (gas) in POL, paid to the network, not to us.</li><li>Use SafePal or any other crypto wallet you trust, and never share your recovery phrase with anyone. We will never ask for it.</li></ul></div>
<div class="card"><h2>Text ad rules</h2><p>Your ad and its link must be your own or ones you have the right to use, and the link must lead to a lawful page that loads. No adult content, malware, phishing, deceptive offers, hate, or anything illegal where you or your visitors live. No link shorteners. We may pause or remove an ad that breaks these rules and close the account behind it.</p></div>
<div class="card"><h2>Fair use</h2><p>Views and clicks count only from verified visitors, and only a few visitors per internet connection count each day. Bots, crawlers and repeat visits do not count. We may refuse visits or clicks we judge not to be real, and may remove anyone who fakes traffic from the board. Do not try to break, overload or game the site.</p></div>
<div class="card"><h2>Your account</h2><p>You sign in with your wallet or through InstantAdPay or LinkSpin. Your network account, username and sponsor are shared across the network through the network hub, as described in the <a href="/privacy">Privacy Policy</a>. You must be old enough to make a binding agreement where you live, and using crypto must be legal there.</p></div>
<div class="card"><h2>The service</h2><p>The site is provided as it is. We work to keep it running but cannot promise it will always be available or free of errors. The smart contract runs on Polygon on its own; its rules are public and can be checked on the <a href="/contract">contract page</a>. We may change features, the price of future Boosts or these terms; changes apply from the date they are posted here.</p></div>
<div class="card"><h2>Limits</h2><p>As far as the law allows, we are not responsible for losses caused by the blockchain, your wallet, the price of POL, third-party websites in ads, or events outside our control, and our total responsibility to you is limited to what you paid for the purchase in question. These terms are governed by the laws of the State of Alabama, USA.</p></div>
<div class="card"><h2>Contact</h2><p>Questions, problems or a request about your data: <a href="https://instantadpay.com/support" target="_blank" rel="noopener">network support</a>, or write to TrustClickz, 615 Green Valley Drive, Moody, AL 35004.</p></div>
</main>
<script src="/assets/common.js?v=3"></script>
<script src="/assets/static.js?v=3"></script>
</body>
</html>
+136
View File
@@ -0,0 +1,136 @@
// ViralAdBlitz real-contract test on a local anvil chain (no fork, nothing leaves this machine, no real POL).
// Deploys the real VABShop (../contracts/out) with a mock Chainlink feed at $0.25, boots the app against it with a stand-in hub
// (line: B -> A1 -> A2 -> A3) and a stand-in Telegram API, and checks through the app's own order flow:
// 1. A3 (top, no line) boosts: nothing qualifies, 100% to the company.
// 2. A1 boosts with a voucher binding [A2, A3]: A2 never boosted and is passed over, A3 gets level 1 at place 2; company 90%.
// 3. B boosts 2 with the app's 1% overpay: the voucher binds B -> A1 and stops (A1 already bound); A1 level 1, A3 level 2;
// company 80%; the overpay comes back in the same transaction (buyer spent = price + gas, exact).
// Every amount exact to the wei; /api/ledger matches the receipts; one Telegram card per Boost, never twice; /api/contract live.
// node qa/chain.mjs (needs anvil: ~/.foundry/bin/anvil(.exe), and forge build output in ../contracts/out)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import http from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
const DATA = path.join(OUT, 'chain-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const ANVIL = process.env.ANVIL || path.join(os.homedir(), '.foundry', 'bin', process.platform === 'win32' ? 'anvil.exe' : 'anvil');
const ART = path.resolve(APP, '..', 'contracts', 'out');
const APORT = Number(process.env.CHAIN_ANVIL_PORT || 8571), PORT = Number(process.env.CHAIN_APP_PORT || 3331);
const RPC = 'http://127.0.0.1:' + APORT, BASE = 'http://127.0.0.1:' + PORT, ADMIN = 'chain-admin-token', HUB_SECRET = 'c'.repeat(40);
// anvil's public dev keys (local chain only)
const K = ['0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80', '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d',
'0x5de4111afa1a4b94908f83103eb1f1706367c2e68ca870fc3fb9a804cdab365a', '0x7c852118294e51e653712a81e05800f419141751be58f605c371e15141b007a6',
'0x47e179ec197488593b187f80a00eb0da91f1b9d0b13f8733639f19c30a34926a', '0x8b3a350cf5c34c9194ca85829a2df0ec3153be0318b5e2d3348e872092edffba'];
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; const procs = [];
const ok = (c, what, extra) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 500) : '')); } };
process.on('exit', () => { for (const p of procs) try { p.kill(); } catch (e) {} });
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; await fn(q, r, b); }).listen(port, '127.0.0.1').unref();
// stand-in Telegram (never the real group)
const TG = []; listen(PORT + 2, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
// stand-in hub: wallet -> { id, username, sponsor wallet }
const people = new Map();
listen(PORT + 1, async (q, r, b) => {
const j = JSON.parse(b || '{}'); r.setHeader('Content-Type', 'application/json');
if (q.url !== '/v1/resolve') return r.end('{"ok":true}');
const all = [...people.entries()];
const w = j.wallet ? String(j.wallet).toLowerCase() : j.id ? (all.find(([, p]) => p.id === j.id) || [])[0] : j.ref ? (all.find(([a, p]) => a === String(j.ref).toLowerCase() || p.username === String(j.ref).toLowerCase()) || [])[0] : null;
const p = w && people.get(w); const sp = p && p.sponsor && people.get(p.sponsor);
r.end(JSON.stringify({ person: p ? { id: p.id, username: p.username, wallet: w, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null } : null }));
});
async function main() {
if (!fs.existsSync(ANVIL)) throw new Error('anvil not found at ' + ANVIL);
const an = spawn(ANVIL, ['--port', String(APORT), '--silent', '--chain-id', '31337'], { stdio: 'ignore' }); procs.push(an);
const provider = new ethers.JsonRpcProvider(RPC, 31337, { staticNetwork: true });
for (let i = 0; i < 60; i++) { try { await provider.getBlockNumber(); break; } catch (e) { await sleep(200); } }
const deployer = new ethers.Wallet(K[0], provider), keeper = new ethers.Wallet(K[1]);
const [A3, A2, A1, B] = [K[2], K[3], K[4], K[5]].map(k => new ethers.Wallet(k, provider));
const company = ethers.Wallet.createRandom().address;
const lc = w => w.address.toLowerCase();
people.set(lc(A3), { id: 'h_' + '3'.repeat(16), username: 'athree' }); people.set(lc(A2), { id: 'h_' + '2'.repeat(16), username: 'atwo', sponsor: lc(A3) });
people.set(lc(A1), { id: 'h_' + '1'.repeat(16), username: 'aone', sponsor: lc(A2) }); people.set(lc(B), { id: 'h_' + 'b'.repeat(16), username: 'buyerb', sponsor: lc(A1) });
const art = n => JSON.parse(fs.readFileSync(path.join(ART, n + '.sol', n + '.json'), 'utf8'));
let nonce = await provider.getTransactionCount(deployer.address);
const fa = art('MockV3Aggregator'); const feed = await new ethers.ContractFactory(fa.abi, fa.bytecode.object, deployer).deploy(25000000n, { nonce: nonce++ }); await feed.waitForDeployment();
const sa = art('VABShop'); const shop = await new ethers.ContractFactory(sa.abi, sa.bytecode.object, deployer).deploy(company, keeper.address, await feed.getAddress(), { nonce: nonce++ }); await shop.waitForDeployment();
await (await shop.setSku(1, 500, 500, true, { nonce: nonce++ })).wait();
const SHOP = await shop.getAddress(); console.log('anvil', RPC, 'VABShop', SHOP);
const env = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', LINK_PROBE: '0', NETWORK_LOOKUP_URL: '', NETWORK_SITES_HUB: '0',
CHAIN_ID: '31337', CONTRACT_ADDRESS: SHOP, CHAIN_RPC: RPC, KEEPER_KEY: K[1], SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '300', EXPLORER: 'https://explorer.invalid', COMPANY_WALLET: company,
HUB_URL: 'http://127.0.0.1:' + (PORT + 1), HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_ENABLED: '0', HUB_CACHE_MS: '200',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + (PORT + 2) });
const log = fs.openSync(path.join(OUT, 'chain-server.log'), 'w');
procs.push(spawn(process.execPath, ['server.js'], { cwd: APP, env, stdio: ['ignore', log, log] }));
for (let i = 0; i < 80; i++) { try { if ((await fetch(BASE + '/health')).ok) break; } catch (e) {} await sleep(150); }
// a member session through the app: wallet sign-in, post an ad
async function member(w, n) {
const jar = {}; const call = async (p, body) => { const r = await fetch(BASE + p, { method: body === undefined ? 'GET' : 'POST', headers: { 'Content-Type': 'application/json', 'User-Agent': 'Mozilla/5.0 ChainTest', Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, body: body === undefined ? undefined : JSON.stringify(body) });
for (const c of r.headers.getSetCookie()) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); } return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); };
const ch = await call('/api/auth/challenge', { address: w.address }); await call('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
const a = await call('/api/my/ad', { headline: 'Chain ad ' + n, line1: 'A real text ad for ' + n, line2: '', link: 'https://chain-' + n + '.example-shop.com/' });
ok(a.ok, n + ' signs in and posts a text ad', a); return call;
}
const bal = a => provider.getBalance(a);
// one Boost through the app: order -> the member's wallet sends it -> the watcher records it
async function boost(w, call, qty) {
const od = await call('/api/my/order', { qty });
const tx = await w.sendTransaction({ to: od.to, data: od.data, value: BigInt(od.value) }); const rc = await tx.wait();
await call('/api/my/paid', {});
for (let i = 0; i < 60; i++) { const l = await call('/api/ledger'); const it = (l.items || []).find(x => x.tx === tx.hash.toLowerCase() && x.pays.every(p => p.to)); if (it) return { od, rc, it, tx }; await sleep(200); }
return { od, rc, it: null, tx };
}
const price = 500n * 10n ** 24n / 25000000n; // $5 at $0.25 = 20 POL
const share = q => q * 1000n / 10000n;
console.log('1. A3 boosts (top of the line): 100% company');
const c3 = await member(A3, 'athree'); let c0 = await bal(company);
let r = await boost(A3, c3, 1);
ok(r.rc.status === 1 && r.od.why === 'no-line' && r.od.line === 0, 'A3 has no line: no voucher, the Boost still goes through', r.od);
ok((await bal(company)) - c0 === price, 'company got the whole 20 POL (nobody to pay)', ((await bal(company)) - c0).toString());
ok(r.it && r.it.pays.length === 1 && r.it.pays[0].level === 0 && r.it.pays[0].wei === price.toString(), 'ledger: one company payment from the receipt', r.it);
console.log('2. A1 boosts: line [A2, A3], A2 passed over');
const c1 = await member(A1, 'aone'); c0 = await bal(company); const a3b = await bal(A3.address), a2b = await bal(A2.address);
r = await boost(A1, c1, 1);
ok(r.od.line === 2 && (await shop.sponsorOf(A1.address)) === A2.address && (await shop.sponsorOf(A2.address)) === A3.address, 'the voucher bound A1 -> A2 -> A3 on chain', r.od);
ok((await bal(A3.address)) - a3b === share(price) && (await bal(A2.address)) === a2b && (await bal(company)) - c0 === price - share(price), 'A3 got 10% (level 1, place 2), A2 nothing, company 90% (exact to the wei)');
ok(r.it.passedOver.length === 1 && r.it.passedOver[0].who === lc(A2) && r.it.passedOver[0].depth === 1 && r.it.pays.find(p => p.level === 1).depth === 2, 'ledger: A2 passed over at place 1, A3 paid at place 2', r.it);
console.log('3. B boosts 2 with the 1% overpay: binds B -> A1 only');
const cb = await member(B, 'buyerb'); c0 = await bal(company); const a1b = await bal(A1.address), a3b2 = await bal(A3.address), bb = await bal(B.address);
r = await boost(B, cb, 2);
const q2 = price * 2n; const gas = r.rc.gasUsed * r.rc.gasPrice;
ok(r.od.line === 3 && (await shop.sponsorOf(B.address)) === A1.address && (await shop.sponsorOf(A1.address)) === A2.address, 'B\'s voucher carried [A1, A2, A3]; only B -> A1 was new, A1\'s link unchanged');
ok((await bal(A1.address)) - a1b === share(q2) && (await bal(A3.address)) - a3b2 === share(q2) && (await bal(company)) - c0 === q2 - 2n * share(q2), 'A1 level 1 (4 POL), A3 level 2 (4 POL), company 80% (32 POL), exact');
ok(bb - (await bal(B.address)) === q2 + gas && BigInt(r.od.value) > q2, 'B sent price + 1% and spent exactly price + gas: the overpay came back in the same transaction');
ok(r.it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name]).join('|') === '1,1,aone|2,3,athree', 'ledger: levels with places and names', r.it.pays);
ok(await provider.getBalance(SHOP) === 0n && (await shop.totalOwed()) === 0n, 'the contract holds nothing');
const my = await cb('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 1000 && my.boosts[0].qty === 2, 'B\'s My page: 2 Boosts = 1,000 guaranteed views', my.boosts);
const myA1 = await c1('/api/my'); ok(myA1.earned.wei === share(q2).toString(), 'A1\'s My page: the level share paid to them', myA1.earned);
console.log('4. trust pack');
for (let i = 0; i < 30 && TG.length < 3; i++) await sleep(200);
await sleep(1500);
ok(TG.length === 3 && TG.every(t => t.method === 'sendPhoto' && t.body.message_thread_id === 632242), 'Telegram: exactly one photo card per Boost (3), payments topic, none repeated', TG.map(t => t.method));
const capB = TG[2].body.caption;
ok(/@buyerb boosted "Chain ad buyerb": 2 Boosts \(1,000 guaranteed views\) · \$10\.00 \(40\.0000 POL\)/.test(capB) && /Level 1 10%: 4\.0000 POL → @aone/.test(capB) && /Level 2 10%: 4\.0000 POL → @athree \(place 3 in the line\)/.test(capB) && /ViralAdBlitz: 32\.0000 POL/.test(capB), 'B\'s card: buyer, ad, each level with POL and place, company', capB);
ok(/1 person in the line had not boosted yet and was passed over/.test(TG[1].body.caption) && /Nobody in this line has boosted yet/.test(TG[0].body.caption), 'cards say who was passed over / that nobody qualified');
const ct = await (await fetch(BASE + '/api/contract')).json();
ok(ct.live && ct.owner === lc(deployer) && ct.company === company.toLowerCase() && ct.keeper === lc(keeper) && ct.orderCount === 3 && ct.balanceWei === '0', '/api/contract reads the live contract', ct);
console.log('\nPOL/USD $0.25: Boost $5 = ' + ethers.formatEther(price) + ' POL, one level share = ' + ethers.formatEther(share(price)) + ' POL');
console.log(pass + ' passed, ' + fail + ' failed');
fs.writeFileSync(path.join(OUT, 'chain.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('chain test crashed:', e.stack || e.message); process.exit(1); });
+432
View File
@@ -0,0 +1,432 @@
// ViralAdBlitz local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out)
// against local stand-ins, then checks: copy rules, pages, the promo kit, sign-in (wallet + network), the one free text ad, member
// pages built from the hub line (first 5 with an ad, by place), verified visits / views / clicks, the weekly board, Boost orders
// (line voucher signed by the keeper, already-bound line, hub down), Boost recording from the chain (ledger split, passed over,
// Telegram card once, hub report), Boost delivery (views counted, starred while active, finished), Network Ad Space finishing,
// old-link redirects, admin, a restart, and Playwright renders on desktop + phone.
// Nothing leaves this machine: hub, InstantAdPay lookup, chain RPC, Telegram and NAS are local stand-ins. No real wallet, no money.
// node qa/smoke.mjs (Playwright renders too, if installed at PLAYWRIGHT)
// SKIP_UI=1 node qa/smoke.mjs (HTTP checks only)
import { spawn } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import http from 'node:http';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const { ethers } = require('ethers');
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true });
const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true });
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const PORT = Number(process.env.SMOKE_APP_PORT || 3317), BASE = 'http://127.0.0.1:' + PORT;
const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'), HUB_SECRET = 'h'.repeat(40);
const KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1
const KEEPER = new ethers.Wallet(KEEPER_PK).address;
const SHOP = '0x00000000000000000000000000000000000Ab0B5';
const sleep = ms => new Promise(r => setTimeout(r, ms));
let pass = 0, fail = 0; let srv = null;
const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 500) : '')); } };
const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; try { await fn(q, r, b); } catch (e) { r.statusCode = 500; r.end(String(e.message)); } }).listen(port, '127.0.0.1').unref();
// ---- stand-in network hub: people = wallet|id -> { id, username, wallet|null, sponsorId, blocked }. Signed as viraladblitz. ----
const HUB = { people: new Map(), down: false, badSig: 0, resolves: 0, got: [] };
function person(username, wallet, sponsorId) { const id = 'h_' + crypto.createHash('sha1').update(username).digest('hex').slice(0, 16); HUB.people.set(id, { id, username, wallet: wallet ? wallet.toLowerCase() : null, sponsorId: sponsorId || null }); return id; }
const hubView = p => { if (!p) return null; const sp = p.sponsorId && HUB.people.get(p.sponsorId); return { id: p.id, username: p.username, wallet: p.wallet, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null }; };
const HUB_PORT = PORT + 1;
listen(HUB_PORT, async (q, r, b) => {
r.setHeader('Content-Type', 'application/json');
if (HUB.down) { r.statusCode = 503; return r.end('{"error":"down"}'); }
const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex');
if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'viraladblitz') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); }
const j = JSON.parse(b || '{}');
if (q.url === '/v1/resolve') {
HUB.resolves++; const all = [...HUB.people.values()]; let p = null;
if (j.id) p = HUB.people.get(j.id); else if (j.wallet) p = all.find(x => x.wallet === String(j.wallet).toLowerCase());
else if (j.ref) { const ref = String(j.ref).toLowerCase(); p = all.find(x => x.wallet === ref || x.username.toLowerCase() === ref); }
else if (j.email) p = all.find(x => x.email === j.email);
return r.end(JSON.stringify({ person: hubView(p) }));
}
HUB.got.push({ route: q.url, body: j }); r.end('{"ok":true}');
});
// ---- stand-in InstantAdPay member lookup (only used while the hub is down) ----
const IAP_KNOWS = new Set(); const LOOKUP_PORT = PORT + 2;
listen(LOOKUP_PORT, async (q, r) => { const a = (new URL(q.url, 'http://x').searchParams.get('a') || '').toLowerCase(); r.setHeader('Content-Type', 'application/json'); r.end(JSON.stringify(IAP_KNOWS.has(a) ? { address: a, username: 'iap' + a.slice(2, 8) } : {})); });
// ---- stand-in Polygon JSON-RPC: quoteWei at POL $0.25 (1 cent = 0.04 POL), sponsorOf from BOUND, contract facts, logs + receipts ----
const IFACE = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 companyPaid)',
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
'event SponsorBound(address indexed member, address indexed sponsor)',
'function quoteWei(uint256 sku, uint256 qty) view returns (uint256)', 'function sponsorOf(address) view returns (address)',
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256)',
'function owner() view returns (address)', 'function company() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)']);
const CHAIN = { head: 1, logs: [], receipts: {}, bound: new Map(), replayAll: false, down: false, times: {} };
const TANGEM = '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70';
const CHAIN_PORT = PORT + 3;
listen(CHAIN_PORT, async (q, r, b) => {
const j = JSON.parse(b || '{}'); let result = null; r.setHeader('Content-Type', 'application/json');
if (CHAIN.down) return r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, error: { code: -1, message: 'down' } }));
if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16);
if (j.method === 'eth_call') {
const d = j.params[0].data; const tx = IFACE.parseTransaction({ data: d });
const enc = (fn, v) => IFACE.encodeFunctionResult(fn, v);
if (tx.name === 'quoteWei') result = enc('quoteWei', [500n * tx.args[1] * 4n * 10n ** 16n]);
if (tx.name === 'sponsorOf') result = enc('sponsorOf', [CHAIN.bound.get(tx.args[0].toLowerCase()) || ethers.ZeroAddress]);
if (tx.name === 'owner' || tx.name === 'company') result = enc(tx.name, [TANGEM]);
if (tx.name === 'keeper') result = enc('keeper', [KEEPER]);
if (tx.name === 'paused') result = enc('paused', [false]);
if (tx.name === 'totalOwed') result = enc('totalOwed', [0n]);
if (tx.name === 'orderCount') result = enc('orderCount', [BigInt(CHAIN.logs.length)]);
}
if (j.method === 'eth_getBalance') result = '0x0';
if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null;
if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16);
if (j.method === 'eth_getBlockByNumber') { const n = j.params[0] === 'latest' ? CHAIN.head : parseInt(j.params[0], 16); result = { number: '0x' + n.toString(16), timestamp: '0x' + (CHAIN.times[n] || Math.floor(Date.now() / 1000)).toString(16), baseFeePerGas: '0x' + (30n * 10n ** 9n).toString(16) }; }
if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); }
r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result }));
});
// a Boost on the stand-in chain: Purchase log + a receipt with SponsorBound / PassedOver / Paid logs, like VABShop emits
let orderId = 0;
function chainBoost(o) {
const id = ++orderId; const block = ++CHAIN.head; const tx = '0x' + crypto.randomBytes(32).toString('hex');
if (o.blockAt) CHAIN.times[block] = o.blockAt;
const weiPaid = 500n * BigInt(o.qty || 1) * 4n * 10n ** 16n; const share = weiPaid / 10n;
const mk = (name, args, li) => { const e = IFACE.encodeEventLog(name, args); return { address: SHOP.toLowerCase(), topics: e.topics, data: e.data, blockNumber: '0x' + block.toString(16), transactionHash: tx, logIndex: '0x' + li.toString(16), removed: false }; };
const logs = []; let li = 0;
for (const [m, s] of o.bound || []) { logs.push(mk('SponsorBound', [m, s], li++)); CHAIN.bound.set(m.toLowerCase(), s.toLowerCase()); }
for (const [w, d] of o.over || []) logs.push(mk('PassedOver', [id, w, d], li++));
(o.pays || []).forEach(([w, d], i) => logs.push(mk('Paid', [id, w, share, i + 1, d], li++)));
const company = weiPaid - share * BigInt((o.pays || []).length);
logs.push(mk('Paid', [id, TANGEM, company, 0, 0], li++));
const purchase = mk('Purchase', [id, o.buyer, 1, o.qty || 1, o.ref || 0, o.views || 500, 500 * (o.qty || 1), weiPaid, (o.pays || []).length, company], li++);
logs.push(purchase); CHAIN.logs.push(purchase);
CHAIN.receipts[tx] = { status: '0x1', blockNumber: '0x' + block.toString(16), to: SHOP.toLowerCase(), from: o.buyer.toLowerCase(), logs };
return { tx, id, weiPaid, share, company };
}
// ---- stand-in Telegram Bot API ----
const TG = []; const TG_PORT = PORT + 4;
listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); });
const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '',
VISIT_SECONDS: '2', VISITS_PER_IP_DAY: '2', LINK_PROBE: '0', NETWORK_LOOKUP_URL: 'http://127.0.0.1:' + LOOKUP_PORT + '/api/network/member',
NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0',
CONTRACT_ADDRESS: SHOP, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid',
HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'viraladblitz', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200',
TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT });
process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} });
let nextIp = 10;
function client(opts = {}) {
const jar = {}; const ip = opts.ip || ('203.0.113.' + (nextIp++)); const ua = opts.ua || ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeBrowser/' + ip);
return { jar, ip, ua,
async req(p, o = {}) {
const headers = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': ip, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, o.headers || {});
const r = await fetch(BASE + p, { method: o.method || 'GET', headers, body: o.body, redirect: 'manual' });
for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); }
return r;
},
async json(p, body, extra) { const r = await this.req(p, body === undefined ? { headers: extra } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extra), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); } };
}
async function boot() {
const log = fs.openSync(path.join(OUT, 'server.log'), 'a');
srv = spawn(process.execPath, ['server.js'], { cwd: APP, env: ENV, stdio: ['ignore', log, log] });
for (let i = 0; i < 80; i++) { try { const r = await fetch(BASE + '/health'); if (r.ok) return; } catch (e) {} await sleep(150); }
throw new Error('server did not start; see qa/out/server.log');
}
async function stop() { const p = srv; srv = null; if (!p) return; const done = new Promise(r => p.once('exit', r)); p.kill('SIGINT'); await Promise.race([done, sleep(3000)]); }
// a member signed in by wallet signature. hub: { username, sponsorId } puts them in the hub; iap: InstantAdPay knows the wallet
async function walletMember(o = {}) {
const w = o.wallet || ethers.Wallet.createRandom(); const c = client(); const a = w.address.toLowerCase();
if (o.hub) c.hubId = person(o.hub.username, a, o.hub.sponsorId);
if (o.iap) IAP_KNOWS.add(a);
const ch = await c.json('/api/auth/challenge', { address: w.address });
const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) });
c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['vab.sid'];
return c;
}
const adBody = (n, extra) => Object.assign({ headline: 'Headline number ' + n, line1: 'First line for ad ' + n + ', plain text', line2: 'Second line ' + n, link: 'https://member-' + n + '.example-shop.com/offer?id=' + n }, extra || {});
// one page load + its verified visit
async function view(c, page, u, wait) {
const d = await c.json('/api/wire?page=' + page + (u ? '&u=' + encodeURIComponent(u) : ''));
if (!d.ticket) return { d, r: { verified: false, why: 'no-ticket' } };
await sleep(wait != null ? wait : 2100);
return { d, r: await c.json('/api/visit/seen', { ticket: d.ticket, visibleMs: wait != null ? wait : 2100 }) };
}
async function main() {
if (await fetch(BASE).then(() => true, () => false)) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT');
console.log('data dir', DATA);
console.log('1. copy rules');
const pub = path.join(APP, 'public');
const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f)));
const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]).concat(['promokit.js', 'proof.js', 'server.js', 'tools/pages.mjs', 'tools/art.mjs'].map(f => [f, fs.readFileSync(path.join(APP, f), 'utf8')]));
ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page, script or copy source', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0]));
const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n');
ok(!/metamask/i.test(html), 'pages never name MetaMask');
ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy says "SafePal or any other crypto wallet"');
ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money|get rich|up to \$?\d+ (a|per)|maximum (you|earn)/i.test(html), 'no income promises and no earnings caps in page copy');
ok(/never a subscription/i.test(html) && /A Boost buys advertising, not income\. Nothing is promised\./.test(html), 'Boost copy: one-time, never a subscription; "advertising, not income. Nothing is promised."');
ok(/TrustClickz/.test(html) && /615 Green Valley Drive, Moody, AL 35004/.test(html), 'legal pages name TrustClickz, 615 Green Valley Drive, Moody, AL 35004');
console.log('2. boot (prototype mode, temp data dir)');
await boot();
const cfg = await (await fetch(BASE + '/api/config')).json();
ok(cfg.boost.usd === 5 && cfg.boost.views === 500 && cfg.boost.sku === 1 && cfg.split.levels === 5 && cfg.split.levelPct === 10 && cfg.split.companyPct === 50, 'config: Boost $5 = 500 views, 5 levels x 10% + 50% company', cfg.boost);
ok(cfg.shop.live === true && cfg.shop.contract.toLowerCase() === SHOP.toLowerCase(), 'shop live against the stand-in contract');
ok(fs.readFileSync(path.join(OUT, 'server.log'), 'utf8').includes('files (prototype mode)'), 'server says prototype mode (no DOCSTORE_URL)');
console.log('3. pages');
const anon = client();
for (const p of ['/', '/my', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy', '/admin', '/robots.txt', '/sitemap.xml', '/art/mark.svg', '/art/og-share.png', '/assets/vab.css', '/assets/common.js']) { const r = await anon.req(p); ok(r.status === 200, 'GET ' + p + ' 200', r.status); }
let r = await anon.req('/'); const home = await r.text();
ok(/Your ad runs on your whole team's pages\. Five levels deep\./.test(home) && /id="boardCards"/.test(home) && /og:image" content="https:\/\/viraladblitz\.com\/art\/og-share\.png/.test(home), 'front page: headline, board, Open Graph');
ok(!r.headers.get('x-frame-options'), 'front page stays frameable (traffic exchanges)');
r = await anon.req('/my'); ok(r.headers.get('x-frame-options') === 'DENY', '/my is never framed');
ok(/script-src[^;]*https:\/\/linkspin\.app/.test(r.headers.get('content-security-policy') || ''), 'CSP admits linkspin.app (network zones)');
r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the wire/.test(await r.text()), 'a username the hub does not know: 404');
r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in');
console.log('4. promo kit');
{ const kr = await anon.req('/api/promo-kit?u=smokeleader'); const k = await kr.json();
ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'GET /api/promo-kit 200 with CORS open');
ok(k.links[0].url === 'https://viraladblitz.com/smokeleader' && k.links.slice(1).every(l => l.url.endsWith('?ref=smokeleader')), 'kit links: the member page + ?ref=', k.links.map(l => l.url));
ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nwvab\?src=viraladblitz&s1=smokeleader/.test(l.tracked)), 'every link has a LinkSpin-tracked twin (nwvab, source viraladblitz)', k.links.map(l => l.tracked));
const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]);
ok(!/[\u2014\u2013]/.test(words) && !/passive income|guaranteed (income|returns|profit)|make money|metamask/i.test(words) && /\$5 one-time Boost buys 500 guaranteed network views/.test(words) && /SafePal or any other crypto wallet/.test(words), 'kit copy: no dashes, no income promises, Boost facts from config, SafePal wording');
ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'kit: 21 creatives in 3 angles', k.creatives.length);
const bad = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://viraladblitz.com', ''))); ok(!bad.length, 'kit: creative paths are ad-blocker neutral', bad.map(c => c.url));
let dimOk = true; const dimBad = [];
for (const c of k.creatives) { const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer()); const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20);
if (rr.status !== 200 || w !== c.w || h !== c.h || !c.html.includes('href="https://viraladblitz.com/smokeleader"')) { dimOk = false; dimBad.push(c.key + ' ' + w + 'x' + h); } }
ok(dimOk, 'kit: every creative is a PNG at its exact size and its HTML links to the member page', dimBad);
const pr = await anon.req('/art/proof/vab-proof-amber.png'); ok(pr.status === 200 && pr.headers.get('content-type') === 'image/png', 'Telegram proof card image served'); }
console.log('5. sign-in and network membership');
// the hub line used through the test (nearest first above OWNER): L1 (ad) <- L2 (NO ad) <- L3 (ad, NO wallet in hub) <- L4 (ad) <- L5 (ad) <- L6 (ad) <- L7 (ad) <- TOP
const W = n => ethers.Wallet.createRandom();
const wTop = W(), w7 = W(), w6 = W(), w5 = W(), w4 = W(), w2 = W(), w1 = W(), wOwner = W(), wDown = W();
const idTop = person('topdog', wTop.address), id7 = person('seven', w7.address, idTop), id6 = person('six', w6.address, id7), id5 = person('five', w5.address, id6), id4 = person('four', w4.address, id5);
const id3 = person('three', null, id4); const id2 = person('two', w2.address, id3), id1 = person('one', w1.address, id2);
const idOwner = person('owner', wOwner.address, id1);
const STR = await walletMember({ iap: false }); let my = await STR.json('/api/my');
ok(STR.ok && my.netVerified === false, 'a wallet the network does not know: signed in, not a network member', my);
let pa = await STR.json('/api/my/ad', adBody(0)); ok(pa._status === 403 && /network members/.test(pa.error), 'a non-member cannot post a text ad', pa);
const M1 = await walletMember({ wallet: w1 }); my = await M1.json('/api/my');
ok(my.netVerified === true && my.username === 'one', 'a wallet the hub knows: network member, username from the hub', my);
const bad = client(); const x0 = ethers.Wallet.createRandom(), x1 = ethers.Wallet.createRandom();
const ch0 = await bad.json('/api/auth/challenge', { address: x0.address }); const v0 = await bad.json('/api/auth/verify', { address: x0.address, signature: await x1.signMessage(ch0.message) });
ok(v0._status === 400 && !bad.jar['vab.sid'], 'a signature from another wallet is refused');
// network sign-in from InstantAdPay: /sso/start -> IAP mints a token -> /sso/in
const L = client(); r = await L.req('/sso/start?mode=go&via=iap&to=%2Fmy'); const loc = r.headers.get('location') || '';
ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=viraladblitz'), 'network sign-in hops to InstantAdPay with r=viraladblitz', loc);
const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET;
const tok = nsso.mint({ iss: 'iap', aud: 'viraladblitz', email: 'owner@example.org', wallet: wOwner.address.toLowerCase(), name: 'owner', st: new URL(loc).searchParams.get('st'), to: '/my' });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok));
ok(r.status === 302 && r.headers.get('location') === '/my' && !!L.jar['vab.sid'], 'the network token signs the member in', { s: r.status, l: r.headers.get('location') });
r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); ok(!/vab\.sid=[0-9a-f]{64}/.test(String(r.headers.get('set-cookie') || '')), 'a network token works only once');
const OWN = L; OWN.address = wOwner.address.toLowerCase();
my = await OWN.json('/api/my'); ok(my.username === 'owner' && my.netVerified && my.page === 'https://viraladblitz.com/owner', 'network member keeps the network username; page = viraladblitz.com/<username>', my);
ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as viraladblitz with HUB_SECRET', HUB.badSig);
HUB.down = true; const FB = await walletMember({ iap: true }); my = await FB.json('/api/my');
ok(my.netVerified === true, 'hub unreachable: InstantAdPay verifies the wallet (fallback)', my); HUB.down = false; await sleep(400);
console.log('6. the free text ad');
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'ab' })); ok(pa._status === 400 && /headline/.test(pa.error), 'a 2-character headline is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'x'.repeat(61) })); ok(pa._status === 400, 'a 61-character headline is refused');
pa = await M1.json('/api/my/ad', adBody(1, { line1: '' })); ok(pa._status === 400 && /first line/.test(pa.error), 'the first line is required', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'http://plain.com/' })); ok(pa._status === 400 && /https/.test(pa.error), 'an http link is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://bit.ly/x' })); ok(pa._status === 400 && /shortener/.test(pa.error), 'a link shortener is refused', pa);
pa = await M1.json('/api/my/ad', adBody(1, { link: 'https://10.0.0.1/' })); ok(pa._status === 400, 'an IP-address link is refused');
pa = await M1.json('/api/my/ad', adBody(1, { headline: 'Line <b>one</b> \u2014 deal', link: 'https://member-1.example-shop.com/o?c={clickid}&p={placement}' }));
ok(pa.ok && pa.created === true, 'a member posts their free text ad', pa);
const ad1 = pa.ad.id;
my = await M1.json('/api/my'); ok(my.ad.headline === 'Line b one /b - deal', 'markup and long dashes are stripped from ad text', my.ad.headline);
pa = await M1.json('/api/my/ad', adBody(1)); ok(pa.ok && pa.created === false && pa.ad.id === ad1, 'posting again edits the same ad (one ad per member)', pa);
// the rest of the line posts ads (L2 never does; L3 has no wallet in the hub but signs in with one the hub does not tie to them)
const M = { 1: M1 };
for (const [k, w] of [[4, w4], [5, w5], [6, w6], [7, w7], ['top', wTop]]) { M[k] = await walletMember({ wallet: w }); const q = await M[k].json('/api/my/ad', adBody(k, k === 5 ? { link: 'https://member-5.example-shop.com/o?c={clickid}&p={placement}' } : {})); ok(q.ok, 'line member ' + k + ' posts an ad'); }
const OWNAD = (await OWN.json('/api/my/ad', adBody('own'))).ad.id;
const DOWN = await walletMember({ wallet: wDown, hub: { username: 'downline', sponsorId: idOwner } }); await DOWN.json('/api/my/ad', adBody('down'));
console.log('7. member page from the hub line');
r = await anon.req('/owner'); ok(r.status === 200 && /member\.js/.test(await r.text()) && /vab\.ref=owner/.test(String(r.headers.get('set-cookie'))), 'GET /owner serves the member page and remembers the referrer');
let mp = await anon.json('/api/wire?page=member&u=owner');
ok(mp.page && mp.page.ad && mp.page.ad.id === OWNAD && mp.page.username === 'owner', 'member page: the owner\'s own ad', mp.page && mp.page.ad);
const lv = (mp.page.line || []).map(x => [x.level, x.owner]);
ok(JSON.stringify(lv) === JSON.stringify([[1, '@one'], [4, '@four'], [5, '@five'], [6, '@six'], [7, '@seven']]), 'five upline ads, by place in the line: L2 (no ad) and L3 (no wallet) skipped, the 6th with an ad (topdog) not shown', lv);
ok(mp.page.joinUrl === 'https://instantadpay.com/?ref=owner', 'join link: InstantAdPay under the page owner', mp.page.joinUrl);
mp = await anon.json('/api/wire?page=member&u=nobody-here'); ok(mp._status === 404, 'unknown member: 404 from the page API');
console.log('8. verified visits, views and clicks');
const botC = client({ ua: 'Mozilla/5.0 (compatible; Googlebot/2.1)' }); let wd = await botC.json('/api/wire?page=front'); ok(!wd.ticket, 'bots get no visit ticket');
const early = client(); let vv = await view(early, 'front', null, 300); ok(!vv.r.verified && vv.r.why === 'early', 'a visit sent before the timer is not verified', vv.r);
const V1 = client(); vv = await view(V1, 'member', 'owner');
ok(vv.r.verified && vv.r.views === 8 && /^[0-9a-f]{24}$/.test(vv.r.vt), 'a verified visit on a member page: every ad shown gets a view (own + 5 line + the rest on the ticker: 8 ads), verified token issued', vv.r);
const v2 = await view(V1, 'member', 'owner'); ok(v2.r.verified && v2.r.views === 0, 'the same visitor again: no second view of the same ads in 24 h', v2.r);
my = await OWN.json('/api/my'); ok(my.ad.views === 1, 'the owner\'s ad has 1 verified view', my.ad.views);
const ownView = await view(OWN, 'member', 'owner'); my = await OWN.json('/api/my'); ok(ownView.r.verified && my.ad.views === 1, 'the owner viewing their own page never counts for their own ad', my.ad.views);
const shared = '198.51.100.7'; const sv = [0, 1, 2].map(i => client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/' + i }));
const svr = []; for (const c of sv) svr.push((await view(c, 'front')).r);
ok(svr.filter(x => x.verified).length === 2 && svr[2].why === 'ip', 'only 2 browsers per connection are verified per day', svr);
// clicks
r = await anon.req('/go/' + ad1 + '?p=ticker'); const gl = new URL(r.headers.get('location'));
ok(r.status === 302 && gl.hostname === 'member-1.example-shop.com', '/go/<ad> sends to the ad link', r.headers.get('location'));
{ const a5 = (await M[5].json('/api/my')).ad.id; const r5 = await anon.req('/go/' + a5 + '?p=ticker'); const g5 = new URL(r5.headers.get('location'));
ok(/^[0-9a-f]{16}$/.test(g5.searchParams.get('c')) && g5.searchParams.get('p') === 'ticker', 'tracking macros: {clickid} and {placement} filled on every click', r5.headers.get('location')); }
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); ok(r.status === 302, 'a verified visitor clicks');
r = await V1.req('/go/' + ad1 + '?p=level1&v=' + vv.r.vt); r = await V1.req('/go/' + ad1 + '?p=level1&v=' + 'f'.repeat(24));
const bc = client({ ua: 'curl/8' }); await bc.req('/go/' + ad1);
my = await M1.json('/api/my'); ok(my.ad.vclicks === 1 && my.ad.clicks >= 4, 'clicks: 1 verified (repeat, bad token and unverified ones are raw only, bots not counted)', { v: my.ad.vclicks, c: my.ad.clicks });
const Vb = client(); const vb = await view(Vb, 'front'); await Vb.req('/go/' + ad1 + '?v=' + vb.r.vt); const Vc = client(); const vcv = await view(Vc, 'front'); const ad4 = (await M[4].json('/api/my')).ad.id; await Vc.req('/go/' + ad4 + '?v=' + vcv.r.vt);
await OWN.req('/go/' + OWNAD + '?v=' + ownView.r.vt);
let fr = await anon.json('/api/wire?page=front');
ok(fr.board.items[0].id === ad1 && fr.board.items[0].clicks === 2 && fr.board.items[0].rank === 1 && fr.board.items.length === 2, 'Top ads this week: ranked by verified clicks (the owner\'s own click never counts)', fr.board.items.map(x => [x.id, x.clicks]));
ok(fr.today.vclicks === 3 && fr.today.ads >= 8, 'today on the wire: verified clicks + ads live', fr.today);
console.log('9. Boost orders (line voucher)');
let q = await OWN.json('/api/quote?qty=1'); ok(q.usd === 5 && q.views === 500 && BigInt(q.wei) === 20n * 10n ** 18n, 'quote: $5 at $0.25 = 20 POL (from the contract)', q);
q = await OWN.json('/api/quote?qty=11'); ok(q._status === 400, '11 Boosts refused (1 to 10)');
const NOAD = await walletMember({ wallet: w2 }); let od = await NOAD.json('/api/my/order', { qty: 1 }); ok(od._status === 400 && /text ad first/.test(od.error), 'no ad: no Boost', od);
od = await OWN.json('/api/my/order', { qty: 2 });
const call = IFACE.parseTransaction({ data: od.data, value: od.value });
const line = call.args[3].map(a => a.toLowerCase());
ok(od._status === 200 && call.name === 'buy' && Number(call.args[0]) === 1 && Number(call.args[1]) === 2 && Number(call.args[2]) === OWNAD, 'order = buy(sku 1, qty 2, ref = the owner\'s ad id)', od);
ok(JSON.stringify(line) === JSON.stringify([w1, w2, w4, w5, w6, w7, wTop].map(w => w.address.toLowerCase())), 'the voucher line = the hub line\'s wallets nearest first (L3 without a wallet left out)', line);
const rec = ethers.verifyTypedData({ name: 'VABShop', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP.toLowerCase()) }, { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] },
{ buyer: ethers.getAddress(OWN.address), line: call.args[3], deadline: call.args[4] }, call.args[5]);
ok(rec === KEEPER, 'the voucher is signed by the keeper (EIP-712 VABShop v1)', rec);
ok(BigInt(od.value) === 40n * 10n ** 18n * 101n / 100n && Number(call.args[4]) > Date.now() / 1000 + 1700, 'value = quote + 1% (refunded by the contract), deadline 30 minutes', od.value);
CHAIN.bound.set(M1.address, w2.address.toLowerCase());
od = await M1.json('/api/my/order', { qty: 1 }); const c2 = IFACE.parseTransaction({ data: od.data, value: od.value });
ok(od.why === 'bound' && c2.args[3].length === 0 && c2.args[5] === '0x', 'a member whose line is already bound on chain: no voucher (the chain\'s binding wins)', od.why);
CHAIN.bound.delete(M1.address); HUB.down = true; await sleep(350);
od = await M[4].json('/api/my/order', { qty: 1 }); ok(od._status === 503 && /sponsor line/.test(od.error), 'hub unreachable: the Boost waits (the line is never signed partial)', od);
HUB.down = false; await sleep(350);
CHAIN.down = true; od = await OWN.json('/api/my/order', { qty: 1 }); ok(od._status === 503, 'chain unreachable: no order'); CHAIN.down = false;
console.log('10. a Boost recorded from the chain');
// the owner's 2 Boosts: line bound; one, four, five, six, seven paid; two passed over (place 2)
const b1 = chainBoost({ buyer: wOwner.address, qty: 2, ref: OWNAD, views: 6, bound: [[wOwner.address, w1.address], [w1.address, w2.address], [w2.address, w4.address]],
over: [[w2.address, 2]], pays: [[w1.address, 1], [w4.address, 3], [w5.address, 4], [w6.address, 5], [w7.address, 6]] });
let led; for (let i = 0; i < 40; i++) { led = await anon.json('/api/ledger'); if (led.items && led.items.length && led.items[0].pays.length > 1 && led.items[0].pays[0].to) break; await sleep(150); }
const it = led.items[0];
ok(led.items.length === 1 && it.tx === b1.tx && it.qty === 2 && it.buyerName === 'owner' && it.ad && it.ad.id === OWNAD, 'the ledger shows the Boost (buyer, ad)', it);
ok(it.pays.filter(p => p.level > 0).map(p => [p.level, p.depth, p.name, p.wei]).every((x, i) => x[0] === i + 1 && x[3] === b1.share.toString()) && it.pays.find(p => p.level === 0).wei === b1.company.toString(), 'the ledger split from the receipt: 5 levels x 10% with their places, company 50%', it.pays);
ok(it.passedOver.length === 1 && it.passedOver[0].depth === 2 && it.passedOver[0].name === 'two', 'passed over: @two at place 2 (never boosted)', it.passedOver);
for (let i = 0; i < 20 && !TG.length; i++) await sleep(150);
ok(TG.length === 1 && TG[0].method === 'sendPhoto' && TG[0].token === 'botstandin-token' && TG[0].body.message_thread_id === 632242 && /\/art\/proof\/vab-proof-[a-z]+\.png$/.test(TG[0].body.photo), 'Telegram: one photo card in the payments topic', TG.map(t => t.method));
const cap = TG[0].body.caption || '';
ok(/@owner boosted "Headline number own"/.test(cap) && /Level 1 10%: 4\.0000 POL → @one/.test(cap) && /Level 2 10%: 4\.0000 POL → @four \(place 3 in the line\)/.test(cap) && /ViralAdBlitz: 20\.0000 POL/.test(cap), 'card: buyer, ad, every level with POL and place, company', cap);
ok(/1 person in the line had not boosted yet and was passed over/.test(cap) && /This week: 2 Boosts · \d+ ads live · \d+ verified clicks/.test(cap) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(cap) && /viraladblitz\.com\/ledger/.test(cap) && !/[\u2014\u2013]/.test(cap), 'card: passed-over line, week stats, verify + ledger links, no dashes', cap);
my = await OWN.json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].views === 6 && my.boosts[0].delivered === 0 && my.boosts[0].status === 'delivering', 'My page: the Boost with its guaranteed views', my.boosts);
my = await M[4].json('/api/my'); ok(my.earned.items.length === 1 && my.earned.items[0].level === 2 && my.earned.wei === b1.share.toString(), 'My page for @four: the level 2 share paid to them', my.earned);
const rc = await anon.json('/api/recent'); ok(rc.items.some(x => x.kind === 'boost' && x.name === 'owner' && x.levels === 5), 'toasts: the Boost with 5 sponsors paid', rc.items);
for (let i = 0; i < 30 && !HUB.got.length; i++) await sleep(150);
ok(HUB.got.length === 1 && HUB.got[0].route === '/v1/contract-bind' && HUB.got[0].body.contract === 'viraladblitz' && HUB.got[0].body.wallet === OWN.address && HUB.got[0].body.sponsorRef === w1.address.toLowerCase() && HUB.got[0].body.spentCents === 1000, 'hub report: contract-bind for the buyer with their direct sponsor', HUB.got);
CHAIN.replayAll = true; await sleep(800); CHAIN.replayAll = false;
led = await anon.json('/api/ledger'); ok(led.items.length === 1 && TG.length === 1, 'a flaky RPC re-sending old logs: no second record, no second Telegram post');
// an old Boost (block 3 hours ago) is recorded but never posted
const old = chainBoost({ buyer: w4.address, qty: 1, ref: 0, views: 500, blockAt: Math.floor(Date.now() / 1000) - 3 * 3600, pays: [[w5.address, 1]] });
for (let i = 0; i < 30; i++) { led = await anon.json('/api/ledger'); if (led.items.length === 2) break; await sleep(150); } await sleep(500);
ok(led.items.length === 2 && TG.length === 1, 'a Boost older than 2 hours is recorded but never posted to Telegram', TG.length);
my = await M[4].json('/api/my'); ok(my.boosts.length === 1 && my.boosts[0].adId === (await M[4].json('/api/my')).ad.id, 'a Boost with ref 0 attaches to the buyer\'s live ad', my.boosts);
console.log('11. Boost delivery');
fr = await anon.json('/api/wire?page=front');
ok(fr.ticker.some(t => t.id === OWNAD && t.boosted), 'the Boosted ad is starred on the ticker', fr.ticker.map(t => [t.id, t.boosted]));
mp = await anon.json('/api/wire?page=member&u=downline');
const mtop = await anon.json('/api/wire?page=member&u=topdog');
ok(mp.page.line[0] && mp.page.line[0].id === OWNAD && mp.page.line[0].boosted, 'downline page: the owner at level 1, starred', mp.page.line[0]);
{ const onPage = new Set([mp.page.ad.id].concat(mp.page.line.map(x => x.id))); ok(mp.page.boosted.every(x => !onPage.has(x.id)), 'downline page: a Boosted place never repeats an ad already on the page', mp.page.boosted.map(x => x.id)); }
ok(mtop.page.line.length === 0 && mtop.page.boosted.length === 2 && mtop.page.boosted.every(x => x.boosted) && mtop.page.boosted.some(x => x.id === OWNAD), 'top of the line (no upline): the 2 Boosted places show Boosted ads', mtop.page.boosted.map(x => x.id));
let delivered = 0; const views = [];
for (let i = 0; i < 7; i++) { const c = client(); const x = await view(c, 'front'); views.push(x.r.boostViews); }
my = await OWN.json('/api/my'); delivered = my.boosts[0].delivered;
ok(delivered === 6 && my.boosts[0].status === 'delivered' && my.boosts[0].remaining === 0, 'every verified visitor delivers one view; the Boost finishes at its 6 guaranteed views', { delivered, s: my.boosts[0].status, views });
const st = await anon.json('/api/admin/status', undefined, { 'x-admin-token': ADMIN });
ok(st.rows.boostViews >= 6 + 7 && st.boosts.delivered >= 6, 'every counted Boost view is kept as an audit row', st.rows);
fr = await anon.json('/api/wire?page=front'); ok(!fr.ticker.some(t => t.id === OWNAD && t.boosted), 'a delivered Boost is no longer starred');
console.log('12. Network Ad Space finishing (stand-in NAS database)');
{
process.env.DATA_DIR = path.join(DATA, 'nas'); fs.mkdirSync(process.env.DATA_DIR, { recursive: true }); require(path.join(APP, 'config.js')).reset();
const vabnas = require(path.join(APP, 'vabnas.js')); const NAS = { rows: [], pays: [] };
const query = async (sql, args) => {
if (/^INSERT INTO payments/.test(sql)) { NAS.pays.push(args); return { insertId: NAS.pays.length }; }
if (/^INSERT INTO sponsorads/.test(sql)) { NAS.rows.push({ ID: NAS.rows.length + 100, sql, args, assigned: args[4], remaining: args[5] }); return { insertId: NAS.rows.length + 99 }; }
if (/^SELECT assigned, remaining/.test(sql)) { const x = NAS.rows.find(y => y.ID === args[0]); return x ? [{ assigned: x.assigned, remaining: x.remaining }] : []; }
return [];
};
const ad = { id: 9, status: 'live', headline: 'Late Boost ad', line1: 'Line one', line2: 'Line two' };
const boosts = [{ key: 'tx1:0', adId: 9, views: 500, delivered: 120, dueAt: Date.now() - 1000 }, { key: 'tx2:0', adId: 9, views: 500, delivered: 10, dueAt: Date.now() + 86400000 }, { key: 'tx3:0', adId: 9, views: 500, delivered: 500, dueAt: Date.now() - 1000 }];
vabnas.init({ boosts: () => boosts, remaining: b => Math.max(0, b.views - b.delivered - vabnas.boostServed(b.key)), ad: () => ad }, { query });
const t1 = await vabnas.tick();
ok(t1.placed === 1 && NAS.rows.length === 1 && NAS.rows[0].assigned === 380, 'a Boost past 30 days with 380 views owed gets one NAS text ad for exactly 380; one still in its window and one delivered are left alone', { t1, rows: NAS.rows.map(r2 => r2.assigned) });
const a0 = NAS.rows[0].args; ok(a0[1] === 'Late Boost ad' && a0[2] === 'Line one Line two' && a0[3] === 'https://viraladblitz.com/go/9?p=nas' && /,1,0,\?\)$/.test(NAS.rows[0].sql.replace(/\s+/g, '')), 'NAS text ad: headline = subject, lines = body, link through /go/<ad>?p=nas (clicks count here), pid 1 (text)', a0.slice(0, 4));
NAS.rows[0].remaining = 380 - 150; await vabnas.tick();
ok(vabnas.boostServed('tx1:0') === 150 && NAS.rows.length === 1, 'NAS impressions read back (assigned - remaining) count toward the Boost; no second NAS ad', vabnas.boostServed('tx1:0'));
NAS.rows[0].remaining = -40; await vabnas.tick(); ok(vabnas.boostServed('tx1:0') === 380, 'NAS counter drift above assigned is clamped');
}
console.log('13. old site links');
r = await anon.req('/api/admin/oldrefs', { method: 'POST', headers: { 'x-admin-token': ADMIN }, body: JSON.stringify({ oldrefs: { janie23: 'owner', 'bad key!': 'x', frank: '<b>' } }) });
const or = await r.json(); ok(or.ok && or.total === 1 && or.skipped === 2, 'admin loads the old-username map (bad rows skipped)', or);
for (const [from, to] of [['/?janie23', '/owner'], ['/?janie23&fbclid=x', '/owner'], ['/splashpg.php?pid=4&r=janie23', '/owner'], ['/lcp.php?pid=2&r=JANIE23', '/owner'], ['/?nobodyold', '/'], ['/members.php', '/'], ['/splashpg.php?pid=4&r=nobody', '/']]) {
r = await anon.req(from); ok(r.status === 301 && r.headers.get('location') === to, 'old link ' + from + ' -> ' + to, r.headers.get('location')); }
r = await anon.req('/?ref=owner'); ok(r.status === 200, '/?ref=<name> is not an old link');
console.log('14. admin');
r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin needs the token');
const sj = JSON.stringify(st);
ok(st.shop.vouchers && st.shop.keeper === KEEPER && !sj.includes(KEEPER_PK.slice(2)) && !sj.includes(HUB_SECRET) && !sj.includes('standin-token') && !sj.includes(SSO_SECRET), 'admin status: keeper address only, no key or secrets', st.shop);
const lk = await anon.json('/api/admin/member-lookup?q=four', undefined, { 'x-admin-token': ADMIN }); ok(lk.address === w4.address.toLowerCase() && lk.earned.items.length === 1 && lk.paidBy.length === 1, 'member lookup: earnings and who paid them', lk.earned);
const rm = await anon.json('/api/admin/ad', { id: (await M[7].json('/api/my')).ad.id, status: 'removed', note: 'smoke' }, { 'x-admin-token': ADMIN }); ok(rm.ok, 'admin removes an ad');
mp = await anon.json('/api/wire?page=member&u=owner'); ok(!mp.page.line.some(x => x.owner === '@seven') && mp.page.line.some(x => x.owner === '@topdog'), 'a removed ad leaves the member pages; the next one up (place 8) moves in', mp.page.line.map(x => [x.level, x.owner]));
console.log('15. restart');
await stop(); await boot(); await sleep(500);
my = await OWN.json('/api/my'); ok(my.ad && my.ad.id === OWNAD && my.boosts[0].delivered === 6, 'after a restart: ads, Boosts and delivery are kept', my.boosts);
led = await anon.json('/api/ledger'); ok(led.items.length === 2 && TG.length === 1, 'after a restart: no re-record, no repost');
const again = await view(client({ ip: shared, ua: 'Mozilla/5.0 SharedBrowser/9' }), 'front'); ok(!again.r.verified && again.r.why === 'ip', 'after a restart: the per-connection cap still holds (rebuilt from the visit rows)', again.r);
if (!process.env.SKIP_UI && fs.existsSync(PW)) {
console.log('16. Playwright renders (desktop 1280 + phone 390)');
const { chromium } = require(PW); const browser = await chromium.launch();
for (const [label, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) {
const ctx = await browser.newContext({ viewport: vp, isMobile: label === 'phone', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + label });
await ctx.route(/^https:\/\//, rt => rt.abort()); // nothing leaves this machine (Google Fonts too: the pages fall back to Georgia + system fonts here)
const errs = []; const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message));
for (const [p, sel] of [['/', '#boardCards .paper'], ['/owner', '#levels .lvl'], ['/boost', '#bQty option'], ['/ledger', '#rows tbody tr'], ['/contract', '#facts th'], ['/promote', '#kit .card'], ['/terms', '.legal .card'], ['/disclaimer', '.legal .card'], ['/privacy', '.legal .card']]) {
await pg.goto(BASE + p, { waitUntil: 'domcontentloaded' }); await pg.waitForSelector(sel, { timeout: 8000 }).catch(() => {});
const found = await pg.$$eval(sel, els => els.length);
const wide = await pg.evaluate(() => document.documentElement.scrollWidth - window.innerWidth);
ok(found > 0 && wide <= 1, label + ' ' + p + ': renders (' + sel + ') with no sideways scroll', { found, wide });
await pg.screenshot({ path: path.join(OUT, label + '-' + (p === '/' ? 'front' : p.slice(1)) + '.png'), fullPage: true });
}
await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#ticker .run a', { timeout: 8000 }).catch(() => {});
ok((await pg.$$eval('#ticker .run a', els => els.length)) > 0 && (await pg.textContent('footer')).includes('TrustClickz') && /Part of the network/.test(await pg.textContent('footer')), label + ': ticker runs; footer has the company line and the network line');
await pg.goto(BASE + '/owner', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#levels .lvl a[data-go]', { timeout: 8000 }).catch(() => {});
await pg.waitForFunction(() => [...document.querySelectorAll('a[data-go]')].some(a => /[?&]v=[0-9a-f]{24}/.test(a.href)), null, { timeout: 9000 }).catch(() => {});
ok(await pg.evaluate(() => [...document.querySelectorAll('a[data-go]')].every(a => /[?&]v=[0-9a-f]{24}/.test(a.href))), label + ': after the dwell the visit verifies and every ad link carries the verified token');
ok(/LEVEL 1/.test(await pg.textContent('#levels')) && /Join free under @owner/.test(await pg.textContent('#join')), label + ': member page shows level rows and "Join free under @owner"');
await ctx.addCookies([{ name: 'vab.sid', value: OWN.jar['vab.sid'], url: BASE }]);
await pg.goto(BASE + '/my', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#dash:not([hidden])', { timeout: 8000 }).catch(() => {});
const mt = await pg.textContent('#dash').catch(() => '');
ok(/@owner/.test(mt) && /viraladblitz\.com\/owner/.test(mt) && /6 of 6 delivered/.test(mt) && (await pg.inputValue('#fHead')) === 'Headline number own', label + ': My page (signed in): page link, ad form filled, Boost delivery');
await pg.screenshot({ path: path.join(OUT, label + '-my.png'), fullPage: true });
await pg.goto(BASE + '/boost', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /about d/.test(document.getElementById('bPol').textContent), null, { timeout: 8000 }).catch(() => {});
ok(/about 20\.00 POL at today/.test(await pg.textContent('#bPol')) && !(await pg.isDisabled('#bBuy')), label + ': Boost page shows the live POL price and an open Buy button', await pg.textContent('#bPol'));
ok(errs.length === 0, label + ': no page errors', errs);
await ctx.close();
}
await browser.close();
} else console.log('16. (Playwright renders skipped)');
await stop();
console.log('\n' + pass + ' passed, ' + fail + ' failed');
fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n');
process.exit(fail ? 1 : 0);
}
main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); });
+135
View File
@@ -0,0 +1,135 @@
// Link + image checks for posted banners (Downline Banners' safety.js, used by ViralAdBlitz for text-ad links only).
// Links: https only, a real public hostname, no shorteners, and (when probed) a page that answers and allows frames.
// Images: a real PNG/JPG/GIF at exactly 125x125 (or 250x250 retina) and at most 100 KB. An https image address is
// fetched once, checked the same way and stored as an upload, so the splash never hotlinks someone else's server.
const net = require('net');
const dns = require('dns');
const https = require('https');
const MAX_UPLOAD = 100 * 1024;
const BAD_HOST = /(^|\.)(localhost|local|internal|lan|home|corp|onion|test|invalid|example)$/i;
// shorteners and redirectors hide where a click goes; a member link must show its real destination
const REDIRECTORS = /(^|\.)(bit\.ly|tinyurl\.com|t\.co|goo\.gl|is\.gd|cutt\.ly|ow\.ly|rebrand\.ly|shorturl\.at|rb\.gy|s\.id|t\.ly|v\.gd|bl\.ink|tiny\.cc)$/i;
function checkLink(raw, what) {
what = what || 'Link';
const s = String(raw || '').trim();
if (!s) return { error: what + ' is empty.' };
if (s.length > 600) return { error: what + ' is too long (600 characters max).' };
if (/[\s<>"'`\\]/.test(s)) return { error: what + ' has spaces or characters a web address cannot have.' };
let u; try { u = new URL(s); } catch (e) { return { error: what + ' is not a valid web address.' }; }
if (u.protocol !== 'https:') return { error: what + ' must start with https://' };
if (u.username || u.password) return { error: what + ' cannot contain a username or password.' };
const h = u.hostname.toLowerCase().replace(/\.$/, '');
if (net.isIP(h.replace(/^\[|\]$/g, ''))) return { error: what + ' must use a domain name, not an IP address.' };
if (!h.includes('.') || BAD_HOST.test(h)) return { error: what + ' must point to a public website.' };
if (!/^[a-z0-9.-]+$/.test(h) && !/^xn--/.test(h)) return { error: what + ' has an unusual domain name.' };
if (REDIRECTORS.test(h)) return { error: 'Use the real destination, not a link shortener.' };
if (u.port && !['443', ''].includes(u.port)) return { error: what + ' must use the normal https port.' };
return { ok: true, url: u.toString() };
}
function imageInfo(buf) {
if (!buf || buf.length < 24) return null;
if (buf.slice(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])))
return { type: 'png', ext: '.png', w: buf.readUInt32BE(16), h: buf.readUInt32BE(20) };
if (buf.slice(0, 6).toString('latin1') === 'GIF87a' || buf.slice(0, 6).toString('latin1') === 'GIF89a')
return { type: 'gif', ext: '.gif', w: buf.readUInt16LE(6), h: buf.readUInt16LE(8) };
if (buf[0] === 0xff && buf[1] === 0xd8) {
let i = 2;
while (i + 9 < buf.length) {
if (buf[i] !== 0xff) { i++; continue; }
const m = buf[i + 1];
if (m >= 0xc0 && m <= 0xcf && m !== 0xc4 && m !== 0xc8 && m !== 0xcc) return { type: 'jpg', ext: '.jpg', h: buf.readUInt16BE(i + 5), w: buf.readUInt16BE(i + 7) };
if (m === 0xd8 || m === 0x01 || (m >= 0xd0 && m <= 0xd7)) { i += 2; continue; }
i += 2 + buf.readUInt16BE(i + 2);
}
return { type: 'jpg', ext: '.jpg', w: 0, h: 0 };
}
return null;
}
function checkImage(buf) {
if (!buf || !buf.length) return { error: 'No file received.' };
if (buf.length > MAX_UPLOAD) return { error: 'That file is ' + Math.ceil(buf.length / 1024) + ' KB. The limit is 100 KB.' };
const info = imageInfo(buf);
if (!info) return { error: 'Use a PNG, JPG or GIF image.' };
const ok = (info.w === 125 && info.h === 125) || (info.w === 250 && info.h === 250);
if (!ok) return { error: 'The image is ' + info.w + 'x' + info.h + '. It must be 125x125 (or 250x250).' };
return { ok: true, info };
}
// ---- outbound requests only to public addresses (the DNS answer used for the connection is the one checked) ----
function privateIp(ip) {
if (net.isIPv4(ip)) {
const [a, b] = ip.split('.').map(Number);
return a === 0 || a === 10 || a === 127 || (a === 100 && b >= 64 && b <= 127) || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 168) || (a === 192 && b === 0) || (a === 198 && (b === 18 || b === 19)) || a >= 224;
}
const s = ip.toLowerCase();
if (s.startsWith('::ffff:')) return privateIp(s.slice(7));
return s === '::' || s === '::1' || s.startsWith('fc') || s.startsWith('fd') || s.startsWith('fe80') || s.startsWith('ff');
}
function safeLookup(host, opts, cb) {
dns.lookup(host, Object.assign({}, opts, { all: false }), (err, addr, fam) => {
if (err) return cb(err);
if (privateIp(addr)) return cb(new Error('private address'));
cb(null, addr, fam);
});
}
// GET with a size cap, a timeout and no redirects followed (a redirect is reported so the caller can decide)
function get(url, maxBytes, timeoutMs) {
return new Promise(resolve => {
let done = false; const fin = v => { if (!done) { done = true; resolve(v); } };
let req;
try {
req = https.get(url, { lookup: safeLookup, timeout: timeoutMs || 5000, headers: { 'User-Agent': 'Mozilla/5.0 (compatible; VABCheck/1.0; +https://viraladblitz.com)', Accept: '*/*' } }, res => {
const out = { status: res.statusCode, headers: res.headers, location: res.headers.location || null };
if (!maxBytes) { res.destroy(); return fin(out); }
const ch = []; let n = 0;
res.on('data', c => { n += c.length; if (n > maxBytes) { res.destroy(); return fin(Object.assign(out, { tooBig: true })); } ch.push(c); });
res.on('end', () => fin(Object.assign(out, { body: Buffer.concat(ch) })));
res.on('error', () => fin(Object.assign(out, { error: 'read' })));
});
req.on('timeout', () => { req.destroy(); fin({ error: 'timeout' }); });
req.on('error', e => fin({ error: /private address/.test(e.message) ? 'private' : 'unreachable' }));
} catch (e) { fin({ error: 'unreachable' }); }
});
}
// does this response allow being shown inside a frame on another site?
function frameVerdict(headers) {
const h = k => String(headers[k] || '').toLowerCase();
if (h('x-frame-options')) return false;
const fa = /frame-ancestors([^;]*)/.exec(h('content-security-policy'));
return !(fa && !/\*|https:/.test(fa[1]));
}
// the target link must answer and allow frames (traffic exchanges and the splash preview show sites in a frame). Up to 3 redirects.
async function probeLink(url, opts) { // opts.frames false: text ads open in a new tab, so frames are not required
let cur = url;
for (let hop = 0; hop < 4; hop++) {
const r = await get(cur, 0, 6000);
if (r.error === 'private') return { error: 'That link points to a private network address.' };
if (r.error) return { error: 'We could not reach that link. Check it opens in your browser and try again.' };
if (r.status >= 300 && r.status < 400 && r.location) {
let next; try { next = new URL(r.location, cur).toString(); } catch (e) { return { error: 'That link redirects somewhere invalid.' }; }
const c = checkLink(next, 'The page your link redirects to'); if (c.error) return c;
cur = c.url; continue;
}
if (r.status >= 400) return { error: 'That link answered with an error (' + r.status + '). Use a page that loads.' };
if (!(opts && opts.frames === false) && !frameVerdict(r.headers)) return { error: 'That site does not allow being shown in a frame, so it cannot rotate here. Use a page that allows frames (most landing pages and LinkSpin links do).' };
return { ok: true };
}
return { error: 'That link redirects too many times.' };
}
// an https image address: fetched once, checked like an upload. -> { ok, buf, info } or { error }
async function fetchImage(url) {
const r = await get(url, MAX_UPLOAD, 6000);
if (r.error === 'private') return { error: 'That image address points to a private network address.' };
if (r.error) return { error: 'We could not download that image. Check the address or upload the file instead.' };
if (r.tooBig) return { error: 'That image is over 100 KB.' };
if (r.status !== 200) return { error: 'The image address answered ' + r.status + '. Use a direct link to the image file, or upload it.' };
const c = checkImage(r.body); if (c.error) return c;
return { ok: true, buf: r.body, info: c.info };
}
module.exports = { checkLink, checkImage, imageInfo, frameVerdict, probeLink, fetchImage, privateIp, MAX_UPLOAD };
+462
View File
@@ -0,0 +1,462 @@
// ViralAdBlitz web app (viraladblitz.com rebuild, Marty approved 2026-11-14). Plain Node http server, no framework (the
// InstantAdPay / Downline Banners / VBB pattern).
// Product: the network's text-ad home. A network member (signed in through InstantAdPay / LinkSpin, membership checked with the
// hub) posts one free text ad: a headline, two lines and an https link. Their page viraladblitz.com/<username> shows their ad plus
// the ads of the 5 people above them in their hub sponsor line, so recruiting spreads an ad 5 levels down. The front page: a live
// amber ticker (Boosted ads starred), "Top ads this week" by verified clicks, 3 steps, the live ledger, contract proof.
// Boost: $5 one-time, 500 guaranteed network views (wire.js delivers and counts them), paid in POL through VABShop and split on
// chain 10% to each of 5 sponsor levels (pass-up to the next person who has boosted) + 50% company.
// Pages: / (front), /<username> (member page), /my, /boost, /ledger, /contract, /promote, /terms, /disclaimer, /privacy, /admin.
'use strict';
const http = require('http');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const { verifyMessage, getAddress } = require('ethers');
const cfgMod = require('./config');
const C = cfgMod.get();
fs.mkdirSync(C.dataDir, { recursive: true });
const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data
const store = require('./store');
const wire = require('./wire');
const safety = require('./safety');
const networksso = require('./networksso');
const shop = require('./shop');
const promokit = require('./promokit');
const hubreport = require('./hubreport');
const hubpeople = require('./hubpeople');
const hubline = require('./hubline');
const proof = require('./proof');
const netsites = require('./netsites');
const vabnas = require('./vabnas');
const PUB = path.join(__dirname, 'public');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/;
const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,40})\/?$/;
const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer|playwright/i;
const SECRET = (() => {
if (process.env.SESSION_SECRET) return process.env.SESSION_SECRET;
const f = path.join(C.dataDir, '.secret');
try { return fs.readFileSync(f, 'utf8').trim(); } catch (e) {}
const s = crypto.randomBytes(32).toString('hex'); try { fs.writeFileSync(f, s, { mode: 0o600 }); } catch (e) {} return s;
})();
const hash = s => crypto.createHmac('sha256', SECRET).update(s).digest('hex').slice(0, 24);
wire.setSecret(SECRET);
// ---- http helpers ----
const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg',
'.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' };
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
+ "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org "
+ "https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; "
+ "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'";
function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); }
function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); }
function sendFile(res, file, extra, code) {
fs.readFile(file, (err, data) => {
if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); }
const ext = path.extname(file).toLowerCase();
res.writeHead(code || 200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra)));
res.end(data);
});
}
function readRaw(req, max) {
return new Promise((resolve, reject) => { const ch = []; let n = 0;
req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); });
req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); });
}
async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } }
function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; }
function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); }
// client IP: the RIGHTMOST X-Forwarded-For entry is the one Coolify's proxy added (earlier ones can be forged). CF_PROXIED=1: cf-connecting-ip.
function ip(req) {
if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim();
const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean);
return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, '');
}
const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']);
const visitorKey = req => hash('vk|' + ip(req) + '|' + (req.headers['user-agent'] || '')); // not a cookie: traffic-exchange frames drop cookies
const ipKey = req => hash('ip|' + ip(req));
const buckets = new Map();
function limited(req, name, max, windowMs) {
const k = name + ':' + ip(req); const now = Date.now(); let b = buckets.get(k);
if (!b || now - b.t > windowMs) { b = { t: now, n: 0 }; buckets.set(k, b); }
if (buckets.size > 100000) buckets.clear();
return ++b.n > max;
}
const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || '');
return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); };
// ---- network membership through the hub (InstantAdPay's lookup only while the hub is unreachable) ----
const netCache = new Map();
async function netMember(q) {
const h = q.u ? await hubpeople.byRef(q.u) : await hubpeople.byWallet(q.a);
if (h.ok) { const a = hubpeople.wallet(h.person); return a ? { address: a, username: h.person.username ? String(h.person.username) : null, hubId: h.person.id || null, via: 'hub' } : null; }
if (!C.networkLookupUrl) return null;
const k = q.u ? 'u:' + q.u.toLowerCase() : 'a:' + q.a.toLowerCase();
const hit = netCache.get(k); if (hit && Date.now() - hit.at < 3600000) return hit.m;
let m = null;
try { const ac = new AbortController(); setTimeout(() => ac.abort(), 4000).unref();
const qs = q.u ? 'u=' + encodeURIComponent(q.u) : 'a=' + encodeURIComponent(q.a);
const j = await (await fetch(C.networkLookupUrl + '?' + qs, { signal: ac.signal })).json();
if (j && ADDR_RE.test(j.address || '') && j.username) m = { address: j.address.toLowerCase(), username: String(j.username), via: 'iap' }; } catch (e) { return null; }
netCache.set(k, { at: Date.now(), m }); if (netCache.size > 20000) netCache.clear();
return m;
}
async function fillUsername(addr) {
const m = store.member(addr); if (!m || m.username) return;
const n = await netMember({ a: addr }).catch(() => null);
if (n && n.address === m.address && NAME_RE.test(n.username || '') && !store.memberByName(n.username)) store.upsertMember(addr, { username: n.username });
}
// network-verified = the hub knows this wallet, or the network member who signed in through InstantAdPay / LinkSpin (their token's
// email, never stored). While the hub is unreachable: InstantAdPay's lookup by wallet, or a network sign-in. Rechecked each visit.
const netVerified = m => !!m && m.netOk === true;
async function verifyNet(addr, email) {
const m = store.member(addr); if (!m || netVerified(m)) return;
const h = await hubpeople.byWallet(addr);
let known = h.ok && !!h.person, down = !h.ok;
if (!known && !down && email) { const e = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }); if (e.ok) known = !!(e.person && !e.person.blocked); else down = true; }
if (!known && down) { const n = await netMember({ a: addr }).catch(() => null); known = (n && n.address === m.address) || m.via === 'iap' || m.via === 'linkspin'; }
if (known) { store.upsertMember(addr, { netOk: true, netAt: Date.now(), netBy: down ? 'fallback' : 'hub' }); await fillUsername(addr).catch(() => {}); }
}
const session = req => store.session(cookies(req)['vab.sid']);
networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase },
isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/my',
member: async req => { const s = session(req); return s ? { address: s.address } : null; },
accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }),
signIn: async (email, req, v) => {
const patch = { via: v.iss };
if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; }
store.upsertMember(v.wallet, patch);
await verifyNet(v.wallet, email).catch(() => {});
return cookie('vab.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true);
},
landing: to => to, signinPath: to => to });
// ---- old site links (the VBB pattern): /?<old username>, /splashpg.php?pid=N&r=<old>, /lcp.php?pid=N&r=<old> -> the same person's
// page here (oldrefs.json, a MySQL document loaded by POST /api/admin/oldrefs, matched by email); any other *.php -> / ----
let oldRefs = { at: 0, map: {} };
function oldRefMap() {
if (Date.now() - oldRefs.at < 60000) return oldRefs.map;
let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {}
oldRefs = { at: Date.now(), map: m }; return m;
}
function oldLink(u) {
const p = u.pathname; const bare = u.search.slice(1).split('&')[0];
if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare)) return p === '/' ? null : '/'; }
else if (!/\.php$/i.test(p)) return null;
const lp = p.toLowerCase();
const old = (lp === '/splashpg.php' || lp === '/lcp.php') ? String(u.searchParams.get('r') || '') : (lp === '/' || lp === '/index.php') ? bare : '';
const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null;
return net ? '/' + encodeURIComponent(net) : '/';
}
const ZONE_404 = ''; // LinkSpin zone "ViralAdBlitz not found" (300x250), to be created on Marty's LinkSpin account; '' = off
const PAGES = { '/': 'index.html', '/my': 'my.html', '/boost': 'boost.html', '/ledger': 'ledger.html', '/contract': 'contract.html', '/admin': 'admin.html',
'/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html' };
const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'my', 'boost', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy']);
const challenges = new Map();
const tickets = new Map();
const srcHost = raw => { try { const u = new URL(String(raw || '')); if (!/^https?:$/.test(u.protocol)) return ''; const h = u.hostname.toLowerCase().replace(/^www\./, ''); return h === C.site || h.endsWith('.' + C.site) || !h.includes('.') ? '' : h.slice(0, 80); } catch (e) { return ''; } };
// ---- a member page: their ad, the first 5 people above them in the hub line who have a live ad here, and Boosted places ----
async function memberPage(name) {
const local = store.memberByName(name);
const lo = await hubline.lineOf({ ref: name.toLowerCase() }, C.lineSearch);
const person = lo.person;
const ownerAddr = local ? local.address : person ? hubpeople.wallet(person) : null;
const ownerName = (person && person.username) || (local && local.username) || name;
const own = ownerAddr ? store.adOf(ownerAddr) : null;
const ownAd = own && own.status === 'live' ? own : null;
const line = []; const used = new Set(ownAd ? [ownAd.id] : []);
for (const p of lo.line) {
if (line.length >= C.levels) break;
let a = p.wallet ? store.adOf(p.wallet) : null;
if (!a && p.username) { const lm = store.memberByName(p.username); if (lm) a = store.adOf(lm.address); }
if (a && a.status === 'live' && a.owner !== ownerAddr && !used.has(a.id)) { used.add(a.id); line.push({ level: p.depth, ad: a }); }
}
const boosted = wire.pickBoosted(C.boostSlots, used);
return { known: !!(local || person), hubOk: lo.ok, stale: !!lo.stale, ownerAddr, ownerName, ownAd, line, boosted };
}
// ---- a page load's ads + its visit ticket (the ads it showed, decided here, never by the browser) ----
function issueTicket(req, page, shownIds, ref, src) {
if (isBot(req) || req.headers['sec-fetch-site'] === 'cross-site' || limited(req, 'ticket', 240, 3600000)) return null;
const s = session(req); const t = crypto.randomBytes(12).toString('hex');
tickets.set(t, { vk: visitorKey(req), iph: ipKey(req), at: Date.now(), page, shown: [...new Set(shownIds)], ref: ref || null, src: srcHost(src), viewer: s ? s.address : null });
if (tickets.size > 50000) { const cut = Date.now() - 1800000; for (const [k, v] of tickets) if (v.at < cut) tickets.delete(k); }
return t;
}
const todayStats = () => { const t = store.today(); return { views: t.views || 0, vclicks: t.vclicks || 0, boosts: t.boosts || 0, ads: store.liveAds().length }; };
const joinUrl = ref => C.joinUrl.split('{ref}').join(encodeURIComponent(ref || ''));
// tracking macros in an ad link, filled on every click: {clickid} a fresh id, {placement} where it was clicked
const MACRO = /\{(clickid|placement)\}|%7B(clickid|placement)%7D/gi;
function clickLink(a, placement) {
const l = String(a.link || ''); if (!l.match(MACRO)) return l;
const v = { clickid: crypto.randomBytes(8).toString('hex'), placement: String(placement || 'site').replace(/[^a-z0-9-]/gi, '').slice(0, 20) || 'site' };
return l.replace(MACRO, (x, p1, p2) => v[(p1 || p2).toLowerCase()]);
}
function cleanText(s, max) { return String(s == null ? '' : s).replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/[\u2013\u2014]/g, '-').replace(/\s+/g, ' ').trim().slice(0, max + 1); }
function myEarned(me) {
let wei = 0n; const list = [];
for (const x of wire.purchases()) for (const p of x.pays || []) if (p.level > 0 && p.to === me) { try { wei += BigInt(p.wei); } catch (e) {} list.push({ tx: String(x.key).split(':')[0], at: (x.blockAt ? x.blockAt * 1000 : x.at), level: p.level, depth: p.depth, wei: p.wei, failed: !!p.failed, buyerName: (store.member(x.buyer) || {}).username || null }); }
return { wei: wei.toString(), items: list.sort((a, b) => (b.at || 0) - (a.at || 0)).slice(0, 50) };
}
const server = http.createServer(async (req, res) => {
const u = new URL(req.url, 'http://x'); const p = u.pathname;
{ const host = String(req.headers.host || '').toLowerCase().split(':')[0];
if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } }
try {
if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return;
if (req.method === 'GET' || req.method === 'HEAD') {
if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files' });
{ const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } }
if (PAGES[p]) {
const ex = {}; const ref = u.searchParams.get('ref');
if (ref && (NAME_RE.test(ref) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('vab.ref', ref, 30 * 86400, false);
if (p === '/my' || p === '/admin') ex['X-Frame-Options'] = 'DENY';
return sendFile(res, path.join(PUB, PAGES[p]), ex);
}
if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); }
if (p === '/sitemap.xml') {
const day = new Date().toISOString().slice(0, 10);
const urls = ['/', '/boost', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy'].map(x => '<url><loc>https://' + C.site + x + '</loc><lastmod>' + day + '</lastmod></url>').join('');
res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' }));
return res.end('<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' + urls + '</urlset>');
}
if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end('User-agent: *\nAllow: /\nDisallow: /my\nDisallow: /admin\nDisallow: /api/\nDisallow: /go/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); }
if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') {
const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); }
return sendFile(res, f);
}
// click relay: /go/<ad id>?v=<verified token>&p=<placement> -> the ad's link. Verified clicks rank the weekly board.
const gm = /^\/go\/(\d{1,9})$/.exec(p);
if (gm) {
const a = store.ad(gm[1]); if (!a || a.status === 'removed') { res.writeHead(302, { Location: '/' }); return res.end(); }
const pl = String(u.searchParams.get('p') || '').slice(0, 20);
if (!isBot(req) && !limited(req, 'click', 600, 3600000)) { const vk = visitorKey(req); const s = session(req); wire.click(a, vk, wire.vtokenOk(vk, u.searchParams.get('v')), s ? s.address : null, pl); }
res.writeHead(302, { Location: clickLink(a, pl), 'Cache-Control': 'no-store', 'Referrer-Policy': 'origin' }); return res.end();
}
// a member page: viraladblitz.com/<network username>
const pm = PAGE_RE.exec(p);
if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) {
const name = pm[1];
const known = store.memberByName(name) || (await hubpeople.byRef(name.toLowerCase()).then(h => (h.ok ? h.person : 'down')).catch(() => 'down'));
if (known) return sendFile(res, path.join(PUB, 'member.html'), { 'Set-Cookie': cookie('vab.ref', name, 30 * 86400, false) });
}
}
// -- public API
if (p === '/api/config' && req.method === 'GET') {
return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId,
boost: C.boost, split: C.split, deliverDays: C.deliverDays, levels: C.levels, visitSeconds: C.visitSeconds, ad: C.ad, sso: networksso.enabled(),
shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, joinUrl: joinUrl('') });
}
// everything a page shows, with its visit ticket. page=front|member|other, u=<username> for member pages
if (p === '/api/wire' && req.method === 'GET') {
const kind = ['front', 'member'].includes(u.searchParams.get('page')) ? u.searchParams.get('page') : 'other';
const tick = wire.ticker(); const shown = tick.map(x => x.id); const out = { ticker: tick, today: todayStats(), week: wire.weekStats() };
let ref = null;
if (kind === 'front') { out.board = wire.board(); out.board.items.forEach(x => shown.push(x.id)); out.joinUrl = joinUrl(''); }
if (kind === 'member') {
const name = String(u.searchParams.get('u') || ''); if (!NAME_RE.test(name)) return json(res, 404, { error: 'Not found' });
const mp = await memberPage(name);
if (!mp.known && mp.hubOk) return json(res, 404, { error: 'No network member by that name.' });
const boostedIds = new Set(wire.activeBoosts().map(b => b.adId));
out.page = { username: mp.ownerName, known: mp.known, hubOk: mp.hubOk, ad: mp.ownAd ? wire.adCard(mp.ownAd, boostedIds.has(mp.ownAd.id)) : null,
line: mp.line.map(x => Object.assign({ level: x.level }, wire.adCard(x.ad, boostedIds.has(x.ad.id)))), boosted: mp.boosted.map(a => wire.adCard(a, true)),
joinUrl: joinUrl(mp.ownerName) };
if (mp.ownAd) shown.push(mp.ownAd.id); mp.line.forEach(x => shown.push(x.ad.id)); mp.boosted.forEach(a => shown.push(a.id));
ref = mp.ownerAddr;
}
out.ticket = issueTicket(req, kind === 'member' ? 'member:' + String(u.searchParams.get('u')).toLowerCase() : kind, shown, ref, u.searchParams.get('src'));
out.seconds = C.visitSeconds;
return json(res, 200, out);
}
if (p === '/api/visit/seen' && req.method === 'POST') {
const b = await readBody(req); const t = tickets.get(String(b.ticket || ''));
if (!t || isBot(req) || t.vk !== visitorKey(req)) return json(res, 200, { verified: false, why: 'ticket' });
const age = Date.now() - t.at;
if (age < C.visitSeconds * 1000 - 300 || Number(b.visibleMs) < C.visitSeconds * 1000 - 300) return json(res, 200, { verified: false, why: 'early' });
tickets.delete(String(b.ticket));
if (age > 1800000) return json(res, 200, { verified: false, why: 'ticket' });
const r = wire.verify(t);
return json(res, 200, Object.assign(r, r.verified ? { vt: wire.vtoken(t.vk) } : {}));
}
if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' });
if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); }
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
// toasts: real events of the last 30 minutes (new ads, Boosts with the levels they paid)
if (p === '/api/recent' && req.method === 'GET') {
const cut = Date.now() - 30 * 60000;
const ads = store.liveAds().filter(a => a.createdAt > cut).slice(-6).map(a => ({ kind: 'ad', key: 'a' + a.id, at: a.createdAt, name: (store.member(a.owner) || {}).username || null, headline: a.headline }));
const boosts = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'boost', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName, levels: x.pays.filter(q => q.level > 0 && !q.failed).length }));
return json(res, 200, { items: ads.concat(boosts).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' });
}
if (p === '/api/quote' && req.method === 'GET') {
if (!shop.watching()) return json(res, 503, { error: 'Boosts are not open yet.' });
if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const qty = Number(u.searchParams.get('qty') || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
try { return json(res, 200, Object.assign({ usd: C.boost.usd * qty, views: C.boost.views * qty }, await shop.quote(C.boost.sku, qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } }
if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') {
if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false });
try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); }
}
// wallet sign-in
if (p === '/api/auth/challenge' && req.method === 'POST') {
if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' });
const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' });
const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex');
const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\nViralAdBlitz sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString();
challenges.set(a, { message, exp: Date.now() + 600000 }); if (challenges.size > 20000) challenges.clear();
return json(res, 200, { message });
}
if (p === '/api/auth/verify' && req.method === 'POST') {
const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a);
if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' });
let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); }
if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' });
challenges.delete(a);
store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' });
await verifyNet(a).catch(() => {});
return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('vab.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) });
}
if (p === '/api/auth/logout' && req.method === 'POST') {
const s = session(req); if (s) store.dropSession(s.token);
return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('vab.sid', '', 0, true), networksso.offCookie()] });
}
if (p === '/api/me' && req.method === 'GET') {
const s = session(req); if (!s) return json(res, 200, { signedIn: false });
const m = store.member(s.address);
return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null, netVerified: netVerified(m) });
}
// -- member API
if (p.startsWith('/api/my')) {
const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' });
const me = s.address; if (!store.member(me)) store.upsertMember(me, { via: 'wallet' });
if (p === '/api/my' && req.method === 'GET') {
await verifyNet(me).catch(() => {}); const m = store.member(me); m.lastSeen = Date.now();
const a = store.adOf(me); const lo = netVerified(m) ? await hubline.lineOf({ wallet: me }, C.lineSearch) : { ok: true, line: [] };
const line = []; for (const x of lo.line) { if (line.length >= C.levels) break; const la = x.wallet ? store.adOf(x.wallet) : null; line.push({ depth: x.depth, username: x.username, hasWallet: !!x.wallet, hasAd: !!(la && la.status === 'live') }); }
const page = m.username ? 'https://' + C.site + '/' + encodeURIComponent(m.username) : null;
return json(res, 200, { address: me, username: m.username, netVerified: netVerified(m), ad: a ? { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2, link: a.link, status: a.status, views: a.views || 0, clicks: a.clicks || 0, vclicks: a.vclicks || 0, createdAt: a.createdAt } : null,
boosts: wire.purchases().filter(b => b.buyer === me).sort((x, y) => (y.at || 0) - (x.at || 0)).map(wire.boostView), earned: myEarned(me), line: line.slice(0, 8), lineOk: lo.ok,
page, joinUrl: joinUrl(''), boost: C.boost });
}
// the member's one text ad: create, or edit (a Boost follows the ad, so editing keeps it)
if (p === '/api/my/ad' && req.method === 'POST') {
if (limited(req, 'ad', 30, 3600000)) return json(res, 429, { error: 'Too many changes this hour.' });
const m = store.member(me); await verifyNet(me).catch(() => {});
if (!netVerified(m)) return json(res, 403, { error: 'Text ads are free for network members. Join InstantAdPay or LinkSpin free, then sign in here through them.', join: joinUrl('') });
const b = await readBody(req);
const headline = cleanText(b.headline, C.ad.headline), line1 = cleanText(b.line1, C.ad.line), line2 = cleanText(b.line2, C.ad.line);
if (headline.length < 3 || headline.length > C.ad.headline) return json(res, 400, { error: 'Write a headline of 3 to ' + C.ad.headline + ' characters.' });
if (line1.length < 3 || line1.length > C.ad.line) return json(res, 400, { error: 'Write the first line in 3 to ' + C.ad.line + ' characters.' });
if (line2.length > C.ad.line) return json(res, 400, { error: 'Keep the second line to ' + C.ad.line + ' characters.' });
const lk = safety.checkLink(b.link, 'Your link'); if (lk.error) return json(res, 400, lk);
const cur = store.adOf(me);
if (C.linkProbe && (!cur || cur.link !== lk.url)) { const pr = await safety.probeLink(lk.url, { frames: false }); if (pr.error) return json(res, 400, pr); }
if (cur) { Object.assign(cur, { headline, line1, line2, link: lk.url, status: cur.status === 'paused' ? 'paused' : 'live' }); store.saveAd(cur); return json(res, 200, { ok: true, ad: { id: cur.id }, created: false }); }
const a = store.addAd({ owner: me, headline, line1, line2, link: lk.url, status: 'live', views: 0, clicks: 0, vclicks: 0 }); store.bump('adsPosted');
wire.attachPending(me, a.id);
return json(res, 200, { ok: true, ad: { id: a.id }, created: true });
}
// a Boost: the buy() call for the member's own wallet, with a fresh line voucher when the line is not bound on chain yet
if (p === '/api/my/order' && req.method === 'POST') {
if (!shop.watching()) return json(res, 503, { error: 'Boosts are not open yet.' });
if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' });
const b = await readBody(req); const qty = Number(b.qty || 1);
if (!Number.isInteger(qty) || qty < 1 || qty > C.boost.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.boost.maxQty + ' Boosts.' });
const a = store.adOf(me); if (!a || a.status !== 'live') return json(res, 400, { error: 'Post your text ad first. A Boost is for your ad.' });
let v = null, why = null; const bound = await shop.boundSponsor(me);
if (bound) why = 'bound';
else if (bound === undefined) return json(res, 503, { error: 'The chain did not answer just now. Try again in a minute.' });
else if (!shop.voucherOn()) why = 'off';
else {
const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE);
if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' });
const wallets = lo.line.filter(x => x.wallet && x.wallet !== me).map(x => x.wallet);
if (!wallets.length) why = 'no-line'; else v = await shop.voucher(me, wallets);
}
try { return json(res, 200, Object.assign({ buyer: me, usd: C.boost.usd * qty, views: C.boost.views * qty, qty, adId: a.id, why }, await shop.order(me, C.boost.sku, qty, a.id, v))); }
catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); }
}
if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); }
return json(res, 404, { error: 'Not found' });
}
// -- admin (x-admin-token: ADMIN_TOKEN)
if (p.startsWith('/api/admin/')) {
if (!isAdmin(req)) return json(res, 401, { error: 'no' });
if (p === '/api/admin/status' && req.method === 'GET') {
const S = store.state(); const B = wire.purchases().map(wire.boostView);
return json(res, 200, { day: store.ctDay(), week: store.ctWeek(), config: { boost: C.boost, split: C.split, deliverDays: C.deliverDays, visitSeconds: C.visitSeconds, perIpDay: C.perIpDay, boostSlots: C.boostSlots, tickerBoosts: C.tickerBoosts, lineSearch: C.lineSearch },
today: store.today(), totals: S.totals, members: store.members().length, ads: { live: store.liveAds().length, all: store.ads().length },
boosts: { orders: B.length, views: B.reduce((t, b) => t + b.views, 0), delivered: B.reduce((t, b) => t + b.delivered, 0), active: B.filter(b => b.remaining > 0).length, late: B.filter(b => b.status === 'finishing-in-network').length, waitingForAd: B.filter(b => b.status === 'waiting-for-ad').length },
rows: { visits: store.visits().length, clicks: store.clicks().length, boostViews: store.bviews().length },
shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), nas: vabnas.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length });
}
if (p === '/api/admin/boosts' && req.method === 'GET') return json(res, 200, { boosts: wire.purchases().map(x => Object.assign(wire.boostView(x), { buyer: x.buyer, usdCents: x.usdCents, weiPaid: x.weiPaid, pays: x.pays || null, over: x.over || null })).sort((a, b) => (b.at || 0) - (a.at || 0)) });
if (p === '/api/admin/oldrefs' && req.method === 'POST') {
let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); }
if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' });
const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v);
fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} };
return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length });
}
if (p === '/api/admin/nas/tick' && req.method === 'POST') return json(res, 200, await vabnas.tick());
// remove an ad that breaks the rules (spam, a dead or harmful link); its Boosts stop delivering until the owner posts again
if (p === '/api/admin/ad' && req.method === 'POST') {
const b = await readBody(req); const a = store.ad(b.id); if (!a) return json(res, 404, { error: 'not found' });
if (!['live', 'paused', 'removed'].includes(b.status)) return json(res, 400, { error: 'status live | paused | removed' });
a.status = b.status; a.note = cleanText(b.note, 200); store.saveAd(a); return json(res, 200, { ok: true, ad: a });
}
if (p === '/api/admin/member-lookup' && req.method === 'GET') {
const q = String(u.searchParams.get('q') || '').trim(); let a = null, via = null;
if (ADDR_RE.test(q)) { a = q.toLowerCase(); via = 'wallet'; }
else if (/^#?\d{1,9}$/.test(q)) { const ad = store.ad(Number(q.replace('#', ''))); a = ad ? ad.owner : null; via = 'ad'; }
else if (NAME_RE.test(q)) { const m = store.memberByName(q); a = m ? m.address : null; via = 'username'; }
if (!a) return json(res, 404, { error: 'not found' });
const P = wire.purchases();
return json(res, 200, { via, address: a, record: store.member(a), ad: store.adOf(a), boosts: P.filter(x => x.buyer === a).map(wire.boostView), earned: myEarned(a),
paidBy: P.filter(x => (x.pays || []).some(q2 => q2.to === a && q2.level > 0)).map(x => ({ tx: String(x.key).split(':')[0], buyer: x.buyer })), contract: C.contractAddress, explorer: C.explorer });
}
return json(res, 404, { error: 'Not found' });
}
if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });
res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' }));
return res.end('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><title>Not found | ViralAdBlitz</title><body style="background:#0a1712;color:#e8efe9;font-family:Georgia,serif;text-align:center;padding:40px 16px"><p style="font-size:22px">Not found.</p><p><a style="color:#ffb000;font-weight:700" href="/">Back to the wire</a></p>'
+ (ZONE_404 ? '<p style="color:#8fa89a;font-size:11px;margin:24px 0 4px">Network</p><script async src="https://linkspin.app/z.js" data-zone="' + ZONE_404 + '"></script>' : '') + '</body>');
} catch (e) {
console.error('request', p, e.message);
if (!res.headersSent) json(res, 500, { error: 'Server error' });
}
});
(async () => {
await docstore.init({ splits: store.SPLITS });
process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); });
store.load();
wire.init({ nasServed: key => vabnas.boostServed(key) });
store.prune(); wire.rebuild();
hubreport.init({ dataDir: C.dataDir, purchases: () => wire.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: x.sponsor || null, usdCents: x.usdCents, block: x.block, at: x.at })) });
proof.init(C, { shop, wire, nameOf: async a => { const m = await netMember({ a }).catch(() => null); return m && m.address === a ? m.username : null; } });
shop.setAttach(rec => { wire.attach(rec); store.bump('boosts', Number(rec.qty) || 1); });
shop.setHook(proof.onPurchase);
shop.init(C);
vabnas.init({ boosts: () => wire.purchases(), remaining: b => wire.remaining(b), ad: id => store.ad(id) });
setInterval(() => { if (store.prune()) wire.rebuild(); }, 3600000).unref();
server.listen(C.port, () => console.log('ViralAdBlitz on :' + C.port + ', Boost $' + C.boost.usd + ' = ' + C.boost.views + ' views, store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)')));
})().catch(e => { console.error('start failed:', e.message); process.exit(1); });
process.on('SIGINT', () => { store.flush(); process.exit(0); });
+173
View File
@@ -0,0 +1,173 @@
// On-chain Boosts (VABShop, ../contracts). Each job is inert until it is configured:
// (a) line vouchers: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Voucher(buyer, address[] line, deadline), line =
// the buyer's network sponsor line from the hub (wallets, nearest first, up to 20). On the buyer's first Boost the contract
// binds every unbound link along it; a bound link never changes (the contract's binding wins, Marty 2026-11-14).
// (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and records each Boost once
// per txHash:logIndex (the dedupe mark and the Boost live in the same document, so they save together).
// (c) buying: quote() reads quoteWei, order() builds the member's buy() call, receipt() / fees() back the page's wait.
// The key never enters config or any API answer.
'use strict';
const { Wallet, Interface, getAddress } = require('ethers');
const store = require('./store');
const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;
const ZERO = '0x0000000000000000000000000000000000000000';
const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 indexed sku, uint256 qty, uint256 ref, uint256 views, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 companyPaid)',
'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)',
'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)',
'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)',
'event SponsorBound(address indexed member, address indexed sponsor)']);
const TOPIC = IFACE.getEvent('Purchase').topicHash;
const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash, over: IFACE.getEvent('PassedOver').topicHash, bound: IFACE.getEvent('SponsorBound').topicHash };
const CALLS = new Interface(['function quoteWei(uint256 sku, uint256 qty) view returns (uint256)',
'function buy(uint256 sku, uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
'function sponsorOf(address) view returns (address)', 'function boostsBought(address) view returns (uint256)',
'function payeesOf(address buyer) view returns (address[] to, uint8[] depth)', 'function skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)']);
const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] };
const MAX_LINE = 20;
const st = { polls: 0, recorded: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null };
let C = null, keeper = null, busy = false, timer = null;
const hooks = { onPurchase: null, attach: null };
function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; }
function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : null; }
function init(cfg) {
C = cfg; keeper = null;
const k = String(process.env.KEEPER_KEY || '').trim();
if (k) { try { keeper = new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { console.error('shop: KEEPER_KEY is not a valid private key; vouchers off'); } }
if (timer) { clearTimeout(timer); timer = null; }
if (watching()) { console.log('shop: watching', C.contractAddress, 'for Boosts'); tick(); }
}
const voucherOn = () => !!(C && keeper && C.contractAddress);
const watching = () => !!(C && C.contractAddress && C.chainRpc);
const domain = () => ({ name: 'VABShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress });
// a voucher binding `line` (wallets, nearest first) above `buyer`, or null (off, empty, bad)
async function voucher(buyer, line) {
if (!voucherOn() || !ADDR_RE.test(buyer || '')) return null;
const b = getAddress(buyer); const seen = new Set([b.toLowerCase()]); const l = [];
for (const w of line || []) { if (!ADDR_RE.test(w || '') || seen.has(w.toLowerCase()) || w === ZERO) continue; seen.add(w.toLowerCase()); l.push(getAddress(w)); if (l.length >= MAX_LINE) break; }
if (!l.length) return null;
const deadline = Math.floor(Date.now() / 1000) + C.voucherSeconds;
const sig = await keeper.signTypedData(domain(), TYPES, { buyer: b, line: l, deadline });
return { buyer: b, line: l, deadline, sig, contract: C.contractAddress, chainId: C.chainId };
}
// record one Purchase log. false = already recorded (or not ours).
function apply(ev) {
const S = store.state(); const P = S.purchases || (S.purchases = {});
const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex;
if (P[key]) { st.dupes++; return false; }
const a = ev.buyer.toLowerCase(); if (!store.member(a)) store.upsertMember(a, { via: 'wallet' });
const rec = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, sku: ev.sku, qty: ev.qty, ref: ev.ref, views: ev.views,
usdCents: ev.usdCents, weiPaid: ev.weiPaid, levelsPaid: ev.levelsPaid, companyPaid: ev.companyPaid, sponsor: ev.sponsor || null, delivered: 0 };
if (hooks.attach) { try { hooks.attach(rec); } catch (e) {} }
P[key] = rec; store.save(); st.recorded++;
if (hooks.onPurchase) { try { hooks.onPurchase(rec, String(ev.txHash).toLowerCase()); } catch (e) {} }
console.log('shop: Boost order', ev.orderId, 'x' + ev.qty, a, ev.views + ' views', rec.adId ? 'for ad #' + rec.adId : '(no ad yet)');
return true;
}
function decode(l) {
if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase() || (l.topics || [])[0] !== TOPIC) return null;
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args;
return { txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), orderId: Number(d.orderId), buyer: d.buyer, sku: Number(d.sku),
qty: Number(d.qty), ref: d.ref.toString(), views: Number(d.views), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), levelsPaid: Number(d.levelsPaid), companyPaid: d.companyPaid.toString() };
}
// the split of one order from its receipt: level payouts (with their place in the line), the company, who was passed over and
// which links of the line this purchase bound. null if the RPC does not answer.
async function readSplit(tx, orderId) {
const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null;
const pays = [], over = [], bound = [];
for (const l of r.logs) {
if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue;
const t0 = l.topics[0];
if (t0 === T.bound) { const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; bound.push({ member: d.member.toLowerCase(), sponsor: d.sponsor.toLowerCase() }); continue; }
if (t0 !== T.paid && t0 !== T.fail && t0 !== T.over) continue;
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue;
if (t0 === T.over) over.push({ who: d.who.toLowerCase(), depth: Number(d.depth) });
else pays.push({ level: Number(d.level), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined });
}
return { pays, over, bound };
}
async function rpc(method, params) {
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 10000); t.unref();
try { const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: ac.signal })).json();
if (j.error) throw new Error(method + ': ' + (j.error.message || JSON.stringify(j.error))); return j.result; } finally { clearTimeout(t); }
}
async function poll() {
if (busy || !watching()) return; busy = true; st.polls++;
try {
const S = store.state(); const sh = S.shop || (S.shop = {});
const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head;
if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 1; if (!C.shopStartBlock) console.log('shop: no SHOP_START_BLOCK, watching from block', head + 1); store.save(); }
while (sh.lastBlock < head) {
const from = sh.lastBlock + 1, to = Math.min(head, from + 999);
const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]);
for (const l of logs || []) {
const ev = decode(l); if (!ev) { st.ignored++; continue; }
const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; if ((S.purchases || {})[key]) { st.dupes++; continue; }
ev.blockAt = await blockTime(ev.block);
try { ev.sponsor = String((await call('sponsorOf', [ev.buyer]))[0]).toLowerCase(); if (ev.sponsor === ZERO) ev.sponsor = null; } catch (e) {}
apply(ev);
}
sh.lastBlock = to; store.save();
}
} catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); }
finally { busy = false; }
}
const btCache = new Map();
async function blockTime(n) {
if (btCache.has(n)) return btCache.get(n);
let t = null; try { const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]); t = b && b.timestamp ? parseInt(b.timestamp, 16) : null; } catch (e) {}
if (t) { btCache.set(n, t); if (btCache.size > 5000) btCache.clear(); }
return t;
}
function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); }
// ---- buying ----
async function call(fn, args, to) {
const r = await rpc('eth_call', [{ to: to || C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']);
return CALLS.decodeFunctionResult(fn, r);
}
const qCache = new Map();
// POL wei for qty Boosts now; sendWei adds 1% for price drift (the contract refunds anything above the price in the same tx)
async function quote(sku, qty) {
const k = sku + 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v;
const wei = (await call('quoteWei', [sku, qty]))[0];
const v = { sku, qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() };
qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear();
return v;
}
async function order(buyer, sku, qty, ref, v) {
const q = await quote(sku, qty);
const data = CALLS.encodeFunctionData('buy', [sku, qty, BigInt(ref || 0), v ? v.line : [], v ? v.deadline : 0, v ? v.sig : '0x']);
return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, line: v ? v.line.length : 0 };
}
// is the buyer's line already bound on chain? (then no voucher is needed: the contract ignores it)
async function boundSponsor(buyer) { try { const s = String((await call('sponsorOf', [buyer]))[0]).toLowerCase(); return s === ZERO ? null : s; } catch (e) { return undefined; } }
async function payees(buyer) { try { const r = await call('payeesOf', [buyer]); return r[0].map((a, i) => ({ to: String(a).toLowerCase(), depth: Number(r[1][i]) })); } catch (e) { return null; } }
async function receipt(hash) {
const r = await rpc('eth_getTransactionReceipt', [hash]);
if (!r) return { found: false };
return { found: true, status: r.status, blockNumber: r.blockNumber, to: r.to ? String(r.to).toLowerCase() : null, from: r.from ? String(r.from).toLowerCase() : null };
}
// Polygon's ~25 gwei priority-fee floor: wallets' own estimates miss it (the Downline Banners fix)
async function fees() {
let tip = 0n, base = 0n;
try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {}
try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {}
const MIN_TIP = C.chainId === 137 ? 30000000000n : 1000000000n;
const priority = tip > MIN_TIP ? tip : MIN_TIP;
return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) };
}
let lastNudge = 0;
function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); }
function view() {
const list = Object.values((store.state() && store.state().purchases) || {});
return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null,
lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, boosts: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orders: list.length,
viewsSold: list.reduce((t, x) => t + (x.views || 0), 0), noAd: list.filter(x => !x.adId).length }, st);
}
module.exports = { setHook, setAttach, init, voucher, voucherOn, watching, apply, poll, view, quote, order, receipt, fees, nudge, call, rpc, readSplit, boundSponsor, payees, TOPIC, IFACE, TYPES, CALLS, MAX_LINE };
+114
View File
@@ -0,0 +1,114 @@
// ViralAdBlitz data. One document (vab.json) holds members, sessions, Boost purchases (the chain's Purchase events with their
// delivery counters), the watcher position and daily counters. Four growing collections are row tables when the app runs on
// MySQL (docstore splits): text ads, verified visits, verified clicks and Boost views (the audit trail of every view counted
// toward a Boost's guarantee). Without DOCSTORE_URL (local prototype + smoke tests only) everything stays in the one file,
// written atomically (tmp + rename). Marty's rule (2026-11-13): MySQL is the standard; never launch on files.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cfgMod = require('./config');
const docstore = require('./docstore');
const DOC = 'vab.json';
const SPLITS = [
{ doc: DOC, field: 'ads', table: 'vab_ads', key: 'id', ts: 'createdAt' },
{ doc: DOC, field: 'visits', table: 'vab_visits', key: 'id', ts: 'at' },
{ doc: DOC, field: 'clicks', table: 'vab_clicks', key: 'id', ts: 'at' },
{ doc: DOC, field: 'bviews', table: 'vab_bviews', key: 'id', ts: 'at' }
];
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
let S = null, saveT = null, rowMode = false;
const adById = new Map(), adByOwner = new Map();
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
function load() {
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
S = Object.assign({ v: 1, seq: { ad: 0, visit: 0, click: 0, bview: 0 }, daily: {}, totals: { visits: 0, views: 0, vclicks: 0, clicks: 0, boostViews: 0 },
members: {}, sessions: {}, purchases: {}, shop: {}, ads: [], visits: [], clicks: [], bviews: [] }, S || {});
rowMode = docstore.isOn();
if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice();
adById.clear(); adByOwner.clear();
for (const a of S.ads) { adById.set(a.id, a); if (a.status !== 'removed') adByOwner.set(a.owner, a); }
const now = Date.now();
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
}
function save(now) {
if (saveT && !now) return;
const run = () => {
saveT = null;
try {
const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S;
const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE());
} catch (e) { console.error('store save failed', e.message); }
};
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800);
}
function flush() { save(true); }
const state = () => S;
function putRow(field, item) {
if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); }
save();
}
function dropRows(field, ids) {
if (!ids.length) return;
const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key]));
if (rowMode) docstore.rowDel(TABLE[field].table, ids);
save();
}
function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; }
// ---- Central time (Marty: everything on US Central) ----
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; }
function ctWeek(ts) { // the Central-time date of that week's Monday
const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10);
}
function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); }
function today() { return S.daily[ctDay()] || {}; }
// ---- text ads (one live ad per member) ----
function ad(id) { return adById.get(Number(id)) || null; }
function adOf(owner) { return adByOwner.get(String(owner || '').toLowerCase()) || null; }
function addAd(a) { a.id = nextId('ad'); a.createdAt = Date.now(); a.updatedAt = a.createdAt; S.ads.push(a); adById.set(a.id, a); adByOwner.set(a.owner, a); putRow('ads', a); return a; }
function saveAd(a) { a.updatedAt = Date.now(); if (a.status === 'removed') { if (adByOwner.get(a.owner) === a) adByOwner.delete(a.owner); } else adByOwner.set(a.owner, a); putRow('ads', a); }
function ads() { return S.ads; }
function liveAds() { return S.ads.filter(a => a.status === 'live'); }
// ---- verified visits / clicks / Boost views ----
function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; }
function addClick(c) { c.id = 'k' + nextId('click'); c.at = c.at || Date.now(); S.clicks.push(c); putRow('clicks', c); return c; }
function addBview(b) { b.id = 'b' + nextId('bview'); b.at = b.at || Date.now(); S.bviews.push(b); putRow('bviews', b); return b; }
const visits = () => S.visits, clicks = () => S.clicks, bviews = () => S.bviews;
// visits + clicks: 15 days (the 24-hour checks, this week's + last week's board); Boost views: 120 days (the delivery audit trail)
function prune() {
const now = Date.now(); let n = 0;
for (const [f, days] of [['visits', 15], ['clicks', 15], ['bviews', 120]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; }
return n;
}
// ---- members ----
function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; }
function upsertMember(addr, patch) {
const a = String(addr).toLowerCase();
const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), via: null, netOk: false });
Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m;
}
function memberByName(name) {
const n = String(name || '').toLowerCase(); if (!n) return null;
for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m;
return null;
}
function members() { return Object.values(S.members); }
// ---- sessions ----
const SESSION_TTL = 7 * 24 * 3600000;
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; }
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
function dropSession(token) { delete S.sessions[token]; save(); }
module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today, ad, adOf, addAd, saveAd, ads, liveAds,
addVisit, addClick, addBview, visits, clicks, bviews, prune, member, upsertMember, memberByName, members, mintSession, session, dropSession, SESSION_TTL };
+72
View File
@@ -0,0 +1,72 @@
// Renders the site art with Playwright (local only): the icon, the OG share image, the Telegram proof cards
// (public/art/proof/vab-proof-{amber,cream,green}.png) and the promo kit (public/art/kit/vab-<angle>-<shape>.png, 3 angles x 7
// shapes, ad-blocker-neutral names). Copy facts come from config.js (Boost price + views) and promokit.js (angles, shapes).
// node tools/art.mjs (PLAYWRIGHT = path to the playwright package)
import fs from 'node:fs';
import path from 'node:path';
import { createRequire } from 'node:module';
import { fileURLToPath } from 'node:url';
const require = createRequire(import.meta.url);
const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright';
const { chromium } = require(PW);
const C = require(path.join(APP, 'config.js')).get();
const { SHAPES } = require(path.join(APP, 'promokit.js'));
const ART = path.join(APP, 'public', 'art');
fs.mkdirSync(path.join(ART, 'kit'), { recursive: true }); fs.mkdirSync(path.join(ART, 'proof'), { recursive: true });
const FONTS = '<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap">';
const BASE = `*{box-sizing:border-box;margin:0}html,body{width:100%;height:100%;overflow:hidden}body{background:#0a1712;color:#e8efe9;font-family:'IBM Plex Sans',sans-serif}
.wm{font-family:'Playfair Display',Georgia,serif;font-weight:900;color:#f4efe3;letter-spacing:-.02em}.mono{font-family:'IBM Plex Mono',monospace}.amber{color:#ffb000}
.tick{background:#000;border-bottom:2px solid #ffb000;color:#ffb000;font-family:'IBM Plex Mono',monospace;white-space:nowrap;overflow:hidden}
.paper{background:#f4efe3;color:#13201a;border-top:6px solid #ffb000}.cta{background:#ffb000;color:#1a1200;font-weight:600;display:inline-block}`;
const views = Number(C.boost.views).toLocaleString('en-US');
const ANG = {
free: { k: 'FREE FOR NETWORK MEMBERS', h: 'Post your text ad free', s: 'It runs on your page and your team\'s pages.', cta: 'Post my free ad' },
spread: { k: 'FIVE LEVELS DEEP', h: 'Your ad on your whole team\'s pages', s: 'Everyone you bring in shows your ad, five levels down.', cta: 'Get my page' },
boost: { k: 'ONE-TIME BOOST', h: '$' + C.boost.usd + ' for ' + views + ' guaranteed views', s: 'Starred on the live ticker. Never a subscription.', cta: 'Boost my ad' }
};
const TICK = '▲ FREE TRAFFIC THAT CONVERTS · ★ BOOSTED: ONE LINK FOR EVERY OFFER · ▲ BUILD A LIST WITH ZERO BUDGET · ▲ ';
function kitHtml(angle, shape, w, h) {
const a = ANG[angle]; const m = Math.min(w, h);
if (shape === 'tile') return `<body style="display:flex;flex-direction:column;justify-content:space-between;padding:9px;border:2px solid #ffb000"><div class="wm" style="font-size:15px">ViralAdBlitz</div><div class="wm" style="font-size:${angle === 'boost' ? 20 : 17}px;line-height:1.02">${angle === 'boost' ? '$' + C.boost.usd + ' = ' + views + ' views' : angle === 'free' ? 'Free text ad' : '5 levels deep'}</div><div class="mono amber" style="font-size:10px">viraladblitz.com</div></body>`;
if (shape === 'strip' || shape === 'leader') {
const big = shape === 'leader';
return `<body style="display:flex;align-items:center;gap:${big ? 18 : 10}px;padding:0 ${big ? 18 : 10}px;border-bottom:3px solid #ffb000"><div class="wm" style="font-size:${big ? 30 : 20}px;flex:0 0 auto">ViralAdBlitz</div><div style="flex:1;min-width:0"><div class="mono amber" style="font-size:${big ? 12 : 9}px;letter-spacing:1px">${a.k}</div><div class="wm" style="font-size:${big ? 24 : 15}px;line-height:1.05;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${a.h}</div></div><div class="cta" style="font-size:${big ? 15 : 11}px;padding:${big ? '10px 14px' : '6px 8px'};flex:0 0 auto">${a.cta}</div></body>`;
}
if (shape === 'tower') return `<body style="display:flex;flex-direction:column"><div class="tick" style="font-size:11px;padding:6px 4px">${TICK}</div><div style="padding:14px;display:flex;flex-direction:column;gap:14px;flex:1"><div class="wm" style="font-size:24px">ViralAdBlitz</div><div class="mono amber" style="font-size:11px;letter-spacing:1px">${a.k}</div><div class="wm" style="font-size:28px;line-height:1.05">${a.h}</div><div style="font-size:14px;color:#b9c8bd;line-height:1.4">${a.s}</div><div class="paper" style="padding:10px;font-size:12px"><b style="font-family:'Playfair Display',serif;font-size:15px">Your headline</b><br>Your two lines. Your link.</div><div style="margin-top:auto"><div class="cta" style="font-size:14px;padding:10px 12px;width:100%;text-align:center">${a.cta}</div><div class="mono amber" style="font-size:10px;margin-top:8px;text-align:center">viraladblitz.com</div></div></div></body>`;
// box, social, square
const f = m / 250;
return `<body style="display:flex;flex-direction:column"><div class="tick" style="font-size:${Math.round(11 * f)}px;padding:${Math.round(6 * f)}px ${Math.round(8 * f)}px">${TICK + TICK}</div>
<div style="flex:1;padding:${Math.round(16 * f)}px;display:flex;flex-direction:column;gap:${Math.round(10 * f)}px;justify-content:center">
<div style="display:flex;align-items:baseline;gap:${Math.round(8 * f)}px"><span class="wm" style="font-size:${Math.round(20 * f)}px">ViralAdBlitz</span><span class="mono amber" style="font-size:${Math.round(9 * f)}px;border:1px solid #ffb000;padding:1px 4px">LIVE</span></div>
<div class="mono amber" style="font-size:${Math.round(10 * f)}px;letter-spacing:1px">${a.k}</div>
<div class="wm" style="font-size:${Math.round((shape === 'social' ? 30 : 26) * f)}px;line-height:1.04">${a.h}</div>
<div style="font-size:${Math.round(12 * f)}px;color:#b9c8bd;line-height:1.4">${a.s}</div>
<div style="display:flex;align-items:center;gap:${Math.round(10 * f)}px;margin-top:${Math.round(4 * f)}px"><span class="cta" style="font-size:${Math.round(12 * f)}px;padding:${Math.round(7 * f)}px ${Math.round(10 * f)}px">${a.cta}</span><span class="mono" style="font-size:${Math.round(10 * f)}px;color:#8fa89a">viraladblitz.com</span></div></div></body>`;
}
function proofHtml(variant) {
const bg = { amber: '#0a1712', cream: '#f4efe3', green: '#0b5d3b' }[variant]; const ink = variant === 'cream' ? '#13201a' : '#f4efe3'; const acc = variant === 'green' ? '#ffd166' : '#ffb000';
return `<body style="background:${bg};color:${ink};display:flex;flex-direction:column"><div class="tick" style="font-size:20px;padding:12px 16px">${TICK + TICK}</div>
<div style="flex:1;padding:48px 60px;display:flex;flex-direction:column;gap:22px;justify-content:center">
<div style="display:flex;align-items:baseline;gap:14px"><span style="font-family:'Playfair Display',serif;font-weight:900;font-size:64px;color:${ink}">ViralAdBlitz</span><span class="mono" style="font-size:18px;color:${acc};border:2px solid ${acc};padding:2px 8px">PAID ON-CHAIN</span></div>
<div style="font-family:'Playfair Display',serif;font-weight:900;font-size:58px;line-height:1.05">A Boost was just paid out on-chain</div>
<div class="mono" style="font-size:24px;color:${acc}">up to 5 sponsor levels x 10% · same transaction</div>
<div style="font-size:22px;opacity:.8">Every Boost and every payout: viraladblitz.com/ledger</div></div></body>`;
}
const ogHtml = () => `<body style="display:flex;flex-direction:column"><div class="tick" style="font-size:20px;padding:12px 16px">${TICK + TICK}</div><div style="flex:1;padding:56px 64px;display:flex;flex-direction:column;gap:20px;justify-content:center">
<div class="mono amber" style="font-size:22px;letter-spacing:3px">THE NETWORK'S TEXT AD WIRE</div><div class="wm" style="font-size:74px;line-height:1.02">Your ad runs on your whole team's pages. Five levels deep.</div>
<div style="display:flex;gap:18px;align-items:center"><span class="cta" style="font-size:26px;padding:14px 22px">Post your free text ad</span><span class="wm" style="font-size:36px">ViralAdBlitz</span></div></div></body>`;
const iconHtml = () => `<body style="display:flex;align-items:center;justify-content:center;background:#0a1712"><img src="data:image/svg+xml;base64,${Buffer.from(fs.readFileSync(path.join(ART, 'mark.svg'))).toString('base64')}" style="width:192px;height:192px"></body>`;
const browser = await chromium.launch(); let made = 0;
async function shot(html, w, h, out) {
const pg = await browser.newPage({ viewport: { width: w, height: h } });
await pg.setContent('<!doctype html><html><head><meta charset="utf-8">' + FONTS + '<style>' + BASE + '</style></head>' + html + '</html>', { waitUntil: 'networkidle' });
await pg.evaluate(() => document.fonts.ready); await pg.screenshot({ path: out, clip: { x: 0, y: 0, width: w, height: h } }); await pg.close(); made++;
}
await shot(iconHtml(), 192, 192, path.join(ART, 'icon-192.png'));
await shot(ogHtml(), 1200, 630, path.join(ART, 'og-share.png'));
for (const v of ['amber', 'cream', 'green']) await shot(proofHtml(v), 1200, 630, path.join(ART, 'proof', 'vab-proof-' + v + '.png'));
for (const angle of Object.keys(ANG)) for (const [shape, [w, h]] of Object.entries(SHAPES)) await shot(kitHtml(angle, shape, w, h), w, h, path.join(ART, 'kit', 'vab-' + angle + '-' + shape + '.png'));
await browser.close();
console.log(made + ' images rendered');
+288
View File
@@ -0,0 +1,288 @@
// Writes public/*.html from one place (the legal.py idea from the trust pack: one source of facts per site). Run after editing:
// node tools/pages.mjs
// Copy rules: no em dashes, no income promises, "Advertising, not income. Nothing is promised.", never an earnings cap,
// wallets = "SafePal or any other crypto wallet" (never recommend MetaMask), one-time Boosts, never a subscription.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const PUB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
const SITE = 'https://viraladblitz.com';
const V = { css: 3, common: 3, page: 3 };
const F = { co: 'TrustClickz', addr: '615 Green Valley Drive, Moody, AL 35004', updated: 'November 14, 2026', boostUsd: 5, views: '500', days: 30 };
const FONTS = 'https://fonts.googleapis.com/css2?family=Playfair+Display:wght@700;900&family=IBM+Plex+Mono:wght@400;600&family=IBM+Plex+Sans:wght@400;600&display=swap';
function head(o) {
const t = o.title, d = o.desc, url = SITE + o.path;
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<title>${t}</title>
<meta name="description" content="${d}">
${o.noindex ? '<meta name="robots" content="noindex">' : `<link rel="canonical" href="${url}">`}
<meta property="og:type" content="website">
<meta property="og:site_name" content="ViralAdBlitz">
<meta property="og:title" content="${t}">
<meta property="og:description" content="${d}">
<meta property="og:url" content="${url}">
<meta property="og:image" content="${SITE}/art/og-share.png">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:alt" content="ViralAdBlitz: the network's text ad wire">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="${t}">
<meta name="twitter:description" content="${d}">
<meta name="twitter:image" content="${SITE}/art/og-share.png">
${o.ld ? '<script type="application/ld+json">' + JSON.stringify(o.ld) + '</script>\n' : ''}<meta name="theme-color" content="#0a1712">
<link rel="icon" type="image/svg+xml" href="/art/mark.svg"><link rel="icon" type="image/png" href="/art/icon-192.png"><link rel="apple-touch-icon" href="/art/icon-192.png">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link rel="stylesheet" href="${FONTS}">
<link rel="stylesheet" href="/assets/vab.css?v=${V.css}">
</head>
<body>
`;
}
const tail = scripts => '<script src="/assets/common.js?v=' + V.common + '"></script>\n' + scripts.map(s => '<script src="/assets/' + s + '?v=' + V.page + '"></script>').join('\n') + '\n</body>\n</html>\n';
const page = (file, o, body, scripts) => fs.writeFileSync(path.join(PUB, file), head(o) + body + tail(scripts));
// ---------------------------------------------------------------- front page
page('index.html', { path: '/', title: 'ViralAdBlitz | Your text ad on your whole team\'s pages, five levels deep',
desc: 'The network\'s text ad wire. Post one free text ad: it shows on your page and on the page of everyone you bring in, five levels down. Live ticker, top ads by verified clicks, a $5 one-time Boost.',
ld: { '@context': 'https://schema.org', '@graph': [{ '@type': 'WebSite', name: 'ViralAdBlitz', url: SITE + '/' }, { '@type': 'Organization', name: 'ViralAdBlitz', url: SITE + '/', logo: SITE + '/art/icon-192.png' }] } }, `<main class="wrap">
<section class="hero">
<div class="copy">
<p class="kicker">The network's text ad wire</p>
<h1>Your ad runs on your whole team's pages. Five levels deep.</h1>
<p class="lead">Write one text ad: a headline, two lines and your link. It shows on your page and on the page of everyone you bring in, and everyone they bring in, five levels down. Free to join for network members.</p>
<div class="row"><a class="cta" href="/my">Post my free text ad</a><a class="btn-line" href="/boost">How a Boost works</a></div>
</div>
<div class="wirebox" aria-label="Today on the wire">
<span class="lab">TODAY ON THE WIRE</span>
<div class="kv"><span>Ad views</span><b id="stViews">0</b></div>
<div class="kv"><span>Verified clicks</span><b id="stClicks">0</b></div>
<div class="kv"><span>Boosts sold</span><b id="stBoosts">0</b></div>
<div class="kv"><span>Ads live</span><b id="stAds">0</b></div>
</div>
</section>
<section id="board">
<div class="shead"><h2>Top ads this week</h2><span class="side">ranked by verified clicks</span></div>
<div class="cards" id="boardCards"><p class="muted">Loading the board...</p></div>
</section>
<section class="steps" aria-label="How it works">
<div class="step"><span class="n">1</span><b>Post one free text ad</b><span>Sign in with your InstantAdPay or LinkSpin account. A headline, two lines and your link.</span></div>
<div class="step"><span class="n">2</span><b>Share your page</b><span>Your page shows your ad and the five people above you. Every visit shows six ads.</span></div>
<div class="step"><span class="n">3</span><b>Your ad spreads down</b><span>Everyone you bring in shows your ad on their page, five levels deep.</span></div>
</section>
<section id="ledger">
<div class="shead"><h2>Live ledger</h2><span class="side">every Boost and every payout, straight from the chain</span></div>
<div class="tscroll"><table class="t" id="ledgerMini"><thead><tr><th>TIME CT</th><th>EVENT</th><th>MEMBER</th><th>POL</th><th>TX</th></tr></thead><tbody><tr><td colspan="5" class="muted">Loading the ledger...</td></tr></tbody></table></div>
<p class="small"><a href="/ledger">Open the full ledger</a></p>
</section>
<section class="box" id="contract">
<div class="txt"><span class="lab">CONTRACT PROOF</span><span class="big">Paid in the same transaction. Nothing held, nothing to withdraw.</span><span class="addr" id="cAddr">Polygon · the contract address shows here once it is live</span></div>
<a class="btn-line" id="cLink" href="/contract">Check the contract</a>
</section>
<p class="muted small">A Boost buys advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
`, ['front.js']);
// ---------------------------------------------------------------- member page
page('member.html', { path: '/', title: 'A member\'s page | ViralAdBlitz', desc: 'Text ads recommended by a ViralAdBlitz member and the five people above them in the network.', noindex: false }, `<main class="wrap">
<p class="kicker" id="who">RECOMMENDED</p>
<div id="own"><p class="muted">Loading...</p></div>
<section>
<div class="shead"><h2 id="teamHead">Also recommended by the team</h2><span class="side">the five people above them in the network</span></div>
<div class="levels" id="levels"></div>
</section>
<section id="boostedSec" hidden>
<div class="shead"><h2>Boosted across the network</h2><span class="side">members who boosted their ad</span></div>
<div class="cards" id="boosted"></div>
</section>
<section class="joinbar" id="join">
<div class="txt"><b id="joinHead">Want your ad on pages like this one?</b><p id="joinText">Join free. Your ad goes on your own page and on every page you bring in, five levels down.</p></div>
<div class="row" style="margin:0"><a class="cta" id="joinBtn" href="/my">Join free</a><a class="btn-line" href="/my">I am a member: sign in</a></div>
</section>
<p class="muted small">Advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
`, ['member.js']);
// ---------------------------------------------------------------- my page
page('my.html', { path: '/my', title: 'My page | ViralAdBlitz', desc: 'Post or edit your free text ad, share your page, and follow your Boost.', noindex: true }, `<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Your desk</p><h1>My page</h1><p class="lead">One free text ad for network members. Share your page and your ad spreads five levels down.</p></div></section>
<section id="signin" hidden>
<div class="card">
<h2>Sign in</h2>
<p>Sign in with your network account. Your username and your sponsor line come with you.</p>
<div class="signin"><a class="cta" id="viaIap" href="/sso/start?mode=go&amp;via=iap&amp;to=%2Fmy">Sign in with InstantAdPay</a><a class="cta" id="viaLs" href="/sso/start?mode=go&amp;via=linkspin&amp;to=%2Fmy">Sign in with LinkSpin</a><button class="btn-line" id="viaWallet" type="button">Sign in with your wallet</button></div>
<p class="small muted">Wallet sign-in works with SafePal or any other crypto wallet. It is a free signature that cannot move funds.</p>
<p class="small">Not in the network yet? <a id="joinLink" href="https://instantadpay.com/" target="_blank" rel="noopener">Join InstantAdPay free</a>, then come back and sign in through it.</p>
</div>
</section>
<section id="dash" hidden>
<div class="stats" id="stats"></div>
<div class="card" id="pageCard" style="margin-top:16px"></div>
<div class="card" id="adCard" style="margin-top:16px">
<h2 id="adHead">Your text ad</h2>
<p class="small" id="adNote">A headline, two lines and your https link. No link shorteners.</p>
<form class="form" id="adForm">
<label class="f">Headline <input id="fHead" maxlength="60" autocomplete="off" required><span class="cnt" id="cHead"></span></label>
<label class="f">First line <input id="fL1" maxlength="90" autocomplete="off" required><span class="cnt" id="cL1"></span></label>
<label class="f">Second line (optional) <input id="fL2" maxlength="90" autocomplete="off"><span class="cnt" id="cL2"></span></label>
<label class="f">Your link <input id="fLink" maxlength="600" autocomplete="off" inputmode="url" placeholder="https://" required></label>
<div class="row" style="margin:0"><button class="btn-green" id="adSave" type="submit">Post my free text ad</button><span class="small muted">Tracking codes work: {clickid} and {placement} are filled on every click.</span></div>
</form>
</div>
<div class="card" id="lineCard" style="margin-top:16px"><h2>Your line</h2><div id="line"></div></div>
<div class="card" id="boostCard" style="margin-top:16px"><h2>Your Boosts</h2><div id="boosts"></div><div class="row"><a class="cta" href="/boost">Boost my ad</a></div></div>
<div class="card" id="earnCard" style="margin-top:16px"><h2>Paid to you</h2><div id="earned"></div></div>
<div class="row"><button class="btn-quiet" id="signout" type="button">Sign out</button></div>
</section>
<div id="status" class="note" hidden></div>
</main>
`, ['wallet.js', 'my.js']);
// ---------------------------------------------------------------- boost
page('boost.html', { path: '/boost', title: 'Boost | ViralAdBlitz', desc: 'A $5 one-time Boost buys 500 guaranteed network views for your text ad, a starred spot on the live ticker and extra places on member pages. Split on-chain five levels up your line.' }, `<main class="wrap">
<section class="hero" style="align-items:stretch">
<div class="copy" style="display:flex;flex-direction:column;gap:14px">
<p class="kicker">One-time, never a subscription</p>
<h1>Boost your text ad across the network</h1>
<p class="lead" style="margin:0">A Boost puts your ad in front of more people: <b id="bViews">500</b> guaranteed network views, a starred spot on the live ticker, and an extra place on the five-level pages. Paid in POL on Polygon.</p>
<p class="small muted" style="margin:0">Views count only from verified visitors: a real browser that keeps the page open and visible for a few seconds, once per visitor per day. If the views are not all delivered on ViralAdBlitz within <span id="bDays">30</span> days, the rest is finished through Network Ad Space.</p>
</div>
<div class="price">
<span class="lab">BOOST PACK</span>
<span class="amt" id="bUsd">$5</span>
<span class="pol" id="bPol">about ... POL at today's price</span>
<ul><li><span id="bViews2">500</span> guaranteed network views</li><li>Starred spot on the live ticker</li><li>Extra place on the five-level pages</li></ul>
<label class="qty">How many <select id="bQty"></select></label>
<button type="button" class="btn-green" id="bBuy">Boost with SafePal or any other crypto wallet</button>
<span class="small" id="bWho" style="color:var(--paper-sub)"></span>
</div>
</section>
<section>
<div class="shead"><h2>Where each Boost goes, in the same transaction</h2></div>
<div class="splits">
<div class="split"><span>LEVEL 1</span><b>10%</b><i>your sponsor</i></div>
<div class="split"><span>LEVEL 2</span><b>10%</b><i>their sponsor</i></div>
<div class="split"><span>LEVEL 3</span><b>10%</b><i>next up</i></div>
<div class="split"><span>LEVEL 4</span><b>10%</b><i>next up</i></div>
<div class="split"><span>LEVEL 5</span><b>10%</b><i>next up</i></div>
<div class="split co"><span>COMPANY</span><b>50%</b><i>runs the network</i></div>
</div>
<p class="sub" style="max-width:820px">Levels follow your sponsor line in the network. Someone in your line who has not bought a Boost is passed over, and their share goes up to the next person who has. The contract looks up to 20 places up the line; a share nobody qualifies for goes to the company. Nothing is held and there is nothing to withdraw. A Boost buys advertising, not income: you are paid only when people in your team buy Boosts, and nothing is promised.</p>
</section>
<section class="box">
<div class="txt"><span class="lab">YOUR LINE IS SET ONCE</span><span class="big">Your sponsor line comes from the network hub.</span><span class="sub">On your first Boost the site signs your line and the contract records it. After that it never changes, so every later Boost pays the same people.</span></div>
</section>
<section style="display:flex;flex-wrap:wrap;gap:32px;align-items:flex-start">
<div style="flex:999 1 460px;min-width:0;display:flex;flex-direction:column;gap:10px">
<h2>Every sale is posted in Telegram</h2>
<p class="sub" style="margin:0">Each Boost posts a card to the network's Telegram with the week's stats and a link to verify the transaction, and every payout gets its own line. The same events show as toasts on the site and rows in the live ledger.</p>
</div>
<div class="card" style="flex:1 1 360px"><span class="small muted">Telegram · payments topic</span><p style="margin:8px 0 0"><b style="font-family:var(--disp);color:var(--cream);font-size:20px">ViralAdBlitz</b><br><span class="mono" style="color:var(--amber)">@member boosted an ad</span><br><span class="mono small">This week: Boosts, ads live, verified clicks</span></p><p class="small">Level payouts in the same transaction. <a href="/ledger">Verify</a></p></div>
</section>
<div id="status" class="note" hidden></div>
</main>
`, ['wallet.js', 'buy.js', 'boost.js']);
// ---------------------------------------------------------------- ledger
page('ledger.html', { path: '/ledger', title: 'Live Ledger | ViralAdBlitz', desc: 'Every ViralAdBlitz Boost and every level payout, read from the Polygon contract, with a link to verify each transaction.' }, `<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Straight from the chain</p><h1>Live ledger</h1><p class="lead">Every Boost and every payout. Each row links to its transaction on Polygonscan, so you can check it yourself.</p></div></section>
<div class="stats" id="totals"></div>
<section>
<div class="tscroll"><table class="t" id="rows"><thead><tr><th>TIME CT</th><th>BOOST</th><th>PAID IN THE SAME TRANSACTION</th><th>TX</th></tr></thead><tbody><tr><td colspan="4" class="muted">Loading the ledger...</td></tr></tbody></table></div>
</section>
<p class="muted small">Levels follow the buyer's sponsor line. Someone who has not bought a Boost is passed over and their share goes up to the next person who has. Advertising, not income. Nothing is promised.</p>
<div id="status" class="note" hidden></div>
</main>
`, ['ledger.js']);
// ---------------------------------------------------------------- contract
page('contract.html', { path: '/contract', title: 'Contract Proof | ViralAdBlitz', desc: 'The ViralAdBlitz Boost contract on Polygon: owner, company, keeper and the fixed five-level split, read live from the chain.' }, `<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Read live from Polygon</p><h1>Contract proof</h1><p class="lead">Every Boost is paid to one smart contract on Polygon. It splits the payment in the same transaction. Check every number here yourself.</p></div></section>
<div class="card"><h2>The contract</h2><table class="facts" id="facts"><tbody><tr><td class="muted">Reading the contract...</td></tr></tbody></table></div>
<section>
<div class="shead"><h2>Where each Boost goes</h2></div>
<div class="splits">
<div class="split"><span>LEVEL 1</span><b>10%</b><i>nearest qualified</i></div><div class="split"><span>LEVEL 2</span><b>10%</b><i>next qualified</i></div>
<div class="split"><span>LEVEL 3</span><b>10%</b><i>next qualified</i></div><div class="split"><span>LEVEL 4</span><b>10%</b><i>next qualified</i></div>
<div class="split"><span>LEVEL 5</span><b>10%</b><i>next qualified</i></div><div class="split co"><span>COMPANY</span><b>50%</b><i>plus any share nobody qualifies for</i></div>
</div>
<p class="sub">The percentages are constants in the contract code: nobody can change who gets what share. There is no owner withdraw. The contract keeps nothing: if a payment cannot be delivered, it waits in the contract for that wallet to claim, and nobody else can take it. Anything sent above the price comes back in the same transaction.</p>
</section>
<div class="card"><h2>Check it yourself</h2><ol class="sub">
<li>Open the contract on Polygonscan (link above) and read its verified source code.</li>
<li>Choose <b>Read Contract</b> and compare owner, company and keeper with this page.</li>
<li>Open any Boost in the <a href="/ledger">live ledger</a> and look at its <b>Logs</b>: one Purchase event, one Paid event per level and one for the company, and a PassedOver event for anyone in the line who had not boosted.</li>
</ol></div>
<div id="status" class="note" hidden></div>
</main>
`, ['contract.js']);
// ---------------------------------------------------------------- promote
page('promote.html', { path: '/promote', title: 'Promote | ViralAdBlitz', desc: 'Your ViralAdBlitz links, creatives in every common size, and copy you can paste anywhere.' }, `<main class="wrap">
<section class="hero"><div class="copy"><p class="kicker">Share the wire</p><h1>Promote ViralAdBlitz</h1><p class="lead">Your links, creatives in every common size, and copy you can paste anywhere. Everything carries your network username.</p></div></section>
<div class="card" id="whoCard"><h3>Your network username</h3>
<p class="small" id="whoNote">Your InstantAdPay or LinkSpin username works here. Sign in on <a href="/my">My page</a> and it fills in by itself.</p>
<form class="kit-who" id="whoForm"><input id="whoIn" autocomplete="off" spellcheck="false" maxlength="42" placeholder="your username"><button class="cta" type="submit">Use it</button></form></div>
<div id="status" class="note" hidden></div>
<div id="kit" style="display:flex;flex-direction:column;gap:16px"><p class="muted">Loading the kit...</p></div>
</main>
`, ['kitpage.js', 'promote.js']);
// ---------------------------------------------------------------- admin
page('admin.html', { path: '/admin', title: 'Admin | ViralAdBlitz', desc: 'ViralAdBlitz admin.', noindex: true }, `<main class="wrap">
<section class="hero"><div class="copy"><h1>Admin</h1></div></section>
<div class="card"><form class="kit-who" id="tokForm"><input id="tok" type="password" autocomplete="off" placeholder="admin token"><button class="cta" type="submit">Load</button></form></div>
<div class="card"><h3>Status</h3><pre class="kit-pre" id="statusOut">Enter the token.</pre></div>
<div class="card"><h3>Boosts</h3><div class="tscroll"><table class="t" id="boostRows"><tbody></tbody></table></div></div>
<div class="card"><h3>Member lookup</h3><form class="kit-who" id="lookForm"><input id="look" placeholder="wallet, #ad id or username"><button class="cta" type="submit">Look up</button></form><pre class="kit-pre" id="lookOut"></pre></div>
<div class="card"><h3>Ad status</h3><form class="kit-who" id="adForm"><input id="adId" placeholder="ad id"><input id="adStatus" placeholder="live | paused | removed"><input id="adNoteIn" placeholder="note"><button class="cta" type="submit">Set</button></form></div>
<div class="card"><h3>Old site links</h3><p class="small">JSON file {"oldrefs": {"old username": "network username"}} replaces the whole map.</p><input type="file" id="oldFile" accept="application/json"><pre class="kit-pre" id="oldOut"></pre></div>
<div id="status" class="note" hidden></div>
</main>
`, ['admin.js']);
// ---------------------------------------------------------------- legal (one source of facts)
const legal = (file, p, title, lead, cards) => page(file, { path: p, title: title + ' | ViralAdBlitz', desc: lead }, `<main class="wrap legal">
<section class="hero"><div class="copy"><h1>${title}</h1><p class="lead">${lead}</p><p class="muted small">Last updated ${F.updated}</p></div></section>
${cards.map(c => ` <div class="card"><h2>${c[0]}</h2>${c[1]}</div>`).join('\n')}
</main>
`, ['static.js']);
const CONTACT = ['Contact', `<p>Questions, problems or a request about your data: <a href="https://instantadpay.com/support" target="_blank" rel="noopener">network support</a>, or write to ${F.co}, ${F.addr}.</p>`];
legal('terms.html', '/terms', 'Terms and Conditions', 'The rules for using ViralAdBlitz, in plain English.', [
['Who we are', `<p>ViralAdBlitz (viraladblitz.com) is run by ${F.co}, ${F.addr}. It is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, Stack POL and Earners Corner. By using ViralAdBlitz you agree to these terms.</p>`],
['What ViralAdBlitz is', `<p>ViralAdBlitz is the network's home for text ads. A network member posts one text ad: a headline, two lines and a link. Each member has a page that shows their own ad and the ads of the five people above them in their network sponsor line, so an ad appears on the pages of the people its owner brings in, five levels down. The front page shows a live ticker of the newest ads and a weekly board of the top ads by verified clicks.</p>`],
['Your free text ad', `<p>One text ad is free for each network member (InstantAdPay or LinkSpin, checked with the network hub). You can edit it at any time. There is nothing to pay to post it.</p>`],
['What a Boost is', `<p>A Boost is a single, one-time purchase of $${F.boostUsd} for your text ad. It buys ${F.views} guaranteed network views, a starred spot on the live ticker while the views are delivered, and an extra place on member pages. You can buy more than one; each adds its own ${F.views} views.</p><p>A view counts only from a verified visitor: a real browser that keeps a ViralAdBlitz page open and visible for a few seconds, once per visitor per ad each day, never your own views, never bots. Views are delivered on ViralAdBlitz pages first. If a Boost's views are not all delivered within ${F.days} days, the rest is delivered through Network Ad Space, a network ad site, as a text ad with the same headline, lines and link.</p><p>Boosts are paid in POL on Polygon at the live Chainlink POL/USD price the contract reads when you buy. Anything you send above the price comes back to you in the same transaction. Nothing renews and nothing is ever billed again. There are no subscriptions.</p><p>What you buy is advertising for your own text ad. It is not income, an investment or a share of anything.</p>`],
['How a payment is split', `<p>The ViralAdBlitz contract splits each Boost in the same transaction it is paid: 10% to each of five levels up the buyer's sponsor line and 50% to ViralAdBlitz.</p><p>Only someone who has bought at least one Boost can receive a level share. Someone in the line who has not is passed over, and the share goes up to the next person who has. The contract looks up to 20 places up the line for five such people; a share nobody qualifies for goes to ViralAdBlitz.</p><p>Your sponsor line comes from the network hub. On your first Boost the site signs it and the contract records it link by link. A link already recorded is never changed, so every later Boost pays along the same line. Members of the line without a wallet in the network cannot receive payments and are left out of the recorded line.</p><p>The split is fixed in the contract code and there is no owner withdraw. The contract keeps nothing: each share goes straight to the person's wallet in the buyer's transaction. If a payment cannot be delivered, it waits in the contract for that wallet to claim, and nobody else can take it.</p>`],
['Nothing is promised', `<p>We do not promise or guarantee any income, payout or result. A level share is paid only when someone in your team chooses to buy a Boost. Read the <a href="/disclaimer">Earnings Disclaimer</a>.</p>`],
['No refunds', `<p>Payments are made on the blockchain and are final once confirmed. We cannot reverse, cancel or refund them. Check the amount before you confirm in your wallet. If your ad is removed for breaking these terms, the views left on its Boosts are not delivered or refunded.</p>`],
['Crypto risk', `<ul><li>The price of POL moves. The dollar value of a payment can be higher or lower later than when it was paid.</li><li>You are responsible for your wallet and its recovery phrase. Nobody, including us, can recover a lost wallet or reverse a payment sent from it.</li><li>Blockchain transactions are final. Each one costs a small network fee (gas) in POL, paid to the network, not to us.</li><li>Use SafePal or any other crypto wallet you trust, and never share your recovery phrase with anyone. We will never ask for it.</li></ul>`],
['Text ad rules', `<p>Your ad and its link must be your own or ones you have the right to use, and the link must lead to a lawful page that loads. No adult content, malware, phishing, deceptive offers, hate, or anything illegal where you or your visitors live. No link shorteners. We may pause or remove an ad that breaks these rules and close the account behind it.</p>`],
['Fair use', `<p>Views and clicks count only from verified visitors, and only a few visitors per internet connection count each day. Bots, crawlers and repeat visits do not count. We may refuse visits or clicks we judge not to be real, and may remove anyone who fakes traffic from the board. Do not try to break, overload or game the site.</p>`],
['Your account', `<p>You sign in with your wallet or through InstantAdPay or LinkSpin. Your network account, username and sponsor are shared across the network through the network hub, as described in the <a href="/privacy">Privacy Policy</a>. You must be old enough to make a binding agreement where you live, and using crypto must be legal there.</p>`],
['The service', `<p>The site is provided as it is. We work to keep it running but cannot promise it will always be available or free of errors. The smart contract runs on Polygon on its own; its rules are public and can be checked on the <a href="/contract">contract page</a>. We may change features, the price of future Boosts or these terms; changes apply from the date they are posted here.</p>`],
['Limits', `<p>As far as the law allows, we are not responsible for losses caused by the blockchain, your wallet, the price of POL, third-party websites in ads, or events outside our control, and our total responsibility to you is limited to what you paid for the purchase in question. These terms are governed by the laws of the State of Alabama, USA.</p>`],
CONTACT]);
legal('disclaimer.html', '/disclaimer', 'Earnings Disclaimer', 'Advertising, not income. Nothing is promised.', [
['What you are buying', `<p>A ViralAdBlitz Boost is advertising for your own text ad: guaranteed views, a ticker spot and member-page places. It is not an investment, a business opportunity, a share of profits or a promise of any payment.</p>`],
['Level shares are not promised', `<p>The contract pays a level share only when someone in your team chooses to buy a Boost. Nobody is required to buy one, and we do not know or promise whether anyone in your team ever will. Many members receive nothing, and many receive less than they spend. Your results depend on other people's free choices, not on anything we do.</p>`],
['No examples are promises', `<p>Any number on this site, in the ledger or in a Telegram post shows what really happened in one transaction. It is not a typical result and not a forecast of what you will receive.</p>`],
['Prices and taxes', `<p>Boosts are priced in US dollars and paid in POL, whose price moves. Anything you receive is in POL and its dollar value can change. You are responsible for any taxes on what you receive where you live.</p>`],
['Who to ask', `<p>${F.co}, ${F.addr}. <a href="https://instantadpay.com/support" target="_blank" rel="noopener">Network support</a>.</p>`]]);
legal('privacy.html', '/privacy', 'Privacy Policy', 'What ViralAdBlitz keeps about you, why, and for how long.', [
['Who we are', `<p>ViralAdBlitz is run by ${F.co}, ${F.addr}.</p>`],
['What we keep', `<ul><li>Your wallet address and network username, and your text ad (it is public: that is its purpose).</li><li>Your network record from the network hub: your hub id and your sponsor line. ViralAdBlitz does not store your email. When you sign in through InstantAdPay or LinkSpin, your email is used once to check your network membership and is not kept.</li><li>Your Boosts, which are public on the Polygon blockchain, and how many of their views have been delivered.</li><li>For counting real views and clicks: a one-way code made from your internet address and browser type (never the address itself), the page, and the site that sent you. Visit and click records are kept 15 days; the records of each view counted toward a Boost are kept 120 days so delivery can be checked.</li></ul>`],
['Cookies', `<p>A sign-in cookie (7 days), a cookie that remembers whose page you came from (30 days), and short-lived cookies for signing in through the network. No advertising or tracking cookies of our own.</p>`],
['Who else sees data', `<ul><li>The Polygon blockchain: every Boost and payment is public there, by its nature.</li><li>The network hub, which keeps one record per person across the network sites (username, wallet, sponsor).</li><li>Our Telegram payments topic: each Boost is posted with the buyer's username (or a shortened wallet) and the amounts paid.</li><li>Services the pages load: Google Fonts, WalletConnect (Reown) when you connect a wallet, LinkSpin network ad zones, and Network Ad Space for finishing Boost views.</li></ul><p>We do not sell personal data.</p>`],
['Your choices', `<p>You can edit your ad at any time, or ask us to remove it and your account here. Records on the blockchain cannot be removed by anyone.</p>`],
CONTACT]);
console.log('pages written');
+66
View File
@@ -0,0 +1,66 @@
// Boost finishing through Network Ad Space (the Downline Banners dlbnas.js pattern, Marty's Boost rule 2026-11-14: "if a Boost
// can't be delivered on-site within 30 days, finish it through the network"). NAS is Marty's own EvolutionScript site; its MySQL
// is the API (InstantAdPay nas.js: INSERT payments, then sponsorads approved=1, pid 1 = TEXT ad, read `remaining` back).
// Why NAS and not LinkSpin zones: NAS serves text ads natively (Subject + Body + link), LinkSpin zones are banner placements.
// - A Boost past its deliverDays with views still owed gets ONE NAS text ad for exactly the views still owed (headline = Subject,
// the two lines = Body, link = viraladblitz.com/go/<ad>?p=nas so the clicks count here too). What NAS serves counts toward
// the Boost's guarantee (served = assigned - remaining, clamped; the InstantAdPay counter rules).
// - On-site views keep counting meanwhile; a Boost is done when on-site + NAS >= its guaranteed views. Over-delivery is fine.
// State in vab-nas.json (a MySQL document through docstore). Inert unless NAS_DB_* are set (tests inject a stand-in query).
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const cfgMod = require('./config');
const CATID_CRYPTO = 5;
let pool = null, S = null, R = null, q = null;
const on = () => !!(q || (process.env.NAS_DB_HOST && process.env.NAS_DB_USER && process.env.NAS_DB_PASSWORD && process.env.NAS_DB_NAME));
const FILE = () => path.join(cfgMod.get().dataDir, 'vab-nas.json');
function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = {}; } S.boosts = S.boosts || {}; return S; }
function save() { try { fs.writeFileSync(FILE(), JSON.stringify(load())); } catch (e) { console.error('vabnas save', e.message); } }
function dbq(sql, args) {
if (q) return q(sql, args);
if (!pool) pool = require('mysql2/promise').createPool({ host: process.env.NAS_DB_HOST, user: process.env.NAS_DB_USER, password: process.env.NAS_DB_PASSWORD,
database: process.env.NAS_DB_NAME, port: Number(process.env.NAS_DB_PORT || 3306), connectionLimit: 2, connectTimeout: 10000 });
return pool.query(sql, args).then(r => r[0]);
}
async function push({ subject, body, link, assigned, ref }) {
const token = 'vab_' + crypto.randomBytes(8).toString('hex'); const now = new Date(); const edate = new Date(now.getTime() + 60 * 86400000);
const pay = await dbq('INSERT INTO payments (Username, Amount, Currency_code, status, Date, pay_address) VALUES (?,?,?,1,?,?)', [token, 0, 'VAB', now, ref]);
try {
const ad = await dbq(`INSERT INTO sponsorads (Username, Subject, Body, WebsiteURL, assigned, remaining, hits, approved, Date, adtype, Name, Email, PaymentDetails, EDate, sp, width, height, BannerURL, pid, ref_by, catid)
VALUES (?,?,?,?,?,?,0,1,?,1,?,?,?,?,'','','',NULL,1,0,?)`,
[token, subject, body, link, assigned, assigned, now, 'ViralAdBlitz', 'ads@viraladblitz.com', ref, edate, CATID_CRYPTO]);
return { id: ad.insertId, assigned };
} catch (e) { try { await dbq('DELETE FROM payments WHERE ID=?', [pay.insertId]); } catch (x) {} throw e; }
}
async function served(id) { const r = await dbq('SELECT assigned, remaining FROM sponsorads WHERE ID=?', [Number(id)]); if (!r.length) return null; return Math.max(0, Math.min(Number(r[0].assigned), Number(r[0].assigned) - Number(r[0].remaining))); }
async function tick() {
if (!on() || !R) return { off: true };
const c = cfgMod.get(); const s = load(); const site = 'https://' + c.site; let placed = 0;
try {
for (const b of R.boosts()) {
const rec = s.boosts[b.key];
if (rec) { const sv = await served(rec.id); if (sv != null) rec.served = sv; continue; }
if (!b.adId || !b.dueAt || Date.now() < b.dueAt) continue;
const owed = R.remaining(b); if (owed <= 0) continue;
const a = R.ad(b.adId); if (!a || a.status !== 'live') continue;
const ad = await push({ subject: String(a.headline).slice(0, 60), body: [a.line1, a.line2].filter(Boolean).join(' ').slice(0, 200), link: site + '/go/' + a.id + '?p=nas', assigned: owed, ref: 'vab_boost:' + b.key });
s.boosts[b.key] = Object.assign(ad, { served: 0, at: Date.now(), adId: a.id }); placed++;
console.log('vabnas: Boost', b.key.slice(0, 14), 'finishing', owed, 'views in NAS, ad', ad.id);
}
s.lastOk = Date.now(); delete s.lastErr;
} catch (e) { s.lastErr = String(e.message).slice(0, 200); console.error('vabnas', e.message); }
save(); return { placed };
}
const boostServed = key => { const r = load().boosts[String(key)]; return r ? (r.served || 0) : 0; };
// deps: { boosts: () => [boost], remaining: b => n, ad: id => ad }; opts.query = a stand-in for tests
function init(deps, opts) {
R = deps; if (opts && opts.query) q = opts.query;
if (!on()) { console.log('vabnas: off (no NAS_DB_*)'); return; }
load(); setTimeout(() => tick().catch(() => {}), 30000).unref(); setInterval(() => tick().catch(() => {}), 6 * 3600000).unref();
}
function view() { const s = load(); return { on: on(), boosts: s.boosts, lastOk: s.lastOk || null, lastErr: s.lastErr || null }; }
module.exports = { init, tick, boostServed, view, on, _reset: () => { S = null; q = null; } };
+152
View File
@@ -0,0 +1,152 @@
// The engine: verified visitors, verified ad views, verified clicks, Boost delivery and what each page shows.
// - A page load gets a ticket listing the ads it showed (server side, never what the browser claims). After the page has been
// visible visitSeconds the browser redeems it: the visitor is verified (bots, early sends, the per-IP cap filtered, the VBB
// rules) and each ad shown gets one verified view, once per visitor per ad per 24 h. The ad owner's own views never count.
// - A Boost (the chain's Purchase event, shop.js) guarantees `views` verified views for one text ad. Its views are counted here
// and every one is kept as a row (vab_bviews: the delivery audit trail). Several Boosts on one ad fill oldest first.
// - Where Boost views come from: every ViralAdBlitz page (the ticker on every page, the "Top ads" board, member pages, whose
// Boosted places pick the Boosts furthest behind first). A Boost not delivered on-site within deliverDays (30) is finished
// through Network Ad Space as a text ad (vabnas.js); NAS impressions count toward the same guarantee.
// - Verified click: /go/<ad> with the visitor's verified token (issued when their visit verified), once per visitor per ad per
// 24 h, never the owner's own. The "Top ads this week" board ranks by verified clicks (Central-time week).
'use strict';
const crypto = require('crypto');
const cfgMod = require('./config');
const store = require('./store');
const C = () => cfgMod.get();
const H24 = 24 * 3600000;
let nasServed = () => 0; // vabnas.js: NAS impressions served for a Boost (by purchase key)
function init(o) { if (o && o.nasServed) nasServed = o.nasServed; rebuild(); }
// ---- indexes (rebuilt from rows at boot) ----
const lastVisitByVk = new Map(), ipVks = new Map(), viewSeen = new Map(), bviewSeen = new Map(), clickSeen = new Map();
function rebuild() {
lastVisitByVk.clear(); ipVks.clear(); bviewSeen.clear(); clickSeen.clear();
const cut = Date.now() - H24;
for (const v of store.visits()) if (v.at >= cut) { lastVisitByVk.set(v.vk, v.at); ipAdd(v.iph, v.vk, v.at); }
for (const b of store.bviews()) if (b.at >= cut) bviewSeen.set(b.vk + '|' + b.adId, b.at);
for (const c of store.clicks()) if (c.at >= cut && c.verified) clickSeen.set(c.vk + '|' + c.adId, c.at);
}
function ipAdd(iph, vk, at) { let m = ipVks.get(iph); if (!m) ipVks.set(iph, m = new Map()); m.set(vk, at); }
const fresh = (m, k) => { const t = m.get(k); return t && Date.now() - t < H24; };
// ---- Boosts ----
function purchases() { return Object.entries(store.state().purchases || {}).map(([key, x]) => Object.assign({ key }, x)); }
const delivered = b => (b.delivered || 0) + (nasServed(b.key) || 0);
const remaining = b => Math.max(0, (b.views || 0) - delivered(b));
function boostsOf(adId) { return purchases().filter(b => b.adId === Number(adId)).sort((a, b) => (a.at || 0) - (b.at || 0)); }
function activeBoost(adId) { return boostsOf(adId).find(b => remaining(b) > 0) || null; }
function activeBoosts() { const out = []; for (const b of purchases()) if (b.adId && remaining(b) > 0) { const a = store.ad(b.adId); if (a && a.status === 'live') out.push(b); } return out.sort((a, b) => (a.at || 0) - (b.at || 0)); }
function boostedAdIds() { return new Set(activeBoosts().map(b => b.adId)); }
// a newly credited Boost: which ad it is for (the ad named in `ref` if the buyer owns it, else the buyer's live ad; none = attached
// when they post one, see attachPending)
function attach(rec) {
const a = store.ad(Number(rec.ref)); const own = a && a.owner === rec.buyer && a.status !== 'removed' ? a : store.adOf(rec.buyer);
rec.adId = own ? own.id : null; rec.delivered = rec.delivered || 0; rec.dueAt = (rec.blockAt ? rec.blockAt * 1000 : rec.at) + C().deliverDays * 86400000;
return rec.adId;
}
function attachPending(owner, adId) {
let n = 0; for (const x of Object.values(store.state().purchases || {})) if (x.buyer === owner && !x.adId) { x.adId = adId; n++; }
if (n) store.save(); return n;
}
function boostView(b) {
const nas = nasServed(b.key) || 0;
return { key: b.key, tx: String(b.key).split(':')[0], orderId: b.orderId, at: (b.blockAt ? b.blockAt * 1000 : b.at) || null, adId: b.adId || null, qty: b.qty, views: b.views,
onSite: b.delivered || 0, nas, delivered: delivered(b), remaining: remaining(b), dueAt: b.dueAt || null, finishedAt: b.finishedAt || null,
status: remaining(b) === 0 ? 'delivered' : !b.adId ? 'waiting-for-ad' : (b.dueAt && Date.now() > b.dueAt ? 'finishing-in-network' : 'delivering') };
}
// pick k Boosted ads for limited places: furthest behind first (delivered share, then oldest), a little shuffle among the
// first 3k so two pages loaded together do not show the same ones
function pickBoosted(k, exclude) {
if (k <= 0) return [];
const ex = exclude || new Set(); const seen = new Set(); const list = [];
for (const b of activeBoosts()) { if (ex.has(b.adId) || seen.has(b.adId)) continue; seen.add(b.adId); list.push(b); }
list.sort((a, b) => delivered(a) / a.views - delivered(b) / b.views || (a.at || 0) - (b.at || 0));
const pool = list.slice(0, k * 3);
for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [pool[i], pool[j]] = [pool[j], pool[i]]; }
return pool.slice(0, k).sort((a, b) => delivered(a) / a.views - delivered(b) / b.views).map(b => store.ad(b.adId)).filter(Boolean);
}
// ---- what pages show ----
function adCard(a, boosted) {
const m = store.member(a.owner);
return { id: a.id, headline: a.headline, line1: a.line1, line2: a.line2 || '', host: hostOf(a.link), href: '/go/' + a.id, owner: m && m.username ? '@' + m.username : short(a.owner), boosted: !!boosted };
}
const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : '';
const hostOf = l => { try { return new URL(l).hostname.replace(/^www\./, ''); } catch (e) { return ''; } };
// the live ticker on every page: Boosted ads (starred) woven between the newest ads
function ticker() {
const boosted = boostedAdIds();
const star = pickBoosted(C().tickerBoosts, null);
const starIds = new Set(star.map(a => a.id));
const newest = store.liveAds().slice().sort((a, b) => b.createdAt - a.createdAt).filter(a => !starIds.has(a.id)).slice(0, C().tickerNewest);
const out = []; let i = 0, j = 0;
while (i < star.length || j < newest.length) { if (i < star.length) out.push(adCard(star[i++], true)); if (j < newest.length) out.push(adCard(newest[j++], boosted.has(newest[j - 1].id))); if (j < newest.length) out.push(adCard(newest[j++], boosted.has(newest[j - 1].id))); }
return out;
}
// this week's verified clicks per ad (Central-time week). Ties: whoever reached the count first.
function board(week, n) {
const wk = week || store.ctWeek(); const per = new Map();
for (const c of store.clicks()) { if (!c.verified || c.wk !== wk) continue; const p = per.get(c.adId) || per.set(c.adId, { adId: c.adId, clicks: 0, lastAt: 0 }).get(c.adId); p.clicks++; if (c.at > p.lastAt) p.lastAt = c.at; }
const boosted = boostedAdIds();
const rows = [...per.values()].map(p => ({ p, a: store.ad(p.adId) })).filter(x => x.a && x.a.status === 'live')
.sort((x, y) => y.p.clicks - x.p.clicks || x.p.lastAt - y.p.lastAt).slice(0, n || C().boardSize);
return { week: wk, items: rows.map((x, i) => Object.assign(adCard(x.a, boosted.has(x.a.id)), { rank: i + 1, clicks: x.p.clicks })) };
}
function weekStats(week) {
const wk = week || store.ctWeek(); let vclicks = 0; for (const c of store.clicks()) if (c.verified && c.wk === wk) vclicks++;
let boosts = 0; for (const b of purchases()) if (store.ctWeek(b.blockAt ? b.blockAt * 1000 : b.at) === wk) boosts += Number(b.qty) || 1;
return { week: wk, boosts, vclicks, adsLive: store.liveAds().length };
}
// ---- verified visitors ----
// ok: a visitor already verified in the last 24 h, or a new one while the connection has fewer than perIpDay browsers
function canVisit(vk, iph) {
if (fresh(lastVisitByVk, vk)) return { ok: true, again: true };
const m = ipVks.get(iph); let n = 0; if (m) for (const [k, t] of m) { if (Date.now() - t < H24) n++; else m.delete(k); }
return n >= C().perIpDay ? { ok: false, why: 'ip' } : { ok: true };
}
// t = { vk, iph, page, ref, src, shown: [adId], viewer: address | null }. -> { verified, why?, views, boostViews }
function verify(t) {
const chk = canVisit(t.vk, t.iph); if (!chk.ok) return { verified: false, why: chk.why };
const now = Date.now(); const day = store.ctDay(now), wk = store.ctWeek(now);
if (!chk.again) { lastVisitByVk.set(t.vk, now); ipAdd(t.iph, t.vk, now); store.addVisit({ at: now, vk: t.vk, iph: t.iph, page: t.page, ref: t.ref || null, src: t.src || '', wk, day }); store.state().totals.visits++; store.bump('visits'); }
let views = 0, boostViews = 0;
for (const id of new Set(t.shown || [])) {
const a = store.ad(id); if (!a || a.status !== 'live' || (t.viewer && a.owner === t.viewer)) continue;
const k = t.vk + '|' + a.id;
if (!fresh(viewSeen, k)) { viewSeen.set(k, now); if (viewSeen.size > 300000) viewSeen.clear(); a.views = (a.views || 0) + 1; views++; store.saveAd(a); }
const b = activeBoost(a.id);
if (b && !fresh(bviewSeen, k)) {
bviewSeen.set(k, now); const rec = store.state().purchases[b.key];
rec.delivered = (rec.delivered || 0) + 1; if (remaining(Object.assign({ key: b.key }, rec)) === 0 && !rec.finishedAt) rec.finishedAt = now;
store.addBview({ at: now, vk: t.vk, adId: a.id, boost: b.key, page: t.page, day }); boostViews++;
}
}
if (views) { store.state().totals.views += views; store.bump('views', views); }
if (boostViews) { store.state().totals.boostViews += boostViews; store.bump('boostViews', boostViews); }
store.save();
return { verified: true, views, boostViews };
}
// a click on /go/<ad>. verifiedVisitor = the visitor's token checked out. -> { verified }
function click(a, vk, verifiedVisitor, viewer, placement) {
a.clicks = (a.clicks || 0) + 1; store.state().totals.clicks++; store.bump('clicks');
let verified = false;
if (verifiedVisitor && fresh(lastVisitByVk, vk) && !(viewer && viewer === a.owner)) {
const k = vk + '|' + a.id;
if (!fresh(clickSeen, k)) {
clickSeen.set(k, Date.now()); verified = true; a.vclicks = (a.vclicks || 0) + 1; store.state().totals.vclicks++; store.bump('vclicks');
store.addClick({ vk, adId: a.id, verified: true, p: String(placement || '').slice(0, 20), wk: store.ctWeek(), day: store.ctDay() });
}
}
store.saveAd(a); return { verified };
}
// the visitor's verified token (HMAC of the visitor key + the day): sent with clicks after their visit verified
let SECRET = crypto.randomBytes(16).toString('hex');
function setSecret(s) { SECRET = String(s); }
const vtoken = vk => crypto.createHmac('sha256', SECRET).update('vt|' + vk + '|' + store.ctDay()).digest('hex').slice(0, 24);
const vtokenOk = (vk, t) => typeof t === 'string' && t.length === 24 && crypto.timingSafeEqual(Buffer.from(t), Buffer.from(vtoken(vk)));
module.exports = { init, rebuild, purchases, activeBoost, activeBoosts, boostsOf, attach, attachPending, boostView, pickBoosted, adCard, ticker, board, weekStats,
canVisit, verify, click, vtoken, vtokenOk, setSecret, remaining, delivered, hostOf };