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(avatar-agent-mcp): resolve .sol names on-chain now that Bonfida's REST API 404s

nirholas56c6900be037
diff --git a/packages/avatar-agent-mcp/package.json b/packages/avatar-agent-mcp/package.json
index e50c2cebc..27c112d94 100644
--- a/packages/avatar-agent-mcp/package.json
+++ b/packages/avatar-agent-mcp/package.json
@@ -58,6 +58,7 @@
"inspect": "npx -y @modelcontextprotocol/inspector node src/index.js"
},
"dependencies": {
+ "@bonfida/spl-name-service": "^3.0.26",
"@gltf-transform/core": "^4.3.0",
"@gltf-transform/extensions": "^4.3.0",
"@gltf-transform/functions": "^4.3.0",
diff --git a/packages/avatar-agent-mcp/src/config.js b/packages/avatar-agent-mcp/src/config.js
index ce602a922..d95d404eb 100644
--- a/packages/avatar-agent-mcp/src/config.js
+++ b/packages/avatar-agent-mcp/src/config.js
@@ -34,6 +34,24 @@ export const SOLANA_RPC_URL = validateRpcUrl(
env('SOLANA_RPC_URL', 'https://api.mainnet-beta.solana.com'),
);
export const ETH_RPC_URL = env('ETH_RPC_URL') || env('MAINNET_RPC_URL') || null;
+
+// Budget for one leg of `ens_sns_resolve`. Both lanes are multi-round-trip
+// (ENS: registry → resolver → addr; SNS: two account reads on a derived PDA),
+// and the free public endpoints both lanes fall back to are throttled, so a
+// tight budget reports "timed out" for names that resolve fine. Raise it when
+// you are pointing at a slow self-hosted RPC.
+export const NAME_RESOLVE_TIMEOUT_MS = (() => {
+ const raw = env('NAME_RESOLVE_TIMEOUT_MS');
+ if (raw === undefined) return 15000;
+ const n = Number(raw);
+ if (!Number.isFinite(n) || n <= 0) {
+ throw Object.assign(
+ new Error(`NAME_RESOLVE_TIMEOUT_MS must be a positive number (got "${raw}")`),
+ { code: 'bad_policy_config' },
+ );
+ }
+ return n;
+})();
export const HELIUS_API_KEY = env('HELIUS_API_KEY', '');
export const OPENAI_API_KEY = env('OPENAI_API_KEY', '');
// NVIDIA NIM key (build.nvidia.com, nvapi-…) — powers the FREE Magpie TTS
diff --git a/packages/avatar-agent-mcp/src/lib/ens-sns.js b/packages/avatar-agent-mcp/src/lib/ens-sns.js
index f190f1566..2b6c0b680 100644
--- a/packages/avatar-agent-mcp/src/lib/ens-sns.js
+++ b/packages/avatar-agent-mcp/src/lib/ens-sns.js
@@ -1,80 +1,122 @@
// ENS (Ethereum) + SNS (Solana) name resolution.
//
+// SNS: read straight from the SPL Name Service accounts on Solana with
+// `@bonfida/spl-name-service` over SOLANA_RPC_URL. Resolution is a pair of
+// getAccountInfo reads on a deterministically-derived PDA, so it depends on
+// nothing but the chain itself and matches what the three.ws backend does
+// (api/agents/sns.js). Bonfida's `sns-api.bonfida.com` REST service used to
+// back this lane; it now answers 404 on every path, which is exactly why the
+// chain is the source of truth here.
+//
// ENS: ethers JsonRpcProvider against the configured ETH_RPC_URL, falling
-// back to ethers' default public provider rotation.
-// SNS: Bonfida's sns-api (the same service three.ws uses on the web side).
+// back to ethers' default public provider rotation. A `.eth` lookup is a
+// multi-round-trip call (registry → resolver → addr), and the community
+// endpoints behind the default rotation are heavily throttled, so the budget
+// is per-lane and overridable with NAME_RESOLVE_TIMEOUT_MS.
import { ethers } from 'ethers';
+import { PublicKey } from '@solana/web3.js';
-import { ETH_RPC_URL } from '../config.js';
+import { ETH_RPC_URL, NAME_RESOLVE_TIMEOUT_MS } from '../config.js';
+import { getConnection } from './solana.js';
const ENS_RE = /^(?:[a-z0-9-]+\.)*[a-z0-9-]+\.eth$/i;
const SOL_RE = /^[a-z0-9-]{1,63}(?:\.sol)?$/i;
-const SNS_API = 'https://sns-api.bonfida.com';
+
+// A reverse/favorite lookup is a bonus field, never the answer, so it gets a
+// tighter budget than the resolution it decorates.
+const EXTRA_RATIO = 0.6;
+// getAllDomains is a getProgramAccounts scan: valuable, but the slowest call in
+// the set and the first thing a throttled RPC drops. Bounded and best-effort.
+const DOMAIN_LIST_LIMIT = 25;
async function withTimeout(promise, ms, label) {
- const timeout = new Promise((_, rej) => setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms));
- return Promise.race([promise, timeout]);
+ let timer;
+ const timeout = new Promise((_, rej) => {
+ timer = setTimeout(() => rej(new Error(`${label} timed out after ${ms}ms`)), ms);
+ });
+ try {
+ return await Promise.race([promise, timeout]);
+ } finally {
+ clearTimeout(timer);
+ }
}
async function resolveEns(name) {
const provider = ETH_RPC_URL
? new ethers.JsonRpcProvider(ETH_RPC_URL)
: ethers.getDefaultProvider('mainnet');
- const address = await withTimeout(provider.resolveName(name), 4000, 'ens');
- if (!address) return null;
- let reverseName = null;
try {
- reverseName = await withTimeout(provider.lookupAddress(address), 3000, 'ens-reverse');
- } catch {
- // best effort
+ const address = await withTimeout(provider.resolveName(name), NAME_RESOLVE_TIMEOUT_MS, 'ens');
+ if (!address) return null;
+ let reverseName = null;
+ try {
+ reverseName = await withTimeout(
+ provider.lookupAddress(address),
+ Math.round(NAME_RESOLVE_TIMEOUT_MS * EXTRA_RATIO),
+ 'ens-reverse',
+ );
+ } catch {
+ // best effort
+ }
+ return { network: 'ethereum', name, address, reverseName, rpc: ETH_RPC_URL || 'ethers-default' };
+ } finally {
+ // ethers keeps a poller alive per provider; without this the process
+ // hangs after the tool returns.
+ provider.destroy?.();
}
- return { network: 'ethereum', name, address, reverseName, rpc: ETH_RPC_URL || 'ethers-default' };
+}
+
+// Owner of `<bare>.sol`, read from the name-registry account. Returns null when
+// the domain has never been registered (the PDA has no account).
+async function snsOwner(connection, bare) {
+ const { getDomainKeySync, NameRegistryState } = await import('@bonfida/spl-name-service');
+ const { pubkey } = getDomainKeySync(bare);
+ const { registry } = await NameRegistryState.retrieve(connection, pubkey);
+ return registry?.owner instanceof PublicKey ? registry.owner : null;
+}
+
+async function snsFavoriteDomain(connection, owner) {
+ const { getFavoriteDomain } = await import('@bonfida/spl-name-service');
+ const fav = await getFavoriteDomain(connection, owner);
+ return fav?.reverse ? `${fav.reverse}.sol` : null;
+}
+
+async function snsOwnedDomains(connection, owner) {
+ const { getAllDomains, reverseLookupBatch } = await import('@bonfida/spl-name-service');
+ const keys = await getAllDomains(connection, owner);
+ if (!keys.length) return [];
+ const names = await reverseLookupBatch(connection, keys.slice(0, DOMAIN_LIST_LIMIT));
+ return names.filter(Boolean).map((n) => `${n}.sol`);
}
async function resolveSns(name) {
const bare = name.toLowerCase().replace(/\.sol$/, '');
if (!/^[a-z0-9-]{1,63}$/.test(bare)) return null;
- const lookup = await fetch(`${SNS_API}/v2/domain/lookup/${bare}.sol`).catch(() => null);
- if (!lookup || !lookup.ok) return null;
- const data = await lookup.json().catch(() => null);
- const owner = data?.owner || data?.[bare + '.sol']?.owner || data?.data?.owner || null;
- if (!owner) return null;
- let allDomains = [];
- try {
- const r = await fetch(`${SNS_API}/v2/user/domains/${owner}`);
- if (r.ok) {
- const body = await r.json();
- const list = body?.[owner] || body?.data?.[owner] || [];
- if (Array.isArray(list)) {
- allDomains = list
- .map((d) => (typeof d === 'string' ? d : d?.domain || d?.name))
- .filter(Boolean);
- }
- }
- } catch {
- // best effort
- }
+ const connection = getConnection();
+ const owner = await withTimeout(snsOwner(connection, bare), NAME_RESOLVE_TIMEOUT_MS, 'sns').catch((e) => {
+ // An unregistered domain is a clean "no", not an upstream failure: the
+ // library throws the same way for both, so only a real transport error
+ // should surface as one.
+ if (/account.*not.*(found|exist)|Invalid name account/i.test(e?.message || '')) return null;
+ throw e;
+ });
+ if (!owner) return null;
- let favoriteDomain = null;
- try {
- const r = await fetch(`${SNS_API}/v2/user/fav-domains/${owner}`);
- if (r.ok) {
- const body = await r.json();
- favoriteDomain = body?.[owner] || body?.data?.[owner] || null;
- }
- } catch {
- // best effort
- }
+ const extraMs = Math.round(NAME_RESOLVE_TIMEOUT_MS * EXTRA_RATIO);
+ const [favoriteDomain, allDomains] = await Promise.all([
+ withTimeout(snsFavoriteDomain(connection, owner), extraMs, 'sns-favorite').catch(() => null),
+ withTimeout(snsOwnedDomains(connection, owner), extraMs, 'sns-domains').catch(() => []),
+ ]);
return {
network: 'solana',
name: `${bare}.sol`,
- address: owner,
+ address: owner.toBase58(),
favoriteDomain,
allDomains,
- source: `${SNS_API}/v2/domain/lookup/${bare}.sol`,
+ source: 'spl-name-service (on-chain)',
};
}