Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c06c58daf | |||
| e1bee03b95 | |||
| e17d8c4fbb | |||
| 7f57aedcb6 | |||
| 968e60835f | |||
| 911dd623c0 | |||
| 4ccdb914c7 | |||
| 82eab8016b | |||
| 4787390e8b | |||
| d033cc7122 | |||
| efb054d916 | |||
| 32f001aade | |||
| edc484db27 | |||
| 836c7b17c2 | |||
| a01d6f2e8c | |||
| ff568d973c | |||
| 5398faadee | |||
| a7c36a908a | |||
| 92288a30f5 | |||
| d626469980 | |||
| e98a6ebcd8 | |||
| f29f6d1407 | |||
| 9efdfc8ee9 | |||
| 4e2178d779 | |||
| f20062133f | |||
| 24b4ae9134 |
@@ -110,7 +110,7 @@ function head(o) {
|
||||
+ '</head><body><div class="wrap bl">';
|
||||
}
|
||||
function tail() {
|
||||
return '</div><script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
||||
return '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20261101th"></script></body></html>';
|
||||
}
|
||||
const authorBox = () => '<div class="author"><img src="/logo-icon.png" alt="InstantAdPay"><div><b>' + AUTHOR + '</b><span>Founder of InstantAdPay and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.</span></div></div>';
|
||||
const cardHtml = p => '<a class="post-card" href="/blog/' + esc(p.slug) + '">' + (p.cover ? '<img src="' + esc(p.cover) + '" alt="" loading="lazy" style="width:100%;border-radius:10px;margin:0 0 12px">' : '') + '<h2>' + esc(p.title) + '</h2><p>' + esc(p.excerpt) + '</p><p class="meta">' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '</p></a>';
|
||||
|
||||
+16
-7
@@ -34,7 +34,7 @@ function key() {
|
||||
function enabled() { return !!key(); }
|
||||
|
||||
// ---- canned answers: instant, free, always in voice ----
|
||||
const KNOWLEDGE_DATE = '2026-11-13'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const KNOWLEDGE_DATE = '2026-11-14'; // bump whenever the canned answers / prompt are brought up to date
|
||||
const SUPPORT_RE = /(contact|reach|email|e-mail|message|talk to|speak (to|with)|get hold of) (the )?(support|admin|administrator|owner|marty|staff|team at instantadpay|someone|a (human|person|real person))|support (email|address|ticket|team|desk)|help ?desk|(open|send|file|submit|raise) (a )?(support )?ticket|\b(human|real person|live (agent|person|chat|support))\b|customer (service|support)|support@|how (do|can) i get (help|support)/i;
|
||||
const CANNED = [
|
||||
// network sign-in (2026-11-12): signed in on one of InstantAdPay / LinkSpin = signed in on the other, no code (networksso.js)
|
||||
@@ -53,7 +53,7 @@ const CANNED = [
|
||||
// this answer names neither; heroesFact() gives the AI the live state.
|
||||
{ id: 'sov-bonus-heroes', title: 'Shards of Valor bonus heroes', q: ['What are the bonus heroes in Shards of Valor?', 'How do I get Kestrel, Valda, Morag or Roland?', 'Is the hero a subscription?'], tags: ['shards of valor', 'heroes', 'bonus heroes', 'kestrel', 'valda', 'morag', 'roland', 'party'],
|
||||
re: /\b(bonus heroe?s?|kestrel|valda|morag|roland|paladin|barbarian|druid hero|archer hero|hero bundle)\b/i,
|
||||
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Each is a one-time purchase, yours for good, with no subscription, and there is a bundle of three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
|
||||
a: 'Shards of Valor has four bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid and Roland the Paladin. Kestrel is free for every player: she joins for good once a hero in your party reaches level 20, and she is not sold. Valda, Morag and Roland are each a one-time purchase, yours for good, with no subscription, and there is a bundle of those three. Like a Game Pass, a hero is paid by a new package purchase of at least its price (your sponsor and team are paid as usual and you keep the package credits for your ads); credits you already hold never buy one. When they are on sale they show on the Game Pass card in Members > Games (https://instantadpay.com/my#games) with each price; if you do not see them there, they are not on sale yet. In the game three heroes fight at a time and you pick which three at an inn, a rest spot or a dungeon camp; heroes waiting in the roster keep their gear and level and earn half experience. A bonus hero joins at your party level (at most 20) and is never stronger than the free heroes. The whole story stays free with Aldric, Sylwen and Borin.' },
|
||||
{ id: 'support', title: 'Contact support or open a ticket', q: ['How do I contact support?', 'How do I talk to a real person?', 'How do I open a support ticket?'], tags: ['support', 'help', 'ticket', 'contact', 'help desk'],
|
||||
re: SUPPORT_RE, handoff: true,
|
||||
a: 'Open Help in your member dashboard (https://instantadpay.com/my#help) to send Marty a ticket, and his replies land right there and in your email. Not signed in or locked out? Use https://instantadpay.com/support, or email support@instantadpay.com. You can also tap "Send this to support" below and I will pass this chat along.' },
|
||||
@@ -129,7 +129,16 @@ const CANNED = [
|
||||
a: 'Any page on instantadpay.com becomes your referral link when you add ?ref= and your username to the end, for example instantadpay.com/blog/what-is-a-feeder-program?ref=yourname. Whoever opens it is tagged to you for 30 days, exactly like your invite link, so if they join from any page on the site the credit is yours. Promo tools > Viral links builds these links for you, and every blog article shows your link when you are signed in.' },
|
||||
{ id: 'refuel', title: 'Monthly Refuel streak and Pit Stops', q: ['What is my refuel day?', 'How does the refuel streak work?', 'What is a Pit Stop?', 'How much should I spend each month?'], tags: ['refuel', 'streak', 'pit stop', 'twin engine', 'bonus credits'],
|
||||
re: /(refuel(ing)? (day|streak|bonus|window)|my refuel|monthly refuel|pit ?stop|twin engine|both engines|refuel streak|streak bonus|free miss)/i,
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed.' },
|
||||
a: 'The Monthly Refuel streak rewards members who refuel their ads every month. A counted refuel is a new package of $20 or more on InstantAdPay, or $25 or more on LinkSpin, bought by one of your own positions. Your first one sets your refuel day; the next is due 30 days later, the window opens 5 days before that day and there is a 5-day grace after it (Central time). Each refuel adds bonus ad credits on the site where you bought: month 1 +10%, month 2 +15%, month 3 +20%, month 4 and up +25%. Refuel BOTH sites in the same cycle and each gets +15%, +20%, +30% or +40% (the first site is topped up to that rate), plus a 100-credit Featured bonus on InstantAdPay from month 4 (enough for two Featured days and more). Either site alone keeps your streak going; both sites in a cycle is the bigger bonus. The bonus stacks on Five Dollar Friday and Wired Wednesday. Another $20+/$25+ package on a site you already refueled this cycle, before your next window opens, is a Pit Stop: half your current rate, once per site per cycle, and it does not count as the refuel. Miss the grace and the streak starts again, except for one free miss a year. Badges at your first refuel and at 3, 6 and 12 months. Each counted refuel also unlocks the Refuel Kit for that month: members-only banners (728x90, 300x250, 468x60, 160x600 and 1200x630) with your @name and a QR code to your own link drawn on them, in Promo tools; they stay yours after the month, a 3-month streak adds an animated version and 6 months a custom-banners credit. Your first counted refuel also opens the Engine Room tab in your member area: three plain dials (fuel left on both sites against this cycle’s refuel with days left at your burn, clicks this week with clicks per 1,000 credits, goals this month against a goal you set), warning lights, six part lights with setup links and one next move. Your refuel day, streak, next bonus and Pit Stop status are on the Refuel card on your Overview (with a Refuel LinkSpin link once this site is done for the cycle). Buy here: https://instantadpay.com/my#buy. The full guide, with the flow step by step: https://instantadpay.com/refuel. Bonus credits are ad credits that buy delivery, never cash, and no income is guaranteed. A counted refuel of $50 or more (either site) also earns you one free Downline Banners spot (downlinebanners.com, the network banner board), paid by the company and placed for your main wallet, so link a wallet to receive it.' },
|
||||
{ id: 'downline-banners', title: 'Downline Banners (network banner board)', q: ['What is Downline Banners?', 'How do I use my LinkSpin Banner Spin on Downline Banners?', 'How do I sign in to Downline Banners?'], tags: ['downline banners', 'banner board', 'spot', 'banner spin'],
|
||||
re: /(downline ?banners|banner (board|spot)|banner line)/i,
|
||||
a: 'Downline Banners (https://downlinebanners.com) is the Crypto Team Build Network banner board on Polygon. A $5 spot (paid in POL) buys 300 guaranteed views on the board and a place in one global line; when later spots sell, the contract pays the 10 spots above them and the buyer\u2019s sponsor in the same transaction. Nothing is promised: you are paid only when spots sell after yours. Signed in on InstantAdPay? Open its My Spots page and you arrive signed in as your linked wallet, and your share link uses your InstantAdPay username. In My Spots, the "Use a LinkSpin Banner Spin" button puts one of your 468x60 Banner Spins on a spot in two taps, with click tracking under a Downline Banners source on LinkSpin. A $50+ Monthly Refuel earns one free spot. To promote it: Promo tools > Network sites > Downline Banners (or downlinebanners.com/promote) has your links, creatives in every common size, lines, headlines, an email and posts, all carrying your username.' },
|
||||
{ id: 'viral-banner-blitz', title: 'Viral Banner Blitz (network banner loop)', q: ['What is Viral Banner Blitz?', 'How do I post on Viral Banner Blitz?'], tags: ['viral banner blitz', 'vbb', 'banner loop', '125x125'],
|
||||
re: /(viral ?banner ?blitz|vbb|banner loop)/i,
|
||||
a: 'Viral Banner Blitz (https://viralbannerblitz.com) is the network’s shared loop of 125x125 banners. InstantAdPay and LinkSpin members get one free post credit each day they sign in there (Sign in with InstantAdPay works). Real, verified visitors move the loop; a banner that rides out the end has cycled and earns network ad views, which are advertising, not cash. Weekly leaderboards count the visitors you send and the traffic sources they come from, with a prize pot paid in POL to the top three on each board. Your link is viralbannerblitz.com/?ref=your-username. Promo tools > Network sites > Viral Banner Blitz (or viralbannerblitz.com/promote) has your links, creatives, lines, headlines, an email and posts.' },
|
||||
{ id: 'network-sites-kits', title: 'Promo tools: Network sites', q: ['Where are the Downline Banners and Viral Banner Blitz banners?', 'How do I promote the other network sites?'], tags: ['network sites', 'promo kit', 'promote', 'creatives'],
|
||||
re: /(network sites|promo kit|promote (downline|viral|the other|network))/i,
|
||||
a: 'Members > Promo tools > Network sites shows the promo kits of Downline Banners and Viral Banner Blitz with your InstantAdPay username already in every link: your personal links, creatives in 125x125, 468x60, 728x90, 300x250, 160x600, 1200x630 and 1080x1080 (download, copy the URL or copy ready HTML that links to you), 5 short lines, 3 headlines, an email and 2 social posts. Your username works as your sponsor link on those sites even if you never visited them. Each site keeps its own kit, so the copy here is always the current one; the same kit is on each site’s Promote page. Each link also has a tracked version that goes through LinkSpin first (so the network can see which site sent the visit) and then opens the same page with your username; use either one.' },
|
||||
{ id: 'wired-wednesday', title: 'Wired Wednesday bonus', q: ['What is Wired Wednesday?', 'What happens on Wednesday?'], tags: ['wired wednesday', 'bonus credits', 'promotion'],
|
||||
re: /(wired wednesday|wednesday (bonus|promo|deal|special)|what happens on wednesday)/i,
|
||||
a: 'Wired Wednesday: every Wednesday (Central time, midnight to midnight), any ad package from $20 up (the Activation pack and above; there is no $10 pack) earns +25% bonus credits, wired into your balance the moment the purchase settles. They are purchased-grade, so they run on any format, login ads included, and the bonus is labelled in your credit log. The page instantadpay.com/wednesday shows whether it is live now and the next date; add ?ref=yourusername to that address and anyone who joins from it is your referral. Every pack still pays its sponsor line in the same on-chain transaction. Credits buy ad delivery and cannot be withdrawn; no income is guaranteed.' },
|
||||
@@ -281,9 +290,9 @@ function seeds() {
|
||||
// BONUS HEROES (2026-11-05): sold one time; while heroSales is off the assistant says they are coming soon, once on it quotes the live prices
|
||||
function heroesFact() {
|
||||
let h = null; try { h = HERO_SALE ? HERO_SALE() : null; } catch (e) { h = null; }
|
||||
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
|
||||
const base = 'Shards of Valor bonus heroes: Kestrel the Archer, Valda the Barbarian, Morag the Druid, Roland the Paladin. Kestrel is FREE for every player once a hero in the party reaches level 20 (since 2026-11-14) and is NOT sold; anyone who bought her before keeps her. Valda, Morag and Roland are sold ONE TIME, owned for good, never a subscription; paid by a NEW package purchase of at least the price (sponsor and team paid as usual, the member keeps the package credits); credits already held never buy one. Three heroes fight at a time, picked at an inn, rest spot or dungeon camp; the roster keeps gear and level and earns half experience. A bonus hero joins at the party level (at most 20) and is never stronger than the free heroes. The Champion and Sovereign passes no longer include a hero (the Necromancer was dropped); the Legend pass opens every bonus hero while it is active.';
|
||||
if (!h || !h.sale) return '- BONUS HEROES (COMING SOON, not on sale yet): ' + base + ' Never quote their prices or a launch date while they are not on sale.\n';
|
||||
const each = (h.rows || []).map(r => r.name + (r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
|
||||
const each = (h.rows || []).map(r => r.name + (r.freeAt ? ' free at level ' + r.freeAt + ' (not sold)' : r.free ? ' free for everyone' : ' $' + r.usd)).join(', ');
|
||||
return '- BONUS HEROES (ON SALE, Members > Games > Game Pass card at https://instantadpay.com/my#games): ' + each + (h.bundle && h.bundle.names.length ? '; the bundle ' + h.bundle.names.join(', ') + ' $' + h.bundle.usd : '') + '. ' + base + ' The bundle is heroes only (no level cap change).\n';
|
||||
}
|
||||
function passTiersFact() {
|
||||
@@ -340,7 +349,7 @@ const gpWithTd = a => tdLive() ? String(a).replace('plus one free supply crate e
|
||||
function sovTestFact() { return GAME_LIVE && GAME_LIVE('shardsofvalor') ? '- SHARDS OF VALOR (OPEN TESTING since Nov 6, https://shardsofvalor.com, Members > Games > Shards of Valor > Play): a pixel adventure RPG for many players at once; lead three heroes across the islands, help the townspeople, fight in the dungeons and recover the eight Shards of Valor. It is in open testing: anyone can play it now, but it is NOT live and pays NO POL until a launch date is set; there is no launch date yet. ALL TESTING PROGRESS IS WIPED AT LAUNCH (heroes, levels, gold and items start fresh), because this phase is only for finding bugs. Never promise a date or a payout. Ask testers to report bugs through Support.\n' : ''; }
|
||||
function turkeydropFact() { return tdLive() ? '- TURKEY DROP (Thanksgiving season game, https://turkeydropgame.com, Members > Games; open Nov 2 through Nov 30 Central, its Games card shows a "Limited time, ends Nov 30" ribbon and is gone after): a free 70s-cartoon arcade game. The WFWL 98.7 radio helicopter drops turkeys over the mall; the player swings a net to catch them before they splat; too many splats and the station pulls them off the air. One-tap sign-in with the InstantAdPay account. PAYS POL: the first time a player reaches each score milestone, plus a weekly top-3 leaderboard POL prize. POL collects in the Turkey Drop balance and is paid automatically to the wallet linked on InstantAdPay. BACK ON THE AIR: after being pulled off the air, a short verified sponsor visit (charged to the advertiser like any game refuel visit) gives one extra life; gameplay only, never POL. Game Pass perk: one free back-on-the-air extra life every day. Never state amounts, caps, totals or a season budget.\n' : tdOver() ? '- TURKEY DROP: the Thanksgiving season game (Nov 2 to 30) has ENDED; say the season is over and point to the other games.\n' : '- TURKEY DROP: COMING SOON, not open yet. Never send members to turkeydropgame.com; say it is coming soon to the Games tab, and do not bring it up unless asked.\n'; }
|
||||
function polminerFact() { return pmLive() ? '- POL MINER (https://polminer.com, Members > Games): a free dig-down mining game. Dig, sell ore for coins, upgrade pick/lamp/cart/thruster, beat a drill boss every 30 m. Pink Polygon crystals pay a random POL amount the first time each one is dug out; each boss pays POL on its first win per account; first trips to 50/100/150/200 m pay POL. Coins never turn into POL. Guests can play and collect at sign-in. POL is paid automatically to the wallet linked on InstantAdPay. The SUPPLY pad opens a sponsored supply crate (full lamp + coins, never POL) after a short sponsor visit.\n' : '- POL MINER: COMING SOON, not open yet. Never send members to polminer.com; say it is coming soon to the Games tab.\n'; }
|
||||
function refuelFact() { return REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'; }
|
||||
function refuelFact() { return "- DOWNLINE BANNERS (LIVE 2026-11-13, https://downlinebanners.com, contract verified on Polygonscan): network banner board; a $5 spot in POL = 300 guaranteed views + a place in one line; the contract pays the 10 spots above and the buyer's sponsor when later spots sell; nothing promised. InstantAdPay sign-in carries members in as their linked wallet; share links use the InstantAdPay username; My Spots has a 'Use a LinkSpin Banner Spin' button. A counted Monthly Refuel of $50+ (either site) earns one free spot for the member's main wallet, paid by the company (no wallet linked = no spot).\n" + (REFUEL_ON() ? "- MONTHLY REFUEL STREAK (built 2026-10-24, switch refuelStreak): ONE streak per member across InstantAdPay and LinkSpin. Counted refuel = a NEW package of $20+ on InstantAdPay or $25+ on LinkSpin by one of the member's own positions. First one sets the member's own refuel day; next due 30 days after the last counted refuel; window opens 5 days before the due day; 5-day grace after it; Central time. Missing the grace resets the streak, except one free miss per 365 days. Bonus (purchased-grade ad credits on the site where bought, credit log 'Refuel streak'): one engine m1 +10%, m2 +15%, m3 +20%, m4+ +25%; both sites in the same cycle m1 +15%, m2 +20%, m3 +30%, m4+ +40% each (first site topped up to the both rate, difference only) plus a 100-credit Featured bonus on InstantAdPay at m4+ (purchased-grade credits, any format). Stacks on Five Dollar Friday / Wired Wednesday. Pit Stop: another $20+/$25+ package on a site already refueled this cycle, before the next window opens (the other site's first package in the cycle is the second engine instead) = half the current streak rate, once per site per cycle, not a counted refuel. Badges: Engine Started (first refuel), Refueled 3 / 6 / 12 months. ENGINE ROOM: unlocked by the first counted refuel (greyed 'Refuel to start your engine' before), IAP tab Engine Room + LinkSpin Ads screen panel, same data both sites: dials Fuel left (credits free + in campaigns on both sites vs this cycle's refuel credits incl. bonus, days left at the recent burn), Clicks this week (vs last week, clicks per 1,000 credits), Goals this month (conversion pixel conversions since the 1st Central vs the member's own goal); streak panel; warning lights (ads at 80%, ads out, refuel day coming, login slot open); six part lights (fuel, banner spin, spin link, page, testing, conversion tracking: green working, amber needs attention, grey not started with a Set it up link); one Next move button from simple rules. REFUEL KIT: each counted refuel unlocks the Central-month's members-only banner set for this site's own program (5 sizes, personalized server-side with @username + QR to the member's link; IAP: Promo tools card with Use in an IAP banner campaign; LinkSpin: Ads screen card with Load into my Banner Spin); kits stay usable after the month; streak month 3+ adds an animated GIF, month 6+ a BannerKitAI custom-banners credit (coming, entitlement saved). Reminders 5 days before, on the day, last call at the end of grace (email + on-site notice). The member's Refuel card (InstantAdPay Overview, LinkSpin Credits/Ads) shows refuel day, streak, next bonus, Pit Stop status. Either site alone keeps the streak (one-engine rates); both sites in one cycle = the bigger bonus; never say both are required. MEMBER GUIDE PAGE (public, 2026-10-24): /refuel on both sites (https://instantadpay.com/refuel and https://linkspin.app/refuel): the flow, the numbers, the member steps, leader coaching and FAQ; point members there for the full picture. Ad credits only, never cash; never promise income. No auto-billing: the member chooses every package. ROUTES (2026-10-25): LinkSpin menu item Refuel = https://linkspin.app/credits#refuel (the Refuel panel, scrolled to and highlighted); packages of $25+ there are marked counts for Refuel; https://linkspin.app/credits#buy = the package picker; https://linkspin.app/ads#engine = LinkSpin Engine Room. InstantAdPay Engine Room = https://instantadpay.com/my#engine; its Set up conversion tracking opens https://instantadpay.com/my#conversions (Campaigns > Conversion tracking card, same goals LinkSpin counts). Engine Room links that cross to LinkSpin (Banner Spin, spin link, page, testing, refuel LinkSpin) open LinkSpin with a note at the top naming the job, Step 1, a guide link and Back to InstantAdPay; same email signs in on both.\n" : '- MONTHLY REFUEL STREAK: built but NOT switched on yet. If asked, say it is coming and nothing counts toward it today; do not quote bonus rates or dates.\n'); }
|
||||
const REFUEL_OFF_ANSWER = 'The Monthly Refuel streak (bonus ad credits for refueling every month, more when you refuel both InstantAdPay and LinkSpin) is built but not switched on yet, so nothing counts toward it today. The bonuses running now are Five Dollar Friday and Wired Wednesday on InstantAdPay. When the streak goes live, your Refuel card will show your refuel day.';
|
||||
function systemPrompt(kbBlock) {
|
||||
return `You are the assistant on InstantAdPay (https://instantadpay.com), a membership advertising platform.
|
||||
@@ -361,7 +370,7 @@ ${passTiersFact()}${heroesFact()}${refuelFact()}${synFact()}${polminerFact()}${w
|
||||
- Free to join with email only (6-digit code sign-in, no passwords). Wallet appears only at purchase or payout activation. Every new member gets a small welcome batch of ad credits — unlocked by the WELCOME TOUR on first sign-in: they visit their upline's line-banner sites (up to 3, 10 seconds each — the same 3 levels the contract pays), then claim the credits. Members with no upline banners get the credits instantly.
|
||||
- SPONSOR ATTRIBUTION: last touch. The invite link opened most recently sets the sponsor (30-day cookie), shown on the join page and again at the code step ("Joining under @name"). It locks when the account is created; the contract binds the buyer to that sponsor at their first purchase. Wrong sponsor before joining: open the right link. Already joined wrong: admin can move the account before the first purchase.
|
||||
- YOUR LINKS (top of Members > Promo tools): the plain invite link plus five angle links (?v=instant paid-in-seconds, ?v=adspend you-buy-ads-anyway, ?v=free costs-nothing-to-try, ?v=ledger no-back-office, ?v=two two-buyers-open-level-two, ?v=wide width-unlocks-depth with the Build Wide video; ?v=play opens the games angle), each with a who-it-is-for note, Copy and Share. Same credit either way; only the first page differs. Link stats on the Overview's coaching card show views/joins/buyers per angle.
|
||||
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. The Games tab (2026-10-31) also carries the EnjoyBestGames arcade kit: enjoybestgames.com is an engagement site with hundreds of free HTML5 games; the featured row Games that pay Polygon is the network's own games and the only ones that pay; the member link enjoybestgames.com/?r=username sets a 30-day cookie so every featured game and the site strip credit that member on InstantAdPay; share image, 4 posts and the 11 banner sizes are in the kit.
|
||||
- PROMO TOOLS (Members > Promo tools, pill menu): Social posts for X/Facebook/LinkedIn/Telegram-WhatsApp with post/share buttons; Text a friend (5 SMS-sized messages with Text it / WhatsApp / Telegram / Copy); Email swipes (short, standard, long, follow-up); Banners in every standard ad size plus 1080x1080, 1080x1920 and 1280x720 (download or copy URL); the member's Banner wall link; an Objection handling bank (truth + ready-to-send reply); a Videos tab with five hook videos, one per angle (Paid before the page reloads, You were buying traffic anyway, Watch first spend never, No back office, Two buyers open level two), each with a caption and the matched angle link, and at Circuit the Video Maker renders them with the member's own end card and QR; a Toolkit tab showing the badge ladder and the AI Copy Engine. Every piece carries the member's invite link; angle links add ?v=instant|adspend|free|ledger. Members who want copy in their own voice can use mybrandedvoice.com. The Games tab (2026-10-31) also carries the EnjoyBestGames arcade kit: enjoybestgames.com is an engagement site with hundreds of free HTML5 games; the featured row Games that pay Polygon is the network's own games and the only ones that pay; the member link enjoybestgames.com/?r=username sets a 30-day cookie so every featured game and the site strip credit that member on InstantAdPay; share image, 4 posts and the 11 banner sizes are in the kit. The Network sites tab (2026-11-14) shows the Downline Banners and Viral Banner Blitz promo kits, read live from each site: the member's links (their InstantAdPay username is their sponsor link there too, even if they never visited), creatives in 7 sizes per angle, 5 lines, 3 headlines, an email and 2 posts; the same kits are on downlinebanners.com/promote and viralbannerblitz.com/promote. Viral Banner Blitz: a shared loop of 125x125 banners, one free post credit a day for InstantAdPay/LinkSpin members, verified visitors move the loop, a banner that cycles earns network ad views (advertising, not cash), weekly leaderboards with a POL prize pot.
|
||||
- INVITE PAGES: a member's link instantadpay.com/join/<username> opens a lead-capture page (email first, wallet later); add ?v=instant|adspend|free|ledger|two|wide|play for an angle-matched headline (?v=wide: 'Width unlocks depth.', opens on the Build Wide video, vertical on phones). New free members get a short getting-started email series over the first week (unsubscribe link in every email; the admin edits the sequence in /admin > Settings).
|
||||
- WALLET DRAIN WARNING: Trust Wallet hard-blocks any purchase that spends most of the wallet's POL ("this transaction will drain your wallet", only "Stop and go back"). It is a balance-proportion heuristic, not a contract issue (there are no token approvals; a buy is one native-POL payable call). Advice: smaller package first, or add POL so the buy is well under half the balance, or use MetaMask/Phantom/SafePal (no hard block). The dashboard warns Trust Wallet users before sending when a buy would use more than ~55% of the balance; other wallets are not prompted. After a blocked attempt the WalletConnect session may be dead: Wallet tab > Disconnect > Connect again.
|
||||
- WALL OWNERSHIP LADDER: the public wall has 3 positions. Position 1 = the member's line banner. Positions 2 and 3 show upline banners (then house ads) UNTIL the member earns them: 2 qualifying buyers ($20+) unlock position 2, 5 unlock position 3; a fully qualified member's wall is 100% their own links/offers (set in Profile > Your wall: label, https link, optional banner image). Empty unlocked slots fall back to upline banners, then house ads.
|
||||
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early
|
||||
// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives
|
||||
// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep
|
||||
// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every
|
||||
// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands).
|
||||
//
|
||||
// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken
|
||||
// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss).
|
||||
// First boot: a document missing from MySQL is imported from its file, and the file is renamed <name>.imported-<date> (kept, not
|
||||
// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by
|
||||
// listing a folder). The SAME file ships in InstantAdPay and LinkSpin.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
|
||||
const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain
|
||||
const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing
|
||||
const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync,
|
||||
unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync };
|
||||
|
||||
let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true;
|
||||
const cache = new Map(); // name -> { body: string, at: ms }
|
||||
const pending = new Map(); // name -> body string | null (delete)
|
||||
let flushing = false, timer = null;
|
||||
const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null };
|
||||
|
||||
function nameOf(p) {
|
||||
if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null;
|
||||
const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null;
|
||||
const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/');
|
||||
if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null;
|
||||
return rel;
|
||||
}
|
||||
const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; };
|
||||
const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null;
|
||||
|
||||
function put(name, body) { cache.set(name, { body, at: Date.now() }); pending.set(name, body); kick(); }
|
||||
function drop(name) { cache.delete(name); pending.set(name, null); kick(); }
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); }
|
||||
|
||||
async function flush() {
|
||||
if (!pool || flushing || !pending.size) return;
|
||||
flushing = true;
|
||||
try {
|
||||
for (const [name, body] of [...pending]) {
|
||||
if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round
|
||||
if (!writer) { pending.delete(name); stats.refused++; continue; }
|
||||
const c = await pool.getConnection();
|
||||
try {
|
||||
await c.beginTransaction();
|
||||
const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE');
|
||||
if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; }
|
||||
if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; }
|
||||
else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; }
|
||||
await c.commit();
|
||||
if (pending.get(name) === body) pending.delete(name);
|
||||
} catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); }
|
||||
finally { c.release(); }
|
||||
}
|
||||
} finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); }
|
||||
}
|
||||
|
||||
// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk.
|
||||
function install(dataDir) {
|
||||
if (ROOT) return; ROOT = path.resolve(dataDir);
|
||||
fs.readFileSync = function (p, o) {
|
||||
if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]);
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) throw enoent(p);
|
||||
return enc(o) ? d.body : Buffer.from(d.body, 'utf8');
|
||||
};
|
||||
fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); };
|
||||
fs.writeFileSync = function (p, data, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments);
|
||||
const flag = o && typeof o === 'object' ? o.flag : null;
|
||||
const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data);
|
||||
put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s);
|
||||
};
|
||||
fs.appendFileSync = function (p, data) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments);
|
||||
put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data)));
|
||||
};
|
||||
fs.renameSync = function (a, b) {
|
||||
const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null;
|
||||
if (!nb && !na) return O.renameSync.apply(fs, arguments);
|
||||
let body;
|
||||
if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); }
|
||||
else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} }
|
||||
if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body);
|
||||
};
|
||||
fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); };
|
||||
fs.statSync = function (p, o) {
|
||||
const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments);
|
||||
const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); }
|
||||
const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at);
|
||||
return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false };
|
||||
};
|
||||
}
|
||||
|
||||
// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app
|
||||
// must not run on an empty copy.
|
||||
async function init(opts) {
|
||||
const url = String(process.env.DOCSTORE_URL || '').trim();
|
||||
if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; }
|
||||
const mysql = require('mysql2/promise');
|
||||
pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' });
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]);
|
||||
const [rows] = await pool.query('SELECT name, body, updated_at FROM docs');
|
||||
for (const r of rows) cache.set(r.name, { body: r.body, at: Number(r.updated_at) });
|
||||
for (const sp of (opts && opts.splits) || []) await openSplit(sp);
|
||||
// first boot for any document: import its file, then set the file aside
|
||||
const stamp = new Date().toISOString().slice(0, 10);
|
||||
const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; };
|
||||
for (const p of walk(ROOT)) {
|
||||
const n = nameOf(p); if (!n || cache.has(n)) continue;
|
||||
const body = O.readFileSync.call(fs, p, 'utf8');
|
||||
if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } }
|
||||
await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]);
|
||||
const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]);
|
||||
cache.set(n, { body: got.body, at: Date.now() }); stats.imported++;
|
||||
O.renameSync.call(fs, p, p + '.imported-' + stamp);
|
||||
}
|
||||
for (const sp of (opts && opts.splits) || []) await migrateSplit(sp);
|
||||
ready = true;
|
||||
console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot');
|
||||
const shut = () => { flush().catch(() => {}).finally(() => {}); };
|
||||
process.once('beforeExit', shut);
|
||||
return true;
|
||||
}
|
||||
// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ----
|
||||
// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest
|
||||
// first); the module inserts / deletes rows itself and saves its document WITHOUT the field.
|
||||
const ROWS = new Map(); const rowQ = []; let rowBusy = false;
|
||||
async function openSplit(sp) {
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
|
||||
const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id');
|
||||
ROWS.set(sp.table, r.map(x => JSON.parse(x.body)));
|
||||
}
|
||||
async function insertMany(table, items, key, ts) {
|
||||
for (let i = 0; i < items.length; i += 500) {
|
||||
const part = items.slice(i, i + 500);
|
||||
await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]);
|
||||
}
|
||||
}
|
||||
// first boot: the array still inside the document moves to its table, then the document is saved without it
|
||||
async function migrateSplit(sp) {
|
||||
const d = cache.get(sp.doc); if (!d) return;
|
||||
let obj; try { obj = JSON.parse(d.body); } catch (e) { return; }
|
||||
const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return;
|
||||
await insertMany(sp.table, arr, sp.key, sp.ts);
|
||||
const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`');
|
||||
if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed');
|
||||
const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key]))));
|
||||
merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged);
|
||||
obj[sp.field] = []; const body = JSON.stringify(obj);
|
||||
await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() });
|
||||
console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table);
|
||||
}
|
||||
function rows(table) { return ROWS.get(table) || null; }
|
||||
function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); }
|
||||
async function runRows() {
|
||||
rowBusy = true;
|
||||
try {
|
||||
while (rowQ.length && writer) {
|
||||
const op = rowQ[0];
|
||||
try {
|
||||
if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]);
|
||||
else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]);
|
||||
rowQ.shift();
|
||||
} catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); }
|
||||
}
|
||||
} finally { rowBusy = false; }
|
||||
}
|
||||
const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) });
|
||||
const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); };
|
||||
function isOn() { return ready && !!pool; }
|
||||
// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true.
|
||||
async function claim(key) {
|
||||
if (!pool) return true;
|
||||
await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB');
|
||||
const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]);
|
||||
return r.affectedRows === 1;
|
||||
}
|
||||
|
||||
// SIGTERM during a deploy: write what is pending, then exit
|
||||
async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } }
|
||||
function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); }
|
||||
module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim };
|
||||
+313
@@ -0,0 +1,313 @@
|
||||
'use strict';
|
||||
// 5xYourTeam "The Draft" partner side (Marty approved the rules 2026-11-15). The network holding tank lives HERE (tank.js);
|
||||
// 5xYourTeam coaches draft from it through four signed calls, and every pick is a real tank adoption through tank.adopt():
|
||||
//
|
||||
// POST /api/partner/draft/pool {} -> { ok, rules, pool: [card], excluded: {why: n} }
|
||||
// POST /api/partner/draft/adopt { rid, coach, person, kind, week?, slot?, note? } -> { ok, ref, person, adoptionId, at, expires, holdUntil }
|
||||
// POST /api/partner/draft/release { rid, coach, ref | person, why: 'coach' | 'return' } -> { ok, outcome: 'returned' | 'kept' | 'done' | <closed status>, already? }
|
||||
// POST /api/partner/draft/status { ids: [person id] } -> { ok, people: { id: milestones | null } }
|
||||
// coach = { wallet, hubId?, username?, positions } (the 5xYourTeam claim: positions = 5x positions this wallet holds)
|
||||
// card = { id, username, door, joinedAt, lastSeen, wallet (bool), ready, holdUntil, opensAt, adoptions (outside 5x), adoptionsTotal, games, surfWei, surfCredits }
|
||||
//
|
||||
// Signature: X-Draft-Ts (ms) + X-Draft-Sig = hex HMAC-SHA256(DRAFT_PARTNER_SECRET, 'draft.v1.' + ts + '\n' + raw body), 5-minute
|
||||
// window. A dedicated secret (not NETWORK_SSO_SECRET): this one can move sponsors. adopt and release carry a request id (rid): a
|
||||
// retried or replayed call answers what the first one did and changes nothing.
|
||||
//
|
||||
// The rules (project-5xyourteam-draft, 11-15):
|
||||
// - only 5xYourTeam position holders draft and coach: the signed claim (positions >= 1) REPLACES InstantAdPay's own-$20-buy rule
|
||||
// for these calls only (the member's own tank button keeps its $20 rule); a coach needs an account here with a wallet linked,
|
||||
// and someone on this contract in their line (tank.partnerEligibility); free members cannot adopt
|
||||
// - the pool = tank.waiting() (rule 3 already applied: nobody the hub reports locked on any contract or sponsored, nobody adopted
|
||||
// on LinkSpin) minus spam / suspended / flagged, throwaway or mistyped email domains, and anyone adopted twice already
|
||||
// - max 10 open picks a coach (and the tank's people-held-at-once cap); max 2 adoptions per person (every pick counts, both sites)
|
||||
// - a pick that has not STARTED (payouts on or a first purchase) in 3 days goes back to the pool; a coach cannot release one in its
|
||||
// first 48 hours; a person who has had their 2 adoptions stays with the coach (the tank sweep rule); started picks stay
|
||||
// - never anyone locked on a network contract: asked fresh at adopt and at every return; a hub that does not answer refuses / waits
|
||||
// - 24-hour sign-up grace (tank.adopt refuses it; the card carries opensAt); coaches never see contact data: no email, phone or
|
||||
// address leaves this module, person ids are hub ids (or an opaque i_ id the hub does not know)
|
||||
// - the only mail: tank.adopt's normal "X is now your sponsor" adoption email. No switch-on-payouts reminders for picks, no
|
||||
// payments-topic post (5xYourTeam posts its own Draft Day card)
|
||||
//
|
||||
// Auto-assign vs the 3-day window (the conflict the 5x build flagged), the rule implemented:
|
||||
// - a drafted person is an open adoption with a sponsor, so they are out of the tank: no 24-hour activation hold, no auto-assign,
|
||||
// no sign-up announcement, no dormant-lead rescue while the pick window runs
|
||||
// - the pick's adoption row expires at +3 days (not IAP's 7), and tank.sweep leaves it alone (hooks.isDraftPick): this module
|
||||
// closes it at 3 days with the pick's rule (started = payouts on or a purchase, a wallet alone is not started)
|
||||
// - a returned pick goes back with their ORIGINAL join time (account `created` is never touched, so no new sign-up grace) and,
|
||||
// with a wallet linked, a fresh 24-hour activation hold like anyone back in the tank (never the company)
|
||||
// - sponsor moves go through tank.js setSponsor (sponsorfollow + the hub's /v1/sponsor-change with by 'adopt' / 'release')
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const db = require('./db');
|
||||
|
||||
const H = 3600000, D = 86400000;
|
||||
const RULES = { returnMs: 3 * D, holdMs: 48 * H, maxOpen: 10, maxAdoptions: 2 };
|
||||
const ADDR = /^0x[0-9a-f]{40}$/;
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
// throwaway / disposable inboxes: the adoption email would go nowhere. Plus a mistyped big-provider domain (emailcheck.js).
|
||||
const THROWAWAY = new Set(['mailinator.com', 'guerrillamail.com', 'guerrillamail.net', 'sharklasers.com', 'grr.la', '10minutemail.com', 'tempmail.com', 'temp-mail.org',
|
||||
'yopmail.com', 'trashmail.com', 'getnada.com', 'maildrop.cc', 'dispostable.com', 'throwawaymail.com', 'fakeinbox.com', 'mintemail.com', 'mohmal.com', 'emailondeck.com',
|
||||
'tempail.com', 'tempr.email', 'discard.email', 'spamgourmet.com', 'mailnesia.com', 'mytemp.email', 'tempmailo.com', 'burnermail.io', 'example.com', 'test.com']);
|
||||
const DOORS = { iap: 'InstantAdPay', instantadpay: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', dlb: 'Downline Banners', vbb: 'Viral Banner Blitz',
|
||||
ctb: 'CryptoTeamBuild', fivex: '5xYourTeam', vab: 'ViralAdBlitz', viraladblitz: 'ViralAdBlitz', dh: 'DownlineHydra', btc4hits: 'BTC4Hits', stackpol: 'Stack POL' };
|
||||
|
||||
let R = null; // { dataDir, accounts, chain, tank, ads, hooks: { hubInfo, resolvePerson, excluded, spamEmails, networkOn, suggestDomain }, requireHub, clock }
|
||||
const clock = () => (R && R.clock ? R.clock() : Date.now());
|
||||
const SECRET = () => String((R && R.secret) || process.env.DRAFT_PARTNER_SECRET || '').trim();
|
||||
const enabled = () => SECRET().length >= 32;
|
||||
|
||||
// ---- storage: MySQL (draft_picks, draft_log) when DATABASE_URL is set, else a JSON document (local QA) ----
|
||||
const J = {
|
||||
st: null, FILE: () => path.join(R.dataDir, 'draft-partner.json'),
|
||||
load() { if (this.st) return this.st; try { this.st = JSON.parse(fs.readFileSync(this.FILE(), 'utf8')); } catch (e) { this.st = null; } if (!this.st || typeof this.st !== 'object') this.st = {}; this.st.nextId = this.st.nextId || 1; this.st.picks = this.st.picks || []; this.st.log = this.st.log || []; return this.st; },
|
||||
save() { const f = this.FILE(); fs.writeFileSync(f + '.tmp', JSON.stringify(this.load())); fs.renameSync(f + '.tmp', f); },
|
||||
async add(p) { const s = this.load(); const row = Object.assign({ id: s.nextId++ }, p); s.picks.push(row); this.save(); return Object.assign({}, row); },
|
||||
async put(p) { const s = this.load(); const i = s.picks.findIndex(x => x.id === p.id); if (i >= 0) s.picks[i] = Object.assign({}, p); this.save(); },
|
||||
async byId(id) { const x = this.load().picks.find(r => r.id === Number(id)); return x ? Object.assign({}, x) : null; },
|
||||
async byRid(rid) { const x = this.load().picks.find(r => r.rid === rid); return x ? Object.assign({}, x) : null; },
|
||||
async byAdoption(aid) { const x = this.load().picks.find(r => r.adoptionId === Number(aid)); return x ? Object.assign({}, x) : null; },
|
||||
async ofPerson(pid) { return this.load().picks.filter(r => r.personId === pid).map(x => Object.assign({}, x)); },
|
||||
async open() { return this.load().picks.filter(r => r.status === 'open').map(x => Object.assign({}, x)); },
|
||||
async openOfCoach(w) { return this.load().picks.filter(r => r.status === 'open' && r.coachWallet === w).map(x => Object.assign({}, x)); },
|
||||
async recent(n) { return this.load().picks.slice(-(n || 100)).reverse().map(x => Object.assign({}, x)); },
|
||||
async countsByAdoptee() { const m = new Map(); for (const r of this.load().picks) m.set(r.adoptee, (m.get(r.adoptee) || 0) + 1); return m; },
|
||||
async log(row) { const s = this.load(); s.log.push(row); if (s.log.length > 2000) s.log = s.log.slice(-2000); this.save(); },
|
||||
async logs(n) { return this.load().log.slice(-(n || 100)).reverse(); }
|
||||
};
|
||||
const COLS = ['rid', 'adoptionId', 'adoptee', 'personId', 'coachEmail', 'coachWallet', 'coachHubId', 'kind', 'week', 'slot', 'ts', 'expires', 'holdUntil', 'status', 'closed', 'outcomeWhy', 'walletAt', 'payoutsAt', 'purchaseAt'];
|
||||
const SQLC = { rid: 'rid', adoptionId: 'adoption_id', adoptee: 'adoptee', personId: 'person_id', coachEmail: 'coach_email', coachWallet: 'coach_wallet', coachHubId: 'coach_hub_id', kind: 'kind', week: 'week', slot: 'slot', ts: 'ts', expires: 'expires', holdUntil: 'hold_until', status: 'status', closed: 'closed', outcomeWhy: 'outcome_why', walletAt: 'wallet_at', payoutsAt: 'payouts_at', purchaseAt: 'purchase_at' };
|
||||
const NUM = new Set(['adoptionId', 'ts', 'expires', 'holdUntil', 'closed', 'walletAt', 'payoutsAt', 'purchaseAt']);
|
||||
const rowP = r => { if (!r) return null; const o = { id: Number(r.id) }; for (const k of COLS) { const v = r[SQLC[k]]; o[k] = NUM.has(k) ? Number(v || 0) : (v == null ? null : String(v)); } return o; };
|
||||
const Q = {
|
||||
async add(p) { const r = await db.q('INSERT INTO draft_picks (' + COLS.map(k => SQLC[k]).join(',') + ') VALUES (' + COLS.map(() => '?').join(',') + ')', COLS.map(k => p[k] == null ? null : p[k])); return Object.assign({ id: r.insertId }, p); },
|
||||
async put(p) { await db.q('UPDATE draft_picks SET ' + COLS.map(k => SQLC[k] + '=?').join(',') + ' WHERE id=?', COLS.map(k => p[k] == null ? null : p[k]).concat([p.id])); },
|
||||
async byId(id) { return rowP((await db.q('SELECT * FROM draft_picks WHERE id=?', [Number(id)]))[0]); },
|
||||
async byRid(rid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE rid=?', [rid]))[0]); },
|
||||
async byAdoption(aid) { return rowP((await db.q('SELECT * FROM draft_picks WHERE adoption_id=?', [Number(aid)]))[0]); },
|
||||
async ofPerson(pid) { return (await db.q('SELECT * FROM draft_picks WHERE person_id=? ORDER BY id', [pid])).map(rowP); },
|
||||
async open() { return (await db.q("SELECT * FROM draft_picks WHERE status='open' ORDER BY id")).map(rowP); },
|
||||
async openOfCoach(w) { return (await db.q("SELECT * FROM draft_picks WHERE status='open' AND coach_wallet=?", [w])).map(rowP); },
|
||||
async recent(n) { return (await db.q('SELECT * FROM draft_picks ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(rowP); },
|
||||
async countsByAdoptee() { return new Map((await db.q('SELECT adoptee, COUNT(*) n FROM draft_picks GROUP BY adoptee')).map(r => [r.adoptee, Number(r.n)])); },
|
||||
async log(x) { await db.q('INSERT INTO draft_log (ts,op,ok,code,reason,coach,person,ref,rid) VALUES (?,?,?,?,?,?,?,?,?)', [x.ts, x.op, x.ok ? 1 : 0, x.code || null, String(x.reason || '').slice(0, 400), x.coach || null, x.person || null, x.ref || null, x.rid || null]); },
|
||||
async logs(n) { return (await db.q('SELECT * FROM draft_log ORDER BY id DESC LIMIT ?', [Number(n) || 100])).map(r => ({ ts: Number(r.ts), op: r.op, ok: !!r.ok, code: r.code, reason: r.reason, coach: r.coach, person: r.person, ref: r.ref, rid: r.rid })); }
|
||||
};
|
||||
const S = () => (db.enabled() ? Q : J);
|
||||
async function ensureTables() {
|
||||
if (!db.enabled()) return;
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS draft_picks (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, rid VARCHAR(80) NOT NULL, adoption_id INT NOT NULL, adoptee VARCHAR(190) NOT NULL, person_id VARCHAR(40) NOT NULL,
|
||||
coach_email VARCHAR(190) NOT NULL, coach_wallet VARCHAR(42) NOT NULL, coach_hub_id VARCHAR(40) NULL, kind VARCHAR(16) NULL, week VARCHAR(16) NULL, slot VARCHAR(16) NULL,
|
||||
ts BIGINT NOT NULL, expires BIGINT NOT NULL, hold_until BIGINT NOT NULL, status VARCHAR(16) NOT NULL, closed BIGINT NULL, outcome_why VARCHAR(200) NULL,
|
||||
wallet_at BIGINT NULL, payouts_at BIGINT NULL, purchase_at BIGINT NULL,
|
||||
UNIQUE KEY rid (rid), KEY adoption (adoption_id), KEY person (person_id), KEY coach (coach_wallet, status), KEY st (status)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // 5xYourTeam draft picks (each one a tank adoption)
|
||||
await db.q(`CREATE TABLE IF NOT EXISTS draft_log (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY, ts BIGINT NOT NULL, op VARCHAR(16) NOT NULL, ok TINYINT NOT NULL, code VARCHAR(40) NULL, reason VARCHAR(400) NULL,
|
||||
coach VARCHAR(42) NULL, person VARCHAR(40) NULL, ref VARCHAR(40) NULL, rid VARCHAR(80) NULL, KEY t (ts)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4`); // every partner call, with its reason
|
||||
}
|
||||
|
||||
async function init(opts) { R = opts; if (R.tank && R.tank.GRACE_MS) RULES.graceMs = R.tank.GRACE_MS; await ensureTables(); }
|
||||
|
||||
// ---- signature ----
|
||||
function sign(ts, raw, secret) { return crypto.createHmac('sha256', secret || SECRET()).update('draft.v1.' + ts + '\n' + raw).digest('hex'); }
|
||||
function verify(headers, raw) {
|
||||
if (!enabled()) return { status: 503, error: 'draft partner not configured' };
|
||||
const ts = String(headers['x-draft-ts'] || ''), sig = String(headers['x-draft-sig'] || '');
|
||||
if (!/^\d{13}$/.test(ts) || Math.abs(Date.now() - Number(ts)) > 5 * 60000) return { status: 401, error: 'stale' };
|
||||
const want = sign(ts, raw);
|
||||
if (want.length !== sig.length || !crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig))) return { status: 401, error: 'bad signature' };
|
||||
try { const b = JSON.parse(raw || '{}'); return b && typeof b === 'object' ? { body: b } : { status: 400, error: 'bad json' }; } catch (e) { return { status: 400, error: 'bad json' }; }
|
||||
}
|
||||
|
||||
// ---- helpers ----
|
||||
const idOf = email => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; return hi && /^h_[0-9a-f]{16}$/.test(hi.id) ? hi.id : 'i_' + crypto.createHmac('sha256', SECRET() || 'local').update('pid:' + lc(email)).digest('hex').slice(0, 16); };
|
||||
const doorOf = (email, via) => { const hi = R.hooks && R.hooks.hubInfo ? R.hooks.hubInfo(email) : null; const k = lc((hi && hi.door) || via); return DOORS[k] || (k === 'hub' ? 'Network' : 'InstantAdPay'); };
|
||||
function throwaway(email) {
|
||||
const d = lc(email).split('@')[1] || ''; if (!d) return true;
|
||||
if (THROWAWAY.has(d)) return true;
|
||||
const fix = R.hooks && R.hooks.suggestDomain ? R.hooks.suggestDomain(d) : null; return !!(fix && fix !== d); // a mistyped provider: the mail bounces
|
||||
}
|
||||
function spamSet() { try { return new Set((R.hooks && R.hooks.spamEmails ? R.hooks.spamEmails() : []).map(lc)); } catch (e) { return new Set(); } }
|
||||
const hubOff = () => R.requireHub !== false && !(R.hooks && R.hooks.networkOn && R.hooks.networkOn());
|
||||
async function logCall(op, x) { const row = Object.assign({ ts: clock(), op }, x); try { await S().log(row); } catch (e) { console.error('draft log', e.message); } if (!x.ok) console.log('draft', op, 'refused', x.code || '', String(x.reason || '').slice(0, 120)); return row; }
|
||||
const fail = async (op, code, reason, x) => { await logCall(op, Object.assign({ ok: false, code, reason }, x || {})); return { error: reason, code }; };
|
||||
function purchasers() { const s = new Set(); for (const ev of R.chain.recentEvents(1e9)) if (ev.type === 'Purchase' && ev.buyerId) s.add(Number(ev.buyerId)); return s; }
|
||||
|
||||
// a coach: the wallet that holds the 5x position, then a position wallet here, then the hub's person for the hub id
|
||||
async function coachAccount(c) {
|
||||
const w = lc(c && c.wallet); if (!ADDR.test(w)) return { code: 'bad_coach', reason: 'Which coach? (wallet missing)' };
|
||||
let a = await R.accounts.byAddress(w).catch(() => null);
|
||||
if (!a && R.accounts.positionOwner) { const po = await R.accounts.positionOwner(w).catch(() => null); if (po && po.email) a = await R.accounts.byEmail(po.email); }
|
||||
if (!a && c.hubId && R.hooks && R.hooks.resolvePerson) { try { const p = await R.hooks.resolvePerson({ id: String(c.hubId) }); if (p && p.email && !p.blocked) a = await R.accounts.byEmail(lc(p.email)); } catch (e) {} }
|
||||
if (!a) return { code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link a wallet.' };
|
||||
return { account: a, wallet: w };
|
||||
}
|
||||
|
||||
// ---- the pool ----
|
||||
let poolCache = null;
|
||||
async function poolRows(fresh) {
|
||||
if (!fresh && poolCache && clock() - poolCache.at < 30000) return poolCache;
|
||||
const list = await R.tank.waiting(); const spam = spamSet(); const ex = { spam: 0, throwaway: 0, adoptedTwice: 0 };
|
||||
const local = await R.tank.summaryMap(); const mine = await S().countsByAdoptee(); const rows = [];
|
||||
for (const w of list) {
|
||||
if ((R.hooks.excluded && R.hooks.excluded(w.email)) || spam.has(lc(w.email))) { ex.spam++; continue; }
|
||||
if (throwaway(w.email)) { ex.throwaway++; continue; }
|
||||
const n = ((local.get(w.email) || {}).count || 0) + (R.tank.remoteCount ? R.tank.remoteCount(w.email) : 0);
|
||||
if (n >= RULES.maxAdoptions) { ex.adoptedTwice++; continue; }
|
||||
rows.push({ email: w.email, card: { id: idOf(w.email), username: w.username || null, door: doorOf(w.email, w.via), joinedAt: Number(w.joined) || 0, lastSeen: Number(w.lastSeen) || 0,
|
||||
// adoptions = OUTSIDE 5xYourTeam (5xYourTeam adds its own picks; counting them here too would double them); adoptionsTotal = all
|
||||
wallet: !!w.wallet, ready: !!w.ready, holdUntil: w.holdUntil || 0, opensAt: w.opensAt || 0, adoptions: Math.max(0, n - (mine.get(w.email) || 0)), adoptionsTotal: n,
|
||||
games: null, surfWei: null, surfCredits: Number(w.earned) || 0 } }); // games: InstantAdPay keeps no per-member game record (never invented)
|
||||
}
|
||||
poolCache = { at: clock(), rows, excluded: ex }; return poolCache;
|
||||
}
|
||||
async function pool() {
|
||||
if (hubOff()) { await logCall('pool', { ok: false, code: 'hub_off', reason: 'the network hub is off, so locked people cannot be ruled out' }); return { ok: true, rules: rulesView(), pool: [], excluded: {}, hubOff: true }; }
|
||||
const p = await poolRows(false);
|
||||
return { ok: true, rules: rulesView(), pool: p.rows.map(r => r.card), excluded: p.excluded };
|
||||
}
|
||||
const rulesView = () => ({ returnHours: RULES.returnMs / H, holdHours: RULES.holdMs / H, maxOpen: RULES.maxOpen, maxAdoptions: RULES.maxAdoptions, graceHours: (RULES.graceMs || D) / H });
|
||||
|
||||
// ---- adopt ----
|
||||
async function adopt(b) {
|
||||
const rid = String(b.rid || '').slice(0, 80); const c = b.coach || {}; const pid = String(b.person || '').slice(0, 40); const kind = /^(draft|instant)$/.test(b.kind) ? b.kind : 'draft';
|
||||
const x = { coach: lc(c.wallet) || null, person: pid || null, rid };
|
||||
if (!/^[A-Za-z0-9_.:-]{8,80}$/.test(rid)) return fail('adopt', 'bad_rid', 'A request id (rid) is required.', x);
|
||||
const prev = await S().byRid(rid);
|
||||
if (prev) return { ok: true, repeat: true, ref: 'iap:' + prev.id, person: prev.personId, adoptionId: prev.adoptionId, at: prev.ts, expires: prev.expires, holdUntil: prev.holdUntil };
|
||||
if (!(Number(c.positions) >= 1)) return fail('adopt', 'not_vested', 'Only 5xYourTeam position holders can draft and coach.', x);
|
||||
if (hubOff()) return fail('adopt', 'hub_off', 'The network hub is off, so nobody can be drafted right now.', x);
|
||||
const co = await coachAccount(c); if (!co.account) return fail('adopt', co.code, co.reason, x);
|
||||
if ((await S().openOfCoach(co.wallet)).length >= RULES.maxOpen) return fail('adopt', 'full', 'Your team is full (' + RULES.maxOpen + ' open picks). Help one get started first.', x);
|
||||
const hit = (await poolRows(true)).rows.find(r => r.card.id === pid);
|
||||
if (!hit) return fail('adopt', 'gone', 'That player is no longer in the holding tank.', x);
|
||||
const r = await R.tank.adopt(co.account.email, hit.email, String(b.note || ''), { partner: { positions: Number(c.positions), ttlMs: RULES.returnMs, maxOpen: RULES.maxOpen }, recordNote: '5xYourTeam draft pick (' + kind + (b.week ? ', week ' + String(b.week).slice(0, 10) : '') + (b.slot ? ', slot ' + String(b.slot).slice(0, 10) : '') + ')' });
|
||||
if (!r || !r.ok) return fail('adopt', (r && r.code) || 'refused', (r && r.error) || 'The tank refused.', x);
|
||||
poolCache = null;
|
||||
const now = clock(); const acct = await R.accounts.byEmail(hit.email);
|
||||
const pick = await S().add({ rid, adoptionId: Number(r.adoption.id), adoptee: hit.email, personId: pid, coachEmail: co.account.email, coachWallet: co.wallet, coachHubId: c.hubId ? String(c.hubId).slice(0, 40) : null,
|
||||
kind, week: b.week ? String(b.week).slice(0, 16) : null, slot: b.slot ? String(b.slot).slice(0, 16) : null, ts: now, expires: now + RULES.returnMs, holdUntil: now + RULES.holdMs, status: 'open', closed: 0, outcomeWhy: null,
|
||||
walletAt: acct && acct.address ? now : 0, payoutsAt: 0, purchaseAt: 0 });
|
||||
await logCall('adopt', Object.assign(x, { ok: true, ref: 'iap:' + pick.id, reason: kind + ' pick by ' + (c.username ? '@' + String(c.username).slice(0, 40) : x.coach) }));
|
||||
return { ok: true, ref: 'iap:' + pick.id, person: pid, adoptionId: pick.adoptionId, at: pick.ts, expires: pick.expires, holdUntil: pick.holdUntil };
|
||||
}
|
||||
|
||||
// is the pick's adoption still the open one? (released on InstantAdPay itself, moved by a LinkSpin follow, ...) -> closed here too
|
||||
async function reconcile(p) {
|
||||
if (p.status !== 'open') return p;
|
||||
const open = await R.tank.openOf(p.adoptee);
|
||||
if (open.some(ad => Number(ad.id) === p.adoptionId)) return p;
|
||||
p.status = 'moved'; p.closed = clock(); p.outcomeWhy = 'the adoption was closed on InstantAdPay (released, moved or followed from LinkSpin)'; await S().put(p);
|
||||
await logCall('reconcile', { ok: true, code: 'moved', reason: p.outcomeWhy, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
|
||||
return p;
|
||||
}
|
||||
// milestones seen so far (first-seen times; the chain events carry no timestamps here)
|
||||
async function observe(p, a, buyers) {
|
||||
if (!a) return p; const now = clock(); let ch = false;
|
||||
if (a.address && !p.walletAt) { p.walletAt = now; ch = true; }
|
||||
if (Number(a.memberId) > 0 && !p.payoutsAt) { p.payoutsAt = now; ch = true; }
|
||||
if (Number(a.memberId) > 0 && !p.purchaseAt && buyers && buyers.has(Number(a.memberId))) { p.purchaseAt = now; ch = true; }
|
||||
if (ch) await S().put(p); return p;
|
||||
}
|
||||
const started = (p, a) => !!(a && Number(a.memberId) > 0) || !!(p.payoutsAt || p.purchaseAt);
|
||||
|
||||
// close one open pick: 'coach' (released after the 48 h hold) or 'return' (3 days, not started). Shared by release() and sweep().
|
||||
async function closePick(p, why, now) {
|
||||
const a = await R.accounts.byEmail(p.adoptee);
|
||||
await observe(p, a, purchasers());
|
||||
if (started(p, a)) { p.status = 'done'; p.closed = now; p.outcomeWhy = 'started (payouts on or a purchase)'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'done'); return { outcome: 'done', why: p.outcomeWhy }; }
|
||||
if (why === 'coach' && now < p.holdUntil) return { code: 'hold', reason: 'You picked them less than ' + (RULES.holdMs / H) + ' hours ago. Give them a little time first (' + Math.ceil((p.holdUntil - now) / H) + ' h left).' };
|
||||
if (why === 'return' && now < p.expires) return { code: 'too_early', reason: 'The pick window runs until ' + new Date(p.expires).toISOString() + '.' };
|
||||
const count = await R.tank.countAll(p.adoptee);
|
||||
if (count >= RULES.maxAdoptions) { // their second adoption: they stay with this coach (the tank sweep rule, never back to nobody)
|
||||
p.status = 'kept'; p.closed = now; p.outcomeWhy = 'adopted twice: stays with this coach'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired');
|
||||
return { outcome: 'kept', why: p.outcomeWhy };
|
||||
}
|
||||
const lk = await R.tank.lockedWhy(p.adoptee);
|
||||
if (lk === 'unknown') return { code: 'hub_unknown', reason: 'The network record cannot be checked right now. Try again later.' };
|
||||
if (lk === 'locked') { p.status = 'kept'; p.closed = now; p.outcomeWhy = 'locked on a network contract: never moved'; await S().put(p); await R.tank.closeAdoption(p.adoptionId, 'expired'); return { outcome: 'kept', why: p.outcomeWhy }; }
|
||||
const note = why === 'return' ? '5xYourTeam pick returned: not started in ' + (RULES.returnMs / D) + ' days' : '5xYourTeam pick released by the coach';
|
||||
const r = await R.tank.setSponsorDeliberate(p.adoptee, '', 'release', note);
|
||||
if (r && r.error) return { code: 'refused', reason: r.error };
|
||||
await R.tank.closeAdoption(p.adoptionId, why === 'return' ? 'expired' : 'dropped'); // both still count toward their two adoptions
|
||||
p.status = 'returned'; p.closed = now; p.outcomeWhy = note; await S().put(p); poolCache = null;
|
||||
return { outcome: 'returned', why: note };
|
||||
}
|
||||
|
||||
async function findPick(b) {
|
||||
const ref = String(b.ref || ''); const m = /^iap:(\d+)$/.exec(ref);
|
||||
if (m) return S().byId(Number(m[1]));
|
||||
const pid = String(b.person || ''); const w = lc(b.coach && b.coach.wallet);
|
||||
const rows = (await S().ofPerson(pid)).filter(p => p.coachWallet === w); return rows.find(p => p.status === 'open') || rows[rows.length - 1] || null;
|
||||
}
|
||||
async function release(b) {
|
||||
const why = b.why === 'return' ? 'return' : 'coach'; const w = lc(b.coach && b.coach.wallet); const rid = String(b.rid || '').slice(0, 80);
|
||||
const x = { coach: w || null, person: b.person ? String(b.person).slice(0, 40) : null, rid, ref: b.ref ? String(b.ref).slice(0, 40) : null };
|
||||
let p = await findPick(b);
|
||||
if (!p) return fail('release', 'no_pick', 'No such pick.', x);
|
||||
if (p.coachWallet !== w) return fail('release', 'not_yours', 'Not your pick.', x);
|
||||
x.person = p.personId; x.ref = 'iap:' + p.id;
|
||||
p = await reconcile(p);
|
||||
if (p.status !== 'open') { await logCall('release', Object.assign(x, { ok: true, code: 'already', reason: why + ': already ' + p.status })); return { ok: true, already: true, outcome: p.status }; }
|
||||
const r = await closePick(p, why, clock());
|
||||
if (!r.outcome) return fail('release', r.code, r.reason, x);
|
||||
await logCall('release', Object.assign(x, { ok: true, code: r.outcome, reason: why + ': ' + r.why }));
|
||||
return { ok: true, outcome: r.outcome };
|
||||
}
|
||||
|
||||
// ---- status: milestones for the people 5xYourTeam holds picks for (anyone else answers null) ----
|
||||
async function status(b) {
|
||||
const ids = [...new Set((Array.isArray(b.ids) ? b.ids : []).map(v => String(v || '').slice(0, 40)).filter(Boolean))].slice(0, 500);
|
||||
const buyers = purchasers(); const out = {};
|
||||
const emails = []; const picksBy = {};
|
||||
for (const id of ids) { const rows = await S().ofPerson(id); if (!rows.length) { out[id] = null; continue; } picksBy[id] = rows; emails.push(rows[0].adoptee); }
|
||||
const tot = R.ads && R.ads.earnedTotals ? await R.ads.earnedTotals(emails).catch(() => ({})) : {};
|
||||
for (const id of Object.keys(picksBy)) {
|
||||
const rows = picksBy[id]; let last = rows[rows.length - 1]; const email = last.adoptee;
|
||||
const a = await R.accounts.byEmail(email); if (!a) { out[id] = null; continue; }
|
||||
last = await reconcile(last); last = await observe(last, a, buyers);
|
||||
const count = await R.tank.countAll(email);
|
||||
out[id] = { username: a.username || null, door: doorOf(email, a.joinedVia), lastSeen: Number(a.lastSeen) || 0,
|
||||
wallet: a.address ? (rows.map(r => r.walletAt).filter(Boolean).sort((x, y) => x - y)[0] || clock()) : 0,
|
||||
payouts: Number(a.memberId) > 0 ? (last.payoutsAt || clock()) : 0, purchase: Number(a.memberId) > 0 && buyers.has(Number(a.memberId)) ? (last.purchaseAt || clock()) : 0,
|
||||
adoptions: Math.max(0, count - rows.length), // adoptions outside 5xYourTeam (5x counts its own picks itself)
|
||||
games: null, surfWei: null, surfCredits: (tot[email] || {}).earned || 0,
|
||||
pick: { ref: 'iap:' + last.id, status: last.status, coachWallet: last.coachWallet, expires: last.expires, holdUntil: last.holdUntil } };
|
||||
}
|
||||
return { ok: true, people: out };
|
||||
}
|
||||
|
||||
// ---- the hourly sweep (server.js, beside tank.sweep): started picks close as done, unstarted ones past 3 days go back ----
|
||||
let sweeping = null;
|
||||
function sweep() { if (!sweeping) sweeping = sweepRun().finally(() => { sweeping = null; }); return sweeping; }
|
||||
async function sweepRun() {
|
||||
const now = clock(); const out = { done: 0, returned: 0, kept: 0, moved: 0, waiting: 0 }; const buyers = purchasers();
|
||||
for (let p of await S().open()) {
|
||||
p = await reconcile(p); if (p.status !== 'open') { out.moved++; continue; }
|
||||
const a = await R.accounts.byEmail(p.adoptee); await observe(p, a, buyers);
|
||||
if (!started(p, a) && now < p.expires) continue;
|
||||
const r = await closePick(p, 'return', now);
|
||||
if (!r.outcome) { out.waiting++; continue; }
|
||||
out[r.outcome] = (out[r.outcome] || 0) + 1;
|
||||
await logCall('sweep', { ok: true, code: r.outcome, reason: r.why, coach: p.coachWallet, person: p.personId, ref: 'iap:' + p.id });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// tank.sweep asks this before closing an expired adoption (the pick's own rule decides)
|
||||
async function isDraftPick(adoptionId) { if (!R) return false; const p = await S().byAdoption(adoptionId); return !!(p && p.status === 'open'); }
|
||||
|
||||
async function adminView() { return { enabled: enabled(), rules: rulesView(), hubOff: hubOff(), picks: (await S().recent(200)).map(p => Object.assign({}, p, { adoptee: undefined, coachEmail: undefined })), log: await S().logs(200) }; }
|
||||
|
||||
// one entry for the HTTP routes (server.js) and the cross-repo test: op = pool | adopt | release | status
|
||||
async function handle(op, body) {
|
||||
if (op === 'pool') return pool();
|
||||
if (op === 'adopt') return adopt(body);
|
||||
if (op === 'release') return release(body);
|
||||
if (op === 'status') return status(body);
|
||||
return { error: 'unknown op', code: 'unknown_op' };
|
||||
}
|
||||
|
||||
module.exports = { init, enabled, verify, sign, handle, pool, adopt, release, status, sweep, isDraftPick, adminView, RULES, _poolReset: () => { poolCache = null; } };
|
||||
+2
-1
@@ -34,7 +34,8 @@ function redirectFor(v, acct, site) {
|
||||
const p = new URLSearchParams({ nonce: v.nonce, email, external_id: email, require_activation: 'false', suppress_welcome_message: 'false' });
|
||||
if (acct.username) { p.set('username', acct.username); p.set('name', acct.username); }
|
||||
if (acct.avatarUrl) p.set('avatar_url', /^https?:/.test(acct.avatarUrl) ? acct.avatarUrl : site + acct.avatarUrl);
|
||||
if (acct.username) p.set('website', 'https://stackpol.com/' + acct.username);
|
||||
// no website on sign-in (Marty 2026-11-14): Discourse holds a new user who "entered profile information without reading" for
|
||||
// approval, and the stackpol.com link we filled in put every new member in the review queue. Members add their own.
|
||||
if (groups.length) p.set('add_groups', groups.join(','));
|
||||
const remove = ['network_members', 'wallet_linked'].filter(g => !groups.includes(g)); if (remove.length) p.set('remove_groups', remove.join(','));
|
||||
const out = Buffer.from(p.toString()).toString('base64');
|
||||
|
||||
+20
-7
@@ -71,14 +71,19 @@ const r6 = x => Math.round((Number(x) || 0) * 1e6) / 1e6;
|
||||
// three). Settings (Admin > Settings, no deploy): heroSales (sale switch, default OFF), heroPrice<Set>Cents per hero (0 = free for
|
||||
// every account, granted like a base hero), heroBundlePriceCents, heroBundleHeroes, heroBundleCap (a level the bundle would raise the
|
||||
// cap to; UNSET = no cap change, Marty has not approved one). key = the wire value Shards of Valor reads (classes.json paid buy).
|
||||
// 2026-11-14 (Marty approved, "Yes make it free"; Dallas: "The Archer should be free to everyone at level 20"): Kestrel is FREE for every
|
||||
// player once a hero in their party reaches level 20 (the game decides, Shards of Valor classes.json freeAt) and is NOT SOLD here any more
|
||||
// (freeAt): no buy, not in any bundle, waiting Kestrel orders are cancelled unpaid. A member who bought her keeps her (record.heroes.kestrel);
|
||||
// nothing refunded. Valda, Morag and Roland, the $50 bundle and every price are unchanged.
|
||||
const HERO_DEFS = [
|
||||
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
|
||||
{ key: 'kestrel', set: 'Kestrel', name: 'Kestrel the Archer', price: 2000, freeAt: 20, blurb: 'Quick and sharp-eyed: arrows on every foe.' },
|
||||
{ key: 'valda', set: 'Valda', name: 'Valda the Barbarian', price: 2000, blurb: 'A berserker: hits harder the more she is hurt, light on armour.' },
|
||||
{ key: 'morag', set: 'Morag', name: 'Morag the Druid', price: 2000, blurb: 'A healer of the wild: heals the whole party.' },
|
||||
{ key: 'roland', set: 'Roland', name: 'Roland the Paladin', price: 2000, blurb: 'A holy knight: sword and shield, heals one hero at a time.' },
|
||||
];
|
||||
const HERO_KEYS = HERO_DEFS.map(d => d.key);
|
||||
const HERO_DEF = Object.fromEntries(HERO_DEFS.map(d => [d.key, d]));
|
||||
const HERO_SOLD = HERO_DEFS.filter(d => !d.freeAt).map(d => d.key); // free at a level in the game (Kestrel at 20): never sold, never in a bundle
|
||||
const HERO_BUNDLE_DEFAULT = 'valda,morag,roland';
|
||||
|
||||
let R = null; // deps from server.js
|
||||
@@ -129,7 +134,7 @@ function cfg() {
|
||||
heroes: (() => {
|
||||
const price = Object.fromEntries(HERO_DEFS.map(d => [d.key, Math.max(0, Math.round(n('heroPrice' + d.set + 'Cents', d.price)))]));
|
||||
const raw = sc.heroBundleHeroes == null || String(sc.heroBundleHeroes).trim() === '' ? HERO_BUNDLE_DEFAULT : String(sc.heroBundleHeroes);
|
||||
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_KEYS.includes(k) && price[k] > 0))];
|
||||
const list = [...new Set(raw.split(',').map(x => x.trim().toLowerCase()).filter(k => HERO_SOLD.includes(k) && price[k] > 0))];
|
||||
const capRaw = String(sc.heroBundleCap == null ? '' : sc.heroBundleCap).trim(), cap = capRaw === '' ? NaN : Number(capRaw);
|
||||
return { sale: on('heroSales'), price, free: HERO_KEYS.filter(k => price[k] === 0), bundle: { heroes: list.length >= 2 ? list : [], price: Math.max(1, Math.round(n('heroBundlePriceCents', 5000))) },
|
||||
cap: Number.isInteger(cap) && cap > 0 ? cap : null };
|
||||
@@ -362,12 +367,19 @@ async function onEvent(ev) {
|
||||
// ---- bonus heroes (2026-11-05) ----
|
||||
// owned for good: record.heroes = { kestrel: { ts, via, tx, order, cents, usd, bundle? } }, record.heroBundle = { ts, via, heroes, tx, order }
|
||||
// (in the passes map, the same durable record as the passes). A hero is never in `bought`, so hero sales never feed the Pass Tournament pool.
|
||||
function heroOrders(e) { const out = []; for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') out.push(Object.assign({ order: k }, o)); return out; }
|
||||
function heroOrders(e) {
|
||||
const out = [];
|
||||
for (const [k, o] of orders) if (o.status === 'waiting' && o.email === e && o.kind === 'hero') {
|
||||
if (HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt) { orders.set(k, Object.assign({}, o, { status: 'cancelled', cancelledAt: Date.now(), why: 'free at level ' + HERO_DEF[o.hero].freeAt + ' in the game' })); continue; } // never paid: she is free now
|
||||
out.push(Object.assign({ order: k }, o));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
function heroOrder(e, key) { return heroOrders(e).find(o => o.hero === key) || null; }
|
||||
const heroOrderPrice = (c, key) => key === 'bundle' ? c.heroes.bundle.price : (c.heroes.price[key] || 0);
|
||||
const heroOrderPrices = c => [c.heroes.bundle.price].concat(Object.values(c.heroes.price).filter(x => x > 0));
|
||||
const heroOrderPrices = c => [c.heroes.bundle.price].concat(HERO_SOLD.map(k => c.heroes.price[k]).filter(x => x > 0));
|
||||
// a waiting hero order still worth fulfilling: nothing in it is owned yet (a bundle also needs its list set)
|
||||
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_KEYS.includes(key) && !own.has(key); }
|
||||
function heroOrderOpen(e, key) { const c = cfg(), own = new Set(heroesOwned(e).owned); if (key === 'bundle') return c.heroes.bundle.heroes.length > 0 && !c.heroes.bundle.heroes.some(k => own.has(k)); return HERO_SOLD.includes(key) && !own.has(key); }
|
||||
// -> { owned: bought, comped and free heroes; bought: on the record; bundle: bought as the bundle }
|
||||
function heroesOwned(email) {
|
||||
const p = rec(String(email || '').toLowerCase()), c = cfg(), H = (p && p.heroes) || {};
|
||||
@@ -393,7 +405,7 @@ function grantHeroes(e, key, via, extra, now) {
|
||||
// the member card part: every hero, its price and state, and the bundle. open = on sale (heroSales) or the admin portal's test (opts.preview)
|
||||
function heroView(email, now, opts) {
|
||||
const e = String(email || '').toLowerCase(), c = cfg(), h = heroesOwned(e), own = new Set(h.owned), preview = !!(opts && opts.preview), open = c.heroes.sale || preview;
|
||||
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key]; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, owned: own.has(d.key), waiting: !!heroOrder(e, d.key), open: open && price > 0 && !own.has(d.key) }; });
|
||||
const items = HERO_DEFS.map(d => { const price = c.heroes.price[d.key], fa = d.freeAt || null; return { key: d.key, name: d.name, blurb: d.blurb, price, usd: price / 100, package: packageFor(price / 100), free: price === 0, freeAt: fa, owned: own.has(d.key), waiting: !fa && !!heroOrder(e, d.key), open: !fa && open && price > 0 && !own.has(d.key) }; });
|
||||
const B = c.heroes.bundle, bOwn = B.heroes.filter(k => own.has(k));
|
||||
const bundle = B.heroes.length ? { key: 'bundle', names: B.heroes.map(k => HERO_DEF[k].name), heroes: B.heroes, price: B.price, usd: B.price / 100, package: packageFor(B.price / 100), owned: bOwn.length === B.heroes.length, some: bOwn.length > 0, waiting: !!heroOrder(e, 'bundle'), open: open && !bOwn.length } : null;
|
||||
return { sale: c.heroes.sale, preview: preview && !c.heroes.sale, show: c.heroes.sale || preview || h.bought.length > 0, items, bundle, owned: h.owned, bundleOwned: h.bundle };
|
||||
@@ -410,6 +422,7 @@ function buyHero(email, now, key, opts) {
|
||||
const B = c.heroes.bundle; if (!B.heroes.length) return { error: 'There is no hero bundle right now.' };
|
||||
const have = B.heroes.filter(k => own.has(k)); if (have.length) return { error: 'You already have ' + have.map(k => HERO_DEF[k].name).join(' and ') + ', so the bundle is not for you: get the others one at a time.' };
|
||||
} else {
|
||||
if (HERO_DEF[key].freeAt) return { error: HERO_DEF[key].name + ' is free for every player at level ' + HERO_DEF[key].freeAt + ' in Shards of Valor, so she is not for sale.' };
|
||||
if (c.heroes.price[key] === 0) return { error: HERO_DEF[key].name + ' is free for everyone.' };
|
||||
if (own.has(key)) return { error: 'You already have ' + HERO_DEF[key].name + '. Heroes are yours for good.' };
|
||||
}
|
||||
@@ -444,7 +457,7 @@ function heroStats() {
|
||||
for (const [k, h] of Object.entries(p.heroes || {})) { if (!(k in out.sold)) continue; if (h.via === 'admin') { out.comped += 1; continue; } out.sold[k] += 1; if (!h.bundle) out.usd += Number(h.usd) || 0; }
|
||||
if (p.heroBundle && p.heroBundle.via !== 'admin') { out.bundles += 1; out.usd += Number(p.heroBundle.usd) || 0; }
|
||||
}
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero') out.waiting += 1;
|
||||
for (const [, o] of orders) if (o.status === 'waiting' && o.kind === 'hero' && !(HERO_DEF[o.hero] && HERO_DEF[o.hero].freeAt)) out.waiting += 1;
|
||||
out.usd = Math.round(out.usd * 100) / 100; return out;
|
||||
}
|
||||
|
||||
|
||||
+140
-18
@@ -11,8 +11,11 @@
|
||||
// exists here keeps its sponsor and only gets empty fields filled. Joins from this site are skipped.
|
||||
// wallet.connected filled only on a waiting account that still has no wallet (lsinbound fill rules). A claimed account
|
||||
// links its own wallet here; the hub's wallet is not proof of ownership on InstantAdPay.
|
||||
// sponsor.changed TODO: no clean path yet. lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the hub
|
||||
// view does not expose, and a 'contract' change is not one of the deliberate kinds. Ignored (logged).
|
||||
// sponsor.changed ignored on purpose (2026-11-14): lsinbound's follow rule needs sponsorSetAt / By / PrevEmail, which the
|
||||
// hub view does not expose, and someone the InstantAdPay contract holds never moves anyway.
|
||||
// Rule 2 (2026-11-14): the sponsor written for an arrival is person.locks.iap's sponsor when that lock exists, never the
|
||||
// plain network sponsor. QUIET: nothing on this path sends mail, a notice or a post, and lssync.js never
|
||||
// pushes a hub waiting account to LinkSpin (qa/hubsync.test.cjs, mail audit).
|
||||
// anything else ignored.
|
||||
// Each seq is applied once (done map). A failing event answers 503 so the hub retries it; after 5 tries it is set aside
|
||||
// in the log so one bad row cannot hold every later event back.
|
||||
@@ -20,6 +23,14 @@
|
||||
// Outbound (/v1/join, /v1/wallet, signed as HUB_SITE): new accounts made here since the flag first went on and every main
|
||||
// wallet linked here go into a persisted outbox (DATA_DIR/hubsync.json) and are sent in order, never in the way of a
|
||||
// sign-up. Retried with backoff on 5xx / network / 404-before-join; a 400/409 refusal is final and logged.
|
||||
// Gaps closed 2026-11-13 (Marty: "let's get the gaps report built"), all still one way:
|
||||
// - any later change to a member's username or sponsor goes to /v1/join again (names them; a sponsor only lands where the
|
||||
// hub has none), old members included, not only accounts made since the flag went on;
|
||||
// - a DELIBERATE sponsor change (sponsorfollow: adopt, rescue, release, expire->expiry, admin) goes to /v1/sponsor-change;
|
||||
// - every MemberActivated on the InstantAdPay contract goes to /v1/contract-bind (contract 'iap', the sponsor by wallet),
|
||||
// by email when the wallet belongs to an account here, else by wallet alone.
|
||||
// - every paid Purchase goes to /v1/contract-spend (2026-11-14, rule 2: the contract with money spent decides the network
|
||||
// sponsor when two contracts hold different ones).
|
||||
// Where the hub and InstantAdPay name different sponsors, nothing is forced on either side: the case goes to `disagree`
|
||||
// (Admin > /api/admin/hub) for Marty, since an InstantAdPay member bound on our contract cannot move anyway.
|
||||
'use strict';
|
||||
@@ -29,7 +40,8 @@ const path = require('path');
|
||||
|
||||
let R = null, st = null, chain_ = Promise.resolve(), timer = null, sending = false, interval = null;
|
||||
const MAX_UP = 25, EVENT_TRIES = 5, OUT_TRIES = 20, KEEP_DONE = 5000;
|
||||
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']); // came here from another site: that site tells the hub itself
|
||||
const SHELL_ORIGINS = new Set(['linkspin', 'btc4hits', 'hub']);
|
||||
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expire', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
|
||||
const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim());
|
||||
const URL_ = () => String(process.env.HUB_URL || '').trim().replace(/\/+$/, '');
|
||||
const SECRET = () => String(process.env.HUB_SECRET || '').trim();
|
||||
@@ -60,9 +72,9 @@ function verify(headers, raw) {
|
||||
const want = sign(ts, raw);
|
||||
return want.length === sig.length && crypto.timingSafeEqual(Buffer.from(want), Buffer.from(sig));
|
||||
}
|
||||
async function hubPost(p, body) {
|
||||
async function hubPost(p, body, timeout) {
|
||||
const raw = JSON.stringify(body); const ts = String(Date.now());
|
||||
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(15000) });
|
||||
const r = await fetch(URL_() + p, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Hub-Site': SITE(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sign(ts, raw) }, body: raw, signal: AbortSignal.timeout(timeout || 15000) });
|
||||
let j = null; try { j = await r.json(); } catch (e) {}
|
||||
return { status: r.status, body: j };
|
||||
}
|
||||
@@ -72,7 +84,11 @@ async function resolve(q) {
|
||||
return (r.body && r.body.person) || null;
|
||||
}
|
||||
const doorOf = p => norm(p && p.firstDoor && p.firstDoor.site).replace(/[^a-z0-9_-]/g, '').slice(0, 30) || 'network';
|
||||
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: (p.sponsor && p.sponsor.email) || null, joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
|
||||
// Rule 2 (Marty 2026-11-14): the sponsor written here is the one the InstantAdPay CONTRACT holds for them when it holds them
|
||||
// (person.locks.iap), never the plain network sponsor, which may come from another contract where they spent money
|
||||
const CONTRACT = 'iap';
|
||||
const sponsorFor = p => { const l = p && p.locks && p.locks[CONTRACT]; if (l) return (l.sponsor && l.sponsor.email) || null; return (p && p.sponsor && p.sponsor.email) || null; };
|
||||
const rowOf = p => ({ email: norm(p.email), username: p.username || null, wallet: p.wallet || null, sponsorEmail: sponsorFor(p), joinedAt: Number(p.firstDoor && p.firstDoor.at) || null, profile: null });
|
||||
|
||||
// what InstantAdPay and the hub each say the sponsor is; a difference is recorded, never forced
|
||||
async function compare(email, hubSponsorEmail, how) {
|
||||
@@ -93,8 +109,8 @@ async function memberJoined(ev) {
|
||||
if (existing && !A.isUnclaimedShell(existing)) rows[0].wallet = null; // a real account links its own wallet here
|
||||
// sponsors not on InstantAdPay yet come along as waiting accounts too (lsinbound builds them from rows in the same batch)
|
||||
let p = first;
|
||||
for (let i = 0; i < MAX_UP && p.sponsor && p.sponsor.email; i++) {
|
||||
const se = norm(p.sponsor.email); if (seen.has(se) || await A.byEmail(se)) break;
|
||||
for (let i = 0; i < MAX_UP && sponsorFor(p); i++) {
|
||||
const se = norm(sponsorFor(p)); if (seen.has(se) || await A.byEmail(se)) break;
|
||||
const up = await resolve({ email: se }); if (!up || !up.email || up.blocked) break;
|
||||
seen.add(se); rows.push(rowOf(up)); doors[se] = doorOf(up); p = up;
|
||||
}
|
||||
@@ -117,8 +133,9 @@ async function walletConnected(ev) {
|
||||
async function apply(ev) {
|
||||
if (ev.type === 'member.joined') return memberJoined(ev);
|
||||
if (ev.type === 'wallet.connected') return walletConnected(ev);
|
||||
// TODO sponsor.changed: needs the deliberate-change record (at / by / previous sponsor) in the hub view before it can go
|
||||
// through sponsorfollow's rule like LinkSpin's changes do. Until then the hub's change is ignored here.
|
||||
// sponsor.changed is IGNORED here on purpose (checked 2026-11-14 for the switch-on): it would need the deliberate-change
|
||||
// record (at / by / previous sponsor) to go through sponsorfollow's rule, and a member locked on the InstantAdPay contract
|
||||
// must never move anyway (the contract pays whoever it holds). qa/hubsync.test.cjs proves a locked member stays put.
|
||||
return 'ignored';
|
||||
}
|
||||
function prune() {
|
||||
@@ -159,17 +176,48 @@ function enqueue(kind, email) {
|
||||
s.outbox.push({ kind, email, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
}
|
||||
function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(e => console.error('hubsync flush', e.message)); }, 2000); }
|
||||
// accounts.onChange: a new account made here (or its first username) goes to /v1/join
|
||||
// accounts.onChange: a new account made here, or a later username / sponsor change on any account, goes to /v1/join;
|
||||
// a deliberate sponsor change also goes to /v1/sponsor-change
|
||||
function touch(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
(async () => {
|
||||
const e = norm(email); const a = await R.accounts.byEmail(e); const s = load();
|
||||
if (!a || SHELL_ORIGINS.has(a.joinedVia) || Number(a.created) < s.since) return;
|
||||
if (!a || SHELL_ORIGINS.has(a.joinedVia)) return;
|
||||
const sp = await R.accounts.sponsorOf(e); const spE = sp ? norm(sp.email) : '';
|
||||
const key = (a.username || '') + '|' + spE;
|
||||
const rep = s.reported[e];
|
||||
if (!rep) { s.reported[e] = { u: a.username || null }; enqueue('join', e); }
|
||||
else if (a.username && rep.u !== a.username) { rep.u = a.username; enqueue('join', e); } // join again names them on the hub
|
||||
if (!rep) { s.reported[e] = { u: a.username || null, k: key }; enqueue('join', e); } // new here, or an older member's first change since the flag
|
||||
else if (rep.k !== key) { rep.u = a.username || null; rep.k = key; enqueue('join', e); }
|
||||
const rec = R.follow && R.follow.get ? R.follow.get(e) : null;
|
||||
if (rec && DELIBERATE.has(rec.by) && norm(rec.sponsorEmail) === spE && Number(rec.at) > 0 && s.reported[e].sc !== Number(rec.at)) {
|
||||
s.reported[e].sc = Number(rec.at); enqueue('sponsor', e);
|
||||
}
|
||||
save();
|
||||
})().catch(err => console.error('hubsync touch', err.message));
|
||||
}
|
||||
// chain.onEvent (once across copies): a payout switch-on on the InstantAdPay contract goes to /v1/contract-bind
|
||||
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) {}
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'bind', email: norm(ev.account), wallet: norm(ev.account), sponsorWallet: spW, at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onChain', err.message));
|
||||
}
|
||||
// chain.onEvent: money paid into the InstantAdPay contract (Purchase with POL in) goes to /v1/contract-spend (Marty 2026-11-14,
|
||||
// rule 2: when two contracts hold different sponsors, the one with money spent decides the network sponsor). Keyed by the
|
||||
// buyer's position wallet, the same key as its bind, so the bind is always sent first; the tx hash makes a resend count once.
|
||||
// A 404 (bind not there yet, or a linked extra position the hub does not know) is retried like any other miss.
|
||||
function onPurchase(ev) {
|
||||
if (!R || !on() || !ev.buyerId || !(Number(ev.priceCents) > 0)) return;
|
||||
try { if (BigInt(ev.paidWei || '0') <= 0n) return; } catch (e) { return; } // nothing paid in: not a spend
|
||||
(async () => {
|
||||
const m = await R.chain.member(ev.buyerId); const w = m && m.account ? norm(m.account) : null; if (!w) return;
|
||||
const s = load(); if (s.outbox.length >= 20000) { s.stats.sendErrors++; return; }
|
||||
s.outbox.push({ kind: 'spend', email: w, wallet: w, cents: Number(ev.priceCents), tx: ev.tx || null, paidAt: Number(ev.ts) || Date.now(), at: Date.now(), tries: 0, next: 0 }); save(); kick();
|
||||
})().catch(err => console.error('hubsync onPurchase', err.message));
|
||||
}
|
||||
// accounts.onWalletLinked: a main wallet linked here goes to /v1/wallet
|
||||
function wallet(email) {
|
||||
if (!R || !on() || !email) return;
|
||||
@@ -178,8 +226,26 @@ function wallet(email) {
|
||||
if (a && a.address && !R.accounts.isUnclaimedShell(a)) enqueue('wallet', norm(email)); // a waiting account's wallet came from a sync
|
||||
})().catch(err => console.error('hubsync wallet', err.message));
|
||||
}
|
||||
// sponsorfollow / tank.js label a window expiry 'expire'; the hub (and its DELIBERATE list) calls it 'expiry' (fixed 2026-11-15:
|
||||
// before, IAP window-expiry moves never reached the hub as a sponsor change)
|
||||
const HUB_BY = { expire: 'expiry' };
|
||||
const hubBy = by => HUB_BY[by] || by;
|
||||
const ROUTE = { join: '/v1/join', wallet: '/v1/wallet', sponsor: '/v1/sponsor-change', bind: '/v1/contract-bind', spend: '/v1/contract-spend' };
|
||||
async function bodyFor(item) {
|
||||
if (item.kind === 'spend') {
|
||||
let owner = null; try { owner = (await R.accounts.byAddress(item.wallet)) || (R.accounts.positionOwner ? await R.accounts.positionOwner(item.wallet) : null); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, cents: item.cents, tx: item.tx || undefined, at: item.paidAt };
|
||||
}
|
||||
if (item.kind === 'bind') {
|
||||
let owner = null; try { owner = await R.accounts.byAddress(item.wallet); } catch (e) {}
|
||||
return { contract: 'iap', email: owner && owner.email ? owner.email : undefined, wallet: item.wallet, sponsorRef: item.sponsorWallet || '' };
|
||||
}
|
||||
const a = await R.accounts.byEmail(item.email); if (!a) return null;
|
||||
if (item.kind === 'sponsor') {
|
||||
const sp = await R.accounts.sponsorOf(a.email); const rec = R.follow && R.follow.get ? R.follow.get(a.email) : null;
|
||||
if (!rec || !DELIBERATE.has(rec.by) || norm(rec.sponsorEmail) !== (sp ? norm(sp.email) : '')) return null; // superseded since
|
||||
return { email: a.email, sponsorEmail: sp ? sp.email : null, by: hubBy(rec.by) };
|
||||
}
|
||||
if (item.kind === 'wallet') return a.address ? { email: a.email, wallet: a.address } : null;
|
||||
const sp = await R.accounts.sponsorOf(a.email);
|
||||
return { email: a.email, ref: sp ? sp.email : (a.sponsorRef || undefined), username: a.username || undefined };
|
||||
@@ -195,13 +261,13 @@ async function flush(force) { // force (tests, admin): ignore the backoff wait
|
||||
let r = null;
|
||||
try {
|
||||
const body = await bodyFor(item); if (!body) { drop('gone'); save(); continue; }
|
||||
r = await hubPost(item.kind === 'join' ? '/v1/join' : '/v1/wallet', body);
|
||||
r = await hubPost(ROUTE[item.kind] || '/v1/wallet', body);
|
||||
} catch (e) { r = { status: 0, body: { error: e.message } }; }
|
||||
const code = (r.body && r.body.error) || null;
|
||||
if (r.status >= 200 && r.status < 300) {
|
||||
drop(null); s.stats.sent++; sent++;
|
||||
if (item.kind === 'join' && r.body && r.body.person) await compare(item.email, r.body.person.sponsor && r.body.person.sponsor.email, 'iap-join');
|
||||
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked')) {
|
||||
} else if ((r.status === 400 || r.status === 409) || (r.status === 403 && code === 'blocked') || (item.kind === 'sponsor' && r.status === 404)) {
|
||||
drop('refused', code); s.stats.refused++;
|
||||
} else {
|
||||
item.tries++; s.stats.sendErrors++;
|
||||
@@ -232,9 +298,65 @@ function start() {
|
||||
const rec = setInterval(() => reconcile().catch(e => console.error('hubsync reconcile', e.message)), 10 * 60000);
|
||||
for (const t of [interval, rec]) if (t.unref) t.unref();
|
||||
}
|
||||
// ---------- rule 3: the holding tank asks the hub (Marty 2026-11-14) ----------
|
||||
// The tank never offers anyone locked on ANY network contract, or anyone the hub already knows a sponsor for. tank.js asks
|
||||
// through its hooks (networkHeld, networkLocked, network); server.js wires them only with HUB_ENABLED, so with the flag off
|
||||
// the tank works exactly as before. One /v1/locked {emails, detail} call per 2,000 emails, cached per email: fresh for 10
|
||||
// minutes. CONSERVATIVE when the hub cannot be reached: the last answer stands for up to 1 hour, after that the person is
|
||||
// held ('unknown', not offered, not moved to the tank, not auto-assigned) until the hub answers again. A held tank for a
|
||||
// while is the safe side; offering someone a contract already holds is not. After a failed call the hub is left alone
|
||||
// for 2 minutes (page views must not each wait for a timeout).
|
||||
const HELD_FRESH_MS = 10 * 60000, HELD_STALE_MS = 60 * 60000, HELD_DOWN_MS = 2 * 60000, HELD_CHUNK = 2000;
|
||||
const held = new Map(); let heldDownUntil = 0, heldBusy = Promise.resolve();
|
||||
async function refreshHeld(emails, timeout) {
|
||||
const run = heldBusy.then(async () => {
|
||||
const now = Date.now(); const miss = emails.filter(e => { const c = held.get(e); return !c || now - c.at > HELD_FRESH_MS; });
|
||||
if (!miss.length || now < heldDownUntil) return;
|
||||
try {
|
||||
for (let i = 0; i < miss.length; i += HELD_CHUNK) {
|
||||
const part = miss.slice(i, i + HELD_CHUNK);
|
||||
const r = await hubPost('/v1/locked', { emails: part, detail: true, ids: true }, timeout || 5000); // ids: hub id + door per row (a hub without it ignores the flag)
|
||||
if (r.status !== 200 || !r.body || !r.body.found || typeof r.body.found !== 'object') throw new Error('hub locked ' + r.status);
|
||||
if (held.size > 60000) held.clear();
|
||||
const at = Date.now(); for (const e of part) held.set(e, { at, row: r.body.found[e] || null });
|
||||
}
|
||||
} catch (e) { heldDownUntil = Date.now() + HELD_DOWN_MS; load().stats.heldErrors = (load().stats.heldErrors || 0) + 1; console.log('hubsync: hub /v1/locked unreachable:', e.message); }
|
||||
});
|
||||
heldBusy = run.catch(() => {}); return run;
|
||||
}
|
||||
const whyHeld = (c, now) => (!c || now - c.at > HELD_STALE_MS ? 'unknown' : c.row && c.row.locked ? 'locked' : c.row && c.row.sponsored ? 'sponsored' : null);
|
||||
// accounts -> Map email -> 'locked' | 'sponsored' | 'unknown' for the ones the tank must not offer
|
||||
async function heldAmong(accts, opts) {
|
||||
const out = new Map(); if (!R || !on()) return out;
|
||||
const emails = [...new Set((accts || []).map(a => norm(a && a.email)).filter(Boolean))]; if (!emails.length) return out;
|
||||
await refreshHeld(emails, opts && opts.timeout);
|
||||
const now = Date.now(); for (const e of emails) { const w = whyHeld(held.get(e), now); if (w) out.set(e, w); }
|
||||
return out;
|
||||
}
|
||||
// release, rescue and expiry moves: 'locked' (on any network contract) | 'unknown' (hub not answering) | null
|
||||
async function lockedAnywhere(email) {
|
||||
if (!R || !on()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const w = whyHeld(held.get(e), Date.now());
|
||||
return w === 'locked' || w === 'unknown' ? w : null;
|
||||
}
|
||||
// the sponsor the hub knows for a tank member, for tank.alignToNetwork: this contract's lock first, else the network sponsor
|
||||
// OFF unless HUB_TANK_ALIGN=on: aligning moves sponsors (and on LinkSpin a linked wallet then has its payouts switched on, which
|
||||
// locks that sponsor on the contract), so the first run over a full tank is Marty's deliberate step, not a side effect of the
|
||||
// deploy. While it is off the people the hub knows a sponsor for are simply held out of the tank (rule 3).
|
||||
const alignOn = () => /^(1|true|on|yes)$/i.test(String(process.env.HUB_TANK_ALIGN || '').trim());
|
||||
async function hubSponsor(email) {
|
||||
if (!R || !on() || !alignOn()) return null; const e = norm(email); if (!e) return null;
|
||||
await refreshHeld([e]); const c = held.get(e); if (!c || !c.row || Date.now() - c.at > HELD_STALE_MS) return null;
|
||||
const l = c.row.locks && Object.prototype.hasOwnProperty.call(c.row.locks, CONTRACT) ? c.row.locks[CONTRACT] : undefined;
|
||||
const sp = norm(l !== undefined ? l : c.row.sponsorEmail);
|
||||
return sp && sp !== e ? { sponsorEmail: sp, via: l !== undefined ? 'network hub, InstantAdPay contract' : 'network hub' } : null;
|
||||
}
|
||||
|
||||
// the hub id and first door of a person the tank cache holds (5xYourTeam draft pool, 2026-11-15): { id, door } | null. Read-only, no call.
|
||||
function hubInfo(email) { const c = held.get(norm(email)); return c && c.row && c.row.id ? { id: c.row.id, door: c.row.door || null } : null; }
|
||||
function adminView() {
|
||||
const s = load();
|
||||
return Object.assign({ enabled: enabled(), on: on(), site: SITE(), url: URL_(), since: s.since, outbox: s.outbox.length, retrying: Object.keys(s.tries).length,
|
||||
disagree: Object.keys(s.disagree).length }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
||||
disagree: Object.keys(s.disagree).length, tankCache: held.size, tankHubDownUntil: heldDownUntil || null }, s.stats, { disagreements: Object.entries(s.disagree).slice(-25).map(([email, d]) => Object.assign({ email }, d)), recent: s.log.slice(-25).reverse() });
|
||||
}
|
||||
module.exports = { init, enabled, on, receive, touch, wallet, flush, reconcile, start, adminView, _sign: sign };
|
||||
module.exports = { _hubBy: hubBy, init, enabled, on, receive, touch, wallet, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, hubInfo, resolvePerson: q => resolve(q), _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ async function renderPage() {
|
||||
const w = winners();
|
||||
if (w.length) h += '<h2 style="font-size:24px;margin:0 0 10px">Past winners</h2>' + w.slice(0, 12).map(x => '<div class="win"><b>' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + '</b>: ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '</div>').join('');
|
||||
h += '<p class="muted small" style="margin-top:30px">Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.</p>';
|
||||
h += '</div><script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
return h;
|
||||
}
|
||||
module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds };
|
||||
|
||||
@@ -75,10 +75,14 @@ async function push(rows) {
|
||||
}
|
||||
st.pushed += sent; st.last = { at: Date.now(), rows: sent }; save(); return sent;
|
||||
}
|
||||
// QUIET (Marty 2026-11-14, "join one = join all"): a waiting account the network hub made here (joinedVia 'hub', never signed
|
||||
// in) is never pushed to LinkSpin. The hub tells LinkSpin itself, quietly; pushed from here, LinkSpin's registry route would
|
||||
// link the wallet and its engine would switch payouts on and email them. Once they sign in here they sync like anyone.
|
||||
const hubShell = a => !!a && a.joinedVia === 'hub' && R.accounts.isUnclaimedShell && R.accounts.isUnclaimedShell(a);
|
||||
// an account just changed: send its row shortly (debounced so a join + username + wallet in a row go as one)
|
||||
function touch(email) {
|
||||
if (!on() || !email) return; pending.set(String(email).toLowerCase(), Date.now());
|
||||
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
|
||||
if (!timer) timer = setTimeout(async () => { timer = null; const st = load(); const emails = [...pending.keys()].filter(e => !muted.has(e)); for (const e of emails) pending.delete(e); try { const rows = []; for (const e of emails) { const a = await R.accounts.byEmail(e); if (a && !hubShell(a)) { const r = await rowFor(a); if (st.hashes[r.email] !== hashOf(r)) rows.push(r); } } if (rows.length) await push(rows); } catch (e) { load().errors++; save(); console.error('lssync touch', e.message); } }, 3000);
|
||||
}
|
||||
// the reconcile pass: only rows whose hash changed since the last push
|
||||
async function tick(force) {
|
||||
@@ -88,7 +92,7 @@ async function tick(force) {
|
||||
const all = await R.accounts.listAll(50000, { shells: true }); const st = load();
|
||||
const byRef = new Map(); for (const a of all) { if (a.username) byRef.set(String(a.username).toLowerCase(), a); if (a.code) byRef.set(String(a.code).toLowerCase(), a); }
|
||||
const T = R.tank && R.tank(); let tankMap = null; if (T) { try { tankMap = await T.summaryMap(); } catch (e) { tankMap = null; } }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const rows = []; for (const a of all) { if (!a.email || muted.has(a.email) || hubShell(a)) continue; const r = await rowFor(a, byRef, tankMap || (T ? new Map() : null)); if (force || st.hashes[r.email] !== hashOf(r)) rows.push(r); }
|
||||
const sent = rows.length ? await push(rows) : 0;
|
||||
return { accounts: all.length, changed: rows.length, sent };
|
||||
} catch (e) { load().errors++; save(); console.error('lssync tick', e.message); return { error: e.message }; }
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
// The network sites list for the footer's "Part of the network" line (Marty 2026-11-14 trust pack).
|
||||
// One source: the hub's public GET /v1/network-sites (HUB_URL). Cached 10 minutes, refreshed in the background, never waits on a
|
||||
// slow hub (2.5 s timeout), and falls back to the same built-in list. Never RM Circle, never the games.
|
||||
// The same file lives in every network site (InstantAdPay, LinkSpin, Downline Banners, VBB, Stack POL).
|
||||
const FALLBACK = [
|
||||
{ id: 'iap', name: 'InstantAdPay', url: 'https://instantadpay.com' },
|
||||
{ id: 'linkspin', name: 'LinkSpin', url: 'https://linkspin.app' },
|
||||
{ id: 'dlb', name: 'Downline Banners', url: 'https://downlinebanners.com' },
|
||||
{ id: 'vbb', name: 'Viral Banner Blitz', url: 'https://viralbannerblitz.com' },
|
||||
{ id: 'stackpol', name: 'Stack POL', url: 'https://stackpol.com' },
|
||||
{ id: 'earnerscorner', name: 'Earners Corner', url: 'https://earnerscorner.com' }
|
||||
];
|
||||
const TTL = 10 * 60 * 1000;
|
||||
let cache = { at: 0, list: FALLBACK, from: 'fallback' };
|
||||
let inflight = null;
|
||||
|
||||
const hubUrl = () => String(process.env.HUB_URL || 'https://hub.saasy.top').trim().replace(/\/+$/, '');
|
||||
function clean(list) {
|
||||
if (!Array.isArray(list)) return null;
|
||||
const ok = list.filter(s => s && typeof s.name === 'string' && /^https:\/\/[a-z0-9.-]+(\/[^\s"'<>]*)?$/i.test(String(s.url || '')))
|
||||
.slice(0, 30).map(s => ({ id: String(s.id || s.name).toLowerCase().replace(/[^a-z0-9]+/g, '').slice(0, 30), name: String(s.name).slice(0, 60), url: String(s.url).replace(/\/+$/, '') }));
|
||||
return ok.length ? ok : null;
|
||||
}
|
||||
function refresh() {
|
||||
if (inflight || process.env.NETWORK_SITES_HUB === '0') return inflight;
|
||||
const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 2500);
|
||||
inflight = fetch(hubUrl() + '/v1/network-sites', { signal: ac.signal })
|
||||
.then(r => (r.ok ? r.json() : null))
|
||||
.then(j => { const l = clean(j); if (l) cache = { at: Date.now(), list: l, from: 'hub' }; else cache.at = Date.now(); })
|
||||
.catch(() => { cache.at = Date.now() - TTL + 60 * 1000; }) // hub down: try again in a minute, keep the last good list
|
||||
.finally(() => { clearTimeout(t); inflight = null; });
|
||||
return inflight;
|
||||
}
|
||||
function list() { if (Date.now() - cache.at > TTL) refresh(); return cache.list; }
|
||||
// Tracked links (Marty 2026-11-14: "make sure each of these sites is its own traffic source and link spun so we can track it"): each
|
||||
// entry also gets go = the LinkSpin network link for that site with ?src=<this site>, so a click shows in LinkSpin Reports under the
|
||||
// site that sent it (LinkSpin netlinks.js: fixed codes on the admin account). This site = NETWORK_SITE_ID, else the request host.
|
||||
// No go for this site itself, or when this site cannot be told (a test host): the page then uses the plain url.
|
||||
const CODES = { iap: 'nwiap', linkspin: 'nwls', dlb: 'nwdlb', vbb: 'nwvbb', stackpol: 'nwsp', earnerscorner: 'nwec' };
|
||||
const linksBase = () => String(process.env.NETWORK_LINKS_BASE || 'https://linkspin.app').trim().replace(/\/+$/, '');
|
||||
const hostOf = u => { try { return new URL(u).hostname.toLowerCase().replace(/^www\./, ''); } catch (e) { return ''; } };
|
||||
function selfId(req, l) {
|
||||
const env = String(process.env.NETWORK_SITE_ID || '').trim().toLowerCase(); if (env) return env;
|
||||
const h = String((req && req.headers && (req.headers['x-forwarded-host'] || req.headers.host)) || '').split(',')[0].trim().toLowerCase().replace(/:\d+$/, '').replace(/^www\./, '');
|
||||
const m = h && (l || list()).find(s => hostOf(s.url) === h); return m ? m.id : '';
|
||||
}
|
||||
// the LinkSpin-tracked link to site `id` sent from site `from` (from = id: the site's own promo kit); extra = { s1: member username, s2: one path segment }
|
||||
function tracked(id, from, extra) {
|
||||
const code = CODES[id]; if (!code || !from) return '';
|
||||
const q = new URLSearchParams({ src: from }); for (const [k, v] of Object.entries(extra || {})) if (v) q.set(k, String(v));
|
||||
return linksBase() + '/r/' + code + '?' + q.toString();
|
||||
}
|
||||
function withGo(l, me) { return l.map(s => { const go = me && s.id !== me ? tracked(s.id, me) : ''; return go ? Object.assign({}, s, { go }) : s; }); }
|
||||
// GET /api/network-sites: public, cacheable, the same answer on every page
|
||||
function handle(req, res) {
|
||||
const l = list();
|
||||
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' });
|
||||
res.end(JSON.stringify(withGo(l, selfId(req, l))));
|
||||
}
|
||||
module.exports = { list, handle, refresh, tracked, selfId, withGo, CODES, FALLBACK, _state: () => cache };
|
||||
+23
-5
@@ -34,10 +34,12 @@ const enabled = () => SECRET().length >= 32;
|
||||
const TTL = 60 * 1000; // token life
|
||||
const SKEW = 30 * 1000; // clock skew allowed between the two servers
|
||||
const STATE_AGE = 300; // seconds: the state cookie
|
||||
const GO_STATE_AGE = 1200; // seconds: the state cookie on a deliberate tap (time to sign in on the provider first, 2026-11-14)
|
||||
const BACK_AGE = 1200; // seconds: the provider remembers an unfinished deliberate check while the member signs in
|
||||
const TRIED_AGE = 1800; // seconds: one silent check per browser per 30 minutes
|
||||
const OFF_AGE = 12 * 3600; // seconds: no silent check after a sign-out on this site
|
||||
const HINT_AGE = 300; // seconds: the email prefill when the member is not here yet
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners' };
|
||||
const NAMES = { iap: 'InstantAdPay', linkspin: 'LinkSpin', bannerline: 'Downline Banners', vbb: 'Viral Banner Blitz', viraladblitz: 'ViralAdBlitz', downlinehydra: 'DownlineHydra' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (2026-11-15); downlinehydra = DownlineHydra (2026-11-15)
|
||||
const WALLET_RE = /^0x[0-9a-f]{40}$/;
|
||||
|
||||
let C = null; // { self, peer, peerBase(), isProd, dataDir, db, member(req), accept(email, req, v), signIn(email, req, v), landing(to), signinPath(to), defaultPath,
|
||||
@@ -160,9 +162,15 @@ async function handle(req, res, u) {
|
||||
const c = cookies(req);
|
||||
if (mode === 'check' && (c['nsso.tried'] || c['nsso.off'])) return go(res, to);
|
||||
const st = crypto.randomBytes(16).toString('hex');
|
||||
const set = [ck('nsso.st', st, STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
const set = [ck('nsso.st', st, mode === 'go' ? GO_STATE_AGE : STATE_AGE, true), ck('nsso.tried', '1', TRIED_AGE, true)];
|
||||
if (mode === 'go' && c['nsso.off']) set.push(ck('nsso.off', '', 0, true));
|
||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to), set);
|
||||
return go(res, (from ? from() : C.peerBase()) + '/sso/check?st=' + st + (C.from ? '&r=' + C.self : '') + '&to=' + encodeURIComponent(to) + (mode === 'go' ? '&m=go' : ''), set);
|
||||
}
|
||||
if (p === '/sso/resume') { // signed in on the provider after a deliberate tap: finish the check it was asked for (2026-11-14)
|
||||
const q = new URLSearchParams(cookies(req)['nsso.back'] || '');
|
||||
const clear = [ck('nsso.back', '', 0, true)];
|
||||
if (!/^[a-f0-9]{32}$/.test(q.get('st') || '')) return go(res, C.defaultPath, clear);
|
||||
return go(res, '/sso/check?st=' + q.get('st') + (q.get('r') ? '&r=' + encodeURIComponent(q.get('r')) : '') + '&to=' + encodeURIComponent(safePath(q.get('to'), '/')), clear);
|
||||
}
|
||||
if (p === '/sso/check') {
|
||||
const st = String(u.searchParams.get('st') || '');
|
||||
@@ -173,7 +181,14 @@ async function handle(req, res, u) {
|
||||
const none = base + '/sso/in?none=1&to=' + encodeURIComponent(to);
|
||||
if (!enabled() || !/^[a-f0-9]{32}$/.test(st)) return go(res, none);
|
||||
let s = null; try { s = await C.member(req); } catch (e) {}
|
||||
if (!s || !s.email) { log('check: not signed in here', null, 'for ' + forName); return go(res, none); }
|
||||
if (!s || !s.email) {
|
||||
if (u.searchParams.get('m') === 'go' && !isBot(req)) { // a deliberate tap: sign in here first, then /sso/resume finishes the trip
|
||||
log('check: not signed in here, asking to sign in', null, 'for ' + forName);
|
||||
const back = new URLSearchParams({ st, to }); if (r) back.set('r', r);
|
||||
return go(res, C.signinPath(C.defaultPath), [ck('nsso.back', back.toString(), BACK_AGE, true)]);
|
||||
}
|
||||
log('check: not signed in here', null, 'for ' + forName); return go(res, none);
|
||||
}
|
||||
let w = null;
|
||||
if (wb) { try { w = await C.wallet(s); } catch (e) {} if (!w || !WALLET_RE.test(String(w.address || '').toLowerCase())) { log('check: no wallet on the account', s.email, 'for ' + forName); return go(res, none); } }
|
||||
log('token issued', s.email, 'for ' + forName);
|
||||
@@ -209,4 +224,7 @@ async function handle(req, res, u) {
|
||||
return false;
|
||||
}
|
||||
|
||||
module.exports = { init, handle, enabled, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
// true when this browser came here from a deliberate network tap and still has to finish it after signing in
|
||||
const pendingBack = req => !!cookies(req)['nsso.back'];
|
||||
|
||||
module.exports = { init, handle, enabled, pendingBack, mint, verify, spend, safePath, isBot, offCookie, mask, TTL, NAMES };
|
||||
|
||||
+1
-1
@@ -652,7 +652,7 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/admin-kb.js?v=20261020kb"></script>
|
||||
<script src="/assets/admin.js?v=20261112txt"></script><script src="/assets/admin-sponsorcheck.js?v=20261107tg"></script><script src="/assets/admin-kits.js?v=20261101th"></script>
|
||||
</body>
|
||||
|
||||
+28
-1
@@ -57,9 +57,36 @@ window.IAP = (function () {
|
||||
f.innerHTML = '<div>© ' + new Date().getFullYear() + ' InstantAdPay</div>'
|
||||
+ '<div style="margin-top:8px;display:flex;gap:16px;justify-content:center;flex-wrap:wrap">'
|
||||
+ '<a href="/">How it works</a><a href="/presentation">Presentation</a><a href="/ledger">Live ledger</a><a href="/contract">The contract</a><a href="/blog">Blog</a><a href="/leaderboard">Leaderboard</a><a href="/whats-new">What\'s new</a>'
|
||||
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/privacy">Privacy</a><a href="/disclaimer">Disclaimer</a></div>';
|
||||
+ '<a href="/facts">Platform facts</a><a href="/support">Support</a><a href="/terms">Terms</a><a href="/disclaimer">Earnings Disclaimer</a><a href="/privacy">Privacy</a></div>'
|
||||
+ '<div style="margin-top:10px">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</div>';
|
||||
document.body.appendChild(f);
|
||||
renderNetworkLine(f);
|
||||
}
|
||||
// "Part of the network" (Marty 2026-11-14 trust pack): the list comes from the hub through /api/network-sites, built-in copy if not
|
||||
const NET_FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] }));
|
||||
let netList = null;
|
||||
async function networkSites() {
|
||||
if (!netList) netList = fetch('/api/network-sites').then(r => r.json()).then(l => (Array.isArray(l) && l.length ? l : NET_FALLBACK)).catch(() => NET_FALLBACK);
|
||||
return netList;
|
||||
}
|
||||
function renderNetworkLine(host) {
|
||||
if (!host || host.querySelector('.netline')) return;
|
||||
const d = document.createElement('div'); d.className = 'netline';
|
||||
d.style.cssText = 'margin-top:10px;display:flex;gap:6px 14px;justify-content:center;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||
host.appendChild(d);
|
||||
const esc = s => String(s).replace(/[&<>"]/g, ch => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[ch]);
|
||||
const paint = list => {
|
||||
d.innerHTML = '<b>Part of the network</b><span>One account across the network:</span>' + list.map(s => (s.id === 'iap' || /instantadpay\.com/.test(s.url))
|
||||
? '<span aria-current="page" style="font-weight:700;color:var(--ink)">' + esc(s.name) + ' (you are here)</span>'
|
||||
: '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>').join('');
|
||||
};
|
||||
paint(NET_FALLBACK);
|
||||
networkSites().then(paint);
|
||||
}
|
||||
// pages with their own footer (the members area) get the network line too
|
||||
function decorateFooters() { document.querySelectorAll('footer.bo-pagefoot').forEach(f => { const w = document.createElement('div'); w.style.width = '100%'; f.appendChild(w); renderNetworkLine(w); }); }
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', decorateFooters); else decorateFooters();
|
||||
async function refreshNavWallet() {
|
||||
try {
|
||||
const me = await (await fetch('/api/me')).json();
|
||||
|
||||
+6
-3
@@ -989,6 +989,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (me.returnTo === 'gkshop' && !render.toGame) { render.toGame = true; location.href = '/gk/shop/resume'; return; }
|
||||
if (me.returnTo === 'spookydoors' && !render.toGame) { render.toGame = true; location.href = '/api/my/spookydoors'; return; } // Spooky Doors sent them here to sign in (2026-10-02)
|
||||
if (me.returnTo === 'polybreak' && !render.toGame) { render.toGame = true; location.href = '/api/my/polybreak'; return; } // PolyBreak sent them here to sign in (2026-10-13)
|
||||
if (me.returnTo === 'nsso' && !render.toGame) { render.toGame = true; location.href = '/sso/resume'; return; } // tapped "Sign in with InstantAdPay" on another network site while signed out here (2026-11-14)
|
||||
if (me.returnTo === 'forum' && !render.toGame) { render.toGame = true; location.href = '/api/my/forum'; return; } // Earners Corner forum sign-in (2026-11-10)
|
||||
if (me.returnTo === 'polminer' && !render.toGame) { render.toGame = true; location.href = '/api/my/polminer'; return; } // POL Miner sent them here to sign in (2026-10-28)
|
||||
if (me.returnTo === 'warpwares' && !render.toGame) { render.toGame = true; location.href = '/api/my/warpwares'; return; } // Warp & Wares sent them here to sign in (2026-10-29)
|
||||
@@ -2119,9 +2120,9 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if (!H || !H.show) return '';
|
||||
const btn = (key, label, pkg) => '<button class="btn small" type="button" data-hero-buy="' + esc(key) + '">' + esc(label) + ' · $' + pkg + ' package</button>';
|
||||
const item = i => '<div class="gp-tier' + (i.owned ? ' on' : '') + '"><h4>' + esc(i.name) + '</h4>'
|
||||
+ '<p class="gp-price">' + (i.free ? 'Free for everyone' : '$' + i.usd + ' <span class="small muted">one time</span>') + '</p>'
|
||||
+ '<p class="gp-price">' + (i.free ? 'Free for everyone' : i.freeAt ? 'Free at level ' + i.freeAt : '$' + i.usd + ' <span class="small muted">one time</span>') + '</p>'
|
||||
+ '<p class="small muted" style="margin:0 0 6px">' + esc(i.blurb) + '</p>'
|
||||
+ (i.owned ? '<p class="small"><b>Yours for good</b></p>' : i.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + i.package + ' package</button>' : i.open ? btn(i.key, 'Get ' + i.name.split(' ')[0], i.package) : '<span class="small muted">Not on sale right now.</span>') + '</div>';
|
||||
+ (i.owned ? '<p class="small"><b>Yours for good</b></p>' : i.freeAt ? '<span class="small muted">Not for sale: joins every player free in the game once a hero reaches level ' + i.freeAt + '.</span>' : i.waiting ? '<button class="btn small" type="button" data-gp-go="1">Buy a $' + i.package + ' package</button>' : i.open ? btn(i.key, 'Get ' + i.name.split(' ')[0], i.package) : '<span class="small muted">Not on sale right now.</span>') + '</div>';
|
||||
const B = H.bundle;
|
||||
const bundle = !B ? '' : '<div class="gp-tier' + (B.owned ? ' on' : '') + '"><h4>Hero bundle</h4><p class="gp-price">$' + B.usd + ' <span class="small muted">one time</span></p>'
|
||||
+ '<p class="small muted" style="margin:0 0 6px">' + esc(B.names.join(', ')) + ', together.</p>'
|
||||
@@ -2812,10 +2813,11 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
if ($('tkGo')) { $('tkGo').addEventListener('click', tkGenerate); $('tkAgain').addEventListener('click', tkGenerate); $('tkCopy').addEventListener('click', async () => { try { await navigator.clipboard.writeText($('tkText').value); IAP.status('Copied.', 'ok'); } catch (e) { $('tkText').select(); } }); $('tkSendBc').addEventListener('click', tkSendBroadcast); }
|
||||
// promo tools: pill menu switches between posts / swipes / banners / wall / videos
|
||||
function setPromoSub(name) {
|
||||
const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'stackpol', 'games', 'bixpay']; // bixpay: the BixPay partner kit, pill hidden while bixpayLive is off (2026-10-29)
|
||||
const ids = ['toolkit', 'posts', 'text', 'swipe', 'banners', 'wall', 'objections', 'videos', 'viral', 'stackpol', 'games', 'network', 'bixpay']; // bixpay: the BixPay partner kit, pill hidden while bixpayLive is off (2026-10-29)
|
||||
if (['polhunter', 'spookydoors', 'gamebanners'].includes(name)) name = 'games'; // those tabs live inside Games now (2026-10-06)
|
||||
if (name === 'toolkit') loadToolkit();
|
||||
if (name === 'stackpol') loadStackPol();
|
||||
if (name === 'network' && window.IAPNetKits) IAPNetKits.load(); // Network sites kits (2026-11-14), loaded when the tab opens
|
||||
const pill = document.querySelector('.promo-pills [data-promo="' + name + '"]');
|
||||
if (!ids.includes(name) || !pill || pill.hidden) name = 'posts';
|
||||
ids.forEach(id => { const el = $('promo-' + id); if (el) el.hidden = id !== name; });
|
||||
@@ -2954,6 +2956,7 @@ function shareLink(ref) { return SHARE_DOMAIN && /^[A-Za-z0-9_]{1,40}$/.test(Str
|
||||
// ── promo tools: content + rendering live in promo.js (IAPPromo.fill) ──
|
||||
function fillPromo(link, me) {
|
||||
if (window.IAPPromo) IAPPromo.fill(link, me || {});
|
||||
if (window.IAPNetKits && me && me.username) { IAPNetKits.setUser(me.username); const ns = $('promo-network'); if (ns && !ns.hidden) IAPNetKits.load(); }
|
||||
// banner kit
|
||||
const bwrap = $('promoBanners');
|
||||
if (bwrap && !bwrap.dataset.filled) {
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
// Promo tools > Network sites (Marty 2026-11-14): the promo kits of the other network sites, read live from each site's own public
|
||||
// feed (GET <site>/api/promo-kit?u=<username>), so a creative or line changed on Downline Banners or Viral Banner Blitz shows here
|
||||
// at once. Usernames are network-wide: the member's InstantAdPay username is their sponsor link on those sites even if they never
|
||||
// visited them. Nothing is stored here.
|
||||
window.IAPNetKits = (function () {
|
||||
const SITES = [
|
||||
{ key: 'dlb', name: 'Downline Banners', feed: 'https://downlinebanners.com/api/promo-kit', blurb: 'One global line of $5 banner spots on Polygon. A spot buys 300 guaranteed views on the board and a place in the line; every sale is split on-chain in the same transaction. Nothing is promised: a spot is paid only when spots sell after it.' },
|
||||
{ key: 'vbb', name: 'Viral Banner Blitz', feed: 'https://viralbannerblitz.com/api/promo-kit', blurb: 'One shared loop of 125x125 banners. Network members post free once a day, real visitors push the loop, and a banner that rides out earns network ad views. Weekly leaderboards for visitors sent. Advertising, not income.' }
|
||||
];
|
||||
const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
const $ = id => document.getElementById(id);
|
||||
let user = '', cur = '', cache = {}, txt = [];
|
||||
try { cur = localStorage.getItem('iap.netkit') || ''; } catch (e) {}
|
||||
if (!SITES.some(s => s.key === cur)) cur = SITES[0].key;
|
||||
function setUser(u) { if (u && u !== user) { user = u; cache = {}; } }
|
||||
async function copy(t, btn) {
|
||||
try { await navigator.clipboard.writeText(t); } catch (e) { const a = document.createElement('textarea'); a.value = t; document.body.appendChild(a); a.select(); try { document.execCommand('copy'); } catch (e2) {} a.remove(); }
|
||||
if (window.IAP && IAP.status) IAP.status('Copied.', 'ok');
|
||||
if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1300); }
|
||||
}
|
||||
const cb = (t, label, cls) => { txt.push(t); return '<button type="button" class="btn small ' + (cls == null ? 'sec' : cls) + '" data-nkc="' + (txt.length - 1) + '">' + esc(label || 'Copy') + '</button>'; };
|
||||
function pick() {
|
||||
const p = $('nkPick'); if (!p) return;
|
||||
p.innerHTML = SITES.map(s => '<button type="button" class="chip-t' + (s.key === cur ? ' on' : '') + '" data-nk="' + s.key + '">' + esc(s.name) + '</button>').join('');
|
||||
p.querySelectorAll('[data-nk]').forEach(b => b.addEventListener('click', () => { cur = b.dataset.nk; try { localStorage.setItem('iap.netkit', cur); } catch (e) {} pick(); show(); }));
|
||||
}
|
||||
function render(site, k) {
|
||||
txt = [];
|
||||
const by = {}; const angles = [];
|
||||
(k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); });
|
||||
let h = '<p class="muted small" style="margin:0 0 12px">' + esc(site.blurb) + '</p>';
|
||||
// tracked links (2026-11-14): the site's LinkSpin network link, credited here to InstantAdPay as the site that sent the visit
|
||||
const strip = (label, url, cls) => '<div class="promo-strip" style="padding:0 0 12px"><div><span class="eyebrow" style="margin:0 0 4px">' + esc(label) + '</span><div class="mono small" style="overflow-wrap:anywhere">' + esc(url) + '</div></div><span>' + cb(url, 'Copy link', cls) + '</span></div>';
|
||||
const fromHere = u => String(u).replace(/([?&]src=)[a-z0-9]+/i, '$1iap');
|
||||
h += k.links.map(l => strip(l.label, l.url, '') + (l.tracked ? strip(l.label + ', tracked', fromHere(l.tracked), 'sec') : '')).join('');
|
||||
if (k.links.some(l => l.tracked)) h += '<p class="muted small" style="margin:0 0 12px">A tracked link goes through LinkSpin first, so the network can see the visit came from InstantAdPay, then opens the same page with your username. Use either one.</p>';
|
||||
h += '<div class="card-head" style="margin-top:6px"><h3>Creatives</h3><span class="sub">every HTML snippet already links to you</span></div>';
|
||||
angles.forEach(a => {
|
||||
h += '<details class="promo-block nk-set"' + (a === angles[0] ? ' open' : '') + '><summary class="pb-head" style="cursor:pointer"><span class="lab"><b>' + esc(a.angleLabel) + '</b></span> <span class="muted small">' + by[a.angle].length + ' sizes</span></summary><div class="nk-grid">'
|
||||
+ by[a.angle].map(c => '<figure class="nk-fig"><a href="' + esc(c.url) + '" target="_blank" rel="noopener"><img src="' + esc(c.url) + '" alt="' + esc(k.name + ', ' + c.label) + '" width="' + c.w + '" height="' + c.h + '" loading="lazy" style="max-width:' + Math.min(c.w, c.w > 600 ? 420 : c.w) + 'px"></a>'
|
||||
+ '<figcaption class="small"><b>' + esc(c.label) + '</b> <span class="muted">' + c.w + '×' + c.h + '</span></figcaption><div class="pb-actions"><a class="btn small sec" href="' + esc(c.url) + '" target="_blank" rel="noopener" download>Download</a> ' + cb(c.url, 'Copy URL') + ' ' + cb(c.html, 'Copy HTML') + '</div></figure>').join('')
|
||||
+ '</div></details>';
|
||||
});
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Short lines</h3><span class="sub">chats, comments, text ads, signatures</span></div>'
|
||||
+ k.lines.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Headlines</h3></div>' + k.headlines.map(t => '<div class="promo-block"><div class="pb-text"><b>' + esc(t) + '</b></div><div class="pb-actions">' + cb(t) + '</div></div>').join('');
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Email</h3><span class="sub">plain text, paste it into any mailer</span></div><div class="promo-block"><div class="pb-head"><span class="lab">Subject:</span> ' + esc(k.email.subject) + '</div><div class="pb-text">' + esc(k.email.body) + '</div><div class="pb-actions">' + cb(k.email.subject, 'Copy subject') + ' ' + cb(k.email.body, 'Copy email', '') + '</div></div>';
|
||||
h += '<div class="card-head" style="margin-top:14px"><h3>Social posts</h3></div>' + k.posts.map(t => '<div class="promo-block"><div class="pb-text">' + esc(t) + '</div><div class="pb-actions">' + cb(t, 'Copy post') + '</div></div>').join('');
|
||||
if (k.note) h += '<p class="muted small" style="margin:12px 0 0">' + esc(k.note) + '</p>';
|
||||
if (k.promotePage) h += '<p class="small" style="margin:8px 0 0">The same kit is on <a href="' + esc(k.promotePage + '?u=' + encodeURIComponent(user)) + '" target="_blank" rel="noopener">' + esc(k.name) + ' › Promote</a>.</p>';
|
||||
return h;
|
||||
}
|
||||
async function show() {
|
||||
const box = $('nkBody'); if (!box) return;
|
||||
const site = SITES.find(s => s.key === cur);
|
||||
if (!user) { box.innerHTML = '<p class="muted">Pick a username first: it becomes your link on every network site.</p>'; return; }
|
||||
box.innerHTML = '<p class="muted small">Loading the ' + esc(site.name) + ' kit...</p>';
|
||||
try {
|
||||
if (!cache[cur]) {
|
||||
const r = await fetch(site.feed + '?u=' + encodeURIComponent(user), { cache: 'no-store' });
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
cache[cur] = await r.json();
|
||||
}
|
||||
if (cur !== site.key) return;
|
||||
box.innerHTML = render(site, cache[cur]);
|
||||
box.querySelectorAll('[data-nkc]').forEach(b => b.addEventListener('click', () => copy(txt[Number(b.dataset.nkc)], b)));
|
||||
} catch (e) { box.innerHTML = '<p class="muted">Could not load the ' + esc(site.name) + ' kit right now. Try again in a minute.</p>'; }
|
||||
}
|
||||
function load(u) { if (u) setUser(u); pick(); show(); }
|
||||
return { load, setUser, SITES };
|
||||
})();
|
||||
@@ -0,0 +1,24 @@
|
||||
// "Part of the network" footer line for pages that do not load common.js (Marty 2026-11-14 trust pack): company line + the network
|
||||
// list from the hub (/api/network-sites, built-in copy if it does not answer). The current site comes from data-site on this tag.
|
||||
(function () {
|
||||
var me = (document.currentScript && document.currentScript.getAttribute('data-site')) || 'iap';
|
||||
var FALLBACK = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'],
|
||||
['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(function (a) { return { id: a[0], name: a[1], url: a[2] }; });
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"' }[c]; }); }
|
||||
function run() {
|
||||
var f = document.querySelector('footer'); if (!f || f.querySelector('.netline')) return;
|
||||
var hasLegal = !!f.querySelector('a[href="/terms"]'); // decided once, before this line adds its own links
|
||||
var host = f.querySelector('.wrap') || f;
|
||||
var box = document.createElement('div'); box.className = 'netline';
|
||||
box.style.cssText = 'flex-basis:100%;width:100%;margin-top:10px;display:flex;gap:6px 14px;flex-wrap:wrap;align-items:baseline;font-size:12.5px';
|
||||
host.appendChild(box);
|
||||
var paint = function (list) {
|
||||
box.innerHTML = (hasLegal ? '' : '<span style="flex-basis:100%"><a href="/terms">Terms</a> · <a href="/disclaimer">Earnings Disclaimer</a> · <a href="/privacy">Privacy</a> · <a href="/contract">Contract</a> · <a href="/ledger">Ledger</a> · <a href="/support">Support</a></span>') + '<span style="flex-basis:100%">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span><b>Part of the network</b><span>One account across the network:</span>' + list.map(function (s) {
|
||||
return s.id === me ? '<span aria-current="page" style="font-weight:700">' + esc(s.name) + ' (you are here)</span>' : '<a href="' + esc(s.go || s.url) + '" target="_blank" rel="noopener nofollow">' + esc(s.name) + '</a>';
|
||||
}).join('');
|
||||
};
|
||||
paint(FALLBACK);
|
||||
fetch('/api/network-sites').then(function (r) { return r.json(); }).then(function (l) { if (Array.isArray(l) && l.length) paint(l); }).catch(function () {});
|
||||
}
|
||||
if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', run); else run();
|
||||
})();
|
||||
+1
-1
@@ -165,7 +165,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/bixpay-guide.js?v=20261029bz"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -143,7 +143,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/contract.js?v=20260908p"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
</body>
|
||||
|
||||
@@ -265,7 +265,8 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/conversion-guide.js?v=20261024ct"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -27,7 +27,7 @@
|
||||
<p class="muted small">You decide whether, and how much, to spend. Never spend more than you can afford to lose.</p>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-1
@@ -97,6 +97,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -127,7 +127,7 @@
|
||||
</ul>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-1
@@ -72,6 +72,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/friday.js?v=20260925a"></script>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+2
-1
@@ -79,6 +79,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/games-page.js?v=20261012b"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -506,7 +506,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wallet.js?v=20260909c"></script>
|
||||
<script src="/assets/home.js?v=20261027tb"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
|
||||
+1
-1
@@ -158,7 +158,7 @@
|
||||
InstantAdPay · <a href="/contract">Contract</a> · <a href="/terms">Terms</a> · <a href="/privacy">Privacy</a> · <a href="/disclaimer">Disclaimer</a>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/join.js?v=20261107nc"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -106,7 +106,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/launch.js?v=20260915b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -41,7 +41,7 @@
|
||||
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/ledger.js?v=20260906m"></script>
|
||||
<script src="https://polhunter.com/embed.js" data-slots="1" async></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
|
||||
+16
-2
@@ -855,6 +855,7 @@
|
||||
<button class="chip-t" data-promo="viral" type="button" role="tab">Viral links</button>
|
||||
<button class="chip-t" data-promo="stackpol" type="button" role="tab">📈 Stack POL</button>
|
||||
<button class="chip-t" data-promo="games" type="button" role="tab">🎮 Games</button>
|
||||
<button class="chip-t" data-promo="network" type="button" role="tab">🌐 Network sites</button>
|
||||
<button class="chip-t" data-promo="bixpay" type="button" role="tab" hidden>💳 BixPay</button>
|
||||
</div>
|
||||
<!-- Stack POL page switch (2026-11-09): stackpol.com/<username> shows every POL payout to the member's wallets across the network -->
|
||||
@@ -886,6 +887,14 @@
|
||||
<div id="bixPromoBanners"></div>
|
||||
<p class="small muted" style="margin:12px 0 0">BixPay is a separate company. BIX issues the wallet and the card through its banking partners and sets its own fees, limits, eligibility and terms. InstantAdPay is not the card issuer and earns a referral commission when you sign up through a partner link. Card availability varies by country. Crypto assets can lose value.</p>
|
||||
</div>
|
||||
<!-- Network sites (2026-11-14): Downline Banners + Viral Banner Blitz kits, read live from each site's /api/promo-kit feed; netkits.js -->
|
||||
<div class="card promo-sec" id="promo-network" hidden>
|
||||
<div class="card-head"><h3>🌐 Network sites</h3><span class="sub">your username is your link on every network site</span></div>
|
||||
<p class="muted small" style="margin:0 0 10px">Your InstantAdPay username works as your sponsor link on the other network sites too, even if you have never visited them. Every link, creative and line below carries it. Each site keeps its own kit, so what you see here is always the current one.</p>
|
||||
<style>.nk-grid{display:flex;flex-wrap:wrap;gap:16px;align-items:flex-start;margin-top:10px}.nk-fig{margin:0;display:flex;flex-direction:column;gap:6px;max-width:100%}.nk-fig img{display:block;max-width:100%;height:auto;border-radius:6px}.nk-set{margin:10px 0}</style>
|
||||
<div class="chips" id="nkPick" style="margin:0 0 12px"></div>
|
||||
<div id="nkBody"></div>
|
||||
</div>
|
||||
<div class="card promo-sec" id="promo-games" hidden>
|
||||
<div class="card-head"><h3>🎮 Our games</h3><span class="sub">free to play, every link carries your username</span></div>
|
||||
<p class="muted small" style="margin:0 0 10px">Every game here is free to play and brings players into InstantAdPay. Your username is built into each link, post and banner, so anyone who joins through them lands on your line. Pick a game.</p>
|
||||
@@ -1269,7 +1278,11 @@
|
||||
<a href="/ledger">Live ledger</a>
|
||||
<a href="/contract">The contract</a>
|
||||
<a href="#help">Support</a>
|
||||
<a href="/terms">Terms</a>
|
||||
<a href="/disclaimer">Earnings Disclaimer</a>
|
||||
<a href="/privacy">Privacy</a>
|
||||
<a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>
|
||||
<span style="width:100%;text-align:center;color:var(--muted)">TrustClickz · 615 Green Valley Drive, Moody, AL 35004</span>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1293,11 +1306,12 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wallet.js?v=20260911a"></script>
|
||||
<script src="/assets/promo.js?v=20261103gp"></script>
|
||||
<script src="/assets/support.js?v=20261101th"></script>
|
||||
<script src="/assets/my.js?v=20261113sso"></script>
|
||||
<script src="/assets/netkits.js?v=20261114ns"></script>
|
||||
<script src="/assets/my.js?v=20261114kes"></script>
|
||||
<script src="/assets/fuel.js?v=20261113sso"></script>
|
||||
<script src="/assets/engine-room.js?v=20261113sso"></script>
|
||||
<script src="/assets/netsso.js?v=20261113sso"></script>
|
||||
|
||||
@@ -131,7 +131,8 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/partners.js?v=20260914a"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -194,7 +194,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/plays.js?v=20260910b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -87,6 +87,6 @@
|
||||
<div class="small">InstantAdPay is the Polygon hub of the <a href="https://cryptoteambuild.com" target="_blank" rel="noopener">Crypto Team Build Network</a>.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/presentation.js?v=20261015b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@
|
||||
<p class="muted small">We use reasonable safeguards, but no system is perfectly secure. Protect your email and your wallet.</p>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -261,6 +261,6 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@
|
||||
<div id="supMain"><div class="card"><p class="muted small">Loading…</p></div></div>
|
||||
<p class="small muted">We will never ask for your recovery phrase or private key, and nobody from InstantAdPay will message you first asking for money or wallet access.</p>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
<script src="/assets/support.js?v=20261101th"></script>
|
||||
<script src="/assets/chat.js?v=20261016n"></script>
|
||||
|
||||
+1
-1
@@ -42,7 +42,7 @@
|
||||
<p class="muted small" style="margin-top:18px">See also the <a href="/disclaimer">Disclaimer</a> and <a href="/privacy">Privacy Policy</a>. Questions: the <a href="/support">support page</a> or <a href="mailto:support@instantadpay.com">support@instantadpay.com</a>.</p>
|
||||
</div>
|
||||
</div></section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/legal.js?v=20260908a"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@
|
||||
<p><a href="/ledger">← Back to the live ledger</a> · <a href="/contract">Read the contract review</a></p>
|
||||
</div>
|
||||
</section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/tx.js?v=20260906m"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -48,7 +48,7 @@
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wall.js?v=20261030pp"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
+1
-1
@@ -123,7 +123,7 @@
|
||||
<div class="small">Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never share your recovery phrase.</div>
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/welcome.js?v=20261101th"></script>
|
||||
<script src="/assets/wallets.js?v=20260911b"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -65,6 +65,7 @@
|
||||
</footer>
|
||||
</div>
|
||||
<script src="/assets/wednesday.js?v=20260929c"></script>
|
||||
<script src="/assets/common.js?v=20261113nl"></script>
|
||||
<script src="/assets/common.js?v=20261114ns"></script>
|
||||
<script src="/assets/netline.js?v=20261114ns" data-site="iap"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -0,0 +1,287 @@
|
||||
// 5xYourTeam "The Draft" partner routes (draftpartner.js + the tank.adopt partner path, 2026-11-15).
|
||||
// node qa/draft-partner.test.mjs (also part of `bash qa/run.sh member`; `bash qa/run.sh draft` alone)
|
||||
// Part A, no server: the REAL tank.js + draftpartner.js with in-memory accounts, a fake chain, a fake hub and a MOCKED CLOCK.
|
||||
// signature, the pool rules (locked / sponsored / spam / throwaway / adopted twice / grace shown with opensAt / no contact data),
|
||||
// adopt (the 5x claim replaces the $20 rule only here, wallet + contract line, 10 open, fresh lock check, hub off, rid repeat,
|
||||
// the normal adoption email is the only mail), the auto-assign conflict rule (a drafted person is out of the tank; tank.sweep
|
||||
// leaves a pick's adoption alone), release (48 h hold, back with the original join time, two adoptions = kept, started = done,
|
||||
// locked = kept, hub silent = wait), the hourly sweep (wallet alone is not started), reconcile, status, the log.
|
||||
// Part B, LOCAL copy (throwaway DATA_DIR, JSON store, DRAFT_ALLOW_NO_HUB=1): the HTTP routes answer signed calls only.
|
||||
// Never production. Exit code 1 on any failure.
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import crypto from 'node:crypto';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { createRequire } from 'node:module';
|
||||
|
||||
const SITE = path.resolve(path.dirname(new URL(import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1')), '..');
|
||||
const require = createRequire(path.join(SITE, 'package.json'));
|
||||
delete process.env.DATABASE_URL; // JSON stores only
|
||||
const SECRET = 'draft-test-secret-' + 'x'.repeat(40);
|
||||
let fails = 0, passes = 0; const ok = (cond, label, extra) => { console.log((cond ? 'PASS ' : 'FAIL ') + label + (cond || extra === undefined ? '' : ' ' + (typeof extra === 'string' ? extra : JSON.stringify(extra)))); if (!cond) fails++; else passes++; };
|
||||
const H = 3600000, D = 86400000;
|
||||
const addr = () => '0x' + crypto.randomBytes(20).toString('hex');
|
||||
|
||||
function fakeAccounts() {
|
||||
const by = new Map(); let nextId = 100;
|
||||
const pub = a => a ? Object.assign({}, a) : null;
|
||||
const find = f => { for (const a of by.values()) if (f(a)) return pub(a); return null; };
|
||||
return {
|
||||
_by: by,
|
||||
add(email, o) { const a = Object.assign({ email, username: email.split('@')[0].replace(/[^a-z0-9_]/g, ''), code: 'c' + (nextId++), sponsorRef: '', memberId: 0, address: null, created: Date.now() - 30 * D, lastSeen: Date.now() - H, joinedVia: null }, o || {}); by.set(email, a); return pub(a); },
|
||||
async byEmail(e) { return pub(by.get(String(e || '').toLowerCase())); },
|
||||
async byUsername(u) { const x = String(u || '').toLowerCase(); return find(a => a.username === x); },
|
||||
async byCode(c) { const x = String(c || '').toLowerCase(); return find(a => a.code === x); },
|
||||
async byMemberId(id) { return find(a => Number(a.memberId) === Number(id) && id > 0); },
|
||||
async byAddress(w) { const x = String(w || '').toLowerCase(); return find(a => a.address && a.address.toLowerCase() === x); },
|
||||
async positionOwner() { return null; },
|
||||
async setSponsorRef(e, ref) { const a = by.get(e); if (!a) return { error: 'No such account.' }; a.sponsorRef = String(ref || '').toLowerCase(); return { ok: true }; },
|
||||
async listAll() { return [...by.values()].map(pub); },
|
||||
isUnclaimedShell: () => false,
|
||||
async sponsorOf(e) { const a = by.get(e); if (!a || !a.sponsorRef) return null; return (await this.byUsername(a.sponsorRef)) || (await this.byCode(a.sponsorRef)); }
|
||||
};
|
||||
}
|
||||
|
||||
function bench(o) {
|
||||
o = o || {};
|
||||
for (const m of ['tank.js', 'draftpartner.js']) delete require.cache[require.resolve(path.join(SITE, m))];
|
||||
const tank = require(path.join(SITE, 'tank.js'));
|
||||
const dp = require(path.join(SITE, 'draftpartner.js'));
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-'));
|
||||
const accounts = fakeAccounts(); const events = []; const chats = []; const mails = []; const notices = []; const assigned = []; const deliberate = [];
|
||||
const hub = { locked: new Set(), sponsored: new Set(), down: false, on: true, ids: new Map() };
|
||||
const flagged = new Set(); const spamList = [];
|
||||
const env = { now: Date.now() };
|
||||
const follow = { setDeliberate: async (email, token, by, note) => { deliberate.push({ email, token, by, note }); return accounts.setSponsorRef(email, token); } };
|
||||
const why = e => hub.down ? 'unknown' : hub.locked.has(e) ? 'locked' : hub.sponsored.has(e) ? 'sponsored' : null;
|
||||
tank.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse(), getConfig: () => ({}) }, follow,
|
||||
messages: { sendChat: async (id, from, to, text) => { chats.push({ from, to, text }); }, lastFrom: async () => 0 },
|
||||
mailer: { hasKey: () => true, send: async (to, subject, body) => { mails.push({ to, subject, body }); } }, site: 'https://iap.test',
|
||||
hooks: { network: () => null, isSuspended: () => false, excluded: e => flagged.has(e), payoutBlocked: async () => false, companyId: () => 1,
|
||||
networkHeld: async accts => new Map(accts.map(a => [a.email, why(a.email)]).filter(x => x[1])),
|
||||
networkLocked: async e => { const w = why(e); return w === 'locked' || w === 'unknown' ? w : null; },
|
||||
isDraftPick: id => dp.isDraftPick(id),
|
||||
assigned: r => { assigned.push(r); }, adminAlert: () => {}, claim: () => true, activated: () => false, notify: async (to, subject, text) => { notices.push({ to, subject, text }); } } });
|
||||
tank.setClock(() => env.now);
|
||||
process.env.DRAFT_PARTNER_SECRET = SECRET;
|
||||
const ready = dp.init({ dataDir: dir, accounts, chain: { recentEvents: () => events.slice().reverse() }, tank, ads: { earnedTotals: async em => Object.fromEntries(em.map(e => [e, { earned: e.startsWith('surf') ? 420 : 0, balance: 0 }])) },
|
||||
requireHub: true, clock: () => env.now,
|
||||
hooks: { hubInfo: e => hub.ids.has(e) ? { id: hub.ids.get(e), door: 'linkspin' } : null, networkOn: () => hub.on, excluded: e => flagged.has(e), spamEmails: () => spamList,
|
||||
suggestDomain: d => require(path.join(SITE, 'emailcheck.js')).suggestDomain(d) } });
|
||||
let block = 1000;
|
||||
// a coach: a wallet linked here and payouts on (member id), but NO $20 purchase (their vesting is the 5x position)
|
||||
const coach = (email, memberId, extra) => accounts.add(email, Object.assign({ memberId, address: addr() }, extra || {}));
|
||||
const buy = (memberId, cents) => events.push({ type: 'Purchase', buyerId: memberId, priceCents: cents || 2000, block: block++ });
|
||||
return { tank, dp, ready, accounts, events, chats, mails, notices, assigned, deliberate, hub, flagged, spamList, env, coach, buy, dir };
|
||||
}
|
||||
const claimOf = (a, positions) => ({ wallet: a.address, username: a.username, positions: positions === undefined ? 1 : positions });
|
||||
let ridN = 0; const rid = () => 'rid-test-' + (++ridN) + '-' + crypto.randomBytes(3).toString('hex');
|
||||
|
||||
async function partA() {
|
||||
console.log('-- Part A: draftpartner.js + tank.js, mocked clock, fake hub');
|
||||
// ---- signature ----
|
||||
{
|
||||
const B = bench(); await B.ready;
|
||||
const raw = JSON.stringify({}); const ts = String(Date.now());
|
||||
const good = B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw);
|
||||
ok(good.body && typeof good.body === 'object', 'signature: a good signature passes');
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw, 'other-secret-' + 'y'.repeat(30)) }, raw).status === 401, 'signature: another secret is refused');
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': B.dp.sign(ts, raw) }, raw + ' ').status === 401, 'signature: a changed body is refused');
|
||||
const old = String(Date.now() - 6 * 60000);
|
||||
ok(B.dp.verify({ 'x-draft-ts': old, 'x-draft-sig': B.dp.sign(old, raw) }, raw).status === 401, 'signature: older than 5 minutes is refused');
|
||||
const keep = process.env.DRAFT_PARTNER_SECRET; process.env.DRAFT_PARTNER_SECRET = 'short';
|
||||
ok(B.dp.verify({ 'x-draft-ts': ts, 'x-draft-sig': 'x' }, raw).status === 503, 'signature: no (or a short) secret = 503, nothing answers');
|
||||
process.env.DRAFT_PARTNER_SECRET = keep;
|
||||
}
|
||||
// ---- the pool ----
|
||||
const B = bench(); await B.ready; const { tank, dp, accounts, env, hub } = B;
|
||||
accounts.add('live@x.co', { address: addr(), lastSeen: env.now - 2 * H });
|
||||
accounts.add('plain@x.co');
|
||||
accounts.add('surfer@x.co');
|
||||
accounts.add('locked@x.co'); hub.locked.add('locked@x.co');
|
||||
accounts.add('sponsoredhub@x.co'); hub.sponsored.add('sponsoredhub@x.co');
|
||||
accounts.add('flagged@x.co'); B.flagged.add('flagged@x.co');
|
||||
accounts.add('farm@x.co'); B.spamList.push('farm@x.co');
|
||||
accounts.add('temp@mailinator.com');
|
||||
accounts.add('typo@gmial.com');
|
||||
accounts.add('fresh@x.co', { created: env.now - 2 * H });
|
||||
accounts.add('kid@x.co', { sponsorRef: 'someone' });
|
||||
accounts.add('twice@x.co');
|
||||
hub.ids.set('live@x.co', 'h_0123456789abcdef');
|
||||
const C1 = B.coach('coach1@x.co', 41); const C2 = B.coach('coach2@x.co', 42);
|
||||
// twice@ has had two adoptions already (an old IAP one and a dropped one)
|
||||
B.buy(43); B.coach('iapadopter@x.co', 43);
|
||||
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // back in the tank by hand: 1 counted
|
||||
await tank.adopt('iapadopter@x.co', 'twice@x.co'); await accounts.setSponsorRef('twice@x.co', ''); // 2 counted
|
||||
for (const ad of await tank.openOf('twice@x.co')) await tank.closeAdoption(ad.id, 'dropped');
|
||||
B.mails.length = 0; B.chats.length = 0;
|
||||
const P = await dp.pool();
|
||||
const names = P.pool.map(c => c.username).sort();
|
||||
ok(P.ok && names.join(',') === ['fresh', 'live', 'plain', 'surfer'].join(','), 'pool: only people who pass every rule', names.join(','));
|
||||
ok(P.excluded.spam === 2 && P.excluded.throwaway === 2 && P.excluded.adoptedTwice === 1, 'pool: spam/flagged, throwaway + mistyped domains and adopted-twice counted out', P.excluded);
|
||||
ok(!names.includes('locked') && !names.includes('sponsoredhub') && !names.includes('kid'), 'pool: nobody locked on a contract, sponsored on the hub or sponsored here');
|
||||
const live = P.pool.find(c => c.username === 'live'); const fresh = P.pool.find(c => c.username === 'fresh'); const plain = P.pool.find(c => c.username === 'plain');
|
||||
ok(live.id === 'h_0123456789abcdef' && live.door === 'LinkSpin' && live.wallet === true && live.joinedAt > 0, 'card: hub id + door from the hub cache, wallet linked yes/no, joined', live);
|
||||
ok(/^i_[0-9a-f]{16}$/.test(plain.id) && plain.door === 'InstantAdPay', 'card: someone the hub does not know gets an opaque i_ id');
|
||||
ok(fresh.opensAt > env.now, 'card: a sign-up inside the 24-hour grace is shown with opensAt');
|
||||
ok(live.games === null && live.surfWei === null && typeof live.surfCredits === 'number', 'card: games null (not tracked here), surfing as credits, never invented');
|
||||
const keys = new Set(P.pool.flatMap(c => Object.keys(c)));
|
||||
ok(!JSON.stringify(P).includes('@') && !keys.has('email') && !keys.has('address'), 'pool: no contact data (no email, no wallet address) in the answer');
|
||||
ok(P.rules.returnHours === 72 && P.rules.holdHours === 48 && P.rules.maxOpen === 10 && P.rules.maxAdoptions === 2 && P.rules.graceHours === 24, 'pool: the rules travel with it', P.rules);
|
||||
|
||||
// ---- adopt ----
|
||||
const a0 = await dp.adopt({ rid: rid(), coach: claimOf(C1, 0), person: plain.id, kind: 'draft' });
|
||||
ok(a0.code === 'not_vested', 'adopt: no 5x position = refused (free members cannot adopt)', a0);
|
||||
const a1 = await dp.adopt({ rid: rid(), coach: { wallet: addr(), positions: 1 }, person: plain.id });
|
||||
ok(a1.code === 'coach_unknown', 'adopt: a wallet with no account here is refused', a1);
|
||||
const nw = accounts.add('nowallet@x.co', { memberId: 0 });
|
||||
accounts._by.get('nowallet@x.co').address = null;
|
||||
const nwc = B.coach('freecoach@x.co', 0);
|
||||
const a2 = await dp.adopt({ rid: rid(), coach: claimOf(nwc), person: plain.id });
|
||||
ok(a2.code === 'no_contract_line', 'adopt: a coach with nobody on this contract in their line is refused (a pick would land under the company)', a2);
|
||||
void nw;
|
||||
hub.on = false;
|
||||
const a3 = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: plain.id });
|
||||
ok(a3.code === 'hub_off', 'adopt: hub off = nobody can be drafted', a3);
|
||||
ok((await dp.pool()).pool.length === 0, 'pool: hub off = empty pool');
|
||||
hub.on = true;
|
||||
ok(!(await tank.eligibility('coach1@x.co')).ok, "the coach is NOT eligible for InstantAdPay's own tank button (keeps its $20 rule)");
|
||||
const r1 = rid();
|
||||
const g = await dp.adopt({ rid: rid(), coach: claimOf(C1), person: fresh.id });
|
||||
ok(g.code === 'grace', 'adopt: a sign-up inside the 24-hour grace is refused', g);
|
||||
const ok1 = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id, kind: 'draft', week: '2026-11-16', slot: '1.1' });
|
||||
ok(ok1.ok && /^iap:\d+$/.test(ok1.ref) && ok1.person === live.id && ok1.expires === env.now + 3 * D && ok1.holdUntil === env.now + 48 * H, 'adopt: a 5x coach with payouts on and no $20 buy adopts; 3-day window, 48 h hold', ok1);
|
||||
const la = await accounts.byEmail('live@x.co');
|
||||
ok(la.sponsorRef === 'coach1', 'adopt: the sponsor is now the coach (InstantAdPay record)', la.sponsorRef);
|
||||
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'adopt'), "adopt: the move went through the deliberate path (sponsorfollow + the hub's sponsor-change, by 'adopt')");
|
||||
const open = await tank.openOf('live@x.co');
|
||||
ok(open.length === 1 && open[0].expires - open[0].ts === 3 * D && /5xYourTeam draft pick/.test(open[0].note), "adopt: the tank adoption's own window is 3 days, noted as a draft pick", open[0]);
|
||||
ok(B.mails.length === 1 && B.mails[0].to === 'live@x.co' && /is now your sponsor on InstantAdPay/.test(B.mails[0].subject), 'mail: exactly one, the normal "X is now your sponsor" adoption email', B.mails.map(m => m.subject));
|
||||
ok(B.chats.some(c => c.to === 'live@x.co' && /your coach from 5xYourTeam/.test(c.text)), 'adopt: a site chat from the coach (site messages only)');
|
||||
ok(!tank.payView().some(x => x.email === 'live@x.co'), 'adopt: no switch-on-payouts reminder mails are queued for a pick');
|
||||
ok(B.assigned.length === 0, 'adopt: no payments-topic pickup post');
|
||||
const rep = await dp.adopt({ rid: r1, coach: claimOf(C1), person: live.id });
|
||||
ok(rep.ok && rep.repeat && rep.ref === ok1.ref && B.mails.length === 1, 'adopt: the same rid again answers the first result and sends nothing');
|
||||
const tw = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: live.id });
|
||||
ok(tw.code === 'gone', 'adopt: someone already picked is no longer in the pool', tw);
|
||||
// fresh lock check at adopt (the pool cache is 30 s old at most; the adopt asks the hub again)
|
||||
accounts.add('late@x.co'); const lp = (await dp.pool()).pool; dp._poolReset();
|
||||
const late = (await dp.pool()).pool.find(c => c.username === 'late');
|
||||
hub.locked.add('late@x.co'); const al = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
|
||||
ok(al.code === 'gone' || al.code === 'locked', 'adopt: locked a moment ago = refused', al); hub.locked.delete('late@x.co'); void lp;
|
||||
hub.down = true; dp._poolReset();
|
||||
const ad = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: late.id });
|
||||
ok(ad.error && (ad.code === 'gone' || ad.code === 'hub_unknown'), 'adopt: a hub that does not answer refuses (the conservative side)', ad);
|
||||
hub.down = false; dp._poolReset();
|
||||
// 10 open picks at most
|
||||
for (let i = 0; i < 10; i++) accounts.add('fill' + i + '@x.co');
|
||||
const pl = (await dp.pool()).pool; let made = 0;
|
||||
for (const c of pl.filter(c => /^fill/.test(c.username))) { const r = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: c.id }); if (r.ok) made++; }
|
||||
const over = await dp.adopt({ rid: rid(), coach: claimOf(C2), person: plain.id });
|
||||
ok(made === 10 && over.code === 'full', 'adopt: 10 open picks a coach, the 11th is refused', { made, over });
|
||||
|
||||
// ---- auto-assign vs the pick window ----
|
||||
env.now += 30 * H; // past any 24-hour activation hold
|
||||
const tick = await tank.readyTick();
|
||||
ok(!tick.assigned.some(x => x.adoptee === 'live@x.co') && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach1', 'conflict rule: a drafted person (wallet linked) is out of the tank, never auto-assigned while the pick runs');
|
||||
ok(!(await tank.waiting()).some(w => w.email === 'live@x.co'), 'conflict rule: not on the waiting list while picked');
|
||||
|
||||
// ---- release ----
|
||||
const early = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
ok(early.code === 'hold', 'release: not inside the 48-hour hold', early);
|
||||
const notMine = await dp.release({ rid: rid(), coach: claimOf(C2), ref: ok1.ref, why: 'coach' });
|
||||
ok(notMine.code === 'not_yours', 'release: another coach cannot release it', notMine);
|
||||
const tooEarly = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'return' });
|
||||
ok(tooEarly.code === 'too_early', 'return: not before the 3 days', tooEarly);
|
||||
env.now += 20 * H; // 50 h after the pick
|
||||
const rel = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
const back = await accounts.byEmail('live@x.co');
|
||||
ok(rel.ok && rel.outcome === 'returned' && back.sponsorRef === '', 'release: after 48 h the pick goes back to the tank', rel);
|
||||
ok(B.deliberate.some(d => d.email === 'live@x.co' && d.by === 'release' && /released by the coach/.test(d.note)), "release: the move went through the deliberate path (by 'release')");
|
||||
dp._poolReset();
|
||||
const again = (await dp.pool()).pool.find(c => c.id === live.id);
|
||||
ok(again && again.joinedAt === live.joinedAt && !again.opensAt, 'release: back in the pool with the ORIGINAL join time, no new sign-up grace', again);
|
||||
ok(again.adoptionsTotal === 1 && again.adoptions === 0, 'release: the dropped pick still counts toward their two (total 1; 0 outside 5xYourTeam, which counts its own picks)', again);
|
||||
const relAgain = await dp.release({ rid: rid(), coach: claimOf(C1), ref: ok1.ref, why: 'coach' });
|
||||
ok(relAgain.ok && relAgain.already && relAgain.outcome === 'returned', 'release: a repeat answers "already" and changes nothing');
|
||||
ok(B.mails.length === 11, 'mail: still only the adoption emails (1 + 10), nothing on release', B.mails.length);
|
||||
// second adoption: C3 picks them again; at 3 days unstarted they stay with C3 (adopted twice)
|
||||
const C3 = B.coach('coach3@x.co', 44);
|
||||
const p2 = await dp.adopt({ rid: rid(), coach: claimOf(C3), person: live.id, kind: 'instant' });
|
||||
ok(p2.ok, 'second pick of the same person (their 2nd adoption)', p2);
|
||||
env.now += 3 * D + H;
|
||||
const sw = await dp.sweep();
|
||||
ok(sw.kept === 1 && (await accounts.byEmail('live@x.co')).sponsorRef === 'coach3', 'sweep: at 3 days, a person on their 2nd adoption stays with the coach (kept)', sw);
|
||||
dp._poolReset();
|
||||
ok(!(await dp.pool()).pool.some(c => c.id === live.id), 'pool: someone adopted twice is never offered again');
|
||||
|
||||
// ---- the hourly sweep: wallet alone is not started; started = done; locked = kept; hub silent = wait ----
|
||||
const C4 = B.coach('coach4@x.co', 45);
|
||||
accounts.add('w1@x.co'); accounts.add('s1@x.co'); accounts.add('k1@x.co'); accounts.add('u1@x.co'); dp._poolReset();
|
||||
const pool4 = (await dp.pool()).pool; const idOf = u => pool4.find(c => c.username === u).id;
|
||||
const pw = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('w1') }); const ps = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('s1') });
|
||||
const pk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('k1') }); const pu = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: idOf('u1') });
|
||||
ok(pw.ok && ps.ok && pk.ok && pu.ok, 'four more picks for the sweep checks');
|
||||
accounts._by.get('w1@x.co').address = addr(); // linked a wallet only
|
||||
accounts._by.get('s1@x.co').address = addr(); accounts._by.get('s1@x.co').memberId = 77; B.buy(77, 1000); // switched on payouts + bought
|
||||
// tank.sweep (the IAP 7-day sweep) leaves a pick's expired adoption alone
|
||||
env.now += 3 * D + H;
|
||||
hub.locked.add('k1@x.co');
|
||||
const st0 = await dp.status({ ids: [idOf('s1'), idOf('w1'), 'h_ffffffffffffffff'] });
|
||||
ok(st0.people['h_ffffffffffffffff'] === null, 'status: someone 5xYourTeam holds no pick for answers null');
|
||||
ok(st0.people[idOf('s1')].payouts > 0 && st0.people[idOf('s1')].purchase > 0 && st0.people[idOf('w1')].wallet > 0 && !st0.people[idOf('w1')].payouts, 'status: milestones (wallet / payouts / purchase as first-seen times)', st0.people[idOf('w1')]);
|
||||
ok(!JSON.stringify(st0).includes('@'), 'status: no contact data');
|
||||
hub.down = true;
|
||||
const swU = await dp.sweep();
|
||||
ok(swU.waiting >= 1 && swU.done === 1 && (await accounts.byEmail('u1@x.co')).sponsorRef === 'coach4', 'sweep: hub not answering = the return waits, nobody moved', swU);
|
||||
hub.down = false;
|
||||
const sw2 = await dp.sweep();
|
||||
ok(sw2.returned === 2 && sw2.kept === 1, 'sweep: started = done (even with the hub silent), wallet-only + plain = returned, locked = kept', sw2);
|
||||
ok((await accounts.byEmail('w1@x.co')).sponsorRef === '' && (await accounts.byEmail('s1@x.co')).sponsorRef === 'coach4' && (await accounts.byEmail('k1@x.co')).sponsorRef === 'coach4', 'sweep: sponsors after the 3 days (wallet-only back to the tank; started and locked stay)');
|
||||
const tsw = await tank.sweep();
|
||||
ok(tsw.back === 0, 'tank.sweep: never touches a pick (the pick rule decides, not the 7-day wallet rule)', tsw);
|
||||
// a pick whose tank adoption was closed some other way (released on InstantAdPay itself, a LinkSpin follow) reconciles
|
||||
accounts.add('m1@x.co'); dp._poolReset(); const pm = (await dp.pool()).pool.find(c => c.username === 'm1');
|
||||
const pmk = await dp.adopt({ rid: rid(), coach: claimOf(C4), person: pm.id });
|
||||
for (const a of await tank.openOf('m1@x.co')) await tank.closeAdoption(a.id, 'moved');
|
||||
const stm = await dp.status({ ids: [pm.id] });
|
||||
ok(pmk.ok && stm.people[pm.id].pick.status === 'moved', 'reconcile: a pick closed on InstantAdPay shows as moved', stm.people[pm.id].pick);
|
||||
// the log: every call with a reason
|
||||
const av = await dp.adminView();
|
||||
ok(av.log.length > 20 && av.log.every(l => l.op && l.ts && (l.ok || l.code)) && av.log.some(l => l.op === 'adopt' && !l.ok && l.code === 'not_vested') && av.log.some(l => l.op === 'sweep' && l.code === 'kept'), 'log: every call is logged with an outcome code / reason', av.log.slice(0, 3));
|
||||
ok(!JSON.stringify(av.picks).includes('@'), 'admin view: picks carry no emails');
|
||||
}
|
||||
|
||||
// ---------------- Part B: the routes on a local copy ----------------
|
||||
async function partB() {
|
||||
console.log('-- Part B: HTTP routes on a local copy');
|
||||
const port = Number(process.env.DRAFT_E2E_PORT || 8825);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'iap-draft-b-'));
|
||||
const env = Object.assign({}, process.env, { PORT: String(port), DATA_DIR: dir, ADMIN_EMAIL: 'admin@iap.test', ADMIN_PASSWORD: 'localtest', DRAFT_PARTNER_SECRET: SECRET, DRAFT_ALLOW_NO_HUB: '1', LS_URL: 'http://127.0.0.1:9', HUB_ENABLED: '' });
|
||||
delete env.DATABASE_URL; delete env.NODE_ENV;
|
||||
const child = spawn(process.execPath, ['server.js'], { cwd: SITE, env, stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
let log = ''; child.stdout.on('data', d => { log += d; }); child.stderr.on('data', d => { log += d; });
|
||||
const base = 'http://127.0.0.1:' + port;
|
||||
try {
|
||||
let up = false; for (let i = 0; i < 40 && !up; i++) { try { up = (await fetch(base + '/api/config')).ok; } catch (e) {} if (!up) await new Promise(r => setTimeout(r, 500)); }
|
||||
ok(up, 'local copy up on :' + port, up ? undefined : log.slice(-600));
|
||||
if (!up) return;
|
||||
const call = async (op, body, opts) => { const raw = JSON.stringify(body || {}); const ts = String(Date.now()); const sig = (opts && opts.sig) || crypto.createHmac('sha256', SECRET).update('draft.v1.' + ts + '\n' + raw).digest('hex');
|
||||
const r = await fetch(base + '/api/partner/draft/' + op, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Draft-Ts': ts, 'X-Draft-Sig': sig }, body: raw }); return { status: r.status, body: await r.json().catch(() => null) }; };
|
||||
const p = await call('pool', {});
|
||||
ok(p.status === 200 && p.body.ok && Array.isArray(p.body.pool) && p.body.rules.maxOpen === 10, 'POST /api/partner/draft/pool signed: 200 with rules + pool', p);
|
||||
ok((await call('pool', {}, { sig: 'f'.repeat(64) })).status === 401, 'unsigned / wrong signature: 401');
|
||||
ok((await call('nope', {})).status === 404, 'unknown op: 404');
|
||||
const a = await call('adopt', { rid: 'rid-route-0001', coach: { wallet: addr(), positions: 1 }, person: 'h_0000000000000000' });
|
||||
ok(a.status === 400 && a.body.code === 'coach_unknown', 'adopt for an unknown coach: 400 with a code', a.body);
|
||||
const s = await call('status', { ids: ['h_0000000000000000'] });
|
||||
ok(s.status === 200 && s.body.people['h_0000000000000000'] === null, 'status: 200, unknown person null');
|
||||
ok((await fetch(base + '/api/admin/draft')).status === 401, 'GET /api/admin/draft needs the admin');
|
||||
} finally { child.kill(); }
|
||||
}
|
||||
|
||||
await partA();
|
||||
if (!process.env.DRAFT_SKIP_B) await partB();
|
||||
console.log(fails ? 'FAILED ' + fails + ' (passed ' + passes + ')' : 'ALL PASSED (' + passes + ')');
|
||||
process.exit(fails ? 1 : 0);
|
||||
+148
-1
@@ -12,13 +12,18 @@ const assert = require('assert');
|
||||
const { spawn } = require('child_process');
|
||||
|
||||
const ROOT = path.join(__dirname, '..');
|
||||
const HUB_DIR = process.env.HUB_DIR || ['..', path.join('..', '..')].flatMap(up => ['network-hub-resolve-id', 'network-hub'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
const HUB_DIR = process.env.HUB_DIR || ['..', path.join('..', '..')].flatMap(up => ['network-hub', 'network-hub-resolve-id'].map(d => path.join(ROOT, up, d))).find(d => fs.existsSync(path.join(d, 'server.js')));
|
||||
let fails = 0, n = 0;
|
||||
async function t(name, fn) { n++; try { await fn(); console.log('ok', name); } catch (e) { fails++; console.log('FAIL', name, '::', e && e.stack ? e.stack.split('\n').slice(0, 3).join(' | ') : e); } }
|
||||
const IAP_SECRET = 'i'.repeat(40), CTB_SECRET = 'c'.repeat(40);
|
||||
const W = k => '0x' + String(k).repeat(40).slice(0, 40);
|
||||
const sig = (secret, ts, raw) => crypto.createHmac('sha256', secret).update(ts + '\n' + raw).digest('hex');
|
||||
const listen = srv => new Promise(ok => srv.listen(0, '127.0.0.1', () => ok(srv.address().port)));
|
||||
// mail audit (2026-11-14): every outbound request this process makes is recorded; only the local hub and site may be called.
|
||||
// mailer.js sends with https.request (SendGrid), Telegram and Sendy go out over https too, so both doors are watched.
|
||||
const outside = [];
|
||||
{ const realFetch = global.fetch; global.fetch = (u, o) => { const s = String(u && u.url ? u.url : u); if (!/^http:[/][/]127[.]0[.]0[.]1:/.test(s)) outside.push(s); return realFetch(u, o); };
|
||||
const https = require('https'); const realReq = https.request; https.request = function (...a) { outside.push('https ' + JSON.stringify((a[0] && a[0].hostname) || a[0])); return realReq.apply(this, a); }; }
|
||||
|
||||
delete process.env.DATABASE_URL; delete process.env.LS_SYNC_SECRET; // JSON stores, LinkSpin push off
|
||||
const HUB_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-hub-'));
|
||||
@@ -164,11 +169,153 @@ const IAP_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-iap-'));
|
||||
const v = hubsync.adminView(); assert.strictEqual(v.outbox, 0); assert.ok(v.recent.find(l => l.type === 'out-refused' && l.code === 'wallet_taken'));
|
||||
});
|
||||
|
||||
await t('rule 2: a paid Purchase on the InstantAdPay contract reaches the hub and moves the network sponsor to this contract (2026-11-14)', async () => {
|
||||
// tureia2003's shape: locked on LinkSpin under silverstussy (activated only), then bound AND paid here under paidtowatch
|
||||
await ctb('/v1/join', { email: 'ptw@example.test', username: 'ptw' }); await ctb('/v1/wallet', { email: 'ptw@example.test', wallet: W('d') });
|
||||
await ctb('/v1/join', { email: 'sil@example.test', username: 'sil' }); await ctb('/v1/wallet', { email: 'sil@example.test', wallet: W('f') });
|
||||
await ctb('/v1/join', { email: 'tur@example.test', ref: 'sil', username: 'tur' });
|
||||
await ctb('/v1/contract-bind', { contract: 'linkspin', email: 'tur@example.test', wallet: W('7'), sponsorRef: W('f') });
|
||||
assert.strictEqual(hubPerson('tur@example.test').sponsorId, hubPerson('sil@example.test').id);
|
||||
const members = { 5: { account: W('d') }, 12: { account: W('7') } };
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound, chain: { member: async id => members[id] || null } });
|
||||
hubsync.onChain({ type: 'MemberActivated', id: 12, account: W('7'), sponsorId: 5 });
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 0, paidWei: '0', tx: '0xfree' }); // nothing paid in: not a spend
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 });
|
||||
hubsync.onChain({ type: 'Purchase', buyerId: 12, priceCents: 3500, paidWei: '1000', tx: '0xpaid', ts: 1700000000000 }); // seen twice
|
||||
await settle(); await hubsync.flush(true);
|
||||
const p = hubPerson('tur@example.test');
|
||||
assert.strictEqual(p.bindings.iap.sponsorId, hubPerson('ptw@example.test').id);
|
||||
assert.strictEqual(p.bindings.iap.spentCents, 3500, 'one purchase counted once');
|
||||
assert.strictEqual(p.bindings.linkspin.sponsorId, hubPerson('sil@example.test').id, 'the LinkSpin lock keeps its sponsor');
|
||||
assert.strictEqual(p.sponsorId, hubPerson('ptw@example.test').id, 'network sponsor = the contract with money spent');
|
||||
assert.strictEqual(hubsync.adminView().outbox, 0);
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound });
|
||||
});
|
||||
|
||||
await t('sponsor.changed and unknown event types are acknowledged and ignored', async () => {
|
||||
const s = signed([{ seq: 99001, type: 'sponsor.changed', personId: hubPerson('bob@example.test').id, data: { by: 'admin' } }, { seq: 99002, type: 'member.blocked', personId: 'h_0000000000000000', data: {} }]);
|
||||
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
||||
});
|
||||
|
||||
const HP = hubReq('lib/people');
|
||||
await t('rule 2 on arrival: someone the InstantAdPay contract holds arrives under that lock sponsor, not the network sponsor; sponsor.changed never moves them', async () => {
|
||||
await ctb('/v1/join', { email: 'lx@example.test', username: 'lockx' }); // their sponsor on the InstantAdPay contract
|
||||
await ctb('/v1/join', { email: 'ly@example.test', username: 'locky' }); // their sponsor on LinkSpin, where the money was spent
|
||||
await ctb('/v1/join', { email: 'lk@example.test', username: 'lockkid', ref: 'locky' });
|
||||
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'lockx', at: 1000 });
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk@example.test', wallet: W('3'), sponsorRef: 'locky', at: 2000, spentCents: 2500 });
|
||||
await hubStore.flush();
|
||||
const hp = hubPerson('lk@example.test');
|
||||
assert.strictEqual(hp.sponsorId, hubPerson('ly@example.test').id, 'network sponsor = LinkSpin (money spent there)');
|
||||
assert.strictEqual(hp.bindings.iap.sponsorId, hubPerson('lx@example.test').id);
|
||||
await deliver();
|
||||
const kid = await accounts.byEmail('lk@example.test'); const lx = await accounts.byEmail('lx@example.test');
|
||||
assert.ok(kid && lx, 'both arrived');
|
||||
assert.strictEqual(kid.sponsorRef, lx.username || lx.code, 'the InstantAdPay lock sponsor is written here');
|
||||
const s = signed([{ seq: 99101, type: 'sponsor.changed', personId: hp.id, data: { by: 'contract', contract: 'linkspin' } }]);
|
||||
assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200);
|
||||
assert.strictEqual((await accounts.byEmail('lk@example.test')).sponsorRef, lx.username || lx.code, 'sponsor.changed is ignored');
|
||||
// climbing: a lock sponsor not on InstantAdPay yet comes along before the member (their event alone)
|
||||
await ctb('/v1/join', { email: 'lz@example.test', username: 'lockz' });
|
||||
await ctb('/v1/join', { email: 'lk2@example.test', username: 'lockkid2', ref: 'locky' });
|
||||
HP.bindContract({ site: 'iap', contract: 'iap', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'lockz', at: 3000, spentCents: 2000 });
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'lk2@example.test', wallet: W('4'), sponsorRef: 'locky', at: 1500, spentCents: 2000 }); // earlier spend: network = locky
|
||||
await hubStore.flush();
|
||||
assert.strictEqual(hubPerson('lk2@example.test').sponsorId, hubPerson('ly@example.test').id);
|
||||
const ev = hubStore.eventsAfter(0, 1e6).find(e => e.type === 'member.joined' && e.personId === hubPerson('lk2@example.test').id);
|
||||
const s2 = signed([ev]); assert.strictEqual((await hubsync.receive(s2.headers, s2.raw)).status, 200);
|
||||
const lz = await accounts.byEmail('lz@example.test');
|
||||
assert.ok(lz, 'the lock sponsor came along'); assert.strictEqual((await accounts.byEmail('lk2@example.test')).sponsorRef, lz.username || lz.code);
|
||||
await deliver();
|
||||
});
|
||||
|
||||
// the holding tank, as server.js wires it with HUB_ENABLED, with a mailer and messages that only record
|
||||
const tank = require(path.join(ROOT, 'tank.js'));
|
||||
const sent = [];
|
||||
const mailer = { hasKey: () => true, send: async (...a) => { sent.push(['mail', a[0], a[1]]); } };
|
||||
const messages = { sendChat: async (...a) => { sent.push(['chat', a[2]]); }, deliver: async (...a) => { sent.push(['notice', a[2]]); }, lastFrom: async () => Date.now() }; // every sponsor 'just wrote': rescue warnings are not what this checks
|
||||
tank.init({ dataDir: IAP_DATA, accounts, chain: { recentEvents: () => [], member: async () => null }, messages, mailer,
|
||||
hooks: { network: async (email, address) => (await hubsync.hubSponsor(email)) || lsinbound.networkSponsor(email, address), networkHeld: a => hubsync.heldAmong(a), networkLocked: e => hubsync.lockedAnywhere(e) } });
|
||||
|
||||
await t('rule 3: the tank never offers anyone locked on any network contract or sponsored in the hub; release refuses a locked member', async () => {
|
||||
await ctb('/v1/join', { email: 'tk1@example.test', username: 'tk1ctb', ref: 'annctb' }); // the hub knows a sponsor
|
||||
for (const e of ['tk1', 'tk2', 'tk3']) assert.ok((await accounts.ensure(e + '@example.test', '', null, null)).created); // signed up here, no sponsor
|
||||
await settle(); await hubsync.flush(true);
|
||||
HP.bindContract({ site: 'linkspin', contract: 'linkspin', email: 'tk2@example.test', wallet: W('5'), sponsorRef: '' }); await hubStore.flush(); // locked, top of that tree
|
||||
hubsync._heldReset();
|
||||
const held = await hubsync.heldAmong([await accounts.byEmail('tk1@example.test'), await accounts.byEmail('tk2@example.test'), await accounts.byEmail('tk3@example.test')]);
|
||||
assert.deepStrictEqual([...held.entries()].sort(), [['tk1@example.test', 'sponsored'], ['tk2@example.test', 'locked']]);
|
||||
const w = (await tank.waiting()).map(x => x.email);
|
||||
assert.ok(w.includes('tk3@example.test'), 'a free member is offered');
|
||||
assert.ok(!w.includes('tk1@example.test') && !w.includes('tk2@example.test'), 'sponsored and locked are not: ' + w.join(','));
|
||||
// tk2 under erin here, not activated here: releasing them to the tank is refused, the hub's lock elsewhere stands
|
||||
const erin = await accounts.byEmail('erin@example.test'); await accounts.setSponsorRef('tk2@example.test', erin.username || erin.code);
|
||||
const r = await tank.release('erin@example.test', 'tk2@example.test');
|
||||
assert.ok(r.error && /locked/.test(r.error), JSON.stringify(r));
|
||||
assert.strictEqual((await accounts.byEmail('tk2@example.test')).sponsorRef, erin.username || erin.code);
|
||||
// the 15-minute tick: with HUB_TANK_ALIGN off tk1 is only held; with it on, aligned to the sponsor the hub knows (ann has a real account here), quietly
|
||||
await tank.readyTick(); assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef || '', '', 'alignment from the hub is off by default');
|
||||
process.env.HUB_TANK_ALIGN = 'on'; await tank.readyTick(); delete process.env.HUB_TANK_ALIGN;
|
||||
assert.strictEqual((await accounts.byEmail('tk1@example.test')).sponsorRef, ann.username || ann.code, 'aligned to the hub sponsor');
|
||||
});
|
||||
|
||||
await t('rule 3 fail-safe: hub unreachable past the 1-hour cache = nobody it was asked about is offered; back = offered again', async () => {
|
||||
process.env.HUB_URL = 'http://127.0.0.1:1'; hubsync._heldAge(30 * 60000);
|
||||
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'within the hour the last answer stands');
|
||||
hubsync._heldReset(); // nothing cached, hub down
|
||||
assert.ok(!(await tank.waiting()).map(x => x.email).includes('tk3@example.test'), 'unknown = held');
|
||||
assert.strictEqual(await hubsync.lockedAnywhere('tk3@example.test'), 'unknown');
|
||||
process.env.HUB_URL = HUB; hubsync._heldReset();
|
||||
assert.ok((await tank.waiting()).map(x => x.email).includes('tk3@example.test'));
|
||||
});
|
||||
|
||||
await t('an adoption-window expiry (tank label expire) reaches the hub as a sponsor change by expiry (fix 2026-11-15)', async () => {
|
||||
assert.strictEqual(hubsync._hubBy('expire'), 'expiry'); assert.strictEqual(hubsync._hubBy('adopt'), 'adopt');
|
||||
const recs = new Map(); const follow = { get: e => recs.get(String(e).toLowerCase()) || null };
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound, follow }); // as server.js passes followStore
|
||||
const erin = await accounts.byEmail('erin@example.test');
|
||||
recs.set('tk3@example.test', { by: 'adopt', sponsorEmail: 'erin@example.test', at: Date.now() });
|
||||
await accounts.setSponsorRef('tk3@example.test', erin.username || erin.code); await settle(); await hubsync.flush(true);
|
||||
let hp = hubPerson('tk3@example.test'); assert.strictEqual(hp.sponsorId, hubPerson('erin@example.test').id, 'adopt reached the hub');
|
||||
recs.set('tk3@example.test', { by: 'expire', sponsorEmail: '', at: Date.now() + 1 });
|
||||
await accounts.setSponsorRef('tk3@example.test', ''); await settle(); await hubsync.flush(true);
|
||||
hp = hubPerson('tk3@example.test'); const last = hp.sponsorHistory[hp.sponsorHistory.length - 1];
|
||||
assert.strictEqual(hp.sponsorId, null, 'expiry cleared the hub sponsor'); assert.strictEqual(last.by, 'expiry', JSON.stringify(last));
|
||||
hubsync.init({ dataDir: IAP_DATA, accounts, lsinbound }); // back as the other tests had it
|
||||
});
|
||||
|
||||
await t('mail audit: hub arrivals (new, sponsor climbed, existing filled, wallet) and the tank ticks send no mail, chat, notice or outside call', async () => {
|
||||
sent.length = 0; outside.length = 0;
|
||||
await ctb('/v1/join', { email: 'ma@example.test', username: 'mailtop' }); await ctb('/v1/wallet', { email: 'ma@example.test', wallet: W('6') });
|
||||
await ctb('/v1/join', { email: 'mb@example.test', username: 'mailkid', ref: 'mailtop' }); await ctb('/v1/wallet', { email: 'mb@example.test', wallet: W('8') });
|
||||
process.env.HUB_ENABLED = ''; await accounts.ensure('mc@example.test', '', null, null); process.env.HUB_ENABLED = '1'; // here before the hub knew them
|
||||
await ctb('/v1/join', { email: 'mc@example.test', username: 'mailfill' }); // an existing InstantAdPay account: empty fields filled
|
||||
const evs = hubStore.eventsAfter(hubStore.cursor('iap'), 100);
|
||||
const kid = evs.find(e => e.personId === hubPerson('mb@example.test').id && e.type === 'member.joined');
|
||||
const s = signed([kid]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 200); // the kid first: the sponsor climbs
|
||||
await deliver();
|
||||
assert.ok(await accounts.byEmail('ma@example.test') && await accounts.byEmail('mb@example.test'));
|
||||
assert.strictEqual((await accounts.byEmail('mb@example.test')).address, W('8'));
|
||||
assert.strictEqual((await accounts.byEmail('mc@example.test')).username, 'mailfill', 'filled');
|
||||
await settle(); await hubsync.flush(true); await tank.readyTick(); await tank.sweep(); await settle(); await hubsync.flush(true);
|
||||
assert.deepStrictEqual(JSON.parse(fs.readFileSync(path.join(IAP_DATA, 'hubsync.json'), 'utf8')).outbox, []);
|
||||
assert.deepStrictEqual(sent, [], 'nothing sent');
|
||||
assert.deepStrictEqual(outside, [], 'no outside call');
|
||||
// the old direct LinkSpin sync never pushes a waiting account the hub made (LinkSpin's registry route would switch payouts
|
||||
// on and email them); a member who signs up here still goes
|
||||
const pushed = []; const lsStub = http.createServer((req, res) => { let d = ''; req.on('data', c => { d += c; }); req.on('end', () => { try { for (const r of JSON.parse(d).rows || []) pushed.push(r.email); } catch (e) {} res.writeHead(200, { 'Content-Type': 'application/json' }); res.end('{"ok":true,"proto":2}'); }); });
|
||||
process.env.LS_URL = 'http://127.0.0.1:' + await listen(lsStub); process.env.LS_SYNC_SECRET = 's'.repeat(40);
|
||||
try {
|
||||
await lssync.tick(true);
|
||||
assert.ok(pushed.length > 0, 'the sync ran');
|
||||
for (const e of ['ma@example.test', 'mb@example.test', 'lk@example.test', 'bob@example.test']) assert.ok(!pushed.includes(e), e + ' (a hub waiting account) was pushed');
|
||||
assert.ok(pushed.includes('erin@example.test'), 'an InstantAdPay sign-up still syncs');
|
||||
} finally { delete process.env.LS_SYNC_SECRET; lsStub.close(); }
|
||||
// and the hub path itself never loads a mail module
|
||||
const loaded = Object.keys(require.cache).map(f => path.basename(f));
|
||||
for (const m of ['mailer.js', 'sendy.js', 'messages.js', 'drip.js']) assert.ok(!loaded.includes(m), m + ' is loaded');
|
||||
});
|
||||
|
||||
await t('flag off: the module answers 404 and reports nothing', async () => {
|
||||
process.env.HUB_ENABLED = '';
|
||||
const s = signed([]); assert.strictEqual((await hubsync.receive(s.headers, s.raw)).status, 404);
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// GET /api/admin/member-extra (2026-11-14): the network hub's member lookup reads opt-out, tank and hold state here. Read-only.
|
||||
// Runs against LOCAL (bash qa/run.sh member starts it). Admin = Bearer localtest.
|
||||
const B = process.env.LOCAL || 'http://127.0.0.1:8796';
|
||||
let pass = 0, fail = 0; const ok = (c, m, x) => { if (c) pass++; else { fail++; console.log('[bug] member-extra ' + m + (x ? ' :: ' + x : '')); } };
|
||||
const email = 'mx' + Date.now() + '@example.com'; const ip = '198.51.100.' + (20 + Math.floor(Math.random() * 200));
|
||||
const H = { 'Content-Type': 'application/json', 'X-Forwarded-For': ip, 'User-Agent': 'Mozilla/5.0 MemberExtraQA' };
|
||||
const post = (p, b) => fetch(B + p, { method: 'POST', headers: H, body: JSON.stringify(b) }).then(r => r.json().catch(() => ({})));
|
||||
const get = (q, auth) => fetch(B + '/api/admin/member-extra?email=' + encodeURIComponent(q), { headers: auth ? { Authorization: 'Bearer ' + auth } : {} });
|
||||
try {
|
||||
ok((await get(email)).status === 401, 'no admin header is refused');
|
||||
ok((await get(email, 'wrong')).status === 401, 'a wrong admin password is refused');
|
||||
ok((await get(email, 'localtest')).status === 404, 'an unknown email is 404');
|
||||
const st = await post('/api/auth/email/start', { email, fts: Date.now() - 8000, fage: 8000 });
|
||||
if (st.devCode) await post('/api/auth/email/verify', { email, code: st.devCode });
|
||||
const r = await get(email, 'localtest'); const j = await r.json().catch(() => null);
|
||||
ok(r.status === 200 && j, 'a known account answers', r.status);
|
||||
ok(j && j.tank && typeof j.tank.inTank === 'boolean', 'tank.inTank is a boolean', JSON.stringify(j));
|
||||
ok(j && 'optedOut' in j, 'optedOut is present');
|
||||
const w = await fetch(B + '/api/admin/member-extra?email=' + encodeURIComponent(email), { method: 'POST', headers: { Authorization: 'Bearer localtest' } });
|
||||
ok(w.status !== 200 || !(await w.text()).includes('optedOut'), 'POST is not a route (read-only)');
|
||||
} catch (e) { fail++; console.log('[bug] member-extra crashed :: ' + e.message); }
|
||||
console.log('member-extra: ' + pass + ' passed, ' + fail + ' failed');
|
||||
process.exit(fail ? 1 : 0);
|
||||
@@ -142,7 +142,8 @@ try {
|
||||
// a session that expired on the provider: the check answers none
|
||||
ctx = await newCtx({ iap: 'f'.repeat(64) }); page = await ctx.newPage();
|
||||
await page.goto(LS + '/sso/start?mode=go&to=%2Fads'); await page.waitForTimeout(1500);
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url() === LS + '/ads', 'an expired IAP session: the check answers none, normal sign-in');
|
||||
ok(!(await meOf(ctx, LS)).signedIn && page.url().startsWith(IAP + '/my'), 'an expired IAP session on a deliberate tap: IAP asks for its own sign-in first (2026-11-14)', page.url());
|
||||
ok((await ctx.cookies(IAP)).some(c => c.name === 'nsso.back'), 'IAP remembers the unfinished trip while the member signs in');
|
||||
await ctx.close();
|
||||
|
||||
// 6. not on the receiving site yet: C (IAP only) going to LinkSpin, D (LinkSpin only) going to IAP
|
||||
|
||||
@@ -82,7 +82,7 @@ const b64u = b => Buffer.from(b).toString('base64').replace(/=+$/, '').replace(/
|
||||
r = await call(R('/sso/start?to=/my', 'nsso.off=1'));
|
||||
ok(r.loc === '/my', 'after a sign-out here: no silent check');
|
||||
r = await call(R('/sso/start?mode=go&to=/my', 'nsso.off=1'));
|
||||
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||
ok(/^https:\/\/ls\.example\/sso\/check\?st=[a-f0-9]{32}&to=%2Fmy&m=go$/.test(r.loc) && r.set.some(c => /^nsso\.off=;/.test(c)), 'a deliberate link from the other site still signs in after a sign-out (and lifts the 12-hour pause)');
|
||||
r = await call(R('/sso/start?to=https://evil.example'));
|
||||
const stc = (r.set.find(c => c.startsWith('nsso.st=')) || '').split(';')[0].split('=')[1];
|
||||
ok(/^[a-f0-9]{32}$/.test(stc) && r.set.some(c => /^nsso\.tried=1;.*Max-Age=1800/.test(c)) && r.set.every(c => /HttpOnly/.test(c) && /Secure/.test(c)) && r.loc.endsWith('&to=%2Fmy'), '/sso/start: HttpOnly state + 30-minute guard, off-site path replaced', r.loc);
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
# bash qa/run.sh all # public + member + earn
|
||||
# bash qa/run.sh kb # chat knowledge base: retrieval unit test + chat endpoint e2e on a local copy with a mock OpenRouter
|
||||
# bash qa/run.sh walletnudge # game wallet push (any linked wallet, activated or not) + no-wallet nudge copy against a mock game (also runs in member)
|
||||
# bash qa/run.sh draft # 5xYourTeam The Draft partner routes: pool / adopt / release / status rules on the real tank.js (mocked clock, fake hub) + the signed HTTP routes on a local copy (also runs in member)
|
||||
# bash qa/run.sh tankhold # holding-tank activation hold, 24-hour safety net (mocked clock) and LinkSpin alignment: unit + local copy (also runs in member)
|
||||
# bash qa/run.sh sponsorfollow # sponsor follow rule + network tank unit tests and the two-server e2e (local IAP + local LinkSpin, throwaway data)
|
||||
# bash qa/run.sh door # Spooky Doors door + costume shop flows on their own local copy (qa/door.mjs boots it)
|
||||
@@ -66,14 +67,17 @@ elif [ "$MODE" = "sso" ]; then
|
||||
node qa/networksso.test.cjs || status=1
|
||||
node qa/networksso.e2e.mjs || status=1
|
||||
elif [ "$MODE" = "member" ]; then
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; }; stop_local 8796
|
||||
start_local 8796 && { LOCAL=http://127.0.0.1:8796 node qa/walk.mjs member || status=1; LOCAL=http://127.0.0.1:8796 node qa/member-extra.mjs || status=1; }; stop_local 8796
|
||||
node qa/networksso.test.cjs || status=1 # network sign-in with the other site: tokens, replay, open redirects, loop guard
|
||||
node qa/networksso.e2e.mjs || status=1 # both servers locally, a real browser across them (skips if the other repo is not beside this one)
|
||||
node qa/tank-hold.mjs || status=1
|
||||
node qa/draft-partner.test.mjs || status=1 # 5xYourTeam draft partner routes (DRAFT_E2E_PORT, default 8825)
|
||||
node qa/walletnudge.test.cjs || status=1
|
||||
node qa/bixpay.test.cjs || status=1
|
||||
node qa/profile-policy.test.cjs || status=1
|
||||
node qa/sov-heroes-store.cjs || status=1
|
||||
elif [ "$MODE" = "draft" ]; then
|
||||
node qa/draft-partner.test.mjs || status=1
|
||||
elif [ "$MODE" = "theme" ]; then
|
||||
start_local 8797 && { LOCAL=http://127.0.0.1:8797 node qa/theme-contrast.mjs || status=1; }; stop_local 8797
|
||||
elif [ "$MODE" = "policy" ]; then
|
||||
|
||||
+40
-26
@@ -5,7 +5,9 @@
|
||||
// Roland by default), order -> fulfil -> ownership (permanent, no expiry), the bundle grants all three, no double charge (owned hero
|
||||
// refused, a waiting order for an owned hero cancelled, each tx once, one package one order), packages bought before the order or too
|
||||
// small, a pass order and a hero order side by side, settings (price 0 = free for everyone, bundle list), the hand-off claim (heroes,
|
||||
// heroBundle, heroSale, heroBundleCap only when set), comp / revoke, stats, and that hero sales never touch the pass records. Exit 1 on failure.
|
||||
// heroBundle, heroSale, heroBundleCap only when set), comp / revoke, stats, and that hero sales never touch the pass records.
|
||||
// 2026-11-14 (Marty approved): Kestrel is free in the game at level 20, so she is never sold here (no buy, never in a bundle, a waiting
|
||||
// Kestrel order is cancelled unpaid); a member who bought her before keeps her. Exit 1 on failure.
|
||||
'use strict';
|
||||
const fs = require('fs'); const os = require('os'); const path = require('path');
|
||||
const gp = require('../gamepass');
|
||||
@@ -27,33 +29,43 @@ const pkg = (email, cents, at, tx) => gp.onEvent({ type: 'Purchase', priceCents:
|
||||
let r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(r.error === 'Bonus heroes are not on sale yet.', 'heroSales off: a member is refused', JSON.stringify(r));
|
||||
ok(![...orders.values()].length, 'a refused buy opens no order');
|
||||
let v = gp.view('m@x.com', T0).heroes; ok(v.show === false && v.items.every(i => !i.open), 'heroSales off: the member card hides the heroes', JSON.stringify(v.items.map(i => i.open)));
|
||||
v = gp.view('admin@x.com', T0, { preview: true }).heroes; ok(v.show && v.preview && v.items.every(i => i.open) && v.bundle.open && v.items.map(i => i.package).join() === '20,20,20,20' && v.bundle.package === 50, 'the admin preview: every hero open, $20 packages, the bundle on the $50 package', JSON.stringify(v));
|
||||
v = gp.view('admin@x.com', T0, { preview: true }).heroes; ok(v.show && v.preview && v.items.filter(i => !i.freeAt).every(i => i.open) && v.items.find(i => i.key === 'kestrel').freeAt === 20 && !v.items.find(i => i.key === 'kestrel').open && v.bundle.open && v.items.map(i => i.package).join() === '20,20,20,20' && v.bundle.package === 50, 'the admin preview: every sold hero open (Kestrel shown free at 20, not open), $20 packages, the bundle on the $50 package', JSON.stringify(v));
|
||||
r = gp.buyHero('admin@x.com', T0, 'roland', { preview: true }); ok(r.needPay && r.price === 2000 && r.package === 20 && /Roland the Paladin joins you in Shards of Valor/.test(r.message) && !/—/.test(r.message), 'the admin test opens a $20 order', JSON.stringify(r));
|
||||
r = gp.cancelHeroOrder('admin@x.com', 'roland'); ok(r.ok && r.order, 'the admin cancels the test order');
|
||||
ok(!(await pkg('admin@x.com', 2000, T0 + 1000)), 'a cancelled order is never fulfilled later');
|
||||
|
||||
// 2. on sale: one hero, order then a fresh package
|
||||
// 2. on sale: Kestrel is never sold (free at 20 in the game); a past Kestrel buyer keeps her; a waiting Kestrel order is cancelled unpaid
|
||||
SC.heroSales = '1';
|
||||
r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(r.needPay && r.payUrl.includes('#buy') && r.usd === 20, 'on sale: buy opens a waiting order, no charge', JSON.stringify(r));
|
||||
const r2 = gp.buyHero('m@x.com', T0 + 10, 'kestrel'); ok(r2.reused && r2.order === r.order, 'a second click reuses the same order');
|
||||
r = gp.buyHero('m@x.com', T0, 'kestrel'); ok(/Kestrel the Archer is free for every player at level 20 in Shards of Valor, so she is not for sale\./.test(r.error || '') && !/\u2014/.test(r.error), 'Kestrel is refused: free at level 20', JSON.stringify(r));
|
||||
ok(![...orders.values()].some(o => o.hero === 'kestrel' && o.status === 'waiting'), 'no Kestrel order opened');
|
||||
passes.set('k@x.com', { until: 0, bought: [], heroes: { kestrel: { ts: T0 - 86400000, via: 'package', tx: '0xoldkes', cents: 2000, usd: 20 } } });
|
||||
ok(gp.heroesOwned('k@x.com').owned.join() === 'kestrel' && gp.heroClaim('k@x.com').heroes.join() === 'kestrel', 'a member who bought Kestrel before keeps her (the hand-off still says so)');
|
||||
v = gp.view('k@x.com', T0).heroes; ok(v.items.find(i => i.key === 'kestrel').owned && v.show, 'her card says Yours for good');
|
||||
orders.set('hero-oldkes', { status: 'waiting', kind: 'hero', hero: 'kestrel', email: 'w@x.com', ts: T0 });
|
||||
ok(!(await pkg('w@x.com', 2000, T0 + 1000)), 'a Kestrel order from before the change is never fulfilled');
|
||||
ok(orders.get('hero-oldkes').status === 'cancelled' && /free at level 20/.test(orders.get('hero-oldkes').why || ''), 'and it is cancelled unpaid', JSON.stringify(orders.get('hero-oldkes')));
|
||||
ok(gp.heroesOwned('w@x.com').owned.length === 0, 'nothing granted for it');
|
||||
// one sold hero: order then a fresh package
|
||||
r = gp.buyHero('m@x.com', T0, 'roland'); ok(r.needPay && r.payUrl.includes('#buy') && r.usd === 20, 'on sale: buy opens a waiting order, no charge', JSON.stringify(r));
|
||||
const r2 = gp.buyHero('m@x.com', T0 + 10, 'roland'); ok(r2.reused && r2.order === r.order, 'a second click reuses the same order');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 - 60000)), 'a package bought before the order does not fulfil it');
|
||||
ok(!(await pkg('m@x.com', 1000, T0 + 1000)), 'a $10 package is too small');
|
||||
let ev = await pkg('m@x.com', 2000, T0 + 2000, '0xkes1');
|
||||
ok(ev && ev.hero === 'kestrel' && ev.heroes.join() === 'kestrel', 'a fresh $20 package fulfils it', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'kestrel', 'Kestrel is owned');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 3000, '0xkes1')), 'the same tx never counts twice');
|
||||
r = gp.buyHero('m@x.com', T0 + 4000, 'kestrel'); ok(/already have Kestrel/.test(r.error || ''), 'no double charge: an owned hero is refused', JSON.stringify(r));
|
||||
const rec = passes.get('m@x.com'); ok(rec.heroes.kestrel.tx === '0xkes1' && rec.heroes.kestrel.via === 'package' && rec.heroes.kestrel.usd === 20 && !rec.heroes.kestrel.until && !(rec.bought || []).length && !rec.tiers, 'stored for good (no expiry), never as a pass sale', JSON.stringify(rec));
|
||||
let ev = await pkg('m@x.com', 2000, T0 + 2000, '0xrol1');
|
||||
ok(ev && ev.hero === 'roland' && ev.heroes.join() === 'roland', 'a fresh $20 package fulfils it', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'roland', 'Roland is owned');
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 3000, '0xrol1')), 'the same tx never counts twice');
|
||||
r = gp.buyHero('m@x.com', T0 + 4000, 'roland'); ok(/already have Roland/.test(r.error || ''), 'no double charge: an owned hero is refused', JSON.stringify(r));
|
||||
const rec = passes.get('m@x.com'); ok(rec.heroes.roland.tx === '0xrol1' && rec.heroes.roland.via === 'package' && rec.heroes.roland.usd === 20 && !rec.heroes.roland.until && !(rec.bought || []).length && !rec.tiers, 'stored for good (no expiry), never as a pass sale', JSON.stringify(rec));
|
||||
ok(gp.flag('m@x.com', T0).active === false, 'a hero is not a Game Pass');
|
||||
ok(gp.heroesOwned('m@x.com').owned.includes('kestrel') && gp.heroesOwned('m@x.com', T0 + 3650 * 86400000).owned.includes('kestrel'), 'owned years later too');
|
||||
ok(gp.heroesOwned('m@x.com').owned.includes('roland') && gp.heroesOwned('m@x.com', T0 + 3650 * 86400000).owned.includes('roland'), 'owned years later too');
|
||||
|
||||
// 3. the bundle: all three, and its refusals
|
||||
r = gp.buyHero('m@x.com', T0, 'bundle'); ok(r.needPay && r.price === 5000 && r.package === 50 && /Valda the Barbarian, Morag the Druid, Roland the Paladin/.test(r.message), 'Kestrel owner may buy the bundle (Kestrel is not in it)', JSON.stringify(r));
|
||||
ok(!(await pkg('m@x.com', 2000, T0 + 5000)), 'a $20 package does not pay the $50 bundle');
|
||||
ev = await pkg('m@x.com', 5000, T0 + 6000);
|
||||
r = gp.buyHero('k@x.com', T0, 'bundle'); ok(r.needPay && r.price === 5000 && r.package === 50 && /Valda the Barbarian, Morag the Druid, Roland the Paladin/.test(r.message), 'a Kestrel owner may buy the bundle (Kestrel is not in it)', JSON.stringify(r));
|
||||
ok(!(await pkg('k@x.com', 2000, T0 + 5000)), 'a $20 package does not pay the $50 bundle');
|
||||
ev = await pkg('k@x.com', 5000, T0 + 6000);
|
||||
ok(ev && ev.hero === 'bundle' && ev.heroes.join() === 'valda,morag,roland', 'a $50 package fulfils the bundle: all three', JSON.stringify(ev));
|
||||
ok(gp.heroesOwned('m@x.com').owned.join() === 'kestrel,valda,morag,roland' && gp.heroesOwned('m@x.com').bundle, 'four owned, bundle flag set');
|
||||
r = gp.buyHero('m@x.com', T0, 'bundle'); ok(/already have/.test(r.error || ''), 'the bundle twice: refused');
|
||||
ok(gp.heroesOwned('k@x.com').owned.join() === 'kestrel,valda,morag,roland' && gp.heroesOwned('k@x.com').bundle, 'four owned, bundle flag set');
|
||||
r = gp.buyHero('k@x.com', T0, 'bundle'); ok(/already have/.test(r.error || ''), 'the bundle twice: refused');
|
||||
r = gp.buyHero('n@x.com', T0, 'morag'); await pkg('n@x.com', 2000, T0 + 100); r = gp.buyHero('n@x.com', T0 + 200, 'bundle');
|
||||
ok(/already have Morag the Druid, so the bundle is not for you/.test(r.error || ''), 'a member who owns one bundle hero is sent to buy the rest one at a time', JSON.stringify(r));
|
||||
|
||||
@@ -68,22 +80,24 @@ const pkg = (email, cents, at, tx) => gp.onEvent({ type: 'Purchase', priceCents:
|
||||
ok(e1 && e1.hero === 'roland' && e2 && e2.tier === 'weekly' && gp.flag('p@x.com', T0 + 3000).active, 'a $20 package pays the hero, a $5 package the weekly pass', JSON.stringify({ e1, e2 }));
|
||||
|
||||
// 5. settings: price 0 = free for every account; bundle list
|
||||
SC.heroPriceKestrelCents = '0';
|
||||
ok(gp.heroesOwned('nobody@x.com').owned.join() === 'kestrel', 'Kestrel priced 0: owned by every account');
|
||||
r = gp.buyHero('q@x.com', T0, 'kestrel'); ok(/free for everyone/.test(r.error || ''), 'a free hero is never sold');
|
||||
let claim = gp.heroClaim('nobody@x.com'); ok(claim.heroes.join() === 'kestrel' && claim.heroSale.free.join() === 'kestrel' && claim.heroBundle === false && !('heroBundleCap' in claim), 'the hand-off says Kestrel is free (the game opens her for guests too)', JSON.stringify(claim));
|
||||
delete SC.heroPriceKestrelCents; SC.heroBundleHeroes = 'kestrel,valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'kestrel,valda,morag', 'the bundle list is a setting');
|
||||
SC.heroPriceRolandCents = '0';
|
||||
ok(gp.heroesOwned('nobody@x.com').owned.join() === 'roland', 'Roland priced 0: owned by every account');
|
||||
r = gp.buyHero('q@x.com', T0, 'roland'); ok(/free for everyone/.test(r.error || ''), 'a free hero is never sold');
|
||||
let claim = gp.heroClaim('nobody@x.com'); ok(claim.heroes.join() === 'roland' && claim.heroSale.free.join() === 'roland' && claim.heroBundle === false && !('heroBundleCap' in claim), 'the hand-off says Roland is free (the game opens him for guests too)', JSON.stringify(claim));
|
||||
delete SC.heroPriceRolandCents; SC.heroBundleHeroes = 'valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'valda,morag', 'the bundle list is a setting');
|
||||
SC.heroBundleHeroes = 'kestrel,valda,morag';
|
||||
ok(gp.cfg().heroes.bundle.heroes.join() === 'valda,morag', 'a bundle setting naming Kestrel drops her (free at 20, never sold)');
|
||||
delete SC.heroBundleHeroes;
|
||||
|
||||
// 6. the hand-off claim and the bundle cap (unset by default; only for bundle owners once set)
|
||||
claim = gp.heroClaim('m@x.com'); ok(claim.heroes.join() === 'kestrel,valda,morag,roland' && claim.heroBundle === true && !('heroBundleCap' in claim) && claim.heroSale.bundle.join() === 'valda,morag,roland' && claim.heroSale.each === 20 && claim.heroSale.bundlePrice === 50, 'claim: owned heroes, bundle, sale; no cap', JSON.stringify(claim));
|
||||
SC.heroBundleCap = '40'; ok(gp.heroClaim('m@x.com').heroBundleCap === 40 && !('heroBundleCap' in gp.heroClaim('n@x.com')), 'heroBundleCap set: only bundle owners carry it'); delete SC.heroBundleCap;
|
||||
claim = gp.heroClaim('k@x.com'); ok(claim.heroes.join() === 'kestrel,valda,morag,roland' && claim.heroBundle === true && !('heroBundleCap' in claim) && claim.heroSale.bundle.join() === 'valda,morag,roland' && claim.heroSale.each === 20 && claim.heroSale.bundlePrice === 50, 'claim: owned heroes, bundle, sale; no cap', JSON.stringify(claim));
|
||||
SC.heroBundleCap = '40'; ok(gp.heroClaim('k@x.com').heroBundleCap === 40 && !('heroBundleCap' in gp.heroClaim('n@x.com')), 'heroBundleCap set: only bundle owners carry it'); delete SC.heroBundleCap;
|
||||
|
||||
// 7. comp, revoke, stats
|
||||
r = gp.compHero('z@x.com', 'valda', 'admin hero test'); ok(r.ok && gp.heroesOwned('z@x.com').owned.join() === 'valda', 'comp grants a hero');
|
||||
r = gp.revokeHero('z@x.com', 'valda', 'admin hero test'); ok(r.ok && !gp.heroesOwned('z@x.com').owned.length, 'revoke takes it back (support only)');
|
||||
const st = gp.heroStats(); ok(st.sold.kestrel === 1 && st.sold.valda === 2 && st.sold.morag === 3 && st.sold.roland === 3 && st.bundles === 2 && st.usd === 160 && st.comped === 0, 'stats: per hero, bundles, dollars (3 x $20 + 2 x $50 = $160)', JSON.stringify(st));
|
||||
const st = gp.heroStats(); ok(st.sold.kestrel === 1 && st.sold.valda === 2 && st.sold.morag === 3 && st.sold.roland === 4 && st.bundles === 2 && st.usd === 180 && st.comped === 0 && st.waiting === 0, 'stats: per hero, bundles, dollars (4 x $20 incl. the old Kestrel sale + 2 x $50 = $180), no waiting order', JSON.stringify(st));
|
||||
const ps = gp.adminStats(T0 + 3000).passes; ok(ps.soldTotal === 1 && ps.usdTotal === 5, 'pass stats count only the weekly pass (no hero in the pass pool)', JSON.stringify(ps));
|
||||
console.log(fails ? '\n' + fails + ' FAILED' : '\nALL PASSED'); process.exit(fails ? 1 : 0);
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
|
||||
@@ -229,6 +229,10 @@ async function record(p) {
|
||||
if (!out.repeat && out.kind === 'refuel' && X.feed && (!X.marks || await X.marks.claim('rffeed:' + tx))) {
|
||||
try { await X.feed(await feedLine(email, out)); } catch (e) { console.error('refuel feed', e.message); }
|
||||
}
|
||||
// a counted refuel of $50+ (either site) earns a Downline Banners spot, paid by the company (Marty 2026-11-13), once per tx
|
||||
if (!out.repeat && out.kind === 'refuel' && cents >= 5000 && X.refuelSpot && (!X.marks || await X.marks.claim('rfspot:' + tx))) {
|
||||
X.refuelSpot({ email, site, tx, cents }).catch(e => console.error('refuel spot', e.message));
|
||||
}
|
||||
await drainLocal().catch(e => console.error('refuel drain', e.message));
|
||||
if (out.kind && out.kind !== 'none') console.log('refuel:', site, out.kind, 'month', out.month, email.replace(/^(.).*(@.*)$/, '$1***$2'), String(tx).slice(0, 12));
|
||||
return Object.assign({ on: true }, out);
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ function renderPage() {
|
||||
h += '<h2 style="font-size:24px;margin:10px 0 16px">Release notes</h2>';
|
||||
h += v.notes.length ? v.notes.map(n => '<article class="note" id="' + esc(n.id) + '"><h2>' + esc(n.title) + n.tags.map(tagChip).join('') + '</h2><p class="when">' + fmt(n.date) + '</p>' + bodyHtml(n.body) + '</article>').join('') : '<p class="muted">No notes yet.</p>';
|
||||
h += '<p class="muted small" style="margin-top:30px">Suggestions and bug reports: the chat bubble on any page, or the InstantAdPay Telegram group.</p>';
|
||||
h += '</div><script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
h += '</div><script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260914a"></script></body></html>';
|
||||
return h;
|
||||
}
|
||||
module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES };
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// Atomic JSON data files (2026-11-13 incident). Every store here saves with fs.writeFileSync(file.json, ...), which truncates
|
||||
// the file and then writes it. During a deploy the old and new app copies share the volume for a few seconds; the new copy read
|
||||
// rotator.json while the old one was half way through writing it, JSON.parse failed, the store fell back to EMPTY and its next
|
||||
// save wrote that empty list over 294 spin links. This makes every .json write inside DATA_DIR atomic (write a temp file in the
|
||||
// same folder, then rename it over the real one), so a reader only ever sees the old file or the new one, never half of one.
|
||||
// The SAME file ships in InstantAdPay and LinkSpin; server.js installs it right after DATA_DIR is known.
|
||||
'use strict';
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
let installed = false;
|
||||
function install(dataDir) {
|
||||
if (installed) return; installed = true;
|
||||
const root = path.resolve(dataDir) + path.sep;
|
||||
const orig = fs.writeFileSync;
|
||||
fs.writeFileSync = function (file, data, opts) {
|
||||
const flag = opts && typeof opts === 'object' ? opts.flag : null;
|
||||
if (typeof file === 'string' && /\.json$/i.test(file) && (!flag || flag === 'w') && path.resolve(file).startsWith(root)) {
|
||||
const tmp = file + '.tmp-' + process.pid + '-' + Math.random().toString(36).slice(2, 8);
|
||||
try { orig.call(fs, tmp, data, opts); fs.renameSync(tmp, file); }
|
||||
catch (e) { try { fs.unlinkSync(tmp); } catch (x) {} throw e; }
|
||||
return;
|
||||
}
|
||||
return orig.apply(fs, arguments);
|
||||
};
|
||||
}
|
||||
module.exports = { install };
|
||||
@@ -55,12 +55,43 @@ const lssync = require('./lssync');
|
||||
const lsconv = require('./lsconv'); // conversion tracking: ad click ids pushed to LinkSpin + the member's goals (2026-10-23)
|
||||
const lsreport = require('./lsreport'); // conversion linkage: the LinkSpin click on the account, sign-up / wallet / purchase reported, reporting only (2026-11-07)
|
||||
const lsinbound = require('./lsinbound'); // reverse registry sync: LinkSpin-first members arrive as waiting accounts (2026-10-15)
|
||||
const draftpartner = require('./draftpartner'); // 5xYourTeam The Draft: signed pool / adopt / release / status on the network tank (2026-11-15, needs DRAFT_PARTNER_SECRET)
|
||||
const hubsync = require('./hubsync'); // network hub: members from other doors arrive as waiting accounts, ours are reported (2026-11-12, only with HUB_ENABLED)
|
||||
const SF = require('./sponsorfollow'); // deliberate sponsor changes follow to LinkSpin until chain-bound + one network tank (2026-10-22)
|
||||
const bixpay = require('./bixpay'); // BixPay Visa card: partner-link field, sponsor-follows resolver, tracked clicks (2026-10-29, gated by site config bixpayLive)
|
||||
let follow = null, followStore = null;
|
||||
const LS_BASE = () => String(process.env.LS_URL || 'https://linkspin.app').replace(/\/+$/, '');
|
||||
const BL_BASE = () => String(process.env.BL_URL || 'https://new.downlinebanners.com').replace(/\/+$/, ''); // Downline Banners (network sign-in by wallet, 2026-11-13)
|
||||
const BL_BASE = () => String(process.env.BL_URL || 'https://downlinebanners.com').replace(/\/+$/, ''); // Downline Banners (network sign-in by wallet, 2026-11-13)
|
||||
const VBB_BASE = () => String(process.env.VBB_URL || 'https://viralbannerblitz.com').replace(/\/+$/, ''); // Viral Banner Blitz (network sign-in by wallet, 2026-11-14)
|
||||
const VAB_BASE = () => String(process.env.VAB_URL || 'https://viraladblitz.com').replace(/\/+$/, ''); // ViralAdBlitz (network sign-in by wallet, 2026-11-15; VAB_URL = the staging host until the domain switch)
|
||||
const DH_BASE = () => String(process.env.DH_URL || 'https://downlinehydra.com').replace(/\/+$/, ''); // DownlineHydra (network sign-in, 2026-11-15; DH_URL = https://dh.saasy.top until the domain switch)
|
||||
// Refuel spots (Marty 2026-11-13: paid from the company fee share, $50+): refuel.js calls this once per counted $50+ refuel tx
|
||||
// (either site). Downline Banners buys the spot for the member's main wallet from the engine wallet (its refuelspots.js), with
|
||||
// their network sponsor's wallet as sponsor. Signed with NETWORK_SSO_SECRET ('net.v1.' + ts + newline + raw body).
|
||||
async function refuelSpotToBL({ email, site, tx, cents }) {
|
||||
const a = await accounts.byEmail(email).catch(() => null);
|
||||
const mask = String(email).replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
if (!a || !a.address) { console.log('refuel spot: no wallet linked, not sent', mask); return; }
|
||||
const sp = await accounts.sponsorOf(email).catch(() => null);
|
||||
const raw = JSON.stringify({ tx, site, cents, wallet: a.address, sponsorWallet: sp && sp.address ? sp.address : null });
|
||||
const sec = String(process.env.NETWORK_SSO_SECRET || '').trim(); if (sec.length < 32) return;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const ts = String(Date.now()); const sig = crypto.createHmac('sha256', sec).update('net.v1.' + ts + '\n' + raw).digest('hex');
|
||||
try {
|
||||
const r = await fetch(BL_BASE() + '/api/partner/refuel-spot', { method: 'POST', body: raw, signal: AbortSignal.timeout(10000), headers: { 'Content-Type': 'application/json', 'X-Net-Ts': ts, 'X-Net-Sig': sig } });
|
||||
const j = await r.json().catch(() => ({}));
|
||||
if (r.ok) {
|
||||
console.log('refuel spot queued on Downline Banners', mask, String(tx).slice(0, 12), j.repeat ? '(repeat)' : '');
|
||||
if (!j.repeat) await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [a.email], 'Your refuel earned a Downline Banners spot',
|
||||
'<p>Your $' + (cents / 100).toFixed(0) + ' refuel earned you a free spot on <a href="https://downlinebanners.com/my">Downline Banners</a>, the network banner board. It is being placed in the line for your wallet now.</p><p>Open <a href="https://downlinebanners.com/my">My Spots</a> to add your banner and link (or use one of your LinkSpin Banner Spins). Your InstantAdPay sign-in carries you in.</p>', 'notice').catch(() => {});
|
||||
return;
|
||||
}
|
||||
if (r.status === 400 || r.status === 401) { console.error('refuel spot refused', r.status, j.error || '', mask); return; }
|
||||
} catch (e) {}
|
||||
await new Promise(ok => setTimeout(ok, 30000 * (i + 1)));
|
||||
}
|
||||
console.error('refuel spot: Downline Banners did not answer', mask, String(tx).slice(0, 12));
|
||||
}
|
||||
let activationCache = { at: 0, map: null };
|
||||
function activationByAddress() { // MemberActivated events by wallet, for the Sponsor check (when the contract bound the sponsor)
|
||||
if (activationCache.map && Date.now() - activationCache.at < 60000) return activationCache.map;
|
||||
@@ -98,12 +129,15 @@ const videomaker = require('./videomaker'); // Circuit tool: promo videos with
|
||||
const TRAFFIC_PAGES = new Set(['/chasing-unicorns', '/', '/ledger', '/contract', '/shorts', '/plays', '/wallets', '/launch', '/partners', '/earning', '/games', '/blog', '/whats-new', '/leaderboard', '/friday', '/wednesday', '/refuel', '/conversion-tracking', '/presentation', '/support', '/bixpay']);
|
||||
let tankWaitCache = null; // dashboard: who is waiting for a sponsor (refreshed every minute)
|
||||
const geo = require('./geo'); // viewer country -> tier (DB-IP lite), for campaign targeting
|
||||
const netsites = require('./netsites'); // footer network list from the hub (2026-11-14 trust pack)
|
||||
const burner = require('./burner'); // automatic on-chain credit burns (inert without ENGINE_KEY)
|
||||
|
||||
const PORT = Number(process.env.PORT || 3000);
|
||||
const ROOT = __dirname;
|
||||
const PUBLIC_DIR = path.join(ROOT, 'public');
|
||||
const DATA_DIR = process.env.DATA_DIR || path.join(ROOT, 'data');
|
||||
require('./safefs').install(DATA_DIR); // every .json data file is written atomically (2026-11-13 rotator.json loss)
|
||||
const docstore = require('./docstore'); docstore.install(DATA_DIR); // data documents live in MySQL when DOCSTORE_URL is set (2026-11-13, database is the standard)
|
||||
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || 'changeme';
|
||||
const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
|
||||
// Admin portal sessions: email-code sign-in allowlisted to ADMIN_EMAIL, kept
|
||||
@@ -112,7 +146,7 @@ const ADMIN_EMAIL = String(process.env.ADMIN_EMAIL || '').trim().toLowerCase();
|
||||
const ADMIN_SESS_FILE = path.join(DATA_DIR, 'admin-sessions.json');
|
||||
const ADMIN_TTL = 12 * 60 * 60 * 1000;
|
||||
let adminSessions = {};
|
||||
try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; }
|
||||
if (!process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } } // with MySQL: loaded right after docstore.init
|
||||
function saveAdminSessions() {
|
||||
const now = Date.now();
|
||||
for (const k of Object.keys(adminSessions)) if (!adminSessions[k] || adminSessions[k].expires < now) delete adminSessions[k];
|
||||
@@ -537,6 +571,9 @@ async function frameCheck(url, inGame) {
|
||||
}
|
||||
async function boot() {
|
||||
await db.init({ dataDir: DATA_DIR }); // no-op without DATABASE_URL (JSON mode)
|
||||
await docstore.init({}); // before any module reads its data
|
||||
process.on('SIGTERM', () => { docstore.drain(8000).finally(() => process.exit(0)); });
|
||||
if (process.env.DOCSTORE_URL) { try { adminSessions = JSON.parse(fs.readFileSync(ADMIN_SESS_FILE, 'utf8')) || {}; } catch (e) { adminSessions = {}; } }
|
||||
marks.init({ db });
|
||||
marks.ensureTable().catch(e => console.error('marks table', e.message));
|
||||
lsconv.init({ db, dataDir: DATA_DIR });
|
||||
@@ -564,6 +601,7 @@ async function boot() {
|
||||
wednesday.onEvent(ev).catch(e => console.error('wednesday bonus', e.message));
|
||||
refuel.onIapPurchase(ev).catch(e => console.error('refuel streak', e.message)); // its own bonus, stacked on Friday/Wednesday; no-op while refuelStreak is off
|
||||
sponsorSyncOnEvent(ev).catch(e => console.error('sponsor sync', e.message));
|
||||
hubsync.onChain(ev); // network hub: payout switch-on -> contract bind (no-op unless HUB_ENABLED)
|
||||
lsReportPurchase(ev).catch(e => console.error('lsreport purchase', e.message)); // reporting only: one local row, delivered in the background
|
||||
}).catch(e => console.error('marks claim', e.message));
|
||||
} });
|
||||
@@ -572,7 +610,7 @@ async function boot() {
|
||||
// only (the admin portal is never shared); an account that is not here yet, or is still a waiting LinkSpin/BTC4Hits account,
|
||||
// gets the normal email-code sign-in with the email filled in, so every new-account check (anti-fraud, sponsor) runs as before.
|
||||
networksso.init({ self: 'iap', peer: 'linkspin', peerBase: LS_BASE, isProd: IS_PROD, dataDir: DATA_DIR, db, defaultPath: '/my',
|
||||
wallets: { bannerline: BL_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one
|
||||
wallets: { bannerline: BL_BASE, vbb: VBB_BASE, viraladblitz: VAB_BASE, downlinehydra: DH_BASE }, // Downline Banners members are wallets: vouch for the wallet they signed in with, else the account's linked one
|
||||
wallet: async s => { const a = await accounts.byEmail(s.email); const addr = String(s.address || (a && a.address) || '').toLowerCase(); return addr ? { address: addr, name: (a && a.username) || '' } : null; },
|
||||
member: async req => { // a wallet sign-in carries the address, not the email: find the account that owns the wallet (2026-11-13)
|
||||
const s = await auth.fromRequest(req); if (!s) return null;
|
||||
@@ -601,7 +639,7 @@ async function boot() {
|
||||
reports.init({ dataDir: DATA_DIR });
|
||||
drip.init({ dataDir: DATA_DIR, mailer, accounts, chain, site: 'https://instantadpay.com' });
|
||||
chatbot.init({ dataDir: DATA_DIR, chain, bixLive: () => bixpay.live(), gameLive: slug => String(siteConfig().gamesLive == null ? 'polhunter' : siteConfig().gamesLive).split(',').map(x => x.trim().toLowerCase()).includes(slug), refuelOn: () => refuel.cfg().on, passTiers: () => { const c = gamepass.cfg(); return { on: c.enabled && c.tierSales, rows: gamepass.TIER_DEFS.filter(d => d.key !== 'weekly').map(d => ({ name: d.name, perks: d.perks, price: c.tiers[d.key].price, usd: c.tiers[d.key].price / 100, days: c.tiers[d.key].days, sale: c.tiers[d.key].sale })) }; },
|
||||
heroSale: () => { const h = gamepass.cfg().heroes, N = Object.fromEntries(gamepass.HERO_DEFS.map(d => [d.key, d.name])); return { sale: h.sale, rows: gamepass.HERO_DEFS.map(d => ({ name: d.name, usd: h.price[d.key] / 100, free: h.price[d.key] === 0 })), bundle: { names: h.bundle.heroes.map(k => N[k]), usd: h.bundle.price / 100 } }; } }); // pass tiers fact follows sovTiers (2026-10-22); bonus heroes follow heroSales (2026-11-05)
|
||||
heroSale: () => { const h = gamepass.cfg().heroes, N = Object.fromEntries(gamepass.HERO_DEFS.map(d => [d.key, d.name])); return { sale: h.sale, rows: gamepass.HERO_DEFS.map(d => ({ name: d.name, usd: h.price[d.key] / 100, free: h.price[d.key] === 0, freeAt: d.freeAt || null })), bundle: { names: h.bundle.heroes.map(k => N[k]), usd: h.bundle.price / 100 } }; } }); // pass tiers fact follows sovTiers (2026-10-22); bonus heroes follow heroSales (2026-11-05)
|
||||
setTimeout(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 1000);
|
||||
setInterval(() => ads.dailySweep().catch(e => console.error('sweep', e.message)), 60 * 60 * 1000);
|
||||
setInterval(() => ads.scheduleSweep().catch(e => console.error('schedule sweep', e.message)), 5 * 60 * 1000); // scheduled starts/ends
|
||||
@@ -654,6 +692,7 @@ async function boot() {
|
||||
featuredPerDay: () => ads.rates().featuredPerDay || 40,
|
||||
message: async (to, subject, html) => { await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [to], subject, html, 'notice'); },
|
||||
badge: (email, key) => postBadgeOnce(email, key, 'Monthly Refuel'),
|
||||
refuelSpot: refuelSpotToBL, // $50+ counted refuel -> one Downline Banners spot (2026-11-13)
|
||||
feed: async text => { const sc = siteConfig(); if (!sc.telegramBotToken || !sc.telegramEchoChatId) return false; return telegramSend(sc.telegramEchoChatId, '\u{1F7E0} <b>InstantAdPay</b> \u00b7 ' + text, sc.telegramEchoTopicId); } });
|
||||
kit.init({ dataDir: DATA_DIR, program: 'iap', publicDir: PUBLIC_DIR, siteUrl: 'https://instantadpay.com',
|
||||
entitled: async email => { const v = await refuel.view(email); return v && v.on ? { on: true, months: v.kits || {}, nextRefuel: v.refuelDayLabel || null, today: v.today || null } : { on: false }; },
|
||||
@@ -693,7 +732,12 @@ async function boot() {
|
||||
activationOf: a => a.address ? activationByAddress().get(String(a.address).toLowerCase()) || null : null });
|
||||
tank.init({ capOpen: () => siteConfig().tankAdoptCap, dataDir: DATA_DIR, chain, accounts, messages, mailer, ads, site: 'https://instantadpay.com', follow, store: followStore,
|
||||
// activation hold + 24-hour safety net (2026-10-27): a tank member is never bound under the fallback position
|
||||
hooks: { network: (email, address) => lsinbound.networkSponsor(email, address), isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
|
||||
// network hub rule 3 (2026-11-14, only with HUB_ENABLED): the hub's sponsor comes first for alignment, and nobody it reports
|
||||
// locked on a network contract or sponsored is offered, moved to the tank or auto-assigned (hubsync.js: cache + fail-safe)
|
||||
hooks: { network: async (email, address) => (hubsync.enabled() ? await hubsync.hubSponsor(email).catch(() => null) : null) || lsinbound.networkSponsor(email, address),
|
||||
networkHeld: hubsync.enabled() ? accts => hubsync.heldAmong(accts) : null, networkLocked: hubsync.enabled() ? email => hubsync.lockedAnywhere(email) : null,
|
||||
isSuspended: em => fraud.isSuspended(em), excluded: em => fraud.excluded(em),
|
||||
isDraftPick: id => draftpartner.isDraftPick(id), // a 5xYourTeam pick's adoption: draftpartner.js owns its 3-day window
|
||||
payoutBlocked: id => payoutChainBlocked(id, 2), companyId: () => Number(siteConfig().defaultSponsorId) || 1,
|
||||
assigned: r => { tankPickupPost(r.adopterName, r.adopteeName, true); }, adminAlert: text => tankAdminAlert(text),
|
||||
// switch-on-payouts reminders after an assignment (2026-10-27): one send per key across both app copies (deploy overlap),
|
||||
@@ -704,7 +748,12 @@ async function boot() {
|
||||
lssync.init({ dataDir: DATA_DIR, accounts, follow: followStore, tank: () => tank }); accounts.onChange(email => lssync.touch(email));
|
||||
lsinbound.init({ dataDir: DATA_DIR, accounts, lssync, follow, store: followStore });
|
||||
// network hub (hubsync.js): nothing at all happens here unless HUB_ENABLED is on; the LinkSpin sync above runs either way
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
if (hubsync.enabled()) { hubsync.init({ dataDir: DATA_DIR, accounts, lsinbound, follow: followStore, chain }); accounts.onChange(email => { lssync.touch(email); hubsync.touch(email); }); hubsync.start(); }
|
||||
// 5xYourTeam draft picks (draftpartner.js, 2026-11-15): the routes answer 503 until DRAFT_PARTNER_SECRET is set; the pool stays empty
|
||||
// and nobody can be drafted while the hub is off (DRAFT_ALLOW_NO_HUB=1 is for local tests only, refused in production)
|
||||
await draftpartner.init({ dataDir: DATA_DIR, accounts, chain, tank, ads, requireHub: !(process.env.DRAFT_ALLOW_NO_HUB === '1' && process.env.NODE_ENV !== 'production'),
|
||||
hooks: { hubInfo: email => (hubsync.enabled() ? hubsync.hubInfo(email) : null), resolvePerson: q => (hubsync.enabled() ? hubsync.resolvePerson(q) : null), networkOn: () => hubsync.enabled(),
|
||||
excluded: em => fraud.excluded(em), spamEmails: () => (((spamscan.view() || {}).last || {}).candidates || []).map(c => c.email), suggestDomain: d => require('./emailcheck').suggestDomain(d) } }).catch(e => console.error('draftpartner init', e.message));
|
||||
setTimeout(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => lssync.tick().catch(e => console.error('lssync', e.message)), 2 * 60 * 1000);
|
||||
setInterval(() => follow.retryPending().catch(e => console.error('sponsorfollow retry', e.message)), 2 * 60 * 1000); // follows waiting on a chain read or a sponsor account
|
||||
@@ -786,6 +835,7 @@ async function boot() {
|
||||
geo.init({ dataDir: DATA_DIR }).catch(e => console.error('geo init', e.message));
|
||||
setInterval(() => geo.refresh().catch(e => console.error('geo refresh', e.message)), 24 * 3600 * 1000); // monthly file, checked daily
|
||||
setInterval(() => tank.sweep().catch(e => console.error('tank sweep', e.message)), 60 * 60 * 1000); // adoptions past their 7-day window
|
||||
setInterval(() => draftpartner.sweep().then(r => { if (r.done || r.returned || r.kept || r.moved) console.log('draft sweep', JSON.stringify(r)); }).catch(e => console.error('draft sweep', e.message)), 60 * 60 * 1000); // 5xYourTeam picks: 3-day window
|
||||
burner.init({ chain, ads, accounts });
|
||||
setTimeout(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 90 * 1000);
|
||||
setInterval(() => coach.nudgeTick().catch(e => console.error('coach', e.message)), 60 * 60 * 1000);
|
||||
@@ -897,7 +947,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': '
|
||||
'.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp',
|
||||
'.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2',
|
||||
'.gif': 'image/gif', '.webm': 'video/webm', '.vtt': 'text/vtt; charset=utf-8', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' };
|
||||
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com https://linkspin.app; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
|
||||
const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://www.networkadspace.com https://networkadspace.com https://polhunter.com 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://polhunter.com https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com https://linkspin.app https://downlinebanners.com https://viralbannerblitz.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:";
|
||||
function baseHeaders(extra) {
|
||||
return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff',
|
||||
'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {});
|
||||
@@ -1571,12 +1621,13 @@ async function tankNotifyTick() {
|
||||
// the first run of this rule: anyone who joined before it was already announced at sign-up.
|
||||
const graceFrom = st.graceFrom || (st.graceFrom = st.last || Date.now());
|
||||
const fresh = [];
|
||||
for (const w of tank.openedSince(await tank.waiting(), since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
||||
const all = await tank.waiting(); // the running total goes in the post too (Marty 2026-11-14: "post those totals")
|
||||
for (const w of tank.openedSince(all, since)) if ((w.joined || 0) > graceFrom && await marks.claim('tankopen:' + w.email + ':' + (w.joined || 0))) fresh.push(w);
|
||||
st.last = Date.now(); fs.writeFileSync(f, JSON.stringify(st));
|
||||
if (!fresh.length) return;
|
||||
const named = fresh.filter(w => w.username).map(w => '@' + w.username);
|
||||
const who = named.length ? ': ' + named.slice(0, 8).join(', ') + (named.length > 8 ? ' and ' + (named.length - 8) + ' more' : '') : '';
|
||||
const text = '\u{1FAA3} <b>InstantAdPay</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who
|
||||
const text = '\u{1FAA3} <b>InstantAdPay</b> \u00b7 ' + fresh.length + ' new member' + (fresh.length === 1 ? '' : 's') + ' waiting for a sponsor in the holding tank' + who + ' (' + tank.adoptableOf(all).length + ' waiting in total)'
|
||||
+ '\nAdopt from My line \u203a Holding tank: <a href="https://instantadpay.com/my#line">instantadpay.com/my</a>';
|
||||
await telegramSend(sc.telegramEchoChatId, text, sc.telegramEchoTopicId);
|
||||
}
|
||||
@@ -2319,7 +2370,7 @@ const server = http.createServer(async (req, res) => {
|
||||
res.writeHead(302, { Location: to, 'Cache-Control': 'no-store', 'X-Robots-Tag': 'noindex' }); return res.end();
|
||||
} }
|
||||
// network sign-in with LinkSpin (2026-11-12): /go/linkspin, /sso/start, /sso/check, /sso/in, /api/sso/status
|
||||
if (req.method === 'GET' && (p === '/go/linkspin' || p === '/go/bannerline' || p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||
if (req.method === 'GET' && (p === '/go/linkspin' || p === '/go/bannerline' || p === '/go/vbb' || p === '/go/viraladblitz' || p === '/go/downlinehydra' || p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return;
|
||||
// network member lookup for Downline Banners (2026-11-13, Marty: share links use the InstantAdPay username): ?u=<username> -> the
|
||||
// account's linked wallet, ?a=<wallet> -> the username. Public data only (usernames are public join links, wallets are on-chain).
|
||||
if (req.method === 'GET' && p === '/api/network/member') {
|
||||
@@ -2479,6 +2530,7 @@ const server = http.createServer(async (req, res) => {
|
||||
try { for (const b of (await blog.listPublished()).slice(0, 40)) pages.push({ path: '/blog/' + b.slug, title: 'Article: ' + b.title, cover: b.cover || null }); } catch (e) {}
|
||||
return json(res, 200, { pages });
|
||||
}
|
||||
if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res);
|
||||
if (p === '/api/config' && req.method === 'GET') {
|
||||
const c = chain.getConfig();
|
||||
// public copy of the site settings: never anything that looks like a credential
|
||||
@@ -2817,7 +2869,7 @@ const server = http.createServer(async (req, res) => {
|
||||
let memberId = 0;
|
||||
if (r.account.address) { try { memberId = await chain.memberIdByAccount(r.account.address); } catch (err) {} }
|
||||
const token = await auth.mintSession({ email: r.account.email, address: r.account.address, memberId });
|
||||
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', turkeydrop: '/api/my/turkeydrop', warpwares: '/api/my/warpwares', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || null }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
|
||||
return json(res, 200, { ok: true, account: r.account, created: !!r.created, next: ({ clutterhunt: '/api/my/clutterhunt', spellwheel: '/api/my/spellwheel', polybreak: '/api/my/polybreak', polminer: '/api/my/polminer', turkeydrop: '/api/my/turkeydrop', warpwares: '/api/my/warpwares', polywarriors: '/api/my/polywarriors', driprunner: '/api/my/driprunner', passivedrip: '/api/my/passivedrip', gemkingdom: '/api/my/gemkingdom', gkshop: '/gk/shop/resume', spookydoors: '/api/my/spookydoors', sdshop: '/sd/shop/resume' })[parseCookies(req)['iap.return']] || (networksso.pendingBack(req) ? '/sso/resume' : null) }, { 'Set-Cookie': auth.sessionCookie(token) }); // next: Drip Runner sent them here to sign in (2026-09-30)
|
||||
}
|
||||
|
||||
// -- in-game sign-in (2026-10-03): see GAME_AUTH. Mirrors /api/auth/email/start + verify, minus cookies.
|
||||
@@ -3020,7 +3072,7 @@ const server = http.createServer(async (req, res) => {
|
||||
if (tankHold) sponsorBlocked = 'tankHold';
|
||||
else if (!sponsorId && memberId !== _defSpon) { sponsorId = _defSpon; sponsorFallback = true; } // orphan fallback → #1 (never self-sponsor)
|
||||
if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {});
|
||||
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : null, sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||
const out = { signedIn: true, gkShop: !!parseCookies(req)['iap.gkshop'], sdShop: !!parseCookies(req)['iap.sdshop'], pwMint: !!parseCookies(req)['iap.pwmint'], returnTo: ['turkeydrop', 'polhunter', 'driprunner', 'passivedrip', 'gemkingdom', 'gkshop', 'spookydoors', 'sdshop', 'pwmint', 'polybreak', 'polminer', 'warpwares', 'shardsofvalor', 'forum'].includes(parseCookies(req)['iap.return']) ? parseCookies(req)['iap.return'] : (networksso.pendingBack(req) ? 'nsso' : null), sponsorBlocked, sponsorRouted, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null,
|
||||
address: s.address || (acct && acct.address) || null, memberId,
|
||||
username: (acct && acct.username) || null, theme: (acct && acct.theme) || null,
|
||||
inviteAsk: !memberId && acct ? tank.inviteAsk(acct) : null, // the Who invited you card (2026-11-07)
|
||||
@@ -3217,6 +3269,19 @@ const server = http.createServer(async (req, res) => {
|
||||
if (!a) return json(res, 404, { error: 'No member matches "' + q.slice(0, 60) + '".' });
|
||||
return json(res, 200, Object.assign(await adminMember.view(a.email), { pwPasses: pwPasses.get(String(a.email).toLowerCase()) || null })); // mint passes on the card (2026-10-10)
|
||||
}
|
||||
// -- admin: the network hub's member lookup (Marty 2026-11-14, read-only): what the member card leaves out. GET ?email=
|
||||
if (p === '/api/admin/member-extra' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const e = String(u.searchParams.get('email') || '').trim().toLowerCase();
|
||||
const a = e ? await accounts.byEmail(e) : null;
|
||||
if (!a) return json(res, 404, { error: 'no such account' });
|
||||
const r = tank.readyRec(e);
|
||||
return json(res, 200, {
|
||||
optedOut: await drip.isUnsubscribed(e).catch(() => null), updatesOptIn: await updates.optedIn(e).catch(() => null),
|
||||
tank: { inTank: !a.sponsorRef && !a.memberId, ready: r ? { readyAt: r.readyAt || null, holdUntil: r.readyAt ? r.readyAt + tank.READY_MS : null } : null, adoptions: await tank.summaryFor(e).catch(() => null) },
|
||||
fraud: await fraud.get(e).then(f => f && { flags: f.flags || [], suspended: !!f.suspended, suspendedReason: f.suspendedReason || null }).catch(() => null)
|
||||
});
|
||||
}
|
||||
if (p === '/api/admin/member' && req.method === 'PATCH') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
@@ -3654,6 +3719,46 @@ const server = http.createServer(async (req, res) => {
|
||||
return json(res, 200, { ok: true, refuel: rv, facts: rv.on ? await engine.facts({ site: 'iap', adminMember, ads, coach }, email) : null });
|
||||
}
|
||||
// -- network hub hooks (hubsync.js, 2026-11-12): signed with HUB_SECRET (X-Hub-Ts + X-Hub-Sig), 5-minute window. Only with HUB_ENABLED.
|
||||
// -- personal notices (2026-11-13, first use: Marty's go on the Downline Banners wallet nudge to sponsors). Admin only. One
|
||||
// message per member, each with its own text: InstantAdPay inbox (messages.deliver, kind notice) + email through the site
|
||||
// mailer, which skips anyone who unsubscribed and adds the unsubscribe link. Once per member per batch (marks.claim
|
||||
// 'nb:<batch>:<email>'), so a repeated call never mails anyone twice. Runs in the background, 400 ms apart;
|
||||
// GET ?batch= reads the result (notice-batches.json).
|
||||
if (p === '/api/admin/notice-batch' && (req.method === 'POST' || req.method === 'GET')) {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'Admin only.' });
|
||||
const NB = path.join(DATA_DIR, 'notice-batches.json');
|
||||
const readNB = () => { try { return JSON.parse(fs.readFileSync(NB, 'utf8')); } catch (e) { return {}; } };
|
||||
if (req.method === 'GET') return json(res, 200, readNB()[String(u.searchParams.get('batch') || '')] || { error: 'No such batch.' });
|
||||
const b = await readBody(req); // { batch, subject, html, text, items: [{ email, vars: { key: value } }] }, {{key}} filled per member
|
||||
const batch = String(b.batch || '').replace(/[^a-z0-9-]/gi, '').slice(0, 60); const subjectT = String(b.subject || '').slice(0, 160);
|
||||
const items = Array.isArray(b.items) ? b.items.slice(0, 5000) : [];
|
||||
const fill = (t, v, html) => String(t || '').replace(/\{\{(\w+)\}\}/g, (m, k) => { const x = v && v[k] != null ? String(v[k]) : ''; return html ? x.replace(/[&<>"]/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c])) : x; });
|
||||
const subject = subjectT;
|
||||
if (!batch || !subject || !items.length) return json(res, 400, { error: 'batch, subject and items required' });
|
||||
const all = readNB(); if (all[batch] && all[batch].running) return json(res, 409, { error: 'That batch is already running.' });
|
||||
all[batch] = { subject, total: items.length, sent: 0, inbox: 0, optedOut: 0, noAccount: 0, repeat: 0, failed: 0, running: true, started: Date.now() };
|
||||
fs.writeFileSync(NB, JSON.stringify(all));
|
||||
json(res, 200, { ok: true, batch, total: items.length });
|
||||
(async () => {
|
||||
const st = all[batch];
|
||||
for (const it of items) {
|
||||
const e = String(it.email || '').trim().toLowerCase();
|
||||
try {
|
||||
const acct = await accounts.byEmail(e); if (!acct) { st.noAccount++; continue; }
|
||||
if (!(await marks.claim('nb:' + batch + ':' + e))) { st.repeat++; continue; }
|
||||
const subj = fill(subjectT, it.vars, false), html = fill(b.html, it.vars, true), text = fill(b.text, it.vars, false);
|
||||
await messages.deliver(1, ADMIN_EMAIL || 'house@instantadpay.com', [e], subj, html, 'notice'); st.inbox++;
|
||||
const ok = await mailer.send(e, subj, text, html);
|
||||
if (ok === false) st.optedOut++; else st.sent++;
|
||||
} catch (err) { st.failed++; console.error('notice-batch', batch, err.message); }
|
||||
const cur = readNB(); cur[batch] = st; fs.writeFileSync(NB, JSON.stringify(cur));
|
||||
await new Promise(r => setTimeout(r, 400));
|
||||
}
|
||||
st.running = false; st.finished = Date.now(); const cur = readNB(); cur[batch] = st; fs.writeFileSync(NB, JSON.stringify(cur));
|
||||
console.log('notice-batch', batch, JSON.stringify(st));
|
||||
})().catch(err => console.error('notice-batch', err.message));
|
||||
return;
|
||||
}
|
||||
if (p === '/api/hub/events' && req.method === 'POST' && hubsync.enabled()) {
|
||||
let raw; try { raw = (await readRaw(req, 2e6)).toString('utf8'); } catch (e) { return json(res, 413, { error: 'too big' }); }
|
||||
const r = await hubsync.receive(req.headers, raw); return json(res, r.status, r.body);
|
||||
@@ -3729,10 +3834,34 @@ const server = http.createServer(async (req, res) => {
|
||||
}
|
||||
if (p === '/api/admin/lssync/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); const b = await readBody(req); return json(res, 200, await lssync.tick(!!(b && b.force))); }
|
||||
if (p === '/api/admin/walletnudge/run' && req.method === 'POST') { if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); return json(res, 200, await walletnudge.tick()); }
|
||||
// -- 5xYourTeam The Draft (draftpartner.js, 2026-11-15): signed partner calls, DRAFT_PARTNER_SECRET as X-Draft-Ts + X-Draft-Sig
|
||||
if (p.startsWith('/api/partner/draft/') && req.method === 'POST') {
|
||||
const raw = await new Promise((ok, no) => { let d = ''; req.on('data', c => { d += c; if (d.length > 64000) { req.destroy(); no(new Error('too big')); } }); req.on('end', () => ok(d)); req.on('error', no); });
|
||||
const sg = draftpartner.verify(req.headers, raw); if (!sg.body) return json(res, sg.status, { error: sg.error });
|
||||
const op = p.slice('/api/partner/draft/'.length);
|
||||
if (!['pool', 'adopt', 'release', 'status'].includes(op)) return json(res, 404, { error: 'unknown op' });
|
||||
const r = await draftpartner.handle(op, sg.body);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
if (p === '/api/admin/draft' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await draftpartner.adminView());
|
||||
}
|
||||
if (p === '/api/admin/tank' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
return json(res, 200, await tank.adminView());
|
||||
}
|
||||
// an adoption made for a member (Marty 2026-11-14: sponsors who lost people when the contract sponsor won get a few from the
|
||||
// tank). The same tank.adopt as the member's own button: their eligibility and cap, the adoptee's email and chat. No payments-topic
|
||||
// post per pickup (a batch would flood it).
|
||||
if (p === '/api/admin/tank/adopt' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
if (!b.adopter || !b.who) return json(res, 400, { error: 'adopter and who' });
|
||||
if (fraud.excluded(b.adopter)) return json(res, 403, { error: 'Adoptions are not available on that account.' });
|
||||
const r = await tank.adopt(String(b.adopter).toLowerCase(), b.who, b.note);
|
||||
return json(res, r.error ? 400 : 200, r);
|
||||
}
|
||||
// -- admin Traffic tab: page views + join-page views + signups + $20 buyers, by referring
|
||||
// domain / first-touch source, by landing page, by angle and by day (Marty, 2026-09-12)
|
||||
// login-ad showings per Central day, dashboard vs games (2026-10-18: a week of combined sign-ins before the cap decision)
|
||||
@@ -6193,7 +6322,7 @@ const server = http.createServer(async (req, res) => {
|
||||
+ '<style>.bp{max-width:560px;text-align:center;padding:40px 16px 60px}.bp img{width:100%;max-width:520px;border-radius:18px;border:1px solid var(--line);box-shadow:0 20px 60px rgba(0,0,0,.45)}.bp h1{font-size:clamp(24px,5vw,34px);margin:22px 0 8px}.bp p{color:var(--muted);max-width:44ch;margin:0 auto 20px}</style></head>'
|
||||
+ '<body><div class="wrap bp"><img src="' + img + '" alt="' + esc(label) + ' badge for @' + esc(un) + '"><h1>@' + esc(un) + ' unlocked <em>' + label + '</em></h1><p>' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On InstantAdPay every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.</p>'
|
||||
+ '<a class="btn" href="/join/' + esc(un) + '">Join @' + esc(un) + '\u2019s line free</a><p class="small" style="margin-top:26px">Advertising with a performance referral program. Not an investment; no income is guaranteed.</p></div>'
|
||||
+ '<script src="/assets/common.js?v=20261113nl"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||
+ '<script src="/assets/common.js?v=20261114ns"></script><script src="/assets/blog-page.js?v=20260921a"></script></body></html>';
|
||||
res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' }));
|
||||
return res.end(html);
|
||||
}
|
||||
|
||||
@@ -86,14 +86,35 @@ const countAll = async email => (await impl().countFor(email)) + remoteCount(ema
|
||||
const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2');
|
||||
const nameOf = a => a.username ? '@' + a.username : (a.memberId ? 'member #' + a.memberId : mask(a.email));
|
||||
const inTank = a => !a.sponsorRef && !a.memberId; // arrived with no sponsor (or fell back), still free
|
||||
// Rule 3 (Marty 2026-11-14): never offer anyone locked on ANY network contract or whom the network hub already knows a sponsor
|
||||
// for (hooks.networkHeld = hubsync.heldAmong, wired only with HUB_ENABLED). A hook that throws holds everyone it was asked
|
||||
// about: the conservative side. No hook (flag off, tests) = nothing held, the tank as before.
|
||||
const lc = v => String(v || '').trim().toLowerCase();
|
||||
async function heldSet(accts) {
|
||||
if (!hooks.networkHeld || !accts.length) return new Map();
|
||||
try { return (await hooks.networkHeld(accts)) || new Map(); } catch (e) { console.error('tank networkHeld', e.message); return new Map(accts.map(a => [lc(a.email), 'unknown'])); }
|
||||
}
|
||||
// release / rescue / expiry: 'locked' | 'unknown' | null (hooks.networkLocked = hubsync.lockedAnywhere)
|
||||
const HELD_WHY = { locked: 'they are locked on a network contract', sponsored: 'it already knows a sponsor for them', unknown: 'nothing (it is not answering)' };
|
||||
async function lockedWhy(email) {
|
||||
if (!hooks.networkLocked) return null;
|
||||
try { return (await hooks.networkLocked(email)) || null; } catch (e) { return 'unknown'; }
|
||||
}
|
||||
|
||||
// waiting list: newest sign-in first so a live one is easy to spot
|
||||
async function waiting() {
|
||||
const all = await accounts.listAll(5000);
|
||||
const rows = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
||||
// one network tank (Marty 2026-11-14: the InstantAdPay and LinkSpin tanks should show the same people): waiting accounts that
|
||||
// never signed in here (BTC4Hits and LinkSpin arrivals) count too, as on LinkSpin; quiet accounts the hub made (joinedVia
|
||||
// 'hub') count too since 2026-11-14 (Marty: the unsponsored old VBB / Downline Banners members go into the holding tank; adopting
|
||||
// one sends the normal adoption email). Rule 3 still keeps out anyone the hub reports locked or sponsored. The weekly email
|
||||
// only counts the tank, it never mails it.
|
||||
const all = await accounts.listAll(1e6, { shells: true });
|
||||
const cand = all.filter(a => inTank(a) && !remoteOpen(a.email)); // one network tank: someone adopted on LinkSpin is not waiting here
|
||||
const held = await heldSet(cand); const rows = cand.filter(a => !held.has(lc(a.email))); // rule 3: locked or sponsored elsewhere
|
||||
// what each of them has earned by surfing on their own, no sponsor (Marty, 2026-09-29), so an adopter can spot the workers
|
||||
const tot = ads && ads.earnedTotals ? await ads.earnedTotals(rows.map(a => a.email)) : {};
|
||||
return rows.map(a => ({ email: a.email, name: nameOf(a), username: a.username || null, joined: a.created, lastSeen: a.lastSeen || 0,
|
||||
via: a.joinedVia || null, // the door they came in by (the 5xYourTeam draft card shows it)
|
||||
wallet: !!a.address, activated: !!a.memberId, // in the tank "activated" is always false (payouts on = out of the tank); wallet can still be linked
|
||||
earned: (tot[a.email] || {}).earned || 0, balance: (tot[a.email] || {}).balance || 0,
|
||||
// wallet linked = ready to switch on payouts, held for an adopter (24-hour clock, autoAssign after that)
|
||||
@@ -119,6 +140,25 @@ async function eligibility(email) {
|
||||
return { ok: true, account: a, open };
|
||||
}
|
||||
|
||||
// 5xYourTeam coaches (Marty 2026-11-15: "not a fan of people adopting if they have nothing vested"; a $10 5x position qualifies,
|
||||
// no IAP $20 package needed). draftpartner.js has already checked the signed claim from 5xYourTeam (p.positions); this is the
|
||||
// InstantAdPay side of the same gate: a real account here with a wallet linked, not suspended or flagged, someone on THIS
|
||||
// contract in their line (them or an upline with payouts on, else a pick who starts here would be walked up to the company, the
|
||||
// one thing the tank exists to stop; the nameSponsor rule), and room under the same people-held-at-once cap as every adopter.
|
||||
async function partnerEligibility(email, p) {
|
||||
const a = await accounts.byEmail(email);
|
||||
if (!a) return { ok: false, code: 'coach_unknown', reason: 'This coach has no InstantAdPay account yet. Sign in on InstantAdPay once (network sign-in) and link the same wallet.' };
|
||||
if (!(Number(p && p.positions) >= 1)) return { ok: false, code: 'not_vested', reason: 'Only 5xYourTeam position holders can draft and coach.' };
|
||||
if (!a.address) return { ok: false, code: 'no_wallet', reason: 'Link a wallet on InstantAdPay first. A coach needs a linked wallet.' };
|
||||
const bar = hooks.excluded || hooks.isSuspended; if (bar && bar(a.email)) return { ok: false, code: 'excluded', reason: 'Adoptions are not available on this account.' };
|
||||
const payee = await firstOnContract(a);
|
||||
if (!payee) return { ok: false, code: 'no_contract_line', reason: 'Neither you nor anyone above you has switched on payouts on InstantAdPay, so a pick who starts there would land under the company. Switch on payouts on InstantAdPay first (one free transaction).' };
|
||||
if (hooks.payoutBlocked && await Promise.resolve(hooks.payoutBlocked(Number(payee.memberId))).catch(() => true)) return { ok: false, code: 'payout_blocked', reason: 'Your line cannot take new members right now.' };
|
||||
const open = await impl().open(a.email); const held = await holding(open); const cap = Math.min(capOpen(), Number(p.maxOpen) > 0 ? Number(p.maxOpen) : capOpen());
|
||||
if (held.length >= cap) return { ok: false, code: 'full', reason: 'You are already helping ' + held.length + ' people from the holding tank, and ' + cap + ' at one time is the most anyone can hold.', full: true, cap, held: held.length };
|
||||
return { ok: true, account: a, open };
|
||||
}
|
||||
|
||||
async function view(email) {
|
||||
const e = String(email || '').toLowerCase();
|
||||
const el = await eligibility(e);
|
||||
@@ -132,27 +172,36 @@ async function view(email) {
|
||||
|
||||
async function adopt(adopterEmail, who, note, opts) {
|
||||
const auto = !!(opts && opts.auto); // the 24-hour safety net (autoAssign): same path, a different record note, both sides emailed
|
||||
// partner = a 5xYourTeam draft pick (draftpartner.js, 2026-11-15): the coach qualifies by a 5x position instead of the $20 buy,
|
||||
// the window is the pick's (3 days, partner.ttlMs), the hub is asked fresh that nobody locked is taken, no reminder mails
|
||||
const partner = (opts && opts.partner) || null;
|
||||
const e = String(adopterEmail || '').toLowerCase();
|
||||
const el = await eligibility(e);
|
||||
if (!el.ok) return { error: el.reason };
|
||||
const el = partner ? await partnerEligibility(e, partner) : await eligibility(e);
|
||||
if (!el.ok) return { error: el.reason, code: el.code || 'not_eligible' };
|
||||
const me = el.account;
|
||||
const key = String(who || '').trim().toLowerCase().replace(/^@/, '');
|
||||
const list = await waiting();
|
||||
const target = list.find(w => (w.username && w.username.toLowerCase() === key) || w.email === key);
|
||||
if (!target) return { error: 'That member is no longer in the tank.' };
|
||||
if (target.email === e) return { error: 'That is you.' };
|
||||
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
|
||||
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.' };
|
||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.' }; // the safety net never leaves anyone to the company
|
||||
if (!target) return { error: 'That member is no longer in the tank.', code: 'gone' };
|
||||
if (target.email === e) return { error: 'That is you.', code: 'self' };
|
||||
if (!auto && target.opensAt > clock()) return { error: 'That member joined less than 24 hours ago, so they still have time to tell us who invited them. You can adopt them in ' + leftText(target.opensAt - clock()) + '.', code: 'grace' }; // the safety net is not held by this: it keeps its 24-hour clock from the wallet link
|
||||
if (remoteOpen(target.email)) return { error: 'That member was just picked up on ' + OTHER + ', so they are no longer in the tank.', code: 'linkspin' };
|
||||
if (!auto && await countAll(target.email) >= MAX_ADOPTIONS) return { error: 'That member has been adopted twice already and stays where they are.', code: 'adopted_twice' }; // the safety net never leaves anyone to the company
|
||||
if (partner) { // never anyone locked on a network contract: asked fresh, a hub that does not answer refuses (the conservative side)
|
||||
const lk = await lockedWhy(target.email);
|
||||
if (lk) return { error: lk === 'locked' ? 'That member is locked to a sponsor on a network contract.' : 'The network record cannot be checked right now. Try again in a few minutes.', code: lk === 'locked' ? 'locked' : 'hub_unknown' };
|
||||
if (await inDownlineOf(target.email, me)) return { error: 'That member is above you in your own line.', code: 'loop' };
|
||||
}
|
||||
const token = me.username || me.code || String(me.memberId);
|
||||
const r = await setSponsor(target.email, token, 'adopt');
|
||||
if (r.error) return r;
|
||||
const now = Date.now();
|
||||
const tgt0 = await accounts.byEmail(target.email); const b4h = !!(tgt0 && (tgt0.joinedVia === 'btc4hits' || tgt0.joinedRef === 'btc4hits')); // a BTC4Hits import (2026-11-11)
|
||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + '. ' + (b4h ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so I picked you up from the holding tank. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + TTL_MS, status: 'open', note: (opts && opts.recordNote) || text });
|
||||
const text = String(note || '').trim().slice(0, 600) || ('Hi, I am ' + nameOf(me) + (partner ? ', your coach from 5xYourTeam' : '') + '. ' + (b4h ? 'Your BTC4Hits account moved to InstantAdPay' : 'You joined InstantAdPay') + ' without a sponsor, so I picked you up from the holding tank' + (partner ? ' in The Draft' : '') + '. I will walk you through the first three steps whenever you are ready. Reply here.');
|
||||
const ttl = partner && Number(partner.ttlMs) > 0 ? Number(partner.ttlMs) : TTL_MS;
|
||||
const ad = await impl().add({ adoptee: target.email, adopter: e, ts: now, expires: now + ttl, status: 'open', note: (opts && opts.recordNote) || text });
|
||||
{ const rr = RS.load().ready[target.email]; if (rr && !rr.done) { rr.done = now; rr.adoptedBy = e; RS.save(); } } // the hold lifts: their sponsor resolves now
|
||||
payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick)
|
||||
if (!partner) payTrack(target.email, e, ad.id, auto); // switch-on-payouts reminders at 24 h and 72 h (payTick); a draft pick gets the adoption email only (Marty 2026-11-15)
|
||||
const link = activateLink();
|
||||
try { await messages.sendChat(me.memberId || 0, e, target.email, text + '\n\n' + chatPayLine(link)); } catch (err) {}
|
||||
if (mailer && mailer.hasKey()) {
|
||||
@@ -167,7 +216,7 @@ async function adopt(adopterEmail, who, note, opts) {
|
||||
} catch (err) {}
|
||||
}
|
||||
}
|
||||
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name };
|
||||
return { ok: true, auto, adoption: ad, name: target.name, adopterName: nameOf(me), adopteeName: target.name, adoptee: target.email };
|
||||
}
|
||||
|
||||
// pay it forward: give one of your own free referrals to the tank
|
||||
@@ -178,6 +227,8 @@ async function release(ownerEmail, directEmail) {
|
||||
const toks = [owner.code, owner.username, owner.memberId ? String(owner.memberId) : null].filter(Boolean).map(String);
|
||||
if (!toks.includes(String(direct.sponsorRef || ''))) return { error: 'That member is not in your line.' };
|
||||
if (direct.memberId) return { error: 'That member has already bought; on-chain sponsorship cannot move.' };
|
||||
const lk = await lockedWhy(d); // rule 3: someone a network contract holds never goes to the tank
|
||||
if (lk) return { error: lk === 'locked' ? nameOf(direct) + ' is locked to a sponsor on a network contract, so they cannot go to the holding tank.' : 'The network record for ' + nameOf(direct) + ' cannot be checked right now. Try again in a few minutes.' };
|
||||
// picked up from the tank recently? then it is not theirs to drop yet (Bradley churned three in 80 seconds, 2026-09-13)
|
||||
const openAds = (await impl().open(null)).filter(ad => ad.adoptee === d);
|
||||
let young = openAds.find(ad => Date.now() - ad.ts < HOLD_MS);
|
||||
@@ -204,10 +255,14 @@ async function sweep() {
|
||||
let done = 0, back = 0, kept = 0;
|
||||
for (const ad of await impl().open(null)) {
|
||||
if (ad.expires > now) continue;
|
||||
if (hooks.isDraftPick && await Promise.resolve(hooks.isDraftPick(ad.id)).catch(() => true)) continue; // a 5xYourTeam pick: draftpartner.js owns its 3-day window (started = payouts on, not a wallet)
|
||||
const a = await accounts.byEmail(ad.adoptee);
|
||||
if (!a) { await impl().setStatus(ad.id, 'expired'); continue; }
|
||||
if (a.address || a.memberId) { await impl().setStatus(ad.id, 'done'); done++; continue; }
|
||||
if (await impl().countFor(ad.adoptee) >= MAX_ADOPTIONS) { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||
const lk = await lockedWhy(ad.adoptee); // rule 3: a person a network contract holds stays with the adopter, never back in the tank
|
||||
if (lk === 'unknown') continue; // the hub is not answering: try again next hour
|
||||
if (lk === 'locked') { await impl().setStatus(ad.id, 'expired'); kept++; continue; }
|
||||
await setSponsor(ad.adoptee, '', 'expire', 'adoption window ended');
|
||||
await impl().setStatus(ad.id, 'expired'); back++;
|
||||
}
|
||||
@@ -272,11 +327,14 @@ async function markContacted(sponsorEmail, leadEmail) {
|
||||
async function rescueSweep() {
|
||||
const now = Date.now();
|
||||
let warned = 0, rescued = 0, dead = 0;
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
const all = await accounts.listAll(5000);
|
||||
await heldSet(all.filter(a => !a.memberId && !a.address && a.sponsorRef)); // one batched hub call warms the cache for lockedWhy below
|
||||
for (const a of all) {
|
||||
if (a.memberId || a.address || !a.sponsorRef) continue; // bound, wallet, or already in the tank
|
||||
if (await impl().hasRecord(a.email)) continue; // adopted / rescued before: the tank's window rules
|
||||
const pv = store && store.get(a.email);
|
||||
if (remoteCount(a.email) || (pv && pv.by !== 'admin')) continue; // adopted / released / rescued on LinkSpin: the tank's window rules there
|
||||
if (await lockedWhy(a.email)) continue; // rule 3: locked on a network contract (or the hub is not answering): no warning, no move
|
||||
const sp = await sponsorOf(a);
|
||||
if (!sp) { // dead sponsor link: nobody can ever coach them, straight to the tank after a day
|
||||
if (now - (a.created || 0) < 86400000) continue;
|
||||
@@ -385,7 +443,7 @@ async function previousSponsors(email) {
|
||||
async function alignToNetwork(a) {
|
||||
if (!a || !inTank(a) || !hooks.network) return null;
|
||||
const e = String(a.email || '').toLowerCase(); if (!e) return null;
|
||||
const n = hooks.network(e, a.address || null); if (!n || !n.sponsorEmail) return null;
|
||||
const n = await Promise.resolve(hooks.network(e, a.address || null)).catch(() => null); if (!n || !n.sponsorEmail) return null; // the hub's answer is async
|
||||
const spEmail = String(n.sponsorEmail).toLowerCase(); if (spEmail === e) return null;
|
||||
if ((await previousSponsors(e)).has(spEmail)) return null; // never back to someone they were released or rescued from
|
||||
const sp = await accounts.byEmail(spEmail);
|
||||
@@ -396,7 +454,7 @@ async function alignToNetwork(a) {
|
||||
for (let i = 0; cur && i < 60; i++) { if (cur.email === e || seen.has(cur.email)) return null; seen.add(cur.email); cur = await accounts.sponsorOf(cur.email); }
|
||||
const fresh = await accounts.byEmail(e); if (!fresh || !inTank(fresh)) return null;
|
||||
const r = await accounts.setSponsorRef(e, token); if (r && r.error) return null;
|
||||
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + ' from LinkSpin (' + (n.via || 'email') + ')';
|
||||
const st = RS.load(); const why = 'aligned to network sponsor ' + nameOf(sp) + (/hub/.test(n.via || '') ? ' (' + n.via + ')' : ' from LinkSpin (' + (n.via || 'email') + ')');
|
||||
st.aligned.push({ email: e, to: sp.email, toName: nameOf(sp), via: n.via || 'email', at: clock(), why });
|
||||
if (st.aligned.length > 300) st.aligned = st.aligned.slice(-300);
|
||||
if (st.ready[e] && !st.ready[e].done) { st.ready[e].done = clock(); st.ready[e].aligned = sp.email; }
|
||||
@@ -447,8 +505,14 @@ async function autoAssignRun() {
|
||||
due.push([e, rec, a]);
|
||||
}
|
||||
due.sort((x, y) => x[1].readyAt - y[1].readyAt);
|
||||
const netHeld = await heldSet(due.map(x => x[2]));
|
||||
let pool = null;
|
||||
for (const [e, rec, a] of due) {
|
||||
if (netHeld.has(e)) { // rule 3: never auto-assigned; the admin hears once (their network sponsor has no usable account here yet, or the hub is not answering)
|
||||
out.held++;
|
||||
if (!rec.networkHeldAlerted) { rec.networkHeldAlerted = clock(); RS.save(); if (hooks.adminAlert) { try { await hooks.adminAlert(BRAND + ' holding tank: ' + nameOf(a) + ' (' + e + ') is held and NOT auto-assigned: the network hub says ' + (HELD_WHY[netHeld.get(e)] || netHeld.get(e)) + ', and that sponsor could not be used here. Set their sponsor in Admin if it should be someone here.'); } catch (err) {} } }
|
||||
continue;
|
||||
}
|
||||
if (!pool) pool = await rotation(e);
|
||||
let done = null;
|
||||
for (const c of pool) {
|
||||
@@ -481,10 +545,12 @@ async function autoAssignRun() {
|
||||
// run the safety net. `fresh` = members who became ready and were not announced yet (server.js posts them).
|
||||
async function readyTick() {
|
||||
const st = RS.load(); const fresh = []; let aligned = 0;
|
||||
for (const a of await accounts.listAll(5000)) {
|
||||
if (!inTank(a)) continue;
|
||||
const tankers = (await accounts.listAll(5000)).filter(inTank);
|
||||
const netHeld = await heldSet(tankers); // one batched hub call; alignToNetwork below reads the same cache
|
||||
for (const a of tankers) {
|
||||
if (await alignToNetwork(a).catch(() => null)) { aligned++; continue; }
|
||||
if (remoteOpen(a.email)) continue;
|
||||
if (netHeld.has(lc(a.email))) continue; // rule 3: not announced, no 24-hour clock while the network holds them
|
||||
const rec = markReady(a);
|
||||
// linkedNow: the member was on the site when they became ready, so they linked the wallet just now; otherwise the
|
||||
// wallet predates this tank visit (e.g. a dormant member returned by a sponsor; Marty 2026-10-29: the notice read as a
|
||||
@@ -641,6 +707,10 @@ async function nameSponsor(email, who, opts) {
|
||||
return { ok: true, name: nameOf(sp), sponsorEmail: sp.email, member: name };
|
||||
}
|
||||
|
||||
// the open adoptions of one person (draftpartner.js checks a pick's adoption is still the open one), and closing one
|
||||
async function openOf(email) { const e = String(email || '').toLowerCase(); return (await impl().open(null)).filter(ad => ad.adoptee === e); }
|
||||
async function closeAdoption(id, status) { await impl().setStatus(id, status); }
|
||||
|
||||
async function adminView() {
|
||||
const recent = await impl().recent(200);
|
||||
const names = {};
|
||||
@@ -648,4 +718,5 @@ async function adminView() {
|
||||
return { waiting: await waiting(), adoptions: recent.map(ad => Object.assign({}, ad, { adopteeName: names[ad.adoptee], adopterName: names[ad.adopter] })), cap: capOpen(), ttlDays: TTL_MS / 86400000, holdHours: READY_MS / 3600000, aligned: alignedRecent(30), payReminders: payView() };
|
||||
}
|
||||
|
||||
module.exports = { init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||
module.exports = { partnerEligibility, openOf, closeAdoption, countAll, remoteCount: email => remoteCount(String(email || '').toLowerCase()), lockedWhy, inTank, setSponsorDeliberate: (email, token, by, note) => setSponsor(email, token, by, note), HOLD_MS, NOT_COUNTED,
|
||||
init, view, adopt, holdFor, markReady, readyRec, readyTick, autoAssign, payTick, payView, activateLink, PAY_R1_MS, PAY_R2_MS, alignToNetwork, alignedRecent, setClock, eligibility, READY_MS, release, sweep, rescueSweep, rescueInfo, markContacted, adminView, waiting, adoptable, adoptableOf, openedSince, leftText, inviteAsk, dismissInvite, nameSponsor, GRACE_MS, hasOwnBuy, recordGift, onFollow, summaryMap, summaryFor, historyMap, capOpen, TTL_MS, WARN_DAYS, RESCUE_DAYS, MAX_ADOPTIONS };
|
||||
|
||||
Reference in New Issue
Block a user