Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(play): name a coin world from a bare deep link instead of titling it Community

nirholasedf2be319072
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 282805167..67703d79f 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -87,7 +87,7 @@ bottom.
| `/play` combat & weapons (server-authoritative, danger zones, wanted, tombstones) | Client: [src/game/combat-system.js](src/game/combat-system.js) `→ /play` (vitals HUD wiring, danger-zone ground, tombstone loot, hit feedback, the `window.twsCombat` bridge into W08's `MobSystem`), HUD [src/game/hud/world-hud.js](src/game/hud/world-hud.js). Server: [multiplayer/src/combat-handlers.js](multiplayer/src/combat-handlers.js) (mob AI, attack/loot intents, death + respawn), pure math [multiplayer/src/combat.js](multiplayer/src/combat.js), weapon/mob/loot tables [multiplayer/src/items.js](multiplayer/src/items.js), zone geometry [multiplayer/src/world-features.js](multiplayer/src/world-features.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W07 of the World Online program (program brief retired to git history). Equip a sword/bat/pistol/bow from the hotbar and press `X` (or tap the touch Attack button) to fight; but only inside one of three named danger zones (Southern Wilds, Northern Wilds, Eastern Marches); town stays lawful by construction. PvE mobs chase and swing back through the same server-side damage path a player's attack uses; a kill (mob or PvP) spills a lootable tombstone, PvP raises the attacker's wanted/heat stars (visible on `WorldHud` and a downed peer's nameplate), and death drops carried cash/pack before an automatic respawn in town. |
| `/play` NPCs & world life (traffic, vendors, quest-givers, mobs) | Manager [src/game/npc/world-life.js](src/game/npc/world-life.js), nav graph [src/game/npc/nav-graph.js](src/game/npc/nav-graph.js), ambient crowd/traffic [src/game/npc/ambient-life.js](src/game/npc/ambient-life.js), quest-giver NPCs [src/game/npc/quest-npcs.js](src/game/npc/quest-npcs.js), quest-zone waypoints [src/game/npc/quest-markers.js](src/game/npc/quest-markers.js), Jobs Board UI [src/game/quests-ui.js](src/game/quests-ui.js), W07-gated mobs [src/game/npc/mobs.js](src/game/npc/mobs.js). Server: quest engine [multiplayer/src/quests.js](multiplayer/src/quests.js), quest zones [multiplayer/src/quest-zones.js](multiplayer/src/quest-zones.js), handlers in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W08 of the World Online program (program brief retired to git history). A deterministic nav graph drives client-side ambient pedestrians + ring-road traffic that read identically for every player without a single packet; real gameplay stays server-authoritative. Five quest-giver NPCs (Dockmaster Reyes, Warden Okoro, Cook Mara, Foreman Dell, The Fixer) front the jobs board the quest engine (W05) already ran server-side but no client ever reached; pressing E opens the real board, accepting a job drops a waypoint at its objective (goto zones auto-complete by walking there, interact zones get their own "press E"), and finishing pays real cash server-side. Hostile mobs are live: W07's `CombatSystem` ([src/game/combat-system.js](src/game/combat-system.js)) installs the `window.twsCombat` contract this module's mobs were built against, so `MobSystem` renders real server-authoritative PvE hostiles with zero changes here. Two jobs; `cross-town-delivery` (North↔South) and `east-west-express` (East↔West); are real driving missions: each `goto` leg is flagged `vehicle: true` and only completes off the authoritative vehicle-driver map ([multiplayer/src/vehicles.js](multiplayer/src/vehicles.js)), so walking through a depot never counts, only driving through it does. Depots sit on the avenue vehicle spawns, so a car is always parked at the start. Tests: [tests/quests-vehicle-delivery.test.js](tests/quests-vehicle-delivery.test.js). |
| Frame governor & power saver (`/play`, `/club`, `/walk`) | [src/shared/frame-governor.js](src/shared/frame-governor.js), wired in [src/game/coincommunities.js](src/game/coincommunities.js), [src/club.js](src/club.js), [src/club-entrance.js](src/club-entrance.js), [src/walk.js](src/walk.js); toggle UI in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) | Live | Shared frame-rate governor for the heavy 3D surfaces: 60fps while active, 30fps when idle or unfocused, plus a user-facing Power-saver mode (30fps + lighter rendering, "for a cooler, quieter machine") persisted in localStorage `tws-power-saver` and shared across surfaces (`getPowerSaver`/`setPowerSaver`/`onPowerSaverChange`, `trackWindowFocus`). Tests: [tests/frame-governor.test.js](tests/frame-governor.test.js) |
-| `/play` safety & lifecycle invariants | Doc [docs/play-hardening.md](docs/play-hardening.md) `→ /docs/play-hardening`. Guards: `cssBgImage()` + `clampParam()` + `isPlausibleMint()` in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) / [src/game/coincommunities.js](src/game/coincommunities.js), avatar template cache + `releaseAvatar()` in [src/game/avatar-rig.js](src/game/avatar-rig.js), reconnect pruning (`_markRemotesStale`/`_pruneStaleRemotes`) and `_disposeObject3D()` in [src/game/coincommunities.js](src/game/coincommunities.js). Harnesses: [scripts/play-desktop-audit.mjs](scripts/play-desktop-audit.mjs), [scripts/play-mobile-repro.mjs](scripts/play-mobile-repro.mjs) | Live | The rules that keep the platform's largest interactive surface safe, honest and phone-survivable, each written against a failure that actually shipped: untrusted display names and coin metadata never become markup or CSS (a tombstone owner's name once ran as HTML for everyone who walked past it; a crafted coin `image_uri` could paint a full-screen overlay across the lobby), a malformed `?coin=` is refused instead of building a convincing world nobody else can join, a reconnect retires the peers who left rather than accumulating frozen ghosts and a tripled headcount, and everything the world loads (crowd/NPC GLBs, the sun's 2048² shadow map, totem, jumbotron, dance floor, district, environment) is genuinely freed on the way out instead of held until the tab is killed. Tests: [tests/play-deeplink-safety.test.js](tests/play-deeplink-safety.test.js) |
+| `/play` safety & lifecycle invariants | Doc [docs/play-hardening.md](docs/play-hardening.md) `→ /docs/play-hardening`. Guards: `cssBgImage()` + `clampParam()` + `isPlausibleMint()` in [src/game/coincommunities-ui.js](src/game/coincommunities-ui.js) / [src/game/coincommunities.js](src/game/coincommunities.js), avatar template cache + `releaseAvatar()` in [src/game/avatar-rig.js](src/game/avatar-rig.js), reconnect pruning (`_markRemotesStale`/`_pruneStaleRemotes`) and `_disposeObject3D()` in [src/game/coincommunities.js](src/game/coincommunities.js). Harnesses: [scripts/play-desktop-audit.mjs](scripts/play-desktop-audit.mjs), [scripts/play-mobile-repro.mjs](scripts/play-mobile-repro.mjs) | Live | The rules that keep the platform's largest interactive surface safe, honest and phone-survivable, each written against a failure that actually shipped: untrusted display names and coin metadata never become markup or CSS (a tombstone owner's name once ran as HTML for everyone who walked past it; a crafted coin `image_uri` could paint a full-screen overlay across the lobby), a malformed `?coin=` is refused instead of building a convincing world nobody else can join, a *valid* `?coin=` that lost the rest of its query (a hand-typed link, a truncated share, an unfurl that kept only the mint) is named from the coin feed by `_fetchCoinIdentity()`/`mergeCoinIdentity()` instead of building a real district under a totem reading "COMMUNITY" with a blank market cap, a reconnect retires the peers who left rather than accumulating frozen ghosts and a tripled headcount, and everything the world loads (crowd/NPC GLBs, the sun's 2048² shadow map, totem, jumbotron, dance floor, district, environment) is genuinely freed on the way out instead of held until the tab is killed. Tests: [tests/play-deeplink-safety.test.js](tests/play-deeplink-safety.test.js), [tests/play-deeplink-identity.test.js](tests/play-deeplink-identity.test.js) |
| Cinematic rendering (shared 3D quality bar) | [src/shared/cinematic-render.js](src/shared/cinematic-render.js) — `applyCinematicDefaults()`, `loadEnvironment()`, `detectQualityTier()`, `updateGroundContactShadow()`; curated HDRIs in [public/hdri/](public/hdri) (CC0, Poly Haven) | Live, wired into every three.js viewer on the platform (`/irl`, talk mode, `/play`, `/club`, `/ar`, `/xr`, `/walk`, `/coin3d`, marketplace lobby, demo pages, the `<agent-3d>`/`<page-agent>` embeds, and more) | One module every WebGLRenderer-based viewer calls into instead of re-deriving ACES tone mapping, sRGB output color space, HDRI image-based lighting, and soft VSM shadows per file. `detectQualityTier()` picks high/medium/mobile from real device signals and caps pixel ratio + disables shadows/HDRI accordingly; `loadEnvironment()` fetches a real photographic HDRI (`studio`/`outdoor`/`sunset`) and falls back to a procedural room environment on mobile tier or fetch failure (including cross-origin embed contexts where the absolute `/hdri/*.hdr` URL can't resolve). `/walk` keeps its own richer per-biome HDR system ([src/walk-environments.js](src/walk-environments.js)); surfaces already running a postprocessing tone-mapping pass (`/oracle-graph`, `/club-entrance`) only take the sRGB/HDRI half to avoid double-applying the curve. |
| `/play` Wheel of Fortune (Fortune's Folly; free/paid $THREE spins) | Client: [src/game/wheel-station.js](src/game/wheel-station.js) (the plaza landmark, proximity prompt, `E` to spin; lazy-imports the actual UI on first interact), spin UI [src/game/spin-wheel-ui.js](src/game/spin-wheel-ui.js) (20-segment wheel, free/paid flow, wallet signing). Server: [multiplayer/src/spin-wheel.js](multiplayer/src/spin-wheel.js) (paytable, RNG, level/cooldown/pack gates, handlers), split-payment settlement [multiplayer/src/game-token.js](multiplayer/src/game-token.js) (`buildSpinPayment`/`verifySpinPayment`; the same primitives the $THREE boutique uses), wheel location [multiplayer/src/world-features.js](multiplayer/src/world-features.js) `WHEEL`, persisted cooldown field in [multiplayer/src/economy.js](multiplayer/src/economy.js), handlers wired in [multiplayer/src/rooms/WalkRoom.js](multiplayer/src/rooms/WalkRoom.js) | In-repo | W09 of the World Online program (program brief retired to git history). Walk up to the wheel in the plaza and press `E`: one free spin every 12h (a real persisted cooldown; survives a disconnect, unlike the ephemeral per-action cooldowns everything else on this row's neighbors use), or pay $3 in `$THREE`; split 50% to the holder-rewards pool / 50% to the treasury, verified on-chain before any prize is granted, mirroring the boutique's proven settlement pattern exactly. Gated behind an average skill level of 3 (a light anti-farm floor, not a grind) and never lets a won prize get lost to a full pack; room for at least one possible item prize is checked before a spin is even offered, paid or free. All 20 wedges are equal-odds by design, matching the client's fixed-angle wheel rendering exactly (see the header note in `spin-wheel.js` on why that must never drift). Tests: [tests/spin-wheel.test.js](tests/spin-wheel.test.js). |
| `/play` live events (countdown chip, agenda drawer, synchronized fireworks) | Config `public/event.json` (one file, shared with the lobby countdown and the server-side souvenir grant). Client: in-world layer [src/game/meetup-event.js](src/game/meetup-event.js) + [src/game/meetup-event.css](src/game/meetup-event.css), pure schedule math [src/game/meetup-schedule.js](src/game/meetup-schedule.js), particle show [src/game/fireworks.js](src/game/fireworks.js), lobby banner + wayfinding pill [src/game/event-countdown.js](src/game/event-countdown.js). Mounted from [pages/play.html](pages/play.html) | In-repo | Turns the `$THREE` home town into a place something is *happening* in for the length of a scheduled event, driven entirely by `public/event.json`: delete the file and the world is normal again, with no code change. A countdown chip docks under the King of the Totem card (and stands the generic pill down, so there is only ever one countdown on screen) and opens a right-docked agenda drawer that marks the running segment, dims finished ones, counts the rest down in local time, and carries a live `$THREE` pulse row (`/api/three-signal`) plus one-tap Buy and commemorative-photo actions. Six phases derive from the wall clock (`far → upcoming → preshow → live → afterglow → ended`), so every player agrees on what is on and what is next without a round-trip. **Fireworks are deterministic, not networked:** four-second buckets hashed with the event id give every client the identical sky (`fireworkPlan()`), the same trick [src/shared/world-clock.js](src/shared/world-clock.js) uses for the shared sun; density ramps into a closing barrage, power-saver halves it, at most 14 shells live at once, and a backgrounded tab rejoins the show live instead of replaying the backlog `requestAnimationFrame` paused through. Preview any schedule with `?meetup=now` or `?meetup=<ISO>`. Doc: [docs/play-live-events.md](docs/play-live-events.md). Browser audit: `npm run audit:meetup` ([scripts/meetup-audit.mjs](scripts/meetup-audit.mjs)). Tests: [tests/meetup-schedule.test.js](tests/meetup-schedule.test.js), [tests/meetup-event-ui.test.js](tests/meetup-event-ui.test.js) |
diff --git a/docs/play-hardening.md b/docs/play-hardening.md
index e752589f2..c09141432 100644
--- a/docs/play-hardening.md
+++ b/docs/play-hardening.md
@@ -81,6 +81,23 @@ The art has a designed failure path in both places it appears. In the loader, a
The loader also sets a provisional `document.title` from the link and stashes the original in `documentElement.dataset.lobbyTitle`; `_setTabTitle()` in [src/game/coincommunities.js](../src/game/coincommunities.js) replaces it with the resolved coin on entry and restores the stashed original on leave, so the two writers never fight and the localised title is never re-spelled in JS.
+### 3b. A link that kept only the mint still opens a named world
+
+**Invariant: `enter()` backfills a missing name, symbol, image or market cap from `/api/pump/coin` before it builds anything, and what the link carried always wins.**
+
+The mint is the only part of `/play?coin=…&name=…&symbol=…&image=…` that identifies the coin. Everything after it is decoration the sharer's client appended to the URL, and it goes missing constantly: a hand-typed link, a chat client that truncated the query, an unfurl that kept only the mint, a link copied out of a screenshot. The market cap was never on the URL at all, because a number that moves cannot be baked into a link people re-share for weeks.
+
+A link short of that decoration used to build the full world anyway, with no identity in it: a totem reading "COMMUNITY", a welcome card offering "the Community community", a tab titled Community, and a blank market cap on both the jumbotron and the in-world chart screen. That is the same failure section 3 refuses for a *broken* mint, arriving through a mint that is perfectly valid.
+
+`_fetchCoinIdentity()` in [src/game/coincommunities.js](../src/game/coincommunities.js) reads the coin from the same feed the lobby cards are built from, and `mergeCoinIdentity()` fills only the blanks: whatever the link did carry is what every peer already on that link sees, so it stays authoritative even if the feed disagrees. The rules from sections 1 through 3 still apply to the result, since it is upstream text like any other: the name and symbol go through `clampParam()`, the image through `proxiedImageURL()`. Four properties keep the lookup from ever being worse than the nameless world it replaces:
+
+- It is skipped entirely for a coin that arrived complete, so a lobby card never pays for it.
+- It is skipped for an EVM mint, which the pump.fun lookup cannot answer for.
+- It is bounded by an `AbortController` at `COIN_IDENTITY_TIMEOUT_MS`, so a slow upstream cannot hold a player on the loading screen; any failure resolves to `null` and the world builds exactly as it did before.
+- It re-checks the entry phase and epoch after awaiting, so backing out mid-lookup bails instead of resurrecting a torn-down world.
+
+The URL rewrite that follows puts the resolved identity back on the address bar, so the next person to receive that link never pays for the lookup at all.
+
## 4. Losing the connection recovers cleanly
**Invariant: a reconnect must retire the peers who left while you were offline.**
@@ -213,7 +230,8 @@ The `WebSocket` case is not hypothetical: `/play` opens the multiplayer socket d
```bash
# Pure-logic guards: CSS-injection, mint validation, param clamping,
# and the image-URL scheme allowlist.
-npx vitest run tests/play-deeplink-safety.test.js tests/ipfs-image-url-safety.test.js
+npx vitest run tests/play-deeplink-safety.test.js tests/play-deeplink-identity.test.js \
+ tests/ipfs-image-url-safety.test.js
# Deliberate failure injection in a real browser: hostile query strings, blocked
# coin art and GLBs, a dead auth gate, an ad blocker, a total API outage.
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 9b039b352..b83d78c3e 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -223,6 +223,32 @@ function mapCoins(raw) {
})).filter((c) => c.mint);
}
+// How long a bare deep link waits for the coin's identity before it gives up and
+// builds the world anyway. Entry already has the sign-in gate, the manifest and
+// an avatar GLB ahead of it, so this is the one place a slow upstream must never
+// be allowed to hold the player on a loading screen.
+const COIN_IDENTITY_TIMEOUT_MS = 6000;
+
+// Fill in whatever a shared world link did not carry. The name/symbol/image on
+// /play?coin=<mint>&name=…&symbol=…&image=… are decoration the sharer's client
+// appended, and they go missing constantly: a hand-typed link, a chat client
+// that truncated the query, an unfurl that kept only the mint. The mint alone
+// still identifies the coin exactly, so a link without the decoration must build
+// the same world as a link with it, not a nameless one titled "Community".
+//
+// Only blanks are filled: anything the link did carry is what every peer on that
+// link already sees, so it stays authoritative here even if the feed disagrees.
+function mergeCoinIdentity(coin, fetched) {
+ if (!fetched) return coin;
+ return {
+ ...coin,
+ name: coin.name || fetched.name || '',
+ symbol: coin.symbol || fetched.symbol || '',
+ image: coin.image || fetched.image || '',
+ marketCap: coin.marketCap || fetched.marketCap || 0,
+ };
+}
+
// Compact USD for the jumbotron's market-cap readout: $1.2B / $940M / $12K.
function formatUsd(n) {
const v = Number(n) || 0;
@@ -850,6 +876,39 @@ export class CoinCommunities {
}
}
+ // The identity behind a bare `?coin=<mint>` link, read from the same pump.fun
+ // record the lobby cards are built from. Never throws and never stalls entry:
+ // a miss returns null and the world falls back to its generated art and the
+ // generic label, exactly as it did before.
+ async _fetchCoinIdentity(mint) {
+ // pump.fun's coin lookup is Solana-only, so an EVM world (Robinhood Chain)
+ // has nothing to gain from the round trip.
+ if (!SOLANA_MINT_RE.test(String(mint || '').trim())) return null;
+ const ctrl = new AbortController();
+ const timer = setTimeout(() => ctrl.abort(), COIN_IDENTITY_TIMEOUT_MS);
+ try {
+ const r = await fetch(`${COIN_URL}?mint=${encodeURIComponent(mint)}`, {
+ headers: { accept: 'application/json' }, signal: ctrl.signal,
+ });
+ if (!r.ok) throw new Error('HTTP ' + r.status);
+ const c = await r.json();
+ if (!c || (c.mint && c.mint !== mint)) return null;
+ return {
+ // Clamped to the same caps the URL params are clamped to: the feed is
+ // upstream text, and the room server truncates it for every peer.
+ name: clampParam(c.name, 48),
+ symbol: clampParam(c.symbol, 16),
+ image: proxiedImageURL(c.image_uri || c.image || c.imageUri || c.logo || '', mint),
+ marketCap: c.usd_market_cap || c.market_cap_usd || c.marketCap || 0,
+ };
+ } catch (err) {
+ log.warn('[coincommunities] coin identity lookup failed:', err?.message);
+ return null;
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+
// Live search across ALL of pump.fun (not just the trending grid) so any
// coin can be turned into a world. Returns mapped coins; throws on failure
// so the UI can distinguish "no matches" from "search unavailable".
@@ -1351,6 +1410,19 @@ export class CoinCommunities {
official: true,
};
}
+ if (!coin.name || !coin.symbol || !coin.marketCap) {
+ // Any link that arrives short of a full identity. A bare mint
+ // used to build a real district under a totem reading COMMUNITY, a
+ // welcome card offering "the Community community", and a tab titled
+ // Community, for a coin the platform can name in one request. Even a
+ // full share link carries no market cap (the rewrite below cannot put a
+ // number that moves onto a URL), so the jumbotron and the world's chart
+ // screen both read blank on every link anyone has ever shared. One
+ // lookup fixes both. Lobby cards arrive complete and skip it.
+ const fetched = await this._fetchCoinIdentity(coin.mint);
+ if (this.phase !== 'loading' || epoch !== this._enterEpoch) return; // backed out mid-lookup
+ coin = mergeCoinIdentity(coin, fetched);
+ }
coin = { ...coin, tier, holderMinUsd, holderMinTokens };
this.coin = coin;
this.ui.enterWorld(coin);
diff --git a/tests/play-deeplink-identity.test.js b/tests/play-deeplink-identity.test.js
new file mode 100644
index 000000000..a4f450e68
--- /dev/null
+++ b/tests/play-deeplink-identity.test.js
@@ -0,0 +1,115 @@
+// A shared /play?coin=<mint> link must build the same world as the lobby card it
+// came from. The name, symbol and image on that URL are optional decoration the
+// sharer's client appended, and they go missing constantly (a hand-typed link, a
+// chat client that truncated the query, an unfurl that kept only the mint); the
+// market cap was never on the URL at all, because a number that moves cannot be
+// baked into a shareable link. Before this, a link short of that decoration built
+// a real district with no identity: a totem reading COMMUNITY, a welcome card
+// offering "the Community community", a tab titled Community, and a blank market
+// cap on both the jumbotron and the in-world chart screen.
+//
+// enter() now backfills the blanks from the same pump.fun record the lobby cards
+// are built from. What the link DID carry stays authoritative: it is what every
+// peer already on that link sees, so the feed must never overwrite it.
+//
+// mergeCoinIdentity() is module-private inside a browser module that cannot be
+// imported under node, so it is re-derived from its source text the way
+// play-deeplink-safety.test.js re-derives its guards. The call-site assertions
+// below cover what a pure function cannot: that entry stays cancellable and
+// cannot be held open by a slow upstream.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+
+const read = (rel) => readFileSync(fileURLToPath(new URL(rel, import.meta.url)), 'utf8');
+
+function extractFn(source, name) {
+ const start = source.indexOf(`function ${name}(`);
+ if (start === -1) throw new Error(`${name}() is no longer defined; update this test with the code that replaced it`);
+ let depth = 0, i = source.indexOf('{', start);
+ for (; i < source.length; i++) {
+ if (source[i] === '{') depth++;
+ else if (source[i] === '}' && --depth === 0) break;
+ }
+ return source.slice(start, i + 1);
+}
+
+const ccSrc = read('../src/game/coincommunities.js');
+// eslint-disable-next-line no-new-func
+const mergeCoinIdentity = new Function(`${extractFn(ccSrc, 'mergeCoinIdentity')}; return mergeCoinIdentity;`)();
+
+const TCAR = { name: 'TRENCH CAR', symbol: 'TCAR', image: '/api/img?url=x', marketCap: 41699 };
+
+describe('mergeCoinIdentity: a bare mint still opens a named world', () => {
+ it('names a link that carried nothing but the mint', () => {
+ const out = mergeCoinIdentity({ mint: 'm' }, TCAR);
+ expect(out).toMatchObject({ mint: 'm', ...TCAR });
+ });
+
+ it('never overwrites what the link carried', () => {
+ const link = { mint: 'm', name: 'Shared name', symbol: 'SHARE', image: '/api/img?url=shared', marketCap: 1 };
+ expect(mergeCoinIdentity(link, TCAR)).toEqual(link);
+ });
+
+ it('fills only the missing halves of a partial link', () => {
+ const out = mergeCoinIdentity({ mint: 'm', name: 'Shared name' }, TCAR);
+ expect(out.name).toBe('Shared name');
+ expect(out.symbol).toBe('TCAR');
+ expect(out.marketCap).toBe(41699);
+ });
+
+ it('leaves the coin untouched when the lookup missed', () => {
+ const link = { mint: 'm', name: '', symbol: '' };
+ expect(mergeCoinIdentity(link, null)).toBe(link);
+ expect(mergeCoinIdentity(link, undefined)).toBe(link);
+ });
+
+ it('keeps world-shaping fields the caller already decided', () => {
+ // The flagship town pins its biome and its official badge before the
+ // lookup runs; a feed record must not be able to strip either.
+ const home = { mint: 'm', biome: 'hometown', official: true };
+ const out = mergeCoinIdentity(home, TCAR);
+ expect(out.biome).toBe('hometown');
+ expect(out.official).toBe(true);
+ });
+
+ it('never turns a missing field into the string "undefined"', () => {
+ const out = mergeCoinIdentity({ mint: 'm' }, { name: undefined, symbol: null });
+ expect(out.name).toBe('');
+ expect(out.symbol).toBe('');
+ expect(out.image).toBe('');
+ expect(out.marketCap).toBe(0);
+ });
+});
+
+describe('the lookup cannot strand or outlive the entry it serves', () => {
+ const fn = ccSrc.slice(ccSrc.indexOf('async _fetchCoinIdentity('));
+
+ it('bounds the request so a slow upstream cannot hold the loading screen', () => {
+ expect(fn).toMatch(/new AbortController\(\)/);
+ expect(fn).toMatch(/setTimeout\(\(\) => ctrl\.abort\(\), COIN_IDENTITY_TIMEOUT_MS\)/);
+ expect(fn).toMatch(/clearTimeout\(timer\)/);
+ expect(ccSrc).toMatch(/const COIN_IDENTITY_TIMEOUT_MS = \d+;/);
+ });
+
+ it('resolves to null on any failure rather than throwing into entry', () => {
+ expect(fn.slice(0, fn.indexOf('\n\t}'))).toMatch(/catch \(err\)[\s\S]*return null;/);
+ });
+
+ it('skips the round trip for an EVM world, which pump.fun cannot answer for', () => {
+ expect(fn).toMatch(/SOLANA_MINT_RE\.test\([\s\S]{0,60}return null;/);
+ });
+
+ it('re-checks phase and epoch after awaiting, so backing out mid-lookup bails', () => {
+ const call = ccSrc.slice(ccSrc.indexOf('const fetched = await this._fetchCoinIdentity('));
+ const guard = call.slice(0, call.indexOf('mergeCoinIdentity'));
+ expect(guard).toMatch(/this\.phase !== 'loading'/);
+ expect(guard).toMatch(/epoch !== this\._enterEpoch/);
+ expect(guard).toMatch(/return;/);
+ });
+
+ it('runs only for a coin that arrived short of an identity', () => {
+ expect(ccSrc).toMatch(/if \(!coin\.name \|\| !coin\.symbol \|\| !coin\.marketCap\) \{/);
+ });
+});