Never hold a purchase: the 3-day claim window is gone. A sponsor with a wallet is activated by the engine (one retry); no wallet, unknown sponsor or a failed activation walks up to the nearest ancestor with a wallet, else the company. Only the buy (intent=buy) moves the member and sends notices; /api/me and /api/sponsor block only on an RPC hiccup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
martbost
2026-10-15 07:55:31 -05:00
parent f47c4ecd54
commit 4a432975b0
6 changed files with 7282 additions and 7279 deletions
+29 -28
View File
@@ -9,9 +9,8 @@
// position on this contract, the engine activates them on their behalf (activateFor,
// engine-signed, gas paid by the engine), walking up until it reaches someone already
// on-chain. The sponsor is told, and their first payout email follows on its own.
// - Sponsor with no wallet at all: the claim window. The member can do everything except
// buy; the sponsor has CLAIM_DAYS to link a wallet. After that the seat walks up to the
// nearest ancestor with a wallet and both sides are told.
// - Sponsor with no wallet at all: NO hold (the claim window was removed 2026-10-15). At the
// buy, the seat walks up to the nearest ancestor with a wallet and both sides are told.
let ethers = null; try { ethers = require('ethers'); } catch (e) {}
const fs = require('fs');
const path = require('path');
@@ -82,36 +81,38 @@ async function onJoin(acct, usedRef) {
}
// ---- before activation / purchase: make sure the sponsor exists on this contract ----
// returns { sponsorId, hold, claim } — hold is set when the buy must wait (claim window)
async function resolveForChain(acct, spd) {
// A purchase is NEVER held (Marty, 2026-10-15: "We should never, ever hold up a purchase"; the 3-day claim
// window is gone). Returns { sponsorId, routed } or null when the normal resolver already has the answer.
// - Sponsor with a wallet: the engine activates them (gas on us) and they are paid, wallet off or not.
// - Sponsor with no wallet, unknown, or an activation that failed: the sale goes to the nearest ancestor
// with a wallet (activated on the spot), else sponsorId 0 = the caller's company fallback.
// Only `commit` (the buyer is about to sign) moves the member and sends the notices; a display check just answers.
async function resolveForChain(acct, spd, opts) {
if (!acct || !acct.sponsorRef) return null;
if (spd.id) return null; // already on-chain: nothing to do
if (spd.reason !== 'notActivated') return null; // unknown token or rpc: the normal guard handles it
if (spd.reason === 'rpc' || spd.reason === 'none') return null; // a chain hiccup is retried by the client; nothing is charged
const commit = !!(opts && opts.commit);
let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef);
if (!sp) return null;
if (sp.address) {
const id = await ensureOnChain(sp, 0);
return id ? { sponsorId: id } : null;
if (sp && sp.address) {
let id = await ensureOnChain(sp, 0);
if (!id) id = await ensureOnChain(sp, 0); // one retry before passing a wallet holder over for our own failure
if (id) return { sponsorId: id };
logEvent({ type: 'activateGaveUp', member: acct.email, sponsor: sp.email });
}
// no wallet: the claim window
const st = state(); const k = norm(acct.email);
let c = st.claims[k];
if (!c) {
c = { member: k, sponsor: sp.email, opened: Date.now(), deadline: Date.now() + claimDays() * DAY, notified: true }; st.claims[k] = c; setState(st);
await tell(sp.email, label(acct) + ' is ready to buy on LinkSpin. Link a wallet to be their sponsor',
label(acct) + ' joined LinkSpin under you and wants to buy a package. The contract can only pay a wallet, and there is none on your LinkSpin account yet.\n\nLink one within ' + claimDays() + ' days (Wallet tab, one free signature) and their purchases pay you. If the window passes, the seat goes to the next person above you who has a wallet.\n\nhttps://' + (X.host || 'linkspin.co') + '/my#wallet');
// walk up to the first ancestor with a wallet the engine can place on the contract
let up = sp ? await nearestWithWallet(sp.email) : null; let id = 0; let hops = 0;
while (up && hops < 25) { id = await ensureOnChain(up, 0); if (id) break; up = await nearestWithWallet(up.email); hops++; }
if (!id) up = null;
const routed = { from: sp ? label(sp) : null, to: up ? label(up) : 'the company', toEmail: up ? up.email : null };
if (commit) {
if (up) await X.accounts.setSponsorRef(acct.email, up.username || up.code);
logEvent({ type: 'walkedUp', member: acct.email, from: sp ? sp.email : acct.sponsorRef, to: up ? up.email : 'company' });
if (sp) await tell(sp.email, 'You missed ' + label(acct) + ' on LinkSpin: no wallet linked',
label(acct) + ' joined LinkSpin under you and bought a package, but there is no wallet on your LinkSpin account, so the contract could not pay you. The sale went to ' + routed.to + ', and ' + label(acct) + ' is now in their line.\n\nLink a wallet now (Wallet tab, one free signature) and every purchase from the people who join under you from here on pays you.\n\nhttps://' + (X.host || 'linkspin.co') + '/my#wallet');
if (up) await tell(up.email, label(acct) + ' was placed under you on LinkSpin',
label(acct) + ' joined through ' + (sp ? label(sp) : 'a link') + ', who has no wallet on LinkSpin, so the network placed them under you. Their purchases pay you from now on.');
}
if (Date.now() < c.deadline) return { sponsorId: 0, hold: true, claim: { sponsor: label(sp), deadline: c.deadline } };
// window passed: walk up to the nearest ancestor with a wallet, activate them, tell both sides
const up = await nearestWithWallet(sp.email);
if (!up) return { sponsorId: 0, hold: true, claim: { sponsor: label(sp), deadline: c.deadline, nobody: true } };
const id = await ensureOnChain(up, 0);
if (!id) return null;
await X.accounts.setSponsorRef(acct.email, up.username || up.code);
delete st.claims[k]; setState(st); logEvent({ type: 'walkedUp', member: acct.email, from: sp.email, to: up.email });
await tell(sp.email, 'The seat for ' + label(acct) + ' passed to ' + label(up), 'No wallet was linked within ' + claimDays() + ' days, so ' + label(acct) + ' was placed under ' + label(up) + ', the nearest person above you with a wallet. Link a wallet now and everyone who joins under you from here on is yours.');
await tell(up.email, label(acct) + ' was placed under you on LinkSpin', label(acct) + ' joined through ' + label(sp) + ', who has no wallet on LinkSpin, so the network placed them under you. Their purchases pay you from now on.');
return { sponsorId: id, movedTo: up.email };
return { sponsorId: id, routed };
}
async function nearestWithWallet(email) {
+3 -3
View File
@@ -89,9 +89,9 @@
}
async function linkWallet() { CR.toast('Check your wallet for the free link signature…'); await IAPWallet.signIn(); CR.toast('Wallet linked. Earnings pay there from now on.'); await load(); }
async function activate() {
const me = await CR.me(true); if (me.sponsorBlocked) { $('holdBox').textContent = holdText(me); $('holdBox').hidden = false; return; }
const sp = await CR.get('/api/sponsor?intent=buy'); if (sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; }
CR.toast('Confirm the free activation in your wallet…');
const r = await IAPWallet.activate(me.sponsorId || 0);
const r = await IAPWallet.activate(sp.sponsorId || 0);
if (!r.receipt || r.receipt.status !== '0x1') throw new Error('Transaction reverted. Check the explorer.');
CR.toast('Payouts are on. Your invite link is live.'); await load();
}
@@ -105,7 +105,7 @@
let cur = String(await IAPWallet.activeAddress() || '').toLowerCase();
if (cur !== want) { CR.toast('Pick ' + want.slice(0, 6) + '…' + want.slice(-4) + ' in your wallet\'s account picker…'); cur = String(await IAPWallet.pickAccount() || '').toLowerCase(); }
if (cur !== want) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but your linked wallet is ' + want.slice(0, 6) + '…' + want.slice(-4) + '. Switch accounts in the wallet app and try again.');
const sp = await CR.get('/api/sponsor');
const sp = await CR.get('/api/sponsor?intent=buy');
if (!me.memberId && sp.sponsorBlocked) { $('holdBox').textContent = holdText(sp); $('holdBox').hidden = false; return; }
try { // pre-flight: the POL has to be there; Trust Wallet refuses transactions that spend most of a balance
const need = BigInt(p.costWei) + BigInt(p.costWei) / 50n;
+2 -2
View File
@@ -2037,7 +2037,7 @@
}
if (cur !== wantAddr) throw new Error('Your wallet connected as ' + cur.slice(0, 6) + '…' + cur.slice(-4) + ' but you chose ' + wantAddr.slice(0, 6) + '…' + wantAddr.slice(-4) + '. Switch accounts in your wallet app and try again.');
}
const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor');
const spNow = fromPos ? { sponsorId: meNow.memberId } : await jretry('/api/sponsor?intent=buy');
if (!fromPos && !meNow.memberId && spNow.sponsorBlocked) { IAP.status(sponsorHoldText(spNow), 'bad'); return; } // first activation must not hand a sponsored member to the company
// pre-flight: stop early if the POL is not there. Trust Wallet also hard-blocks any
// transaction that spends most of the balance ("drain your wallet"), so Trust users
@@ -2284,7 +2284,7 @@
return 'Your sponsor link could not be matched to a member. Message support before buying so ' + who + ' gets credit.';
}
$('activateBtn').addEventListener('click', busy($('activateBtn'), async () => {
const me = await (await fetch('/api/me')).json();
const me = await (await fetch('/api/sponsor?intent=buy')).json();
if (me.sponsorBlocked) { IAP.status(sponsorHoldText(me), 'bad'); return; }
IAP.status('Confirm the free activation in your wallet…');
const r = await IAPWallet.activate(me.sponsorId || 0);
+1 -1
View File
@@ -81,6 +81,6 @@
<script src="/assets/common.js?v=20261009a"></script>
<script src="/assets/wallet.js?v=20261008a"></script>
<script src="/assets/cr-shell.js?v=20261012a"></script>
<script src="/assets/credits-screen.js?v=20261007a"></script>
<script src="/assets/credits-screen.js?v=20261015a"></script>
</body>
</html>
+1 -1
View File
@@ -1012,7 +1012,7 @@
<script src="/assets/tools.js?v=20261011a"></script>
<script src="/assets/wallet.js?v=20261008a"></script>
<script src="/assets/promo.js?v=20261009b"></script>
<script src="/assets/my.js?v=20261008c"></script>
<script src="/assets/my.js?v=20261015a"></script>
<script src="/assets/chat.js?v=20260907l"></script>
</body>
</html>
+14 -12
View File
@@ -614,10 +614,10 @@ async function resolveSponsorToken(tok) { return (await resolveSponsorDetailed(t
const sponsorAlertLast = new Map(); // email -> ts (one alert per member per hour)
function sponsorBlockedAlert(who, r) {
const k = String(who || '?'); if (Date.now() - (sponsorAlertLast.get(k) || 0) < 3600000) return; sponsorAlertLast.set(k, Date.now());
const text = '\u26A0\uFE0F LinkSpin: purchase held for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be resolved (' + r.reason + '), so the buy was blocked instead of crediting the company. ' + (r.reason === 'notActivated' ? 'The sponsor needs to switch on payouts.' : r.reason === 'rpc' ? 'Chain lookup failed; they can retry.' : 'Check the sponsor field in Admin > Members.');
const text = '\u26A0\uFE0F LinkSpin: sale routed for ' + k.replace(/^(.{2}).*(@.*)$/, '$1***$2') + '. Their sponsor ' + (r.name || r.tok || '?') + ' could not be paid (' + r.reason + '), so the purchase went to ' + (r.routedTo || 'the company') + ' and the member moved with it. Purchases are never held.';
const sc = siteConfig();
if (sc.telegramBotToken && sc.telegramAdminChatId) telegramSend(sc.telegramAdminChatId, text).catch(() => {});
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: purchase held, sponsor unresolved', text).catch(() => {});
else if (ADMIN_EMAIL && mailer.hasKey()) mailer.send(ADMIN_EMAIL, 'LinkSpin: sale routed, sponsor could not be paid', text).catch(() => {});
}
// The moment someone joins through a code, nudge its owner to activate.
// Email a member's sponsor the moment they get a new referral (free OR paid).
@@ -1139,19 +1139,21 @@ const server = http.createServer(async (req, res) => {
const acct = s && s.email ? await accounts.byEmail(s.email) : null;
const tok = (acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor'] || '';
const spd = await resolveSponsorDetailed(tok); let sponsorId = spd.id;
// LinkSpin carry-over: a known sponsor with a wallet is activated on this contract by the engine
// before the member's first transaction; one with no wallet opens the claim window (the buy waits)
let claim = null;
// LinkSpin carry-over: a sponsor with a wallet is activated on this contract by the engine before the
// member's first transaction. A purchase is NEVER held (Marty, 2026-10-15): no wallet / unknown sponsor
// walks up to the nearest ancestor with a wallet, else the company. intent=buy commits the move + notices.
const intentBuy = u.searchParams.get('intent') === 'buy';
let sponsorRouted = null;
if (acct && !sponsorId) {
try {
const cr = await carry.resolveForChain(acct, spd);
const cr = await carry.resolveForChain(acct, spd, { commit: intentBuy });
if (cr && cr.sponsorId) { sponsorId = cr.sponsorId; spd.reason = 'ok'; }
else if (cr && cr.hold) { claim = cr.claim; }
if (cr && cr.routed) { sponsorRouted = cr.routed; spd.reason = 'ok'; }
} catch (e) {}
}
if (claim) return json(res, 200, { ref: tok, sponsorId: 0, sponsorBlocked: 'claim', claim, sponsorName: spd.name || null, invited: true, name: null, avatarUrl: null, own: false, bio: null, cobrand: false });
let sponsorBlocked = null; // set when the account itself names a sponsor that cannot be paid right now: the client refuses the transaction
if (acct && acct.sponsorRef && !sponsorId && spd.reason !== 'none') { sponsorBlocked = spd.reason; sponsorBlockedAlert(acct.email, Object.assign({ tok }, spd)); }
let sponsorBlocked = null; // only a momentary chain lookup failure: the client says "try again in a minute", nothing is charged
if (acct && acct.sponsorRef && !sponsorId && spd.reason === 'rpc') sponsorBlocked = 'rpc';
if (sponsorRouted && intentBuy) sponsorBlockedAlert(acct.email, Object.assign({ tok, routedTo: sponsorRouted.to }, spd));
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) { console.log('sponsor routed away from no-payout chain', sponsorId); sponsorId = 0; }
// orphan fallback: an unresolvable/absent sponsor (dead link, no link) lands
// the new member under the configured catch position (#1) instead of root
@@ -1171,7 +1173,7 @@ const server = http.createServer(async (req, res) => {
if (!a && /^\d+$/.test(nameTok)) a = await accounts.byMemberId(Number(nameTok));
if (a) { name = a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : null); avatarUrl = a.avatarUrl || null; own = !!(acct && a.email === acct.email); var bio = null, cobrand = false; try { cobrand = (await ads.milestonesOf(a.email)).includes('level3'); if (cobrand) bio = a.bio ? String(a.bio).slice(0, 220) : null; } catch (e) {} }
}
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
return json(res, 200, { ref: tok, sponsorId, sponsorBlocked, sponsorRouted, sponsorName: spd.name || null, invited: !!(tok || showTok), name, avatarUrl, own, bio: typeof bio === 'undefined' ? null : bio, cobrand: typeof cobrand === 'undefined' ? false : cobrand });
}
if (p === '/api/stats' && req.method === 'GET') {
let members = 0; try { members = await chain.memberCount(); } catch (e) {}
@@ -1376,7 +1378,7 @@ const server = http.createServer(async (req, res) => {
const memberId = await auth.refreshMemberId(s);
const acct = (s.email && await accounts.byEmail(s.email)) || (s.address && await accounts.byAddress(s.address)) || null;
const spdMe = await resolveSponsorDetailed((acct && acct.sponsorRef) || parseCookies(req)['iap.sponsor']); let sponsorId = spdMe.id;
const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason !== 'none') ? spdMe.reason : null;
const sponsorBlocked = (acct && acct.sponsorRef && !sponsorId && spdMe.reason === 'rpc') ? 'rpc' : null; // never hold: the buy/activate paths resolve through /api/sponsor?intent=buy (carry walk-up)
if (sponsorId && await payoutChainBlocked(sponsorId, 2)) sponsorId = 0;
const _defSpon = Number(siteConfig().defaultSponsorId) || 1;
if (!sponsorId && memberId !== _defSpon) sponsorId = _defSpon; // orphan fallback → #1 (never self-sponsor)