{"files":[{"path":"docs/scoring.md","role":"The rulebook in words. The code below implements it.","lines":148,"sha256":"ce66be4efcd5905c11a4feca004de4621966fe53fb0a301a30a8461f0238fca5","content":"# Sentinel rulebook: grading AI projects\n\nSentinel grades AI projects whose token was launched from a launchpad on Elysium (Montra, Kleos, Ascend and others). One score per project per UTC day, from things anyone can check: the project's own public endpoints and the chain. The question behind every measurement is the same: **does the project do what it says it does?**\n\nThis is the rulebook, not live scores. Constants live in one place in the code (`RULES` in `src/engine/project.ts`).\n\n## What a listing contains\n\nSentinel writes each listing from the project's own pages, with a link to where each statement was made. Anyone can ask for a project to be looked at on the request page, for a small fee paid on Elysium (0.25 HYPE for now). The fee pays for the review: it never buys a listing, a score or a place on the board, and a listed project that paid is graded exactly like one that did not. Every request and its answer is public.\n\n| Item | Meaning |\n| --- | --- |\n| **Product claims** | The headline things the project says its product does, quoted from its site. Each one either has a **probe** (an automated check Sentinel can run) or is marked **untested**. |\n| **Money promises** | What the project says it does with money and tokens: buyback and burn shares, liquidity locks, team holdings. Each is compared with the chain. |\n| **Disclosed wallets** | Deployer, fee, treasury and team wallets the project has published. |\n| **Token facts** | Supply, burned amount, tax, liquidity status, holders. |\n\n## The listing floor\n\nA project is on the board only while its market cap is at least **$25,000**. Market cap here is the token's price times its supply net of burns. A project joins the board at $25,000 and leaves it under $20,000 (80% of the floor), so one hovering at the line does not flicker on and off.\n\n- A project under the floor is still checked every hour and keeps its own page, with every reading. It is not ranked and does not count toward the board's totals.\n- If its market cap is back above the floor it rejoins the board with its history intact.\n- A project with no market reading stays where it was; a missing price is not treated as a dead project.\n- **Market cap never changes a score.** It decides only whether a project is on the board. A small project is not a bad one: several of the best-verified products are small.\n\n## Probes\n\nA probe is a small automated check with a yes-or-no answer. Kinds:\n\n- `http`: a public URL answers 200 (optionally containing a given text, or JSON with a given field).\n- `mcp`: an MCP endpoint completes `initialize` and lists at least a given number of tools (optionally including named ones).\n- `mcp_call`: an MCP tool is called with read-only arguments and its answer contains what the project says it should.\n- `evm_code`: a contract address the project names has code on Elysium.\n\nA web or MCP answer that is JSON can be held to more than \"it answered\":\n\n- **Fields**: named fields must be present and of the right kind (a number, a list that is not empty). Text appearing somewhere on the page is not enough.\n- **It must be running**: a field (a ledger count, the latest trade) must have changed since the previous hourly run. A frozen copy of the product fails.\n- **Its figures must match the chain**: a balance the project publishes for its own wallet must match that wallet on Elysium, within 2%.\n\nChain checks hold what a project publishes about money against Elysium itself:\n\n- `payouts`: every payment in a list the project publishes (prizes, rewards) is looked up on Elysium. Each must have succeeded, come from the project's published wallet, paid the named recipient and moved the listed amount. One mismatch fails the run.\n- `eligibility`: everyone the project paid met its own rule for being paid, such as \"hold at least 2,500,000 tokens to win\". The recipient's balance is read in the block before the payment. Payments before the rule started are not judged; when the project publishes the amount, the lower of its figure today and the listing's is used.\n- `token_rule`: a wallet never sends the token anywhere but a burn address or the pool, for a project that says it never sends tokens to anyone.\n\nProbes run on every refresh (hourly is the target). A probe run **passes** or **fails**; a timeout is a failure. A mined transaction never changes, so each one is read once and kept. Each run makes a limited number of new chain reads; the rest wait for the next run. A run in which a chain check had nothing to judge yet, because its reads are still queued, is not counted at all. Probes show that a product is reachable and answers as described, and chain checks that the project's own records match the chain. They do not show that the product is good, safe or audited.\n\nA project gets a score **48 hours after its token launched**: the block time of its launch transaction on Elysium, recorded in the listing (`launchedAt`, written by `scripts/launch-times.ts`). It also needs at least one round of checks. Until then it is listed as **Too new**, with every measurement so far shown. A listing without a launch transaction counts from its first check instead. A score from checks on fewer than **3 UTC days** is labelled **Early**: it is the same score, but it rests on little data and will move.\n\n## The six measurements\n\nWindow: the last 30 UTC days with probe runs.\n\n**1. Product (35%).** For each headline claim: the share of probe runs that passed in the window, or 0 if the claim is untested.\n\n```\nclaim score = passes ÷ runs          (0 if the claim has no probe)\nS_product   = 100 × average of the claim scores\n```\n\nA claim counts as **verified** when it is tested and at least 90% of its runs passed.\n\n**2. Promises kept (25%).** Each money promise gets a ratio from 0 to 1.\n\n- *Share of fees* (for example \"50% of fees to buyback and burn\"): `owed = share × fee income`, `done = what was actually spent that way`, `ratio = min(1, done ÷ owed)`. Fee income, buys and burns are read from the disclosed fee wallet. A buyback counts toward \"buyback and burn\" only to the extent the bought tokens were burned.\n- *State* (for example \"liquidity locked\", \"team holds 5% or less\"): 1 if the chain agrees, 0 if not.\n- *Share of income to one use* (for example \"30% of what comes in goes to the prize pot\"): `owed = share × fee income`, `done = the payments the project lists for that use, each confirmed on Elysium as sent from its wallet`, `ratio = min(1, done ÷ owed)`. Fee income is what the launchpad's fee contract paid the wallet. The window starts at the oldest entry in the project's own list, or 30 days ago if that is later, so a list that only goes back so far is not read as unpaid. It is scored only once every listed payment in the window has been read.\n- A promise that cannot be measured yet is left out and listed as unmeasured.\n\n```\nS_promises = 100 × average ratio of the measured promises\n           = 40 if the project has published no promise, or none can be measured yet\n```\n\nPublishing nothing is not a free 100.\n\n**3. Token safety (15%).** Four readings, combined by weight over the ones available.\n\n| Reading | Weight | 100 points | 0 points |\n| --- | --- | --- | --- |\n| Liquidity | 35% | locked or cannot be removed | not locked (30 if unknown) |\n| Insider holdings: share of supply in the wallet that launched the token and in any team, fee or treasury wallet the project discloses | 25% | 2% or less | 20% or more |\n| Concentration: share held by the ten largest holders, leaving out pools, burn addresses and insider wallets | 25% | 15% or less | 60% or more |\n| Tax: buy tax plus sell tax | 15% | 2% or less | 20% or more |\n\n**Liquidity is read from the chain where Sentinel knows how the launchpad holds it.** Montra and Ascend seed each token's Uniswap v4 pool in its launch transaction, with the position owned by the launchpad's own hook. Sentinel checked each hook once: it cannot be changed (no proxy, no DELEGATECALL or SELFDESTRUCT), it has no function that removes its own position (documented by Montra; matched against Ascend's published interface), and across every pool it has ever seeded it has never removed liquidity. On every chain read, for each token, Sentinel finds the seed position in the launch transaction, confirms the hook still has the checked code, and reads how much of the seeded liquidity is still in the position: all of it is **locked**, less is **not locked**. When the chain gives an answer it is the one scored, whatever the project's own page says, and the page shows both. For other launchpads, or when the read fails, the project's own statement is used, and unknown scores 30.\n\n**4. Adoption (10%).** Token holders, on a log scale: 50 holders or fewer scores 0, 5,000 or more scores 100. This is the weakest measurement (holders can be inflated), which is why it carries little weight.\n\n**5. Disclosure (10%).** A checklist; the score is the share of items met.\n\n1. The official token address is published on the project's site.\n2. The deployer or fee wallet is published.\n3. The fee or tax split is published.\n4. The liquidity status is stated.\n5. The token contract's source is verified on the explorer.\n6. Public documentation describes how the product works.\n\n**6. Freshness (5%).** 100 if everything was read within 6 hours, 0 at 48 hours or more, a straight line between.\n\n## Score and grade\n\n```\nscore = 35% product + 25% promises + 15% token safety\n      + 10% adoption + 10% disclosure + 5% freshness\n      − penalties, then caps, kept between 0 and 100\n```\n\n| Grade | A | B | C | D | F |\n| --- | --- | --- | --- | --- | --- |\n| Score | 85–100 | 70–84 | 55–69 | 40–54 | 0–39 |\n\nThe published score is rounded to a whole number and the grade is read from the rounded score.\n\n## Flags, penalties, caps\n\n| Condition | Effect |\n| --- | --- |\n| **Product down.** A tested claim failed every probe run on its two most recent probe days | Flag, −15 |\n| **Promise missed.** A measured money promise is under 50% kept | Flag, −15 |\n| **Claim contradicted.** A public statement by the project is contradicted by the chain | Flag, −20 |\n| **Too new.** Probe runs on fewer than 7 UTC days | No score, unranked |\n| **Stale.** No complete read in 48 hours | Flag, score capped at 60 |\n| **Unverified.** The wallets needed to check the project's promises are not disclosed, or cannot be tied to the token | Score capped at 70, clearly labelled, no Verified badge |\n\nPenalties stack; each flag applies once however many claims or promises trigger it. Status shown, first that applies: Too new, Stale, Flagged, then Verified or Unverified. Flagged and Unverified together is shown as **Flagged, Unverified**.\n\n## What this does not measure\n\n- **Price.** A rising token is not evidence of a working product. Market cap is shown and decides whether a project is on the board (the listing floor), but it never enters a score.\n- **Quality or safety of the product.** A probe shows that an endpoint answers as described, not that the code behind it is correct or audited.\n- **Whether it is \"really AI\".** Sentinel checks what can be checked from outside.\n- **Claims nobody can test from outside.** They are listed as untested and score 0 toward Product, so a project is graded on what it lets the public verify.\n\n## Why it is hard to game\n\n- A claim only earns points while a probe keeps passing. A demo that worked once does not.\n- Untested claims earn nothing, so adding grand claims lowers the Product score unless they can be checked.\n- Promises are compared with the fee wallet's own transactions, in the token and in HYPE, not with announcements.\n- Hiding the fee wallet makes the project Unverified and caps it at 70.\n- Each day's report is hashed, and the hash is meant to be written on Elysium, so a past board cannot be quietly edited.\n\n## What is verified today\n\nProbes and chain reads run off-chain on Sentinel's server, and anyone can repeat them: every probe's URL and every wallet is on the project's page. The daily hash proves the published board was not changed later. It does not prove the reads themselves. Choosing which statements count as a project's headline claims is Sentinel's judgement; each one is quoted and linked so it can be disputed.\n"},{"path":"src/engine/project.ts","role":"The scoring function: six measurements, weights, flags, caps and the grade. Its inputs are listed in ProjectInputs; price and market cap are not among them.","lines":306,"sha256":"36be0bcd7d70e5bcfab3a5db00023dc3fbb7635e7990bef016b569bc986d9e38","content":"import { clamp, gradeOf, scoreFreshness } from \"./score.ts\";\nimport type { Grade, Linkage, Status } from \"./types.ts\";\n\n/**\n * The rulebook for AI projects (docs/scoring.md) as pure functions: observations in, scorecard out. Nothing here\n * reads the network or the clock, so a published score can be recomputed from the published observations.\n */\n\n/** Every constant in docs/scoring.md. Change the rulebook and this object together. */\nexport const RULES = {\n  /** Hours from a token's launch to its project's first score. */\n  minHoursSinceLaunch: 48,\n  /** A score with checks on fewer UTC days than this is labelled Early: it rests on little data and will move. */\n  earlyBelowDays: 3,\n  windowDays: 30,\n  weights: { product: 0.35, promises: 0.25, safety: 0.15, adoption: 0.1, disclosure: 0.1, fresh: 0.05 },\n  /** A tested claim counts as verified at or above this pass rate. */\n  verifiedAt: 0.9,\n  noPromiseScore: 40,\n  safety: {\n    weights: { liquidity: 0.35, insiders: 0.25, concentration: 0.25, tax: 0.15 },\n    liquidity: { locked: 100, unlocked: 0, unknown: 30 },\n    insiders: { full: 0.02, zero: 0.2 },\n    concentration: { full: 0.15, zero: 0.6 },\n    tax: { full: 0.02, zero: 0.2 },\n  },\n  adoption: { zero: 50, full: 5000 },\n  penalties: { product_down: 15, promise_missed: 15, contradicted: 20 },\n  promiseMissedBelow: 0.5,\n  caps: { stale: 60, unverified: 70 },\n  staleHours: 48,\n  /**\n   * The listing floor. Market cap never changes a score; it only decides whether a project is on the board. A\n   * project joins at `floorUsd` and leaves under `floorUsd × leaveAt`, so one hovering at the line does not flicker.\n   */\n  listing: { floorUsd: 25_000, leaveAt: 0.8 },\n} as const;\n\nexport type ComponentKey = keyof typeof RULES.weights;\nexport type FlagKey = \"product_down\" | \"promise_missed\" | \"contradicted\" | \"stale\";\n\n/** One UTC day of probe runs for one claim. */\nexport interface ProbeDay {\n  date: string;\n  runs: number;\n  passes: number;\n}\n\nexport interface ClaimObs {\n  id: string;\n  /** False when the claim has no probe: it cannot be checked from outside. */\n  tested: boolean;\n  /** Ascending by date. Empty for an untested claim. */\n  days: ProbeDay[];\n}\n\nexport interface PromiseObs {\n  id: string;\n  /** 0..1: how much of the promise was kept. null = cannot be measured yet. */\n  ratio: number | null;\n}\n\nexport type Liquidity = \"locked\" | \"unlocked\" | \"unknown\";\n\nexport interface TokenObs {\n  liquidity: Liquidity;\n  /** Share of supply held by disclosed team, deployer and fee wallets. 0.034 = 3.4%. null = not read. */\n  insiderShare: number | null;\n  /** Share held by the ten largest holders, leaving out pools, burn addresses and insiders. null = not read. */\n  top10Share: number | null;\n  /** Buy tax plus sell tax. 0.06 = 3% + 3%. null = not known. */\n  taxTotal: number | null;\n}\n\nexport interface ProjectInputs {\n  claims: ClaimObs[];\n  promises: PromiseObs[];\n  token: TokenObs;\n  holders: number | null;\n  disclosure: { id: string; met: boolean }[];\n  /** Public statements contradicted by the chain. */\n  contradicted: string[];\n  ageHours: number;\n  /** Hours since the token launched (its launch transaction's block time). */\n  hoursSinceLaunch: number;\n  linkage: Linkage;\n}\n\nexport interface Component {\n  key: ComponentKey;\n  weight: number;\n  score: number;\n  points: number;\n}\n\nexport interface Flag {\n  key: FlagKey;\n  penalty: number;\n  cap: number | null;\n  /** The claim, promise or statement ids that triggered it. */\n  on: string[];\n}\n\nexport interface ClaimResult {\n  id: string;\n  tested: boolean;\n  runs: number;\n  passes: number;\n  /** passes ÷ runs in the window; 0 when untested or never run. */\n  rate: number;\n  verified: boolean;\n  down: boolean;\n  /** The window's probe days, for the strip on the project page. */\n  days: ProbeDay[];\n}\n\nexport interface Metrics {\n  probeDays: number;\n  /** Hours since the token launched. A project is scored from RULES.minHoursSinceLaunch on. */\n  hoursSinceLaunch: number;\n  windowStart: string | null;\n  windowEnd: string | null;\n  claims: number;\n  claimsTested: number;\n  claimsVerified: number;\n  /** Passes ÷ runs across every tested claim. null when nothing has run. */\n  uptime: number | null;\n  promises: number;\n  promisesMeasured: number;\n  /** Average ratio of the measured promises. null when none is measured. */\n  promisesKept: number | null;\n  safety: { liquidity: number; insiders: number | null; concentration: number | null; tax: number | null };\n  holders: number | null;\n  disclosed: number;\n  disclosureItems: number;\n  ageHours: number;\n}\n\nexport interface ProjectCard {\n  status: Status;\n  unverified: boolean;\n  score: number | null;\n  grade: Grade | null;\n  /** Scored, but on checks from fewer than RULES.earlyBelowDays UTC days. A label only: the score is the same. */\n  early: boolean;\n  base: number | null;\n  components: Component[];\n  flags: Flag[];\n  capsApplied: { key: \"stale\" | \"unverified\"; cap: number }[];\n  metrics: Metrics;\n  claims: ClaimResult[];\n  /** Probe runs per day across all tested claims, for the uptime strip. */\n  days: ProbeDay[];\n}\n\n/** 100 at `full` or better, 0 at `zero` or worse, a straight line between. Works whichever way round they are. */\nexport const ramp = (x: number, full: number, zero: number) => clamp((100 * (x - zero)) / (full - zero), 0, 100);\n\nexport const scoreInsiders = (share: number) => ramp(share, RULES.safety.insiders.full, RULES.safety.insiders.zero);\nexport const scoreConcentration = (share: number) => ramp(share, RULES.safety.concentration.full, RULES.safety.concentration.zero);\nexport const scoreTax = (total: number) => ramp(total, RULES.safety.tax.full, RULES.safety.tax.zero);\n/** Log scale: 50 holders or fewer → 0, 5,000 or more → 100. */\nexport const scoreAdoption = (holders: number | null) =>\n  !holders || holders <= 0 ? 0 : ramp(Math.log10(holders), Math.log10(RULES.adoption.full), Math.log10(RULES.adoption.zero));\n\n/** The four token readings as one number: a weighted average over the readings that are available. */\nexport function scoreSafety(token: TokenObs): { score: number; parts: Metrics[\"safety\"] } {\n  const w = RULES.safety.weights;\n  const parts: Metrics[\"safety\"] = {\n    liquidity: RULES.safety.liquidity[token.liquidity],\n    insiders: token.insiderShare === null ? null : scoreInsiders(token.insiderShare),\n    concentration: token.top10Share === null ? null : scoreConcentration(token.top10Share),\n    tax: token.taxTotal === null ? null : scoreTax(token.taxTotal),\n  };\n  let sum = 0;\n  let weight = 0;\n  for (const k of Object.keys(w) as (keyof typeof w)[]) {\n    const v = parts[k];\n    if (v === null) continue;\n    sum += w[k] * v;\n    weight += w[k];\n  }\n  return { score: weight ? sum / weight : 0, parts };\n}\n\nconst sum = (xs: number[]) => xs.reduce((a, b) => a + b, 0);\n\n/** Grade one project for one day. */\nexport function scoreProject(input: ProjectInputs): ProjectCard {\n  const unverified = input.linkage !== \"verified\";\n\n  // The window: the last 30 UTC days on which any probe ran.\n  const allDates = [...new Set(input.claims.flatMap((c) => c.days.filter((d) => d.runs > 0).map((d) => d.date)))].sort();\n  const window = new Set(allDates.slice(-RULES.windowDays));\n\n  const claims: ClaimResult[] = input.claims.map((c) => {\n    const days = c.days.filter((d) => window.has(d.date) && d.runs > 0).sort((a, b) => a.date.localeCompare(b.date));\n    const runs = sum(days.map((d) => d.runs));\n    const passes = sum(days.map((d) => d.passes));\n    const rate = c.tested && runs ? passes / runs : 0;\n    const lastTwo = days.slice(-2);\n    return { id: c.id, tested: c.tested, runs, passes, rate, verified: c.tested && runs > 0 && rate >= RULES.verifiedAt, down: c.tested && lastTwo.length === 2 && lastTwo.every((d) => d.passes === 0), days };\n  });\n\n  const days: ProbeDay[] = [...window].map((date) => {\n    const on = claims.flatMap((c) => c.days.filter((d) => d.date === date));\n    return { date, runs: sum(on.map((d) => d.runs)), passes: sum(on.map((d) => d.passes)) };\n  });\n\n  const measured = input.promises.filter((p): p is PromiseObs & { ratio: number } => p.ratio !== null);\n  const promisesKept = measured.length ? sum(measured.map((p) => clamp(p.ratio, 0, 1))) / measured.length : null;\n  const safety = scoreSafety(input.token);\n  const totalRuns = sum(claims.map((c) => c.runs));\n  const met = input.disclosure.filter((d) => d.met).length;\n\n  const metrics: Metrics = {\n    probeDays: allDates.length,\n    hoursSinceLaunch: input.hoursSinceLaunch,\n    windowStart: days[0]?.date ?? null,\n    windowEnd: days[days.length - 1]?.date ?? null,\n    claims: claims.length,\n    claimsTested: claims.filter((c) => c.tested).length,\n    claimsVerified: claims.filter((c) => c.verified).length,\n    uptime: totalRuns ? sum(claims.map((c) => c.passes)) / totalRuns : null,\n    promises: input.promises.length,\n    promisesMeasured: measured.length,\n    promisesKept,\n    safety: safety.parts,\n    holders: input.holders,\n    disclosed: met,\n    disclosureItems: input.disclosure.length,\n    ageHours: input.ageHours,\n  };\n\n  const parts: Record<ComponentKey, number> = {\n    product: claims.length ? (100 * sum(claims.map((c) => c.rate))) / claims.length : 0,\n    promises: promisesKept === null ? RULES.noPromiseScore : 100 * promisesKept,\n    safety: safety.score,\n    adoption: scoreAdoption(input.holders),\n    disclosure: input.disclosure.length ? (100 * met) / input.disclosure.length : 0,\n    fresh: scoreFreshness(input.ageHours),\n  };\n  const components: Component[] = (Object.keys(parts) as ComponentKey[]).map((key) => ({ key, weight: RULES.weights[key], score: parts[key], points: RULES.weights[key] * parts[key] }));\n  const base = sum(components.map((c) => c.points));\n\n  // Launched less than 48 hours ago, or never checked: the readings so far are shown, but there is no score, no flags and no rank.\n  if (!allDates.length || input.hoursSinceLaunch < RULES.minHoursSinceLaunch) {\n    return { status: \"too_new\", unverified, score: null, grade: null, early: false, base: null, components, flags: [], capsApplied: [], metrics, claims, days };\n  }\n\n  const flags: Flag[] = [];\n  const down = claims.filter((c) => c.down).map((c) => c.id);\n  if (down.length) flags.push({ key: \"product_down\", penalty: RULES.penalties.product_down, cap: null, on: down });\n  const missed = measured.filter((p) => p.ratio < RULES.promiseMissedBelow).map((p) => p.id);\n  if (missed.length) flags.push({ key: \"promise_missed\", penalty: RULES.penalties.promise_missed, cap: null, on: missed });\n  if (input.contradicted.length) flags.push({ key: \"contradicted\", penalty: RULES.penalties.contradicted, cap: null, on: input.contradicted });\n  const stale = input.ageHours >= RULES.staleHours;\n  if (stale) flags.push({ key: \"stale\", penalty: 0, cap: RULES.caps.stale, on: [] });\n\n  let s = clamp(base - sum(flags.map((f) => f.penalty)), 0, 100);\n  const capsApplied: ProjectCard[\"capsApplied\"] = [];\n  if (stale && s > RULES.caps.stale) {\n    s = RULES.caps.stale;\n    capsApplied.push({ key: \"stale\", cap: RULES.caps.stale });\n  }\n  if (unverified && s > RULES.caps.unverified) {\n    s = RULES.caps.unverified;\n    capsApplied.push({ key: \"unverified\", cap: RULES.caps.unverified });\n  }\n  const score = Math.round(s);\n  const status: Status = stale ? \"stale\" : flags.some((f) => f.penalty > 0) ? \"flagged\" : unverified ? \"unverified\" : \"verified\";\n\n  return { status, unverified, score, grade: gradeOf(score), early: allDates.length < RULES.earlyBelowDays, base, components, flags, capsApplied, metrics, claims, days };\n}\n\n/** Board order: by score, then the unrounded sum, then product score. Too-new projects are left out. */\nexport function rank<T extends { card: ProjectCard; slug: string }>(projects: T[]): T[] {\n  const product = (c: ProjectCard) => c.components.find((x) => x.key === \"product\")?.score ?? 0;\n  return projects\n    .filter((p) => p.card.score !== null)\n    .sort((a, b) => b.card.score! - a.card.score! || (b.card.base ?? 0) - (a.card.base ?? 0) || product(b.card) - product(a.card) || a.slug.localeCompare(b.slug));\n}\n\n/**\n * How much of a \"share of fees to buyback and burn\" promise was kept. `income` is fee income in the window, `spent`\n * what was spent buying the token, `bought` and `burned` token amounts. A buyback counts only to the extent the\n * bought tokens were burned. Returns null when there was no fee income, so nothing was owed.\n */\nexport function buybackBurnRatio(share: number, income: number, spent: number, bought: number, burned: number): number | null {\n  const owed = share * income;\n  if (!(owed > 0)) return null;\n  const burnedPart = bought > 0 ? Math.min(1, burned / bought) : 0;\n  return clamp((spent * burnedPart) / owed, 0, 1);\n}\n\n/**\n * Whether a project is on the board, given whether it was before and its market cap now. A project with no market\n * reading stays where it was, and a new one starts on the board: a missing price is not evidence of a dead project.\n */\nexport function onBoard(was: boolean | null, mcapUsd: number | null): boolean {\n  if (mcapUsd === null || !Number.isFinite(mcapUsd)) return was ?? true;\n  if (mcapUsd >= RULES.listing.floorUsd) return true;\n  if (mcapUsd < RULES.listing.floorUsd * RULES.listing.leaveAt) return false;\n  return was ?? false;\n}\n"},{"path":"src/engine/score.ts","role":"Shared helpers the scoring function uses: clamping, grade bands and freshness.","lines":215,"sha256":"9ae87f8448859b3d49fc7b39a059df5618bfd3521b91a5448951b0278584db30","content":"import type { Component, ComponentKey, DayPoint, DeskInputs, Flag, Grade, Metrics, Scorecard, SeriesPoint, Status } from \"./types.ts\";\n\n/** Every constant in docs/scoring.md, in one place. Change the rulebook and this object together. */\nexport const RULES = {\n  minPrevEquity: 100,\n  minValidDays: 7,\n  windowDays: 30,\n  weights: { ret: 0.25, dd: 0.2, lev: 0.15, hon: 0.25, con: 0.1, fresh: 0.05 } satisfies Record<ComponentKey, number>,\n  ret: { mid: 50, slope: 250 },\n  ddZero: 0.3,\n  avgLev: { free: 1, span: 9 },\n  peakLev: { free: 2, span: 18 },\n  levMix: { avg: 0.6, peak: 0.4 },\n  noPolicyHonesty: 40,\n  sortino: { mid: 50, slope: 16.67 },\n  consistency: { win: 40, sortino: 0.6 },\n  fresh: { full: 6, zero: 48 },\n  spike: { peak: 15, avg: 2, ratio: 3 },\n  penalties: { leverage_spike: 10, missed_buyback: 15, false_claim: 20 },\n  missedBuybackBelow: 0.5,\n  caps: { stale: 60, unverified: 70 },\n  grades: [\n    { grade: \"A\", min: 85 },\n    { grade: \"B\", min: 70 },\n    { grade: \"C\", min: 55 },\n    { grade: \"D\", min: 40 },\n    { grade: \"F\", min: 0 },\n  ] as { grade: Grade; min: number }[],\n} as const;\n\nexport const clamp = (x: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, x));\nconst mean = (xs: number[]) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);\n\nexport function gradeOf(score: number): Grade {\n  for (const g of RULES.grades) if (score >= g.min) return g.grade;\n  return \"F\";\n}\n\n/** 0% → 50, +20% caps at 100, −20% floors at 0. */\nexport const scoreReturn = (twr: number) => clamp(RULES.ret.mid + RULES.ret.slope * twr, 0, 100);\n/** 0% drawdown → 100; 30% zeros it. */\nexport const scoreDrawdown = (mdd: number) => clamp(100 * (1 - mdd / RULES.ddZero), 0, 100);\n/** 1× or below → 100; 10× average → 0. */\nexport const scoreAvgLev = (avg: number) => clamp(100 * (1 - Math.max(0, avg - RULES.avgLev.free) / RULES.avgLev.span), 0, 100);\n/** 2× or below → 100; 20× peak → 0. */\nexport const scorePeakLev = (peak: number) => clamp(100 * (1 - Math.max(0, peak - RULES.peakLev.free) / RULES.peakLev.span), 0, 100);\n/** Annualized Sortino +3 → 100, −3 → 0. null = no down days (+∞). */\nexport const scoreSortino = (sortino: number | null) =>\n  sortino === null ? 100 : clamp(RULES.sortino.mid + RULES.sortino.slope * sortino, 0, 100);\n/** ≤ 6 h → 100, ≥ 48 h → 0, a straight line between. */\nexport const scoreFreshness = (ageHours: number) =>\n  ageHours <= RULES.fresh.full\n    ? 100\n    : ageHours >= RULES.fresh.zero\n      ? 0\n      : (100 * (RULES.fresh.zero - ageHours)) / (RULES.fresh.zero - RULES.fresh.full);\n\ninterface ValidDay {\n  point: DayPoint;\n  prev: DayPoint;\n  ret: number;\n}\n\n/** A day counts only if the point before it had at least $100 of equity. */\nexport function validDays(days: DayPoint[]): ValidDay[] {\n  const out: ValidDay[] = [];\n  for (let i = 1; i < days.length; i++) {\n    const prev = days[i - 1];\n    const point = days[i];\n    if (!(prev.equity >= RULES.minPrevEquity)) continue;\n    out.push({ point, prev, ret: (point.equity - prev.equity - point.flow) / prev.equity });\n  }\n  return out;\n}\n\n/** Score one desk for one day. Pure: same inputs, same scorecard. */\nexport function scoreDesk(input: DeskInputs): Scorecard {\n  const all = validDays(input.days);\n  const window = all.slice(-RULES.windowDays);\n  const unverified = input.linkage !== \"verified\";\n  const last = input.days[input.days.length - 1];\n\n  // NAV, drawdown and the per-day series.\n  const series: SeriesPoint[] = [];\n  let nav = 1;\n  let peak = 1;\n  let mdd = 0;\n  for (const d of window) {\n    nav *= 1 + d.ret;\n    peak = Math.max(peak, nav);\n    const drawdown = 1 - nav / peak;\n    mdd = Math.max(mdd, drawdown);\n    const lev = d.point.notional !== null && d.point.equity > 0 ? d.point.notional / d.point.equity : null;\n    series.push({ date: d.point.date, ret: d.ret, nav, drawdown, equity: d.point.equity, flow: d.point.flow, lev, source: d.point.source });\n  }\n  const twr = nav - 1;\n  const rets = window.map((d) => d.ret);\n\n  // Leverage: only days where it was observed and equity was positive.\n  const levs = series.map((s) => s.lev).filter((x): x is number => x !== null);\n  const avgLev = levs.length ? mean(levs) : null;\n  const peakLev = levs.length ? Math.max(...levs) : null;\n  const negativeEquity = window.some((d) => d.point.notional !== null && d.point.equity <= 0);\n\n  // Dollar profit, flows removed. Not the same thing as TWR.\n  const flowsUsd = window.reduce((a, d) => a + d.point.flow, 0);\n  const profitUsd = window.length ? window[window.length - 1].point.equity - window[0].prev.equity - flowsUsd : 0;\n\n  const falseClaim = input.profitClaimed && profitUsd < 0;\n  const owedUsd = input.promisedShare === null ? null : Math.max(0, input.promisedShare * profitUsd);\n  let honesty: number | null;\n  if (falseClaim) honesty = 0;\n  else if (owedUsd === null) honesty = null;\n  else if (owedUsd > 0) honesty = Math.min(1, input.buybackUsd / owedUsd);\n  else honesty = 1;\n  const overBuyback = owedUsd !== null && owedUsd > 0 && input.buybackUsd > owedUsd;\n\n  // Consistency.\n  const mu = mean(rets);\n  const downside = Math.sqrt(mean(rets.map((r) => Math.min(r, 0) ** 2)));\n  const sortino = downside === 0 ? null : (Math.sqrt(365) * mu) / downside;\n  const winRate = rets.length ? rets.filter((r) => r > 0).length / rets.length : 0;\n\n  const metrics: Metrics = {\n    validDays: all.length,\n    windowStart: window.length ? window[0].point.date : null,\n    windowEnd: window.length ? window[window.length - 1].point.date : null,\n    twr,\n    mdd,\n    avgLev,\n    peakLev,\n    levDays: levs.length,\n    profitUsd,\n    flowsUsd,\n    owedUsd,\n    buybackUsd: input.buybackUsd,\n    honesty,\n    winRate,\n    sortino,\n    ageHours: input.ageHours,\n    equityUsd: last ? last.equity : 0,\n  };\n\n  // Fewer than 7 valid days: no composite, unranked.\n  if (all.length < RULES.minValidDays) {\n    return { status: \"too_new\", unverified, score: null, grade: null, base: null, components: [], flags: [], capsApplied: [], overBuyback, metrics, series };\n  }\n\n  const sAvg = avgLev === null ? null : scoreAvgLev(avgLev);\n  const sPeak = peakLev === null ? null : scorePeakLev(peakLev);\n  // With no leverage observation at all the component cannot be computed; the pipeline always snapshots before it\n  // scores, so this is a guard, not a path. It scores 0 rather than handing out free points.\n  const sLev = sAvg === null || sPeak === null ? 0 : RULES.levMix.avg * sAvg + RULES.levMix.peak * sPeak;\n  const sHon = falseClaim ? 0 : honesty === null ? RULES.noPolicyHonesty : 100 * honesty;\n  const sCon = clamp(RULES.consistency.win * winRate + RULES.consistency.sortino * scoreSortino(sortino), 0, 100);\n\n  const parts: Record<ComponentKey, number> = {\n    ret: scoreReturn(twr),\n    dd: scoreDrawdown(mdd),\n    lev: sLev,\n    hon: sHon,\n    con: sCon,\n    fresh: scoreFreshness(input.ageHours),\n  };\n  const components: Component[] = (Object.keys(parts) as ComponentKey[]).map((key) => ({\n    key,\n    weight: RULES.weights[key],\n    score: parts[key],\n    points: RULES.weights[key] * parts[key],\n  }));\n  const base = components.reduce((a, c) => a + c.points, 0);\n\n  const flags: Flag[] = [];\n  if (peakLev !== null && avgLev !== null && (peakLev >= RULES.spike.peak || (avgLev >= RULES.spike.avg && peakLev >= RULES.spike.ratio * avgLev)))\n    flags.push({ key: \"leverage_spike\", penalty: RULES.penalties.leverage_spike, cap: null });\n  if (!falseClaim && owedUsd !== null && owedUsd > 0 && honesty !== null && honesty < RULES.missedBuybackBelow)\n    flags.push({ key: \"missed_buyback\", penalty: RULES.penalties.missed_buyback, cap: null });\n  if (falseClaim) flags.push({ key: \"false_claim\", penalty: RULES.penalties.false_claim, cap: null });\n  if (negativeEquity) flags.push({ key: \"negative_equity\", penalty: 0, cap: null });\n  const stale = input.ageHours >= RULES.fresh.zero;\n  if (stale) flags.push({ key: \"stale\", penalty: 0, cap: RULES.caps.stale });\n\n  let s = clamp(base - flags.reduce((a, f) => a + f.penalty, 0), 0, 100);\n  const capsApplied: Scorecard[\"capsApplied\"] = [];\n  if (stale && s > RULES.caps.stale) {\n    s = RULES.caps.stale;\n    capsApplied.push({ key: \"stale\", cap: RULES.caps.stale });\n  }\n  if (unverified && s > RULES.caps.unverified) {\n    s = RULES.caps.unverified;\n    capsApplied.push({ key: \"unverified\", cap: RULES.caps.unverified });\n  }\n  const score = Math.round(s);\n\n  // Too new > Stale > Flagged > Verified or Unverified.\n  const penalised = flags.some((f) => f.penalty > 0);\n  const status: Status = stale ? \"stale\" : penalised ? \"flagged\" : unverified ? \"unverified\" : \"verified\";\n\n  return { status, unverified, score, grade: gradeOf(score), base, components, flags, capsApplied, overBuyback, metrics, series };\n}\n\n/** Board order: scored desks by score, ties broken by return then lower drawdown; too-new desks are left out. */\nexport function rank<T extends { card: Scorecard; slug: string }>(desks: T[]): T[] {\n  return desks\n    .filter((d) => d.card.score !== null)\n    .sort(\n      (a, b) =>\n        b.card.score! - a.card.score! ||\n        (b.card.base ?? 0) - (a.card.base ?? 0) ||\n        b.card.metrics.twr - a.card.metrics.twr ||\n        a.card.metrics.mdd - b.card.metrics.mdd ||\n        a.slug.localeCompare(b.slug),\n    );\n}\n"},{"path":"src/engine/types.ts","role":"Shared types: grades, statuses and linkage.","lines":121,"sha256":"f8409139e61f6b0c112a0733fe03313a3fb3414fc1172236f97daed2a514fdb0","content":"/**\n * Sentinel's scoring types. The rules live in docs/scoring.md; this folder is their implementation and has no\n * I/O: every function here takes plain numbers and returns plain numbers, so anyone can re-run a published score.\n */\n\n/** Where a day's numbers came from. `backfill` = rebuilt from Hyperliquid's own portfolio history, not our snapshot. */\nexport type DaySource = \"snapshot\" | \"backfill\" | \"example\";\n\n/** One point per desk per UTC day. */\nexport interface DayPoint {\n  /** UTC day, YYYY-MM-DD. */\n  date: string;\n  /** E_t: account value in USD at the snapshot. */\n  equity: number;\n  /** F_t: net external flow in USD since the previous point. Positive = net deposit. */\n  flow: number;\n  /** N_t: gross position notional in USD, or null when it was not observed (backfilled days). */\n  notional: number | null;\n  source: DaySource;\n}\n\nexport type Linkage = \"verified\" | \"unverified\";\n\nexport interface DeskInputs {\n  /** Ascending by date. */\n  days: DayPoint[];\n  /** B: USD spent on buybacks (or burned) from the disclosed wallet, inside the window. */\n  buybackUsd: number;\n  /** π: published buyback share of profit, 0..1. null = no published policy. */\n  promisedShare: number | null;\n  /** The desk publicly claimed a profit inside the window. */\n  profitClaimed: boolean;\n  /** Hours since the last successful snapshot of every source. */\n  ageHours: number;\n  linkage: Linkage;\n}\n\nexport type ComponentKey = \"ret\" | \"dd\" | \"lev\" | \"hon\" | \"con\" | \"fresh\";\n\nexport interface Component {\n  key: ComponentKey;\n  /** 0..1, sums to 1 across the six components. */\n  weight: number;\n  /** 0..100. */\n  score: number;\n  /** weight × score: this component's points in the composite. */\n  points: number;\n}\n\nexport type FlagKey = \"leverage_spike\" | \"missed_buyback\" | \"false_claim\" | \"stale\" | \"negative_equity\";\n\nexport interface Flag {\n  key: FlagKey;\n  /** Points taken off the composite (0 when the flag only caps or informs). */\n  penalty: number;\n  /** A cap on the published score, if this flag sets one. */\n  cap: number | null;\n}\n\nexport type Status = \"too_new\" | \"stale\" | \"flagged\" | \"verified\" | \"unverified\";\nexport type Grade = \"A\" | \"B\" | \"C\" | \"D\" | \"F\";\n\nexport interface Metrics {\n  /** Days that count: each has a previous point with equity of at least $100. */\n  validDays: number;\n  windowStart: string | null;\n  windowEnd: string | null;\n  /** Flow-adjusted time-weighted return over the window. 0.186 = +18.6%. */\n  twr: number;\n  /** Max drawdown on NAV over the window. 0.041 = 4.1%. */\n  mdd: number;\n  avgLev: number | null;\n  peakLev: number | null;\n  /** How many window days had an observed leverage. */\n  levDays: number;\n  /** P: dollar profit over the window, flows removed. */\n  profitUsd: number;\n  /** Net external flow over the window. */\n  flowsUsd: number;\n  /** B*: buyback owed = max(0, π × P). null when no policy is published. */\n  owedUsd: number | null;\n  buybackUsd: number;\n  /** H, 0..1. null when no policy is published. */\n  honesty: number | null;\n  winRate: number;\n  /** Annualized Sortino. null when there were no down days (treated as +∞). */\n  sortino: number | null;\n  ageHours: number;\n  equityUsd: number;\n}\n\nexport interface SeriesPoint {\n  date: string;\n  ret: number;\n  nav: number;\n  drawdown: number;\n  equity: number;\n  flow: number;\n  lev: number | null;\n  source: DaySource;\n}\n\nexport interface Scorecard {\n  status: Status;\n  /** True when wallet linkage is not verified, whatever the status shows. */\n  unverified: boolean;\n  /** Published score, a whole number 0..100. null when the desk is too new to score. */\n  score: number | null;\n  grade: Grade | null;\n  /** The weighted sum before penalties and caps. */\n  base: number | null;\n  components: Component[];\n  flags: Flag[];\n  /** Caps that actually lowered the score, in the order applied. */\n  capsApplied: { key: \"stale\" | \"unverified\"; cap: number }[];\n  /** B was larger than B*: noted, never scored above 100. */\n  overBuyback: boolean;\n  metrics: Metrics;\n  series: SeriesPoint[];\n}\n"},{"path":"src/engine/report.ts","role":"The daily report's canonical form and its sha256 hash.","lines":29,"sha256":"8c69c2a7d1bcf9c7191eb5a5e93e399d5b795cbf8957b2218c9e1d44d0025ab7","content":"import { createHash } from \"node:crypto\";\n\n/**\n * The daily report is what gets committed on-chain as a hash. Canonical form: keys sorted, numbers rounded to 8\n * decimals, no whitespace. Two honest runs over the same inputs must produce the same bytes.\n */\nexport function canonical(value: unknown): string {\n  if (value === null || value === undefined) return \"null\";\n  if (typeof value === \"number\") {\n    if (!Number.isFinite(value)) return \"null\";\n    const r = Math.round(value * 1e8) / 1e8;\n    return Object.is(r, -0) ? \"0\" : String(r);\n  }\n  if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n  if (typeof value === \"string\") return JSON.stringify(value);\n  if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n  const obj = value as Record<string, unknown>;\n  return `{${Object.keys(obj)\n    .filter((k) => obj[k] !== undefined)\n    .sort()\n    .map((k) => `${JSON.stringify(k)}:${canonical(obj[k])}`)\n    .join(\",\")}}`;\n}\n\n/** sha256 of the canonical bytes, as 0x + 64 hex: fits a bytes32. */\nexport function reportHash(report: unknown): `0x${string}` {\n  return `0x${createHash(\"sha256\").update(canonical(report)).digest(\"hex\")}`;\n}\n"},{"path":"src/server/pipeline.ts","role":"What is read and stored for each project, how readings become scoring inputs (inputsFor), and how the daily report is built.","lines":427,"sha256":"825d76a35b12cd894f418a6a95d9bb319a7fbe4d727fd8b4e57c94a8636b590c","content":"import { buybackBurnRatio, onBoard, RULES, scoreProject, type ProbeDay, type ProjectCard, type ProjectInputs } from \"../engine/project.ts\";\nimport { reportHash } from \"../engine/report.ts\";\nimport { balanceOf, concentration, feeFlows, holderCount, sourceVerified, topHolders, totalSupply, walletHistory, type FeeFlows, type HolderShare } from \"../sources/elysium.ts\";\nimport { readTx, recordsOf, splitRatio, type ReadBudget } from \"../sources/chain-checks.ts\";\nimport { utcDay } from \"../sources/hyperliquid.ts\";\nimport { liquidityOf } from \"../lib/liquidity.ts\";\nimport { readLaunchLiquidity, type LiquidityFacts } from \"../sources/liquidity.ts\";\nimport { fetchHypeUsd, fetchTokenMarket } from \"../sources/market.ts\";\nimport { readJson, runProbe, type ProbeResult } from \"../sources/probes.ts\";\nimport { DISCLOSURE, type MoneyPromise, type Project } from \"./registry.ts\";\nimport { store } from \"./store.ts\";\n\n/** What the chain says about a project's token. */\nexport interface TokenFacts {\n  supply: number;\n  /** At the burn address or the zero address. */\n  burned: number;\n  holders: number;\n  /** The project's disclosed wallets and what they hold. */\n  insiders: { label: string; address: string; balance: number; share: number }[];\n  insiderShare: number;\n  /** The ten largest ordinary holders. */\n  top: HolderShare[];\n  top10Share: number;\n  sourceVerified: boolean;\n  /** The launch liquidity, read from the chain (src/sources/liquidity.ts). Missing on reads from before it existed. */\n  liquidity?: LiquidityFacts;\n  readAt: number;\n}\n\n/** A fee wallet's last 30 days, sorted into income, buybacks and burns. */\nexport interface FeeFacts extends FeeFlows {\n  wallet: string;\n  since: number;\n  /** False if the wallet's history was longer than Sentinel reads. */\n  complete: boolean;\n  readAt: number;\n}\n\n/** A market reading. Never scored: it only decides whether the project is on the board. */\nexport interface MarketFacts {\n  priceHype: number;\n  hypeUsd: number;\n  /** Price × supply net of burns, in dollars. */\n  mcapUsd: number;\n  volumeHype: number;\n  readAt: number;\n}\n\n/** A promised share of fee income, measured on chain: fee income in, verified payments out (src/sources/chain-checks.ts). */\nexport interface SplitFacts {\n  wallet: string;\n  /** The window: the last 30 days, or from the oldest entry in the project's own list if that is later. */\n  since: number;\n  /** HYPE the fee sources paid the wallet in the window. */\n  incomeHype: number;\n  /** HYPE the wallet paid in the window, in the listed payments that Elysium confirms. */\n  paidHype: number;\n  /** Listed payments Elysium confirms, and listed payments it does not (wrong sender, failed, not found). */\n  payments: number;\n  unconfirmed: number;\n  readAt: number;\n}\n\n/** Everything Sentinel has observed about one project. */\nexport interface ProjectDoc {\n  slug: string;\n  /** The latest market reading, or null before the first one. */\n  market: MarketFacts | null;\n  /** Whether the project is on the board (the listing floor). null before the first market reading. */\n  listed: boolean | null;\n  /** When the first probe ran, ms. Missing on documents from before it was recorded (see firstCheckOf). */\n  firstCheckAt?: number;\n  /** Probe runs per claim, one row per UTC day, ascending. */\n  probes: Record<string, ProbeDay[]>;\n  /** Each claim's most recent probe run. */\n  last: Record<string, ProbeResult & { at: number }>;\n  token: TokenFacts | null;\n  /** By wallet address, lower case. */\n  fees: Record<string, FeeFacts>;\n  /** Promised shares of income, by promise id. Missing on documents from before they were measured. */\n  splits?: Record<string, SplitFacts>;\n  /** When every chain read last succeeded, ms. */\n  refreshedAt: number;\n  /** What went wrong on the latest refresh, if anything. */\n  errors: string[];\n}\n\nconst DAY = 86_400_000;\nexport const emptyDoc = (slug: string): ProjectDoc => ({ slug, market: null, listed: null, probes: {}, last: {}, token: null, fees: {}, refreshedAt: 0, errors: [] });\nexport const loadProject = async (slug: string) => ({ ...emptyDoc(slug), ...((await store().get<ProjectDoc>(`project.${slug}`)) ?? {}) });\n\n/** Add one round of probe results to the document. Pure. */\nexport function applyProbes(doc: ProjectDoc, results: Record<string, ProbeResult>, now: number): ProjectDoc {\n  const today = utcDay(now);\n  const probes = { ...doc.probes };\n  const last = { ...doc.last };\n  for (const [id, r] of Object.entries(results)) {\n    // Nothing judged this run (its chain reads are queued): not a run, so neither a pass nor a failure.\n    if (r.skipped) continue;\n    const days = [...(probes[id] ?? [])];\n    const at = days.findIndex((d) => d.date === today);\n    const row = at < 0 ? { date: today, runs: 0, passes: 0 } : { ...days[at] };\n    row.runs += 1;\n    row.passes += r.ok ? 1 : 0;\n    if (at < 0) days.push(row);\n    else days[at] = row;\n    // A year of days is far more than any window needs.\n    probes[id] = days.sort((a, b) => a.date.localeCompare(b.date)).slice(-400);\n    last[id] = { ...r, at: now };\n  }\n  return { ...doc, firstCheckAt: firstCheckOf(doc) ?? now, probes, last };\n}\n\n/**\n * When a project was first checked. Documents written before this was recorded only know the UTC day of their first\n * checks, so for them the clock starts at the end of that day: never earlier than the real first check, so the wait\n * before a score is never shortened. Pure.\n */\nexport function firstCheckOf(doc: Pick<ProjectDoc, \"firstCheckAt\" | \"probes\">): number | null {\n  if (doc.firstCheckAt) return doc.firstCheckAt;\n  const first = Object.values(doc.probes)\n    .flat()\n    .filter((d) => d.runs > 0)\n    .map((d) => d.date)\n    .sort()[0];\n  return first ? Date.parse(`${first}T00:00:00Z`) + DAY : null;\n}\n\n/**\n * The wallets whose holdings count as insider holdings: the ones the project publishes, plus the wallet that\n * launched the token when the listing records it. One entry per address; a published label wins.\n */\nexport function insiderWallets(project: Project): { label: string; address: string }[] {\n  const out = project.wallets.map((w) => ({ label: w.label, address: w.address.toLowerCase() }));\n  const creator = project.creator?.toLowerCase();\n  if (creator && !out.some((w) => w.address === creator)) out.push({ label: \"Token creator (from the launch transaction)\", address: creator });\n  return out;\n}\n\nexport async function readToken(project: Project, now: number): Promise<TokenFacts> {\n  const supply = await totalSupply(project.token);\n  const burned = (await balanceOf(project.token, \"0x000000000000000000000000000000000000dEaD\")) + (await balanceOf(project.token, \"0x0000000000000000000000000000000000000000\"));\n  const live = Math.max(1, supply - burned);\n  const insiders = [];\n  for (const w of insiderWallets(project)) {\n    const balance = await balanceOf(project.token, w.address);\n    insiders.push({ label: w.label, address: w.address, balance, share: balance / live });\n  }\n  const holders = await holderCount(project.token);\n  const { top, top10Share } = concentration(await topHolders(project.token), { supply, burned, exclude: [...project.pools, ...insiders.map((w) => w.address)] });\n  const liquidity = await readLaunchLiquidity(project.pad, project.launchTx, project.token, now);\n  return { supply, burned, holders, insiders, insiderShare: insiders.reduce((a, i) => a + i.share, 0), top, top10Share, sourceVerified: await sourceVerified(project.token), liquidity, readAt: now };\n}\n\nexport async function readFees(project: Project, wallet: string, now: number): Promise<FeeFacts> {\n  const since = now - RULES.windowDays * DAY;\n  const history = await walletHistory(wallet, project.token);\n  const flows = feeFlows(history, { wallet, feeSources: project.feeSources, launchTx: project.launchTx, since });\n  return { ...flows, events: flows.events.slice(0, 40), wallet: wallet.toLowerCase(), since, complete: history.complete, readAt: now };\n}\n\n/**\n * Measure a promised share: fee income the wallet received on chain, against the payments it lists for that share,\n * each confirmed on chain. The window starts at the oldest entry of the project's own list (if later than 30 days\n * ago), so a list that only goes back so far is not read as unpaid. Returns null until every listed payment in the\n * window has been read, so a half-read list is never scored.\n */\nexport async function readSplit(project: Project, p: Extract<MoneyPromise, { kind: \"split\" }>, now: number): Promise<SplitFacts | null> {\n  const data = await readJson(p.payouts.from);\n  const all = recordsOf(data, { ...p.payouts, where: undefined });\n  const mine = recordsOf(data, p.payouts);\n  if (!all || !mine) throw new Error(`no list at \"${p.payouts.path}\"`);\n  const times = all.map((r) => r.time).filter((t): t is number => t !== null);\n  const since = Math.max(now - RULES.windowDays * DAY, times.length ? Math.min(...times) : 0);\n  const wallet = p.wallet.toLowerCase();\n  const budget: ReadBudget = { left: 30 };\n  let paidHype = 0;\n  let payments = 0;\n  let unconfirmed = 0;\n  for (const r of mine) {\n    if (!r.tx || (r.time !== null && r.time < since)) continue;\n    const f = await readTx(r.tx, store(), budget);\n    if (!f) return null;\n    if (f.time < since) continue;\n    if (!f.found || !f.ok || f.from !== wallet) {\n      unconfirmed++;\n      continue;\n    }\n    payments++;\n    paidHype += f.value;\n  }\n  const history = await walletHistory(wallet, project.token);\n  const { incomeHype } = feeFlows(history, { wallet, feeSources: project.feeSources, launchTx: project.launchTx, since });\n  return { wallet, since, incomeHype, paidHype, payments, unconfirmed, readAt: now };\n}\n\n/** Run every probe a project has, once, and save the results. */\nexport async function refreshProbes(project: Project, now = Date.now()): Promise<ProjectDoc> {\n  const results: Record<string, ProbeResult> = {};\n  const before = await loadProject(project.slug);\n  // Chain reads a project's checks may make per run; what is left waits for the next run. Mined transactions are\n  // cached for good, so each one is read once.\n  const budget: ReadBudget = { left: 30 };\n  // One at a time: most of a project's probes hit the same server.\n  for (const claim of project.claims)\n    if (claim.probe) results[claim.id] = await runProbe(claim.probe, { prev: before.last[claim.id]?.seen, cache: store(), budget });\n  const doc = applyProbes(await loadProject(project.slug), results, now);\n  await store().set(`project.${project.slug}`, doc);\n  return doc;\n}\n\n/** Fold one market reading into a document and decide whether the project is on the board. Pure. */\nexport function applyMarket(doc: ProjectDoc, m: { priceHype: number; volumeHype: number; hypeUsd: number }, now: number): ProjectDoc {\n  // Supply net of burns once the token has been read; before that, the launchpads' fixed supply of one billion.\n  const live = doc.token ? Math.max(0, doc.token.supply - doc.token.burned) : 1_000_000_000;\n  const mcapUsd = m.priceHype * live * m.hypeUsd;\n  return { ...doc, market: { priceHype: m.priceHype, hypeUsd: m.hypeUsd, mcapUsd, volumeHype: m.volumeHype, readAt: now }, listed: onBoard(doc.listed, mcapUsd) };\n}\n\n/** Read a project's market cap and save it. A failed read leaves the last reading, and the listing, as they were. */\nexport async function refreshMarket(project: Project, now = Date.now()): Promise<ProjectDoc> {\n  const [market, hypeUsd] = await Promise.all([fetchTokenMarket(project.token), fetchHypeUsd(now)]);\n  const doc = applyMarket(await loadProject(project.slug), { ...market, hypeUsd }, now);\n  await store().set(`project.${project.slug}`, doc);\n  return doc;\n}\n\n/** Read a project's token and fee wallets from Elysium and save the result. */\nexport async function refreshChain(project: Project, now = Date.now()): Promise<ProjectDoc> {\n  const doc = await loadProject(project.slug);\n  const errors: string[] = [];\n  try {\n    doc.token = await readToken(project, now);\n  } catch (e) {\n    errors.push(`token: ${e instanceof Error ? e.message : \"read failed\"}`);\n  }\n  const wallets = [...new Set(project.promises.flatMap((p) => (p.kind === \"buyback_burn\" ? [p.wallet.toLowerCase()] : [])))];\n  for (const wallet of wallets) {\n    try {\n      doc.fees = { ...doc.fees, [wallet]: await readFees(project, wallet, now) };\n    } catch (e) {\n      errors.push(`fee wallet: ${e instanceof Error ? e.message : \"read failed\"}`);\n    }\n  }\n  for (const p of project.promises) {\n    if (p.kind !== \"split\") continue;\n    try {\n      const measured = await readSplit(project, p, now);\n      if (measured) doc.splits = { ...(doc.splits ?? {}), [p.id]: measured };\n    } catch (e) {\n      errors.push(`${p.id}: ${e instanceof Error ? e.message : \"read failed\"}`);\n    }\n  }\n  doc.errors = errors;\n  if (!errors.length) doc.refreshedAt = now;\n  await store().set(`project.${project.slug}`, doc);\n  return doc;\n}\n\n/** Probe a project's claims, then read its token and fee wallets. */\nexport async function refreshProject(project: Project, now = Date.now()): Promise<ProjectDoc> {\n  await refreshProbes(project, now);\n  await refreshChain(project, now);\n  try {\n    return await refreshMarket(project, now);\n  } catch {\n    return loadProject(project.slug);\n  }\n}\n\n/** Chain facts move slowly, so they are re-read when older than this. Freshness is full up to 6 hours. */\nconst CHAIN_MAX_AGE_MS = 2.5 * 3_600_000;\n\n/**\n * One scheduled run over every project. Probes run for all of them at once (they call different servers). Chain\n * reads go one project at a time through shared public services, so each run only re-reads the `chainBudget`\n * projects whose chain facts are oldest; with an hourly run every project is re-read every few hours.\n */\nexport async function refreshAll(projects: Project[], o: { now?: number; chainBudget?: number } = {}): Promise<{ slug: string; probes: string; chain: string }[]> {\n  const now = o.now ?? Date.now();\n  const probed = await Promise.all(\n    projects.map(async (project) => {\n      try {\n        const doc = await refreshProbes(project, now);\n        const ran = project.claims.filter((c) => c.probe);\n        return { project, doc, probes: `${ran.filter((c) => doc.last[c.id]?.ok).length}/${ran.length} passed` };\n      } catch (e) {\n        return { project, doc: null, probes: `failed: ${e instanceof Error ? e.message : \"error\"}` };\n      }\n    }),\n  );\n  // Market caps: one small request per project, one at a time. A failure here changes nothing.\n  for (const { project } of probed) {\n    try {\n      await refreshMarket(project, now);\n    } catch {\n      /* keep the last reading */\n    }\n  }\n  const due = probed\n    .filter((p) => !p.doc || now - p.doc.refreshedAt > CHAIN_MAX_AGE_MS)\n    .sort((a, b) => (a.doc?.refreshedAt ?? 0) - (b.doc?.refreshedAt ?? 0))\n    .slice(0, o.chainBudget ?? 6);\n  const chain = new Map<string, string>();\n  for (const { project } of due) {\n    try {\n      const doc = await refreshChain(project, now);\n      chain.set(project.slug, doc.errors.length ? `incomplete: ${doc.errors.join(\"; \")}` : \"read\");\n    } catch (e) {\n      chain.set(project.slug, `failed: ${e instanceof Error ? e.message : \"error\"}`);\n    }\n  }\n  return probed.map((p) => ({ slug: p.project.slug, probes: p.probes, chain: chain.get(p.project.slug) ?? \"not due\" }));\n}\n\n/** How much of one money promise was kept, from what has been read. null = cannot be measured (yet). */\nexport function promiseRatio(p: MoneyPromise, doc: ProjectDoc): number | null {\n  if (p.kind === \"buyback_burn\") {\n    const f = doc.fees[p.wallet.toLowerCase()];\n    return f ? buybackBurnRatio(p.share, f.incomeHype, f.buybackHype, f.bought, f.burned) : null;\n  }\n  if (p.kind === \"insider_max\") return doc.token ? (doc.token.insiderShare <= p.max ? 1 : 0) : null;\n  if (p.kind === \"split\") {\n    const s = doc.splits?.[p.id];\n    return s ? splitRatio(p.share, s.incomeHype, s.paidHype) : null;\n  }\n  return null;\n}\n\nexport { liquidityOf };\n\n/** The disclosure checklist for a project: five items judged from its pages, one read from the explorer. */\nexport function disclosureOf(project: Project, doc: ProjectDoc): { id: string; met: boolean }[] {\n  return DISCLOSURE.map((id) => ({ id, met: id === \"sourceVerified\" ? !!doc.token?.sourceVerified : !!project.disclosure[id]?.met }));\n}\n\n/** The engine's inputs for a project, as of `now`. */\nexport function inputsFor(project: Project, doc: ProjectDoc, now: number): ProjectInputs {\n  return {\n    claims: project.claims.map((c) => ({ id: c.id, tested: !!c.probe, days: c.probe ? (doc.probes[c.id] ?? []) : [] })),\n    promises: project.promises.map((p) => ({ id: p.id, ratio: promiseRatio(p, doc) })),\n    token: {\n      liquidity: liquidityOf(project, doc).status,\n      // With no insider wallet known there is nothing to read: the reading is left out, not scored as zero held.\n      insiderShare: doc.token && doc.token.insiders.length ? doc.token.insiderShare : null,\n      top10Share: doc.token ? doc.token.top10Share : null,\n      taxTotal: project.tax ? project.tax.buy + project.tax.sell : null,\n    },\n    holders: doc.token ? doc.token.holders : null,\n    disclosure: disclosureOf(project, doc),\n    contradicted: project.contradictions.map((c) => c.id),\n    ageHours: doc.refreshedAt ? (now - doc.refreshedAt) / 3_600_000 : Infinity,\n    // From the launch transaction's block time (scripts/launch-times.ts); a listing without one counts from its first check.\n    hoursSinceLaunch: (now - (project.launchedAt ? Date.parse(project.launchedAt) : (firstCheckOf(doc) ?? now))) / 3_600_000,\n    linkage: project.linkage,\n  };\n}\n\n// ── the daily report ────────────────────────────────────────────────────────\n\nexport interface Report {\n  /** The UTC day this report closes. */\n  date: string;\n  rulebook: string;\n  /** Fingerprint of the published scoring code that made this report (src/server/source.ts, shown at /code). */\n  code?: string;\n  projects: { slug: string; listed: boolean; status: ProjectCard[\"status\"]; unverified: boolean; score: number | null; grade: ProjectCard[\"grade\"]; base: number | null; flags: string[]; components: Record<string, number>; metrics: ProjectCard[\"metrics\"] }[];\n}\n\nexport interface StoredReport {\n  report: Report;\n  hash: `0x${string}`;\n  publishedAt: number;\n  /** The Elysium transaction that committed the hash, once it has been sent (src/server/commit.ts). */\n  commitTx: string | null;\n  /** The wallet that sent it. */\n  commitFrom?: string | null;\n  /** Why the last attempt to send it failed, if it did. */\n  commitError?: string | null;\n}\n\nexport function buildReport(date: string, cards: { slug: string; card: ProjectCard; listed?: boolean }[], code?: string): Report {\n  return {\n    date,\n    rulebook: \"docs/scoring.md\",\n    ...(code ? { code } : {}),\n    projects: [...cards]\n      .sort((a, b) => a.slug.localeCompare(b.slug))\n      .map(({ slug, card, listed }) => ({\n        slug,\n        listed: listed ?? true,\n        status: card.status,\n        unverified: card.unverified,\n        score: card.score,\n        grade: card.grade,\n        base: card.base,\n        flags: card.flags.map((f) => f.key),\n        components: Object.fromEntries(card.components.map((c) => [c.key, c.score])),\n        metrics: card.metrics,\n      })),\n  };\n}\n\n/** Score every project through the last finished UTC day and store the report with its hash. Once per day. */\nexport async function publishReport(projects: Project[], now = Date.now(), code?: string): Promise<StoredReport> {\n  const date = utcDay(now - DAY);\n  const existing = await store().get<StoredReport>(`report.${date}`);\n  if (existing) return existing;\n  const cards = await Promise.all(\n    projects.map(async (project) => {\n      const doc = await loadProject(project.slug);\n      // Only probe days that had finished by the report's date.\n      const closed = { ...doc, probes: Object.fromEntries(Object.entries(doc.probes).map(([id, days]) => [id, days.filter((d) => d.date <= date)])) };\n      return { slug: project.slug, card: scoreProject(inputsFor(project, closed, now)), listed: doc.listed ?? true };\n    }),\n  );\n  const report = buildReport(date, cards, code);\n  const stored: StoredReport = { report, hash: reportHash(report), publishedAt: now, commitTx: null };\n  await store().set(`report.${date}`, stored);\n  await store().set(\"report.latest\", { date, hash: stored.hash });\n  // Every report's date, oldest first, so the reports can be listed (the Analyst API, /api/report).\n  const index = (await store().get<string[]>(\"report.index\")) ?? [];\n  if (!index.includes(date)) await store().set(\"report.index\", [...index, date].sort());\n  return stored;\n}\n"},{"path":"src/server/board.ts","role":"Ranking, the listing floor and what the board and project pages show.","lines":163,"sha256":"498b50a3c06dded1d62ada5379415d9eabfb4212360083f17194fa852c8078c0","content":"import { rank, scoreProject, type ProjectCard } from \"../engine/project.ts\";\nimport { reportHash } from \"../engine/report.ts\";\nimport { exampleProjects } from \"./example.ts\";\nimport { buildReport, inputsFor, loadProject, promiseRatio, type FeeFacts, type MarketFacts, type ProjectDoc, type SplitFacts, type StoredReport, type TokenFacts } from \"./pipeline.ts\";\nimport { liveProjects, type Project } from \"./registry.ts\";\nimport { store } from \"./store.ts\";\n\n/** `live` = real projects from the registry. `example` = fictional projects from the generator. */\nexport type Mode = \"example\" | \"live\";\n\nexport interface BoardRow {\n  project: Pick<Project, \"slug\" | \"name\" | \"ticker\" | \"pad\" | \"blurb\" | \"image\" | \"token\">;\n  /** 1-based place among scored projects; null for projects too new to score. */\n  rank: number | null;\n  card: Omit<ProjectCard, \"claims\" | \"days\">;\n  /** Share of probe runs that passed, per window day, for the strip. */\n  spark: number[];\n  /** Market cap in dollars. Shown, never scored. */\n  mcapUsd: number | null;\n}\n\nexport interface Board {\n  mode: Mode;\n  /** True when real projects are listed, whichever board this is. */\n  hasLive: boolean;\n  asOf: string;\n  generatedAt: number;\n  /** When the most recent probe ran, ms. null if none has. */\n  checkedAt: number | null;\n  /** Probe runs and passes across every project's window. */\n  checks: { runs: number; passes: number };\n  rows: BoardRow[];\n  /** Projects under the listing floor: still checked, not on the board. Largest market cap first. */\n  below: BoardRow[];\n  report: { date: string; hash: string; commitTx: string | null } | null;\n}\n\nexport interface ProjectPage {\n  mode: Mode;\n  project: Project;\n  rank: number | null;\n  ranked: number;\n  card: ProjectCard;\n  /** Each claim's most recent probe run. */\n  last: ProjectDoc[\"last\"];\n  token: TokenFacts | null;\n  fees: FeeFacts[];\n  /** Promised shares measured on chain, by promise id. */\n  splits: Record<string, SplitFacts>;\n  /** How much of each money promise was kept; null = not measured. */\n  promises: { id: string; ratio: number | null }[];\n  refreshedAt: number | null;\n  errors: string[];\n  asOf: string;\n  /** False when the project is under the listing floor and so off the board. */\n  listed: boolean;\n  market: MarketFacts | null;\n}\n\ninterface Loaded {\n  mode: Mode;\n  now: number;\n  projects: { project: Project; doc: ProjectDoc; card: ProjectCard }[];\n  report: Board[\"report\"];\n}\n\nconst memo: Partial<Record<Mode, { at: number; value: Promise<Loaded> }>> = {};\n\nasync function load(mode: Mode): Promise<Loaded> {\n  const now = Date.now();\n  if (mode === \"example\") {\n    const projects = exampleProjects(now).map(({ project, doc }) => ({ project, doc, card: scoreProject(inputsFor(project, doc, now)) }));\n    const asOf = asOfOf(projects, now);\n    // The example board gets a hash too, so the page can show what a commitment looks like. Nothing is on-chain.\n    return { mode, now, projects, report: { date: asOf, hash: reportHash(buildReport(asOf, projects.map((p) => ({ slug: p.project.slug, card: p.card })))), commitTx: null } };\n  }\n  const projects = await Promise.all(\n    liveProjects().map(async (project) => {\n      const doc = await loadProject(project.slug);\n      return { project, doc, card: scoreProject(inputsFor(project, doc, now)) };\n    }),\n  );\n  const latest = await store().get<{ date: string; hash: string }>(\"report.latest\");\n  const stored = latest ? await store().get<StoredReport>(`report.${latest.date}`) : null;\n  return { mode, now, projects, report: stored ? { date: stored.report.date, hash: stored.hash, commitTx: stored.commitTx } : null };\n}\n\n/** One load serves every request for half a minute. */\nfunction loaded(mode: Mode): Promise<Loaded> {\n  const hit = memo[mode];\n  if (hit && Date.now() - hit.at < 30_000) return hit.value;\n  const value = load(mode);\n  memo[mode] = { at: Date.now(), value };\n  value.catch(() => {\n    if (memo[mode]?.value === value) delete memo[mode];\n  });\n  return value;\n}\n\nconst asOfOf = (projects: { card: ProjectCard }[], now: number) =>\n  projects.map((p) => p.card.metrics.windowEnd).filter((x): x is string => !!x).sort().at(-1) ?? new Date(now).toISOString().slice(0, 10);\n\n/** The board to show at `/`: real projects when any are listed, otherwise the example. */\nexport const defaultMode = (): Mode => (liveProjects().length ? \"live\" : \"example\");\n\nconst isListed = (doc: ProjectDoc) => doc.listed ?? true;\n\nexport async function getBoard(mode: Mode = defaultMode()): Promise<Board> {\n  const l = await loaded(mode);\n  const listed = l.projects.filter((p) => isListed(p.doc));\n  const order = rank(listed.map((p) => ({ ...p, slug: p.project.slug })));\n  const place = new Map(order.map((p, i) => [p.slug, i + 1]));\n  // Projects without a score yet are listed by how much of what they claim has been verified so far.\n  const product = (c: ProjectCard) => c.components.find((x) => x.key === \"product\")?.score ?? 0;\n  const unranked = listed\n    .filter((p) => p.card.score === null)\n    .sort((a, b) => product(b.card) - product(a.card) || b.card.metrics.claimsVerified - a.card.metrics.claimsVerified || a.project.name.localeCompare(b.project.name));\n  const row = ({ project, card, doc }: Loaded[\"projects\"][number]): BoardRow => {\n    const { claims: _claims, days, ...rest } = card;\n    const { slug, name, ticker, pad, blurb, image, token } = project;\n    return { project: { slug, name, ticker, pad, blurb, image, token }, rank: place.get(slug) ?? null, card: rest, spark: days.map((d) => (d.runs ? d.passes / d.runs : 0)), mcapUsd: doc.market?.mcapUsd ?? null };\n  };\n  const below = l.projects.filter((p) => !isListed(p.doc)).sort((a, b) => (b.doc.market?.mcapUsd ?? 0) - (a.doc.market?.mcapUsd ?? 0));\n  const lastRuns = l.projects.flatMap((p) => Object.values(p.doc.last).map((r) => r.at));\n  const checks = listed.reduce((a, p) => ({ runs: a.runs + p.card.claims.reduce((n, c) => n + c.runs, 0), passes: a.passes + p.card.claims.reduce((n, c) => n + c.passes, 0) }), { runs: 0, passes: 0 });\n  return {\n    mode,\n    hasLive: liveProjects().length > 0,\n    asOf: asOfOf(l.projects, l.now),\n    generatedAt: l.now,\n    checkedAt: lastRuns.length ? Math.max(...lastRuns) : null,\n    checks,\n    rows: [...order, ...unranked].map(row),\n    below: below.map(row),\n    report: l.report,\n  };\n}\n\nexport async function getProjectPage(slug: string, mode: Mode = defaultMode()): Promise<ProjectPage | null> {\n  const l = await loaded(mode);\n  const hit = l.projects.find((p) => p.project.slug === slug);\n  if (!hit) return null;\n  const order = rank(l.projects.filter((p) => isListed(p.doc)).map((p) => ({ ...p, slug: p.project.slug })));\n  const at = order.findIndex((p) => p.slug === slug);\n  return {\n    mode,\n    project: hit.project,\n    rank: at < 0 ? null : at + 1,\n    ranked: order.length,\n    card: hit.card,\n    last: hit.doc.last,\n    token: hit.doc.token,\n    fees: Object.values(hit.doc.fees),\n    splits: hit.doc.splits ?? {},\n    promises: hit.project.promises.map((p) => ({ id: p.id, ratio: promiseRatio(p, hit.doc) })),\n    refreshedAt: hit.doc.refreshedAt || null,\n    errors: hit.doc.errors,\n    asOf: asOfOf(l.projects, l.now),\n    listed: isListed(hit.doc),\n    market: hit.doc.market,\n  };\n}\n"},{"path":"src/server/registry.ts","role":"The listing format: claims, probes, wallets and money promises.","lines":79,"sha256":"0df5eda30ad96048deb0a23f510d5e7876a34db8c1da34913c58183fd52c17f3","content":"import { listings } from \"../../projects/index.ts\";\nimport type { Linkage } from \"../engine/types.ts\";\nimport type { Liquidity } from \"../engine/project.ts\";\nimport type { Probe } from \"../sources/probes.ts\";\nimport type { ListSpec } from \"../sources/chain-checks.ts\";\n\n/** Launchpads on Elysium. */\nexport type Pad = \"montra\" | \"kleos\" | \"ascend\" | \"boxa\" | \"elyspump\";\n\nexport interface Claim {\n  id: string;\n  /** The project's own words. */\n  text: string;\n  /** The page those words are on. */\n  source: string;\n  /** In plain words, what the probe checks. */\n  check?: string;\n  probe?: Probe;\n  /** Why there is no probe, for a claim that cannot be checked from outside. */\n  untested?: string;\n}\n\nexport type MoneyPromise = { id: string; text: string; source: string } & (\n  | { kind: \"buyback_burn\"; share: number; wallet: string }\n  /** The disclosed wallets together hold no more than `max` of supply. */\n  | { kind: \"insider_max\"; max: number }\n  /**\n   * `share` of the fee income `wallet` receives goes to one use (a prize pot, say), paid out in the payments the\n   * project lists at `payouts`. Measured on chain: fee income in, listed payments confirmed on Elysium.\n   */\n  | { kind: \"split\"; share: number; wallet: string; use: string; payouts: ListSpec }\n  | { kind: \"unmeasured\"; note: string }\n);\n\nexport const DISCLOSURE = [\"tokenAddress\", \"feeWallet\", \"feeSplit\", \"liquidityStated\", \"sourceVerified\", \"docs\"] as const;\nexport type DisclosureKey = (typeof DISCLOSURE)[number];\n\nexport interface Project {\n  slug: string;\n  name: string;\n  ticker: string;\n  pad: Pad;\n  token: string;\n  website: string;\n  x?: string;\n  blurb: string;\n  /** The token's own picture, served by Sentinel (scripts/token-images.ts). */\n  image?: string;\n  /** Where that picture came from: the IPFS file in the token's launch metadata. */\n  imageSource?: string;\n  listed: string;\n  linkage: Linkage;\n  linkageNote?: string;\n  /** The wallet that sent the token's launch transaction, read from the chain. Counted as an insider wallet. */\n  creator?: string | null;\n  /** Team, fee and treasury wallets the project itself publishes. */\n  wallets: { label: string; address: string; source: string }[];\n  /** Pool or locker contracts that hold this token for others: not counted as holders. */\n  pools: string[];\n  tax: { buy: number; sell: number; source: string } | null;\n  liquidity: { status: Liquidity; note: string; source?: string };\n  /** Contracts that pay this project its fees (the launchpad's fee contract). */\n  feeSources: string[];\n  /** The launch transaction: a creator's own first buy in it is not a buyback. */\n  launchTx?: string | null;\n  /** When the token launched: the launch transaction's block time, ISO (scripts/launch-times.ts). Scoring starts 48 hours later. */\n  launchedAt?: string | null;\n  claims: Claim[];\n  promises: MoneyPromise[];\n  /** Checklist items judged from the project's pages. `sourceVerified` is read from the explorer instead. */\n  disclosure: Partial<Record<Exclude<DisclosureKey, \"sourceVerified\">, { met: boolean; source?: string }>>;\n  /** Public statements the chain contradicts. Each one costs the project the \"claim contradicted\" penalty once. */\n  contradictions: { id: string; statement: string; evidence: string; source?: string }[];\n  /** Facts worth a reader's attention that carry no penalty. */\n  observations: { text: string; tx?: string }[];\n}\n\nexport const liveProjects = (): Project[] => listings as Project[];\n"},{"path":"src/sources/probes.ts","role":"How each automated check calls a project's product and decides pass or fail.","lines":305,"sha256":"d47c81fff1707f5c07364c1bdfefd980961e1ddafd5d1ea6363dcdd51aadb832","content":"import { BURN_OR_POOL, holdBreach, matchesChain, payoutProblem, pick, recordsOf, readTx, balanceBefore, short, tokenRuleBreaches, type Cache, type ListSpec, type ReadBudget } from \"./chain-checks.ts\";\nimport { balanceOf, codeSize, nativeBalance, tokenTransfers } from \"./elysium.ts\";\n\n/**\n * Probes: small automated checks with a yes-or-no answer. Each one calls something the project has made public\n * and checks that it answers the way the project says it does; the chain checks then hold what it publishes\n * against Elysium. A timeout or an error is a failure.\n */\n/** Plain JSON, so a probe can be stored and sent to the page as it is. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** What a field in a JSON answer must be. \"nonempty\": a non-empty list, object or text. */\nexport type FieldRule = \"number\" | \"string\" | \"boolean\" | \"array\" | \"object\" | \"nonempty\";\n\n/** Checks on a JSON answer, beyond \"it answered\". */\nexport interface Shape {\n  /** Fields that must be present, by dotted path, and what each must be. */\n  fields?: Record<string, FieldRule>;\n  /** A field that must change between runs: a frozen copy of the product cannot pass. */\n  changes?: string;\n  /** A figure the answer publishes that must match the chain: a wallet's HYPE balance, or its balance of `token`. */\n  chainMatch?: { path: string; wallet: string; token?: string; tolerance?: number };\n}\n\nexport type Probe =\n  /** A URL answers 200. `contains`: the body includes this text. `json`: these top-level fields have these values. */\n  | ({ kind: \"http\"; url: string; contains?: string; json?: Record<string, string | number | boolean> } & Shape)\n  /** An MCP endpoint completes `initialize` and lists at least `minTools` tools, including every name in `tools`. */\n  | { kind: \"mcp\"; url: string; minTools?: number; tools?: string[] }\n  /** An MCP tool is called with read-only arguments and its answer includes every string in `expect`. */\n  | ({ kind: \"mcp_call\"; url: string; tool: string; args?: { [k: string]: Json }; expect?: string[] } & Shape)\n  /** A contract the project names has code on Elysium. */\n  | { kind: \"evm_code\"; address: string }\n  /**\n   * Every payment in a list the project publishes is on Elysium as described: the transaction succeeded, came from\n   * the published wallet, went to the named recipient and moved the listed amount. `recent`: how many of the list's\n   * paid items are checked (default 60).\n   */\n  | { kind: \"payouts\"; list: ListSpec; wallet: string; asset?: \"native\" | string; recent?: number }\n  /**\n   * Everyone the project paid met its own rule for winning: held at least `min` of `token` just before the payment.\n   * Payments before `since` are not judged. `minFrom`: where the project publishes the amount today; the lower of\n   * the two is used, so a rule that steps down is never applied too strictly.\n   */\n  | { kind: \"eligibility\"; list: ListSpec; token: string; unit: string; min: number; minFrom?: { from: ListSpec[\"from\"]; path: string }; since: string; recent?: number }\n  /** A wallet never sends `token` anywhere but `allowTo` (by default: burn addresses and the pool). */\n  | { kind: \"token_rule\"; token: string; wallet: string; allowTo?: string[] };\n\nexport interface ProbeResult {\n  ok: boolean;\n  ms: number;\n  /** One line a reader can understand: what was seen, or what went wrong. */\n  detail: string;\n  /** The value of the `changes` field this run, kept to compare with the next run. */\n  seen?: Json;\n  /** Nothing could be judged this run (the chain reads it needs are still queued). Not counted as a run. */\n  skipped?: boolean;\n}\n\n/** What a probe may use besides the network: the last run's `changes` value, a cache and a budget for chain reads. */\nexport interface ProbeContext {\n  prev?: Json;\n  cache?: Cache;\n  budget?: ReadBudget;\n}\n\nconst TIMEOUT_MS = 20_000;\nconst UA = \"Mozilla/5.0 (compatible; sentinel-probe)\";\n\nasync function mcp(url: string, method: string, params?: unknown): Promise<{ result?: Record<string, unknown>; error?: { message?: string } }> {\n  const res = await fetch(url, {\n    method: \"POST\",\n    headers: { \"content-type\": \"application/json\", accept: \"application/json, text/event-stream\", \"user-agent\": UA },\n    body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, ...(params === undefined ? {} : { params }) }),\n    signal: AbortSignal.timeout(TIMEOUT_MS),\n  });\n  if (!res.ok) throw new Error(`answered ${res.status}`);\n  const text = (await res.text()).trim();\n  // Streamable HTTP may answer as JSON or as a one-message event stream.\n  const payload = text.startsWith(\"{\") ? text : (text.split(\"\\n\").filter((l) => l.startsWith(\"data:\")).pop() ?? \"\").slice(5);\n  return JSON.parse(payload);\n}\n\n/** The text of an MCP tool's answer. */\nasync function mcpText(url: string, tool: string, args?: { [k: string]: Json }): Promise<string> {\n  const out = await mcp(url, \"tools/call\", { name: tool, arguments: args ?? {} });\n  if (!out.result) throw new Error(`${tool} failed: ${out.error?.message ?? \"no result\"}`);\n  if (out.result.isError) throw new Error(`${tool} returned an error`);\n  return ((out.result.content as { text?: string }[] | undefined) ?? []).map((c) => c.text ?? \"\").join(\"\\n\");\n}\n\nconst parse = (text: string, what: string): unknown => {\n  try {\n    return JSON.parse(text);\n  } catch {\n    throw new Error(`${what} is not JSON`);\n  }\n};\n\n/** A JSON document the project publishes: a URL, or a read-only MCP tool. */\nexport async function readJson(from: ListSpec[\"from\"]): Promise<unknown> {\n  if (\"url\" in from) {\n    const res = await fetch(from.url, { headers: { \"user-agent\": UA }, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: \"follow\" });\n    if (res.status !== 200) throw new Error(`${from.url} answered ${res.status}`);\n    return parse(await res.text(), \"the answer\");\n  }\n  return parse(await mcpText(from.mcp, from.tool, from.args), `the ${from.tool} answer`);\n}\n\nconst kindOf = (v: unknown) => (Array.isArray(v) ? \"array\" : v === null ? \"null\" : typeof v);\n\n/** Check a JSON answer's fields, its link to the chain and whether it moved. Writes the `changes` value to `out`. */\nasync function checkShape(data: unknown, p: Shape, ctx: ProbeContext, out: { seen?: Json }): Promise<string[]> {\n  const notes: string[] = [];\n  if (p.changes) {\n    const v = pick(data, p.changes);\n    if (v === undefined) throw new Error(`the answer has no \"${p.changes}\"`);\n    out.seen = v as Json;\n    if (ctx.prev !== undefined && JSON.stringify(ctx.prev) === JSON.stringify(v)) throw new Error(`\"${p.changes}\" has not changed since the last check (still ${JSON.stringify(v).slice(0, 60)})`);\n    notes.push(ctx.prev === undefined ? `\"${p.changes}\" read for the first time` : `\"${p.changes}\" moved since the last check`);\n  }\n  for (const [path, rule] of Object.entries(p.fields ?? {})) {\n    const v = pick(data, path);\n    if (v === undefined) throw new Error(`the answer has no \"${path}\"`);\n    const k = kindOf(v);\n    const ok = rule === \"nonempty\" ? (Array.isArray(v) ? v.length > 0 : typeof v === \"string\" ? v.length > 0 : !!v && typeof v === \"object\" && Object.keys(v).length > 0) : k === rule;\n    if (!ok) throw new Error(rule === \"nonempty\" ? `\"${path}\" is empty` : `\"${path}\" is ${k}, expected ${rule}`);\n  }\n  if (p.fields) notes.push(`${Object.keys(p.fields).length} field${Object.keys(p.fields).length === 1 ? \"\" : \"s\"} present`);\n  if (p.chainMatch) {\n    const m = p.chainMatch;\n    const published = Number(pick(data, m.path));\n    if (!Number.isFinite(published)) throw new Error(`\"${m.path}\" is not a number`);\n    const chain = m.token ? await balanceOf(m.token, m.wallet) : await nativeBalance(m.wallet);\n    const unit = m.token ? \"tokens\" : \"HYPE\";\n    if (!matchesChain(published, chain, m.tolerance ?? 0.02)) throw new Error(`publishes ${m.path} = ${published.toLocaleString(\"en-US\")}, but ${short(m.wallet)} holds ${chain.toLocaleString(\"en-US\", { maximumFractionDigits: 4 })} ${unit} on Elysium`);\n    notes.push(`${m.path} matches the chain (${chain.toLocaleString(\"en-US\", { maximumFractionDigits: 4 })} ${unit})`);\n  }\n  return notes;\n}\n\nconst withShape = (base: string, notes: string[]) => (notes.length ? `${base}; ${notes.join(\"; \")}` : base);\nconst day = (ms: number) => new Date(ms).toISOString().slice(0, 10);\n\n/** In memory, for runs without a store (scripts, tests). */\nexport const memoryCache = (): Cache => {\n  const m = new Map<string, unknown>();\n  return { get: async <T,>(k: string) => (m.has(k) ? (m.get(k) as T) : null), set: async (k, v) => m.set(k, v) };\n};\n\ntype Outcome = string | { detail: string; skipped: true };\n\nasync function run(p: Probe, ctx: ProbeContext, out: { seen?: Json }): Promise<Outcome> {\n  const cache = ctx.cache ?? memoryCache();\n  const budget = ctx.budget ?? { left: 40 };\n  switch (p.kind) {\n    case \"http\": {\n      const res = await fetch(p.url, { headers: { \"user-agent\": UA }, signal: AbortSignal.timeout(TIMEOUT_MS), redirect: \"follow\" });\n      if (res.status !== 200) throw new Error(`answered ${res.status}`);\n      const body = await res.text();\n      if (p.contains && !body.includes(p.contains)) throw new Error(`answered 200 but the page does not contain \"${p.contains}\"`);\n      const needsJson = p.json || p.fields || p.changes || p.chainMatch;\n      const data = needsJson ? parse(body, \"the answer\") : null;\n      if (p.json) {\n        for (const [k, v] of Object.entries(p.json)) if ((data as Record<string, unknown>)[k] !== v) throw new Error(`\"${k}\" is ${JSON.stringify((data as Record<string, unknown>)[k])}, expected ${JSON.stringify(v)}`);\n      }\n      return withShape(\"answered 200 as described\", await checkShape(data, p, ctx, out));\n    }\n    case \"mcp\": {\n      const init = await mcp(p.url, \"initialize\", { protocolVersion: \"2025-06-18\", capabilities: {}, clientInfo: { name: \"sentinel-probe\", version: \"1\" } });\n      if (!init.result) throw new Error(`initialize failed: ${init.error?.message ?? \"no result\"}`);\n      const list = await mcp(p.url, \"tools/list\");\n      const tools = ((list.result?.tools as { name: string }[] | undefined) ?? []).map((t) => t.name);\n      if (tools.length < (p.minTools ?? 1)) throw new Error(`lists ${tools.length} tools, expected at least ${p.minTools ?? 1}`);\n      const missing = (p.tools ?? []).filter((t) => !tools.includes(t));\n      if (missing.length) throw new Error(`missing tools: ${missing.join(\", \")}`);\n      return `connected and lists ${tools.length} tools`;\n    }\n    case \"mcp_call\": {\n      const text = await mcpText(p.url, p.tool, p.args);\n      const missing = (p.expect ?? []).filter((e) => !text.includes(e));\n      if (missing.length) throw new Error(`${p.tool} answered without ${missing.map((m) => JSON.stringify(m)).join(\", \")}`);\n      const needsJson = p.fields || p.changes || p.chainMatch;\n      return withShape(`${p.tool} answered as described`, needsJson ? await checkShape(parse(text, `the ${p.tool} answer`), p, ctx, out) : []);\n    }\n    case \"evm_code\": {\n      const size = await codeSize(p.address);\n      if (!size) throw new Error(\"no contract at that address\");\n      return `contract present (${size.toLocaleString(\"en-US\")} bytes)`;\n    }\n    case \"payouts\": {\n      const records = recordsOf(await readJson(p.list.from), p.list);\n      if (!records) throw new Error(`the answer has no list at \"${p.list.path}\"`);\n      const paid = records.filter((r) => r.tx);\n      if (!paid.length) throw new Error(\"the list has no payment with a transaction to look up\");\n      const rule = { wallet: p.wallet, asset: p.asset ?? \"native\" };\n      let unread = 0;\n      const bad: string[] = [];\n      let checked = 0;\n      for (const r of paid.slice(0, p.recent ?? 60)) {\n        const f = await readTx(r.tx!, cache, budget);\n        if (!f) {\n          unread++;\n          continue;\n        }\n        checked++;\n        const problem = payoutProblem(r, f, rule);\n        if (problem) bad.push(`${short(r.tx!)}: ${problem}`);\n      }\n      if (!checked) return { detail: `${unread} payments queued for chain reads`, skipped: true };\n      if (bad.length) throw new Error(`${bad.length} of ${checked} payments do not match Elysium. ${bad.slice(0, 2).join(\". \")}`);\n      const extra = [unread ? `${unread} still to read` : \"\", records.length > paid.length ? `${records.length - paid.length} listed without a transaction yet` : \"\"].filter(Boolean);\n      return `${checked} payments match Elysium: sent from ${short(p.wallet)}${p.list.to ? \", to the named recipient\" : \"\"}${p.list.amount ? \", for the listed amount\" : \"\"}${extra.length ? ` (${extra.join(\"; \")})` : \"\"}`;\n    }\n    case \"eligibility\": {\n      const records = recordsOf(await readJson(p.list.from), p.list);\n      if (!records) throw new Error(`the answer has no list at \"${p.list.path}\"`);\n      let min = p.min;\n      if (p.minFrom) {\n        const live = Number(pick(await readJson(p.minFrom.from), p.minFrom.path));\n        if (Number.isFinite(live) && live > 0 && live < min) min = live;\n      }\n      const rule = { token: p.token, min, since: Date.parse(p.since) };\n      const breaches: { recipient: string; held: number; time: number; hash: string }[] = [];\n      let judged = 0;\n      let unread = 0;\n      for (const r of records.filter((r) => r.tx && r.to).slice(0, p.recent ?? 60)) {\n        const f = await readTx(r.tx!, cache, budget);\n        if (!f) {\n          unread++;\n          continue;\n        }\n        if (!f.found || !f.ok || f.time < rule.since) continue;\n        const held = await balanceBefore(p.token, r.to!, f.block, cache, budget);\n        if (held === null) {\n          unread++;\n          continue;\n        }\n        judged++;\n        const b = holdBreach(f, r.to!, held, rule);\n        if (b) breaches.push(b);\n      }\n      const amount = `${min.toLocaleString(\"en-US\")} ${p.unit}`;\n      if (!judged) return unread ? { detail: `${unread} payments queued for chain reads`, skipped: true } : `no payment since ${day(rule.since)} to judge`;\n      if (breaches.length) {\n        const wallets = [...new Set(breaches.map((b) => b.recipient))];\n        const worst = [...breaches].sort((a, b) => a.held - b.held)[0];\n        throw new Error(\n          `${breaches.length} of ${judged} payments since ${day(rule.since)} went to wallets holding under ${amount} (${wallets.length} wallet${wallets.length === 1 ? \"\" : \"s\"}); ${short(worst.recipient)} held ${worst.held.toLocaleString(\"en-US\", { maximumFractionDigits: 3 })} when paid on ${day(worst.time)}`,\n        );\n      }\n      return `all ${judged} payments since ${day(rule.since)} went to wallets holding at least ${amount}${unread ? ` (${unread} still to read)` : \"\"}`;\n    }\n    case \"token_rule\": {\n      const { transfers, complete } = await tokenTransfers(p.wallet, p.token);\n      const allow = p.allowTo ?? BURN_OR_POOL;\n      const breaches = tokenRuleBreaches(transfers, p.wallet, allow);\n      if (breaches.length) {\n        const last = breaches[breaches.length - 1];\n        throw new Error(`${breaches.length} transfer${breaches.length === 1 ? \"\" : \"s\"} out to other addresses; the latest sent ${last.amount.toLocaleString(\"en-US\", { maximumFractionDigits: 2 })} to ${short(last.to)} on ${day(last.time)}`);\n      }\n      const outs = transfers.filter((t) => t.from === p.wallet.toLowerCase() && t.amount > 0);\n      const burns = outs.filter((t) => BURN_OR_POOL.slice(0, 2).includes(t.to)).length;\n      return `${outs.length} transfer${outs.length === 1 ? \"\" : \"s\"} out, all allowed: ${burns} to a burn address, ${outs.length - burns} into the pool${complete ? \"\" : \" (history longer than Sentinel reads)\"}`;\n    }\n  }\n}\n\nexport async function runProbe(p: Probe, ctx: ProbeContext = {}): Promise<ProbeResult> {\n  const start = Date.now();\n  const out: { seen?: Json } = {};\n  try {\n    const r = await run(p, ctx, out);\n    const seen = out.seen !== undefined ? { seen: out.seen } : {};\n    return typeof r === \"string\" ? { ok: true, detail: r, ms: Date.now() - start, ...seen } : { ok: false, skipped: true, detail: r.detail, ms: Date.now() - start, ...seen };\n  } catch (e) {\n    const why = e instanceof Error ? (e.name === \"TimeoutError\" ? \"no answer in 20 seconds\" : e.message) : \"failed\";\n    // A frozen value is kept as seen, so the next run still compares against it.\n    const seen = out.seen !== undefined ? { seen: out.seen } : ctx.prev !== undefined ? { seen: ctx.prev } : {};\n    return { ok: false, detail: why.slice(0, 300), ms: Date.now() - start, ...seen };\n  }\n}\n\nconst listName = (l: ListSpec) => (\"url\" in l.from ? l.from.url : `MCP tool ${l.from.tool} at ${l.from.mcp}`);\n\n/** What a probe calls, in words, for the project page. */\nexport function describeProbe(p: Probe): string {\n  switch (p.kind) {\n    case \"http\":\n      return `GET ${p.url}`;\n    case \"mcp\":\n      return `MCP connect and list tools at ${p.url}`;\n    case \"mcp_call\":\n      return `MCP tool ${p.tool} at ${p.url}`;\n    case \"evm_code\":\n      return `Contract code at ${p.address}`;\n    case \"payouts\":\n      return `Each payment in ${listName(p.list)} (${p.list.path}), looked up on Elysium`;\n    case \"eligibility\":\n      return `${p.unit} held by each recipient in ${listName(p.list)} (${p.list.path}), read on Elysium just before the payment`;\n    case \"token_rule\":\n      return `Every ${short(p.token)} transfer out of ${p.wallet}, read on Elysium`;\n  }\n}\n"},{"path":"src/sources/elysium.ts","role":"Chain reads: supply, burns, holders, insider wallets and fee-wallet flows.","lines":249,"sha256":"abe03a0e9c87fb2dd3d7c7b0c83f890e832e9c6acfbd63dee7a33c9a86c0d601","content":"/**\n * Reads from Elysium: the public RPC for balances and code, and the explorer's Etherscan-style API for holders and\n * a wallet's history. Read-only, no key. Requests to each host are spaced a second apart: both are shared public\n * services.\n */\nconst RPC = process.env.ELYSIUM_RPC ?? \"https://rpc.elysium.kinetiq.xyz\";\nconst EXPLORER = process.env.ELYSIUM_EXPLORER_API ?? \"https://elysium.kinetiq.xyz/api\";\nconst GAP_MS = Number(process.env.ELYSIUM_GAP_MS ?? 1100);\n\nexport const DEAD = \"0x000000000000000000000000000000000000dead\";\nexport const ZERO = \"0x0000000000000000000000000000000000000000\";\n/** Uniswap's v4 PoolManager on Elysium: it holds every pool's tokens, so it is never counted as a holder. */\nexport const POOL_MANAGERS = [\"0xe2e105d3f7209a9da11f83ccf3e7398a753823f1\"];\n\nconst lc = (a: string) => a.toLowerCase();\nconst next: Record<string, number> = {};\n/** Wait until this host may be called again. */\nasync function pace(host: string) {\n  const now = Date.now();\n  const at = Math.max(now, next[host] ?? 0);\n  next[host] = at + GAP_MS;\n  if (at > now) await new Promise((r) => setTimeout(r, at - now));\n}\n\nexport async function rpc<T>(method: string, params: unknown[]): Promise<T> {\n  await pace(\"rpc\");\n  const res = await fetch(RPC, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ jsonrpc: \"2.0\", id: 1, method, params }), signal: AbortSignal.timeout(15_000) });\n  if (!res.ok) throw new Error(`Elysium RPC answered ${res.status}`);\n  const body = (await res.json()) as { result?: T; error?: { message: string } };\n  if (body.error || body.result === undefined) throw new Error(`Elysium RPC: ${body.error?.message ?? \"no result\"}`);\n  return body.result;\n}\n\nconst word = (address: string) => lc(address).replace(/^0x/, \"\").padStart(64, \"0\");\nconst units = (hex: string, decimals = 18) => (hex && hex !== \"0x\" ? Number(BigInt(hex)) / 10 ** decimals : 0);\n\nexport const totalSupply = async (token: string, decimals = 18) => units(await rpc<string>(\"eth_call\", [{ to: token, data: \"0x18160ddd\" }, \"latest\"]), decimals);\nexport const balanceOf = async (token: string, holder: string, decimals = 18) =>\n  units(await rpc<string>(\"eth_call\", [{ to: token, data: `0x70a08231${word(holder)}` }, \"latest\"]), decimals);\n/** A wallet's HYPE balance now. */\nexport const nativeBalance = async (address: string) => units(await rpc<string>(\"eth_getBalance\", [address, \"latest\"]));\n/** Bytes of code at an address: 0 for a plain wallet. */\nexport const codeSize = async (address: string) => ((await rpc<string>(\"eth_getCode\", [address, \"latest\"])).length - 2) / 2;\n\nasync function explorer<T>(params: Record<string, string | number>): Promise<T> {\n  await pace(\"explorer\");\n  const query = new URLSearchParams({ ...Object.fromEntries(Object.entries(params).map(([k, v]) => [k, String(v)])), apikey: \"sentinel\" });\n  const res = await fetch(`${EXPLORER}?${query}`, { headers: { \"user-agent\": \"Mozilla/5.0 (compatible; sentinel)\" }, signal: AbortSignal.timeout(25_000) });\n  if (!res.ok) throw new Error(`Elysium explorer answered ${res.status}`);\n  const body = (await res.json()) as { status?: string; message?: string; result: T };\n  // \"No transactions found\" comes back as status 0 with an empty list.\n  if (body.status === \"0\" && !Array.isArray(body.result)) throw new Error(`Elysium explorer: ${String(body.result).slice(0, 120)}`);\n  return body.result;\n}\n\nexport const holderCount = async (token: string) => Number(await explorer<string>({ module: \"token\", action: \"tokenholdercount\", contractaddress: token }));\n\nexport interface Holder {\n  address: string;\n  amount: number;\n}\nexport async function topHolders(token: string, n = 40, decimals = 18): Promise<Holder[]> {\n  const rows = await explorer<{ TokenHolderAddress: string; TokenHolderQuantity: string }[]>({ module: \"token\", action: \"tokenholderlist\", contractaddress: token, page: 1, offset: n });\n  return rows.map((r) => ({ address: lc(r.TokenHolderAddress), amount: Number(r.TokenHolderQuantity) / 10 ** decimals })).sort((a, b) => b.amount - a.amount);\n}\n\n/** A token's name and symbol from the explorer, and the contract that created it (a launchpad's factory). */\nexport async function tokenOrigin(token: string): Promise<{ name: string | null; symbol: string | null; factory: string | null; creator: string | null; createdAt: number | null } | null> {\n  const info = await explorer<{ tokenName?: string; symbol?: string }[] | string>({ module: \"token\", action: \"tokeninfo\", contractaddress: token }).catch(() => null);\n  const t = Array.isArray(info) ? info[0] : null;\n  if (!t) return null;\n  const made = await explorer<{ contractFactory?: string; contractCreator?: string; timestamp?: string }[]>({ module: \"contract\", action: \"getcontractcreation\", contractaddresses: token }).catch(() => []);\n  const m = Array.isArray(made) ? made[0] : undefined;\n  return {\n    name: t.tokenName || null,\n    symbol: t.symbol || null,\n    factory: m?.contractFactory ? lc(m.contractFactory) : null,\n    creator: m?.contractCreator ? lc(m.contractCreator) : null,\n    createdAt: m?.timestamp ? Number(m.timestamp) * 1000 : null,\n  };\n}\n\nexport async function sourceVerified(address: string): Promise<boolean> {\n  const rows = await explorer<{ ABI: string }[]>({ module: \"contract\", action: \"getsourcecode\", address });\n  return !!rows[0] && !/not verified/i.test(rows[0].ABI);\n}\n\n// ── a wallet's history ──────────────────────────────────────────────────────\n\nexport interface Tx {\n  hash: string;\n  time: number;\n  from: string;\n  to: string;\n  /** Native HYPE. */\n  value: number;\n  failed: boolean;\n}\nexport interface TokenTx {\n  hash: string;\n  time: number;\n  from: string;\n  to: string;\n  amount: number;\n}\nexport interface WalletHistory {\n  /** Transactions the wallet sent or received directly. */\n  txs: Tx[];\n  /** HYPE moved to or from the wallet by contracts. */\n  internal: Tx[];\n  /** Transfers of one token in or out of the wallet. */\n  token: TokenTx[];\n  /** False if a list was cut at the page limit. */\n  complete: boolean;\n}\n\ninterface RawTx {\n  hash?: string;\n  transactionHash?: string;\n  timeStamp: string;\n  from: string;\n  to: string | null;\n  value: string;\n  isError?: string;\n  tokenDecimal?: string;\n}\n\nconst PAGE = 1000;\nasync function pages(params: Record<string, string | number>, max = 5): Promise<{ rows: RawTx[]; complete: boolean }> {\n  const rows: RawTx[] = [];\n  for (let page = 1; page <= max; page++) {\n    const batch = await explorer<RawTx[]>({ ...params, page, offset: PAGE, sort: \"asc\" });\n    rows.push(...batch);\n    if (batch.length < PAGE) return { rows, complete: true };\n  }\n  return { rows, complete: false };\n}\nconst asTx = (r: RawTx): Tx => ({ hash: lc(r.hash ?? r.transactionHash ?? \"\"), time: Number(r.timeStamp) * 1000, from: lc(r.from), to: lc(r.to ?? \"\"), value: Number(r.value) / 1e18, failed: r.isError === \"1\" });\n\nexport async function walletHistory(wallet: string, token: string): Promise<WalletHistory> {\n  const txs = await pages({ module: \"account\", action: \"txlist\", address: wallet });\n  const internal = await pages({ module: \"account\", action: \"txlistinternal\", address: wallet });\n  const tok = await pages({ module: \"account\", action: \"tokentx\", address: wallet, contractaddress: token });\n  return {\n    txs: txs.rows.map(asTx),\n    internal: internal.rows.map(asTx),\n    token: tok.rows.map((r) => ({ hash: lc(r.hash ?? \"\"), time: Number(r.timeStamp) * 1000, from: lc(r.from), to: lc(r.to ?? \"\"), amount: Number(r.value) / 10 ** Number(r.tokenDecimal ?? 18) })),\n    complete: txs.complete && internal.complete && tok.complete,\n  };\n}\n\n/** Every transfer of one token in or out of a wallet, oldest first; `complete` is false if the list was cut. */\nexport async function tokenTransfers(wallet: string, token: string): Promise<{ transfers: TokenTx[]; complete: boolean }> {\n  const tok = await pages({ module: \"account\", action: \"tokentx\", address: wallet, contractaddress: token });\n  return {\n    transfers: tok.rows.map((r) => ({ hash: lc(r.hash ?? \"\"), time: Number(r.timeStamp) * 1000, from: lc(r.from), to: lc(r.to ?? \"\"), amount: Number(r.value) / 10 ** Number(r.tokenDecimal ?? 18) })),\n    complete: tok.complete,\n  };\n}\n\nexport type FeeEventKind = \"fee\" | \"buyback\" | \"burn\" | \"token_out\";\nexport interface FeeEvent {\n  time: number;\n  kind: FeeEventKind;\n  hash: string;\n  hype: number;\n  tokens: number;\n  /** Where tokens went, for transfers out. */\n  to?: string;\n}\nexport interface FeeFlows {\n  /** HYPE received from the fee sources (the launchpad's fee contract). */\n  incomeHype: number;\n  /** HYPE the wallet spent in transactions that delivered the project's token back to it. */\n  buybackHype: number;\n  /** Tokens those buybacks delivered. */\n  bought: number;\n  /** Tokens the wallet sent to a burn address. */\n  burned: number;\n  /** Tokens the wallet sent anywhere else. */\n  tokensOut: number;\n  /** HYPE the wallet sent out in transactions that were not buybacks. */\n  otherHypeOut: number;\n  events: FeeEvent[];\n}\n\n/**\n * Sort a fee wallet's history into fee income, buybacks and burns since `since`. Pure. A buyback is a transaction\n * the wallet itself sent, carrying HYPE, in which the project's token came back to the wallet. The launch\n * transaction is left out: a creator's own first buy is not a buyback.\n */\nexport function feeFlows(h: WalletHistory, o: { wallet: string; feeSources: string[]; launchTx?: string | null; since: number }): FeeFlows {\n  const wallet = lc(o.wallet);\n  const sources = new Set(o.feeSources.map(lc));\n  const launch = o.launchTx ? lc(o.launchTx) : \"\";\n  const sent = new Map(h.txs.filter((t) => t.from === wallet && !t.failed).map((t) => [t.hash, t]));\n  const events: FeeEvent[] = [];\n  const out: FeeFlows = { incomeHype: 0, buybackHype: 0, bought: 0, burned: 0, tokensOut: 0, otherHypeOut: 0, events };\n\n  for (const t of h.internal) {\n    if (t.time < o.since || t.failed || t.to !== wallet || !sources.has(t.from) || t.value <= 0) continue;\n    out.incomeHype += t.value;\n    events.push({ time: t.time, kind: \"fee\", hash: t.hash, hype: t.value, tokens: 0 });\n  }\n\n  const buybackTxs = new Set<string>();\n  for (const t of h.token) {\n    if (t.time < o.since) continue;\n    if (t.to === wallet) {\n      const tx = sent.get(t.hash);\n      if (!tx || t.hash === launch || tx.value <= 0) continue;\n      out.bought += t.amount;\n      const first = !buybackTxs.has(t.hash);\n      buybackTxs.add(t.hash);\n      if (first) out.buybackHype += tx.value;\n      events.push({ time: t.time, kind: \"buyback\", hash: t.hash, hype: first ? tx.value : 0, tokens: t.amount });\n    } else if (t.from === wallet) {\n      const burn = t.to === DEAD || t.to === ZERO;\n      if (burn) out.burned += t.amount;\n      else out.tokensOut += t.amount;\n      events.push({ time: t.time, kind: burn ? \"burn\" : \"token_out\", hash: t.hash, hype: 0, tokens: t.amount, to: t.to });\n    }\n  }\n\n  for (const t of sent.values()) {\n    if (t.time >= o.since && t.value > 0 && !buybackTxs.has(t.hash) && t.hash !== launch) out.otherHypeOut += t.value;\n  }\n  events.sort((a, b) => b.time - a.time);\n  return out;\n}\n\nexport interface HolderShare {\n  address: string;\n  share: number;\n}\n/**\n * The ten largest holders that are ordinary holders: pools, burn addresses and the project's own wallets are left\n * out. Shares are of supply net of burns.\n */\nexport function concentration(holders: Holder[], o: { supply: number; burned: number; exclude: string[] }): { top: HolderShare[]; top10Share: number } {\n  const skip = new Set([DEAD, ZERO, ...POOL_MANAGERS, ...o.exclude.map(lc)]);\n  const live = Math.max(1, o.supply - o.burned);\n  const top = holders\n    .filter((h) => !skip.has(h.address))\n    .slice(0, 10)\n    .map((h) => ({ address: h.address, share: h.amount / live }));\n  return { top, top10Share: top.reduce((a, h) => a + h.share, 0) };\n}\n"},{"path":"src/sources/chain-checks.ts","role":"Chain checks: a project's published payments, its rules for who gets paid, its income splits and its wallet rules, held against Elysium.","lines":223,"sha256":"3fa49234e9c8fc4e078e9e07ad0ea7b67bc4324d9576d8d5bc9b90f5727dc6e2","content":"import { DEAD, POOL_MANAGERS, rpc, ZERO } from \"./elysium.ts\";\n\n/**\n * Checks that hold a project's published records against Elysium. A project says \"we paid these prizes\", \"only\n * holders can win\", \"we split fees this way\", \"this wallet never sends tokens\": these functions read the records it\n * publishes and look each one up on chain. The deciding functions are pure; the readers take a cache, because a\n * mined transaction never changes and each one is read once.\n */\n\n/** Plain JSON. */\nexport type Json = string | number | boolean | null | Json[] | { [k: string]: Json };\n\n/** A value inside parsed JSON, by a dotted path: `buckets.prize.paid`, `awards.0.wallet`. Pure. */\nexport function pick(data: unknown, path: string): unknown {\n  if (!path) return data;\n  let at: unknown = data;\n  for (const part of path.split(\".\")) {\n    if (at === null || typeof at !== \"object\") return undefined;\n    at = (at as Record<string, unknown>)[part];\n  }\n  return at;\n}\n\n/** Where a project publishes a list of its own payments, and which field of each item is which. */\nexport interface ListSpec {\n  /** A JSON URL, or a read-only MCP tool whose answer is JSON. */\n  from: { url: string } | { mcp: string; tool: string; args?: { [k: string]: Json } };\n  /** The path to the list in that JSON. */\n  path: string;\n  /** Only items whose fields equal these values. */\n  where?: Record<string, string | number | boolean>;\n  /** The fields holding the transaction hash, the recipient, the amount (whole units) and the time. */\n  tx: string;\n  to?: string;\n  amount?: string;\n  time?: string;\n}\n\n/** One payment as the project publishes it. */\nexport interface PaidRecord {\n  tx: string | null;\n  to: string | null;\n  amount: number | null;\n  /** ms, when the project gives one. */\n  time: number | null;\n}\n\nconst lc = (a: string) => a.toLowerCase();\nconst isHash = (x: unknown): x is string => typeof x === \"string\" && /^0x[0-9a-fA-F]{64}$/.test(x);\nconst isAddress = (x: unknown): x is string => typeof x === \"string\" && /^0x[0-9a-fA-F]{40}$/.test(x);\n\n/** The items of a published list, read with a spec. Items with no valid transaction hash keep tx null. Pure. */\nexport function recordsOf(data: unknown, spec: Pick<ListSpec, \"path\" | \"where\" | \"tx\" | \"to\" | \"amount\" | \"time\">): PaidRecord[] | null {\n  const list = pick(data, spec.path);\n  if (!Array.isArray(list)) return null;\n  return list\n    .filter((item) => item && typeof item === \"object\" && Object.entries(spec.where ?? {}).every(([k, v]) => pick(item, k) === v))\n    .map((item) => {\n      const tx = pick(item, spec.tx);\n      const to = spec.to ? pick(item, spec.to) : null;\n      const amount = spec.amount ? Number(pick(item, spec.amount)) : NaN;\n      const t = spec.time ? Number(pick(item, spec.time)) : NaN;\n      return {\n        tx: isHash(tx) ? lc(tx) : null,\n        to: isAddress(to) ? lc(to) : null,\n        amount: Number.isFinite(amount) ? amount : null,\n        // Seconds or milliseconds, whichever the project uses.\n        time: Number.isFinite(t) && t > 0 ? (t < 1e12 ? t * 1000 : t) : null,\n      };\n    });\n}\n\n// ── what the chain says about one transaction ───────────────────────────────\n\nexport interface TxFacts {\n  hash: string;\n  found: boolean;\n  /** Mined and succeeded. */\n  ok: boolean;\n  from: string;\n  /** The address the transaction was sent to (for a plain HYPE payment, the recipient). */\n  to: string;\n  /** Native HYPE sent with it. */\n  value: number;\n  block: number;\n  /** Block time, ms. */\n  time: number;\n  /** ERC-20 transfers in its receipt, 18 decimals assumed. */\n  transfers: { token: string; from: string; to: string; amount: number }[];\n}\n\n/** A cache that outlives one run (the store). A mined transaction never changes, so its facts are kept for good. */\nexport interface Cache {\n  get<T>(key: string): Promise<T | null>;\n  set(key: string, value: unknown): Promise<unknown>;\n}\n\n/** How many chain reads one check may still make in this run. Shared by the checks of one run. */\nexport interface ReadBudget {\n  left: number;\n}\n\nconst TRANSFER = \"0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\";\nconst wordAddress = (w: string) => lc(`0x${w.slice(-40)}`);\n\nexport async function readTx(hash: string, cache: Cache, budget: ReadBudget): Promise<TxFacts | null> {\n  const key = `chain.tx.${lc(hash)}`;\n  const hit = await cache.get<TxFacts>(key);\n  if (hit) return hit;\n  if (budget.left <= 0) return null;\n  budget.left -= 1;\n  const tx = await rpc<{ from: string; to: string | null; value: string; blockNumber: string | null } | null>(\"eth_getTransactionByHash\", [hash]);\n  if (!tx || !tx.blockNumber) {\n    // Not found, or not mined yet: not cached, so it is looked up again next run.\n    return { hash: lc(hash), found: false, ok: false, from: \"\", to: \"\", value: 0, block: 0, time: 0, transfers: [] };\n  }\n  const rc = await rpc<{ status: string; logs: { address: string; topics: string[]; data: string }[] }>(\"eth_getTransactionReceipt\", [hash]);\n  const blk = await rpc<{ timestamp: string }>(\"eth_getBlockByNumber\", [tx.blockNumber, false]);\n  const facts: TxFacts = {\n    hash: lc(hash),\n    found: true,\n    ok: rc.status === \"0x1\",\n    from: lc(tx.from),\n    to: lc(tx.to ?? \"\"),\n    value: Number(BigInt(tx.value)) / 1e18,\n    block: Number(BigInt(tx.blockNumber)),\n    time: Number(BigInt(blk.timestamp)) * 1000,\n    transfers: rc.logs\n      .filter((l) => l.topics[0] === TRANSFER && l.topics.length === 3)\n      .map((l) => ({ token: lc(l.address), from: wordAddress(l.topics[1]), to: wordAddress(l.topics[2]), amount: Number(BigInt(l.data)) / 1e18 })),\n  };\n  await cache.set(key, facts);\n  return facts;\n}\n\n/** A token balance just before a block (at the end of the block before it), read once and kept. */\nexport async function balanceBefore(token: string, holder: string, block: number, cache: Cache, budget: ReadBudget): Promise<number | null> {\n  const key = `chain.bal.${lc(token)}.${lc(holder)}.${block - 1}`;\n  const hit = await cache.get<number>(key);\n  if (hit !== null && hit !== undefined) return hit;\n  if (budget.left <= 0) return null;\n  budget.left -= 1;\n  const raw = await rpc<string>(\"eth_call\", [{ to: token, data: `0x70a08231${lc(holder).slice(2).padStart(64, \"0\")}` }, `0x${(block - 1).toString(16)}`]);\n  const amount = raw && raw !== \"0x\" ? Number(BigInt(raw)) / 1e18 : 0;\n  await cache.set(key, amount);\n  return amount;\n}\n\n// ── 1. payouts: each published payment is on chain as described ────────────\n\n/** What a payment must look like on chain. `asset` is \"native\" for HYPE, or a token address. */\nexport interface PayoutRule {\n  wallet: string;\n  asset: \"native\" | string;\n}\n\n/** Why one published payment does not match the chain, or null if it does. Pure. */\nexport function payoutProblem(r: PaidRecord, f: TxFacts, rule: PayoutRule): string | null {\n  if (!f.found) return \"transaction not found on Elysium\";\n  if (!f.ok) return \"transaction failed\";\n  const wallet = lc(rule.wallet);\n  if (rule.asset === \"native\") {\n    if (f.from !== wallet) return `sent from ${short(f.from)}, not the published wallet`;\n    if (r.to && f.to !== r.to) return `paid ${short(f.to)}, not the named recipient ${short(r.to)}`;\n    if (r.amount !== null && !near(f.value, r.amount)) return `moved ${num(f.value)} HYPE, not the ${num(r.amount)} listed`;\n    return null;\n  }\n  const token = lc(rule.asset);\n  const moved = f.transfers.filter((t) => t.token === token && t.from === wallet && (!r.to || t.to === r.to));\n  if (!moved.length) return r.to ? `no transfer of the token from the published wallet to ${short(r.to)}` : \"no transfer of the token from the published wallet\";\n  const total = moved.reduce((a, t) => a + t.amount, 0);\n  if (r.amount !== null && !near(total, r.amount)) return `moved ${num(total)} tokens, not the ${num(r.amount)} listed`;\n  return null;\n}\n\n/** Equal to the precision a project publishes: within 0.0001, or 0.1% for large amounts. */\nexport const near = (a: number, b: number) => Math.abs(a - b) <= Math.max(1e-4, Math.abs(b) * 1e-3);\n\n// ── 2. eligibility: who was paid met the project's own rule ────────────────\n\nexport interface HoldRule {\n  token: string;\n  /** Whole tokens a winner must hold. */\n  min: number;\n  /** ms: payments before the rule started are not judged. */\n  since: number;\n}\n\n/** Whether one paid recipient met the rule: null if the payment is outside the rule. Pure. */\nexport function holdBreach(f: TxFacts, recipient: string, held: number, rule: HoldRule): { recipient: string; held: number; time: number; hash: string } | false | null {\n  if (!f.found || !f.ok || f.time < rule.since) return null;\n  return held + 1e-9 < rule.min ? { recipient, held, time: f.time, hash: f.hash } : false;\n}\n\n// ── 3. split: a share of income really went where it was promised ──────────\n\n/** How much of a promised share was paid, measured on chain. Pure. */\nexport function splitRatio(share: number, incomeHype: number, paidHype: number): number | null {\n  const owed = share * incomeHype;\n  if (!(owed > 0)) return null;\n  return Math.max(0, Math.min(1, paidHype / owed));\n}\n\n// ── 4. wallet rule: where a wallet's tokens may go ─────────────────────────\n\n/** Addresses a wallet may send its token to without breaking \"we never send tokens\": burns and the pool. */\nexport const BURN_OR_POOL = [DEAD, ZERO, ...POOL_MANAGERS];\n\n/** Transfers out of `wallet` to anywhere not allowed. Pure. */\nexport function tokenRuleBreaches(transfers: { from: string; to: string; amount: number; hash: string; time: number }[], wallet: string, allowTo: string[]): typeof transfers {\n  const w = lc(wallet);\n  const allowed = new Set(allowTo.map(lc));\n  return transfers.filter((t) => lc(t.from) === w && !allowed.has(lc(t.to)) && t.amount > 0);\n}\n\n// ── 6. API figures against the chain ───────────────────────────────────────\n\n/** Whether a figure a project publishes matches the chain: within `tolerance` (a share) or 0.01, whichever is larger. Pure. */\nexport const matchesChain = (published: number, chain: number, tolerance: number) => Math.abs(published - chain) <= Math.max(0.01, Math.abs(chain) * tolerance);\n\nexport const short = (a: string) => (a.length > 12 ? `${a.slice(0, 6)}…${a.slice(-4)}` : a);\nconst num = (n: number) => n.toLocaleString(\"en-US\", { maximumFractionDigits: 4 });\n"},{"path":"src/sources/liquidity.ts","role":"Whether launch liquidity is locked, read from the chain: the launchpad hook's seed position, its code, and how much liquidity is still in it.","lines":101,"sha256":"a9f654139dd729b52a9de0eb8f2d8ba413866a57da06dda74c874073fca2e81c","content":"import { encodeAbiParameters, encodePacked, keccak256, type Hex } from \"viem\";\nimport { LAUNCHPADS } from \"../lib/liquidity.ts\";\nimport { rpc } from \"./elysium.ts\";\n\nexport { LAUNCHPADS };\n\n/**\n * Whether a token's launch liquidity is locked, read from the chain instead of taken from the project's own page.\n *\n * Montra and Ascend both launch a token by seeding a Uniswap v4 pool in one transaction, with the seed position owned\n * by the launchpad's own hook contract. So the question per token is: does the launchpad's hook hold the launch\n * position, is the hook the contract that was checked (same code), and is the liquidity still all there?\n *\n * What was checked about each hook, once (27 Nov 2026), is in LAUNCHPADS (src/lib/liquidity.ts). What is read for each token, every chain\n * refresh: the launch transaction's seed position, the hook's code hash, and the position's liquidity today.\n */\nexport const POOL_MANAGER = \"0xe2e105d3f7209a9da11f83ccf3e7398a753823f1\";\nconst INITIALIZE = \"0xdd466e674ea557f56295e2d0218a125ea4b4f0f6f3307b95f85e6110838d6438\";\nconst MODIFY_LIQUIDITY = \"0xf208f4912782fd25c7f114ca3723a2d5dd6f3bcc3ac8db5af63baa85f711d5ec\";\n/** Uniswap v4 PoolManager storage: `pools` mapping slot, and the `positions` mapping's offset inside a pool. */\nconst POOLS_SLOT = 6n;\nconst POSITIONS_OFFSET = 6n;\n\nexport interface LiquidityFacts {\n  status: \"locked\" | \"unlocked\" | \"unknown\";\n  /** One sentence: what was found. */\n  why: string;\n  pad: string | null;\n  hook: string | null;\n  pool: string | null;\n  /** The seed position's liquidity at launch and now (Uniswap liquidity units, as decimal strings). */\n  launchLiquidity: string | null;\n  liquidityNow: string | null;\n  /** liquidityNow ÷ launchLiquidity. */\n  share: number | null;\n  readAt: number;\n}\n\ninterface Log {\n  address: string;\n  topics: string[];\n  data: string;\n}\n\nconst word = (data: string, i: number) => BigInt(`0x${data.slice(2 + 64 * i, 2 + 64 * (i + 1))}`);\nconst int = (x: bigint) => BigInt.asIntN(256, x);\nconst topicOf = (address: string) => `0x${address.toLowerCase().replace(/^0x/, \"\").padStart(64, \"0\")}`;\n\n/** The launch position the hook created for this token in its launch transaction. Pure. */\nexport function seedPosition(logs: Log[], token: string, hook: string): { pool: Hex; tickLower: number; tickUpper: number; salt: Hex; liquidity: bigint } | null {\n  const t = topicOf(token);\n  const pool = logs.find((l) => l.address.toLowerCase() === POOL_MANAGER && l.topics[0] === INITIALIZE && (l.topics[2]?.toLowerCase() === t || l.topics[3]?.toLowerCase() === t))?.topics[1];\n  if (!pool) return null;\n  const add = logs.find(\n    (l) => l.address.toLowerCase() === POOL_MANAGER && l.topics[0] === MODIFY_LIQUIDITY && l.topics[1] === pool && l.topics[2]?.toLowerCase() === topicOf(hook) && int(word(l.data, 2)) > 0n,\n  );\n  if (!add) return null;\n  return {\n    pool: pool as Hex,\n    tickLower: Number(int(word(add.data, 0))),\n    tickUpper: Number(int(word(add.data, 1))),\n    salt: `0x${add.data.slice(2 + 64 * 3, 2 + 64 * 4)}` as Hex,\n    liquidity: int(word(add.data, 2)),\n  };\n}\n\n/** The PoolManager storage slot holding a position's liquidity (StateLibrary's layout). Pure. */\nexport function positionSlot(pool: Hex, owner: `0x${string}`, tickLower: number, tickUpper: number, salt: Hex): Hex {\n  const positionKey = keccak256(encodePacked([\"address\", \"int24\", \"int24\", \"bytes32\"], [owner, tickLower, tickUpper, salt]));\n  const stateSlot = BigInt(keccak256(encodeAbiParameters([{ type: \"bytes32\" }, { type: \"uint256\" }], [pool, POOLS_SLOT])));\n  const positions = stateSlot + POSITIONS_OFFSET;\n  return keccak256(encodeAbiParameters([{ type: \"bytes32\" }, { type: \"uint256\" }], [positionKey, positions]));\n}\n\nconst unknown = (why: string, now: number, pad: string | null = null): LiquidityFacts => ({ status: \"unknown\", why, pad, hook: null, pool: null, launchLiquidity: null, liquidityNow: null, share: null, readAt: now });\n\n/** Read a token's launch liquidity from Elysium. Never throws: a failed read is \"unknown\", with the reason. */\nexport async function readLaunchLiquidity(pad: string, launchTx: string | null | undefined, token: string, now = Date.now()): Promise<LiquidityFacts> {\n  const lp = LAUNCHPADS[pad];\n  if (!lp) return unknown(`Sentinel does not yet read how ${pad} holds launch liquidity.`, now, pad);\n  if (!launchTx || !/^0x[0-9a-fA-F]{64}$/.test(launchTx)) return unknown(\"The listing has no launch transaction to read the pool from.\", now, pad);\n  try {\n    const receipt = await rpc<{ status: string; logs: Log[] } | null>(\"eth_getTransactionReceipt\", [launchTx]);\n    if (!receipt || receipt.status !== \"0x1\") return unknown(\"The launch transaction could not be read.\", now, pad);\n    const seed = seedPosition(receipt.logs, token, lp.hook);\n    if (!seed) return unknown(`The launch transaction does not seed this token's pool from ${lp.name}'s hook.`, now, pad);\n    const code = await rpc<Hex>(\"eth_getCode\", [lp.hook, \"latest\"]);\n    if (keccak256(code) !== lp.codeHash) return unknown(`${lp.name}'s hook no longer has the code Sentinel checked, so its lock is not assumed.`, now, pad);\n    const slot = positionSlot(seed.pool, lp.hook, seed.tickLower, seed.tickUpper, seed.salt);\n    const raw = await rpc<Hex>(\"eth_call\", [{ to: POOL_MANAGER, data: `0x1e2eaeaf${slot.slice(2)}` }, \"latest\"]);\n    const liquidityNow = BigInt(raw) & ((1n << 128n) - 1n);\n    const share = Number((liquidityNow * 10_000n) / seed.liquidity) / 10_000;\n    const base = { pad, hook: lp.hook, pool: seed.pool, launchLiquidity: seed.liquidity.toString(), liquidityNow: liquidityNow.toString(), share, readAt: now };\n    if (liquidityNow >= seed.liquidity)\n      return { ...base, status: \"locked\", why: `All of the launch liquidity is still in the pool, held by ${lp.name}'s hook, which cannot remove it.` };\n    return { ...base, status: \"unlocked\", why: `${Math.round((1 - share) * 1000) / 10}% of the launch liquidity has left the position ${lp.name}'s hook holds.` };\n  } catch (e) {\n    return unknown(`The chain read failed: ${e instanceof Error ? e.message.slice(0, 120) : \"error\"}.`, now, pad);\n  }\n}\n"},{"path":"src/lib/liquidity.ts","role":"Which liquidity reading counts: the chain's when it is clear, otherwise the project's own statement.","lines":55,"sha256":"cdae049aaf2fe981cc29c3fda7fe31b71229a0e362518d6b8d790bbfb47f97a0","content":"import type { ProjectDoc } from \"../server/pipeline.ts\";\nimport type { Project } from \"../server/registry.ts\";\n\ntype Hex = `0x${string}`;\n\n/** How each launchpad holds a token's launch liquidity, and why a position it holds cannot be removed. */\nexport interface Launchpad {\n  name: string;\n  /** The hook contract that owns every launch position. */\n  hook: `0x${string}`;\n  /** keccak256 of the hook's runtime code when it was checked. A different hash means a different contract. */\n  codeHash: Hex;\n  /** Why a position held by this hook cannot be removed, in one sentence each, and where to check. */\n  basis: string[];\n  docs: string;\n}\n\nexport const LAUNCHPADS: Record<string, Launchpad> = {\n  montra: {\n    name: \"Montra\",\n    hook: \"0x6b1216a40b65c83e9c9e18a562c446697b8cf8ec\",\n    codeHash: \"0x1be97e9e8bab23afd85598310005dd27f934013c3993cc3db6bd806ae8d1d953\",\n    basis: [\n      \"Montra's hook owns the launch position; no wallet does.\",\n      \"The hook cannot be changed: it is not a proxy, and its code has no DELEGATECALL or SELFDESTRUCT.\",\n      \"Montra documents that the hook never removes liquidity from its own position and has no function that could.\",\n      \"Checked 27 Nov 2026: across all 114,068 Montra pools, the hook has added liquidity and never removed any.\",\n    ],\n    docs: \"https://montraxyz.com/docs/reference#the-pool-and-its-lines-launchhook\",\n  },\n  ascend: {\n    name: \"Ascend\",\n    hook: \"0xe0def4221b9840a610d4e7d55812a79a6431a8ec\",\n    codeHash: \"0x190f4d572cbca47e96519434e6c6dfd537ffd13ce9e5a657fa5fa120a4bad6f1\",\n    basis: [\n      \"Ascend's launchpad contract (its hook) owns the launch position; no wallet does.\",\n      \"The contract cannot be changed: it is not a proxy, and its code has no DELEGATECALL or SELFDESTRUCT.\",\n      \"Its functions match Ascend's published contract interface, and none of them removes liquidity. The owner's pause stops new launches, not trading.\",\n      \"Checked 27 Nov 2026: across all 4,531 Ascend pools, the contract has added liquidity and never removed any.\",\n    ],\n    docs: \"https://app.ascendlaunch.xyz/technical-docs\",\n  },\n};\n\n\n/**\n * The liquidity reading that counts: the chain's (src/sources/liquidity.ts) when it could tell locked from unlocked;\n * otherwise what the project itself states. `source` says which. Pure, and safe to use in the browser.\n */\nexport function liquidityOf(project: Pick<Project, \"liquidity\">, doc: Pick<ProjectDoc, \"token\">): { status: Project[\"liquidity\"][\"status\"]; source: \"chain\" | \"stated\" } {\n  const chain = doc.token?.liquidity;\n  if (chain && chain.status !== \"unknown\") return { status: chain.status, source: \"chain\" };\n  return { status: project.liquidity.status, source: \"stated\" };\n}\n"},{"path":"src/sources/market.ts","role":"The market-cap read. It decides only whether a project is on the board, never its score.","lines":36,"sha256":"51cf547d252fa692cffdd8fcafce09449264d9df54e4600887b2fef43c5c66c6","content":"/**\n * Market readings. They never enter a score: they only decide whether a project is on the board (the listing\n * floor in docs/scoring.md). A token's price in HYPE comes from the Kleos launchpad indexer, which follows Montra\n * and Ascend pools; HYPE's dollar price is Hyperliquid's mid.\n */\nconst PADS_URL = process.env.PADS_API_URL ?? \"https://rpc.thekleos.pro/pads\";\nconst HL_INFO_URL = process.env.HL_INFO_URL ?? \"https://api.hyperliquid.xyz/info\";\n\nexport interface TokenMarket {\n  /** Price of one token in HYPE. */\n  priceHype: number;\n  /** HYPE traded in the last 24 hours. */\n  volumeHype: number;\n}\n\nexport async function fetchTokenMarket(token: string): Promise<TokenMarket> {\n  const res = await fetch(`${PADS_URL}/token/${token.toLowerCase()}`, { signal: AbortSignal.timeout(15_000) });\n  if (!res.ok) throw new Error(`price source answered ${res.status}`);\n  const body = (await res.json()) as { priceHype?: number; volumeHype?: number };\n  if (!(Number(body.priceHype) > 0)) throw new Error(\"price source has no price for this token\");\n  return { priceHype: Number(body.priceHype), volumeHype: Number(body.volumeHype) || 0 };\n}\n\nlet hype: { at: number; usd: number } | null = null;\n\n/** HYPE in dollars, remembered for a minute so one run asks once. */\nexport async function fetchHypeUsd(now = Date.now()): Promise<number> {\n  if (hype && now - hype.at < 60_000) return hype.usd;\n  const res = await fetch(HL_INFO_URL, { method: \"POST\", headers: { \"content-type\": \"application/json\" }, body: JSON.stringify({ type: \"allMids\" }), signal: AbortSignal.timeout(15_000) });\n  if (!res.ok) throw new Error(`Hyperliquid answered ${res.status}`);\n  const usd = Number(((await res.json()) as Record<string, string>).HYPE);\n  if (!(usd > 0)) throw new Error(\"Hyperliquid has no HYPE price\");\n  hype = { at: now, usd };\n  return usd;\n}\n"}],"fingerprint":"0xc803a06f2083c591ac2b542a0cce3bcfa0b42fda1177acc0754168481ef2e92b"}