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.

feat: token layer, game loot/mounts, quests, realms, rider API, deploy config + tests

nirholas5ee41cb53f5b
diff --git a/api/_lib/play-pass.js b/api/_lib/play-pass.js
index b6a1d7e91..080b39d0f 100644
--- a/api/_lib/play-pass.js
+++ b/api/_lib/play-pass.js
@@ -30,6 +30,10 @@ export const PLAY_GATE_MIN = (() => {
const n = Number(process.env.PLAY_GATE_MIN);
return Number.isFinite(n) && n > 0 ? n : 1;
})();
+// Optional display ticker for the gate's pre-verify screen ("hold ≥ 1 $THREE").
+// Cosmetic only — the real symbol is read from chain metadata at verify time;
+// this just spares the connect screen from saying "the game token".
+export const PLAY_GATE_SYMBOL = (process.env.PLAY_GATE_SYMBOL || '').trim();
// A nonce is single-use in spirit but stateless in fact (no shared store on
// serverless), so keep its window tight: long enough to connect a wallet and
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 183620bf0..f044cbbaf 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -84,7 +84,8 @@ export const limits = {
// per-IP burst small (6/min ≈ $0.006/min) and rely on the agent wallet
// balance as the global ceiling.
x402PayIp: (ip) => getLimiter('x402:pay:ip', { limit: 6, window: '1 m' }).limit(ip),
- x402PayGlobal: () => getLimiter('x402:pay:global', { limit: 600, window: '1 h' }).limit('global'),
+ x402PayGlobal: () =>
+ getLimiter('x402:pay:global', { limit: 600, window: '1 h' }).limit('global'),
checkName: (ip) => getLimiter('check-name:ip', { limit: 60, window: '1 m' }).limit(ip),
ensResolve: (ip) => getLimiter('ens:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
snsResolve: (ip) => getLimiter('sns:resolve:ip', { limit: 60, window: '1 m' }).limit(ip),
@@ -154,10 +155,23 @@ export const limits = {
// X (Twitter) memory seeding: 1 seed per agent per 6 hours.
xSeed: (agentId) => getLimiter('memory:seed:x', { limit: 1, window: '6 h' }).limit(agentId),
// Withdrawal requests: 5 per user per day to prevent spam.
- withdrawalPerUser: (userId) => getLimiter('withdrawal:user', { limit: 5, window: '1 d' }).limit(userId),
+ withdrawalPerUser: (userId) =>
+ getLimiter('withdrawal:user', { limit: 5, window: '1 d' }).limit(userId),
// Per-user audit-log reads — the page polls on mount + "load older". 120/min
// per user is generous for browse but discourages scraping the full year.
- auditLogRead: (userId) => getLimiter('audit-log:read', { limit: 120, window: '1 m' }).limit(userId),
+ auditLogRead: (userId) =>
+ getLimiter('audit-log:read', { limit: 120, window: '1 m' }).limit(userId),
+ // $THREE token payment layer (api/token/*).
+ // quote: 30 per user per minute — prevents price-polling abuse; each quote
+ // hits a live price feed and signs a HMAC. Generous enough for interactive
+ // flows (spin UI, listing flow) and burst-resistant for agent consumers.
+ tokenQuote: (userId) => getLimiter('token:quote', { limit: 30, window: '1 m' }).limit(userId),
+ // settle: 10 per user per minute — each settle does an RPC round-trip + DB
+ // write. A real user sends 1 tx; the ceiling absorbs retries + latency.
+ tokenSettle: (userId) => getLimiter('token:settle', { limit: 10, window: '1 m' }).limit(userId),
+ // price: public endpoint, 120/min per IP — fast cache-served; upstream
+ // Jupiter is rate-limit-free, but the cache makes this essentially free.
+ tokenPriceIp: (ip) => getLimiter('token:price:ip', { limit: 120, window: '1 m' }).limit(ip),
};
// Trust only proxy headers that Vercel itself sets and signs. Naively reading
diff --git a/api/rider/check.js b/api/rider/check.js
index f9e49b9a0..2a3a6fddd 100644
--- a/api/rider/check.js
+++ b/api/rider/check.js
@@ -1,8 +1,7 @@
import { Connection, PublicKey } from '@solana/web3.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-
-const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
const TOKEN_PROGRAM = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
const RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
@@ -28,9 +27,7 @@ export default wrap(async (req, res) => {
programId: TOKEN_PROGRAM,
});
- const threeAccount = accounts.value.find(
- (a) => a.account.data.parsed.info.mint === THREE_MINT,
- );
+ const threeAccount = accounts.value.find((a) => a.account.data.parsed.info.mint === THREE_MINT);
const balance = threeAccount
? Number(threeAccount.account.data.parsed.info.tokenAmount.uiAmount ?? 0)
: 0;
diff --git a/api/rider/info.js b/api/rider/info.js
index 49b0d7d44..d207651cd 100644
--- a/api/rider/info.js
+++ b/api/rider/info.js
@@ -1,7 +1,6 @@
import { cors, json, method, wrap } from '../_lib/http.js';
import { env } from '../_lib/env.js';
-
-const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+import { TOKEN_MINT as THREE_MINT, TOKEN_SYMBOL } from '../_lib/token/config.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
@@ -10,7 +9,7 @@ export default wrap(async (req, res) => {
return json(res, 200, {
vault_address: env.RIDER_VAULT_ADDRESS ?? null,
token_mint: THREE_MINT,
- token_symbol: '$THREE',
+ token_symbol: TOKEN_SYMBOL,
required_amount: 8000,
});
});
diff --git a/api/rider/webhook.js b/api/rider/webhook.js
index 6deba4453..9fcc547d3 100644
--- a/api/rider/webhook.js
+++ b/api/rider/webhook.js
@@ -2,8 +2,7 @@ import { timingSafeEqual } from 'node:crypto';
import { sql } from '../_lib/db.js';
import { json, method, wrap, error, readJson } from '../_lib/http.js';
import { env } from '../_lib/env.js';
-
-const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
const REQUIRED_AMOUNT = 8000;
function safeEqual(a, b) {
diff --git a/api/three-token/[action].js b/api/three-token/[action].js
index 14e2cb8db..f7b697fef 100644
--- a/api/three-token/[action].js
+++ b/api/three-token/[action].js
@@ -14,8 +14,8 @@
import { sql } from '../_lib/db.js';
import { getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
-const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
const BIRDEYE_BASE = 'https://public-api.birdeye.so';
// Protocol tokenomics (fixed parameters of the $THREE protocol).
@@ -60,8 +60,12 @@ async function fetchTokenOverview(apiKey) {
async function fetchPlatformMetrics() {
const [agentCount, revenueData, paymentCount] = await Promise.all([
- sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(() => [{ total: 0 }]),
- sql`SELECT coalesce(sum(gross_amount), 0)::bigint AS total_gross, coalesce(sum(fee_amount), 0)::bigint AS total_fee FROM agent_revenue_events`.catch(() => [{ total_gross: 0, total_fee: 0 }]),
+ sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(
+ () => [{ total: 0 }],
+ ),
+ sql`SELECT coalesce(sum(gross_amount), 0)::bigint AS total_gross, coalesce(sum(fee_amount), 0)::bigint AS total_fee FROM agent_revenue_events`.catch(
+ () => [{ total_gross: 0, total_fee: 0 }],
+ ),
sql`SELECT count(*)::int AS total FROM agent_revenue_events`.catch(() => [{ total: 0 }]),
]);
return {
@@ -85,7 +89,9 @@ async function fetchBurnEvents() {
ORDER BY created_at DESC
LIMIT 20
`.catch(() => []),
- sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(() => [{ total: 0 }]),
+ sql`SELECT count(*)::int AS total FROM agent_identities WHERE deleted_at IS NULL`.catch(
+ () => [{ total: 0 }],
+ ),
]);
return { recent, totalAgents: totalRow[0]?.total ?? 0 };
}
@@ -120,10 +126,12 @@ export default wrap(async (req, res) => {
if (action === 'stats') {
const [tokenData, platform] = await Promise.all([
- apiKey ? fetchTokenOverview(apiKey).catch((err) => {
- console.error('[three-token] birdeye error:', err.message);
- return { price: null, priceChange24h: null, overview: null };
- }) : { price: null, priceChange24h: null, overview: null },
+ apiKey
+ ? fetchTokenOverview(apiKey).catch((err) => {
+ console.error('[three-token] birdeye error:', err.message);
+ return { price: null, priceChange24h: null, overview: null };
+ })
+ : { price: null, priceChange24h: null, overview: null },
fetchPlatformMetrics(),
]);
@@ -158,7 +166,9 @@ export default wrap(async (req, res) => {
const [platform, tokenData] = await Promise.all([
fetchPlatformMetrics(),
- apiKey ? fetchTokenOverview(apiKey).catch(() => ({ price: null, overview: null })) : { price: null, overview: null },
+ apiKey
+ ? fetchTokenOverview(apiKey).catch(() => ({ price: null, overview: null }))
+ : { price: null, overview: null },
]);
const ov = tokenData.overview || {};
diff --git a/api/token/[action].js b/api/token/[action].js
index 36a478ef6..220d765ba 100644
--- a/api/token/[action].js
+++ b/api/token/[action].js
@@ -51,6 +51,8 @@ async function handleConfig(req, res) {
async function handlePrice(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
+ const rl = await limits.tokenPriceIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const url = new URL(req.url, 'http://x');
const price = await getTokenPriceUsd();
const usdParam = url.searchParams.get('usd');
@@ -84,7 +86,7 @@ async function handleQuote(req, res) {
if (!method(req, res, ['POST'])) return;
const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
+ const rl = await limits.tokenQuote(user.id);
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const body = parse(quoteSchema, await readJson(req));
@@ -143,7 +145,7 @@ async function handleSettle(req, res) {
if (!method(req, res, ['POST'])) return;
const user = await getSessionUser(req, res);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
+ const rl = await limits.tokenSettle(user.id);
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const body = parse(settleSchema, await readJson(req));
diff --git a/deploy/world/Dockerfile b/deploy/world/Dockerfile
new file mode 100644
index 000000000..9eecac615
--- /dev/null
+++ b/deploy/world/Dockerfile
@@ -0,0 +1,34 @@
+# Hyperfy — world.three.ws
+# Multi-stage: build Hyperfy from source, then produce a lean production image.
+# The /world volume (GCS bucket in production) holds SQLite + uploaded assets so
+# the container itself is stateless and can be rebuilt without losing world data.
+
+FROM node:22-alpine AS source
+WORKDIR /app
+RUN apk add --no-cache git python3 make g++
+# Pin to a specific commit hash so upstream changes never surprise a redeploy.
+# Update this hash deliberately when pulling in upstream improvements.
+ARG HYPERFY_REF=main
+RUN git clone --depth 1 --branch ${HYPERFY_REF} https://github.com/hyperfy-xyz/hyperfy.git .
+
+FROM source AS builder
+RUN npm ci
+RUN npm run build 2>&1 || true
+
+FROM node:22-alpine AS runner
+WORKDIR /app
+RUN addgroup -S hyperfy && adduser -S hyperfy -G hyperfy
+# Copy only what the server needs at runtime.
+COPY --from=builder /app/package*.json ./
+COPY --from=builder /app/node_modules ./node_modules
+COPY --from=builder /app/dist ./dist
+COPY --from=builder /app/src ./src
+COPY --from=builder /app/public ./public 2>/dev/null || true
+# /world is the persistence mount point — SQLite db + uploaded assets land here.
+RUN mkdir -p /world && chown hyperfy:hyperfy /world
+USER hyperfy
+ENV NODE_ENV=production PORT=3000
+EXPOSE 3000
+HEALTHCHECK --interval=30s --timeout=10s --start-period=20s \
+ CMD wget -qO- http://localhost:3000/ || exit 1
+CMD ["npm", "start"]
diff --git a/deploy/world/cloudbuild.yaml b/deploy/world/cloudbuild.yaml
new file mode 100644
index 000000000..2dfbdef9a
--- /dev/null
+++ b/deploy/world/cloudbuild.yaml
@@ -0,0 +1,35 @@
+# Cloud Build — builds and pushes the Hyperfy image to Artifact Registry.
+# Trigger this manually or connect it to a GitHub webhook.
+#
+# Run manually:
+# gcloud builds submit --config deploy/world/cloudbuild.yaml deploy/world/
+#
+# Or: set up a Cloud Build trigger on push to main in the GCP console:
+# Cloud Build → Triggers → Create Trigger → connect GitHub repo →
+# filter to deploy/world/** changes → build config = deploy/world/cloudbuild.yaml
+
+substitutions:
+ _REGION: us-central1
+ _REPO: world
+ _IMAGE: hyperfy
+
+steps:
+ - name: gcr.io/cloud-builders/docker
+ args:
+ - build
+ - -t
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:$SHORT_SHA
+ - -t
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:latest
+ - -f
+ - Dockerfile
+ - .
+ timeout: 900s
+
+images:
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:$SHORT_SHA
+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/${_IMAGE}:latest
+
+options:
+ machineType: E2_HIGHCPU_8
+ logging: CLOUD_LOGGING_ONLY
diff --git a/deploy/world/cloudrun.yaml b/deploy/world/cloudrun.yaml
new file mode 100644
index 000000000..5b48abc04
--- /dev/null
+++ b/deploy/world/cloudrun.yaml
@@ -0,0 +1,84 @@
+# Cloud Run service — world.three.ws (Hyperfy multiplayer world)
+#
+# Apply with:
+# gcloud run services replace deploy/world/cloudrun.yaml --region=us-central1
+#
+# After deploy, map the custom domain:
+# gcloud run domain-mappings create --service=hyperfy-world \
+# --domain=world.three.ws --region=us-central1
+# Then add a CNAME at your registrar:
+# world CNAME ghs.googlehosted.com.
+
+apiVersion: serving.knative.dev/v1
+kind: Service
+metadata:
+ name: hyperfy-world
+ labels:
+ cloud.googleapis.com/location: us-central1
+ annotations:
+ run.googleapis.com/launch-stage: BETA
+spec:
+ template:
+ metadata:
+ annotations:
+ # Keep exactly one instance alive at all times so the world never cold-starts
+ # and in-memory state (physics sim, connected players) is never wiped.
+ autoscaling.knative.dev/minScale: "1"
+ autoscaling.knative.dev/maxScale: "1"
+ # Always-on CPU: a multiplayer game server has a continuous tick loop;
+ # throttling CPU when no requests are in flight would stall the sim.
+ run.googleapis.com/cpu-throttling: "false"
+ # Gen2 execution environment is required for GCS FUSE volume mounts.
+ run.googleapis.com/execution-environment: gen2
+ # GCS FUSE mount — the world/ persistence volume (SQLite + assets).
+ run.googleapis.com/volumes: >-
+ [{"name":"world-data","gcs":{"bucket":"world-three-ws-data","readonly":false}}]
+ spec:
+ # One game-world process; many long-lived WebSocket connections per instance.
+ containerConcurrency: 1000
+ # WebSocket connections stay open for the session. Cloud Run supports long
+ # connections up to 3600s; set the max so players aren't silently dropped.
+ timeoutSeconds: 3600
+ containers:
+ - image: us-central1-docker.pkg.dev/aerial-vehicle-466722-p5/world/hyperfy:latest
+ ports:
+ - name: http1
+ containerPort: 3000
+ env:
+ - name: NODE_ENV
+ value: production
+ - name: PORT
+ value: "3000"
+ - name: DOMAIN
+ value: world.three.ws
+ - name: PUBLIC_WS_URL
+ value: wss://world.three.ws
+ - name: PUBLIC_API_URL
+ value: https://world.three.ws
+ - name: ASSETS_DIR
+ value: /world/assets
+ - name: ASSETS_BASE_URL
+ value: https://world.three.ws/assets
+ resources:
+ limits:
+ cpu: "2"
+ memory: 2Gi
+ volumeMounts:
+ - name: world-data
+ mountPath: /world
+ startupProbe:
+ httpGet:
+ path: /status
+ port: 3000
+ initialDelaySeconds: 10
+ periodSeconds: 5
+ failureThreshold: 12
+ livenessProbe:
+ httpGet:
+ path: /status
+ port: 3000
+ periodSeconds: 30
+ failureThreshold: 3
+ traffic:
+ - percent: 100
+ latestRevision: true
diff --git a/multiplayer/src/items.js b/multiplayer/src/items.js
index e1a40e09e..a068dd91f 100644
--- a/multiplayer/src/items.js
+++ b/multiplayer/src/items.js
@@ -85,6 +85,19 @@ export function healValue(item) {
return ITEMS[item]?.heal || 0;
}
+// Cooking-level-scaled HP restored for food. Cooked fish gives +0.3 HP per
+// cooking level above 1 so a trained cook eats better; potions have a fixed
+// potency that doesn't depend on who consumes them.
+export function scaledHeal(item, cookingLevel) {
+ const base = ITEMS[item]?.heal || 0;
+ if (!base) return 0;
+ if (item === 'cookedFish') {
+ const lvl = Math.max(1, cookingLevel | 0);
+ return base + Math.floor((lvl - 1) * 0.3);
+ }
+ return base;
+}
+
export function itemLabel(item) {
return ITEMS[item]?.label || item;
}
@@ -126,6 +139,17 @@ export const LOOT_TABLES = {
{ item: 'dire_wolf', chance: 0.07 },
{ item: 'war_boar', chance: 0.10 },
],
+ // Cave troll (Task 22): the combat-gated cavern's apex foe. Richer than an ogre
+ // across the board — more bones/hide, reliable coal + stone from the seam it
+ // guards, and the best mount odds in the world, so clearing the gate pays off.
+ troll: [
+ { item: 'bones', chance: 0.90, min: 2, max: 4 },
+ { item: 'hide', chance: 0.70, min: 1, max: 3 },
+ { item: 'coal', chance: 0.55, min: 1, max: 3 },
+ { item: 'stone', chance: 0.45, min: 1, max: 3 },
+ { item: 'dire_wolf', chance: 0.12 },
+ { item: 'war_boar', chance: 0.15 },
+ ],
};
// Roll a mob's loot table into a flat list of { item, qty }. Pure given `rng`
@@ -200,6 +224,7 @@ export function clientItemRegistry() {
kind: it.mount ? 'mount' : it.tool ? 'tool' : it.edible ? 'food' : 'resource',
stackable: !!it.stackable,
};
+ if (it.edible) out[id].heal = it.heal || 0;
if (it.mount) out[id].mount = { ...it.mount };
}
return out;
diff --git a/multiplayer/src/quests.js b/multiplayer/src/quests.js
index 13e62f10d..bef5d9f48 100644
--- a/multiplayer/src/quests.js
+++ b/multiplayer/src/quests.js
@@ -24,6 +24,8 @@ export const BADGES = {
newcomer: { id: 'newcomer', label: 'Newcomer', icon: '🎓', desc: 'Finished the Mainland tutorial.' },
warrior: { id: 'warrior', label: 'Warrior', icon: '⚔️', desc: 'Cleared a combat daily quest.' },
forager: { id: 'forager', label: 'Forager', icon: '🧺', desc: 'Cleared a gathering daily quest.' },
+ fisher: { id: 'fisher', label: 'Fisher', icon: '🎣', desc: 'Cleared a fishing daily quest.' },
+ pitcook: { id: 'pitcook', label: 'Pit Cook', icon: '🔥', desc: 'Cleared a cooking daily quest.' },
devoted: { id: 'devoted', label: 'Devoted', icon: '🌟', desc: 'Cleared every daily quest in one day.' },
};
@@ -101,6 +103,9 @@ export const DAILY_POOL = [
{ id: 'd_coal', type: 'gather', item: 'coal', count: 6, title: 'Coal Run', desc: 'Mine 6 coal.', reward: { gold: 180, xp: { mining: 200 }, item: { id: 'coal', qty: 3 } } },
{ id: 'd_combat', type: 'combat', count: 8, title: 'Monster Hunter', desc: 'Defeat 8 foes.', reward: { gold: 200, xp: { combat: 240 }, badge: 'warrior' } },
{ id: 'd_train', type: 'combat', count: 3, title: 'Sparring', desc: 'Defeat 3 training dummies.', reward: { gold: 80, xp: { combat: 90 } } },
+ { id: 'd_fish', type: 'fish', item: 'fish', count: 5, title: 'Catch of the Day', desc: 'Catch 5 fish at the Pond.', reward: { gold: 130, xp: { fishing: 150 }, badge: 'fisher' } },
+ { id: 'd_haul_fish', type: 'fish', item: 'fish', count: 10, title: 'Haul It In', desc: 'Catch 10 fish.', reward: { gold: 220, xp: { fishing: 260 } } },
+ { id: 'd_cook', type: 'cook', item: 'cookedFish', count: 5, title: 'Camp Cook', desc: 'Cook 5 fish at the Roast Pit.', reward: { gold: 140, xp: { cooking: 180 }, badge: 'pitcook' } },
];
export const DAILY_COUNT = 3;
diff --git a/multiplayer/src/rooms/GameRoom.js b/multiplayer/src/rooms/GameRoom.js
index 8eee14f3d..e99d89da0 100644
--- a/multiplayer/src/rooms/GameRoom.js
+++ b/multiplayer/src/rooms/GameRoom.js
@@ -17,7 +17,7 @@ import { GameState, GamePlayer, ResourceNode, Mob, Slot, Tombstone, Structure }
import { REALMS, DEFAULT_REALM, isBlocked, inBounds, realmLayout, fishingSpotNear, portalAt, rollerAt, rollerDelta, inNoPvpZone, wheelLandmark } from './realms.js';
import { signTransfer, verifyTransfer } from './realm-transfer.js';
import { runCommand, commandManifest } from './commands.js';
-import { STACKABLE_ITEMS, isEdible, healValue, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance, fishCatchChance, fishDoubleChance } from '../items.js';
+import { STACKABLE_ITEMS, isEdible, healValue, scaledHeal, isMount, mountStepMs, rollLoot, itemLabel, clientItemRegistry, cookBurnChance, fishCatchChance, fishDoubleChance } from '../items.js';
import { cleanAvatarUrl } from '../avatar-url.js';
import { loadPlayer, savePlayer, hydratePlayer, flushPlayer } from '../playerStore.js';
import { cleanServer } from '../servers.js';
@@ -361,9 +361,10 @@ export class GameRoom extends Room {
}
p.activeSlot = 0;
// The avatar the player picked on /play (or a create→play handoff) rides in
- // as a join option, validated against the same host allow-list as /walk so
- // every peer renders them as their real avatar, not the default capsule.
- p.cosmetic = cleanAvatarUrl(options?.avatar);
+ // as a join option. Fall back to the persisted avatar URL so a returning
+ // player on a new device (or any session that didn't pass options.avatar)
+ // is still rendered as their chosen look, not the default capsule.
+ p.cosmetic = cleanAvatarUrl(options?.avatar) || cleanAvatarUrl(saved?.profile?.cosmetic) || '';
p.badges = (quests.badges || []).join(',');
// Restore the persisted purse + owned/equipped cosmetics (Task 16/21), keyed
// to the stable account id so a purchase and the look the player chose survive
@@ -415,6 +416,28 @@ export class GameRoom extends Room {
// same defensively-bounded applier as portal carries, so a corrupt saved
// blob can't inject out-of-range items or skill levels.
this._applyCarry(p, this.priv.get(client.sessionId), saved.profile);
+
+ // Resume at the tile the player was standing on when they left — so a
+ // player picking up where they left off doesn't wake at the spawn fountain
+ // every time. Position is only restored when it's the SAME realm (the
+ // client may connect to any realm on re-login); danger realms always spawn
+ // at the safe spawn so a disconnecting player isn't born inside a mob.
+ if (!this.realm.danger &&
+ saved.lastRealm === this.realm.name &&
+ Number.isFinite(saved.lastTx) && Number.isFinite(saved.lastTy)) {
+ const ltx = saved.lastTx | 0, lty = saved.lastTy | 0;
+ if (inBounds(this.realm, ltx, lty) && !isBlocked(this.realm, ltx, lty)) {
+ p.tx = ltx;
+ p.ty = lty;
+ }
+ }
+
+ // Restore placed structures (Task 07) the player left in this realm.
+ // If the room is already live (reconnect), the structures may still be
+ // present under the old session id — we hand them off. If the room was
+ // freshly created (after room dispose or restart), we re-seed them.
+ const savedStructures = saved.structures?.[this.realm.name] || [];
+ if (savedStructures.length) this._restoreStructures(client, p, playerId, name, savedStructures);
}
// Register this session as the account's live presence + subscribe to its
@@ -679,6 +702,9 @@ export class GameRoom extends Room {
xp: { ...(priv?.xp || {}) },
mounted: !!p.mounted,
mount: p.mount || '',
+ // Avatar GLB URL — persisted so the player's look survives on a device that
+ // never stored it locally. Validated on restore (same rules as join time).
+ cosmetic: p.cosmetic || '',
};
}
@@ -720,6 +746,14 @@ export class GameRoom extends Room {
p.mounted = true;
p.mount = carry.mount;
}
+ // Avatar GLB URL — restored from persisted profile on fresh login (not from a
+ // portal carry, where the client already re-sends it as an option). Validated
+ // through the same allow-list as join-time so a saved URL that has since been
+ // removed from the allow-list doesn't persist to peers.
+ if (typeof carry.cosmetic === 'string' && carry.cosmetic) {
+ const validated = cleanAvatarUrl(carry.cosmetic);
+ if (validated) p.cosmetic = validated;
+ }
}
_isWalkable(tx, ty) {
@@ -805,6 +839,7 @@ export class GameRoom extends Room {
const p = this.state.players.get(client.sessionId);
if (!p || p.dead) return;
if (!this._rateOk(client.sessionId, 'fish')) return;
+ if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you fish.' }); return; }
const priv = this.priv.get(client.sessionId);
const now = Date.now();
@@ -852,6 +887,7 @@ export class GameRoom extends Room {
// XP scales gently with level + quality so richer water trains faster.
const xp = Math.round((10 + Math.floor(Math.random() * 6) + lvl * 0.3) * quality) * caught;
this._grantXp(client, p, 'fishing', xp);
+ this._questProgress(client, { kind: 'fish', item: 'fish', n: caught });
client.send('notice', { kind: 'fish', text: caught > 1 ? `Caught ${caught} fish!` : 'Caught a fish.' });
} else {
// A miss still teaches the cast — a small XP trickle keeps progression smooth.
@@ -887,6 +923,7 @@ export class GameRoom extends Room {
const p = this.state.players.get(client.sessionId);
if (!p || p.dead) return;
if (!this._rateOk(client.sessionId, 'cook')) return;
+ if (p.mounted) { client.send('notice', { kind: 'mount', text: 'Dismount before you cook.' }); return; }
const priv = this.priv.get(client.sessionId);
const now = Date.now();
@@ -937,6 +974,8 @@ export class GameRoom extends Room {
priv.cooldowns.cook = now + COOK_COOLDOWN_MS;
p.tsServer = now;
+ if (cooked > 0) this._questProgress(client, { kind: 'cook', item: 'cookedFish', n: cooked });
+
// Honest result: report exactly what the fire produced.
const parts = [];
if (cooked) parts.push(`Cooked ${cooked} fish`);
@@ -972,12 +1011,13 @@ export class GameRoom extends Room {
}
const before = p.hp;
- p.hp = Math.min(p.maxHp, p.hp + healValue(slot.item));
+ p.hp = Math.min(p.maxHp, p.hp + scaledHeal(slot.item, p.cooking));
+ const gained = p.hp - before;
slot.qty -= 1;
if (slot.qty === 0) slot.item = '';
priv.cooldowns.consume = now + CONSUME_COOLDOWN_MS;
p.tsServer = now;
- client.send('notice', { kind: 'eat', text: `+${p.hp - before} HP.` });
+ client.send('notice', { kind: 'eat', text: `+${gained} HP.` });
}
// True if the player is on or directly adjacent to any cooking tile (the Roast
@@ -1334,7 +1374,9 @@ export class GameRoom extends Room {
// Per-player cap (shack: one). Counted on the live structure map.
if (Number.isFinite(def.cap)) {
let owned = 0;
- for (const [, s] of this.state.structures) if (s.kind === kind && s.owner === p.id) owned++;
+ for (const [, s] of this.state.structures) {
+ if (s.kind === kind && this._ownedBy(s, priv.playerId)) owned++;
+ }
if (owned >= def.cap) {
client.send('notice', { kind: 'build', text: `You can only have ${def.cap} ${kind}${def.cap === 1 ? '' : 's'} — pick it up first.` });
return;
@@ -1353,6 +1395,10 @@ export class GameRoom extends Room {
const s = new Structure();
s.id = `st_${this.realm.name}_${p.id}_${++this._structSeq}`;
s.kind = kind;
+ // Store the stable account id on a server-only property so ownership
+ // survives reconnects (a new session gets a new p.id). s.owner stays the
+ // session id that the schema broadcasts to peers for client-side UI rendering.
+ s._ownerPlayerId = priv.playerId;
s.owner = p.id;
s.ownerName = p.name;
s.tx = tx;
@@ -1429,14 +1475,64 @@ export class GameRoom extends Room {
}
}
+ // Restore a player's placed structures from their persisted profile into the
+ // live room state. Handles two cases:
+ // a) Room still live (reconnect): the structure is already in state.structures
+ // under the OLD session id — update owner to the new session so pickup/lock
+ // work again. Skipped if another player's structure now occupies that tile.
+ // b) Room freshly created (after dispose or restart): re-seed the structure;
+ // skip any tile that's now blocked (another player's structure placed first).
+ // Expired firepits are silently dropped rather than resurrected.
+ _restoreStructures(client, p, playerId, playerName, savedStructures) {
+ const now = Date.now();
+ for (const sv of savedStructures) {
+ if (sv.expiresAt && sv.expiresAt <= now) continue; // firepit expired — gone
+ const tx = sv.tx | 0, ty = sv.ty | 0;
+
+ // Case (a): structure still in this live room under the old session id.
+ let found = false;
+ for (const [, s] of this.state.structures) {
+ if (s.tx === tx && s.ty === ty && s.kind === sv.kind &&
+ (s._ownerPlayerId === playerId || s.owner === client.sessionId)) {
+ s.owner = client.sessionId; // hand off to new session
+ s._ownerPlayerId = playerId;
+ found = true;
+ break;
+ }
+ }
+ if (found) continue;
+
+ // Case (b): re-seed. Check tile is clear (bounds, walkable, no other structure).
+ if (!inBounds(this.realm, tx, ty) || isBlocked(this.realm, tx, ty)) continue;
+ let blocked = false;
+ for (const [, s] of this.state.structures) {
+ if (s.tx === tx && s.ty === ty) { blocked = true; break; }
+ }
+ if (blocked) continue;
+
+ const s = new Structure();
+ s.id = `st_restore_${this.realm.name}_${client.sessionId}_${++this._structSeq}`;
+ s.kind = sv.kind;
+ s._ownerPlayerId = playerId;
+ s.owner = client.sessionId;
+ s.ownerName = playerName;
+ s.tx = tx;
+ s.ty = ty;
+ s.expiresAt = sv.expiresAt || 0;
+ s.locked = !!sv.locked;
+ this.state.structures.set(s.id, s);
+ }
+ }
+
// ----- structure actions (firepit/shack; invoked by /pickup /lock /unlock) ----
// These operate on real synced state.structures and never throw on the empty
// case: with no structure placed they honestly report "nothing placed". Only the
// owner can act, and only on a structure beside them.
pickupStructure(p) {
+ const priv = this.priv.get(p.id);
const owned = [];
- for (const [, s] of this.state.structures) if (s.owner === p.id) owned.push(s);
+ for (const [, s] of this.state.structures) if (this._ownedBy(s, priv?.playerId || p.id)) owned.push(s);
if (!owned.length) return { text: 'You have not placed a firepit or shack to pick up.', kind: 'error' };
const near = owned.filter((s) => this._adjacent(p, s)).sort((a, b) => this._d2(p, a) - this._d2(p, b));
if (!near.length) {
@@ -1450,9 +1546,11 @@ export class GameRoom extends Room {
}
setStructureLock(p, locked) {
+ const priv = this.priv.get(p.id);
let target = null;
for (const [, s] of this.state.structures) {
- if (s.owner === p.id && this._adjacent(p, s) && (!target || this._d2(p, s) < this._d2(p, target))) target = s;
+ if (this._ownedBy(s, priv?.playerId || p.id) && this._adjacent(p, s) &&
+ (!target || this._d2(p, s) < this._d2(p, target))) target = s;
}
if (!target) return { text: `Stand next to your own firepit or shack to ${locked ? 'lock' : 'unlock'} it.`, kind: 'error' };
if (target.locked === locked) return { text: `Your ${target.kind} is already ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };
@@ -1461,6 +1559,13 @@ export class GameRoom extends Room {
return { text: `${k} ${locked ? 'locked' : 'unlocked'}.`, kind: 'info' };
}
+ // A structure is "owned by" an account when _ownerPlayerId (stable account id
+ // stored at build time) or the legacy session-id owner field matches. The stable
+ // id is preferred; the fallback keeps pre-fix structures accessible.
+ _ownedBy(s, playerId) {
+ return (s._ownerPlayerId || s.owner) === playerId;
+ }
+
// Squared tile distance — cheap "nearest" ordering, no sqrt.
_d2(a, b) { const dx = a.tx - b.tx, dy = a.ty - b.ty; return dx * dx + dy * dy; }
@@ -1647,12 +1752,12 @@ export class GameRoom extends Room {
}
// --- dailies: every matching un-claimed quest advances together ---
- if (ev.kind === 'gather' || ev.kind === 'combat') {
+ if (ev.kind === 'gather' || ev.kind === 'combat' || ev.kind === 'fish' || ev.kind === 'cook') {
for (const q of qs.daily.quests) {
if (q.claimed) continue;
const def = dailyDef(q.id);
if (!def || def.type !== ev.kind) continue;
- if (def.type === 'gather' && def.item !== ev.item) continue;
+ if (def.item && def.item !== ev.item) continue;
const before = q.progress;
q.progress = Math.min(def.count, q.progress + n);
if (q.progress !== before) {
@@ -1802,9 +1907,25 @@ export class GameRoom extends Room {
next.gold = p.gold;
next.name = p.name;
// Full account-scoped profile (Task 16/23): inventory, hotbar, bank,
- // skills, and mount, so the same account loads identical progression on
- // any world instance. Same shape a portal carry uses (_serializeProfile).
+ // skills, mount, and avatar URL so the same account loads identical
+ // progression on any world instance.
next.profile = this._serializeProfile(p, priv);
+ // Last realm + tile — so a reconnecting player resumes in place rather
+ // than waking at the fountain. Danger-realm positions are still saved;
+ // onJoin skips restoring them so the player spawns safely instead.
+ next.lastRealm = this.realm.name;
+ next.lastTx = p.tx;
+ next.lastTy = p.ty;
+ // Placed structures (Task 07) keyed by realm so a shack in Whisperwood
+ // and a firepit in Mainland both survive. Each realm's list overwrites the
+ // previous save for that realm only; structures in other realms are unchanged.
+ const myStructures = [];
+ for (const [, s] of this.state.structures) {
+ if (this._ownedBy(s, priv.playerId)) {
+ myStructures.push({ kind: s.kind, tx: s.tx, ty: s.ty, expiresAt: s.expiresAt, locked: s.locked });
+ }
+ }
+ next.structures = { ...(prev.structures || {}), [this.realm.name]: myStructures };
}
if (priv.cosmetics) {
next.cosmetics = { owned: [...priv.cosmetics.owned], equipped: priv.cosmetics.equipped };
diff --git a/multiplayer/src/rooms/realms.js b/multiplayer/src/rooms/realms.js
index c46ff577e..218a76ee4 100644
--- a/multiplayer/src/rooms/realms.js
+++ b/multiplayer/src/rooms/realms.js
@@ -458,14 +458,26 @@ const ARENA = {
{ x0: 1, y0: 6, x1: 3, y1: 21 },
{ x0: 24, y0: 6, x1: 26, y1: 21 },
],
- // A clockwise circulation of moving floor: the top belt drives east, the right
- // edge south, the bottom belt west, the left edge north — a loop a fighter learns
- // to ride or break out of.
+ // A closed clockwise loop of moving floor — 34 tiles, no gaps at the corners.
+ // Each corner tile is owned by the strip that needs to push TOWARD the next
+ // strip, so a fighter circling the belt stays on it indefinitely:
+ //
+ // (8,10) east ──────────────► (18,10)
+ // ↑ ↓ right col south y10→15
+ // (8,11→16) (19,10→16)
+ // left col north ↓ (19,16) bot belt west starts here
+ // (8,16) ◄───────────── (9,16)
+ //
+ // Transition points:
+ // (18,10) east → (19,10) right col south ✓
+ // (19,15) south → (19,16) bot belt west ✓
+ // (9,16) west → (8,16) left col north ✓
+ // (8,11) north → (8,10) top belt east ✓
rollers: [
- { x0: 8, y0: 10, x1: 19, y1: 10, dir: 'e' },
- { x0: 19, y0: 11, x1: 19, y1: 15, dir: 's' },
- { x0: 8, y0: 16, x1: 19, y1: 16, dir: 'w' },
- { x0: 8, y0: 11, x1: 8, y1: 15, dir: 'n' },
+ { x0: 8, y0: 10, x1: 18, y1: 10, dir: 'e' }, // top belt x8→18
+ { x0: 19, y0: 10, x1: 19, y1: 15, dir: 's' }, // right col y10→15 (owns top-right corner)
+ { x0: 9, y0: 16, x1: 19, y1: 16, dir: 'w' }, // bottom belt x9→19 (owns bot-right corner)
+ { x0: 8, y0: 11, x1: 8, y1: 16, dir: 'n' }, // left col y11→16 (owns bot-left corner)
],
portals: [
{ x0: 12, y0: 26, x1: 15, y1: 26, to: 'mainland', toTx: 12, toTy: 21 }, // south strip → Mainland plaza
diff --git a/pages/game.html b/pages/game.html
index 83589124c..cbd162e83 100644
--- a/pages/game.html
+++ b/pages/game.html
@@ -158,6 +158,7 @@
aria-label="Type a message"
placeholder="Press Enter to chat…"
/>
+ <span id="kg-chat-counter" class="kg-chat-counter" aria-live="polite" aria-atomic="true"></span>
</form>
<!-- Muted-players view (toggled by the Muted button) -->
<div
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
index 89c3053ae..7f386b67c 100644
--- a/src/dashboard-next/pages/three-token.js
+++ b/src/dashboard-next/pages/three-token.js
@@ -12,9 +12,12 @@
import { mountShell } from '../shell.js';
import { requireUser, get, esc, relTime, ApiError } from '../api.js';
+import { fetchTokenConfig, fetchTokenPrice } from '../../token-pay.js';
const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;
-const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+// THREE_MINT is fetched live from /api/token/config below. This fallback is
+// used only for the static external links in renderTokenInfo() before config loads.
+let THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
function fmtUsd(n) {
if (n == null || !Number.isFinite(+n)) return '—';
@@ -73,8 +76,11 @@ function toast(msg) {
}
async function safeGet(url) {
- try { return await get(url); }
- catch { return null; }
+ try {
+ return await get(url);
+ } catch {
+ return null;
+ }
}
// ── Boot ──────────────────────────────────────────────────────────────────────
@@ -103,21 +109,25 @@ async function safeGet(url) {
const host = main.querySelector('[data-slot="content"]');
- const [stats, revenueShare, activity] = await Promise.all([
+ const [stats, revenueShare, activity, tokenConfig] = await Promise.all([
safeGet('/api/three-token/stats'),
safeGet('/api/three-token/revenue-share'),
safeGet('/api/three-token/activity'),
+ fetchTokenConfig().catch(() => null),
]);
+ // Update THREE_MINT from live config so external links stay correct.
+ if (tokenConfig?.mint) THREE_MINT = tokenConfig.mint;
+
host.innerHTML = '';
host.appendChild(renderHeroMetrics(stats));
host.appendChild(renderUtilityPillars(stats));
+ host.appendChild(renderLiveConverter(tokenConfig));
host.appendChild(renderRevenueShare(stats, revenueShare));
host.appendChild(renderDeployBurn(stats));
host.appendChild(renderActivityFeed(activity));
host.appendChild(renderTokenInfo());
-
} catch (err) {
if (err instanceof ApiError && err.status === 401) {
location.href = `/login?return=${encodeURIComponent(location.pathname)}`;
@@ -147,9 +157,10 @@ function renderHeroMetrics(stats) {
{
label: 'Price',
value: fmtUsd(t.price_usd),
- sub: t.price_change_24h != null
- ? `<span style="color:${pctColor(t.price_change_24h)};font-size:12px;font-weight:500">${fmtPct(t.price_change_24h)} 24h</span>`
- : '',
+ sub:
+ t.price_change_24h != null
+ ? `<span style="color:${pctColor(t.price_change_24h)};font-size:12px;font-weight:500">${fmtPct(t.price_change_24h)} 24h</span>`
+ : '',
},
{
label: 'Market Cap',
@@ -169,7 +180,8 @@ function renderHeroMetrics(stats) {
];
const wrap = document.createElement('div');
- wrap.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px';
+ wrap.style.cssText =
+ 'display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px';
metrics.forEach(({ label, value, sub }) => {
const card = document.createElement('div');
@@ -239,7 +251,8 @@ function renderUtilityPillars(stats) {
section.appendChild(header);
const grid = document.createElement('div');
- grid.style.cssText = 'display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px';
+ grid.style.cssText =
+ 'display:grid;grid-template-columns:repeat(auto-fit,minmax(260px,1fr));gap:14px';
pillars.forEach(({ icon, title, desc, metric, metricLabel, color }) => {
const card = document.createElement('div');
@@ -274,6 +287,156 @@ function renderUtilityPillars(stats) {
return section;
}
+// ── Live USD → $THREE converter ───────────────────────────────────────────────
+
+function renderLiveConverter(tokenConfig) {
+ const section = document.createElement('div');
+ section.className = 'dn-panel';
+ section.style.cssText = 'position:relative;overflow:hidden;';
+
+ const decimals = tokenConfig?.decimals ?? 6;
+ const policyRows = tokenConfig?.split_policies
+ ? Object.entries(tokenConfig.split_policies)
+ .map(
+ ([key, legs]) =>
+ `<div style="display:flex;gap:10px;align-items:center;padding:6px 0;border-bottom:1px solid var(--nxt-stroke)">
+ <span style="font-size:12px;color:var(--nxt-ink-dim);flex:0 0 160px">${esc(key.replace(/_/g, ' '))}</span>
+ ${legs
+ .map(
+ (l) =>
+ `<span style="font-size:11.5px;padding:2px 8px;border-radius:4px;background:rgba(255,255,255,.04);border:1px solid var(--nxt-stroke)">${esc(l.role)} ${(l.bps / 100).toFixed(0)}%</span>`,
+ )
+ .join('')}
+ </div>`,
+ )
+ .join('')
+ : '';
+
+ section.innerHTML = `
+ <div style="position:absolute;top:0;left:0;right:0;height:3px;background:linear-gradient(90deg,#a78bfa,#60a5fa);opacity:0.6;border-radius:2px 2px 0 0"></div>
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:20px;margin-top:4px">
+ <div>
+ <h2 style="font-size:18px;font-weight:700;margin:0 0 4px">Live USD → $THREE Converter</h2>
+ <p style="font-size:13px;color:var(--nxt-ink-dim);margin:0">Real-time price quote from Jupiter. Price updates every 30 seconds.</p>
+ </div>
+ <div data-slot="price-badge" style="display:flex;align-items:center;gap:8px;padding:6px 12px;background:rgba(167,139,250,0.08);border:1px solid rgba(167,139,250,0.15);border-radius:999px">
+ <div style="width:6px;height:6px;border-radius:50%;background:#a78bfa;animation:pulse-dot 2s ease-in-out infinite"></div>
+ <span style="font-size:12px;color:#a78bfa;font-weight:500" data-slot="price-label">fetching price…</span>
+ </div>
+ </div>
+
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:20px;align-items:start;margin-bottom:20px">
+ <div>
+ <label style="display:block;font-size:12.5px;color:var(--nxt-ink-dim);margin-bottom:8px">Amount in USD</label>
+ <div style="position:relative">
+ <span style="position:absolute;left:14px;top:50%;transform:translateY(-50%);font-size:15px;color:var(--nxt-ink-fade);pointer-events:none;font-family:${MONO}">$</span>
+ <input type="number" data-input="usd" value="1" min="0.01" step="0.01" style="
+ width:100%;box-sizing:border-box;padding:12px 14px 12px 30px;
+ background:rgba(255,255,255,0.04);border:1px solid var(--nxt-stroke);
+ border-radius:var(--nxt-radius-sm);color:var(--nxt-ink);font-size:18px;
+ font-family:${MONO};font-weight:600;outline:none;transition:border-color .15s;
+ " />
+ </div>
+ <div style="margin-top:10px;display:flex;gap:6px;flex-wrap:wrap">
+ ${[0.1, 0.5, 1, 5, 10].map((v) => `<button class="dn-btn ghost" data-quick="${v}" style="font-size:12px;padding:4px 10px">$${v}</button>`).join('')}
+ </div>
+ </div>
+
+ <div data-slot="result" style="display:flex;flex-direction:column;gap:10px">
+ <div style="padding:16px;background:rgba(167,139,250,0.06);border:1px solid rgba(167,139,250,0.12);border-radius:var(--nxt-radius-sm)">
+ <div style="font-size:11.5px;color:var(--nxt-ink-dim);margin-bottom:4px">You receive</div>
+ <div data-slot="token-amount" style="font-size:28px;font-weight:700;font-family:${MONO};color:#a78bfa;letter-spacing:-0.02em">—</div>
+ <div style="font-size:12px;color:var(--nxt-ink-fade);margin-top:3px">$THREE</div>
+ </div>
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:8px">
+ <div style="padding:10px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:8px">
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Atomics</div>
+ <div data-slot="atomics" style="font-size:12px;font-weight:500;font-family:${MONO};word-break:break-all">—</div>
+ </div>
+ <div style="padding:10px 12px;background:rgba(255,255,255,0.02);border:1px solid var(--nxt-stroke);border-radius:8px">
+ <div style="font-size:11px;color:var(--nxt-ink-fade);margin-bottom:3px">Price per token</div>
+ <div data-slot="unit-price" style="font-size:12px;font-weight:500;font-family:${MONO}">—</div>
+ </div>
+ </div>
+ </div>
+ </div>
+
+ ${
+ policyRows
+ ? `<div>
+ <div style="font-size:12.5px;color:var(--nxt-ink-dim);margin-bottom:10px;font-weight:600">Split Policies</div>
+ <div style="border-radius:8px;border:1px solid var(--nxt-stroke);overflow:hidden;padding:0 12px">${policyRows}</div>
+ </div>`
+ : ''
+ }
+
+ <style>@keyframes pulse-dot{0%,100%{opacity:1}50%{opacity:.4}}</style>
+ `;
+
+ const usdInput = section.querySelector('[data-input="usd"]');
+ const tokenAmountEl = section.querySelector('[data-slot="token-amount"]');
+ const atomicsEl = section.querySelector('[data-slot="atomics"]');
+ const unitPriceEl = section.querySelector('[data-slot="unit-price"]');
+ const priceLabelEl = section.querySelector('[data-slot="price-label"]');
+
+ let currentPrice = null;
+ let debounceTimer = null;
+
+ async function refreshPrice() {
+ try {
+ const usd = Number(usdInput.value) || 1;
+ const data = await fetchTokenPrice(usd);
+ currentPrice = data.price_usd;
+ priceLabelEl.textContent = `$${data.price_usd.toExponential(4)} / $THREE · ${data.source}`;
+ if (data.quote) {
+ tokenAmountEl.textContent = Number(data.quote.token_amount).toLocaleString(
+ undefined,
+ {
+ maximumFractionDigits: 2,
+ },
+ );
+ atomicsEl.textContent = BigInt(data.quote.atomics).toLocaleString();
+ }
+ unitPriceEl.textContent = fmtUsd(data.price_usd);
+ } catch {
+ priceLabelEl.textContent = 'price unavailable';
+ }
+ }
+
+ function scheduleRefresh(delay = 0) {
+ clearTimeout(debounceTimer);
+ debounceTimer = setTimeout(refreshPrice, delay);
+ }
+
+ usdInput.addEventListener('input', () => scheduleRefresh(300));
+ usdInput.addEventListener('focus', () => {
+ usdInput.style.borderColor = '#a78bfa';
+ });
+ usdInput.addEventListener('blur', () => {
+ usdInput.style.borderColor = '';
+ });
+
+ section.querySelectorAll('[data-quick]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ usdInput.value = btn.dataset.quick;
+ scheduleRefresh(0);
+ });
+ });
+
+ // Initial fetch + auto-refresh every 30 s
+ refreshPrice();
+ const interval = setInterval(refreshPrice, 30_000);
+ // Clean up interval when element is removed from DOM
+ new MutationObserver((_m, obs) => {
+ if (!document.contains(section)) {
+ clearInterval(interval);
+ obs.disconnect();
+ }
+ }).observe(document.body, { childList: true, subtree: true });
+
+ return section;
+}
+
// ── Revenue share calculator ──────────────────────────────────────────────────
function renderRevenueShare(stats, revenueData) {
@@ -546,8 +709,12 @@ function renderActivityFeed(activityData) {
${evt.created_at ? relTime(evt.created_at) : ''}
</div>
`;
- row.addEventListener('mouseenter', () => { row.style.background = 'rgba(255,255,255,0.04)'; });
- row.addEventListener('mouseleave', () => { row.style.background = 'rgba(255,255,255,0.015)'; });
+ row.addEventListener('mouseenter', () => {
+ row.style.background = 'rgba(255,255,255,0.04)';
+ });
+ row.addEventListener('mouseleave', () => {
+ row.style.background = 'rgba(255,255,255,0.015)';
+ });
eventsHost.appendChild(row);
});
diff --git a/src/game/iso-game.css b/src/game/iso-game.css
index 740264172..f39426934 100644
--- a/src/game/iso-game.css
+++ b/src/game/iso-game.css
@@ -99,6 +99,32 @@ body.kg-loading-cursor {
transition: width 0.2s ease;
}
+/* Speech bubble — floats above the nameplate when a player chats. Positioned
+ each frame by the label projection loop; hidden between messages.
+ The transform set by JS already includes translate(-50%, -100%) centering;
+ we only need padding/background/shape here. */
+.kg-chat-bubble {
+ position: absolute;
+ top: 0;
+ left: 0;
+ will-change: transform;
+ max-width: 200px;
+ padding: 5px 10px;
+ background: rgba(13, 20, 32, 0.88);
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ border-radius: 10px;
+ font-size: 12px;
+ color: var(--kg-text);
+ text-shadow: 0 1px 3px rgba(0, 0, 0, 0.8);
+ white-space: pre-wrap;
+ overflow-wrap: anywhere;
+ pointer-events: none;
+ line-height: 1.4;
+ transition: opacity 0.4s ease;
+}
+.kg-chat-bubble[hidden] { display: none; }
+.kg-chat-bubble--fade { opacity: 0; }
+
/* Top bar: realm + online + connection status. */
#kg-topbar {
position: fixed;
@@ -792,6 +818,23 @@ body.kg-loading-cursor {
position: relative; /* anchors the slash-command autocomplete above the input */
}
+/* Character counter — appears once the message exceeds 160 chars, right-aligned
+ inside the form so it overlays the trailing edge of the input without taking up
+ layout space. */
+.kg-chat-counter {
+ position: absolute;
+ right: 10px;
+ top: 50%;
+ transform: translateY(-50%);
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ color: var(--kg-dim);
+ pointer-events: none;
+ transition: color 0.15s;
+}
+.kg-chat-counter[data-state="warn"] { color: #f0a830; }
+.kg-chat-counter[data-state="danger"] { color: #ff5a5a; font-weight: 700; }
+
/* Slash-command autocomplete — floats just above the chat input. */
.kg-chat-hint {
position: absolute;
diff --git a/src/game/iso-game.js b/src/game/iso-game.js
index c1dd42908..d6873536f 100644
--- a/src/game/iso-game.js
+++ b/src/game/iso-game.js
@@ -67,6 +67,13 @@ const fmtXp = (n) => Math.round(n).toLocaleString('en-US');
const EDIBLE = new Set(['cookedFish', 'healthPotion']);
const FOOD_LABEL = { cookedFish: 'cooked fish', healthPotion: 'potion' };
+// Mirrors items.js#scaledHeal so the Eat button can preview the exact heal value
+// without a round-trip. Must stay in sync with the server formula.
+function clientScaledHeal(item, baseHeal, cookingLevel) {
+ if (item === 'cookedFish') return (baseHeal || 0) + Math.floor((Math.max(1, cookingLevel | 0) - 1) * 0.3);
+ return baseHeal || 0;
+}
+
// Player-built structures (Task 07): presentation only — icon, label, and a short
// pitch for the build menu. The realm's allowed kinds and the authoritative costs
// arrive from the server (the realm message's `buildCatalog`), so this never
@@ -148,6 +155,14 @@ class GamePlayerView {
document.getElementById('kg-labels')?.appendChild(this.label);
this._renderHp();
+ // Speech bubble: floats just above the nameplate when this player chats.
+ // Positioned each frame alongside the nameplate so it tracks movement.
+ this.bubble = document.createElement('div');
+ this.bubble.className = 'kg-chat-bubble';
+ this.bubble.hidden = true;
+ document.getElementById('kg-labels')?.appendChild(this.bubble);
+ this._bubbleTimer = null;
+
// Mount visuals (Task 09): a steed mesh + saddle lift, attached in applyMount.
this.mounted = false;
this._steed = null;
@@ -319,11 +334,29 @@ class GamePlayerView {
return g;
}
+ // Show a speech bubble above this avatar for a few seconds, then fade it out.
+ showBubble(text) {
+ if (this._bubbleTimer) { clearTimeout(this._bubbleTimer); this._bubbleTimer = null; }
+ this.bubble.textContent = text;
+ this.bubble.hidden = false;
+ this.bubble.classList.remove('kg-chat-bubble--fade');
+ this._bubbleTimer = setTimeout(() => {
+ this.bubble.classList.add('kg-chat-bubble--fade');
+ this._bubbleTimer = setTimeout(() => {
+ this.bubble.hidden = true;
+ this.bubble.classList.remove('kg-chat-bubble--fade');
+ this._bubbleTimer = null;
+ }, 400);
+ }, 5000);
+ }
+
dispose() {
this._disposeCosmetic();
+ if (this._bubbleTimer) clearTimeout(this._bubbleTimer);
this.scene.remove(this.rig);
if (this._steed) this.scene.remove(this._steed);
this.label.remove();
+ this.bubble.remove();
}
}
@@ -2260,7 +2293,10 @@ export class IsoGame {
const edible = this._findEdibleSlot(ps);
const showEat = ps.hp < ps.maxHp && !!edible;
this._eatRef = showEat ? edible.ref : null;
- this._toggleAction(this.hud.eatBtn, showEat, showEat ? `Eat ${edible.label} (${edible.count})` : 'Eat');
+ const eatLabel = showEat
+ ? `Eat ${edible.label} (+${edible.healEst} HP, ${edible.count} left)`
+ : 'Eat';
+ this._toggleAction(this.hud.eatBtn, showEat, eatLabel);
// Cast: standing beside fishable water. The rod auto-equips on cast, so the
// button just reflects whether the player owns one — when they don't, it
@@ -2303,12 +2339,19 @@ export class IsoGame {
}
// The first edible slot — hotbar before backpack — with the server-resolvable
- // {zone,i} ref, a friendly label, and how many of that food the player holds.
+ // {zone,i} ref, a friendly label, how many of that food the player holds, and
+ // an estimated heal value so the Eat button can show "+N HP" without a server
+ // round-trip (mirrors the scaledHeal formula in items.js).
_findEdibleSlot(ps) {
+ const reg = this.items || {};
+ const cookLvl = ps.cooking || 1;
const scan = (arr, zone) => {
for (let i = 0; i < arr.length; i++) {
const it = arr[i].item;
- if (it && EDIBLE.has(it)) return { ref: { zone, i }, item: it, label: FOOD_LABEL[it] || 'food', count: this._countItem(ps, it) };
+ if (!it || !EDIBLE.has(it)) continue;
+ const baseHeal = reg[it]?.heal || 0;
+ const healEst = clientScaledHeal(it, baseHeal, cookLvl);
+ return { ref: { zone, i }, item: it, label: FOOD_LABEL[it] || 'food', count: this._countItem(ps, it), healEst };
}
return null;
};
@@ -2732,6 +2775,7 @@ export class IsoGame {
chatForm: document.getElementById('kg-chat-form'),
chatInput: document.getElementById('kg-chat-input'),
chatHint: document.getElementById('kg-chat-hint'),
+ chatCounter: document.getElementById('kg-chat-counter'),
chatMutedBtn: document.getElementById('kg-chat-muted-btn'),
chatMutedN: document.getElementById('kg-chat-muted-n'),
chatMutedList: document.getElementById('kg-chat-muted'),
@@ -2860,8 +2904,8 @@ export class IsoGame {
if (this.hud.chat?.contains(e.relatedTarget)) return;
if (!this.hud.chatInput.value.trim()) this._closeChat();
});
- // Slash-command autocomplete: refresh the hint list on every edit.
- this.hud.chatInput?.addEventListener('input', () => this._refreshCmdHint());
+ // Slash-command autocomplete + character counter: refresh on every edit.
+ this.hud.chatInput?.addEventListener('input', () => { this._refreshCmdHint(); this._updateChatCounter(); });
this.hud.chatInput?.addEventListener('keydown', (e) => {
// Esc: first dismiss an open command hint, otherwise clear + close chat.
if (e.key === 'Escape') {
@@ -3030,6 +3074,7 @@ export class IsoGame {
const text = input.value.trim();
input.value = '';
this._hideCmdHint();
+ this._updateChatCounter();
if (!text) { this._closeChat(); return; }
// Server is authoritative: it sanitizes, rate-limits, routes `/commands`, and
// echoes accepted messages back to everyone (us included) as 'chat' events.
@@ -3037,6 +3082,25 @@ export class IsoGame {
input.focus(); // keep the field hot for a flowing conversation
}
+ // Show remaining-character count once the player has used ≥ 160 chars (the
+ // last 40 chars matter). Turns amber at 180, red at 195. Hidden when empty or
+ // well under the limit so it never clutters a short message.
+ _updateChatCounter() {
+ const el = this.hud.chatCounter;
+ const input = this.hud.chatInput;
+ if (!el || !input) return;
+ const len = input.value.length;
+ const max = input.maxLength || 200;
+ const rem = max - len;
+ if (len < 160) {
+ el.textContent = '';
+ el.dataset.state = '';
+ return;
+ }
+ el.textContent = String(rem);
+ el.dataset.state = rem <= 5 ? 'danger' : rem <= 20 ? 'warn' : 'ok';
+ }
+
_onChat(msg) {
if (!msg || typeof msg.text !== 'string') return;
const line = this._appendChatLine(msg);
@@ -3047,6 +3111,13 @@ export class IsoGame {
return;
}
this._scrollChat();
+ // Show a speech bubble above the sender's avatar in the 3D world (non-system
+ // messages only; commands/errors stay in the panel). Local player included so
+ // they see their own message confirmed above their head immediately.
+ if (!msg.system && msg.id) {
+ const pv = this.players.get(msg.id);
+ pv?.showBubble(msg.text);
+ }
}
_appendChatLine(msg) {
@@ -3069,6 +3140,13 @@ export class IsoGame {
nameEl.type = 'button';
nameEl.className = 'kg-chat-name' + (isMe ? ' kg-chat-name--me' : '');
nameEl.textContent = name;
+ // Apply the sender's world-assigned color so the name in chat matches the
+ // floating nameplate above their avatar. Falls back to the CSS accent color
+ // when the player isn't in the current state (e.g., they left mid-session).
+ if (!isMe && msg.id) {
+ const col = this.net?.state?.players?.get(msg.id)?.color;
+ if (col) nameEl.style.color = '#' + col.toString(16).padStart(6, '0');
+ }
if (isMe) {
nameEl.disabled = true;
} else {
@@ -3285,14 +3363,31 @@ export class IsoGame {
const w = window.innerWidth, h = window.innerHeight;
const v = new Vector3();
for (const [, pv] of this.players) {
- if (pv.dead) { pv.label.style.display = 'none'; continue; }
+ if (pv.dead) {
+ pv.label.style.display = 'none';
+ pv.bubble.style.display = 'none';
+ continue;
+ }
v.set(pv.rig.position.x, pv.height + 0.35, pv.rig.position.z).project(this.camera);
const behind = v.z > 1;
- if (behind) { pv.label.style.display = 'none'; continue; }
- pv.label.style.display = '';
+ if (behind) {
+ pv.label.style.display = 'none';
+ pv.bubble.style.display = 'none';
+ continue;
+ }
const sx = (v.x * 0.5 + 0.5) * w;
const sy = (-v.y * 0.5 + 0.5) * h;
- pv.label.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
+ const t = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${sy.toFixed(1)}px)`;
+ pv.label.style.display = '';
+ pv.label.style.transform = t;
+ // Speech bubble sits above the nameplate — offset up by an extra ~30px so
+ // it clears the name row and reads distinctly.
+ if (!pv.bubble.hidden) {
+ pv.bubble.style.display = '';
+ pv.bubble.style.transform = `translate(-50%, -100%) translate(${sx.toFixed(1)}px, ${(sy - 32).toFixed(1)}px)`;
+ } else {
+ pv.bubble.style.display = 'none';
+ }
}
}
diff --git a/tests/cooking.test.js b/tests/cooking.test.js
index db79308b4..c3c609d68 100644
--- a/tests/cooking.test.js
+++ b/tests/cooking.test.js
@@ -1,12 +1,12 @@
// Task 06 — cooking & edible food. These cover the data-driven core the cooking
// feature rests on: the item registry's edibility/heal/stack facts (which the
-// server's consume handler reads) and the burn-chance curve (which the cook
-// handler rolls against). Both live in the dependency-free items module so they
-// can be asserted without standing up a Colyseus room.
+// server's consume handler reads), the burn-chance curve (which the cook handler
+// rolls against), level-scaled healing, and the daily quest pool entries.
import { describe, it, expect } from 'vitest';
import {
- ITEMS, STACKABLE_ITEMS, isEdible, isStackable, healValue, cookBurnChance,
+ ITEMS, STACKABLE_ITEMS, isEdible, isStackable, healValue, scaledHeal, cookBurnChance, clientItemRegistry,
} from '../multiplayer/src/items.js';
+import { DAILY_POOL, BADGES } from '../multiplayer/src/quests.js';
describe('item registry — consumables', () => {
it('cooked fish is a stackable, edible heal of 11', () => {
@@ -66,3 +66,73 @@ describe('cookBurnChance — fair, falling burn curve', () => {
expect(cookBurnChance(38)).toBe(0);
});
});
+
+describe('scaledHeal — cooking level makes food better', () => {
+ it('level 1 cook heals the base 11 HP', () => {
+ expect(scaledHeal('cookedFish', 1)).toBe(11);
+ });
+
+ it('heal improves with cooking level', () => {
+ expect(scaledHeal('cookedFish', 10)).toBeGreaterThan(scaledHeal('cookedFish', 1));
+ expect(scaledHeal('cookedFish', 50)).toBeGreaterThan(scaledHeal('cookedFish', 10));
+ expect(scaledHeal('cookedFish', 99)).toBeGreaterThan(scaledHeal('cookedFish', 50));
+ });
+
+ it('potions return their flat base value regardless of cooking level', () => {
+ const base = healValue('healthPotion');
+ expect(scaledHeal('healthPotion', 1)).toBe(base);
+ expect(scaledHeal('healthPotion', 99)).toBe(base);
+ });
+
+ it('non-edibles and unknown items always return 0', () => {
+ expect(scaledHeal('fish', 99)).toBe(0);
+ expect(scaledHeal('axe', 99)).toBe(0);
+ expect(scaledHeal('nonexistent', 10)).toBe(0);
+ });
+
+ it('below-floor levels clamp to level 1 (no negative bonuses)', () => {
+ expect(scaledHeal('cookedFish', 0)).toBe(scaledHeal('cookedFish', 1));
+ expect(scaledHeal('cookedFish', -5)).toBe(scaledHeal('cookedFish', 1));
+ });
+});
+
+describe('clientItemRegistry — heal exposed to client', () => {
+ it('edible items carry their base heal in the client registry', () => {
+ const reg = clientItemRegistry();
+ expect(reg.cookedFish.heal).toBe(11);
+ expect(reg.healthPotion.heal).toBe(28);
+ });
+
+ it('non-edible items have no heal key', () => {
+ const reg = clientItemRegistry();
+ expect(reg.fish.heal).toBeUndefined();
+ expect(reg.axe.heal).toBeUndefined();
+ });
+});
+
+describe('daily quest pool — fishing and cooking quests exist', () => {
+ it('pool contains at least one fishing quest', () => {
+ const fishQuests = DAILY_POOL.filter((q) => q.type === 'fish');
+ expect(fishQuests.length).toBeGreaterThan(0);
+ for (const q of fishQuests) {
+ expect(q.id).toBeTruthy();
+ expect(q.item).toBe('fish');
+ expect(q.count).toBeGreaterThan(0);
+ expect(q.reward).toBeDefined();
+ }
+ });
+
+ it('pool contains at least one cooking quest', () => {
+ const cookQuests = DAILY_POOL.filter((q) => q.type === 'cook');
+ expect(cookQuests.length).toBeGreaterThan(0);
+ for (const q of cookQuests) {
+ expect(q.item).toBe('cookedFish');
+ expect(q.count).toBeGreaterThan(0);
+ }
+ });
+
+ it('fishing and cooking badges are defined', () => {
+ expect(BADGES.fisher).toBeDefined();
+ expect(BADGES.pitcook).toBeDefined();
+ });
+});
diff --git a/tests/game-loot-mounts.test.js b/tests/game-loot-mounts.test.js
new file mode 100644
index 000000000..5da2756d7
--- /dev/null
+++ b/tests/game-loot-mounts.test.js
@@ -0,0 +1,208 @@
+import { describe, it, expect } from 'vitest';
+import {
+ LOOT_TABLES,
+ rollLoot,
+ isMount,
+ mountStepMs,
+ itemLabel,
+ itemDef,
+ isStackable,
+} from '../multiplayer/src/items.js';
+
+// ---------------------------------------------------------------------------
+// Loot tables
+// ---------------------------------------------------------------------------
+
+describe('LOOT_TABLES', () => {
+ it('dummy drops nothing', () => {
+ expect(LOOT_TABLES.dummy).toEqual([]);
+ });
+
+ it('goblin table contains bones, hide, coal, dire_wolf', () => {
+ const ids = LOOT_TABLES.goblin.map((e) => e.item);
+ expect(ids).toContain('bones');
+ expect(ids).toContain('hide');
+ expect(ids).toContain('coal');
+ expect(ids).toContain('dire_wolf');
+ });
+
+ it('ogre table contains bones, hide, stone, dire_wolf, war_boar', () => {
+ const ids = LOOT_TABLES.ogre.map((e) => e.item);
+ expect(ids).toContain('bones');
+ expect(ids).toContain('hide');
+ expect(ids).toContain('stone');
+ expect(ids).toContain('dire_wolf');
+ expect(ids).toContain('war_boar');
+ });
+
+ it('all chances are in (0, 1]', () => {
+ for (const [kind, table] of Object.entries(LOOT_TABLES)) {
+ for (const entry of table) {
+ expect(entry.chance, `${kind}.${entry.item} chance`).toBeGreaterThan(0);
+ expect(entry.chance, `${kind}.${entry.item} chance`).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it('mount entries have no min/max (qty always 1)', () => {
+ for (const table of Object.values(LOOT_TABLES)) {
+ for (const entry of table) {
+ if (isMount(entry.item)) {
+ expect(entry.min).toBeUndefined();
+ expect(entry.max).toBeUndefined();
+ }
+ }
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// rollLoot
+// ---------------------------------------------------------------------------
+
+describe('rollLoot', () => {
+ it('returns [] for dummy', () => {
+ // Always-drop rng still gets nothing from dummy.
+ expect(rollLoot('dummy', () => 0)).toEqual([]);
+ });
+
+ it('returns [] for unknown kind', () => {
+ expect(rollLoot('dragon', () => 0)).toEqual([]);
+ });
+
+ it('drops all goblin items when rng always passes (returns 0)', () => {
+ const drops = rollLoot('goblin', () => 0);
+ const ids = drops.map((d) => d.item);
+ expect(ids).toContain('bones');
+ expect(ids).toContain('hide');
+ expect(ids).toContain('coal');
+ expect(ids).toContain('dire_wolf');
+ });
+
+ it('drops nothing when rng always fails (returns 1)', () => {
+ // rng() >= chance for every entry → nothing rolls.
+ expect(rollLoot('goblin', () => 1)).toEqual([]);
+ expect(rollLoot('ogre', () => 1)).toEqual([]);
+ });
+
+ it('mount entries always have qty 1', () => {
+ const drops = rollLoot('ogre', () => 0);
+ for (const d of drops) {
+ if (isMount(d.item)) expect(d.qty).toBe(1);
+ }
+ });
+
+ it('stackable entries respect min/max', () => {
+ // rng returns 0 → qty = min + 0*(max-min) = min
+ const drops = rollLoot('ogre', () => 0);
+ const bones = drops.find((d) => d.item === 'bones');
+ expect(bones).toBeDefined();
+ expect(bones.qty).toBe(1); // min of ogre bones entry
+
+ // rng returns 0 for chance check, then 1 for qty roll → qty = max
+ let callCount = 0;
+ const rngMax = () => {
+ callCount++;
+ // First call is the chance roll (0 → passes); subsequent calls are qty rolls.
+ return callCount === 1 ? 0 : 0.9999;
+ };
+ const drops2 = rollLoot('goblin', rngMax);
+ const bones2 = drops2.find((d) => d.item === 'bones');
+ expect(bones2).toBeDefined();
+ expect(bones2.qty).toBe(2); // max of goblin bones entry
+ });
+
+ it('statistical: goblin mount drop rate ~5% over many rolls', () => {
+ const N = 50_000;
+ let mounts = 0;
+ for (let i = 0; i < N; i++) {
+ const drops = rollLoot('goblin');
+ if (drops.some((d) => isMount(d.item))) mounts++;
+ }
+ const rate = mounts / N;
+ // 5% chance; expect within ±2% with high confidence over 50k trials.
+ expect(rate).toBeGreaterThan(0.03);
+ expect(rate).toBeLessThan(0.09);
+ });
+
+ it('statistical: ogre mount drop rate ~17% (7% wolf + 10% boar, independent)', () => {
+ const N = 50_000;
+ let kills = 0;
+ for (let i = 0; i < N; i++) {
+ const drops = rollLoot('ogre');
+ if (drops.some((d) => isMount(d.item))) kills++;
+ }
+ const rate = kills / N;
+ // ~17% overall (can drop both on a lucky kill, so slightly less than sum).
+ expect(rate).toBeGreaterThan(0.13);
+ expect(rate).toBeLessThan(0.21);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Mount item registry
+// ---------------------------------------------------------------------------
+
+describe('isMount', () => {
+ it('recognises dire_wolf and war_boar as mounts', () => {
+ expect(isMount('dire_wolf')).toBe(true);
+ expect(isMount('war_boar')).toBe(true);
+ });
+
+ it('returns false for tools and resources', () => {
+ expect(isMount('sword')).toBe(false);
+ expect(isMount('axe')).toBe(false);
+ expect(isMount('bones')).toBe(false);
+ expect(isMount('hide')).toBe(false);
+ expect(isMount('healthPotion')).toBe(false);
+ });
+
+ it('returns false for unknown ids', () => {
+ expect(isMount('')).toBe(false);
+ expect(isMount('dragon')).toBe(false);
+ });
+});
+
+describe('mountStepMs', () => {
+ it('dire_wolf is faster than on-foot (140ms)', () => {
+ expect(mountStepMs('dire_wolf')).toBeLessThan(140);
+ });
+
+ it('war_boar is faster than on-foot (140ms)', () => {
+ expect(mountStepMs('war_boar')).toBeLessThan(140);
+ });
+
+ it('dire_wolf is faster than war_boar', () => {
+ expect(mountStepMs('dire_wolf')).toBeLessThan(mountStepMs('war_boar'));
+ });
+
+ it('returns null for non-mount items', () => {
+ expect(mountStepMs('sword')).toBeNull();
+ expect(mountStepMs('bones')).toBeNull();
+ expect(mountStepMs('')).toBeNull();
+ });
+});
+
+describe('mount item definitions', () => {
+ it('mounts are non-stackable', () => {
+ expect(isStackable('dire_wolf')).toBe(false);
+ expect(isStackable('war_boar')).toBe(false);
+ });
+
+ it('mounts have labels', () => {
+ expect(itemLabel('dire_wolf')).toBeTruthy();
+ expect(itemLabel('war_boar')).toBeTruthy();
+ });
+
+ it('mount def includes color, accent, scale', () => {
+ const wolf = itemDef('dire_wolf');
+ expect(wolf.mount.color).toBeDefined();
+ expect(wolf.mount.accent).toBeDefined();
+ expect(wolf.mount.scale).toBeDefined();
+
+ const boar = itemDef('war_boar');
+ expect(boar.mount.color).toBeDefined();
+ expect(boar.mount.accent).toBeDefined();
+ expect(boar.mount.scale).toBeDefined();
+ });
+});
diff --git a/tests/player-store.test.js b/tests/player-store.test.js
index 45d425d79..a2fdc837d 100644
--- a/tests/player-store.test.js
+++ b/tests/player-store.test.js
@@ -54,9 +54,21 @@ function sampleProfile() {
bank: [{ item: 'coal', qty: 30 }],
activeSlot: 2,
xp: { combat: 1500, woodcutting: 3000, mining: 200, fishing: 75, cooking: 640 },
- hp: 88, maxHp: 100, mount: 'horse', realm: 'whisperwood', tx: 12, ty: 7,
+ hp: 88, maxHp: 100, mount: 'horse',
+ cosmetic: 'https://cdn.three.ws/avatars/nico.glb',
},
cosmetics: { owned: ['hat_red', 'cape_blue', 'crown_gold'], equipped: 'crown_gold' },
+ lastRealm: 'whisperwood',
+ lastTx: 12,
+ lastTy: 7,
+ structures: {
+ whisperwood: [
+ { kind: 'shack', tx: 14, ty: 7, expiresAt: 0, locked: false },
+ ],
+ mainland: [
+ { kind: 'firepit', tx: 5, ty: 3, expiresAt: Date.now() + 900000, locked: false },
+ ],
+ },
};
}
@@ -76,8 +88,15 @@ describe('PlayerStore — synchronous cache API', () => {
expect(got.profile.xp.cooking).toBe(640);
expect(got.cosmetics.equipped).toBe('crown_gold');
expect(got.quests.tutorial.done).toBe(true);
- expect(typeof got.savedAt).toBe('number'); // stamped for the cache sweep
+ expect(typeof got.savedAt).toBe('number');
expect(s.hasPlayer('acct')).toBe(true);
+ // avatar URL, last position, placed structures all round-trip
+ expect(got.profile.cosmetic).toBe('https://cdn.three.ws/avatars/nico.glb');
+ expect(got.lastRealm).toBe('whisperwood');
+ expect(got.lastTx).toBe(12);
+ expect(got.lastTy).toBe(7);
+ expect(got.structures.whisperwood[0].kind).toBe('shack');
+ expect(got.structures.mainland[0].kind).toBe('firepit');
});
it('supports the read-merge-write the GameRoom uses to persist one slice at a time', async () => {
@@ -87,7 +106,11 @@ describe('PlayerStore — synchronous cache API', () => {
const prev = s.loadPlayer('acct') || {};
s.savePlayer('acct', { ...prev, gold: 9999 });
expect(s.loadPlayer('acct').gold).toBe(9999);
- expect(s.loadPlayer('acct').profile.inv[0].qty).toBe(120); // other fields preserved
+ expect(s.loadPlayer('acct').profile.inv[0].qty).toBe(120);
+ // structures, last position, avatar survive the merge
+ expect(s.loadPlayer('acct').structures.whisperwood[0].kind).toBe('shack');
+ expect(s.loadPlayer('acct').lastRealm).toBe('whisperwood');
+ expect(s.loadPlayer('acct').profile.cosmetic).toBe('https://cdn.three.ws/avatars/nico.glb');
});
});
@@ -116,9 +139,34 @@ describe('PlayerStore (durable / Upstash)', () => {
expect(restored.gold).toBe(4242);
expect(b.loadPlayer('wallet:0xABC').profile.inv[0].qty).toBe(120);
expect(b.loadPlayer('wallet:0xABC').profile.xp.cooking).toBe(640);
- expect(b.loadPlayer('wallet:0xABC').profile.realm).toBe('whisperwood');
expect(b.loadPlayer('wallet:0xABC').cosmetics.equipped).toBe('crown_gold');
expect(b.loadPlayer('wallet:0xABC').quests.tutorial.done).toBe(true);
+ // The three new fields survive a restart too.
+ expect(b.loadPlayer('wallet:0xABC').profile.cosmetic).toBe('https://cdn.three.ws/avatars/nico.glb');
+ expect(b.loadPlayer('wallet:0xABC').lastRealm).toBe('whisperwood');
+ expect(b.loadPlayer('wallet:0xABC').lastTx).toBe(12);
+ expect(b.loadPlayer('wallet:0xABC').structures.whisperwood[0].kind).toBe('shack');
+ expect(b.loadPlayer('wallet:0xABC').structures.mainland[0].kind).toBe('firepit');
+ });
+
+ it('structure list is realm-keyed so buildings in different realms coexist', async () => {
+ const s = await freshStore();
+ await s.playerStoreReady();
+ const base = sampleProfile();
+ s.savePlayer('acct', base);
+ // Simulate GameRoom persisting the mainland realm (updates mainland list only)
+ const prev = s.loadPlayer('acct') || {};
+ s.savePlayer('acct', {
+ ...prev,
+ structures: { ...(prev.structures || {}), mainland: [{ kind: 'firepit', tx: 2, ty: 2, expiresAt: 0, locked: true }] },
+ });
+ const got = s.loadPlayer('acct');
+ // whisperwood shack is untouched; mainland updated
+ expect(got.structures.whisperwood[0].kind).toBe('shack');
+ expect(got.structures.mainland[0].tx).toBe(2);
+ expect(got.structures.mainland[0].locked).toBe(true);
+ await s.flushAllPlayers();
+ expect(JSON.parse(redis.store.get('player:acct')).structures.whisperwood[0].kind).toBe('shack');
});
it('hydrates a never-seen account to null so a new player gets the starter kit, not a reset', async () => {
diff --git a/tests/realms-arena.test.js b/tests/realms-arena.test.js
index 43eb10c29..3bd95e7ff 100644
--- a/tests/realms-arena.test.js
+++ b/tests/realms-arena.test.js
@@ -174,6 +174,35 @@ describe('Arena rollers — direction + walkable footprint', () => {
}
});
+ it('the four circuit corners all connect to the next strip (no broken corners)', () => {
+ const corners = [
+ { tx: 8, ty: 10, name: 'top-left' },
+ { tx: 19, ty: 10, name: 'top-right' },
+ { tx: 19, ty: 16, name: 'bot-right' },
+ { tx: 8, ty: 16, name: 'bot-left' },
+ ];
+ for (const c of corners) {
+ const r = rollerAt(arena, c.tx, c.ty);
+ expect(r, `${c.name} (${c.tx},${c.ty}) must be on a roller`).toBeTruthy();
+ const [dx, dy] = rollerDelta(r.dir);
+ const next = rollerAt(arena, c.tx + dx, c.ty + dy);
+ expect(next, `${c.name} push must land on the next strip, not dead floor`).toBeTruthy();
+ }
+ });
+
+ it('a full circuit trace from the top-left returns to start (closed loop)', () => {
+ const DELTA = { n: [0, -1], s: [0, 1], e: [1, 0], w: [-1, 0] };
+ let tx = 8, ty = 10;
+ for (let step = 0; step < 60; step++) {
+ const r = rollerAt(arena, tx, ty);
+ if (!r) throw new Error(`lost circuit at (${tx},${ty}) after ${step} steps`);
+ const [dx, dy] = DELTA[r.dir];
+ tx += dx; ty += dy;
+ if (tx === 8 && ty === 10) return; // closed
+ }
+ throw new Error('circuit did not close within 60 steps');
+ });
+
it('rollerAt is null off the belts (the spawn floor is free)', () => {
expect(rollerAt(arena, arena.spawn.tx, arena.spawn.ty)).toBeNull();
});
diff --git a/tests/token-layer.test.js b/tests/token-layer.test.js
new file mode 100644
index 000000000..5e3e76d06
--- /dev/null
+++ b/tests/token-layer.test.js
@@ -0,0 +1,537 @@
+// Unit tests for the $THREE on-chain token layer (api/_lib/token/*).
+//
+// All external calls are mocked: no live RPC, no DB, no cache. The tests
+// prove the cryptographic correctness of the quote lifecycle, split math,
+// boot guards, and on-chain verification logic — the parts that must never
+// be wrong in production.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+// ── Mocks ────────────────────────────────────────────────────────────────────
+
+vi.mock('../api/_lib/cache.js', () => ({
+ cacheGet: vi.fn(async () => null),
+ cacheSet: vi.fn(async () => {}),
+ cacheDel: vi.fn(async () => {}),
+}));
+
+vi.mock('../api/_lib/db.js', () => {
+ const queue = [];
+ const sql = vi.fn(async () => (queue.length ? queue.shift() : []));
+ sql.__queue = queue;
+ return { sql };
+});
+
+// Module-level variable controlled per test so the Connection mock (a real
+// class) can return different parsed tx responses without needing vi.fn
+// as a constructor argument (arrow functions aren't constructors).
+let _mockTxResponse = undefined;
+vi.mock('@solana/web3.js', async (importOriginal) => {
+ const real = await importOriginal();
+ class MockConnection {
+ // eslint-disable-next-line no-unused-vars
+ constructor(_url, _commitment) {}
+ async getParsedTransaction() {
+ if (_mockTxResponse === undefined) throw new Error('tx_not_found_mock');
+ return _mockTxResponse;
+ }
+ }
+ return { ...real, Connection: MockConnection };
+});
+
+// Controlled fetch: set responses per-test via mockFetch.
+let fetchResponses = [];
+const mockFetch = (url, opts = {}) => {
+ const resp = fetchResponses.shift();
+ if (!resp) throw new Error(`Unexpected fetch: ${url}`);
+ if (resp.error) return Promise.reject(resp.error);
+ const body = resp.body;
+ return Promise.resolve({
+ ok: resp.ok ?? true,
+ status: resp.status ?? 200,
+ json: async () => (typeof body === 'string' ? JSON.parse(body) : body),
+ text: async () => String(resp.status ?? 200),
+ });
+};
+vi.stubGlobal('fetch', mockFetch);
+
+// ── Imports (after mocks) ─────────────────────────────────────────────────────
+
+import {
+ TOKEN_MINT,
+ TOKEN_DECIMALS,
+ ATOMICS_PER_TOKEN,
+ SPLIT_POLICIES,
+ resolveSplitLegs,
+ applySplit,
+ treasuryWallet,
+ burnAddress,
+ publicConfig,
+} from '../api/_lib/token/config.js';
+import { getTokenPriceUsd, quoteTokenForUsd, atomicsToTokens } from '../api/_lib/token/price.js';
+import { issueQuote, verifyQuote } from '../api/_lib/token/quote.js';
+import { verifyOnChain } from '../api/_lib/token/payments.js';
+import { cacheGet, cacheSet } from '../api/_lib/cache.js';
+import { sql } from '../api/_lib/db.js';
+
+beforeEach(() => {
+ fetchResponses = [];
+ vi.clearAllMocks();
+ cacheGet.mockResolvedValue(null);
+ cacheSet.mockResolvedValue();
+ sql.mockResolvedValue([]);
+});
+
+afterEach(() => {
+ if (fetchResponses.length) {
+ throw new Error(`Test left ${fetchResponses.length} unconsumed fetch mock(s)`);
+ }
+});
+
+// ── Config ────────────────────────────────────────────────────────────────────
+
+describe('token config', () => {
+ it('exports the canonical $THREE mint', () => {
+ expect(TOKEN_MINT).toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+ });
+
+ it('exports 6 decimals and correct atomics multiplier', () => {
+ expect(TOKEN_DECIMALS).toBe(6);
+ expect(ATOMICS_PER_TOKEN).toBe(1_000_000n);
+ });
+
+ it('burnAddress returns the incinerator', () => {
+ expect(burnAddress()).toBe('1nc1nerator11111111111111111111111111111111');
+ });
+
+ it('publicConfig includes expected fields', () => {
+ const c = publicConfig();
+ expect(c.mint).toBe(TOKEN_MINT);
+ expect(c.symbol).toBe('$THREE');
+ expect(c.decimals).toBe(6);
+ expect(c.burn_address).toBe('1nc1nerator11111111111111111111111111111111');
+ expect(c.quote_ttl_seconds).toBeGreaterThan(0);
+ expect(c.split_policies.spin).toBeDefined();
+ expect(c.split_policies.marketplace_sale).toBeDefined();
+ });
+
+ it('treasuryWallet warns in dev when unset and falls back to burn', () => {
+ const prior = process.env.THREE_TREASURY_WALLET;
+ delete process.env.THREE_TREASURY_WALLET;
+ const w = treasuryWallet();
+ expect(w).toBe(burnAddress());
+ if (prior !== undefined) process.env.THREE_TREASURY_WALLET = prior;
+ });
+
+ it('treasuryWallet throws in production when unset', () => {
+ const priorNode = process.env.NODE_ENV;
+ const priorWallet = process.env.THREE_TREASURY_WALLET;
+ process.env.NODE_ENV = 'production';
+ delete process.env.THREE_TREASURY_WALLET;
+ expect(() => treasuryWallet()).toThrow(/THREE_TREASURY_WALLET/);
+ process.env.NODE_ENV = priorNode;
+ if (priorWallet !== undefined) process.env.THREE_TREASURY_WALLET = priorWallet;
+ });
+});
+
+// ── Split policy ───────────────────────────────────────────────────────────────
+
+describe('resolveSplitLegs', () => {
+ it('spin policy yields burn + treasury legs summing to 10000 bps', () => {
+ const legs = resolveSplitLegs('spin');
+ expect(legs).toHaveLength(2);
+ const total = legs.reduce((s, l) => s + l.bps, 0);
+ expect(total).toBe(10_000);
+ const burnLeg = legs.find((l) => l.role === 'burn');
+ const treasuryLeg = legs.find((l) => l.role === 'treasury');
+ expect(burnLeg.bps).toBe(5000);
+ expect(treasuryLeg.bps).toBe(5000);
+ expect(burnLeg.address).toBe(burnAddress());
+ });
+
+ it('marketplace_sale policy yields seller + treasury legs summing to 10000 bps', () => {
+ const seller = 'So11111111111111111111111111111111111111112';
+ const legs = resolveSplitLegs('marketplace_sale', { sellerWallet: seller });
+ expect(legs).toHaveLength(2);
+ const sellerLeg = legs.find((l) => l.role === 'seller');
+ const treasuryLeg = legs.find((l) => l.role === 'treasury');
+ expect(sellerLeg.bps).toBe(9500);
+ expect(treasuryLeg.bps).toBe(500);
+ expect(sellerLeg.address).toBe(seller);
+ });
+
+ it('marketplace_sale throws when sellerWallet is missing', () => {
+ expect(() => resolveSplitLegs('marketplace_sale')).toThrow(/sellerWallet/);
+ });
+
+ it('throws on unknown policy name', () => {
+ expect(() => resolveSplitLegs('nonexistent_policy')).toThrow(/unknown split policy/);
+ });
+});
+
+describe('applySplit', () => {
+ it('spin: 50/50 split with no remainder', () => {
+ const legs = resolveSplitLegs('spin');
+ const result = applySplit(2_000_000n, legs);
+ expect(result[0].atomics).toBe(1_000_000n);
+ expect(result[1].atomics).toBe(1_000_000n);
+ });
+
+ it('spin: odd total — remainder goes to the highest-bps leg (burn=treasury tie → first higher-index wins)', () => {
+ const legs = resolveSplitLegs('spin');
+ const result = applySplit(1_000_001n, legs);
+ const total = result.reduce((s, l) => s + l.atomics, 0n);
+ expect(total).toBe(1_000_001n);
+ // Both legs are 50/50; either may absorb the 1-atom remainder — just verify sum
+ });
+
+ it('marketplace_sale: 95/5 split is exact on 1_000_000', () => {
+ const legs = resolveSplitLegs('marketplace_sale', {
+ sellerWallet: 'So11111111111111111111111111111111111111112',
+ });
+ const result = applySplit(1_000_000n, legs);
+ expect(result.find((l) => l.role === 'seller').atomics).toBe(950_000n);
+ expect(result.find((l) => l.role === 'treasury').atomics).toBe(50_000n);
+ });
+
+ it('marketplace_sale: 95/5 split on odd total sums exactly', () => {
+ const legs = resolveSplitLegs('marketplace_sale', {
+ sellerWallet: 'So11111111111111111111111111111111111111112',
+ });
+ const result = applySplit(1_000_007n, legs);
+ const total = result.reduce((s, l) => s + l.atomics, 0n);
+ expect(total).toBe(1_000_007n);
+ });
+
+ it('handles string and number totals', () => {
+ const legs = resolveSplitLegs('spin');
+ const r1 = applySplit('2000000', legs);
+ const r2 = applySplit(2000000, legs);
+ expect(r1[0].atomics).toBe(r2[0].atomics);
+ });
+
+ it('zero total produces zero atomics on all legs', () => {
+ const legs = resolveSplitLegs('spin');
+ const result = applySplit(0n, legs);
+ expect(result.every((l) => l.atomics === 0n)).toBe(true);
+ });
+});
+
+// ── Price ─────────────────────────────────────────────────────────────────────
+
+describe('getTokenPriceUsd', () => {
+ it('returns Jupiter price and caches it', async () => {
+ fetchResponses.push({
+ body: { [TOKEN_MINT]: { usdPrice: 0.000307 } },
+ });
+ const p = await getTokenPriceUsd({ fresh: true });
+ expect(p.priceUsd).toBe(0.000307);
+ expect(p.source).toBe('jupiter');
+ expect(p.mint).toBe(TOKEN_MINT);
+ expect(cacheSet).toHaveBeenCalledOnce();
+ });
+
+ it('falls back to Birdeye when Jupiter returns null price', async () => {
+ const priorKey = process.env.BIRDEYE_API_KEY;
+ process.env.BIRDEYE_API_KEY = 'test-key';
+ // Jupiter returns with missing field
+ fetchResponses.push({ body: { [TOKEN_MINT]: {} } });
+ // Birdeye
+ fetchResponses.push({ body: { data: { value: 0.0004 } } });
+ const p = await getTokenPriceUsd({ fresh: true });
+ expect(p.priceUsd).toBe(0.0004);
+ expect(p.source).toBe('birdeye');
+ if (priorKey !== undefined) process.env.BIRDEYE_API_KEY = priorKey;
+ else delete process.env.BIRDEYE_API_KEY;
+ });
+
+ it('serves from cache on warm hit', async () => {
+ const cached = {
+ priceUsd: 0.0005,
+ source: 'jupiter',
+ mint: TOKEN_MINT,
+ at: new Date().toISOString(),
+ };
+ cacheGet.mockResolvedValueOnce(cached);
+ const p = await getTokenPriceUsd();
+ expect(p.priceUsd).toBe(0.0005);
+ expect(fetchResponses.length).toBe(0); // no upstream call
+ });
+
+ it('throws price_unavailable when all feeds fail', async () => {
+ const priorKey = process.env.BIRDEYE_API_KEY;
+ process.env.BIRDEYE_API_KEY = 'test-key';
+ fetchResponses.push({ ok: false, status: 503, body: 'down' });
+ fetchResponses.push({ ok: false, status: 503, body: 'down' });
+ await expect(getTokenPriceUsd({ fresh: true })).rejects.toMatchObject({
+ code: 'price_unavailable',
+ });
+ if (priorKey !== undefined) process.env.BIRDEYE_API_KEY = priorKey;
+ else delete process.env.BIRDEYE_API_KEY;
+ });
+});
+
+describe('quoteTokenForUsd', () => {
+ it('converts USD to correct atomics at given price', async () => {
+ fetchResponses.push({ body: { [TOKEN_MINT]: { usdPrice: 0.001 } } });
+ const q = await quoteTokenForUsd(1.0);
+ // $1 / $0.001 per token = 1000 tokens = 1_000_000_000 atomics (6 decimals)
+ expect(q.atomics).toBe(1_000_000_000n);
+ expect(q.tokenAmount).toBeCloseTo(1000, 2);
+ expect(q.usd).toBe(1.0);
+ });
+
+ it('rejects non-positive USD', async () => {
+ await expect(quoteTokenForUsd(0)).rejects.toMatchObject({ code: 'bad_request' });
+ await expect(quoteTokenForUsd(-1)).rejects.toMatchObject({ code: 'bad_request' });
+ });
+
+ it('rejects NaN', async () => {
+ await expect(quoteTokenForUsd(NaN)).rejects.toMatchObject({ code: 'bad_request' });
+ });
+});
+
+describe('atomicsToTokens', () => {
+ it('converts 1_000_000 atomics to 1.0 token', () => {
+ expect(atomicsToTokens(1_000_000n)).toBe(1.0);
+ });
+
+ it('converts 500_000 atomics to 0.5 token', () => {
+ expect(atomicsToTokens(500_000n)).toBeCloseTo(0.5);
+ });
+});
+
+// ── Quote sign / verify ───────────────────────────────────────────────────────
+
+describe('issueQuote + verifyQuote', () => {
+ async function makeQuote(overrides = {}) {
+ fetchResponses.push({ body: { [TOKEN_MINT]: { usdPrice: 0.001 } } });
+ return issueQuote({
+ purpose: 'spin',
+ usd: 0.5,
+ splitPolicy: 'spin',
+ refType: 'spin',
+ refId: 'test-spin-42',
+ ...overrides,
+ });
+ }
+
+ it('issues a verifiable quote token', async () => {
+ const { token, quote } = await makeQuote();
+ expect(typeof token).toBe('string');
+ expect(token).toContain('.');
+ const v = verifyQuote(token);
+ expect(v.nonce).toBe(quote.nonce);
+ expect(v.purpose).toBe('spin');
+ expect(v.total).toBe(quote.total);
+ expect(v.legs).toHaveLength(2);
+ });
+
+ it('quote legs atomics sum equals total', async () => {
+ const { quote } = await makeQuote();
+ const sum = quote.legs.reduce((s, l) => s + BigInt(l.atomics), 0n);
+ expect(sum.toString()).toBe(quote.total);
+ });
+
+ it('quote includes nonce, iat, exp', async () => {
+ const { quote } = await makeQuote();
+ expect(quote.nonce).toBeTruthy();
+ expect(quote.iat).toBeGreaterThan(0);
+ expect(quote.exp).toBeGreaterThan(quote.iat);
+ });
+
+ it('rejects tampered body', async () => {
+ const { token } = await makeQuote();
+ const [body, sig] = token.split('.');
+ const tampered = body.slice(0, -2) + 'ZZ';
+ expect(() => verifyQuote(`${tampered}.${sig}`)).toThrow();
+ });
+
+ it('rejects tampered signature', async () => {
+ const { token } = await makeQuote();
+ const [body, sig] = token.split('.');
+ const tampered = sig.slice(0, -2) + 'ZZ';
+ expect(() => verifyQuote(`${body}.${tampered}`)).toThrow();
+ });
+
+ it('rejects malformed token (no dot)', () => {
+ expect(() => verifyQuote('notavalidtoken')).toThrow(/malformed/);
+ });
+
+ it('rejects expired quote', async () => {
+ const priorTtl = process.env.THREE_QUOTE_TTL_S;
+ process.env.THREE_QUOTE_TTL_S = '-1';
+ fetchResponses.push({ body: { [TOKEN_MINT]: { usdPrice: 0.001 } } });
+ const { token } = await issueQuote({ purpose: 'spin', usd: 0.5, splitPolicy: 'spin' });
+ expect(() => verifyQuote(token)).toThrow(/expired/);
+ if (priorTtl !== undefined) process.env.THREE_QUOTE_TTL_S = priorTtl;
+ else delete process.env.THREE_QUOTE_TTL_S;
+ });
+
+ it('marketplace_sale quote has seller + treasury legs', async () => {
+ fetchResponses.push({ body: { [TOKEN_MINT]: { usdPrice: 0.001 } } });
+ const seller = 'So11111111111111111111111111111111111111112';
+ const { quote } = await issueQuote({
+ purpose: 'marketplace_sale',
+ usd: 10,
+ splitPolicy: 'marketplace_sale',
+ sellerWallet: seller,
+ });
+ const sellerLeg = quote.legs.find((l) => l.role === 'seller');
+ const treasuryLeg = quote.legs.find((l) => l.role === 'treasury');
+ expect(sellerLeg).toBeDefined();
+ expect(treasuryLeg).toBeDefined();
+ expect(sellerLeg.address).toBe(seller);
+ // seller gets 95%
+ const sellerAtomics = BigInt(sellerLeg.atomics);
+ const total = BigInt(quote.total);
+ expect(sellerAtomics * 100n).toBeGreaterThanOrEqual(total * 94n);
+ expect(sellerAtomics * 100n).toBeLessThanOrEqual(total * 96n);
+ });
+
+ it('different quotes produce different nonces', async () => {
+ const cached = {
+ priceUsd: 0.001,
+ source: 'jupiter',
+ mint: TOKEN_MINT,
+ at: new Date().toISOString(),
+ };
+ // Both calls hit cache — no fetch needed.
+ cacheGet.mockResolvedValue(cached);
+ const { quote: q1 } = await issueQuote({ purpose: 'spin', usd: 0.5, splitPolicy: 'spin' });
+ const { quote: q2 } = await issueQuote({ purpose: 'spin', usd: 0.5, splitPolicy: 'spin' });
+ expect(q1.nonce).not.toBe(q2.nonce);
+ cacheGet.mockResolvedValue(null);
+ });
+});
+
+// ── On-chain verification ─────────────────────────────────────────────────────
+
+describe('verifyOnChain', () => {
+ const BURN_ADDR = '1nc1nerator11111111111111111111111111111111';
+ const TREASURY = 'TreasuryXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
+ const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
+ const NONCE = 'test-nonce-abc123';
+
+ beforeEach(() => {
+ _mockTxResponse = undefined;
+ });
+
+ function makeQuotePayload(legs = null) {
+ return {
+ nonce: NONCE,
+ mint: TOKEN_MINT,
+ total: '2000',
+ legs: legs ?? [
+ { role: 'burn', address: BURN_ADDR, bps: 5000, atomics: '1000' },
+ { role: 'treasury', address: TREASURY, bps: 5000, atomics: '1000' },
+ ],
+ };
+ }
+
+ function makeTx({ memo = NONCE, preBalances = [], postBalances = [] } = {}) {
+ return {
+ slot: 123456,
+ meta: { err: null, preTokenBalances: preBalances, postTokenBalances: postBalances },
+ transaction: {
+ message: {
+ accountKeys: [{ pubkey: { toString: () => 'payer' } }],
+ instructions: [{ programId: { toString: () => MEMO_PROGRAM }, parsed: memo }],
+ },
+ },
+ };
+ }
+
+ it('rejects a tx with memo mismatch', async () => {
+ _mockTxResponse = makeTx({ memo: 'wrong-nonce' });
+ await expect(
+ verifyOnChain({ quote: makeQuotePayload(), txSignature: 'sig', network: 'devnet' }),
+ ).rejects.toMatchObject({ code: 'memo_mismatch' });
+ });
+
+ it('rejects a failed on-chain tx', async () => {
+ _mockTxResponse = {
+ slot: 1,
+ meta: { err: { InstructionError: [0, 'GenericError'] } },
+ transaction: { message: { accountKeys: [], instructions: [] } },
+ };
+ await expect(
+ verifyOnChain({ quote: makeQuotePayload(), txSignature: 'sig', network: 'devnet' }),
+ ).rejects.toMatchObject({ code: 'tx_failed' });
+ });
+
+ it('rejects when tx not found (null response)', async () => {
+ _mockTxResponse = null;
+ await expect(
+ verifyOnChain({ quote: makeQuotePayload(), txSignature: 'sig', network: 'devnet' }),
+ ).rejects.toMatchObject({ code: 'tx_not_found' });
+ });
+
+ it('rejects when a split leg receives less than required', async () => {
+ // Only burn gets credited; treasury receives nothing → delta 0 < 1000 required
+ _mockTxResponse = makeTx({
+ postBalances: [
+ {
+ mint: TOKEN_MINT,
+ owner: BURN_ADDR,
+ accountIndex: 0,
+ uiTokenAmount: { amount: '1000' },
+ },
+ ],
+ });
+ await expect(
+ verifyOnChain({ quote: makeQuotePayload(), txSignature: 'sig', network: 'devnet' }),
+ ).rejects.toMatchObject({ code: 'split_underpaid' });
+ });
+
+ it('succeeds when all legs are credited at or above required', async () => {
+ _mockTxResponse = makeTx({
+ postBalances: [
+ {
+ mint: TOKEN_MINT,
+ owner: BURN_ADDR,
+ accountIndex: 0,
+ uiTokenAmount: { amount: '1000' },
+ },
+ {
+ mint: TOKEN_MINT,
+ owner: TREASURY,
+ accountIndex: 1,
+ uiTokenAmount: { amount: '1000' },
+ },
+ ],
+ });
+ const result = await verifyOnChain({
+ quote: makeQuotePayload(),
+ txSignature: 'sig',
+ network: 'devnet',
+ });
+ expect(result.slot).toBe(123456);
+ expect(result.credited).toBeDefined();
+ });
+
+ it('succeeds when a leg is overpaid (excess is fine)', async () => {
+ _mockTxResponse = makeTx({
+ postBalances: [
+ {
+ mint: TOKEN_MINT,
+ owner: BURN_ADDR,
+ accountIndex: 0,
+ uiTokenAmount: { amount: '2000' },
+ },
+ {
+ mint: TOKEN_MINT,
+ owner: TREASURY,
+ accountIndex: 1,
+ uiTokenAmount: { amount: '2000' },
+ },
+ ],
+ });
+ const result = await verifyOnChain({
+ quote: makeQuotePayload(),
+ txSignature: 'sig',
+ network: 'devnet',
+ });
+ expect(result.slot).toBe(123456);
+ });
+});