diff --git a/accounts.js b/accounts.js
index 06a265c..da19652 100644
--- a/accounts.js
+++ b/accounts.js
@@ -440,10 +440,16 @@ async function downline(email, depth = 3) {
}
return levels;
}
+// wallet-linked hook (Marty, 2026-10-17): the engine switches payouts on as soon as a wallet lands on an account, however
+// it got there (wallet screen, wallet sign-in, InstantAdPay sync). Set by server.js; runs after the link, never blocks it.
+let walletHook = null;
+function onWalletLinked(f) { walletHook = f; }
async function linkWallet(email, address) {
const a = normAddr(address);
if (!/^0x[0-9a-f]{40}$/.test(a)) return { error: 'Bad wallet address.' };
- return impl().linkWallet(normEmail(email), a).then(tap(normEmail(email)));
+ const r = await impl().linkWallet(normEmail(email), a).then(tap(normEmail(email)));
+ if (r && !r.error && walletHook) { try { Promise.resolve(walletHook(normEmail(email))).catch(e => console.error('wallet hook', e.message)); } catch (e) {} }
+ return r;
}
async function count() { return impl().count(); }
// admin: newest-first account list, and re-pointing a member's sponsor (a
@@ -474,7 +480,7 @@ async function getChatSettings(email) {
}
module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, byCode, byUsername, byMemberId: id => impl().byMemberId(Number(id) || 0), listAll, setSponsorRef,
- setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, count,
+ setUsername, setMemberId, namesForMembers, listByReferrer, downline, linkWallet, onWalletLinked, count,
setLineBanner: (e, b, t) => impl().setLineBanner(String(e || '').toLowerCase(), b, t),
setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j),
setProfile: (e, a, bio, socials) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials).then(tap(String(e || '').toLowerCase())),
diff --git a/carry.js b/carry.js
index 94f00f4..2186737 100644
--- a/carry.js
+++ b/carry.js
@@ -1,190 +1,191 @@
-// Sponsor carry-over (LinkSpin, 2026-09-15). Marty's rule: a sponsor is never passed over for
-// being absent, only for having no wallet.
-// - At join: if the registry knows the email and no invite link was used, the member's
-// InstantAdPay sponsor becomes their LinkSpin sponsor. If that sponsor has no LinkSpin
-// account yet, a shell account is created for them (email, username, wallet from the
-// registry) so the line exists on the site immediately; it becomes theirs the first time
-// they sign in with that email. The sponsor is told.
-// - Before a member's first activation or purchase: if the sponsor has a wallet but no
-// 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: 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');
-
-let X = {}; // { dataDir, accounts, registry, chain, mailer, messages, siteConfig, adminEmail }
-const DAY = 86400000;
-const ABI = ['function activateFor(address account, uint32 sponsorId) returns (uint32)', 'function engineSigner() view returns (address)'];
-const norm = e => String(e || '').trim().toLowerCase();
-
-function init(opts) { X = opts; }
-function claimDays() { const n = Number((X.siteConfig && X.siteConfig().carryClaimDays) || 3); return n > 0 ? n : 3; }
-const STATE = () => path.join(X.dataDir, 'carry-state.json');
-function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { claims: {}, log: [] }; } }
-function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} }
-function logEvent(ev) { const s = state(); s.log = (s.log || []).concat([Object.assign({ ts: Date.now() }, ev)]).slice(-500); setState(s); }
-
-function keyHex() {
- let k = String(process.env.ENGINE_KEY || '').trim();
- if (!k && process.env.ENGINE_KEY_FILE) { try { k = fs.readFileSync(process.env.ENGINE_KEY_FILE, 'utf8').trim(); } catch (e) {} }
- if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
- return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
-}
-function engineReady() { return !!(ethers && keyHex()); }
-function signer(i) {
- const c = X.chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc];
- const p = new ethers.JsonRpcProvider(urls[(i || 0) % urls.length], Number(c.chainId), { staticNetwork: true });
- return new ethers.Wallet(keyHex(), p);
-}
-const sleep = ms => new Promise(r => setTimeout(r, ms));
-
-// ---- notices: email + on-site inbox, sent as the company account ----
-async function tell(email, subject, text) {
- const emailOk = !(X.siteConfig && String(X.siteConfig().carryNotices || '1') === '0'); // test area: 0 = on-site notices only
- try { if (emailOk && X.mailer && X.mailer.hasKey()) X.mailer.send(email, subject, text + '\n\nLinkSpin').catch(() => {}); } catch (e) {}
- try {
- const html = '
' + String(text).replace(/&/g, '&').replace(/$1').split('\n\n').join('
').replace(/\n/g, '
') + '
';
- if (X.messages) await X.messages.deliver(1, X.adminEmail || 'house@linkspin.co', [email], subject, html, 'notice'); // quiet inbox, never the sign-in modal (Marty 2026-10-15)
- } catch (e) {}
-}
-const label = a => a ? (a.username ? '@' + a.username : a.email.replace(/^(.).*(@.*)$/, '$1***$2')) : 'a member';
-
-// ---- join: give the member their network sponsor if no link was used ----
-async function onJoin(acct, usedRef) {
- try {
- const reg = await X.registry.get(acct.email);
- // carry the member's own facts (username, wallet) forward when the site does not have them yet
- if (reg && reg.username && !acct.username) { try { await X.accounts.setUsername(acct.email, reg.username); } catch (e) {} }
- if (usedRef || !reg || !reg.sponsorEmail) return { carried: false };
- const spReg = await X.registry.get(reg.sponsorEmail); if (!spReg) return { carried: false };
- let sp = await X.accounts.byEmail(spReg.email);
- if (!sp) {
- // shell account for the sponsor: exists on the site now, becomes theirs at first sign-in
- const r = await X.accounts.ensure(spReg.email, '', 'carried', 'network');
- sp = r.account;
- if (spReg.username && !sp.username) { try { await X.accounts.setUsername(spReg.email, spReg.username); sp = await X.accounts.byEmail(spReg.email); } catch (e) {} }
- if (spReg.wallet && !sp.address) { try { await X.accounts.linkWallet(spReg.email, spReg.wallet); sp = await X.accounts.byEmail(spReg.email); } catch (e) {} }
- // give the shell its own network sponsor too, so the line keeps climbing
- if (spReg.sponsorEmail) { const up = await X.accounts.byEmail(spReg.sponsorEmail); const upReg = await X.registry.get(spReg.sponsorEmail); const tok = up ? (up.username || up.code) : (upReg && upReg.username); if (tok) await X.accounts.setSponsorRef(spReg.email, tok); }
- }
- const tok = sp.username || sp.code;
- await X.accounts.setSponsorRef(acct.email, tok);
- logEvent({ type: 'carried', member: acct.email, sponsor: sp.email });
- await tell(sp.email, label(acct) + ' just joined LinkSpin under you',
- 'Your InstantAdPay referral ' + label(acct) + ' just joined LinkSpin, and the network placed them under you, the same sponsor line you already built.\n\n'
- + (sp.address ? 'Your LinkSpin position will be set up for you the moment it is needed, so you are paid from their first purchase whether or not you have signed in yet. ' : 'Link a wallet on LinkSpin now (Wallet tab, one free signature). Purchases never wait: if they buy before you have a wallet, the sale and the member go to the nearest person above you who has one. ')
- + 'Sign in with this email to see your line: https://' + (X.host || 'linkspin.co') + '/my');
- return { carried: true, sponsor: sp.email };
- } catch (e) { return { carried: false, error: e.message }; }
-}
-
-// ---- before activation / purchase: make sure the sponsor exists on this contract ----
-// 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 === '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 && 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 });
- }
- // 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.');
- }
- return { sponsorId: id, routed };
-}
-
-async function nearestWithWallet(email) {
- let cur = await X.accounts.byEmail(email); const seen = new Set([norm(email)]); let hops = 0;
- while (cur && cur.sponsorRef && hops < 25) {
- let sp = await X.accounts.byCode(cur.sponsorRef); if (!sp) sp = await X.accounts.byUsername(cur.sponsorRef);
- if (!sp || seen.has(norm(sp.email))) return null; seen.add(norm(sp.email)); hops++;
- if (sp.address) return sp; cur = sp;
- }
- return null;
-}
-
-// activate `acct` on this contract via the engine, after its own sponsor is there (recursive, bounded)
-async function ensureOnChain(acct, depth) {
- if (!acct || !acct.address) return 0;
- try { const id = await X.chain.memberIdByAccount(acct.address); if (id) return id; } catch (e) {}
- if (!engineReady() || depth > 25) return 0;
- let sponsorId = 0;
- if (acct.sponsorRef) {
- let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef);
- if (sp && sp.address) sponsorId = await ensureOnChain(sp, depth + 1);
- }
- if (!sponsorId) sponsorId = Number((X.siteConfig && X.siteConfig().defaultSponsorId) || 1) || 1;
- try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet
- // send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations
- // mined while a 403 on the follow-up read logged them as failures and skipped their notices)
- let id = 0, txHash = null, lastErr = null;
- for (let attempt = 0; attempt < 3 && !id; attempt++) {
- try {
- const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w);
- const tx = await ctr.activateFor(acct.address, sponsorId, { gasLimit: 160000n }); txHash = tx.hash;
- await tx.wait(1);
- } catch (e) { lastErr = e; }
- for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); }
- }
- if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; }
- logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash });
- await noticeActivated(acct);
- return id;
-}
-async function noticeActivated(acct) {
- await tell(acct.email, X.seeding ? 'Your LinkSpin payouts are switched on' : 'We set up your LinkSpin position so you would not miss a payout',
- (X.seeding ? 'Your wallet was already on file with the network, so we switched on your LinkSpin payouts for you, at no cost to you. Your position on the LinkSpin contract is active for your wallet ' + acct.address.slice(0, 6) + '…' + acct.address.slice(-4) + ', bound to your own sponsor, and your team is already placed under you. When anyone in your line buys a LinkSpin package, your share lands in this wallet in the same transaction, and you will be notified.'
- : 'Someone in your line was about to buy on LinkSpin, so the network activated your position on the LinkSpin contract for your wallet ' + acct.address.slice(0, 6) + '…' + acct.address.slice(-4) + ', bound to your own sponsor. Nothing was charged and nothing else was touched. Your share of that purchase lands in this wallet in the same transaction.')
- + '\n\nSee your line: https://' + (X.host || 'linkspin.co') + '/my');
-}
-
-// pre-seed: activate every account with a wallet, sponsors before their downline
-async function seedAll(limit) {
- const all = await X.accounts.listAll(5000);
- const withWallet = all.filter(a => a.address);
- let done = 0, failed = 0, already = 0; X.seeding = true;
- try {
- for (const a of withWallet) {
- if (limit && done + failed >= limit) break;
- try {
- if (await X.chain.memberIdByAccount(a.address)) {
- already++;
- // activated by us but logged as a failure (the 403 read), so the notice never went: send it now, once
- const lg = state().log || []; const me = norm(a.email);
- if (lg.some(e => e.type === 'activateFailed' && norm(e.email) === me) && !lg.some(e => (e.type === 'activated' || e.type === 'noticeLate') && norm(e.email) === me)) {
- await noticeActivated(a); logEvent({ type: 'noticeLate', email: a.email });
- }
- continue;
- }
- } catch (e) {}
- const id = await ensureOnChain(a, 0); if (id) done++; else failed++;
- }
- } finally { X.seeding = false; }
- return { candidates: withWallet.length, already, done, failed };
-}
-function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; }
-
-module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady };
+// Sponsor carry-over (LinkSpin, 2026-09-15). Marty's rule: a sponsor is never passed over for
+// being absent, only for having no wallet.
+// - At join: if the registry knows the email and no invite link was used, the member's
+// InstantAdPay sponsor becomes their LinkSpin sponsor. If that sponsor has no LinkSpin
+// account yet, a shell account is created for them (email, username, wallet from the
+// registry) so the line exists on the site immediately; it becomes theirs the first time
+// they sign in with that email. The sponsor is told.
+// - Before a member's first activation or purchase: if the sponsor has a wallet but no
+// 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: 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');
+
+let X = {}; // { dataDir, accounts, registry, chain, mailer, messages, siteConfig, adminEmail }
+const DAY = 86400000;
+const ABI = ['function activateFor(address account, uint32 sponsorId) returns (uint32)', 'function engineSigner() view returns (address)'];
+const norm = e => String(e || '').trim().toLowerCase();
+
+function init(opts) { X = opts; }
+function claimDays() { const n = Number((X.siteConfig && X.siteConfig().carryClaimDays) || 3); return n > 0 ? n : 3; }
+const STATE = () => path.join(X.dataDir, 'carry-state.json');
+function state() { try { return JSON.parse(fs.readFileSync(STATE(), 'utf8')); } catch (e) { return { claims: {}, log: [] }; } }
+function setState(s) { try { fs.writeFileSync(STATE(), JSON.stringify(s)); } catch (e) {} }
+function logEvent(ev) { const s = state(); s.log = (s.log || []).concat([Object.assign({ ts: Date.now() }, ev)]).slice(-500); setState(s); }
+
+function keyHex() {
+ let k = String(process.env.ENGINE_KEY || '').trim();
+ if (!k && process.env.ENGINE_KEY_FILE) { try { k = fs.readFileSync(process.env.ENGINE_KEY_FILE, 'utf8').trim(); } catch (e) {} }
+ if (!k) return null; if (!k.startsWith('0x')) k = '0x' + k;
+ return /^0x[0-9a-fA-F]{64}$/.test(k) ? k : null;
+}
+function engineReady() { return !!(ethers && keyHex()); }
+function signer(i) {
+ const c = X.chain.getConfig(); const urls = (c.rpcs && c.rpcs.length) ? c.rpcs : [c.rpc];
+ const p = new ethers.JsonRpcProvider(urls[(i || 0) % urls.length], Number(c.chainId), { staticNetwork: true });
+ return new ethers.Wallet(keyHex(), p);
+}
+const sleep = ms => new Promise(r => setTimeout(r, ms));
+
+// ---- notices: email + on-site inbox, sent as the company account ----
+async function tell(email, subject, text) {
+ const emailOk = !(X.siteConfig && String(X.siteConfig().carryNotices || '1') === '0'); // test area: 0 = on-site notices only
+ try { if (emailOk && X.mailer && X.mailer.hasKey()) X.mailer.send(email, subject, text + '\n\nLinkSpin').catch(() => {}); } catch (e) {}
+ try {
+ const html = '' + String(text).replace(/&/g, '&').replace(/$1').split('\n\n').join('
').replace(/\n/g, '
') + '
';
+ if (X.messages) await X.messages.deliver(1, X.adminEmail || 'house@linkspin.co', [email], subject, html, 'notice'); // quiet inbox, never the sign-in modal (Marty 2026-10-15)
+ } catch (e) {}
+}
+const label = a => a ? (a.username ? '@' + a.username : a.email.replace(/^(.).*(@.*)$/, '$1***$2')) : 'a member';
+
+// ---- join: give the member their network sponsor if no link was used ----
+async function onJoin(acct, usedRef) {
+ try {
+ const reg = await X.registry.get(acct.email);
+ // carry the member's own facts (username, wallet) forward when the site does not have them yet
+ if (reg && reg.username && !acct.username) { try { await X.accounts.setUsername(acct.email, reg.username); } catch (e) {} }
+ if (usedRef || !reg || !reg.sponsorEmail) return { carried: false };
+ const spReg = await X.registry.get(reg.sponsorEmail); if (!spReg) return { carried: false };
+ let sp = await X.accounts.byEmail(spReg.email);
+ if (!sp) {
+ // shell account for the sponsor: exists on the site now, becomes theirs at first sign-in
+ const r = await X.accounts.ensure(spReg.email, '', 'carried', 'network');
+ sp = r.account;
+ if (spReg.username && !sp.username) { try { await X.accounts.setUsername(spReg.email, spReg.username); sp = await X.accounts.byEmail(spReg.email); } catch (e) {} }
+ if (spReg.wallet && !sp.address) { try { await X.accounts.linkWallet(spReg.email, spReg.wallet); sp = await X.accounts.byEmail(spReg.email); } catch (e) {} }
+ // give the shell its own network sponsor too, so the line keeps climbing
+ if (spReg.sponsorEmail) { const up = await X.accounts.byEmail(spReg.sponsorEmail); const upReg = await X.registry.get(spReg.sponsorEmail); const tok = up ? (up.username || up.code) : (upReg && upReg.username); if (tok) await X.accounts.setSponsorRef(spReg.email, tok); }
+ }
+ const tok = sp.username || sp.code;
+ await X.accounts.setSponsorRef(acct.email, tok);
+ logEvent({ type: 'carried', member: acct.email, sponsor: sp.email });
+ await tell(sp.email, label(acct) + ' just joined LinkSpin under you',
+ 'Your InstantAdPay referral ' + label(acct) + ' just joined LinkSpin, and the network placed them under you, the same sponsor line you already built.\n\n'
+ + (sp.address ? 'Your LinkSpin position will be set up for you the moment it is needed, so you are paid from their first purchase whether or not you have signed in yet. ' : 'Link a wallet on LinkSpin now (Wallet tab, one free signature). Purchases never wait: if they buy before you have a wallet, the sale and the member go to the nearest person above you who has one. ')
+ + 'Sign in with this email to see your line: https://' + (X.host || 'linkspin.co') + '/my');
+ return { carried: true, sponsor: sp.email };
+ } catch (e) { return { carried: false, error: e.message }; }
+}
+
+// ---- before activation / purchase: make sure the sponsor exists on this contract ----
+// 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 === '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 && 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 });
+ }
+ // 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.');
+ }
+ return { sponsorId: id, routed };
+}
+
+async function nearestWithWallet(email) {
+ let cur = await X.accounts.byEmail(email); const seen = new Set([norm(email)]); let hops = 0;
+ while (cur && cur.sponsorRef && hops < 25) {
+ let sp = await X.accounts.byCode(cur.sponsorRef); if (!sp) sp = await X.accounts.byUsername(cur.sponsorRef);
+ if (!sp || seen.has(norm(sp.email))) return null; seen.add(norm(sp.email)); hops++;
+ if (sp.address) return sp; cur = sp;
+ }
+ return null;
+}
+
+// activate `acct` on this contract via the engine, after its own sponsor is there (recursive, bounded)
+async function ensureOnChain(acct, depth, why) {
+ if (!acct || !acct.address) return 0;
+ try { const id = await X.chain.memberIdByAccount(acct.address); if (id) return id; } catch (e) {}
+ if (!engineReady() || depth > 25) return 0;
+ let sponsorId = 0;
+ if (acct.sponsorRef) {
+ let sp = await X.accounts.byCode(acct.sponsorRef); if (!sp) sp = await X.accounts.byUsername(acct.sponsorRef);
+ if (sp && sp.address) sponsorId = await ensureOnChain(sp, depth + 1);
+ }
+ if (!sponsorId) sponsorId = Number((X.siteConfig && X.siteConfig().defaultSponsorId) || 1) || 1;
+ try { if (sponsorId > await X.chain.memberCount()) sponsorId = 0; } catch (e) {} // first member on a fresh contract: no catch position exists yet
+ // send with provider rotation; after ANY error re-read the chain first (2026-10-15 seed: six activations
+ // mined while a 403 on the follow-up read logged them as failures and skipped their notices)
+ let id = 0, txHash = null, lastErr = null;
+ for (let attempt = 0; attempt < 3 && !id; attempt++) {
+ try {
+ const w = signer(attempt); const ctr = new ethers.Contract(X.chain.getConfig().contract, ABI, w);
+ const tx = await ctr.activateFor(acct.address, sponsorId, { gasLimit: 160000n }); txHash = tx.hash;
+ await tx.wait(1);
+ } catch (e) { lastErr = e; }
+ for (let k = 0; k < 4 && !id; k++) { try { id = Number(await X.chain.memberIdByAccount(acct.address)) || 0; } catch (e) {} if (!id) await sleep(3000); }
+ }
+ if (!id) { logEvent({ type: 'activateFailed', email: acct.email, error: String((lastErr && (lastErr.shortMessage || lastErr.message)) || 'not on-chain after send').slice(0, 160) }); return 0; }
+ logEvent({ type: 'activated', email: acct.email, id, sponsorId, tx: txHash });
+ await noticeActivated(acct, why);
+ return id;
+}
+async function noticeActivated(acct, why) {
+ const own = X.seeding || why === 'wallet'; // switched on because their own wallet arrived, not because someone below them bought
+ await tell(acct.email, own ? 'Your LinkSpin payouts are switched on' : 'We set up your LinkSpin position so you would not miss a payout',
+ (own ? 'Your wallet was already on file with the network, so we switched on your LinkSpin payouts for you, at no cost to you. Your position on the LinkSpin contract is active for your wallet ' + acct.address.slice(0, 6) + '…' + acct.address.slice(-4) + ', bound to your own sponsor, and your team is already placed under you. When anyone in your line buys a LinkSpin package, your share lands in this wallet in the same transaction, and you will be notified.'
+ : 'Someone in your line was about to buy on LinkSpin, so the network activated your position on the LinkSpin contract for your wallet ' + acct.address.slice(0, 6) + '…' + acct.address.slice(-4) + ', bound to your own sponsor. Nothing was charged and nothing else was touched. Your share of that purchase lands in this wallet in the same transaction.')
+ + '\n\nSee your line: https://' + (X.host || 'linkspin.co') + '/my');
+}
+
+// pre-seed: activate every account with a wallet, sponsors before their downline
+async function seedAll(limit) {
+ const all = await X.accounts.listAll(5000);
+ const withWallet = all.filter(a => a.address);
+ let done = 0, failed = 0, already = 0; X.seeding = true;
+ try {
+ for (const a of withWallet) {
+ if (limit && done + failed >= limit) break;
+ try {
+ if (await X.chain.memberIdByAccount(a.address)) {
+ already++;
+ // activated by us but logged as a failure (the 403 read), so the notice never went: send it now, once
+ const lg = state().log || []; const me = norm(a.email);
+ if (lg.some(e => e.type === 'activateFailed' && norm(e.email) === me) && !lg.some(e => (e.type === 'activated' || e.type === 'noticeLate') && norm(e.email) === me)) {
+ await noticeActivated(a); logEvent({ type: 'noticeLate', email: a.email });
+ }
+ continue;
+ }
+ } catch (e) {}
+ const id = await ensureOnChain(a, 0); if (id) done++; else failed++;
+ }
+ } finally { X.seeding = false; }
+ return { candidates: withWallet.length, already, done, failed };
+}
+function status() { const s = state(); return { engine: engineReady(), claims: Object.values(s.claims || {}), log: (s.log || []).slice(-50).reverse(), claimDays: claimDays() }; }
+
+module.exports = { init, onJoin, resolveForChain, ensureOnChain, seedAll, status, engineReady };
diff --git a/server.js b/server.js
index 71bddd5..4be1410 100644
--- a/server.js
+++ b/server.js
@@ -457,6 +457,8 @@ async function boot() {
pipeline.init({ dataDir: DATA_DIR, accounts, coach, chain });
registry.init({ dataDir: DATA_DIR });
carry.init({ dataDir: DATA_DIR, accounts, registry, chain, mailer, messages, siteConfig, adminEmail: ADMIN_EMAIL, host: SITE_HOST });
+ // payouts on the moment a wallet is linked (Marty, 2026-10-17); the engine pays the gas, sponsors above are activated first
+ accounts.onWalletLinked(async email => { const a = await accounts.byEmail(email); if (a && a.address) await carry.ensureOnChain(a, 0, 'wallet'); });
// reverse registry sync (2026-10-15): account changes reach InstantAdPay within seconds; a 2-minute reconcile catches the rest
iapsync.init({ dataDir: DATA_DIR, accounts, registry, host: SITE_HOST }); accounts.onChange(email => iapsync.touch(email));
setTimeout(() => iapsync.tick().catch(e => console.error('iapsync', e.message)), 2 * 60 * 1000);