From 9408b7af8b040ae0688273f4727a1eb19d488bfe Mon Sep 17 00:00:00 2001 From: martbost Date: Fri, 13 Nov 2026 08:55:44 -0600 Subject: [PATCH] My Spots: 'Use a LinkSpin Banner Spin' (two taps: pick a 468x60 spin, image + tracking link fill and save). Refuel spots: /api/partner/refuel-spot (signed) queues one buyFor per $50+ counted refuel tx, bought from the engine wallet with a 3 POL reserve, every cost recorded (refuelspots.js); never sends at the same time as the keeper. my.js?v=5, line.css?v=4 Co-Authored-By: Claude Opus 5.5 --- keeper.js | 6 ++-- public/assets/line.css | 1 + public/assets/my.js | 27 +++++++++++++++- public/board.html | 2 +- public/how.html | 2 +- public/index.html | 2 +- public/join.html | 2 +- public/my.html | 4 +-- refuelspots.js | 73 ++++++++++++++++++++++++++++++++++++++++++ server.js | 29 ++++++++++++++++- 10 files changed, 138 insertions(+), 10 deletions(-) create mode 100644 refuelspots.js diff --git a/keeper.js b/keeper.js index 236b194..1adffb4 100644 --- a/keeper.js +++ b/keeper.js @@ -54,9 +54,11 @@ function decide(now) { return { act: true, giftee: cands.length ? cands[0].address : chain.ZERO, candidates: cands.length, fundToday }; } +let otherBusy = () => false; // refuelspots.js signs with the same wallet: never two sends at once +function setOtherBusy(f) { otherBusy = f; } async function tick() { const c = cfgMod.get(); - if (running || !c.keeperEnabled || !process.env.KEEPER_KEY || !c.contract) return; + if (running || otherBusy() || !c.keeperEnabled || !process.env.KEEPER_KEY || !c.contract) return; running = true; try { await chain.tail(); // decide on fresh data @@ -93,4 +95,4 @@ function init() { } function statusInfo() { const c = cfgMod.get(); return { enabled: c.keeperEnabled && !!process.env.KEEPER_KEY, last: lastDecision, preview: decide(), log: store.keeperEntries().slice(-20).reverse() }; } -module.exports = { init, tick, decide, candidates, statusInfo, centralDay }; +module.exports = { init, tick, decide, candidates, statusInfo, centralDay, setOtherBusy, busy: () => running }; diff --git a/public/assets/line.css b/public/assets/line.css index ff22fe8..e7b29bc 100644 --- a/public/assets/line.css +++ b/public/assets/line.css @@ -48,3 +48,4 @@ nav .links a.active{color:var(--mint-ink);background:var(--mint)} .brand{display:flex;align-items:center;gap:11px;color:var(--ink);text-decoration:none!important;min-width:0} .brand img{flex:none;filter:drop-shadow(0 4px 14px rgba(155,123,255,.35))} .brand .logo{letter-spacing:-.02em} +.ls-pick{margin:6px 0 4px}.ls-pick .row{gap:8px} diff --git a/public/assets/my.js b/public/assets/my.js index bacafe0..ca1af16 100644 --- a/public/assets/my.js +++ b/public/assets/my.js @@ -42,9 +42,34 @@ el.innerHTML = head + '
' + '
Tracking: {clickid}, {spot} and {type} in your link are filled on every click (LinkSpin has a Downline Banners source ready for this).
' + '
' - + '
'; + + '
' + + '
'; const prev = el.querySelector('.lots'); prev.appendChild(BL.tile({ t: 'x', img: (s.showing && s.showing.img) || '/art/house-line.svg', href: s.link || '#' })); const url = kind === 'spot' ? '/api/my/spot/' + s.id : '/api/my/default'; + // LinkSpin Banner Spin (2026-11-13): pick one of your 468x60 spins; the image and the tracking link fill in and save + const pick = el.querySelector('.ls-pick'); + el.querySelector('[data-a=ls]').onclick = async () => { + pick.hidden = false; pick.innerHTML = '

Looking up your LinkSpin Banner Spins...

'; + const d = await BL.getJSON('/api/my/lsspins'); + if (d.error) { pick.innerHTML = '

' + esc(d.error) + '

'; return; } + const make = 'make one on LinkSpin'; + if (!d.account) { pick.innerHTML = '

No LinkSpin account holds this wallet yet. Join LinkSpin (free) with the same email as InstantAdPay, link this wallet there, then ' + make + '.

