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: prod-error hardening — Neon tx array, non-throwing treasury read, gate-config unknown state, cosmetic earnings panel

nirholas871b2ba29108
diff --git a/api/_lib/token/config.js b/api/_lib/token/config.js
index 9f624d674..f6ee098e7 100644
--- a/api/_lib/token/config.js
+++ b/api/_lib/token/config.js
@@ -49,6 +49,17 @@ export function treasuryWallet() {
return burnAddress();
}
+/**
+ * Non-throwing treasury lookup for READ paths (public config, status). Returns
+ * the configured address or `null` when unset — never throws. A missing
+ * treasury is a misconfiguration of the *fund-routing* path; it must not 500 a
+ * read-only endpoint. Fund-moving callers use `treasuryWallet()` (strict) so
+ * they still fail closed and never route to an unset address.
+ */
+export function treasuryWalletOrNull() {
+ return env.THREE_TREASURY_WALLET || null;
+}
+
/** The burn sink. Defaults to the Solana incinerator (unspendable ATA). */
export function burnAddress() {
return env.THREE_BURN_ADDRESS;
@@ -129,11 +140,15 @@ export function applySplit(totalAtomics, legs) {
/** Public, non-secret config for clients to display and build transactions. */
export function publicConfig() {
+ // Read path: surface the treasury as null when unset rather than throwing.
+ // The strict treasuryWallet() guard stays on the fund-routing path only.
+ const treasury = treasuryWalletOrNull();
return {
mint: TOKEN_MINT,
symbol: TOKEN_SYMBOL,
decimals: TOKEN_DECIMALS,
- treasury: treasuryWallet(),
+ treasury,
+ treasury_configured: treasury != null,
burn_address: burnAddress(),
quote_ttl_seconds: env.THREE_QUOTE_TTL_S,
split_policies: Object.fromEntries(
diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.js
index 38cef85f7..c79591ee4 100644
--- a/api/agents/[id]/skills-pricing.js
+++ b/api/agents/[id]/skills-pricing.js
@@ -58,14 +58,18 @@ async function handlePut(req, res, agentId) {
const { prices } = parsed.data;
- await sql.transaction(async (tx) => {
- // Deactivate all existing prices for this agent
- await tx`
- UPDATE agent_skill_prices SET is_active = false WHERE agent_id = ${agentId}
- `;
- // Insert or update new prices
- for (const p of prices) {
- await tx`
+ // Neon's serverless driver runs a transaction as an ARRAY of queries in a
+ // single round-trip — not the interactive `async (tx) => {}` callback of
+ // node-postgres (which throws "transaction() expects an array of queries, or
+ // a function returning an array of queries"). Every statement is known up
+ // front, so we build the array and pass it. Atomic: the deactivate + all
+ // upserts commit together or not at all.
+ const statements = [
+ // Deactivate all existing prices for this agent…
+ sql`UPDATE agent_skill_prices SET is_active = false WHERE agent_id = ${agentId}`,
+ // …then (re)assert the submitted set as the active prices.
+ ...prices.map(
+ (p) => sql`
INSERT INTO agent_skill_prices
(agent_id, skill, amount, currency_mint, chain, is_active, trial_uses, time_pass_hours, time_pass_amount)
VALUES
@@ -80,9 +84,11 @@ async function handlePut(req, res, agentId) {
time_pass_hours = EXCLUDED.time_pass_hours,
time_pass_amount = EXCLUDED.time_pass_amount,
updated_at = now()
- `;
- }
- });
+ `,
+ ),
+ ];
+
+ await sql.transaction(statements);
return json(res, 200, { ok: true });
}
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md b/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md
new file mode 100644
index 000000000..8248deca0
--- /dev/null
+++ b/docs/agent-briefs/PROD-errors-2026-06-05/10-cron-index-delegations-rpc.md
@@ -0,0 +1,34 @@
+# Brief 10 — index-delegations cron uses dead/limited public ETH RPC (~50 errors)
+
+## The errors
+```
+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: method not available"}
+{"stage":"index-delegations","chainId":1,"error":"RPC HTTP 429 from https://1rpc.io/eth"}
+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: block range extends beyond current head block"}
+{"stage":"index-delegations","chainId":1,"error":"RPC eth_getLogs error: You've reached the usage limit..."}
+{"stage":"index-delegations","chainId":1,"error":"fetch failed"}
+```
+Function: `/api/cron/[name]` → `index-delegations`.
+
+## Root cause
+The Ethereum mainnet (chainId 1) delegation indexer points at **free public RPCs (`1rpc.io/eth`
+and similar) that rate-limit (429), don't support `eth_getLogs`, or are flaky** (`fetch failed`).
+Plus the indexer requests a **block range beyond the current head**, meaning the cursor/`toBlock`
+math is wrong. So the cron silently fails to index delegations.
+
+## Required fix
+1. **Use a real, keyed RPC.** Replace the public endpoint with a proper provider
+ (Alchemy/Infura/QuickNode) via env var (e.g. `ETH_RPC_URL` / `ETH_MAINNET_RPC_URL`). Confirm
+ which env the indexer reads (`grep` the cron + delegation indexer lib) and set it in prod.
+ Don't hardcode `1rpc.io`. Keep a sane fallback list but put the keyed provider first.
+2. **Fix the block-range math.** Clamp `toBlock` to `min(cursor+window, currentHead)` so it never
+ exceeds the head. Page `eth_getLogs` in bounded ranges (e.g. ≤2k–10k blocks) to avoid provider
+ limits. Persist the cursor only after a range succeeds so retries are idempotent
+ (`indexer_state` table — see `specs/schema/indexer_state.sql`).
+3. **Backoff + don't crash the cron.** On 429/`fetch failed`, backoff and retry the same range
+ next run; log structured progress. A transient RPC error must not lose the cursor.
+
+## Done when
+- `index-delegations` runs against a keyed RPC, pages within the head block, advances and persists
+ its cursor, and logs success — no `method not available` / `beyond current head` / sustained 429.
+- Confirm the indexed delegations land in the DB (`agent_delegations`).
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md b/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md
new file mode 100644
index 000000000..6bddcb586
--- /dev/null
+++ b/docs/agent-briefs/PROD-errors-2026-06-05/11-treasury-env-and-config.md
@@ -0,0 +1,31 @@
+# Brief 11 — THREE_TREASURY_WALLET unset in production (34 errors)
+
+## The error
+```
+[api] unhandled Error: [token] THREE_TREASURY_WALLET is required in production
+— refusing to route treasury funds to an unset address.
+```
+Function: `/api/three-token/[action]` (and any token-routing path).
+
+## Root cause
+The token routing code correctly **fails closed** when `THREE_TREASURY_WALLET` is missing (good —
+do not weaken this guard), but the env var is **not set in the production Vercel environment**, so
+the feature is hard-down. This is a config gap, not a code bug.
+
+## Required fix
+1. Confirm the correct treasury wallet address with the user (the `$THREE` treasury). Set it:
+ ```bash
+ vercel env add THREE_TREASURY_WALLET production
+ ```
+ and redeploy. Verify `vercel env ls` shows it. Do **not** hardcode the address in source.
+2. Keep the fail-closed guard. Additionally, make the **user-facing** response a clean typed 503
+ ("treasury temporarily unavailable") rather than an unhandled 500, so a future misconfig
+ degrades gracefully.
+3. Audit sibling required-env guards for the same prod gap (`grep -rn "is required in production"
+ api/`) and ensure each referenced var is actually set in prod. List any others you find for the
+ user to populate.
+
+## Done when
+- `THREE_TREASURY_WALLET` is set in prod; the token route works end-to-end with the real treasury.
+- Missing required envs return a typed 503, never an unhandled 500.
+- No other `required in production` guard is silently tripping in the logs.
diff --git a/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md b/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md
new file mode 100644
index 000000000..cb0024862
--- /dev/null
+++ b/docs/agent-briefs/PROD-errors-2026-06-05/12-misc-hardening.md
@@ -0,0 +1,48 @@
+# Brief 12 — Long-tail hardening (~40 errors across several small bugs)
+
+Each of these is low-volume but a real defect. Fix the source; add a boundary guard.
+
+## 12a. Empty / malformed JSON bodies → `SyntaxError: Unexpected end of JSON input` (7)
+- Root cause: a handler does `JSON.parse(body)` / `await req.json()` on an empty or non-JSON
+ request body without a try/catch. Find the routes (the `[api] unhandled SyntaxError` rows) and
+ parse defensively: validate `content-length`/content-type, wrap parse in try/catch, return
+ **400** with a clear message on bad input. Never 500 on a malformed client body.
+
+## 12b. Vercel Runtime Timeout — 30s (27, mostly /api/chat, some elsewhere)
+- Mostly covered by Brief 03 for `/api/chat`. For any *other* route timing out, find the slow
+ upstream/DB call and add a timeout + failover. No handler should be able to run the full 30s on
+ a single unbounded await.
+
+## 12c. UTF-8 / encoding errors
+```
+NeonDbError: invalid byte sequence for encoding "UTF8": 0x.. (1)
+RangeError: encoding overruns Uint8Array (Solana — see Brief 08)
+```
+- Root cause: raw bytes/invalid UTF-8 reaching Postgres. Sanitize/normalize string inputs
+ (strip null bytes, validate UTF-8) at the write boundary before they hit `sql\`...\``.
+
+## 12d. Fontconfig error (2)
+```
+Fontconfig error: Cannot load default config file: No such file: (null)
+```
+- Root cause: an OG-image / canvas / headless render path needs fonts but the lambda has no
+ fontconfig. Bundle the font(s) the renderer needs and point `FONTCONFIG_PATH` / load the font
+ explicitly so image generation doesn't warn/degrade. Find the render route (likely an `og`/image
+ function) and make font loading explicit and self-contained.
+
+## 12e. ENOENT file open (2)
+```
+[api] unhandled Error: ENOENT: no such file or directory, open '...'
+```
+- Root cause: a handler reads a file that isn't included in the deployed bundle (Vercel NFT didn't
+ trace it). Identify the file, and either inline its contents, mark it for inclusion via
+ `vercel.json` `includeFiles`, or read it from a bundled import instead of `fs` at runtime.
+
+## 12f. `seed-default-agent` / `[audit] insert failed` (2 + 5)
+- These reference DB inserts failing — likely the same missing-table/migration class as Brief 04,
+ or a constraint violation. Trace the failing insert, confirm the target table/columns exist in
+ prod, and make the seed/audit path idempotent (`ON CONFLICT DO NOTHING`) so reruns don't error.
+
+## Done when
+- Each sub-item: the source bug is fixed, bad input returns a typed 4xx (not 500), and the log line
+ no longer appears in a preview-deploy smoke test.
diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.js
index d845b0a05..4b83b8b6e 100644
--- a/src/dashboard-next/pages/monetize.js
+++ b/src/dashboard-next/pages/monetize.js
@@ -153,6 +153,7 @@ async function loadAndRender(host, me, agents) {
host.appendChild(renderSubscriptionPlans({ creatorPlans, me }));
host.appendChild(renderWithdrawals({ withdrawals, wallets, available, host, me, agents }));
host.appendChild(renderLegacyPayoutWallets({ wallets, host, me, agents }));
+ host.appendChild(renderCosmeticEarnings({ wallets }));
host.appendChild(renderPlanUsage(summary));
host.appendChild(renderTokensPanel(agents));
}
@@ -1433,6 +1434,164 @@ function renderPlanUsage(summary) {
return panel;
}
+// -- Cosmetic creator earnings (R25) --
+//
+// Real, settled earnings from cosmetic sales tied to the creator's coins. When a
+// player buys a premium cosmetic inside one of your coin's /play worlds, a
+// configurable share of the settled USDC pays out to your Solana wallet on-chain.
+// This panel reads /api/cosmetics/earnings (settled-sale ledger) for the user's
+// Solana payout wallet(s) — only real numbers, with the payout's on-chain status.
+
+function renderCosmeticEarnings({ wallets }) {
+ const panel = document.createElement('div');
+ panel.className = 'dn-panel';
+
+ // Candidate Solana wallets the creator earns to, from their payout wallets.
+ const solWallets = [...new Set(
+ (wallets || [])
+ .map((w) => w?.solana_address || w?.solana || '')
+ .filter((a) => a && SOLANA_ADDR_RE.test(a)),
+ )];
+
+ panel.innerHTML = `
+ <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:6px">
+ <div>
+ <div class="dn-panel-title">Cosmetic creator earnings</div>
+ <div class="dn-panel-sub" style="margin:2px 0 0">
+ Your share of cosmetics sold in your coins’ worlds — paid out in USDC on-chain.
+ </div>
+ </div>
+ <div data-slot="wallet-pick"></div>
+ </div>
+ <div data-slot="ce-body"></div>
+ `;
+
+ const body = panel.querySelector('[data-slot="ce-body"]');
+
+ if (!solWallets.length) {
+ body.innerHTML = `
+ <div style="text-align:center;padding:26px 12px;color:var(--nxt-ink-fade)">
+ <div style="font-size:28px;opacity:.5" aria-hidden="true">✦</div>
+ <div style="font-weight:600;color:var(--nxt-ink);margin-top:6px">No Solana payout wallet yet</div>
+ <div style="font-size:13px;margin-top:6px;max-width:46ch;margin-inline:auto;line-height:1.5">
+ Add a Solana payout wallet above to start receiving your share of cosmetic
+ sales in your coins’ worlds. The split pays out in USDC on-chain.
+ </div>
+ </div>`;
+ return panel;
+ }
+
+ // Wallet picker (only when more than one) + load.
+ let selected = solWallets[0];
+ const pickHost = panel.querySelector('[data-slot="wallet-pick"]');
+ if (solWallets.length > 1) {
+ pickHost.innerHTML = `<select class="mon-select" aria-label="Earnings wallet">${
+ solWallets.map((w) => `<option value="${esc(w)}">${esc(w.slice(0, 4) + '…' + w.slice(-4))}</option>`).join('')
+ }</select>`;
+ pickHost.querySelector('select').addEventListener('change', (e) => {
+ selected = e.target.value;
+ loadCosmeticEarnings(body, selected);
+ });
+ }
+
+ loadCosmeticEarnings(body, selected);
+ return panel;
+}
+
+async function loadCosmeticEarnings(body, wallet) {
+ body.innerHTML = `<div style="padding:20px;color:var(--nxt-ink-fade);font-size:13px">Loading settled earnings…</div>`;
+ let data;
+ try {
+ data = await get(`/api/cosmetics/earnings?creator=${encodeURIComponent(wallet)}`);
+ } catch (err) {
+ body.innerHTML = `<div style="padding:18px;color:var(--nxt-danger);font-size:13px">
+ Couldn’t load earnings. <button class="dn-btn" data-slot="ce-retry" style="margin-left:8px">Retry</button></div>`;
+ body.querySelector('[data-slot="ce-retry"]')?.addEventListener('click', () => loadCosmeticEarnings(body, wallet));
+ return;
+ }
+
+ const t = data?.totals || {};
+ const usd = (n) => '$' + (Number(n) || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
+
+ if (!t.sales) {
+ body.innerHTML = `
+ <div style="text-align:center;padding:24px 12px;color:var(--nxt-ink-fade)">
+ <div style="font-weight:600;color:var(--nxt-ink)">No cosmetic sales yet</div>
+ <div style="font-size:13px;margin-top:6px;max-width:46ch;margin-inline:auto;line-height:1.5">
+ When a player buys a premium cosmetic inside one of your coins’ worlds,
+ your share lands here — and a payout is sent to your wallet on-chain.
+ </div>
+ </div>`;
+ return;
+ }
+
+ const stat = (label, value, sub) => `
+ <div style="background:var(--nxt-surface-2,rgba(255,255,255,.02));border:1px solid var(--nxt-stroke);border-radius:12px;padding:14px 16px">
+ <div style="font-size:12px;color:var(--nxt-ink-fade)">${esc(label)}</div>
+ <div style="font-size:22px;font-weight:700;margin-top:4px;letter-spacing:-.01em">${esc(value)}</div>
+ ${sub ? `<div style="font-size:11.5px;color:var(--nxt-ink-fade);margin-top:2px">${esc(sub)}</div>` : ''}
+ </div>`;
+
+ const payoutBadge = (s) => {
+ const map = {
+ paid: ['var(--nxt-success)', 'Paid'],
+ pending: ['var(--nxt-warn)', 'Pending'],
+ failed: ['var(--nxt-danger)', 'Retrying'],
+ skipped: ['var(--nxt-ink-fade)', 'Accrued'],
+ none: ['var(--nxt-ink-fade)', '—'],
+ };
+ const [color, label] = map[s] || map.none;
+ return `<span style="font-size:11px;font-weight:600;color:${color}">${esc(label)}</span>`;
+ };
+
+ const recentRows = (data.recent || []).map((r) => {
+ const tx = r.payoutTx
+ ? `<a href="https://solscan.io/tx/${esc(r.payoutTx)}" target="_blank" rel="noopener" style="color:var(--nxt-accent,#8aa0ff);text-decoration:none">view ↗</a>`
+ : '';
+ return `
+ <tr style="border-top:1px solid var(--nxt-stroke)">
+ <td style="padding:8px 10px">${esc(r.name)}</td>
+ <td style="padding:8px 10px;text-transform:capitalize;color:var(--nxt-ink-fade)">${esc(r.rarity)}</td>
+ <td style="padding:8px 10px;text-align:right;font-variant-numeric:tabular-nums">${usd(r.earnedUsdc)}</td>
+ <td style="padding:8px 10px">${payoutBadge(r.payoutStatus)} ${tx}</td>
+ <td style="padding:8px 10px;color:var(--nxt-ink-fade)">${r.settledAt ? esc(relTime(r.settledAt)) : ''}</td>
+ </tr>`;
+ }).join('');
+
+ body.innerHTML = `
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin:6px 0 18px">
+ ${stat('Total earned', usd(t.earnedUsdc), `${t.sales} sale${t.sales === 1 ? '' : 's'} · ${t.buyers} buyer${t.buyers === 1 ? '' : 's'}`)}
+ ${stat('Paid out', usd(t.paidUsdc), 'settled on-chain')}
+ ${stat('Pending', usd(t.pendingUsdc), 'awaiting payout')}
+ ${stat('Last 30 days', usd(t.earned30dUsdc), null)}
+ </div>
+ ${(data.perCosmetic || []).length ? `
+ <div style="font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--nxt-ink-fade);margin-bottom:8px">Top earning cosmetics</div>
+ <div style="display:flex;flex-wrap:wrap;gap:8px;margin-bottom:18px">
+ ${data.perCosmetic.slice(0, 8).map((c) => `
+ <div style="display:flex;align-items:center;gap:8px;background:var(--nxt-surface-2,rgba(255,255,255,.02));border:1px solid var(--nxt-stroke);border-radius:999px;padding:5px 12px;font-size:12.5px">
+ <span style="font-weight:600">${esc(c.name)}</span>
+ <span style="color:var(--nxt-ink-fade)">${c.sales}×</span>
+ <span style="font-weight:600;color:var(--nxt-success)">${usd(c.earnedUsdc)}</span>
+ </div>`).join('')}
+ </div>` : ''}
+ ${recentRows ? `
+ <div style="font-size:12px;text-transform:uppercase;letter-spacing:.05em;color:var(--nxt-ink-fade);margin-bottom:6px">Recent sales</div>
+ <div style="overflow:auto;border:1px solid var(--nxt-stroke);border-radius:12px">
+ <table style="width:100%;border-collapse:collapse;font-size:13px">
+ <thead><tr style="text-align:left;color:var(--nxt-ink-fade)">
+ <th style="padding:8px 10px;font-weight:500">Cosmetic</th>
+ <th style="padding:8px 10px;font-weight:500">Rarity</th>
+ <th style="padding:8px 10px;font-weight:500;text-align:right">Your cut</th>
+ <th style="padding:8px 10px;font-weight:500">Payout</th>
+ <th style="padding:8px 10px;font-weight:500">When</th>
+ </tr></thead>
+ <tbody>${recentRows}</tbody>
+ </table>
+ </div>` : ''}
+ `;
+}
+
// -- Token earnings --
function renderTokensPanel(agents) {
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 70caf30b9..45532aba9 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -880,7 +880,7 @@ export class CommunityUI {
// token amount a wallet must hold to enter the Holders world, or removes the
// requirement. `onSave(minTokens)` returns a promise that resolves to the saved
// config or rejects with a coded error; we drive the busy/error states off it.
- openGateConfig(coin, { minTokens = 0, onSave } = {}) {
+ openGateConfig(coin, { minTokens = 0, unknown = false, onSave } = {}) {
this.closeGateConfig();
const sym = coin?.symbol ? '$' + String(coin.symbol).replace(/^\$/, '').toUpperCase() : 'this coin';
const input = el('input', {
@@ -888,12 +888,16 @@ export class CommunityUI {
class: 'cc-gatecfg-input', value: minTokens > 0 ? String(minTokens) : '',
placeholder: 'e.g. 1000000', 'aria-label': `Minimum ${sym} to enter the holders world`,
});
- const errLine = el('p', { class: 'cc-gatecfg-err', hidden: true });
+ const errLine = el('p', { class: 'cc-gatecfg-err', hidden: !unknown });
+ if (unknown) errLine.textContent = 'Couldn’t load the current gate — saving will overwrite it.';
const hint = el('p', { class: 'cc-gatecfg-hint', text: `Leave blank to use the default ($-value) floor. Set a number to require that many ${sym} on-chain.` });
const saveBtn = el('button', { type: 'button', class: 'cc-gate-btn cc-gate-primary', text: 'Save gate' });
+ // "Remove gate" whenever a gate exists — or might exist (the read failed). Only
+ // a confirmed-ungated world shows a plain "Cancel".
+ const canRemove = minTokens > 0 || unknown;
const clearBtn = el('button', {
type: 'button', class: 'cc-gate-btn cc-gate-ghost',
- text: minTokens > 0 ? 'Remove gate' : 'Cancel',
+ text: canRemove ? 'Remove gate' : 'Cancel',
});
const busy = (on) => {
saveBtn.disabled = on; clearBtn.disabled = on; input.disabled = on;
@@ -901,7 +905,7 @@ export class CommunityUI {
};
const fail = (msg) => { errLine.textContent = msg; errLine.hidden = false; busy(false); };
const commit = async (value) => {
- errLine.hidden = true;
+ errLine.hidden = true; errLine.textContent = '';
busy(true);
try {
await onSave?.(value);
@@ -916,7 +920,7 @@ export class CommunityUI {
if (!Number.isFinite(v) || v <= 0) return fail('Enter a positive number of tokens, or use Remove gate.');
commit(v);
};
- clearBtn.onclick = () => { if (minTokens > 0) commit(0); else this.closeGateConfig(); };
+ clearBtn.onclick = () => { if (canRemove) commit(0); else this.closeGateConfig(); };
input.onkeydown = (e) => { if (e.key === 'Enter') { e.preventDefault(); saveBtn.click(); } e.stopPropagation(); };
const body = el('div', { class: 'cc-gate-body' }, [
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 2474b0ffb..b89bd0fe0 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -1249,6 +1249,9 @@ export class CoinCommunities {
onPurchased: (item) => { this.equipCosmeticPreview(item); },
});
}
+ // The shop is built once and reused across worlds, so refresh the coin tie
+ // each open — a sale always credits the world the player is currently in.
+ this._shop.h.coinMint = this.coin?.mint || '';
this._shop.toggle();
}
@@ -1730,12 +1733,19 @@ export class CoinCommunities {
const coin = this.coin;
if (!coin?.mint) return;
let current = 0;
+ let unknown = false;
try {
const cfg = await getWorldGate(coin.mint);
current = cfg?.minTokens || 0;
- } catch { /* fall back to a blank form — the save still validates server-side */ }
+ } catch {
+ // Couldn't read the current gate — open in an "unknown" state so the creator
+ // can still overwrite or remove it, rather than a blank form that wrongly
+ // implies the world is ungated. The save validates server-side regardless.
+ unknown = true;
+ }
this.ui.openGateConfig(coin, {
minTokens: current,
+ unknown,
onSave: async (minTokens) => {
const saved = await setWorldGate(coin.mint, minTokens);
const next = saved?.minTokens || 0;