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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
refactor(nft): derive the Alchemy NFT host from the shared RPC module instead of a copied map
nirholasdd8afe7d2035
diff --git a/api/_lib/evm/rpc.js b/api/_lib/evm/rpc.jsindex 848e032c6..9d5e346b6 100644--- a/api/_lib/evm/rpc.js+++ b/api/_lib/evm/rpc.js@@ -49,13 +49,43 @@ const ALCHEMY_CHAIN_KEY = {42161: 'ALCHEMY_ARB_KEY',};+function alchemyKey(chainId) {+ const chainKeyName = ALCHEMY_CHAIN_KEY[chainId];+ return (chainKeyName && process.env[chainKeyName]) || process.env.ALCHEMY_API_KEY || null;+}+function alchemyUrl(chainId) {const sub = ALCHEMY_SUBDOMAIN[chainId];- const chainKeyName = ALCHEMY_CHAIN_KEY[chainId];- const key = (chainKeyName && process.env[chainKeyName]) || process.env.ALCHEMY_API_KEY;+ const key = alchemyKey(chainId);return sub && key ? `https://${sub}.g.alchemy.com/v2/${key}` : null;}+/**+ * Alchemy NFT API v3 base URL for a chain, or null when the chain has no Alchemy+ * host or no key is configured for it. The NFT API shares the JSON-RPC API's+ * network slugs, so deriving it here is what keeps /api/nft/resolve aligned with+ * this module: it used to carry its own hand-copied host map, which silently+ * lost polygon-amoy and avax-fuji (both rejected as "unsupported chainId" even+ * though the keyless on-chain rung could read them), and it read the shared+ * ALCHEMY_API_KEY directly, so a deployment using the per-chain overrides above+ * had a working RPC lane and a dead NFT lane.+ */+export function alchemyNftBaseUrl(chainId) {+ const sub = ALCHEMY_SUBDOMAIN[chainId];+ const key = alchemyKey(chainId);+ return sub && key ? `https://${sub}.g.alchemy.com/nft/v3/${key}` : null;+}++/**+ * True when Alchemy publishes a host for this chain, independent of whether a+ * key is configured. Call sites that must distinguish "we cannot index this+ * chain at all" from "we could, but the key is missing" need this, since+ * alchemyNftBaseUrl collapses both to null.+ */+export function alchemySupportsChain(chainId) {+ return Boolean(ALCHEMY_SUBDOMAIN[chainId]);+}+// Hosts that answer a server-side keyless POST with a guaranteed failure, so// leading with one burns a full round trip per call before failover:// - eth.llamarpc.com Cloudflare bot-wall, 403 on datacenter POSTsdiff --git a/api/nft/resolve.js b/api/nft/resolve.jsindex f21975cd0..1823b19f9 100644--- a/api/nft/resolve.js+++ b/api/nft/resolve.js@@ -4,7 +4,12 @@ import { cacheGet, cacheSet } from '../_lib/cache.js';import { dasRpcUrl } from '../_lib/nft-gate.js';import { resolveGateway } from '../_lib/solana-agents-normalize.js';import { fetchTokenMeta } from '../_lib/solana-token-meta.js';-import { evmFallbackProvider } from '../_lib/evm/rpc.js';+import {+ evmFallbackProvider,+ evmRpcEndpoints,+ alchemyNftBaseUrl,+ alchemySupportsChain,+} from '../_lib/evm/rpc.js';// NFT metadata is effectively immutable, but the Helius `getAsset` (DAS) and// Alchemy `getNFTMetadata` calls behind this endpoint are billed per request and@@ -107,39 +112,6 @@ function pickModel(doc) {return { model: null, mime: null };}-// Alchemy NFT API host per EVM chainId. An id of the form-// "chainId:contract:tokenId" (exactly what api/users/[username]/collectibles.js-// emits for every EVM collectible) used to have its chainId parsed and then-// thrown away, so a Base or Polygon NFT was always looked up on Ethereum-// mainnet and came back as a 404 or, worse, as an unrelated Ethereum token that-// happens to share the contract/tokenId pair.-//-// This map is also the endpoint's supported-chain gate: a chainId missing here-// is rejected 400 before either rung runs, so an omission costs the caller the-// keyless on-chain read too, which needs no Alchemy key at all. Keep it aligned-// with api/_lib/evm/rpc.js ALCHEMY_SUBDOMAIN, which is what let polygon-amoy and-// avax-fuji drop out: both are in that map and in the chain registry with public-// RPCs, and both answered "unsupported evm chainId" here regardless.-const ALCHEMY_NFT_HOST = {- 1: 'eth-mainnet',- 10: 'opt-mainnet',- 56: 'bnb-mainnet',- 137: 'polygon-mainnet',- 324: 'zksync-mainnet',- 8453: 'base-mainnet',- 42161: 'arb-mainnet',- 43114: 'avax-mainnet',- 59144: 'linea-mainnet',- 534352: 'scroll-mainnet',- // testnets- 84532: 'base-sepolia',- 421614: 'arb-sepolia',- 43113: 'avax-fuji',- 80002: 'polygon-amoy',- 11155111: 'eth-sepolia',- 11155420: 'opt-sepolia',-};-/*** Keyless Solana rung: read the Metaplex metadata account over the platform's* ordinary RPC failover chain and follow its `uri`.@@ -380,8 +352,13 @@ export default wrap(async (req, res) => {return error(res, 400, 'bad_request', 'evm id must be "contract:tokenId" or "chainId:contract:tokenId"');}- const host = ALCHEMY_NFT_HOST[chainId];- if (!host) {+ // Gate on whether the platform can reach the chain AT ALL, not on whether the+ // indexer covers it. The keyless rung below reads the token's own metadata+ // pointer over the chain's public RPC list and needs no Alchemy host, so a+ // chain the registry knows is resolvable even when the indexer is not an+ // option. A chainId nothing in the stack has an endpoint for still 400s here+ // rather than timing out against nothing.+ if (evmRpcEndpoints(chainId).length === 0) {return error(res, 400, 'bad_request', `unsupported evm chainId ${parts[0]}`);}// Both the Alchemy call and the on-chain rung take these verbatim, so reject a@@ -399,20 +376,22 @@ export default wrap(async (req, res) => {// `env` exposes no ALCHEMY getter, so the previous `env.ALCHEMY_API_KEY` read// was undefined in every environment: the whole EVM branch built a URL with a// literal "undefined" key and answered 502 on a 401 from Alchemy, configured- // or not. Read the raw var (the same way collectibles.js, balances.js and- // scene/gate-check.js do) and say plainly when it is missing.- const apiKey = process.env.ALCHEMY_API_KEY;- if (!apiKey) {+ // or not. alchemyNftBaseUrl resolves the host and the key together, honoring+ // the per-chain key overrides (ALCHEMY_BASE_KEY and friends) that the RPC lane+ // already respects, and returns null when either half is absent.+ const baseUrl = alchemyNftBaseUrl(chainId);+ if (!baseUrl) {+ // Two different operator problems wear the same null, and telling them+ // apart is the difference between "provision a key" and "this chain has no+ // indexer, the keyless rung is all there is".+ const reason = alchemySupportsChain(chainId)+ ? `no Alchemy API key configured for chainId ${chainId}`+ : `Alchemy does not index chainId ${chainId}`;return evmRescue(() =>- error(- res,- 503,- 'not_configured',- 'ALCHEMY_API_KEY not configured and the token names no readable metadata',- ),+ error(res, 503, 'not_configured', `${reason} and the token names no readable metadata`),);}- const url = `https://${host}.g.alchemy.com/nft/v3/${apiKey}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;+ const url = `${baseUrl}/getNFTMetadata?contractAddress=${encodeURIComponent(contractAddress)}&tokenId=${encodeURIComponent(tokenId)}`;let resp;try {resp = await fetch(url, { signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });diff --git a/tests/nft-resolve-evm-chain-gate.test.js b/tests/nft-resolve-evm-chain-gate.test.jsnew file mode 100644index 000000000..5925327f8--- /dev/null+++ b/tests/nft-resolve-evm-chain-gate.test.js@@ -0,0 +1,98 @@+// /api/nft/resolve — the EVM chain gate and the Alchemy NFT URL it builds.+//+// The handler used to carry its own hand-copied Alchemy host map. Two things+// went wrong with the copy and neither was visible from the outside:+//+// 1. It lost polygon-amoy (80002) and avax-fuji (43113). Both are in the RPC+// module's host map and both have public RPCs in the chain registry, so+// the keyless on-chain rung could have read them. The gate rejected them+// 400 "unsupported evm chainId" before either rung ran.+// 2. It read process.env.ALCHEMY_API_KEY directly, ignoring the per-chain+// overrides (ALCHEMY_BASE_KEY and friends) that api/_lib/evm/rpc.js honors.+// A deployment provisioned that way had a working RPC lane and a dead NFT+// lane on the same chain.+//+// Both host maps now come from one place. These tests pin that: the NFT base+// URL is derived from the same table and the same key resolution as the JSON-RPC+// URL, and the gate admits every chain the platform can actually reach.++import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';++const ORIGINAL_ENV = { ...process.env };+const ALCHEMY_KEYS = [+ 'ALCHEMY_API_KEY',+ 'ALCHEMY_ETH_KEY',+ 'ALCHEMY_OPT_KEY',+ 'ALCHEMY_POLYGON_KEY',+ 'ALCHEMY_BASE_KEY',+ 'ALCHEMY_ARB_KEY',+];++async function loadModule() {+ vi.resetModules();+ return import('../api/_lib/evm/rpc.js');+}++beforeEach(() => {+ for (const key of ALCHEMY_KEYS) delete process.env[key];+});++afterEach(() => {+ process.env = { ...ORIGINAL_ENV };+});++describe('alchemyNftBaseUrl', () => {+ it('builds the v3 NFT base URL on the same host the JSON-RPC lane uses', async () => {+ process.env.ALCHEMY_API_KEY = 'shared-key';+ const { alchemyNftBaseUrl } = await loadModule();+ expect(alchemyNftBaseUrl(8453)).toBe('https://base-mainnet.g.alchemy.com/nft/v3/shared-key');+ expect(alchemyNftBaseUrl(1)).toBe('https://eth-mainnet.g.alchemy.com/nft/v3/shared-key');+ });++ it('honors the per-chain key override ahead of the shared key', async () => {+ process.env.ALCHEMY_API_KEY = 'shared-key';+ process.env.ALCHEMY_BASE_KEY = 'base-only-key';+ const { alchemyNftBaseUrl } = await loadModule();+ expect(alchemyNftBaseUrl(8453)).toBe('https://base-mainnet.g.alchemy.com/nft/v3/base-only-key');+ // A chain with no override still falls back to the shared key.+ expect(alchemyNftBaseUrl(59144)).toBe('https://linea-mainnet.g.alchemy.com/nft/v3/shared-key');+ });++ it('returns null when no key is configured, so the caller can fail over', async () => {+ const { alchemyNftBaseUrl } = await loadModule();+ expect(alchemyNftBaseUrl(8453)).toBeNull();+ });++ it('returns null for a chain Alchemy publishes no host for', async () => {+ process.env.ALCHEMY_API_KEY = 'shared-key';+ const { alchemyNftBaseUrl, alchemySupportsChain } = await loadModule();+ expect(alchemySupportsChain(999999)).toBe(false);+ expect(alchemyNftBaseUrl(999999)).toBeNull();+ });+});++describe('the EVM chain gate', () => {+ // The handler admits a chainId when evmRpcEndpoints() can name at least one+ // endpoint for it, because that is exactly what the keyless rung needs.+ it('admits the testnets the old hand-copied host map dropped', async () => {+ const { evmRpcEndpoints, alchemySupportsChain } = await loadModule();+ for (const chainId of [80002, 43113]) {+ expect(alchemySupportsChain(chainId)).toBe(true);+ expect(evmRpcEndpoints(chainId).length).toBeGreaterThan(0);+ }+ });++ it('admits every chain Alchemy indexes, key or no key', async () => {+ const { evmRpcEndpoints, alchemySupportsChain } = await loadModule();+ const indexed = [1, 10, 56, 137, 324, 8453, 42161, 43114, 59144, 534352, 84532, 421614, 43113, 80002, 11155111, 11155420];+ for (const chainId of indexed) {+ expect(alchemySupportsChain(chainId)).toBe(true);+ expect(evmRpcEndpoints(chainId).length, `chain ${chainId} has no reachable endpoint`).toBeGreaterThan(0);+ }+ });++ it('rejects a chainId nothing in the stack has an endpoint for', async () => {+ const { evmRpcEndpoints } = await loadModule();+ expect(evmRpcEndpoints(999999)).toHaveLength(0);+ });+});