a8a1a8eec7
Plant a program free (referral link with {id}, link check green / yellow / red, daily recheck, reports), members save their
referral IDs in its packet, a sponsor-first link (member page / ?r= / the hub sponsor line, then the planter), the sprout meter
to REVIEW_SAVES (DEFAULT 25) -> Marty's review queue -> approved packets exported for the CTB builder / DownlineHydra wild heads
with every saved ID. Dormant old programs confirmed by their owner, old-link redirects (oldrefs), Spotlight on YPBShop (NOT
deployed; DEFAULT $10 / 1,000 views, 20/5/5/5/5, company 60), verified views with Spotlight delivery, trust pack (ledger,
contract, toasts, Telegram card, terms / disclaimer / privacy, TrustClickz only), network footer row, chatbot, promo kit,
Guides, PolHunter slot, LinkSpin tracked-link and zone hooks, AI writer through the hub. Seed-catalog look from the approved
mockup. Tests: qa/unit.test.cjs 33/33, qa/e2e.mjs 121/121 on a local anvil chain.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
179 lines
12 KiB
JavaScript
179 lines
12 KiB
JavaScript
// On-chain side (YPBShop, ../contracts; NOT deployed: staging runs with no CONTRACT_ADDRESS, so every job here is inert).
|
|
// (a) orders: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Order(buyer, sku, qty, ref, line[], nonce, deadline).
|
|
// line = the buyer's network sponsor line from the hub (wallets, nearest first, up to 20). ref = the packet id. The contract
|
|
// pays places 1..5 of the line (20% / 5% / 5% / 5% / 5%, DEFAULT split) and the company the rest, in the same transaction.
|
|
// Nobody needs a Spotlight to earn. Compression happens in server.js (/api/my/order): only network members with a linked
|
|
// wallet go in the line, so a level passes up to the next eligible person; levels left when the line runs out go to the company.
|
|
// (b) watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and records each once per
|
|
// txHash:logIndex. The split of each order is read from its receipt (Paid / PaymentFailed).
|
|
// No key ever enters config or any API answer.
|
|
'use strict';
|
|
const crypto = require('crypto');
|
|
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 kind, uint8 depth)',
|
|
'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 kind, uint8 depth)']);
|
|
const TOPIC = IFACE.getEvent('Purchase').topicHash;
|
|
const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').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 nonce, uint256 deadline, bytes sig) payable returns (uint256 orderId)',
|
|
'function levelBps() view returns (uint16[])', 'function levelCount() view returns (uint8)', 'function purchases(address) view 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)', 'function SKU_DELAY() view returns (uint256)',
|
|
'function skus(uint256) view returns (uint64 usdCents, uint64 views, bool active)', 'function pendingSku(uint256) view returns (uint64 usdCents, uint64 views, bool active, uint64 eta)']);
|
|
const TYPES = {
|
|
Order: [{ name: 'buyer', type: 'address' }, { name: 'sku', type: 'uint256' }, { name: 'qty', type: 'uint256' }, { name: 'ref', type: 'uint256' }, { name: 'line', type: 'address[]' },
|
|
{ name: 'nonce', type: 'uint256' }, { 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; }
|
|
const keyOf = k => { k = String(k || '').trim(); if (!k) return null; try { return new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { return null; } };
|
|
|
|
function init(cfg) {
|
|
C = cfg; keeper = keyOf(process.env.KEEPER_KEY);
|
|
if (process.env.KEEPER_KEY && !keeper) console.error('shop: KEEPER_KEY is not a valid private key; orders off');
|
|
if (timer) { clearTimeout(timer); timer = null; }
|
|
if (watching()) { console.log('shop: watching', C.contractAddress); tick(); }
|
|
}
|
|
const signerOn = () => !!(C && keeper && C.contractAddress);
|
|
const watching = () => !!(C && C.contractAddress && C.chainRpc);
|
|
const domain = () => ({ name: 'YPBShop', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress });
|
|
const nonce = () => BigInt('0x' + crypto.randomBytes(16).toString('hex'));
|
|
function cleanLine(buyer, line) {
|
|
const b = String(buyer).toLowerCase(); const seen = new Set([b]); const l = [];
|
|
for (const w of line || []) { const x = String(w || '').toLowerCase(); if (!ADDR_RE.test(x) || x === ZERO || seen.has(x) || x === String(C.contractAddress).toLowerCase()) continue; seen.add(x); l.push(getAddress(x)); if (l.length >= MAX_LINE) break; }
|
|
return l;
|
|
}
|
|
// the buy() call for `buyer`: a signed order carrying the sponsor line and the packet id
|
|
async function order(buyer, sku, qty, ref, line) {
|
|
if (!signerOn()) throw new Error('orders off');
|
|
const b = getAddress(String(buyer).toLowerCase());
|
|
const o = { buyer: b, sku: BigInt(sku), qty: BigInt(qty), ref: BigInt(ref || 0), line: cleanLine(b, line), nonce: nonce(), deadline: BigInt(Math.floor(Date.now() / 1000) + C.voucherSeconds) };
|
|
const sig = await keeper.signTypedData(domain(), { Order: TYPES.Order }, o);
|
|
const q = await quote(sku, qty);
|
|
const data = CALLS.encodeFunctionData('buy', [o.sku, o.qty, o.ref, o.line, o.nonce, o.deadline, sig]);
|
|
return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, line: o.line.length };
|
|
}
|
|
|
|
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 };
|
|
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: Spotlight order', ev.orderId, 'x' + ev.qty, a, rec.packetId ? 'for packet #' + rec.packetId : '(packet ' + ev.ref + ' not found)');
|
|
return true;
|
|
}
|
|
function decode(l) {
|
|
if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase()) return null;
|
|
if ((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: kind 0 company, 1..5 sponsor levels (depth = place in the compressed line)
|
|
async function readSplit(tx, orderId) {
|
|
const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null;
|
|
const pays = [];
|
|
for (const l of r.logs) {
|
|
if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue;
|
|
const t0 = l.topics[0]; if (t0 !== T.paid && t0 !== T.fail) continue;
|
|
const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue;
|
|
pays.push({ kind: Number(d.kind), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined });
|
|
}
|
|
return { pays };
|
|
}
|
|
|
|
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; 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; }
|
|
if ((S.purchases || {})[String(ev.txHash).toLowerCase() + ':' + ev.logIndex]) { st.dupes++; continue; }
|
|
ev.blockAt = await blockTime(ev.block);
|
|
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(); } }); }
|
|
|
|
async function call(fn, args) {
|
|
const r = await rpc('eth_call', [{ to: C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']);
|
|
return CALLS.decodeFunctionResult(fn, r);
|
|
}
|
|
const qCache = new Map();
|
|
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;
|
|
}
|
|
// the live split and SKU from the contract (cached 5 minutes); null when the chain is not set or does not answer
|
|
let rules = null;
|
|
async function liveRules(sku) {
|
|
if (!watching()) return null;
|
|
if (rules && Date.now() - rules.at < 300000) return rules.v;
|
|
try {
|
|
const [l, s, pend] = await Promise.all([call('levelBps').then(x => x[0]), call('skus', [sku || 1]), call('pendingSku', [sku || 1])]);
|
|
const v = { levelBps: l.map(Number), sku: { usdCents: Number(s[0]), views: Number(s[1]), active: !!s[2] }, pending: Number(pend[3]) ? { usdCents: Number(pend[0]), views: Number(pend[1]), active: !!pend[2], eta: Number(pend[3]) } : null };
|
|
rules = { at: Date.now(), v }; return v;
|
|
} catch (e) { return rules ? rules.v : 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 };
|
|
}
|
|
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(), orders: signerOn(), keeper: keeper ? keeper.address : null,
|
|
lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, spotlights: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orderCount: list.length }, st);
|
|
}
|
|
module.exports = { setHook, setAttach, init, order, signerOn, watching, apply, poll, view, quote, liveRules, receipt, fees, nudge, call, rpc, readSplit, TOPIC, IFACE, TYPES, CALLS, MAX_LINE, ZERO };
|