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(rpc): fail over on -32603 and silent per-shape hangs instead of handing the error envelope to callers

nirholas3dc265d573e8
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index 7a73e3344..478453068 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -843,6 +843,22 @@ const PROVIDER_CAPACITY_CODES = new Set([
429, // Alchemy: monthly capacity exceeded, reported as a JSON-RPC code
]);
+// -32603 is the JSON-RPC spec's "Internal error": the node accepted the call and
+// then failed on its own side. It is NOT deterministic across providers, which is
+// what separates it from the -32600/-32601/-32602 family excluded above, and in
+// practice it is per (lane, method): measured 2026-08-12, Leo RPC answers EVERY
+// getTokenLargestAccounts with -32603 while serving getAccountInfo and
+// getMultipleAccounts normally.
+//
+// Unclassified it was not a failover signal at all, so the error envelope reached
+// the caller as though it were the chain's answer, with lanes that do serve the
+// method (both Tatum hosts, keylessly) never tried. That is the whole reason
+// /api/crypto/holders answered 503 and /api/crypto/security reported
+// riskLevel:"unknown" with "holder concentration could not be read" on live mints
+// while Helius and Alchemy sat quota-exhausted. Disposition is a (lane, method)
+// demotion, never a lane bench: the lane is healthy for every other shape.
+const JSONRPC_INTERNAL_ERROR = -32603;
+
// A provider that refuses one call shape — by paid-tier gate, by policy, or by
// switching the method off — answers with a method-shaped JSON-RPC error, and the
// dangerous variant answers HTTP 200 so no status-driven rotation fires. Measured
@@ -952,6 +968,19 @@ export function classifyRpcBody(body) {
methodBlock: isMethodRefusal(msg),
};
}
+ // The node's own internal fault on this call shape (see JSONRPC_INTERNAL_ERROR).
+ // Fail the request over and demote the shape on this lane so the next caller
+ // spends its budget on a lane that answers it.
+ if (hasError && item.error?.code === JSONRPC_INTERNAL_ERROR) {
+ const msg = String(item.error?.message || '');
+ return {
+ status: 502,
+ reason: 'node internal error',
+ log: `200 + node internal error -32603 ${msg.slice(0, 48)}`.trim(),
+ bodyText: msg,
+ methodBlock: true,
+ };
+ }
}
return null;
}
@@ -1112,6 +1141,22 @@ export function makeRotatingFetch(endpoints) {
}),
};
} catch (err) {
+ // The CALLER's budget ran out, not the lane's patience. Rotation is over
+ // either way, and this attempt learned nothing about the endpoint, so
+ // penalising it here would bench a healthy node for the caller's deadline.
+ if (init?.signal?.aborted) return { error: err };
+ // The lane accepted the request and never answered within the attempt
+ // bound. Measured 2026-08-12: PublicNode hangs indefinitely on
+ // getTokenLargestAccounts (no response at 35s) while answering
+ // getAccountInfo in milliseconds — a silent per-shape refusal. Cooling the
+ // whole lane for it benched the primary free lane for every other method,
+ // which is how one unanswerable shape starved the holder and security
+ // readers. Demote the shape instead; markMethodDemotion's breadth guard
+ // still benches a lane that hangs on everything.
+ if (attemptSignal.aborted && methods.length) {
+ penalise(url, 504, '', true, `no answer within ${Math.round(ATTEMPT_TIMEOUT_MS / 1000)}s`);
+ return { error: err };
+ }
// A thrown fetch is a transient network/DNS blip, not a quota signal —
// cool only briefly so a healthy provider isn't parked for long.
_endpointCooldown.set(url, Date.now() + NETWORK_COOLDOWN_MS);
diff --git a/public/cz/boot.js b/public/cz/boot.js
deleted file mode 100644
index af9cec528..000000000
--- a/public/cz/boot.js
+++ /dev/null
@@ -1,191 +0,0 @@
-/**
- * CZ landing page initialization — loads state, wires up CTAs, handles claim flow.
- */
-
-import { startClaim, mountEmbedCopy, fireAnalytics } from '../../src/cz-flow.js';
-
-async function init() {
- // Load state
- let state = {
- status: 'pre-onchain',
- chainId: null,
- agentId: null,
- metadataURI: null,
- ownerAddress: null,
- avatarUrl: '/avatars/cz.glb',
- };
-
- try {
- const res = await fetch('./state.json');
- if (res.ok) {
- state = await res.json();
- }
- } catch (err) {
- console.warn('Failed to load state.json:', err);
- }
-
- // Update footer with state
- updateFooter(state);
-
- // Wire up claim button
- const claimBtn = document.getElementById('cz-claim-btn');
- if (claimBtn) {
- claimBtn.addEventListener('click', () => handleClaimClick(state));
- }
-
- // Wire up embed copy
- const embedContainer = document.getElementById('cz-embed-container');
- if (embedContainer) {
- mountEmbedCopy(embedContainer, { state });
- }
-
- // Fire landing view event
- fireAnalytics('landing_view', { status: state.status });
-}
-
-function updateFooter(state) {
- const footer = document.getElementById('cz-footer');
- if (!footer) return;
-
- if (state.status === 'pre-onchain') {
- footer.innerHTML = `
- <p>Not yet onchain</p>
- `;
- } else {
- const chainName = getChainName(state.chainId);
- footer.innerHTML = `
- <p><strong>Chain:</strong> ${chainName}</p>
- <p><strong>Agent ID:</strong> ${state.agentId}</p>
- ${state.metadataURI ? `<p><strong>Metadata:</strong> <code>${truncate(state.metadataURI, 40)}</code></p>` : ''}
- `;
- }
-}
-
-function getChainName(chainId) {
- const chains = {
- 1: 'Ethereum',
- 8453: 'Base',
- 84532: 'Base Sepolia',
- };
- return chains[chainId] || `Chain ${chainId}`;
-}
-
-function truncate(str, len) {
- return str.length > len ? str.slice(0, len - 3) + '…' : str;
-}
-
-async function handleClaimClick(state) {
- const claimBtn = document.getElementById('cz-claim-btn');
- const modal = document.getElementById('cz-claim-modal');
-
- if (!modal) return;
-
- fireAnalytics('claim_start', {});
-
- // Show modal with spinner
- modal.style.display = 'flex';
- const content = document.getElementById('cz-modal-content');
- const closeBtn = document.getElementById('cz-modal-close');
-
- content.innerHTML = `
- <div class="modal-spinner"></div>
- <p>Initializing claim flow…</p>
- `;
-
- // Result panels are rendered from strings; their OK/Dismiss buttons declare
- // data-close-claim-modal and this delegated listener closes the modal. Inline
- // onclick attributes cannot run under the site CSP.
- document.addEventListener('click', (event) => {
- if (event.target.closest('[data-close-claim-modal]')) modal.style.display = 'none';
- });
-
- closeBtn.addEventListener('click', () => {
- modal.style.display = 'none';
- });
-
- modal.addEventListener('click', (e) => {
- if (e.target === modal) modal.style.display = 'none';
- });
-
- // Run claim flow
- const result = await startClaim({
- state,
- onProgress: (progress) => {
- updateModal(progress, state);
- },
- });
-
- if (result.ok) {
- if (result.message === 'pre_onchain') {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Coming Soon</h3>
- <p>CZ is not yet registered on-chain. Claiming opens once the registration is complete.</p>
- <button class="modal-close-btn" data-close-claim-modal>OK</button>
- `;
- } else if (result.message === 'already_owned') {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Already Claimed</h3>
- <p>This agent is already owned by <code>${truncate(state.ownerAddress, 20)}</code>.</p>
- <button class="modal-close-btn" data-close-claim-modal>OK</button>
- `;
- } else {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Claim Successful</h3>
- <p>Transaction: <code>${result.txHash}</code></p>
- <button class="modal-close-btn" data-close-claim-modal>OK</button>
- `;
- }
- } else {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Error</h3>
- <p>${result.error}</p>
- <button class="modal-close-btn" data-close-claim-modal>Dismiss</button>
- `;
- }
-}
-
-function updateModal(progress, state) {
- const content = document.getElementById('cz-modal-content');
- const { step, status, error } = progress;
-
- if (error) {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Error</h3>
- <p>${error}</p>
- `;
- return;
- }
-
- const messages = {
- connect_wallet: {
- connecting: 'Connecting wallet…',
- connected: `Connected: ${progress.address?.slice(0, 10)}…`,
- },
- check_state: {
- pre_onchain: 'Checking agent status…',
- },
- claim: {
- submitting: 'Submitting claim…',
- pending: 'Waiting for confirmation…',
- confirmed: 'Claim confirmed!',
- already_owned: 'Already owned.',
- },
- transfer: {
- submitting: 'Submitting transfer…',
- pending: 'Waiting for confirmation…',
- confirmed: 'Transfer confirmed!',
- },
- };
-
- const msg = messages[step]?.[status] || `${step}: ${status}`;
- content.innerHTML = `
- <div class="modal-spinner"></div>
- <p>${msg}</p>
- `;
-}
-
-if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', init);
-} else {
- init();
-}
diff --git a/public/cz/state.json b/public/cz/state.json
deleted file mode 100644
index e31fd0a94..000000000
--- a/public/cz/state.json
+++ /dev/null
@@ -1,8 +0,0 @@
-{
- "status": "pre-onchain",
- "chainId": null,
- "agentId": null,
- "metadataURI": null,
- "ownerAddress": null,
- "avatarUrl": "/avatars/cz.glb"
-}
diff --git a/src/cz-flow.js b/src/cz-flow.js
deleted file mode 100644
index 285e4d8d4..000000000
--- a/src/cz-flow.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/**
- * CZ demo claim flow — manages wallet connection, claiming, and transfer flows.
- */
-
-import { ensureWallet, getIdentityRegistry } from './erc8004/agent-registry.js';
-import { log } from './shared/log.js';
-
-/**
- * Start the claim flow based on the current state.
- *
- * @param {object} opts
- * @param {object} opts.state Current state (status, chainId, agentId, ownerAddress, etc.)
- * @param {(progress) => void} opts.onProgress Callback with { step, status, txHash?, error? }
- * @returns {Promise<{ ok: true, txHash? } | { ok: false, error }>}
- */
-export async function startClaim({ state, onProgress }) {
- const log = (step, status, extra = {}) => {
- onProgress?.({ step, status, ...extra });
- };
-
- try {
- // Step 1: Connect wallet
- log('connect_wallet', 'connecting');
- const { address, chainId, signer } = await ensureWallet();
- log('connect_wallet', 'connected', { address, chainId });
-
- // Step 2: Check state
- if (state.status === 'pre-onchain') {
- log('check_state', 'pre_onchain', {
- message:
- 'CZ is not yet registered on-chain. Claiming opens once registration is complete.',
- });
- return { ok: true, message: 'pre_onchain' };
- }
-
- const registry = getIdentityRegistry(chainId, signer);
-
- // Step 3: If ownerAddress is 0x0 (unclaimed), call claim()
- if (state.ownerAddress === '0x0000000000000000000000000000000000000000') {
- log('claim', 'submitting');
- const tx = await registry.claim(state.agentId);
- log('claim', 'pending', { txHash: tx.hash });
-
- await tx.wait();
- log('claim', 'confirmed', { txHash: tx.hash });
-
- fireAnalytics('claim_tx_sent', { txHash: tx.hash, agentId: state.agentId });
- fireAnalytics('claim_complete', { agentId: state.agentId });
- return { ok: true, txHash: tx.hash };
- }
-
- // Step 4: Already owned by the connected wallet.
- if (state.ownerAddress?.toLowerCase() === address.toLowerCase()) {
- log('claim', 'already_owned', { owner: address });
- return { ok: true, message: 'already_owned' };
- }
-
- // Step 5: Transfer from the current owner to the connected wallet.
- // ERC-721 transferFrom can only be called by the token owner or an approved
- // operator. Verify the connected wallet is the owner before submitting so we
- // surface a clean error instead of an opaque on-chain revert.
- const onchainOwner = await registry.ownerOf(state.agentId).catch(() => null);
- if (onchainOwner && onchainOwner.toLowerCase() !== address.toLowerCase()) {
- return {
- ok: false,
- error: `Transfer failed: the connected wallet (${address}) is not the current owner. The agent is owned by ${onchainOwner}.`,
- };
- }
- log('transfer', 'submitting', { from: state.ownerAddress, to: address });
- const tx = await registry.transferFrom(state.ownerAddress, address, state.agentId);
- log('transfer', 'pending', { txHash: tx.hash });
- await tx.wait();
- log('transfer', 'confirmed', { txHash: tx.hash });
- fireAnalytics('transfer_complete', { txHash: tx.hash, agentId: state.agentId });
- return { ok: true, txHash: tx.hash };
- } catch (err) {
- log('claim', 'error', { error: err.message });
- fireAnalytics('claim_error', { error: err.message });
- return { ok: false, error: err.message };
- }
-}
-
-/**
- * Mount the embed copy CTA to a container.
- * Copies an <agent-3d> snippet to clipboard with chain/agentId interpolated.
- *
- * @param {HTMLElement} container
- * @param {object} opts
- * @param {object} opts.state Current state
- */
-export function mountEmbedCopy(container, { state }) {
- const button = document.createElement('button');
- button.id = 'cz-embed-copy';
- button.textContent = 'Copy embed';
- button.setAttribute('aria-label', 'Copy embed code to clipboard');
-
- button.addEventListener('click', async () => {
- const snippet = buildEmbedSnippet(state);
- try {
- await navigator.clipboard.writeText(snippet);
- const orig = button.textContent;
- button.textContent = 'Copied!';
- fireAnalytics('embed_copied', {
- hasChainId: !!state.chainId,
- hasAgentId: !!state.agentId,
- });
- setTimeout(() => {
- button.textContent = orig;
- }, 2000);
- } catch (err) {
- log.error('Copy failed:', err);
- button.textContent = 'Copy failed';
- setTimeout(() => {
- button.textContent = 'Copy embed';
- }, 2000);
- }
- });
-
- container.appendChild(button);
- return button;
-}
-
-/**
- * Build the embed snippet HTML based on state.
- */
-function buildEmbedSnippet(state) {
- let agentAttr = '';
- if (state.chainId && state.agentId) {
- agentAttr = ` agent-id="onchain:${state.chainId}:${state.agentId}"`;
- } else {
- // Fallback: just use the GLB directly
- agentAttr = ` body="${state.avatarUrl}"`;
- }
-
- return `<agent-3d${agentAttr} src="${state.avatarUrl}" eager></agent-3d>
-<script type="module" src="https://three.ws/dist-lib/agent-3d.js"><\/script>`;
-}
-
-/**
- * Fire a custom event for analytics.
- */
-function fireAnalytics(event, props = {}) {
- window.dispatchEvent(
- new CustomEvent('cz-demo-event', {
- detail: { event, props, timestamp: Date.now() },
- }),
- );
-}
-
-export { fireAnalytics };