commit f26ac1571203a14c672e5e273a95532239cc84e0 Author: martbost Date: Sun Nov 15 06:16:10 2026 -0600 5xYourTeam The Draft v1 (phase 1, local only): weekly earned-order draft of holding-tank people, picks as adoptions (stub tank), coaching tools, cards, boards, trust pack $10 one-time DraftPosition purchases (sponsor 25%, L2-5 5%, 10% Best Coach pot, 45% company) with keeper-signed hub-line vouchers; pure draft engine with a mocked clock; no contact data anywhere; Telegram to an outbox unless TG_LIVE=1. Unit 60/60, smoke 156/156 (Playwright 1280/390). Not deployed. Co-Authored-By: Claude Opus 5.5 diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..6ee9fa9 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,5 @@ +.git +node_modules +data +qa/out +.env diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..85144b7 --- /dev/null +++ b/.env.example @@ -0,0 +1,36 @@ +# 5xYourTeam (phase 2 values; nothing here is set yet). Never commit real secrets. +PORT=3000 +NODE_ENV=production +SITE_HOST=5xyourteam.com +DOCSTORE_URL=mysql://user:pass@host:3306/fivex # REQUIRED in production (never launch on files); set binlog expiry to hours +ADMIN_TOKEN= +SESSION_SECRET= +NETWORK_SSO_SECRET= # same 64-hex value as InstantAdPay / LinkSpin +HUB_ENABLED=1 +HUB_URL=https://hub.saasy.top +HUB_SECRET= # hub HUB_SITES entry 'fivex' (not added yet) +HUB_SITE=fivex +NETWORK_SITE_ID=fivex +# DraftPosition (../contracts), after Marty's go +CONTRACT_ADDRESS= +SHOP_START_BLOCK= +PRIZE_WALLET= # the Best Coach pot wallet passed to the constructor +CHAIN_RPC= +KEEPER_KEY= # the voucher key; its address = the contract's keeper +WALLETCONNECT_PROJECT_ID= +# the holding tank: stub (phase 1 fixture) | hub (phase 2, not wired) +TANK_MODE=stub +# the draft (Central time); every value here is an open question for Marty +DRAFT_DOW=1 +DRAFT_HOUR_CT=19 +DRAFT_ROUNDS=5 +DRAFT_PICK_SECONDS=90 +PICK_RETURN_DAYS=3 +PICK_MAX_OPEN=10 +POT_SPLIT=50,30,20 +# Telegram: nothing is sent unless TG_LIVE=1 (phase 1 writes tg-outbox.json) +TG_LIVE= +TG_TOKEN= +TG_CHAT=-1001258691510 +TG_PAY_TOPIC=632242 +OWNER_USERNAME=martbost diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..39893be --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +node_modules/ +data/ +*.log +qa/out/data-* +qa/out/server.log +qa/out/view/ +.env diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..dd09809 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM node:22-alpine +WORKDIR /app +COPY package.json package-lock.json ./ +RUN npm ci --omit=dev --no-audit --no-fund +COPY . . +RUN mkdir -p /app/data +ENV NODE_ENV=production +ENV PORT=3000 +EXPOSE 3000 +# a container that cannot boot is never swapped in (2026-10-08 rule) +HEALTHCHECK --interval=15s --timeout=5s --start-period=20s --retries=4 CMD wget -qO- http://127.0.0.1:3000/health >/dev/null || exit 1 +CMD ["node","server.js"] diff --git a/README.md b/README.md new file mode 100644 index 0000000..e98bbc5 --- /dev/null +++ b/README.md @@ -0,0 +1,70 @@ +# 5xYourTeam app: The Draft (5xyourteam.com rebuild) + +Phase 1, LOCAL ONLY (Marty 2026-11-15). Nothing here is deployed; no contract is on chain; the holding tank is a local stub +that adopts nobody and sends no mail; Telegram posts go to an outbox. Plain Node http server, no framework (the ViralAdBlitz / +DownlineHydra pattern). Contract: `../contracts` (DraftPosition). + +## What it does + +- **A position**: $10 one-time in POL (never a subscription). It gives 5 instant picks from the current pool and a spot in every + weekly draft. Paid through DraftPosition: sponsor 25%, levels 2-5 5% each (pass-up over people with no position, 20 places), + 10% to the Best Coach prize pot wallet, 45% company. The server builds the `buy()` call with a keeper-signed EIP-712 line + voucher from the hub line (shop.js, the VABShop pattern); the watcher records each `Purchase` once and adds the instant picks. +- **The draft** (draft.js, pure and unit-tested with a mocked clock; league.js wires it): every Monday 7 PM Central (env), 5 rounds, + straight order. Draft order is EARNED: most of last week's picks started (payouts on or a first purchase), then started ever, + then the earlier position, then a fixed shuffle of (week, coach). A coach in the draft room (the board pinged within 2 minutes) + gets a 90-second clock; an away coach is auto-picked at once from their own queue, else the best available by scouting score. + A coach with 10 open picks is skipped for that slot. A draft missed by more than 6 hours (app down) is skipped, never run late. +- **Picks are adoptions** (tankpool.js): every pick goes through `tank.adopt()` first. The pool never has anyone locked on a + network contract, already sponsored, adopted twice (every pick counts, plus the network's count), spam/throwaway, or inside the + 24-hour sign-up grace. An unconverted pick returns to the pool after 3 days, unless that person has now had 2 adoptions (then + they stay with the coach). A started pick stays. A coach cannot release a pick in its first 48 hours. +- **Coaching tools** (`/team`): stat tiles (on my team, started this week, next draft spot, back to pool soon), the focused pick + card (scouting stats, the 5 getting-started steps, one-tap messages, the composer and thread, release), the rest of the team, + who to help first (back to pool soon, one step from payouts, quiet), the draft queue. Someone who is a pick sees their coach, + the steps and the thread, and the coach's builder links. Messages go through the site only. No email, phone or any contact + data is ever shown, stored from sign-in, or exported (smoke-tested). +- **Scouting stats** on draft cards: last seen, the door they came from, wallet linked, game plays and title, POL earned in + games and surfing where the network tracks it ("not tracked yet" otherwise, never invented). Earnings show to coaches only. +- **Cards**: trading cards Rookie (drafted), Starter (wallet), Pro (payouts on), All-Star (first purchase), Hall of Fame (holds a + position of their own). Public cards show milestones, never earnings. Coach page `5xyourteam.com/`. +- **Boards**: Best Coach (picks started inside the Central week; tie = got there first), the week's pot (10% of positions sold + that week, from the Purchase events), Rookie of the Week (the pick that climbed highest that week), last week's top 3. +- **Builder** (`/builder`, wild.js from DownlineHydra, the CryptoTeamBuild builder programs seeded from + `data-seed/programs.seed.json`): coaches save referral IDs; their picks see the coach's link for each program. +- **Trust pack** (proof.js): `/ledger` (every share with its place in the line, passed over, pot, company; Best Coach payouts + with tx), `/contract` (live facts incl. the prize wallet), toasts (positions, picks, level-ups), Telegram sale card (rotated + proof images), Draft Day card (`/draftday/` 1080x1080, PNG via `tools/art.mjs --draftday`), a line per pot payout; + Terms / Earnings Disclaimer / Privacy naming TrustClickz, 615 Green Valley Drive, Moody, AL 35004; the network footer from the + hub (netsites.js, 5xYourTeam added locally as `fivex`, LinkSpin code `nw5x`). +- **Promo kit** (`/promote`, `/api/promo-kit?u=`): 21 creatives `public/art/kit/fx-{draft,coach,cards}-{shape}.png`, swipe copy. +- **Old links**: `/?`, `/splashpg.php?r=`, `/lcp.php?r=`, `/index.php?r=` 301 to the coach page via the old-ref map + (`POST /api/admin/oldrefs`), `/members/*` to `/team`, any other `*.php` to `/`. +- **Admin** (`/admin`, `ADMIN_TOKEN`): status, run a tick, the week's pot shares, record a pot payout (`POST /api/admin/pot/paid`), + old-link map. Test-only: `POST /api/admin/clock` (needs `ALLOW_TEST_CLOCK=1`, refused in production), `POST /api/admin/stub/status`. +- **Data**: docstore.js (MySQL via `DOCSTORE_URL`, the LinkSpin copy that skips unchanged writes): document `fivex.json` + row + tables `fx_picks`, `fx_msgs`, `fx_refids`; `hubreport.json`, `oldrefs.json`, `tg-outbox.json`, `stub-tank.json` are documents. + +## Look + +The approved draft-night mockup (2026-11-14): stadium navy #0b1530 / bar #07102a, gold #ffc93c rule and accents, red #ff4d4d +week tag, white scouting cards with navy heads, Oswald + Inter. One stylesheet `public/assets/fx.css`. +Deviation from the mockup on purpose: the mockup's coach card showed an email line; it is gone (no contact data, Marty's rule). + +## Run and test + +``` +npm ci +node server.js # prototype mode (files, stub tank); never launch this way +node qa/unit.test.cjs # 60 checks: tiers, tank rules, earned order, the clocked draft, returns, boards, the split model + # against the fork rehearsal (to the wei), Central weeks, the league end to end +node qa/smoke.mjs # 156 checks against stand-in hub / chain / Telegram (ports 3561-3564) + Playwright 1280/390 +UI_FONTS=1 node qa/smoke.mjs # same, Google Fonts allowed so qa/out screenshots show the real type +node tools/pages.mjs # regenerate public/*.html (one source of copy + legal facts) +node tools/art.mjs # icon, OG, proof cards, kit, tier cards; --draftday for a Draft Day PNG +``` + +## Phase 2 (needs Marty's go): see the open questions in the build report + +Hub `HUB_SITES` entry `fivex` + secret; `tankpool.js` hub mode (pool read, adopt through the tank, status); the network-sites list +and LinkSpin `nw5x`; the contract on chain with the prize wallet; DOCSTORE_URL; old-member reconciliation; PolHunter mission. diff --git a/config.js b/config.js new file mode 100644 index 0000000..1f55d9e --- /dev/null +++ b/config.js @@ -0,0 +1,71 @@ +// All runtime config comes from env (Coolify sets these in phase 2). Read once. +// 5xYourTeam "The Draft" (Marty approved 2026-11-14): a $10 one-time position = 5 picks right away + a draft spot every week. Each +// Monday the coaches draft people waiting in the network holding tank, in rounds; draft order is EARNED by how many of last week's +// picks switched on payouts or bought. A pick is an ADOPTION under the tank rules (tankpool.js). Paid in POL through DraftPosition +// (../contracts): sponsor 25%, levels 2-5 5% each (pass-up), 10% weekly Best Coach prize pot, 45% company. +// Purchases are inert until CONTRACT_ADDRESS / CHAIN_RPC / KEEPER_KEY are set. +const path = require('path'); + +let cfg = null; +function get() { + if (cfg) return cfg; + const e = process.env; + const num = (v, d, min, max) => { const n = Number(v); return Number.isFinite(n) && v !== '' && v != null ? Math.min(max, Math.max(min, Math.round(n))) : d; }; + const addr = v => /^0x[0-9a-fA-F]{40}$/.test(String(v || '').trim()) ? require('ethers').getAddress(String(v).trim().toLowerCase()) : ''; + cfg = { + port: Number(e.PORT || 3000), + isProd: e.NODE_ENV === 'production', + site: e.SITE_HOST || '5xyourteam.com', + siteName: '5xYourTeam', + siteId: 'fivex', // hub site id, network sign-in audience, netsites id + dataDir: e.DATA_DIR || path.join(__dirname, 'data'), + chainId: Number(e.CHAIN_ID || 137), + chainName: e.CHAIN_NAME || 'Polygon', + publicRpc: e.PUBLIC_RPC || 'https://polygon-bor-rpc.publicnode.com', + walletConnectProjectId: (e.WALLETCONNECT_PROJECT_ID || '').trim(), + // ---- the position (Marty 2026-11-14: "$10 on 5x your team makes sense"). One-time, never a subscription. The contract's + // priceCents holds the real price; this is display copy and must match it (smoke + chain tests check). + position: { usd: Number(e.POSITION_USD || 10), maxQty: 10, picksOnBuy: num(e.PICKS_ON_BUY, 5, 1, 20) }, + // DraftPosition constants (display copy): option C + split: { sponsorPct: 25, levelPct: 5, levels: 5, potPct: 10, companyPct: 45, maxDepth: 20 }, + // ---- the weekly draft (US Central). Every number here is an open question for Marty; these are the build's defaults. + draft: { + dow: num(e.DRAFT_DOW, 1, 0, 6), // 1 = Monday + hour: num(e.DRAFT_HOUR_CT, 19, 0, 23), // 7 PM Central + rounds: num(e.DRAFT_ROUNDS, 5, 1, 20), // "draft 5 people from that week's pool" + pickSeconds: num(e.DRAFT_PICK_SECONDS, 90, 5, 3600), // the clock for a coach who is in the draft room + presenceSeconds: num(e.DRAFT_PRESENCE_SECONDS, 120, 10, 3600), // "in the room" = the board page pinged within this long + tickMs: num(e.DRAFT_TICK_MS, 5000, 100, 600000), + lateHours: num(e.DRAFT_LATE_HOURS, 6, 0, 72) // a draft missed by more than this (app down) is skipped + }, + picks: { + returnDays: num(e.PICK_RETURN_DAYS, 3, 1, 30), // an unconverted pick goes back to the pool after this + holdHours: num(e.PICK_HOLD_HOURS, 48, 0, 720), // a coach cannot release a pick sooner (the IAP churn rule) + maxOpen: num(e.PICK_MAX_OPEN, 10, 1, 100), // open picks per coach (Marty 11-13: "10 at a time") + maxAdoptions: 2, // per person, lifetime, across the network (tank rule) + graceHours: num(e.PICK_GRACE_HOURS, 24, 0, 168) // a new sign-up is not draftable for this long (IAP GRACE_MS) + }, + pot: { split: String(e.POT_SPLIT || '50,30,20').split(',').map(Number).filter(n => n > 0) }, // Best Coach places, % of the week's pot + explorer: String(e.EXPLORER || (Number(e.CHAIN_ID || 137) === 137 ? 'https://polygonscan.com' : '')).replace(/\/+$/, ''), + // DraftPosition (../contracts). KEEPER_KEY is read by shop.js only, never kept here. + contractAddress: addr(e.CONTRACT_ADDRESS), + companyWallet: addr(e.COMPANY_WALLET) || '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70', // Tangem (immutable in the contract) + prizeWallet: addr(e.PRIZE_WALLET), // the Best Coach pot (immutable in the contract; decided at deploy) + chainRpc: String(e.CHAIN_RPC || '').trim(), + shopStartBlock: num(e.SHOP_START_BLOCK, 0, 0, 1e12), + shopConfirmations: num(e.SHOP_CONFIRMATIONS, 10, 0, 1000), + shopPollMs: num(e.SHOP_POLL_MS, 30000, 200, 3600000), + voucherSeconds: num(e.VOUCHER_SECONDS, 1800, 60, 86400), + iapBase: String(e.IAP_URL || 'https://instantadpay.com').replace(/\/+$/, ''), + lsBase: String(e.LS_URL || 'https://linkspin.app').replace(/\/+$/, ''), + joinUrl: String(e.JOIN_URL || 'https://instantadpay.com/join/{ref}'), + // the holding tank behind the draft: 'stub' (phase 1, local fixture, adopts nobody for real) | 'hub' (phase 2) + tankMode: /^hub$/i.test(String(e.TANK_MODE || '')) ? 'hub' : 'stub', + stubPool: String(e.STUB_POOL_FILE || '').trim(), + owner: String(e.OWNER_USERNAME || 'martbost'), // builder fallback links (the DownlineHydra rule) + testClock: e.ALLOW_TEST_CLOCK === '1' && e.NODE_ENV !== 'production' + }; + return cfg; +} + +module.exports = { get, reset: () => { cfg = null; } }; diff --git a/data-seed/programs.seed.json b/data-seed/programs.seed.json new file mode 100644 index 0000000..524fde5 --- /dev/null +++ b/data-seed/programs.seed.json @@ -0,0 +1,789 @@ +{ + "source": "CryptoTeamBuild downline builder, read-only list (yfw-builder.py list rhi cryptoteambuild cryptoteambuild.com) 2026-11-14 6:45 PM CT", + "rules": "hidden+network = a core or growing head or another network site: never shown as a wild head (admin can change). ctbMemberLinks is the count on cryptoteambuild.com, for reference only; never shown as a DownlineHydra joined count.", + "cats": [ + { + "id": "6", + "name": "Ads Earn Network", + "short": "Ads Earn Network" + }, + { + "id": "7", + "name": "Infinity Family", + "short": "Infinity Family" + }, + { + "id": "8", + "name": "Free Builders", + "short": "Free Builders" + }, + { + "id": "9", + "name": "More Ways to Earn", + "short": "More Ways to Earn" + }, + { + "id": "10", + "name": "AI and Tools", + "short": "AI and Tools" + }, + { + "id": "11", + "name": "Crypto Team Build Network", + "short": "CTB Network" + }, + { + "id": "12", + "name": "Crypto Faucets", + "short": "Crypto Faucets" + }, + { + "id": "13", + "name": "Safelist Mailers and Traffic Exchanges", + "short": "Mailers and Traffic" + }, + { + "id": "0", + "name": "Other programs", + "short": "Other" + } + ], + "programs": [ + { + "id": "ctb2", + "builderId": 2, + "name": "Ads Earn LTC", + "builderTitle": "Ads Earn LTC", + "url": "https://www.adsearnltc.com/?r={affiliateid}", + "idKind": "path", + "cat": "6", + "order": 1, + "ctbMemberLinks": 119, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb6", + "builderId": 6, + "name": "Elite Downline Club", + "builderTitle": "Elite Downline Club", + "url": "https://www.elitedownlineclub.com/index.php?r={affiliateid}&t=ctb", + "idKind": "path", + "cat": "11", + "order": 2, + "ctbMemberLinks": 179, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb12", + "builderId": 12, + "name": "Infinity Mailer Boost", + "builderTitle": "Infinity Mailer Boost", + "url": "https://infinitymailerboost.com/{affiliateid}", + "idKind": "path", + "cat": "7", + "order": 3, + "ctbMemberLinks": 145, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb13", + "builderId": 13, + "name": "Infinity Traffic Boost", + "builderTitle": "Infinity Traffic Boost", + "url": "https://infinitytrafficboost.com/{affiliateid}", + "idKind": "path", + "cat": "7", + "order": 4, + "ctbMemberLinks": 183, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb14", + "builderId": 14, + "name": "My Lead Gen Secret", + "builderTitle": "My Lead Gen Secret", + "url": "https://www.myleadgensecret.com/?rid={affiliateid}", + "idKind": "path", + "cat": "9", + "order": 5, + "ctbMemberLinks": 71, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb15", + "builderId": 15, + "name": "Traffic Zipper", + "builderTitle": "Traffic Zipper", + "url": "https://trafficzipper.com/index2.php?af={affiliateid}", + "idKind": "path", + "cat": "13", + "order": 6, + "ctbMemberLinks": 100, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb16", + "builderId": 16, + "name": "Leased Ad Space", + "builderTitle": "Leased Ad Space", + "url": "https://leasedadspace.com/?aid={affiliateid}", + "idKind": "path", + "cat": "7", + "order": 7, + "ctbMemberLinks": 136, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb18", + "builderId": 18, + "name": "Unstoppable Domains", + "builderTitle": "Unstoppable Domains", + "url": "https://unstoppabledomains.com/?ref={affiliateid}", + "idKind": "path", + "cat": "9", + "order": 8, + "ctbMemberLinks": 57, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb19", + "builderId": 19, + "name": "Ads Earn Network", + "builderTitle": "Ads Earn Network", + "url": "https://www.adsearnnetwork.com/?{affiliateid}", + "idKind": "path", + "cat": "6", + "order": 9, + "ctbMemberLinks": 147, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb20", + "builderId": 20, + "name": "Team Builder BTC 2.0", + "builderTitle": "Team Builder BTC 2.0", + "url": "https://www.teambuilderbtc.com/?r={affiliateid}", + "idKind": "path", + "cat": "6", + "order": 10, + "ctbMemberLinks": 95, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb21", + "builderId": 21, + "name": "Early Birds Downline Builder", + "builderTitle": "Early Birds Downline Builder", + "url": "https://www.earlybirdsdownline.com/me/{affiliateid}", + "idKind": "path", + "cat": "6", + "order": 11, + "ctbMemberLinks": 128, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb23", + "builderId": 23, + "name": "Tron Banners", + "builderTitle": "Tron Banners", + "url": "https://tronbanners.io/?{affiliateid}", + "idKind": "path", + "cat": "9", + "order": 12, + "ctbMemberLinks": 116, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb26", + "builderId": 26, + "name": "Ads Earn Tron", + "builderTitle": "Ads Earn Tron", + "url": "https://www.adsearntron.com/?r={affiliateid}", + "idKind": "path", + "cat": "6", + "order": 13, + "ctbMemberLinks": 111, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb27", + "builderId": 27, + "name": "Team Profit Builder", + "builderTitle": "Team Profit Builder", + "url": "https://teamprofitbuilder.com/splashpg.php?pid=2&r={affiliateid}", + "idKind": "path", + "cat": "9", + "order": 14, + "ctbMemberLinks": 107, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb28", + "builderId": 28, + "name": "YourProgramBuilder", + "builderTitle": "Grow Your Downline With Your Program Builder For FREE", + "url": "https://yourprogrambuilder.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 15, + "ctbMemberLinks": 330, + "hidden": true, + "network": true, + "note": "growing head YourProgramBuilder", + "defaultId": "", + "featured": false + }, + { + "id": "ctb29", + "builderId": 29, + "name": "ViralAdBlitz", + "builderTitle": "Join Viral Ad Blitz For FREE", + "url": "https://viraladblitz.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 16, + "ctbMemberLinks": 304, + "hidden": true, + "network": true, + "note": "core head ViralAdBlitz", + "defaultId": "", + "featured": false + }, + { + "id": "ctb30", + "builderId": 30, + "name": "DownlineHydra", + "builderTitle": "Downline Hydra Join It FREE", + "url": "https://downlinehydra.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 17, + "ctbMemberLinks": 305, + "hidden": true, + "network": true, + "note": "this site (DownlineHydra)", + "defaultId": "", + "featured": false + }, + { + "id": "ctb31", + "builderId": 31, + "name": "DownlineScaler", + "builderTitle": "Grow Your Team With Downline Scaler For FREE", + "url": "https://downlinescaler.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 18, + "ctbMemberLinks": 302, + "hidden": true, + "network": true, + "note": "growing head DownlineScaler", + "defaultId": "", + "featured": false + }, + { + "id": "ctb32", + "builderId": 32, + "name": "5xYourTeam", + "builderTitle": "5x Your Team For FREE", + "url": "https://5xyourteam.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 19, + "ctbMemberLinks": 299, + "hidden": true, + "network": true, + "note": "growing head 5xYourTeam", + "defaultId": "", + "featured": false + }, + { + "id": "ctb33", + "builderId": 33, + "name": "Viral Ad Source", + "builderTitle": "Join Our Viral Text Ad Marketing System FREE", + "url": "https://viraladsource.com?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 20, + "ctbMemberLinks": 170, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb34", + "builderId": 34, + "name": "Downline Banners", + "builderTitle": "Put Your Banners On Autopilot With This Free Platform", + "url": "https://downlinebanners.com?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 21, + "ctbMemberLinks": 280, + "hidden": true, + "network": true, + "note": "core head Downline Banners", + "defaultId": "", + "featured": false + }, + { + "id": "ctb35", + "builderId": 35, + "name": "Network Ad Space", + "builderTitle": "Network Ad Space - Our CTB Ad Marketplace", + "url": "https://networkadspace.com/?id={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 22, + "ctbMemberLinks": 288, + "hidden": true, + "network": true, + "note": "network site Network Ad Space", + "defaultId": "", + "featured": false + }, + { + "id": "ctb36", + "builderId": 36, + "name": "Viral Banner Blitz", + "builderTitle": "Grow Your For Free With Viral Banner Blitz", + "url": "https://viralbannerblitz.com?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 23, + "ctbMemberLinks": 272, + "hidden": true, + "network": true, + "note": "core head Viral Banner Blitz", + "defaultId": "", + "featured": false + }, + { + "id": "ctb37", + "builderId": 37, + "name": "Ads Earn ETH", + "builderTitle": "Ads Earn ETH", + "url": "https://adsearneth.com/?id={affiliateid}", + "idKind": "path", + "cat": "6", + "order": 24, + "ctbMemberLinks": 61, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb39", + "builderId": 39, + "name": "PassiveDrip", + "builderTitle": "Join Our Auto Faucet And Earn Every 2 Minutes At PassiveDrip.com", + "url": "https://passivedrip.com/?ref={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 25, + "ctbMemberLinks": 152, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb40", + "builderId": 40, + "name": "CTB VIP", + "builderTitle": "The Crypto Team Build VIP Program", + "url": "https://teambuildvip.com/lcpjoinvip.php?r={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 26, + "ctbMemberLinks": 255, + "hidden": true, + "network": true, + "note": "growing head VIP (The Crypto Team Build VIP Program)", + "defaultId": "", + "featured": false + }, + { + "id": "ctb41", + "builderId": 41, + "name": "PaidOfferTasks", + "builderTitle": "PaidOfferTasks.com - Get Paid To Complete Surveys And Tasks", + "url": "https://paidoffertasks.com/?ref={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 27, + "ctbMemberLinks": 89, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb43", + "builderId": 43, + "name": "My Link Shortener", + "builderTitle": "My Link Shortener", + "url": "https://mylnks.xyz/?ref={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 28, + "ctbMemberLinks": 76, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb46", + "builderId": 46, + "name": "CrankOutAI", + "builderTitle": "CrankOutAI.com", + "url": "https://crankoutai.com/?ref={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 29, + "ctbMemberLinks": 81, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb47", + "builderId": 47, + "name": "BTC4Hits", + "builderTitle": "BTC4Hits URL Rotator", + "url": "https://btc4hits.com/?{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 30, + "ctbMemberLinks": 237, + "hidden": true, + "network": true, + "note": "network site BTC4Hits (merging into LinkSpin)", + "defaultId": "", + "featured": false + }, + { + "id": "ctb49", + "builderId": 49, + "name": "Mailer.gold", + "builderTitle": "Mailer.gold", + "url": "https://mailer.gold/{affiliateid}", + "idKind": "path", + "cat": "7", + "order": 31, + "ctbMemberLinks": 85, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb50", + "builderId": 50, + "name": "100 Percent Clicks", + "builderTitle": "100 Percent Clicks Viral Advertising Mailer", + "url": "https://100percentclicks.com/index.php?r={affiliateid}", + "idKind": "path", + "cat": "13", + "order": 32, + "ctbMemberLinks": 93, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb51", + "builderId": 51, + "name": "Traffic Leads 2 Income", + "builderTitle": "Traffic Leads 2 Income - The Income Driven Viral Mailer", + "url": "https://tl2icashmailer.com/?rid={affiliateid}", + "idKind": "path", + "cat": "13", + "order": 33, + "ctbMemberLinks": 83, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb59", + "builderId": 59, + "name": "Xpress Viral Mailer", + "builderTitle": "Xpress Viral Mailer", + "url": "https://xpressviralmailer.com/index.php?referrer={affiliateid}", + "idKind": "path", + "cat": "0", + "order": 34, + "ctbMemberLinks": 52, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb62", + "builderId": 62, + "name": "Tangled Social", + "builderTitle": "Tangled Social (Earn Crypto Just For Using It)", + "url": "https://{affiliateid}.tangled.com", + "idKind": "subdomain", + "cat": "9", + "order": 35, + "ctbMemberLinks": 33, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb63", + "builderId": 63, + "name": "Ads Earn XRP", + "builderTitle": "Ads Earn XRP", + "url": "https://www.adsearnxrp.com/?{affiliateid}", + "idKind": "path", + "cat": "6", + "order": 36, + "ctbMemberLinks": 24, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb66", + "builderId": 66, + "name": "Passive Crypto AI", + "builderTitle": "Passive Crypto AI", + "url": "https://passivecryptoai.com/?r={affiliateid}", + "idKind": "path", + "cat": "11", + "order": 37, + "ctbMemberLinks": 33, + "hidden": true, + "network": true, + "note": "network rebuild Passive Crypto AI (downline-builder site)", + "defaultId": "", + "featured": false + }, + { + "id": "ctb67", + "builderId": 67, + "name": "Really Smart Art", + "builderTitle": "Really Smart Art", + "url": "https://www.reallysmart.art/video.aspx?u={affiliateid}", + "idKind": "path", + "cat": "10", + "order": 38, + "ctbMemberLinks": 29, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": true + }, + { + "id": "ctb69", + "builderId": 69, + "name": "Sparky AI (PHG Hub)", + "builderTitle": "Automatic Duplication System With Sparky AI", + "url": "https://phghub.ai/{affiliateid}", + "idKind": "path", + "cat": "0", + "order": 39, + "ctbMemberLinks": 16, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb71", + "builderId": 71, + "name": "Amplify AI Workshop", + "builderTitle": "Jour Our Amplify AI Workshop Skool Community", + "url": "https://www.skool.com/amplify-ai/about?ref={affiliateid}", + "idKind": "path", + "cat": "10", + "order": 40, + "ctbMemberLinks": 8, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb72", + "builderId": 72, + "name": "CTB Rewards Telegram App", + "builderTitle": "Earn For Free In Our Native Telegram CTB Rewards App", + "url": "https://ctbrewards.saasy.top/invite/{affiliateid}", + "idKind": "path", + "cat": "11", + "order": 41, + "ctbMemberLinks": 11, + "hidden": false, + "network": false, + "note": "builder URL had a misspelled {affiliateid} placeholder, fixed here", + "defaultId": "", + "featured": false + }, + { + "id": "ctb73", + "builderId": 73, + "name": "ClickBaitPays", + "builderTitle": "ClickBaitPays", + "url": "https://cbp-calculator.saasy.top/?ref={affiliateid}", + "idKind": "path", + "cat": "9", + "order": 42, + "ctbMemberLinks": 16, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb74", + "builderId": 74, + "name": "RM Circle", + "builderTitle": "Join Our RM Circle Team Build", + "url": "https://rmcircle.team/my/{affiliateid}", + "idKind": "path", + "cat": "9", + "order": 43, + "ctbMemberLinks": 12, + "hidden": false, + "network": false, + "note": "Marty 2026-11-14: RM Circle is a wild head (never a network core head)", + "defaultId": "", + "featured": true + }, + { + "id": "ctb75", + "builderId": 75, + "name": "Ads Earn SOL", + "builderTitle": "Ads Earn SOL", + "url": "https://www.adsearnsol.com/?{affiliateid}", + "idKind": "path", + "cat": "6", + "order": 44, + "ctbMemberLinks": 3, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb76", + "builderId": 76, + "name": "Massifly", + "builderTitle": "Massifly", + "url": "https://massifly.com/?r={affiliateid}", + "idKind": "path", + "cat": "13", + "order": 45, + "ctbMemberLinks": 3, + "hidden": false, + "network": false, + "note": "", + "defaultId": "", + "featured": false + }, + { + "id": "ctb77", + "builderId": 77, + "name": "InstantAdPay", + "builderTitle": "InstantAdPay", + "url": "https://instantadpay.com/join/{affiliateid}?promo=CTB&src=cryptoteambuild", + "idKind": "path", + "cat": "11", + "order": 46, + "ctbMemberLinks": 4, + "hidden": true, + "network": true, + "note": "core head InstantAdPay", + "defaultId": "", + "featured": false + } + ] +} \ No newline at end of file diff --git a/docstore.js b/docstore.js new file mode 100644 index 0000000..c3cdbda --- /dev/null +++ b/docstore.js @@ -0,0 +1,197 @@ +// Database-backed data documents (Marty 2026-11-13, standing rule: "everything database-driven ... files only for early +// prototyping"). Every *.json / *.jsonl data document under DATA_DIR that a module reads or writes with the fs *Sync calls lives +// in MySQL instead of on the volume: table `docs` (name = path relative to DATA_DIR, body LONGTEXT, updated_at). The modules keep +// their code; install() routes their fs calls on those paths to an in-memory copy that init() loads from MySQL at boot, and every +// change is written through to MySQL (coalesced per document, newest body wins, in order, retried until it lands). +// +// One writer at a time: init() claims the `docs_writer` row; an older app copy still running during a deploy finds the row taken +// and stops writing (logged), so it can never put stale data over the new copy's (the 2026-11-13 rotator.json loss). +// First boot: a document missing from MySQL is imported from its file, and the file is renamed .imported- (kept, not +// read again). Files the volume keeps on purpose: KEEP (rebuildable caches, uploads, images, the geo database, queues read by +// listing a folder). The SAME file ships in InstantAdPay and LinkSpin. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); + +const KEEP_FILES = new Set(['chain-index.json']); // a rebuildable cache of the blockchain +const KEEP_DIRS = ['uploads', 'geo', 'refuel-pending', 'backups', 'marks', 'kits', 'kitimg']; // binary files, or folders read by listing +const O = { readFileSync: fs.readFileSync, writeFileSync: fs.writeFileSync, existsSync: fs.existsSync, renameSync: fs.renameSync, + unlinkSync: fs.unlinkSync, statSync: fs.statSync, appendFileSync: fs.appendFileSync }; + +let ROOT = null, pool = null, ME = crypto.randomBytes(8).toString('hex'), ready = false, writer = true; +const cache = new Map(); // name -> { body: string, at: ms } +const pending = new Map(); // name -> body string | null (delete) +const stored = new Map(); // name -> body as last read from or written to MySQL: an unchanged save is not rewritten (2026-11-15: whole-document rewrites filled core with 115 GB of binlogs) +let flushing = false, timer = null; +const stats = { writes: 0, deletes: 0, refused: 0, errors: 0, imported: 0, lastError: null }; + +function nameOf(p) { + if (!ROOT || typeof p !== 'string' || !/\.jsonl?$/i.test(p)) return null; + const abs = path.resolve(p); if (!abs.startsWith(ROOT + path.sep)) return null; + const rel = abs.slice(ROOT.length + 1).split(path.sep).join('/'); + if (KEEP_FILES.has(rel) || KEEP_DIRS.some(d => rel === d || rel.startsWith(d + '/'))) return null; + return rel; +} +const enoent = p => { const e = new Error("ENOENT: no such file or directory, open '" + p + "'"); e.code = 'ENOENT'; e.errno = -2; e.path = p; return e; }; +const enc = o => (typeof o === 'string' ? o : o && o.encoding) || null; + +function put(name, body) { + cache.set(name, { body, at: Date.now() }); + if (stored.get(name) === body) { pending.delete(name); return; } // same as what MySQL already holds: nothing to write + pending.set(name, body); kick(); +} +function drop(name) { cache.delete(name); pending.set(name, null); kick(); } +function kick() { if (!timer) timer = setTimeout(() => { timer = null; flush().catch(() => {}); }, 300); } + +async function flush() { + if (!pool || flushing || !pending.size) return; + flushing = true; + try { + for (const [name, body] of [...pending]) { + if (pending.get(name) !== body) continue; // replaced while we were busy: the newer body goes next round + if (!writer) { pending.delete(name); stats.refused++; continue; } + const c = await pool.getConnection(); + try { + await c.beginTransaction(); + const [[w]] = await c.query('SELECT owner FROM docs_writer WHERE id = 1 FOR UPDATE'); + if (!w || w.owner !== ME) { await c.rollback(); writer = false; pending.delete(name); stats.refused++; console.error('docstore: another app copy took over writing; this copy stops writing'); continue; } + if (body === null) { await c.query('DELETE FROM docs WHERE name = ?', [name]); stats.deletes++; } + else { await c.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), updated_at = VALUES(updated_at)', [name, body, Date.now()]); stats.writes++; } + await c.commit(); + if (body === null) stored.delete(name); else stored.set(name, body); + if (pending.get(name) === body) pending.delete(name); + } catch (e) { try { await c.rollback(); } catch (x) {} stats.errors++; stats.lastError = String(e.message).slice(0, 200); console.error('docstore write', name, e.message); } + finally { c.release(); } + } + } finally { flushing = false; if (pending.size) setTimeout(() => flush().catch(() => {}), 1000); } +} + +// Route the fs *Sync calls on data documents. Installed before any module runs; until init() the documents read from disk. +function install(dataDir) { + if (ROOT) return; ROOT = path.resolve(dataDir); + fs.readFileSync = function (p, o) { + if (!ready && process.env.DOCSTORE_URL && nameOf(p)) console.error('docstore: read before init', p, new Error().stack.split('\n')[2]); + const n = ready ? nameOf(p) : null; if (!n) return O.readFileSync.apply(fs, arguments); + const d = cache.get(n); if (!d) throw enoent(p); + return enc(o) ? d.body : Buffer.from(d.body, 'utf8'); + }; + fs.existsSync = function (p) { const n = ready ? nameOf(p) : null; return n ? cache.has(n) : O.existsSync.apply(fs, arguments); }; + fs.writeFileSync = function (p, data, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.writeFileSync.apply(fs, arguments); + const flag = o && typeof o === 'object' ? o.flag : null; + const s = Buffer.isBuffer(data) ? data.toString('utf8') : String(data); + put(n, flag && flag[0] === 'a' ? ((cache.get(n) || {}).body || '') + s : s); + }; + fs.appendFileSync = function (p, data) { + const n = ready ? nameOf(p) : null; if (!n) return O.appendFileSync.apply(fs, arguments); + put(n, ((cache.get(n) || {}).body || '') + (Buffer.isBuffer(data) ? data.toString('utf8') : String(data))); + }; + fs.renameSync = function (a, b) { + const nb = ready ? nameOf(b) : null; const na = ready ? nameOf(a) : null; + if (!nb && !na) return O.renameSync.apply(fs, arguments); + let body; + if (na) { const d = cache.get(na); if (!d) throw enoent(a); body = d.body; drop(na); } + else { body = O.readFileSync.call(fs, a, 'utf8'); try { O.unlinkSync.call(fs, a); } catch (e) {} } + if (nb) put(nb, body); else O.writeFileSync.call(fs, b, body); + }; + fs.unlinkSync = function (p) { const n = ready ? nameOf(p) : null; if (!n) return O.unlinkSync.apply(fs, arguments); if (!cache.has(n)) throw enoent(p); drop(n); }; + fs.statSync = function (p, o) { + const n = ready ? nameOf(p) : null; if (!n) return O.statSync.apply(fs, arguments); + const d = cache.get(n); if (!d) { if (o && o.throwIfNoEntry === false) return undefined; throw enoent(p); } + const size = Buffer.byteLength(d.body, 'utf8'); const t = new Date(d.at); + return { size, mtimeMs: d.at, mtime: t, ctime: t, birthtime: t, isFile: () => true, isDirectory: () => false, isSymbolicLink: () => false }; + }; +} + +// Connect, claim writing, load every document, import files MySQL does not have yet. Throws if MySQL is unreachable: the app +// must not run on an empty copy. +async function init(opts) { + const url = String(process.env.DOCSTORE_URL || '').trim(); + if (!url) { console.log('docstore: no DOCSTORE_URL, documents stay files (prototype mode)'); return false; } + const mysql = require('mysql2/promise'); + pool = mysql.createPool({ uri: url, connectionLimit: 6, charset: 'utf8mb4' }); + await pool.query('CREATE TABLE IF NOT EXISTS docs (name VARCHAR(190) PRIMARY KEY, body LONGTEXT NOT NULL, updated_at BIGINT NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + await pool.query('CREATE TABLE IF NOT EXISTS docs_writer (id TINYINT PRIMARY KEY, owner VARCHAR(40) NOT NULL, at BIGINT NOT NULL) ENGINE=InnoDB'); + await pool.query('INSERT INTO docs_writer (id, owner, at) VALUES (1, ?, ?) ON DUPLICATE KEY UPDATE owner = VALUES(owner), at = VALUES(at)', [ME, Date.now()]); + const [rows] = await pool.query('SELECT name, body, updated_at FROM docs'); + for (const r of rows) { cache.set(r.name, { body: r.body, at: Number(r.updated_at) }); stored.set(r.name, r.body); } + for (const sp of (opts && opts.splits) || []) await openSplit(sp); + // first boot for any document: import its file, then set the file aside + const stamp = new Date().toISOString().slice(0, 10); + const walk = dir => { let out = []; let ents = []; try { ents = fs.readdirSync(dir, { withFileTypes: true }); } catch (e) {} for (const e of ents) { const p = path.join(dir, e.name); if (e.isDirectory()) out = out.concat(walk(p)); else out.push(p); } return out; }; + for (const p of walk(ROOT)) { + const n = nameOf(p); if (!n || cache.has(n)) continue; + const body = O.readFileSync.call(fs, p, 'utf8'); + if (/\.json$/i.test(n) && body.trim()) { try { JSON.parse(body); } catch (e) { throw new Error('docstore: ' + n + ' is not valid JSON; fix or move it before switching to MySQL'); } } + await pool.query('INSERT INTO docs (name, body, updated_at) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE name = name', [n, body, Date.now()]); + const [[got]] = await pool.query('SELECT body FROM docs WHERE name = ?', [n]); + cache.set(n, { body: got.body, at: Date.now() }); stats.imported++; + O.renameSync.call(fs, p, p + '.imported-' + stamp); + } + for (const sp of (opts && opts.splits) || []) await migrateSplit(sp); + ready = true; + console.log('docstore: MySQL documents ready,', cache.size, 'documents,', stats.imported, 'imported from files this boot'); + const shut = () => { flush().catch(() => {}).finally(() => {}); }; + process.once('beforeExit', shut); + return true; +} +// ---- row tables: an ever-growing array (spin-link clicks) is one row per item, never a rewrite of the whole document ---- +// spec { doc: 'rotator.json', field: 'hits', table: 'rot_hits', key: 'id', ts: 'ts' }. rows(table) gives the loaded items (oldest +// first); the module inserts / deletes rows itself and saves its document WITHOUT the field. +const ROWS = new Map(); const rowQ = []; let rowBusy = false; +async function openSplit(sp) { + await pool.query('CREATE TABLE IF NOT EXISTS `' + sp.table + '` (id VARCHAR(64) PRIMARY KEY, ts BIGINT NOT NULL, body MEDIUMTEXT NOT NULL, KEY ts (ts)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4'); + const [r] = await pool.query('SELECT body FROM `' + sp.table + '` ORDER BY ts, id'); + ROWS.set(sp.table, r.map(x => JSON.parse(x.body))); +} +async function insertMany(table, items, key, ts) { + for (let i = 0; i < items.length; i += 500) { + const part = items.slice(i, i + 500); + await pool.query('INSERT INTO `' + table + '` (id, ts, body) VALUES ? ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [part.map(x => [String(x[key]), Number(x[ts]) || 0, JSON.stringify(x)])]); + } +} +// first boot: the array still inside the document moves to its table, then the document is saved without it +async function migrateSplit(sp) { + const d = cache.get(sp.doc); if (!d) return; + let obj; try { obj = JSON.parse(d.body); } catch (e) { return; } + const arr = Array.isArray(obj[sp.field]) ? obj[sp.field] : null; if (!arr || !arr.length) return; + await insertMany(sp.table, arr, sp.key, sp.ts); + const [[{ n }]] = await pool.query('SELECT COUNT(*) n FROM `' + sp.table + '`'); + if (n < arr.length) throw new Error('docstore: ' + sp.table + ' holds ' + n + ' rows after moving ' + arr.length + '; stopping before the document is changed'); + const seen = new Set((ROWS.get(sp.table) || []).map(x => String(x[sp.key]))); const merged = (ROWS.get(sp.table) || []).concat(arr.filter(x => !seen.has(String(x[sp.key])))); + merged.sort((a, b) => (Number(a[sp.ts]) || 0) - (Number(b[sp.ts]) || 0)); ROWS.set(sp.table, merged); + obj[sp.field] = []; const body = JSON.stringify(obj); + await pool.query('UPDATE docs SET body = ?, updated_at = ? WHERE name = ?', [body, Date.now(), sp.doc]); cache.set(sp.doc, { body, at: Date.now() }); + console.log('docstore:', arr.length, sp.field, 'moved from', sp.doc, 'to table', sp.table); +} +function rows(table) { return ROWS.get(table) || null; } +function rowOp(op) { if (!pool || !writer) return; rowQ.push(op); if (!rowBusy) runRows(); } +async function runRows() { + rowBusy = true; + try { + while (rowQ.length && writer) { + const op = rowQ[0]; + try { + if (op.del) await pool.query('DELETE FROM `' + op.table + '` WHERE id IN (?)', [op.ids]); + else await pool.query('INSERT INTO `' + op.table + '` (id, ts, body) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE body = VALUES(body), ts = VALUES(ts)', [op.id, op.ts, op.body]); + rowQ.shift(); + } catch (e) { stats.errors++; stats.lastError = String(e.message).slice(0, 200); await new Promise(r => setTimeout(r, 1000)); } + } + } finally { rowBusy = false; } +} +const rowPut = (table, id, ts, obj) => rowOp({ table, id: String(id), ts: Number(ts) || 0, body: JSON.stringify(obj) }); +const rowDel = (table, ids) => { const list = [...ids].map(String); for (let i = 0; i < list.length; i += 1000) rowOp({ table, del: true, ids: list.slice(i, i + 1000) }); }; +function isOn() { return ready && !!pool; } +// once across app copies (two run side by side during a deploy): true for the first caller of a key, false after. Without MySQL: true. +async function claim(key) { + if (!pool) return true; + await pool.query('CREATE TABLE IF NOT EXISTS doc_claims (k VARCHAR(190) PRIMARY KEY, at BIGINT NOT NULL) ENGINE=InnoDB'); + const [r] = await pool.query('INSERT IGNORE INTO doc_claims (k, at) VALUES (?, ?)', [String(key).slice(0, 190), Date.now()]); + return r.affectedRows === 1; +} + +// SIGTERM during a deploy: write what is pending, then exit +async function drain(ms) { const end = Date.now() + (ms || 8000); while ((pending.size || flushing || rowQ.length || rowBusy) && Date.now() < end) { await flush().catch(() => {}); await new Promise(r => setTimeout(r, 100)); } } +function view() { return Object.assign({ ready, writer, documents: cache.size, pending: pending.size, rowQueue: rowQ.length, rowTables: Object.fromEntries([...ROWS].map(([k, v]) => [k, v.length])), bytes: [...cache.values()].reduce((t, d) => t + d.body.length, 0) }, stats); } +module.exports = { install, init, drain, flush, view, nameOf, rows, rowPut, rowDel, isOn, claim }; diff --git a/draft.js b/draft.js new file mode 100644 index 0000000..125e33d --- /dev/null +++ b/draft.js @@ -0,0 +1,205 @@ +// THE DRAFT ENGINE. Pure functions: no I/O, no Date.now(). Every function takes `now` (ms) and the data it needs, so the weekly +// draft is deterministic and unit-tested with a mocked clock (qa/unit.test.cjs). server.js feeds it the store and the tank adapter. +// +// The rules (Marty 2026-11-14, project-5xyourteam-draft): +// - Every coach (holds a position) gets a draft spot every week. Each Monday the coaches draft from that week's pool, in rounds. +// - Draft order is EARNED: most of LAST week's picks "started" (switched on payouts or bought) picks first. Ties: more started +// picks ever, then the earlier first position (seniority), then a fixed shuffle of (week, coach) so nobody is always last. +// - A pick is an ADOPTION under the holding-tank rules: never anyone locked on a network contract or already sponsored, never a +// person adopted twice already (max 2 per person, lifetime, every pick counts), never spam / throwaway, never inside the 24-hour +// sign-up grace, never someone already on a team. +// - A coach in the draft room (the board pinged recently) gets the clock (pickSeconds); a coach who is away is auto-picked at once: +// the first available person on their own queue, else the best available by the scouting score. A coach with a full team +// (maxOpen open picks) is skipped for that slot. +// - An unconverted pick returns to the pool after returnDays. A person whose adoption count has reached the limit stays with the +// coach instead (never back to nobody: the IAP sweep rule). A converted pick (started) stays for good. +'use strict'; + +const TIERS = ['rookie', 'starter', 'pro', 'allstar', 'hof']; +const TIER_NAME = { rookie: 'Rookie', starter: 'Starter', pro: 'Pro', allstar: 'All-Star', hof: 'Hall of Fame' }; +const DAY = 86400000; + +// ---- milestones -> card tier. m = { wallet, payouts, purchase, ownTeam } as timestamps (0/absent = not yet) ---- +function tierOf(m) { + m = m || {}; + if (m.ownTeam) return 'hof'; // holds a 5xYourTeam position of their own: they coach a team now + if (m.purchase) return 'allstar'; // first purchase on the network + if (m.payouts) return 'pro'; // switched on payouts + if (m.wallet) return 'starter'; // linked a wallet + return 'rookie'; // drafted +} +const tierRank = t => TIERS.indexOf(t); +const tierAt = (m, t) => ({ hof: m.ownTeam, allstar: m.purchase, pro: m.payouts, starter: m.wallet }[t] || 0); +// "started" = the conversion the draft order and Best Coach count: payouts switched on or a purchase +const started = m => !!(m && (m.payouts || m.purchase)); +const startedAt = m => { if (!m) return 0; const t = [m.payouts, m.purchase].filter(Boolean); return t.length ? Math.min(...t) : 0; }; + +// ---- scouting score (only real fields; a missing field adds nothing) ---- +function score(c, now) { + let s = 0; + if (c.wallet) s += 30; + if (c.games && Number(c.games.plays) > 0) s += Math.min(40, Number(c.games.plays)); + const seen = Number(c.lastSeen) || 0; + if (seen) { const age = now - seen; s += age < DAY ? 25 : age < 3 * DAY ? 12 : age < 7 * DAY ? 5 : 0; } + if (c.surfWei && BigInt(c.surfWei) > 0n) s += 10; + if (c.games && c.games.earnedWei && BigInt(c.games.earnedWei) > 0n) s += 10; + return s; +} + +// how many adoptions a person has had: every pick here counts, plus the network's count from elsewhere (the tank's own record) +const adoptionCount = (c, picks) => (Number(c.adoptions) || 0) + picks.filter(p => p.person === c.id && p.status !== 'void').length; +const OPEN = ['open']; +// why a tank candidate cannot be drafted right now (null = draftable) +function blocked(c, picks, rules, now) { + if (!c || !c.id) return 'unknown'; + if (c.locked) return 'locked'; // locked on a network contract: never offered + if (c.sponsored) return 'sponsored'; // the hub knows a sponsor for them + if (c.spam || c.throwaway) return 'spam'; // spam / throwaway addresses are skipped + if (c.joinedAt && now - c.joinedAt < rules.graceHours * 3600000) return 'grace'; + if (picks.some(p => p.person === c.id && OPEN.includes(p.status))) return 'taken'; + if (picks.some(p => p.person === c.id && ['done', 'kept'].includes(p.status))) return 'taken'; + if (adoptionCount(c, picks) >= rules.maxAdoptions) return 'adopted-twice'; + return null; +} +// the draftable pool, best scouting score first (ties: newest sign-in, then id, so the order is fixed) +function pool(cands, picks, rules, now) { + return (cands || []).filter(c => !blocked(c, picks, rules, now)) + .map(c => Object.assign({}, c, { score: score(c, now) })) + .sort((a, b) => b.score - a.score || (Number(b.lastSeen) || 0) - (Number(a.lastSeen) || 0) || String(a.id).localeCompare(String(b.id))); +} + +// ---- draft order ---- +function fnv(s) { let h = 0x811c9dc5; for (const ch of String(s)) { h ^= ch.charCodeAt(0); h = Math.imul(h, 0x01000193) >>> 0; } return h; } +// coaches: [{ address, username, since }]; picks carry week, coach, m (milestones). prevWeek = last week's Monday date. +function standings(coaches, picks, week, prevWeek) { + return coaches.map(c => { + const mine = picks.filter(p => p.coach === c.address); + return { address: c.address, username: c.username || null, since: c.since || 0, + lastWeek: mine.filter(p => p.week === prevWeek && started(p.m)).length, + lifetime: mine.filter(p => started(p.m)).length, tie: fnv(week + '|' + c.address) }; + }).sort((a, b) => b.lastWeek - a.lastWeek || b.lifetime - a.lifetime || (a.since || Infinity) - (b.since || Infinity) || a.tie - b.tie); +} + +// a new draft: straight rounds (the earned order every round) +function newDraft(o) { + const slots = []; + for (let r = 1; r <= o.rounds; r++) o.order.forEach((coach, i) => slots.push({ round: r, n: i + 1, coach })); + return { week: o.week, at: o.at, rounds: o.rounds, order: o.order.slice(), standings: o.standings || null, slots, made: [], taken: [], unavailable: [], + status: o.order.length ? 'live' : 'done', clockAt: o.at, doneAt: o.order.length ? null : o.at, poolSize: o.poolSize || 0 }; +} +const slotLabel = s => s.round + '.' + s.n; +const current = d => (d && d.status === 'live' ? d.slots[d.made.length] || null : null); + +// ctx: { pool: [ids, best first], present(addr) -> bool, queue(addr) -> [ids], openCount(addr) -> n, rules: { maxOpen }, pickSeconds } +// -> { type: 'wait', until } | { type: 'auto', slot, coach, person } | { type: 'skip', slot, why } | { type: 'done', why } +function nextAction(d, ctx, now) { + if (!d || d.status !== 'live') return { type: 'done', why: 'not live' }; + const i = d.made.length; if (i >= d.slots.length) return { type: 'done', why: 'all rounds made' }; + const gone = new Set(d.taken.concat(d.unavailable)); + const avail = ctx.pool.filter(id => !gone.has(id)); + if (!avail.length) return { type: 'done', why: 'pool empty' }; + const slot = d.slots[i]; + if (ctx.openCount(slot.coach) >= ctx.rules.maxOpen) return { type: 'skip', slot, why: 'team full' }; + const until = d.clockAt + ctx.pickSeconds * 1000; + if (ctx.present(slot.coach) && now < until) return { type: 'wait', until }; + const q = (ctx.queue(slot.coach) || []).find(id => avail.includes(id)); + return { type: 'auto', slot, coach: slot.coach, person: q || avail[0], fromQueue: !!q }; +} +// a coach on the clock picks by hand -> the same action shape, or { error } +function manual(d, coach, person, ctx, now) { + const slot = current(d); if (!slot) return { error: 'The draft is not live.' }; + if (slot.coach !== coach) return { error: 'You are not on the clock.' }; + const gone = new Set(d.taken.concat(d.unavailable)); + if (gone.has(person) || !ctx.pool.includes(person)) return { error: 'That player is no longer available.' }; + if (ctx.openCount(coach) >= ctx.rules.maxOpen) return { error: 'Your team is full this week.' }; + return { type: 'pick', slot, coach, person, manual: true }; +} +// record what happened for the current slot (the adoption already went through, or was refused) +function record(d, act, res, now) { + if (act.type === 'skip') { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.slot.coach, skipped: act.why, at: now }); d.clockAt = now; } + else if (res && res.ok) { d.made.push({ slot: slotLabel(act.slot), round: act.slot.round, n: act.slot.n, coach: act.coach, person: act.person, auto: act.type === 'auto', fromQueue: !!act.fromQueue, pickId: res.pickId || null, at: now }); d.taken.push(act.person); d.clockAt = now; } + else { d.unavailable.push(act.person); } // the tank refused this person (locked a moment ago, adopted elsewhere): the same coach chooses again + return d; +} +function finish(d, why, now) { d.status = 'done'; d.doneAt = now; d.why = why; return d; } +// run every decision due at `now`; adopt(act) -> { ok, pickId } | { error } (may be async). Returns the draft (mutated). +async function run(d, ctx, adopt, now, maxSteps) { + for (let n = 0; n < (maxSteps || 10000); n++) { + const a = nextAction(d, ctx, now); + if (a.type === 'wait') return d; + if (a.type === 'done') { if (d.status === 'live') finish(d, a.why, now); return d; } + if (a.type === 'skip') { record(d, a, null, now); continue; } + const res = await adopt(a); + record(d, a, res, now); + } + return d; +} + +// ---- pick returns (the rolling pool) ---- +// statusOf(person) -> fresh milestones (or null when the network cannot say: then nothing changes). Returns the changes to apply. +function sweep(picks, statusOf, rules, now) { + const out = []; + for (const p of picks) { + if (p.status !== 'open') continue; + const m = statusOf(p.person); if (!m) continue; + if (started(m)) { out.push({ pick: p, set: { status: 'done', m, tier: tierOf(m), doneAt: now } }); continue; } + if (now < p.expires) { if (JSON.stringify(m) !== JSON.stringify(p.m)) out.push({ pick: p, set: { m, tier: tierOf(m) } }); continue; } + // the window ended unconverted: back to the pool, unless this person has had their adoptions (then they stay with this coach) + const count = (Number(m.adoptions) || 0) + picks.filter(x => x.person === p.person && x.status !== 'void').length; + if (count >= rules.maxAdoptions) out.push({ pick: p, set: { status: 'kept', m, tier: tierOf(m), keptAt: now } }); + else out.push({ pick: p, set: { status: 'returned', m, tier: tierOf(m), returnedAt: now }, release: true }); + } + return out; +} +// may this coach release a pick now? (the IAP churn rule: not inside the hold) +function canRelease(p, rules, now) { if (p.status !== 'open') return 'That pick is not open.'; if (now - p.at < rules.holdHours * 3600000) return 'You picked them less than ' + rules.holdHours + ' hours ago. Give them a little time first.'; return null; } + +// ---- boards ---- +// Best Coach: picks that STARTED inside the week [from, to), per coach. Ties: who got there first, then username. +function bestCoach(picks, from, to, nameOf) { + const by = new Map(); + for (const p of picks) { + const t = startedAt(p.m); if (!t || t < from || t >= to) continue; + const x = by.get(p.coach) || { coach: p.coach, started: 0, lastAt: 0 }; x.started++; x.lastAt = Math.max(x.lastAt, t); by.set(p.coach, x); + } + return [...by.values()].map(x => Object.assign(x, { username: nameOf ? nameOf(x.coach) : null })) + .sort((a, b) => b.started - a.started || a.lastAt - b.lastAt || String(a.username || a.coach).localeCompare(String(b.username || b.coach))) + .map((x, i) => Object.assign(x, { rank: i + 1 })); +} +// Rookie of the Week: of the picks made that week, the one that climbed highest; ties: reached it first, then the pick id +function rookie(picks, week) { + const l = picks.filter(p => p.week === week && p.status !== 'void').map(p => ({ p, t: tierOf(p.m) })).filter(x => x.t !== 'rookie'); + l.sort((a, b) => tierRank(b.t) - tierRank(a.t) || tierAt(a.p.m, a.t) - tierAt(b.p.m, b.t) || a.p.id - b.p.id); + return l.length ? { pick: l[0].p, tier: l[0].t } : null; +} +// the week's pot split into places (percentages of the pot; dust stays in the pot wallet) +function potShares(potWei, split, board) { + const pot = BigInt(potWei || 0); + return split.slice(0, board.length).map((pct, i) => ({ rank: i + 1, coach: board[i].coach, username: board[i].username, pct, wei: (pot * BigInt(Math.round(pct * 100)) / 10000n).toString() })); +} + +// ---- coaching: who to help first, and what to say ---- +const STEPS = [['signedIn', 'Signed in'], ['username', 'Username'], ['wallet', 'Wallet linked'], ['payouts', 'Payouts on'], ['purchase', 'First purchase']]; +function steps(m) { m = m || {}; const done = { signedIn: !!m.lastSeen, username: !!m.username, wallet: !!m.wallet, payouts: !!m.payouts, purchase: !!m.purchase }; + const next = STEPS.find(s => !done[s[0]]); return STEPS.map(s => ({ key: s[0], label: s[1], done: done[s[0]], next: !!next && next[0] === s[0] })); } +function helpList(picks, now) { + return picks.filter(p => p.status === 'open').map(p => { + const m = p.m || {}; const left = p.expires - now; const quiet = m.lastSeen ? now - m.lastSeen : Infinity; + let why, say, urgency; + if (left < DAY) { why = 'Back to the pool in ' + (left < 3600000 ? 'under an hour' : Math.ceil(left / 3600000) + ' hours'); urgency = 100; } + else if (m.wallet && !m.payouts) { why = 'Wallet linked: one step from payouts'; urgency = 80; } + else if (quiet > 2 * DAY) { why = m.lastSeen ? 'Quiet ' + Math.floor(quiet / DAY) + ' days: send a nudge' : 'Has not signed in yet'; urgency = 60; } + else if (!m.wallet) { why = 'Active, no wallet yet'; urgency = 40; } + else { why = 'Doing fine'; urgency = 10; } + const nx = steps(m).find(s => s.next); + say = !nx ? 'Great work. Want to build a team of your own next?' + : nx.key === 'wallet' ? 'Want me to walk you through linking a wallet? SafePal or any other crypto wallet works.' + : nx.key === 'payouts' ? 'Ready to switch on payouts? I will walk you through it.' + : nx.key === 'purchase' ? 'You are set up. When you are ready, I can show you the first purchase step.' + : 'Welcome! I am your coach. Reply here any time and I will help you get going.'; + return { pickId: p.id, person: p.person, username: p.personName || null, why, say, urgency, daysLeft: Math.max(0, Math.ceil(left / DAY)), next: nx ? nx.label : null }; + }).sort((a, b) => b.urgency - a.urgency || a.daysLeft - b.daysLeft || a.pickId - b.pickId); +} + +module.exports = { TIERS, TIER_NAME, tierOf, tierRank, started, startedAt, score, blocked, pool, adoptionCount, standings, newDraft, nextAction, manual, record, finish, run, + current, slotLabel, sweep, canRelease, bestCoach, rookie, potShares, steps, helpList, fnv }; diff --git a/hubline.js b/hubline.js new file mode 100644 index 0000000..5e5e5c2 --- /dev/null +++ b/hubline.js @@ -0,0 +1,40 @@ +// A member's sponsor line from the network hub (the one source of truth, Marty 2026-11-13/14). Walks hubpeople.sponsorOf() +// up to `max` places, nearest first: [{ depth, id, username, wallet }]. Used two ways: +// - position vouchers: the wallets of the line, bound on chain on the buyer's first position (DraftPosition binds link by link) +// - the coach card: who sponsors this coach on the network +// Answers are cached 5 minutes per start person. {ok: false} = the hub did not answer all the way (the line is partial); the +// caller decides (pages fall back to the last good line; vouchers are not signed on a partial line). +'use strict'; +const hubpeople = require('./hubpeople'); + +const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000); +const cache = new Map(); const lastGood = new Map(); + +async function walk(person, max) { + const line = []; const seen = new Set([person.id]); let p = person; + for (let depth = 1; depth <= max; depth++) { + if (!p.sponsor || !p.sponsor.id) return { ok: true, line }; + if (seen.has(p.sponsor.id)) return { ok: true, line, loop: true }; // a loop in the hub data: stop + const r = await hubpeople.sponsorOf(p); if (!r.ok) return { ok: false, line }; + if (!r.person) return { ok: true, line }; + seen.add(r.person.id); + line.push({ depth, id: r.person.id, username: r.person.username ? String(r.person.username) : null, wallet: hubpeople.wallet(r.person) }); + p = r.person; + } + return { ok: true, line }; +} + +// start = { ref: username } | { wallet }. -> { ok, person, line, stale? } +async function lineOf(start, max) { + const k = JSON.stringify(start) + '|' + max; const hit = cache.get(k); + if (hit && Date.now() - hit.at < TTL()) return hit.v; + const me = start.wallet ? await hubpeople.byWallet(start.wallet) : await hubpeople.byRef(start.ref); + let v; + if (!me.ok) v = { ok: false, person: null, line: [] }; + else if (!me.person) v = { ok: true, person: null, line: [] }; + else { const w = await walk(me.person, max); v = { ok: w.ok, person: me.person, line: w.line }; } + if (v.ok) { cache.set(k, { at: Date.now(), v }); lastGood.set(k, v); if (cache.size > 20000) cache.clear(); if (lastGood.size > 20000) lastGood.clear(); return v; } + const lg = lastGood.get(k); return lg ? Object.assign({}, lg, { ok: false, stale: true }) : v; +} + +module.exports = { lineOf, walk, _reset: () => { cache.clear(); lastGood.clear(); } }; diff --git a/hubpeople.js b/hubpeople.js new file mode 100644 index 0000000..32de588 --- /dev/null +++ b/hubpeople.js @@ -0,0 +1,62 @@ +// Network hub lookups (Marty 2026-11-14: "want everything looped through the hub to verify membership"). The hub is the one +// record per person across the network; this asks it who a username, wallet or hub id is: +// POST /v1/resolve {ref: } | {wallet} | {id: 'h_...'} -> {person: view or null} +// signed as HUB_SITE with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)), the same +// scheme as hubreport.js. This site cannot see emails (seeEmails false): a person is {id, username, wallet, sponsor: {id, username}, blocked, ...}. +// Answers (people and misses) are cached HUB_CACHE_MS (5 minutes). A failed call (timeout, refused, any non-200) is never +// cached: it returns {ok: false} so the caller can fall back, and the hub is skipped for 30 seconds so pages never wait on it. +// On unless HUB_LOOKUP=0; needs HUB_URL and a 32+ character HUB_SECRET (HUB_ENABLED only switches the shadow report). +'use strict'; +const crypto = require('crypto'); + +const DEFAULT_SITE = 'fivex'; +const ADDR_RE = /^0x[0-9a-f]{40}$/; +const TTL = () => Number(process.env.HUB_CACHE_MS || 5 * 60000); +const TIMEOUT = () => Number(process.env.HUB_LOOKUP_TIMEOUT_MS || 2500); +const on = () => !/^(0|false|no|off)$/i.test(String(process.env.HUB_LOOKUP || '').trim()) + && !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32; +const cache = new Map(); let downUntil = 0; let lastError = null; const stats = { asked: 0, cached: 0, failed: 0 }; + +async function call(body) { + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex'); + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), TIMEOUT()); + try { + const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + '/v1/resolve', { method: 'POST', body: raw, signal: ac.signal, + headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || DEFAULT_SITE).trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } }); + if (r.status !== 200) throw new Error('hub answered ' + r.status); + const j = await r.json(); + if (!j || typeof j !== 'object' || !('person' in j)) throw new Error('hub answer has no person field'); + return j.person && typeof j.person === 'object' ? j.person : null; + } finally { clearTimeout(t); } +} + +// {ok: true, person: view | null} when the hub answered; {ok: false} when it is off or unreachable (the caller falls back) +async function resolve(body) { + if (!on() || Date.now() < downUntil) return { ok: false }; + const k = JSON.stringify(body); const hit = cache.get(k); + if (hit && Date.now() - hit.at < TTL()) { stats.cached++; return { ok: true, person: hit.person }; } + stats.asked++; + let person; + try { person = await call(body); } catch (e) { + stats.failed++; downUntil = Date.now() + Number(process.env.HUB_DOWN_MS || 30000); + if (!lastError || Date.now() - lastError.at > 600000) console.error('hub lookup failed, falling back:', e.name === 'AbortError' ? 'timeout' : e.message); + lastError = { at: Date.now(), error: e.name === 'AbortError' ? 'timeout' : String(e.message).slice(0, 120) }; + return { ok: false }; + } + if (cache.size > 20000) cache.clear(); + cache.set(k, { at: Date.now(), person }); + if (person && person.id) cache.set(JSON.stringify({ id: person.id }), { at: Date.now(), person }); + return { ok: true, person }; +} + +const wallet = p => (p && ADDR_RE.test(String(p.wallet || '').toLowerCase()) ? String(p.wallet).toLowerCase() : null); +// a username or wallet -> person (a blocked person counts as unknown) +async function byRef(ref) { const r = await resolve({ ref: String(ref || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +async function byWallet(w) { const r = await resolve({ wallet: String(w || '').trim().toLowerCase() }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +async function byId(id) { if (!/^h_[0-9a-f]{16}$/.test(String(id || ''))) return { ok: true, person: null }; const r = await resolve({ id: String(id) }); return r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r; } +// the person's network sponsor as a full person (with wallet), resolved through the hub by hub id. {ok, person: sponsor or null} +async function sponsorOf(p) { if (!p || !p.sponsor || !p.sponsor.id) return { ok: true, person: null }; return byId(p.sponsor.id); } + +function view() { return { on: on(), down: Date.now() < downUntil, cached: cache.size, stats, lastError }; } +module.exports = { resolve, byRef, byWallet, byId, sponsorOf, wallet, view, on, _reset: () => { cache.clear(); downUntil = 0; } }; diff --git a/hubreport.js b/hubreport.js new file mode 100644 index 0000000..f985e74 --- /dev/null +++ b/hubreport.js @@ -0,0 +1,75 @@ +// Network hub report (the Downline Banners / VBB hubreport.js pattern, 2026-11-14). 5xYourTeam coaches are wallets, so every DraftPosition purchase +// goes to the hub by wallet: +// the buyer's first purchase: POST /v1/contract-bind { contract: 'fivex', wallet, sponsorRef: , spentCents, tx, at } +// every later purchase: POST /v1/contract-spend { contract: 'fivex', wallet, cents, tx, at } +// signed as HUB_SITE (default fivex) with HUB_SECRET (X-Hub-Site, X-Hub-Ts, X-Hub-Sig = hex HMAC-SHA256(ts + newline + raw body)). +// One way only: nothing the hub answers changes anything here. A wallet the hub does not know (404) is kept in `unknown` and asked +// again every 6 hours (the member may link it on InstantAdPay later). Off unless HUB_ENABLED=1 with HUB_URL and a 32+ char HUB_SECRET. +// State lives in hubreport.json (a MySQL document through docstore when DOCSTORE_URL is set). +'use strict'; +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const CONTRACT = 'fivex'; +const ZERO = '0x0000000000000000000000000000000000000000'; +const enabled = () => /^(1|true|yes|on)$/i.test(String(process.env.HUB_ENABLED || '').trim()) + && !!String(process.env.HUB_URL || '').trim() && String(process.env.HUB_SECRET || '').trim().length >= 32; +const RECHECK = 6 * 3600000; +let R = null, st = null, busy = false; +const FILE = () => path.join(R.dataDir, 'hubreport.json'); +function load() { + if (st) return st; + try { st = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { st = {}; } + st.sent = st.sent || {}; st.bound = st.bound || {}; st.unknown = st.unknown || {}; st.errors = st.errors || {}; st.log = st.log || []; + return st; +} +function save() { try { fs.writeFileSync(FILE() + '.tmp', JSON.stringify(load())); fs.renameSync(FILE() + '.tmp', FILE()); } catch (e) { console.error('hubreport save', e.message); } } +function note(x) { const s = load(); s.log.push(Object.assign({ ts: Date.now() }, x)); if (s.log.length > 200) s.log = s.log.slice(-200); } + +async function post(route, body) { + const raw = JSON.stringify(body); const ts = String(Date.now()); + const sig = crypto.createHmac('sha256', String(process.env.HUB_SECRET).trim()).update(ts + '\n' + raw).digest('hex'); + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 15000); + try { + const r = await fetch(String(process.env.HUB_URL).trim().replace(/\/+$/, '') + route, { method: 'POST', body: raw, signal: ac.signal, + headers: { 'Content-Type': 'application/json', 'X-Hub-Site': String(process.env.HUB_SITE || 'fivex').trim(), 'X-Hub-Ts': ts, 'X-Hub-Sig': sig } }); + let j = null; try { j = await r.json(); } catch (e) {} + return { status: r.status, body: j }; + } finally { clearTimeout(t); } +} + +async function tick() { + if (!enabled() || busy) return; busy = true; + try { + const s = load(); const now = Date.now(); + const list = R.purchases().slice().sort((a, b) => (a.block || 0) - (b.block || 0) || (a.at || 0) - (b.at || 0)); + for (const p of list) { + if (s.sent[p.key]) continue; + const a = p.buyer; + if (s.unknown[a] && now - s.unknown[a].at < RECHECK) continue; + const tx = String(p.key).split(':')[0]; + const bind = !s.bound[a]; + const body = bind + ? { contract: CONTRACT, wallet: a, sponsorRef: p.sponsor && p.sponsor !== ZERO ? p.sponsor : '', spentCents: p.usdCents || 0, tx, at: p.at || now } + : { contract: CONTRACT, wallet: a, cents: p.usdCents || 0, tx, at: p.at || now }; + let r; try { r = await post(bind ? '/v1/contract-bind' : '/v1/contract-spend', body); } + catch (e) { s.errors[p.key] = { at: now, error: e.message }; break; } // hub unreachable: try again next tick + if (r.status === 200) { s.sent[p.key] = { at: now, route: bind ? 'bind' : 'spend' }; if (bind) s.bound[a] = now; delete s.unknown[a]; delete s.errors[p.key]; note({ sent: p.key, bind }); } + else if (r.status === 404) { s.unknown[a] = { at: now, sponsor: p.sponsor || null }; note({ unknown: a }); } + else { s.errors[p.key] = { at: now, status: r.status, error: r.body && (r.body.error || r.body.message) }; note({ error: p.key, status: r.status }); if (r.status >= 500) break; } + } + save(); + } finally { busy = false; } +} + +// deps: { dataDir, purchases: () => [{ key, buyer, sponsor, usdCents, block, at }] } +function init(deps) { + R = deps; if (!enabled()) return; load(); save(); + const every = Math.max(200, Number(process.env.HUB_TICK_MS) || 60000); + setTimeout(() => tick().catch(e => console.error('hubreport', e.message)), Math.min(20000, every)).unref(); + setInterval(() => tick().catch(e => console.error('hubreport', e.message)), every).unref(); +} +function view() { if (!R) return { enabled: false }; const s = load(); return { enabled: enabled(), site: String(process.env.HUB_SITE || 'fivex').trim(), sent: Object.keys(s.sent).length, bound: Object.keys(s.bound).length, unknown: s.unknown, errors: s.errors, log: s.log.slice(-30) }; } + +module.exports = { init, tick, view, enabled, CONTRACT }; diff --git a/league.js b/league.js new file mode 100644 index 0000000..182b290 --- /dev/null +++ b/league.js @@ -0,0 +1,150 @@ +// The league: the draft engine (draft.js, pure) wired to the store and the holding tank (tankpool.js). One tick at a time: +// 1. sweep the open picks: fresh milestones from the tank; started picks stay (done), unconverted ones past the return window go +// back to the pool (or stay with the coach once the person has had their 2 adoptions) +// 2. on draft day at the draft hour (Central): create the week's draft from the earned order and the pool snapshot +// 3. while the draft is live: run every decision that is due (a coach in the room gets the clock, an absent coach is auto-picked) +// 4. when it finishes: the Draft Day card (proof.js, the outbox in phase 1) +// Every pick goes through tank.adopt() first; a pick is recorded only when the adoption went through. +// The clock is injectable (clock.now()): tests move it with POST /api/admin/clock when ALLOW_TEST_CLOCK=1 (never in production). +'use strict'; +const store = require('./store'); +const draft = require('./draft'); +const tank = require('./tankpool'); + +const D = 86400000; +let C = null, proof = null, offset = 0, busy = Promise.resolve(), cands = [], candsAt = 0; +const clock = { now: () => Date.now() + offset, set: t => { offset = t - Date.now(); }, offset: () => offset }; +const rules = () => ({ maxOpen: C.picks.maxOpen, maxAdoptions: C.picks.maxAdoptions, graceHours: C.picks.graceHours, holdHours: C.picks.holdHours, returnDays: C.picks.returnDays }); +const lock = fn => { const r = busy.then(fn, fn); busy = r.catch(() => {}); return r; }; +function init(cfg, deps) { C = cfg; proof = deps.proof; } + +// ---- weeks (Central) ---- +function weekInfo(now) { + const week = store.ctWeek(now); + const at = w => store.ctToMs(store.addDays(w, (C.draft.dow + 6) % 7), C.draft.hour); // dow 1 = Monday = the week's first day + const draftAt = at(week); const next = at(store.addDays(week, 7)); + return { week, prevWeek: store.addDays(week, -7), nextWeek: store.addDays(week, 7), draftAt, nextDraftAt: now < draftAt ? draftAt : next, + from: store.ctToMs(week, 0), to: store.ctToMs(store.addDays(week, 7), 0) }; +} +const nameOf = a => { const m = store.member(a); return m && m.username ? m.username : null; }; +const openCount = a => store.picksOf(a).filter(p => p.status === 'open').length; + +// ---- the pool ---- +async function candidates(now, fresh) { + if (fresh || now - candsAt > 15000 || !cands.length) { try { cands = await tank.candidates(now); candsAt = now; } catch (e) { console.error('tank candidates', e.message); } } + return cands; +} +async function pool(now) { return draft.pool(await candidates(now), store.picks(), rules(), now); } +const ownTeam = id => { const m = store.memberByHub(id); return m && store.positionsOf(m.address) > 0 ? (store.firstPositionAt(m.address) || 1) : 0; }; + +// ---- a pick = an adoption ---- +async function makePick(coach, person, kind, extra, now) { + const c = cands.find(x => x.id === person) || { id: person }; + const r = await tank.adopt({ coach: { address: coach, username: nameOf(coach), hubId: (store.member(coach) || {}).hubId || null }, person, kind }); + if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' }; + const s = (await tank.status([person], now))[person] || {}; + const m = Object.assign({ lastSeen: s.lastSeen || 0, username: s.username || c.username || null, wallet: s.wallet || 0, payouts: s.payouts || 0, purchase: s.purchase || 0, ownTeam: ownTeam(person) }, { door: s.door || c.door || null, games: s.games || c.games || null, surfWei: s.surfWei || c.surfWei || null }); + const p = store.addPick(Object.assign({ week: weekInfo(now).week, kind, coach, coachName: nameOf(coach), person, personName: c.username || s.username || null, door: c.door || null, + status: 'open', at: now, expires: now + C.picks.returnDays * D, m, tier: draft.tierOf(m), ref: r.ref || null }, extra || {})); + candsAt = 0; // the pool changed + store.bump('picks'); + return { ok: true, pickId: p.id, pick: p }; +} + +// ---- 1. sweep ---- +async function sweep(now) { + const open = store.picks().filter(p => p.status === 'open' || p.status === 'done' || p.status === 'kept'); + if (!open.length) return { changed: 0 }; + const ids = [...new Set(open.map(p => p.person))]; + const sts = await tank.status(ids, now); + const statusOf = id => { const s = sts[id]; if (!s) return null; return Object.assign({}, s, { ownTeam: ownTeam(id) }); }; + // done / kept picks only refresh their milestones (cards keep levelling up) + for (const p of open.filter(x => x.status !== 'open')) { const m = statusOf(p.person); if (m) { const t = draft.tierOf(m); if (t !== p.tier || JSON.stringify(m) !== JSON.stringify(p.m)) { if (t !== p.tier) p.levelAt = now; p.m = m; p.tier = t; store.savePick(p); } } } + const ch = draft.sweep(store.picks(), statusOf, rules(), now); + for (const c of ch) { + if (c.release) { const r = await tank.release({ coach: c.pick.coach, person: c.pick.person, why: 'return window ended' }); if (!r || !r.ok) continue; } + if (c.set.tier && c.set.tier !== c.pick.tier) c.pick.levelAt = now; // the toast time, on the league clock + Object.assign(c.pick, c.set); store.savePick(c.pick); + } + if (ch.length) candsAt = 0; + return { changed: ch.length }; +} + +// ---- 2 + 3. the draft ---- +function ctx(d, now) { + return { pool: d.poolIds || [], present: a => { const m = store.member(a); return !!(m && m.presenceAt && now - m.presenceAt < C.draft.presenceSeconds * 1000); }, + queue: a => (store.member(a) || {}).queue || [], openCount, rules: rules(), pickSeconds: C.draft.pickSeconds }; +} +async function ensureDraft(now) { + const w = weekInfo(now); + if (now < w.draftAt || store.draft(w.week)) return store.draft(w.week); + if (now > w.draftAt + C.draft.lateHours * 3600000) return null; // the app was down through draft time: that week is skipped, never run late + const coaches = store.coaches().map(m => ({ address: m.address, username: m.username, since: store.firstPositionAt(m.address) })); + const stand = draft.standings(coaches, store.picks(), w.week, w.prevWeek); + const pl = await pool(now); + const d = draft.newDraft({ week: w.week, at: now, rounds: C.draft.rounds, order: stand.map(s => s.address), standings: stand.map(s => ({ address: s.address, username: s.username, lastWeek: s.lastWeek, lifetime: s.lifetime })), poolSize: pl.length }); + d.poolIds = pl.map(c => c.id); + store.putDraft(d); + console.log('draft: week', w.week, 'started with', stand.length, 'coaches,', pl.length, 'in the pool'); + return d; +} +async function advance(d, now) { + if (!d || d.status !== 'live') return d; + await candidates(now); + const was = d.status; + await draft.run(d, ctx(d, now), act => makePick(act.coach, act.person, 'draft', { slot: draft.slotLabel(act.slot), round: act.slot.round, auto: act.type === 'auto' }, now), now); + store.putDraft(d); + if (was === 'live' && d.status === 'done') { + const rows = d.made.filter(x => x.person).map(x => ({ slot: x.slot, coach: nameOf(x.coach), person: (store.pick(x.pickId) || {}).personName || null })); + const w = weekInfo(now); + proof && proof.draftDay(d, rows, { players: rows.length, coaches: d.order.length, potWei: proof.potOf(w.from, w.to) }).catch(() => {}); + } + return d; +} +async function tick() { + return lock(async () => { + const now = clock.now(); + const s = await sweep(now).catch(e => { console.error('sweep', e.message); return { changed: 0 }; }); + let d = await ensureDraft(now).catch(e => { console.error('draft create', e.message); return null; }); + d = await advance(d, now).catch(e => { console.error('draft run', e.message); return d; }); + return { swept: s.changed, draft: d ? { week: d.week, status: d.status, made: d.made.length } : null }; + }); +} +// a coach on the clock picks by hand +async function manualPick(coach, person) { + return lock(async () => { + const now = clock.now(); const d = store.draft(weekInfo(now).week); + if (!d || d.status !== 'live') return { error: 'The draft is not live right now.' }; + await candidates(now); + const act = draft.manual(d, coach, person, ctx(d, now), now); if (act.error) return act; + const res = await makePick(coach, person, 'draft', { slot: draft.slotLabel(act.slot), round: act.slot.round, auto: false }, now); + draft.record(d, act, res, now); store.putDraft(d); + if (res.error) return res; + await advance(d, now); + return { ok: true, pickId: res.pickId }; + }); +} +// instant picks: 5 per position, from the current pool, any time outside a live draft +async function instantPick(coach, person) { + return lock(async () => { + const now = clock.now(); const d = store.draft(weekInfo(now).week); + if (d && d.status === 'live') return { error: 'The draft is live. Instant picks open again when it ends.' }; + if (store.credits(coach) < 1) return { error: 'You have no instant picks left. Your next picks come in the Monday draft.' }; + if (openCount(coach) >= C.picks.maxOpen) return { error: 'Your team is full (' + C.picks.maxOpen + ' open picks). Help one get started first.' }; + const pl = await pool(now); if (!pl.some(c => c.id === person)) return { error: 'That player is no longer available.' }; + const res = await makePick(coach, person, 'instant', {}, now); if (res.error) return res; + store.addCredits(coach, -1); + return { ok: true, pickId: res.pickId, credits: store.credits(coach) }; + }); +} +async function release(coach, pickId) { + return lock(async () => { + const now = clock.now(); const p = store.pick(pickId); + if (!p || p.coach !== coach) return { error: 'Not your pick.' }; + const why = draft.canRelease(p, rules(), now); if (why) return { error: why }; + const r = await tank.release({ coach, person: p.person, why: 'released by the coach' }); if (!r || !r.ok) return { error: (r && r.error) || 'The holding tank did not answer.' }; + p.status = 'returned'; p.releasedAt = now; p.released = true; store.savePick(p); candsAt = 0; + return { ok: true }; + }); +} +module.exports = { init, clock, tick, sweep, ensureDraft, advance, manualPick, instantPick, release, pool, candidates, weekInfo, rules, openCount, nameOf }; diff --git a/netsites.js b/netsites.js new file mode 100644 index 0000000..218c332 --- /dev/null +++ b/netsites.js @@ -0,0 +1,63 @@ +// 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, ViralAdBlitz, 5xYourTeam, Stack POL). +// 5xYourTeam: its 'fivex' entry and the LinkSpin code nw5x are local until the hub list and LinkSpin netlinks.js add them (phase 2). +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: 'viraladblitz', name: 'ViralAdBlitz', url: 'https://viraladblitz.com' }, + { id: 'fivex', name: '5xYourTeam', url: 'https://5xyourteam.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=, 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', viraladblitz: 'nwvab', fivex: 'nw5x', 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 }; diff --git a/networksso.js b/networksso.js new file mode 100644 index 0000000..9360e02 --- /dev/null +++ b/networksso.js @@ -0,0 +1,230 @@ +// Network sign-in between InstantAdPay and LinkSpin (Marty approved 2026-11-12). The SAME file ships in both repos; each +// server calls init({ self, peer, peerBase, ... hooks }) and hands every request to handle() before its own routes. +// +// One flow, used two ways. R = the site the member is going TO (receiver), P = the site they are signed in on (provider). +// 1. R GET /sso/start?mode=go|check&to=/path R makes a random state, keeps it in a 5-minute HttpOnly cookie (nsso.st), +// sets the loop guard (nsso.tried, 30 minutes) and sends the browser to P. +// 2. P GET /sso/check?st=&to=/path P looks at its OWN member session (never the admin portal). Signed in: +// P mints a token bound to R, the state and the email, and sends the browser +// to R /sso/in?t=. Not signed in: R /sso/in?none=1&to=/path. +// 3. R GET /sso/in?t= R checks signature, audience, expiry (60 s), the state against its cookie +// (so nobody can push their own token into someone else's browser), and spends +// the nonce (a second use is refused). The email must already be a member +// here; then R makes an ordinary session and redirects to the relative path. +// Outbound links: P GET /go/?to=/path is the hop a signed-in member's cross-site link points at. Signed out (or the +// secret not set), it is a plain redirect to the other site, so it is always safe to link through. +// Silent check: R's sign-in page calls GET /api/sso/status; { check: true } means "bounce once through P". The guard cookie +// stops a second bounce for 30 minutes, signing out sets nsso.off (12 hours, cleared by the next deliberate cross-site link), +// bots and non-page fetches never bounce. +// Token: "v1..", JSON = { iss, aud, email, +// st, to, iat, exp, n[, wallet, name] }. The token grants a plain member session and nothing else: no wallet action, payout or purchase rides on it. +// +// Wallet sites (Downline Banners, 2026-11-13, Marty: "sign in once and be logged into all these sites"). Downline Banners has no email +// accounts; its members are wallets. IAP and LinkSpin list it under `wallets: { bannerline: base }` and vouch one way: /go/bannerline +// and /sso/check?r=bannerline mint a token that also carries the member's wallet (the one they signed in with, else the main wallet +// their account linked by signature) and username. Downline Banners runs this file with `from: { iap, linkspin }`, accepts a token from +// either, and makes a session for that wallet. /sso/start?via= picks which site to ask; old copies ignore the new parameters. +'use strict'; +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const SECRET = () => String(process.env.NETWORK_SSO_SECRET || '').trim(); +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', viraladblitz: 'ViralAdBlitz', fivex: '5xYourTeam' }; // vbb = Viral Banner Blitz, a wallet site like Downline Banners (2026-11-14); viraladblitz = ViralAdBlitz, a wallet site like VBB (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, + // wallets?: { site: base() } + wallet(session) -> { address, name }, from?: { site: base() } } + +const b64u = buf => Buffer.from(buf).toString('base64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_'); +const unb64u = s => Buffer.from(String(s).replace(/-/g, '+').replace(/_/g, '/'), 'base64'); +const mac = s => crypto.createHmac('sha256', SECRET()).update('nsso.v1.' + s).digest(); +const mask = e => String(e || '').replace(/^(.).*(@.*)$/, '$1***$2'); +const log = (what, email, extra) => console.log('network-sso', what, email ? mask(email) : '-', extra || ''); + +// a same-site relative path, or the default. No scheme, no host, no protocol-relative //x, no backslashes, no control characters. +function safePath(to, dflt) { + const d = dflt == null ? '/' : dflt; + const s = String(to == null ? '' : to); + if (!s || s.length > 600 || s[0] !== '/' || s[1] === '/' || s[1] === '\\' || /[\\\u0000-\u001f\u007f\s]/.test(s)) return d; + try { const x = new URL(s, 'http://x.invalid'); if (x.host !== 'x.invalid' || x.protocol !== 'http:') return d; return x.pathname + x.search + x.hash; } catch (e) { return d; } +} + +function mint(o) { + const now = o.now || Date.now(); + const t = { iss: o.iss, aud: o.aud, email: String(o.email || '').trim().toLowerCase(), st: o.st, to: safePath(o.to), iat: now, exp: now + TTL, n: crypto.randomBytes(16).toString('hex') }; + if (o.wallet) t.wallet = String(o.wallet).toLowerCase(); + if (o.name) t.name = String(o.name).slice(0, 40); + const body = b64u(JSON.stringify(t)); + return 'v1.' + body + '.' + b64u(mac(body)); +} + +// -> { ok, email, to, n, exp } or { error: reason } +function verify(tok, o) { + if (!enabled()) return { error: 'off' }; + const m = /^v1\.([A-Za-z0-9_-]{20,2000})\.([A-Za-z0-9_-]{43})$/.exec(String(tok || '')); + if (!m) return { error: 'malformed' }; + const want = mac(m[1]), got = unb64u(m[2]); + if (want.length !== got.length || !crypto.timingSafeEqual(want, got)) return { error: 'signature' }; + let p; try { p = JSON.parse(unb64u(m[1]).toString('utf8')); } catch (e) { return { error: 'malformed' }; } + const now = (o && o.now) || Date.now(); + if (!p || p.aud !== o.aud || ![].concat(o.iss).includes(p.iss)) return { error: 'audience' }; + if (!(Number(p.exp) > now) || Number(p.iat) > now + SKEW || Number(p.exp) - Number(p.iat) > TTL) return { error: 'expired' }; + if (!/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(String(p.email || ''))) return { error: 'email' }; + if (!/^[a-f0-9]{32}$/.test(String(p.n || ''))) return { error: 'malformed' }; + const st = String((o && o.st) || ''); + if (!/^[a-f0-9]{32}$/.test(st) || !/^[a-f0-9]{32}$/.test(String(p.st || '')) || !crypto.timingSafeEqual(Buffer.from(st), Buffer.from(p.st))) return { error: 'state' }; + if (p.wallet != null && !WALLET_RE.test(String(p.wallet))) return { error: 'wallet' }; + const name = p.name != null && /^[A-Za-z0-9_.-]{1,40}$/.test(String(p.name)) ? String(p.name) : null; + return { ok: true, iss: p.iss, email: String(p.email).toLowerCase(), wallet: p.wallet || null, name, to: safePath(p.to), n: p.n, exp: Number(p.exp) }; +} + +// single use: true the first time a nonce is spent. MySQL when the site runs on it (two app copies during a deploy share it), +// else memory + a small file in DATA_DIR (survives a restart inside the 60-second window). +const used = new Map(); let fileLoaded = false, tableReady = null; +const FILE = () => C && C.dataDir ? path.join(C.dataDir, 'network-sso-nonces.json') : null; +function prune(now) { for (const [k, exp] of used) if (exp < now) used.delete(k); } +function loadFile() { + if (fileLoaded) return; fileLoaded = true; + try { const o = JSON.parse(fs.readFileSync(FILE(), 'utf8')); for (const k of Object.keys(o)) used.set(k, Number(o[k])); } catch (e) {} +} +function saveFile() { const f = FILE(); if (!f) return; try { fs.writeFileSync(f + '.tmp', JSON.stringify(Object.fromEntries(used))); fs.renameSync(f + '.tmp', f); } catch (e) { console.error('network-sso nonce save', e.message); } } +async function spend(n, exp) { + const now = Date.now(); loadFile(); prune(now); + if (used.has(n)) return false; + used.set(n, Number(exp) + SKEW); saveFile(); + const db = C && C.db; + if (db && db.enabled && db.enabled()) { + try { + if (!tableReady) tableReady = db.q('CREATE TABLE IF NOT EXISTS network_sso_nonces (n VARCHAR(40) PRIMARY KEY, exp BIGINT NOT NULL) ENGINE=InnoDB').catch(e => { tableReady = null; throw e; }); + await tableReady; + await db.q('INSERT INTO network_sso_nonces (n, exp) VALUES (?, ?)', [n, Number(exp) + SKEW]); + if (Math.random() < 0.05) db.q('DELETE FROM network_sso_nonces WHERE exp < ?', [now]).catch(() => {}); + } catch (e) { if (/duplicate/i.test(e.message || '') || e.code === 'ER_DUP_ENTRY') return false; console.error('network-sso nonce db', e.message); return false; } // fail closed + } + return true; +} + +// crawlers, link previews and headless browsers never bounce +const BOT_RE = /bot|crawl|spider|slurp|preview|facebookexternalhit|embedly|quora link|whatsapp|telegram|discord|skype|curl|wget|python|httpclient|headless|lighthouse|pingdom|monitor|go-http|java\/|okhttp|axios|node-fetch|undici/i; +const isBot = req => { const ua = String(req.headers['user-agent'] || ''); return !ua || BOT_RE.test(ua); }; +// only a real top-level page load may start a bounce (sec-fetch-dest is sent by every current browser) +const notPage = req => { const d = req.headers['sec-fetch-dest']; return !!d && d !== 'document'; }; + +function cookies(req) { + const out = {}; + for (const p of String(req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { out[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } + return out; +} +const ck = (k, v, age, httpOnly) => k + '=' + encodeURIComponent(v) + '; Path=/; SameSite=Lax; Max-Age=' + age + (httpOnly ? '; HttpOnly' : '') + (C && C.isProd ? '; Secure' : ''); +const go = (res, loc, set) => { const h = { Location: loc, 'Cache-Control': 'no-store', 'Referrer-Policy': 'no-referrer', 'X-Robots-Tag': 'noindex' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(302, h); res.end(); return true; }; +const sendJson = (res, obj, set) => { const h = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }; if (set && set.length) h['Set-Cookie'] = set; res.writeHead(200, h); res.end(JSON.stringify(obj)); return true; }; + +function init(opts) { C = Object.assign({ defaultPath: '/' }, opts); fileLoaded = false; used.clear(); } + +// the cookie a sign-out adds: no silent check on this site for 12 hours (a deliberate cross-site link still signs in) +const offCookie = () => ck('nsso.off', '1', OFF_AGE, true); + +// -> true when the request was one of ours and has been answered +async function handle(req, res, u) { + if (!C || req.method !== 'GET') return false; + const p = u.pathname; + const peerName = NAMES[C.peer] || C.peer; + const goTo = p.startsWith('/go/') ? p.slice(4) : ''; + const walletBase = x => (C.wallets && Object.prototype.hasOwnProperty.call(C.wallets, x) ? C.wallets[x] : null); + if (goTo && (goTo === C.peer || walletBase(goTo))) { + const base = goTo === C.peer ? C.peerBase() : walletBase(goTo)(); + const to = safePath(u.searchParams.get('to'), '/'); + const plain = base + to; + if (!enabled() || isBot(req)) return go(res, plain); + let s = null; try { s = await C.member(req); } catch (e) {} + if (!s || !s.email) return go(res, plain); + if (goTo !== C.peer) { let w = null; try { w = await C.wallet(s); } catch (e) {} if (!w || !w.address) return go(res, plain); } // no wallet to vouch for: a plain link + return go(res, base + '/sso/start?mode=go' + (goTo === C.peer ? '' : '&via=' + C.self) + '&to=' + encodeURIComponent(to)); + } + if (p === '/sso/start') { + const to = safePath(u.searchParams.get('to'), C.defaultPath); + const mode = u.searchParams.get('mode') === 'go' ? 'go' : 'check'; + const via = String(u.searchParams.get('via') || ''); + const from = C.from && Object.prototype.hasOwnProperty.call(C.from, via) ? C.from[via] : null; // a wallet site may ask either provider + if (!enabled() || isBot(req) || notPage(req)) return go(res, to); + let s = null; try { s = await C.member(req); } catch (e) {} + if (s && (s.email || s.address)) return go(res, to); // already signed in here + 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, 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) + (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') || ''); + const to = safePath(u.searchParams.get('to'), '/'); + const r = String(u.searchParams.get('r') || ''); + const wb = r && r !== C.peer ? walletBase(r) : null; // a wallet site asking: the token carries the wallet + const base = wb ? wb() : C.peerBase(), aud = wb ? r : C.peer, forName = NAMES[aud] || aud; + 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) { + 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); + return go(res, base + '/sso/in?t=' + mint({ iss: C.self, aud, email: s.email, wallet: w && w.address, name: w && w.name, st, to })); + } + if (p === '/sso/in') { + const c = cookies(req); + const set = [ck('nsso.st', '', 0, true)]; + if (u.searchParams.get('none')) { log('none: not signed in on ' + peerName); return go(res, C.signinPath(safePath(u.searchParams.get('to'), C.defaultPath)), set); } + const v = verify(u.searchParams.get('t'), { iss: [C.peer].concat(Object.keys(C.from || {})), aud: C.self, st: c['nsso.st'] }); + if (v.error) { log('refused: ' + v.error); return go(res, C.signinPath(C.defaultPath), set); } + if (!(await spend(v.n, v.exp))) { log('refused: token already used', v.email); return go(res, C.signinPath(v.to), set); } + let a = null; try { a = await C.accept(v.email, req, v); } catch (e) { a = { fallback: 'error ' + e.message }; } + if (!a || !a.ok) { // not a member here yet (or not allowed to sign in): the normal email-code sign-in, email filled in + log('fallback to email code: ' + ((a && a.fallback) || 'not accepted'), v.email); + set.push(ck('nsso.hint', v.email, HINT_AGE, true)); + return go(res, C.signinPath(v.to), set); + } + let cookie = null; try { cookie = await C.signIn(v.email, req, v); } catch (e) { console.error('network-sso sign-in', e.message); } + if (!cookie) { log('fallback to email code: session not made', v.email); return go(res, C.signinPath(v.to), set); } + set.push(cookie); if (c['nsso.off']) set.push(ck('nsso.off', '', 0, true)); + log('signed in from ' + (NAMES[v.iss] || peerName), v.email); + return go(res, C.landing(v.to === '/' ? C.defaultPath : v.to), set); // no page named: the dashboard, not the public home page (2026-11-13) + } + if (p === '/api/sso/status') { + const c = cookies(req); const set = []; + let s = null; try { s = await C.member(req); } catch (e) {} + const signedIn = !!(s && (s.email || s.address)); + const out = { peer: peerName, check: enabled() && !signedIn && !isBot(req) && !c['nsso.tried'] && !c['nsso.off'] }; + if (c['nsso.hint']) { if (!signedIn) out.hint = c['nsso.hint']; set.push(ck('nsso.hint', '', 0, true)); } + return sendJson(res, out, set); + } + return false; +} + +// 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 }; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f9cbe8c --- /dev/null +++ b/package-lock.json @@ -0,0 +1,240 @@ +{ + "name": "5xyourteam", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "5xyourteam", + "version": "0.1.0", + "dependencies": { + "ethers": "^6.13.0", + "mysql2": "^3.11.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@adraffy/ens-normalize": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@adraffy/ens-normalize/-/ens-normalize-1.11.1.tgz", + "integrity": "sha512-nhCBV3quEgesuf7c7KYfperqSS14T8bYuvJ8PcLJp6znkZpFc0AuW4qBtr8eKVyPPe/8RSr7sglCWPU5eaxwKQ==", + "license": "MIT" + }, + "node_modules/@noble/curves": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@noble/curves/-/curves-1.2.0.tgz", + "integrity": "sha512-oYclrNgRaM9SsBUBVbb8M6DTV7ZHRTKugureoYEncY5c65HOmRzvSiTE3y5CYaPYJA/GVkrhXEoF0M3Ya9PMnw==", + "license": "MIT", + "dependencies": { + "@noble/hashes": "1.3.2" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@noble/hashes": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-1.3.2.tgz", + "integrity": "sha512-MVC8EAQp7MvEcm30KWENFjgR+Mkmf+D189XJTkFIlwohU5hcBbn1ZkKq7KVTi2Hme3PMGF390DaL52beVrIihQ==", + "license": "MIT", + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + } + }, + "node_modules/@types/node": { + "version": "22.7.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.7.5.tgz", + "integrity": "sha512-jML7s2NAzMWc//QSJ1a3prpk78cOPchGvXJsC3C6R6PSMoooztvRVQEz89gmBTBY1SPMaqo5teB4uNHPdetShQ==", + "license": "MIT", + "dependencies": { + "undici-types": "~6.19.2" + } + }, + "node_modules/aes-js": { + "version": "4.0.0-beta.5", + "resolved": "https://registry.npmjs.org/aes-js/-/aes-js-4.0.0-beta.5.tgz", + "integrity": "sha512-G965FqalsNyrPqgEGON7nIx1e/OVENSgiEIzyC63haUMuvNnwIgIjMs52hlTCKhkBny7A2ORNlfY9Zu+jmGk1Q==", + "license": "MIT" + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/ethers": { + "version": "6.17.0", + "resolved": "https://registry.npmjs.org/ethers/-/ethers-6.17.0.tgz", + "integrity": "sha512-BpyrpIPJ3ydEVow8zGaz1DuPS7YU8DcWxuBnY9a0UA/lvAPwrMr+EPXsfrul628SRaekPNeIM4UFh/91GWZang==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/ethers-io/" + }, + { + "type": "individual", + "url": "https://www.buymeacoffee.com/ricmoo" + } + ], + "license": "MIT", + "dependencies": { + "@adraffy/ens-normalize": "1.11.1", + "@noble/curves": "1.2.0", + "@noble/hashes": "1.3.2", + "@types/node": "22.7.5", + "aes-js": "4.0.0-beta.5", + "tslib": "2.7.0", + "ws": "8.21.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "license": "Apache-2.0" + }, + "node_modules/lru.min": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz", + "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/mysql2": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", + "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==", + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.3", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.5.1" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "license": "MIT" + }, + "node_modules/sql-escaper": { + "version": "1.5.2", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.2.tgz", + "integrity": "sha512-6CKD38c31SENivxOADeMNLdukOnUxUcflKtzVWzace7Riv1v7cAEym5Cx9Q7gYZ3ezIJI7ZpqecQq8cqNeSSFg==", + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, + "node_modules/tslib": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.7.0.tgz", + "integrity": "sha512-gLXCKdN1/j47AiHiOkJN69hJmcbGTHI0ImLmbYLHykhgeN0jVGola9yVjFgzCUklsZQMW55o+dW7IXv3RCXDzA==", + "license": "0BSD" + }, + "node_modules/undici-types": { + "version": "6.19.8", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz", + "integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==", + "license": "MIT" + }, + "node_modules/ws": { + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..258433f --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "5xyourteam", + "version": "0.1.0", + "private": true, + "description": "5xYourTeam (5xyourteam.com rebuild): The Draft. A $10 one-time position = 5 picks right away + a draft spot every week; coaches draft people waiting in the network holding tank every Monday, draft order earned by last week's started picks. DraftPosition split on-chain: sponsor 25%, levels 2-5 5% each, 10% Best Coach pot, 45% company.", + "main": "server.js", + "scripts": { + "start": "node server.js", + "test": "node qa/unit.test.cjs", + "qa": "node qa/smoke.mjs" + }, + "engines": { "node": ">=20" }, + "dependencies": { + "ethers": "^6.13.0", + "mysql2": "^3.11.0" + } +} diff --git a/promokit.js b/promokit.js new file mode 100644 index 0000000..b3b8f49 --- /dev/null +++ b/promokit.js @@ -0,0 +1,99 @@ +// Promo kit (the VBB / ViralAdBlitz pattern): the ONE place the 5xYourTeam creatives and swipe copy live. Published as a public JSON +// feed, GET /api/promo-kit?u=, read by /promote and by InstantAdPay's promo center ("Network sites"). +// Facts come from config.js (position price, picks on buy, split). Copy rules: a position buys a seat in the draft, not income; +// nothing is promised; no em dashes; no earnings caps; wallets = "SafePal or any other crypto wallet"; never a subscription. +// Creatives: public/art/kit/fx--.png, rendered by tools/art.mjs (neutral names: no size tokens, no ad words). +'use strict'; +const fs = require('fs'); +const path = require('path'); +const C = require('./config').get(); +const netsites = require('./netsites'); + +const KIT_DIR = path.join(__dirname, 'public', 'art', 'kit'); +const SHAPES = { tile: [125, 125, 'Square button'], strip: [468, 60, 'Strip'], leader: [728, 90, 'Leaderboard'], box: [300, 250, 'Box'], + tower: [160, 600, 'Skyscraper'], social: [1200, 630, 'Social share'], square: [1080, 1080, 'Square post'] }; +const ANGLES = { draft: 'The weekly draft', coach: 'Coach your picks', cards: 'Trading cards that level up' }; + +function copy() { + const p = C.position; + const seat = '$' + p.usd + ' one-time position gives you ' + p.picksOnBuy + ' picks right away and a draft spot every week'; + return { + lines: [ + 'Every Monday the coaches on 5xYourTeam draft people who joined the network without a sponsor. A ' + seat + '. {{LINK}}', + 'Draft order is earned: help last week\'s picks get started and you pick first next Monday. {{LINK}}', + 'Your picks show up as trading cards that level up as they do: Rookie, Starter, Pro, All-Star, Hall of Fame. {{LINK}}', + 'You get the right to sponsor and help, never anyone\'s contact details. Coaching happens in site messages. {{LINK}}', + 'One payment in POL with SafePal or any other crypto wallet, never a subscription, split on-chain in the same transaction. {{LINK}}' + ], + headlines: ['Draft Your Team Every Monday', 'Coach Them Up, Pick First', 'Five Picks Today, More Every Week'], + email: { + subject: 'A weekly draft for people who need a sponsor', + body: [ + 'Hi,', + '', + 'People join our network every day without a sponsor. On 5xYourTeam the coaches draft them, every Monday, in rounds.', + '', + 'A ' + seat + '. The draft order is earned: the coaches who helped the most of last week\'s picks get started pick first.', + '', + 'Each pick shows a scouting card (last seen, the door they came in through, wallet linked, games played where that is tracked) and you coach them through site messages. Nobody\'s email is ever shown or sold.', + '', + 'It is paid once in POL with SafePal or any other crypto wallet, never a subscription, and split on-chain in the same transaction.', + '', + 'A position buys a seat in the draft and coaching tools, not income. Nothing is promised.', + '', + 'Here is my page:', + '{{LINK}}' + ].join('\n') + }, + posts: [ + 'I coach a team on 5xYourTeam. Every Monday we draft people who joined the network without a sponsor, and draft order is earned by helping your picks get started.\n\n{{LINK}}', + 'My picks are trading cards that level up as they get going. Rookie today, Pro when payouts go on. A ' + seat + '.\n\n{{LINK}}' + ] + }; +} +const NOTE = 'A position buys a seat in the draft and coaching tools, not income. Nothing is promised.'; +const REF_RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/; +const base = () => 'https://' + C.site; +let files = null; +function creatives() { + if (files) return files; + let names = []; try { names = fs.readdirSync(KIT_DIR).filter(f => /^fx-[a-z]+-[a-z]+\.png$/.test(f)); } catch (e) {} + const out = []; + for (const angle of Object.keys(ANGLES)) for (const shape of Object.keys(SHAPES)) { + const f = 'fx-' + angle + '-' + shape + '.png'; if (!names.includes(f)) continue; + const [w, h, label] = SHAPES[shape]; + out.push({ key: angle + '-' + shape, angle, angleLabel: ANGLES[angle], shape, label, w, h, url: base() + '/art/kit/' + f }); + } + return (files = out); +} +function kit(u) { + const ref = REF_RE.test(String(u || '')) ? String(u) : ''; + const link = ref && !/^0x/i.test(ref) ? base() + '/' + encodeURIComponent(ref) : base() + '/' + (ref ? '?ref=' + encodeURIComponent(ref) : ''); + const q = ref ? '?ref=' + encodeURIComponent(ref) : ''; + const fill = s => s.split('{{LINK}}').join(link); + const track = seg => netsites.tracked(C.siteId, C.siteId, { s1: ref, s2: seg }); + const t = copy(); + return { + v: 1, site: C.site, name: C.siteName, updated: '2026-11-15', username: ref || null, + tagline: 'The weekly draft for people who need a sponsor.', + links: [ + { key: 'page', label: 'Your coach page', url: link, tracked: track('') }, + { key: 'join', label: 'Get a position', url: base() + '/join' + q, tracked: track('join') }, + { key: 'ledger', label: 'Live ledger', url: base() + '/ledger' + q, tracked: track('ledger') } + ], + linkTemplate: base() + '/{username}', trackedTemplate: netsites.tracked(C.siteId, C.siteId) + '&s1={username}', + creatives: creatives().map(c => Object.assign({}, c, { html: '5xYourTeam' })), + lines: t.lines.map(fill), headlines: t.headlines, email: { subject: t.email.subject, body: fill(t.email.body) }, posts: t.posts.map(fill), + note: NOTE, promotePage: base() + '/promote' + }; +} +function handle(req, res, u, sendFile) { + if (u.pathname === '/promote' && (req.method === 'GET' || req.method === 'HEAD') && sendFile) { sendFile(res, path.join(__dirname, 'public', 'promote.html')); return true; } + if (u.pathname !== '/api/promo-kit') return false; + const cors = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type' }; + if (req.method === 'OPTIONS') { res.writeHead(204, cors); res.end(); return true; } + if (req.method !== 'GET' && req.method !== 'HEAD') return false; + res.writeHead(200, Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'public, max-age=300', 'X-Content-Type-Options': 'nosniff' }, cors)); + res.end(JSON.stringify(kit(u.searchParams.get('u')))); return true; +} +module.exports = { kit, handle, creatives, SHAPES, ANGLES, copy, NOTE }; diff --git a/proof.js b/proof.js new file mode 100644 index 0000000..05cebfd --- /dev/null +++ b/proof.js @@ -0,0 +1,181 @@ +// Trust pack (Marty 2026-11-14: live ledger, contract proof, toasts, a Telegram post per sale with an image + stats, payment +// notifications). The ViralAdBlitz / Downline Banners pattern, with the 5xYourTeam split: +// - ledger(): every position purchase (the Purchase events shop.js recorded) with its split read from the receipt: the sponsor +// share (level 1, 25%), levels 2-5 (5% each) with each person's place in the buyer's line, who was passed over, the Best Coach +// prize pot (10%), the company. Plus the Best Coach pot payouts recorded by the admin (tx hashes). +// - contract(): live facts for /contract (owner, company, prize wallet, keeper, paused, orders, what it holds), cached 5 minutes. +// - Telegram: (1) a sale card per purchase (a prebuilt 5xYourTeam proof image, rotated; the coach, every share paid in the same +// transaction with its POL, this week's numbers, the verify link); (2) the Draft Day card after each draft (results image + +// picks); (3) one line per Best Coach payout. PHASE 1: nothing is sent unless TG_LIVE=1 with TG_TOKEN + TG_CHAT; otherwise every +// post goes to the document tg-outbox.json (shown on /admin) so the wording can be checked. Once per key across app copies +// (in-process guard + docstore.claim), never a sale older than 2 hours. TG_API (tests) = a stand-in. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const store = require('./store'); +const docstore = require('./docstore'); + +const SPLIT = { sponsorBps: 2500, levelBps: 500, potBps: 1000, denom: 10000, potLevel: 6 }; // DraftPosition constants +const CARDS = ['/art/proof/fx-proof-navy.png', '/art/proof/fx-proof-gold.png', '/art/proof/fx-proof-field.png']; // rotated per post +const st = { posted: 0, queued: 0, skipped: 0, failed: 0, lastError: null }; +let C = null, shop = null, names = null, weekStats = () => ({}); +const sent = new Set(); +const once = k => { if (sent.has(k)) return false; sent.add(k); if (sent.size > 5000) sent.clear(); return true; }; + +function init(cfg, deps) { C = cfg; shop = deps.shop; names = deps.nameOf || null; if (deps.weekStats) weekStats = deps.weekStats; } +const live = () => process.env.TG_LIVE === '1' && !!(process.env.TG_TOKEN && process.env.TG_CHAT); +const lc = a => String(a || '').toLowerCase(); +const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; +function nameLocal(addr) { const m = store.member(lc(addr)); return m && m.username ? m.username : null; } +async function nameOf(addr) { const local = nameLocal(addr); if (local) return local; if (names) { try { const n = await names(lc(addr)); if (n) return n; } catch (e) {} } return null; } +const who = (addr, name) => name ? '@' + name : short(lc(addr)); +const pol = wei => { const v = Number(BigInt(wei || 0) / 10n ** 12n) / 1e6; return v >= 100 ? v.toFixed(2) : v.toFixed(4); }; +const usd = cents => '$' + (Number(cents || 0) / 100).toFixed(2); +const esc = s => String(s == null ? '' : s).replace(/[&<>]/g, c => ({ '&': '&', '<': '<', '>': '>' }[c])); +const what = x => (Number(x.qty) > 1 ? x.qty + ' positions' : 'a position'); + +// the split of one order: from the receipt when read, else from the Purchase event (who got each level is then unknown) +function split(x) { + if (Array.isArray(x.pays) && x.pays.length) return x.pays; + let paid = 0n; try { paid = BigInt(x.weiPaid || 0); } catch (e) {} + const out = []; + for (let i = 1; i <= Number(x.levelsPaid || 0); i++) out.push({ level: i, depth: null, to: null, wei: (paid * BigInt(i === 1 ? SPLIT.sponsorBps : SPLIT.levelBps) / BigInt(SPLIT.denom)).toString() }); + out.push({ level: SPLIT.potLevel, depth: 0, to: lc(C.prizeWallet), wei: String(x.prizePaid != null ? x.prizePaid : paid * BigInt(SPLIT.potBps) / BigInt(SPLIT.denom)) }); + out.push({ level: 0, depth: 0, to: lc(C.companyWallet), wei: String(x.companyPaid || 0) }); + return out; +} +// the contract's pass-up split as a pure model (preview + tests): line = [{ who, qualified }] nearest first, wei = POL kept. +// Mirrors DraftPosition._split exactly: first qualified 25%, next four 5%, within 20 places; pot 10%; company the remainder. +function model(line, wei) { + const W = BigInt(wei); const sp = W * BigInt(SPLIT.sponsorBps) / BigInt(SPLIT.denom), lv = W * BigInt(SPLIT.levelBps) / BigInt(SPLIT.denom), pot = W * BigInt(SPLIT.potBps) / BigInt(SPLIT.denom); + const pays = [], over = [], seen = new Set(); let total = 0n; + for (let i = 0; i < Math.min(line.length, 20) && pays.length < 5; i++) { + const x = line[i]; if (!x.qualified) { over.push({ who: x.who, depth: i + 1 }); continue; } + if (seen.has(x.who)) continue; seen.add(x.who); + const amt = pays.length === 0 ? sp : lv; pays.push({ level: pays.length + 1, depth: i + 1, to: x.who, wei: amt.toString() }); total += amt; + } + return { pays, over, pot: pot.toString(), company: (W - total - pot).toString() }; +} +const label = p => p.level === 0 ? 'company' : p.level === SPLIT.potLevel ? 'pot' : p.level === 1 ? 'sponsor' : 'level ' + p.level; + +// ---- public ledger ---- +function rows() { return store.purchases().map(x => Object.assign({ tx: x.key.split(':')[0] }, x)); } +function ledger(n) { + const lim = Math.min(200, Math.max(1, Number(n) || 50)); + const list = rows().map(x => ({ kind: 'position', tx: x.tx, at: (x.blockAt ? x.blockAt * 1000 : x.at) || null, orderId: x.orderId, buyer: x.buyer, buyerName: nameLocal(x.buyer), what: what(x), qty: x.qty, + usdCents: x.usdCents, weiPaid: x.weiPaid, + pays: split(x).map(p => ({ level: p.level, label: label(p), depth: p.depth, to: p.to, name: p.to ? nameLocal(p.to) : null, wei: p.wei, failed: p.failed || undefined })), + passedOver: (x.over || []).map(o => ({ depth: o.depth, name: nameLocal(o.who) || null, who: o.who })) })).sort((a, b) => (b.at || 0) - (a.at || 0)); + let wei = 0n, pot = 0n, cents = 0, positions = 0; + for (const x of rows()) { positions += Number(x.qty) || 1; cents += Number(x.usdCents) || 0; try { wei += BigInt(x.weiPaid || 0); pot += BigInt(x.prizePaid || 0); } catch (e) {} } + const payouts = Object.entries(store.state().payouts || {}).flatMap(([week, l]) => l.map(p => Object.assign({ week }, p))).sort((a, b) => (b.at || 0) - (a.at || 0)); + return { contract: C.contractAddress || null, explorer: C.explorer, prizeWallet: C.prizeWallet || null, items: list.slice(0, lim), payouts: payouts.slice(0, 50), + totals: { positions, orders: list.length, usdCents: cents, weiPaid: wei.toString(), potWei: pot.toString() } }; +} +// the week's pot: 10% of every position sold that Central week (from the Purchase events) +function potOf(from, to) { + let w = 0n; for (const x of rows()) { const t = (x.blockAt ? x.blockAt * 1000 : x.at) || 0; if (t >= from && t < to) { try { w += BigInt(x.prizePaid || 0); } catch (e) {} } } + return w.toString(); +} + +// ---- contract facts (cached 5 minutes) ---- +let cCache = null; +async function contract() { + if (cCache && Date.now() - cCache.at < 300000) return cCache.v; + const v = { address: C.contractAddress || null, chainId: C.chainId, explorer: C.explorer, split: C.split, position: { usd: C.position.usd }, + verified: { sourcify: false, polygonscan: 'pending', sourcifyUrl: C.contractAddress ? 'https://repo.sourcify.dev/' + C.chainId + '/' + C.contractAddress : null }, + ownerNote: "Marty's Tangem hardware wallet", prizeWallet: C.prizeWallet || null, live: false }; + if (shop && shop.watching()) { + const { Interface } = require('ethers'); + const I = new Interface(['function owner() view returns (address)', 'function company() view returns (address)', 'function prizeWallet() view returns (address)', 'function keeper() view returns (address)', + 'function paused() view returns (bool)', 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function priceCents() view returns (uint256)']); + const read = async fn => I.decodeFunctionResult(fn, await shop.rpc('eth_call', [{ to: C.contractAddress, data: I.encodeFunctionData(fn, []) }, 'latest']))[0]; + try { + const [owner, company, prize, keeper, paused, totalOwed, orderCount, cents, bal] = await Promise.all(['owner', 'company', 'prizeWallet', 'keeper', 'paused', 'totalOwed', 'orderCount', 'priceCents'].map(read) + .concat([shop.rpc('eth_getBalance', [C.contractAddress, 'latest'])])); + Object.assign(v, { owner: lc(owner), company: lc(company), prizeWallet: lc(prize), keeper: lc(keeper), paused: !!paused, totalOwedWei: totalOwed.toString(), orderCount: Number(orderCount), + priceCents: Number(cents), balanceWei: BigInt(bal).toString(), live: true, readAt: Date.now() }); + } catch (e) { v.error = 'The chain did not answer just now. Try again in a minute.'; } + } + cCache = { at: Date.now(), v }; + if (v.error) cCache.at = Date.now() - 240000; + return v; +} + +// ---- Telegram (phase 1: the outbox) ---- +const OUTBOX = () => path.join(C.dataDir, 'tg-outbox.json'); +function outbox() { try { return JSON.parse(fs.readFileSync(OUTBOX(), 'utf8')); } catch (e) { return []; } } +async function tg(method, body, key) { + if (!live()) { + const l = outbox(); l.push({ at: Date.now(), key, method, body }); fs.writeFileSync(OUTBOX(), JSON.stringify(l.slice(-100))); st.queued++; return true; + } + const base = String(process.env.TG_API || 'https://api.telegram.org').replace(/\/+$/, ''); + const b = Object.assign({ chat_id: process.env.TG_CHAT, parse_mode: 'HTML' }, body); + if (process.env.TG_PAY_TOPIC) b.message_thread_id = Number(process.env.TG_PAY_TOPIC); + const r = await fetch(base + '/bot' + process.env.TG_TOKEN + '/' + method, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(b), signal: AbortSignal.timeout(15000) }); + const j = await r.json().catch(() => ({})); + if (!j.ok) { st.failed++; st.lastError = String(j.description || r.status).slice(0, 160); console.error('proof: telegram', method, 'failed', r.status, st.lastError); return false; } + st.posted++; return true; +} +const photoUrl = p => (process.env.TG_PHOTO_BASE ? String(process.env.TG_PHOTO_BASE).replace(/\/+$/, '') : 'https://' + C.site) + p; +function weekLine() { + const w = weekStats(); + return '\u{1F4CA} This week: ' + (w.positions || 0) + ' position' + (w.positions === 1 ? '' : 's') + ' ยท ' + (w.coaches || 0) + ' coaches ยท ' + (w.started || 0) + ' picks started ยท pot ' + pol(w.potWei || 0) + ' POL'; +} +async function caption(x) { + const lines = ['\u{1F3C8} 5xYourTeam', '\u{1F4DD} ' + esc(who(x.buyer, await nameOf(x.buyer))) + ' joined The Draft: ' + esc(what(x)) + ' ยท ' + usd(x.usdCents) + ' (' + pol(x.weiPaid) + ' POL)']; + const s = split(x); let levels = 0; + for (const p of s) { + if (p.level === 0) { lines.push('\u{1F3E6} 5xYourTeam: ' + pol(p.wei) + ' POL'); continue; } + if (p.level === SPLIT.potLevel) { lines.push('\u{1F3C6} Best Coach pot 10%: ' + pol(p.wei) + ' POL'); continue; } + levels++; + const where = p.depth && p.depth !== p.level ? ' (place ' + p.depth + ' in the line)' : ''; + const pct = p.level === 1 ? 'Sponsor 25%' : 'Level ' + p.level + ' 5%'; + if (p.failed) lines.push('โš ๏ธ ' + pct + ' payment to ' + esc(who(p.to, await nameOf(p.to))) + ' bounced; it waits in the contract for them to claim'); + else lines.push('\u{1F4B8} ' + pct + ': ' + pol(p.wei) + ' POL โ†’ ' + (p.to ? esc(who(p.to, await nameOf(p.to))) : 'sponsor') + where); + } + if (levels === 0) lines.push('Nobody in this line holds a position yet, so the level shares went to 5xYourTeam.'); + if ((x.over || []).length) lines.push(x.over.length === 1 ? '1 person in the line holds no position yet and was passed over; their share went up the line.' : x.over.length + ' people in the line hold no position yet and were passed over; their shares went up the line.'); + lines.push('Paid by the contract in this same transaction. It keeps nothing and there is nothing to withdraw.'); + lines.push(weekLine()); + lines.push('ยท Verify on Polygonscan ยท Live ledger'); + return lines.join('\n'); +} +let card = 0; +// shop.js calls this once per newly recorded purchase (rec = the stored purchase, tx = its transaction) +function onPurchase(rec, tx) { + const x = Object.assign({ tx }, rec); + (async () => { + try { + const sp = await shop.readSplit(tx, rec.orderId); + if (sp) { const S = store.state(); const k = Object.keys(S.purchases || {}).find(k2 => k2.startsWith(lc(tx) + ':') && S.purchases[k2].orderId === rec.orderId); + if (k) { Object.assign(S.purchases[k], { pays: sp.pays, over: sp.over, bound: sp.bound }); store.save(); } Object.assign(x, { pays: sp.pays, over: sp.over }); } + } catch (e) {} + const at = (rec.blockAt ? rec.blockAt * 1000 : rec.at) || Date.now(); + if (Date.now() - at > 2 * 3600000) { st.skipped++; return; } + const text = await caption(x); + const key = 'fxtg:' + lc(tx) + ':' + rec.orderId; + if (!once(key) || !(await docstore.claim(key))) return; // never the same sale twice + const photo = photoUrl(CARDS[card++ % CARDS.length]); + let ok = await tg('sendPhoto', { photo, caption: text }, key); + if (!ok) ok = await tg('sendMessage', { text, disable_web_page_preview: true }, key); + })().catch(e => { st.failed++; st.lastError = String(e.message).slice(0, 160); }); +} +// the Draft Day card: d = the finished draft, rows = [{ slot, coach, person }], stats = { players, coaches, potWei } +async function draftDay(d, rows, stats) { + const key = 'fxdraft:' + d.week; + if (!once(key) || !(await docstore.claim(key))) return false; + const top = rows.slice(0, 12).map(r => '' + esc(r.slot) + ' ' + esc('@' + (r.coach || '?')) + ' takes ' + esc('@' + (r.person || '?'))).join('\n'); + const text = ['\u{1F3C8} 5xYourTeam ยท Draft Day results, week of ' + esc(d.week) + '', top, (rows.length > 12 ? '...and ' + (rows.length - 12) + ' more picks' : ''), + '\u{1F465} ' + stats.players + ' players drafted ยท ' + stats.coaches + ' coaches', '\u{1F3C6} Best Coach pot this week: ' + pol(stats.potWei) + ' POL', + 'Draft order next Monday is earned: get your picks started. ยท The draft board'].filter(Boolean).join('\n'); + return tg('sendPhoto', { photo: photoUrl('/art/draftday/week-' + d.week + '.png'), caption: text }, key); +} +// one line per Best Coach payout (recorded by the admin with its tx hash) +async function payoutLine(week, p) { + const key = 'fxpot:' + week + ':' + p.rank; + if (!once(key) || !(await docstore.claim(key))) return false; + return tg('sendMessage', { text: '\u{1F3C6} 5xYourTeam Best Coach, week of ' + esc(week) + ': #' + p.rank + ' ' + esc('@' + (p.username || short(p.coach))) + ' got ' + pol(p.wei) + ' POL from the pot ยท Verify', disable_web_page_preview: true }, key); +} +function view() { return Object.assign({ telegram: live() ? 'live' : 'outbox (phase 1: nothing is sent)', topic: process.env.TG_PAY_TOPIC || null, outbox: outbox().slice(-10) }, st); } +module.exports = { model, init, ledger, potOf, contract, onPurchase, draftDay, payoutLine, caption, split, view, live, outbox, CARDS, SPLIT }; diff --git a/public/admin.html b/public/admin.html new file mode 100644 index 0000000..e23f7c9 --- /dev/null +++ b/public/admin.html @@ -0,0 +1,34 @@ + + + + +Admin | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+
+

Status

+

Best Coach pot (last week)

+

Old-link map (JSON {"oldrefs": {"old": "network username"}})

+
+ + + + diff --git a/public/art/cards/fx-coach-card.png b/public/art/cards/fx-coach-card.png new file mode 100644 index 0000000..1b86a01 Binary files /dev/null and b/public/art/cards/fx-coach-card.png differ diff --git a/public/art/cards/fx-tiers.png b/public/art/cards/fx-tiers.png new file mode 100644 index 0000000..f965a47 Binary files /dev/null and b/public/art/cards/fx-tiers.png differ diff --git a/public/art/icon-192.png b/public/art/icon-192.png new file mode 100644 index 0000000..ca7722e Binary files /dev/null and b/public/art/icon-192.png differ diff --git a/public/art/kit/fx-cards-box.png b/public/art/kit/fx-cards-box.png new file mode 100644 index 0000000..05be346 Binary files /dev/null and b/public/art/kit/fx-cards-box.png differ diff --git a/public/art/kit/fx-cards-leader.png b/public/art/kit/fx-cards-leader.png new file mode 100644 index 0000000..f55eaaa Binary files /dev/null and b/public/art/kit/fx-cards-leader.png differ diff --git a/public/art/kit/fx-cards-social.png b/public/art/kit/fx-cards-social.png new file mode 100644 index 0000000..8bdf611 Binary files /dev/null and b/public/art/kit/fx-cards-social.png differ diff --git a/public/art/kit/fx-cards-square.png b/public/art/kit/fx-cards-square.png new file mode 100644 index 0000000..9237e7c Binary files /dev/null and b/public/art/kit/fx-cards-square.png differ diff --git a/public/art/kit/fx-cards-strip.png b/public/art/kit/fx-cards-strip.png new file mode 100644 index 0000000..089de2c Binary files /dev/null and b/public/art/kit/fx-cards-strip.png differ diff --git a/public/art/kit/fx-cards-tile.png b/public/art/kit/fx-cards-tile.png new file mode 100644 index 0000000..dd4f2b8 Binary files /dev/null and b/public/art/kit/fx-cards-tile.png differ diff --git a/public/art/kit/fx-cards-tower.png b/public/art/kit/fx-cards-tower.png new file mode 100644 index 0000000..bc132cc Binary files /dev/null and b/public/art/kit/fx-cards-tower.png differ diff --git a/public/art/kit/fx-coach-box.png b/public/art/kit/fx-coach-box.png new file mode 100644 index 0000000..2f179f0 Binary files /dev/null and b/public/art/kit/fx-coach-box.png differ diff --git a/public/art/kit/fx-coach-leader.png b/public/art/kit/fx-coach-leader.png new file mode 100644 index 0000000..50e02fe Binary files /dev/null and b/public/art/kit/fx-coach-leader.png differ diff --git a/public/art/kit/fx-coach-social.png b/public/art/kit/fx-coach-social.png new file mode 100644 index 0000000..a71b0d2 Binary files /dev/null and b/public/art/kit/fx-coach-social.png differ diff --git a/public/art/kit/fx-coach-square.png b/public/art/kit/fx-coach-square.png new file mode 100644 index 0000000..c60b41a Binary files /dev/null and b/public/art/kit/fx-coach-square.png differ diff --git a/public/art/kit/fx-coach-strip.png b/public/art/kit/fx-coach-strip.png new file mode 100644 index 0000000..d64dc18 Binary files /dev/null and b/public/art/kit/fx-coach-strip.png differ diff --git a/public/art/kit/fx-coach-tile.png b/public/art/kit/fx-coach-tile.png new file mode 100644 index 0000000..0c70729 Binary files /dev/null and b/public/art/kit/fx-coach-tile.png differ diff --git a/public/art/kit/fx-coach-tower.png b/public/art/kit/fx-coach-tower.png new file mode 100644 index 0000000..fbf1919 Binary files /dev/null and b/public/art/kit/fx-coach-tower.png differ diff --git a/public/art/kit/fx-draft-box.png b/public/art/kit/fx-draft-box.png new file mode 100644 index 0000000..7fb9302 Binary files /dev/null and b/public/art/kit/fx-draft-box.png differ diff --git a/public/art/kit/fx-draft-leader.png b/public/art/kit/fx-draft-leader.png new file mode 100644 index 0000000..ce1ebdb Binary files /dev/null and b/public/art/kit/fx-draft-leader.png differ diff --git a/public/art/kit/fx-draft-social.png b/public/art/kit/fx-draft-social.png new file mode 100644 index 0000000..6e33668 Binary files /dev/null and b/public/art/kit/fx-draft-social.png differ diff --git a/public/art/kit/fx-draft-square.png b/public/art/kit/fx-draft-square.png new file mode 100644 index 0000000..50ead50 Binary files /dev/null and b/public/art/kit/fx-draft-square.png differ diff --git a/public/art/kit/fx-draft-strip.png b/public/art/kit/fx-draft-strip.png new file mode 100644 index 0000000..235902c Binary files /dev/null and b/public/art/kit/fx-draft-strip.png differ diff --git a/public/art/kit/fx-draft-tile.png b/public/art/kit/fx-draft-tile.png new file mode 100644 index 0000000..279771c Binary files /dev/null and b/public/art/kit/fx-draft-tile.png differ diff --git a/public/art/kit/fx-draft-tower.png b/public/art/kit/fx-draft-tower.png new file mode 100644 index 0000000..ea16f65 Binary files /dev/null and b/public/art/kit/fx-draft-tower.png differ diff --git a/public/art/og-share.png b/public/art/og-share.png new file mode 100644 index 0000000..5dc1069 Binary files /dev/null and b/public/art/og-share.png differ diff --git a/public/art/proof/fx-proof-field.png b/public/art/proof/fx-proof-field.png new file mode 100644 index 0000000..6ce0e87 Binary files /dev/null and b/public/art/proof/fx-proof-field.png differ diff --git a/public/art/proof/fx-proof-gold.png b/public/art/proof/fx-proof-gold.png new file mode 100644 index 0000000..0f2236d Binary files /dev/null and b/public/art/proof/fx-proof-gold.png differ diff --git a/public/art/proof/fx-proof-navy.png b/public/art/proof/fx-proof-navy.png new file mode 100644 index 0000000..320e61f Binary files /dev/null and b/public/art/proof/fx-proof-navy.png differ diff --git a/public/assets/board.js b/public/assets/board.js new file mode 100644 index 0000000..dad6963 --- /dev/null +++ b/public/assets/board.js @@ -0,0 +1,90 @@ +// The Draft Board (front page): who is on the clock, this week's pool as scouting cards, the draft tracker, Best Coach standings, +// Rookie of the Week and the Best Coach pot. Every figure comes from /api/board; a missing stat says "not tracked yet". +(async function () { + FX.renderNav('/'); FX.renderFooter(); + const $ = FX.$, esc = FX.esc; + const c = await FX.getConfig().catch(() => ({})); + const me = await FX.getJSON('/api/me').catch(() => ({})); + let B = null, busy = false, showAll = false; + const days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; + const hourLabel = h => (h % 12 || 12) + ' ' + (h < 12 ? 'AM' : 'PM'); + const pol = w => w == null ? 'not tracked yet' : FX.polOf(w) + ' POL'; + function hero(b) { + const d = b.draft; const cur = d && d.onClock; + const when = days[(c.draft || {}).dow == null ? 1 : c.draft.dow] + ' ' + hourLabel(b.draftHour) + ' Central'; + if (d && d.status === 'live' && cur) { + $('heroKick').textContent = cur.me ? 'YOU\'RE ON THE CLOCK' : 'THE DRAFT IS LIVE'; + $('heroTitle').textContent = cur.me ? 'Pick ' + cur.n + ' of Round ' + cur.round + '. Make it count.' : 'Pick ' + cur.n + ' of Round ' + cur.round + ': @' + cur.coach + ' is on the clock.'; + $('heroClock').hidden = false; $('heroClock').dataset.until = cur.until; + } else if (d && d.status === 'done' && b.now < b.nextDraftAt) { + $('heroKick').textContent = 'NEXT DRAFT: ' + when.toUpperCase(); + $('heroTitle').textContent = d.made ? d.made + ' players drafted this week. Get your picks started.' : 'Next draft ' + FX.when(b.nextDraftAt) + '.'; + $('heroClock').hidden = false; $('heroClock').dataset.until = b.nextDraftAt; + } else { + $('heroKick').textContent = 'DRAFT DAY: ' + when.toUpperCase(); + $('heroTitle').textContent = b.rounds + ' rounds. Draft order is earned.'; + $('heroClock').hidden = false; $('heroClock').dataset.until = b.now < b.draftAt ? b.draftAt : b.nextDraftAt; + } + } + function clock() { const el = $('heroClock'); if (!el || el.hidden) return; const u = Number(el.dataset.until || 0); const live = B && B.draft && B.draft.status === 'live'; + el.textContent = live ? 'Clock: ' + FX.left(u - Date.now() - (B.now - B.fetched)) : 'Starts in ' + FX.left(u - Date.now() - (B.now - B.fetched)); } + function scout(p, b) { + const coach = b.me && b.me.coach; const live = b.draft && b.draft.status === 'live'; const onClock = live && b.draft.onClock && b.draft.onClock.me; + const queued = b.me && (b.me.queue || []).includes(p.id); + let act = ''; + if (onClock) act = ''; + else if (coach && !live && b.me.credits > 0) act = ''; + else if (coach) act = ''; + else act = 'GET A POSITION'; + const rows = [['Game plays', p.plays == null ? 'not tracked yet' : FX.n(p.plays)], ['Plays', p.game || (p.plays === 0 ? 'none yet' : p.plays == null ? 'not tracked yet' : 'none yet')]]; + if (coach) rows.push(['Earned in games', pol(p.gameWei)], ['Earned surfing', pol(p.surfWei)]); + rows.push(['Last seen', FX.ago(p.lastSeen, b.now)], ['Came from', p.door || 'not tracked yet'], ['Wallet', p.wallet ? 'linked' : 'not yet']); + return '
@' + esc(p.username || 'player') + '' + (p.hot ? 'HOT' : '') + '
' + + rows.map(r => '
' + r[0] + '' + esc(r[1]) + '
').join('') + '
' + act + '
'; + } + function paint(b) { + B = b; B.fetched = Date.now(); FX.setWeek(b.week); hero(b); + $('potWei').textContent = FX.polOf(b.pot.wei) + ' POL'; + $('potRank').innerHTML = b.me && b.me.coach ? 'Your draft spot next Monday#' + esc(b.me.nextSpot || '?') + '' : 'Coaches this week' + FX.n(b.coaches) + ''; + const coach = b.me && b.me.coach; + $('poolNote').textContent = (b.poolSize ? FX.n(b.poolSize) + ' people waiting for a sponsor. ' : '') + (coach ? (b.me.credits > 0 && !(b.draft && b.draft.status === 'live') ? 'You have ' + b.me.credits + ' instant pick' + (b.me.credits === 1 ? '' : 's') + ': draft now, or queue players for Monday.' : 'Queue the players you want; an away coach is auto-picked from their queue.') : 'Usernames only, never contact details. Coaches see earnings where they are tracked.'); + const shown = showAll ? b.pool : b.pool.slice(0, 8); + $('poolMore').hidden = showAll || b.pool.length <= 8; $('poolMore').textContent = 'Show all ' + b.pool.length + ' players'; + $('pool').innerHTML = b.pool.length ? shown.map(p => scout(p, b)).join('') : '

The pool is empty right now. People who join the network without a sponsor show up here after their first 24 hours.

'; + // tracker + const d = b.draft; + if (d && d.status === 'live') { + $('trackTitle').textContent = 'DRAFT TRACKER: ROUND ' + (d.onClock ? d.onClock.round : ''); + const rows = d.rows.slice(0, 6).reverse().map(x => '' + esc(x.slot) + '@' + esc(x.coach) + '' + (x.person ? '@' + esc(x.person) : '' + esc(x.skipped === 'team full' ? 'skipped: team full' : 'skipped') + '') + '' + esc(x.tierName || '') + '') + .concat(d.room.map((r, i) => '' + esc(r.slot) + '' + (i === 0 ? (r.me ? 'You are on the clock' : '@' + esc(r.coach) + ' is on the clock') : '@' + esc(r.coach)) + '' + (i === 0 ? '...' : '') + '')); + $('track').innerHTML = rows.join(''); + } else if (d && d.rows.length) { + $('trackTitle').textContent = 'DRAFT RESULTS: WEEK OF ' + b.week; + $('track').innerHTML = d.rows.filter(x => x.person).slice(0, 15).map(x => '' + esc(x.slot) + '@' + esc(x.coach) + '@' + esc(x.person) + '' + esc(x.tierName || '') + '').join(''); + } else { $('trackTitle').textContent = 'DRAFT TRACKER'; $('track').innerHTML = 'The draft starts ' + esc(FX.when(b.now < b.draftAt ? b.draftAt : b.nextDraftAt)) + '. Every coach gets a spot every week.'; } + $('best').innerHTML = b.best.length ? b.best.map(x => '
' + x.rank + '. @' + esc(x.coach) + '' + x.started + ' started
').join('') + : '

No picks started yet this week. The first coach to get one going leads the board.

'; + $('potRule').textContent = '"Started" = a pick switched on payouts or made a first purchase. The pot is 10% of every position sold this week' + (b.pot.split && b.pot.split.length ? ', shared ' + b.pot.split.join('/') + ' by the top ' + b.pot.split.length + ' coaches after the week.' : '.'); + $('rookie').innerHTML = b.rookie ? FX.card(b.rookie) : '

The first pick this week to link a wallet takes it.

'; + $('lastBest').innerHTML = b.lastWeekBest.length ? b.lastWeekBest.map(x => '
' + x.rank + '. @' + esc(x.coach) + '' + x.started + ' started
').join('') : '

No results from last week yet.

'; + wire(); + } + function wire() { + document.querySelectorAll('[data-draft]').forEach(el => el.onclick = () => act('/api/draft/pick', { person: el.dataset.draft }, 'Drafted. They show on My Team now.')); + document.querySelectorAll('[data-instant]').forEach(el => el.onclick = () => act('/api/my/instant', { person: el.dataset.instant }, 'Drafted. They show on My Team now.')); + document.querySelectorAll('[data-queue]').forEach(el => el.onclick = async () => { + const q = (B.me.queue || []).slice(); const id = el.dataset.queue; const i = q.indexOf(id); if (i >= 0) q.splice(i, 1); else q.push(id); + const r = await FX.post('/api/my/queue', { ids: q }); if (r.error) return FX.status(r.error, 'err'); B.me.queue = r.queue; paint(B); + }); + } + async function act(url, body, okMsg) { + if (busy) return; busy = true; + try { const r = await FX.post(url, body); if (r.error) FX.status(r.error, 'err'); else FX.status(okMsg, 'ok'); await load(); } finally { busy = false; } + } + async function load() { const b = await FX.getJSON('/api/board'); if (!b.error) paint(b); return b; } + $('poolMore').onclick = () => { showAll = true; paint(B); }; + await load(); + setInterval(clock, 1000); clock(); + setInterval(() => { load().catch(() => {}); }, 6000); + if (me.signedIn) { const ping = () => FX.post('/api/presence', {}).catch(() => {}); ping(); setInterval(ping, 30000); } +})(); diff --git a/public/assets/cards.js b/public/assets/cards.js new file mode 100644 index 0000000..e7fc797 --- /dev/null +++ b/public/assets/cards.js @@ -0,0 +1,18 @@ +// Card Collection: trading cards that level up as the picks do (Rookie, Starter, Pro, All-Star, Hall of Fame). Public cards show +// milestones, never earnings. ?u= shows that coach's team; signed in, your own team; otherwise the five tiers explained. +(async function () { + FX.renderNav('/cards'); FX.renderFooter(); + const $ = FX.$, esc = FX.esc; + const TIERS = [['rookie', 'Rookie', 'Drafted'], ['starter', 'Starter', 'Wallet linked'], ['pro', 'Pro', 'Payouts switched on'], ['allstar', 'All-Star', 'First purchase'], ['hof', 'Hall of Fame', 'Built a team of their own']]; + $('tiers').innerHTML = TIERS.map(t => FX.card({ tier: t[0], tierName: t[1], username: t[1].toLowerCase().replace(/[^a-z]/g, ''), coach: 'your team', milestone: t[2], plays: null, kind: 'draft', round: null })).join(''); + let u = new URLSearchParams(location.search).get('u') || ''; + let title = '', list = []; + if (!/^[A-Za-z0-9_.-]{2,40}$/.test(u)) { + const me = await FX.getJSON('/api/me').catch(() => ({})); + if (me.signedIn) { const d = await FX.getJSON('/api/my'); if (!d.error) { list = (d.picks || []).filter(p => p.status !== 'returned').map(p => ({ tier: p.tier, tierName: p.tierName, username: p.username, coach: d.username || 'me', round: p.round, kind: p.kind, milestone: TIERS.find(t => t[0] === p.tier)[2], plays: p.plays, status: p.status })); title = 'My team'; } } + } else { + const d = await FX.getJSON('/api/coach?u=' + encodeURIComponent(u)); + if (!d.error) { list = d.team; title = '@' + d.username + '\'s team'; } + } + if (title) { $('mine').hidden = false; $('mineTitle').textContent = title; $('mineCards').innerHTML = list.length ? list.map(x => FX.card(x)).join('') : '

No cards yet: they appear with the first pick.

'; } +})(); diff --git a/public/assets/coach.js b/public/assets/coach.js new file mode 100644 index 0000000..154ad69 --- /dev/null +++ b/public/assets/coach.js @@ -0,0 +1,14 @@ +// A coach page, 5xyourteam.com/: the coach card (since, positions, picks started) and the team as trading cards. Public: +// milestones only, never earnings or contact details. +(async function () { + FX.renderNav(''); FX.renderFooter(); + const $ = FX.$, esc = FX.esc; + const u = decodeURIComponent(location.pathname.replace(/^\/|\/$/g, '')); + const d = await FX.getJSON('/api/coach?u=' + encodeURIComponent(u)); + if (d.error) { $('cName').textContent = 'No coach by that name yet'; return; } + $('cName').textContent = '@' + d.username; + $('cSince').textContent = 'Coach since ' + FX.when(d.since); + $('cStats').innerHTML = '
Positions' + FX.n(d.positions) + '
On the team' + FX.n(d.team.length) + '
Picks started' + FX.n(d.started) + '
'; + $('cTeam').innerHTML = d.team.length ? d.team.map(x => FX.card(x)).join('') : '

Their first picks show here.

'; + $('cJoin').href = d.joinUrl; $('cJoin').textContent = 'Join the network free under @' + d.username; +})(); diff --git a/public/assets/common.js b/public/assets/common.js new file mode 100644 index 0000000..3e2f850 --- /dev/null +++ b/public/assets/common.js @@ -0,0 +1,97 @@ +// Shared page helpers (FX namespace, modelled on the ViralAdBlitz / VBB common.js): nav, footer (legal links, the company line, the +// network line from the hub), toasts of real events, and small formatters. Every number on a page comes from the API. +window.FX = (function () { + let cfgP = null; + const $ = id => document.getElementById(id); + const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + const getConfig = () => cfgP || (cfgP = fetch('/api/config').then(r => r.json())); + const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; + const n = x => Number(x || 0).toLocaleString('en-US'); + function status(msg, cls, id) { const el = $(id || 'status'); if (!el) return; el.hidden = !msg; el.className = 'note ' + (cls || ''); el.textContent = msg || ''; } + async function getJSON(url, opts) { const r = await fetch(url, opts); let j = {}; try { j = await r.json(); } catch (e) {} if (!r.ok && !j.error) j.error = 'Request failed (' + r.status + ')'; j._status = r.status; return j; } + const post = (url, body) => getJSON(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body || {}) }); + const polOf = (w, d) => { try { const k = BigInt(w || 0); if (k === 0n) return '0'; const v = Number(k / 10n ** 12n) / 1e6; return v.toFixed(d != null ? d : (v >= 100 ? 2 : v >= 1 ? 2 : 4)); } catch (e) { return '0'; } }; + const when = t => t ? new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago', weekday: 'short', month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' }) + ' CT' : ''; + // "today", "yesterday", "3 days ago" (Central days) or "not seen yet" + function ago(t, nowMs) { + if (!t) return 'not seen yet'; + const day = x => new Date(x).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); + const now = nowMs || Date.now(); const dd = Math.round((Date.parse(day(now)) - Date.parse(day(t))) / 86400000); + return dd <= 0 ? 'today' : dd === 1 ? 'yesterday' : dd + ' days ago'; + } + function left(ms) { if (ms <= 0) return 'now'; const m = Math.ceil(ms / 60000); if (m < 60) return m + ' min'; const h = Math.floor(m / 60); if (h < 48) return h + ' h ' + (m % 60) + ' min'; return Math.round(h / 24) + ' days'; } + const initials = s => String(s || '?').replace(/[^A-Za-z0-9]/g, '').slice(0, 2).toUpperCase() || '?'; + let weekLabel = ''; + function renderNav(active, week) { + const nav = document.createElement('nav'); nav.className = 'top'; + const links = [['/', 'Draft Board'], ['/team', 'My Team'], ['/cards', 'Card Collection'], ['/join', 'Get a Position'], ['/ledger', 'Ledger'], ['/contract', 'Contract']]; + nav.innerHTML = '
5XYOURTEAM
'; + document.body.prepend(nav); + if (week) setWeek(week); + } + // ISO-ish week number of a Monday date (the mockup's "DRAFT WEEK 46") + function weekNo(monday) { const d = new Date(monday + 'T12:00:00Z'); const t = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate() + 3)); const y = new Date(Date.UTC(t.getUTCFullYear(), 0, 4)); return 1 + Math.round(((t - y) / 86400000 - 3 + ((y.getUTCDay() + 6) % 7)) / 7); } + function setWeek(monday) { const el = $('navWeek'); if (!el || !monday) return; weekLabel = 'DRAFT WEEK ' + weekNo(monday); el.textContent = weekLabel; el.hidden = false; } + const NET = [['iap', 'InstantAdPay', 'https://instantadpay.com'], ['linkspin', 'LinkSpin', 'https://linkspin.app'], ['dlb', 'Downline Banners', 'https://downlinebanners.com'], + ['vbb', 'Viral Banner Blitz', 'https://viralbannerblitz.com'], ['viraladblitz', 'ViralAdBlitz', 'https://viraladblitz.com'], ['fivex', '5xYourTeam', 'https://5xyourteam.com'], ['stackpol', 'Stack POL', 'https://stackpol.com'], ['earnerscorner', 'Earners Corner', 'https://earnerscorner.com']].map(a => ({ id: a[0], name: a[1], url: a[2] })); + function netLine(el) { + if (!el) return; + const paint = list => { el.innerHTML = 'Part of the network · One account across the network: ' + list.map(s => (s.id === 'fivex' || /5xyourteam\.com/.test(s.url)) + ? '' + esc(s.name) + '' : '' + esc(s.name) + '').join(' · '); }; + paint(NET); + fetch('/api/network-sites').then(r => r.json()).then(l => { if (Array.isArray(l) && l.length) paint(l.some(s => s.id === 'fivex') ? l : l.concat([NET[5]])); }).catch(() => {}); + } + function renderFooter() { + const f = document.createElement('footer'); f.className = 'foot'; + f.innerHTML = '

5xYourTeam, the weekly draft for people who need a sponsor

' + + '

A position buys a draft spot and coaching tools, not income. Nothing is promised.

' + + '

Draft Board · My Team · Cards · Get a Position · Promote

' + + '' + + '

TrustClickz · 615 Green Valley Drive, Moody, AL 35004

'; + document.body.appendChild(f); + netLine(f.querySelector('.netline')); + toasts(); + } + // live toasts: real new positions, picks and level-ups only, bottom-right, never older than 30 minutes + let toastsOn = false; + function toasts() { + if (toastsOn) return; toastsOn = true; + const seen = new Set(); let first = true; + const box = document.createElement('div'); box.className = 'toasts'; box.setAttribute('aria-live', 'polite'); document.body.appendChild(box); + const show = c => { + const el = document.createElement('a'); el.className = 'toast' + (c.kind === 'position' ? ' red' : ''); + if (c.kind === 'position') { el.href = '/ledger'; el.innerHTML = '' + (c.name ? '@' + esc(c.name) : 'A new coach') + ' joined The Draft
Paid on-chain, split by the contract in the same transaction'; } + else if (c.kind === 'level') { el.href = '/cards'; el.innerHTML = '@' + esc(c.person || 'a pick') + ' just made ' + esc(c.tierName) + (c.name ? ' on @' + esc(c.name) + '\'s team' : '') + '
' + (c.tierName === 'Starter' ? 'Wallet linked. One step from Pro.' : c.tierName === 'Pro' ? 'Payouts switched on.' : 'Leveling up.') + ''; } + else { el.href = '/'; el.innerHTML = '' + (c.name ? '@' + esc(c.name) : 'A coach') + ' drafted @' + esc(c.person || 'a player') + '
' + (c.slot ? 'Pick ' + esc(c.slot) : 'An instant pick') + ''; } + box.appendChild(el); requestAnimationFrame(() => el.classList.add('in')); + setTimeout(() => { el.classList.remove('in'); setTimeout(() => el.remove(), 400); }, 7000); + }; + const tick = async () => { + const d = await getJSON('/api/recent').catch(() => null); const all = (d && d.items) || []; + const fresh = all.filter(c => !seen.has(c.key)); all.forEach(c => seen.add(c.key)); + const list = first ? fresh.slice(0, 1) : fresh.reverse(); first = false; + list.slice(0, 3).forEach((c, i) => setTimeout(() => show(c), 1500 + i * 8000)); + }; + tick(); setInterval(tick, 25000); + } + // a trading card (milestones only, never earnings) + function card(c, opts) { + const o = opts || {}; + return '
' + esc(c.tierName) + '
' + esc(initials(c.username)) + '
' + + '
@' + esc(c.username || 'player') + 'Team @' + esc(c.coach) + (c.round ? ' ยท Round ' + esc(c.round) : c.kind === 'instant' ? ' ยท Instant pick' : '') + '' + esc(c.milestone) + '' + + 'Games played: ' + (c.plays == null ? 'not tracked yet' : n(c.plays)) + '' + (c.status === 'returned' ? 'Back in the pool' : '') + (o.extra || '') + '
'; + } + // signed in on InstantAdPay already? one quick hop there and back signs you in here too + async function silentSso(to) { try { const ss = await getJSON('/api/sso/status'); if (ss && ss.check) { location.replace('/sso/start?mode=check&via=iap&to=' + encodeURIComponent(to)); return true; } } catch (e) {} return false; } + function signInBlock(to) { + const t = encodeURIComponent(to); + return '' + + '

Your wallet: SafePal or any other crypto wallet. Signing in is free and cannot move funds.

'; + } + function wireSignIn(root) { + (root || document).querySelectorAll('[data-wallet-signin]').forEach(b => { b.onclick = async () => { + try { status('Check your wallet for the sign-in message.'); await FXWallet.signIn(); location.reload(); } catch (e) { status(String(e && e.message || e).slice(0, 300), 'err'); } }; }); + } + return { $, esc, getConfig, short, status, getJSON, post, n, polOf, when, ago, left, initials, renderNav, renderFooter, setWeek, weekNo, card, silentSso, signInBlock, wireSignIn }; +})(); diff --git a/public/assets/contract.js b/public/assets/contract.js new file mode 100644 index 0000000..cfd9809 --- /dev/null +++ b/public/assets/contract.js @@ -0,0 +1,24 @@ +// Contract proof page (trust pack): live facts from /api/contract (read from Polygon, cached 5 minutes on the server). +(async function () { + FX.renderNav('/contract'); FX.renderFooter(); + const el = document.getElementById('facts'); const esc = FX.esc; + let d; try { d = await FX.getJSON('/api/contract'); } catch (e) { d = {}; } + const ex = d.explorer || 'https://polygonscan.com'; + const addr = (a, note) => a ? '' + esc(a) + '' + (note ? '
' + note + '' : '') : 'not read yet'; + const sp = d.split || { sponsorPct: 25, levelPct: 5, potPct: 10, companyPct: 45, maxDepth: 20 }; + const splitRow = ['The split', 'Sponsor ' + sp.sponsorPct + '%, levels 2 to 5 ' + sp.levelPct + '% each, Best Coach pot ' + sp.potPct + '%, 5xYourTeam ' + sp.companyPct + '%. Someone in the line with no position is passed over and the share goes up to the next person who holds one, up to ' + sp.maxDepth + ' places. Fixed in the code: no setter can change it.']; + if (!d.address) { el.innerHTML = 'StatusThe contract is not live yet. Its address, owner, prize pot wallet and every position will show here, read straight from Polygon.' + splitRow[0] + '' + splitRow[1] + ''; return; } + const rows = [ + ['Contract', addr(d.address, 'DraftPosition on ' + (d.chainId === 137 ? 'Polygon' : 'chain ' + d.chainId))], + ['Source code', 'Verified source on Polygonscan and Sourcify: ' + esc(d.verified && d.verified.polygonscan === 'pending' ? 'pending' : 'done')], + ['Owner', addr(d.owner, 'A Tangem hardware wallet. It can pause new sales, set the price of future positions and change the keeper. It cannot move anyone\'s money or change the split.')], + ['Company', addr(d.company, '5xYourTeam. Fixed in the contract when it was deployed.')], + ['Best Coach pot', addr(d.prizeWallet, 'Receives 10% of every position in the same transaction. Fixed in the contract when it was deployed. Each payout from it is listed on the ledger.')], + ['Keeper', addr(d.keeper, 'The site\'s signing key. It only signs a buyer\'s sponsor line from the network hub, once, on their first position.')], + splitRow, + ['Position', '$' + esc(d.position && d.position.usd) + ' one-time, paid in POL at the live Chainlink price' + (d.priceCents ? ' (contract price: $' + (d.priceCents / 100).toFixed(2) + ')' : '')], + ['Sales', d.live ? (d.paused ? 'Paused' : 'Open') + ' ยท ' + FX.n(d.orderCount) + ' orders so far' : '' + esc(d.error || 'not read yet') + ''], + ['Held by the contract', d.live ? FX.polOf(d.balanceWei) + ' POL' + (BigInt(d.totalOwedWei || 0) > 0n ? ' (all of it owed to wallets whose payment bounced, waiting for them to claim)' : ' (nothing is kept: every position is paid out in the same transaction)') : 'not read yet'] + ]; + el.innerHTML = '' + rows.map(r => '' + r[0] + '' + r[1] + '').join('') + ''; +})(); diff --git a/public/assets/fx.css b/public/assets/fx.css new file mode 100644 index 0000000..8c6edbc --- /dev/null +++ b/public/assets/fx.css @@ -0,0 +1,175 @@ +/* 5xYourTeam: the approved "draft night" look (mockup 2026-11-14): stadium navy, gold, a red tag; white trading cards with a navy + header; Oswald headlines + Inter text. Distinct from the other network sites (IAP mint, DLB ultraviolet, VBB pop-art, + ViralAdBlitz daylight royal, DownlineHydra parchment). One stylesheet, variables up top. */ +:root{ + --bg:#0b1530;--bar:#07102a;--panel:#13214a;--panel2:#1b2c5e;--line:#2a3a6e;--ink:#eef2fb;--muted:#b8c4e0;--dim:#8f9cc0; + --gold:#ffc93c;--gold2:#ffe08a;--red:#ff4d4d;--paper:#fff;--paperInk:#0b1530;--paperMuted:#4a587e; + --rookie:#9aa6c4;--starter:#1f8a5b;--pro:#2f5be0;--allstar:#ffc93c;--hof:#ff4d4d; + --disp:Oswald,Impact,'Arial Narrow',sans-serif;--text:Inter,system-ui,-apple-system,'Segoe UI',sans-serif; +} +*{box-sizing:border-box} +html{-webkit-text-size-adjust:100%} +body{margin:0;background:var(--bg);color:var(--ink);font-family:var(--text);font-size:16px;line-height:1.5;overflow-x:hidden} +a{color:var(--gold)}a:hover{color:var(--gold2)} +img{max-width:100%} +h1,h2,h3{font-family:var(--disp);font-weight:700;letter-spacing:.5px;line-height:1.05;margin:0} +h2{font-size:30px;text-transform:uppercase} +h3{font-size:20px;text-transform:uppercase} +.wrap{max-width:1200px;margin:0 auto;padding:0 24px} +main.wrap{padding-top:32px;padding-bottom:40px;display:flex;flex-direction:column;gap:32px} +.kicker{margin:0;font-family:var(--disp);font-size:14px;letter-spacing:3px;color:var(--gold);text-transform:uppercase} +.muted{color:var(--muted)}.dim{color:var(--dim)} +.note{margin:0;padding:10px 14px;background:var(--panel2);border-left:4px solid var(--gold);font-size:14px} +.note.err{border-color:var(--red)}.note.ok{border-color:var(--starter)} +.hidden,[hidden]{display:none!important} +/* header */ +nav.top{background:var(--bar);border-bottom:4px solid var(--gold);position:relative;z-index:5} +nav.top .wrap{display:flex;align-items:center;gap:20px;flex-wrap:wrap;padding-top:14px;padding-bottom:14px} +.brand{display:flex;align-items:center;gap:10px;margin-right:auto;text-decoration:none} +.wm{font-family:var(--disp);font-weight:700;font-size:30px;letter-spacing:1px;color:#fff;white-space:nowrap}.wm b{color:var(--gold);font-weight:700} +.wk{font-family:var(--disp);font-size:12px;background:var(--red);color:#fff;padding:3px 8px;letter-spacing:2px;white-space:nowrap} +nav.top .links{display:flex;gap:18px;flex-wrap:wrap;font-size:14px;font-weight:600} +nav.top .links a{color:var(--muted);text-decoration:none;padding-bottom:2px;border-bottom:2px solid transparent} +nav.top .links a.on,nav.top .links a:hover{color:#fff;border-bottom-color:var(--gold)} +/* buttons */ +.btn,.btn-gold,.btn-line,.btn-ghost{display:inline-flex;align-items:center;justify-content:center;gap:8px;border:0;cursor:pointer;text-decoration:none;font-family:var(--disp);letter-spacing:1px;text-transform:uppercase;font-size:16px;padding:12px 18px;line-height:1.1} +.btn{background:var(--paperInk);color:var(--gold)}.btn:hover{background:#13214a;color:var(--gold2)} +.btn-gold{background:var(--gold);color:var(--paperInk)}.btn-gold:hover{background:var(--gold2);color:var(--paperInk)} +.btn-line{background:transparent;color:#fff;border:2px solid var(--gold);padding:10px 16px}.btn-line:hover{background:var(--panel2);color:#fff} +.btn-ghost{background:transparent;color:var(--muted);border:2px solid var(--line);padding:10px 16px;font-family:var(--text);text-transform:none;letter-spacing:0;font-weight:600;font-size:14px} +button:disabled{opacity:.5;cursor:not-allowed} +.row{display:flex;flex-wrap:wrap;gap:10px;align-items:center} +/* hero */ +.hero{display:flex;flex-wrap:wrap;gap:16px;align-items:stretch} +.hero .copy{flex:999 1 520px;min-width:0;display:flex;flex-direction:column;gap:10px} +.hero h1{font-size:58px;color:#fff} +.hero .lead{margin:0;font-size:17px;color:var(--muted);max-width:640px} +.potbox{flex:1 1 280px;background:var(--panel);border:2px solid var(--gold);padding:18px;display:flex;flex-direction:column;gap:10px} +.potbox .lab{font-family:var(--disp);letter-spacing:2px;color:var(--gold);font-size:13px;text-transform:uppercase} +.potbox b.big{font-family:var(--disp);font-size:44px;color:#fff;line-height:1} +.potbox .kv{display:flex;justify-content:space-between;border-top:1px solid var(--line);padding-top:10px;font-size:14px}.potbox .kv b{color:var(--gold)} +.clock{font-family:var(--disp);font-size:22px;color:var(--gold);letter-spacing:1px} +/* section heads */ +.sh{display:flex;align-items:baseline;justify-content:space-between;flex-wrap:wrap;gap:8px} +.sh p{margin:0;color:var(--muted);font-size:14px} +/* scouting cards (the pool) */ +.pool{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:14px} +.scout{background:var(--paper);color:var(--paperInk);display:flex;flex-direction:column} +.scout .hd{background:var(--panel);color:#fff;padding:12px 14px;display:flex;justify-content:space-between;align-items:center;gap:8px} +.scout .hd b{font-family:var(--disp);font-size:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0} +.tag{font-family:var(--disp);font-size:12px;background:var(--gold);color:var(--paperInk);padding:2px 6px;letter-spacing:1px;white-space:nowrap} +.tag.red{background:var(--red);color:#fff} +.scout .bd{padding:14px;display:flex;flex-direction:column;gap:6px;font-size:14px;flex:1} +.kvr{display:flex;justify-content:space-between;gap:10px}.kvr span{color:var(--paperMuted)}.kvr b{text-align:right} +.scout .ft{margin:0 14px 14px;display:flex;gap:6px} +.scout .ft .btn{flex:1;font-size:15px;padding:11px 8px} +.scout .ft .q{flex:0 0 auto;background:#e5e9f4;color:var(--paperInk);border:0;font-family:var(--disp);padding:0 12px;cursor:pointer;letter-spacing:1px} +.scout .ft .q.on{background:var(--gold)} +.scout.mine .hd{background:var(--starter)} +/* panels, tables */ +.panel{background:var(--panel);padding:20px;display:flex;flex-direction:column;gap:10px;min-width:0} +.split{display:flex;flex-wrap:wrap;gap:20px} +.split>.wide{flex:999 1 560px}.split>.side{flex:1 1 300px} +.tbl{overflow-x:auto} +table{width:100%;border-collapse:collapse;font-size:14px} +th{color:var(--gold);text-align:left;font-family:var(--disp);letter-spacing:1px;font-weight:500;padding:8px;border-bottom:1px solid var(--line);white-space:nowrap} +td{padding:8px;border-bottom:1px solid var(--line);vertical-align:top} +tr.me td{background:var(--panel2)}tr.me td.c{color:var(--gold);font-weight:700} +.board{display:flex;flex-direction:column;gap:6px} +.board .r{display:flex;justify-content:space-between;font-size:15px;border-bottom:1px solid var(--line);padding-bottom:6px;gap:10px} +.board .r b{color:var(--gold);white-space:nowrap}.board .r.me span{color:var(--gold);font-weight:700} +.small{font-size:13px;color:var(--muted)} +/* stat tiles */ +.stats{display:flex;flex-wrap:wrap;gap:14px} +.stat{flex:1 1 200px;background:var(--panel);padding:16px;display:flex;flex-direction:column;gap:4px} +.stat span{font-family:var(--disp);letter-spacing:2px;font-size:12px;color:var(--gold);text-transform:uppercase} +.stat b{font-family:var(--disp);font-size:36px;line-height:1} +.stat em{font-style:normal;font-size:13px;color:var(--muted)} +/* the focused pick */ +.focus{background:var(--paper);color:var(--paperInk);display:flex;flex-wrap:wrap} +.focus .who{flex:1 1 280px;background:var(--panel);color:#fff;padding:22px;display:flex;flex-direction:column;gap:8px} +.focus .who .k{font-family:var(--disp);letter-spacing:2px;color:var(--gold);font-size:13px;text-transform:uppercase} +.focus .who b.n{font-family:var(--disp);font-size:30px;word-break:break-all} +.focus .who .kvr span{color:var(--muted)} +.focus .act{flex:999 1 520px;min-width:0;padding:22px;display:flex;flex-direction:column;gap:14px} +.focus h3{font-size:22px} +.steps{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px;font-size:13px;text-align:center} +.steps div{background:#e5e9f4;color:var(--paperMuted);padding:10px 6px} +.steps .done{background:var(--starter);color:#fff}.steps .next{background:var(--gold);color:var(--paperInk);font-weight:700} +.taps{display:flex;flex-wrap:wrap;gap:8px} +.taps button{background:var(--paperInk);color:#fff;border:0;padding:12px 14px;font-size:14px;cursor:pointer;text-align:left;font-family:var(--text)} +.taps button:hover{background:var(--panel2)} +textarea,input,select{font:inherit;font-size:15px;padding:10px 12px;border:2px solid #c6cde0;background:#fff;color:var(--paperInk);width:100%;border-radius:0} +.dark textarea,.dark input,.dark select{background:var(--bar);color:var(--ink);border-color:var(--line)} +textarea{min-height:84px;resize:vertical} +.thread{display:flex;flex-direction:column;gap:8px;max-height:260px;overflow:auto;padding:4px 0} +.msg{padding:10px 12px;background:#eef1f8;font-size:14px;max-width:85%;white-space:pre-wrap;word-break:break-word} +.msg.mine{background:var(--paperInk);color:#fff;align-self:flex-end} +.msg em{display:block;font-style:normal;font-size:11px;opacity:.7;margin-top:4px} +/* team grid */ +.team{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:12px} +.mini{background:var(--panel);padding:14px;display:flex;flex-direction:column;gap:6px;cursor:pointer;border:2px solid transparent;text-align:left;color:var(--ink);font:inherit} +.mini:hover,.mini.on{border-color:var(--gold)} +.mini b{font-family:var(--disp);font-size:18px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.mini .t{color:var(--gold);font-size:13px;text-transform:uppercase;letter-spacing:1px} +.mini .s{color:var(--muted);font-size:13px} +.help{display:flex;flex-direction:column;gap:8px} +.help .h{display:flex;gap:12px;align-items:center;justify-content:space-between;background:var(--panel2);padding:10px 12px;flex-wrap:wrap} +.help .h b{font-family:var(--disp);font-size:17px} +/* trading cards */ +.cards{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:20px} +.tc{border:6px solid var(--rookie);background:#e5e9f4;color:var(--paperInk);min-height:380px;display:flex;flex-direction:column} +.tc .tier{font-family:var(--disp);letter-spacing:3px;text-align:center;padding:6px;background:var(--rookie);color:var(--paperInk);text-transform:uppercase} +.tc .face{height:150px;display:flex;align-items:center;justify-content:center;font-family:var(--disp);font-size:48px;background:#c6cde0;color:var(--paperMuted)} +.tc .info{padding:12px;display:flex;flex-direction:column;gap:4px;font-size:13px} +.tc .info b{font-family:var(--disp);font-size:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.tc.starter{border-color:var(--starter);background:#eaf6ef}.tc.starter .tier{background:var(--starter);color:#fff}.tc.starter .face{background:#bfe3cf;color:#1f5c40} +.tc.pro{border-color:var(--pro);background:#e8eefc}.tc.pro .tier{background:var(--pro);color:#fff}.tc.pro .face{background:#c3d2fa;color:#1d3a96} +.tc.allstar{border-color:var(--allstar);background:#fff7df;box-shadow:0 0 0 3px var(--paperInk),0 0 24px rgba(255,201,60,.6)}.tc.allstar .tier{background:var(--allstar)}.tc.allstar .face{background:#ffe8a3;color:#7a5a00} +.tc.hof{border-color:var(--gold);background:#1a1030;color:#fff;box-shadow:0 0 0 3px var(--red)}.tc.hof .tier{background:linear-gradient(90deg,var(--gold),var(--red))}.tc.hof .face{background:#2a1a4a;color:var(--gold)} +.tc.faded{opacity:.55} +/* coach card */ +.ccard{display:flex;flex-wrap:wrap;gap:0;background:var(--paper);color:var(--paperInk)} +.ccard .l{flex:1 1 260px;background:var(--panel);color:#fff;padding:22px;display:flex;flex-direction:column;gap:8px;border-left:8px solid var(--gold)} +.ccard .l b{font-family:var(--disp);font-size:36px;word-break:break-all} +.ccard .r{flex:999 1 400px;padding:22px;display:flex;flex-direction:column;gap:12px} +/* steps strip on the front page */ +.how{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px} +.how .s{background:var(--panel);padding:18px;display:flex;flex-direction:column;gap:6px;border-top:4px solid var(--gold)} +.how .s b{font-family:var(--disp);font-size:40px;color:var(--gold);line-height:1} +.splitbar{display:flex;height:34px;font-size:12px;font-weight:700} +.splitbar div{display:flex;align-items:center;justify-content:center;color:var(--paperInk);overflow:hidden;white-space:nowrap} +.legal .card{background:var(--panel);padding:20px}.legal .card h2{font-size:22px;margin-bottom:8px}.legal .card p,.legal .card li{color:var(--muted)} +.signin{display:flex;flex-wrap:wrap;gap:10px} +/* footer */ +footer.foot{border-top:1px solid var(--line);padding:24px 0;text-align:center;color:var(--dim);font-size:13px} +footer.foot p{margin:4px 0}footer.foot a{color:var(--gold)}footer.foot .here{color:#fff;font-weight:700} +/* toasts */ +.toasts{position:fixed;right:24px;bottom:24px;z-index:50;display:flex;flex-direction:column;gap:8px;max-width:320px;pointer-events:none} +.toast{background:#fff;color:var(--paperInk);border-left:6px solid var(--gold);padding:12px 16px;font-size:14px;box-shadow:0 8px 24px rgba(0,0,0,.45);text-decoration:none;opacity:0;transform:translateY(10px);transition:all .35s;pointer-events:auto} +.toast.in{opacity:1;transform:none}.toast span{color:var(--paperMuted)}.toast.red{border-color:var(--red)} +.net-zone{text-align:center;margin:12px auto}.net-zone-label{font-size:11px;color:var(--dim)} +/* phones */ +@media (max-width:1000px){.pool,.team{grid-template-columns:repeat(2,minmax(0,1fr))}.cards{grid-template-columns:repeat(3,minmax(0,1fr))}} +@media (max-width:640px){ + .wrap{padding:0 16px}main.wrap{padding-top:20px;gap:24px} + .wm{font-size:24px}nav.top .links{gap:12px;font-size:13px} + .hero h1{font-size:38px}h2{font-size:24px} + .pool{grid-template-columns:minmax(0,1fr)}.team{grid-template-columns:repeat(2,minmax(0,1fr))}.cards{grid-template-columns:repeat(2,minmax(0,1fr));gap:12px} + .tc{min-height:300px}.tc .face{height:100px;font-size:36px} + .steps{grid-template-columns:repeat(2,minmax(0,1fr))}.how{grid-template-columns:minmax(0,1fr)} + .toasts{left:16px;right:16px;bottom:16px;max-width:none} +} +/* promo kit (kitpage.js) */ +.card{background:var(--panel);padding:20px;display:flex;flex-direction:column;gap:10px} +.btn.small{font-size:13px;padding:8px 12px}.btn.sec{background:var(--panel2);color:#fff} +.kit-row{display:flex;gap:10px;align-items:center;justify-content:space-between;border-bottom:1px solid var(--line);padding:8px 0;flex-wrap:wrap} +.kit-l{display:flex;flex-direction:column;gap:2px;min-width:0;flex:1}.kit-lab{font-size:12px;color:var(--gold);font-family:var(--disp);letter-spacing:1px;text-transform:uppercase;display:block} +.kit-url{font-size:13px;color:var(--muted);word-break:break-all}.kit-txt{margin:0;flex:1;min-width:0;color:var(--ink)} +.kit-tabs{display:flex;flex-wrap:wrap;gap:6px}.kit-tab{background:var(--panel2);color:var(--muted);border:0;padding:8px 12px;cursor:pointer;font:inherit;font-size:14px}.kit-tab.on{background:var(--gold);color:var(--paperInk)} +.kit-set{display:flex;flex-wrap:wrap;gap:16px;align-items:flex-start}.kit-fig{margin:0;display:flex;flex-direction:column;gap:6px;max-width:100%} +.kit-fig img{height:auto;max-width:100%;display:block}.kit-social img,.kit-square img{width:360px} +.kit-fig figcaption{font-size:13px;display:flex;flex-wrap:wrap;gap:6px;align-items:center}.kit-acts{display:flex;gap:6px;flex-wrap:wrap} +.kit-pre{white-space:pre-wrap;font:inherit;font-size:14px;color:var(--muted);margin:0;background:var(--bar);padding:12px} +.ccard .l .kvr{color:var(--muted)}.ccard .l .kvr span{color:var(--muted)}.ccard .l .kvr b{font-family:var(--text);font-size:15px;color:#fff;word-break:normal} +.splitbar div{font-size:11px;padding:0 4px} diff --git a/public/assets/join.js b/public/assets/join.js new file mode 100644 index 0000000..afa6c77 --- /dev/null +++ b/public/assets/join.js @@ -0,0 +1,44 @@ +// Get a Position: $10 one-time through DraftPosition. The server builds the buy() call for the signed-in member (POST /api/my/order, +// with a fresh line voucher when the member's sponsor line is not on the contract yet); the member's own wallet sends it. After the +// transaction confirms, the page waits for the watcher to record it (then the 5 instant picks show on My Team). +(async function () { + FX.renderNav('/join'); FX.renderFooter(); + const $ = FX.$, esc = FX.esc; + const c = await FX.getConfig().catch(() => ({})); + const P = c.position || { usd: 10, picksOnBuy: 5, maxQty: 10 }, S = c.split || {}; + $('jPrice').textContent = '$' + P.usd; $('jPicks').textContent = P.picksOnBuy; + $('splitbar').innerHTML = [['Sponsor ' + S.sponsorPct + '%', S.sponsorPct, '#ffc93c'], ['L2-5 ' + S.levelPct + '% each', S.levelPct * 4, '#ffe08a'], ['Pot ' + S.potPct + '%', S.potPct, '#1f8a5b'], ['5xYourTeam ' + S.companyPct + '%', S.companyPct, '#c6cde0']] + .map(x => '
' + esc(x[0]) + '
').join(''); + $('jQty').innerHTML = Array.from({ length: P.maxQty }, (_, i) => '').join(''); + const fmtPol = (wei, d) => { const k = d || 4; const s = (BigInt(wei) * 10n ** BigInt(k) / 10n ** 18n).toString().padStart(k + 1, '0'); return s.slice(0, -k) + '.' + s.slice(-k); }; + const me = await FX.getJSON('/api/me').catch(() => ({})); + if (!me.signedIn) { $('jSign').hidden = false; $('jSignBox').innerHTML = FX.signInBlock('/join'); FX.wireSignIn($('jSignBox')); } + async function quote() { + if (!c.shop || !c.shop.live) { $('jPol').textContent = 'Positions open when the contract goes live.'; $('jBuy').disabled = true; return; } + const q = await FX.getJSON('/api/quote?qty=' + $('jQty').value); + $('jPol').textContent = q.error ? q.error : 'about ' + fmtPol(q.wei, 2) + ' POL at today\'s Chainlink price'; + $('jBuy').disabled = !!q.error || !me.signedIn; + } + $('jQty').onchange = quote; quote(); + $('jBuy').onclick = async () => { + const say = (m, cls) => FX.status(m, cls); + try { + $('jBuy').disabled = true; + say('Connecting your wallet...'); + const addr = String(await FXWallet.activeAddress(await FXWallet.connect()) || '').toLowerCase(); + if (!addr) throw new Error('No wallet connected. Tap the button again and pick SafePal or any other crypto wallet.'); + if (addr !== me.address) throw new Error('Your wallet is connected as ' + FX.short(addr) + ', but you are signed in here as ' + FX.short(me.address) + '. A position goes to the wallet that pays, so switch your wallet app to ' + FX.short(me.address) + ', or sign out and sign in with ' + FX.short(addr) + '.'); + const od = await FX.post('/api/my/order', { qty: Number($('jQty').value) }); if (od.error) throw new Error(od.error); + const value = BigInt(od.value); + try { const bal = await FXWallet.balance(addr); if (bal < value) throw new Error('This wallet holds ' + fmtPol(bal) + ' POL. The position needs about ' + fmtPol(value) + ' POL plus a little gas. Add POL on Polygon and try again.'); } catch (e) { if (/holds/.test(e.message)) throw e; } + say('Confirm the payment in your wallet: about ' + fmtPol(value) + ' POL ($' + od.usd + '). Anything above the exact price comes straight back in the same transaction.'); + const hash = await FXWallet.sendTx(od.to, od.data, od.value); + say('Payment sent. Waiting for Polygon to confirm it...'); + const r = await FXWallet.waitTx(hash); + if (r.status !== '0x1') throw new Error('The transaction did not go through, so nothing was charged except gas.'); + FX.post('/api/my/paid', {}).catch(() => {}); + say('Confirmed on Polygon. Your instant picks show on My Team within about a minute.', 'ok'); + for (let i = 0; i < 72; i++) { await new Promise(res => setTimeout(res, 5000)); if (i % 4 === 3) FX.post('/api/my/paid', {}).catch(() => {}); const d = await FX.getJSON('/api/my'); if (d.coach) { location.href = '/team'; return; } } + } catch (e) { say(String(e && e.message || e).slice(0, 400), 'err'); $('jBuy').disabled = false; } + }; +})(); diff --git a/public/assets/kitpage.js b/public/assets/kitpage.js new file mode 100644 index 0000000..9865404 --- /dev/null +++ b/public/assets/kitpage.js @@ -0,0 +1,51 @@ +// Promote page renderer (2026-11-14). Draws a promo kit (GET /api/promo-kit) into a container: links, creatives grouped by angle, +// swipe lines, headlines, an email and social posts, each with a copy button. Same file on Downline Banners, Viral Banner Blitz, ViralAdBlitz and 5xYourTeam; +// the page script decides the username and the look comes from the site's own CSS (.card, .btn, .kit-*). +window.KitPage = (function () { + const esc = s => String(s == null ? '' : s).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); + async function copy(text, btn) { + try { await navigator.clipboard.writeText(text); } catch (e) { + const t = document.createElement('textarea'); t.value = text; document.body.appendChild(t); t.select(); try { document.execCommand('copy'); } catch (e2) {} t.remove(); + } + if (btn) { const o = btn.textContent; btn.textContent = 'Copied'; setTimeout(() => { btn.textContent = o; }, 1400); } + } + const TXT = []; + const cb = (text, label, cls) => { TXT.push(text); return ''; }; + // on the kit's own site, show creatives from this origin (same files; the copied URL stays absolute) + function local(url, k) { try { const u = new URL(url); return u.hostname === k.site && location.hostname !== k.site ? u.pathname : url; } catch (e) { return url; } } + const row = (label, url, cls) => '
' + esc(label) + '' + esc(url) + '
' + cb(url, 'Copy link', cls) + '
'; + function render(root, k) { + TXT.length = 0; + const angles = []; const by = {}; + (k.creatives || []).forEach(c => { if (!by[c.angle]) { by[c.angle] = []; angles.push(c); } by[c.angle].push(c); }); + let h = ''; + h += '

Your links

' + (k.username ? '

Every link, creative and line below carries ' + esc(k.username) + '.

' : '

Add your network username above so these links carry it.

') + + k.links.map(l => row(l.label, l.url, '') + (l.tracked ? row(l.label + ', tracked', l.tracked, 'sec') : '')).join('') + + (k.links.some(l => l.tracked) ? '

A tracked link goes through LinkSpin first, so the network can see which site sent the visit, then opens the same page with your username. Use either one.

' : '') + '
'; + h += '

Creatives

Download them, or copy the HTML: it already links to you.

' + + angles.map((c, i) => '').join('') + '
'; + angles.forEach((a, i) => { + h += '
' + by[a.angle].map(c => + '
' + esc(k.name + ', ' + c.label) + '' + + '
' + esc(c.label) + ' ' + c.w + 'x' + c.h + 'Download' + cb(c.url, 'Copy URL') + cb(c.html, 'Copy HTML') + '
').join('') + '
'; + }); + h += '
'; + h += '

Short lines

For chats, comments, text ads and signatures.

' + k.lines.map(t => '

' + esc(t) + '

' + cb(t) + '
').join('') + '
'; + h += '

Headlines

' + k.headlines.map(t => '

' + esc(t) + '

' + cb(t) + '
').join('') + '
'; + h += '

Email

Subject' + esc(k.email.subject) + '

' + cb(k.email.subject, 'Copy subject') + '
' + + '
' + esc(k.email.body) + '
' + cb(k.email.body, 'Copy email') + '
'; + h += '

Social posts

' + k.posts.map(t => '
' + esc(t) + '
' + cb(t, 'Copy post') + '
').join('') + '
'; + if (k.note) h += '

' + esc(k.note) + '

'; + root.innerHTML = h; + root.querySelectorAll('[data-kc]').forEach(b => b.addEventListener('click', () => copy(TXT[Number(b.dataset.kc)], b))); + root.querySelectorAll('[data-ka]').forEach(b => b.addEventListener('click', () => { + root.querySelectorAll('[data-ka]').forEach(x => x.classList.toggle('on', x === b)); + root.querySelectorAll('[data-ks]').forEach(s => { s.hidden = s.dataset.ks !== b.dataset.ka; }); + })); + } + async function load(root, u) { + const r = await fetch('/api/promo-kit' + (u ? '?u=' + encodeURIComponent(u) : ''), { cache: 'no-store' }); + const k = await r.json(); render(root, k); return k; + } + return { render, load, copy }; +})(); diff --git a/public/assets/ledger.js b/public/assets/ledger.js new file mode 100644 index 0000000..6409a17 --- /dev/null +++ b/public/assets/ledger.js @@ -0,0 +1,31 @@ +// Live ledger (trust pack): every position with every share paid in the same transaction (sponsor 25%, levels 2-5 5%, with each +// person's place in the buyer's line), who was passed over, the Best Coach pot and the company, plus every Best Coach payout, from +// /api/ledger, refreshed every 30 seconds. +(function () { + FX.renderNav('/ledger'); FX.renderFooter(); + const esc = FX.esc; + const pol = w => FX.polOf(w) + ' POL'; + const usd = c => '$' + (Number(c || 0) / 100).toFixed(2); + const who = (a, nm) => nm ? '@' + esc(nm) : '' + esc(FX.short(a || '')) + ''; + async function load() { + let d; try { d = await FX.getJSON('/api/ledger?n=100'); } catch (e) { return; } if (!d || !d.items) return; + const ex = d.explorer || 'https://polygonscan.com'; const t = d.totals || {}; + document.getElementById('totals').innerHTML = '
Positions on-chain' + FX.n(t.positions) + '
' + + '
To the Best Coach pot' + pol(t.potWei) + '10% of every position
' + + '
In positions' + usd(t.usdCents) + 'at the price when bought
' + + '
Withdrawals needed0every share is paid in the same transaction
'; + const body = document.querySelector('#rows tbody'); + if (!d.items.length) body.innerHTML = 'No positions yet. The first one shows here within a minute of its transaction.'; + else body.innerHTML = d.items.map(r => { + const link = 'verify'; + const pays = (r.pays || []).map(p => p.level === 0 ? '5xYourTeam: ' + pol(p.wei) : p.level === 6 ? 'Best Coach pot: ' + pol(p.wei) + : (p.level === 1 ? 'Sponsor 25%' : 'Level ' + p.level + ' 5%') + ': ' + pol(p.wei) + ' to ' + (p.to ? who(p.to, p.name) : 'sponsor') + (p.depth && p.depth !== p.level ? ' (place ' + p.depth + ')' : '') + (p.failed ? ' (bounced, waiting in the contract for them to claim)' : '')).join('
'); + const over = (r.passedOver || []).length ? '
Passed over (no position yet): ' + r.passedOver.map(o => (o.name ? '@' + esc(o.name) : esc(FX.short(o.who))) + ' at place ' + o.depth).join(', ') + '' : ''; + return '' + FX.when(r.at) + '' + who(r.buyer, r.buyerName) + ' bought ' + esc(r.what) + ' for ' + usd(r.usdCents) + '' + pays + over + '' + link + ''; + }).join(''); + const pb = document.querySelector('#payouts tbody'); + pb.innerHTML = (d.payouts || []).length ? d.payouts.map(p => '' + esc(p.week) + '#' + esc(p.rank) + ' ' + who(p.coach, p.username) + '' + pol(p.wei) + 'verify').join('') + : 'No Best Coach payouts yet. Each one is listed here with its transaction.'; + } + load(); setInterval(load, 30000); +})(); diff --git a/public/assets/misc.js b/public/assets/misc.js new file mode 100644 index 0000000..e0ba2cf --- /dev/null +++ b/public/assets/misc.js @@ -0,0 +1,46 @@ +// Small pages: promote (the kit), builder (my CryptoTeamBuild builder IDs), admin, legal. One file, chosen by data-page on . +(async function () { + const page = document.body.dataset.page; const $ = FX.$, esc = FX.esc; + if (page === 'legal') { FX.renderNav(''); FX.renderFooter(); return; } + if (page === 'promote') { + FX.renderNav(''); FX.renderFooter(); + const RE = /^(?:[A-Za-z0-9_.-]{2,40}|0x[0-9a-fA-F]{40})$/; + let u = new URLSearchParams(location.search).get('u') || ''; + if (!RE.test(u)) { u = ''; try { const me = await FX.getJSON('/api/me'); if (me.signedIn) u = me.username || me.address || ''; } catch (e) {} } + if (!u) { try { u = localStorage.getItem('kit.u') || ''; } catch (e) {} if (!RE.test(u)) u = ''; } + $('whoIn').value = u; + const show = async name => { try { await KitPage.load($('kit'), name); FX.status(''); } catch (e) { FX.status('Could not load the kit. Try again in a moment.', 'err'); } }; + $('whoForm').addEventListener('submit', e => { e.preventDefault(); const v = $('whoIn').value.trim().replace(/^@/, ''); if (v && !RE.test(v)) return FX.status('That does not look like a username.', 'err'); try { localStorage.setItem('kit.u', v); } catch (e2) {} show(v); }); + return show(u); + } + if (page === 'builder') { + FX.renderNav(''); FX.renderFooter(); + const me = await FX.getJSON('/api/me'); + if (!me.signedIn) { $('bSign').hidden = false; $('bSignBox').innerHTML = FX.signInBlock('/builder'); FX.wireSignIn($('bSignBox')); return; } + const d = await FX.getJSON('/api/my/builder'); if (d.error) return FX.status(d.error, 'err'); + $('bList').innerHTML = d.programs.map(p => '
' + esc(p.name) + '' + esc(p.example) + '
').join(''); + document.querySelectorAll('[data-s]').forEach(b => b.onclick = async () => { const inp = document.querySelector('[data-p="' + b.dataset.s + '"]'); const r = await FX.post('/api/my/builder', { program: b.dataset.s, refId: inp.value }); FX.status(r.error || 'Saved. Your picks see this link when they open your builder links.', r.error ? 'err' : 'ok'); if (!r.error) inp.value = r.refId; }); + return; + } + if (page === 'admin') { + FX.renderNav(''); FX.renderFooter(); + let tok = ''; try { tok = sessionStorage.getItem('fx.admin') || ''; } catch (e) {} + const H = () => ({ 'x-admin-token': tok, 'Content-Type': 'application/json' }); + const show = (el, o) => { el.textContent = JSON.stringify(o, null, 2); }; + const load = async () => { if (!tok) return; show($('statusOut'), await FX.getJSON('/api/admin/status', { headers: H() })); show($('potOut'), await FX.getJSON('/api/admin/pot', { headers: H() })); }; + $('tokForm').addEventListener('submit', e => { e.preventDefault(); tok = $('tok').value.trim(); try { sessionStorage.setItem('fx.admin', tok); } catch (x) {} load(); }); + $('tickBtn').onclick = async () => { show($('statusOut'), await FX.getJSON('/api/admin/tick', { method: 'POST', headers: H(), body: '{}' })); }; + $('oldFile').addEventListener('change', async e => { const f = e.target.files[0]; if (!f) return; const r = await fetch('/api/admin/oldrefs', { method: 'POST', headers: H(), body: await f.text() }); show($('oldOut'), await r.json()); }); + return load(); + } + if (page === 'draftday') { + // the 1080 x 1080 Draft Day results card (tools/art.mjs renders it to PNG for Telegram); no nav, no footer + const wk = location.pathname.split('/').pop(); + const d = await FX.getJSON('/api/draftday?week=' + encodeURIComponent(wk)); + $('ddWeek').textContent = 'WEEK ' + FX.weekNo(wk); + $('ddRows').innerHTML = (d.rows || []).slice(0, 6).map(r => '
' + esc(r.slot) + '@' + esc(r.coach) + ' takes @' + esc(r.person) + '
').join('') || '
No picks yet
'; + $('ddStats').textContent = FX.n(d.players || 0) + ' players drafted ยท ' + FX.n(d.coaches || 0) + ' coaches'; + $('ddPot').textContent = 'Best Coach pot: ' + FX.polOf(d.potWei || 0) + ' POL'; + document.body.dataset.ready = '1'; + } +})(); diff --git a/public/assets/team.js b/public/assets/team.js new file mode 100644 index 0000000..f7589bd --- /dev/null +++ b/public/assets/team.js @@ -0,0 +1,81 @@ +// My Team (the coach's dashboard): stat tiles, instant picks left, the focused pick card (scouting stats, the getting-started +// steps, one-tap messages, the message composer and thread, release), the rest of the team, who to help first, the draft queue. +// Someone who is a pick sees their coach here instead (steps, the thread, the coach's builder links). Messages go through the +// site only; no contact details are ever shown. Every figure comes from /api/my. +(async function () { + FX.renderNav('/team'); FX.renderFooter(); + const $ = FX.$, esc = FX.esc; + const c = await FX.getConfig().catch(() => ({})); + const me = await FX.getJSON('/api/me'); + if (!me.signedIn) { + if (await FX.silentSso('/team')) return; + $('signin').hidden = false; $('signinBox').innerHTML = FX.signInBlock('/team'); FX.wireSignIn($('signinBox')); return; + } + $('signout').hidden = false; $('signout').onclick = async () => { await FX.post('/api/auth/logout'); location.reload(); }; + const pol = w => w == null ? 'not tracked yet' : FX.polOf(w) + ' POL'; + let D = null, focus = null; + const stat = (k, v, note) => '
' + k + '' + v + '' + (note ? '' + note + '' : '') + '
'; + const stepsHtml = steps => '
' + steps.map(s => '
' + esc(s.label) + (s.next ? ' (next)' : '') + '
').join('') + '
'; + const thread = items => items.length ? items.map(x => '
' + esc(x.text) + '' + esc(FX.when(x.at)) + '
').join('') : '

No messages yet. Say hello: they see it in their member area.

'; + + async function load() { + const d = await FX.getJSON('/api/my'); if (d.error) { FX.status(d.error, 'err'); return; } + D = d; $('dash').hidden = false; + $('hello').textContent = d.username ? '@' + d.username : FX.short(d.address); + // a pick: their coach + if (d.myCoach) { + const mc = d.myCoach; $('myCoach').hidden = false; + $('mcName').textContent = '@' + mc.coach; $('mcTier').textContent = mc.tierName + ' ยท on the team since ' + FX.when(mc.since); + $('mcSteps').innerHTML = stepsHtml(mc.steps); + $('mcThread').innerHTML = thread(mc.messages.map(x => ({ mine: x.dir === 'out', text: x.text, at: x.at }))); + $('mcSend').onclick = async () => { const t = $('mcText').value.trim(); if (!t) return; const r = await FX.post('/api/my/message', { pick: mc.pickId, text: t }); if (r.error) return FX.status(r.error, 'err'); $('mcText').value = ''; load(); }; + $('mcBuilder').innerHTML = mc.builder.slice(0, 8).map(p => '' + esc(p.name) + '').join(' ') || 'No builder links yet.'; + } + if (!d.coach && !d.picks.length) { $('noCoach').hidden = false; if (!d.myCoach) $('coachTools').hidden = true; return; } + $('coachTools').hidden = false; + const s = d.stats; + $('stats').innerHTML = stat('On my team', s.onTeam, s.open + ' open of ' + s.maxOpen) + stat('Started this week', s.startedThisWeek, 'payouts on or a first purchase') + + stat('Next draft spot', s.nextSpot ? '#' + s.nextSpot : '-', 'earned by this week\'s starts') + stat('Back to pool soon', s.backSoon, 'within 24 hours'); + $('credits').hidden = !(d.credits > 0); + $('creditsN').textContent = d.credits + ' instant pick' + (d.credits === 1 ? '' : 's'); + if (d.page) { $('myPage').hidden = false; $('myPageLink').href = d.page; $('myPageLink').textContent = d.page.replace(/^https:\/\//, ''); } + const team = d.picks.filter(p => ['open', 'done', 'kept'].includes(p.status)); + if (!focus || !team.some(p => p.id === focus)) focus = (d.help[0] && d.help[0].pickId) || (team[0] && team[0].id) || null; + paintFocus(team.find(p => p.id === focus)); + const rest = team.filter(p => p.id !== focus); + $('team').innerHTML = rest.length ? rest.map(p => '').join('') + : '

' + (team.length ? 'Nobody else on the team yet. ' : 'No picks yet. ') + (d.credits ? 'Use your instant picks on the Draft Board.' : 'Your next picks come in the Monday draft.') + '

'; + document.querySelectorAll('[data-f]').forEach(b => b.onclick = () => { focus = Number(b.dataset.f); load(); }); + $('help').innerHTML = d.help.length ? d.help.slice(0, 8).map(h => '
@' + esc(h.username || 'player') + '
' + esc(h.why) + '
').join('') + : '

Nobody needs a nudge right now.

'; + document.querySelectorAll('[data-f2]').forEach(b => b.onclick = () => { focus = Number(b.dataset.f2); load().then(() => $('focus').scrollIntoView({ behavior: 'smooth' })); }); + const past = d.picks.filter(p => p.status === 'returned'); + $('pastWrap').hidden = !past.length; + $('past').innerHTML = past.slice(0, 12).map(p => '@' + esc(p.username || 'player') + '').join(' '); + $('queue').innerHTML = d.queue.length ? '

' + d.queue.length + ' player' + (d.queue.length === 1 ? '' : 's') + ' on your queue. If you are away when your pick comes up, the first one still available is drafted for you. Edit it on the Draft Board.

' : '

Your queue is empty: if you are away when your pick comes up, the best available player by scouting score is drafted for you. Add players from the Draft Board.

'; + } + async function paintFocus(p) { + const el = $('focus'); if (!p) { el.hidden = true; return; } el.hidden = false; + const label = p.kind === 'instant' ? 'INSTANT PICK' : 'ROUND ' + (p.round || '?') + ' PICK'; + $('fKick').textContent = label + ' ยท ' + p.tierName.toUpperCase(); + $('fName').textContent = '@' + (p.username || 'player'); + $('fWhen').textContent = 'Picked ' + FX.when(p.at) + (p.status === 'open' ? ' ยท ' + (p.daysLeft ? p.daysLeft + ' day' + (p.daysLeft === 1 ? '' : 's') + ' left to start' : 'goes back to the pool today') : ' ยท started, stays on your team'); + $('fStats').innerHTML = [['Game plays', p.plays == null ? 'not tracked yet' : FX.n(p.plays) + (p.game ? ' (' + p.game + ')' : '')], ['Earned in games', pol(p.gameWei)], ['Earned surfing', pol(p.surfWei)], ['Came from', p.door || 'not tracked yet'], ['Last seen', FX.ago(p.lastSeen)]] + .map(r => '
' + r[0] + '' + esc(r[1]) + '
').join(''); + $('fSteps').innerHTML = stepsHtml(p.steps); + const h = D.help.find(x => x.pickId === p.id); + const taps = [h ? h.say : 'Great work so far. Anything I can help with?', 'Any questions so far? Reply here and I will walk you through it.', p.game ? 'Nice run in ' + p.game + '!' : 'Welcome to the team! I am here to help.']; + $('fTaps').innerHTML = taps.map((t, i) => '').join(''); + document.querySelectorAll('[data-tap]').forEach(b => b.onclick = () => { $('fText').value = taps[Number(b.dataset.tap)]; $('fText').focus(); }); + $('fSend').onclick = async () => { const t = $('fText').value.trim(); if (!t) return; const r = await FX.post('/api/my/message', { pick: p.id, text: t }); if (r.error) return FX.status(r.error, 'err'); $('fText').value = ''; FX.status('Sent. They see it in their member area.', 'ok'); thr(); }; + $('fRelease').hidden = p.status !== 'open'; + $('fRelease').onclick = async () => { if (!confirmBox()) return; const r = await FX.post('/api/my/release', { pick: p.id }); FX.status(r.error || 'Released back to the pool.', r.error ? 'err' : 'ok'); load(); }; + async function thr() { const t = await FX.getJSON('/api/my/messages?pick=' + p.id); $('fThread').innerHTML = thread(t.items || []); } + thr(); + } + // releasing is a commitment decision: ask in the page (no browser dialogs) + let armed = 0; function confirmBox() { if (Date.now() - armed < 6000) { armed = 0; return true; } armed = Date.now(); FX.status('Tap "Release to the pool" again within 6 seconds to confirm. They go back to the pool for another coach, and it still counts as one of their two adoptions.', ''); return false; } + await load(); + setInterval(() => { load().catch(() => {}); }, 30000); +})(); diff --git a/public/assets/wallet.js b/public/assets/wallet.js new file mode 100644 index 0000000..6b64203 --- /dev/null +++ b/public/assets/wallet.js @@ -0,0 +1,233 @@ +// 5xYourTeam wallet sign-in: the VBB / Downline Banners wallet.js (same AppKit build, chain guard, dead-session recovery) +// with its buy flow (2026-11-14): sendTx() hard-guards the chain, sets Polygon's fee floor from /api/gas and recovers a dead +// WalletConnect session once; waitTx() polls /api/tx; balance() is the pre-flight check. The page builds the call on the server. +window.FXWallet = (function () { + const pad = v => BigInt(v).toString(16).padStart(64, '0'); + const padAddr = a => { if (!a) return pad(0); if (!/^0x[0-9a-fA-F]{40}$/.test(a)) throw new Error('Bad address: ' + a); return a.slice(2).toLowerCase().padStart(64, '0'); }; + // Normalize a chainId to a decimal number. eth_chainId is meant to return a + // hex string, but some wallets return a number or a decimal string โ€” compare + // numerically so a wallet's shape never crashes the flow. + const chainNum = v => { + if (v == null) return NaN; + if (typeof v === 'number') return v; + const s = String(v).trim(); + return /^0x/i.test(s) ? parseInt(s, 16) : parseInt(s, 10); + }; + const APPKIT_URL = 'https://cdn.jsdelivr.net/npm/@reown/appkit-cdn@1.8.23/dist/appkit.js'; + + let modal = null, akPromise = null, provider = null; + + async function initAppKit(c) { + if (modal) return modal; + if (akPromise) return akPromise; + akPromise = (async () => { + const mod = await import(APPKIT_URL); + const { createAppKit, WagmiAdapter, networks } = mod; + const netMap = { 80002: networks.polygonAmoy, 137: networks.polygon, 31337: networks.hardhat || networks.localhost }; + const base = netMap[Number(c.chainId)] || networks.polygonAmoy; + // Override the chain's RPC with our clean public endpoint. AppKit's built-in + // networks advertise the WalletConnect RPC proxy + // (rpc.walletconnect.org/v1/?chainId=โ€ฆ&projectId=โ€ฆ) as the chain RPC, and + // wallets reject that query-string URL as "Invalid URL" when adding/switching + // the network โ€” the cause of Trust's "Invalid URL", MetaMask's switch loop, + // and the failed mobile buy (the chain switch never completed). + const rpc = String(c.rpc || '').trim(); + const net = rpc ? Object.assign({}, base, { rpcUrls: { default: { http: [rpc] }, public: { http: [rpc] } } }) : base; + // Accept the wallet's usual networks too, so AppKit doesn't trap the user in + // its own "Switch Network" modal โ€” that modal loops on a testnet the wallet + // can't auto-add. We switch to `net` ourselves (wallet_addEthereumChain adds + // + switches in one step) and sendTx hard-guards the chain before signing. + const allNets = [net]; + for (const k of ['polygon', 'mainnet']) { + try { const n = networks[k]; if (n && n.id !== net.id) allNets.push(n); } catch (e) {} + } + const projectId = String(c.walletConnectProjectId || '').trim(); + const wagmiAdapter = new WagmiAdapter({ networks: allNets, projectId }); + modal = createAppKit({ + adapters: [wagmiAdapter], networks: allNets, projectId, defaultNetwork: net, + metadata: { name: '5xYourTeam', description: 'The weekly draft for people who need a sponsor.', + url: location.origin, icons: [location.origin + '/art/icon-192.png'] }, + features: { analytics: false, email: false, socials: [] }, + // Picker order: wallets without Trust's balance-proportion block go first. + // Trust Wallet is NOT excluded; it just drops out of the featured row into + // "All wallets" (Marty, 2026-09-09: move Trust to the bottom, not off). + featuredWalletIds: [ + '0b415a746fb9ee99cce155c2ceca0c6f6061b1dbca2d722b3ba16381d0562150', // SafePal (recommended, listed first) + 'c57ca95b47569778a828d19178114f4db188b89b763c899ba0be274e97267d96', // MetaMask + 'a797aa35c0fadbfc1a53e7f675162ed5226968b44a19ee3d24385c64d1d3c393', // Phantom + 'fd20dc426fb37566d803205b19bbc1d4096b248ac04548e3cfb6b3a38bd033aa' // Coinbase Wallet + ] + }); + return modal; + })(); + return akPromise; + } + + function currentAddress() { try { return (modal && modal.getAddress && modal.getAddress()) || null; } catch (e) { return null; } } + + function waitForConnection(timeoutMs) { + if (currentAddress()) return Promise.resolve(currentAddress()); + return new Promise((resolve, reject) => { + let done = false, unsub = null; + const finish = (addr, err) => { if (done) return; done = true; try { unsub && unsub(); } catch (e) {} err ? reject(err) : resolve(addr); }; + try { unsub = modal.subscribeAccount(acc => { if (acc && acc.isConnected && acc.address) finish(acc.address); }); } catch (e) {} + const t0 = Date.now(); + (function poll() { + if (done) return; + const a = currentAddress(); + if (a) return finish(a); + if (Date.now() - t0 > (timeoutMs || 180000)) return finish(null, new Error('Wallet connection timed out. Tap Connect and try again.')); + setTimeout(poll, 400); + })(); + }); + } + + async function resolveProvider() { + for (let i = 0; i < 20; i++) { + try { const p = modal.getWalletProvider ? await Promise.resolve(modal.getWalletProvider()) : null; if (p && p.request) return p; } catch (e) {} + await new Promise(r => setTimeout(r, 300)); + } + throw new Error('Could not reach your wallet. Try connecting again.'); + } + + function eth() { if (!provider) throw new Error('Connect your wallet first.'); return provider; } + const isInjected = () => !!(provider && window.ethereum && (provider === window.ethereum || provider.isMetaMask)); + // the account the wallet will actually sign with: for an injected wallet (MetaMask + // extension) that is its active account, which can differ from AppKit's cached one + async function activeAddress(fallback) { + if (isInjected()) { try { const a = await provider.request({ method: 'eth_accounts' }); if (a && a[0]) return a[0]; } catch (e) {} } + return fallback || currentAddress(); + } + // Force the wallet's own account picker. Injected wallets stay connected to the + // site, so a plain disconnect/reconnect never shows one: asking for permissions + // again makes MetaMask open its account-selection prompt, and whatever the user + // ticks becomes the active account. WalletConnect wallets fall back to a fresh + // session (the picker + the wallet app's own account choice). + async function pickAccount() { + const c = await FX.getConfig(); + await initAppKit(c); + const inj = window.ethereum; + if (inj && inj.request) { + try { + await inj.request({ method: 'wallet_requestPermissions', params: [{ eth_accounts: {} }] }); + const accs = await inj.request({ method: 'eth_accounts' }); + if (accs && accs[0]) { provider = inj; await ensureChain(c).catch(() => {}); return accs[0]; } + } catch (e) { + if (e && (e.code === 4001 || /reject|denied/i.test(String(e.message || '')))) throw new Error('You closed the account picker. Pick the account you want and try again.'); + } + } + return freshConnect(c); + } + + // A WalletConnect session can die underneath AppKit's cached "connected" + // state: the wallet app rejects or kills it (Trust does this after its own + // security stop), the phone sleeps, the relay drops. AppKit still reports an + // address, so the next request fails with a "disconnected" style error. + // Detect that, wipe the stale session, and re-open the picker for a fresh one. + const DEAD_RE = /disconnect|not connected|no matching key|session (topic|expired|deleted|not found)|call connect|please call connect|missing or invalid|relay/i; + const isDead = e => DEAD_RE.test(String((e && e.message) || e || '')); + async function freshConnect(c) { + try { FX.status('Your wallet session dropped. Reconnect in the pickerโ€ฆ'); } catch (e) {} + await disconnect(); + try { await modal.open(); } catch (e) {} + const addr = await waitForConnection(180000); + try { if (modal && modal.close) await modal.close(); } catch (e) {} + provider = await resolveProvider(); + await ensureChain(c).catch(() => {}); + return addr; + } + + async function connect() { + const c = await FX.getConfig(); + await initAppKit(c); + let addr = currentAddress(); + if (!addr) { + // give AppKit a moment to rehydrate an existing session before popping the + // picker โ€” otherwise an already-connected wallet still gets the modal + for (let i = 0; i < 8 && !addr; i++) { await new Promise(r => setTimeout(r, 150)); addr = currentAddress(); } + } + if (!addr) { try { await modal.open(); } catch (e) {} addr = await waitForConnection(180000); } + try { if (modal && modal.close) await modal.close(); } catch (e) {} // dismiss the picker once we're connected + provider = await resolveProvider(); + // probe the session: a dead WalletConnect session answers with a disconnect error + try { await provider.request({ method: 'eth_chainId' }); } + catch (e) { if (isDead(e)) return freshConnect(c); } + await ensureChain(c).catch(() => {}); // AppKit already connects on the right network; switch is best-effort + return addr; + } + + async function ensureChain(c) { + const want = '0x' + Number(c.chainId).toString(16); + let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) { return; } + if (chainNum(cur) === Number(c.chainId)) return; + try { + await eth().request({ method: 'wallet_switchEthereumChain', params: [{ chainId: want }] }); + } catch (e) { + // any failure (not just 4902): try to add the chain โ€” wallet_addEthereumChain + // adds AND switches in one step, which is what unblocks wallets that can't + // otherwise reach a chain they don't already have (e.g. a testnet). + const addParams = { chainId: want, chainName: c.chainName, nativeCurrency: { name: 'POL', symbol: 'POL', decimals: 18 }, rpcUrls: [c.rpc] }; + if (c.explorer && /^https?:\/\//i.test(c.explorer)) addParams.blockExplorerUrls = [c.explorer]; + try { await eth().request({ method: 'wallet_addEthereumChain', params: [addParams] }); } catch (e2) {} + } + } + + // SIWE: challenge -> personal_sign -> verify (server sets the session cookie) + async function signIn(opts) { + const addr = (opts && opts.pick) ? await pickAccount() : await activeAddress(await connect()); + const ch = await (await fetch('/api/auth/challenge', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr }) })).json(); + if (ch.error) throw new Error(ch.error); + // hex-encode the message (Trust and others require hex for personal_sign) + const hexMsg = '0x' + Array.from(new TextEncoder().encode(ch.message)).map(b => b.toString(16).padStart(2, '0')).join(''); + const sig = await eth().request({ method: 'personal_sign', params: [hexMsg, addr] }); + const r = await (await fetch('/api/auth/verify', { method: 'POST', + headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ address: addr, signature: sig, asPosition: !!(opts && opts.asPosition) }) })).json(); + if (r.error) throw new Error(r.error); + return r; + } + + async function sendTx(to, data, valueHex) { + const c = await FX.getConfig(); + const addr = await connect(); + const wantNum = Number(c.chainId); + let cur; try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {} + if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum) { + await ensureChain(c); + try { cur = await eth().request({ method: 'eth_chainId' }); } catch (e) {} + if (!isNaN(chainNum(cur)) && chainNum(cur) !== wantNum) + throw new Error('Your wallet is on the wrong network. Switch it to ' + (c.chainName || 'Polygon') + ', then try again.'); + } + const tx = { from: await activeAddress(addr), to, data }; + if (valueHex) tx.value = valueHex; + try { const g = await (await fetch('/api/gas')).json(); if (g && g.maxPriorityFeePerGas && g.maxFeePerGas) { tx.maxPriorityFeePerGas = g.maxPriorityFeePerGas; tx.maxFeePerGas = g.maxFeePerGas; } } catch (e) {} + try { return await eth().request({ method: 'eth_sendTransaction', params: [tx] }); } + catch (e) { + if (!isDead(e)) throw e; + tx.from = await freshConnect(c); + return eth().request({ method: 'eth_sendTransaction', params: [tx] }); + } + } + async function waitTx(hash) { + for (let i = 0; i < 120; i++) { + try { const r = await (await fetch('/api/tx/' + hash)).json(); if (r.found) return r; } catch (e) { /* app switch on a phone: keep polling */ } + await new Promise(res => setTimeout(res, 2500)); + } + throw new Error('Still waiting for the transaction. Check it on the explorer; your position shows once it confirms.'); + } + async function balance(addr) { + await connect(); + return BigInt(await eth().request({ method: 'eth_getBalance', params: [addr || currentAddress(), 'latest'] })); + } + + async function disconnect() { + // AppKit's disconnect can hang on the WalletConnect relay (esp. mobile) โ€” + // never block on it, so the UI can't get stuck "disconnecting". + try { if (modal && modal.disconnect) await Promise.race([modal.disconnect(), new Promise(r => setTimeout(r, 1200))]); } catch (e) {} + provider = null; + try { Object.keys(localStorage).forEach(k => { if (/wc@2|walletconnect|w3m|wcm|reown|wagmi|appkit/i.test(k)) localStorage.removeItem(k); }); } catch (e) {} + } + + function walletName() { try { const w = modal && modal.getWalletInfo && modal.getWalletInfo(); return (w && w.name) || ''; } catch (e) { return ''; } } + return { connect, signIn, sendTx, waitTx, balance, disconnect, address: currentAddress, activeAddress, pickAccount, walletName }; +})(); diff --git a/public/builder.html b/public/builder.html new file mode 100644 index 0000000..72d887a --- /dev/null +++ b/public/builder.html @@ -0,0 +1,35 @@ + + + + +My Builder Links | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

MY BUILDER LINKS

The CryptoTeamBuild downline builder

Save your referral ID for the programs you are in. Your picks see your link for each one on their My Team page.

+ + +
+
+ + + + + diff --git a/public/cards.html b/public/cards.html new file mode 100644 index 0000000..d740c3a --- /dev/null +++ b/public/cards.html @@ -0,0 +1,34 @@ + + + + +Card Collection | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

CARD COLLECTION

Trading cards: they level up as your picks do

Public cards show milestones, never earnings.

+ +

The five tiers

+

Rookie when drafted, Starter when they link a wallet, Pro when they switch on payouts, All-Star at their first purchase, Hall of Fame when they hold a position of their own and coach a team.

+
+ + + + diff --git a/public/coach.html b/public/coach.html new file mode 100644 index 0000000..949f0ca --- /dev/null +++ b/public/coach.html @@ -0,0 +1,33 @@ + + + + +Coach | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+
COACH
+

The team

Milestones only. Every Monday this coach drafts people who joined the network without a sponsor and helps them get started.

+
+
+ + + + diff --git a/public/contract.html b/public/contract.html new file mode 100644 index 0000000..f94c1b7 --- /dev/null +++ b/public/contract.html @@ -0,0 +1,32 @@ + + + + +The Contract | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

CONTRACT

Check the contract yourself

Read live from Polygon. No owner withdraw, no proxy, the split fixed in the code.

+
+
+ + + + diff --git a/public/disclaimer.html b/public/disclaimer.html new file mode 100644 index 0000000..0091695 --- /dev/null +++ b/public/disclaimer.html @@ -0,0 +1,36 @@ + + + + +Earnings Disclaimer | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

5XYOURTEAM

Earnings Disclaimer

A position buys a draft spot and coaching tools, not income. Nothing is promised.

+

What you are buying

A 5xYourTeam position is a seat in the weekly draft and the tools to coach the people you draft. It is not an investment, a business opportunity, a share of profits or a promise of any payment.

+

Level shares and prizes are not promised

The contract pays a level share only when someone in your line chooses to buy a position. Nobody is required to buy one, and we do not know or promise whether anyone ever will. Many coaches receive nothing, and many receive less than they spend. The Best Coach pot depends on what is sold that week. Your results depend on other people's free choices.

+

No examples are promises

Any number on this site, in the ledger or in a Telegram post shows what really happened in one transaction. It is not a typical result and not a forecast.

+

Prices and taxes

Positions are priced in US dollars and paid in POL, whose price moves. You are responsible for any taxes on what you receive where you live.

+

Who to ask

TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Network support.

+
+ + + + diff --git a/public/draftday.html b/public/draftday.html new file mode 100644 index 0000000..bb78015 --- /dev/null +++ b/public/draftday.html @@ -0,0 +1,13 @@ +Draft Day | 5xYourTeam +
5XYOURTEAM
+

DRAFT DAY
RESULTS

+
5xyourteam.com
+ diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..12942e5 --- /dev/null +++ b/public/index.html @@ -0,0 +1,59 @@ + + + + +5xYourTeam | The weekly draft for people who need a sponsor + + + + + + + + + + + + + + + + + + + +
+
+

THE DRAFT

Draft your team every Monday.

+

Draft order is earned: the coaches who got the most of last week's picks started pick first. Help your picks get going and you move up next Monday.

+
+
Best Coach pot this week0 POL10% of every position sold this week
+
+ +
+

This week's pool

People waiting for a sponsor. Usernames only, never contact details.

+
+
+
+
+

DRAFT TRACKER

PICKCOACHDRAFTEDCARD
+

Best Coach standings

+

Last week

+
+
+

Rookie of the Week

+

How The Draft works

+
+
1

Get a position

$10 one-time in POL with SafePal or any other crypto wallet, never a subscription. It comes with 5 picks right away.

+
2

Draft every Monday

5 rounds from that week's pool. Away? You are auto-picked from your queue, or the best available player.

+
3

Coach them up

Help them link a wallet and switch on payouts, through site messages. Picks that do not start go back to the pool after 3 days.

+
+

You get the right to sponsor and help your picks, never their email or any contact details: you coach through site messages, and they get the network's normal "you have a new sponsor" email. Nobody locked on a network contract is ever in the pool, and nobody is adopted more than twice.

+ +

A position buys a draft spot and coaching tools, not income. Nothing is promised.

+
+
+ + + + diff --git a/public/join.html b/public/join.html new file mode 100644 index 0000000..c4e1994 --- /dev/null +++ b/public/join.html @@ -0,0 +1,41 @@ + + + + +Get a Position | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

GET A POSITION

$10 once. 5 picks today. A draft spot every Monday.

+

One payment in POL with SafePal or any other crypto wallet. It never renews and is never a subscription.

+
What you get
  • 5 instant picks from this week's pool
  • A spot in every Monday draft, 5 rounds
  • Coaching tools: scouting stats, the steps, site messages, who to help first
  • A coach page and trading cards for your team
  • Up to 10 open picks at a time
+ +

Buy

+
+

Anything you send above the exact price comes back to you in the same transaction. Payments are final once confirmed.

+

Where your $10 goes, in the same transaction

+

Your sponsor gets 25% and levels 2 to 5 of your network sponsor line get 5% each. Only people who hold a position can receive a share: anyone in your line who does not is passed over and the share goes up to the next person who does. 10% goes to the weekly Best Coach pot and 45% to 5xYourTeam. The contract keeps nothing. Check it on the contract page and every payment on the ledger.

+

A position buys a draft spot and coaching tools, not income. Nothing is promised.

+
+ + + + + diff --git a/public/ledger.html b/public/ledger.html new file mode 100644 index 0000000..6c93eb8 --- /dev/null +++ b/public/ledger.html @@ -0,0 +1,34 @@ + + + + +Live Ledger | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

LIVE LEDGER

Every position, every share, on-chain

+
+
WHENPOSITIONPAID IN THE SAME TRANSACTION
+

Best Coach payouts

WEEKCOACHPOL
+
+ + + + diff --git a/public/privacy.html b/public/privacy.html new file mode 100644 index 0000000..707a0f9 --- /dev/null +++ b/public/privacy.html @@ -0,0 +1,38 @@ + + + + +Privacy Policy | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

5XYOURTEAM

Privacy Policy

What 5xYourTeam keeps about you, why, and for how long.

+

Who we are

5xYourTeam is run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004.

+

What we keep

  • Your wallet address and network username.
  • Your network record from the network hub: your hub id and your sponsor line. 5xYourTeam does not store your email. When you sign in through InstantAdPay or LinkSpin, your email is used once to find your network record and is not kept.
  • Your positions, which are public on the Polygon blockchain.
  • The draft: who drafted whom and when, each pick's milestones (wallet linked, payouts on, first purchase), and the scouting facts shown on draft cards where the network tracks them (last seen, the site you joined through, game plays and earnings).
  • Site messages between a coach and their pick.
  • Your saved builder referral IDs.
+

What coaches see about a pick

A username, the scouting facts above and their milestones. Never an email, phone number or any other contact details, and no list is ever exported or sold. Anyone can see trading cards, which show milestones only, never earnings.

+

Cookies

A sign-in cookie (7 days), a cookie that remembers whose page you came from (30 days), and short-lived cookies for signing in through the network. No advertising or tracking cookies of our own.

+

Who else sees data

  • The Polygon blockchain: every position and payment is public there.
  • The network hub, which keeps one record per person across the network sites.
  • The network holding tank (InstantAdPay and LinkSpin), which records each adoption and sends the normal new-sponsor email.
  • Our Telegram payments topic: each position is posted with the buyer's username (or a shortened wallet) and the amounts paid, and the Draft Day results with usernames.
  • Services the pages load: Google Fonts and WalletConnect (Reown) when you connect a wallet.

We do not sell personal data.

+

Your choices

You can ask us to remove your account and messages here. Records on the blockchain cannot be removed by anyone.

+

Contact

TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Network support. Last updated November 15, 2026.

+
+ + + + diff --git a/public/promote.html b/public/promote.html new file mode 100644 index 0000000..f70df63 --- /dev/null +++ b/public/promote.html @@ -0,0 +1,35 @@ + + + + +Promo Kit | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

PROMO KIT

Share The Draft

+
+ +
+
+ + + + + diff --git a/public/team.html b/public/team.html new file mode 100644 index 0000000..41d0761 --- /dev/null +++ b/public/team.html @@ -0,0 +1,59 @@ + + + + +My Team | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+ + + +
+ + + + + diff --git a/public/terms.html b/public/terms.html new file mode 100644 index 0000000..6bacca0 --- /dev/null +++ b/public/terms.html @@ -0,0 +1,43 @@ + + + + +Terms and Conditions | 5xYourTeam + + + + + + + + + + + + + + + + + + + +
+

5XYOURTEAM

Terms and Conditions

The rules for using 5xYourTeam, in plain English.

+

Who we are

5xYourTeam (5xyourteam.com) is run by TrustClickz, 615 Green Valley Drive, Moody, AL 35004. It is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, 5xYourTeam, Stack POL and Earners Corner. By using 5xYourTeam you agree to these terms.

+

What 5xYourTeam is

5xYourTeam runs The Draft. People who join the network without a sponsor wait in the network holding tank. Every Monday the coaches on 5xYourTeam draft them, in rounds. A drafted person (a pick) is adopted by their coach under the holding-tank rules, and their coach becomes their network sponsor while the pick is open.

+

What a position is

A position is a single, one-time purchase of $10. It gives you 5 instant picks from the current pool, a spot in every weekly draft, the coaching tools, a coach page and trading cards. You can buy more than one; each adds 5 instant picks. Nothing renews and nothing is ever billed again. There are no subscriptions.

Positions are paid in POL on Polygon at the live Chainlink POL/USD price the contract reads when you buy. Anything you send above the price comes back to you in the same transaction.

What you buy is a seat in the draft and the tools to coach. It is not income, an investment or a share of anything.

+

The draft

The draft order is earned: coaches with more of last week's picks started (payouts switched on, or a first purchase) pick first; ties go to more picks started overall, then the earlier position. A coach in the draft room has a clock for each pick; a coach who is away is picked for automatically, from their own queue or the best available player. A coach may hold up to 10 open picks.

A pick that has not started within 3 days goes back to the pool, unless that person has now been adopted twice, in which case they stay with their coach. A started pick stays on the team. A coach cannot release a pick in its first 48 hours. The pool never includes anyone locked to a sponsor on a network contract, anyone the network already knows a sponsor for, anyone adopted twice, spam or throwaway sign-ups, or anyone in their first 24 hours.

+

Coaching rules

Coaches get the right to sponsor and help their picks. They never get a pick's email, phone number or any other contact details, and no list of picks is ever sold or exported. Coaching happens through 5xYourTeam site messages; the pick also receives the network's normal email telling them who their new sponsor is. Be helpful and honest: no spam, no pressure, no income claims, nothing illegal. We may remove a coach who breaks these rules.

+

How a payment is split

The DraftPosition contract splits each position in the same transaction it is paid: 25% to your sponsor, 5% to each of levels 2 to 5 of your network sponsor line, 10% to the weekly Best Coach prize pot wallet, and 45% to 5xYourTeam.

Only someone who holds a position can receive a level share. Someone in the line who does not is passed over, and the share goes up to the next person who does: the first such person gets the 25% share, the next four get 5% each, looking up to 20 places up the line. A share nobody qualifies for goes to 5xYourTeam.

Your sponsor line comes from the network hub. On your first position the site signs it and the contract records it link by link. A link already recorded is never changed. The split is fixed in the contract code and there is no owner withdraw.

+

The Best Coach pot

10% of every position goes to a separate prize wallet fixed in the contract. Each week the pot is shared among the coaches whose picks started the most that week, as announced on the draft board. Every payout from the pot is listed on the ledger with its transaction. Prizes depend on the pot that week and are not promised.

+

Nothing is promised

We do not promise or guarantee any income, payout, prize or result. A level share is paid only when someone in your line chooses to buy a position. Read the Earnings Disclaimer.

+

No refunds

Payments are made on the blockchain and are final once confirmed. We cannot reverse, cancel or refund them. Check the amount before you confirm in your wallet.

+

Crypto risk

  • The price of POL moves. The dollar value of a payment can be higher or lower later than when it was paid.
  • You are responsible for your wallet and its recovery phrase. Nobody, including us, can recover a lost wallet or reverse a payment sent from it.
  • Each transaction costs a small network fee (gas) in POL, paid to the network, not to us.
  • Use SafePal or any other crypto wallet you trust, and never share your recovery phrase with anyone. We will never ask for it.
+

The service

The site is provided as it is. We work to keep it running but cannot promise it will always be available or free of errors. The smart contract runs on Polygon on its own; its rules are public on the contract page. We may change features, draft settings, the price of future positions or these terms; changes apply from the date they are posted here. As far as the law allows, our total responsibility to you is limited to what you paid for the purchase in question. These terms are governed by the laws of the State of Alabama, USA.

+

Contact

TrustClickz, 615 Green Valley Drive, Moody, AL 35004. Network support. Last updated November 15, 2026.

+
+ + + + diff --git a/qa/fixtures/pool.json b/qa/fixtures/pool.json new file mode 100644 index 0000000..37f1cbb --- /dev/null +++ b/qa/fixtures/pool.json @@ -0,0 +1,344 @@ +{ + "note": "LOCAL TEST FIXTURE for the phase 1 stub tank. Not real people. Times are hours before the app booted.", + "people": [ + { + "id": "h_3affc1ada35faebb", + "username": "rookie_one", + "door": "InstantAdPay", + "joinedHoursAgo": 939, + "seenHoursAgo": 3, + "walletHoursAgo": 104, + "games": { + "plays": 3, + "title": "Road Agent", + "earnedWei": "380000000000000000" + } + }, + { + "id": "h_eb022863fe3bc491", + "username": "surfqueen", + "door": "LinkSpin", + "joinedHoursAgo": 910, + "seenHoursAgo": 20, + "surfWei": "269000000000000000" + }, + { + "id": "h_6238d6f010f3f9c5", + "username": "newbie77", + "door": "BTC4Hits", + "joinedHoursAgo": 185, + "seenHoursAgo": null, + "games": { + "plays": 0, + "title": null, + "earnedWei": null + } + }, + { + "id": "h_887d6e1bb8235fe8", + "username": "cryptomike", + "door": "Downline Banners", + "joinedHoursAgo": 100, + "seenHoursAgo": 50, + "walletHoursAgo": 163 + }, + { + "id": "h_a1436ef135f3db34", + "username": "gamerdad", + "door": "Viral Banner Blitz", + "joinedHoursAgo": 874, + "seenHoursAgo": 1, + "games": { + "plays": 54, + "title": "Shards of Valor", + "earnedWei": "90000000000000000" + } + }, + { + "id": "h_fa121ef0eac78fde", + "username": "lunaclicks", + "door": "CryptoTeamBuild", + "joinedHoursAgo": 591, + "seenHoursAgo": 30, + "surfWei": "275000000000000000" + }, + { + "id": "h_0aeabeb6af047906", + "username": "tradewinds", + "door": "LinkSpin", + "joinedHoursAgo": 367, + "seenHoursAgo": 3, + "walletHoursAgo": 103, + "games": { + "plays": 46, + "title": "ClutterHunt", + "earnedWei": "240000000000000000" + } + }, + { + "id": "h_9f18ef0a0d91dc4d", + "username": "polypat", + "door": "InstantAdPay", + "joinedHoursAgo": 189, + "seenHoursAgo": 120 + }, + { + "id": "h_172d8f222f9eb21b", + "username": "clickfox", + "door": "InstantAdPay", + "joinedHoursAgo": 506, + "seenHoursAgo": 3, + "games": { + "plays": 30, + "title": "Circuit Brawl", + "earnedWei": "350000000000000000" + } + }, + { + "id": "h_da20f879170c19a4", + "username": "maria_g", + "door": "LinkSpin", + "joinedHoursAgo": 664, + "seenHoursAgo": 3, + "walletHoursAgo": 112, + "surfWei": "120000000000000000" + }, + { + "id": "h_3f3409eb1420f7eb", + "username": "bitbuilder", + "door": "BTC4Hits", + "joinedHoursAgo": 374, + "seenHoursAgo": 200, + "games": { + "plays": 29, + "title": "Circuit Brawl", + "earnedWei": "180000000000000000" + } + }, + { + "id": "h_1b1edcfd7d4b6fe4", + "username": "sunnyside", + "door": "Downline Banners", + "joinedHoursAgo": 186, + "seenHoursAgo": 3 + }, + { + "id": "h_99673703afc3a234", + "username": "jetsetjoe", + "door": "Viral Banner Blitz", + "joinedHoursAgo": 639, + "seenHoursAgo": 50, + "walletHoursAgo": 19, + "games": { + "plays": 39, + "title": "PolyBreak", + "earnedWei": "300000000000000000" + } + }, + { + "id": "h_47213d4ea578f9d1", + "username": "adsurfer", + "door": "CryptoTeamBuild", + "joinedHoursAgo": 922, + "seenHoursAgo": 70, + "surfWei": "99000000000000000" + }, + { + "id": "h_9848af6d869e9db9", + "username": "kimchi_k", + "door": "LinkSpin", + "joinedHoursAgo": 423, + "seenHoursAgo": 30, + "games": { + "plays": 23, + "title": "Gem Kingdom", + "earnedWei": "80000000000000000" + } + }, + { + "id": "h_3fe73adad20e7c82", + "username": "dealhunter", + "door": "InstantAdPay", + "joinedHoursAgo": 627, + "seenHoursAgo": 20, + "walletHoursAgo": 158 + }, + { + "id": "h_f06b5bded0aae139", + "username": "quietquill", + "door": "InstantAdPay", + "joinedHoursAgo": 763, + "seenHoursAgo": 50, + "games": { + "plays": 5, + "title": "PolyBreak", + "earnedWei": "80000000000000000" + } + }, + { + "id": "h_f0fe77765837b89e", + "username": "lotusleaf", + "door": "LinkSpin", + "joinedHoursAgo": 407, + "seenHoursAgo": 200, + "surfWei": "98000000000000000" + }, + { + "id": "h_39fea889d5a1d527", + "username": "hopscotch", + "door": "BTC4Hits", + "joinedHoursAgo": 404, + "seenHoursAgo": 200, + "walletHoursAgo": 194, + "games": { + "plays": 43, + "title": "Road Agent", + "earnedWei": "380000000000000000" + } + }, + { + "id": "h_e25cdaa177422bbb", + "username": "pixelpaul", + "door": "Downline Banners", + "joinedHoursAgo": 882, + "seenHoursAgo": 8 + }, + { + "id": "h_0c4f10d69e5305f4", + "username": "nightowl22", + "door": "Viral Banner Blitz", + "joinedHoursAgo": 767, + "seenHoursAgo": 200, + "games": { + "plays": 13, + "title": "Shards of Valor", + "earnedWei": "260000000000000000" + } + }, + { + "id": "h_86e910ef9cb5ff2f", + "username": "garden_gina", + "door": "CryptoTeamBuild", + "joinedHoursAgo": 133, + "seenHoursAgo": 50, + "walletHoursAgo": 46, + "surfWei": "297000000000000000" + }, + { + "id": "h_e7b0293c9b3d76d1", + "username": "ridgeback", + "door": "LinkSpin", + "joinedHoursAgo": 31, + "seenHoursAgo": 8, + "games": { + "plays": 56, + "title": "PolyBreak", + "earnedWei": "260000000000000000" + } + }, + { + "id": "h_bb41753eafce6811", + "username": "tinytrader", + "door": "InstantAdPay", + "joinedHoursAgo": 618, + "seenHoursAgo": 1 + }, + { + "id": "h_489c134cec719d65", + "username": "mapleleaf", + "door": "InstantAdPay", + "joinedHoursAgo": 559, + "seenHoursAgo": 1, + "walletHoursAgo": 52, + "games": { + "plays": 50, + "title": "Gem Kingdom", + "earnedWei": "240000000000000000" + } + }, + { + "id": "h_e1abfd1b267ee264", + "username": "oceanview", + "door": "LinkSpin", + "joinedHoursAgo": 117, + "seenHoursAgo": 3, + "surfWei": "205000000000000000" + }, + { + "id": "h_91c2569472b58816", + "username": "redrover", + "door": "BTC4Hits", + "joinedHoursAgo": 481, + "seenHoursAgo": 8, + "games": { + "plays": 9, + "title": "ClutterHunt", + "earnedWei": "350000000000000000" + } + }, + { + "id": "h_a6b75313af665383", + "username": "buzzybee", + "door": "Downline Banners", + "joinedHoursAgo": 829, + "seenHoursAgo": 30, + "walletHoursAgo": 188 + }, + { + "id": "h_locked0000000001", + "username": "lockedlarry", + "door": "InstantAdPay", + "joinedHoursAgo": 300, + "seenHoursAgo": 2, + "locked": true + }, + { + "id": "h_sponsored0000001", + "username": "hasasponsor", + "door": "LinkSpin", + "joinedHoursAgo": 300, + "seenHoursAgo": 2, + "sponsored": true + }, + { + "id": "h_spam000000000001", + "username": "xx_spam_xx", + "door": "LinkSpin", + "joinedHoursAgo": 300, + "seenHoursAgo": 2, + "spam": true + }, + { + "id": "h_throwaway000001", + "username": "temp_mail_9", + "door": "InstantAdPay", + "joinedHoursAgo": 300, + "seenHoursAgo": 2, + "throwaway": true + }, + { + "id": "h_grace00000000001", + "username": "brandnew", + "door": "InstantAdPay", + "joinedHoursAgo": 5, + "seenHoursAgo": 1 + }, + { + "id": "h_twice00000000001", + "username": "twiceadopted", + "door": "InstantAdPay", + "joinedHoursAgo": 900, + "seenHoursAgo": 4, + "adoptionsElsewhere": 2 + }, + { + "id": "h_once000000000001", + "username": "onceadopted", + "door": "LinkSpin", + "joinedHoursAgo": 900, + "seenHoursAgo": 4, + "adoptionsElsewhere": 1, + "walletHoursAgo": 40 + } + ] +} \ No newline at end of file diff --git a/qa/out/desktop-board.png b/qa/out/desktop-board.png new file mode 100644 index 0000000..f8dfa70 Binary files /dev/null and b/qa/out/desktop-board.png differ diff --git a/qa/out/desktop-builder.png b/qa/out/desktop-builder.png new file mode 100644 index 0000000..c78c957 Binary files /dev/null and b/qa/out/desktop-builder.png differ diff --git a/qa/out/desktop-cards.png b/qa/out/desktop-cards.png new file mode 100644 index 0000000..32628a2 Binary files /dev/null and b/qa/out/desktop-cards.png differ diff --git a/qa/out/desktop-coachann.png b/qa/out/desktop-coachann.png new file mode 100644 index 0000000..974aa9d Binary files /dev/null and b/qa/out/desktop-coachann.png differ diff --git a/qa/out/desktop-contract.png b/qa/out/desktop-contract.png new file mode 100644 index 0000000..a1ac360 Binary files /dev/null and b/qa/out/desktop-contract.png differ diff --git a/qa/out/desktop-disclaimer.png b/qa/out/desktop-disclaimer.png new file mode 100644 index 0000000..10b57cc Binary files /dev/null and b/qa/out/desktop-disclaimer.png differ diff --git a/qa/out/desktop-join.png b/qa/out/desktop-join.png new file mode 100644 index 0000000..91909a6 Binary files /dev/null and b/qa/out/desktop-join.png differ diff --git a/qa/out/desktop-ledger.png b/qa/out/desktop-ledger.png new file mode 100644 index 0000000..ea26a4b Binary files /dev/null and b/qa/out/desktop-ledger.png differ diff --git a/qa/out/desktop-privacy.png b/qa/out/desktop-privacy.png new file mode 100644 index 0000000..609ec44 Binary files /dev/null and b/qa/out/desktop-privacy.png differ diff --git a/qa/out/desktop-promote.png b/qa/out/desktop-promote.png new file mode 100644 index 0000000..ead6cc5 Binary files /dev/null and b/qa/out/desktop-promote.png differ diff --git a/qa/out/desktop-team-as-pick.png b/qa/out/desktop-team-as-pick.png new file mode 100644 index 0000000..a2cfc6e Binary files /dev/null and b/qa/out/desktop-team-as-pick.png differ diff --git a/qa/out/desktop-team.png b/qa/out/desktop-team.png new file mode 100644 index 0000000..6c69bc0 Binary files /dev/null and b/qa/out/desktop-team.png differ diff --git a/qa/out/desktop-terms.png b/qa/out/desktop-terms.png new file mode 100644 index 0000000..7496f0e Binary files /dev/null and b/qa/out/desktop-terms.png differ diff --git a/qa/out/draftday-2026-11-16.png b/qa/out/draftday-2026-11-16.png new file mode 100644 index 0000000..2c04201 Binary files /dev/null and b/qa/out/draftday-2026-11-16.png differ diff --git a/qa/out/phone-board.png b/qa/out/phone-board.png new file mode 100644 index 0000000..d041698 Binary files /dev/null and b/qa/out/phone-board.png differ diff --git a/qa/out/phone-builder.png b/qa/out/phone-builder.png new file mode 100644 index 0000000..2c3a168 Binary files /dev/null and b/qa/out/phone-builder.png differ diff --git a/qa/out/phone-cards.png b/qa/out/phone-cards.png new file mode 100644 index 0000000..50916f0 Binary files /dev/null and b/qa/out/phone-cards.png differ diff --git a/qa/out/phone-coachann.png b/qa/out/phone-coachann.png new file mode 100644 index 0000000..b3cdf0a Binary files /dev/null and b/qa/out/phone-coachann.png differ diff --git a/qa/out/phone-contract.png b/qa/out/phone-contract.png new file mode 100644 index 0000000..0f1e6f9 Binary files /dev/null and b/qa/out/phone-contract.png differ diff --git a/qa/out/phone-disclaimer.png b/qa/out/phone-disclaimer.png new file mode 100644 index 0000000..75fd083 Binary files /dev/null and b/qa/out/phone-disclaimer.png differ diff --git a/qa/out/phone-join.png b/qa/out/phone-join.png new file mode 100644 index 0000000..b9e5477 Binary files /dev/null and b/qa/out/phone-join.png differ diff --git a/qa/out/phone-ledger.png b/qa/out/phone-ledger.png new file mode 100644 index 0000000..b6e6fd4 Binary files /dev/null and b/qa/out/phone-ledger.png differ diff --git a/qa/out/phone-privacy.png b/qa/out/phone-privacy.png new file mode 100644 index 0000000..c0e680d Binary files /dev/null and b/qa/out/phone-privacy.png differ diff --git a/qa/out/phone-promote.png b/qa/out/phone-promote.png new file mode 100644 index 0000000..9ed952c Binary files /dev/null and b/qa/out/phone-promote.png differ diff --git a/qa/out/phone-team.png b/qa/out/phone-team.png new file mode 100644 index 0000000..b3d09ce Binary files /dev/null and b/qa/out/phone-team.png differ diff --git a/qa/out/phone-terms.png b/qa/out/phone-terms.png new file mode 100644 index 0000000..e9317c3 Binary files /dev/null and b/qa/out/phone-terms.png differ diff --git a/qa/out/smoke.txt b/qa/out/smoke.txt new file mode 100644 index 0000000..d0bdacc --- /dev/null +++ b/qa/out/smoke.txt @@ -0,0 +1 @@ +2026-11-15T12:15:13.035Z 156 passed, 0 failed diff --git a/qa/smoke.mjs b/qa/smoke.mjs new file mode 100644 index 0000000..f6b310f --- /dev/null +++ b/qa/smoke.mjs @@ -0,0 +1,418 @@ +// 5xYourTeam local smoke test. Boots the app in prototype mode (no DOCSTORE_URL: files in a throwaway data dir under qa/out) with +// the STUB holding tank and a test clock, against local stand-ins, then checks: copy rules, pages, the promo kit, sign-in (wallet + +// network), position orders (line voucher signed by the keeper, already-bound line, hub down), purchases recorded from the chain +// (ledger split: sponsor 25%, levels 5%, pot 10%, company; passed over; Telegram card once; hub report), instant picks, a live +// draft (on the clock, manual pick, auto-picks, queue), coaching messages (no contact data anywhere), milestones -> cards, Best +// Coach + Rookie, picks returning to the pool, the release hold, the Draft Day card, old links, admin, a restart, and Playwright +// renders at 1280 and 390 with screenshots in qa/out. +// Nothing leaves this machine: hub, chain RPC and Telegram are local stand-ins. No real wallet, no money, nobody adopted. +// node qa/smoke.mjs SKIP_UI=1 node qa/smoke.mjs (HTTP only) UI_FONTS=1 (let Google Fonts load) +import { spawn, spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import path from 'node:path'; +import crypto from 'node:crypto'; +import http from 'node:http'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +const require = createRequire(import.meta.url); +const { ethers } = require('ethers'); + +const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const OUT = path.join(APP, 'qa', 'out'); fs.mkdirSync(OUT, { recursive: true }); +const DATA = path.join(OUT, 'data-' + Date.now()); fs.mkdirSync(DATA, { recursive: true }); +const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; +const PORT = Number(process.env.SMOKE_APP_PORT || 3561), BASE = 'http://127.0.0.1:' + PORT; +const ADMIN = 'smoke-admin-token', SSO_SECRET = crypto.randomBytes(32).toString('hex'), HUB_SECRET = 'h'.repeat(40); +const KEEPER_PK = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d'; // anvil's public test key #1 +const KEEPER = new ethers.Wallet(KEEPER_PK).address; +const SHOP = '0x00000000000000000000000000000000005A5A5A'; +const PRIZE = '0x000000000000000000000000000000000000bead'; +const TANGEM = '0x7627Fc78876948AC9d95C1C9eB061E7D6d647b70'; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +let pass = 0, fail = 0; let srv = null; +const ok = (cond, what, extra) => { if (cond) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra, (k, v) => typeof v === 'bigint' ? v.toString() : v).slice(0, 600) : '')); } }; +const listen = (port, fn) => http.createServer(async (q, r) => { let b = ''; for await (const c of q) b += c; try { await fn(q, r, b); } catch (e) { r.statusCode = 500; r.end(String(e.message)); } }).listen(port, '127.0.0.1').unref(); +const H = 3600000, D = 86400000; +const POOL = JSON.parse(fs.readFileSync(path.join(APP, 'qa', 'fixtures', 'pool.json'), 'utf8')).people; +const pid = name => POOL.find(p => p.username === name).id; + +// ---- stand-in network hub (signed as fivex) ---- +const HUB = { people: new Map(), down: false, badSig: 0, resolves: 0, got: [] }; +function person(username, wallet, sponsorId, id) { id = id || 'h_' + crypto.createHash('sha1').update(username).digest('hex').slice(0, 16); HUB.people.set(id, { id, username, wallet: wallet ? wallet.toLowerCase() : null, sponsorId: sponsorId || null }); return id; } +const hubView = p => { if (!p) return null; const sp = p.sponsorId && HUB.people.get(p.sponsorId); return { id: p.id, username: p.username, wallet: p.wallet, blocked: false, sponsor: sp ? { id: sp.id, username: sp.username } : null }; }; +const HUB_PORT = PORT + 1; +listen(HUB_PORT, async (q, r, b) => { + r.setHeader('Content-Type', 'application/json'); + if (q.method === 'GET' && q.url === '/v1/network-sites') return r.end('[]'); + if (HUB.down) { r.statusCode = 503; return r.end('{"error":"down"}'); } + const want = crypto.createHmac('sha256', HUB_SECRET).update(q.headers['x-hub-ts'] + '\n' + b).digest('hex'); + if (q.headers['x-hub-sig'] !== want || q.headers['x-hub-site'] !== 'fivex') { HUB.badSig++; r.statusCode = 401; return r.end('{}'); } + const j = JSON.parse(b || '{}'); + if (q.url === '/v1/resolve') { + HUB.resolves++; const all = [...HUB.people.values()]; let p = null; + if (j.id) p = HUB.people.get(j.id); else if (j.wallet) p = all.find(x => x.wallet === String(j.wallet).toLowerCase()); + else if (j.ref) { const ref = String(j.ref).toLowerCase(); p = all.find(x => x.wallet === ref || x.username.toLowerCase() === ref); } + return r.end(JSON.stringify({ person: hubView(p) })); + } + HUB.got.push({ route: q.url, body: j }); r.end('{"ok":true}'); +}); +// ---- stand-in Polygon JSON-RPC (DraftPosition): quoteWei at POL $0.25 ($10 = 40 POL), sponsorOf, contract facts, logs ---- +const IFACE = new ethers.Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 qty, uint256 ref, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 prizePaid, uint256 companyPaid)', + 'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)', + 'event SponsorBound(address indexed member, address indexed sponsor)', + 'function quoteWei(uint256 qty) view returns (uint256)', 'function sponsorOf(address) view returns (address)', + 'function buy(uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256)', + 'function owner() view returns (address)', 'function company() view returns (address)', 'function prizeWallet() view returns (address)', 'function keeper() view returns (address)', 'function paused() view returns (bool)', + 'function totalOwed() view returns (uint256)', 'function orderCount() view returns (uint256)', 'function priceCents() view returns (uint256)']); +const CHAIN = { head: 1, logs: [], receipts: {}, bound: new Map(), replayAll: false, down: false, times: {} }; +const CHAIN_PORT = PORT + 2; +listen(CHAIN_PORT, async (q, r, b) => { + const j = JSON.parse(b || '{}'); let result = null; r.setHeader('Content-Type', 'application/json'); + if (CHAIN.down) return r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, error: { code: -1, message: 'down' } })); + if (j.method === 'eth_blockNumber') result = '0x' + CHAIN.head.toString(16); + if (j.method === 'eth_call') { + const tx = IFACE.parseTransaction({ data: j.params[0].data }); const enc = (fn, v) => IFACE.encodeFunctionResult(fn, v); + if (tx.name === 'quoteWei') result = enc('quoteWei', [1000n * tx.args[0] * 4n * 10n ** 16n]); + if (tx.name === 'sponsorOf') result = enc('sponsorOf', [CHAIN.bound.get(tx.args[0].toLowerCase()) || ethers.ZeroAddress]); + if (tx.name === 'owner' || tx.name === 'company') result = enc(tx.name, [TANGEM]); + if (tx.name === 'prizeWallet') result = enc('prizeWallet', [PRIZE]); + if (tx.name === 'keeper') result = enc('keeper', [KEEPER]); + if (tx.name === 'paused') result = enc('paused', [false]); + if (tx.name === 'totalOwed') result = enc('totalOwed', [0n]); + if (tx.name === 'orderCount') result = enc('orderCount', [BigInt(CHAIN.logs.length)]); + if (tx.name === 'priceCents') result = enc('priceCents', [1000n]); + } + if (j.method === 'eth_getBalance') result = '0x0'; + if (j.method === 'eth_getTransactionReceipt') result = CHAIN.receipts[j.params[0]] || null; + if (j.method === 'eth_maxPriorityFeePerGas') result = '0x' + (40n * 10n ** 9n).toString(16); + if (j.method === 'eth_getBlockByNumber') { const n = j.params[0] === 'latest' ? CHAIN.head : parseInt(j.params[0], 16); result = { number: '0x' + n.toString(16), timestamp: '0x' + (CHAIN.times[n] || Math.floor(Date.now() / 1000)).toString(16), baseFeePerGas: '0x' + (30n * 10n ** 9n).toString(16) }; } + if (j.method === 'eth_getLogs') { const f = j.params[0], lo = parseInt(f.fromBlock, 16), hi = parseInt(f.toBlock, 16); result = CHAIN.logs.filter(l => CHAIN.replayAll || (parseInt(l.blockNumber, 16) >= lo && parseInt(l.blockNumber, 16) <= hi)); } + r.end(JSON.stringify({ jsonrpc: '2.0', id: j.id, result })); +}); +// a position bought on the stand-in chain: Purchase log + a receipt with SponsorBound / PassedOver / Paid logs, like DraftPosition emits +let orderId = 0; +function chainBuy(o) { + const id = ++orderId; const block = ++CHAIN.head; const tx = '0x' + crypto.randomBytes(32).toString('hex'); + CHAIN.times[block] = o.blockAt || Math.floor(Date.now() / 1000); + const qty = BigInt(o.qty || 1); const weiPaid = 1000n * qty * 4n * 10n ** 16n; const sp = weiPaid * 2500n / 10000n, lv = weiPaid * 500n / 10000n, pot = weiPaid / 10n; + const mk = (name, args, li) => { const e = IFACE.encodeEventLog(name, args); return { address: SHOP.toLowerCase(), topics: e.topics, data: e.data, blockNumber: '0x' + block.toString(16), transactionHash: tx, logIndex: '0x' + li.toString(16), removed: false }; }; + const logs = []; let li = 0; let lvl = 0n; + for (const [m, s] of o.bound || []) { logs.push(mk('SponsorBound', [m, s], li++)); CHAIN.bound.set(m.toLowerCase(), s.toLowerCase()); } + for (const [w, d] of o.over || []) logs.push(mk('PassedOver', [id, w, d], li++)); + (o.pays || []).forEach(([w, d], i) => { const a = i === 0 ? sp : lv; lvl += a; logs.push(mk('Paid', [id, w, a, i + 1, d], li++)); }); + logs.push(mk('Paid', [id, PRIZE, pot, 6, 0], li++)); + const company = weiPaid - lvl - pot; logs.push(mk('Paid', [id, TANGEM, company, 0, 0], li++)); + const purchase = mk('Purchase', [id, o.buyer, qty, o.ref || 0, 1000n * qty, weiPaid, (o.pays || []).length, pot, company], li++); + logs.push(purchase); CHAIN.logs.push(purchase); + CHAIN.receipts[tx] = { status: '0x1', blockNumber: '0x' + block.toString(16), to: SHOP.toLowerCase(), from: o.buyer.toLowerCase(), logs }; + return { tx, id, weiPaid, sp, lv, pot, company }; +} +// ---- stand-in Telegram Bot API ---- +const TG = []; const TG_PORT = PORT + 3; +listen(TG_PORT, async (q, r, b) => { TG.push({ method: q.url.split('/').pop(), token: q.url.split('/')[1], body: JSON.parse(b || '{}') }); r.setHeader('Content-Type', 'application/json'); r.end('{"ok":true,"result":{}}'); }); + +const ENV = Object.assign({}, process.env, { PORT: String(PORT), DATA_DIR: DATA, ADMIN_TOKEN: ADMIN, NODE_ENV: 'development', DOCSTORE_URL: '', ALLOW_TEST_CLOCK: '1', TANK_MODE: 'stub', + NETWORK_SSO_SECRET: SSO_SECRET, IAP_URL: 'https://iap.invalid', LS_URL: 'https://ls.invalid', NETWORK_SITES_HUB: '0', DRAFT_TICK_MS: '200', DRAFT_PICK_SECONDS: '300', + CONTRACT_ADDRESS: SHOP, PRIZE_WALLET: PRIZE, CHAIN_RPC: 'http://127.0.0.1:' + CHAIN_PORT, KEEPER_KEY: KEEPER_PK, SHOP_START_BLOCK: '1', SHOP_CONFIRMATIONS: '0', SHOP_POLL_MS: '200', EXPLORER: 'https://explorer.invalid', + HUB_ENABLED: '1', HUB_URL: 'http://127.0.0.1:' + HUB_PORT, HUB_SECRET, HUB_SITE: 'fivex', HUB_TICK_MS: '300', HUB_DOWN_MS: '300', HUB_CACHE_MS: '200', + TG_LIVE: '1', TG_TOKEN: 'standin-token', TG_CHAT: '-100123', TG_PAY_TOPIC: '632242', TG_API: 'http://127.0.0.1:' + TG_PORT, OWNER_USERNAME: 'coachann' }); +process.on('exit', () => { try { srv && srv.kill(); } catch (e) {} }); + +let nextIp = 10; +function client(opts = {}) { + const jar = {}; const ip = opts.ip || ('203.0.113.' + (nextIp++)); const ua = opts.ua || ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) SmokeBrowser/' + ip); + return { jar, ip, ua, + async req(p, o = {}) { + const headers = Object.assign({ 'User-Agent': ua, 'X-Forwarded-For': ip, Cookie: Object.entries(jar).map(([k, v]) => k + '=' + v).join('; ') }, o.headers || {}); + const r = await fetch(BASE + p, { method: o.method || 'GET', headers, body: o.body, redirect: 'manual' }); + for (const c of r.headers.getSetCookie ? r.headers.getSetCookie() : []) { const [kv] = c.split(';'); const i = kv.indexOf('='); jar[kv.slice(0, i)] = kv.slice(i + 1); } + return r; + }, + async json(p, body, extra) { const r = await this.req(p, body === undefined ? { headers: extra } : { method: 'POST', headers: Object.assign({ 'Content-Type': 'application/json' }, extra), body: JSON.stringify(body) }); return Object.assign({ _status: r.status }, await r.json().catch(() => ({}))); } }; +} +const admin = (p, body) => client().json(p, body, { 'x-admin-token': ADMIN }); +async function boot(extraEnv) { + const log = fs.openSync(path.join(OUT, 'server.log'), 'a'); + srv = spawn(process.execPath, ['server.js'], { cwd: APP, env: Object.assign({}, ENV, extraEnv || {}), stdio: ['ignore', log, log] }); + for (let i = 0; i < 80; i++) { try { const r = await fetch(BASE + '/health'); if (r.ok) return; } catch (e) {} await sleep(150); } + throw new Error('server did not start; see qa/out/server.log'); +} +async function stop() { const p = srv; srv = null; if (!p) return; const done = new Promise(r => p.once('exit', r)); p.kill('SIGINT'); await Promise.race([done, sleep(3000)]); } +async function walletMember(o = {}) { + const w = o.wallet || ethers.Wallet.createRandom(); const c = client(); const a = w.address.toLowerCase(); + if (o.hub) c.hubId = person(o.hub.username, a, o.hub.sponsorId, o.hub.id); + const ch = await c.json('/api/auth/challenge', { address: w.address }); + const v = await c.json('/api/auth/verify', { address: w.address, signature: await w.signMessage(ch.message) }); + c.address = a; c.wallet = w; c.ok = v.ok === true && !!c.jar['fx.sid']; + return c; +} +const until = async (fn, ms) => { const end = Date.now() + (ms || 8000); let v; while (Date.now() < end) { v = await fn(); if (v) return v; await sleep(150); } return v; }; +const ctToMs = (day, hour) => { const [y, m, d] = day.split('-').map(Number); for (const off of [6, 5]) { const t = Date.UTC(y, m - 1, d, hour + off); const h = Number(new Date(t).toLocaleString('en-US', { timeZone: 'America/Chicago', hour: 'numeric', hour12: false })); if (h % 24 === hour) return t; } return Date.UTC(y, m - 1, d, hour + 6); }; +const EMAIL_RE = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/; + +async function main() { + if (await fetch(BASE).then(() => true, () => false)) throw new Error('port ' + PORT + ' is already in use; set SMOKE_APP_PORT'); + console.log('data dir', DATA); + + console.log('1. copy rules'); + const pub = path.join(APP, 'public'); + const files = fs.readdirSync(pub).filter(f => f.endsWith('.html')).map(f => path.join(pub, f)).concat(fs.readdirSync(path.join(pub, 'assets')).filter(f => /\.(js|css)$/.test(f) && f !== 'wallet.js').map(f => path.join(pub, 'assets', f))); + const texts = files.map(f => [path.basename(f), fs.readFileSync(f, 'utf8')]).concat(['promokit.js', 'proof.js', 'server.js', 'draft.js', 'league.js', 'tools/pages.mjs', 'tools/art.mjs'].map(f => [f, fs.readFileSync(path.join(APP, f), 'utf8')])); + ok(texts.every(([, t]) => !/[\u2014\u2013]/.test(t)), 'no em or en dashes in any page, script or copy source', texts.filter(([, t]) => /[\u2014\u2013]/.test(t)).map(x => x[0])); + const html = texts.filter(([n]) => n.endsWith('.html')).map(x => x[1]).join('\n'); + ok(!/metamask/i.test(html), 'pages never name MetaMask'); + ok(/SafePal or any other crypto wallet/.test(html), 'wallet copy: "SafePal or any other crypto wallet"'); + ok(!/passive income|guaranteed (income|returns|profit)|earn (cash|money)|make money|get rich|up to \$?\d+ (a|per)|maximum (you|earn)/i.test(html), 'no income promises and no earnings caps in page copy'); + ok(/never a subscription/i.test(html) && /A position buys a draft spot and coaching tools, not income\. Nothing is promised\./.test(html), 'position copy: one-time, never a subscription; "not income. Nothing is promised."'); + ok(/TrustClickz/.test(html) && /615 Green Valley Drive, Moody, AL 35004/.test(html), 'legal pages name TrustClickz, 615 Green Valley Drive, Moody, AL 35004'); + ok(/never their email or any contact details/.test(html) && /never an email, phone number or any other contact details/i.test(html), 'copy: coaches get the right to sponsor and help, never contact data'); + + console.log('2. boot (prototype mode, stub tank, test clock)'); + // the test clock starts on Sunday 2026-11-15 noon Central: last Monday's draft (11-09) is long past and skipped, never run late + const SUN = ctToMs('2026-11-15', 12), MON = ctToMs('2026-11-16', 19); + await boot(); + let r0 = await admin('/api/admin/clock', { now: SUN }); ok(r0.ok, 'admin moves the test clock (ALLOW_TEST_CLOCK=1, never in production)', r0); + await sleep(500); + const cfg = await (await fetch(BASE + '/api/config')).json(); + ok(cfg.position.usd === 10 && cfg.position.picksOnBuy === 5 && cfg.split.sponsorPct === 25 && cfg.split.levelPct === 5 && cfg.split.potPct === 10 && cfg.split.companyPct === 45 && cfg.tank === 'stub', 'config: $10 position, 5 picks, split 25/5x4/10/45, stub tank', cfg); + ok(cfg.shop.live === true && cfg.draft.dow === 1 && cfg.draft.hour === 19 && cfg.draft.rounds === 5 && cfg.picks.returnDays === 3, 'shop live (stand-in); draft Monday 7 PM Central, 5 rounds; picks return after 3 days', cfg.draft); + let st = await admin('/api/admin/status'); + ok(st.draft === null || (st.draft && st.draft.made === 0), 'the app came up after last Monday\'s draft window: that draft is skipped, not run late', st.draft); + + console.log('3. pages'); + const anon = client(); + for (const p of ['/', '/team', '/cards', '/join', '/ledger', '/contract', '/promote', '/builder', '/terms', '/disclaimer', '/privacy', '/admin', '/robots.txt', '/sitemap.xml', '/art/og-share.png', '/art/icon-192.png', '/assets/fx.css', '/assets/common.js']) { const r = await anon.req(p); ok(r.status === 200, 'GET ' + p + ' 200', r.status); } + let r = await anon.req('/team'); ok(r.headers.get('x-frame-options') === 'DENY', '/team is never framed'); + r = await anon.req('/nobody-at-all'); ok(r.status === 404 && /Back to the draft board/.test(await r.text()), 'an unknown coach name: 404'); + r = await anon.req('/api/my'); ok(r.status === 401, '/api/my needs sign-in'); + let b = await anon.json('/api/board'); + ok(b.poolSize === 29 && b.pool.length === 24 && b.pool.every(p => p.gameWei === undefined && p.surfWei === undefined), 'the pool (stub tank: 29 draftable of 35); visitors see scouting facts but no earnings', { size: b.poolSize, keys: Object.keys(b.pool[0]) }); + ok(!b.pool.some(p => /lockedlarry|hasasponsor|xx_spam_xx|temp_mail_9|brandnew|twiceadopted/.test(p.username)), 'never locked, sponsored, spam, throwaway, inside the grace or adopted twice', b.pool.map(p => p.username)); + ok(!EMAIL_RE.test(JSON.stringify(b)), 'no email address anywhere in the board data'); + + console.log('4. promo kit'); + { const kr = await anon.req('/api/promo-kit?u=coachann'); const k = await kr.json(); + ok(kr.status === 200 && kr.headers.get('access-control-allow-origin') === '*', 'GET /api/promo-kit 200 with CORS open'); + ok(k.links[0].url === 'https://5xyourteam.com/coachann' && k.links.slice(1).every(l => l.url.endsWith('?ref=coachann')), 'kit links: the coach page + ?ref=', k.links.map(l => l.url)); + ok(k.links.every(l => /^https:\/\/linkspin\.app\/r\/nw5x\?src=fivex&s1=coachann/.test(l.tracked)), 'every link has a LinkSpin-tracked twin (nw5x, source fivex)', k.links.map(l => l.tracked)); + const words = JSON.stringify([k.lines, k.headlines, k.email, k.posts, k.note, k.tagline]); + ok(!/[\u2014\u2013]/.test(words) && !/passive income|guaranteed (income|returns|profit)|make money|metamask/i.test(words) && /\$10 one-time position gives you 5 picks right away/.test(words) && /SafePal or any other crypto wallet/.test(words) && /never a subscription/.test(words), 'kit copy: no dashes, no income promises, facts from config, SafePal wording, never a subscription'); + ok(k.creatives.length === 21 && new Set(k.creatives.map(c => c.angle)).size === 3, 'kit: 21 creatives in 3 angles', k.creatives.length); + const bad = k.creatives.filter(c => /\d{2,4}x\d{2,4}|banner|[-_/]ads?[-_./]/i.test(c.url.replace('https://5xyourteam.com', ''))); ok(!bad.length, 'kit: creative paths are ad-blocker neutral', bad.map(c => c.url)); + let dimOk = true; const dimBad = []; + for (const c of k.creatives) { const rr = await anon.req(new URL(c.url).pathname); const buf = Buffer.from(await rr.arrayBuffer()); const w = buf.readUInt32BE(16), h = buf.readUInt32BE(20); if (rr.status !== 200 || w !== c.w || h !== c.h) { dimOk = false; dimBad.push(c.key + ' ' + w + 'x' + h); } } + ok(dimOk, 'kit: every creative is a PNG at its exact size', dimBad); + for (const p of ['/art/proof/fx-proof-navy.png', '/art/proof/fx-proof-gold.png', '/art/proof/fx-proof-field.png']) { const pr = await anon.req(p); ok(pr.status === 200 && pr.headers.get('content-type') === 'image/png', 'Telegram proof card ' + p); } } + + console.log('5. sign-in'); + // hub line above the coaches: top <- l2 (NO position) <- l1 <- coachann ; coachbob and coachcy are under coachann + const wTop = ethers.Wallet.createRandom(), wL2 = ethers.Wallet.createRandom(), wL1 = ethers.Wallet.createRandom(); + const idTop = person('topcoach', wTop.address), idL2 = person('lineup2', wL2.address, idTop), idL1 = person('lineup1', wL1.address, idL2); + const A = await walletMember({ hub: { username: 'coachann', sponsorId: idL1 } }); + let me = await A.json('/api/me'); ok(A.ok && me.username === 'coachann' && me.onNetwork && !me.coach, 'a wallet the hub knows: signed in, network username, not a coach yet', me); + const Bc = await walletMember({ hub: { username: 'coachbob', sponsorId: A.hubId } }); + const Cc = await walletMember({ hub: { username: 'coachcy', sponsorId: A.hubId } }); + const bad = client(); const x0 = ethers.Wallet.createRandom(), x1 = ethers.Wallet.createRandom(); + const ch0 = await bad.json('/api/auth/challenge', { address: x0.address }); const v0 = await bad.json('/api/auth/verify', { address: x0.address, signature: await x1.signMessage(ch0.message) }); + ok(v0._status === 400 && !bad.jar['fx.sid'], 'a signature from another wallet is refused'); + const L = client(); r = await L.req('/sso/start?mode=go&via=iap&to=%2Fteam'); const loc = r.headers.get('location') || ''; + ok(r.status === 302 && loc.startsWith('https://iap.invalid/sso/check?st=') && loc.includes('&r=fivex'), 'network sign-in hops to InstantAdPay with r=fivex', loc); + const nsso = require(path.join(APP, 'networksso.js')); process.env.NETWORK_SSO_SECRET = SSO_SECRET; + const wPick = ethers.Wallet.createRandom(); person('gamerdad', wPick.address, null, pid('gamerdad')); // a pool person who signs in later (their hub id = the fixture id) + const tok = nsso.mint({ iss: 'iap', aud: 'fivex', email: 'gamerdad@example.org', wallet: wPick.address.toLowerCase(), name: 'gamerdad', st: new URL(loc).searchParams.get('st'), to: '/team' }); + r = await L.req('/sso/in?t=' + encodeURIComponent(tok)); + ok(r.status === 302 && r.headers.get('location') === '/team' && !!L.jar['fx.sid'], 'the network token signs a member in', { s: r.status, l: r.headers.get('location') }); + const PICK = L; + ok(HUB.resolves > 0 && HUB.badSig === 0, 'hub lookups are signed as fivex with HUB_SECRET', HUB.badSig); + ok(!fs.readdirSync(DATA).some(f => /\.json$/.test(f) && fs.readFileSync(path.join(DATA, f), 'utf8').includes('gamerdad@example.org')), 'the sign-in email is never stored'); + + console.log('6. a position order (line voucher)'); + let q = await A.json('/api/quote?qty=1'); ok(q.usd === 10 && q.picks === 5 && BigInt(q.wei) === 40n * 10n ** 18n, 'quote: $10 at $0.25 = 40 POL (from the contract)', q); + q = await A.json('/api/quote?qty=11'); ok(q._status === 400, '11 positions refused (1 to 10)'); + let od = await A.json('/api/my/order', { qty: 1 }); + const call = IFACE.parseTransaction({ data: od.data, value: od.value }); + const line = call.args[2].map(a => a.toLowerCase()); + ok(od._status === 200 && call.name === 'buy' && Number(call.args[0]) === 1 && BigInt(call.args[1]) > 0n, 'order = buy(qty 1, ref = a short hash of the hub id)', od); + ok(JSON.stringify(line) === JSON.stringify([wL1, wL2, wTop].map(w => w.address.toLowerCase())), 'the voucher line = the hub line\'s wallets nearest first', line); + const rec = ethers.verifyTypedData({ name: 'DraftPosition', version: '1', chainId: 137, verifyingContract: ethers.getAddress(SHOP.toLowerCase()) }, { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] }, + { buyer: ethers.getAddress(A.address), line: call.args[2], deadline: call.args[3] }, call.args[4]); + ok(rec === KEEPER, 'the voucher is signed by the keeper (EIP-712 DraftPosition v1)', rec); + ok(BigInt(od.value) === 40n * 10n ** 18n * 101n / 100n, 'value = quote + 1% (the contract refunds the excess in the same tx)', od.value); + CHAIN.bound.set(Bc.address, A.address); + od = await Bc.json('/api/my/order', { qty: 1 }); const c2 = IFACE.parseTransaction({ data: od.data, value: od.value }); + ok(od.why === 'bound' && c2.args[2].length === 0 && c2.args[4] === '0x', 'a line already bound on chain: no voucher (the chain\'s binding wins)', od.why); + CHAIN.bound.delete(Bc.address); HUB.down = true; await sleep(350); + od = await Cc.json('/api/my/order', { qty: 1 }); ok(od._status === 503 && /sponsor line/.test(od.error), 'hub unreachable: the order waits (a line is never signed partial)', od); + HUB.down = false; await sleep(350); + + console.log('7. positions recorded from the chain'); + // coachann buys first (line bound, lineup1 paid 25% as sponsor; lineup2 passed over; topcoach 5%), then coachbob (2 positions) and coachcy + const tA = Math.floor(Date.now() / 1000) - 1800; // real block times (the Telegram card skips anything older than 2 hours) + const bA = chainBuy({ buyer: A.wallet.address, blockAt: tA, bound: [[A.wallet.address, wL1.address], [wL1.address, wL2.address], [wL2.address, wTop.address]], over: [[wL2.address, 2]], pays: [[wL1.address, 1], [wTop.address, 3]] }); + let led = await until(async () => { const l = await anon.json('/api/ledger'); return l.items && l.items.length && l.items[0].pays.some(p => p.to) ? l : null; }); + const it = led.items[0]; + ok(led.items.length === 1 && it.buyerName === 'coachann' && it.usdCents === 1000, 'the ledger shows the position', it); + const pays = Object.fromEntries(it.pays.map(p => [p.label, p])); + ok(pays.sponsor.wei === bA.sp.toString() && pays.sponsor.wei === (10n ** 19n).toString() && pays['level 2'].wei === (2n * 10n ** 18n).toString() && pays['level 2'].depth === 3 && pays.pot.wei === (4n * 10n ** 18n).toString() && pays.company.wei === (24n * 10n ** 18n).toString(), + 'split from the receipt: sponsor 25% = 10 POL, level 2 5% = 2 POL (place 3), pot 10% = 4 POL, company 24 POL (45% + the unfilled levels)', it.pays); + ok(it.passedOver.length === 1 && it.passedOver[0].depth === 2, 'passed over: place 2 (no position)', it.passedOver); + for (let i = 0; i < 30 && !TG.length; i++) await sleep(150); + const cap = (TG[0] && TG[0].body.caption) || ''; + ok(TG.length === 1 && TG[0].method === 'sendPhoto' && TG[0].body.message_thread_id === 632242 && /\/art\/proof\/fx-proof-[a-z]+\.png$/.test(TG[0].body.photo), 'Telegram: one photo card in the payments topic', TG.map(t => t.method)); + ok(/@coachann joined The Draft: a position ยท \$10\.00 \(40\.0000 POL\)/.test(cap) && /Sponsor 25%: 10\.0000 POL โ†’ /.test(cap) && /Level 2 5%: 2\.0000 POL โ†’ .*\(place 3 in the line\)/.test(cap) && /Best Coach pot 10%: 4\.0000 POL/.test(cap) && /5xYourTeam: 24\.0000 POL/.test(cap) && /passed over/.test(cap) && /explorer\.invalid\/tx\/0x[0-9a-f]{64}/.test(cap) && !/[\u2014\u2013]/.test(cap), 'sale card: coach, every share with POL and place, pot, company, passed over, verify link, no dashes', cap); + chainBuy({ buyer: Bc.wallet.address, qty: 2, blockAt: tA + 600, pays: [[A.wallet.address, 1]] }); + chainBuy({ buyer: Cc.wallet.address, blockAt: tA + 1200, pays: [[A.wallet.address, 1]] }); + await until(async () => (await anon.json('/api/ledger')).items.length === 3); + me = await A.json('/api/me'); let my = await A.json('/api/my'); + ok(me.coach && my.positions === 1 && my.credits === 5, 'coachann is a coach with 5 instant picks', { coach: me.coach, credits: my.credits }); + my = await Bc.json('/api/my'); ok(my.positions === 2 && my.credits === 10, '2 positions = 10 instant picks', my.credits); + for (let i = 0; i < 30 && !HUB.got.length; i++) await sleep(150); + ok(HUB.got.some(g => g.route === '/v1/contract-bind' && g.body.contract === 'fivex' && g.body.wallet === A.address && g.body.sponsorRef === wL1.address.toLowerCase()), 'hub report: contract-bind for the coach with their direct sponsor', HUB.got.slice(0, 2)); + CHAIN.replayAll = true; await sleep(800); CHAIN.replayAll = false; + led = await anon.json('/api/ledger'); ok(led.items.length === 3 && TG.length === 3, 'a flaky RPC re-sending old logs: no second record, no second Telegram post'); + ok(led.totals.potWei === (16n * 10n ** 18n).toString(), 'ledger total to the Best Coach pot: 10% of 4 positions = 16 POL', led.totals); + b = await A.json('/api/board'); ok(b.pot.wei === (16n * 10n ** 18n).toString() && b.me.coach && b.pool[0].gameWei !== undefined, 'the board: this week\'s pot; coaches see earnings on scouting cards', b.pot); + + console.log('8. instant picks'); + const p1 = b.pool[0].id; + let ip = await A.json('/api/my/instant', { person: p1 }); ok(ip.ok && ip.credits === 4, 'an instant pick from the pool (5 -> 4 credits)', ip); + ip = await Bc.json('/api/my/instant', { person: p1 }); ok(/no longer available/.test(ip.error), 'the same player cannot be taken twice', ip); + ip = await PICK.json('/api/my/instant', { person: b.pool[1].id }); ok(ip._status === 403, 'no position: no instant pick', ip); + ip = await A.json('/api/my/instant', { person: pid('lockedlarry') }); ok(/no longer available/.test(ip.error), 'someone locked on a network contract can never be picked', ip); + const gd = pid('gamerdad'); + ip = await A.json('/api/my/instant', { person: gd }); ok(ip.ok, 'coachann picks @gamerdad (who will sign in as a pick)', ip); + my = await A.json('/api/my'); + ok(my.picks.length === 2 && my.picks.every(p => p.status === 'open' && p.kind === 'instant' && p.daysLeft === 3) && my.help.length === 2, 'My Team: 2 open instant picks with 3 days to start, both on the who-to-help list', my.picks.map(p => [p.username, p.daysLeft])); + ok(!EMAIL_RE.test(JSON.stringify(my)), 'no email address anywhere in My Team data'); + + console.log('9. coaching messages (through the site only)'); + const gpk = my.picks.find(p => p.person === gd); + let m = await A.json('/api/my/message', { pick: gpk.id, text: 'Welcome! I am your coach here.' }); ok(m.ok, 'the coach writes to their pick'); + m = await Bc.json('/api/my/message', { pick: gpk.id, text: 'hi' }); ok(m._status === 403, 'another coach cannot write to someone else\'s pick', m); + me = await PICK.json('/api/my'); ok(me.myCoach && me.myCoach.coach === 'coachann' && me.myCoach.messages.length === 1 && me.myCoach.messages[0].text === 'Welcome! I am your coach here.', 'the pick sees their coach and the message (markup stripped)', me.myCoach); + m = await PICK.json('/api/my/message', { pick: gpk.id, text: 'Thanks coach, how do I link a wallet?' }); ok(m.ok, 'the pick replies through the site'); + let th = await A.json('/api/my/messages?pick=' + gpk.id); ok(th.items.length === 2 && th.items[1].mine === false && th.with === 'gamerdad', 'the coach sees the thread', th); + ok(!EMAIL_RE.test(JSON.stringify(me)) && !EMAIL_RE.test(JSON.stringify(th)), 'no contact data in the pick or coach views'); + + console.log('10. the live draft (test clock: Monday 7 PM Central)'); + await A.json('/api/my/queue', { ids: [] }); + const bq = (await Cc.json('/api/board')).pool; const cyWant = bq[bq.length - 1].id; // the lowest scouting score: nobody else's auto-pick + await Cc.json('/api/my/queue', { ids: [cyWant] }); + await admin('/api/admin/clock', { now: MON - 2000 }); await A.json('/api/presence', {}); await sleep(2600); + b = await A.json('/api/board'); + ok(b.draft && b.draft.status === 'live' && b.draft.onClock && b.draft.onClock.me && b.draft.onClock.slot === '1.1' && b.draft.coaches === 3, 'the draft starts at 7 PM Central: coachann (earliest position, no starts last week) is on the clock at 1.1', b.draft && b.draft.onClock); + ip = await Bc.json('/api/my/instant', { person: b.pool[0].id }); ok(/draft is live/.test(ip.error), 'no instant picks while the draft is live', ip); + let dp = await PICK.json('/api/draft/pick', { person: b.pool[0].id }); ok(/not on the clock/.test(dp.error), 'someone who is not on the clock cannot pick', dp); + const mine1 = b.pool[2].id; dp = await A.json('/api/draft/pick', { person: mine1 }); ok(dp.ok, 'coachann drafts by hand', dp); + b = await until(async () => { const x = await A.json('/api/board'); return x.draft.made >= 3 ? x : null; }); + ok(b.draft.made === 3 && b.draft.onClock.slot === '2.1' && b.draft.onClock.me, 'coachbob and coachcy are away: auto-picked at once; round 2 puts coachann back on the clock', b.draft); + const cyRow = (await A.json('/api/board')).draft.rows.find(x => x.coach === 'coachcy'); + ok(cyRow && cyRow.person === (bq.find(p => p.id === cyWant) || {}).username, 'coachcy (away) got the first player on their queue', cyRow); + await admin('/api/admin/clock', { now: MON + 400 * 1000 }); // past the 300-second clock and the 120-second room window: coachann is away now + const done = await until(async () => { const x = await A.json('/api/board'); return x.draft.status === 'done' ? x : null; }, 10000); + ok(done && done.draft.made === 15, 'the clock ran out and coachann was away: everyone auto-picked, 3 coaches x 5 rounds = 15 picks', done && done.draft); + const tdd = await until(async () => TG.find(t => /Draft Day results/.test(t.body.caption || '')), 5000); + ok(tdd && /\/art\/draftday\/week-2026-11-16\.png$/.test(tdd.body.photo) && /1\.1<\/b> @coachann takes @/.test(tdd.body.caption) && /15 players drafted ยท 3 coaches/.test(tdd.body.caption), 'the Draft Day card: results image + the picks, once', tdd && tdd.body); + const dd = await anon.json('/api/draftday?week=2026-11-16'); ok(dd.rows.length === 15 && dd.players === 15, 'the Draft Day data for the card', dd.players); + my = await A.json('/api/my'); ok(my.picks.filter(p => p.status === 'open').length === 7 && my.stats.onTeam === 7, 'coachann: 2 instant + 5 drafted = 7 open picks', my.stats); + + console.log('11. milestones, cards, Best Coach, Rookie of the Week'); + await admin('/api/admin/stub/status', { id: gd, wallet: true }); await admin('/api/admin/tick', {}); + my = await A.json('/api/my'); let g = my.picks.find(p => p.person === gd); + ok(g.tier === 'starter' && g.steps.find(s => s.key === 'wallet').done && g.steps.find(s => s.next).key === 'payouts', 'a pick links a wallet: Starter, next step payouts', g.steps); + ok(my.help[0].pickId === g.id || my.help.some(h => h.pickId === g.id && /one step from payouts/.test(h.why)), 'who to help: @gamerdad is one step from payouts', my.help.slice(0, 3)); + await admin('/api/admin/stub/status', { id: gd, payouts: true }); await admin('/api/admin/tick', {}); + const bpk = (await Bc.json('/api/my')).picks.filter(p => p.status === 'open'); + await admin('/api/admin/stub/status', { id: bpk[0].person, purchase: true }); await admin('/api/admin/stub/status', { id: bpk[1].person, wallet: true, payouts: true }); await admin('/api/admin/tick', {}); + my = await A.json('/api/my'); g = my.picks.find(p => p.person === gd); + ok(g.status === 'done' && g.tier === 'pro', '@gamerdad switched on payouts: started, stays on the team (Pro card)', g); + b = await A.json('/api/board'); + ok(b.best.length === 2 && b.best[0].coach === 'coachbob' && b.best[0].started === 2 && b.best[1].coach === 'coachann', 'Best Coach standings: coachbob 2 started, coachann 1', b.best); + ok(b.rookie && b.rookie.tier === 'allstar', 'Rookie of the Week: the pick that climbed highest (All-Star)', b.rookie); + const cards = await anon.json('/api/coach?u=coachann'); + ok(cards.team.some(c => c.username === 'gamerdad' && c.tierName === 'Pro' && c.milestone === 'Payouts switched on') && !/"(gameWei|surfWei|earned\w*|weiPaid)"/.test(JSON.stringify(cards)), 'public cards: milestones only, never earnings', cards.team.slice(0, 3)); + r = await anon.req('/coachann'); ok(r.status === 200 && /coach\.js/.test(await r.text()), 'GET /coachann serves the coach page'); + const rc = await anon.json('/api/recent'); ok(rc.items.some(x => x.kind === 'level' && x.person === 'gamerdad') && rc.items.some(x => x.kind === 'pick'), 'toasts: picks and level-ups (real events only)', rc.items.slice(0, 4)); + const pot = await admin('/api/admin/pot?week=2026-11-16'); + ok(pot.shares.length === 2 && pot.shares[0].username === 'coachbob' && pot.shares[0].pct === 50, 'admin: the week\'s pot shares by place (rule open for Marty)', pot); + + console.log('12. picks return to the pool; the release hold'); + let rl = await A.json('/api/my/release', { pick: my.picks.find(p => p.status === 'open').id }); ok(/less than 48 hours/.test(rl.error), 'a pick cannot be released in its first 48 hours', rl); + await admin('/api/admin/clock', { now: MON + 3 * D + 3600000 }); await admin('/api/admin/tick', {}); + my = await A.json('/api/my'); + ok(my.picks.filter(p => p.status === 'open').length === 0 && my.picks.filter(p => p.status === 'returned').length >= 5 && my.picks.find(p => p.person === gd).status === 'done', 'after 3 days the unconverted picks go back to the pool; the started one stays', my.picks.map(p => p.status)); + b = await anon.json('/api/board'); ok(b.poolSize > 15, 'they are draftable again', b.poolSize); + th = await A.json('/api/my/message', { pick: my.picks.find(p => p.status === 'returned').id, text: 'still there?' }); ok(/back in the pool/.test(th.error), 'a returned pick\'s thread is closed', th); + + console.log('13. old site links'); + r = await anon.req('/api/admin/oldrefs', { method: 'POST', headers: { 'x-admin-token': ADMIN }, body: JSON.stringify({ oldrefs: { janie23: 'coachann', 'bad key!': 'x' } }) }); + const or = await r.json(); ok(or.ok && or.total === 1 && or.skipped === 1, 'admin loads the old-username map', or); + for (const [from, to] of [['/?janie23', '/coachann'], ['/splashpg.php?pid=4&r=janie23', '/coachann'], ['/lcp.php?r=JANIE23', '/coachann'], ['/index.php?r=janie23', '/coachann'], ['/members/login.php', '/team'], ['/?nobodyold', '/'], ['/whatever.php', '/']]) { + r = await anon.req(from); ok(r.status === 301 && r.headers.get('location') === to, 'old link ' + from + ' -> ' + to, r.headers.get('location')); } + r = await anon.req('/?ref=coachann'); ok(r.status === 200, '/?ref= is not an old link'); + + console.log('14. admin'); + r = await anon.req('/api/admin/status'); ok(r.status === 401, 'admin needs the token'); + st = await admin('/api/admin/status'); const sj = JSON.stringify(st); + ok(st.shop.vouchers && st.shop.keeper === KEEPER && !sj.includes(KEEPER_PK.slice(2)) && !sj.includes(HUB_SECRET) && !sj.includes('standin-token') && !sj.includes(SSO_SECRET), 'admin status: keeper address only, no key or secrets', st.shop); + ok(st.tank.mode === 'stub' && st.tank.adoptionMailsThatWouldSend >= 17, 'stub tank: every pick went through adopt (mails counted, none sent)', st.tank); + const pp = await admin('/api/admin/pot/paid', { week: '2026-11-16', rank: 1, coach: Bc.address, wei: '8000000000000000000', tx: '0x' + 'ab'.repeat(32) }); + ok(pp.ok && (await anon.json('/api/ledger')).payouts.length === 1, 'a Best Coach payout recorded with its tx shows on the ledger', pp); + const tpl = await until(async () => TG.find(t => /Best Coach, week of 2026-11-16: #1 @coachbob got 8\.0000 POL/.test(t.body.text || '')), 4000); + ok(!!tpl, 'one Telegram line per Best Coach payout'); + + console.log('15. restart (Telegram not live: the outbox)'); + await sleep(700); { const sd = JSON.parse(fs.readFileSync(path.join(DATA, 'fivex.json'), 'utf8')).drafts['2026-11-16']; ok(sd && sd.status === 'done', 'the finished draft is saved as done before the restart', sd && sd.status); } + await stop(); await boot({ TG_LIVE: '' }); await admin('/api/admin/clock', { now: MON + 3 * D + 3700000 }); await sleep(500); + my = await A.json('/api/my'); ok(my.positions === 1 && my.picks.length === 7 && my.picks.find(p => p.person === gd).tier === 'pro', 'after a restart: positions, picks and milestones are kept'); + const tgBefore = TG.length; + chainBuy({ buyer: Cc.wallet.address, blockAt: Math.floor(Date.now() / 1000), pays: [[A.wallet.address, 1]] }); + await until(async () => (await anon.json('/api/ledger')).items.length === 4); await sleep(800); + st = await admin('/api/admin/status'); + ok(TG.length === tgBefore && st.proof.queued === 1 && /outbox/.test(st.proof.telegram) && st.proof.outbox.some(x => /coachcy joined The Draft/.test(x.body.caption || '')), 'with TG_LIVE unset nothing is sent: the sale card waits in the outbox', st.proof); + + if (!process.env.SKIP_UI && fs.existsSync(PW)) { + console.log('16. Playwright renders (desktop 1280 + phone 390)'); + // next Monday's draft: coachbob (2 started last week) picks first, then coachann, who is in the room: on the clock + await admin('/api/admin/clock', { now: ctToMs('2026-11-23', 19) - 2500 }); await A.json('/api/presence', {}); await sleep(3200); + b = await A.json('/api/board'); ok(b.draft && b.draft.status === 'live' && b.draft.onClock && b.draft.onClock.me && b.draft.made === 1, 'week 2: draft order earned (coachbob first); coachann is on the clock', b.draft && b.draft.onClock); + const { chromium } = require(PW); const browser = await chromium.launch(); + for (const [label, vp] of [['desktop', { width: 1280, height: 900 }], ['phone', { width: 390, height: 844 }]]) { + const ctx = await browser.newContext({ viewport: vp, isMobile: label === 'phone', userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/130.0 Safari/537.36 SmokeUI-' + label }); + await ctx.route(/^https:\/\//, rt => (process.env.UI_FONTS && /^https:\/\/fonts\.(googleapis|gstatic)\.com\//.test(rt.request().url())) ? rt.continue() : rt.abort()); + await ctx.addCookies([{ name: 'fx.sid', value: A.jar['fx.sid'], url: BASE }]); + const errs = []; const pg = await ctx.newPage(); pg.on('pageerror', e => errs.push(e.message)); + for (const [p, sel] of [['/', '#pool .scout'], ['/team', '#focus:not([hidden]) .steps div'], ['/cards', '#mineCards .tc'], ['/join', '#jQty option'], ['/coachann', '#cTeam .tc'], ['/ledger', '#rows tbody tr'], ['/contract', '#facts th'], ['/promote', '#kit .card'], ['/builder', '#bList .kit-row'], ['/terms', '.legal .card'], ['/disclaimer', '.legal .card'], ['/privacy', '.legal .card']]) { + await pg.goto(BASE + p, { waitUntil: 'domcontentloaded' }); await pg.waitForSelector(sel, { timeout: 8000 }).catch(() => {}); + await sleep(300); + const found = await pg.$$eval(sel, els => els.length); + const wide = await pg.evaluate(() => document.documentElement.scrollWidth - window.innerWidth); + ok(found > 0 && wide <= 1, label + ' ' + p + ': renders (' + sel + ') with no sideways scroll', { found, wide }); + await pg.screenshot({ path: path.join(OUT, label + '-' + (p === '/' ? 'board' : p.slice(1)) + '.png'), fullPage: true }); + } + await pg.goto(BASE + '/', { waitUntil: 'domcontentloaded' }); await pg.waitForFunction(() => /ON THE CLOCK/.test(document.getElementById('heroKick').textContent), null, { timeout: 8000 }).catch(() => {}); + ok(/YOU'RE ON THE CLOCK/.test(await pg.textContent('#heroKick')) && /Pick 2 of Round 1/.test(await pg.textContent('#heroTitle')) && (await pg.$$eval('[data-draft]', e => e.length)) > 0, label + ': board says YOU\'RE ON THE CLOCK with DRAFT buttons'); + ok((await pg.textContent('footer')).includes('TrustClickz') && /Part of the network/.test(await pg.textContent('footer')) && /5xYourTeam/.test(await pg.textContent('footer .netline')), label + ': footer has the company line and the network line'); + ok(errs.length === 0, label + ': no page errors', errs); + await ctx.close(); + } + // a pick's view of /team (their coach and the thread) + { const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } }); await ctx.route(/^https:\/\//, rt => (process.env.UI_FONTS && /^https:\/\/fonts\.(googleapis|gstatic)\.com\//.test(rt.request().url())) ? rt.continue() : rt.abort()); + await ctx.addCookies([{ name: 'fx.sid', value: PICK.jar['fx.sid'], url: BASE }]); const pg = await ctx.newPage(); + await pg.goto(BASE + '/team', { waitUntil: 'domcontentloaded' }); await pg.waitForSelector('#myCoach:not([hidden]) .msg', { timeout: 8000 }).catch(() => {}); + ok(/@coachann/.test(await pg.textContent('#mcName')) && (await pg.$$eval('#mcThread .msg', e => e.length)) === 2, 'a pick sees their coach and the thread on /team'); + await pg.screenshot({ path: path.join(OUT, 'desktop-team-as-pick.png'), fullPage: true }); + const p2 = await (await browser.newContext({ viewport: { width: 1080, height: 1080 } })).newPage(); + await p2.goto(BASE + '/draftday/2026-11-16', { waitUntil: 'domcontentloaded' }); await p2.waitForSelector('body[data-ready="1"]', { timeout: 8000 }).catch(() => {}); + ok((await p2.$$eval('.dd-r', e => e.length)) === 6 && /15 players drafted/.test(await p2.textContent('#ddStats')), 'the Draft Day card renders from the week\'s results'); + await p2.screenshot({ path: path.join(OUT, 'draftday-2026-11-16.png') }); + await ctx.close(); } + await browser.close(); + } else console.log('16. (Playwright renders skipped)'); + + await stop(); + console.log('\n' + pass + ' passed, ' + fail + ' failed'); + fs.writeFileSync(path.join(OUT, 'smoke.txt'), new Date().toISOString() + ' ' + pass + ' passed, ' + fail + ' failed\n'); + process.exit(fail ? 1 : 0); +} +main().catch(e => { console.error('smoke crashed:', e.stack || e.message); fail++; process.exit(1); }); diff --git a/qa/unit.test.cjs b/qa/unit.test.cjs new file mode 100644 index 0000000..9e7529f --- /dev/null +++ b/qa/unit.test.cjs @@ -0,0 +1,172 @@ +// Unit tests: the draft engine (draft.js) with a mocked clock, the pass-up split model (proof.model) against the DraftPosition fork +// rehearsal numbers, Central-time weeks, and the league (league.js + the stub tank) end to end on a temp data dir. No network. +// node qa/unit.test.cjs +'use strict'; +const path = require('path'); +const fs = require('fs'); +const os = require('os'); +const APP = path.resolve(__dirname, '..'); +let pass = 0, fail = 0; +const ok = (c, what, extra) => { if (c) { pass++; console.log(' ok ' + what); } else { fail++; console.log(' FAIL ' + what + (extra !== undefined ? ' -> ' + JSON.stringify(extra).slice(0, 400) : '')); } }; +const D = 86400000, H = 3600000; +const draft = require(path.join(APP, 'draft.js')); +const RULES = { maxOpen: 10, maxAdoptions: 2, graceHours: 24, holdHours: 48, returnDays: 3 }; + +(async () => { + console.log('1. tiers'); + ok(draft.tierOf({}) === 'rookie' && draft.tierOf({ wallet: 1 }) === 'starter' && draft.tierOf({ wallet: 1, payouts: 2 }) === 'pro' && draft.tierOf({ purchase: 3 }) === 'allstar' && draft.tierOf({ purchase: 3, ownTeam: 4 }) === 'hof', 'tiers: Rookie, Starter (wallet), Pro (payouts), All-Star (purchase), Hall of Fame (own team)'); + ok(!draft.started({ wallet: 5 }) && draft.started({ payouts: 5 }) && draft.started({ purchase: 5 }) && draft.startedAt({ payouts: 9, purchase: 7 }) === 7, '"started" = payouts on or a purchase (a wallet alone is not)'); + + console.log('2. the pool: tank rules'); + const T = 1_800_000_000_000; + const c = (id, o) => Object.assign({ id, username: id, joinedAt: T - 10 * D, lastSeen: T - H }, o || {}); + const cands = [c('h_a'), c('h_locked', { locked: true }), c('h_spons', { sponsored: true }), c('h_spam', { spam: true }), c('h_throw', { throwaway: true }), + c('h_new', { joinedAt: T - 5 * H }), c('h_twice', { adoptions: 2 }), c('h_once', { adoptions: 1 }), c('h_taken'), c('h_done'), c('h_ret')]; + const picks0 = [{ id: 1, person: 'h_once', status: 'returned' }, { id: 2, person: 'h_taken', status: 'open' }, { id: 3, person: 'h_done', status: 'done' }, { id: 4, person: 'h_ret', status: 'returned' }]; + const why = Object.fromEntries(cands.map(x => [x.id, draft.blocked(x, picks0, RULES, T)])); + ok(why.h_locked === 'locked' && why.h_spons === 'sponsored' && why.h_spam === 'spam' && why.h_throw === 'spam', 'never anyone locked on a network contract, already sponsored, spam or throwaway', why); + ok(why.h_new === 'grace', 'a sign-up inside the 24-hour grace is not draftable', why.h_new); + ok(why.h_twice === 'adopted-twice' && why.h_once === 'adopted-twice', 'max 2 adoptions per person: 2 elsewhere, or 1 elsewhere + 1 pick here', [why.h_twice, why.h_once]); + ok(why.h_taken === 'taken' && why.h_done === 'taken', 'someone on a team (open or started) is not draftable', [why.h_taken, why.h_done]); + ok(why.h_ret === null && why.h_a === null, 'a person back in the pool after one return can be drafted once more', why.h_ret); + const pl = draft.pool([c('h_x', { lastSeen: T - 30 * D }), c('h_y', { wallet: true }), c('h_z', { games: { plays: 12, title: 'Gem Kingdom', earnedWei: '1' } })], [], RULES, T); + ok(pl.map(x => x.id).join() === 'h_y,h_z,h_x' && pl[0].score === 55 && pl[1].score === 47, 'best available by scouting score (wallet 30, plays up to 40, seen today 25, earned 10)', pl.map(x => [x.id, x.score])); + ok(draft.score(c('h_q', { lastSeen: 0, games: null, surfWei: null }), T) === 0, 'missing scouting data adds nothing (never invented)'); + + console.log('3. draft order is earned'); + const coaches = [{ address: '0xa', username: 'ann', since: 100 }, { address: '0xb', username: 'bob', since: 50 }, { address: '0xc', username: 'cy', since: 200 }, { address: '0xd', username: 'dee', since: 300 }]; + const P = [{ coach: '0xc', week: 'W1', m: { payouts: 1 } }, { coach: '0xc', week: 'W1', m: { purchase: 1 } }, { coach: '0xa', week: 'W1', m: { payouts: 1 } }, { coach: '0xa', week: 'W1', m: { wallet: 1 } }, + { coach: '0xb', week: 'W1', m: { payouts: 1 } }, { coach: '0xb', week: 'W0', m: { payouts: 1 } }]; + const st = draft.standings(coaches, P, 'W2', 'W1'); + ok(st.map(x => x.username).join() === 'cy,bob,ann,dee', 'most of last week\'s picks started first (cy 2); tie on 1 broken by lifetime (bob 2 > ann 1); a wallet alone does not count', st.map(x => [x.username, x.lastWeek, x.lifetime])); + const st2 = draft.standings([{ address: '0xe', since: 10 }, { address: '0xf', since: 5 }], [], 'W2', 'W1'); + ok(st2[0].address === '0xf', 'no picks yet: the earlier position picks first'); + const st3a = draft.standings([{ address: '0x1', since: 0 }, { address: '0x2', since: 0 }, { address: '0x3', since: 0 }], [], 'W5', 'W4').map(x => x.address).join(); + const st3b = draft.standings([{ address: '0x3', since: 0 }, { address: '0x2', since: 0 }, { address: '0x1', since: 0 }], [], 'W5', 'W4').map(x => x.address).join(); + ok(st3a === st3b, 'a full tie is a fixed shuffle of (week, coach): same order whatever the input order', [st3a, st3b]); + + console.log('4. the draft with a mocked clock'); + const d = draft.newDraft({ week: 'W2', at: T, rounds: 2, order: ['0xa', '0xb', '0xc'] }); + ok(d.slots.length === 6 && d.slots.map(s => draft.slotLabel(s) + s.coach).join() === '1.10xa,1.20xb,1.30xc,2.10xa,2.20xb,2.30xc', 'straight rounds: the earned order every round', d.slots.map(draft.slotLabel)); + const present = new Set(['0xa']); const queues = { '0xc': ['h_p4', 'h_p2'] }; const open = { '0xa': 0, '0xb': 0, '0xc': 0 }; + const ctx = { pool: ['h_p1', 'h_p2', 'h_p3', 'h_p4', 'h_p5', 'h_p6'], present: a => present.has(a), queue: a => queues[a] || [], openCount: a => open[a], rules: RULES, pickSeconds: 90 }; + let refuse = new Set(['h_p3']); const adopted = []; + const adopt = act => { if (refuse.has(act.person)) { refuse.delete(act.person); return { error: 'locked a moment ago' }; } adopted.push([act.coach, act.person]); open[act.coach]++; return { ok: true, pickId: adopted.length }; }; + await draft.run(d, ctx, adopt, T); + ok(d.made.length === 0, 'the first coach is in the draft room: the clock runs, nothing is auto-picked yet'); + let a = draft.manual(d, '0xb', 'h_p1', ctx, T + 1000); ok(a.error === 'You are not on the clock.', 'a coach who is not on the clock cannot pick', a); + a = draft.manual(d, '0xa', 'h_p2', ctx, T + 1000); ok(a.type === 'pick', 'the coach on the clock picks by hand'); + draft.record(d, a, adopt(a), T + 1000); + await draft.run(d, ctx, adopt, T + 1000); + ok(d.made.length === 3 && d.made[1].coach === '0xb' && d.made[1].person === 'h_p1' && d.made[1].auto, 'an absent coach is auto-picked at once: the best available', d.made); + ok(d.made[2].coach === '0xc' && d.made[2].person === 'h_p4' && d.made[2].fromQueue, 'an absent coach with a queue gets their first available queued player', d.made[2]); + ok(d.made.length === 3 && draft.current(d).coach === '0xa' && d.clockAt === T + 1000, 'round 2: the present coach gets a fresh clock', draft.current(d)); + await draft.run(d, ctx, adopt, T + 1000 + 89000); ok(d.made.length === 3, 'still inside the 90-second clock: waiting'); + await draft.run(d, ctx, adopt, T + 1000 + 90000); + ok(d.made[3].person === 'h_p5' && d.unavailable.includes('h_p3'), 'clock ran out: auto-pick; the tank refused h_p3 (locked meanwhile), so it is skipped and the same coach gets the next one', d.made.slice(3)); + ok(d.status === 'done' && d.made.length === 5 && d.why === 'pool empty', 'the pool ran out: the draft ends', [d.status, d.why, d.made.length]); + ok(new Set(adopted.map(x => x[1])).size === adopted.length, 'nobody is drafted twice'); + const d2 = draft.newDraft({ week: 'W2', at: T, rounds: 1, order: ['0xa', '0xb'] }); + const full = { '0xa': 10, '0xb': 0 }; + await draft.run(d2, Object.assign({}, ctx, { present: () => false, openCount: x => full[x] }), act => ({ ok: true }), T); + ok(d2.made[0].skipped === 'team full' && d2.made[1].person === 'h_p1', 'a coach with a full team (10 open) is skipped for that slot', d2.made); + const d3 = draft.newDraft({ week: 'W2', at: T, rounds: 3, order: [] }); ok(d3.status === 'done', 'no coaches: nothing to draft'); + + console.log('5. picks return to the pool'); + const pk = (id, o) => Object.assign({ id, person: 'h_' + id, coach: '0xa', status: 'open', at: T - 4 * D, expires: T - D, m: {} }, o); + const ps = [pk(1), pk(2), pk(3), pk(4, { expires: T + D }), pk(5, { status: 'done' })]; + const sts = { h_1: { payouts: T - 2 * D }, h_2: { wallet: T - D }, h_3: { adoptions: 1 }, h_4: { wallet: T - H } }; + const ch = draft.sweep(ps, id => sts[id] || null, RULES, T); + const by = Object.fromEntries(ch.map(x => [x.pick.id, x])); + ok(by[1].set.status === 'done' && by[1].set.tier === 'pro', 'a pick that switched on payouts stays for good (done, Pro)', by[1].set); + ok(by[2].set.status === 'returned' && by[2].release === true, 'unconverted past the return window: back to the pool (released in the tank)', by[2]); + ok(by[3].set.status === 'kept' && !by[3].release, 'past the window but adopted twice now (1 elsewhere + this one): stays with the coach, never back to nobody', by[3]); + ok(by[4].set.tier === 'starter' && !by[4].set.status, 'inside the window: milestones refresh, no status change', by[4].set); + ok(!by[5], 'started picks are not swept'); + ok(draft.sweep([pk(9)], () => null, RULES, T).length === 0, 'the network cannot say: nothing changes'); + ok(/less than 48 hours/.test(draft.canRelease(pk(7, { at: T - H }), RULES, T)) && draft.canRelease(pk(8, { at: T - 3 * D }), RULES, T) === null, 'a coach cannot release a pick inside the 48-hour hold'); + + console.log('6. boards'); + const from = T, to = T + 7 * D; + const bp = [{ id: 1, coach: '0xa', m: { payouts: T + D } }, { id: 2, coach: '0xa', m: { purchase: T + 2 * D } }, { id: 3, coach: '0xb', m: { payouts: T + H } }, { id: 4, coach: '0xb', m: { payouts: T + 3 * D } }, + { id: 5, coach: '0xc', m: { payouts: T - D } }, { id: 6, coach: '0xc', m: { wallet: T + H } }]; + const best = draft.bestCoach(bp, from, to, a2 => ({ '0xa': 'ann', '0xb': 'bob', '0xc': 'cy' })[a2]); + ok(best.map(x => x.username + x.started).join() === 'ann2,bob2' && best[0].rank === 1, 'Best Coach: picks started inside the week; a tie goes to who got there first; last week\'s start and a wallet alone do not count', best); + const shares = draft.potShares('1000000000000000001', [50, 30, 20], best); + ok(shares.length === 2 && shares[0].wei === '500000000000000000' && shares[1].wei === '300000000000000000', 'pot shares by place (50/30/20 of the pot; places without a coach stay in the pot)', shares); + const rk = draft.rookie([{ id: 1, week: 'W', m: { wallet: 5 } }, { id: 2, week: 'W', m: { payouts: 9 } }, { id: 3, week: 'W', m: { payouts: 7 } }, { id: 4, week: 'V', m: { purchase: 1 } }], 'W'); + ok(rk && rk.pick.id === 3 && rk.tier === 'pro', 'Rookie of the Week: the pick that climbed highest that week, first to get there wins a tie', rk); + const help = draft.helpList([pk(1, { expires: T + 5 * H, m: { lastSeen: T - H, username: 'u1' } }), pk(2, { expires: T + 2 * D, m: { wallet: 1, lastSeen: T - H, username: 'u2' } }), pk(3, { expires: T + 2 * D, m: { lastSeen: T - 4 * D, username: 'u3' } }), pk(4, { status: 'done' })], T); + ok(help.map(x => x.pickId).join() === '1,2,3' && /Back to the pool in 5 hours/.test(help[0].why) && /payouts/.test(help[1].say) && /SafePal or any other crypto wallet/.test(help[2].say), 'who to help: back-to-pool soon first, then one step from payouts, then quiet; suggested messages', help); + const allSay = help.map(x => x.say + x.why).join(' '); + ok(!/[โ€“โ€”]/.test(allSay) && !/metamask|income|earn \$/i.test(allSay), 'coaching copy: no dashes, no wallet brand but SafePal, no income talk'); + + console.log('7. the pass-up split model = the contract (fork rehearsal 2026-11-15)'); + const proof = require(path.join(APP, 'proof.js')); + const q = 122663264805456062018n; + const q1 = (l) => l.map((w, i) => ({ who: w[0], qualified: w[1] })); + let mo = proof.model(q1([['A1', 1], ['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); + ok(mo.pays.map(x => x.to + x.level + 'd' + x.depth).join() === 'A11d1,A32d3,A53d5,A64d6,A75d7' && mo.over.map(x => x.who).join() === 'A2,A4', 'B1 line: A1 L1, A3 A5 A6 A7 L2-L5, A2 A4 passed over', mo); + ok(mo.pays[0].wei === '30665816201364015504' && mo.pays[1].wei === '6133163240272803100' && mo.pot === '12266326480545606201' && mo.company === '55198469162455227913', 'B1 exact wei: sponsor 30.665816 POL, level 6.133163 POL, pot 12.266326 POL, company 55.198469 POL (A1 + A3 deltas below)', mo); + const mB3 = proof.model(q1([['B1', 1], ['A1', 1], ['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); + const mB5 = proof.model(q1([['A2', 0], ['A3', 1], ['A4', 0], ['A5', 1], ['A6', 1], ['A7', 1]]), q); + const got = n => [mo, mB3, mB5].reduce((t, m) => t + m.pays.filter(x => x.to === n).reduce((s, x) => s + BigInt(x.wei), 0n), 0n).toString(); + ok(got('A1') === '36798979441636818604' && got('A3') === '42932142681909621704' && got('A5') === '18399489720818409300' && got('A6') === '18399489720818409300' && got('A7') === '12266326480545606200', + 'the model\'s totals for A1 A3 A5 A6 A7 over B1 + B3 + B5 equal the fork rehearsal deltas to the wei', ['A1', 'A3', 'A5', 'A6', 'A7'].map(got)); + ok(mB5.pays[0].to === 'A3' && mB5.pays[0].depth === 2 && mB5.pays.length === 4, 'an unqualified direct sponsor: the 25% passes up to the nearest qualified (A3 at place 2); one level unfilled goes to the company', mB5.pays); + const none = proof.model(q1([['X', 0], ['Y', 0]]), 1000n); + ok(none.pays.length === 0 && none.pot === '100' && none.company === '900', 'nobody qualified: pot 10%, company 90%', none); + const deep = proof.model(Array.from({ length: 21 }, (_, i) => ({ who: 'D' + i, qualified: i === 20 })), 1000n); + ok(deep.pays.length === 0, 'a qualified person at place 21 is beyond MAX_DEPTH and gets nothing'); + const many = proof.model(Array.from({ length: 8 }, (_, i) => ({ who: 'M' + i, qualified: true })), 10000n); + ok(many.pays.length === 5 && many.pays.map(x => x.wei).join() === '2500,500,500,500,500' && many.company === '4500' && many.pot === '1000', 'more than 5 qualified: only the nearest 5; 25/5/5/5/5 + pot 10 + company 45', many); + + console.log('8. Central-time weeks'); + const store = require(path.join(APP, 'store.js')); + ok(store.ctToMs('2026-11-16', 19) === Date.UTC(2026, 10, 17, 1) && store.ctToMs('2026-07-06', 19) === Date.UTC(2026, 6, 7, 0), 'Monday 7 PM Central = 01:00 UTC in November (CST), 00:00 UTC in July (CDT)'); + ok(store.ctWeek(Date.UTC(2026, 10, 16, 5)) === '2026-11-09' && store.ctWeek(Date.UTC(2026, 10, 16, 7)) === '2026-11-16', 'the week turns at Monday midnight Central (05:00 UTC is still Sunday night)'); + + console.log('9. the league end to end (stub tank, temp data dir, mocked clock)'); + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'fx-unit-')); + Object.assign(process.env, { DATA_DIR: dir, DOCSTORE_URL: '', TANK_MODE: 'stub', DRAFT_ROUNDS: '2', PICK_RETURN_DAYS: '3' }); + require(path.join(APP, 'config.js')).reset(); const C = require(path.join(APP, 'config.js')).get(); + const league = require(path.join(APP, 'league.js')); const tank = require(path.join(APP, 'tankpool.js')); + require(path.join(APP, 'docstore.js')).install(dir); store.load(); + const monday7pm = store.ctToMs('2026-11-16', 19); + league.clock.set(monday7pm - 2 * H); + tank.init(C, { now: league.clock.now }); league.init(C, { proof: { draftDay: async () => true, potOf: () => '0' } }); + const S = store.state(); + const buy = (a, qty, at) => { S.purchases[a + ':0'] = { buyer: a, qty, at, blockAt: Math.floor(at / 1000), usdCents: 1000 * qty, weiPaid: '1', prizePaid: '0' }; store.upsertMember(a, { username: 'coach' + a.slice(-1) }); store.addCredits(a, 5 * qty); }; + const A = '0x' + 'a'.repeat(40), B = '0x' + 'b'.repeat(40); + buy(A, 1, monday7pm - 5 * D); buy(B, 1, monday7pm - 4 * D); + let r = await league.tick(); ok(!r.draft || r.draft.week !== '2026-11-16', 'before the draft hour: no draft this week', r); + const pool0 = await league.pool(league.clock.now()); + ok(pool0.length === 29 && !pool0.some(x => /locked|sponsor|spam|temp_mail|brandnew|twice/.test(x.username)), 'stub pool: 29 draftable of 35 (locked, sponsored, spam, throwaway, inside the grace, adopted twice left out)', pool0.length); + r = await league.instantPick(A, pool0[0].id); + ok(r.ok && store.credits(A) === 4 && store.picksOf(A)[0].kind === 'instant', 'an instant pick from the current pool uses one of the 5 credits', r); + r = await league.instantPick(A, pool0[0].id); ok(/no longer available/.test(r.error), 'the same player cannot be picked twice', r); + league.clock.set(monday7pm + 1000); + r = await league.tick(); + const dW = store.draft('2026-11-16'); + ok(dW && dW.status === 'done' && dW.made.filter(x => x.person).length === 4, 'at the draft hour: the draft runs (nobody in the room, all auto-picked): 2 coaches x 2 rounds', dW && dW.made); + ok(dW.order[0] === A, 'draft order: no starts last week, so the earlier position (A) picks first', dW.order); + ok(store.picks().every(p => p.status === 'open' && p.expires === p.at + 3 * D), 'every pick is an open adoption with a 3-day return window'); + ok(tank.view().adopted === 5 && tank.view().adoptionMailsThatWouldSend === 5, 'every pick went through the tank adopt call (stub: nobody adopted for real, mails only counted)', tank.view()); + r = await league.tick(); ok(store.draft('2026-11-16').made.length === dW.made.length, 'a second tick does not draft again'); + const first = store.picksOf(B)[0]; + tank.setStatus(first.person, { wallet: true, payouts: true }); + league.clock.set(monday7pm + 2 * D); await league.tick(); + ok(store.pick(first.id).status === 'done' && store.pick(first.id).tier === 'pro', 'a pick that switches on payouts is done (Pro) on the next sweep', store.pick(first.id)); + league.clock.set(monday7pm + 3 * D + 2000); await league.tick(); + const kept = store.picks().filter(p => p.status === 'kept').length; + ok(store.picks().filter(p => p.status === 'returned').length + kept === 4 && store.picks().filter(p => p.status === 'done').length === 1 && store.picks().filter(p => p.status === 'kept').every(p => p.personName === 'onceadopted'), 'after 3 days the unconverted picks go back to the pool (a person on their 2nd adoption stays with the coach)', store.picks().map(p => p.personName + ':' + p.status)); + const back = await league.pool(league.clock.now()); ok(back.length === 29 - 1 - kept + 1 && back.some(x => x.username === 'brandnew'), 'they are draftable again (29 - 1 started - any kept, + brandnew whose 24-hour grace has ended)', back.length); + // next week: B started 1 last week -> B picks first + const next7 = store.ctToMs('2026-11-23', 19); league.clock.set(next7 + 1000); await league.tick(); + ok(store.draft('2026-11-23').order[0] === B, 'next Monday the order is earned: B (1 pick started last week) picks before A (0)', store.draft('2026-11-23').order); + ok(store.picks().filter(p => p.week === '2026-11-23').every(p => !store.picks().some(q2 => q2.person === p.person && q2.status === 'done')), 'nobody already started on a team is drafted again'); + fs.rmSync(dir, { recursive: true, force: true }); + + console.log('\n' + pass + ' passed, ' + fail + ' failed'); + process.exit(fail ? 1 : 0); +})().catch(e => { console.error('unit crashed:', e.stack || e.message); process.exit(1); }); diff --git a/server.js b/server.js new file mode 100644 index 0000000..8a63e3b --- /dev/null +++ b/server.js @@ -0,0 +1,464 @@ +// 5xYourTeam web app (5xyourteam.com rebuild, "The Draft", Marty approved 2026-11-14). Plain Node http server, no framework (the +// InstantAdPay / Downline Banners / VBB / ViralAdBlitz pattern). Phase 1 = local build: nothing here deploys, posts or adopts for real. +// Product: a $10 one-time position = 5 picks right away + a draft spot every week. Every Monday the coaches draft people waiting in +// the network holding tank, in rounds; the draft order is earned (last week's picks started). Picks are adoptions (tankpool.js): +// coaches get the right to sponsor and help, never contact data. Coaching tools: pick cards with scouting stats, a message composer +// that goes through the site, a "who to help" list, the coach's builder links (the CryptoTeamBuild downline builder, wild.js). +// Pages: / (draft board), /team, /cards, /join, / (coach page), /ledger, /contract, /promote, /terms, /disclaimer, +// /privacy, /admin. +'use strict'; +const http = require('http'); +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const { verifyMessage, getAddress } = require('ethers'); +const cfgMod = require('./config'); + +const C = cfgMod.get(); +fs.mkdirSync(C.dataDir, { recursive: true }); +const docstore = require('./docstore'); docstore.install(C.dataDir); // before any module reads data +const store = require('./store'); +const draft = require('./draft'); +const league = require('./league'); +const tank = require('./tankpool'); +const networksso = require('./networksso'); +const shop = require('./shop'); +const promokit = require('./promokit'); +const hubreport = require('./hubreport'); +const hubpeople = require('./hubpeople'); +const hubline = require('./hubline'); +const proof = require('./proof'); +const netsites = require('./netsites'); +const wild = require('./wild'); + +const PUB = path.join(__dirname, 'public'); +const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; +const NAME_RE = /^[A-Za-z0-9_.-]{1,40}$/; +const PAGE_RE = /^\/([A-Za-z0-9_.-]{2,40})\/?$/; +const HUBID_RE = /^h_[0-9a-z]{16}$/; +const BOT_UA = /bot|crawl|spider|slurp|facebookexternalhit|preview|monitor|wget|curl|python|httpclient|scrapy|semrush|ahrefs|headless|lighthouse|pingdom|go-http|java\/|okhttp|axios|node-fetch|phantom|selenium|puppeteer/i; +const now = () => league.clock.now(); +const DAY = 86400000; + +// ---- http helpers ---- +const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': 'text/javascript', '.png': 'image/png', '.jpg': 'image/jpeg', + '.gif': 'image/gif', '.svg': 'image/svg+xml', '.ico': 'image/x-icon', '.json': 'application/json', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml' }; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net https://linkspin.app; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; " + + "img-src 'self' data: blob: https:; connect-src 'self' https://linkspin.app 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; " + + "font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: 'self'"; +function headers(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); } +function json(res, code, obj, extra) { res.writeHead(code, headers(Object.assign({ 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }, extra))); res.end(JSON.stringify(obj)); } +function sendFile(res, file, extra, code) { + fs.readFile(file, (err, data) => { + if (err) { res.writeHead(404, headers({ 'Content-Type': 'text/plain' })); return res.end('Not found'); } + const ext = path.extname(file).toLowerCase(); + res.writeHead(code || 200, headers(Object.assign({ 'Content-Type': MIME[ext] || 'application/octet-stream', 'Cache-Control': ext === '.html' ? 'no-store, must-revalidate' : 'public, max-age=3600' }, extra))); + res.end(data); + }); +} +function readRaw(req, max) { + return new Promise((resolve, reject) => { const ch = []; let n = 0; + req.on('data', c => { n += c.length; if (n > max * 8) { req.destroy(); return; } if (n <= max) ch.push(c); }); + req.on('end', () => n > max ? reject(new Error('too big')) : resolve(Buffer.concat(ch))); req.on('error', reject); }); +} +async function readBody(req) { const b = await readRaw(req, 32 * 1024); try { return b.length ? JSON.parse(b.toString('utf8')) : {}; } catch (e) { return {}; } } +function cookies(req) { const o = {}; for (const p of (req.headers.cookie || '').split(';')) { const i = p.indexOf('='); if (i > 0) { try { o[p.slice(0, i).trim()] = decodeURIComponent(p.slice(i + 1).trim()); } catch (e) {} } } return o; } +function cookie(name, val, maxAgeSec, httpOnly) { return name + '=' + encodeURIComponent(val) + '; Path=/; SameSite=Lax; Max-Age=' + maxAgeSec + (httpOnly ? '; HttpOnly' : '') + (C.isProd ? '; Secure' : ''); } +function ip(req) { + if (process.env.CF_PROXIED === '1' && req.headers['cf-connecting-ip']) return String(req.headers['cf-connecting-ip']).trim(); + const xff = String(req.headers['x-forwarded-for'] || '').split(',').map(s => s.trim()).filter(Boolean); + return (xff.length ? xff[xff.length - 1] : String(req.socket.remoteAddress || '')).replace(/^::ffff:/, ''); +} +const isBot = req => !req.headers['user-agent'] || BOT_UA.test(req.headers['user-agent']); +const buckets = new Map(); +function limited(req, name, max, windowMs) { + const k = name + ':' + ip(req); const t = Date.now(); let b = buckets.get(k); + if (!b || t - b.t > windowMs) { b = { t, n: 0 }; buckets.set(k, b); } + if (buckets.size > 100000) buckets.clear(); + return ++b.n > max; +} +const isAdmin = req => { const t = String(process.env.ADMIN_TOKEN || ''); const g = String(req.headers['x-admin-token'] || ''); + return t.length >= 8 && g.length === t.length && crypto.timingSafeEqual(Buffer.from(g), Buffer.from(t)); }; +function cleanText(s, max) { return String(s == null ? '' : s).replace(/<[^>]{0,200}>/g, '').replace(/[\u0000-\u0008\u000b-\u001f\u007f<>]/g, ' ').replace(/[\u2013\u2014]/g, '-').replace(/[ \t]+/g, ' ').trim().slice(0, max); } + +// ---- who is signed in: a wallet; the hub says who they are on the network ---- +async function linkHub(addr, email) { + const m = store.member(addr); if (!m) return; + if (m.hubId && m.netAt && Date.now() - m.netAt < 3600000) return; + let h = await hubpeople.byWallet(addr); + if (h.ok && !h.person && email) h = await hubpeople.resolve({ email: String(email).trim().toLowerCase() }).then(r => (r.ok ? { ok: true, person: r.person && !r.person.blocked ? r.person : null } : r)); + if (!h.ok) return; + const patch = { netAt: Date.now(), netOk: !!h.person }; + if (h.person) { patch.hubId = h.person.id || null; if (h.person.username && NAME_RE.test(h.person.username)) { const o = store.memberByName(h.person.username); if (!o || o.address === m.address) patch.username = String(h.person.username); } } + store.upsertMember(addr, patch); +} +const session = req => store.session(cookies(req)['fx.sid']); +networksso.init({ self: C.siteId, peer: 'iap', peerBase: () => C.iapBase, from: { iap: () => C.iapBase, linkspin: () => C.lsBase }, + isProd: C.isProd, dataDir: C.dataDir, defaultPath: '/team', + member: async req => { const s = session(req); return s ? { address: s.address } : null; }, + accept: async (email, req, v) => (v && v.wallet ? { ok: true } : { fallback: 'no wallet in the token' }), + signIn: async (email, req, v) => { + const patch = { via: v.iss }; + if (v.name && NAME_RE.test(v.name)) { const other = store.memberByName(v.name); if (!other || other.address === v.wallet) patch.username = v.name; } + store.upsertMember(v.wallet, patch); + await linkHub(v.wallet, email).catch(() => {}); // the email is used for this one hub lookup and never stored + return cookie('fx.sid', store.mintSession(v.wallet), store.SESSION_TTL / 1000, true); + }, + landing: to => to, signinPath: to => to }); + +// ---- old site links (the YFW downline builder: /?, /splashpg.php?r=, /lcp.php?r=, /index.php?r=) -> the coach page ---- +let oldRefs = { at: 0, map: {} }; +function oldRefMap() { + if (Date.now() - oldRefs.at < 60000) return oldRefs.map; + let m = {}; try { m = JSON.parse(fs.readFileSync(path.join(C.dataDir, 'oldrefs.json'), 'utf8')) || {}; } catch (e) {} + oldRefs = { at: Date.now(), map: m }; return m; +} +function oldLink(u) { + const p = u.pathname; const bare = u.search.slice(1).split('&')[0]; + if (/^\/members(\/|$)/i.test(p)) return '/team'; + if (p === '/' || p === '/index.php') { if (!/^[A-Za-z0-9_.-]{2,40}$/.test(bare) && !u.searchParams.get('r')) return p === '/' ? null : '/'; } + else if (!/\.php$/i.test(p)) return null; + const lp = p.toLowerCase(); + const old = (lp === '/splashpg.php' || lp === '/lcp.php' || u.searchParams.get('r')) ? String(u.searchParams.get('r') || '') : bare; + const net = /^[A-Za-z0-9_.-]{2,40}$/.test(old) ? oldRefMap()[old.toLowerCase()] : null; + return net ? '/' + encodeURIComponent(net) : '/'; +} + +const PAGES = { '/': 'index.html', '/team': 'team.html', '/cards': 'cards.html', '/join': 'join.html', '/ledger': 'ledger.html', '/contract': 'contract.html', '/admin': 'admin.html', + '/terms': 'terms.html', '/disclaimer': 'disclaimer.html', '/privacy': 'privacy.html', '/builder': 'builder.html' }; +const RESERVED = new Set(['api', 'assets', 'art', 'go', 'r', 'sso', 'health', 'promote', 'sitemap.xml', 'robots.txt', 'favicon.ico', 'index.php', 'team', 'cards', 'join', 'ledger', 'contract', 'admin', 'terms', 'disclaimer', 'privacy', 'builder', 'members', 'draft', 'board']); +const challenges = new Map(); +const joinUrl = ref => ref ? C.joinUrl.split('{ref}').join(encodeURIComponent(ref)) : C.joinUrl.replace(/\/join\/\{ref\}.*$/, '/').replace(/[?&]ref=\{ref\}/, '').split('{ref}').join(''); +const short = a => a ? a.slice(0, 6) + '...' + a.slice(-4) : ''; +const display = a => { const m = store.member(a); return m && m.username ? m.username : short(a); }; +const isCoach = a => store.positionsOf(a) > 0; + +// ---- payload builders ---- +// a scouting card for a person in the pool. Earnings (game POL, surf POL) only for coaches; anyone sees the public facts. +function scoutCard(c, full) { + const out = { id: c.id, username: c.username || null, door: c.door || null, lastSeen: c.lastSeen || 0, joinedAt: c.joinedAt || 0, wallet: !!c.wallet, score: c.score || 0, + hot: (c.score || 0) >= 60, plays: c.games ? Number(c.games.plays) || 0 : null, game: c.games ? c.games.title || null : null }; + if (full) { out.gameWei = c.games ? c.games.earnedWei || null : null; out.surfWei = c.surfWei || null; } + return out; +} +function pickView(p, t) { + const m = p.m || {}; + return { id: p.id, person: p.person, username: p.personName || m.username || null, week: p.week, kind: p.kind, slot: p.slot || null, round: p.round || null, status: p.status, + at: p.at, expires: p.expires, daysLeft: p.status === 'open' ? Math.max(0, Math.ceil((p.expires - t) / DAY)) : null, tier: p.tier || draft.tierOf(m), tierName: draft.TIER_NAME[p.tier || draft.tierOf(m)], + door: p.door || m.door || null, lastSeen: m.lastSeen || 0, steps: draft.steps(m), plays: m.games ? Number(m.games.plays) || 0 : null, game: m.games ? m.games.title || null : null, + gameWei: m.games ? m.games.earnedWei || null : null, surfWei: m.surfWei || null, unread: store.msgsOfPick(p.id).filter(x => x.dir === 'in' && !x.read).length }; +} +// a trading card: milestones only, never earnings (public) +function cardView(p) { + const m = p.m || {}; const t = p.tier || draft.tierOf(m); + const line = { rookie: 'Drafted', starter: 'Wallet linked', pro: 'Payouts switched on', allstar: 'First purchase', hof: 'Built a team of their own' }[t]; + return { id: p.id, username: p.personName || m.username || null, coach: p.coachName || display(p.coach), round: p.round || null, kind: p.kind, week: p.week, tier: t, tierName: draft.TIER_NAME[t], milestone: line, + plays: m.games ? Number(m.games.plays) || 0 : null, status: p.status }; +} +function weekStats(t) { + const w = league.weekInfo(t != null ? t : now()); + const P = store.purchases().filter(x => { const at = (x.blockAt ? x.blockAt * 1000 : x.at) || 0; return at >= w.from && at < w.to; }); + return { positions: P.reduce((n, x) => n + (Number(x.qty) || 1), 0), coaches: store.coaches().length, started: draft.bestCoach(store.picks(), w.from, w.to).reduce((n, x) => n + x.started, 0), potWei: proof.potOf(w.from, w.to) }; +} +async function board(me) { + const t = now(); const w = league.weekInfo(t); const d = store.draft(w.week); + const coach = me && isCoach(me); + const pl = await league.pool(t); + const cur = d ? draft.current(d) : null; + const room = d && d.status === 'live' ? d.slots.slice(d.made.length, d.made.length + 6).map(s => ({ slot: draft.slotLabel(s), coach: display(s.coach), me: s.coach === me })) : []; + const made = d ? d.made.slice(-30).reverse().map(x => { const p = x.pickId ? store.pick(x.pickId) : null; return { slot: x.slot, coach: display(x.coach), person: p ? p.personName : null, tier: p ? p.tier : null, tierName: p ? draft.TIER_NAME[p.tier] : null, auto: !!x.auto, skipped: x.skipped || null, me: x.coach === me }; }) : []; + const best = draft.bestCoach(store.picks(), w.from, w.to, display).slice(0, 10); + const pot = proof.potOf(w.from, w.to); + const rk = draft.rookie(store.picks(), w.week); + const prev = league.weekInfo(t - 7 * DAY); + const lastBest = draft.bestCoach(store.picks(), prev.from, prev.to, display).slice(0, 3); + const out = { week: w.week, now: t, draftAt: w.draftAt, nextDraftAt: w.nextDraftAt, draftDay: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'][C.draft.dow], draftHour: C.draft.hour, rounds: C.draft.rounds, + draft: d ? { status: d.status, coaches: d.order.length, poolSize: d.poolSize, made: d.made.filter(x => x.person).length, slots: d.slots.length, + onClock: cur ? { slot: draft.slotLabel(cur), round: cur.round, n: cur.n, coach: display(cur.coach), me: cur.coach === me, until: d.clockAt + C.draft.pickSeconds * 1000 } : null, room, rows: made, doneAt: d.doneAt || null } : null, + pool: pl.slice(0, 24).map(c => scoutCard(c, coach)), poolSize: pl.length, pot: { wei: pot, week: w.week, split: C.pot.split }, + best: best.map(x => ({ rank: x.rank, coach: x.username, started: x.started, me: x.coach === me })), lastWeekBest: lastBest.map(x => ({ rank: x.rank, coach: x.username, started: x.started })), + rookie: rk ? cardView(rk.pick) : null, coaches: store.coaches().length, seconds: C.draft.pickSeconds }; + if (me) { + const m = store.member(me); + out.me = { coach, credits: store.credits(me), open: league.openCount(me), maxOpen: C.picks.maxOpen, queue: (m && m.queue) || [], username: m ? m.username : null }; + if (coach) { const st = draft.standings(store.coaches().map(x => ({ address: x.address, username: x.username, since: store.firstPositionAt(x.address) })), store.picks(), w.nextWeek, w.week); + out.me.nextSpot = st.findIndex(x => x.address === me) + 1; out.me.startedThisWeek = (best.find(x => x.coach === m.username) || {}).started || 0; } + } + return out; +} +// the person signed in may be someone's pick (their hub id): their coach and the thread +function myCoach(m) { + if (!m || !m.hubId) return null; + const p = store.picksOfPerson(m.hubId).filter(x => ['open', 'done', 'kept'].includes(x.status)).sort((a, b) => b.at - a.at)[0]; if (!p) return null; + return { pickId: p.id, coach: display(p.coach), since: p.at, tier: p.tier, tierName: draft.TIER_NAME[p.tier], steps: draft.steps(p.m), + messages: store.msgsOfPick(p.id).map(x => ({ id: x.id, dir: x.dir === 'out' ? 'in' : 'out', text: x.text, at: x.at })), builder: builderFor(p.coach) }; +} +// the CryptoTeamBuild builder: the coach's links (else the owner's, else the program default, else its home page) +const programs = () => (store.state().programs || []); +function builderFor(addr) { + const owner = store.memberByName(C.owner); + const idOf = (person, pid) => store.refidOf(person.address, pid); + const chain = addr ? [{ address: addr, username: display(addr), depth: 1 }] : []; + return wild.visible(programs()).map(p => { const l = wild.sponsorLink(p, chain, idOf, owner ? { address: owner.address, username: owner.username } : null); + return { id: p.id, name: p.name, cat: p.cat, url: l.url, by: l.by, fallback: l.fallback }; }); +} + +const server = http.createServer(async (req, res) => { + const u = new URL(req.url, 'http://x'); const p = u.pathname; + { const host = String(req.headers.host || '').toLowerCase().split(':')[0]; + if (C.isProd && host !== C.site && host.endsWith('.' + C.site)) { res.writeHead(301, { Location: 'https://' + C.site + req.url, 'Cache-Control': 'no-store' }); return res.end(); } } + try { + if (req.method === 'GET' && (p.startsWith('/sso/') || p === '/api/sso/status') && await networksso.handle(req, res, u)) return; + if ((p === '/api/promo-kit' || p === '/promote') && promokit.handle(req, res, u, sendFile)) return; + + if (req.method === 'GET' || req.method === 'HEAD') { + if (p === '/health') return json(res, 200, { ok: true, store: docstore.isOn() ? 'mysql' : 'files', tank: C.tankMode }); + { const to = oldLink(u); if (to) { res.writeHead(301, { Location: to, 'Cache-Control': 'no-store' }); return res.end(); } } + if (PAGES[p]) { + const ex = {}; const ref = u.searchParams.get('ref'); + if (ref && (NAME_RE.test(ref) || ADDR_RE.test(ref))) ex['Set-Cookie'] = cookie('fx.ref', ref, 30 * 86400, false); + if (p === '/team' || p === '/admin') ex['X-Frame-Options'] = 'DENY'; + return sendFile(res, path.join(PUB, PAGES[p]), ex); + } + if (/^\/r\/[^/]+$/.test(p)) { res.writeHead(302, { Location: '/' + encodeURIComponent(decodeURIComponent(p.slice(3))) }); return res.end(); } + if (p === '/sitemap.xml') { + const day = new Date().toISOString().slice(0, 10); + const urls = ['/', '/join', '/cards', '/ledger', '/contract', '/promote', '/terms', '/disclaimer', '/privacy'].map(x => 'https://' + C.site + x + '' + day + '').join(''); + res.writeHead(200, headers({ 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })); + return res.end('' + urls + ''); + } + if (p === '/robots.txt') { res.writeHead(200, headers({ 'Content-Type': 'text/plain; charset=utf-8' })); return res.end('User-agent: *\nAllow: /\nDisallow: /team\nDisallow: /admin\nDisallow: /api/\nDisallow: /sso/\n\nSitemap: https://' + C.site + '/sitemap.xml\n'); } + if (p.startsWith('/assets/') || p.startsWith('/art/') || p === '/favicon.ico') { + const f = path.normalize(path.join(PUB, p === '/favicon.ico' ? '/art/icon-192.png' : p)); if (!f.startsWith(PUB + path.sep)) { res.writeHead(400); return res.end(); } + return sendFile(res, f); + } + // the Draft Day results card (1080 x 1080, rendered to PNG by tools/art.mjs for Telegram) + const dd = /^\/draftday\/(\d{4}-\d{2}-\d{2})$/.exec(p); + if (dd) return sendFile(res, path.join(PUB, 'draftday.html')); + // a coach page: 5xyourteam.com/ + const pm = PAGE_RE.exec(p); + if (pm && !RESERVED.has(pm[1].toLowerCase()) && !/\.php$/i.test(pm[1])) { + const m = store.memberByName(pm[1]); + if (m) return sendFile(res, path.join(PUB, 'coach.html'), { 'Set-Cookie': cookie('fx.ref', m.username, 30 * 86400, false) }); + } + } + + // -- public API + if (p === '/api/config' && req.method === 'GET') { + return json(res, 200, { site: C.site, siteName: C.siteName, chainId: C.chainId, chainName: C.chainName, rpc: C.publicRpc, walletConnectProjectId: C.walletConnectProjectId, + position: C.position, split: C.split, draft: { dow: C.draft.dow, hour: C.draft.hour, rounds: C.draft.rounds, pickSeconds: C.draft.pickSeconds }, picks: { returnDays: C.picks.returnDays, maxOpen: C.picks.maxOpen, holdHours: C.picks.holdHours }, + pot: C.pot, sso: networksso.enabled(), shop: { live: shop.watching(), contract: shop.watching() ? C.contractAddress : null }, explorer: C.explorer, tank: C.tankMode, joinUrl: joinUrl('') }); + } + if (p === '/api/board' && req.method === 'GET') { const s = session(req); return json(res, 200, await board(s ? s.address : null)); } + if (p === '/api/draftday' && req.method === 'GET') { + const wk = String(u.searchParams.get('week') || ''); const d = store.draft(wk); if (!d) return json(res, 404, { error: 'No draft that week.' }); + const rows = d.made.filter(x => x.person).map(x => ({ slot: x.slot, coach: display(x.coach), person: (store.pick(x.pickId) || {}).personName || null })); + const w = league.weekInfo(store.ctToMs(wk, 12)); + return json(res, 200, { week: wk, rows, players: rows.length, coaches: d.order.length, potWei: proof.potOf(w.from, w.to) }); + } + if (p === '/api/coach' && req.method === 'GET') { + const m = store.memberByName(String(u.searchParams.get('u') || '')); if (!m || !isCoach(m.address)) return json(res, 404, { error: 'No coach by that name.' }); + const mine = store.picksOf(m.address).filter(x => x.status !== 'void' && x.status !== 'returned'); + return json(res, 200, { username: m.username, since: store.firstPositionAt(m.address), positions: store.positionsOf(m.address), team: mine.map(cardView), + started: mine.filter(x => draft.started(x.m)).length, joinUrl: joinUrl(m.username) }); + } + if (p === '/api/ledger' && req.method === 'GET') return json(res, 200, proof.ledger(u.searchParams.get('n')), { 'Cache-Control': 'public, max-age=10' }); + if (p === '/api/contract' && req.method === 'GET') { if (limited(req, 'contract', 600, 3600000)) return json(res, 429, { error: 'Too many requests' }); return json(res, 200, await proof.contract(), { 'Cache-Control': 'public, max-age=60' }); } + if (p === '/api/network-sites' && req.method === 'GET') return netsites.handle(req, res); + // toasts: real events of the last 30 minutes (new coaches, picks, picks that levelled up) + if (p === '/api/recent' && req.method === 'GET') { + const t = now(); const cut = t - 30 * 60000; + const buys = proof.ledger(10).items.filter(x => x.at && x.at > cut).map(x => ({ kind: 'position', key: 'b' + x.tx + x.orderId, at: x.at, name: x.buyerName })); + const picks = store.picks().filter(x => x.at > cut).slice(-6).map(x => ({ kind: 'pick', key: 'p' + x.id, at: x.at, name: x.coachName, person: x.personName, slot: x.slot || null })); + const ups = store.picks().filter(x => x.levelAt > cut && x.tier && x.tier !== 'rookie').slice(-6).map(x => ({ kind: 'level', key: 'l' + x.id + x.tier, at: x.levelAt, name: x.coachName, person: x.personName, tierName: draft.TIER_NAME[x.tier] })); + return json(res, 200, { items: buys.concat(picks, ups).sort((a, b) => b.at - a.at) }, { 'Cache-Control': 'public, max-age=10' }); + } + if (p === '/api/quote' && req.method === 'GET') { + if (!shop.watching()) return json(res, 503, { error: 'Positions are not open yet.' }); + if (limited(req, 'quote', 600, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' }); + const qty = Number(u.searchParams.get('qty') || 1); + if (!Number.isInteger(qty) || qty < 1 || qty > C.position.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.position.maxQty + ' positions.' }); + try { return json(res, 200, Object.assign({ usd: C.position.usd * qty, picks: C.position.picksOnBuy * qty }, await shop.quote(qty))); } catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); } + } + if (p === '/api/gas' && req.method === 'GET') { try { return json(res, 200, shop.watching() ? await shop.fees() : {}); } catch (e) { return json(res, 200, {}); } } + if (/^\/api\/tx\/0x[0-9a-fA-F]{64}$/.test(p) && req.method === 'GET') { + if (!shop.watching() || limited(req, 'tx', 1200, 3600000)) return json(res, 200, { found: false }); + try { return json(res, 200, await shop.receipt(p.slice(8))); } catch (e) { return json(res, 200, { found: false }); } + } + + // wallet sign-in + if (p === '/api/auth/challenge' && req.method === 'POST') { + if (limited(req, 'auth', 30, 600000)) return json(res, 429, { error: 'Too many sign-in attempts. Wait a few minutes.' }); + const b = await readBody(req); if (!ADDR_RE.test(b.address || '')) return json(res, 400, { error: 'Bad address' }); + const a = b.address.toLowerCase(); const nonce = crypto.randomBytes(16).toString('hex'); + const message = C.site + ' wants you to sign in with your wallet:\n' + getAddress(a) + '\n\n5xYourTeam sign-in. This signature is free and cannot move funds or approve anything.\n\nChain ID: ' + C.chainId + '\nNonce: ' + nonce + '\nIssued At: ' + new Date().toISOString(); + challenges.set(a, { message, exp: Date.now() + 600000 }); if (challenges.size > 20000) challenges.clear(); + return json(res, 200, { message }); + } + if (p === '/api/auth/verify' && req.method === 'POST') { + const b = await readBody(req); const a = String(b.address || '').toLowerCase(); const ch = challenges.get(a); + if (!ch || ch.exp < Date.now()) return json(res, 400, { error: 'Sign-in request expired. Tap sign in again.' }); + let rec; try { rec = verifyMessage(ch.message, String(b.signature || '')).toLowerCase(); } catch (e) { return json(res, 400, { error: 'Invalid signature.' }); } + if (rec !== a) return json(res, 400, { error: 'Your wallet signed with a different account (' + rec.slice(0, 6) + '...' + rec.slice(-4) + '). Switch accounts and try again.' }); + challenges.delete(a); + store.upsertMember(a, store.member(a) ? {} : { via: 'wallet' }); + await linkHub(a).catch(() => {}); + return json(res, 200, { ok: true, address: a }, { 'Set-Cookie': cookie('fx.sid', store.mintSession(a), store.SESSION_TTL / 1000, true) }); + } + if (p === '/api/auth/logout' && req.method === 'POST') { + const s = session(req); if (s) store.dropSession(s.token); + return json(res, 200, { ok: true }, { 'Set-Cookie': [cookie('fx.sid', '', 0, true), networksso.offCookie()] }); + } + if (p === '/api/me' && req.method === 'GET') { + const s = session(req); if (!s) return json(res, 200, { signedIn: false }); + const m = store.member(s.address); + return json(res, 200, { signedIn: true, address: s.address, username: m ? m.username : null, coach: isCoach(s.address), onNetwork: !!(m && m.hubId) }); + } + + // -- member API + if (p.startsWith('/api/my') || p === '/api/presence' || p === '/api/draft/pick') { + const s = session(req); if (!s) return json(res, 401, { error: 'Sign in first.' }); + const me = s.address; if (!store.member(me)) store.upsertMember(me, { via: 'wallet' }); + const m = store.member(me); + if (p === '/api/presence' && req.method === 'POST') { m.presenceAt = now(); store.save(); return json(res, 200, { ok: true }); } + if (p === '/api/draft/pick' && req.method === 'POST') { + const b = await readBody(req); if (!HUBID_RE.test(String(b.person || ''))) return json(res, 400, { error: 'Pick a player.' }); + m.presenceAt = now(); return json(res, 200, await league.manualPick(me, String(b.person))); + } + if (p === '/api/my' && req.method === 'GET') { + await linkHub(me).catch(() => {}); + const t = now(); const mine = store.picksOf(me).filter(x => x.status !== 'void'); + const open = mine.filter(x => x.status === 'open'); + const w = league.weekInfo(t); + const bd = await board(me); + return json(res, 200, { address: me, username: m.username, onNetwork: !!m.hubId, coach: isCoach(me), positions: store.positionsOf(me), credits: store.credits(me), + stats: { onTeam: mine.filter(x => ['open', 'done', 'kept'].includes(x.status)).length, startedThisWeek: mine.filter(x => { const a = draft.startedAt(x.m); return a >= w.from && a < w.to; }).length, + nextSpot: bd.me && bd.me.nextSpot ? bd.me.nextSpot : null, backSoon: open.filter(x => x.expires - t < DAY).length, open: open.length, maxOpen: C.picks.maxOpen }, + picks: mine.sort((a, b) => (a.status === 'open' ? 0 : 1) - (b.status === 'open' ? 0 : 1) || b.at - a.at).map(x => pickView(x, t)), help: draft.helpList(mine, t), + queue: m.queue || [], myCoach: myCoach(m), page: m.username && isCoach(me) ? 'https://' + C.site + '/' + encodeURIComponent(m.username) : null, joinUrl: joinUrl('') }); + } + if (p === '/api/my/instant' && req.method === 'POST') { + const b = await readBody(req); if (!HUBID_RE.test(String(b.person || ''))) return json(res, 400, { error: 'Pick a player.' }); + if (!isCoach(me)) return json(res, 403, { error: 'Get a position first: it comes with ' + C.position.picksOnBuy + ' picks right away.' }); + return json(res, 200, await league.instantPick(me, String(b.person))); + } + if (p === '/api/my/queue' && req.method === 'POST') { + const b = await readBody(req); const ids = (Array.isArray(b.ids) ? b.ids : []).map(String).filter(x => HUBID_RE.test(x)).slice(0, 30); + m.queue = [...new Set(ids)]; store.save(); return json(res, 200, { ok: true, queue: m.queue }); + } + if (p === '/api/my/release' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, await league.release(me, Number(b.pick))); } + // messages: a coach writes to their own pick; a pick replies to their coach. Through the site only, no contact data. + if (p === '/api/my/messages' && req.method === 'GET') { + const pk = store.pick(Number(u.searchParams.get('pick'))); if (!pk) return json(res, 404, { error: 'Not found' }); + const asCoach = pk.coach === me, asPick = m.hubId && pk.person === m.hubId; if (!asCoach && !asPick) return json(res, 403, { error: 'Not your thread.' }); + const list = store.msgsOfPick(pk.id); let changed = false; + for (const x of list) if (!x.read && ((asCoach && x.dir === 'in') || (asPick && x.dir === 'out'))) { x.read = now(); store.saveMsg(x); changed = true; } + return json(res, 200, { pick: pk.id, with: asCoach ? pk.personName : display(pk.coach), items: list.map(x => ({ id: x.id, mine: asCoach ? x.dir === 'out' : x.dir === 'in', text: x.text, at: x.at })), changed }); + } + if (p === '/api/my/message' && req.method === 'POST') { + if (limited(req, 'msg', 60, 3600000)) return json(res, 429, { error: 'That is a lot of messages this hour. Give them a little time to answer.' }); + const b = await readBody(req); const pk = store.pick(Number(b.pick)); if (!pk) return json(res, 404, { error: 'Not found' }); + const asCoach = pk.coach === me, asPick = m.hubId && pk.person === m.hubId; if (!asCoach && !asPick) return json(res, 403, { error: 'You can message your own picks and your own coach.' }); + if (!['open', 'done', 'kept'].includes(pk.status)) return json(res, 400, { error: 'They are back in the pool, so this thread is closed.' }); + const text = cleanText(b.text, 600); if (text.length < 2) return json(res, 400, { error: 'Write a message first.' }); + const x = store.addMsg({ pick: pk.id, dir: asCoach ? 'out' : 'in', from: me, text, at: now(), read: 0, deliveredVia: 'site' }); + return json(res, 200, { ok: true, id: x.id }); + } + // builder: my referral ID for one CryptoTeamBuild program + if (p === '/api/my/builder' && req.method === 'GET') return json(res, 200, { programs: wild.visible(programs()).map(pr => ({ id: pr.id, name: pr.name, cat: pr.cat, myId: store.refidOf(me, pr.id), example: wild.fillUrl(pr, 'YOURID') })) }); + if (p === '/api/my/builder' && req.method === 'POST') { + const b = await readBody(req); const pr = programs().find(x => x.id === String(b.program || '')); + if (!pr || pr.hidden || pr.network) return json(res, 404, { error: 'That program is not in the builder.' }); + const id = wild.cleanId(pr, b.refId); if (id === null) return json(res, 400, { error: 'That does not look like a referral ID for ' + pr.name + '.' }); + store.setRefid(me, pr.id, id); return json(res, 200, { ok: true, refId: id, link: id ? wild.fillUrl(pr, id) : null }); + } + // a position: the buy() call for the member's own wallet, with a fresh line voucher when the line is not bound on chain yet + if (p === '/api/my/order' && req.method === 'POST') { + if (!shop.watching()) return json(res, 503, { error: 'Positions are not open yet.' }); + if (limited(req, 'order', 60, 3600000)) return json(res, 429, { error: 'Too many requests this hour.' }); + const b = await readBody(req); const qty = Number(b.qty || 1); + if (!Number.isInteger(qty) || qty < 1 || qty > C.position.maxQty) return json(res, 400, { error: 'Pick 1 to ' + C.position.maxQty + ' positions.' }); + let v = null, why = null; const bound = await shop.boundSponsor(me); + if (bound) why = 'bound'; + else if (bound === undefined) return json(res, 503, { error: 'The chain did not answer just now. Try again in a minute.' }); + else if (!shop.voucherOn()) why = 'off'; + else { + const lo = await hubline.lineOf({ wallet: me }, shop.MAX_LINE); + if (!lo.ok) return json(res, 503, { error: 'Your sponsor line could not be checked with the network just now. Try again in a minute, so your team gets paid.' }); + const wallets = lo.line.filter(x => x.wallet && x.wallet !== me).map(x => x.wallet); + if (!wallets.length) why = 'no-line'; else v = await shop.voucher(me, wallets); + } + const hubRef = m.hubId ? BigInt('0x' + crypto.createHash('sha256').update(m.hubId).digest('hex').slice(0, 15)) : 0n; // ref = a short hash of the hub id (free data) + try { return json(res, 200, Object.assign({ buyer: me, usd: C.position.usd * qty, picks: C.position.picksOnBuy * qty, qty, why }, await shop.order(me, qty, hubRef, v))); } + catch (e) { return json(res, 503, { error: 'Price unavailable right now. Try again in a minute.' }); } + } + if (p === '/api/my/paid' && req.method === 'POST') { shop.nudge(); return json(res, 200, { ok: true, confirmations: C.shopConfirmations }); } + return json(res, 404, { error: 'Not found' }); + } + + // -- admin (x-admin-token: ADMIN_TOKEN) + if (p.startsWith('/api/admin/')) { + if (!isAdmin(req)) return json(res, 401, { error: 'no' }); + if (p === '/api/admin/status' && req.method === 'GET') { + const t = now(); const w = league.weekInfo(t); const d = store.draft(w.week); + return json(res, 200, { day: store.ctDay(t), week: w.week, now: t, draftAt: w.draftAt, config: { position: C.position, split: C.split, draft: C.draft, picks: C.picks, pot: C.pot, tankMode: C.tankMode }, + members: store.members().length, coaches: store.coaches().length, picks: { all: store.picks().length, open: store.picks().filter(x => x.status === 'open').length, done: store.picks().filter(x => x.status === 'done').length, returned: store.picks().filter(x => x.status === 'returned').length, kept: store.picks().filter(x => x.status === 'kept').length }, + draft: d ? { status: d.status, made: d.made.length, slots: d.slots.length, why: d.why || null } : null, pot: { weekWei: proof.potOf(w.from, w.to), best: draft.bestCoach(store.picks(), w.from, w.to, display).slice(0, 5) }, + shop: shop.view(), proof: proof.view(), hub: hubreport.view(), hubLookup: hubpeople.view(), tank: tank.view(), docstore: docstore.view(), oldrefs: Object.keys(oldRefMap()).length, testClock: C.testClock }); + } + if (p === '/api/admin/tick' && req.method === 'POST') return json(res, 200, await league.tick()); + if (p === '/api/admin/clock' && req.method === 'POST') { + if (!C.testClock) return json(res, 403, { error: 'test clock off' }); + const b = await readBody(req); if (!Number.isFinite(Number(b.now))) return json(res, 400, { error: 'now (ms) required' }); + league.clock.set(Number(b.now)); return json(res, 200, { ok: true, now: now() }); + } + if (p === '/api/admin/stub/status' && req.method === 'POST') { const b = await readBody(req); return json(res, 200, tank.setStatus(String(b.id || ''), b)); } + // the week's Best Coach shares (the pot wallet's holder pays them; Marty decides the rule) and recording a payout tx + if (p === '/api/admin/pot' && req.method === 'GET') { + const wk = String(u.searchParams.get('week') || league.weekInfo(now() - 7 * DAY).week); const w = league.weekInfo(store.ctToMs(wk, 12)); + const bd = draft.bestCoach(store.picks(), w.from, w.to, display); const pot = proof.potOf(w.from, w.to); + return json(res, 200, { week: wk, potWei: pot, split: C.pot.split, shares: draft.potShares(pot, C.pot.split, bd), paid: (store.state().payouts || {})[wk] || [] }); + } + if (p === '/api/admin/pot/paid' && req.method === 'POST') { + const b = await readBody(req); if (!/^\d{4}-\d{2}-\d{2}$/.test(String(b.week || '')) || !/^0x[0-9a-fA-F]{64}$/.test(String(b.tx || '')) || !ADDR_RE.test(String(b.coach || ''))) return json(res, 400, { error: 'week, coach, tx required' }); + const S = store.state(); const l = S.payouts[b.week] || (S.payouts[b.week] = []); + const row = { rank: Number(b.rank) || l.length + 1, coach: String(b.coach).toLowerCase(), username: display(String(b.coach).toLowerCase()), wei: String(BigInt(b.wei || 0)), tx: String(b.tx).toLowerCase(), at: Date.now() }; + l.push(row); store.save(); proof.payoutLine(b.week, row).catch(() => {}); return json(res, 200, { ok: true, row }); + } + if (p === '/api/admin/oldrefs' && req.method === 'POST') { + let b; try { b = JSON.parse((await readRaw(req, 4 * 1024 * 1024)).toString('utf8')); } catch (e) { return json(res, 400, { error: 'bad json' }); } + if (!b || !b.oldrefs || typeof b.oldrefs !== 'object') return json(res, 400, { error: 'oldrefs object required' }); + const o = {}; for (const [k, v] of Object.entries(b.oldrefs)) if (/^[a-z0-9_.-]{2,40}$/.test(k) && NAME_RE.test(String(v))) o[k] = String(v); + fs.writeFileSync(path.join(C.dataDir, 'oldrefs.json'), JSON.stringify(o)); oldRefs = { at: 0, map: {} }; + return json(res, 200, { ok: true, total: Object.keys(o).length, skipped: Object.keys(b.oldrefs).length - Object.keys(o).length }); + } + return json(res, 404, { error: 'Not found' }); + } + + if (p.startsWith('/api/')) return json(res, 404, { error: 'Not found' }); + res.writeHead(404, headers({ 'Content-Type': 'text/html; charset=utf-8' })); + return res.end('Not found | 5xYourTeam

Not found.

Back to the draft board

'); + } catch (e) { + console.error('request', p, e.message); + if (!res.headersSent) json(res, 500, { error: 'Server error' }); + } +}); + +(async () => { + await docstore.init({ splits: store.SPLITS }); + process.on('SIGTERM', () => { store.flush(); docstore.drain(8000).finally(() => process.exit(0)); }); + store.load(); + if (!store.state().programs) { try { store.state().programs = JSON.parse(fs.readFileSync(path.join(__dirname, 'data-seed', 'programs.seed.json'), 'utf8')).programs; store.save(); } catch (e) { store.state().programs = []; } } + tank.init(C, { now }); + proof.init(C, { shop, weekStats, nameOf: async a => { const h = await hubpeople.byWallet(a).catch(() => ({ ok: false })); return h.ok && h.person && h.person.username ? h.person.username : null; } }); + league.init(C, { proof }); + hubreport.init({ dataDir: C.dataDir, purchases: () => store.purchases().map(x => ({ key: x.key, buyer: x.buyer, sponsor: x.sponsor || null, usdCents: x.usdCents, block: x.block, at: x.at })) }); + shop.setAttach(rec => { store.addCredits(rec.buyer, C.position.picksOnBuy * (Number(rec.qty) || 1)); store.bump('positions', Number(rec.qty) || 1); }); + shop.setHook(proof.onPurchase); + shop.init(C); + const loop = () => league.tick().catch(e => console.error('league tick', e.message)).finally(() => setTimeout(loop, C.draft.tickMs).unref()); + setTimeout(loop, 300).unref(); + server.listen(C.port, () => console.log('5xYourTeam on :' + C.port + ', position $' + C.position.usd + ', tank ' + C.tankMode + ', store: ' + (docstore.isOn() ? 'MySQL documents' : 'files (prototype mode)'))); +})().catch(e => { console.error('start failed:', e.message); process.exit(1); }); +process.on('SIGINT', () => { store.flush(); process.exit(0); }); diff --git a/shop.js b/shop.js new file mode 100644 index 0000000..37a3956 --- /dev/null +++ b/shop.js @@ -0,0 +1,172 @@ +// On-chain positions (DraftPosition, ../contracts). Each job is inert until it is configured: +// (a) line vouchers: KEEPER_KEY (the keeper the contract trusts) signs EIP-712 Voucher(buyer, address[] line, deadline), line = +// the buyer's network sponsor line from the hub (wallets, nearest first, up to 20). On the buyer's first position the contract +// binds every unbound link along it; a bound link never changes (the contract's binding wins, Marty 2026-11-14). +// (b) chain watcher: with CONTRACT_ADDRESS + CHAIN_RPC it polls Purchase logs (confirmed blocks only) and records each position purchase once +// per txHash:logIndex (the dedupe mark and the purchase live in the same document, so they save together). +// (c) buying: quote() reads quoteWei, order() builds the member's buy() call, receipt() / fees() back the page's wait. +// The key never enters config or any API answer. +'use strict'; +const { Wallet, Interface, getAddress } = require('ethers'); +const store = require('./store'); + +const ADDR_RE = /^0x[0-9a-fA-F]{40}$/; +const ZERO = '0x0000000000000000000000000000000000000000'; +const IFACE = new Interface(['event Purchase(uint256 indexed orderId, address indexed buyer, uint256 qty, uint256 ref, uint256 usdCents, uint256 weiPaid, uint256 levelsPaid, uint256 prizePaid, uint256 companyPaid)', + 'event Paid(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', + 'event PaymentFailed(uint256 indexed orderId, address indexed to, uint256 amount, uint8 level, uint8 depth)', + 'event PassedOver(uint256 indexed orderId, address indexed who, uint8 depth)', + 'event SponsorBound(address indexed member, address indexed sponsor)']); +const TOPIC = IFACE.getEvent('Purchase').topicHash; +const T = { paid: IFACE.getEvent('Paid').topicHash, fail: IFACE.getEvent('PaymentFailed').topicHash, over: IFACE.getEvent('PassedOver').topicHash, bound: IFACE.getEvent('SponsorBound').topicHash }; +const CALLS = new Interface(['function quoteWei(uint256 qty) view returns (uint256)', + 'function buy(uint256 qty, uint256 ref, address[] line, uint256 deadline, bytes sig) payable returns (uint256 orderId)', + 'function sponsorOf(address) view returns (address)', 'function positionsHeld(address) view returns (uint256)', + 'function payeesOf(address buyer) view returns (address[] to, uint8[] depth)', 'function priceCents() view returns (uint256)']); +const TYPES = { Voucher: [{ name: 'buyer', type: 'address' }, { name: 'line', type: 'address[]' }, { name: 'deadline', type: 'uint256' }] }; +const MAX_LINE = 20; +const st = { polls: 0, recorded: 0, dupes: 0, ignored: 0, errors: 0, lastError: null, head: null }; +let C = null, keeper = null, busy = false, timer = null; +const hooks = { onPurchase: null, attach: null }; +function setHook(fn) { hooks.onPurchase = typeof fn === 'function' ? fn : null; } +function setAttach(fn) { hooks.attach = typeof fn === 'function' ? fn : null; } + +function init(cfg) { + C = cfg; keeper = null; + const k = String(process.env.KEEPER_KEY || '').trim(); + if (k) { try { keeper = new Wallet(k.startsWith('0x') ? k : '0x' + k); } catch (e) { console.error('shop: KEEPER_KEY is not a valid private key; vouchers off'); } } + if (timer) { clearTimeout(timer); timer = null; } + if (watching()) { console.log('shop: watching', C.contractAddress, 'for positions'); tick(); } +} +const voucherOn = () => !!(C && keeper && C.contractAddress); +const watching = () => !!(C && C.contractAddress && C.chainRpc); +const domain = () => ({ name: 'DraftPosition', version: '1', chainId: C.chainId, verifyingContract: C.contractAddress }); + +// a voucher binding `line` (wallets, nearest first) above `buyer`, or null (off, empty, bad) +async function voucher(buyer, line) { + if (!voucherOn() || !ADDR_RE.test(buyer || '')) return null; + const b = getAddress(buyer); const seen = new Set([b.toLowerCase()]); const l = []; + for (const w of line || []) { if (!ADDR_RE.test(w || '') || seen.has(w.toLowerCase()) || w === ZERO) continue; seen.add(w.toLowerCase()); l.push(getAddress(w)); if (l.length >= MAX_LINE) break; } + if (!l.length) return null; + const deadline = Math.floor(Date.now() / 1000) + C.voucherSeconds; + const sig = await keeper.signTypedData(domain(), TYPES, { buyer: b, line: l, deadline }); + return { buyer: b, line: l, deadline, sig, contract: C.contractAddress, chainId: C.chainId }; +} + +// record one Purchase log. false = already recorded (or not ours). +function apply(ev) { + const S = store.state(); const P = S.purchases || (S.purchases = {}); + const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; + if (P[key]) { st.dupes++; return false; } + const a = ev.buyer.toLowerCase(); if (!store.member(a)) store.upsertMember(a, { via: 'wallet' }); + const rec = { at: Date.now(), blockAt: ev.blockAt || null, block: ev.block, orderId: ev.orderId, buyer: a, qty: ev.qty, ref: ev.ref, + usdCents: ev.usdCents, weiPaid: ev.weiPaid, levelsPaid: ev.levelsPaid, prizePaid: ev.prizePaid, companyPaid: ev.companyPaid, sponsor: ev.sponsor || null }; + if (hooks.attach) { try { hooks.attach(rec); } catch (e) {} } + P[key] = rec; store.save(); st.recorded++; + if (hooks.onPurchase) { try { hooks.onPurchase(rec, String(ev.txHash).toLowerCase()); } catch (e) {} } + console.log('shop: position order', ev.orderId, 'x' + ev.qty, a); + return true; +} +function decode(l) { + if (!l || l.removed || String(l.address || '').toLowerCase() !== C.contractAddress.toLowerCase() || (l.topics || [])[0] !== TOPIC) return null; + const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; + return { txHash: l.transactionHash, logIndex: parseInt(l.logIndex, 16), block: parseInt(l.blockNumber, 16), orderId: Number(d.orderId), buyer: d.buyer, + qty: Number(d.qty), ref: d.ref.toString(), usdCents: Number(d.usdCents), weiPaid: d.weiPaid.toString(), levelsPaid: Number(d.levelsPaid), prizePaid: d.prizePaid.toString(), companyPaid: d.companyPaid.toString() }; +} +// the split of one order from its receipt: level payouts (with their place in the line), the prize pot (level 6), the company, who was passed over and +// which links of the line this purchase bound. null if the RPC does not answer. +async function readSplit(tx, orderId) { + const r = await rpc('eth_getTransactionReceipt', [tx]); if (!r || !Array.isArray(r.logs)) return null; + const pays = [], over = [], bound = []; + for (const l of r.logs) { + if (String(l.address).toLowerCase() !== C.contractAddress.toLowerCase()) continue; + const t0 = l.topics[0]; + if (t0 === T.bound) { const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; bound.push({ member: d.member.toLowerCase(), sponsor: d.sponsor.toLowerCase() }); continue; } + if (t0 !== T.paid && t0 !== T.fail && t0 !== T.over) continue; + const d = IFACE.parseLog({ topics: l.topics, data: l.data }).args; if (Number(d.orderId) !== Number(orderId)) continue; + if (t0 === T.over) over.push({ who: d.who.toLowerCase(), depth: Number(d.depth) }); + else pays.push({ level: Number(d.level), depth: Number(d.depth), to: d.to.toLowerCase(), wei: d.amount.toString(), failed: t0 === T.fail || undefined }); + } + return { pays, over, bound }; +} + +async function rpc(method, params) { + const ac = new AbortController(); const t = setTimeout(() => ac.abort(), 10000); t.unref(); + try { const j = await (await fetch(C.chainRpc, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }), signal: ac.signal })).json(); + if (j.error) throw new Error(method + ': ' + (j.error.message || JSON.stringify(j.error))); return j.result; } finally { clearTimeout(t); } +} +async function poll() { + if (busy || !watching()) return; busy = true; st.polls++; + try { + const S = store.state(); const sh = S.shop || (S.shop = {}); + const head = parseInt(await rpc('eth_blockNumber', []), 16) - C.shopConfirmations; st.head = head; + if (sh.lastBlock == null) { sh.lastBlock = (C.shopStartBlock || head + 1) - 1; if (!C.shopStartBlock) console.log('shop: no SHOP_START_BLOCK, watching from block', head + 1); store.save(); } + while (sh.lastBlock < head) { + const from = sh.lastBlock + 1, to = Math.min(head, from + 999); + const logs = await rpc('eth_getLogs', [{ address: C.contractAddress, topics: [TOPIC], fromBlock: '0x' + from.toString(16), toBlock: '0x' + to.toString(16) }]); + for (const l of logs || []) { + const ev = decode(l); if (!ev) { st.ignored++; continue; } + const key = String(ev.txHash).toLowerCase() + ':' + ev.logIndex; if ((S.purchases || {})[key]) { st.dupes++; continue; } + ev.blockAt = await blockTime(ev.block); + try { ev.sponsor = String((await call('sponsorOf', [ev.buyer]))[0]).toLowerCase(); if (ev.sponsor === ZERO) ev.sponsor = null; } catch (e) {} + apply(ev); + } + sh.lastBlock = to; store.save(); + } + } catch (e) { st.errors++; st.lastError = String(e.message).slice(0, 200); } + finally { busy = false; } +} +const btCache = new Map(); +async function blockTime(n) { + if (btCache.has(n)) return btCache.get(n); + let t = null; try { const b = await rpc('eth_getBlockByNumber', ['0x' + n.toString(16), false]); t = b && b.timestamp ? parseInt(b.timestamp, 16) : null; } catch (e) {} + if (t) { btCache.set(n, t); if (btCache.size > 5000) btCache.clear(); } + return t; +} +function tick() { poll().finally(() => { if (watching()) { timer = setTimeout(tick, C.shopPollMs); timer.unref(); } }); } + +// ---- buying ---- +async function call(fn, args, to) { + const r = await rpc('eth_call', [{ to: to || C.contractAddress, data: CALLS.encodeFunctionData(fn, args || []) }, 'latest']); + return CALLS.decodeFunctionResult(fn, r); +} +const qCache = new Map(); +// POL wei for qty positions now; sendWei adds 1% for price drift (the contract refunds anything above the price in the same tx) +async function quote(qty) { + const k = 'x' + qty; const hit = qCache.get(k); if (hit && Date.now() - hit.at < 15000) return hit.v; + const wei = (await call('quoteWei', [qty]))[0]; + const v = { qty, wei: wei.toString(), sendWei: (wei + wei / 100n).toString() }; + qCache.set(k, { at: Date.now(), v }); if (qCache.size > 200) qCache.clear(); + return v; +} +async function order(buyer, qty, ref, v) { + const q = await quote(qty); + const data = CALLS.encodeFunctionData('buy', [qty, BigInt(ref || 0), v ? v.line : [], v ? v.deadline : 0, v ? v.sig : '0x']); + return { to: C.contractAddress, chainId: C.chainId, data, value: '0x' + BigInt(q.sendWei).toString(16), wei: q.wei, sendWei: q.sendWei, line: v ? v.line.length : 0 }; +} +// is the buyer's line already bound on chain? (then no voucher is needed: the contract ignores it) +async function boundSponsor(buyer) { try { const s = String((await call('sponsorOf', [buyer]))[0]).toLowerCase(); return s === ZERO ? null : s; } catch (e) { return undefined; } } +async function payees(buyer) { try { const r = await call('payeesOf', [buyer]); return r[0].map((a, i) => ({ to: String(a).toLowerCase(), depth: Number(r[1][i]) })); } catch (e) { return null; } } +async function receipt(hash) { + const r = await rpc('eth_getTransactionReceipt', [hash]); + if (!r) return { found: false }; + return { found: true, status: r.status, blockNumber: r.blockNumber, to: r.to ? String(r.to).toLowerCase() : null, from: r.from ? String(r.from).toLowerCase() : null }; +} +// Polygon's ~25 gwei priority-fee floor: wallets' own estimates miss it (the Downline Banners fix) +async function fees() { + let tip = 0n, base = 0n; + try { tip = BigInt(await rpc('eth_maxPriorityFeePerGas', [])); } catch (e) {} + try { const blk = await rpc('eth_getBlockByNumber', ['latest', false]); base = BigInt((blk && blk.baseFeePerGas) || '0x0'); } catch (e) {} + const MIN_TIP = C.chainId === 137 ? 30000000000n : 1000000000n; + const priority = tip > MIN_TIP ? tip : MIN_TIP; + return { maxPriorityFeePerGas: '0x' + priority.toString(16), maxFeePerGas: '0x' + (base * 2n + priority).toString(16) }; +} +let lastNudge = 0; +function nudge() { if (!watching() || Date.now() - lastNudge < 3000) return; lastNudge = Date.now(); poll().catch(() => {}); } + +function view() { + const list = Object.values((store.state() && store.state().purchases) || {}); + return Object.assign({ contract: C ? C.contractAddress || null : null, watching: watching(), vouchers: voucherOn(), keeper: keeper ? keeper.address : null, + lastBlock: ((store.state() || {}).shop || {}).lastBlock ?? null, positions: list.reduce((t, x) => t + (Number(x.qty) || 1), 0), orders: list.length }, st); +} +module.exports = { setHook, setAttach, init, voucher, voucherOn, watching, apply, poll, view, quote, order, receipt, fees, nudge, call, rpc, readSplit, boundSponsor, payees, TOPIC, IFACE, TYPES, CALLS, MAX_LINE }; diff --git a/store.js b/store.js new file mode 100644 index 0000000..080ad2a --- /dev/null +++ b/store.js @@ -0,0 +1,122 @@ +// 5xYourTeam data. One document (fivex.json) holds members (coaches and anyone signed in), sessions, position purchases (the +// chain's Purchase events), the watcher position, the weekly drafts, instant-pick credits, Best Coach pot payouts and daily counters. +// Three growing collections are row tables on MySQL (docstore splits): picks (each pick = one adoption), messages (coach <-> pick, +// through the site only) and builder referral IDs. Without DOCSTORE_URL (local prototype + tests only) everything stays in the one +// file, written atomically. Marty's rule (2026-11-13): MySQL is the standard; never launch on files. +'use strict'; +const fs = require('fs'); +const path = require('path'); +const crypto = require('crypto'); +const cfgMod = require('./config'); +const docstore = require('./docstore'); + +const DOC = 'fivex.json'; +const SPLITS = [ + { doc: DOC, field: 'picks', table: 'fx_picks', key: 'id', ts: 'at' }, + { doc: DOC, field: 'msgs', table: 'fx_msgs', key: 'id', ts: 'at' }, + { doc: DOC, field: 'refids', table: 'fx_refids', key: 'id', ts: 'at' } +]; +const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s])); + +let S = null, saveT = null, rowMode = false; +const FILE = () => path.join(cfgMod.get().dataDir, DOC); + +function load() { + try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; } + S = Object.assign({ v: 1, seq: { pick: 0, msg: 0, refid: 0 }, daily: {}, members: {}, sessions: {}, purchases: {}, shop: {}, drafts: {}, credits: {}, + payouts: {}, programs: null, picks: [], msgs: [], refids: [] }, S || {}); + rowMode = docstore.isOn(); + if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice(); + const now = Date.now(); + for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k]; +} +function save(now) { + if (saveT && !now) return; + const run = () => { + saveT = null; + try { + const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S; + const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE()); + } catch (e) { console.error('store save failed', e.message); } + }; + if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 500); +} +function flush() { save(true); } +const state = () => S; +function putRow(field, item) { if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } save(); } +function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; } + +// ---- Central time (Marty: everything on US Central) ---- +const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short', hour: '2-digit', minute: '2-digit', hour12: false }); +const parts = ts => Object.fromEntries(fmt.formatToParts(new Date(ts)).map(x => [x.type, x.value])); +function ctDay(ts) { const p = parts(ts == null ? Date.now() : ts); return p.year + '-' + p.month + '-' + p.day; } +function ctWeek(ts) { // the Central-time date of that week's Monday + const p = parts(ts == null ? Date.now() : ts); + const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0; + return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10); +} +// a Central wall-clock time (YYYY-MM-DD, hour) -> epoch ms (handles CST / CDT) +function ctToMs(day, hour) { + const [y, m, d] = day.split('-').map(Number); + for (const off of [6, 5]) { const t = Date.UTC(y, m - 1, d, hour + off); const p = parts(t); if (Number(p.hour) % 24 === hour && p.day === String(d).padStart(2, '0')) return t; } + return Date.UTC(y, m - 1, d, hour + 6); +} +const addDays = (day, n) => new Date(Date.parse(day + 'T00:00:00Z') + n * 86400000).toISOString().slice(0, 10); +function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); } +function today() { return S.daily[ctDay()] || {}; } + +// ---- members (keyed by wallet) ---- +function member(addr) { return S.members[String(addr || '').toLowerCase()] || null; } +function upsertMember(addr, patch) { + const a = String(addr).toLowerCase(); + const m = S.members[a] || (S.members[a] = { address: a, username: null, hubId: null, joinedAt: Date.now(), via: null, netOk: false, queue: [] }); + Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m; +} +function memberByName(name) { const n = String(name || '').toLowerCase(); if (!n) return null; for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m; return null; } +function memberByHub(id) { if (!id) return null; for (const m of Object.values(S.members)) if (m.hubId === id) return m; return null; } +function members() { return Object.values(S.members); } + +// ---- sessions ---- +const SESSION_TTL = 7 * 24 * 3600000; +function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: address.toLowerCase(), expires: Date.now() + SESSION_TTL }; save(); return token; } +function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; } +function dropSession(token) { delete S.sessions[token]; save(); } + +// ---- positions (from the chain) ---- +const purchases = () => Object.entries(S.purchases || {}).map(([key, x]) => Object.assign({ key }, x)); +function positionsOf(addr) { const a = String(addr || '').toLowerCase(); return purchases().filter(x => x.buyer === a).reduce((t, x) => t + (Number(x.qty) || 1), 0); } +function firstPositionAt(addr) { const a = String(addr || '').toLowerCase(); const l = purchases().filter(x => x.buyer === a).map(x => (x.blockAt ? x.blockAt * 1000 : x.at) || 0); return l.length ? Math.min(...l) : 0; } +function coaches() { const seen = new Set(purchases().map(x => x.buyer)); return [...seen].map(a => member(a) || upsertMember(a, { via: 'wallet' })); } + +// ---- instant-pick credits (5 per position, used from the current pool) ---- +const credits = addr => Number(S.credits[String(addr).toLowerCase()] || 0); +function addCredits(addr, n) { const a = String(addr).toLowerCase(); S.credits[a] = Math.max(0, credits(a) + n); save(); return S.credits[a]; } + +// ---- picks ---- +const picks = () => S.picks; +function pick(id) { return S.picks.find(p => p.id === Number(id)) || null; } +function addPick(p) { p.id = nextId('pick'); p.at = p.at || Date.now(); S.picks.push(p); putRow('picks', p); return p; } +function savePick(p) { p.updatedAt = Date.now(); putRow('picks', p); } +const picksOf = addr => S.picks.filter(p => p.coach === String(addr).toLowerCase()); +const picksOfPerson = id => S.picks.filter(p => p.person === id); + +// ---- messages (coach <-> pick, through the site) ---- +function addMsg(m) { m.id = nextId('msg'); m.at = m.at || Date.now(); S.msgs.push(m); putRow('msgs', m); return m; } +const msgsOfPick = id => S.msgs.filter(m => m.pick === Number(id)); +function saveMsg(m) { putRow('msgs', m); } + +// ---- builder referral IDs (the CryptoTeamBuild downline builder, the DownlineHydra wild heads) ---- +function setRefid(addr, program, refId) { + const a = String(addr).toLowerCase(); let r = S.refids.find(x => x.member === a && x.program === program); + if (!r) { r = { id: nextId('refid'), member: a, program, refId, at: Date.now() }; S.refids.push(r); } else { r.refId = refId; r.at = Date.now(); } + putRow('refids', r); return r; +} +const refidOf = (addr, program) => { const r = S.refids.find(x => x.member === String(addr || '').toLowerCase() && x.program === program); return r && r.refId ? r.refId : ''; }; + +// ---- drafts ---- +const draft = week => S.drafts[week] || null; +function putDraft(d) { S.drafts[d.week] = d; save(); return d; } + +module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, ctToMs, addDays, bump, today, member, upsertMember, memberByName, memberByHub, members, + mintSession, session, dropSession, SESSION_TTL, purchases, positionsOf, firstPositionAt, coaches, credits, addCredits, + picks, pick, addPick, savePick, picksOf, picksOfPerson, addMsg, msgsOfPick, saveMsg, setRefid, refidOf, draft, putDraft }; diff --git a/tankpool.js b/tankpool.js new file mode 100644 index 0000000..869cc9e --- /dev/null +++ b/tankpool.js @@ -0,0 +1,91 @@ +// The holding tank behind The Draft. ONE interface, two implementations: +// +// candidates(now) -> [{ id, username, joinedAt, lastSeen, door, wallet, locked, sponsored, spam, throwaway, adoptions, +// games: { plays, title, earnedWei } | null, surfWei | null }] people waiting for a sponsor +// status(ids, now) -> { id: { lastSeen, username, wallet, payouts, purchase, games, surfWei, adoptions } | null } +// milestones are timestamps (0 = not yet); null = the network cannot say right now +// adopt({ coach, person, kind, note }) -> { ok, ref } | { error } the pick becomes this coach's adoption +// release({ coach, person, why }) -> { ok } | { error } back to the tank (return window ended, or released) +// +// Contact data never crosses this interface: no emails, no phone numbers. Coaches get the RIGHT TO SPONSOR AND HELP; the only +// mail a pick gets is the tank's normal "X is now your sponsor" adoption email, which the tank (InstantAdPay / LinkSpin) sends. +// +// 'stub' (phase 1, TANK_MODE unset): a local fixture (STUB_POOL_FILE, else qa/fixtures/pool.json) with relative times, adoption +// state in the document stub-tank.json. It adopts nobody for real and sends no mail. Admin test routes can move a person's +// milestones (POST /api/admin/stub/status) so the coaching tools, cards and boards can be exercised. +// 'hub' (phase 2): NOT WIRED. Every call answers { error } / [] so nothing is drafted. What it needs (open for Marty + the hub): +// - a pool read: the network tank's waiting list (InstantAdPay tank.waiting() is the source today, the hub has no tank route) +// with rule 3 applied (hub /v1/locked detail), username, door (hub joinedVia), last seen, wallet linked +// - scouting stats where they exist: game plays + POL earned (game wallet watchers), surf earnings (IAP ads.earnedTotals) +// - adopt: the tank's own adopt (so the 2-adoption count, the hold, the adoption email and the Telegram line stay in one place), +// e.g. IAP POST /api/admin/tank/adopt with the coach as adopter, then hub /v1/sponsor-change { by: 'adopt' } +// - status: payouts on / first purchase per person (IAP memberId + chain Purchase), hub /v1/activity/person for last seen +'use strict'; +const fs = require('fs'); +const path = require('path'); + +const H = 3600000, D = 86400000; +let C = null, mode = 'stub', fixture = null, nowFn = () => Date.now(); +const FILE = () => path.join(C.dataDir, 'stub-tank.json'); +function st() { let s = {}; try { s = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) {} s.adopted = s.adopted || {}; s.over = s.over || {}; s.log = s.log || []; s.mails = s.mails || 0; return s; } +function put(s) { s.log = s.log.slice(-300); fs.writeFileSync(FILE() + '.tmp', JSON.stringify(s)); fs.renameSync(FILE() + '.tmp', FILE()); } + +function init(cfg, opts) { + C = cfg; mode = cfg.tankMode; if (opts && opts.now) nowFn = opts.now; + if (mode === 'stub') { + const f = cfg.stubPool || path.join(__dirname, 'qa', 'fixtures', 'pool.json'); + try { fixture = JSON.parse(fs.readFileSync(f, 'utf8')); } catch (e) { fixture = { people: [] }; console.error('tankpool: no stub pool at', f); } + fixture.base = nowFn(); // relative times are measured from boot + console.log('tankpool: STUB mode (' + fixture.people.length + ' fixture people, nobody is adopted for real, no mail)'); + } else console.log('tankpool: hub mode is not wired yet (phase 2): the pool is empty and no pick can be made'); +} +const isStub = () => mode === 'stub'; +const ago = (h, base) => (h == null ? 0 : base - h * H); +// a fixture person at time `now` (relative hours), with any admin override applied +function person(p, s, now) { + const o = s.over[p.id] || {}; const base = fixture.base; + const ts = k => (o[k] !== undefined ? o[k] : p[k + 'HoursAgo'] != null ? ago(p[k + 'HoursAgo'], base) : 0); + return { id: p.id, username: p.username || null, door: p.door || null, joinedAt: ago(p.joinedHoursAgo, base), lastSeen: ts('seen'), + wallet: ts('wallet'), payouts: ts('payouts'), purchase: ts('purchase'), locked: !!p.locked, sponsored: !!p.sponsored || !!(s.adopted[p.id] && s.adopted[p.id].sticky), + spam: !!p.spam, throwaway: !!p.throwaway, adoptions: Number(p.adoptionsElsewhere) || 0, + games: p.games ? { plays: Number(p.games.plays) || 0, title: p.games.title || null, earnedWei: p.games.earnedWei || null } : null, surfWei: p.surfWei || null }; +} + +async function candidates(now) { + if (!isStub()) return []; + const s = st(); now = now || nowFn(); + return fixture.people.filter(p => !s.adopted[p.id]).map(p => { const x = person(p, s, now); return Object.assign(x, { wallet: !!x.wallet }); }) + .filter(x => !x.payouts && !x.purchase); // payouts on = out of the tank (the IAP rule) +} +async function status(ids, now) { + const out = {}; if (!isStub()) { for (const id of ids) out[id] = null; return out; } + const s = st(); now = now || nowFn(); + for (const id of ids) { const p = fixture.people.find(x => x.id === id); if (!p) { out[id] = null; continue; } const x = person(p, s, now); + out[id] = { lastSeen: x.lastSeen, username: x.username, wallet: x.wallet, payouts: x.payouts, purchase: x.purchase, games: x.games, surfWei: x.surfWei, adoptions: x.adoptions, door: x.door }; } + return out; +} +async function adopt(o) { + if (!isStub()) return { error: 'The holding tank is not connected yet.' }; + const s = st(); const p = fixture.people.find(x => x.id === o.person); + if (!p) return { error: 'Not in the holding tank.' }; + if (p.locked) return { error: 'Locked on a network contract.' }; + if (p.sponsored) return { error: 'Already has a sponsor.' }; + if (s.adopted[p.id]) return { error: 'Already adopted.' }; + s.adopted[p.id] = { coach: o.coach, at: nowFn(), kind: o.kind || 'draft' }; s.mails++; // phase 2: the tank sends the normal adoption email here + s.log.push({ at: nowFn(), adopt: p.id, coach: o.coach, kind: o.kind }); put(s); + return { ok: true, ref: 'stub:' + p.id }; +} +async function release(o) { + if (!isStub()) return { error: 'The holding tank is not connected yet.' }; + const s = st(); if (!s.adopted[o.person]) return { ok: true }; + delete s.adopted[o.person]; s.log.push({ at: nowFn(), release: o.person, why: o.why || '' }); put(s); return { ok: true }; +} +// admin test hook (stub only): move a person's milestones, e.g. { id, wallet: true, payouts: true, seen: true } +function setStatus(id, patch) { + if (!isStub()) return { error: 'stub only' }; + const s = st(); const o = s.over[id] || (s.over[id] = {}); const t = nowFn(); + for (const k of ['wallet', 'payouts', 'purchase', 'seen']) if (patch[k] !== undefined) o[k] = patch[k] ? (typeof patch[k] === 'number' ? patch[k] : t) : 0; + put(s); return { ok: true, over: o }; +} +function view() { if (!C) return {}; const s = isStub() ? st() : null; return { mode, fixture: fixture ? fixture.people.length : 0, adopted: s ? Object.keys(s.adopted).length : 0, adoptionMailsThatWouldSend: s ? s.mails : 0, log: s ? s.log.slice(-20) : [] }; } +module.exports = { init, candidates, status, adopt, release, setStatus, view, isStub, H, D }; diff --git a/tools/art.mjs b/tools/art.mjs new file mode 100644 index 0000000..6be1fa3 --- /dev/null +++ b/tools/art.mjs @@ -0,0 +1,103 @@ +// Renders the site art with Playwright (local only, nothing is uploaded): the icon, the OG share image, the Telegram sale proof +// cards (public/art/proof/fx-proof-{navy,gold,field}.png), the promo kit (public/art/kit/fx--.png, 3 angles x 7 +// shapes, ad-blocker-neutral names), the five trading-card tiers and a sample coach card (public/art/cards/), and, with +// node tools/art.mjs --draftday http://127.0.0.1:3561 2026-11-16 +// the Draft Day results card for that week from a running app (public/art/draftday/week-.png, the Telegram image). +// Copy facts come from config.js; the look is the approved draft-night mockup (navy, gold, red tag, Oswald + Inter). +import fs from 'node:fs'; +import path from 'node:path'; +import { createRequire } from 'node:module'; +import { fileURLToPath } from 'node:url'; +const require = createRequire(import.meta.url); +const APP = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const PW = process.env.PLAYWRIGHT || 'D:/Projects/MarketingAgent/qa-tester/node_modules/playwright'; +const { chromium } = require(PW); +const C = require(path.join(APP, 'config.js')).get(); +const { SHAPES } = require(path.join(APP, 'promokit.js')); +const ART = path.join(APP, 'public', 'art'); +for (const d of ['kit', 'proof', 'cards', 'draftday']) fs.mkdirSync(path.join(ART, d), { recursive: true }); +const FONTS = ''; +const BASE = `*{box-sizing:border-box;margin:0}html,body{width:100%;height:100%;overflow:hidden} +body{background:#0b1530;color:#fff;font-family:Inter,sans-serif;position:relative} +.wm{font-family:Oswald,Impact,sans-serif;font-weight:700;letter-spacing:1px;white-space:nowrap}.wm b{color:#ffc93c} +.d{font-family:Oswald,Impact,sans-serif;font-weight:700;text-transform:uppercase;line-height:.95} +.g{color:#ffc93c}.tag{display:inline-block;background:#ff4d4d;color:#fff;font-family:Oswald,sans-serif;letter-spacing:2px;white-space:nowrap} +.cta{display:inline-block;background:#ffc93c;color:#0b1530;font-family:Oswald,sans-serif;letter-spacing:1px;text-transform:uppercase;white-space:nowrap} +.stripes{position:absolute;inset:0;background:repeating-linear-gradient(90deg,transparent 0 9.5%,rgba(255,255,255,.045) 9.5% 10%);pointer-events:none} +.tc{border-style:solid;display:flex;flex-direction:column;color:#0b1530}.tc .t{font-family:Oswald,sans-serif;letter-spacing:3px;text-align:center}.tc .f{display:flex;align-items:center;justify-content:center;font-family:Oswald,sans-serif}`; +const WM = px => `5XYOURTEAM`; +const TIERS = { rookie: ['ROOKIE', '#e5e9f4', '#9aa6c4', '#0b1530', '#c6cde0', '#4a587e', 'Drafted'], starter: ['STARTER', '#eaf6ef', '#1f8a5b', '#fff', '#bfe3cf', '#1f5c40', 'Wallet linked'], + pro: ['PRO', '#e8eefc', '#2f5be0', '#fff', '#c3d2fa', '#1d3a96', 'Payouts switched on'], allstar: ['ALL-STAR', '#fff7df', '#ffc93c', '#0b1530', '#ffe8a3', '#7a5a00', 'First purchase'], + hof: ['HALL OF FAME', '#1a1030', '#ffc93c', '#0b1530', '#2a1a4a', '#ffc93c', 'Built a team of their own'] }; +// one trading card at scale f (base 220 x 380) +function tcard(tier, name, team, f) { + const [lab, bg, bd, ink, face, fink, ms] = TIERS[tier]; + const hof = tier === 'hof'; + return `
+
${lab}
+
${name.slice(0, 2).toUpperCase()}
+
@${name}Team @${team}${ms}
`; +} +const ANG = { + draft: { k: 'EVERY MONDAY', h1: 'Draft your team', h2: 'every Monday', s: 'Coaches draft people who joined the network without a sponsor. Draft order is earned.', cta: 'Get a position' }, + coach: { k: 'EARN YOUR DRAFT SPOT', h1: 'Coach them up', h2: 'pick first', s: 'Get last week\'s picks going and you pick first next Monday. Coaching through site messages.', cta: 'Start coaching' }, + cards: { k: 'TRADING CARDS', h1: 'Rookie to', h2: 'Hall of Fame', s: 'Your picks are cards that level up as they do. $' + C.position.usd + ' once, ' + C.position.picksOnBuy + ' picks today.', cta: 'See the cards' } +}; +const fan = f => `
${tcard('starter', 'surfqueen', 'you', .55 * f)}${tcard('allstar', 'gamerdad', 'you', .68 * f)}${tcard('pro', 'lunaclicks', 'you', .55 * f)}
`; +function kitHtml(angle, shape, w, h) { + const a = ANG[angle]; const m = Math.min(w, h); + if (shape === 'tile') return `
${WM(13)}
${angle === 'cards' ? 'Level' : angle === 'coach' ? 'Coach' : 'Draft'}
${angle === 'cards' ? 'them up' : angle === 'coach' ? 'them up' : 'Monday'}
5xyourteam.com
`; + if (shape === 'strip' || shape === 'leader') { const big = shape === 'leader'; + return `
${WM(big ? 24 : 15)}
${a.k}
${a.h1} ${a.h2}
${a.cta}`; } + if (shape === 'tower') return `
${WM(19)}${a.k}
${a.h1}
${a.h2}
${a.s}
${tcard('allstar', 'gamerdad', 'you', .45)}
${a.cta}
5xyourteam.com
`; + const f = m / 250; const wide = shape === 'social' || shape === 'square'; + return `
+
+
+
${WM(Math.round(17 * f))}${a.k}
+
${a.h1}
${a.h2}
+
${a.s}
+
${a.cta}5xyourteam.com
+ ${wide ? `
${fan(shape === 'square' ? f * .8 : f * .75)}
` : ''}
`; +} +function proofHtml(v) { + const V = { navy: ['#0b1530', '#ffc93c'], gold: ['#13214a', '#ffc93c'], field: ['#0e3b2a', '#ffc93c'] }[v]; + return `
+
${WM(48)}PAID ON-CHAIN
+
A coach just
joined The Draft
+
${tcard('rookie', 'newcoach', 'draft', 1.15)}
Sponsor 25%Levels 2-5: 5% eachBest Coach pot 10%Same transaction.
The contract keeps nothing.
+
Every position and every payout: 5xyourteam.com/ledger
`; +} +const ogHtml = () => `
+
${WM(40)}THE DRAFT ยท EVERY MONDAY +
Draft your team
every Monday
+
$${C.position.usd} once: ${C.position.picksOnBuy} picks today,
a draft spot every week.
+
${fan(1.25)}
`; +const iconHtml = () => `
5X
`; +const tiersHtml = () => `${Object.keys(TIERS).map((t, i) => tcard(t, ['newbie77', 'surfqueen', 'lunaclicks', 'gamerdad', 'cryptomike'][i], 'martbost', 1)).join('')}`; +const coachHtml = () => `
COACH@martbostCoach since November 2026${WM(30)}
${tcard('pro', 'lunaclicks', 'martbost', .8)}${tcard('starter', 'surfqueen', 'martbost', .8)}${tcard('rookie', 'newbie77', 'martbost', .8)}
`; + +async function shot(browser, html, file, w, h, fonts) { + const pg = await browser.newPage({ viewport: { width: w, height: h } }); + await pg.setContent('' + (fonts ? FONTS : '') + '' + html + '', { waitUntil: 'load' }); + await pg.evaluate(() => document.fonts && document.fonts.ready).catch(() => {}); + await pg.screenshot({ path: file, clip: { x: 0, y: 0, width: w, height: h } }); await pg.close(); +} +const browser = await chromium.launch(); +const ddIdx = process.argv.indexOf('--draftday'); +if (ddIdx > 0) { + const base = process.argv[ddIdx + 1], week = process.argv[ddIdx + 2]; + const pg = await browser.newPage({ viewport: { width: 1080, height: 1080 } }); + await pg.goto(base + '/draftday/' + week, { waitUntil: 'load' }); await pg.waitForSelector('body[data-ready="1"]', { timeout: 10000 }).catch(() => {}); + await pg.evaluate(() => document.fonts && document.fonts.ready).catch(() => {}); + const out = path.join(ART, 'draftday', 'week-' + week + '.png'); await pg.screenshot({ path: out, clip: { x: 0, y: 0, width: 1080, height: 1080 } }); + console.log('draft day card', out); await browser.close(); process.exit(0); +} +await shot(browser, iconHtml(), path.join(ART, 'icon-192.png'), 192, 192, true); +await shot(browser, ogHtml(), path.join(ART, 'og-share.png'), 1200, 630, true); +for (const v of ['navy', 'gold', 'field']) await shot(browser, proofHtml(v), path.join(ART, 'proof', 'fx-proof-' + v + '.png'), 1080, 1080, true); +await shot(browser, tiersHtml(), path.join(ART, 'cards', 'fx-tiers.png'), 1280, 460, true); +await shot(browser, coachHtml(), path.join(ART, 'cards', 'fx-coach-card.png'), 1200, 420, true); +for (const angle of Object.keys(ANG)) for (const [shape, [w, h]] of Object.entries(SHAPES)) await shot(browser, kitHtml(angle, shape, w, h), path.join(ART, 'kit', 'fx-' + angle + '-' + shape + '.png'), w, h, true); +await browser.close(); +console.log('art rendered'); diff --git a/tools/pages.mjs b/tools/pages.mjs new file mode 100644 index 0000000..dcf0326 --- /dev/null +++ b/tools/pages.mjs @@ -0,0 +1,235 @@ +// Writes public/*.html from one place (one source of copy and legal facts, the trust-pack legal.py idea). Run after editing: +// node tools/pages.mjs +// Copy rules: no em dashes, no income promises, never an earnings cap, "A position buys a draft spot and coaching tools, not +// income. Nothing is promised.", wallets = "SafePal or any other crypto wallet" (never recommend MetaMask), one-time, never a +// subscription, coaches get the right to sponsor and help and never contact data. +import fs from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +const PUB = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'public'); +const SITE = 'https://5xyourteam.com'; +const V = { css: 1, js: 1 }; +const F = { co: 'TrustClickz', addr: '615 Green Valley Drive, Moody, AL 35004', updated: 'November 15, 2026', usd: 10, picks: 5, rounds: 5, returnDays: 3, maxOpen: 10 }; +const FONTS = 'https://fonts.googleapis.com/css2?family=Oswald:wght@500;700&family=Inter:wght@400;600;700&display=swap'; +const NOTE = 'A position buys a draft spot and coaching tools, not income. Nothing is promised.'; + +function head(o) { + const t = o.title, d = o.desc, url = SITE + o.path; + return ` + + + +${t} + +${o.noindex ? '' : ``} + + + + + + + + + + + + + + + + + +`; +} +const tail = scripts => ['common.js'].concat(scripts).map(s => '').join('\n') + '\n\n\n'; +const page = (file, o, body, scripts) => fs.writeFileSync(path.join(PUB, file), head(o) + body + tail(scripts)); +const STATUS = ''; + +// ---------------------------------------------------------------- the draft board (front page) +page('index.html', { path: '/', title: '5xYourTeam | The weekly draft for people who need a sponsor', + desc: `Every Monday the coaches draft people who joined the network without a sponsor. A $${F.usd} one-time position: ${F.picks} picks right away and a draft spot every week. Draft order is earned.` }, `
+
+

THE DRAFT

Draft your team every Monday.

+

Draft order is earned: the coaches who got the most of last week's picks started pick first. Help your picks get going and you move up next Monday.

+
+
Best Coach pot this week0 POL10% of every position sold this week
+
+ ${STATUS} +
+

This week's pool

People waiting for a sponsor. Usernames only, never contact details.

+
+
+
+
+

DRAFT TRACKER

PICKCOACHDRAFTEDCARD
+

Best Coach standings

+

Last week

+
+
+

Rookie of the Week

+

How The Draft works

+
+
1

Get a position

$${F.usd} one-time in POL with SafePal or any other crypto wallet, never a subscription. It comes with ${F.picks} picks right away.

+
2

Draft every Monday

${F.rounds} rounds from that week's pool. Away? You are auto-picked from your queue, or the best available player.

+
3

Coach them up

Help them link a wallet and switch on payouts, through site messages. Picks that do not start go back to the pool after ${F.returnDays} days.

+
+

You get the right to sponsor and help your picks, never their email or any contact details: you coach through site messages, and they get the network's normal "you have a new sponsor" email. Nobody locked on a network contract is ever in the pool, and nobody is adopted more than twice.

+ +

${NOTE}

+
+
+`, ['board.js']); + +// ---------------------------------------------------------------- my team +page('team.html', { path: '/team', title: 'My Team | 5xYourTeam', desc: 'Coach your picks: scouting stats, the getting-started steps, one-tap messages and who to help first.', noindex: true }, `
+ + ${STATUS} + +
+`, ['wallet.js', 'team.js']); + +// ---------------------------------------------------------------- cards +page('cards.html', { path: '/cards', title: 'Card Collection | 5xYourTeam', desc: 'Trading cards that level up as your picks do: Rookie, Starter, Pro, All-Star, Hall of Fame.' }, `
+

CARD COLLECTION

Trading cards: they level up as your picks do

Public cards show milestones, never earnings.

+ +

The five tiers

+

Rookie when drafted, Starter when they link a wallet, Pro when they switch on payouts, All-Star at their first purchase, Hall of Fame when they hold a position of their own and coach a team.

+
+`, ['cards.js']); + +// ---------------------------------------------------------------- get a position +page('join.html', { path: '/join', title: 'Get a Position | 5xYourTeam', desc: `A $${F.usd} one-time position: ${F.picks} picks right away and a draft spot every Monday. Paid in POL, split on-chain in the same transaction.` }, `
+

GET A POSITION

$${F.usd} once. ${F.picks} picks today. A draft spot every Monday.

+

One payment in POL with SafePal or any other crypto wallet. It never renews and is never a subscription.

+
What you get
  • ${F.picks} instant picks from this week's pool
  • A spot in every Monday draft, ${F.rounds} rounds
  • Coaching tools: scouting stats, the steps, site messages, who to help first
  • A coach page and trading cards for your team
  • Up to ${F.maxOpen} open picks at a time
+ +

Buy

+
${STATUS} +

Anything you send above the exact price comes back to you in the same transaction. Payments are final once confirmed.

+

Where your $${F.usd} goes, in the same transaction

+

Your sponsor gets 25% and levels 2 to 5 of your network sponsor line get 5% each. Only people who hold a position can receive a share: anyone in your line who does not is passed over and the share goes up to the next person who does. 10% goes to the weekly Best Coach pot and 45% to 5xYourTeam. The contract keeps nothing. Check it on the contract page and every payment on the ledger.

+

${NOTE}

+
+`, ['wallet.js', 'join.js']); + +// ---------------------------------------------------------------- coach page +page('coach.html', { path: '/', title: 'Coach | 5xYourTeam', desc: 'A 5xYourTeam coach and their team, as trading cards.' }, `
+
COACH
+

The team

Milestones only. Every Monday this coach drafts people who joined the network without a sponsor and helps them get started.

+
+
+`, ['coach.js']); + +// ---------------------------------------------------------------- ledger, contract +page('ledger.html', { path: '/ledger', title: 'Live Ledger | 5xYourTeam', desc: 'Every 5xYourTeam position and every share it paid, in the same transaction, with links to verify on Polygonscan.' }, `
+

LIVE LEDGER

Every position, every share, on-chain

+
+
WHENPOSITIONPAID IN THE SAME TRANSACTION
+

Best Coach payouts

WEEKCOACHPOL
+
+`, ['ledger.js']); +page('contract.html', { path: '/contract', title: 'The Contract | 5xYourTeam', desc: 'DraftPosition on Polygon: who owns it, the fixed split, the Best Coach pot wallet, what it holds.' }, `
+

CONTRACT

Check the contract yourself

Read live from Polygon. No owner withdraw, no proxy, the split fixed in the code.

+
+
+`, ['contract.js']); + +// ---------------------------------------------------------------- promote, builder, admin, draft day +page('promote.html', { path: '/promote', title: 'Promo Kit | 5xYourTeam', desc: 'Links, creatives and copy for 5xYourTeam, with your username in every link.', data: 'promote' }, `
+

PROMO KIT

Share The Draft

+
+ ${STATUS} +
+
+`, ['kitpage.js', 'misc.js']); +page('builder.html', { path: '/builder', title: 'My Builder Links | 5xYourTeam', desc: 'Your referral IDs in the CryptoTeamBuild downline builder: your picks see your links.', noindex: true, data: 'builder' }, `
+

MY BUILDER LINKS

The CryptoTeamBuild downline builder

Save your referral ID for the programs you are in. Your picks see your link for each one on their My Team page.

+ + ${STATUS} +
+
+`, ['wallet.js', 'misc.js']); +page('admin.html', { path: '/admin', title: 'Admin | 5xYourTeam', desc: 'Admin.', noindex: true, data: 'admin' }, `
+
+

Status

+

Best Coach pot (last week)

+

Old-link map (JSON {"oldrefs": {"old": "network username"}})

+
+`, ['misc.js']); +fs.writeFileSync(path.join(PUB, 'draftday.html'), `Draft Day | 5xYourTeam +
5XYOURTEAM
+

DRAFT DAY
RESULTS

+
5xyourteam.com
+ +`); + +// ---------------------------------------------------------------- legal +const CONTACT = ['Contact', `

${F.co}, ${F.addr}. Network support. Last updated ${F.updated}.

`]; +function legal(file, p, title, lead, cards) { + page(file, { path: p, title: title + ' | 5xYourTeam', desc: lead, data: 'legal' }, `
+

5XYOURTEAM

${title}

${lead}

+${cards.map(c => `

${c[0]}

${c[1]}
`).join('\n')} +
+`, ['misc.js']); +} +legal('terms.html', '/terms', 'Terms and Conditions', 'The rules for using 5xYourTeam, in plain English.', [ + ['Who we are', `

5xYourTeam (5xyourteam.com) is run by ${F.co}, ${F.addr}. It is part of the network: one network account works across InstantAdPay, LinkSpin, Downline Banners, Viral Banner Blitz, ViralAdBlitz, 5xYourTeam, Stack POL and Earners Corner. By using 5xYourTeam you agree to these terms.

`], + ['What 5xYourTeam is', `

5xYourTeam runs The Draft. People who join the network without a sponsor wait in the network holding tank. Every Monday the coaches on 5xYourTeam draft them, in rounds. A drafted person (a pick) is adopted by their coach under the holding-tank rules, and their coach becomes their network sponsor while the pick is open.

`], + ['What a position is', `

A position is a single, one-time purchase of $${F.usd}. It gives you ${F.picks} instant picks from the current pool, a spot in every weekly draft, the coaching tools, a coach page and trading cards. You can buy more than one; each adds ${F.picks} instant picks. Nothing renews and nothing is ever billed again. There are no subscriptions.

Positions are paid in POL on Polygon at the live Chainlink POL/USD price the contract reads when you buy. Anything you send above the price comes back to you in the same transaction.

What you buy is a seat in the draft and the tools to coach. It is not income, an investment or a share of anything.

`], + ['The draft', `

The draft order is earned: coaches with more of last week's picks started (payouts switched on, or a first purchase) pick first; ties go to more picks started overall, then the earlier position. A coach in the draft room has a clock for each pick; a coach who is away is picked for automatically, from their own queue or the best available player. A coach may hold up to ${F.maxOpen} open picks.

A pick that has not started within ${F.returnDays} days goes back to the pool, unless that person has now been adopted twice, in which case they stay with their coach. A started pick stays on the team. A coach cannot release a pick in its first 48 hours. The pool never includes anyone locked to a sponsor on a network contract, anyone the network already knows a sponsor for, anyone adopted twice, spam or throwaway sign-ups, or anyone in their first 24 hours.

`], + ['Coaching rules', `

Coaches get the right to sponsor and help their picks. They never get a pick's email, phone number or any other contact details, and no list of picks is ever sold or exported. Coaching happens through 5xYourTeam site messages; the pick also receives the network's normal email telling them who their new sponsor is. Be helpful and honest: no spam, no pressure, no income claims, nothing illegal. We may remove a coach who breaks these rules.

`], + ['How a payment is split', `

The DraftPosition contract splits each position in the same transaction it is paid: 25% to your sponsor, 5% to each of levels 2 to 5 of your network sponsor line, 10% to the weekly Best Coach prize pot wallet, and 45% to 5xYourTeam.

Only someone who holds a position can receive a level share. Someone in the line who does not is passed over, and the share goes up to the next person who does: the first such person gets the 25% share, the next four get 5% each, looking up to 20 places up the line. A share nobody qualifies for goes to 5xYourTeam.

Your sponsor line comes from the network hub. On your first position the site signs it and the contract records it link by link. A link already recorded is never changed. The split is fixed in the contract code and there is no owner withdraw.

`], + ['The Best Coach pot', `

10% of every position goes to a separate prize wallet fixed in the contract. Each week the pot is shared among the coaches whose picks started the most that week, as announced on the draft board. Every payout from the pot is listed on the ledger with its transaction. Prizes depend on the pot that week and are not promised.

`], + ['Nothing is promised', `

We do not promise or guarantee any income, payout, prize or result. A level share is paid only when someone in your line chooses to buy a position. Read the Earnings Disclaimer.

`], + ['No refunds', `

Payments are made on the blockchain and are final once confirmed. We cannot reverse, cancel or refund them. Check the amount before you confirm in your wallet.

`], + ['Crypto risk', `
  • The price of POL moves. The dollar value of a payment can be higher or lower later than when it was paid.
  • You are responsible for your wallet and its recovery phrase. Nobody, including us, can recover a lost wallet or reverse a payment sent from it.
  • Each transaction costs a small network fee (gas) in POL, paid to the network, not to us.
  • Use SafePal or any other crypto wallet you trust, and never share your recovery phrase with anyone. We will never ask for it.
`], + ['The service', `

The site is provided as it is. We work to keep it running but cannot promise it will always be available or free of errors. The smart contract runs on Polygon on its own; its rules are public on the contract page. We may change features, draft settings, the price of future positions or these terms; changes apply from the date they are posted here. As far as the law allows, our total responsibility to you is limited to what you paid for the purchase in question. These terms are governed by the laws of the State of Alabama, USA.

`], + CONTACT]); +legal('disclaimer.html', '/disclaimer', 'Earnings Disclaimer', NOTE, [ + ['What you are buying', `

A 5xYourTeam position is a seat in the weekly draft and the tools to coach the people you draft. It is not an investment, a business opportunity, a share of profits or a promise of any payment.

`], + ['Level shares and prizes are not promised', `

The contract pays a level share only when someone in your line chooses to buy a position. Nobody is required to buy one, and we do not know or promise whether anyone ever will. Many coaches receive nothing, and many receive less than they spend. The Best Coach pot depends on what is sold that week. Your results depend on other people's free choices.

`], + ['No examples are promises', `

Any number on this site, in the ledger or in a Telegram post shows what really happened in one transaction. It is not a typical result and not a forecast.

`], + ['Prices and taxes', `

Positions are priced in US dollars and paid in POL, whose price moves. You are responsible for any taxes on what you receive where you live.

`], + ['Who to ask', `

${F.co}, ${F.addr}. Network support.

`]]); +legal('privacy.html', '/privacy', 'Privacy Policy', 'What 5xYourTeam keeps about you, why, and for how long.', [ + ['Who we are', `

5xYourTeam is run by ${F.co}, ${F.addr}.

`], + ['What we keep', `
  • Your wallet address and network username.
  • Your network record from the network hub: your hub id and your sponsor line. 5xYourTeam does not store your email. When you sign in through InstantAdPay or LinkSpin, your email is used once to find your network record and is not kept.
  • Your positions, which are public on the Polygon blockchain.
  • The draft: who drafted whom and when, each pick's milestones (wallet linked, payouts on, first purchase), and the scouting facts shown on draft cards where the network tracks them (last seen, the site you joined through, game plays and earnings).
  • Site messages between a coach and their pick.
  • Your saved builder referral IDs.
`], + ['What coaches see about a pick', `

A username, the scouting facts above and their milestones. Never an email, phone number or any other contact details, and no list is ever exported or sold. Anyone can see trading cards, which show milestones only, never earnings.

`], + ['Cookies', `

A sign-in cookie (7 days), a cookie that remembers whose page you came from (30 days), and short-lived cookies for signing in through the network. No advertising or tracking cookies of our own.

`], + ['Who else sees data', `
  • The Polygon blockchain: every position and payment is public there.
  • The network hub, which keeps one record per person across the network sites.
  • The network holding tank (InstantAdPay and LinkSpin), which records each adoption and sends the normal new-sponsor email.
  • Our Telegram payments topic: each position is posted with the buyer's username (or a shortened wallet) and the amounts paid, and the Draft Day results with usernames.
  • Services the pages load: Google Fonts and WalletConnect (Reown) when you connect a wallet.

We do not sell personal data.

`], + ['Your choices', `

You can ask us to remove your account and messages here. Records on the blockchain cannot be removed by anyone.

`], + CONTACT]); +console.log('pages written'); diff --git a/wild.js b/wild.js new file mode 100644 index 0000000..e13ceb4 --- /dev/null +++ b/wild.js @@ -0,0 +1,76 @@ +// WILD HEADS: the CryptoTeamBuild downline builder programs (outside programs we promote but do not run). Pure functions, no I/O, +// so the rules are unit-tested on their own (qa/unit.test.cjs). +// +// A member saves their referral ID for a program. Whoever looks at a program sees ONE link: their sponsor's. +// chain = the people whose link should come first, nearest first: [{ id: hub id, username, depth }] +// a member page / or a ?ref= visitor: [u (depth 0), u's sponsor (1), ...]; a signed-in member: [sponsor (1), ...] +// walk = the first person in the chain who saved an ID for that program +// then = the site owner's saved ID (Marty, martbost), then the program's default ID (admin), then the program's plain home page +// "[N] in the builder have joined" counts real saved IDs only (never the CTB builder's own counts, never the owner's default). +'use strict'; + +const PH = /\{affil[a-z]*id\}/gi; // the builder's {affiliateid} (one entry has a misspelling; both are filled) +const ID_PATH = /^[A-Za-z0-9_.@+-]{1,64}$/; // an ID that goes into a path or query +const ID_SUB = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/; // an ID that becomes a subdomain (Tangled: https://{affiliateid}.tangled.com) + +const PH1 = /\{affil[a-z]*id\}/i; +const kindOf = url => { const m = /^https?:\/\/([^/?#]+)/i.exec(String(url || '')); return m && PH1.test(m[1]) ? 'subdomain' : 'path'; }; +// -> the cleaned ID, '' for "remove my ID", or null when it cannot be an ID for this program +function cleanId(program, raw) { + let s = String(raw == null ? '' : raw).trim(); + if (!s) return ''; + // people paste their whole referral link: take the part where the builder puts the ID + const m = /^https?:\/\//i.test(s) || /^(www\.)?[a-z0-9-]+(\.[a-z0-9-]+)+[/?]/i.test(s) ? idFromLink(program, s) : null; if (m) s = m; + if ((program.idKind || kindOf(program.url)) === 'subdomain') { s = s.toLowerCase(); return ID_SUB.test(s) ? s : null; } + return ID_PATH.test(s) ? s : null; +} +// a pasted link that matches the program's template -> the ID in it +function idFromLink(program, link) { + const parts = String(program.url || '').split(PH1); if (parts.length !== 2) return null; + const bare = x => String(x).trim().replace(/^https?:\/\//i, '').replace(/^www\./i, ''); + const pre = bare(parts[0]).toLowerCase(), l = bare(link); + if (!l.toLowerCase().startsWith(pre)) return null; + const stop = '/?#&' + (parts[1] ? parts[1][0] : ''); + let id = ''; for (const ch of l.slice(pre.length)) { if (stop.includes(ch)) break; id += ch; } + if (!id) return null; + try { return decodeURIComponent(id); } catch (e) { return id; } +} +function fillUrl(program, id) { + const v = (program.idKind || kindOf(program.url)) === 'subdomain' ? String(id).toLowerCase() : encodeURIComponent(String(id)); + return String(program.url).replace(PH, v); +} +// the program without anyone's ID: its plain home page (no broken {affiliateid} link is ever shown) +function homeUrl(program) { + const u = String(program.url || ''); + try { const x = new URL(u.replace(/\{affil[a-z]*id\}\./gi, '').replace(PH, 'x')); return x.origin + '/'; } catch (e) { return ''; } +} + +// idOf(person, programId) -> saved ID or ''. owner = { id?, username }. -> { url, by, depth, fallback } +// fallback: null (someone in the chain), 'owner', 'default', 'none' (the plain home page, nobody's ID) +function sponsorLink(program, chain, idOf, owner) { + for (const p of chain || []) { + const id = idOf(p, program.id); + if (id) return { url: fillUrl(program, id), by: p.username || null, depth: p.depth, fallback: null }; + } + const oid = owner ? idOf(owner, program.id) : ''; + if (oid) return { url: fillUrl(program, oid), by: owner.username, depth: null, fallback: 'owner' }; + if (program.defaultId) return { url: fillUrl(program, program.defaultId), by: owner ? owner.username : null, depth: null, fallback: 'default' }; + return { url: homeUrl(program), by: null, depth: null, fallback: 'none' }; +} + +// the visible wild heads, in builder order: never hidden ones, never network sites +const visible = programs => programs.filter(p => !p.hidden && !p.network).sort((a, b) => (a.order || 0) - (b.order || 0) || String(a.id).localeCompare(String(b.id))); + +// "My team joined": members whose sponsor line (stored when they last signed in) includes me, who saved an ID for the program. +// lines: [{ key, line: [{ id, username }] , ids: Set(programId) }] +function inLine(line, me) { return (line || []).findIndex(x => (me.id && x.id === me.id) || (me.username && x.username && x.username.toLowerCase() === me.username.toLowerCase())); } +function teamCounts(me, members, programIds) { + const out = Object.fromEntries(programIds.map(id => [id, 0])); + for (const m of members) { + if (m.key === me.key || inLine(m.line, me) < 0) continue; + for (const pid of programIds) if (m.ids && m.ids.has(pid)) out[pid]++; + } + return out; +} + +module.exports = { cleanId, idFromLink, fillUrl, homeUrl, sponsorLink, visible, teamCounts, inLine, kindOf, ID_PATH, ID_SUB };