Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c06c58daf | |||
| e1bee03b95 | |||
| e17d8c4fbb | |||
| 7f57aedcb6 | |||
| 968e60835f | |||
| 911dd623c0 | |||
| 4ccdb914c7 | |||
| 82eab8016b | |||
| 4787390e8b | |||
| d033cc7122 | |||
| efb054d916 | |||
| 32f001aade | |||
| edc484db27 |
@@ -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>';
|
||||
|
||||
+12
-6
@@ -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.' },
|
||||
@@ -132,7 +132,13 @@ const CANNED = [
|
||||
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.' },
|
||||
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.' },
|
||||
@@ -284,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() {
|
||||
@@ -364,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.
|
||||
|
||||
+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; } };
|
||||
+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;
|
||||
}
|
||||
|
||||
|
||||
+11
-5
@@ -26,7 +26,7 @@
|
||||
// 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, expiry, admin) goes to /v1/sponsor-change;
|
||||
// - 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
|
||||
@@ -41,7 +41,7 @@ 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']);
|
||||
const DELIBERATE = new Set(['adopt', 'rescue', 'release', 'expiry', 'admin']); // sponsorfollow.js kinds the hub accepts // came here from another site: that site tells the hub itself
|
||||
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();
|
||||
@@ -226,6 +226,10 @@ 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') {
|
||||
@@ -240,7 +244,7 @@ async function bodyFor(item) {
|
||||
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: rec.by };
|
||||
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);
|
||||
@@ -311,7 +315,7 @@ async function refreshHeld(emails, timeout) {
|
||||
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 }, timeout || 5000);
|
||||
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 });
|
||||
@@ -348,9 +352,11 @@ async function hubSponsor(email) {
|
||||
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, 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, onChain, flush, reconcile, start, adminView, heldAmong, lockedAnywhere, hubSponsor, _sign: sign, _heldReset: () => { held.clear(); heldDownUntil = 0; }, _heldAge: ms => { for (const c of held.values()) c.at -= ms; } };
|
||||
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 };
|
||||
|
||||
+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', vbb: 'Viral Banner Blitz' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14)
|
||||
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);
|
||||
@@ -269,6 +269,21 @@ const IAP_DATA = fs.mkdtempSync(path.join(os.tmpdir(), 'hubsync-iap-'));
|
||||
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') });
|
||||
|
||||
@@ -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); });
|
||||
|
||||
+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 };
|
||||
|
||||
@@ -55,6 +55,7 @@ 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)
|
||||
@@ -62,6 +63,8 @@ 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://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).
|
||||
@@ -126,6 +129,7 @@ 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);
|
||||
@@ -606,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, vbb: VBB_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;
|
||||
@@ -635,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
|
||||
@@ -733,6 +737,7 @@ async function boot() {
|
||||
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),
|
||||
@@ -744,6 +749,11 @@ async function boot() {
|
||||
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, 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
|
||||
@@ -825,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);
|
||||
@@ -936,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 || {});
|
||||
@@ -2359,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 === '/go/vbb' || 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') {
|
||||
@@ -2519,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
|
||||
@@ -2857,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.
|
||||
@@ -3060,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)
|
||||
@@ -3257,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);
|
||||
@@ -3809,6 +3834,19 @@ 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());
|
||||
@@ -6284,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);
|
||||
}
|
||||
|
||||
@@ -103,12 +103,18 @@ async function lockedWhy(email) {
|
||||
|
||||
// waiting list: newest sign-in first so a live one is easy to spot
|
||||
async function waiting() {
|
||||
const all = await accounts.listAll(5000);
|
||||
// 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)
|
||||
@@ -134,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);
|
||||
@@ -147,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()) {
|
||||
@@ -182,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
|
||||
@@ -221,6 +255,7 @@ 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; }
|
||||
@@ -672,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 = {};
|
||||
@@ -679,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