diff --git a/.env.example b/.env.example index d0234bd..d5538c1 100644 --- a/.env.example +++ b/.env.example @@ -31,6 +31,10 @@ DATABASE_URL=postgresql://user:password@localhost:5432/megastera # MINERAL_ECONOMY_CUTOVER_AT= # Keep disabled until the migration, SIWE env, and production smoke test are complete. # MINERAL_UPGRADES_ENABLED=false +# First finalized JackpotSettled block ingested by the leaderboard worker. Empty disables Galaxy Pulse. +# GALAXY_PULSE_START_BLOCK= +# Secret used by the protected Vercel Cron leaderboard worker endpoint. +# CRON_SECRET= # Required only before enabling upgrades: exact canonical HTTPS origin, without a trailing slash. # SIWE_ORIGIN= # Required only before enabling upgrades: server-only random secret containing at least 32 bytes. diff --git a/.gitignore b/.gitignore index 4723e95..28c8023 100644 --- a/.gitignore +++ b/.gitignore @@ -61,3 +61,5 @@ packages/planet-generator/generated-*/ # Claude Code workspace state (settings, launch configs, hooks) .claude/ +.vercel +.env* diff --git a/README.md b/README.md index bd75d9a..a11742a 100644 --- a/README.md +++ b/README.md @@ -111,6 +111,8 @@ The automated reward contract is a future upgrade; it is not presented as part o Seasonal rewards can expand beyond monetary payouts over time and may include gameplay assets, planets or other items introduced by future mechanics. +Implementation note: the active backend exposes live standings with a current UTC-day period label and has a separate daily finalization worker for archived rows. Reward settlement is not an automated smart-contract or HTTP path in this repository; the Season 1 countdown and prize copy are presented by the client. + ## Why Megapot is core Megapot is not a secondary widget, a link-out, or an unrelated protocol attached to the game. @@ -234,6 +236,7 @@ The browser handles interaction, but it is not the authority for planet creation - Planet generation is deterministic and idempotent. - Conflicting persisted provenance fails closed. - Mining is derived from persisted planet data rather than mutable browser state. +- Same-type collection bonuses are derived from persisted Planet generation times rather than a browser-owned ledger. - After the mineral-economy cutover, wallet balances and current leaderboard scores are derived from persisted integer-micro account and upgrade history; V1 remains the pre-cutover fallback. - Generated GIF bytes are stored with an immutable content hash. - Server credentials and database secrets never enter the Vite client environment. @@ -251,7 +254,7 @@ Future seasons can expand that foundation with colonies, stars, ships, trading, ## Repository ```text -megastera/ +MegasteraGame/ ├── src/ # React application and game UI ├── api/ # Receipt verification, planet API, mining, leaderboard ├── packages/planet-generator # Shared deterministic planet generator @@ -265,10 +268,10 @@ megastera/ ### Stack -**Frontend:** React 19, TypeScript, Vite, wagmi, viem, RainbowKit -**Protocol:** Megapot on Base -**Backend:** Hono, PostgreSQL, Prisma -**Rendering:** shared deterministic planet generator +**Frontend:** React 19, TypeScript, Vite, wagmi, viem, RainbowKit
+**Protocol:** Megapot on Base
+**Backend:** Hono, PostgreSQL, Prisma
+**Rendering:** shared deterministic planet generator
**Quality:** Vitest, TypeScript, Biome, GitHub Actions ## Run locally @@ -290,13 +293,13 @@ Copy the required values from [`.env.example`](.env.example) into your local env Every pull request and push to `main` runs the repository quality gate: ```bash +pnpm db:generate +pnpm db:validate pnpm lint pnpm typecheck pnpm test pnpm --filter @megaplanets/planet-generator golden pnpm build -pnpm db:generate -pnpm db:validate ``` ## License diff --git a/api/README.md b/api/README.md index 977710f..034171d 100644 --- a/api/README.md +++ b/api/README.md @@ -38,4 +38,4 @@ The HTTP server defaults to `127.0.0.1:8787`; set `MEGAPLANETS_API_HOST` and `ME - Receipt verification checks Base mainnet, canonical jackpot/source, event fields, confirmation depth, block hash, and optional wallet recipient. - Generation is idempotent on `originTxHash:logIndex`; conflicting persisted provenance is rejected. - GIF bytes are stored in PostgreSQL and served with an immutable content hash. -- Leaderboard reads are derived from ready persisted Planet records, collection milestones, and—after cutover—mineral account and upgrade history. +- Leaderboard reads are derived from ready persisted Planet records and same-type collection milestones; after cutover, mineral account and upgrade history also contribute to spendable scores. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 5a6bdb7..f2838a4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -38,7 +38,7 @@ The source tag is always `MEGASTERA`. It is a Megapot attribution value and does ## Backend API -The Vercel entrypoint `api/index.ts` delegates to `server/api/index.ts`, which mounts only: +The Vercel entrypoint `api/index.ts` delegates to `server/api/index.ts`, which mounts: - backend Planet generation, collection, GIF, and wallet mining routes; - the server-disabled Planet upgrade endpoint; @@ -52,6 +52,8 @@ The Vercel entrypoint `api/index.ts` delegates to `server/api/index.ts`, which m No active module signs vouchers, pins media, reads a Planet contract, projects Planet events, scans all tickets continuously, or writes transfer/accrual ledgers. The upgrade endpoint remains server-disabled because it does not yet verify a request-wallet signature. +`server/api/leaderboardWorker.ts` is the scheduler entrypoint. The protected `/api/internal/leaderboard-worker` Vercel endpoint runs it from the daily production Cron; `pnpm api:leaderboard-worker` remains available for local/manual runs. It finalizes completed UTC-day periods into `LeaderboardPeriod` and `LeaderboardEntry`. + ## Frontend boundaries `src/pages/Play.tsx` owns checkout and, after canonical receipt recovery in the purchase hooks, requests backend generation with bounded finality retries. The active UI has two stages: Buy tickets and Explore planets. On success it shows the generated cards full screen with `Explore again` and `My planets` actions. @@ -71,6 +73,7 @@ The `BackendPlanet` model is linked one-to-one to `TicketPurchase` and stores: - ready/failed status plus bounded generation error text. This worktree additionally stores `upgradeLevel` and `upgradeBonusBps` on `BackendPlanet`, opening/current balances in `MineralAccount`, the authoritative cutover in `MineralEconomyCutover`, and idempotent `(planetId, targetLevel)` charges in `PlanetUpgradePurchase`. V2 calculations use integer micros and keep the V1 opening-balance calculation as the cutover anchor. +Same-type collection bonuses are derived at read time from Planet generation timestamps; they are not stored as accrual or ledger rows. The active leaderboard and wallet/Planet mining reads therefore remain reproducible from immutable Planet data. Legacy Prisma tables and migrations are retained only for database compatibility. No active code writes the legacy Planet, voucher, artifact, projector, or accrual paths. diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md index effff7a..595a94d 100644 --- a/docs/OPERATIONS.md +++ b/docs/OPERATIONS.md @@ -18,6 +18,8 @@ MEGAPLANETS_API_HOST # optional standalone server host MEGAPLANETS_API_PORT # optional standalone server port MINERAL_ECONOMY_CUTOVER_AT # optional exact UTC-midnight ISO timestamp; empty keeps V1 MINERAL_UPGRADES_ENABLED=false # reserved; public upgrades remain server-disabled +GALAXY_PULSE_START_BLOCK # optional first JackpotSettled block; empty disables Galaxy Pulse +CRON_SECRET # required by the protected Vercel leaderboard worker Cron ``` Frontend values use `VITE_*` only for public configuration, including `VITE_CHAIN`, wallet/RPC settings, `VITE_API_BASE_URL`, and optional `VITE_BACKEND_API_BASE_URL`. The Megapot Data API defaults to `https://api.megapot.io/v1` for Base mainnet. If `VITE_API_BASE_URL=/api/megapot` is used, the checked-in proxy targets that same mainnet host and may use server-only `MEGAPOT_API_KEY`. Never put `DATABASE_URL`, server tokens, or private keys in a Vite variable. @@ -39,12 +41,14 @@ Check: - `GET /api/leaderboard/current` for live standings; and - `/api/megapot/*` for the same-origin Megapot Data API proxy. -There is intentionally no readiness route that probes a Planet contract and no indexer process to start. +There is intentionally no readiness route that probes a Planet contract. In production, Vercel Cron calls `/api/internal/leaderboard-worker` daily at 00:05 UTC with `CRON_SECRET`; the endpoint runs the same idempotent leaderboard worker used by `pnpm api:leaderboard-worker`. ## Purchase and generation troubleshooting The frontend must send the execution transaction hash and exact `TicketPurchased` log index. The API then checks receipt status, Base mainnet, canonical jackpot, `MEGASTERA` source tag, ticket fields, confirmation depth, canonical block hash, and optional recipient. The Play screen retries the same reference while the receipt reaches finality; the backend persists the proof before rendering the GIF, so a generation/storage failure leaves a retryable pending collection row. +Play checkout checks the current USDC allowance against the exact purchase total before showing the purchase action. If the allowance is insufficient, the approval transaction grants a reusable allowance to the route-specific Megapot spender; bulk-order simulation runs only after that approval gate resolves. The UI distinguishes insufficient USDC balance, a rejected wallet transaction, and wallet/network failures. + If generation returns `422`, inspect server logs for the request and RPC stage; do not retry with a different log index unless the receipt actually contains another canonical ticket event. Repeating the same valid request is safe: the key is `originTxHash:logIndex`, and an existing ready row is returned. If the receipt is not yet final, My Planets keeps the browser-confirmed receipt as a pending card and the catch-up pass retries it later. If the database already contains a conflicting ticket or Planet row, preserve it and investigate the immutable provenance mismatch. Do not delete production data as a first response. @@ -59,11 +63,13 @@ With no `MINERAL_ECONOMY_CUTOVER_AT`, mining and leaderboard reads follow the V1 baseMineralsPerDay × elapsed milliseconds × 1_000_000 / 86_400_000 ``` -The start time is the backend generation timestamp. Same-type collection milestones apply at 3 (+5%), 5 (+7.5%), and 10 (+10%) matching Planets. The browser never writes accrual or ledger rows. Before cutover, public leaderboard routes calculate current rows from ready backend Planet `generatedAt` and `baseMineralsPerDay` values and apply the V1 collection calculation. Live leaderboard reads are uncached. +The start time is the backend generation timestamp. The base rate is `baseMineralsPerDay × 1_000_000` micros/day. Same-type collection milestones apply at 3 (+5%), 5 (+7.5%), and 10 (+10%) matching Planets. Earned micros are calculated over each rate interval with integer arithmetic; the browser only interpolates the returned snapshot for display and never writes accrual or ledger rows. Before cutover, public leaderboard routes calculate current rows from ready backend Planet `generatedAt` and `baseMineralsPerDay` values and apply the V1 collection calculation. Live leaderboard reads are uncached. When the prepared cutover is active, the wallet mining route settles `MineralAccount` balance in integer micros from the cutover forward. New Planet generation settles the owner's account before inserting the new Planet. Level 1/2/3 persistence primitives retain +10%/+25%/+50% bonuses and idempotent `(planetId, targetLevel)` charges, but `POST /api/planets/:planetId/upgrade` remains server-disabled until owner-bound authorization exists. A configured cutover that was not persisted before PostgreSQL reaches it fails closed. -The cutover migration must be applied before setting the environment variable. Before cutover, the current leaderboard remains V1; after cutover, it ranks spendable mineral scores reconstructed as opening balance plus historical production minus upgrade costs, and reports the effective per-day rate after collection and upgrade events. +The cutover migration must be applied before setting the environment variable. Before cutover, the current leaderboard remains V1; after cutover, it ranks spendable mineral scores reconstructed as opening balance plus historical production minus upgrade costs, and reports the effective per-day rate after collection, upgrade, and Galaxy Pulse events. + +Galaxy Pulse starts strictly at `GALAXY_PULSE_START_BLOCK`; there is no historical backfill. The leaderboard worker verifies finalized `JackpotSettled` receipts, derives a deterministic seed from `drawingId` and `winningNumbers`, and advances the sole indexer cursor. Wallet mining reads only the latest authoritative database snapshot. Balance mutations and leaderboard finalization fail closed until the database round matches the current settled drawing reported by the Megapot Data API. ### Cutover preparation @@ -92,7 +98,7 @@ pnpm minerals:backfill It refuses to run when the cutover variable is absent or when PostgreSQL `clock_timestamp()` is before the configured cutover. Account creation is create-only and idempotent: existing `MineralAccount` balances are never reset; concurrent duplicates are skipped. If the configured cutover conflicts with the persisted singleton, the command fails closed. Keep the transaction short and rerun after correcting configuration or clock/migration state. -`pnpm api:leaderboard-worker` is the separate finalization command for completed UTC days; it writes archived `LeaderboardPeriod`/`LeaderboardEntry` rows when scheduled, but no HTTP history/finalization route is exposed. +`pnpm api:leaderboard-worker` first ingests finalized Galaxy Pulse rounds, then finalizes completed UTC days. It writes archived `LeaderboardPeriod`/`LeaderboardEntry` rows when scheduled, but no HTTP history/finalization or separate Galaxy Pulse route is exposed. Ticket status uses `useJackpotState` for the live drawing countdown/phase and the Base mainnet Megapot Data API for wallet ticket/win history. The wallet ticket list follows opaque cursors to completion for My Planets and stops on API errors without showing a false empty collection. `Claim winnings` remains an on-chain `Jackpot.claimWinnings(uint256[])` call after simulation, capped at 50 IDs per batch; confirmed receipts invalidate the wallet ticket/win queries. diff --git a/package.json b/package.json index 51d7103..6cb9450 100644 --- a/package.json +++ b/package.json @@ -8,7 +8,7 @@ "scripts": { "bootstrap": "pnpm install", "dev": "vite", - "prebuild": "pnpm --filter @megaplanets/planet-generator build", + "prebuild": "node scripts/deploy-production-migrations.mjs && pnpm --filter @megaplanets/planet-generator build", "predev": "pnpm --filter @megaplanets/planet-generator build", "pretest": "pnpm --filter @megaplanets/planet-generator build", "build": "prisma generate && tsc -b && vite build && node scripts/prepare-site-worker.mjs", @@ -18,7 +18,6 @@ "minerals:prepare": "node --import tsx/esm server/api/mineralCutoverPrepare.ts", "minerals:backfill": "node --import tsx/esm server/api/mineralBackfill.ts", "minerals:backfill:dry-run": "pnpm minerals:backfill --dry-run", - "test:postgres": "pnpm --filter @megaplanets/planet-generator build && MINERAL_ECONOMY_REQUIRE_POSTGRES=1 vitest run server/api/mineralConcurrency.postgres.test.ts", "preview": "vite preview", "typecheck": "tsc -b --noEmit && tsc -p tsconfig.vercel.json --noEmit", "typecheck:vercel": "tsc -p tsconfig.vercel.json --noEmit", diff --git a/prisma/migrations/20260822160000_galaxy_pulse_rounds/migration.sql b/prisma/migrations/20260822160000_galaxy_pulse_rounds/migration.sql new file mode 100644 index 0000000..06a2c63 --- /dev/null +++ b/prisma/migrations/20260822160000_galaxy_pulse_rounds/migration.sql @@ -0,0 +1,10 @@ +CREATE TABLE "galaxy_pulse_rounds" ( + "drawingId" DECIMAL(78,0) NOT NULL, + "entropy" CHAR(66) NOT NULL, + "settlementTxHash" CHAR(66) NOT NULL, + "settledAt" TIMESTAMPTZ(3) NOT NULL, + + CONSTRAINT "galaxy_pulse_rounds_pkey" PRIMARY KEY ("drawingId") +); + +CREATE INDEX "galaxy_pulse_rounds_settledAt_idx" ON "galaxy_pulse_rounds"("settledAt"); diff --git a/prisma/migrations/20260823100000_galaxy_pulse_seed/migration.sql b/prisma/migrations/20260823100000_galaxy_pulse_seed/migration.sql new file mode 100644 index 0000000..fb33553 --- /dev/null +++ b/prisma/migrations/20260823100000_galaxy_pulse_seed/migration.sql @@ -0,0 +1 @@ +ALTER TABLE "galaxy_pulse_rounds" RENAME COLUMN "entropy" TO "seed"; diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 147ac23..736a627 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -251,6 +251,16 @@ model IndexerCursor { @@map("indexer_cursors") } +model GalaxyPulseRound { + drawingId Decimal @id @db.Decimal(78, 0) + seed String @db.Char(66) + settlementTxHash String @db.Char(66) + settledAt DateTime @db.Timestamptz(3) + + @@index([settledAt]) + @@map("galaxy_pulse_rounds") +} + model DailySnapshotRecord { id String @id @default(uuid()) @db.Uuid blockNumber BigInt diff --git a/public/galaxy-pulse/desert.png b/public/galaxy-pulse/desert.png new file mode 100644 index 0000000..be7c949 Binary files /dev/null and b/public/galaxy-pulse/desert.png differ diff --git a/public/galaxy-pulse/gaia.png b/public/galaxy-pulse/gaia.png new file mode 100644 index 0000000..2877dda Binary files /dev/null and b/public/galaxy-pulse/gaia.png differ diff --git a/public/galaxy-pulse/gas-giant.png b/public/galaxy-pulse/gas-giant.png new file mode 100644 index 0000000..fa9b947 Binary files /dev/null and b/public/galaxy-pulse/gas-giant.png differ diff --git a/public/galaxy-pulse/nebula.png b/public/galaxy-pulse/nebula.png new file mode 100644 index 0000000..908af34 Binary files /dev/null and b/public/galaxy-pulse/nebula.png differ diff --git a/public/galaxy-pulse/oceanic.png b/public/galaxy-pulse/oceanic.png new file mode 100644 index 0000000..9a9bc3e Binary files /dev/null and b/public/galaxy-pulse/oceanic.png differ diff --git a/public/galaxy-pulse/rocky.png b/public/galaxy-pulse/rocky.png new file mode 100644 index 0000000..c0f7afd Binary files /dev/null and b/public/galaxy-pulse/rocky.png differ diff --git a/public/galaxy-pulse/toxic.png b/public/galaxy-pulse/toxic.png new file mode 100644 index 0000000..f44f0fa Binary files /dev/null and b/public/galaxy-pulse/toxic.png differ diff --git a/public/galaxy-pulse/triplex.png b/public/galaxy-pulse/triplex.png new file mode 100644 index 0000000..e6cd206 Binary files /dev/null and b/public/galaxy-pulse/triplex.png differ diff --git a/public/galaxy-pulse/void.png b/public/galaxy-pulse/void.png new file mode 100644 index 0000000..9cfb028 Binary files /dev/null and b/public/galaxy-pulse/void.png differ diff --git a/public/galaxy-pulse/volcanic.png b/public/galaxy-pulse/volcanic.png new file mode 100644 index 0000000..e71720d Binary files /dev/null and b/public/galaxy-pulse/volcanic.png differ diff --git a/public/landing/gifs-512/planet-001.gif b/public/landing/gifs-512/planet-001.gif new file mode 100644 index 0000000..8428a29 Binary files /dev/null and b/public/landing/gifs-512/planet-001.gif differ diff --git a/public/landing/gifs-512/planet-002.gif b/public/landing/gifs-512/planet-002.gif new file mode 100644 index 0000000..a98ffd5 Binary files /dev/null and b/public/landing/gifs-512/planet-002.gif differ diff --git a/public/landing/gifs-512/planet-003.gif b/public/landing/gifs-512/planet-003.gif new file mode 100644 index 0000000..b913f34 Binary files /dev/null and b/public/landing/gifs-512/planet-003.gif differ diff --git a/public/landing/gifs-512/planet-004.gif b/public/landing/gifs-512/planet-004.gif new file mode 100644 index 0000000..4140abe Binary files /dev/null and b/public/landing/gifs-512/planet-004.gif differ diff --git a/public/landing/gifs-512/planet-005.gif b/public/landing/gifs-512/planet-005.gif new file mode 100644 index 0000000..4d364d6 Binary files /dev/null and b/public/landing/gifs-512/planet-005.gif differ diff --git a/public/landing/gifs-512/planet-006.gif b/public/landing/gifs-512/planet-006.gif new file mode 100644 index 0000000..686bc49 Binary files /dev/null and b/public/landing/gifs-512/planet-006.gif differ diff --git a/public/landing/gifs-512/planet-007.gif b/public/landing/gifs-512/planet-007.gif new file mode 100644 index 0000000..471992b Binary files /dev/null and b/public/landing/gifs-512/planet-007.gif differ diff --git a/public/landing/gifs-512/planet-008.gif b/public/landing/gifs-512/planet-008.gif new file mode 100644 index 0000000..8526016 Binary files /dev/null and b/public/landing/gifs-512/planet-008.gif differ diff --git a/public/landing/gifs-512/planet-009.gif b/public/landing/gifs-512/planet-009.gif new file mode 100644 index 0000000..4ca0812 Binary files /dev/null and b/public/landing/gifs-512/planet-009.gif differ diff --git a/public/landing/gifs-512/planet-010.gif b/public/landing/gifs-512/planet-010.gif new file mode 100644 index 0000000..517e719 Binary files /dev/null and b/public/landing/gifs-512/planet-010.gif differ diff --git a/public/landing/gifs-512/planet-011.gif b/public/landing/gifs-512/planet-011.gif new file mode 100644 index 0000000..004ce86 Binary files /dev/null and b/public/landing/gifs-512/planet-011.gif differ diff --git a/public/landing/gifs-512/planet-012.gif b/public/landing/gifs-512/planet-012.gif new file mode 100644 index 0000000..01a8eb5 Binary files /dev/null and b/public/landing/gifs-512/planet-012.gif differ diff --git a/public/landing/gifs-512/planet-013.gif b/public/landing/gifs-512/planet-013.gif new file mode 100644 index 0000000..2698d1e Binary files /dev/null and b/public/landing/gifs-512/planet-013.gif differ diff --git a/public/landing/gifs-512/planet-014.gif b/public/landing/gifs-512/planet-014.gif new file mode 100644 index 0000000..76c1d77 Binary files /dev/null and b/public/landing/gifs-512/planet-014.gif differ diff --git a/public/landing/gifs-512/planet-015.gif b/public/landing/gifs-512/planet-015.gif new file mode 100644 index 0000000..daf0a79 Binary files /dev/null and b/public/landing/gifs-512/planet-015.gif differ diff --git a/public/landing/gifs-512/planet-016.gif b/public/landing/gifs-512/planet-016.gif new file mode 100644 index 0000000..f471a4e Binary files /dev/null and b/public/landing/gifs-512/planet-016.gif differ diff --git a/public/landing/gifs-512/planet-017.gif b/public/landing/gifs-512/planet-017.gif new file mode 100644 index 0000000..833dcbc Binary files /dev/null and b/public/landing/gifs-512/planet-017.gif differ diff --git a/public/landing/gifs-512/planet-018.gif b/public/landing/gifs-512/planet-018.gif new file mode 100644 index 0000000..d36f4ec Binary files /dev/null and b/public/landing/gifs-512/planet-018.gif differ diff --git a/public/landing/gifs-512/planet-019.gif b/public/landing/gifs-512/planet-019.gif new file mode 100644 index 0000000..4780c2a Binary files /dev/null and b/public/landing/gifs-512/planet-019.gif differ diff --git a/public/landing/gifs-512/planet-020.gif b/public/landing/gifs-512/planet-020.gif new file mode 100644 index 0000000..e1ab00a Binary files /dev/null and b/public/landing/gifs-512/planet-020.gif differ diff --git a/public/landing/gifs-512/planet-021.gif b/public/landing/gifs-512/planet-021.gif new file mode 100644 index 0000000..c4f6b60 Binary files /dev/null and b/public/landing/gifs-512/planet-021.gif differ diff --git a/public/landing/gifs-512/planet-022.gif b/public/landing/gifs-512/planet-022.gif new file mode 100644 index 0000000..ba8dac7 Binary files /dev/null and b/public/landing/gifs-512/planet-022.gif differ diff --git a/public/landing/gifs-512/planet-023.gif b/public/landing/gifs-512/planet-023.gif new file mode 100644 index 0000000..790ddcb Binary files /dev/null and b/public/landing/gifs-512/planet-023.gif differ diff --git a/public/landing/gifs-512/planet-024.gif b/public/landing/gifs-512/planet-024.gif new file mode 100644 index 0000000..9b13a49 Binary files /dev/null and b/public/landing/gifs-512/planet-024.gif differ diff --git a/public/landing/gifs-512/planet-025.gif b/public/landing/gifs-512/planet-025.gif new file mode 100644 index 0000000..32ae49b Binary files /dev/null and b/public/landing/gifs-512/planet-025.gif differ diff --git a/public/landing/gifs-512/planet-026.gif b/public/landing/gifs-512/planet-026.gif new file mode 100644 index 0000000..bac183b Binary files /dev/null and b/public/landing/gifs-512/planet-026.gif differ diff --git a/public/landing/gifs-512/planet-027.gif b/public/landing/gifs-512/planet-027.gif new file mode 100644 index 0000000..cc946a0 Binary files /dev/null and b/public/landing/gifs-512/planet-027.gif differ diff --git a/public/landing/gifs-512/planet-028.gif b/public/landing/gifs-512/planet-028.gif new file mode 100644 index 0000000..c422ce5 Binary files /dev/null and b/public/landing/gifs-512/planet-028.gif differ diff --git a/public/landing/gifs-512/planet-029.gif b/public/landing/gifs-512/planet-029.gif new file mode 100644 index 0000000..4cd6e02 Binary files /dev/null and b/public/landing/gifs-512/planet-029.gif differ diff --git a/public/landing/gifs-512/planet-030.gif b/public/landing/gifs-512/planet-030.gif new file mode 100644 index 0000000..c7eb04e Binary files /dev/null and b/public/landing/gifs-512/planet-030.gif differ diff --git a/public/landing/gifs-512/planet-031.gif b/public/landing/gifs-512/planet-031.gif new file mode 100644 index 0000000..5fecf13 Binary files /dev/null and b/public/landing/gifs-512/planet-031.gif differ diff --git a/public/landing/gifs-512/planet-032.gif b/public/landing/gifs-512/planet-032.gif new file mode 100644 index 0000000..29d5151 Binary files /dev/null and b/public/landing/gifs-512/planet-032.gif differ diff --git a/public/landing/gifs-512/planet-033.gif b/public/landing/gifs-512/planet-033.gif new file mode 100644 index 0000000..d4c44dd Binary files /dev/null and b/public/landing/gifs-512/planet-033.gif differ diff --git a/public/landing/gifs-512/planet-034.gif b/public/landing/gifs-512/planet-034.gif new file mode 100644 index 0000000..ed6d126 Binary files /dev/null and b/public/landing/gifs-512/planet-034.gif differ diff --git a/public/landing/gifs-512/planet-035.gif b/public/landing/gifs-512/planet-035.gif new file mode 100644 index 0000000..c920dd9 Binary files /dev/null and b/public/landing/gifs-512/planet-035.gif differ diff --git a/public/landing/gifs-512/planet-036.gif b/public/landing/gifs-512/planet-036.gif new file mode 100644 index 0000000..9d0155e Binary files /dev/null and b/public/landing/gifs-512/planet-036.gif differ diff --git a/public/landing/gifs-512/planet-037.gif b/public/landing/gifs-512/planet-037.gif new file mode 100644 index 0000000..ec60b28 Binary files /dev/null and b/public/landing/gifs-512/planet-037.gif differ diff --git a/public/landing/gifs-512/planet-038.gif b/public/landing/gifs-512/planet-038.gif new file mode 100644 index 0000000..11ba302 Binary files /dev/null and b/public/landing/gifs-512/planet-038.gif differ diff --git a/public/landing/gifs-512/planet-039.gif b/public/landing/gifs-512/planet-039.gif new file mode 100644 index 0000000..7881973 Binary files /dev/null and b/public/landing/gifs-512/planet-039.gif differ diff --git a/public/landing/gifs-512/planet-040.gif b/public/landing/gifs-512/planet-040.gif new file mode 100644 index 0000000..65013c0 Binary files /dev/null and b/public/landing/gifs-512/planet-040.gif differ diff --git a/public/landing/gifs-512/planet-041.gif b/public/landing/gifs-512/planet-041.gif new file mode 100644 index 0000000..268bc2a Binary files /dev/null and b/public/landing/gifs-512/planet-041.gif differ diff --git a/public/landing/gifs-512/planet-042.gif b/public/landing/gifs-512/planet-042.gif new file mode 100644 index 0000000..bd66fac Binary files /dev/null and b/public/landing/gifs-512/planet-042.gif differ diff --git a/public/landing/gifs-512/planet-043.gif b/public/landing/gifs-512/planet-043.gif new file mode 100644 index 0000000..4edd305 Binary files /dev/null and b/public/landing/gifs-512/planet-043.gif differ diff --git a/public/landing/gifs-512/planet-044.gif b/public/landing/gifs-512/planet-044.gif new file mode 100644 index 0000000..5328ef2 Binary files /dev/null and b/public/landing/gifs-512/planet-044.gif differ diff --git a/public/landing/gifs-512/planet-045.gif b/public/landing/gifs-512/planet-045.gif new file mode 100644 index 0000000..630c201 Binary files /dev/null and b/public/landing/gifs-512/planet-045.gif differ diff --git a/public/landing/gifs-512/planet-046.gif b/public/landing/gifs-512/planet-046.gif new file mode 100644 index 0000000..dc2f89f Binary files /dev/null and b/public/landing/gifs-512/planet-046.gif differ diff --git a/public/landing/gifs-512/planet-047.gif b/public/landing/gifs-512/planet-047.gif new file mode 100644 index 0000000..7c08c1d Binary files /dev/null and b/public/landing/gifs-512/planet-047.gif differ diff --git a/public/landing/gifs-512/planet-048.gif b/public/landing/gifs-512/planet-048.gif new file mode 100644 index 0000000..8a258d3 Binary files /dev/null and b/public/landing/gifs-512/planet-048.gif differ diff --git a/public/landing/gifs-512/planet-049.gif b/public/landing/gifs-512/planet-049.gif new file mode 100644 index 0000000..5abd563 Binary files /dev/null and b/public/landing/gifs-512/planet-049.gif differ diff --git a/public/landing/gifs-512/planet-050.gif b/public/landing/gifs-512/planet-050.gif new file mode 100644 index 0000000..44220bd Binary files /dev/null and b/public/landing/gifs-512/planet-050.gif differ diff --git a/public/landing/gifs-512/planet-051.gif b/public/landing/gifs-512/planet-051.gif new file mode 100644 index 0000000..caeaa91 Binary files /dev/null and b/public/landing/gifs-512/planet-051.gif differ diff --git a/public/landing/gifs-512/planet-052.gif b/public/landing/gifs-512/planet-052.gif new file mode 100644 index 0000000..ed66df4 Binary files /dev/null and b/public/landing/gifs-512/planet-052.gif differ diff --git a/public/landing/gifs-512/planet-053.gif b/public/landing/gifs-512/planet-053.gif new file mode 100644 index 0000000..4dcd462 Binary files /dev/null and b/public/landing/gifs-512/planet-053.gif differ diff --git a/public/landing/gifs-512/planet-054.gif b/public/landing/gifs-512/planet-054.gif new file mode 100644 index 0000000..cf40496 Binary files /dev/null and b/public/landing/gifs-512/planet-054.gif differ diff --git a/public/landing/gifs-512/planet-055.gif b/public/landing/gifs-512/planet-055.gif new file mode 100644 index 0000000..addeba4 Binary files /dev/null and b/public/landing/gifs-512/planet-055.gif differ diff --git a/public/landing/gifs-512/planet-056.gif b/public/landing/gifs-512/planet-056.gif new file mode 100644 index 0000000..a844fbb Binary files /dev/null and b/public/landing/gifs-512/planet-056.gif differ diff --git a/public/landing/gifs-512/planet-057.gif b/public/landing/gifs-512/planet-057.gif new file mode 100644 index 0000000..9e8e06c Binary files /dev/null and b/public/landing/gifs-512/planet-057.gif differ diff --git a/public/landing/gifs-512/planet-058.gif b/public/landing/gifs-512/planet-058.gif new file mode 100644 index 0000000..f35623a Binary files /dev/null and b/public/landing/gifs-512/planet-058.gif differ diff --git a/public/landing/gifs-512/planet-059.gif b/public/landing/gifs-512/planet-059.gif new file mode 100644 index 0000000..beff938 Binary files /dev/null and b/public/landing/gifs-512/planet-059.gif differ diff --git a/public/landing/gifs-512/planet-060.gif b/public/landing/gifs-512/planet-060.gif new file mode 100644 index 0000000..c19b698 Binary files /dev/null and b/public/landing/gifs-512/planet-060.gif differ diff --git a/public/landing/gifs-512/planet-061.gif b/public/landing/gifs-512/planet-061.gif new file mode 100644 index 0000000..c49bd0a Binary files /dev/null and b/public/landing/gifs-512/planet-061.gif differ diff --git a/public/landing/gifs-512/planet-062.gif b/public/landing/gifs-512/planet-062.gif new file mode 100644 index 0000000..10c4d19 Binary files /dev/null and b/public/landing/gifs-512/planet-062.gif differ diff --git a/public/landing/gifs-512/planet-063.gif b/public/landing/gifs-512/planet-063.gif new file mode 100644 index 0000000..17a99c1 Binary files /dev/null and b/public/landing/gifs-512/planet-063.gif differ diff --git a/public/landing/gifs-512/planet-064.gif b/public/landing/gifs-512/planet-064.gif new file mode 100644 index 0000000..ec173c8 Binary files /dev/null and b/public/landing/gifs-512/planet-064.gif differ diff --git a/public/landing/gifs-512/planet-065.gif b/public/landing/gifs-512/planet-065.gif new file mode 100644 index 0000000..306318b Binary files /dev/null and b/public/landing/gifs-512/planet-065.gif differ diff --git a/public/landing/gifs-512/planet-066.gif b/public/landing/gifs-512/planet-066.gif new file mode 100644 index 0000000..fe5b9ed Binary files /dev/null and b/public/landing/gifs-512/planet-066.gif differ diff --git a/public/landing/gifs-512/planet-067.gif b/public/landing/gifs-512/planet-067.gif new file mode 100644 index 0000000..7b56c26 Binary files /dev/null and b/public/landing/gifs-512/planet-067.gif differ diff --git a/public/landing/gifs-512/planet-068.gif b/public/landing/gifs-512/planet-068.gif new file mode 100644 index 0000000..fee079d Binary files /dev/null and b/public/landing/gifs-512/planet-068.gif differ diff --git a/public/landing/gifs-512/planet-069.gif b/public/landing/gifs-512/planet-069.gif new file mode 100644 index 0000000..694c53e Binary files /dev/null and b/public/landing/gifs-512/planet-069.gif differ diff --git a/public/landing/gifs-512/planet-070.gif b/public/landing/gifs-512/planet-070.gif new file mode 100644 index 0000000..5ffe52e Binary files /dev/null and b/public/landing/gifs-512/planet-070.gif differ diff --git a/public/landing/gifs-512/planet-071.gif b/public/landing/gifs-512/planet-071.gif new file mode 100644 index 0000000..5d51f25 Binary files /dev/null and b/public/landing/gifs-512/planet-071.gif differ diff --git a/public/landing/gifs-512/planet-072.gif b/public/landing/gifs-512/planet-072.gif new file mode 100644 index 0000000..ed83668 Binary files /dev/null and b/public/landing/gifs-512/planet-072.gif differ diff --git a/public/landing/gifs-512/planet-073.gif b/public/landing/gifs-512/planet-073.gif new file mode 100644 index 0000000..cefb5a9 Binary files /dev/null and b/public/landing/gifs-512/planet-073.gif differ diff --git a/public/landing/gifs-512/planet-074.gif b/public/landing/gifs-512/planet-074.gif new file mode 100644 index 0000000..20f6cac Binary files /dev/null and b/public/landing/gifs-512/planet-074.gif differ diff --git a/public/landing/gifs-512/planet-075.gif b/public/landing/gifs-512/planet-075.gif new file mode 100644 index 0000000..7c4ec27 Binary files /dev/null and b/public/landing/gifs-512/planet-075.gif differ diff --git a/public/landing/gifs-512/planet-076.gif b/public/landing/gifs-512/planet-076.gif new file mode 100644 index 0000000..6bc2863 Binary files /dev/null and b/public/landing/gifs-512/planet-076.gif differ diff --git a/public/landing/gifs-512/planet-077.gif b/public/landing/gifs-512/planet-077.gif new file mode 100644 index 0000000..a3e29f0 Binary files /dev/null and b/public/landing/gifs-512/planet-077.gif differ diff --git a/public/landing/gifs-512/planet-078.gif b/public/landing/gifs-512/planet-078.gif new file mode 100644 index 0000000..37184c2 Binary files /dev/null and b/public/landing/gifs-512/planet-078.gif differ diff --git a/public/landing/gifs-512/planet-079.gif b/public/landing/gifs-512/planet-079.gif new file mode 100644 index 0000000..ad4f5c3 Binary files /dev/null and b/public/landing/gifs-512/planet-079.gif differ diff --git a/public/landing/gifs-512/planet-080.gif b/public/landing/gifs-512/planet-080.gif new file mode 100644 index 0000000..96e087d Binary files /dev/null and b/public/landing/gifs-512/planet-080.gif differ diff --git a/public/landing/gifs-512/planet-081.gif b/public/landing/gifs-512/planet-081.gif new file mode 100644 index 0000000..0f24325 Binary files /dev/null and b/public/landing/gifs-512/planet-081.gif differ diff --git a/public/landing/gifs-512/planet-082.gif b/public/landing/gifs-512/planet-082.gif new file mode 100644 index 0000000..54b9b30 Binary files /dev/null and b/public/landing/gifs-512/planet-082.gif differ diff --git a/public/landing/gifs-512/planet-083.gif b/public/landing/gifs-512/planet-083.gif new file mode 100644 index 0000000..d96b892 Binary files /dev/null and b/public/landing/gifs-512/planet-083.gif differ diff --git a/public/landing/gifs-512/planet-084.gif b/public/landing/gifs-512/planet-084.gif new file mode 100644 index 0000000..508d511 Binary files /dev/null and b/public/landing/gifs-512/planet-084.gif differ diff --git a/public/landing/gifs-512/planet-085.gif b/public/landing/gifs-512/planet-085.gif new file mode 100644 index 0000000..27caead Binary files /dev/null and b/public/landing/gifs-512/planet-085.gif differ diff --git a/public/landing/gifs-512/planet-086.gif b/public/landing/gifs-512/planet-086.gif new file mode 100644 index 0000000..4623401 Binary files /dev/null and b/public/landing/gifs-512/planet-086.gif differ diff --git a/public/landing/gifs-512/planet-087.gif b/public/landing/gifs-512/planet-087.gif new file mode 100644 index 0000000..97e223a Binary files /dev/null and b/public/landing/gifs-512/planet-087.gif differ diff --git a/public/landing/gifs-512/planet-088.gif b/public/landing/gifs-512/planet-088.gif new file mode 100644 index 0000000..804c19e Binary files /dev/null and b/public/landing/gifs-512/planet-088.gif differ diff --git a/public/landing/gifs-512/planet-089.gif b/public/landing/gifs-512/planet-089.gif new file mode 100644 index 0000000..cc7e9cb Binary files /dev/null and b/public/landing/gifs-512/planet-089.gif differ diff --git a/public/landing/gifs-512/planet-090.gif b/public/landing/gifs-512/planet-090.gif new file mode 100644 index 0000000..bd4d94d Binary files /dev/null and b/public/landing/gifs-512/planet-090.gif differ diff --git a/public/landing/gifs-512/planet-091.gif b/public/landing/gifs-512/planet-091.gif new file mode 100644 index 0000000..6d8aa7e Binary files /dev/null and b/public/landing/gifs-512/planet-091.gif differ diff --git a/public/landing/gifs-512/planet-092.gif b/public/landing/gifs-512/planet-092.gif new file mode 100644 index 0000000..c247b47 Binary files /dev/null and b/public/landing/gifs-512/planet-092.gif differ diff --git a/public/landing/gifs-512/planet-093.gif b/public/landing/gifs-512/planet-093.gif new file mode 100644 index 0000000..479ce82 Binary files /dev/null and b/public/landing/gifs-512/planet-093.gif differ diff --git a/public/landing/gifs-512/planet-094.gif b/public/landing/gifs-512/planet-094.gif new file mode 100644 index 0000000..2ead119 Binary files /dev/null and b/public/landing/gifs-512/planet-094.gif differ diff --git a/public/landing/gifs-512/planet-095.gif b/public/landing/gifs-512/planet-095.gif new file mode 100644 index 0000000..4e4acaa Binary files /dev/null and b/public/landing/gifs-512/planet-095.gif differ diff --git a/public/landing/gifs-512/planet-096.gif b/public/landing/gifs-512/planet-096.gif new file mode 100644 index 0000000..db96527 Binary files /dev/null and b/public/landing/gifs-512/planet-096.gif differ diff --git a/public/landing/gifs-512/planet-097.gif b/public/landing/gifs-512/planet-097.gif new file mode 100644 index 0000000..6ffd9b2 Binary files /dev/null and b/public/landing/gifs-512/planet-097.gif differ diff --git a/public/landing/gifs-512/planet-098.gif b/public/landing/gifs-512/planet-098.gif new file mode 100644 index 0000000..0e8582c Binary files /dev/null and b/public/landing/gifs-512/planet-098.gif differ diff --git a/public/landing/gifs-512/planet-099.gif b/public/landing/gifs-512/planet-099.gif new file mode 100644 index 0000000..15cbe25 Binary files /dev/null and b/public/landing/gifs-512/planet-099.gif differ diff --git a/public/landing/gifs-512/planet-100.gif b/public/landing/gifs-512/planet-100.gif new file mode 100644 index 0000000..48eafb9 Binary files /dev/null and b/public/landing/gifs-512/planet-100.gif differ diff --git a/public/landing/png/planet-001.png b/public/landing/png/planet-001.png new file mode 100644 index 0000000..e8c654a Binary files /dev/null and b/public/landing/png/planet-001.png differ diff --git a/public/landing/png/planet-002.png b/public/landing/png/planet-002.png new file mode 100644 index 0000000..18147a2 Binary files /dev/null and b/public/landing/png/planet-002.png differ diff --git a/public/landing/png/planet-003.png b/public/landing/png/planet-003.png new file mode 100644 index 0000000..b4e0101 Binary files /dev/null and b/public/landing/png/planet-003.png differ diff --git a/public/landing/png/planet-004.png b/public/landing/png/planet-004.png new file mode 100644 index 0000000..0fc100e Binary files /dev/null and b/public/landing/png/planet-004.png differ diff --git a/public/landing/png/planet-005.png b/public/landing/png/planet-005.png new file mode 100644 index 0000000..5e0ebb9 Binary files /dev/null and b/public/landing/png/planet-005.png differ diff --git a/public/landing/png/planet-006.png b/public/landing/png/planet-006.png new file mode 100644 index 0000000..e86b968 Binary files /dev/null and b/public/landing/png/planet-006.png differ diff --git a/public/landing/png/planet-007.png b/public/landing/png/planet-007.png new file mode 100644 index 0000000..d451f23 Binary files /dev/null and b/public/landing/png/planet-007.png differ diff --git a/public/landing/png/planet-008.png b/public/landing/png/planet-008.png new file mode 100644 index 0000000..a0b950d Binary files /dev/null and b/public/landing/png/planet-008.png differ diff --git a/public/landing/png/planet-009.png b/public/landing/png/planet-009.png new file mode 100644 index 0000000..590954e Binary files /dev/null and b/public/landing/png/planet-009.png differ diff --git a/public/landing/png/planet-010.png b/public/landing/png/planet-010.png new file mode 100644 index 0000000..f0628be Binary files /dev/null and b/public/landing/png/planet-010.png differ diff --git a/public/landing/png/planet-011.png b/public/landing/png/planet-011.png new file mode 100644 index 0000000..381e056 Binary files /dev/null and b/public/landing/png/planet-011.png differ diff --git a/public/landing/png/planet-012.png b/public/landing/png/planet-012.png new file mode 100644 index 0000000..ceff778 Binary files /dev/null and b/public/landing/png/planet-012.png differ diff --git a/public/landing/png/planet-013.png b/public/landing/png/planet-013.png new file mode 100644 index 0000000..c6c49f3 Binary files /dev/null and b/public/landing/png/planet-013.png differ diff --git a/public/landing/png/planet-014.png b/public/landing/png/planet-014.png new file mode 100644 index 0000000..60888eb Binary files /dev/null and b/public/landing/png/planet-014.png differ diff --git a/public/landing/png/planet-015.png b/public/landing/png/planet-015.png new file mode 100644 index 0000000..012042e Binary files /dev/null and b/public/landing/png/planet-015.png differ diff --git a/public/landing/png/planet-016.png b/public/landing/png/planet-016.png new file mode 100644 index 0000000..2240d35 Binary files /dev/null and b/public/landing/png/planet-016.png differ diff --git a/public/landing/png/planet-017.png b/public/landing/png/planet-017.png new file mode 100644 index 0000000..3ec5821 Binary files /dev/null and b/public/landing/png/planet-017.png differ diff --git a/public/landing/png/planet-018.png b/public/landing/png/planet-018.png new file mode 100644 index 0000000..62d9a10 Binary files /dev/null and b/public/landing/png/planet-018.png differ diff --git a/public/landing/png/planet-019.png b/public/landing/png/planet-019.png new file mode 100644 index 0000000..70771a2 Binary files /dev/null and b/public/landing/png/planet-019.png differ diff --git a/public/landing/png/planet-020.png b/public/landing/png/planet-020.png new file mode 100644 index 0000000..4f2fbdc Binary files /dev/null and b/public/landing/png/planet-020.png differ diff --git a/public/landing/png/planet-021.png b/public/landing/png/planet-021.png new file mode 100644 index 0000000..66f5aa4 Binary files /dev/null and b/public/landing/png/planet-021.png differ diff --git a/public/landing/png/planet-022.png b/public/landing/png/planet-022.png new file mode 100644 index 0000000..1204b02 Binary files /dev/null and b/public/landing/png/planet-022.png differ diff --git a/public/landing/png/planet-023.png b/public/landing/png/planet-023.png new file mode 100644 index 0000000..ae8918b Binary files /dev/null and b/public/landing/png/planet-023.png differ diff --git a/public/landing/png/planet-024.png b/public/landing/png/planet-024.png new file mode 100644 index 0000000..558f0f9 Binary files /dev/null and b/public/landing/png/planet-024.png differ diff --git a/public/landing/png/planet-025.png b/public/landing/png/planet-025.png new file mode 100644 index 0000000..e8c0ba7 Binary files /dev/null and b/public/landing/png/planet-025.png differ diff --git a/public/landing/png/planet-026.png b/public/landing/png/planet-026.png new file mode 100644 index 0000000..0a3ba1d Binary files /dev/null and b/public/landing/png/planet-026.png differ diff --git a/public/landing/png/planet-027.png b/public/landing/png/planet-027.png new file mode 100644 index 0000000..67d936b Binary files /dev/null and b/public/landing/png/planet-027.png differ diff --git a/public/landing/png/planet-028.png b/public/landing/png/planet-028.png new file mode 100644 index 0000000..c89d7f9 Binary files /dev/null and b/public/landing/png/planet-028.png differ diff --git a/public/landing/png/planet-029.png b/public/landing/png/planet-029.png new file mode 100644 index 0000000..9eed01e Binary files /dev/null and b/public/landing/png/planet-029.png differ diff --git a/public/landing/png/planet-030.png b/public/landing/png/planet-030.png new file mode 100644 index 0000000..2bd87a3 Binary files /dev/null and b/public/landing/png/planet-030.png differ diff --git a/public/landing/png/planet-031.png b/public/landing/png/planet-031.png new file mode 100644 index 0000000..08f7454 Binary files /dev/null and b/public/landing/png/planet-031.png differ diff --git a/public/landing/png/planet-032.png b/public/landing/png/planet-032.png new file mode 100644 index 0000000..05f8ccb Binary files /dev/null and b/public/landing/png/planet-032.png differ diff --git a/public/landing/png/planet-033.png b/public/landing/png/planet-033.png new file mode 100644 index 0000000..5c495fe Binary files /dev/null and b/public/landing/png/planet-033.png differ diff --git a/public/landing/png/planet-034.png b/public/landing/png/planet-034.png new file mode 100644 index 0000000..c08f4ac Binary files /dev/null and b/public/landing/png/planet-034.png differ diff --git a/public/landing/png/planet-035.png b/public/landing/png/planet-035.png new file mode 100644 index 0000000..132ba42 Binary files /dev/null and b/public/landing/png/planet-035.png differ diff --git a/public/landing/png/planet-036.png b/public/landing/png/planet-036.png new file mode 100644 index 0000000..2ede483 Binary files /dev/null and b/public/landing/png/planet-036.png differ diff --git a/public/landing/png/planet-037.png b/public/landing/png/planet-037.png new file mode 100644 index 0000000..6f2d5cb Binary files /dev/null and b/public/landing/png/planet-037.png differ diff --git a/public/landing/png/planet-038.png b/public/landing/png/planet-038.png new file mode 100644 index 0000000..33abf27 Binary files /dev/null and b/public/landing/png/planet-038.png differ diff --git a/public/landing/png/planet-039.png b/public/landing/png/planet-039.png new file mode 100644 index 0000000..fa627ba Binary files /dev/null and b/public/landing/png/planet-039.png differ diff --git a/public/landing/png/planet-040.png b/public/landing/png/planet-040.png new file mode 100644 index 0000000..ac2e8e9 Binary files /dev/null and b/public/landing/png/planet-040.png differ diff --git a/public/landing/png/planet-041.png b/public/landing/png/planet-041.png new file mode 100644 index 0000000..3edaab0 Binary files /dev/null and b/public/landing/png/planet-041.png differ diff --git a/public/landing/png/planet-042.png b/public/landing/png/planet-042.png new file mode 100644 index 0000000..7aed7ac Binary files /dev/null and b/public/landing/png/planet-042.png differ diff --git a/public/landing/png/planet-043.png b/public/landing/png/planet-043.png new file mode 100644 index 0000000..8893490 Binary files /dev/null and b/public/landing/png/planet-043.png differ diff --git a/public/landing/png/planet-044.png b/public/landing/png/planet-044.png new file mode 100644 index 0000000..4e58c16 Binary files /dev/null and b/public/landing/png/planet-044.png differ diff --git a/public/landing/png/planet-045.png b/public/landing/png/planet-045.png new file mode 100644 index 0000000..c440bd1 Binary files /dev/null and b/public/landing/png/planet-045.png differ diff --git a/public/landing/png/planet-046.png b/public/landing/png/planet-046.png new file mode 100644 index 0000000..401b057 Binary files /dev/null and b/public/landing/png/planet-046.png differ diff --git a/public/landing/png/planet-047.png b/public/landing/png/planet-047.png new file mode 100644 index 0000000..899af28 Binary files /dev/null and b/public/landing/png/planet-047.png differ diff --git a/public/landing/png/planet-048.png b/public/landing/png/planet-048.png new file mode 100644 index 0000000..21e5274 Binary files /dev/null and b/public/landing/png/planet-048.png differ diff --git a/public/landing/png/planet-049.png b/public/landing/png/planet-049.png new file mode 100644 index 0000000..b3fd2a3 Binary files /dev/null and b/public/landing/png/planet-049.png differ diff --git a/public/landing/png/planet-050.png b/public/landing/png/planet-050.png new file mode 100644 index 0000000..83ffd0f Binary files /dev/null and b/public/landing/png/planet-050.png differ diff --git a/public/landing/png/planet-051.png b/public/landing/png/planet-051.png new file mode 100644 index 0000000..c816852 Binary files /dev/null and b/public/landing/png/planet-051.png differ diff --git a/public/landing/png/planet-052.png b/public/landing/png/planet-052.png new file mode 100644 index 0000000..68002b0 Binary files /dev/null and b/public/landing/png/planet-052.png differ diff --git a/public/landing/png/planet-053.png b/public/landing/png/planet-053.png new file mode 100644 index 0000000..0dfbb48 Binary files /dev/null and b/public/landing/png/planet-053.png differ diff --git a/public/landing/png/planet-054.png b/public/landing/png/planet-054.png new file mode 100644 index 0000000..96980b9 Binary files /dev/null and b/public/landing/png/planet-054.png differ diff --git a/public/landing/png/planet-055.png b/public/landing/png/planet-055.png new file mode 100644 index 0000000..fa2e7a1 Binary files /dev/null and b/public/landing/png/planet-055.png differ diff --git a/public/landing/png/planet-056.png b/public/landing/png/planet-056.png new file mode 100644 index 0000000..3a87dd2 Binary files /dev/null and b/public/landing/png/planet-056.png differ diff --git a/public/landing/png/planet-057.png b/public/landing/png/planet-057.png new file mode 100644 index 0000000..f213865 Binary files /dev/null and b/public/landing/png/planet-057.png differ diff --git a/public/landing/png/planet-058.png b/public/landing/png/planet-058.png new file mode 100644 index 0000000..de8a3e0 Binary files /dev/null and b/public/landing/png/planet-058.png differ diff --git a/public/landing/png/planet-059.png b/public/landing/png/planet-059.png new file mode 100644 index 0000000..02265e6 Binary files /dev/null and b/public/landing/png/planet-059.png differ diff --git a/public/landing/png/planet-060.png b/public/landing/png/planet-060.png new file mode 100644 index 0000000..08b7097 Binary files /dev/null and b/public/landing/png/planet-060.png differ diff --git a/public/landing/png/planet-061.png b/public/landing/png/planet-061.png new file mode 100644 index 0000000..be5ba2a Binary files /dev/null and b/public/landing/png/planet-061.png differ diff --git a/public/landing/png/planet-062.png b/public/landing/png/planet-062.png new file mode 100644 index 0000000..798c00a Binary files /dev/null and b/public/landing/png/planet-062.png differ diff --git a/public/landing/png/planet-063.png b/public/landing/png/planet-063.png new file mode 100644 index 0000000..72feddc Binary files /dev/null and b/public/landing/png/planet-063.png differ diff --git a/public/landing/png/planet-064.png b/public/landing/png/planet-064.png new file mode 100644 index 0000000..68151ad Binary files /dev/null and b/public/landing/png/planet-064.png differ diff --git a/public/landing/png/planet-065.png b/public/landing/png/planet-065.png new file mode 100644 index 0000000..a158246 Binary files /dev/null and b/public/landing/png/planet-065.png differ diff --git a/public/landing/png/planet-066.png b/public/landing/png/planet-066.png new file mode 100644 index 0000000..8d34090 Binary files /dev/null and b/public/landing/png/planet-066.png differ diff --git a/public/landing/png/planet-067.png b/public/landing/png/planet-067.png new file mode 100644 index 0000000..b0e6c43 Binary files /dev/null and b/public/landing/png/planet-067.png differ diff --git a/public/landing/png/planet-068.png b/public/landing/png/planet-068.png new file mode 100644 index 0000000..257a4fb Binary files /dev/null and b/public/landing/png/planet-068.png differ diff --git a/public/landing/png/planet-069.png b/public/landing/png/planet-069.png new file mode 100644 index 0000000..da8863d Binary files /dev/null and b/public/landing/png/planet-069.png differ diff --git a/public/landing/png/planet-070.png b/public/landing/png/planet-070.png new file mode 100644 index 0000000..7241aea Binary files /dev/null and b/public/landing/png/planet-070.png differ diff --git a/public/landing/png/planet-071.png b/public/landing/png/planet-071.png new file mode 100644 index 0000000..eb2c0b6 Binary files /dev/null and b/public/landing/png/planet-071.png differ diff --git a/public/landing/png/planet-072.png b/public/landing/png/planet-072.png new file mode 100644 index 0000000..da0d5fe Binary files /dev/null and b/public/landing/png/planet-072.png differ diff --git a/public/landing/png/planet-073.png b/public/landing/png/planet-073.png new file mode 100644 index 0000000..22b0736 Binary files /dev/null and b/public/landing/png/planet-073.png differ diff --git a/public/landing/png/planet-074.png b/public/landing/png/planet-074.png new file mode 100644 index 0000000..8e59e2e Binary files /dev/null and b/public/landing/png/planet-074.png differ diff --git a/public/landing/png/planet-075.png b/public/landing/png/planet-075.png new file mode 100644 index 0000000..51e7a61 Binary files /dev/null and b/public/landing/png/planet-075.png differ diff --git a/public/landing/png/planet-076.png b/public/landing/png/planet-076.png new file mode 100644 index 0000000..d37109f Binary files /dev/null and b/public/landing/png/planet-076.png differ diff --git a/public/landing/png/planet-077.png b/public/landing/png/planet-077.png new file mode 100644 index 0000000..85fa9a6 Binary files /dev/null and b/public/landing/png/planet-077.png differ diff --git a/public/landing/png/planet-078.png b/public/landing/png/planet-078.png new file mode 100644 index 0000000..7ee5190 Binary files /dev/null and b/public/landing/png/planet-078.png differ diff --git a/public/landing/png/planet-079.png b/public/landing/png/planet-079.png new file mode 100644 index 0000000..15167ec Binary files /dev/null and b/public/landing/png/planet-079.png differ diff --git a/public/landing/png/planet-080.png b/public/landing/png/planet-080.png new file mode 100644 index 0000000..ce514a5 Binary files /dev/null and b/public/landing/png/planet-080.png differ diff --git a/public/landing/png/planet-081.png b/public/landing/png/planet-081.png new file mode 100644 index 0000000..3081717 Binary files /dev/null and b/public/landing/png/planet-081.png differ diff --git a/public/landing/png/planet-082.png b/public/landing/png/planet-082.png new file mode 100644 index 0000000..576df5d Binary files /dev/null and b/public/landing/png/planet-082.png differ diff --git a/public/landing/png/planet-083.png b/public/landing/png/planet-083.png new file mode 100644 index 0000000..48d2394 Binary files /dev/null and b/public/landing/png/planet-083.png differ diff --git a/public/landing/png/planet-084.png b/public/landing/png/planet-084.png new file mode 100644 index 0000000..4d1218e Binary files /dev/null and b/public/landing/png/planet-084.png differ diff --git a/public/landing/png/planet-085.png b/public/landing/png/planet-085.png new file mode 100644 index 0000000..d6e04ee Binary files /dev/null and b/public/landing/png/planet-085.png differ diff --git a/public/landing/png/planet-086.png b/public/landing/png/planet-086.png new file mode 100644 index 0000000..1653da7 Binary files /dev/null and b/public/landing/png/planet-086.png differ diff --git a/public/landing/png/planet-087.png b/public/landing/png/planet-087.png new file mode 100644 index 0000000..e96053e Binary files /dev/null and b/public/landing/png/planet-087.png differ diff --git a/public/landing/png/planet-088.png b/public/landing/png/planet-088.png new file mode 100644 index 0000000..83e0d7b Binary files /dev/null and b/public/landing/png/planet-088.png differ diff --git a/public/landing/png/planet-089.png b/public/landing/png/planet-089.png new file mode 100644 index 0000000..174bad6 Binary files /dev/null and b/public/landing/png/planet-089.png differ diff --git a/public/landing/png/planet-090.png b/public/landing/png/planet-090.png new file mode 100644 index 0000000..3e637fb Binary files /dev/null and b/public/landing/png/planet-090.png differ diff --git a/public/landing/png/planet-091.png b/public/landing/png/planet-091.png new file mode 100644 index 0000000..15de077 Binary files /dev/null and b/public/landing/png/planet-091.png differ diff --git a/public/landing/png/planet-092.png b/public/landing/png/planet-092.png new file mode 100644 index 0000000..ca85cd6 Binary files /dev/null and b/public/landing/png/planet-092.png differ diff --git a/public/landing/png/planet-093.png b/public/landing/png/planet-093.png new file mode 100644 index 0000000..bfe4894 Binary files /dev/null and b/public/landing/png/planet-093.png differ diff --git a/public/landing/png/planet-094.png b/public/landing/png/planet-094.png new file mode 100644 index 0000000..301d3a1 Binary files /dev/null and b/public/landing/png/planet-094.png differ diff --git a/public/landing/png/planet-095.png b/public/landing/png/planet-095.png new file mode 100644 index 0000000..ed70c55 Binary files /dev/null and b/public/landing/png/planet-095.png differ diff --git a/public/landing/png/planet-096.png b/public/landing/png/planet-096.png new file mode 100644 index 0000000..5319414 Binary files /dev/null and b/public/landing/png/planet-096.png differ diff --git a/public/landing/png/planet-097.png b/public/landing/png/planet-097.png new file mode 100644 index 0000000..f0f4c7b Binary files /dev/null and b/public/landing/png/planet-097.png differ diff --git a/public/landing/png/planet-098.png b/public/landing/png/planet-098.png new file mode 100644 index 0000000..ad3ed09 Binary files /dev/null and b/public/landing/png/planet-098.png differ diff --git a/public/landing/png/planet-099.png b/public/landing/png/planet-099.png new file mode 100644 index 0000000..9915124 Binary files /dev/null and b/public/landing/png/planet-099.png differ diff --git a/public/landing/png/planet-100.png b/public/landing/png/planet-100.png new file mode 100644 index 0000000..06d2609 Binary files /dev/null and b/public/landing/png/planet-100.png differ diff --git a/scripts/deploy-production-migrations.mjs b/scripts/deploy-production-migrations.mjs new file mode 100644 index 0000000..a614d0a --- /dev/null +++ b/scripts/deploy-production-migrations.mjs @@ -0,0 +1,6 @@ +import { spawnSync } from 'node:child_process'; + +if (process.env.VERCEL_ENV === 'production') { + const result = spawnSync('pnpm', ['db:migrate:deploy'], { stdio: 'inherit' }); + process.exitCode = result.status ?? 1; +} diff --git a/server/api/backendConfig.test.ts b/server/api/backendConfig.test.ts index b43c1fd..b4e2f59 100644 --- a/server/api/backendConfig.test.ts +++ b/server/api/backendConfig.test.ts @@ -11,6 +11,19 @@ describe('Minerals Economy configuration', () => { const config = loadBackendPlanetConfig(baseEnv); expect(config.mineralEconomyCutoverAt).toBeNull(); expect(config.mineralUpgradesEnabled).toBe(false); + expect(config.galaxyPulseStartBlock).toBeNull(); + }); + + it('enables Galaxy Pulse from one explicit non-negative start block', () => { + expect(loadBackendPlanetConfig({ + ...baseEnv, + GALAXY_PULSE_START_BLOCK: '34567890', + }).galaxyPulseStartBlock).toBe(34_567_890n); + + expect(() => loadBackendPlanetConfig({ + ...baseEnv, + GALAXY_PULSE_START_BLOCK: '-1', + })).toThrow('GALAXY_PULSE_START_BLOCK must be a non-negative integer'); }); it('parses a cutover and opt-in upgrade flag without changing Planet requirements', () => { diff --git a/server/api/backendConfig.ts b/server/api/backendConfig.ts index ca0c3cb..7815587 100644 --- a/server/api/backendConfig.ts +++ b/server/api/backendConfig.ts @@ -9,6 +9,7 @@ export type BackendPlanetConfig = { /** Optional in dependency overrides so pre-v2 Planet APIs remain source-compatible. */ mineralEconomyCutoverAt?: Date | null; mineralUpgradesEnabled?: boolean; + galaxyPulseStartBlock?: bigint | null; siweOrigin?: string; siweSessionSecret?: string; }; @@ -48,6 +49,15 @@ function parseMineralUpgradesEnabled(env: Record): b throw new Error('MINERAL_UPGRADES_ENABLED must be a boolean.'); } +function parseGalaxyPulseStartBlock(env: Record): bigint | null { + const raw = env.GALAXY_PULSE_START_BLOCK?.trim(); + if (!raw) return null; + if (!/^\d+$/.test(raw)) { + throw new Error('GALAXY_PULSE_START_BLOCK must be a non-negative integer.'); + } + return BigInt(raw); +} + function parseSiweOrigin( env: Record, requiredForUpgrades: boolean, @@ -124,6 +134,7 @@ export function loadBackendPlanetConfig( rpcFallbackUrls, databaseUrl, confirmations, + galaxyPulseStartBlock: parseGalaxyPulseStartBlock(env), ...mineralEconomy, siweOrigin: parseSiweOrigin(env, mineralEconomy.mineralUpgradesEnabled), siweSessionSecret: parseSiweSessionSecret(env, mineralEconomy.mineralUpgradesEnabled), diff --git a/server/api/backendPlanetRoutes.test.ts b/server/api/backendPlanetRoutes.test.ts index f13cfb2..b8e6c71 100644 --- a/server/api/backendPlanetRoutes.test.ts +++ b/server/api/backendPlanetRoutes.test.ts @@ -61,6 +61,7 @@ function makeUpgradeApp() { purchasedAt: NOW.toISOString(), }); const getPrisma = vi.fn(() => ({} as never)); + const assertPulseFresh = vi.fn().mockResolvedValue(undefined); const app = new Hono(); app.route('/api', createBackendPlanetRoutes({ ...makeAppDependencies(), @@ -68,8 +69,9 @@ function makeUpgradeApp() { loadConfig: () => upgradeConfig, now: () => NOW, purchaseUpgrade, + assertPulseFresh, })); - return { app, getPrisma, purchaseUpgrade }; + return { app, assertPulseFresh, getPrisma, purchaseUpgrade }; } function makeAppDependencies() { @@ -81,6 +83,7 @@ function makeAppDependencies() { getStore: () => store, allows: () => true, now: () => new Date('2026-08-21T00:00:00.000Z'), + assertPulseFresh: vi.fn().mockResolvedValue(undefined), }; } @@ -131,6 +134,20 @@ describe('backend Planet routes', () => { expect((await gif.arrayBuffer()).byteLength).toBeGreaterThan(6); }); + it('checks Pulse freshness before a generation that can settle balance', async () => { + const dependencies = makeAppDependencies(); + const app = new Hono(); + app.route('/api', createBackendPlanetRoutes(dependencies)); + const response = await app.request('/api/planets/generate', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ transactionHash: proof.originTxHash, logIndex: Number(proof.logIndex) }), + }); + + expect(response.status).toBe(201); + expect(dependencies.assertPulseFresh).toHaveBeenCalledOnce(); + }); + it('retires the per-Planet mining route', async () => { const getPrisma = vi.fn(); const app = new Hono(); @@ -246,7 +263,7 @@ describe('backend Planet routes', () => { }); it('passes only the authenticated session wallet into an owner upgrade', async () => { - const { app, purchaseUpgrade } = makeUpgradeApp(); + const { app, assertPulseFresh, purchaseUpgrade } = makeUpgradeApp(); const response = await app.request(`${SIWE_ORIGIN}/api/planets/planet-1/upgrade`, { method: 'POST', @@ -260,6 +277,7 @@ describe('backend Planet routes', () => { expect(response.status).toBe(200); expect(await response.json()).toMatchObject({ upgrade: { purchaseId: 'purchase-1' } }); + expect(assertPulseFresh).toHaveBeenCalledOnce(); expect(purchaseUpgrade).toHaveBeenCalledWith(expect.anything(), { authenticatedWalletAddress: proof.recipient.toLowerCase(), cutoverAt: upgradeConfig.mineralEconomyCutoverAt, diff --git a/server/api/backendPlanetRoutes.ts b/server/api/backendPlanetRoutes.ts index 7751b39..db74236 100644 --- a/server/api/backendPlanetRoutes.ts +++ b/server/api/backendPlanetRoutes.ts @@ -17,6 +17,10 @@ import { saveMegasteraProof } from './prismaTicketPurchase.js'; import { reportBackendError } from './errorDiagnostics.js'; import type { PrismaClient } from './generated/prisma/client.js'; import { purchasePlanetUpgrade } from './mineralAccounts.js'; +import { + assertGalaxyPulseFresh, + isGalaxyPulseFreshnessError, +} from './galaxyPulseFreshness.js'; import { createSiweAuthRoutes, getSiweSessionAddress, @@ -34,6 +38,11 @@ export type BackendPlanetRouteDependencies = { now: () => Date; getPrisma?: (config: BackendPlanetConfig) => PrismaClient; purchaseUpgrade: typeof purchasePlanetUpgrade; + assertPulseFresh: ( + config: BackendPlanetConfig, + prisma: PrismaClient, + now: Date, + ) => Promise; }; const MAX_BATCH = 50; @@ -75,6 +84,11 @@ function defaultDependencies(): BackendPlanetRouteDependencies { allows: createRateLimiter(), now: () => new Date(), purchaseUpgrade: purchasePlanetUpgrade, + assertPulseFresh: (config, prisma, now) => assertGalaxyPulseFresh({ + prisma, + galaxyPulseStartBlock: config.galaxyPulseStartBlock ?? null, + now, + }), }; } @@ -117,6 +131,7 @@ export function createBackendPlanetRoutes( if (!dependencies.allows(key)) throw new Error('Planet generation is rate limited.'); const proof = await dependencies.findTicket(config, reference); await dependencies.saveProof(config, proof); + await dependencies.assertPulseFresh(config, getPrisma(config), dependencies.now()); return dependencies.getStore(config).generatePlanet(proof); })(); inFlight.set(key, operation); @@ -143,7 +158,10 @@ export function createBackendPlanetRoutes( if (!reference) return c.json({ error: 'Every reference must contain a valid transactionHash and logIndex.' }, 400); try { planets.push(serializePlanet(await generate(reference))); - } catch { + } catch (error) { + if (isGalaxyPulseFreshnessError(error)) { + return c.json({ error: 'Galaxy Pulse is updating. Retry later.' }, 503); + } return c.json({ error: 'Planet generation failed.' }, 422); } } @@ -163,6 +181,9 @@ export function createBackendPlanetRoutes( return c.json({ planet: serializePlanet(await generate(reference)) }, 201); } catch (error) { if (error instanceof Error && error.message.includes('rate limited')) return c.json({ error: error.message }, 429); + if (isGalaxyPulseFreshnessError(error)) { + return c.json({ error: 'Galaxy Pulse is updating. Retry later.' }, 503); + } return c.json({ error: 'Planet generation failed.' }, 422); } }); @@ -297,6 +318,7 @@ export function createBackendPlanetRoutes( ) return c.json({ error: 'Wallet authentication is required.' }, 401); try { + await dependencies.assertPulseFresh(config, getPrisma(config), dependencies.now()); const upgrade = await dependencies.purchaseUpgrade(getPrisma(config), { authenticatedWalletAddress, cutoverAt: config.mineralEconomyCutoverAt, diff --git a/server/api/collectionMining.ts b/server/api/collectionMining.ts index 9be93c3..065ca67 100644 --- a/server/api/collectionMining.ts +++ b/server/api/collectionMining.ts @@ -44,16 +44,17 @@ export function collectionBonusBpsForCount(count: number): number { export function calculateEffectiveMineralsPerDayMicros( baseMineralsPerDay: bigint, - collectionBonusBps: number, + totalModifierBps: number, ): bigint { if (baseMineralsPerDay < 0n) throw new Error('baseMineralsPerDay cannot be negative.'); - if (!Number.isInteger(collectionBonusBps) || collectionBonusBps < 0) { - throw new RangeError('Collection bonus basis points must be a non-negative integer.'); + if (!Number.isInteger(totalModifierBps)) { + throw new RangeError('Mining modifier basis points must be an integer.'); } + const multiplierBps = Math.max(0, 10_000 + totalModifierBps); return ( baseMineralsPerDay * MINERAL_SCALE * - BigInt(10_000 + collectionBonusBps) + BigInt(multiplierBps) ) / BONUS_DENOMINATOR_BPS; } diff --git a/server/api/eligibility.test.ts b/server/api/eligibility.test.ts index 143dc8e..cf6b2bd 100644 --- a/server/api/eligibility.test.ts +++ b/server/api/eligibility.test.ts @@ -59,6 +59,12 @@ describe('Megastera eligibility', () => { ); }); + it('fails closed when the requested log is not a TicketPurchased event', () => { + const unrelatedLog = ticketLog({ topics: [`0x${'00'.repeat(32)}`] as Log['topics'] }); + + expect(() => decodeEligibleTicket(unrelatedLog)).toThrow(/TicketPurchased event/i); + }); + it('locates the requested log index before decoding it', () => { const otherLog = ticketLog({ logIndex: 3 }); expect(findEligibleTicket([otherLog, ticketLog()], 4).ticketId).toBe(456n); diff --git a/server/api/eligibility.ts b/server/api/eligibility.ts index b4e38f1..1c6467b 100644 --- a/server/api/eligibility.ts +++ b/server/api/eligibility.ts @@ -1,4 +1,4 @@ -import { decodeEventLog, getAddress, isHash, stringToHex, type Address, type Hex, type Log, type TransactionReceipt } from 'viem'; +import { getAddress, isAddress, isHash, isHex, parseEventLogs, stringToHex, type Address, type Hex, type Log, type TransactionReceipt } from 'viem'; import { BASE_CHAIN_ID, MEGASTERA_SOURCE } from './config.js'; import { validateTicketPurchasedFields } from '../../shared/ticketValidation.js'; @@ -32,6 +32,30 @@ export type MegasteraProofReference = { const CANONICAL_SOURCE = stringToHex(MEGASTERA_SOURCE, { size: 32 }); +type TicketPurchasedEventArgs = { + recipient: Address; + currentDrawingId: bigint; + source: Hex; + userTicketId: bigint; + normals: readonly number[]; + bonusball: number; +}; + +function isTicketPurchasedEventArgs(value: unknown): value is TicketPurchasedEventArgs { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return false; + const args = value as Record; + return ( + typeof args.recipient === 'string' && + isAddress(args.recipient) && + typeof args.currentDrawingId === 'bigint' && + isHex(args.source) && + typeof args.userTicketId === 'bigint' && + Array.isArray(args.normals) && + args.normals.every((normal: unknown) => typeof normal === 'number') && + typeof args.bonusball === 'number' + ); +} + function asBigInt(value: unknown, label: string): bigint { try { const result = typeof value === 'bigint' ? value : BigInt(String(value)); @@ -80,20 +104,21 @@ export function normalizeMegasteraProof(value: MegasteraProof | Record({ abi: TICKET_PURCHASED_ABI, eventName: 'TicketPurchased', - data: log.data, - topics: log.topics, + logs: [log], + strict: true, }); - if (event.args.source !== stringToHex(MEGASTERA_SOURCE, { size: 32 })) throw new Error('Ticket was not purchased through MEGASTERA.'); - const { recipient } = event.args; - if (!recipient) throw new Error('Malformed TicketPurchased event.'); + const args = event?.args; + if (!isTicketPurchasedEventArgs(args)) throw new Error('Malformed TicketPurchased event.'); + if (args.source !== stringToHex(MEGASTERA_SOURCE, { size: 32 })) throw new Error('Ticket was not purchased through MEGASTERA.'); + const { recipient } = args; const validated = validateTicketPurchasedFields({ - ticketId: event.args.userTicketId, - drawingId: event.args.currentDrawingId, - normals: event.args.normals, - bonusBall: event.args.bonusball, + ticketId: args.userTicketId, + drawingId: args.currentDrawingId, + normals: args.normals, + bonusBall: args.bonusball, logIndex: log.logIndex, }); return { recipient, ...validated, originTxHash: log.transactionHash, blockNumber: log.blockNumber }; diff --git a/server/api/galaxyPulse.test.ts b/server/api/galaxyPulse.test.ts new file mode 100644 index 0000000..862f5c0 --- /dev/null +++ b/server/api/galaxyPulse.test.ts @@ -0,0 +1,73 @@ +import type { Address, Hex } from 'viem'; +import { describe, expect, it } from 'vitest'; +import { + aggregateGalaxyPulseByType, + deriveGalaxyPulseSeed, + deriveGalaxyPulseV1, + GALAXY_PULSE_ALGORITHM_VERSION, + type GalaxyPulseSlot, + resolveGalaxyPulseBps, +} from './galaxyPulse.js'; + +const INPUT = { + drawingId: 218n, + seed: `0x${'11'.repeat(32)}` as Hex, + chainId: 8453, + jackpotAddress: '0x1111111111111111111111111111111111111111' as Address, +} as const; + +describe('Galaxy Pulse V1', () => { + it('derives a stable seed from the drawing and winning numbers', () => { + expect(deriveGalaxyPulseSeed({ drawingId: 151n, winningNumbers: 0x1234n })).toBe( + '0x947b7cc15a9029cfc6aa39072ad5b89bb0dbdbd5fc60872e887bd5c9dfeaffc9', + ); + }); + + it('keeps a literal deterministic vector', () => { + expect(GALAXY_PULSE_ALGORITHM_VERSION).toBe('MEGASTERA_GALAXY_PULSE_V1'); + expect(deriveGalaxyPulseV1(INPUT)).toEqual([ + { planetType: 'gaia', modifierBps: 1_400 }, + { planetType: 'desert', modifierBps: 834 }, + { planetType: 'oceanic', modifierBps: 4_673 }, + { planetType: 'volcanic', modifierBps: -2_454 }, + ] satisfies readonly GalaxyPulseSlot[]); + }); + + it('derives four signed integer slots inside the BPS range', () => { + const slots = deriveGalaxyPulseV1(INPUT); + + expect(slots).toHaveLength(4); + for (const slot of slots) { + expect(Number.isInteger(slot.modifierBps)).toBe(true); + expect(slot.modifierBps).toBeGreaterThanOrEqual(-5_000); + expect(slot.modifierBps).toBeLessThanOrEqual(5_000); + } + }); + + it('is deterministic for identical inputs', () => { + expect(deriveGalaxyPulseV1(INPUT)).toEqual(deriveGalaxyPulseV1(INPUT)); + expect(deriveGalaxyPulseV1({ ...INPUT, drawingId: 219n })).not.toEqual( + deriveGalaxyPulseV1(INPUT), + ); + }); + + it('sums repeated types and resolves stored type casing', () => { + const slots: readonly GalaxyPulseSlot[] = [ + { planetType: 'nebula', modifierBps: 1_250 }, + { planetType: 'gaia', modifierBps: -500 }, + { planetType: 'nebula', modifierBps: -250 }, + { planetType: 'nebula', modifierBps: 1_000 }, + ]; + const byType = aggregateGalaxyPulseByType(slots); + + expect(byType).toEqual( + new Map([ + ['nebula', 2_000], + ['gaia', -500], + ]), + ); + expect(resolveGalaxyPulseBps(byType, 'NEBULA')).toBe(2_000); + expect(resolveGalaxyPulseBps(byType, 'GaIa')).toBe(-500); + expect(resolveGalaxyPulseBps(byType, 'unknown')).toBe(0); + }); +}); diff --git a/server/api/galaxyPulse.ts b/server/api/galaxyPulse.ts new file mode 100644 index 0000000..a326da3 --- /dev/null +++ b/server/api/galaxyPulse.ts @@ -0,0 +1,99 @@ +import { PLANET_TYPES, type PlanetTypeId } from '@megaplanets/planet-generator'; +import { type Address, encodeAbiParameters, type Hex, keccak256 } from 'viem'; + +export const GALAXY_PULSE_ALGORITHM_VERSION = 'MEGASTERA_GALAXY_PULSE_V1' as const; +export const GALAXY_PULSE_SEED_VERSION = 'MEGASTERA_GALAXY_PULSE_SEED_V1' as const; + +const SLOT_COUNT = 4; +const BPS_RANGE = 10_001n; + +export type GalaxyPulseInput = { + drawingId: bigint; + seed: Hex; + chainId: number; + jackpotAddress: Address; +}; + +export function deriveGalaxyPulseSeed(input: { + drawingId: bigint; + winningNumbers: bigint; +}): Hex { + return keccak256( + encodeAbiParameters( + [ + { type: 'string', name: 'version' }, + { type: 'uint256', name: 'drawingId' }, + { type: 'uint256', name: 'winningNumbers' }, + ], + [GALAXY_PULSE_SEED_VERSION, input.drawingId, input.winningNumbers], + ), + ); +} + +export type GalaxyPulseSlot = { + planetType: PlanetTypeId; + modifierBps: number; +}; + +function deriveRootSeed(input: GalaxyPulseInput): Hex { + return keccak256( + encodeAbiParameters( + [ + { type: 'string', name: 'algorithm' }, + { type: 'uint256', name: 'chainId' }, + { type: 'address', name: 'jackpotAddress' }, + { type: 'uint256', name: 'drawingId' }, + { type: 'bytes32', name: 'seed' }, + ], + [ + GALAXY_PULSE_ALGORITHM_VERSION, + BigInt(input.chainId), + input.jackpotAddress, + input.drawingId, + input.seed, + ], + ), + ); +} + +function deriveSlotSeed(rootSeed: Hex, slotIndex: number): Hex { + return keccak256( + encodeAbiParameters( + [ + { type: 'bytes32', name: 'rootSeed' }, + { type: 'uint256', name: 'slotIndex' }, + ], + [rootSeed, BigInt(slotIndex)], + ), + ); +} + +export function deriveGalaxyPulseV1(input: GalaxyPulseInput): readonly GalaxyPulseSlot[] { + const rootSeed = deriveRootSeed(input); + return Array.from({ length: SLOT_COUNT }, (_, slotIndex) => { + const value = BigInt(deriveSlotSeed(rootSeed, slotIndex)); + const planetType = PLANET_TYPES[Number(value % BigInt(PLANET_TYPES.length))]; + if (!planetType) throw new Error('Canonical Planet type is missing.'); + return { + planetType, + modifierBps: Number((value >> 8n) % BPS_RANGE) - 5_000, + }; + }); +} + +export function aggregateGalaxyPulseByType( + slots: readonly GalaxyPulseSlot[], +): Map { + const byType = new Map(); + for (const slot of slots) { + byType.set(slot.planetType, (byType.get(slot.planetType) ?? 0) + slot.modifierBps); + } + return byType; +} + +export function resolveGalaxyPulseBps( + byType: ReadonlyMap, + storedPlanetType: string, +): number { + return byType.get(storedPlanetType.toLowerCase()) ?? 0; +} diff --git a/server/api/galaxyPulseFreshness.test.ts b/server/api/galaxyPulseFreshness.test.ts new file mode 100644 index 0000000..18d08e8 --- /dev/null +++ b/server/api/galaxyPulseFreshness.test.ts @@ -0,0 +1,111 @@ +import { describe, expect, it, vi } from 'vitest'; +import { assertGalaxyPulseFresh, isGalaxyPulseFreshnessError } from './galaxyPulseFreshness.js'; +import type { PrismaClient } from './generated/prisma/client.js'; + +const active = { + id: '151', + status: 'active', + ended_at: '2026-08-22T17:00:00.000Z', +}; +const settled = { + id: '150', + status: 'settled', + settled_at: '2026-08-21T17:00:11.000Z', +}; + +function response(value: unknown, status = 200): Response { + return new Response(JSON.stringify(value), { + status, + headers: { 'content-type': 'application/json' }, + }); +} + +describe('Galaxy Pulse economic freshness', () => { + it('accepts only when official active, latest-settled, and DB Pulse agree', async () => { + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(response(active)) + .mockResolvedValueOnce(response(settled)); + const prisma = { + galaxyPulseRound: { + findFirst: vi.fn().mockResolvedValue({ drawingId: { toString: () => '150' } }), + }, + } as unknown as PrismaClient; + + await expect( + assertGalaxyPulseFresh({ + prisma, + galaxyPulseStartBlock: 1n, + now: new Date('2026-08-22T16:59:00.000Z'), + fetchImpl, + }), + ).resolves.toBeUndefined(); + expect(fetchImpl).toHaveBeenCalledTimes(2); + }); + + it('fails closed after drawing time until the API and worker DB have advanced', async () => { + const prisma = { + galaxyPulseRound: { + findFirst: vi.fn().mockResolvedValue({ drawingId: { toString: () => '150' } }), + }, + } as unknown as PrismaClient; + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(response(active)) + .mockResolvedValueOnce(response(settled)); + + await expect( + assertGalaxyPulseFresh({ + prisma, + galaxyPulseStartBlock: 1n, + now: new Date(active.ended_at), + fetchImpl, + }), + ).rejects.toThrow('Galaxy Pulse is not fresh'); + }); + + it('fails closed when the latest official settlement is not persisted', async () => { + const prisma = { + galaxyPulseRound: { + findFirst: vi.fn().mockResolvedValue({ drawingId: { toString: () => '149' } }), + }, + } as unknown as PrismaClient; + const fetchImpl = vi + .fn() + .mockResolvedValueOnce(response(active)) + .mockResolvedValueOnce(response(settled)); + + await expect( + assertGalaxyPulseFresh({ + prisma, + galaxyPulseStartBlock: 1n, + now: new Date('2026-08-22T16:59:00.000Z'), + fetchImpl, + }), + ).rejects.toThrow('Galaxy Pulse is not fresh'); + }); + + it('does no network or DB work while Pulse is disabled', async () => { + const fetchImpl = vi.fn(); + const findFirst = vi.fn(); + await assertGalaxyPulseFresh({ + prisma: { galaxyPulseRound: { findFirst } } as unknown as PrismaClient, + galaxyPulseStartBlock: null, + now: new Date(), + fetchImpl, + }); + expect(fetchImpl).not.toHaveBeenCalled(); + expect(findFirst).not.toHaveBeenCalled(); + }); + + it('normalizes network failures to the retryable freshness error', async () => { + const request = assertGalaxyPulseFresh({ + prisma: { galaxyPulseRound: { findFirst: vi.fn() } } as unknown as PrismaClient, + galaxyPulseStartBlock: 1n, + now: new Date('2026-08-22T16:59:00.000Z'), + fetchImpl: vi.fn().mockRejectedValue(new TypeError('network down')), + }); + + await expect(request).rejects.toSatisfy(isGalaxyPulseFreshnessError); + }); +}); diff --git a/server/api/galaxyPulseFreshness.ts b/server/api/galaxyPulseFreshness.ts new file mode 100644 index 0000000..a8134d1 --- /dev/null +++ b/server/api/galaxyPulseFreshness.ts @@ -0,0 +1,67 @@ +import type { PrismaClient } from './generated/prisma/client.js'; + +const ACTIVE_ROUND_URL = 'https://api.megapot.io/v1/rounds/active'; +const LATEST_SETTLED_ROUND_URL = 'https://api.megapot.io/v1/rounds/latest-settled'; +const STALE_ERROR = 'Galaxy Pulse is not fresh; retry later.'; + +export function isGalaxyPulseFreshnessError(error: unknown): boolean { + return error instanceof Error && error.message === STALE_ERROR; +} + +type RoundSummary = { + id: string; + status: 'active' | 'settled'; + ended_at?: string | null; + settled_at?: string | null; +}; + +async function readRound(fetchImpl: typeof fetch, url: string): Promise { + const response = await fetchImpl(url, { + headers: { accept: 'application/json' }, + signal: AbortSignal.timeout(5_000), + }); + if (!response.ok) throw new Error(STALE_ERROR); + const value = (await response.json()) as Partial; + if (typeof value.id !== 'string' || !/^\d+$/.test(value.id)) throw new Error(STALE_ERROR); + if (value.status !== 'active' && value.status !== 'settled') throw new Error(STALE_ERROR); + return value as RoundSummary; +} + +export async function assertGalaxyPulseFresh(input: { + prisma: PrismaClient; + galaxyPulseStartBlock: bigint | null; + now: Date; + fetchImpl?: typeof fetch; +}): Promise { + if (input.galaxyPulseStartBlock === null) return; + try { + const fetchImpl = input.fetchImpl ?? fetch; + const [active, settled, latestPulse] = await Promise.all([ + readRound(fetchImpl, ACTIVE_ROUND_URL), + readRound(fetchImpl, LATEST_SETTLED_ROUND_URL), + input.prisma.galaxyPulseRound.findFirst({ + orderBy: { drawingId: 'desc' }, + select: { drawingId: true }, + }), + ]); + const endedAt = active.ended_at ? new Date(active.ended_at) : null; + const settledAt = settled.settled_at ? new Date(settled.settled_at) : null; + const activeId = BigInt(active.id); + const settledId = BigInt(settled.id); + if ( + active.status !== 'active' || + settled.status !== 'settled' || + !endedAt || + !Number.isFinite(endedAt.getTime()) || + !settledAt || + !Number.isFinite(settledAt.getTime()) || + input.now >= endedAt || + activeId !== settledId + 1n || + !latestPulse || + BigInt(latestPulse.drawingId.toString()) !== settledId + ) + throw new Error(STALE_ERROR); + } catch { + throw new Error(STALE_ERROR); + } +} diff --git a/server/api/galaxyPulseIndexer.test.ts b/server/api/galaxyPulseIndexer.test.ts new file mode 100644 index 0000000..3da11ba --- /dev/null +++ b/server/api/galaxyPulseIndexer.test.ts @@ -0,0 +1,175 @@ +import { + encodeAbiParameters, + type Hex, + keccak256, + type Log, + type TransactionReceipt, + toBytes, +} from 'viem'; +import { describe, expect, it } from 'vitest'; +import { + decodeGalaxyPulseSettlementReceipt, + type GalaxyPulseRound, + type GalaxyPulseRoundStore, + persistGalaxyPulseRound, +} from './galaxyPulseIndexer.js'; + +const JACKPOT_ADDRESS = '0x1111111111111111111111111111111111111111' as const; +const WRONG_ADDRESS = '0x3333333333333333333333333333333333333333' as const; +const TRANSACTION_HASH = `0x${'11'.repeat(32)}` as Hex; +const BLOCK_HASH = `0x${'22'.repeat(32)}` as Hex; +const DRAWING_ID = 42n; +const BLOCK_NUMBER = 123_456n; +const BLOCK_TIMESTAMP = new Date('2026-08-22T12:34:56.000Z'); + +function eventTopic(signature: string): Hex { + return keccak256(toBytes(signature)); +} + +function makeLog(input: { + address: string; + data: Hex; + topics: readonly Hex[]; + logIndex: number; +}): Log { + return { + address: input.address, + blockHash: BLOCK_HASH, + blockNumber: BLOCK_NUMBER, + data: input.data, + logIndex: input.logIndex, + removed: false, + topics: input.topics, + transactionHash: TRANSACTION_HASH, + transactionIndex: 0, + blockTimestamp: undefined, + } as unknown as Log; +} + +function makeJackpotSettledLog( + overrides: Partial<{ address: string; drawingId: bigint; logIndex: number }> = {}, +): Log { + const drawingId = overrides.drawingId ?? DRAWING_ID; + return makeLog({ + address: overrides.address ?? JACKPOT_ADDRESS, + logIndex: overrides.logIndex ?? 0, + topics: [ + eventTopic('JackpotSettled(uint256,uint256,uint256,uint8,uint256,uint256)'), + encodeAbiParameters([{ type: 'uint256' }], [drawingId]), + ], + data: encodeAbiParameters( + [ + { type: 'uint256' }, + { type: 'uint256' }, + { type: 'uint8' }, + { type: 'uint256' }, + { type: 'uint256' }, + ], + [100n, 200n, 5, 0x1234n, 300n], + ), + }); +} + +function makeReceipt(logs: readonly Log[]): TransactionReceipt { + return { + blockHash: BLOCK_HASH, + blockNumber: BLOCK_NUMBER, + cumulativeGasUsed: 1n, + effectiveGasPrice: 1n, + from: JACKPOT_ADDRESS, + gasUsed: 1n, + logs, + logsBloom: `0x${'00'.repeat(256)}`, + status: 'success', + to: JACKPOT_ADDRESS, + transactionHash: TRANSACTION_HASH, + transactionIndex: 0, + type: 'eip1559', + } as unknown as TransactionReceipt; +} + +function validSettlement(): GalaxyPulseRound { + return { + drawingId: DRAWING_ID, + seed: '0xfab72b15dd628f60b7525cf14fa40841b6fab21a6269c3a336cde9bdd890ffae', + settlementTxHash: TRANSACTION_HASH, + settledAt: BLOCK_TIMESTAMP, + }; +} + +function makeStore() { + const rows = new Map(); + const store: GalaxyPulseRoundStore = { + async findByDrawingId(drawingId) { + return rows.get(drawingId.toString()) ?? null; + }, + async create(round) { + rows.set(round.drawingId.toString(), round); + return round; + }, + }; + return { rows, store }; +} + +describe('decodeGalaxyPulseSettlementReceipt', () => { + it('extracts the drawing and derives a seed from the winning numbers', () => { + const result = decodeGalaxyPulseSettlementReceipt({ + receipt: makeReceipt([makeJackpotSettledLog()]), + jackpotAddress: JACKPOT_ADDRESS, + blockTimestamp: BLOCK_TIMESTAMP, + }); + + expect(result).toEqual(validSettlement()); + }); + + it('rejects an ambiguous receipt with more than one settlement event', () => { + expect(() => + decodeGalaxyPulseSettlementReceipt({ + receipt: makeReceipt([ + makeJackpotSettledLog(), + makeJackpotSettledLog({ logIndex: 2 }), + ]), + jackpotAddress: JACKPOT_ADDRESS, + blockTimestamp: 1n, + }), + ).toThrow(/exactly one JackpotSettled/i); + }); + + it.each([ + [ + 'JackpotSettled', + makeJackpotSettledLog({ address: WRONG_ADDRESS }), + ], + ])('rejects %s emitted by an unexpected address', (_name, settlementLog) => { + expect(() => + decodeGalaxyPulseSettlementReceipt({ + receipt: makeReceipt([settlementLog]), + jackpotAddress: JACKPOT_ADDRESS, + blockTimestamp: 1n, + }), + ).toThrow(/unexpected|expected/i); + }); +}); + +describe('persistGalaxyPulseRound', () => { + it('returns the existing row on an identical replay', async () => { + const { rows, store } = makeStore(); + const first = await persistGalaxyPulseRound(store, validSettlement()); + const replay = await persistGalaxyPulseRound(store, { ...validSettlement() }); + + expect(replay).toBe(first); + expect(rows.size).toBe(1); + }); + + it.each([ + ['seed', { seed: `0x${'bb'.repeat(32)}` as Hex }], + ['transaction hash', { settlementTxHash: `0x${'33'.repeat(32)}` as Hex }], + ])('fails closed when a replay conflicts on %s', async (_field, conflict) => { + const { store } = makeStore(); + await persistGalaxyPulseRound(store, validSettlement()); + + await expect( + persistGalaxyPulseRound(store, { ...validSettlement(), ...conflict }), + ).rejects.toThrow(/conflict/i); + }); +}); diff --git a/server/api/galaxyPulseIndexer.ts b/server/api/galaxyPulseIndexer.ts new file mode 100644 index 0000000..11722f5 --- /dev/null +++ b/server/api/galaxyPulseIndexer.ts @@ -0,0 +1,182 @@ +import { + type Address, + decodeEventLog, + getAddress, + type Hex, + isHash, + keccak256, + type Log, + type TransactionReceipt, + toBytes, +} from 'viem'; +import { deriveGalaxyPulseSeed } from './galaxyPulse.js'; + +export const JACKPOT_SETTLED_ABI = [ + { + type: 'event', + name: 'JackpotSettled', + inputs: [ + { indexed: true, name: 'drawingId', type: 'uint256' }, + { indexed: false, name: 'totalTicketsSold', type: 'uint256' }, + { indexed: false, name: 'userWinnings', type: 'uint256' }, + { indexed: false, name: 'winningBonusball', type: 'uint8' }, + { indexed: false, name: 'winningNumbers', type: 'uint256' }, + { indexed: false, name: 'newDrawingAccumulator', type: 'uint256' }, + ], + }, +] as const; + +const JACKPOT_SETTLED_TOPIC = keccak256( + toBytes('JackpotSettled(uint256,uint256,uint256,uint8,uint256,uint256)'), +); + +export type GalaxyPulseRound = { + drawingId: bigint; + seed: Hex; + settlementTxHash: Hex; + settledAt: Date; +}; + +export type GalaxyPulseRoundStore = { + findByDrawingId(drawingId: bigint): Promise; + create(round: GalaxyPulseRound): Promise; +}; + +export type GalaxyPulseSettlementReceiptInput = { + receipt: TransactionReceipt; + jackpotAddress: Address; + /** Block timestamps returned by viem are Unix seconds; Date is accepted for tests/adapters. */ + blockTimestamp: bigint | number | Date; +}; + +function receiptProvenance(receipt: TransactionReceipt): { + transactionHash: Hex; + blockHash: Hex; + blockNumber: bigint; +} { + if (receipt.status !== 'success') + throw new Error('Galaxy Pulse settlement receipt did not succeed.'); + if ( + typeof receipt.transactionHash !== 'string' || + !isHash(receipt.transactionHash) || + typeof receipt.blockHash !== 'string' || + !isHash(receipt.blockHash) || + typeof receipt.blockNumber !== 'bigint' + ) { + throw new Error('Galaxy Pulse settlement receipt has incomplete block provenance.'); + } + return { + transactionHash: receipt.transactionHash, + blockHash: receipt.blockHash, + blockNumber: receipt.blockNumber, + }; +} + +function assertLogProvenance(log: Log, provenance: ReturnType): void { + if ( + log.transactionHash && + log.transactionHash.toLowerCase() !== provenance.transactionHash.toLowerCase() + ) { + throw new Error('Galaxy Pulse event log transaction hash is not canonical.'); + } + if (log.blockHash && log.blockHash.toLowerCase() !== provenance.blockHash.toLowerCase()) { + throw new Error('Galaxy Pulse event log block hash is not canonical.'); + } + if ( + log.blockNumber !== undefined && + log.blockNumber !== null && + log.blockNumber !== provenance.blockNumber + ) { + throw new Error('Galaxy Pulse event log block number is not canonical.'); + } +} + +function findExactlyOneEvent( + receipt: TransactionReceipt, + topic: Hex, + label: string, + expectedAddress: Address, + provenance: ReturnType, +): Log { + const matchingLogs = receipt.logs.filter( + (log) => log.topics[0]?.toLowerCase() === topic.toLowerCase(), + ); + if (matchingLogs.length !== 1) { + throw new Error(`Galaxy Pulse receipt must contain exactly one ${label} event.`); + } + const [log] = matchingLogs; + if (!log || getAddress(log.address) !== getAddress(expectedAddress)) { + throw new Error(`Galaxy Pulse ${label} event was emitted by an unexpected address.`); + } + assertLogProvenance(log, provenance); + return log; +} + +function blockTimestampDate(value: bigint | number | Date): Date { + if (value instanceof Date) { + const milliseconds = value.getTime(); + if (!Number.isSafeInteger(milliseconds) || milliseconds < 0) { + throw new Error('Galaxy Pulse block timestamp is invalid.'); + } + return new Date(milliseconds); + } + if ( + (typeof value !== 'bigint' && typeof value !== 'number') || + value < 0 || + (typeof value === 'number' && !Number.isSafeInteger(value)) + ) { + throw new Error('Galaxy Pulse block timestamp is invalid.'); + } + const seconds = typeof value === 'bigint' ? value : BigInt(value); + const maxSeconds = BigInt(Math.floor(Number.MAX_SAFE_INTEGER / 1_000)); + if (seconds > maxSeconds) throw new Error('Galaxy Pulse block timestamp is invalid.'); + return new Date(Number(seconds) * 1_000); +} + +/** Decodes one finalized JackpotSettled receipt and derives its Galaxy Pulse seed. */ +export function decodeGalaxyPulseSettlementReceipt( + input: GalaxyPulseSettlementReceiptInput, +): GalaxyPulseRound { + const provenance = receiptProvenance(input.receipt); + const settledLog = findExactlyOneEvent( + input.receipt, + JACKPOT_SETTLED_TOPIC, + 'JackpotSettled', + input.jackpotAddress, + provenance, + ); + const settled = decodeEventLog({ + abi: JACKPOT_SETTLED_ABI, + eventName: 'JackpotSettled', + data: settledLog.data, + topics: settledLog.topics, + }); + return { + drawingId: settled.args.drawingId, + seed: deriveGalaxyPulseSeed({ + drawingId: settled.args.drawingId, + winningNumbers: settled.args.winningNumbers, + }), + settlementTxHash: provenance.transactionHash, + settledAt: blockTimestampDate(input.blockTimestamp), + }; +} + +/** Inserts once, reuses exact replays, and rejects any drawing conflict. */ +export async function persistGalaxyPulseRound( + store: GalaxyPulseRoundStore, + round: GalaxyPulseRound, +): Promise { + if (!isHash(round.seed) || !isHash(round.settlementTxHash)) { + throw new Error('Galaxy Pulse round hash is invalid.'); + } + const existing = await store.findByDrawingId(round.drawingId); + if (!existing) return store.create(round); + if ( + existing.seed.toLowerCase() !== round.seed.toLowerCase() || + existing.settlementTxHash.toLowerCase() !== round.settlementTxHash.toLowerCase() + ) { + throw new Error(`Galaxy Pulse round conflict for drawing ${round.drawingId.toString()}.`); + } + return existing; +} diff --git a/server/api/galaxyPulseStore.test.ts b/server/api/galaxyPulseStore.test.ts new file mode 100644 index 0000000..3a4965b --- /dev/null +++ b/server/api/galaxyPulseStore.test.ts @@ -0,0 +1,101 @@ +import type { Hex } from 'viem'; +import { describe, expect, it, vi } from 'vitest'; +import { BASE_CHAIN_ID } from './config.js'; +import { BASE_JACKPOT } from './eligibility.js'; +import { aggregateGalaxyPulseByType, deriveGalaxyPulseV1 } from './galaxyPulse.js'; +import { + type GalaxyPulseRoundRow, + type GalaxyPulseStoreClient, + type GalaxyPulseTemporalRound, + loadGalaxyPulseRounds, + serializeCurrentGalaxyPulse, +} from './galaxyPulseStore.js'; + +const TO = new Date('2026-08-22T00:00:00.000Z'); +const SEED_A = `0x${'11'.repeat(32)}` as Hex; +const SEED_B = `0x${'22'.repeat(32)}` as Hex; + +function row( + drawingId: bigint, + settledAt: string, + seed: Hex, +): GalaxyPulseRoundRow & { seed: Hex } { + return { drawingId, seed, settledAt: new Date(settledAt) }; +} + +function drawingId(round: GalaxyPulseRoundRow): bigint { + return BigInt(round.drawingId.toString()); +} + +function expectedModifiers(round: GalaxyPulseRoundRow & { seed: Hex }): Record { + return Object.fromEntries( + aggregateGalaxyPulseByType( + deriveGalaxyPulseV1({ + drawingId: drawingId(round), + seed: round.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + }), + ), + ); +} + +describe('Galaxy Pulse store', () => { + it('loads settled rounds through an explicit minimal client in deterministic time order', async () => { + const later = row(2n, '2026-08-21T00:00:00.000Z', SEED_B); + const earlier = row(1n, '2026-08-20T00:00:00.000Z', SEED_A); + const findMany = vi.fn(async () => [later, earlier]); + const client: GalaxyPulseStoreClient = { galaxyPulseRound: { findMany } }; + + await expect(loadGalaxyPulseRounds(client, TO)).resolves.toEqual([ + { + drawingId: 1n, + settledAt: earlier.settledAt, + slots: deriveGalaxyPulseV1({ + drawingId: drawingId(earlier), + seed: earlier.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + }), + modifiersBps: expectedModifiers(earlier), + }, + { + drawingId: 2n, + settledAt: later.settledAt, + slots: deriveGalaxyPulseV1({ + drawingId: drawingId(later), + seed: later.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + }), + modifiersBps: expectedModifiers(later), + }, + ]); + expect(findMany).toHaveBeenCalledWith({ + where: { settledAt: { lte: TO } }, + orderBy: { settledAt: 'asc' }, + }); + }); + + it('serializes the current stored round with raw slots and stable strings', () => { + const stored = row(218n, '2026-08-21T12:34:56.000Z', SEED_A); + const temporal: GalaxyPulseTemporalRound = { + drawingId: drawingId(stored), + settledAt: stored.settledAt, + slots: deriveGalaxyPulseV1({ + drawingId: drawingId(stored), + seed: stored.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + }), + modifiersBps: expectedModifiers(stored), + }; + + expect(serializeCurrentGalaxyPulse(temporal)).toEqual({ + drawingId: '218', + settledAt: stored.settledAt.toISOString(), + slots: temporal.slots, + }); + expect(serializeCurrentGalaxyPulse(null)).toBeNull(); + }); +}); diff --git a/server/api/galaxyPulseStore.ts b/server/api/galaxyPulseStore.ts new file mode 100644 index 0000000..13714c1 --- /dev/null +++ b/server/api/galaxyPulseStore.ts @@ -0,0 +1,92 @@ +import { isHash } from 'viem'; +import { BASE_CHAIN_ID } from './config.js'; +import { BASE_JACKPOT } from './eligibility.js'; +import { + aggregateGalaxyPulseByType, + deriveGalaxyPulseV1, + type GalaxyPulseSlot, +} from './galaxyPulse.js'; + +export type GalaxyPulseRoundRow = { + drawingId: bigint | string | { toString(): string }; + seed: string; + settledAt: Date; +}; + +export type GalaxyPulseStoreClient = { + galaxyPulseRound: { + findMany(args: { + where: { settledAt: { lte: Date } }; + orderBy: { settledAt: 'asc' }; + }): Promise; + }; +}; + +export type GalaxyPulseTemporalRound = { + drawingId: bigint; + settledAt: Date; + slots: readonly GalaxyPulseSlot[]; + modifiersBps: Readonly>; +}; + +export type SerializedGalaxyPulse = { + drawingId: string; + settledAt: string; + slots: readonly GalaxyPulseSlot[]; +}; + +function normalizeDrawingId(row: GalaxyPulseRoundRow): bigint { + const drawingId = BigInt(row.drawingId.toString()); + if (drawingId < 0n) throw new RangeError('Galaxy Pulse drawing ID cannot be negative.'); + return drawingId; +} + +function deriveSlots(row: GalaxyPulseRoundRow): readonly GalaxyPulseSlot[] { + if (!isHash(row.seed)) throw new Error('Galaxy Pulse seed is invalid.'); + return deriveGalaxyPulseV1({ + drawingId: normalizeDrawingId(row), + seed: row.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + }); +} + +function temporalRound(row: GalaxyPulseRoundRow): GalaxyPulseTemporalRound { + const drawingId = normalizeDrawingId(row); + const slots = deriveSlots(row); + return { + drawingId, + settledAt: row.settledAt, + slots, + modifiersBps: Object.fromEntries(aggregateGalaxyPulseByType(slots)), + }; +} + +export async function loadGalaxyPulseRounds( + client: GalaxyPulseStoreClient, + to: Date, +): Promise { + const rows = await client.galaxyPulseRound.findMany({ + where: { settledAt: { lte: to } }, + orderBy: { settledAt: 'asc' }, + }); + return rows + .filter((row) => row.settledAt.getTime() <= to.getTime()) + .map((row) => temporalRound(row)) + .sort( + (left, right) => + left.settledAt.getTime() - right.settledAt.getTime() || + (left.drawingId < right.drawingId ? -1 : left.drawingId > right.drawingId ? 1 : 0), + ); +} + +export function serializeCurrentGalaxyPulse( + round: GalaxyPulseTemporalRound | null, +): SerializedGalaxyPulse | null { + if (!round) return null; + return { + drawingId: round.drawingId.toString(), + settledAt: round.settledAt.toISOString(), + slots: round.slots, + }; +} diff --git a/server/api/index.test.ts b/server/api/index.test.ts index dec339a..54b9185 100644 --- a/server/api/index.test.ts +++ b/server/api/index.test.ts @@ -3,6 +3,7 @@ import { createApp } from './index.js'; afterEach(() => { vi.restoreAllMocks(); + vi.unstubAllEnvs(); }); describe('active API surface', () => { @@ -18,6 +19,13 @@ describe('active API surface', () => { expect((await app.request('/api/planets/readiness')).status).toBe(404); }); + it('protects the leaderboard worker trigger with the cron secret', async () => { + vi.stubEnv('CRON_SECRET', 'test-secret'); + const response = await createApp().request('/api/internal/leaderboard-worker'); + + expect(response.status).toBe(401); + }); + it('forwards the configured Megapot API path used by the production bundle', async () => { const upstreamResponse = { id: '148', status: 'active' }; const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue( diff --git a/server/api/index.ts b/server/api/index.ts index 9f9ebbf..5f415ef 100644 --- a/server/api/index.ts +++ b/server/api/index.ts @@ -5,6 +5,8 @@ import { type BackendPlanetRouteDependencies, } from './backendPlanetRoutes.js'; import { createLeaderboardRoutes } from './leaderboardRoutes.js'; +import { reportBackendError } from './errorDiagnostics.js'; +import { runLeaderboardFinalization } from './leaderboardWorker.js'; import { createOperationalState } from './operations.js'; import megapotProxy from '../proxy.js'; @@ -31,6 +33,22 @@ export function createApp( app.get('/api/planets/metrics', (c) => c.json({ ok: true, service: 'api', operations: operations.snapshot() }), ); + app.get('/api/internal/leaderboard-worker', async (c) => { + const cronSecret = process.env.CRON_SECRET?.trim(); + if (!cronSecret || c.req.header('authorization') !== `Bearer ${cronSecret}`) { + return c.json({ error: 'Unauthorized.' }, 401); + } + try { + await runLeaderboardFinalization(); + return c.json({ ok: true }); + } catch (error) { + return c.json( + { error: 'Leaderboard worker failed.' }, + 500, + reportBackendError('GET /api/internal/leaderboard-worker', error), + ); + } + }); app.route('/', megapotProxy); app.route('/api', createBackendPlanetRoutes(backendPlanetOverrides)); app.route('/api/leaderboard', createLeaderboardRoutes()); diff --git a/server/api/leaderboardStore.test.ts b/server/api/leaderboardStore.test.ts index 7602091..7faefa2 100644 --- a/server/api/leaderboardStore.test.ts +++ b/server/api/leaderboardStore.test.ts @@ -256,6 +256,34 @@ describe('live leaderboard', () => { }); describe('post-cutover spendable leaderboard', () => { + it('uses the same Galaxy Pulse boundaries for score and current rate', () => { + const rows = calculatePostCutoverLeaderboardRows({ + period: POST_CUTOVER_PERIOD, + asOf: new Date('2026-08-22T00:00:00.000Z'), + cutoverAt: CUTOVER, + accounts: [{ ownerAddress: ADDRESS_A, openingBalanceMicros: 0n }], + planets: [{ + id: 'pulse-planet', + ownerAddress: ADDRESS_A, + planetType: 'Gaia', + baseMineralsPerDay: 1n, + generatedAt: CUTOVER, + }], + purchases: [], + pulseRounds: [{ + settledAt: new Date('2026-08-20T12:00:00.000Z'), + modifiersBps: { gaia: 5_000 }, + }], + }); + + expect(rows).toEqual([{ + rank: 1, + walletAddress: ADDRESS_A, + scoreMicros: 1_250_000n, + effectiveMineralsPerDayMicros: 1_500_000n, + }]); + }); + it('rejects a reconstructed negative spendable balance', () => { expect(() => calculatePostCutoverLeaderboardRows({ period: POST_CUTOVER_PERIOD, diff --git a/server/api/leaderboardStore.ts b/server/api/leaderboardStore.ts index d6e42db..141b1cf 100644 --- a/server/api/leaderboardStore.ts +++ b/server/api/leaderboardStore.ts @@ -13,7 +13,9 @@ import { } from './leaderboard.js'; import { calculateHistoricalProduction, + galaxyPulseBpsAt, upgradeBonusBpsAt, + type GalaxyPulseMiningRound, type MineralCollectionPlanet, type MineralUpgradePurchase, } from './mineralEconomy.js'; @@ -24,6 +26,7 @@ import { getPostgresClockTimestamp, resolveMineralEconomyForOperation, } from './mineralAccounts.js'; +import { loadGalaxyPulseRounds, type GalaxyPulseTemporalRound } from './galaxyPulseStore.js'; import { calculateLifetimeMinerals, MINERAL_SCALE } from './mining.js'; const ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'; @@ -214,6 +217,7 @@ export function calculatePostCutoverLeaderboardRows(input: { accounts: readonly SpendableLeaderboardAccount[]; planets: readonly SpendableLeaderboardPlanet[]; purchases: readonly SpendableLeaderboardPurchase[]; + pulseRounds?: readonly GalaxyPulseMiningRound[]; useCurrentBalance?: boolean; }): RankedLeaderboardRow[] { if (!Number.isFinite(input.cutoverAt.getTime())) @@ -274,6 +278,7 @@ export function calculatePostCutoverLeaderboardRows(input: { from: input.cutoverAt, to: cutoff, anchor: input.cutoverAt, + pulseRounds: input.pulseRounds, }); const purchaseCostsMicros = purchases.reduce((total, purchase) => total + purchase.costMicros, 0n); const currentAccount = account && account.balanceMicros !== undefined && account.lastSettledAt instanceof Date @@ -287,6 +292,7 @@ export function calculatePostCutoverLeaderboardRows(input: { asOf: cutoff, planets, purchases, + pulseRounds: input.pulseRounds, }) : openingBalanceMicros + producedMicros - purchaseCostsMicros; if (scoreMicros < 0n) { @@ -302,7 +308,9 @@ export function calculatePostCutoverLeaderboardRows(input: { ownerAddress, calculateEffectiveMineralsPerDayMicros( planet.baseMineralsPerDay, - (collection?.collectionBonusBps ?? 0) + upgradeBonusBps, + (collection?.collectionBonusBps ?? 0) + + upgradeBonusBps + + galaxyPulseBpsAt(input.pulseRounds ?? [], planet.planetType, cutoff.getTime()), ), ); } @@ -399,7 +407,7 @@ async function getLiveLeaderboardSnapshot( if (!cutoverAt || asOf < cutoverAt) { return { asOf, rows: calculateLiveLeaderboardRows({ asOf, planets }) }; } - const [accounts, purchases] = await Promise.all([ + const [accounts, purchases, pulseRounds] = await Promise.all([ transaction.mineralAccount.findMany({ select: { ownerAddress: true, @@ -420,6 +428,7 @@ async function getLiveLeaderboardSnapshot( purchasedAt: true, }, }), + transaction.galaxyPulseRound ? loadGalaxyPulseRounds(transaction, asOf) : [], ]); return { asOf, @@ -430,6 +439,7 @@ async function getLiveLeaderboardSnapshot( accounts, planets, purchases, + pulseRounds, useCurrentBalance: true, }), }; @@ -448,6 +458,7 @@ type FinalizationRead = { planets: unknown[]; accounts?: unknown[]; purchases?: unknown[]; + pulseRounds?: readonly GalaxyPulseTemporalRound[]; }; async function readFinalizationData( @@ -481,7 +492,7 @@ async function readFinalizationData( }).planetUpgradePurchase; if (!accountModel || !purchaseModel) throw new Error('Post-cutover leaderboard models are unavailable.'); - const [accounts, purchases] = await Promise.all([ + const [accounts, purchases, pulseRounds] = await Promise.all([ accountModel.findMany({ select: { ownerAddress: true, openingBalanceMicros: true } }), purchaseModel.findMany({ where: { purchasedAt: { lt: period.endsAt } }, @@ -495,8 +506,11 @@ async function readFinalizationData( purchasedAt: true, }, }), + transaction.galaxyPulseRound + ? loadGalaxyPulseRounds(transaction, new Date(period.endsAt.getTime() - 1)) + : [], ]); - return { postCutover, planets, accounts, purchases }; + return { postCutover, planets, accounts, purchases, pulseRounds }; } function rowsForFinalization( @@ -512,6 +526,7 @@ function rowsForFinalization( planets: data.planets as SpendableLeaderboardPlanet[], accounts: data.accounts as SpendableLeaderboardAccount[], purchases: data.purchases as SpendableLeaderboardPurchase[], + pulseRounds: data.pulseRounds, }); } return calculateLeaderboardRows({ diff --git a/server/api/leaderboardWorker.test.ts b/server/api/leaderboardWorker.test.ts new file mode 100644 index 0000000..2187ab8 --- /dev/null +++ b/server/api/leaderboardWorker.test.ts @@ -0,0 +1,284 @@ +import { + encodeAbiParameters, + type Hex, + keccak256, + type Log, + type TransactionReceipt, + toBytes, +} from 'viem'; +import { describe, expect, it, vi } from 'vitest'; +import type { PrismaClient } from './generated/prisma/client.js'; +import { + GALAXY_PULSE_JACKPOT_ADDRESS, + ingestGalaxyPulseRounds, + runLeaderboardFinalization, +} from './leaderboardWorker.js'; + +const TRANSACTION_HASH = `0x${'11'.repeat(32)}` as Hex; +const BLOCK_HASH = `0x${'22'.repeat(32)}` as Hex; +const SETTLEMENT_BLOCK = 110n; +const FINALIZED_TO_BLOCK = 118n; +const BLOCK_TIMESTAMP = 1_787_000_000n; +const NOW = new Date('2026-08-22T18:00:00.000Z'); + +const JACKPOT_SETTLED_TOPIC = keccak256( + toBytes('JackpotSettled(uint256,uint256,uint256,uint8,uint256,uint256)'), +); + +function makeLog(input: { + address: string; + topics: readonly Hex[]; + data: Hex; + logIndex: number; +}): Log { + return { + address: input.address, + blockHash: BLOCK_HASH, + blockNumber: SETTLEMENT_BLOCK, + data: input.data, + logIndex: input.logIndex, + removed: false, + topics: input.topics, + transactionHash: TRANSACTION_HASH, + transactionIndex: 0, + } as unknown as Log; +} + +function makeSettlementLogs(): Log[] { + return [ + makeLog({ + address: GALAXY_PULSE_JACKPOT_ADDRESS, + topics: [JACKPOT_SETTLED_TOPIC, encodeAbiParameters([{ type: 'uint256' }], [42n])], + data: encodeAbiParameters( + [ + { type: 'uint256' }, + { type: 'uint256' }, + { type: 'uint8' }, + { type: 'uint256' }, + { type: 'uint256' }, + ], + [100n, 200n, 5, 0x1234n, 300n], + ), + logIndex: 0, + }), + ]; +} + +function makeReceipt( + logs: readonly Log[], + status: 'success' | 'reverted' = 'success', +): TransactionReceipt { + return { + blockHash: BLOCK_HASH, + blockNumber: SETTLEMENT_BLOCK, + cumulativeGasUsed: 1n, + effectiveGasPrice: 1n, + from: GALAXY_PULSE_JACKPOT_ADDRESS, + gasUsed: 1n, + logs, + logsBloom: `0x${'00'.repeat(256)}`, + status, + to: GALAXY_PULSE_JACKPOT_ADDRESS, + transactionHash: TRANSACTION_HASH, + transactionIndex: 0, + type: 'eip1559', + } as unknown as TransactionReceipt; +} + +function makePrisma(cursorNextBlock = 100n, lastBlockHash: string | null = null) { + const events: string[] = []; + let cursor = { + chainId: 8453, + contractAddress: GALAXY_PULSE_JACKPOT_ADDRESS.toLowerCase(), + stream: 'galaxy-pulse-rounds', + nextBlock: cursorNextBlock, + lastBlockHash, + }; + const rounds = new Map< + string, + { drawingId: string; seed: string; settlementTxHash: string; settledAt: Date } + >(); + const indexerCursor = { + findUnique: vi.fn(async () => cursor), + upsert: vi.fn( + async ({ create, update }: { create: typeof cursor; update: Partial }) => { + events.push('cursor'); + cursor = { ...cursor, ...create, ...update }; + return cursor; + }, + ), + }; + const galaxyPulseRound = { + findUnique: vi.fn( + async ({ where }: { where: { drawingId: string } }) => rounds.get(where.drawingId) ?? null, + ), + create: vi.fn( + async ({ + data, + }: { + data: { drawingId: string; seed: string; settlementTxHash: string; settledAt: Date }; + }) => { + events.push('persist'); + rounds.set(data.drawingId, data); + return data; + }, + ), + }; + return { + events, + cursor: indexerCursor, + rounds, + prisma: { indexerCursor, galaxyPulseRound } as unknown as PrismaClient, + }; +} + +function makeClient(logs = makeSettlementLogs(), receipt = makeReceipt(logs)) { + return { + getBlockNumber: vi.fn(async () => 120n), + getLogs: vi.fn(async () => logs.filter((log) => log.address === GALAXY_PULSE_JACKPOT_ADDRESS)), + getTransactionReceipt: vi.fn(async () => receipt), + getBlock: vi.fn(async () => ({ hash: BLOCK_HASH, timestamp: BLOCK_TIMESTAMP })), + }; +} + +const BASE_ENV = { + BASE_RPC_URL: 'https://rpc.example.test', + DATABASE_URL: 'postgresql://example.test/db', +}; + +describe('ingestGalaxyPulseRounds', () => { + it('processes finalized logs before advancing the separate cursor', async () => { + const { events, cursor, rounds, prisma } = makePrisma(); + const client = makeClient(); + + await ingestGalaxyPulseRounds({ + prisma, + startBlock: 100n, + confirmations: 2n, + rpcEndpoints: ['fixture'], + makeClient: () => client, + }); + + expect(client.getLogs).toHaveBeenCalledWith( + expect.objectContaining({ + address: GALAXY_PULSE_JACKPOT_ADDRESS, + fromBlock: 100n, + toBlock: FINALIZED_TO_BLOCK, + }), + ); + expect(client.getTransactionReceipt).toHaveBeenCalledWith({ hash: TRANSACTION_HASH }); + expect(client.getBlock).toHaveBeenCalledWith({ blockNumber: SETTLEMENT_BLOCK }); + expect(events).toEqual(['persist', 'cursor']); + expect(rounds.get('42')).toEqual({ + drawingId: '42', + seed: '0xfab72b15dd628f60b7525cf14fa40841b6fab21a6269c3a336cde9bdd890ffae', + settlementTxHash: TRANSACTION_HASH, + settledAt: new Date(Number(BLOCK_TIMESTAMP) * 1_000), + }); + expect(cursor.upsert).toHaveBeenCalledWith( + expect.objectContaining({ + update: { nextBlock: 119n, lastBlockHash: BLOCK_HASH }, + }), + ); + }); + + it('does not advance the cursor when receipt verification fails', async () => { + const { events, cursor, prisma } = makePrisma(); + const logs = makeSettlementLogs(); + const client = makeClient(logs, makeReceipt(logs, 'reverted')); + + await expect( + ingestGalaxyPulseRounds({ + prisma, + startBlock: 100n, + confirmations: 2n, + rpcEndpoints: ['fixture'], + makeClient: () => client, + }), + ).rejects.toThrow(/did not succeed/i); + + expect(events).toEqual([]); + expect(cursor.upsert).not.toHaveBeenCalled(); + }); + + it('fails closed when the persisted cursor provenance is no longer canonical', async () => { + const { cursor, prisma } = makePrisma(100n, `0x${'33'.repeat(32)}`); + const client = makeClient(); + + await expect( + ingestGalaxyPulseRounds({ + prisma, + startBlock: 90n, + confirmations: 2n, + rpcEndpoints: ['fixture'], + makeClient: () => client, + }), + ).rejects.toThrow(/cursor.*canonical/i); + + expect(cursor.upsert).not.toHaveBeenCalled(); + }); +}); + +describe('runLeaderboardFinalization', () => { + it('keeps legacy mode free of Pulse scan and freshness calls', async () => { + const events: string[] = []; + await runLeaderboardFinalization(BASE_ENV, { + prisma: {} as PrismaClient, + now: NOW, + assertFresh: async () => { + events.push('fresh'); + }, + finalize: async () => { + events.push('finalize'); + }, + }); + + expect(events).toEqual(['finalize']); + }); + + it('runs freshness before finalization when Pulse is enabled', async () => { + const events: string[] = []; + await runLeaderboardFinalization( + { + ...BASE_ENV, + GALAXY_PULSE_START_BLOCK: '1000', + }, + { + prisma: {} as PrismaClient, + now: NOW, + assertFresh: async () => { + events.push('fresh'); + }, + finalize: async () => { + events.push('finalize'); + }, + makeClient: () => makeClient(), + }, + ); + + expect(events).toEqual(['fresh', 'finalize']); + }); + + it('does not finalize when Pulse freshness fails', async () => { + const finalize = vi.fn(); + await expect( + runLeaderboardFinalization( + { + ...BASE_ENV, + GALAXY_PULSE_START_BLOCK: '1000', + }, + { + prisma: {} as PrismaClient, + now: NOW, + assertFresh: async () => { + throw new Error('stale Pulse'); + }, + finalize, + makeClient: () => makeClient(), + }, + ), + ).rejects.toThrow('stale Pulse'); + + expect(finalize).not.toHaveBeenCalled(); + }); +}); diff --git a/server/api/leaderboardWorker.ts b/server/api/leaderboardWorker.ts index cf906db..8c7b559 100644 --- a/server/api/leaderboardWorker.ts +++ b/server/api/leaderboardWorker.ts @@ -1,13 +1,301 @@ +import { + type Address, + createPublicClient, + getAddress, + type Hex, + http, + isHash, + keccak256, + type Log, + type TransactionReceipt, + toBytes, +} from 'viem'; +import { base } from 'viem/chains'; +import { loadBackendPlanetConfig } from './backendConfig.js'; +import { BASE_CHAIN_ID } from './config.js'; +import { BASE_JACKPOT } from './eligibility.js'; import { getPrismaClient } from './database.js'; +import { assertGalaxyPulseFresh } from './galaxyPulseFreshness.js'; +import { + decodeGalaxyPulseSettlementReceipt, + type GalaxyPulseRound, + type GalaxyPulseRoundStore, + persistGalaxyPulseRound, +} from './galaxyPulseIndexer.js'; import { ensureOverdueLeaderboardPeriodsFinalized } from './leaderboardStore.js'; -import { loadBackendPlanetConfig } from './backendConfig.js'; +import { getLogsAdaptive, readWithRpcFallback } from './rpc.js'; + +export const GALAXY_PULSE_JACKPOT_ADDRESS = BASE_JACKPOT; +export const GALAXY_PULSE_CURSOR_STREAM = 'galaxy-pulse-rounds'; + +const JACKPOT_SETTLED_TOPIC = keccak256( + toBytes('JackpotSettled(uint256,uint256,uint256,uint8,uint256,uint256)'), +); + +type GalaxyPulseRpcClient = { + getBlockNumber(): Promise; + getLogs(args: { + address: Address; + topics: readonly Hex[]; + fromBlock: bigint; + toBlock: bigint; + }): Promise; + getTransactionReceipt(args: { hash: Hex }): Promise; + getBlock(args: { blockNumber: bigint }): Promise<{ hash: Hex | null; timestamp: bigint }>; +}; + +type GalaxyPulseCursor = { + nextBlock: bigint; + lastBlockHash: string | null; +}; + +type GalaxyPulsePrisma = { + indexerCursor: { + findUnique(args: unknown): Promise; + upsert(args: unknown): Promise; + }; + galaxyPulseRound: { + findUnique(args: unknown): Promise<{ + drawingId: { toString(): string } | bigint | string; + seed: string; + settlementTxHash: string; + settledAt: Date; + } | null>; + create(args: unknown): Promise<{ + drawingId: { toString(): string } | bigint | string; + seed: string; + settlementTxHash: string; + settledAt: Date; + }>; + }; +}; + +export type GalaxyPulseIngestOptions = { + prisma: import('./generated/prisma/client.js').PrismaClient; + startBlock: bigint; + confirmations: bigint; + rpcEndpoints: readonly string[]; + jackpotAddress?: Address; + makeClient?: (rpcUrl: string) => GalaxyPulseRpcClient; +}; + +export type LeaderboardWorkerDependencies = { + prisma?: import('./generated/prisma/client.js').PrismaClient; + now?: Date; + makeClient?: (rpcUrl: string) => GalaxyPulseRpcClient; + assertFresh?: typeof assertGalaxyPulseFresh; + finalize?: typeof ensureOverdueLeaderboardPeriodsFinalized; +}; + +function asGalaxyPulsePrisma( + prisma: import('./generated/prisma/client.js').PrismaClient, +): GalaxyPulsePrisma { + return prisma as unknown as GalaxyPulsePrisma; +} + +function asRound( + row: Awaited>, +): GalaxyPulseRound { + return { + drawingId: BigInt(row.drawingId.toString()), + seed: row.seed as Hex, + settlementTxHash: row.settlementTxHash as Hex, + settledAt: row.settledAt, + }; +} + +function makeGalaxyPulseRoundStore(prisma: GalaxyPulsePrisma): GalaxyPulseRoundStore { + return { + async findByDrawingId(drawingId) { + const row = await prisma.galaxyPulseRound.findUnique({ + where: { drawingId: drawingId.toString() }, + }); + return row ? asRound(row) : null; + }, + async create(round) { + const row = await prisma.galaxyPulseRound.create({ + data: { + drawingId: round.drawingId.toString(), + seed: round.seed, + settlementTxHash: round.settlementTxHash, + settledAt: round.settledAt, + }, + }); + return asRound(row); + }, + }; +} + +function defaultGalaxyPulseClient(rpcUrl: string): GalaxyPulseRpcClient { + return createPublicClient({ + chain: base, + transport: http(rpcUrl), + }) as unknown as GalaxyPulseRpcClient; +} + +async function ingestGalaxyPulseOnClient( + options: Omit & { + client: GalaxyPulseRpcClient; + jackpotAddress: Address; + }, +): Promise { + if (options.confirmations < 0n) + throw new Error('Galaxy Pulse confirmations must be non-negative.'); + const latestBlock = await options.client.getBlockNumber(); + if (latestBlock < options.confirmations) return; + const toBlock = latestBlock - options.confirmations; + if (options.startBlock > toBlock) return; + const pulsePrisma = asGalaxyPulsePrisma(options.prisma); + const cursor = await pulsePrisma.indexerCursor.findUnique({ + where: { + chainId_contractAddress_stream: { + chainId: BASE_CHAIN_ID, + contractAddress: options.jackpotAddress.toLowerCase(), + stream: GALAXY_PULSE_CURSOR_STREAM, + }, + }, + }); + if (cursor?.lastBlockHash && cursor.nextBlock > options.startBlock) { + const previous = await options.client.getBlock({ blockNumber: cursor.nextBlock - 1n }); + if (!previous.hash || previous.hash.toLowerCase() !== cursor.lastBlockHash.toLowerCase()) { + throw new Error('Galaxy Pulse cursor is no longer canonical.'); + } + } + const fromBlock = + cursor && cursor.nextBlock > options.startBlock ? cursor.nextBlock : options.startBlock; + if (fromBlock > toBlock) return; + + const logs = await getLogsAdaptive({ fromBlock, toBlock }, (rangeFrom, rangeTo) => + options.client.getLogs({ + address: options.jackpotAddress, + topics: [JACKPOT_SETTLED_TOPIC], + fromBlock: rangeFrom, + toBlock: rangeTo, + }), + ); + const orderedLogs = [...logs].sort((left, right) => { + const leftBlock = left.blockNumber ?? 0n; + const rightBlock = right.blockNumber ?? 0n; + return leftBlock === rightBlock + ? Number(left.logIndex) - Number(right.logIndex) + : leftBlock < rightBlock + ? -1 + : 1; + }); + const roundStore = makeGalaxyPulseRoundStore(pulsePrisma); + for (const log of orderedLogs) { + if (getAddress(log.address) !== options.jackpotAddress) { + throw new Error('Galaxy Pulse settlement log was emitted by an unexpected address.'); + } + if ( + log.blockNumber !== undefined && + log.blockNumber !== null && + (log.blockNumber < fromBlock || log.blockNumber > toBlock) + ) { + throw new Error('Galaxy Pulse settlement log is outside the finalized scan range.'); + } + if (!log.transactionHash || !isHash(log.transactionHash)) { + throw new Error('Galaxy Pulse settlement log has no valid transaction hash.'); + } + const receipt = await options.client.getTransactionReceipt({ hash: log.transactionHash }); + if ( + !isHash(receipt.transactionHash) || + receipt.transactionHash.toLowerCase() !== log.transactionHash.toLowerCase() || + typeof receipt.blockNumber !== 'bigint' || + !isHash(receipt.blockHash) + ) { + throw new Error('Galaxy Pulse receipt provenance does not match the settlement log.'); + } + if ( + receipt.blockNumber < fromBlock || + receipt.blockNumber > toBlock || + (log.blockNumber !== undefined && + log.blockNumber !== null && + log.blockNumber !== receipt.blockNumber) || + (log.blockHash !== undefined && + log.blockHash !== null && + (!isHash(log.blockHash) || log.blockHash.toLowerCase() !== receipt.blockHash.toLowerCase())) + ) { + throw new Error('Galaxy Pulse receipt is not finalized at the scan boundary.'); + } + const block = await options.client.getBlock({ blockNumber: receipt.blockNumber }); + if ( + !block.hash || + !isHash(block.hash) || + !isHash(receipt.blockHash) || + block.hash.toLowerCase() !== receipt.blockHash.toLowerCase() + ) { + throw new Error('Galaxy Pulse receipt block is no longer canonical.'); + } + const round = decodeGalaxyPulseSettlementReceipt({ + receipt, + jackpotAddress: options.jackpotAddress, + blockTimestamp: block.timestamp, + }); + await persistGalaxyPulseRound(roundStore, round); + } + + const cursorBlock = await options.client.getBlock({ blockNumber: toBlock }); + if (!cursorBlock.hash || !isHash(cursorBlock.hash)) { + throw new Error('Galaxy Pulse cursor boundary block has no canonical hash.'); + } + await pulsePrisma.indexerCursor.upsert({ + where: { + chainId_contractAddress_stream: { + chainId: BASE_CHAIN_ID, + contractAddress: options.jackpotAddress.toLowerCase(), + stream: GALAXY_PULSE_CURSOR_STREAM, + }, + }, + create: { + chainId: BASE_CHAIN_ID, + contractAddress: options.jackpotAddress.toLowerCase(), + stream: GALAXY_PULSE_CURSOR_STREAM, + nextBlock: toBlock + 1n, + lastBlockHash: cursorBlock.hash, + }, + update: { + nextBlock: toBlock + 1n, + lastBlockHash: cursorBlock.hash, + }, + }); +} + +export async function ingestGalaxyPulseRounds(options: GalaxyPulseIngestOptions): Promise { + const jackpotAddress = getAddress(options.jackpotAddress ?? GALAXY_PULSE_JACKPOT_ADDRESS); + const makeClient = options.makeClient ?? defaultGalaxyPulseClient; + await readWithRpcFallback(options.rpcEndpoints, async (rpcUrl) => + ingestGalaxyPulseOnClient({ + ...options, + client: makeClient(rpcUrl), + jackpotAddress, + }), + ); +} /** Explicit worker entry point for the mutating daily leaderboard finalization. */ export async function runLeaderboardFinalization( env: Record = process.env, + dependencies: LeaderboardWorkerDependencies = {}, ): Promise { const config = loadBackendPlanetConfig(env); - await ensureOverdueLeaderboardPeriodsFinalized(getPrismaClient(config.databaseUrl), new Date(), { + const prisma = dependencies.prisma ?? getPrismaClient(config.databaseUrl); + const now = dependencies.now ?? new Date(); + if (config.galaxyPulseStartBlock != null) { + await ingestGalaxyPulseRounds({ + prisma, + startBlock: config.galaxyPulseStartBlock, + confirmations: config.confirmations, + rpcEndpoints: [config.rpcUrl, ...(config.rpcFallbackUrls ?? [])], + makeClient: dependencies.makeClient, + }); + await (dependencies.assertFresh ?? assertGalaxyPulseFresh)({ + prisma, + galaxyPulseStartBlock: config.galaxyPulseStartBlock, + now, + }); + } + await (dependencies.finalize ?? ensureOverdueLeaderboardPeriodsFinalized)(prisma, now, { mineralEconomyCutoverAt: config.mineralEconomyCutoverAt, }); } diff --git a/server/api/mineralAccounts.test.ts b/server/api/mineralAccounts.test.ts index c983dec..3c95472 100644 --- a/server/api/mineralAccounts.test.ts +++ b/server/api/mineralAccounts.test.ts @@ -33,6 +33,27 @@ describe('MineralAccount initialization', () => { })).toBe(1_000_100n); }); + it('uses Galaxy Pulse boundaries for the current wallet balance', () => { + expect(calculateCurrentMineralBalanceMicros({ + account: { balanceMicros: 0n, lastSettledAt: CUTOVER }, + openingBalanceMicros: 0n, + cutoverAt: CUTOVER, + asOf: new Date('2026-08-22T00:00:00.000Z'), + planets: [{ + id: 'pulse-wallet', + ownerAddress: OWNER, + planetType: 'Gaia', + baseMineralsPerDay: 1n, + generatedAt: CUTOVER, + }], + purchases: [], + pulseRounds: [{ + settledAt: new Date('2026-08-21T00:00:00.000Z'), + modifiersBps: { gaia: 5_000 }, + }], + })).toBe(2_500_000n); + }); + it('rejects a missing account when spending history exists', () => { expect(() => calculateCurrentMineralBalanceMicros({ account: null, diff --git a/server/api/mineralAccounts.ts b/server/api/mineralAccounts.ts index 87f0265..c7cae3d 100644 --- a/server/api/mineralAccounts.ts +++ b/server/api/mineralAccounts.ts @@ -1,9 +1,11 @@ import { type CollectionMiningPlanet, calculateCollectionMining } from './collectionMining.js'; import { calculateHistoricalProduction, + type GalaxyPulseMiningRound, type MineralCollectionPlanet, type MineralUpgradePurchase, } from './mineralEconomy.js'; +import { loadGalaxyPulseRounds } from './galaxyPulseStore.js'; import { calculateUpgradeCostMicros, getMineralUpgradeConfig } from './mineralUpgrades.js'; import { Prisma, type PrismaClient } from './generated/prisma/client.js'; @@ -229,6 +231,7 @@ export function calculateCurrentMineralBalanceMicros(input: { asOf: Date; planets: readonly MineralCollectionPlanet[]; purchases: readonly MineralUpgradePurchase[]; + pulseRounds?: readonly GalaxyPulseMiningRound[]; }): bigint { assertCutover(input.cutoverAt); assertTimestamp(input.asOf, 'Current balance'); @@ -249,6 +252,7 @@ export function calculateCurrentMineralBalanceMicros(input: { from, to: input.asOf, anchor: input.cutoverAt, + pulseRounds: input.pulseRounds, }); const balanceMicros = (input.account?.balanceMicros ?? input.openingBalanceMicros) + producedMicros; if (balanceMicros < 0n) throw new Error('Mineral balance cannot be negative.'); @@ -465,6 +469,7 @@ export async function settleMineralAccount(input: { }; planets: readonly MineralSettlementPlanet[]; purchases: readonly MineralSettlementPurchase[]; + pulseRounds?: readonly GalaxyPulseMiningRound[]; settledAt: Date; anchor: Date; }) { @@ -473,12 +478,16 @@ export async function settleMineralAccount(input: { if (input.settledAt < input.account.lastSettledAt) { throw new Error('Settlement timestamp cannot move backwards.'); } + const pulseRounds = input.pulseRounds ?? (input.prisma.galaxyPulseRound + ? await loadGalaxyPulseRounds(input.prisma, input.settledAt) + : []); const producedMicros = calculateHistoricalProduction({ planets: input.planets, purchases: input.purchases, from: input.account.lastSettledAt, to: input.settledAt, anchor: input.anchor, + pulseRounds, }); if (producedMicros === 0n && input.settledAt.getTime() === input.account.lastSettledAt.getTime()) { return { ...input.account, balanceMicros: input.account.balanceMicros }; diff --git a/server/api/mineralConcurrency.postgres.test.ts b/server/api/mineralConcurrency.postgres.test.ts deleted file mode 100644 index dad3099..0000000 --- a/server/api/mineralConcurrency.postgres.test.ts +++ /dev/null @@ -1,685 +0,0 @@ -import { PrismaPg } from '@prisma/adapter-pg'; -import { Hono } from 'hono'; -import { createSiweMessage } from 'viem/siwe'; -import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { PrismaBackendPlanetStore } from './backendPlanet.js'; -import { MEGASTERA_SOURCE } from './config.js'; -import { Prisma, PrismaClient } from './generated/prisma/client.js'; -import { finalizeLeaderboardPeriod } from './leaderboardStore.js'; -import { calculateHistoricalProduction } from './mineralEconomy.js'; -import { getBackendWalletMiningSnapshot } from './miningStore.js'; -import { - acquireMineralEconomyExclusiveBarrier, - acquireMineralEconomySharedBarrier, - acquireMineralWalletLock, - purchasePlanetUpgrade, - resolveMineralEconomyCutover, - runMineralAccountsBackfill, -} from './mineralAccounts.js'; -import { createSiweAuthRoutes } from './siweAuth.js'; - -const testDatabaseUrl = process.env.MINERAL_ECONOMY_TEST_DATABASE_URL?.trim(); -if (!testDatabaseUrl && process.env.MINERAL_ECONOMY_REQUIRE_POSTGRES === '1') { - throw new Error( - 'MINERAL_ECONOMY_TEST_DATABASE_URL is required for the PostgreSQL concurrency suite.', - ); -} -const describePostgres = testDatabaseUrl ? describe : describe.skip; -const OWNER = '0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; -const OTHER_OWNER = '0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; -let nextFixtureId = 99_001; - -function createClient() { - if (!testDatabaseUrl) - throw new Error('The explicit mineral economy test database is not configured.'); - return new PrismaClient({ - adapter: new PrismaPg({ connectionString: testDatabaseUrl, max: 1 }), - }); -} - -async function postgresNow(prisma: PrismaClient): Promise { - const rows = await prisma.$queryRaw>( - Prisma.sql`SELECT clock_timestamp()::timestamptz(3) AS "now"`, - ); - const value = rows[0]?.now; - if (!(value instanceof Date) || !Number.isFinite(value.getTime())) - throw new Error('PostgreSQL time is invalid.'); - return value; -} - -function utcMidnightBefore(value: Date): Date { - return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate() - 1)); -} - -function utcMidnightAfter(value: Date): Date { - return new Date(Date.UTC(value.getUTCFullYear(), value.getUTCMonth(), value.getUTCDate() + 1)); -} - -function repeatedHex(value: number): `0x${string}` { - const byte = (value % 256).toString(16).padStart(2, '0'); - return `0x${byte.repeat(32)}` as `0x${string}`; -} - -async function createTicket(prisma: PrismaClient, ownerAddress: string, purchasedAt: Date) { - const fixtureId = nextFixtureId++; - const ticket = await prisma.ticketPurchase.create({ - data: { - chainId: 8453, - jackpotAddress: `0x${'11'.repeat(20)}`, - ticketId: fixtureId.toString(), - drawingId: fixtureId.toString(), - recipient: ownerAddress, - normals: [1, 2, 3, 4, 5], - bonusBall: 6, - source: MEGASTERA_SOURCE.padEnd(66, '0'), - originTxHash: repeatedHex(fixtureId), - blockNumber: BigInt(30_000_000 + fixtureId), - blockHash: repeatedHex(fixtureId + 1), - logIndex: fixtureId, - purchasedAt, - }, - }); - return { ticket, fixtureId }; -} - -async function createFixture( - prisma: PrismaClient, - ownerAddress: string, - generatedAt: Date, - baseMineralsPerDay = 1n, -) { - const { ticket, fixtureId } = await createTicket(prisma, ownerAddress, generatedAt); - const planet = await prisma.backendPlanet.create({ - data: { - ticketPurchaseId: ticket.id, - chainId: 8453, - ticketId: fixtureId.toString(), - ownerAddress, - seed: repeatedHex(fixtureId + 2), - traitsHash: repeatedHex(fixtureId + 3), - generatorVersion: 1, - planetName: `Concurrency Planet ${fixtureId}`, - planetType: 'Gaia', - terrain: 'Plains', - rarity: 'Common', - satelliteCount: 0, - hasRing: false, - baseMineralsPerDay, - generatedAt, - status: 'READY', - gifData: Buffer.from('gif'), - gifHash: repeatedHex(fixtureId + 4), - }, - }); - return { ticket, planet, fixtureId }; -} - -async function seedAccount(prisma: PrismaClient, ownerAddress: string, lastSettledAt: Date) { - return prisma.mineralAccount.create({ - data: { - ownerAddress, - openingBalanceMicros: 10_000_000n, - balanceMicros: 10_000_000n, - lastSettledAt, - }, - }); -} - -function proofForTicket( - ticket: Awaited>['ticket'], - ownerAddress: string, -) { - return { - chainId: 8453, - recipient: ownerAddress as `0x${string}`, - ticketId: BigInt(ticket.ticketId.toString()), - drawingId: BigInt(ticket.drawingId.toString()), - normals: ticket.normals, - bonusBall: ticket.bonusBall, - originTxHash: ticket.originTxHash as `0x${string}`, - blockNumber: ticket.blockNumber, - blockHash: ticket.blockHash as `0x${string}`, - logIndex: BigInt(ticket.logIndex), - purchasedAt: ticket.purchasedAt, - } as const; -} - -async function clearTestDatabase(prisma: PrismaClient): Promise { - await prisma.siweNonce.deleteMany(); - await prisma.leaderboardEntry.deleteMany(); - await prisma.leaderboardPeriod.deleteMany(); - // Upgrade history is immutable in production; TRUNCATE keeps test cleanup read/write-safe without firing delete triggers. - await prisma.$executeRaw(Prisma.sql`TRUNCATE TABLE "planet_upgrade_purchases", "mineral_economy_cutover"`); - await prisma.mineralAccount.deleteMany(); - await prisma.backendPlanet.deleteMany(); - await prisma.ticketPurchase.deleteMany(); -} - -async function ensurePersistedCutover(prisma: PrismaClient, cutoverAt: Date): Promise { - const existing = await prisma.mineralEconomyCutover.findUnique({ where: { id: 1 } }); - if (!existing) { - await prisma.mineralEconomyCutover.create({ data: { id: 1, cutoverAt } }); - return cutoverAt; - } - return existing.cutoverAt; -} - -describePostgres('Mineral upgrade PostgreSQL concurrency', () => { - let first: PrismaClient; - let second: PrismaClient; - let blocker: PrismaClient; - - beforeAll(() => { - first = createClient(); - second = createClient(); - blocker = createClient(); - }); - - beforeEach(async () => { - await clearTestDatabase(first); - }); - - afterAll(async () => { - await Promise.all([first.$disconnect(), second.$disconnect(), blocker.$disconnect()]); - }); - - it('fails a configured but unpersisted cutover after PostgreSQL reaches T', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = utcMidnightBefore(databaseNow); - - await expect( - getBackendWalletMiningSnapshot(first, OWNER, databaseNow, { - mineralEconomyCutoverAt: cutoverAt, - }), - ).rejects.toThrow('configured mineral economy cutover is not persisted'); - }); - - it('enforces immutable history/account identity while allowing READY Planet upgrades and media repair', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const fixture = await createFixture(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - const purchase = await first.planetUpgradePurchase.create({ - data: { - planetId: fixture.planet.id, - walletAddress: OWNER, - targetLevel: 1, - bonusBpsAfter: 1_000, - costMicros: 200_000n, - purchasedAt: databaseNow, - }, - }); - - await expect( - first.planetUpgradePurchase.update({ where: { id: purchase.id }, data: { costMicros: 1n } }), - ).rejects.toThrow('immutable'); - await expect(first.planetUpgradePurchase.delete({ where: { id: purchase.id } })).rejects.toThrow('immutable'); - await expect( - first.mineralAccount.update({ where: { ownerAddress: OWNER }, data: { openingBalanceMicros: 1n } }), - ).rejects.toThrow('immutable'); - await expect( - first.backendPlanet.update({ where: { id: fixture.planet.id }, data: { baseMineralsPerDay: 2n } }), - ).rejects.toThrow('immutable'); - await expect( - first.backendPlanet.update({ - where: { id: fixture.planet.id }, - data: { upgradeLevel: 1, upgradeBonusBps: 1_000, gifData: Buffer.from('repaired') }, - }), - ).resolves.toBeTruthy(); - }); - - it('persists a pre-cutover generation without creating a V2 account', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = utcMidnightAfter(databaseNow); - const ticket = await createTicket(first, OWNER, databaseNow); - - const generated = await new PrismaBackendPlanetStore( - first, - () => databaseNow, - cutoverAt, - ).generatePlanet(proofForTicket(ticket.ticket, OWNER)); - - expect(new Date(generated.generatedAt).getTime()).toBeLessThan(cutoverAt.getTime()); - expect(await first.backendPlanet.count({ where: { ticketPurchaseId: ticket.ticket.id } })).toBe( - 1, - ); - expect(await first.mineralAccount.findUnique({ where: { ownerAddress: OWNER } })).toBeNull(); - expect(await first.mineralEconomyCutover.findUnique({ where: { id: 1 } })).toBeNull(); - }); - - it('charges one concurrent upgrade exactly once', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const fixture = await createFixture(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - - try { - let releaseLock!: () => void; - const releasePromise = new Promise((resolve) => { - releaseLock = resolve; - }); - let lockHeld!: () => void; - const lockHeldPromise = new Promise((resolve) => { - lockHeld = resolve; - }); - const blockerTransaction = blocker.$transaction(async (transaction) => { - await transaction.$queryRaw( - Prisma.sql`SELECT "id" FROM "mineral_accounts" WHERE "ownerAddress" = ${OWNER} FOR UPDATE`, - ); - lockHeld(); - await releasePromise; - }); - await lockHeldPromise; - - let completed = 0; - const firstUpgrade = purchasePlanetUpgrade(first, { - authenticatedWalletAddress: OWNER, - planetId: fixture.planet.id, - targetLevel: 1, - cutoverAt, - }).then((result) => { - completed += 1; - return result; - }); - const secondUpgrade = purchasePlanetUpgrade(second, { - authenticatedWalletAddress: OWNER, - planetId: fixture.planet.id, - targetLevel: 1, - cutoverAt, - }).then((result) => { - completed += 1; - return result; - }); - await new Promise((resolve) => setImmediate(resolve)); - expect(completed).toBe(0); - releaseLock(); - await blockerTransaction; - - const results = await Promise.all([firstUpgrade, secondUpgrade]); - - expect(results[0]?.targetLevel).toBe(1); - expect(results[1]?.targetLevel).toBe(1); - expect( - await first.planetUpgradePurchase.count({ - where: { planetId: fixture.planet.id, targetLevel: 1 }, - }), - ).toBe(1); - const balance = (await first.mineralAccount.findUnique({ where: { ownerAddress: OWNER } })) - ?.balanceMicros; - expect(balance).toBeGreaterThanOrEqual(9_800_000n); - expect(balance).toBeLessThan(10_000_000n); - } finally { - await clearTestDatabase(first); - } - }); - - it('rolls back every economic write when the authenticated wallet is not the locked Planet owner', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const fixture = await createFixture(first, OWNER, cutoverAt); - const account = await seedAccount(first, OTHER_OWNER, databaseNow); - - await expect(purchasePlanetUpgrade(first, { - authenticatedWalletAddress: OTHER_OWNER, - planetId: fixture.planet.id, - targetLevel: 1, - cutoverAt, - })).rejects.toThrow('Authenticated wallet does not own this Planet'); - - expect((await first.mineralAccount.findUnique({ where: { ownerAddress: OTHER_OWNER } }))?.balanceMicros) - .toBe(account.balanceMicros); - expect((await first.backendPlanet.findUnique({ where: { id: fixture.planet.id } }))?.upgradeLevel) - .toBe(0); - expect(await first.planetUpgradePurchase.count({ where: { planetId: fixture.planet.id } })) - .toBe(0); - }); - - it('lets only one of two parallel SIWE verify requests create a session', async () => { - const origin = 'https://megastera.example'; - const databaseNow = await postgresNow(first); - const nonce = 'c'.repeat(96); - let arrivals = 0; - let release!: () => void; - const bothVerified = new Promise((resolve) => { - release = resolve; - }); - const app = new Hono(); - app.route('/api/auth/siwe', createSiweAuthRoutes({ - generateNonce: () => nonce, - getPrisma: () => first, - loadConfig: () => ({ - chainId: 8453, - confirmations: 6n, - databaseUrl: testDatabaseUrl ?? '', - mineralUpgradesEnabled: true, - rpcUrl: 'https://rpc.example.test', - siweOrigin: origin, - siweSessionSecret: 's'.repeat(32), - }), - now: () => databaseNow, - verifySignature: async () => { - arrivals += 1; - if (arrivals === 2) release(); - await bothVerified; - return true; - }, - })); - const challengeResponse = await app.request(`${origin}/api/auth/siwe/nonce`, { - method: 'POST', - headers: { 'content-type': 'application/json', origin }, - body: JSON.stringify({ address: OWNER }), - }); - const challenge = await challengeResponse.json() as { - address: `0x${string}`; - chainId: number; - domain: string; - expirationTime: string; - issuedAt: string; - nonce: string; - scheme: string; - uri: string; - version: '1'; - }; - const message = createSiweMessage({ - ...challenge, - expirationTime: new Date(challenge.expirationTime), - issuedAt: new Date(challenge.issuedAt), - }); - const verify = () => app.request(`${origin}/api/auth/siwe/verify`, { - method: 'POST', - headers: { 'content-type': 'application/json', origin }, - body: JSON.stringify({ message, signature: '0x12' }), - }); - - const responses = await Promise.all([verify(), verify()]); - - expect(responses.map((response) => response.status).sort()).toEqual([204, 401]); - expect(responses.filter((response) => response.headers.has('set-cookie'))).toHaveLength(1); - expect(await first.siweNonce.count({ where: { nonce } })).toBe(0); - }); - - it('serializes different Planet upgrades for one wallet', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const firstFixture = await createFixture(first, OWNER, cutoverAt); - const secondFixture = await createFixture(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - - const [firstPurchase, secondPurchase] = await Promise.all([ - purchasePlanetUpgrade(first, { - authenticatedWalletAddress: OWNER, - planetId: firstFixture.planet.id, - targetLevel: 1, - cutoverAt, - }), - purchasePlanetUpgrade(second, { - authenticatedWalletAddress: OWNER, - planetId: secondFixture.planet.id, - targetLevel: 1, - cutoverAt, - }), - ]); - - expect(firstPurchase.targetLevel).toBe(1); - expect(secondPurchase.targetLevel).toBe(1); - expect(await first.planetUpgradePurchase.count({ where: { walletAddress: OWNER } })).toBe(2); - const balance = (await first.mineralAccount.findUnique({ where: { ownerAddress: OWNER } })) - ?.balanceMicros; - expect(balance).toBeGreaterThanOrEqual(9_600_000n); - expect(balance).toBeLessThan(10_000_000n); - }); - - it('orders generation and upgrade through the shared economy barrier', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const existing = await createFixture(first, OWNER, cutoverAt); - const generationTicket = await createTicket(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - - const generation = new PrismaBackendPlanetStore( - second, - () => databaseNow, - cutoverAt, - ).generatePlanet(proofForTicket(generationTicket.ticket, OWNER)); - const upgrade = purchasePlanetUpgrade(first, { - authenticatedWalletAddress: OWNER, - planetId: existing.planet.id, - targetLevel: 1, - cutoverAt, - }); - const [generated, purchase] = await Promise.all([generation, upgrade]); - - expect(generated.status).toBe('READY'); - expect(purchase.targetLevel).toBe(1); - expect( - await first.backendPlanet.count({ where: { ownerAddress: OWNER, status: 'READY' } }), - ).toBe(2); - expect(await first.planetUpgradePurchase.count({ where: { walletAddress: OWNER } })).toBe(1); - }); - - it('serializes two concurrent generations for one wallet', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const firstTicket = await createTicket(first, OWNER, cutoverAt); - const secondTicket = await createTicket(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - - const [firstPlanet, secondPlanet] = await Promise.all([ - new PrismaBackendPlanetStore(first, () => databaseNow, cutoverAt).generatePlanet( - proofForTicket(firstTicket.ticket, OWNER), - ), - new PrismaBackendPlanetStore(second, () => databaseNow, cutoverAt).generatePlanet( - proofForTicket(secondTicket.ticket, OWNER), - ), - ]); - - expect(firstPlanet.status).toBe('READY'); - expect(secondPlanet.status).toBe('READY'); - expect( - await first.backendPlanet.count({ where: { ownerAddress: OWNER, status: 'READY' } }), - ).toBe(2); - expect(await first.mineralAccount.count({ where: { ownerAddress: OWNER } })).toBe(1); - const account = await first.mineralAccount.findUnique({ where: { ownerAddress: OWNER } }); - const planets = await first.backendPlanet.findMany({ - where: { ownerAddress: OWNER, status: 'READY' }, - select: { - id: true, - ownerAddress: true, - planetType: true, - baseMineralsPerDay: true, - generatedAt: true, - }, - }); - expect(account?.balanceMicros).toBe( - 10_000_000n + calculateHistoricalProduction({ - planets, - purchases: [], - from: databaseNow, - to: account?.lastSettledAt ?? databaseNow, - anchor: cutoverAt, - }), - ); - }); - - it('timestamps generation after waiting on the wallet lock', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const ticket = await createTicket(first, OWNER, databaseNow); - await seedAccount(first, OWNER, databaseNow); - - let releaseWallet!: () => void; - const release = new Promise((resolve) => { - releaseWallet = resolve; - }); - let walletHeld!: () => void; - const held = new Promise((resolve) => { - walletHeld = resolve; - }); - const blockerTransaction = blocker.$transaction(async (transaction) => { - await acquireMineralEconomySharedBarrier(transaction); - await acquireMineralWalletLock(transaction, OWNER); - walletHeld(); - await release; - }); - await held; - - let completed = false; - const generation = new PrismaBackendPlanetStore( - second, - () => databaseNow, - cutoverAt, - ).generatePlanet(proofForTicket(ticket.ticket, OWNER)).then((result) => { - completed = true; - return result; - }); - await new Promise((resolve) => setImmediate(resolve)); - expect(completed).toBe(false); - const releasedAt = await postgresNow(first); - releaseWallet(); - await Promise.all([blockerTransaction, generation]); - - const generated = await first.backendPlanet.findUnique({ - where: { ticketPurchaseId: ticket.ticket.id }, - }); - expect(generated?.generatedAt.getTime()).toBeGreaterThanOrEqual(releasedAt.getTime()); - const account = await first.mineralAccount.findUnique({ where: { ownerAddress: OWNER } }); - const planets = await first.backendPlanet.findMany({ - where: { ownerAddress: OWNER, status: 'READY' }, - select: { - id: true, - ownerAddress: true, - planetType: true, - baseMineralsPerDay: true, - generatedAt: true, - }, - }); - expect(account?.balanceMicros).toBe( - 10_000_000n + calculateHistoricalProduction({ - planets, - purchases: [], - from: databaseNow, - to: account?.lastSettledAt ?? databaseNow, - anchor: cutoverAt, - }), - ); - }); - - it('keeps backfill and in-flight generation ordered by the economy barrier', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = await ensurePersistedCutover(first, utcMidnightBefore(databaseNow)); - const ticket = await createTicket(first, OWNER, cutoverAt); - - let releaseBarrier!: () => void; - const release = new Promise((resolve) => { - releaseBarrier = resolve; - }); - let barrierHeld!: () => void; - const held = new Promise((resolve) => { - barrierHeld = resolve; - }); - const blockerTransaction = blocker.$transaction(async (transaction) => { - await acquireMineralEconomyExclusiveBarrier(transaction); - barrierHeld(); - await release; - }); - await held; - - const generation = new PrismaBackendPlanetStore( - second, - () => databaseNow, - cutoverAt, - ).generatePlanet(proofForTicket(ticket.ticket, OWNER)); - const backfill = runMineralAccountsBackfill(first, cutoverAt); - releaseBarrier(); - await Promise.all([blockerTransaction, generation, backfill]); - - expect( - await first.backendPlanet.count({ where: { ownerAddress: OWNER, status: 'READY' } }), - ).toBe(1); - expect(await first.mineralAccount.count({ where: { ownerAddress: OWNER } })).toBe(1); - }); - - it('lets finalization drain a late pre-boundary mutation before its snapshot', async () => { - const databaseNow = await postgresNow(first); - const cutoverAt = utcMidnightBefore(databaseNow); - const fixture = await createFixture(first, OWNER, cutoverAt); - await seedAccount(first, OWNER, databaseNow); - const persistedCutoverAt = await ensurePersistedCutover(first, cutoverAt); - const period = { - id: persistedCutoverAt.toISOString().slice(0, 10), - startsAt: persistedCutoverAt, - endsAt: new Date(persistedCutoverAt.getTime() + 86_400_000), - }; - - let releaseMutation!: () => void; - const release = new Promise((resolve) => { - releaseMutation = resolve; - }); - let mutationHeld!: () => void; - const held = new Promise((resolve) => { - mutationHeld = resolve; - }); - const mutation = first.$transaction(async (transaction) => { - await acquireMineralEconomySharedBarrier(transaction); - mutationHeld(); - await release; - await transaction.planetUpgradePurchase.create({ - data: { - planetId: fixture.planet.id, - walletAddress: OWNER, - targetLevel: 1, - bonusBpsAfter: 1_000, - costMicros: 200_000n, - purchasedAt: new Date(period.endsAt.getTime() - 1), - }, - }); - }); - await held; - let finalized = false; - const finalization = finalizeLeaderboardPeriod(second, period, databaseNow, { - mineralEconomyCutoverAt: persistedCutoverAt, - }).then((result) => { - finalized = true; - return result; - }); - await new Promise((resolve) => setImmediate(resolve)); - expect(finalized).toBe(false); - releaseMutation(); - await Promise.all([mutation, finalization]); - - expect( - await first.planetUpgradePurchase.count({ where: { planetId: fixture.planet.id } }), - ).toBe(1); - expect( - (await first.leaderboardPeriod.findUnique({ where: { id: period.id } }))?.finalizedAt, - ).not.toBeNull(); - const archived = await first.leaderboardEntry.findUnique({ - where: { periodId_walletAddress: { periodId: period.id, walletAddress: OWNER } }, - }); - expect(archived?.scoreMicros).toBe(10_800_000n); - }); - - it('uses a persisted cutover when configuration is missing', async () => { - const cutoverAt = await ensurePersistedCutover( - first, - utcMidnightBefore(await postgresNow(first)), - ); - - await expect(resolveMineralEconomyCutover(first, null)).resolves.toEqual({ - state: 'V2', - cutoverAt, - source: 'database', - }); - }); - - it('fails closed when configured and persisted cutovers conflict', async () => { - const persistedCutoverAt = await ensurePersistedCutover( - first, - utcMidnightBefore(await postgresNow(first)), - ); - - await expect( - resolveMineralEconomyCutover(first, new Date(persistedCutoverAt.getTime() - 86_400_000)), - ).rejects.toThrow('conflicts with the persisted database cutover'); - }); -}); diff --git a/server/api/mineralEconomy.test.ts b/server/api/mineralEconomy.test.ts index e070ef8..9b3d9e7 100644 --- a/server/api/mineralEconomy.test.ts +++ b/server/api/mineralEconomy.test.ts @@ -145,6 +145,74 @@ describe('Minerals Economy v2 temporal calculations', () => { expect(first + second).toBe(whole); }); + it('uses the Pulse active in each half-open historical interval', () => { + const planet: MineralCollectionPlanet = { + id: 'pulse-boundaries', + ownerAddress: '0xabc', + planetType: 'Gaia', + baseMineralsPerDay: 1n, + activatedAt: ANCHOR, + }; + + expect(calculateHistoricalPlanetProduction({ + planet, + planets: [planet], + purchases: [], + pulseRounds: [ + { settledAt: new Date('2026-08-11T00:00:00.000Z'), modifiersBps: { gaia: 5_000 } }, + { settledAt: new Date('2026-08-12T00:00:00.000Z'), modifiersBps: { gaia: -2_500 } }, + ], + from: ANCHOR, + to: new Date('2026-08-13T00:00:00.000Z'), + anchor: ANCHOR, + })).toBe(3_250_000n); + }); + + it('adds collection, permanent upgrade, and Pulse BPS in one rate calculation', () => { + const planets: MineralCollectionPlanet[] = ['one', 'two', 'three'].map((id) => ({ + id, + ownerAddress: '0xabc', + planetType: 'Gaia', + baseMineralsPerDay: 1n, + activatedAt: ANCHOR, + })); + + expect(calculateHistoricalPlanetProduction({ + planet: planets[0] as MineralCollectionPlanet, + planets, + purchases: [{ + planetId: 'one', + targetLevel: 1, + bonusBpsAfter: 1_000, + purchasedAt: ANCHOR, + }], + pulseRounds: [{ settledAt: ANCHOR, modifiersBps: { gaia: 2_000 } }], + from: ANCHOR, + to: new Date('2026-08-11T00:00:00.000Z'), + anchor: ANCHOR, + })).toBe(1_350_000n); + }); + + it('clamps stacked Pulse debuffs so production cannot become negative', () => { + const planet: MineralCollectionPlanet = { + id: 'pulse-clamp', + ownerAddress: '0xabc', + planetType: 'Gaia', + baseMineralsPerDay: 1n, + activatedAt: ANCHOR, + }; + + expect(calculateHistoricalPlanetProduction({ + planet, + planets: [planet], + purchases: [], + pulseRounds: [{ settledAt: ANCHOR, modifiersBps: { gaia: -15_000 } }], + from: ANCHOR, + to: new Date('2026-08-11T00:00:00.000Z'), + anchor: ANCHOR, + })).toBe(0n); + }); + it('activates collection bonuses at the historical third activation', () => { const planets: MineralCollectionPlanet[] = [ { diff --git a/server/api/mineralEconomy.ts b/server/api/mineralEconomy.ts index 32d90f2..b31cc7e 100644 --- a/server/api/mineralEconomy.ts +++ b/server/api/mineralEconomy.ts @@ -27,6 +27,11 @@ export type MineralUpgradePurchase = { purchasedAt: Date; }; +export type GalaxyPulseMiningRound = { + settledAt: Date; + modifiersBps: Readonly>; +}; + function activationAt(planet: MineralCollectionPlanet): Date { const value = planet.activatedAt ?? planet.generatedAt; if (!value) throw new Error(`Planet ${planet.id} activation timestamp is missing.`); @@ -220,11 +225,31 @@ export function upgradeBonusBpsAt( return bonusBps; } +export function galaxyPulseBpsAt( + rounds: readonly GalaxyPulseMiningRound[], + planetType: string, + atMilliseconds: number, +): number { + let active: GalaxyPulseMiningRound | undefined; + let activeAt = Number.NEGATIVE_INFINITY; + for (const round of rounds) { + const settledAt = timestamp(round.settledAt, 'Galaxy Pulse settlement'); + if (settledAt <= atMilliseconds && settledAt >= activeAt) { + active = round; + activeAt = settledAt; + } + } + const modifierBps = active?.modifiersBps[planetType.toLowerCase()] ?? 0; + if (!Number.isInteger(modifierBps)) throw new Error('Galaxy Pulse modifier must be an integer.'); + return modifierBps; +} + /** Calculates historical production with collection and upgrade events over [from, to). */ export function calculateHistoricalPlanetProduction(input: { planet: MineralCollectionPlanet; planets: readonly MineralCollectionPlanet[]; purchases: readonly MineralUpgradePurchase[]; + pulseRounds?: readonly GalaxyPulseMiningRound[]; from: Date; to: Date; anchor: Date; @@ -251,19 +276,24 @@ export function calculateHistoricalPlanetProduction(input: { eventTimes.add(purchaseTime); } } + for (const pulse of input.pulseRounds ?? []) { + const pulseTime = timestamp(pulse.settledAt, 'Galaxy Pulse settlement'); + if (pulseTime > startMilliseconds && pulseTime < toMilliseconds) eventTimes.add(pulseTime); + } const orderedEvents = [...eventTimes].sort((left, right) => left - right); let cursor = new Date(startMilliseconds); let activeCount = group.filter((candidate) => activationAt(candidate).getTime() <= startMilliseconds).length; let activeBonusBps = collectionBonusBpsForCount(activeCount); let activeUpgradeBonusBps = upgradeBonusBpsAt(input.purchases, input.planet.id, startMilliseconds); + let activePulseBps = galaxyPulseBpsAt(input.pulseRounds ?? [], input.planet.planetType, startMilliseconds); let total = 0n; for (const eventTime of orderedEvents) { total += calculateConstantRateSegment({ rateMicrosPerDay: calculateEffectiveMineralsPerDayMicros( input.planet.baseMineralsPerDay, - activeBonusBps + activeUpgradeBonusBps, + activeBonusBps + activeUpgradeBonusBps + activePulseBps, ), from: cursor, to: new Date(eventTime), @@ -273,13 +303,14 @@ export function calculateHistoricalPlanetProduction(input: { activeCount += eventActivations; activeBonusBps = collectionBonusBpsForCount(activeCount); activeUpgradeBonusBps = upgradeBonusBpsAt(input.purchases, input.planet.id, eventTime); + activePulseBps = galaxyPulseBpsAt(input.pulseRounds ?? [], input.planet.planetType, eventTime); cursor = new Date(eventTime); } total += calculateConstantRateSegment({ rateMicrosPerDay: calculateEffectiveMineralsPerDayMicros( input.planet.baseMineralsPerDay, - activeBonusBps + activeUpgradeBonusBps, + activeBonusBps + activeUpgradeBonusBps + activePulseBps, ), from: cursor, to: input.to, @@ -292,6 +323,7 @@ export function calculateHistoricalPlanetProduction(input: { export function calculateHistoricalProduction(input: { planets: readonly MineralCollectionPlanet[]; purchases: readonly MineralUpgradePurchase[]; + pulseRounds?: readonly GalaxyPulseMiningRound[]; from: Date; to: Date; anchor: Date; diff --git a/server/api/mineralMutations.test.ts b/server/api/mineralMutations.test.ts index a09754c..9f53580 100644 --- a/server/api/mineralMutations.test.ts +++ b/server/api/mineralMutations.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it, vi } from 'vitest'; import type { PrismaClient } from './generated/prisma/client.js'; +import { calculateEffectiveMineralsPerDayMicros } from './collectionMining.js'; +import { BASE_CHAIN_ID } from './config.js'; +import { BASE_JACKPOT } from './eligibility.js'; +import { aggregateGalaxyPulseByType, deriveGalaxyPulseV1 } from './galaxyPulse.js'; import { purchasePlanetUpgrade, settleMineralAccount } from './mineralAccounts.js'; const OWNER = '0x1111111111111111111111111111111111111111'; @@ -24,6 +28,7 @@ function makePrisma(overrides: { account?: Record; existingPurchase?: Record | null; clockAt?: Date; + pulseRows?: Array<{ drawingId: bigint; seed: `0x${string}`; settledAt: Date }>; } = {}) { const planet = makePlanet(); const balanceMicros = typeof overrides.account?.balanceMicros === 'bigint' ? overrides.account.balanceMicros : 500_000n; @@ -85,6 +90,7 @@ function makePrisma(overrides: { findMany: vi.fn().mockResolvedValue([]), create: vi.fn().mockImplementation(({ data }: { data: Record }) => ({ id: 'purchase-1', ...data })), }, + galaxyPulseRound: { findMany: vi.fn().mockResolvedValue(overrides.pulseRows ?? []) }, }; return { prisma: { @@ -98,6 +104,33 @@ function makePrisma(overrides: { } describe('mineral upgrade mutations', () => { + it('loads authoritative Pulse rounds before fixing an account balance', async () => { + const pulse = { + drawingId: 150n, + seed: `0x${'33'.repeat(32)}` as const, + settledAt: CUTOVER, + }; + const fixture = makePrisma({ account: { balanceMicros: 0n }, pulseRows: [pulse] }); + const pulseBps = aggregateGalaxyPulseByType(deriveGalaxyPulseV1({ + drawingId: pulse.drawingId, + seed: pulse.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + })).get('gaia') ?? 0; + + const settled = await settleMineralAccount({ + prisma: fixture.tx as never, + account: fixture.account, + planets: [makePlanet()], + purchases: [], + settledAt: PURCHASED_AT, + anchor: CUTOVER, + }); + + expect(settled.balanceMicros).toBe(calculateEffectiveMineralsPerDayMicros(1n, pulseBps)); + expect(fixture.tx.galaxyPulseRound.findMany).toHaveBeenCalledOnce(); + }); + it('keeps split account settlement equal to one continuous anchored settlement', async () => { const fixture = makePrisma({ account: { balanceMicros: 0n } }); const firstAt = new Date('2026-08-20T12:34:56.789Z'); diff --git a/server/api/miningStore.test.ts b/server/api/miningStore.test.ts index 28a16ea..d4b1800 100644 --- a/server/api/miningStore.test.ts +++ b/server/api/miningStore.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it, vi } from 'vitest'; import type { PrismaClient } from './generated/prisma/client.js'; +import { aggregateGalaxyPulseByType, deriveGalaxyPulseV1 } from './galaxyPulse.js'; +import { BASE_CHAIN_ID } from './config.js'; +import { BASE_JACKPOT } from './eligibility.js'; import { getBackendWalletMiningSnapshot } from './miningStore.js'; import { getCurrentLeaderboard } from './leaderboardStore.js'; @@ -53,11 +56,24 @@ describe('backend Planet mining snapshots', () => { balanceMicros: 100_000_000n, lastSettledAt: cutoverAt, }; + const pulseRow = { + drawingId: 150n, + seed: `0x${'33'.repeat(32)}` as const, + settlementTxHash: `0x${'44'.repeat(32)}` as const, + settledAt: cutoverAt, + }; + const pulseBps = aggregateGalaxyPulseByType(deriveGalaxyPulseV1({ + drawingId: pulseRow.drawingId, + seed: pulseRow.seed, + chainId: BASE_CHAIN_ID, + jackpotAddress: BASE_JACKPOT, + })).get('gaia') ?? 0; const walletTransaction = { $queryRaw: vi.fn().mockResolvedValue([{ now: databaseNow }]), mineralAccount: { findUnique: vi.fn().mockResolvedValue(account) }, backendPlanet: { findMany: vi.fn().mockResolvedValue([planet]) }, planetUpgradePurchase: { findMany: vi.fn().mockResolvedValue([]) }, + galaxyPulseRound: { findMany: vi.fn().mockResolvedValue([pulseRow]) }, }; const walletPrisma = { $transaction: vi.fn(async (callback: (value: typeof walletTransaction) => unknown) => callback(walletTransaction)), @@ -67,6 +83,7 @@ describe('backend Planet mining snapshots', () => { backendPlanet: { findMany: vi.fn().mockResolvedValue([planet]) }, mineralAccount: { findMany: vi.fn().mockResolvedValue([account]) }, planetUpgradePurchase: { findMany: vi.fn().mockResolvedValue([]) }, + galaxyPulseRound: { findMany: vi.fn().mockResolvedValue([pulseRow]) }, }; const leaderboardPrisma = { $transaction: vi.fn(async (callback: (value: typeof leaderboardTransaction) => unknown) => callback(leaderboardTransaction)), @@ -84,9 +101,12 @@ describe('backend Planet mining snapshots', () => { expect(wallet.asOf).toBe(databaseNow.toISOString()); expect(leaderboard.asOf).toBe(databaseNow); - expect(wallet.currentBalanceMicros).toBe('200000000'); - expect(leaderboard.rows[0]?.scoreMicros).toBe(200_000_000n); + expect(wallet.galaxyPulse).toMatchObject({ drawingId: '150', slots: expect.any(Array) }); + expect(wallet.planets[0]).toMatchObject({ galaxyPulseBps: pulseBps }); expect(BigInt(wallet.currentBalanceMicros)).toBe(leaderboard.rows[0]?.scoreMicros); + expect(BigInt(wallet.effectiveMineralsPerDayMicros)).toBe( + leaderboard.rows[0]?.effectiveMineralsPerDayMicros, + ); }); it('calculates lifetime production from backend-generatedAt', async () => { diff --git a/server/api/miningStore.ts b/server/api/miningStore.ts index ca0237d..4cc799d 100644 --- a/server/api/miningStore.ts +++ b/server/api/miningStore.ts @@ -7,9 +7,11 @@ import { import { calculateHistoricalPlanetProduction, collectionBonusBpsAt, + galaxyPulseBpsAt, type MineralCollectionPlanet, type MineralUpgradePurchase, } from './mineralEconomy.js'; +import { loadGalaxyPulseRounds, serializeCurrentGalaxyPulse } from './galaxyPulseStore.js'; import { calculateCurrentMineralBalanceMicros, calculateV1WalletOpeningBalance, @@ -70,6 +72,9 @@ export async function getBackendWalletMiningSnapshot( asOf, ); } + const pulseRounds = transaction.galaxyPulseRound + ? await loadGalaxyPulseRounds(transaction, asOf) + : []; const planets = await transaction.backendPlanet.findMany({ where: { ownerAddress: ownerAddress.toLowerCase(), status: 'READY', generatedAt: { lte: asOf } }, select: { @@ -117,6 +122,7 @@ export async function getBackendWalletMiningSnapshot( asOf, planets: economyPlanets, purchases, + pulseRounds, }); const preCutoverCalculations = calculateCollectionMining({ planets: openingPlanets as BackendMiningPlanetRow[], @@ -132,9 +138,10 @@ export async function getBackendWalletMiningSnapshot( candidate.generatedAt && candidate.generatedAt.getTime() <= asOf.getTime(), ).length; const upgradeBonusBps = planet.upgradeBonusBps; + const galaxyPulseBps = galaxyPulseBpsAt(pulseRounds, planet.planetType, asOf.getTime()); const effectiveRate = calculateEffectiveMineralsPerDayMicros( planet.baseMineralsPerDay, - collectionBonusBps + upgradeBonusBps, + collectionBonusBps + upgradeBonusBps + galaxyPulseBps, ); effectiveMineralsPerDayMicros += effectiveRate; const preCutoverEarned = preCutoverCalculations.get(planet.id)?.earnedMicros ?? 0n; @@ -145,6 +152,7 @@ export async function getBackendWalletMiningSnapshot( from: cutoverAt, to: asOf, anchor: cutoverAt, + pulseRounds, }); let nextUpgrade = null; try { @@ -172,6 +180,7 @@ export async function getBackendWalletMiningSnapshot( collectionBonusBps, upgradeLevel: planet.upgradeLevel, upgradeBonusBps: planet.upgradeBonusBps, + galaxyPulseBps, effectiveMineralsPerDayMicros: effectiveRate.toString(), earnedMicros: (preCutoverEarned + postCutoverEarned).toString(), activeSince: planet.generatedAt.toISOString(), @@ -191,6 +200,7 @@ export async function getBackendWalletMiningSnapshot( currentBalanceMicros: currentBalanceMicros.toString(), effectiveMineralsPerDayMicros: effectiveMineralsPerDayMicros.toString(), upgradesEnabled: options.mineralUpgradesEnabled === true, + galaxyPulse: serializeCurrentGalaxyPulse(pulseRounds.at(-1) ?? null), planets: snapshots, }; }, @@ -218,6 +228,7 @@ async function getV1WalletMiningSnapshot(prisma: PrismaClient, ownerAddress: str planetType: calculated.planetType, sameTypeCount: calculated.sameTypeCount, collectionBonusBps: calculated.collectionBonusBps, + galaxyPulseBps: 0, effectiveMineralsPerDayMicros: calculated.effectiveMineralsPerDayMicros.toString(), earnedMicros: calculated.earnedMicros.toString(), activeSince: planet.generatedAt.toISOString(), @@ -231,6 +242,7 @@ async function getV1WalletMiningSnapshot(prisma: PrismaClient, ownerAddress: str currentBalanceMicros: earnedMicros.toString(), effectiveMineralsPerDayMicros: effectiveMineralsPerDayMicros.toString(), upgradesEnabled: false, + galaxyPulse: null, planets: snapshots, }; } diff --git a/server/api/receiptVerification.test.ts b/server/api/receiptVerification.test.ts index 4ad6872..8d67c3b 100644 --- a/server/api/receiptVerification.test.ts +++ b/server/api/receiptVerification.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { assertReceiptFinality } from './receiptVerification.js'; +import { assertReceiptFinality, parseReceiptReference } from './receiptVerification.js'; + +const transactionHash = `0x${'ab'.repeat(32)}` as const; +const recipient = '0x1111111111111111111111111111111111111111' as const; describe('receipt verification', () => { it('requires confirmation depth and canonical block hash', () => { @@ -13,4 +16,13 @@ describe('receipt verification', () => { { latestBlock: 106n, canonicalBlockHash: '0xbbb', confirmations: 6n }, )).toThrow(/canonical/i); }); + + it('narrows an optional recipient before normalizing a receipt reference', () => { + expect(parseReceiptReference({ transactionHash, logIndex: 4, recipient })).toEqual({ + transactionHash, + logIndex: 4, + recipient, + }); + expect(parseReceiptReference({ transactionHash, logIndex: 4, recipient: 123 })).toBeUndefined(); + }); }); diff --git a/server/api/receiptVerification.ts b/server/api/receiptVerification.ts index 0bb4861..83eb353 100644 --- a/server/api/receiptVerification.ts +++ b/server/api/receiptVerification.ts @@ -85,10 +85,14 @@ export function parseReceiptReference(value: unknown): ReceiptReference | undefi candidate.logIndex < 0 ) return undefined; const recipient = candidate.recipient; - if (recipient !== undefined && (typeof recipient !== 'string' || !isAddress(recipient))) return undefined; + let normalizedRecipient: Address | undefined; + if (recipient !== undefined) { + if (typeof recipient !== 'string' || !isAddress(recipient)) return undefined; + normalizedRecipient = getAddress(recipient); + } return { transactionHash: candidate.transactionHash, logIndex: candidate.logIndex, - recipient: recipient === undefined ? undefined : getAddress(recipient), + recipient: normalizedRecipient, }; } diff --git a/src/components/common/Button.test.tsx b/src/components/common/Button.test.tsx new file mode 100644 index 0000000..0552bbb --- /dev/null +++ b/src/components/common/Button.test.tsx @@ -0,0 +1,25 @@ +// @vitest-environment jsdom +import '@testing-library/jest-dom/vitest'; +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { Button } from './Button'; + +describe('Button', () => { + it('uses contained primary and outlined secondary hierarchy with restrained rounding', () => { + render( + <> + + + , + ); + + expect(screen.getByRole('button', { name: 'Primary' })).toHaveClass( + 'rounded-md', + 'shadow-sm', + ); + expect(screen.getByRole('button', { name: 'Secondary' })).toHaveClass( + 'bg-transparent', + 'border', + ); + }); +}); diff --git a/src/components/common/Button.tsx b/src/components/common/Button.tsx index 6cb5c8e..1182b00 100644 --- a/src/components/common/Button.tsx +++ b/src/components/common/Button.tsx @@ -27,21 +27,22 @@ export type ButtonVariant = 'primary' | 'secondary' | 'danger'; export type ButtonSize = 'sm' | 'md' | 'lg'; const VARIANT_CLASSES: Record = { - primary: 'bg-[var(--primary)] text-[var(--primary-foreground)] hover:bg-[var(--primary-hover)]', + primary: + 'bg-[var(--primary)] text-[var(--primary-foreground)] shadow-sm hover:-translate-y-0.5 hover:bg-[var(--primary-hover)] hover:shadow-md', secondary: - 'border border-[var(--border)] bg-[var(--surface-raised)] text-[var(--text-primary)] hover:bg-[var(--surface-hover)]', + 'border border-[var(--border)] bg-transparent text-[var(--text-primary)] hover:border-[var(--primary)] hover:bg-[var(--surface-hover)]', danger: 'bg-[var(--danger)] text-[#28070d] hover:brightness-110', }; const SIZE_CLASSES: Record = { - sm: 'rounded-lg px-3 py-2 text-xs font-semibold', + sm: 'rounded-md px-3 py-2 text-xs font-semibold', md: 'rounded-lg px-4 py-2.5 text-sm font-semibold', - lg: 'rounded-xl px-6 py-4 text-base font-semibold', + lg: 'rounded-lg px-6 py-4 text-base font-semibold', }; const BASE_CLASSES = - 'min-h-10 font-hud uppercase tracking-wide transition-transform duration-150 ease-out disabled:cursor-not-allowed disabled:opacity-50'; + 'min-h-10 font-hud uppercase tracking-wide transition-all duration-150 ease-out disabled:cursor-not-allowed disabled:opacity-50'; export type ButtonProps = ButtonHTMLAttributes & { variant?: ButtonVariant; diff --git a/src/components/explore/ExpeditionConfigurator.test.tsx b/src/components/explore/ExpeditionConfigurator.test.tsx index 470d7f6..7f515e6 100644 --- a/src/components/explore/ExpeditionConfigurator.test.tsx +++ b/src/components/explore/ExpeditionConfigurator.test.tsx @@ -26,12 +26,19 @@ describe('ExpeditionConfigurator', () => { expect(screen.getByRole('heading', { name: 'Win up to $123.46' })).toBeInTheDocument(); expect(container.querySelectorAll('.depth-text__layer')).toHaveLength(32); + expect(container.querySelector('h1')).toHaveClass( + 'w-full', + 'min-w-0', + 'max-w-full', + 'overflow-hidden', + ); expect(container.querySelector('.depth-text')).toHaveStyle({ '--depth-text-perspective': '1500px', - '--depth-text-font-size': 'clamp(3.45rem, 5.6vw, 5.3rem)', + '--depth-text-font-size': 'clamp(2rem, 7vw, 5.3rem)', '--depth-text-font-weight': '800', '--depth-text-face-color': '#f8fafc', }); + expect(container.querySelector('.depth-text')).toHaveClass('block', 'w-full', 'min-w-0'); expect(container.querySelector('.depth-text__layer')).toHaveStyle({ transform: 'translateZ(-128px)', }); @@ -112,31 +119,25 @@ describe('ExpeditionConfigurator', () => { expect(screen.getByRole('button', { name: 'Explore 3 · $3.00 USDC' })).toBeEnabled(); - expect(screen.getByTestId('expedition-core')).toHaveAttribute('data-layout-anchor', 'fixed'); - expect(screen.getByTestId('expedition-core')).toHaveClass('max-w-[840px]'); - expect(screen.getByTestId('coordinates-disclosure')).toHaveAttribute('data-side', 'right'); + expect(screen.getByTestId('expedition-core')).toHaveAttribute('data-layout-anchor', 'flow'); + expect(screen.getByTestId('expedition-core')).toHaveClass('max-w-[1120px]', 'min-w-0'); + expect(screen.getByTestId('coordinates-disclosure')).toHaveAttribute('data-side', 'in-flow'); expect(screen.getByTestId('coordinates-disclosure')).toHaveAttribute('data-state', 'closed'); - expect(screen.getByTestId('coordinates-disclosure')).toHaveClass('w-0'); + expect(screen.getByTestId('coordinates-disclosure')).toHaveClass('max-h-0'); const [toggle] = screen.getAllByRole('button', { name: 'Open coordinates' }); expect(toggle).toHaveAttribute('aria-expanded', 'false'); - expect(toggle).toHaveClass('transition-[right,background-color]'); - expect(toggle).toHaveClass('h-60', 'w-20'); - expect(toggle).toHaveClass('fixed'); - expect(toggle).toHaveStyle({ right: '0px' }); - expect(toggle.querySelector('.text-\\[1rem\\]')).toBeInTheDocument(); - expect(toggle.querySelector('.text-\\[2\\.25rem\\]')).toBeInTheDocument(); - expect(screen.getByTestId('coordinates-disclosure')).toHaveClass('fixed'); - expect(screen.getByTestId('coordinates-disclosure')).toHaveStyle({ right: '0px' }); + expect(toggle).toHaveClass('w-full'); + expect(toggle).not.toHaveClass('fixed'); + expect(screen.getAllByRole('button', { name: 'Open coordinates' })).toHaveLength(1); expect(screen.getAllByText('Bonus Ball influences Planet generation.')).toHaveLength(1); await user.click(toggle); - expect(screen.getAllByRole('region', { name: 'Coordinates' })).toHaveLength(2); + expect(screen.getAllByRole('region', { name: 'Coordinates' })).toHaveLength(1); expect(screen.getByTestId('coordinates-disclosure')).toHaveAttribute('data-state', 'open'); - expect(screen.getByTestId('coordinates-disclosure')).toHaveClass('w-[380px]'); + expect(screen.getByTestId('coordinates-disclosure')).not.toHaveClass('max-h-0'); const [closeToggle] = screen.getAllByRole('button', { name: 'Close coordinates' }); - expect(closeToggle).toHaveStyle({ right: '380px' }); await user.click(closeToggle); expect(toggle).toHaveAttribute('aria-expanded', 'false'); }); diff --git a/src/components/explore/ExpeditionConfigurator.tsx b/src/components/explore/ExpeditionConfigurator.tsx index 2f20051..5f636b2 100644 --- a/src/components/explore/ExpeditionConfigurator.tsx +++ b/src/components/explore/ExpeditionConfigurator.tsx @@ -81,15 +81,15 @@ export function ExpeditionConfigurator({ return (
-
+
-

