diff --git a/chainskus.js b/chainskus.js new file mode 100644 index 0000000..c468f81 --- /dev/null +++ b/chainskus.js @@ -0,0 +1,42 @@ +// Live SKU values from the shop contract (VABShop: skus(sku) = usdCents, views, active) (Marty 2026-11-17, Network Weekend): every page, pack card and the chatbot show what the +// contract will really credit, so a late or early owner setSku never shows a wrong number. skus(sku) is read over CHAIN_RPC every +// 60 s in the background (never on a request); until the first read answers, or if the RPC is down, the env values stand. +// The crediting itself never depends on this: the watcher credits the Purchase event's own credits (shop.js apply). +'use strict'; +const { Interface } = require('ethers'); +const IFACE = new Interface(['function skus(uint256) view returns (uint64 usdCents, uint64 units, bool active)']); +const TTL = 60 * 1000; +let onRead = null; +let C = null, ids = [], live = new Map(), at = 0, timer = null, inflight = null; +async function read(sku) { + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 8000); t.unref && t.unref(); + try { + const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, signal: ac.signal, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'eth_call', params: [{ to: C.contractAddress, data: IFACE.encodeFunctionData('skus', [sku]) }, 'latest'] }) })).json(); + if (j.error || !j.result || j.result === '0x') throw new Error('skus(' + sku + ') ' + (j.error ? j.error.message : 'empty')); + const r = IFACE.decodeFunctionResult('skus', j.result); + return { usdCents: Number(r[0]), units: Number(r[1]), active: !!r[2] }; + } finally { clearTimeout(t); } +} +function refresh() { + if (inflight || !C || !C.contractAddress || !C.chainRpc) return inflight || Promise.resolve(); + inflight = Promise.all(ids.map(async s => { try { live.set(s, await read(s)); } catch (e) {} })).then(() => { at = Date.now(); if (onRead) try { onRead(); } catch (e) {} }).finally(() => { inflight = null; }); + return inflight; +} +function init(cfg, skuIds, after) { + C = cfg; onRead = typeof after === 'function' ? after : null; ids = (skuIds || []).filter(n => Number.isSafeInteger(n) && n > 0); + if (timer) clearInterval(timer); + if (C.contractAddress && C.chainRpc && ids.length) { refresh(); timer = setInterval(refresh, TTL); timer.unref && timer.unref(); } +} +// { usdCents, units, active } as the contract holds it, or null (not read yet / RPC down) +function get(sku) { return live.get(Number(sku)) || null; } +// VAB: the Boost as the contract holds it right now. C.boost (the one config object every module shares) is kept in step after each +// read, so the pages, quotes, proof page and chatbot all say the live views; C.boost.normalViews keeps the BOOST_VIEWS env value. +function syncBoost(C) { + if (C.boost.normalViews == null) { C.boost.normalViews = C.boost.views; C.boost.normalUsd = C.boost.usd; } + const l = get(C.boost.sku); + if (l && l.active && l.units > 0 && l.usdCents > 0) { C.boost.views = l.units; C.boost.usd = l.usdCents / 100; } + else { C.boost.views = C.boost.normalViews; C.boost.usd = C.boost.normalUsd; } + return C.boost; +} +module.exports = { init, get, syncBoost, refresh, _set: (sku, v) => live.set(Number(sku), v), _clear: () => live.clear(), _state: () => ({ at, n: live.size }) }; diff --git a/chatbot.js b/chatbot.js index 43b9ee1..6040a01 100644 --- a/chatbot.js +++ b/chatbot.js @@ -13,7 +13,9 @@ const core = require('./chatcore'); const C = require('./config').get(); -const KNOWLEDGE_DATE = '2026-11-15'; +const KNOWLEDGE_DATE = '2026-11-17'; +const weekend = require('./weekend'); // Network Weekend (2026-11-17): dated fact, from the live chain Boost (C.boost follows chainskus.js) +if (C.boost.normalViews == null) { C.boost.normalViews = C.boost.views; C.boost.normalUsd = C.boost.usd; } // before the first chain read const URL_ = 'https://' + C.site; const SUPPORT = 'https://instantadpay.com/support'; const B = C.boost, SP = C.split; @@ -98,15 +100,33 @@ const FACTS = () => [ '- SPONSOR LINE: from the network hub (same sponsor as InstantAdPay/LinkSpin). On the first Boost the keeper signs the line and the contract records it link by link; a recorded link never changes. People without a wallet in the network are left out.', '- TRUST: ' + URL_ + '/ledger (every Boost, every level paid, who was passed over, delivery), ' + URL_ + '/contract (live contract facts), toasts of real events, a Telegram card per Boost. Terms ' + URL_ + '/terms, Earnings Disclaimer ' + URL_ + '/disclaimer, Privacy ' + URL_ + '/privacy. Run by TrustClickz.', '- PROMO: ' + URL_ + '/promote (links, creatives in every common size, copy, all with the member\'s network username). Old ViralAdBlitz referral links open the member\'s new page; old balances were not carried.', - '- NO REFUNDS: blockchain payments are final; views left on a removed ad\'s Boosts are not delivered or refunded. SUPPORT for account or purchase problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site).' -].join('\n'); + '- NO REFUNDS: blockchain payments are final; views left on a removed ad\'s Boosts are not delivered or refunded. SUPPORT for account or purchase problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site).', + weekendFact() +].filter(Boolean).join('\n'); + +// Network Weekend (Black Friday to Cyber Monday, Fri 11-27 00:00 CT to Tue 12-01 00:00 CT): only while it runs, and only the +// Boost the contract really sells right now +function weekendFact() { + if (!weekend.on()) return ''; + return '- NETWORK WEEKEND (Black Friday to Cyber Monday, midnight to midnight Central, ends Monday 11-30 at 11:59 PM Central): ' + + (weekend.bonus(C) ? 'a $' + B.usd + ' Boost carries ' + B.views + ' guaranteed views instead of ' + B.normalViews + ', same price, for Boosts bought during the weekend. ' : '') + + 'Other network deals: https://instantadpay.com/weekend'; +} +// instant answers carry the normal Boost views; at answer time say what the contract sells right now +function render(t) { + if (!weekend.bonus(C)) return t; + return String(t).replace(new RegExp('(^|[^0-9,.$])' + B.normalViews + '(?=( guaranteed| views))', 'g'), '$1' + B.views) + .replace(new RegExp('\\b(own|your) ' + B.normalViews + '\\b', 'g'), '$1 ' + B.views); +} const SITE = { id: 'viraladblitz', hubSite: 'viraladblitz', netId: 'viraladblitz', name: 'ViralAdBlitz', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE, - dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, - intro: 'You are the assistant on ViralAdBlitz (' + URL_ + '), the network\'s text-ad site: one free text ad per network member that spreads five levels down their team, and a $' + B.usd + ' Boost for ' + B.views + ' guaranteed views. It is part of a network of sites that share one account.', + dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, render, quickTopics: ['How does my ad spread?', 'What is a Boost?', 'Where does the $5 go?', 'What is DownlineHydra?'] }; function init() { return core.init(SITE); } -module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE }; +const INTRO = () => 'You are the assistant on ViralAdBlitz (' + URL_ + '), the network\'s text-ad site: one free text ad per network member that spreads five levels down their team, and a $' + B.usd + ' Boost for ' + B.views + ' guaranteed views. It is part of a network of sites that share one account.'; +// the intro follows the live Boost too (it was a string fixed at boot) +Object.defineProperty(SITE, 'intro', { enumerable: true, get: () => INTRO() }); +module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE, FACTS, render }; diff --git a/chatcore.js b/chatcore.js index df23ff4..724599e 100644 --- a/chatcore.js +++ b/chatcore.js @@ -28,6 +28,8 @@ function key() { try { return fs.readFileSync(path.join(S.dataDir, 'openrouter.key'), 'utf8').trim(); } catch (e) { return ''; } } const enabled = () => !!key(); +// optional per-site rewrite of an instant answer at answer time (2026-11-17, Network Weekend: live chain numbers and dated deals) +const R = t => { try { return S && typeof S.render === 'function' ? S.render(t) : t; } catch (e) { return t; } }; // CANNED + FAQ in the shape kb.js stores (order keeps the first-match-wins sequence) function seeds() { @@ -129,14 +131,14 @@ async function answerRaw(message, historyText) { if (hit && other.length && !hit.handoff) hit = null; } catch (e) { kbOk = false; console.error('kb fast path', e.message); } // a hand-off (support, one person's account problem) always answers from its exact pattern, before anything else - if (hit && hit.handoff) return { reply: hit.answer, canned: true, kb: hit.id, handoff: true }; + if (hit && hit.handoff) return { reply: R(hit.answer), canned: true, kb: hit.id, handoff: true }; // then meaning (2026-11-16, netkb.route): the hub's semantic match over the network KB answers, keeps or overrules the // pattern hit, and picks the prompt context. Hub or model slow or down: null, and the pattern + BM25 path below runs as before. let sem = null; if (kbOk) { try { sem = await netkb.route(msg, { fast: hit, own: await kb.own(), prefer: other }); } catch (e) { sem = null; } } if (sem) hit = sem.hit; - if (hit) return Object.assign({ reply: hit.answer, canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, hit.handoff ? { handoff: true } : {}); - if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: c.a, canned: true }, c.handoff ? { handoff: true } : {}); + if (hit) return Object.assign({ reply: R(hit.answer), canned: true, kb: hit.id }, sem ? { via: sem.via } : {}, hit.handoff ? { handoff: true } : {}); + if (!kbOk) for (const c of S.canned) if (c.re && c.re.test(msg)) return Object.assign({ reply: R(c.a), canned: true }, c.handoff ? { handoff: true } : {}); let kbBlock = '', kbIds = [], hits = []; try { const query = msg.split(/\s+/).length < 4 && historyText ? msg + ' ' + String(historyText).slice(-200) : msg; diff --git a/netdeals.js b/netdeals.js new file mode 100644 index 0000000..f24c466 --- /dev/null +++ b/netdeals.js @@ -0,0 +1,55 @@ +// Network deals for this site's "Network Weekend" ribbon (Marty 2026-11-17). One source: the hub's public GET /v1/network-deals +// (HUB_URL). Cached 2 minutes, refreshed in the background, never waits on a slow hub (2.5 s timeout); hub down = no ribbon. +// The same file lives in every network site. Never RM Circle, never the games (the hub list never names them). +// The page (/assets/netweekend.js) switches the ribbon on and off by its own clock at startsAt / endsAt, so a cached copy never +// shows early or late. setLocal(fn) lets a site rewrite its own deal line from live data (for example a price read from chain), +// so the ribbon never shows a number the contract does not charge: fn(deal) returns the deal, a changed copy, or null to drop it. +const TTL = 2 * 60 * 1000; +let cache = { at: 0, body: { events: [] } }; +let inflight = null; +let local = null; + +const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, ''); +const safeUrl = u => (/^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(u || '')) ? String(u) : ''); +const str = (v, n) => String(v == null ? '' : v).slice(0, n || 300); +function clean(j) { + if (!j || !Array.isArray(j.events)) return null; + return { events: j.events.slice(0, 5).filter(e => e && e.id && !Number.isNaN(Date.parse(e.startsAt)) && !Number.isNaN(Date.parse(e.endsAt))).map(e => ({ + id: str(e.id, 60), name: str(e.name, 60), tagline: str(e.tagline, 160), url: safeUrl(e.url), startsAt: e.startsAt, endsAt: e.endsAt, + days: e.days && typeof e.days === 'object' ? Object.fromEntries(Object.entries(e.days).slice(0, 20).map(([k, v]) => [str(k, 10), str(v, 40)])) : {}, + deals: (Array.isArray(e.deals) ? e.deals : []).slice(0, 40).map(d => { + const x = { site: str(d.site, 30), name: str(d.name, 80), url: safeUrl(d.url), text: str(d.text), endsAt: Number.isNaN(Date.parse(d.endsAt)) ? e.endsAt : d.endsAt }; + if (d.note) x.note = str(d.note, 120); + if (d.byDay && typeof d.byDay === 'object') x.byDay = Object.fromEntries(Object.entries(d.byDay).slice(0, 20).map(([k, v]) => [str(k, 10), str(v)])); + return x; + }) + })) }; +} +function refresh() { + if (inflight || process.env.NETWORK_DEALS_HUB === '0') return inflight; + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500); + inflight = fetch(hubUrl() + '/v1/network-deals', { signal: ac.signal }) + .then(r => (r.ok ? r.json() : null)) + .then(j => { const b = clean(j); if (b) cache = { at: Date.now(), body: b }; else cache.at = Date.now(); }) + .catch(() => { cache.at = Date.now() - TTL + 30 * 1000; }) // hub down: try again in 30 s, keep the last good copy + .finally(() => { clearTimeout(t); inflight = null; }); + return inflight; +} +function current() { if (Date.now() - cache.at > TTL) refresh(); return cache.body; } +function setLocal(fn) { local = typeof fn === 'function' ? fn : null; } +function withLocal(body, self) { + if (!local) return body; + return { events: body.events.map(e => Object.assign({}, e, { deals: e.deals.map(d => { + if (d.site !== self) return d; + try { const r = local(Object.assign({}, d)); return r === undefined ? d : r; } catch (err) { return d; } + }).filter(Boolean) })) }; +} +// GET /api/network-deals: public, short cache, the same answer on every page. self = this site's network id (NETWORK_SITE_ID). +async function handle(req, res, self) { + if (!cache.at) { try { await refresh(); } catch (e) {} } // first ask after a boot waits for the hub once (2.5 s cap) + const me = String(self || process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); + const body = Object.assign({ self: me }, withLocal(current(), me)); + res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=60', 'X-Content-Type-Options': 'nosniff' }); + res.end(JSON.stringify(body)); +} +module.exports = { current, handle, refresh, setLocal, clean, _set: b => { cache = { at: Date.now(), body: clean(b) || { events: [] } }; } }; diff --git a/public/admin.html b/public/admin.html index 6266778..48a0b99 100644 --- a/public/admin.html +++ b/public/admin.html @@ -35,7 +35,7 @@
JSON file {"oldrefs": {"old username": "network username"}} replaces the whole map.