diff --git a/chainskus.js b/chainskus.js new file mode 100644 index 0000000..f9d7af3 --- /dev/null +++ b/chainskus.js @@ -0,0 +1,37 @@ +// Live SKU values from the shop contract (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 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(); }).finally(() => { inflight = null; }); + return inflight; +} +function init(cfg, skuIds) { + C = cfg; 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; } +// VBB: the credit packs as the contract holds them right now; the env values (CREDIT_PACKS) until the first read answers +function packs(C) { + return C.packs.map(p => { const l = get(p.sku); return l && l.active && l.units > 0 && l.usdCents > 0 ? { credits: l.units, usd: l.usdCents / 100, sku: p.sku } : p; }); +} +function lookUsd(C) { const l = get(C.lookSku); return l && l.active && l.usdCents > 0 ? l.usdCents / 100 : C.lookUsd; } +module.exports = { init, get, packs, lookUsd, 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 2c5531f..5c789e7 100644 --- a/chatbot.js +++ b/chatbot.js @@ -13,11 +13,16 @@ const core = require('./chatcore'); const C = require('./config').get(); -const KNOWLEDGE_DATE = '2026-11-15'; +const KNOWLEDGE_DATE = '2026-11-17'; const URL_ = 'https://' + C.site; const SUPPORT = 'https://instantadpay.com/support'; const NOT_INCOME = 'You buy advertising for your own banners, not an income opportunity.'; -const packs = C.packs.map(p => p.credits + ' post credits for $' + p.usd).join(' or '); +const chainskus = require('./chainskus'); // live VBBShop SKU values (2026-11-17) +const weekend = require('./weekend'); // Network Weekend date gate (2026-11-17) +const packsOf = list => list.map(p => p.credits + ' post credits for $' + p.usd).join(' or '); +const packs = packsOf(C.packs); // the normal packs, as the stored instant answers say them; render() swaps in the live ones +const livePacksText = () => packsOf(chainskus.packs(C)); +const freeNow = () => weekend.freePerDay(C.freeCreditsPerDay); const places = C.prizePot.places.join('/'); const CANNED = [ @@ -83,21 +88,38 @@ const FAQ = [ const FACTS = () => [ '- WHAT IT IS: Viral Banner Blitz (' + URL_ + ') is one public loop of ' + C.loopSize + ' member banners (125x125 tiles). A posted banner waits in line, then enters at the front. Every ' + C.perShift + ' verified visitors shift every banner one place; the banner at the end rides out (has cycled) and its owner earns ' + C.viewsPerCycle + ' network ad views. Cycles are recorded on My Banners now; crediting those views to network advertising is NOT switched on yet.', '- VERIFIED VISITOR: a real browser keeps the loop page open and visible about ' + C.visitSeconds + ' seconds; once per visitor per 24 hours; bots, crawlers, repeats and more than ' + C.perIpDay + ' browsers per connection per day do not count.', - '- POSTING: one post credit per banner. Network members (InstantAdPay or LinkSpin, checked with the network hub) get 1 free post credit each day they sign in (Central day). Up to ' + C.maxQueuedPerMember + ' banners waiting per member. Image 125x125, 100 KB max, or post a LinkSpin Banner Spin (125x125 or 250x250). The link must answer. SPIN tiles in empty places are LinkSpin Banner Spins: they never shift, cycle or earn.', + '- POSTING: one post credit per banner. Network members (InstantAdPay or LinkSpin, checked with the network hub) get ' + freeNow() + ' free post credit' + (freeNow() === 1 ? '' : 's') + ' each day they sign in (Central day). Up to ' + C.maxQueuedPerMember + ' banners waiting per member. Image 125x125, 100 KB max, or post a LinkSpin Banner Spin (125x125 or 250x250). The link must answer. SPIN tiles in empty places are LinkSpin Banner Spins: they never shift, cycle or earn.', '- ONE SWAP PER BANNER: a banner that is waiting or in the loop can swap its image and/or link ONE time from My Banners (a Banner Spin to another of the member\'s own 125x125/250x250 spins). It keeps its id, place, clicks and loop progress; the new image and link get the same checks as a new post. No second swap. Members cannot withdraw or remove a banner and credits are not refunded. The admin can take a banner down (the owner sees the reason; the admin decides whether the post credit comes back); its place stays as a house tile until it would have ridden out, so nobody else moves, and it never cycles or earns.', - '- PACKAGES (one-time, POL at the live price, never a subscription, overpayment returned): ' + packs + '; banner look $' + C.lookUsd + ' per banner (border + hover teaser, on a waiting or in-loop banner, one per banner); tokens (network visits at the InstantAdPay visit rate) coming soon.', + '- PACKAGES (one-time, POL at the live price, never a subscription, overpayment returned; read from the VBBShop contract just now): ' + livePacksText() + '; banner look $' + C.lookUsd + ' per banner (border + hover teaser, on a waiting or in-loop banner, one per banner); tokens (network visits at the InstantAdPay visit rate) coming soon.', '- SPLIT (VBBShop constants, no owner withdraw): 30% to the member who introduced the buyer (bound once, by a keeper-signed voucher, on the first purchase; none = company), 10% to the weekly prize pot, 60% company, same transaction. Failed sends wait in the contract for their owner to claim.', '- LEADERBOARDS (Monday to Sunday Central): most verified visitors sent (the member\'s ?ref= link) and most different traffic sources (referring sites). Prize pot = 10% of the week\'s sales, half per board, top three ' + places + ' percent, paid in POL to the winners\' VBB wallets the following Monday at the POL price at payout; ties to whoever got there first. Never state a maximum or a cap.', '- PAGES: / (the loop), /how, /packages, /my (My Banners), /leaders, /promote, /ledger, /contract, /terms, /disclaimer, /privacy. Sign in through InstantAdPay, LinkSpin or a wallet signature.', + weekendFact(), '- NO REFUNDS: blockchain payments are final. SUPPORT for account or payment problems: network support at ' + SUPPORT + ' (InstantAdPay runs the one desk for every network site). ' + NOT_INCOME -].join('\n'); +].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, from live values +function weekendFact() { + if (!weekend.on()) return ''; + const big = chainskus.packs(C).slice().sort((a, b) => b.usd - a.usd)[0]; const base = C.packs.slice().sort((a, b) => b.usd - a.usd)[0]; + return '- NETWORK WEEKEND (Black Friday to Cyber Monday, midnight to midnight Central, ends Monday 11-30 at 11:59 PM Central): network members get ' + freeNow() + ' free post credits a day.' + + (big && base && big.credits > base.credits ? ' The $' + big.usd + ' pack carries ' + big.credits + ' credits instead of ' + base.credits + ', same price.' : '') + + ' Other network deals: https://instantadpay.com/weekend'; +} +// instant answers carry the normal numbers; at answer time swap in the live packs and, during Network Weekend, today's free credits +function render(t) { + let out = String(t).split(packs).join(livePacksText()); + if (freeNow() > 1) out = out.replace(/\b(get|gets) one free post credit (each|every) day they sign in/g, '$1 ' + freeNow() + ' free post credits each day they sign in during Network Weekend (through Monday 11-30, Central)') + .replace(/you get a free post credit each day you sign in/g, 'you get ' + freeNow() + ' free post credits each day you sign in during Network Weekend (through Monday 11-30, Central)'); + return out; +} const SITE = { id: 'vbb', hubSite: 'vbb', netId: 'vbb', name: 'Viral Banner Blitz', url: URL_, supportUrl: SUPPORT, knowledgeDate: KNOWLEDGE_DATE, - dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, + dataDir: C.dataDir, canned: CANNED, faq: FAQ, facts: FACTS, render, intro: 'You are the assistant on Viral Banner Blitz (' + URL_ + '), one public banner loop the community moves with verified visitors: post a 125x125 banner, ride it out, earn network ad views. Network members post free once a day; credit packs and a banner look are one-time purchases.', quickTopics: ['How does the loop work?', 'Is posting free?', 'How do the leaderboards work?', 'What is ViralAdBlitz?'] }; function init() { return core.init(SITE); } -module.exports = { init, handle: core.handle, answer: core.answer, KNOWLEDGE_DATE, CANNED, FAQ, SITE }; +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..e708583 --- /dev/null +++ b/netdeals.js @@ -0,0 +1,54 @@ +// 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). +function handle(req, res, self) { + 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 5587317..309c8c0 100644 --- a/public/admin.html +++ b/public/admin.html @@ -39,7 +39,7 @@
- +