'; return; } + if (!d.spins.length) { pick.innerHTML = '

You have no 468x60 Banner Spin yet: ' + make + ', then come back and tap the button again.

'; return; } + pick.innerHTML = '

Pick a 468x60 Banner Spin. Its rotating image and tracking link go on this spot, and LinkSpin reports clicks under your Downline Banners source.

'; + const row = pick.querySelector('.row'); + for (const sp of d.spins) { + const bt = document.createElement('button'); bt.className = 'btn sec small'; bt.textContent = sp.name + ' (' + sp.banners + ' banners' + (sp.paused ? ', paused' : '') + ')'; + bt.onclick = async () => { + BL.status('Connecting your Banner Spin...'); + const u = await BL.post('/api/my/lsspins/use', { spinId: sp.id }); + if (u.error || !u.use) return BL.status(u.error || 'Could not use that Banner Spin.', 'err'); + el.querySelector('[data-k=link]').value = u.use.link; el.querySelector('[data-k=img]').value = u.use.img; + el.querySelector('[data-a=save]').click(); + if (u.use.otherSource) BL.status('Saved. This Banner Spin already reports under another LinkSpin source, so clicks stay there.', 'ok'); + }; + row.appendChild(bt); + } + }; el.querySelector('[data-a=save]').onclick = async () => { const link = el.querySelector('[data-k=link]').value.trim(), img = el.querySelector('[data-k=img]').value.trim(); const body = { link }; if (img || !String(s.img || '').startsWith('/art/u/')) body.img = img; diff --git a/public/board.html b/public/board.html index 5b302e4..240384a 100644 --- a/public/board.html +++ b/public/board.html @@ -7,7 +7,7 @@ - +
diff --git a/public/how.html b/public/how.html index 649ea37..385d4bf 100644 --- a/public/how.html +++ b/public/how.html @@ -7,7 +7,7 @@ - +
diff --git a/public/index.html b/public/index.html index ba1cd28..26acf84 100644 --- a/public/index.html +++ b/public/index.html @@ -7,7 +7,7 @@ - +
diff --git a/public/join.html b/public/join.html index cee0eee..f533363 100644 --- a/public/join.html +++ b/public/join.html @@ -7,7 +7,7 @@ - +
diff --git a/public/my.html b/public/my.html index 05778e7..fd3b11d 100644 --- a/public/my.html +++ b/public/my.html @@ -7,7 +7,7 @@ - +
@@ -28,6 +28,6 @@
- + diff --git a/refuelspots.js b/refuelspots.js new file mode 100644 index 0000000..5dd791d --- /dev/null +++ b/refuelspots.js @@ -0,0 +1,73 @@ +// Refuel spots (Marty 2026-11-13: "it will get paid from the company fee share ... the $50+"). A counted Monthly Refuel of $50 or +// more on InstantAdPay or LinkSpin (InstantAdPay decides, it keeps the one streak for both sites) earns the refueling member one +// Downline Banners spot: buyFor(member wallet, member's network sponsor wallet), paid by the engine wallet (KEEPER_KEY), which +// Marty tops up from the company fee share. InstantAdPay posts each one to /api/partner/refuel-spot signed with +// NETWORK_SSO_SECRET ('net.v1.' + ts + newline + raw body). One spot per refuel tx, ever (refuelspots.json is keyed by it). +// Never spends below RESERVE: with too little POL the spot waits in the queue ("engine wallet low") and is bought once topped up. +// Every buy is recorded with its cost, so the company's spend on refuel spots can be totalled exactly. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const { Wallet, JsonRpcProvider } = require('ethers'); +const cfgMod = require('./config'); +const chain = require('./chain'); +const { iface } = require('./abi'); + +const RESERVE = 3n * 10n ** 18n; // POL kept for gas (the engine wallet also signs InstantAdPay credit burns and fund buys) +const ADDR = /^0x[0-9a-f]{40}$/; +let S = null, busy = false, lockFn = () => false; +const FILE = () => path.join(cfgMod.get().dataDir, 'refuelspots.json'); +function load() { if (S) return S; try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = {}; } S.items = S.items || {}; return S; } +function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('refuelspots save', e.message); } } + +// -> { ok, queued | repeat } or { error } +function enqueue(b) { + const tx = String(b.tx || '').toLowerCase(); const w = String(b.wallet || '').toLowerCase(); const sp = String(b.sponsorWallet || '').toLowerCase(); + if (!/^0x[0-9a-f]{64}$/.test(tx)) return { error: 'tx' }; + if (!ADDR.test(w)) return { error: 'wallet' }; + if (!(Number(b.cents) >= 5000)) return { error: 'below $50' }; + const s = load(); if (s.items[tx]) return { ok: true, repeat: true, status: s.items[tx].status }; + s.items[tx] = { tx, site: String(b.site || '').slice(0, 10), wallet: w, sponsor: ADDR.test(sp) && sp !== w ? sp : null, cents: Number(b.cents), status: 'queued', at: Date.now(), tries: 0 }; + save(); setTimeout(() => tick().catch(() => {}), 2000); + return { ok: true, queued: true }; +} + +async function tick() { + const c = cfgMod.get(); + if (busy || lockFn() || !process.env.KEEPER_KEY || !c.contract) return; + const s = load(); const next = Object.values(s.items).find(x => x.status === 'queued' && (!x.retryAt || x.retryAt < Date.now())); + if (!next) return; + busy = true; + try { + const provider = new JsonRpcProvider(c.rpcs[0], c.chainId, { staticNetwork: true }); + const signer = new Wallet(process.env.KEEPER_KEY, provider); + const q = await chain.quote(); const value = BigInt(q.sendWei || q.wei); // the contract refunds anything above the price + const bal = await provider.getBalance(signer.address); + if (bal < value + RESERVE) { next.why = 'engine wallet low: ' + (Number(bal / 10n ** 15n) / 1000) + ' POL, needs ' + (Number((value + RESERVE) / 10n ** 15n) / 1000); next.retryAt = Date.now() + 30 * 60000; save(); return; } + const fees = await chain.suggestedFees(); + const sponsor = next.sponsor || chain.ZERO; + const tx = await signer.sendTransaction({ to: c.contract, value, data: iface.encodeFunctionData('buyFor', [next.wallet, sponsor]), + maxFeePerGas: BigInt(fees.maxFeePerGas), maxPriorityFeePerGas: BigInt(fees.maxPriorityFeePerGas) }); + next.status = 'sent'; next.spotTx = tx.hash; next.sentWei = value.toString(); delete next.why; save(); + console.log('refuel spot sent', tx.hash, 'for', next.wallet); + const r = await tx.wait(1, 180000).catch(() => null); + if (r && r.status === 1) { + next.status = 'bought'; next.boughtAt = Date.now(); next.gasWei = (BigInt(r.gasUsed) * BigInt(r.gasPrice || r.effectiveGasPrice || 0)).toString(); + try { const ev = r.logs.map(l => { try { return iface.parseLog(l); } catch (e) { return null; } }).find(x => x && x.name === 'SpotBought'); if (ev) { next.spotId = Number(ev.args.id); next.costWei = String(ev.args.valueWei); } } catch (e) {} + } else { next.status = r ? 'reverted' : 'unconfirmed'; } + save(); await chain.tail().catch(() => {}); + } catch (e) { + next.tries = (next.tries || 0) + 1; next.why = String(e && (e.shortMessage || e.message) || e).slice(0, 200); + if (next.status === 'queued') next.retryAt = Date.now() + Math.min(6 * 3600000, 5 * 60000 * 2 ** Math.min(next.tries, 6)); save(); + console.error('refuel spot', next.why); + } finally { busy = false; } +} + +function init(opts) { if (opts && opts.lock) lockFn = opts.lock; load(); const t = setInterval(() => tick().catch(e => console.error('refuelspots', e.message)), 120000); t.unref && t.unref(); } +function view() { + const items = Object.values(load().items).sort((a, b) => b.at - a.at); + const bought = items.filter(x => x.status === 'bought'); + const sum = k => bought.reduce((t, x) => t + BigInt(x[k] || 0), 0n).toString(); + return { queued: items.filter(x => x.status === 'queued').length, bought: bought.length, costWei: sum('costWei'), gasWei: sum('gasWei'), recent: items.slice(0, 20) }; +} +module.exports = { init, enqueue, tick, view, busy: () => busy }; diff --git a/server.js b/server.js index 9ec30e5..21a188c 100644 --- a/server.js +++ b/server.js @@ -13,6 +13,7 @@ const board = require('./board'); const safety = require('./safety'); const keeper = require('./keeper'); const { iface } = require('./abi'); +const refuelspots = require('./refuelspots'); // refuel spots: $50+ Monthly Refuels earn a spot, engine wallet pays (2026-11-13) const hubreport = require('./hubreport'); // network hub, shadow mode: members reported by wallet (2026-11-13), off unless HUB_ENABLED const networksso = require('./networksso'); // network sign-in: arrive signed in from InstantAdPay or LinkSpin (2026-11-13), see networksso.js const SEL = { buy: iface.getFunction('buy').selector, buyFor: iface.getFunction('buyFor').selector }; // the browser builds calldata from these (ABI stays in abi.js) @@ -22,6 +23,7 @@ fs.mkdirSync(path.join(C.dataDir, 'art'), { recursive: true }); store.load(); chain.init(); hubreport.init({ dataDir: C.dataDir, members: () => chain.allMembers() }); +refuelspots.init({ lock: () => keeper.busy() }); keeper.setOtherBusy(() => refuelspots.busy()); keeper.init(); const PUB = path.join(__dirname, 'public'); @@ -92,6 +94,19 @@ async function netMember(q) { return m; } const nameOf = async addr => { const m = await netMember({ a: addr }); return m && m.address === addr.toLowerCase() ? m.username : null; }; +// ---- LinkSpin Banner Spins for My Spots (Marty 2026-11-13: pull a Banner Spin in with a couple of clicks) ---- +// Signed with NETWORK_SSO_SECRET: X-Net-Ts + X-Net-Sig = hex HMAC-SHA256('net.v1.' + ts + newline + raw body). LinkSpin answers +// for the account holding the signed-in wallet only. +async function lsSpins(body) { + const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); if (sec.length < 32) return { error: 'LinkSpin link is not set up.' }; + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 8000); + try { + const r = await fetch(C.lsBase + '/api/partner/bl/spins', { method: 'POST', body: raw, signal: ac.signal, headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } }); + const j = await r.json().catch(() => ({})); return r.ok ? j : { error: j.error || 'LinkSpin did not answer.' }; + } catch (e) { return { error: 'LinkSpin did not answer. Try again in a minute.' }; } finally { clearTimeout(t); } +} // ---- sponsor ref (?ref=
) ---- async function resolveRef(raw) { const r = String(raw || '').trim(); @@ -317,6 +332,8 @@ const server = http.createServer(async (req, res) => { const s = session(req); if (!s) return json(res, 401, { error: 'Sign in with your wallet first.' }); const me = s.address; if (p === '/api/my' && req.method === 'GET') return json(res, 200, await myData(me)); + if (p === '/api/my/lsspins' && req.method === 'GET') { const r = await lsSpins({ wallet: me }); return json(res, r.error ? 502 : 200, r); } + if (p === '/api/my/lsspins/use' && req.method === 'POST') { const b = await readBody(req); const r = await lsSpins({ wallet: me, spinId: Number(b.spinId) || 0 }); return json(res, r.error ? 400 : 200, r); } let m = /^\/api\/my\/spot\/(\d+)$/.exec(p); if (m && req.method === 'POST') { const sp = chain.spot(m[1]); if (!sp || sp.owner !== me) return json(res, 403, { error: 'That spot is not yours.' }); @@ -347,10 +364,20 @@ const server = http.createServer(async (req, res) => { return json(res, 404, { error: 'Not found' }); } + // -- InstantAdPay -> refuel spot (signed with NETWORK_SSO_SECRET, see refuelspots.js) + if (p === '/api/partner/refuel-spot' && req.method === 'POST') { + const raw = (await readRaw(req, 4096)).toString('utf8'); + const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); const ts = String(req.headers['x-net-ts'] || ''); const sig = String(req.headers['x-net-sig'] || ''); + if (sec.length < 32 || !/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 300000) return json(res, 401, { error: 'unauthorized' }); + const want = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex'); + if (sig.length !== want.length || !crypto.timingSafeEqual(Buffer.from(sig), Buffer.from(want))) return json(res, 401, { error: 'unauthorized' }); + let b; try { b = JSON.parse(raw || '{}'); } catch (e) { return json(res, 400, { error: 'bad json' }); } + const r = refuelspots.enqueue(b); return json(res, r.error ? 400 : 200, r); + } // -- admin (ADMIN_TOKEN header): keeper preview + index status. No key material is ever returned. if (p === '/api/admin/status' && req.method === 'GET') { const tok = process.env.ADMIN_TOKEN; if (!tok || req.headers['x-admin-token'] !== tok) return json(res, 401, { error: 'no' }); - return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view() }); + return json(res, 200, { index: chain.status(), totals: chain.totals(), keeper: keeper.statusInfo(), hub: hubreport.view(), refuelSpots: refuelspots.view() }); } if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' });