+

{jackpotStatus === 'ready' ? ( @@ -178,66 +179,36 @@ export function ExpeditionConfigurator({

+
+
-
- - {coordinatesOpen && ( -
- -
- )} -
); } diff --git a/src/components/explore/StaticDepthStack.test.tsx b/src/components/explore/StaticDepthStack.test.tsx index 00e7a57..0a09a13 100644 --- a/src/components/explore/StaticDepthStack.test.tsx +++ b/src/components/explore/StaticDepthStack.test.tsx @@ -11,14 +11,20 @@ describe('StaticDepthStack', () => { }); it('uses random mystery colors on an expanded vertical orbit', () => { - vi.spyOn(Math, 'random') - .mockReturnValueOnce(0) - .mockReturnValueOnce(0.99) - .mockReturnValue(0.5); + vi.spyOn(Math, 'random').mockReturnValueOnce(0).mockReturnValueOnce(0.99).mockReturnValue(0.5); render(); - expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass('h-[200px]', 'sm:h-[360px]'); + expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass( + 'h-[200px]', + 'min-[381px]:h-[300px]', + 'sm:h-[360px]', + 'lg:mt-12', + 'min-w-0', + 'overflow-hidden', + 'lg:aspect-[8/5]', + 'lg:h-auto', + ); const images = screen.getAllByRole('img', { name: /selected planet/i }); expect(images[0]).toHaveAttribute('src', expect.stringContaining('blue')); expect(images[1]).toHaveAttribute('src', expect.stringContaining('violet')); @@ -30,7 +36,12 @@ describe('StaticDepthStack', () => { it('adds newly selected planets as animated visual slots', () => { const { rerender } = render(); - expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass('h-[200px]', 'sm:h-[360px]'); + expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass( + 'h-[200px]', + 'sm:h-[360px]', + 'lg:aspect-[8/5]', + 'lg:h-auto', + ); const orbitItem = screen.getByTestId('planet-orbit').querySelector('.orbit-item'); expect(orbitItem).toHaveStyle({ width: '560px', @@ -42,7 +53,12 @@ describe('StaticDepthStack', () => { rerender(); expect(screen.getAllByRole('img', { name: /selected planet/i })).toHaveLength(3); - expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass('h-[200px]', 'sm:h-[360px]'); + expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass( + 'h-[200px]', + 'sm:h-[360px]', + 'lg:aspect-[8/5]', + 'lg:h-auto', + ); expect(screen.getByTestId('planet-orbit').querySelector('.orbit-item')).toHaveStyle({ width: '510px', height: '510px', @@ -55,7 +71,12 @@ describe('StaticDepthStack', () => { expect(screen.getAllByRole('img', { name: /selected planet/i })).toHaveLength(20); expect(screen.queryByText('20 planets selected')).not.toBeInTheDocument(); - expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass('h-[200px]', 'sm:h-[360px]'); + expect(screen.getByRole('group', { name: 'Selected planets visualization' })).toHaveClass( + 'h-[200px]', + 'sm:h-[360px]', + 'lg:aspect-[8/5]', + 'lg:h-auto', + ); expect(screen.queryByTestId('orbit-planet-count')).not.toBeInTheDocument(); }); diff --git a/src/components/explore/StaticDepthStack.tsx b/src/components/explore/StaticDepthStack.tsx index c368617..298820b 100644 --- a/src/components/explore/StaticDepthStack.tsx +++ b/src/components/explore/StaticDepthStack.tsx @@ -26,7 +26,7 @@ export function StaticDepthStack({ const radiusY = visibleCards === 1 ? 1 : Math.min(190, Math.max(90, 72 + visibleCards * 5)); return (
) { return ( + ); +} + +export function PlanetIcon(props: SVGProps) { + return ( + ); } diff --git a/src/components/landing/LandingHowItWorks.test.tsx b/src/components/landing/LandingHowItWorks.test.tsx index 7d66b87..ae2476e 100644 --- a/src/components/landing/LandingHowItWorks.test.tsx +++ b/src/components/landing/LandingHowItWorks.test.tsx @@ -21,11 +21,17 @@ describe('LandingHowItWorks', () => { expect(screen.getByText('How does the Planet leaderboard fit in?')).toBeInTheDocument(); fireEvent.click(screen.getByText('Is the Planet another ticket?')); fireEvent.click(screen.getByText('Who powers the jackpot?')); - expect(screen.getByText(/A Megapot Ticket is a \$1 USDC entry for the daily draw/i)).toBeInTheDocument(); - expect(screen.getByText(/Megastera binds one generated Planet to that ticket/i)).toBeInTheDocument(); + expect( + screen.getByText(/A Megapot Ticket is a \$1 USDC entry for the daily draw/i), + ).toBeInTheDocument(); + expect( + screen.getByText(/Megastera binds one generated Planet to that ticket/i), + ).toBeInTheDocument(); expect(screen.getByText(/Pyth supplies verifiable randomness/i)).toBeInTheDocument(); expect(screen.getByText(/70% of ticket value enters the jackpot pool/i)).toBeInTheDocument(); expect(screen.getByText(/The Planet is not a second ticket/i)).toBeInTheDocument(); - expect(container.querySelectorAll('.landing-how-it-works .split-parent').length).toBeGreaterThanOrEqual(17); + expect( + container.querySelectorAll('.landing-how-it-works .split-parent').length, + ).toBeGreaterThanOrEqual(17); }); }); diff --git a/src/components/landing/LandingHowItWorks.tsx b/src/components/landing/LandingHowItWorks.tsx index 5509f7d..9d2aeb2 100644 --- a/src/components/landing/LandingHowItWorks.tsx +++ b/src/components/landing/LandingHowItWorks.tsx @@ -50,7 +50,11 @@ const faqItems: readonly LandingFaqItem[] = [ export function LandingHowItWorks() { return ( -
+
@@ -72,8 +76,20 @@ export function LandingHowItWorks() { {faqItems.map((item, index) => (
- - + + { vi.useRealTimers(); }); - it('shows the live jackpot, drawing number, and a ticking countdown with a larger echo', () => { + it('shows the live jackpot and countdown without phase or drawing-number clutter', () => { render(); const jackpot = screen.getByTestId('landing-jackpot-echo'); expect(jackpot).toHaveTextContent('$123.46'); expect(jackpot.querySelectorAll('.depth-text__layer')).toHaveLength(64); expect(screen.getByTestId('landing-jackpot-layout')).toHaveClass('landing-live-jackpot-layout'); - expect(screen.getByTestId('landing-drawing-in')).toBeInTheDocument(); + const drawing = screen.getByTestId('landing-drawing-in'); + expect(drawing).toBeInTheDocument(); + expect(screen.getByText('LIVE JACKPOT').parentElement).toContainElement(drawing); + expect(drawing.querySelector('.landing-live-jackpot-countdown-line')).toHaveTextContent( + 'DRAWING IN01:01:01', + ); expect(screen.getByText('LIVE JACKPOT')).toBeInTheDocument(); expect(screen.getByText('DRAWING IN')).toBeInTheDocument(); - expect(screen.getByText('DRAWING #88')).toBeInTheDocument(); + expect(screen.queryByText('TICKETS OPEN')).not.toBeInTheDocument(); + expect(screen.queryByText('DRAWING #88')).not.toBeInTheDocument(); expect(screen.getByRole('timer')).toHaveTextContent('01:01:01'); act(() => { diff --git a/src/components/landing/LandingLiveJackpot.tsx b/src/components/landing/LandingLiveJackpot.tsx index bdc2243..12f94e1 100644 --- a/src/components/landing/LandingLiveJackpot.tsx +++ b/src/components/landing/LandingLiveJackpot.tsx @@ -1,20 +1,19 @@ import { formatUnits } from 'viem'; -import { Countdown } from '@/components/lottery/Countdown'; import { DepthText } from '@/components/common/DepthText'; +import { Countdown } from '@/components/lottery/Countdown'; import { useJackpotState } from '@/hooks/useJackpotState'; import { LandingSplitText } from './LandingSplitText'; function formatJackpot(amount: bigint | undefined) { - if (amount === undefined) return '$—'; + if (amount === undefined) return '$-'; return `$${Number(formatUnits(amount, 6)).toLocaleString('en-US', { maximumFractionDigits: 2, })}`; } export function LandingLiveJackpot() { - const { state, drawingId, phase } = useJackpotState(); + const { state, phase } = useJackpotState(); const drawingLabel = phase === 'open' ? 'DRAWING IN' : 'DRAWING LIVE'; - const phaseLabel = phase === 'open' ? 'TICKETS OPEN' : 'SETTLEMENT ACTIVE'; return ( ); diff --git a/src/components/landing/LandingMiningLeaderboard.test.tsx b/src/components/landing/LandingMiningLeaderboard.test.tsx index aedcc06..180d73b 100644 --- a/src/components/landing/LandingMiningLeaderboard.test.tsx +++ b/src/components/landing/LandingMiningLeaderboard.test.tsx @@ -9,6 +9,12 @@ vi.mock('@/hooks/useLeaderboard', () => ({ useCurrentLeaderboard: vi.fn(), })); +vi.mock('@/components/planets/PlanetGif', () => ({ + PlanetGif: ({ preview }: { preview: { visualTraitsHash: string } }) => ( + + ), +})); + const mockUseCurrentLeaderboard = vi.mocked(useCurrentLeaderboard); const leaderboardData = { @@ -18,9 +24,9 @@ const leaderboardData = { endsAt: '2026-08-15T00:00:00.000Z', }, asOf: '2026-08-14T12:00:00.000Z', - total: 3, + total: 5, offset: 0, - limit: 3, + limit: 5, rows: [ { rank: 1, @@ -40,6 +46,18 @@ const leaderboardData = { scoreMicros: '76000000', effectiveMineralsPerDayMicros: '3600000', }, + { + rank: 4, + walletAddress: '0x4444444444444444444444444444444444444444' as `0x${string}`, + scoreMicros: '64000000', + effectiveMineralsPerDayMicros: '3100000', + }, + { + rank: 5, + walletAddress: '0x5555555555555555555555555555555555555555' as `0x${string}`, + scoreMicros: '52000000', + effectiveMineralsPerDayMicros: '2800000', + }, ], }; @@ -49,7 +67,7 @@ describe('LandingMiningLeaderboard', () => { vi.clearAllMocks(); }); - it('shows the mining promise and the live top three leaderboard rows', () => { + it('shows Planet levels, active players, prizes, and a live top five', () => { mockUseCurrentLeaderboard.mockReturnValue({ data: leaderboardData, error: null, @@ -58,14 +76,49 @@ describe('LandingMiningLeaderboard', () => { render(); - expect(screen.getByRole('region', { name: /Keep mining\.\s*Climb higher\./ })).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: /Keep mining\.\s*Climb higher\./ })).toBeInTheDocument(); - expect(screen.getByText(/Your Planet keeps mining minerals/i)).toBeInTheDocument(); - expect(screen.getByText(/Same type bonus: collect 3, 5, or 10 Planets of one type to boost mining by \+5%, \+7\.5%, or \+10%\./i)).toBeInTheDocument(); - expect(screen.getByRole('link', { name: 'View leaderboard' })).toHaveAttribute('href', '/leaderboard'); + expect( + screen.getByRole('region', { name: /Keep mining\.\s*Upgrade\.\s*Climb higher\./ }), + ).toBeInTheDocument(); + expect( + screen.getByRole('heading', { name: /Keep mining\.\s*Upgrade\.\s*Climb higher\./ }), + ).toBeInTheDocument(); + expect( + screen.getByText(/Spend mined Minerals to upgrade production and climb the leaderboard/i), + ).toBeInTheDocument(); + expect(screen.getByText(/Each upgrade increases your Planet level and mining output/i)).toBeInTheDocument(); + expect(screen.queryByText(/Same type bonus/i)).not.toBeInTheDocument(); + expect(screen.getByTestId('landing-upgrade-preview')).toBeInTheDocument(); + expect(screen.getAllByTestId('landing-upgrade-stage')).toHaveLength(3); + expect( + screen.getAllByTestId('landing-upgrade-stage').map((stage) => stage.getAttribute('data-ornament')), + ).toEqual(['crystal', 'winged', 'crowned']); + const visualSeeds = screen + .getAllByTestId('landing-upgrade-stage') + .map((stage) => stage.getAttribute('data-planet-visual-seed')); + expect(new Set(visualSeeds).size).toBe(3); + expect(screen.getAllByText('+10%')).toHaveLength(2); + expect(screen.getAllByText('+25%')).toHaveLength(2); + expect(screen.getAllByText('+50%')).toHaveLength(2); + expect(screen.getByText('UPGRADE IMPACT')).toBeInTheDocument(); + expect(screen.getAllByTestId('landing-upgrade-impact-meter')).toHaveLength(3); + expect(screen.getByText('LEVEL 1')).toBeInTheDocument(); + expect(screen.getByText('LEVEL 2')).toBeInTheDocument(); + expect(screen.getByText('LEVEL 3')).toBeInTheDocument(); + expect(screen.queryByText(/stage|signal/i)).not.toBeInTheDocument(); expect(screen.getByText('LIVE STANDINGS')).toBeInTheDocument(); + expect(screen.getByText('ACTIVE PLAYERS')).toBeInTheDocument(); + expect(screen.getByTestId('landing-active-players')).toHaveTextContent('5'); + expect(screen.getByText('Megapot Tickets')).toBeInTheDocument(); + expect(screen.getByText('(USDC)')).toBeInTheDocument(); + expect(screen.getByText('1/1 NFT Planets')).toBeInTheDocument(); + const standings = screen.getByText('LIVE STANDINGS').closest('.landing-mining-standings'); + expect(standings).not.toBeNull(); + expect(standings).toContainElement(screen.getByRole('link', { name: 'View leaderboard' })); + expect(screen.getByRole('link', { name: 'View leaderboard' })).toHaveAttribute('href', '/leaderboard'); expect(screen.getByText('0x1111…1111')).toBeInTheDocument(); expect(screen.getByText('125')).toBeInTheDocument(); - expect(screen.getAllByRole('listitem')).toHaveLength(3); + expect(mockUseCurrentLeaderboard).toHaveBeenCalledWith(0, 5); + expect(screen.getByText('TOP 5')).toBeInTheDocument(); + expect(standings?.querySelectorAll('li')).toHaveLength(5); }); }); diff --git a/src/components/landing/LandingMiningLeaderboard.tsx b/src/components/landing/LandingMiningLeaderboard.tsx index d056694..698eab5 100644 --- a/src/components/landing/LandingMiningLeaderboard.tsx +++ b/src/components/landing/LandingMiningLeaderboard.tsx @@ -1,6 +1,30 @@ import mineIcon from '@/assets/mine-icon.png'; +import { PlanetIcon, TicketsIcon } from '@/components/icons/TicketsIcon'; +import { PlanetGif } from '@/components/planets/PlanetGif'; import { useCurrentLeaderboard } from '@/hooks/useLeaderboard'; import { formatMinerals } from '@/lib/minerals'; +import { useState } from 'react'; +import { createRandomLandingPlanetPreviews } from './landingPlanetPreview'; + +const UPGRADE_STAGES = [ + { + level: '1', + bonus: '+10%', + ornament: 'crystal', + }, + { + level: '2', + bonus: '+25%', + ornament: 'winged', + }, + { + level: '3', + bonus: '+50%', + ornament: 'crowned', + }, +] as const; + +const UPGRADE_CRYSTAL_KEYS = ['primary', 'secondary', 'tertiary'] as const; function shortAddress(address: string) { return `${address.slice(0, 6)}…${address.slice(-4)}`; @@ -11,8 +35,9 @@ function formatScore(scoreMicros: string) { } export function LandingMiningLeaderboard() { - const leaderboard = useCurrentLeaderboard(0, 3); - const rows = leaderboard.data?.rows.slice(0, 3) ?? []; + const [upgradePlanets] = useState(() => createRandomLandingPlanetPreviews(UPGRADE_STAGES.length)); + const leaderboard = useCurrentLeaderboard(0, 5); + const rows = leaderboard.data?.rows.slice(0, 5) ?? []; const hasRows = !leaderboard.isLoading && !leaderboard.error && rows.length > 0; return ( @@ -25,42 +50,102 @@ export function LandingMiningLeaderboard() { MINING / LEADERBOARD

Keep mining. + Upgrade. Climb higher.

- Once generated, your Planet keeps mining minerals and competing for leaderboard rewards. + Spend mined Minerals to upgrade production and climb the leaderboard.

-

- Same type bonus: collect 3, 5, or 10 Planets of one type to boost mining by +5%, +7.5%, or +10%. +

+ Each upgrade increases your Planet level and mining output.

- - View leaderboard -
-
- Generated Planet preview -
+
+
+ PLANET UPGRADE PATH + 3 LEVELS +
+ +
+ {UPGRADE_STAGES.map((stage, index) => { + const preview = upgradePlanets[index]; + return ( +
+ +
+ +
+
+ LEVEL {stage.level} + {stage.bonus} +
+
+ ); + })} +
+ +
+
+ UPGRADE IMPACT + MINING OUTPUT +
+
    + {UPGRADE_STAGES.map((stage) => ( +
  1. + 0{stage.level} + + {stage.bonus} +
  2. + ))} +
+
+ +
    + {UPGRADE_STAGES.map((stage) => ( +
  1. + {stage.level} +
  2. + ))} +
+
- PLANET / MINING + Mine Minerals to unlock the next level.
LIVE STANDINGS - {hasRows ? 'TOP 3' : 'LEADERBOARD'} + {hasRows ? 'TOP 5' : 'LEADERBOARD'} +
+
+ ACTIVE PLAYERS + {leaderboard.data?.total ?? '-'}
{hasRows ? (
    {rows.map((row) => ( -
  1. +
  2. #{row.rank} {shortAddress(row.walletAddress)} {formatScore(row.scoreMicros)} @@ -71,9 +156,21 @@ export function LandingMiningLeaderboard() {

    {leaderboard.isLoading ? 'Syncing standings.' + : leaderboard.error + ? 'Standings temporarily unavailable.' : 'Standings appear as Planets begin mining.'}

    )} +
    +
    + PRIZES + Megapot Tickets (USDC) + 1/1 NFT Planets +
    + + View leaderboard + +
diff --git a/src/components/landing/LandingPlanetCard.tsx b/src/components/landing/LandingPlanetCard.tsx index ec8238c..764fbff 100644 --- a/src/components/landing/LandingPlanetCard.tsx +++ b/src/components/landing/LandingPlanetCard.tsx @@ -1,36 +1,48 @@ -import type { PlanetRarity } from '@megaplanets/planet-generator'; import mineralIcon from '@/assets/mineral-icon.png'; -import { rarityBorderClass } from '@/lib/planetInventory'; -import { LandingSplitText } from './LandingSplitText'; + +type LandingPlanetRarity = 'Common' | 'Uncommon' | 'Epic' | 'Legendary'; type LandingPlanetCardProps = { image: string; name: string; - rarity: PlanetRarity; + type: string; + rarity: LandingPlanetRarity; ticketId: string; - minerals: number; + rate: string; + active: boolean; }; -export function LandingPlanetCard({ image, name, rarity, ticketId, minerals }: LandingPlanetCardProps) { +export function LandingPlanetCard({ + image, + name, + type, + rarity, + ticketId, + rate, + active, +}: LandingPlanetCardProps) { return (
-
+
{`${name} + {type}
-
-
- - +
+
+

{name}

+ {rarity}
-
- +
+ Minerals - + {rate} / day - + Ticket #{ticketId}
diff --git a/src/components/landing/PlanetCardStack.test.tsx b/src/components/landing/PlanetCardStack.test.tsx new file mode 100644 index 0000000..e2c5cf5 --- /dev/null +++ b/src/components/landing/PlanetCardStack.test.tsx @@ -0,0 +1,34 @@ +// @vitest-environment jsdom +import '@testing-library/jest-dom/vitest'; +import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { PlanetCardStack } from './PlanetCardStack'; + +describe('PlanetCardStack', () => { + afterEach(cleanup); + + it('cycles real Planet cards and animates only the active asset', () => { + render(); + + const carousel = screen.getByRole('region', { name: 'Planet discovery carousel' }); + expect(screen.getByText('DRAG PLANETS')).toBeInTheDocument(); + expect(carousel.querySelector('.landing-planet-stack-drag-visual')).toBeInTheDocument(); + const firstActiveImage = carousel.querySelector('[data-active="true"] img'); + expect(firstActiveImage).toHaveAttribute('src', expect.stringMatching(/\.gif$/)); + + const firstName = carousel.querySelector('[data-active="true"] h3')?.textContent; + fireEvent.click(screen.getByRole('button', { name: 'Show next Planet' })); + + const nextActive = carousel.querySelector('[data-active="true"]'); + expect(nextActive?.querySelector('h3')?.textContent).not.toBe(firstName); + expect(nextActive?.querySelector('img')).toHaveAttribute( + 'src', + expect.stringMatching(/\.gif$/), + ); + expect( + [...carousel.querySelectorAll('[data-active="false"] img')].every((image) => + image.getAttribute('src')?.endsWith('.png'), + ), + ).toBe(true); + }); +}); diff --git a/src/components/landing/PlanetCardStack.tsx b/src/components/landing/PlanetCardStack.tsx new file mode 100644 index 0000000..554e5a4 --- /dev/null +++ b/src/components/landing/PlanetCardStack.tsx @@ -0,0 +1,95 @@ +import { motion, type PanInfo, useReducedMotion } from 'motion/react'; +import { useEffect, useState } from 'react'; +import { LandingPlanetCard } from './LandingPlanetCard'; + +// Interaction adapted from React Bits Stack (MIT + Commons Clause). +const planets = [ + { id: '006', name: 'Vesper Arc', type: 'Toxic', rarity: 'Epic', rate: '4.82' }, + { id: '017', name: 'Kairox Bloom', type: 'Gaia', rarity: 'Legendary', rate: '6.14' }, + { id: '029', name: 'Nereid Rift', type: 'Oceanic', rarity: 'Uncommon', rate: '3.27' }, + { id: '039', name: 'Cinder-39', type: 'Volcanic', rarity: 'Epic', rate: '5.08' }, + { id: '055', name: 'Pelagos', type: 'Gaia', rarity: 'Common', rate: '2.91' }, + { id: '067', name: 'Ion Veil', type: 'Toxic', rarity: 'Legendary', rate: '6.72' }, + { id: '092', name: 'Orison Belt', type: 'Desert', rarity: 'Uncommon', rate: '3.64' }, +] as const; + +export function PlanetCardStack() { + const [order, setOrder] = useState(() => planets.map((_, index) => index)); + const [paused, setPaused] = useState(false); + const reduceMotion = useReducedMotion(); + + const next = () => setOrder((current) => [current[current.length - 1], ...current.slice(0, -1)]); + const previous = () => setOrder((current) => [...current.slice(1), current[0]]); + + useEffect(() => { + if (paused || reduceMotion) return; + const timer = window.setInterval( + () => setOrder((current) => [current[current.length - 1], ...current.slice(0, -1)]), + 4500, + ); + return () => window.clearInterval(timer); + }, [paused, reduceMotion]); + + const handleDragEnd = (_event: MouseEvent | TouchEvent | PointerEvent, info: PanInfo) => { + if (Math.abs(info.offset.x) > 80 || Math.abs(info.offset.y) > 80) next(); + }; + + return ( +
setPaused(true)} + onMouseLeave={() => setPaused(false)} + > +
+ {order.map((planetIndex, index) => { + const planet = planets[planetIndex]; + const active = index === order.length - 1; + const depth = order.length - index - 1; + return ( + + + + ); + })} +
+
+ + + + DRAG PLANETS + + +
+
+ ); +} diff --git a/src/components/landing/PlanetGeneratorHero.test.tsx b/src/components/landing/PlanetGeneratorHero.test.tsx index bc46170..2114b4b 100644 --- a/src/components/landing/PlanetGeneratorHero.test.tsx +++ b/src/components/landing/PlanetGeneratorHero.test.tsx @@ -1,30 +1,57 @@ // @vitest-environment jsdom import '@testing-library/jest-dom/vitest'; import { act, fireEvent, render, screen } from '@testing-library/react'; -import { afterEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { PlanetGeneratorHero } from './PlanetGeneratorHero'; vi.mock('@/components/planets/PlanetGif', () => ({ - PlanetGif: ({ preview }: { preview: { descriptor: { input: { ticketId: bigint } } } }) => ( - Generated ticket {preview.descriptor.input.ticketId.toString()} + PlanetGif: ({ + preview, + }: { + preview: { descriptor: { input: { ticketId: bigint } }; visualTraitsHash: string }; + }) => ( + + Generated ticket {preview.descriptor.input.ticketId.toString()} + ), })); describe('PlanetGeneratorHero', () => { + beforeEach(() => { + const values = [100, 900_000]; + vi.stubGlobal('crypto', { + getRandomValues: vi.fn((buffer: Uint32Array) => { + buffer[0] = values.shift() ?? 42; + return buffer; + }), + }); + }); + afterEach(() => { vi.useRealTimers(); + vi.unstubAllGlobals(); }); - it('generates another Planet preview only on demand', () => { + it('starts from a random ticket and generates a different Planet only on demand', () => { vi.useFakeTimers(); const { container } = render(); - expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 5001'); - expect(screen.getByRole('article', { name: 'Interactive Planet preview' })).toBeInTheDocument(); + expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 1100'); + const previewArticle = screen.getByRole('article', { name: 'Interactive Planet preview' }); + const initialVisualSeed = previewArticle.getAttribute('data-planet-visual-seed'); + const initialVisualTraitsHash = screen + .getByTestId('planet-gif-preview') + .getAttribute('data-visual-traits-hash'); + expect(initialVisualSeed).not.toBeNull(); + expect(initialVisualSeed ?? '').toMatch(/^0x[0-9a-f]{64}$/); + expect(initialVisualTraitsHash).not.toBeNull(); + expect(initialVisualTraitsHash ?? '').toMatch(/^0x[0-9a-f]{64}$/); expect(container.querySelector('.landing-live-generator')).toBeInTheDocument(); expect(container.querySelector('.landing-live-generator-topline')).not.toBeInTheDocument(); expect(container.querySelector('.landing-live-generator-meta')).not.toBeInTheDocument(); - expect(container.querySelector('.landing-live-generator-art.landing-planet-card')).not.toBeInTheDocument(); + expect( + container.querySelector('.landing-live-generator-art.landing-planet-card'), + ).not.toBeInTheDocument(); expect(screen.queryByText('PLANET = TICKET')).not.toBeInTheDocument(); expect(screen.queryByText('MEGAPOT · IN DRAW')).not.toBeInTheDocument(); @@ -36,11 +63,16 @@ describe('PlanetGeneratorHero', () => { expect(screen.queryByRole('button', { name: /Generate another/i })).not.toBeInTheDocument(); fireEvent.click(generatePlanetButton); - expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 5002'); + expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 901000'); + expect(previewArticle.getAttribute('data-planet-visual-seed')).toMatch(/^0x[0-9a-f]{64}$/); + expect(previewArticle.getAttribute('data-planet-visual-seed')).not.toBe(initialVisualSeed); + expect(screen.getByTestId('planet-gif-preview').getAttribute('data-visual-traits-hash')).not.toBe( + initialVisualTraitsHash, + ); act(() => { vi.advanceTimersByTime(3_000); }); - expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 5002'); + expect(screen.getByTestId('planet-gif-preview')).toHaveTextContent('Generated ticket 901000'); }); }); diff --git a/src/components/landing/PlanetGeneratorHero.tsx b/src/components/landing/PlanetGeneratorHero.tsx index f62b3b0..07bb076 100644 --- a/src/components/landing/PlanetGeneratorHero.tsx +++ b/src/components/landing/PlanetGeneratorHero.tsx @@ -1,40 +1,24 @@ -import { derivePlanetPreview, type PlanetPreview } from '@megaplanets/planet-generator'; -import { useCallback, useMemo, useState } from 'react'; +import { useCallback, useState } from 'react'; import { PlanetGif } from '@/components/planets/PlanetGif'; -import { PLANET_CONFIG } from '@/config/planetConfig'; +import { createRandomLandingPlanetPreviews } from './landingPlanetPreview'; import { LandingSplitText } from './LandingSplitText'; -const PREVIEW_ORIGIN_TX_HASH = `0x${'51'.repeat(32)}` as `0x${string}`; -const INITIAL_TICKET_NUMBER = 5001; - -function createPreview(ticketNumber: number): PlanetPreview { - const normalStart = (ticketNumber * 13) % 255; - const normals = Array.from( - { length: 5 }, - (_, index) => ((normalStart + index * 31) % 255) + 1, - ); - - return derivePlanetPreview( - { - ticketId: BigInt(ticketNumber), - drawingId: BigInt(700 + (ticketNumber % 5)), - normals, - bonusBall: ((ticketNumber * 17) % 255) + 1, - originTxHash: PREVIEW_ORIGIN_TX_HASH, - }, - PLANET_CONFIG, - ); -} - export function PlanetGeneratorHero() { - const [ticketNumber, setTicketNumber] = useState(INITIAL_TICKET_NUMBER); - const preview = useMemo(() => createPreview(ticketNumber), [ticketNumber]); - const generatePlanet = useCallback(() => setTicketNumber((current) => current + 1), []); + const [preview, setPreview] = useState(() => createRandomLandingPlanetPreviews(1)[0]); + const generatePlanet = useCallback(() => { + setPreview((current) => + createRandomLandingPlanetPreviews(1, [Number(current.descriptor.input.ticketId)])[0], + ); + }, []); return ( -
+
- + diff --git a/src/components/landing/landingPlanetPreview.ts b/src/components/landing/landingPlanetPreview.ts new file mode 100644 index 0000000..d41b3a1 --- /dev/null +++ b/src/components/landing/landingPlanetPreview.ts @@ -0,0 +1,46 @@ +import { derivePlanetPreview, type PlanetPreview } from '@megaplanets/planet-generator'; +import { PLANET_CONFIG } from '@/config/planetConfig'; + +const PREVIEW_ORIGIN_TX_HASH = `0x${'51'.repeat(32)}` as `0x${string}`; +const MIN_TICKET_NUMBER = 1_000; +const TICKET_NUMBER_RANGE = 999_000; + +function randomUint32(): number { + const values = new Uint32Array(1); + if (typeof globalThis.crypto?.getRandomValues === 'function') { + globalThis.crypto.getRandomValues(values); + return values[0]; + } + return Date.now() >>> 0; +} + +function createPreview(ticketNumber: number): PlanetPreview { + const normalStart = (ticketNumber * 13) % 255; + const normals = Array.from({ length: 5 }, (_, index) => ((normalStart + index * 31) % 255) + 1); + + return derivePlanetPreview( + { + ticketId: BigInt(ticketNumber), + drawingId: BigInt(700 + (ticketNumber % 97)), + normals, + bonusBall: ((ticketNumber * 17) % 255) + 1, + originTxHash: PREVIEW_ORIGIN_TX_HASH, + }, + PLANET_CONFIG, + ); +} + +export function createRandomLandingPlanetPreviews( + count: number, + excludedTicketNumbers: readonly number[] = [], +): PlanetPreview[] { + const used = new Set(excludedTicketNumbers); + return Array.from({ length: count }, () => { + let ticketNumber = MIN_TICKET_NUMBER + (randomUint32() % TICKET_NUMBER_RANGE); + while (used.has(ticketNumber)) { + ticketNumber = MIN_TICKET_NUMBER + ((ticketNumber - MIN_TICKET_NUMBER + 1) % TICKET_NUMBER_RANGE); + } + used.add(ticketNumber); + return createPreview(ticketNumber); + }); +} diff --git a/src/components/layout/Layout.test.tsx b/src/components/layout/Layout.test.tsx index 7f20a16..8721c45 100644 --- a/src/components/layout/Layout.test.tsx +++ b/src/components/layout/Layout.test.tsx @@ -16,7 +16,11 @@ describe('Layout', () => { afterEach(cleanup); it('renders the global footer with external links only', () => { - render(

Page content

); + render( + +

Page content

+
, + ); expect(screen.getByText('Page content')).toBeInTheDocument(); const footer = screen.getByRole('contentinfo'); @@ -31,10 +35,26 @@ describe('Layout', () => { }); it('renders an uppercase text-only brand in the shell', () => { - render(

Page content

); + render( + +

Page content

+
, + ); const brandLink = screen.getByRole('link', { name: 'MEGASTERA' }); expect(brandLink).toHaveTextContent('MEGASTERA'); expect(brandLink.querySelector('svg')).not.toBeInTheDocument(); }); + + it('gives Play a wider centered shell with mobile bottom clearance', () => { + render( + +

Page content

+
, + ); + + const main = screen.getByRole('main'); + expect(main).toHaveClass('max-w-[1440px]'); + expect(main).toHaveClass('pb-[calc(env(safe-area-inset-bottom)+5rem)]'); + }); }); diff --git a/src/components/layout/Layout.tsx b/src/components/layout/Layout.tsx index 38e435d..b887644 100644 --- a/src/components/layout/Layout.tsx +++ b/src/components/layout/Layout.tsx @@ -13,10 +13,10 @@ */ import type { ReactNode } from 'react'; import { COPY } from '@/config/copy'; +import { Footer } from './Footer'; import { MobileWalletBar } from './MobileWalletBar'; import { MobileBottomNav, Nav, type NavKey } from './Nav'; import { ProfileCard } from './ProfileCard'; -import { Footer } from './Footer'; export function Layout({ active, @@ -27,6 +27,11 @@ export function Layout({ onSelect: (k: NavKey) => void; children: ReactNode; }) { + const mainMaxWidth = + active === 'planets' ? 'max-w-[1480px]' : active === 'play' ? 'max-w-[1440px]' : 'max-w-5xl'; + const mainBottomPadding = + active === 'play' ? 'pb-[calc(env(safe-area-inset-bottom)+5rem)]' : 'pb-6'; + return (
@@ -42,7 +47,11 @@ export function Layout({
-
{children}
+
+ {children} +
({ + rank, + walletAddress: `0x${String(rank).repeat(40)}` as `0x${string}`, + scoreMicros: `${rank}000000`, + effectiveMineralsPerDayMicros: `${rank}000000`, +})) satisfies LeaderboardRow[]; + +describe('LeaderboardTable', () => { + afterEach(cleanup); + + it('uses the server rank for the same tier treatment on desktop and mobile', () => { + const { container } = render( + , + ); + + const expectedTiers = new Map([ + ['1', ['gold', 'border-[var(--warning)]', 'bg-[linear-gradient(90deg,rgba(255,184,77,0.08),transparent)]']], + ['2', ['silver', 'border-[var(--text-secondary)]', 'bg-[linear-gradient(90deg,rgba(150,154,173,0.06),transparent)]']], + ['3', ['bronze', 'border-[#c58b62]', 'bg-[linear-gradient(90deg,rgba(197,139,98,0.06),transparent)]']], + ['4', ['quiet', 'border-[var(--border-strong)]', 'bg-[linear-gradient(90deg,rgba(150,154,173,0.04),transparent)]']], + ['5', ['quiet', 'border-[var(--border-strong)]', 'bg-[linear-gradient(90deg,rgba(150,154,173,0.04),transparent)]']], + ['6', ['ordinary', 'border-transparent', null]], + ]); + + const desktopRows = [...container.querySelectorAll('tbody tr')] as HTMLElement[]; + const mobileRows = [...container.querySelectorAll('[data-mobile-standings] article')] as HTMLElement[]; + + for (const [rank, [tier, badgeClass, rowClass]] of expectedTiers) { + const badges = [...container.querySelectorAll(`[data-rank="${rank}"]`)] as HTMLElement[]; + expect(badges).toHaveLength(2); + badges.forEach((badge) => { + expect(badge).toHaveAttribute('data-rank-tier', tier); + expect(badge).toHaveClass(badgeClass); + }); + + for (const rowsForViewport of [desktopRows, mobileRows]) { + const row = rowsForViewport.find((candidate) => candidate.querySelector(`[data-rank="${rank}"]`)); + expect(row).toBeDefined(); + if (rowClass) { + expect(row).toHaveClass(rowClass); + } else { + expect(row?.className).not.toMatch(/bg-\[linear-gradient/); + } + expect(row).toHaveAttribute('data-rank-tier', tier); + } + } + + const walletRows = [...container.querySelectorAll('[data-wallet-row="true"]')] as HTMLElement[]; + expect(walletRows).toHaveLength(2); + walletRows.forEach((row) => { + expect(row).toHaveClass('bg-violet-500/10'); + expect(row).toHaveClass('bg-[linear-gradient(90deg,rgba(197,139,98,0.06),transparent)]'); + expect(row).toHaveTextContent('You'); + }); + }); +}); diff --git a/src/components/leaderboard/LeaderboardTable.tsx b/src/components/leaderboard/LeaderboardTable.tsx index 08061f9..dcb54c5 100644 --- a/src/components/leaderboard/LeaderboardTable.tsx +++ b/src/components/leaderboard/LeaderboardTable.tsx @@ -14,6 +14,45 @@ function toMineralNumber(micros: string) { return Number(formatMinerals(BigInt(micros)).replaceAll(',', '')); } +type RankTier = 'gold' | 'silver' | 'bronze' | 'quiet' | 'ordinary'; + +function rankTier(rank: number): RankTier { + if (rank === 1) return 'gold'; + if (rank === 2) return 'silver'; + if (rank === 3) return 'bronze'; + if (rank === 4 || rank === 5) return 'quiet'; + return 'ordinary'; +} + +const RANK_BADGE_CLASSES: Record = { + gold: 'border-[var(--warning)] bg-[rgba(255,184,77,0.1)] text-[var(--warning)]', + silver: 'border-[var(--text-secondary)] bg-[rgba(150,154,173,0.1)] text-[var(--text-primary)]', + bronze: 'border-[#c58b62] bg-[rgba(197,139,98,0.1)] text-[#d8a27c]', + quiet: 'border-[var(--border-strong)] bg-[var(--surface-hover)] text-[var(--text-secondary)]', + ordinary: 'border-transparent bg-transparent text-[var(--text-primary)]', +}; + +const RANK_ROW_CLASSES: Record = { + gold: 'bg-[linear-gradient(90deg,rgba(255,184,77,0.08),transparent)]', + silver: 'bg-[linear-gradient(90deg,rgba(150,154,173,0.06),transparent)]', + bronze: 'bg-[linear-gradient(90deg,rgba(197,139,98,0.06),transparent)]', + quiet: 'bg-[linear-gradient(90deg,rgba(150,154,173,0.04),transparent)]', + ordinary: '', +}; + +function RankBadge({ rank }: { rank: number }) { + const tier = rankTier(rank); + return ( + + #{rank} + + ); +} + export function LeaderboardTable({ rows, walletAddress }: { rows: LeaderboardRow[]; walletAddress?: string }) { return (
@@ -24,11 +63,12 @@ export function LeaderboardTable({ rows, walletAddress }: { rows: LeaderboardRow {rows.map((row) => { const own = isWallet(row, walletAddress); + const tier = rankTier(row.rank); const score = toMineralNumber(row.scoreMicros); const perDay = toMineralNumber(row.effectiveMineralsPerDayMicros); return ( - - #{row.rank} + + {shortAddress(row.walletAddress)}{own ? You : null} @@ -40,12 +80,16 @@ export function LeaderboardTable({ rows, walletAddress }: { rows: LeaderboardRow
{rows.map((row) => { const own = isWallet(row, walletAddress); + const tier = rankTier(row.rank); const score = toMineralNumber(row.scoreMicros); const perDay = toMineralNumber(row.effectiveMineralsPerDayMicros); return ( -
- #{row.rank} - {shortAddress(row.walletAddress)} +
+ + + {shortAddress(row.walletAddress)} + {own ? You : null} +

+/day

); diff --git a/src/components/planets/GalaxyPulsePanel.test.tsx b/src/components/planets/GalaxyPulsePanel.test.tsx new file mode 100644 index 0000000..27c79cd --- /dev/null +++ b/src/components/planets/GalaxyPulsePanel.test.tsx @@ -0,0 +1,81 @@ +// @vitest-environment jsdom +import '@testing-library/jest-dom/vitest'; +import { cleanup, render, screen, within } from '@testing-library/react'; +import { afterEach, describe, expect, it } from 'vitest'; +import { GalaxyPulsePanel } from './GalaxyPulsePanel'; + +const pulse = { + drawingId: '8421', + settledAt: '2026-08-22T12:34:56.000Z', + slots: [ + { planetType: 'Gaia', modifierBps: 125 }, + { planetType: 'Gaia', modifierBps: -50 }, + { planetType: 'Volcanic', modifierBps: 0 }, + { planetType: 'Toxic', modifierBps: 100 }, + ], +} as const; + +describe('GalaxyPulsePanel', () => { + afterEach(cleanup); + + it('shows a neutral empty state when there is no active pulse', () => { + render(); + + expect(screen.getByRole('heading', { name: 'GALAXY PULSE' })).toBeInTheDocument(); + expect(screen.getAllByText('No active GALAXY PULSE')).toHaveLength(2); + expect(screen.queryByText('ACTIVE DRAWING')).not.toBeInTheDocument(); + expect(screen.queryByRole('list')).not.toBeInTheDocument(); + }); + + it('renders each raw slot in order with its type icon and signed percentage', () => { + render(); + + const panel = screen.getByTestId('galaxy-pulse-panel'); + const tooltip = screen.getByRole('tooltip'); + expect(within(panel).getByRole('heading', { name: 'GALAXY PULSE' })).toBeInTheDocument(); + expect(within(tooltip).getByText('GALAXY PULSE')).toBeInTheDocument(); + const items = within(tooltip).getAllByRole('listitem'); + expect(items).toHaveLength(4); + expect(items.map((item) => item.textContent)).toEqual([ + 'Gaia+1.25%', + 'Gaia-0.5%', + 'Volcanic+0%', + 'Toxic+1%', + ]); + expect(within(panel).getAllByText('Gaia')).toHaveLength(2); + expect(within(tooltip).getByText('DRAWING #8421')).toBeInTheDocument(); + expect(within(tooltip).getByText('Settled Aug 22, 12:34 UTC')).toBeInTheDocument(); + expect(within(tooltip).getByText('Settled Aug 22, 12:34 UTC')).toHaveAttribute( + 'datetime', + '2026-08-22T12:34:56.000Z', + ); + const icons = tooltip.querySelectorAll('img'); + expect(icons).toHaveLength(4); + expect(icons[0]).toHaveAttribute('src', '/galaxy-pulse/gaia.png'); + expect(icons[1]).toHaveAttribute('src', '/galaxy-pulse/gaia.png'); + expect(icons[2]).toHaveAttribute('src', '/galaxy-pulse/volcanic.png'); + expect(icons[3]).toHaveAttribute('src', '/galaxy-pulse/toxic.png'); + expect(icons[0]).toHaveAttribute('alt', ''); + }); + + it('exposes a detailed tooltip with the pulse explanation and effects', () => { + render(); + + const trigger = screen.getByTestId('galaxy-pulse-tooltip-trigger'); + const tooltip = screen.getByRole('tooltip'); + + expect(trigger).toHaveAttribute('type', 'button'); + expect(trigger).toHaveAttribute('aria-describedby', 'galaxy-pulse-details'); + expect(tooltip).toHaveTextContent( + 'GALAXY PULSE is a set of mining modifiers selected for this drawing.', + ); + expect(tooltip).toHaveTextContent('Each effect applies to planets of the matching type.'); + expect(within(tooltip).getByRole('heading', { name: 'Effects' })).toBeInTheDocument(); + expect(within(tooltip).getAllByRole('listitem')).toHaveLength(4); + expect( + within(tooltip) + .getAllByRole('listitem') + .map((item) => item.textContent), + ).toEqual(['Gaia+1.25%', 'Gaia-0.5%', 'Volcanic+0%', 'Toxic+1%']); + }); +}); diff --git a/src/components/planets/GalaxyPulsePanel.tsx b/src/components/planets/GalaxyPulsePanel.tsx new file mode 100644 index 0000000..a3c3989 --- /dev/null +++ b/src/components/planets/GalaxyPulsePanel.tsx @@ -0,0 +1,186 @@ +export type GalaxyPulseSlot = { + planetType: string; + modifierBps: number; +}; + +export type GalaxyPulse = { + drawingId: string; + settledAt: string; + slots: readonly GalaxyPulseSlot[]; +}; + +export type GalaxyPulsePanelProps = { + pulse: GalaxyPulse | null; +}; + +const GALAXY_PULSE_TOOLTIP_ID = 'galaxy-pulse-details'; + +const PLANET_TYPE_ICONS: Record = { + Nebula: '/galaxy-pulse/nebula.png', + Desert: '/galaxy-pulse/desert.png', + Triplex: '/galaxy-pulse/triplex.png', + Toxic: '/galaxy-pulse/toxic.png', + Void: '/galaxy-pulse/void.png', + Gaia: '/galaxy-pulse/gaia.png', + Volcanic: '/galaxy-pulse/volcanic.png', + 'Gas Giant': '/galaxy-pulse/gas-giant.png', + Rocky: '/galaxy-pulse/rocky.png', + Oceanic: '/galaxy-pulse/oceanic.png', +}; + +function formatModifierBps(modifierBps: number): string { + const value = Math.abs(modifierBps / 100) + .toFixed(2) + .replace(/\.?0+$/, ''); + return `${modifierBps < 0 ? '-' : '+'}${value}%`; +} + +function formatSettledAt(settledAt: string): string { + return new Intl.DateTimeFormat('en-US', { + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + hour12: false, + timeZone: 'UTC', + }).format(new Date(settledAt)); +} + +export function GalaxyPulsePanel({ pulse }: GalaxyPulsePanelProps) { + const previewSlotOccurrences = new Map(); + const effectSlotOccurrences = new Map(); + + return ( +
+
+
+
+

+ GALAXY PULSE +

+ {pulse ? ( + + DRAWING #{pulse.drawingId} + + ) : ( + + No active GALAXY PULSE + + )} +
+ + {pulse ? ( + + ) : null} +
+ +
+
+ ); +} diff --git a/src/components/planets/PlanetMiningOverlay.test.tsx b/src/components/planets/PlanetMiningOverlay.test.tsx index fb85ed5..ec5b34d 100644 --- a/src/components/planets/PlanetMiningOverlay.test.tsx +++ b/src/components/planets/PlanetMiningOverlay.test.tsx @@ -13,6 +13,7 @@ const mining = { effectiveMineralsPerDayMicros: '25200000', upgradeLevel: 1, upgradeBonusBps: 1000, + galaxyPulseBps: 0, nextUpgrade: { targetLevel: 2, bonusBpsAfter: 2500, costMicros: '300000' }, }; @@ -28,17 +29,19 @@ describe('PlanetMiningOverlay', () => { const boost = screen.getByText('BOOST'); expect(rate.compareDocumentPosition(boost) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); const rateTooltip = screen.getByRole('tooltip', { name: 'Minerals per day including boost' }); - const boostTooltip = screen.getByRole('tooltip', { name: 'Bonus from matching planet types' }); + const boostTooltip = screen.getByRole('tooltip', { + name: 'Matching Planets +5% Planet Level +10% Galaxy Pulse +0% Total Boost +15%', + }); expect(rateTooltip).toHaveClass('h-[22px]', 'px-2', 'text-[10px]', 'font-medium', 'duration-150', 'group-hover/metric:opacity-100'); expect(rateTooltip).not.toHaveClass('group-hover:opacity-100'); - expect(boostTooltip).toHaveClass('h-[22px]', 'px-2', 'text-[10px]', 'font-medium', 'duration-150'); - expect(boostTooltip).toHaveClass('group-hover/metric:opacity-100'); + expect(boostTooltip).toHaveClass('px-2', 'text-[10px]', 'font-medium', 'duration-150', 'group-hover/metric:opacity-100', 'group-focus/metric:opacity-100'); + expect(screen.getByText('BOOST').parentElement).toHaveAttribute('type', 'button'); expect(screen.queryByRole('tooltip', { name: 'Total minerals collected' })).not.toBeInTheDocument(); expect(screen.queryByTitle('Minerals per day after all collection bonuses')).not.toBeInTheDocument(); expect(screen.getByText('25.2')).toHaveClass('text-[var(--rare)]'); expect(screen.queryByText('24')).not.toBeInTheDocument(); expect(screen.queryByText('10.1')).not.toBeInTheDocument(); - expect(screen.getByText('+5%')).toHaveClass('text-[var(--rare)]'); + expect(screen.getByText('+15%')).toHaveClass('text-[var(--rare)]'); expect(screen.queryByText('MINERALS / DAY')).not.toBeInTheDocument(); }); @@ -48,11 +51,23 @@ describe('PlanetMiningOverlay', () => { mining={{ ...mining, sameTypeCount: 2, collectionBonusBps: 0 }} />, ); - expect(screen.getByText('+0%')).toBeInTheDocument(); - expect(screen.getByText('+0%')).toHaveClass('text-[var(--text-secondary)]'); + expect(screen.getByText('+10%')).toBeInTheDocument(); + expect(screen.getByText('+10%')).toHaveClass('text-[var(--rare)]'); + expect(screen.getByRole('tooltip', { + name: 'Matching Planets +0% Planet Level +10% Galaxy Pulse +0% Total Boost +10%', + })).toBeInTheDocument(); expect(screen.getByText('BOOST')).toBeInTheDocument(); }); + it('includes the Galaxy Pulse modifier in the boost breakdown and total', () => { + render(); + + expect(screen.getByRole('tooltip', { + name: 'Matching Planets +5% Planet Level +10% Galaxy Pulse -2.5% Total Boost +12.5%', + })).toBeInTheDocument(); + expect(screen.getByText('+12.5%')).toBeInTheDocument(); + }); + it('does not invent mining values when the backend snapshot is unavailable', () => { render(); expect(screen.getByText('Mining unavailable')).toBeInTheDocument(); @@ -70,7 +85,7 @@ describe('PlanetMiningOverlay', () => { render(); const overlay = screen.getByTestId('planet-mining-overlay'); expect(overlay).toHaveClass('inset-x-2', 'bottom-2'); - expect(overlay.querySelector(':scope > div')).toHaveClass('p-2'); + expect(overlay.querySelector(':scope > button')).toHaveClass('p-2'); expect(screen.getByText('RATE')).toBeInTheDocument(); expect(screen.getByText('BOOST')).toBeInTheDocument(); expect(screen.getByText('25.2')).toHaveClass('text-sm', 'text-[var(--rare)]'); diff --git a/src/components/planets/PlanetMiningOverlay.tsx b/src/components/planets/PlanetMiningOverlay.tsx index ade8631..970cb91 100644 --- a/src/components/planets/PlanetMiningOverlay.tsx +++ b/src/components/planets/PlanetMiningOverlay.tsx @@ -11,13 +11,12 @@ type PlanetMiningMetricsProps = { mining?: PlanetMiningSnapshot; }; -function formatCollectionBonus(bps: number): string { - return `+${bps / 100}%`; +function formatBonusBps(bps: number): string { + return `${bps < 0 ? '' : '+'}${bps / 100}%`; } const METRIC_TOOLTIPS = { rate: 'Minerals per day including boost', - boost: 'Bonus from matching planet types', } as const; function MetricTooltip({ @@ -25,26 +24,32 @@ function MetricTooltip({ description, id, className, + tooltipClassName = '', + accessibleDescription, }: { children: ReactNode; - description: string; + description: ReactNode; id: string; className: string; + tooltipClassName?: string; + accessibleDescription?: string; }) { return ( -
{children} {description} -
+ ); } @@ -56,7 +61,10 @@ function MetricsContent({ mining, size }: PlanetMiningMetricsProps & { size: Met return Mining unavailable; } - const boosted = mining.collectionBonusBps > 0; + const upgradeBonusBps = mining.upgradeBonusBps ?? 0; + const galaxyPulseBps = mining.galaxyPulseBps ?? 0; + const totalBonusBps = mining.collectionBonusBps + upgradeBonusBps + galaxyPulseBps; + const boosted = totalBonusBps > 0; const effectiveRateClass = boosted ? 'text-[var(--rare)]' : 'text-[var(--text-primary)]'; const bonusClass = boosted ? 'text-[var(--rare)]' : 'text-[var(--text-secondary)]'; const cellSpacing = size === 'compact' ? 'p-2' : 'p-3'; @@ -72,10 +80,25 @@ function MetricsContent({ mining, size }: PlanetMiningMetricsProps & { size: Met {formatMinerals(BigInt(mining.effectiveMineralsPerDayMicros))} - + + Matching Planets {formatBonusBps(mining.collectionBonusBps)} + Planet Level {formatBonusBps(upgradeBonusBps)} + Galaxy Pulse {formatBonusBps(galaxyPulseBps)} + + Total Boost {formatBonusBps(totalBonusBps)} + + + } + id={`${tooltipId}-boost`} + className={`text-center ${cellSpacing}`} + tooltipClassName="h-auto min-w-[10.5rem] whitespace-normal px-2 py-1.5 text-left leading-4" + accessibleDescription={`Matching Planets ${formatBonusBps(mining.collectionBonusBps)} Planet Level ${formatBonusBps(upgradeBonusBps)} Galaxy Pulse ${formatBonusBps(galaxyPulseBps)} Total Boost ${formatBonusBps(totalBonusBps)}`} + >

BOOST

- {formatCollectionBonus(mining.collectionBonusBps)} + {formatBonusBps(totalBonusBps)}
diff --git a/src/components/planets/PlanetTicketAction.test.tsx b/src/components/planets/PlanetTicketAction.test.tsx index ca8f4fd..6c7db9f 100644 --- a/src/components/planets/PlanetTicketAction.test.tsx +++ b/src/components/planets/PlanetTicketAction.test.tsx @@ -45,11 +45,17 @@ describe('PlanetTicketAction', () => { status={{ kind: 'claimable', amount: payout, ticketId: 456n }} />, ); - expect(screen.getByRole('button', { name: 'Claim $12.50 USDC' })).toHaveClass('bg-white', 'text-black', 'min-h-8'); + expect(screen.getByRole('button', { name: 'Claim $12.50 USDC' })).toHaveClass('bg-white', 'text-black', 'min-h-10'); rerender(); - expect(screen.getByTestId('planet-ticket-action')).toHaveClass('min-h-8'); - expect(screen.getByTestId('ticket-status-drawn')).toHaveClass('bg-zinc-800', 'text-zinc-300'); + expect(screen.getByTestId('planet-ticket-action')).toHaveClass('w-full', 'justify-center', 'sm:justify-end'); + expect(screen.getByTestId('ticket-status-drawn')).toHaveClass( + 'bg-zinc-800', + 'text-zinc-300', + 'min-h-10', + 'px-3', + 'py-2', + ); rerender(); expect(screen.getByTestId('ticket-status-claimed')).toHaveClass('bg-zinc-800', 'text-zinc-300'); @@ -58,6 +64,39 @@ describe('PlanetTicketAction', () => { expect(screen.getByTestId('ticket-status-countdown')).toHaveClass('border-amber-400', 'text-amber-200'); }); + it('uses one bounded action contract for collection cards and planet detail', () => { + const { rerender } = render( + , + ); + + const compactButton = screen.getByRole('button', { name: 'Claim $12.50 USDC' }); + const compactButtonClassName = compactButton.className; + expect(compactButton).toHaveClass('w-full', 'max-w-full', 'whitespace-nowrap', 'sm:w-auto'); + expect(screen.getByTestId('planet-ticket-action')).toHaveClass('w-full', 'items-center', 'sm:items-end'); + + rerender( + , + ); + + const detailButton = screen.getByRole('button', { name: 'Claim $12.50 USDC' }); + expect(detailButton.className).toBe(compactButtonClassName); + expect(screen.getByTestId('planet-ticket-action')).toHaveClass('w-full', 'items-center', 'sm:items-start'); + + rerender(); + const compactStatusClassName = screen.getByTestId('ticket-status-drawn').className; + expect(screen.getByTestId('planet-ticket-action')).toHaveClass('w-full', 'justify-center', 'sm:justify-end'); + expect(screen.getByTestId('ticket-status-drawn').parentElement).toHaveClass('sm:w-auto'); + + rerender(); + expect(screen.getByTestId('ticket-status-drawn').className).toBe(compactStatusClassName); + expect(screen.getByTestId('planet-ticket-action')).toHaveClass('w-full', 'justify-center', 'sm:justify-start'); + }); + it('disables the claim action while the existing claim hook is pending', () => { render( +
{claimError ? ( -

+

Claim failed — try again.

) : null} @@ -42,9 +53,13 @@ export function PlanetTicketAction({ return (
- +
span]:min-w-0 [&>span]:max-w-full [&>span]:overflow-hidden [&>span]:text-ellipsis [&>span]:whitespace-nowrap`} + > + +
); } diff --git a/src/components/planets/PlanetUpgradeAction.test.tsx b/src/components/planets/PlanetUpgradeAction.test.tsx index 87fd97d..2bbab4f 100644 --- a/src/components/planets/PlanetUpgradeAction.test.tsx +++ b/src/components/planets/PlanetUpgradeAction.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import '@testing-library/jest-dom/vitest'; -import { cleanup, fireEvent, render, screen } from '@testing-library/react'; +import { cleanup, fireEvent, render, screen, within } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { PlanetUpgradeAction } from './PlanetUpgradeAction'; @@ -9,7 +9,7 @@ const nextUpgrade = { targetLevel: 2, bonusBpsAfter: 2500, costMicros: '300000' describe('PlanetUpgradeAction', () => { afterEach(cleanup); - it('renders the enabled next-level action and sends only its target level', () => { + it('renders the enabled upgrade action and sends only its target level', () => { const onUpgrade = vi.fn(); render( { />, ); - expect(screen.getByText('Level L1')).toBeInTheDocument(); - expect(screen.getByText('Next upgrade: L2')).toBeInTheDocument(); + expect(screen.getByText('Upgrades')).toBeInTheDocument(); + expect(screen.getByText('+10%')).toBeInTheDocument(); + expect(screen.getByText('+25%')).toBeInTheDocument(); + expect(screen.getByText('+50%')).toBeInTheDocument(); expect(screen.getByText('0.3 minerals')).toBeInTheDocument(); - fireEvent.click(screen.getByRole('button', { name: 'Upgrade to L2' })); + fireEvent.click(screen.getByRole('button', { name: 'Upgrade · 0.3 minerals' })); expect(onUpgrade).toHaveBeenCalledWith(2); }); + it('renders a filled accessible 1-2-3 progression and a white costed primary action', () => { + render( + , + ); + + const progression = screen.getByTestId('upgrade-progression'); + expect(progression).toHaveAttribute('role', 'progressbar'); + expect(progression).toHaveAttribute('aria-valuenow', '1'); + expect(progression).toHaveAttribute('aria-valuetext', 'Level 1 of Level 3'); + expect(within(screen.getByTestId('upgrade-level-1')).getByText('1')).toBeInTheDocument(); + expect(within(screen.getByTestId('upgrade-level-2')).getByText('2')).toBeInTheDocument(); + expect(within(screen.getByTestId('upgrade-level-3')).getByText('3')).toBeInTheDocument(); + expect(screen.getByTestId('upgrade-level-1')).toHaveAttribute('data-state', 'current'); + expect(screen.getByTestId('upgrade-level-2')).toHaveAttribute('data-state', 'next'); + expect(screen.getByTestId('upgrade-level-3')).toHaveAttribute('data-state', 'locked'); + expect(screen.getByTestId('upgrade-level-1')).toHaveTextContent(/^1$/); + expect(screen.getByTestId('upgrade-level-2')).toHaveTextContent(/^2$/); + expect(screen.getByTestId('upgrade-level-3')).toHaveTextContent(/^3$/); + + const button = screen.getByRole('button', { name: 'Upgrade · 0.3 minerals' }); + expect(button).toHaveClass('bg-white', 'text-black'); + expect(button).toHaveTextContent('0.3 minerals'); + expect(screen.queryByText('Complete')).not.toBeInTheDocument(); + expect(screen.queryByText('Current')).not.toBeInTheDocument(); + expect(screen.queryByText('Next')).not.toBeInTheDocument(); + expect(screen.queryByText('Locked')).not.toBeInTheDocument(); + expect(screen.getByRole('tooltip', { + name: 'Upgrade to Level 2 · +25% bonus · Cost: 0.3 minerals', + })).toBeInTheDocument(); + }); + it('disables the action when the authoritative balance is insufficient', () => { render( { />, ); - expect(screen.getByRole('button', { name: 'Upgrade to L2' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Upgrade · 0.3 minerals' })).toBeDisabled(); expect(screen.getByRole('status')).toHaveTextContent('Insufficient balance'); }); @@ -56,8 +96,10 @@ describe('PlanetUpgradeAction', () => { onUpgrade={vi.fn()} />, ); - expect(screen.getByRole('button', { name: 'Upgrade to L2' })).toBeDisabled(); - expect(screen.getByRole('button', { name: 'Upgrade to L2' })).toHaveTextContent('Upgrading'); + expect(screen.getByRole('button', { name: 'Upgrade · 0.3 minerals' })).toBeDisabled(); + expect(screen.getByRole('button', { name: 'Upgrade · 0.3 minerals' })).toHaveTextContent( + 'Upgrading', + ); rerender( { expect(screen.getByText('Upgrades are disabled.')).toBeInTheDocument(); expect(screen.queryByRole('button')).not.toBeInTheDocument(); }); + + it('fills exactly the three upgrade segments at the maximum level', () => { + render( + , + ); + + const progression = screen.getByTestId('upgrade-progression'); + expect(progression.querySelectorAll('[data-testid^="upgrade-level-"]')).toHaveLength(3); + for (const level of [1, 2, 3]) { + expect(screen.getByTestId(`upgrade-level-${level}`)).toHaveAttribute( + 'data-state', + level === 3 ? 'current' : 'complete', + ); + expect(screen.getByTestId(`upgrade-level-${level}`)).toHaveClass('bg-[var(--rare)]'); + } + expect(screen.getByText('Maximum level reached.')).toBeInTheDocument(); + }); }); diff --git a/src/components/planets/PlanetUpgradeAction.tsx b/src/components/planets/PlanetUpgradeAction.tsx index 5505954..773a8c0 100644 --- a/src/components/planets/PlanetUpgradeAction.tsx +++ b/src/components/planets/PlanetUpgradeAction.tsx @@ -1,7 +1,51 @@ +import { useId, type ReactNode } from 'react'; import { Button } from '@/components/common/Button'; import type { PlanetUpgradeSnapshot } from '@/hooks/useWalletMining'; import { formatMinerals } from '@/lib/minerals'; +const UPGRADE_LEVELS = [1, 2, 3] as const; +const UPGRADE_BONUS_LABELS = ['+10%', '+25%', '+50%'] as const; + +type UpgradeLevelState = 'complete' | 'current' | 'next' | 'locked'; + +function upgradeLevelState( + level: number, + currentLevel: number, + nextUpgrade: PlanetUpgradeSnapshot | null, +): UpgradeLevelState { + if (level < currentLevel) return 'complete'; + if (level === currentLevel) return 'current'; + if (nextUpgrade?.targetLevel === level) return 'next'; + return 'locked'; +} + +function UpgradeTooltip({ + children, + id, + targetLevel, + bonusLabel, + costLabel, +}: { + children: ReactNode; + id: string; + targetLevel: number; + bonusLabel: string; + costLabel: string; +}) { + return ( + + {children} + + Upgrade to Level {targetLevel} · {bonusLabel} bonus · Cost: {costLabel} minerals + + + ); +} + type PlanetUpgradeActionProps = { upgradesEnabled: boolean; upgradeLevel: number; @@ -22,42 +66,103 @@ export function PlanetUpgradeAction({ onUpgrade, }: PlanetUpgradeActionProps) { const balanceMicros = BigInt(currentBalanceMicros); + const upgradeTooltipId = useId(); return ( -
-
-

Upgrades

- Level L{upgradeLevel} +
+

Upgrades

+
+
+ {UPGRADE_BONUS_LABELS.map((bonus) => ( + {bonus} + ))} +
+
+ {UPGRADE_LEVELS.map((level) => { + const state = upgradeLevelState(level, upgradeLevel, nextUpgrade); + const filled = state === 'complete' || state === 'current'; + return ( +
+ {level} +
+ ); + })} +
{!upgradesEnabled ? ( -

Upgrades are disabled.

+

+ Upgrades are disabled. +

) : nextUpgrade === null ? (

Maximum level reached.

- ) : (() => { - const insufficientBalance = balanceMicros < BigInt(nextUpgrade.costMicros); - const disabled = isPending || insufficientBalance; - return ( - <> -
- Next upgrade: L{nextUpgrade.targetLevel} - {formatMinerals(BigInt(nextUpgrade.costMicros))} minerals -
- {error ?

{error.message}

: null} - {insufficientBalance ?

Insufficient balance.

: null} - - - ); - })()} + ) : ( + (() => { + const insufficientBalance = balanceMicros < BigInt(nextUpgrade.costMicros); + const disabled = isPending || insufficientBalance; + const costLabel = formatMinerals(BigInt(nextUpgrade.costMicros)); + const buttonLabel = `Upgrade · ${costLabel} minerals`; + const bonusLabel = UPGRADE_BONUS_LABELS[nextUpgrade.targetLevel - 1] ?? '—'; + return ( + <> + {error ? ( +

+ {error.message} +

+ ) : null} + {insufficientBalance ? ( +

+ Insufficient balance. +

+ ) : null} + + + + + ); + })() + )}
); } diff --git a/src/components/tickets/TicketStatusBadge.tsx b/src/components/tickets/TicketStatusBadge.tsx index 75f724a..2ed98d1 100644 --- a/src/components/tickets/TicketStatusBadge.tsx +++ b/src/components/tickets/TicketStatusBadge.tsx @@ -21,7 +21,7 @@ function ClockIcon() { } const BASE = 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide'; -const COMPACT_BASE = 'inline-flex min-h-8 items-center gap-1 rounded-full border px-3 py-1 text-[10px] font-semibold uppercase tracking-wide'; +const COMPACT_BASE = 'inline-flex min-h-10 items-center gap-1 rounded-full border px-3 py-2 text-[10px] font-semibold uppercase tracking-wide'; export function TicketStatusBadge({ status, appearance = 'default' }: { status: TicketStatus; appearance?: 'default' | 'compact' }) { const base = appearance === 'compact' ? COMPACT_BASE : BASE; diff --git a/src/hooks/useMiningLeaderboard.test.ts b/src/hooks/useMiningLeaderboard.test.ts index 4a70ac1..72cc416 100644 --- a/src/hooks/useMiningLeaderboard.test.ts +++ b/src/hooks/useMiningLeaderboard.test.ts @@ -15,7 +15,7 @@ describe('backend mining fetchers', () => { }); it('loads one aggregated wallet mining snapshot', async () => { - const payload = { mining: { ownerAddress: ADDRESS, asOf: '2026-08-12T12:00:00.000Z', ownedPlanetCount: 1, currentBalanceMicros: '2', effectiveMineralsPerDayMicros: '3', upgradesEnabled: false, planets: [] } }; + const payload = { mining: { ownerAddress: ADDRESS, asOf: '2026-08-12T12:00:00.000Z', ownedPlanetCount: 1, currentBalanceMicros: '2', effectiveMineralsPerDayMicros: '3', upgradesEnabled: false, galaxyPulse: null, planets: [] } }; const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(payload), { status: 200 })); vi.stubGlobal('fetch', fetchMock); diff --git a/src/hooks/useWalletMining.test.ts b/src/hooks/useWalletMining.test.ts index 5d27413..2ffeec8 100644 --- a/src/hooks/useWalletMining.test.ts +++ b/src/hooks/useWalletMining.test.ts @@ -21,6 +21,16 @@ describe('wallet mining refresh', () => { currentBalanceMicros: '5000000', effectiveMineralsPerDayMicros: '86400000000', upgradesEnabled: true, + galaxyPulse: { + drawingId: '150', + settledAt: '2026-08-21T17:00:11.000Z', + slots: [ + { planetType: 'gaia', modifierBps: 5_000 }, + { planetType: 'nebula', modifierBps: -2_000 }, + { planetType: 'gaia', modifierBps: 1_000 }, + { planetType: 'void', modifierBps: 0 }, + ], + }, planets: [{ planetId: 'planet-1', planetType: 'Nebula', @@ -30,6 +40,7 @@ describe('wallet mining refresh', () => { effectiveMineralsPerDayMicros: '25200000', upgradeLevel: 1, upgradeBonusBps: 1000, + galaxyPulseBps: -2_000, nextUpgrade: { targetLevel: 2, bonusBpsAfter: 2500, costMicros: '300000' }, }], }, diff --git a/src/hooks/useWalletMining.ts b/src/hooks/useWalletMining.ts index 5c80ab7..d6cfd8a 100644 --- a/src/hooks/useWalletMining.ts +++ b/src/hooks/useWalletMining.ts @@ -16,9 +16,16 @@ export type PlanetMiningSnapshot = { effectiveMineralsPerDayMicros: string; upgradeLevel: number; upgradeBonusBps: number; + galaxyPulseBps: number; nextUpgrade: PlanetUpgradeSnapshot | null; }; +export type GalaxyPulseSnapshot = { + drawingId: string; + settledAt: string; + slots: Array<{ planetType: string; modifierBps: number }>; +}; + export type WalletMiningSnapshot = { ownerAddress: `0x${string}`; asOf: string; @@ -26,6 +33,7 @@ export type WalletMiningSnapshot = { currentBalanceMicros: string; effectiveMineralsPerDayMicros: string; upgradesEnabled: boolean; + galaxyPulse: GalaxyPulseSnapshot | null; planets: PlanetMiningSnapshot[]; }; @@ -60,6 +68,13 @@ function requiredInteger(value: unknown, label: string, minimum: number): number return value; } +function requiredSignedInteger(value: unknown, label: string, minimum: number, maximum: number): number { + if (typeof value !== 'number' || !Number.isInteger(value) || value < minimum || value > maximum) { + throw new Error(`Wallet mining ${label} is malformed.`); + } + return value; +} + function isWalletAddress(value: unknown): value is `0x${string}` { return typeof value === 'string' && /^0x[\da-fA-F]{40}$/.test(value); } @@ -89,6 +104,30 @@ function parseNextUpgrade(value: unknown): PlanetUpgradeSnapshot | null { }; } +function parseGalaxyPulse(value: unknown): GalaxyPulseSnapshot | null { + if (value === null || value === undefined) return null; + const pulse = requiredObject(value, 'galaxyPulse'); + if (!Array.isArray(pulse.slots) || pulse.slots.length !== 4) { + throw new Error('Wallet mining galaxyPulse.slots is malformed.'); + } + return { + drawingId: requiredMicros(pulse.drawingId, 'galaxyPulse.drawingId'), + settledAt: requiredTimestamp(pulse.settledAt, 'galaxyPulse.settledAt'), + slots: pulse.slots.map((value) => { + const slot = requiredObject(value, 'galaxyPulse slot'); + return { + planetType: requiredString(slot.planetType, 'galaxyPulse slot planetType'), + modifierBps: requiredSignedInteger( + slot.modifierBps, + 'galaxyPulse slot modifierBps', + -5_000, + 5_000, + ), + }; + }), + }; +} + function parsePlanet(value: unknown, upgradesEnabled: boolean): PlanetMiningSnapshot { const planet = requiredObject(value, 'Planet'); const upgradeLevel = planet.upgradeLevel === undefined && !upgradesEnabled @@ -111,6 +150,9 @@ function parsePlanet(value: unknown, upgradesEnabled: boolean): PlanetMiningSnap effectiveMineralsPerDayMicros: requiredMicros(planet.effectiveMineralsPerDayMicros, 'Planet effectiveMineralsPerDayMicros'), upgradeLevel, upgradeBonusBps, + galaxyPulseBps: planet.galaxyPulseBps === undefined + ? 0 + : requiredSignedInteger(planet.galaxyPulseBps, 'Planet galaxyPulseBps', -20_000, 20_000), nextUpgrade, }; } @@ -128,6 +170,7 @@ export function parseWalletMiningSnapshot(value: unknown): WalletMiningSnapshot currentBalanceMicros: requiredMicros(mining.currentBalanceMicros, 'currentBalanceMicros'), effectiveMineralsPerDayMicros: requiredMicros(mining.effectiveMineralsPerDayMicros, 'effectiveMineralsPerDayMicros'), upgradesEnabled, + galaxyPulse: parseGalaxyPulse(mining.galaxyPulse), planets: mining.planets.map((planet) => parsePlanet(planet, upgradesEnabled)), }; } diff --git a/src/pages/Landing.css b/src/pages/Landing.css index 72a3246..07813c1 100644 --- a/src/pages/Landing.css +++ b/src/pages/Landing.css @@ -98,25 +98,31 @@ gap: 14px; min-height: 52px; padding: 0 22px; + border-radius: 8px; border: 1px solid var(--landing-mineral); - background: var(--landing-mineral); - color: var(--landing-void); + background: transparent; + color: var(--landing-mineral); cursor: pointer; font-size: 0.72rem; font-weight: 700; letter-spacing: 0.08em; text-decoration: none; text-transform: uppercase; - transition: transform 180ms ease, background-color 180ms ease, color 180ms ease; + transition: + transform 180ms ease, + background-color 180ms ease, + color 180ms ease, + box-shadow 180ms ease; } .landing a.landing-button { - color: var(--landing-void); + color: var(--landing-mineral); } .landing-button:hover { - background: var(--landing-dust); border-color: var(--landing-dust); + background: rgb(174 185 255 / 0.08); + color: var(--landing-dust); transform: translateY(-2px); } @@ -243,7 +249,9 @@ width: fit-content; border-radius: 4px; filter: drop-shadow(0 3px 10px rgb(255 255 255 / 0.12)); - transition: transform 200ms ease, filter 200ms ease; + transition: + transform 200ms ease, + filter 200ms ease; } .landing-powered-by:hover { @@ -294,22 +302,18 @@ } .landing-live-jackpot-layout { - display: grid; - grid-template-columns: minmax(0, 1fr) minmax(220px, 0.34fr); - align-items: end; - gap: clamp(26px, 5vw, 80px); + display: block; } .landing-live-jackpot-main { min-width: 0; } -.landing-live-jackpot-header, -.landing-live-jackpot-footer { +.landing-live-jackpot-header { display: flex; - align-items: end; - justify-content: space-between; - gap: 18px; + align-items: flex-start; + flex-direction: column; + gap: 8px; } .landing-live-jackpot-status, @@ -330,13 +334,14 @@ .landing-live-jackpot-echo { min-width: 0; padding: 24px 0 18px; - overflow: visible; + overflow: hidden; } .landing-live-jackpot-echo .depth-text { display: block; width: fit-content; max-width: 100%; + transform-origin: left center; filter: saturate(1.08) drop-shadow(0 20px 34px rgb(0 0 0 / 0.24)); } @@ -348,20 +353,14 @@ letter-spacing: -0.07em; } -.landing-live-jackpot-footer { - align-items: end; - min-height: 126px; - padding: 18px 0 12px 28px; - border-top: 0; - border-left: 1px solid rgb(244 247 255 / 0.16); -} - -.landing-live-jackpot-footer > div { - display: grid; - gap: 5px; +.landing-live-jackpot-countdown-line { + display: flex; + align-items: baseline; + gap: 12px; + white-space: nowrap; } -.landing-live-jackpot-footer [role="timer"] { +.landing-live-jackpot-drawing-panel [role="timer"] { margin: 0; color: var(--landing-dust); font-family: "JetBrains Mono", ui-monospace, monospace; @@ -372,10 +371,7 @@ } .landing-live-jackpot-drawing-panel { - display: grid; - align-content: end; - justify-content: space-between; - gap: 22px; + display: block; } .landing-live-generator { @@ -427,6 +423,7 @@ min-height: 40px; padding: 0 15px; overflow: hidden; + border-radius: 6px; border: 1px solid rgb(174 185 255 / 0.54); background: var(--landing-mineral); color: var(--landing-void); @@ -437,8 +434,13 @@ letter-spacing: 0.08em; text-align: center; text-transform: uppercase; - box-shadow: 0 0 0 1px rgb(174 185 255 / 0.42), 0 0 22px rgb(174 185 255 / 0.2); - transition: transform 180ms ease, box-shadow 180ms ease, color 180ms ease; + box-shadow: + 0 0 0 1px rgb(174 185 255 / 0.42), + 0 0 22px rgb(174 185 255 / 0.2); + transition: + transform 180ms ease, + box-shadow 180ms ease, + color 180ms ease; } .landing-live-generator-button::before { @@ -456,7 +458,9 @@ .landing-live-generator-button:hover { color: var(--landing-void); - box-shadow: 0 0 0 1px rgb(242 241 233 / 0.62), 0 0 24px rgb(174 185 255 / 0.34); + box-shadow: + 0 0 0 1px rgb(242 241 233 / 0.62), + 0 0 24px rgb(174 185 255 / 0.34); transform: translateY(-2px); } @@ -472,7 +476,21 @@ min-width: 148px; min-height: 64px; padding-inline: 30px; + background: var(--landing-mineral); + color: var(--landing-void); font-size: 0.78rem; + box-shadow: 0 5px 14px rgb(0 0 0 / 0.28); +} + +.landing a.landing-button-primary { + color: var(--landing-void); +} + +.landing-button-primary:hover { + border-color: var(--landing-dust); + background: var(--landing-dust); + color: var(--landing-void); + box-shadow: 0 8px 18px rgb(0 0 0 / 0.34); } .landing-live-jackpot-powered-by { @@ -725,7 +743,11 @@ border-radius: 1rem; background: var(--landing-graphite); box-shadow: 0 18px 42px rgb(0 0 0 / 0.52); - transition: transform 200ms ease, background-color 200ms ease, box-shadow 200ms ease, filter 200ms ease; + transition: + transform 200ms ease, + background-color 200ms ease, + box-shadow 200ms ease, + filter 200ms ease; } .landing-my-planet-card:hover { @@ -1030,6 +1052,66 @@ white-space: nowrap; } +.landing-mining-active-players { + display: flex; + align-items: baseline; + justify-content: space-between; + gap: 12px; + padding: 11px 18px; + border-bottom: 1px solid rgb(244 247 255 / 0.12); + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.56rem; + letter-spacing: 0.12em; +} + +.landing-mining-active-players strong { + color: var(--landing-dust); + font-size: 0.82rem; + letter-spacing: 0; +} + +.landing-mining-standings-footer { + display: grid; + gap: 14px; + padding: 16px 18px 18px; + border-top: 1px solid rgb(244 247 255 / 0.16); +} + +.landing-mining-prizes { + display: grid; + gap: 8px; + color: var(--landing-dust); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.58rem; +} + +.landing-mining-prizes > span:not(.landing-mining-prizes-title) { + display: flex; + align-items: center; + gap: 8px; +} + +.landing-mining-prizes svg { + width: 14px; + height: 14px; + color: var(--warning); +} + +.landing-mining-prizes small, +.landing-mining-prizes-title { + color: var(--landing-haze); +} + +.landing-mining-prizes-title { + letter-spacing: 0.12em; +} + +.landing-mining-standings-footer .landing-button { + width: 100%; + min-width: 0; +} + .landing-mining-standings-empty { display: grid; min-height: 180px; @@ -1247,7 +1329,6 @@ .landing-planet-mechanic { border-top: 0; } - } @media (max-width: 700px) { @@ -1281,20 +1362,12 @@ gap: 0; } - .landing-live-jackpot-header, - .landing-live-jackpot-footer { + .landing-live-jackpot-header { align-items: flex-start; flex-direction: column; gap: 9px; } - .landing-live-jackpot-footer { - min-height: 0; - padding: 18px 0 0; - border-top: 1px solid rgb(244 247 255 / 0.12); - border-left: 0; - } - .landing-live-jackpot-status, .landing-live-jackpot-drawing { text-align: left; @@ -1388,5 +1461,594 @@ animation-duration: 0.01ms; animation-iteration-count: 1; } +} +/* Narrow polish for the approved Planet discovery deck. */ +.landing-button-small { + min-width: 144px; + min-height: 46px; + padding-inline: 18px; + font-size: 0.65rem; +} + +.landing-header .landing-button-small { + min-width: 0; + min-height: 42px; + padding-inline: 16px; + font-size: 0.62rem; +} + +.landing-button-primary { + min-width: 184px; + min-height: 64px; +} + +.landing-planet-mechanic > .landing-planet-stack-shell { + display: grid; + min-height: 444px; + margin-block: 30px 28px; + padding: 22px 16px 18px; + border: 1px solid rgb(244 247 255 / 0.16); + background: var(--landing-void); + place-items: center; +} + +.landing-planet-stack { + position: relative; + width: min(100%, 326px); + aspect-ratio: 0.78; + perspective: 900px; +} + +.landing-planet-stack-item { + position: absolute; + inset: 0; + cursor: grab; + transform-origin: 10% 10%; +} + +.landing-planet-stack-item:active { + cursor: grabbing; +} + +.landing-planet-card { + display: grid; + grid-template-rows: 1fr auto; + height: 100%; + overflow: hidden; + border: 1px solid var(--landing-border-strong); + background: var(--landing-graphite); + clip-path: polygon( + 0 0, + calc(100% - 20px) 0, + 100% 20px, + 100% 100%, + 20px 100%, + 0 calc(100% - 20px) + ); + box-shadow: 18px 18px 45px rgb(0 0 0 / 0.46); +} + +.landing-planet-card--legendary { + border-color: var(--landing-mineral); +} + +.landing-planet-card--epic { + border-color: var(--landing-rare); +} + +.landing-planet-card--uncommon { + border-color: var(--landing-success); +} + +.landing-planet-card-media { + position: relative; + height: auto; + aspect-ratio: 1; + overflow: hidden; + border-bottom: 1px solid var(--landing-border); + background: var(--landing-void); +} + +.landing-planet-card-media::after { + position: absolute; + inset: 0; + background: repeating-linear-gradient(0deg, transparent 0 3px, rgb(0 0 0 / 0.14) 4px); + content: ""; + pointer-events: none; +} + +.landing-planet-card-media img { + display: block; + width: 100%; + height: 100%; + object-fit: cover; + image-rendering: pixelated; + pointer-events: none; +} + +.landing-planet-card-type { + position: absolute; + top: 16px; + left: 16px; + z-index: 2; + padding: 6px 9px; + border-left: 2px solid var(--landing-mineral); + color: var(--landing-dust); + background: rgb(5 7 8 / 0.84); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.58rem; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.landing-planet-card-body { + display: grid; + gap: 12px; + padding: 16px 18px 18px; +} + +.landing-planet-card-heading, +.landing-planet-card-metrics { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; +} + +.landing-planet-card-heading h3 { + min-width: 0; + margin: 0; + overflow-wrap: anywhere; + color: var(--landing-dust); + font-size: 1.08rem; + font-weight: 600; + letter-spacing: -0.03em; +} + +.landing-planet-card-heading > span, +.landing-planet-card-metrics { + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.56rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.landing-planet-card-metrics > span:first-child { + display: inline-flex; + align-items: center; + gap: 7px; + color: var(--landing-dust); +} + +.landing-planet-card-metrics img { + width: 15px; + height: 15px; + image-rendering: pixelated; +} + +.landing-planet-stack-controls { + display: flex; + align-items: center; + gap: 14px; + margin-top: 20px; + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.56rem; + letter-spacing: 0.12em; +} + +.landing-planet-stack-drag-cue { + display: grid; + min-width: 112px; + gap: 5px; + place-items: center; +} + +.landing-planet-stack-drag-visual { + display: grid; + grid-template-columns: auto 34px auto; + align-items: center; + gap: 6px; + color: var(--landing-mineral); + font-size: 0.72rem; +} + +.landing-planet-stack-drag-visual b { + position: relative; + height: 1px; + background: currentColor; +} + +.landing-planet-stack-drag-visual b::after { + position: absolute; + top: -2px; + left: 50%; + width: 5px; + height: 5px; + border: 1px solid currentColor; + background: var(--landing-void); + content: ""; + transform: translateX(-50%) rotate(45deg); +} + +@media (prefers-reduced-motion: no-preference) { + .landing-planet-stack-drag-visual { + animation: landing-drag-cue 1.8s ease-in-out infinite; + } +} + +@keyframes landing-drag-cue { + 0%, 100% { transform: translateX(-3px); } + 50% { transform: translateX(3px); } +} + +.landing-planet-stack-controls button { + display: grid; + width: 44px; + height: 40px; + border-radius: 6px; + border: 1px solid var(--landing-border-strong); + color: var(--landing-dust); + background: transparent; + cursor: pointer; + place-items: center; +} + +.landing-planet-stack-controls button:hover, +.landing-planet-stack-controls button:focus-visible { + border-color: var(--landing-mineral); + color: var(--landing-mineral); + outline: none; +} + +@media (max-width: 700px) { + .landing-planet-mechanic > .landing-planet-stack-shell { + min-height: 420px; + margin-block: 36px 28px; + padding-inline: 10px; + } + + .landing-planet-stack { + width: min(78vw, 300px); + } + + .landing-planet-card-body { + gap: 10px; + padding: 14px; + } + + .landing-planet-card-heading h3 { + font-size: 0.98rem; + } + + .landing-planet-card-heading > span, + .landing-planet-card-metrics { + font-size: 0.52rem; + } +} + +.landing-mining-stage { + grid-template-columns: minmax(0, 1.45fr) minmax(250px, 0.85fr); + align-items: stretch; +} + +.landing-mining-upgrade-preview { + position: relative; + isolation: isolate; + display: grid; + grid-template-rows: auto auto minmax(112px, 1fr) auto auto; + min-width: 0; + padding: 18px; + border: 1px solid rgb(244 247 255 / 0.16); + background: var(--landing-graphite); +} + +.landing-mining-upgrade-preview::before { + position: absolute; + z-index: -1; + inset: 0; + background: + linear-gradient(90deg, transparent 0 49.8%, rgb(174 185 255 / 0.06) 50%, transparent 50.2%), + linear-gradient(180deg, rgb(174 185 255 / 0.04), transparent 34%); + content: ""; + pointer-events: none; +} + +.landing-mining-upgrade-header, +.landing-mining-upgrade-footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + color: var(--landing-mineral); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.56rem; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.landing-mining-upgrade-header span:last-child { + color: var(--landing-haze); +} + +.landing-mining-upgrade-gallery { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; + margin-block: 28px 16px; + align-items: stretch; +} + +.landing-mining-upgrade-stage { + position: relative; + display: grid; + grid-template-rows: minmax(0, 1fr) auto; + min-width: 0; + margin: 0; + overflow: visible; + border: 1px solid var(--landing-border-strong); + background: var(--landing-void); + box-shadow: 0 18px 40px rgb(0 0 0 / 0.16); + transition: + border-color 180ms ease, + transform 180ms ease, + box-shadow 180ms ease; +} + +.landing-mining-upgrade-stage:hover { + border-color: rgb(174 185 255 / 0.72); + box-shadow: 0 22px 48px rgb(0 0 0 / 0.28); + transform: translateY(-3px); +} + +.landing-mining-upgrade-media, +.landing-mining-upgrade-media > *, +.landing-mining-upgrade-media img, +.landing-mining-upgrade-media canvas { + display: block; + width: 100%; + aspect-ratio: 1; +} + +.landing-mining-upgrade-media { + overflow: hidden; + background: #050610; +} + +.landing-mining-upgrade-media img, +.landing-mining-upgrade-media canvas { + object-fit: cover; + image-rendering: pixelated; +} + +.landing-mining-upgrade-ornament { + position: absolute; + z-index: 3; + top: -8px; + left: 50%; + display: flex; + min-width: 34px; + height: 18px; + align-items: center; + justify-content: center; + gap: 5px; + padding-inline: 7px; + background: var(--landing-void); + transform: translateX(-50%); +} + +.landing-mining-upgrade-ornament::before, +.landing-mining-upgrade-ornament::after { + width: 8px; + height: 1px; + background: var(--landing-border-strong); + content: ""; +} + +.landing-mining-upgrade-stage--crystal .landing-mining-upgrade-ornament::before, +.landing-mining-upgrade-stage--crystal .landing-mining-upgrade-ornament::after { + display: none; +} + +.landing-mining-upgrade-ornament i { + width: 9px; + height: 9px; + border: 1px solid var(--landing-mineral); + background: color-mix(in srgb, var(--landing-mineral) 70%, transparent); + box-shadow: 0 0 12px rgb(174 185 255 / 0.38); + transform: rotate(45deg); + animation: landing-upgrade-signal 2.8s ease-in-out infinite; +} + +.landing-mining-upgrade-stage--crowned .landing-mining-upgrade-ornament i:nth-child(2) { + width: 12px; + height: 12px; + background: var(--landing-dust); +} + +.landing-mining-upgrade-stage figcaption { + display: flex; + justify-content: space-between; + gap: 8px; + padding: 9px 8px 10px; + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.5rem; + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.landing-mining-upgrade-stage figcaption span:first-child { + color: var(--landing-dust); +} + +.landing-mining-upgrade-stage--crystal { border-color: var(--landing-haze); } +.landing-mining-upgrade-stage--winged { border-color: var(--landing-mineral); } +.landing-mining-upgrade-stage--crowned { border-color: var(--landing-dust); } + +.landing-mining-upgrade-impact { + display: grid; + align-content: center; + gap: 14px; + min-height: 112px; + padding: 14px 0 16px; + border-top: 1px solid rgb(244 247 255 / 0.1); +} + +.landing-mining-upgrade-impact-header, +.landing-mining-upgrade-impact li { + display: grid; + grid-template-columns: 28px minmax(0, 1fr) 38px; + align-items: center; + gap: 10px; + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.5rem; + letter-spacing: 0.08em; +} + +.landing-mining-upgrade-impact-header { + grid-template-columns: 1fr auto; + letter-spacing: 0.12em; +} + +.landing-mining-upgrade-impact-header span:first-child, +.landing-mining-upgrade-impact strong { + color: var(--landing-dust); +} + +.landing-mining-upgrade-impact ol { + display: grid; + gap: 9px; + margin: 0; + padding: 0; + list-style: none; +} + +.landing-mining-upgrade-impact-meter { + height: 4px; + overflow: hidden; + border-radius: 2px; + background: rgb(244 247 255 / 0.1); +} + +.landing-mining-upgrade-impact-meter i { + display: block; + height: 100%; + border-radius: inherit; + background: var(--landing-mineral); + box-shadow: 0 0 10px rgb(174 185 255 / 0.42); +} + +.landing-mining-upgrade-impact li:nth-child(1) i { width: 20%; } +.landing-mining-upgrade-impact li:nth-child(2) i { width: 50%; } +.landing-mining-upgrade-impact li:nth-child(3) i { width: 100%; } + +.landing-mining-upgrade-track { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 5px; + margin: 0 0 16px; + padding: 0; + list-style: none; +} + +.landing-mining-upgrade-track li { + position: relative; + min-height: 20px; + border-top: 2px solid var(--landing-border-strong); +} + +.landing-mining-upgrade-track li:nth-child(1) { + border-color: var(--landing-haze); +} + +.landing-mining-upgrade-track li:nth-child(2) { + border-color: var(--landing-mineral); +} + +.landing-mining-upgrade-track li:nth-child(3) { + border-color: var(--landing-dust); +} + +.landing-mining-upgrade-track span { + position: absolute; + top: 7px; + left: 0; + color: var(--landing-haze); + font-family: "JetBrains Mono", ui-monospace, monospace; + font-size: 0.56rem; +} + +.landing-mining-upgrade-footer { + justify-content: flex-start; + color: var(--landing-dust); + font-size: 0.52rem; + letter-spacing: 0.08em; +} + +.landing-mining-upgrade-footer img { + width: 16px; + height: 16px; + filter: invert(1); + image-rendering: pixelated; +} + +.landing-mining-copy .landing-mining-upgrade-note { + max-width: 420px; + margin-top: 16px; + padding-left: 14px; + border-left: 2px solid var(--landing-mineral); + color: var(--landing-dust); + font-size: 0.78rem; + line-height: 1.55; +} + +.landing-mining-standings-list li { + transition: + background-color 180ms ease, + transform 180ms ease; +} + +.landing-mining-standings-list li:hover { + transform: translateX(3px); +} + +.landing-mining-standings-list li[data-rank="1"] { + background: linear-gradient(90deg, rgb(240 190 86 / 0.16), transparent 72%); +} + +.landing-mining-standings-list li[data-rank="2"] { + background: linear-gradient(90deg, rgb(201 211 229 / 0.12), transparent 72%); +} + +.landing-mining-standings-list li[data-rank="3"] { + background: linear-gradient(90deg, rgb(190 123 78 / 0.14), transparent 72%); +} + +.landing-mining-standings-list li[data-rank="4"], +.landing-mining-standings-list li[data-rank="5"] { + background: linear-gradient(90deg, rgb(174 185 255 / 0.06), transparent 72%); +} + +@keyframes landing-upgrade-signal { + 0%, 100% { opacity: 0.66; filter: brightness(0.9); } + 50% { opacity: 1; filter: brightness(1.35); } +} + +@media (max-width: 700px) { + .landing-mining-stage { + grid-template-columns: 1fr; + } + .landing-mining-upgrade-preview { + padding: 14px; + } + + .landing-mining-upgrade-gallery { + grid-template-columns: repeat(3, minmax(88px, 1fr)); + overflow-x: auto; + padding-top: 2px; + } } diff --git a/src/pages/Landing.test.tsx b/src/pages/Landing.test.tsx index 3aa3a31..de3553f 100644 --- a/src/pages/Landing.test.tsx +++ b/src/pages/Landing.test.tsx @@ -29,7 +29,9 @@ describe('Landing', () => { const { container } = render(); expect(screen.getByRole('heading', { name: /Explore\.\s*Mine\.\s*Win\./ })).toBeInTheDocument(); - expect(screen.getByText('Every ticket becomes a Planet and enters the draw.')).toBeInTheDocument(); + expect( + screen.getByText('Every ticket becomes a Planet and enters the draw.'), + ).toBeInTheDocument(); expect(container.textContent).not.toContain('Explore Planets. Win prizes.'); const poweredBy = screen.getByRole('link', { name: 'Powered by Megapot' }); expect(poweredBy).toHaveAttribute('href', 'https://megapot.io/ecosystem'); @@ -85,31 +87,60 @@ describe('Landing', () => { const ctas = screen.getAllByRole('link', { name: 'Play' }); expect(ctas.length).toBeGreaterThanOrEqual(2); expect(ctas.every((cta) => cta.getAttribute('href') === '/play')).toBe(true); - expect(container.querySelectorAll('.landing-button > span[aria-hidden="true"]')).toHaveLength(0); - expect(container.querySelector('.landing-hero-actions .landing-button')).toHaveClass('landing-button-primary'); + expect(container.querySelectorAll('.landing-button > span[aria-hidden="true"]')).toHaveLength( + 0, + ); + expect(container.querySelector('.landing-hero-actions .landing-button')).toHaveClass( + 'landing-button-primary', + ); expect(screen.queryByText('Mint Planet')).not.toBeInTheDocument(); expect( - [...container.querySelectorAll('img')] - .filter((image) => image.getAttribute('src')?.includes('/artifacts/')) - .every((image) => image.closest('.landing-planet-card, .landing-mining-planet')), + [...container.querySelectorAll('img')].some((image) => + image.getAttribute('src')?.includes('/landing/'), + ), ).toBe(true); + expect( + [...container.querySelectorAll('img')].some((image) => + image.getAttribute('src')?.includes('/artifacts/'), + ), + ).toBe(false); }); - it('explains the two linked mechanics in one compact block', () => { + it('explains the two linked mechanics in one compact block and keeps the discovery deck in the Planet slot', () => { const { container } = render(); const landing = within(container); expect(container.querySelectorAll('.landing > main > section')).toHaveLength(4); - expect(landing.getByRole('region', { name: /One ticket\.\s*One Planet\./ })).toBeInTheDocument(); - expect(landing.getByRole('heading', { name: /One ticket\.\s*One Planet\./ })).toBeInTheDocument(); + expect( + landing.getByRole('region', { name: /One ticket\.\s*One Planet\./ }), + ).toBeInTheDocument(); + expect( + landing.getByRole('heading', { name: /One ticket\.\s*One Planet\./ }), + ).toBeInTheDocument(); expect(landing.getByRole('heading', { name: 'Megapot Tickets' })).toBeInTheDocument(); expect(landing.getByRole('heading', { name: 'Planets' })).toBeInTheDocument(); - expect(landing.getByRole('region', { name: /Keep mining\.\s*Climb higher\./ })).toBeInTheDocument(); - expect(landing.getByRole('heading', { name: /Keep mining\.\s*Climb higher\./ })).toBeInTheDocument(); - expect(landing.getByText(/ticket numbers become the coordinates that generate your Planet/i)).toBeInTheDocument(); - expect(landing.getByText(/Every Planet is unique and keeps mining minerals after the draw/i)).toBeInTheDocument(); - expect(landing.getByText(/enters the Megapot draw and can win the jackpot/i)).toBeInTheDocument(); - expect(landing.queryByText(/tied to that ticket, mines minerals and competes on the leaderboard/i)).not.toBeInTheDocument(); + expect( + landing.getByRole('region', { name: /Keep mining\.\s*Upgrade\.\s*Climb higher\./ }), + ).toBeInTheDocument(); + expect( + landing.getByRole('heading', { name: /Keep mining\.\s*Upgrade\.\s*Climb higher\./ }), + ).toBeInTheDocument(); + expect( + landing.getByText(/Spend mined Minerals to upgrade production and climb the leaderboard/i), + ).toBeInTheDocument(); + expect(container.querySelectorAll('[data-testid="landing-upgrade-stage"]')).toHaveLength(3); + expect( + landing.getByText(/ticket numbers become the coordinates that generate your Planet/i), + ).toBeInTheDocument(); + expect( + landing.getByText(/Every Planet is unique and keeps mining minerals after the draw/i), + ).toBeInTheDocument(); + expect( + landing.getByText(/enters the Megapot draw and can win the jackpot/i), + ).toBeInTheDocument(); + expect( + landing.queryByText(/tied to that ticket, mines minerals and competes on the leaderboard/i), + ).not.toBeInTheDocument(); expect(landing.queryByText('PLANET COORDINATES')).not.toBeInTheDocument(); expect(container.textContent).not.toContain('01 / MEGAPOT TICKET'); expect(container.textContent).not.toContain('ONE TICKET'); @@ -118,6 +149,7 @@ describe('Landing', () => { expect(container.querySelector('.landing-mechanics-connection')).not.toBeInTheDocument(); expect(landing.queryByText('PLANET = TICKET')).not.toBeInTheDocument(); expect(landing.queryByText('MEGAPOT · IN DRAW')).not.toBeInTheDocument(); + const generatePlanetButton = landing.getByRole('button', { name: 'Tap' }); expect(generatePlanetButton).toBeInTheDocument(); expect(generatePlanetButton).not.toHaveTextContent('↗'); @@ -125,36 +157,65 @@ describe('Landing', () => { expect(generatePlanetButton).not.toHaveAttribute('title'); expect(generatePlanetButton.closest('.landing-live-generator-art')).toBeTruthy(); expect(container.querySelector('.landing-megapot-ticket')).toBeInTheDocument(); - expect(container.querySelector('.landing-ticket-visual-stack')).toHaveClass('landing-ticket-visual-stack--vertical'); + expect(container.querySelector('.landing-ticket-visual-stack')).toHaveClass( + 'landing-ticket-visual-stack--vertical', + ); expect(container.querySelectorAll('.landing-megapot-ticket')).toHaveLength(3); expect(container.querySelectorAll('.landing-ticket-ball')).toHaveLength(18); expect(container.querySelectorAll('.landing-ticket-ball-bonus')).toHaveLength(3); - expect(container.querySelectorAll('.landing-my-planet-card')).toHaveLength(3); - expect(container.querySelector('.landing-my-planet-card')).toHaveAttribute('data-rarity', 'Common'); - expect(container.querySelectorAll('.landing-my-planet-card-media')).toHaveLength(3); - expect(container.querySelectorAll('.landing-my-planet-card-minerals')).toHaveLength(3); - expect(landing.getByText('Draheunia')).toBeInTheDocument(); - expect(landing.getByText('Ticket #5001')).toBeInTheDocument(); - expect(landing.getByText('TICKET / 5001')).toBeInTheDocument(); - expect(landing.getByText('TICKET / 5005')).toBeInTheDocument(); - expect(landing.getByText('TICKET / 5009')).toBeInTheDocument(); - expect(landing.getByText('25')).toBeInTheDocument(); + + const carousel = landing.getByRole('region', { name: 'Planet discovery carousel' }); + expect(carousel.closest('.landing-planet-mechanic')).toBeTruthy(); + expect(carousel.querySelectorAll('.landing-planet-card')).toHaveLength(7); + expect(carousel.querySelectorAll('[data-active="true"]')).toHaveLength(1); + expect(carousel.querySelector('[data-active="true"] img')).toHaveAttribute( + 'src', + expect.stringContaining('/landing/gifs-512/'), + ); + expect( + [...carousel.querySelectorAll('[data-active="false"] img')].every((image) => + image.getAttribute('src')?.endsWith('.png'), + ), + ).toBe(true); + expect(landing.getByRole('region', { name: /How it works/i })).toBeInTheDocument(); expect(container.querySelectorAll('.landing-how-it-works details')).toHaveLength(8); expect(landing.queryByText('The core loop')).not.toBeInTheDocument(); expect(landing.queryByText('Explore. Reveal. Compete.')).not.toBeInTheDocument(); expect(landing.queryByText('No two discoveries')).not.toBeInTheDocument(); expect(landing.queryByText('feel the same.')).not.toBeInTheDocument(); - expect(landing.queryByRole('region', { name: /Circular Planet gallery/ })).not.toBeInTheDocument(); + expect( + landing.queryByRole('region', { name: /Circular Planet gallery/ }), + ).not.toBeInTheDocument(); expect(container.querySelector('.landing-hero-lightfall')).not.toBeInTheDocument(); expect(container.querySelector('.landing-live-jackpot')).toBeInTheDocument(); expect(landing.getByText('LIVE JACKPOT')).toBeInTheDocument(); expect(landing.getByText('DRAWING IN')).toBeInTheDocument(); expect(container.querySelector('.landing-mystery-orbit')).not.toBeInTheDocument(); expect(container.querySelectorAll('.landing-mystery-orbit .orbit-item')).toHaveLength(0); - expect(container.querySelectorAll('.landing-hero-title .split-parent')).toHaveLength(2); - expect([...container.querySelectorAll('img')].filter((image) => image.getAttribute('src')?.includes('/artifacts/')).length).toBeGreaterThanOrEqual(3); - expect([...container.querySelectorAll('img')].filter((image) => image.getAttribute('alt')?.startsWith('Unrevealed'))).toHaveLength(0); + expect( + [...container.querySelectorAll('img')].filter((image) => + image.getAttribute('src')?.includes('/landing/'), + ).length, + ).toBeGreaterThanOrEqual(3); + expect( + [...container.querySelectorAll('img')].some((image) => + image.getAttribute('src')?.includes('/artifacts/'), + ), + ).toBe(false); + expect( + [...container.querySelectorAll('img')].filter((image) => + image.getAttribute('alt')?.startsWith('Unrevealed'), + ), + ).toHaveLength(0); + }); + + it('does not retain the rejected full-page game-loop copy or stage', () => { + render(); + + expect(screen.queryByText('A ticket is only the beginning.')).not.toBeInTheDocument(); + expect(screen.queryByRole('region', { name: 'How the game works' })).not.toBeInTheDocument(); + expect(screen.queryByRole('figure', { name: 'Planet mining monitor' })).not.toBeInTheDocument(); }); it('uses SplitText across every landing copy block', () => { @@ -166,9 +227,7 @@ describe('Landing', () => { '.landing-hero-subtitle.split-parent', '.landing-hero-actions .landing-button .split-parent', '.landing-live-jackpot-header .landing-kicker.split-parent', - '.landing-live-jackpot-status.split-parent', - '.landing-live-jackpot-footer .landing-micro-label.split-parent', - '.landing-live-jackpot-drawing.split-parent', + '.landing-live-jackpot-header .landing-micro-label.split-parent', '.landing-live-generator-button .split-parent', '.landing-mechanics-heading .landing-kicker.split-parent', '.landing-mechanics-heading h2 .split-parent', @@ -185,7 +244,6 @@ describe('Landing', () => { '.landing-how-it-works .landing-faq-question.split-parent', '.landing-how-it-works .landing-faq-answer.split-parent', '.landing-footer .landing-wordmark .split-parent', - '.landing-footer .landing-footer-meta.split-parent', ]; for (const selector of animatedCopySelectors) { diff --git a/src/pages/Landing.tsx b/src/pages/Landing.tsx index f12b12b..2209c4b 100644 --- a/src/pages/Landing.tsx +++ b/src/pages/Landing.tsx @@ -1,18 +1,42 @@ import './Landing.css'; import { useEffect } from 'react'; -import { COPY } from '@/config/copy'; -import { LandingLiveJackpot } from '@/components/landing/LandingLiveJackpot'; import { LandingHowItWorks } from '@/components/landing/LandingHowItWorks'; +import { LandingLiveJackpot } from '@/components/landing/LandingLiveJackpot'; import { LandingMiningLeaderboard } from '@/components/landing/LandingMiningLeaderboard'; -import { LandingPlanetCard } from '@/components/landing/LandingPlanetCard'; import { LandingSplitText } from '@/components/landing/LandingSplitText'; +import { PlanetCardStack } from '@/components/landing/PlanetCardStack'; import { PlanetGeneratorHero } from '@/components/landing/PlanetGeneratorHero'; import { FOOTER_LINKS } from '@/components/layout/Footer'; +import { COPY } from '@/config/copy'; const generatedPlanetAssets = [ - { image: '/artifacts/megastera-generated/planet-01.gif', name: 'Draheunia', rarity: 'Common', ticketId: '5001', minerals: 25, numbers: [7, 14, 18, 23, 29], bonus: 3 }, - { image: '/artifacts/megastera-generated/planet-05.gif', name: 'Wheuagawa III', rarity: 'Uncommon', ticketId: '5005', minerals: 75, numbers: [4, 11, 19, 27, 36], bonus: 8 }, - { image: '/artifacts/megastera-generated/planet-09.gif', name: 'Auclagua-94', rarity: 'Common', ticketId: '5009', minerals: 10, numbers: [2, 13, 21, 30, 37], bonus: 6 }, + { + image: '/landing/gifs-512/planet-006.gif', + name: 'Draheunia', + rarity: 'Common', + ticketId: '5001', + minerals: 25, + numbers: [7, 14, 18, 23, 29], + bonus: 3, + }, + { + image: '/landing/gifs-512/planet-055.gif', + name: 'Wheuagawa III', + rarity: 'Uncommon', + ticketId: '5005', + minerals: 75, + numbers: [4, 11, 19, 27, 36], + bonus: 8, + }, + { + image: '/landing/gifs-512/planet-092.gif', + name: 'Auclagua-94', + rarity: 'Common', + ticketId: '5009', + minerals: 10, + numbers: [2, 13, 21, 30, 37], + bonus: 6, + }, ] as const; export function Landing() { @@ -26,7 +50,9 @@ export function Landing() { return (
-
+

- +
- - + +
- +
- - + +

))}
-

+

+ +

); diff --git a/src/pages/Leaderboard.test.tsx b/src/pages/Leaderboard.test.tsx index 6d06eac..551c805 100644 --- a/src/pages/Leaderboard.test.tsx +++ b/src/pages/Leaderboard.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import '@testing-library/jest-dom/vitest'; -import userEvent from '@testing-library/user-event'; import { act, cleanup, render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; const refreshMocks = vi.hoisted(() => ({ current: vi.fn(), wallet: vi.fn() })); @@ -69,8 +69,11 @@ describe('Leaderboard', () => { expect(screen.queryByText(/Current lifetime mining/)).not.toBeInTheDocument(); expect(screen.getByText('Active players').parentElement).toHaveTextContent('2'); const details = screen.getByRole('complementary', { name: 'Leaderboard details' }); - expect(within(details).getByRole('region', { name: 'Season overview' })).toHaveTextContent('USDC'); - expect(within(details).getByRole('region', { name: 'Season overview' })).toHaveTextContent('1/1 NFT Planets'); + const seasonOverview = within(details).getByRole('region', { name: 'Season overview' }); + expect(seasonOverview).toHaveTextContent('Megapot Tickets'); + expect(seasonOverview).toHaveTextContent('(USDC)'); + expect(seasonOverview).toHaveTextContent('1/1 NFT Planets'); + expect(seasonOverview.querySelectorAll('svg[aria-hidden="true"]')).toHaveLength(2); expect(screen.queryByText('LIVE MINERAL SCORE')).not.toBeInTheDocument(); expect(screen.queryByText('LIVE · GENERATED AT + BASE RATE')).not.toBeInTheDocument(); expect(screen.queryByText(/As of Aug 12/)).not.toBeInTheDocument(); diff --git a/src/pages/Leaderboard.tsx b/src/pages/Leaderboard.tsx index dcc02a5..4c8f2cf 100644 --- a/src/pages/Leaderboard.tsx +++ b/src/pages/Leaderboard.tsx @@ -2,12 +2,17 @@ import { useEffect, useState } from 'react'; import { useAccount } from 'wagmi'; import { Button } from '@/components/common/Button'; import { FadeArc } from '@/components/common/FadeArc'; +import { PlanetIcon, TicketsIcon } from '@/components/icons/TicketsIcon'; import { LeaderboardTable } from '@/components/leaderboard/LeaderboardTable'; import { WalletRankCard } from '@/components/leaderboard/WalletRankCard'; import { useCurrentLeaderboard, useWalletLeaderboardPosition } from '@/hooks/useLeaderboard'; const SEASON_END_AT = Date.parse('2026-08-28T23:59:00.000Z'); -const SEASON_REWARDS = ['USDC', '1/1 NFT Planets'] as const; + +const SEASON_REWARDS = [ + { label: 'Megapot Tickets', detail: '(USDC)', icon: TicketsIcon }, + { label: '1/1 NFT Planets', detail: null, icon: PlanetIcon }, +] as const; function relativeTimeLabel(timestamp: number | undefined, now: number) { if (!timestamp || !Number.isFinite(timestamp)) return 'waiting for first refresh'; @@ -82,8 +87,14 @@ export function Leaderboard() {

Season prizes

-
- {SEASON_REWARDS.map((reward) => {reward})} +
+ {SEASON_REWARDS.map(({ label, detail, icon: Icon }, index) => ( +
0 ? 'border-t border-[var(--border)] pt-2' : ''}`}> + + {label} + {detail ? {detail} : null} +
+ ))}
@@ -98,18 +109,19 @@ export function Leaderboard() { return (
-
+

Leaderboard

-
-
+
+
Active players {data?.total.toLocaleString() ?? '—'}
- Last refresh: {relativeTimeLabel(lastRefreshAt, now)} + Last refresh: {relativeTimeLabel(lastRefreshAt, now)} -
+
-
- +
+
); } -type TicketCoordinatesValue = Pick; +type TicketCoordinatesValue = Pick< + BackendPlanet['ticket'], + 'ticketId' | 'drawingId' | 'normals' | 'bonusBall' +>; function TicketCoordinates({ ticket }: { ticket: TicketCoordinatesValue }) { return ( -
+

Ticket coordinates

- DRAWING #{ticket.drawingId} + + DRAWING #{ticket.drawingId} +
{ticket.normals.map((coordinate) => ( - + {coordinate} ))} - + {ticket.bonusBall}
@@ -155,14 +274,24 @@ function TicketCoordinates({ ticket }: { ticket: TicketCoordinatesValue }) { function WinningNumbers({ winningNumbers }: { winningNumbers: MegapotWinningNumbers }) { return ( -
+

Winning numbers

{winningNumbers.normals.map((number) => ( ))} - +
); @@ -186,30 +315,52 @@ function TicketBlock({ originTxHash: string; }) { return ( -
+

Ticket

- DRAWING #{ticket.drawingId} + + DRAWING #{ticket.drawingId} +

Your numbers

{ticket.normals.map((coordinate) => ( - + {coordinate} ))} - + {ticket.bonusBall}
{winningNumbers ? : null}
- +
- + View source ticket receipt ↗
@@ -237,20 +388,41 @@ function PendingPlanetCard({
-
✦
+
+ ✦ +

PLANET GENERATION PENDING

-

The ticket is safe

-

Your receipt is saved. The backend will finish this Planet automatically.

+

+ The ticket is safe +

+

+ Your receipt is saved. The backend will finish this Planet automatically. +

- TICKET #{row.ticket.ticketId} - DRAWING #{row.ticket.drawingId} + + TICKET #{row.ticket.ticketId} + + + DRAWING #{row.ticket.drawingId} +
- -
@@ -275,19 +447,41 @@ function TicketOnlyCard({
-
TKT
+
+ TKT +

MEGAPOT TICKET

-

No Megastera planet attached

-

This wallet ticket was not purchased through the Megastera site.

+

+ No Megastera planet attached +

+

+ This wallet ticket was not purchased through the Megastera site. +

- TICKET #{ticket.user_ticket_id} - DRAWING #{ticket.round_id} + + TICKET #{ticket.user_ticket_id} + + + DRAWING #{ticket.round_id} +
- - + +
); @@ -305,7 +499,6 @@ function DetailValue({ label, value }: { label: string; value: string | number } function PlanetDetail({ planet, mining, - onBack, ticketStatus, round, onClaim, @@ -319,7 +512,6 @@ function PlanetDetail({ }: { planet: BackendPlanet; mining?: PlanetMiningSnapshot; - onBack?: () => void; ticketStatus: TicketStatus; round?: Round; onClaim: () => void; @@ -333,15 +525,14 @@ function PlanetDetail({ }) { const winningNumbers = round?.status === 'settled' ? round.winning_numbers : null; return ( -
- {onBack ? ( -
- -
- ) : null} -
+
+
{`${planet.name}
-

{planet.name}

+

+ {planet.name} +

-
-

Details

+
+

+ Details +

@@ -408,8 +607,11 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp const [claimingTicketId, setClaimingTicketId] = useState(null); const [retryingKey, setRetryingKey] = useState(null); const [generationError, setGenerationError] = useState(null); - const [locallyConfirmedTickets, setLocallyConfirmedTickets] = useState([]); + const [locallyConfirmedTickets, setLocallyConfirmedTickets] = useState< + readonly PurchasedTicket[] + >([]); const [manualRefreshing, setManualRefreshing] = useState(false); + const [collectionSort, setCollectionSort] = useState('newest'); const siteRows = planets.data ?? []; useEffect(() => { @@ -423,14 +625,16 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp setLocallyConfirmedTickets( persisted.flatMap((ticket) => ticket.originTxHash !== null && ticket.logIndex !== null - ? [{ - ticketId: ticket.ticketId, - drawingId: ticket.drawingId, - normals: ticket.normals, - bonusBall: ticket.bonusBall, - originTxHash: ticket.originTxHash, - logIndex: ticket.logIndex, - }] + ? [ + { + ticketId: ticket.ticketId, + drawingId: ticket.drawingId, + normals: ticket.normals, + bonusBall: ticket.bonusBall, + originTxHash: ticket.originTxHash, + logIndex: ticket.logIndex, + }, + ] : [], ), ); @@ -448,46 +652,90 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp [locallyConfirmedTickets, siteRows, ticketHistory.tickets], ); const generatedRows = useMemo( - () => siteRows.filter((row): row is BackendPlanetCollectionRow & { planet: BackendPlanet } => row.generationStatus === 'generated' && row.planet !== null), + () => + siteRows.filter( + (row): row is BackendPlanetCollectionRow & { planet: BackendPlanet } => + row.generationStatus === 'generated' && row.planet !== null, + ), [siteRows], ); const miningByPlanetId = useMemo( () => new Map((mining.data?.planets ?? []).map((item) => [item.planetId, item] as const)), [mining.data?.planets], ); + const sortedCollection = useMemo(() => { + const generated = collection + .map((item, index) => ({ item, index })) + .filter(({ item }) => item.kind === 'site' && item.site.planet !== null) + .sort( + (left, right) => + compareGeneratedPlanets(left.item, right.item, collectionSort, miningByPlanetId) || + left.index - right.index, + ) + .map(({ item }) => item); + let generatedIndex = 0; + return collection.map((item) => { + if (item.kind !== 'site' || item.site.planet === null) return item; + const next = generated[generatedIndex]; + generatedIndex += 1; + return next ?? item; + }); + }, [collection, collectionSort, miningByPlanetId]); const ticketsById = useMemo( () => new Map(ticketHistory.tickets.map((ticket) => [ticket.user_ticket_id, ticket] as const)), [ticketHistory.tickets], ); - const selectedPlanetForRound = generatedRows.find((row) => row.planet.planetId === selectedPlanetId)?.planet; - const selectedRound = useRound(selectedPlanetForRound?.ticket.drawingId, { pollUntilSettled: true }); + const selectedPlanetForRound = generatedRows.find( + (row) => row.planet.planetId === selectedPlanetId, + )?.planet; + const selectedRound = useRound(selectedPlanetForRound?.ticket.drawingId, { + pollUntilSettled: true, + }); const ticketStatusByTicketId = useMemo( - () => new Map( - collection.map((item) => { - const ticket = item.kind === 'site' ? item.site.ticket : { - ticketId: item.apiTicket.user_ticket_id, - drawingId: item.apiTicket.round_id, - normals: item.apiTicket.normals, - bonusBall: item.apiTicket.bonusball, - }; - return [ticket.ticketId, deriveTicketStatus({ - ticketId: ticket.ticketId, - drawingId: ticket.drawingId, - currentDrawingId: jackpot.drawingId, - phase: jackpot.phase, - drawingStateLoading: jackpot.isLoading, - drawingTime: jackpot.state?.drawingTime, - nowMs, - apiTicket: ticketsById.get(ticket.ticketId), - })] as const; - }), - ), - [collection, jackpot.drawingId, jackpot.isLoading, jackpot.phase, jackpot.state?.drawingTime, nowMs, ticketsById], + () => + new Map( + collection.map((item) => { + const ticket = + item.kind === 'site' + ? item.site.ticket + : { + ticketId: item.apiTicket.user_ticket_id, + drawingId: item.apiTicket.round_id, + normals: item.apiTicket.normals, + bonusBall: item.apiTicket.bonusball, + }; + return [ + ticket.ticketId, + deriveTicketStatus({ + ticketId: ticket.ticketId, + drawingId: ticket.drawingId, + currentDrawingId: jackpot.drawingId, + phase: jackpot.phase, + drawingStateLoading: jackpot.isLoading, + drawingTime: jackpot.state?.drawingTime, + nowMs, + apiTicket: ticketsById.get(ticket.ticketId), + }), + ] as const; + }), + ), + [ + collection, + jackpot.drawingId, + jackpot.isLoading, + jackpot.phase, + jackpot.state?.drawingTime, + nowMs, + ticketsById, + ], ); - const shouldTickCountdown = jackpot.phase === 'open' && jackpot.drawingId !== undefined && collection.some((item) => { - const drawingId = item.kind === 'site' ? item.site.ticket.drawingId : item.apiTicket.round_id; - return BigInt(drawingId) === jackpot.drawingId; - }); + const shouldTickCountdown = + jackpot.phase === 'open' && + jackpot.drawingId !== undefined && + collection.some((item) => { + const drawingId = item.kind === 'site' ? item.site.ticket.drawingId : item.apiTicket.round_id; + return BigInt(drawingId) === jackpot.drawingId; + }); useEffect(() => { if (routePlanetId) { @@ -536,28 +784,85 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp } }; - const refreshing = manualRefreshing || planets.isFetching || ticketHistory.isFetching || mining.isFetching || selectedRound.isFetching; + const refreshing = + manualRefreshing || + planets.isFetching || + ticketHistory.isFetching || + mining.isFetching || + selectedRound.isFetching; if (!address) { - return onNavigate('play')}>Explore} />; + return ( + onNavigate('play')}> + Explore + + } + /> + ); } if (planets.isLoading && !planets.data) { return ( -
- -

Loading My Planets

-

Reading the backend registry and the complete Megapot wallet ticket list…

+
+ +

+ Loading My Planets +

+

+ Reading the backend registry and the complete Megapot wallet ticket list… +

); } if (collection.length === 0 && (planets.isError || ticketHistory.error)) { - return void handleRefresh()}>Refresh} role="alert" />; + return ( + void handleRefresh()}> + Refresh + + } + role="alert" + /> + ); } - if (!collection.length) return onNavigate('play')}>Explore} />; + if (!collection.length) + return ( + onNavigate('play')}> + Explore + + } + /> + ); const selected = generatedRows.find((row) => row.planet.planetId === selectedPlanetId)?.planet; if (routePlanetId && !selected) { - return onNavigate('planets')}>Back to My Planets} />; + return ( + onNavigate('planets')}> + Back to My Planets + + } + /> + ); } const claimTicket = (ticketId: string) => { @@ -587,18 +892,19 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp setSelectedPlanetId(planetId); onViewPlanet(planetId); }; - const clearRoute = () => onNavigate('planets'); - const selectedTicketStatus = selected ? ticketStatusByTicketId.get(selected.ticket.ticketId) ?? UNAVAILABLE_TICKET_STATUS : UNAVAILABLE_TICKET_STATUS; + const selectedTicketStatus = selected + ? (ticketStatusByTicketId.get(selected.ticket.ticketId) ?? UNAVAILABLE_TICKET_STATUS) + : UNAVAILABLE_TICKET_STATUS; const upgradePlanet = (planetId: string, targetLevel: number) => { upgrade.reset(); upgrade.mutate({ planetId, targetLevel }); }; - const upgradeMatchesSelected = selected !== undefined && upgrade.variables?.planetId === selected.planetId; + const upgradeMatchesSelected = + selected !== undefined && upgrade.variables?.planetId === selected.planetId; const detail = selected ? ( claimTicket(selected.ticket.ticketId)} @@ -611,23 +917,34 @@ export function Planets({ onNavigate, onViewPlanet, routePlanetId }: PlanetsProp upgradeError={upgradeMatchesSelected ? upgrade.error : null} /> ) : null; - const totalRate = mining.data?.effectiveMineralsPerDayMicros ? `${formatMinerals(BigInt(mining.data.effectiveMineralsPerDayMicros))}/day` : '—'; - const totalBalance = mining.data?.currentBalanceMicros && mining.data.asOf ? ( - - ) : '—'; + const totalRate = mining.data?.effectiveMineralsPerDayMicros + ? `${formatMinerals(BigInt(mining.data.effectiveMineralsPerDayMicros))}/day` + : '—'; + const totalBalance = + mining.data?.currentBalanceMicros && mining.data.asOf ? ( + + ) : ( + '—' + ); const generatedCount = generatedRows.length; return (
-
+
-

My Planets

+

+ My Planets +

-
+ +
- + - {planets.isError ?
The Megastera site registry is temporarily unavailable. Wallet tickets remain visible; refresh to retry Planet rows.
: null} - {ticketHistory.error ?
Megapot ticket statuses are temporarily unavailable. Site Planet rows remain visible.
: null} - {generationError ?
{generationError.message}
: null} - {mining.isError ?
Mining is temporarily unavailable. Planet details remain available.
: null} + {planets.isError ? ( +
+ The Megastera site registry is temporarily unavailable. Wallet tickets remain visible; + refresh to retry Planet rows. +
+ ) : null} + {ticketHistory.error ? ( +
+ Megapot ticket statuses are temporarily unavailable. Site Planet rows remain visible. +
+ ) : null} + {generationError ? ( +
+ {generationError.message} +
+ ) : null} + {mining.isError ? ( +
+ Mining is temporarily unavailable. Planet details remain available. +
+ ) : null}
+
+ + +
- {collection.map((item: MegasteraCollectionItem) => { + {sortedCollection.map((item: MegasteraCollectionItem) => { if (item.kind === 'ticket-only') { const ticketId = item.apiTicket.user_ticket_id; - return claimTicket(ticketId)} isClaimPending={ticketId === claimingTicketId && claim.isPending} claimError={ticketId === claimingTicketId ? claim.error : null} />; + return ( + claimTicket(ticketId)} + isClaimPending={ticketId === claimingTicketId && claim.isPending} + claimError={ticketId === claimingTicketId ? claim.error : null} + /> + ); } const ticketId = item.site.ticket.ticketId; const status = ticketStatusByTicketId.get(ticketId) ?? UNAVAILABLE_TICKET_STATUS; if (!item.site.planet) { - return void retryGeneration(item.site, item.key)} retrying={retryingKey === item.key} onClaim={() => claimTicket(ticketId)} isClaimPending={ticketId === claimingTicketId && claim.isPending} claimError={ticketId === claimingTicketId ? claim.error : null} />; + return ( + void retryGeneration(item.site, item.key)} + retrying={retryingKey === item.key} + onClaim={() => claimTicket(ticketId)} + isClaimPending={ticketId === claimingTicketId && claim.isPending} + claimError={ticketId === claimingTicketId ? claim.error : null} + /> + ); } const planet = item.site.planet; - return selectPlanet(planet.planetId)} ticketStatus={status} onClaim={() => claimTicket(ticketId)} isClaimPending={ticketId === claimingTicketId && claim.isPending} claimError={ticketId === claimingTicketId ? claim.error : null} />; + return ( + selectPlanet(planet.planetId)} + ticketStatus={status} + onClaim={() => claimTicket(ticketId)} + isClaimPending={ticketId === claimingTicketId && claim.isPending} + claimError={ticketId === claimingTicketId ? claim.error : null} + /> + ); })}
- -
- -
- {routePlanetId ? detail : null} + {detail ? ( + + ) : null}
); } -function EmptyState({ title, description, action, role }: { title: string; description: string; action?: import('react').ReactNode; role?: 'status' | 'alert' }) { +function EmptyState({ + title, + description, + action, + role, +}: { + title: string; + description: string; + action?: import('react').ReactNode; + role?: 'status' | 'alert'; +}) { return ( -
+

{title}

{description}

{action ?
{action}
: null} diff --git a/src/pages/Play.tsx b/src/pages/Play.tsx index d887dd6..522fba7 100644 --- a/src/pages/Play.tsx +++ b/src/pages/Play.tsx @@ -261,7 +261,7 @@ export function Play() { } return ( -
+
{phase !== 'open' && Tickets are paused until the next drawing opens.} {content} {isBulk && bulk.minimumTicketCount !== undefined && !meetsBulkMinimum && !flowActive && ( diff --git a/vercel.json b/vercel.json index 92a09db..3b86225 100644 --- a/vercel.json +++ b/vercel.json @@ -2,6 +2,9 @@ "$schema": "https://openapi.vercel.sh/vercel.json", "installCommand": "pnpm install --frozen-lockfile", "buildCommand": "pnpm build", + "crons": [ + { "path": "/api/internal/leaderboard-worker", "schedule": "5 0 * * *" } + ], "routes": [ { "src": "/api(?:/.*)?", "dest": "/api/index.ts" }, { "handle": "filesystem" },