diff --git a/hubsync.js b/hubsync.js index 311314d..2efc890 100644 --- a/hubsync.js +++ b/hubsync.js @@ -14,6 +14,7 @@ // (sponsorfollow: adopt, rescue, release, expiry, admin) also goes to /v1/sponsor-change; BTC4Hits accounts (carried // here with joinedRef 'btc4hits', no other door reports them) are reported like LinkSpin's own; every MemberActivated on // the LinkSpin contract goes to /v1/contract-bind (contract 'linkspin', sponsor by wallet) from its own queue (binds). +// 2026-11-14: every paid Purchase goes to /v1/contract-spend (queue spends, after the binds) for the hub's rule 2. // The InstantAdPay<->LinkSpin sync (iapsync.js, /api/partner/registry) is not touched by any of this. 'use strict'; const crypto = require('crypto'); @@ -185,6 +186,7 @@ async function report(e) { const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // chain.onEvent: a payout switch-on on the LinkSpin contract -> /v1/contract-bind (queued, retried with backoff) function onChain(ev) { + if (ev && ev.type === 'Purchase') return onPurchase(ev); if (!R || !on() || !ev || ev.type !== 'MemberActivated' || !ev.account) return; (async () => { let spW = null; try { const m = ev.sponsorId ? await R.chain.member(ev.sponsorId) : null; spW = m && m.account ? norm(m.account) : null; } catch (e) {} @@ -192,6 +194,33 @@ function onChain(ev) { if (st.binds.length < 20000 && !st.binds.some(b => b.wallet === norm(ev.account))) { st.binds.push({ wallet: norm(ev.account), sponsorWallet: spW, tries: 0, next: 0 }); save(); } })().catch(err => console.error('hubsync onChain', err.message)); } +// chain.onEvent: money paid into the LinkSpin contract (a Purchase with POL in; activation alone is not a spend) -> the hub's +// /v1/contract-spend (Marty 2026-11-14, rule 2: when two contracts hold different sponsors, the one with money spent decides +// the network sponsor). Sent after the binds in each flush; the tx hash makes a resend count once; a 404 (bind not there yet) +// waits and retries. +function onPurchase(ev) { + if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return; + try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } + (async () => { + const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return; + const st = load(); st.spends = st.spends || []; + if (st.spends.length < 20000 && !st.spends.some(x => x.tx && x.tx === ev.tx)) { st.spends.push({ wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), tries: 0, next: 0 }); save(); } + })().catch(err => console.error('hubsync onPurchase', err.message)); +} +async function flushSpends() { + const st = load(); st.spends = st.spends || []; const now = Date.now(); + const waitingBind = new Set((st.binds || []).map(b => b.wallet)); + for (const x of st.spends.slice()) { + if (x.next > now || waitingBind.has(x.wallet)) continue; // its bind goes first + let owner = null; try { owner = await R.accounts.byAddress(x.wallet); } catch (e) {} + let r; try { r = await call('/v1/contract-spend', { contract: 'linkspin', email: owner && owner.email ? owner.email : undefined, wallet: x.wallet, cents: x.cents, tx: x.tx || undefined, at: x.paidAt }); } + catch (e) { r = { status: 0, body: { error: e.message } }; } + if (r.status === 200) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.spends = (st.stats.spends || 0) + 1; } + else if (r.status === 400 || r.status === 409) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.dropped++; console.log('hubsync spend refused', r.status, r.body.error || '', x.wallet); } + else { x.tries++; if (x.tries >= 20) { st.spends.splice(st.spends.indexOf(x), 1); st.stats.dropped++; } else x.next = now + Math.min(3600000, 30000 * 2 ** Math.min(x.tries, 7)); } + save(); + } +} async function flushBinds() { const st = load(); st.binds = st.binds || []; const now = Date.now(); for (const b of st.binds.slice()) { @@ -210,7 +239,7 @@ async function flush() { flushing = true; let done = 0, failed = 0; try { const st = load(); const now = Date.now(); - await flushBinds(); + await flushBinds(); await flushSpends(); for (const [e, o] of Object.entries(st.outbox)) { if (o.next > now) continue; try { await report(e); delete st.outbox[e]; done++; } diff --git a/qa/hubsync.test.cjs b/qa/hubsync.test.cjs index 011e91e..d41cf15 100644 --- a/qa/hubsync.test.cjs +++ b/qa/hubsync.test.cjs @@ -125,7 +125,25 @@ const W = n => '0x' + String(n).padStart(40, '0'); await hooks.tick(); assert.strictEqual(hubsync.adminView().lastSeq, seqNow, 'not advanced while the hub cannot be asked'); process.env.HUB_URL = `http://127.0.0.1:${hubPort}`; await hooks.tick(); assert.ok(await accounts.byEmail(E('rose')), 'arrived on the retry'); - console.log('hubsync: ok (10 checks)'); + // 11. rule 2 (2026-11-14): a LinkSpin activation alone does not decide against a contract with money spent; a paid + // LinkSpin Purchase is reported once (tx) and only after its bind + const per = e => hstore.byEmailKey(e); + await ctb('/v1/join', { email: E('ptw'), username: 'ptw' }); await ctb('/v1/wallet', { email: E('ptw'), wallet: W(91) }); + await ctb('/v1/join', { email: E('sil'), username: 'sil' }); await ctb('/v1/wallet', { email: E('sil'), wallet: W(92) }); + await ctb('/v1/join', { email: E('tur'), ref: 'ptw', username: 'tur' }); + await ctb('/v1/contract-bind', { contract: 'iap', email: E('tur'), wallet: W(93), sponsorRef: W(91), spentCents: 3500 }); + const members = { 7: { account: W(92) }, 8: { account: W(93) } }; + hubsync.init({ dataDir: LS_DIR, accounts, registry, carry, follow: null, chain: { member: async id => members[id] || null } }); + hubsync.onChain({ type: 'MemberActivated', id: 8, account: W(93), sponsorId: 7 }); + hubsync.onChain({ type: 'Purchase', buyerId: 8, priceCents: 1000, paidWei: '5', tx: '0xls1', ts: Date.now() + 60000 }); + hubsync.onChain({ type: 'Purchase', buyerId: 8, priceCents: 1000, paidWei: '5', tx: '0xls1', ts: Date.now() + 60000 }); + await new Promise(r => setTimeout(r, 50)); await hubsync.flush(); + const tur = per(E('tur')); + assert.strictEqual(tur.bindings.linkspin.sponsorId, per(E('sil')).id, 'LinkSpin lock under its own sponsor'); + assert.strictEqual(tur.bindings.linkspin.spentCents, 1000, 'one purchase counted once'); + assert.strictEqual(tur.sponsorId, per(E('ptw')).id, 'the earlier spend (InstantAdPay) still decides'); + assert.strictEqual(hubsync.adminView().stats.spends, 1); + console.log('hubsync: ok (11 checks)'); } finally { hub.close(); ls.close(); } process.exit(0); })().catch(e => { console.error('hubsync: FAIL', e.stack || e.message); process.exit(1); });