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(bnb): chain constants + resilient RPC client (prompt 01)

fudjiaceb2c0345458
diff --git a/api/_lib/bnb/chains.js b/api/_lib/bnb/chains.js
new file mode 100644
index 000000000..cdc41978d
--- /dev/null
+++ b/api/_lib/bnb/chains.js
@@ -0,0 +1,195 @@
+/**
+ * BNB Chain constants + resilient RPC client + block-time probe.
+ *
+ * The single source of truth for every `api/_lib/bnb/*` module and the BNB
+ * product surfaces (latency proof, hub, vault, on-chain world). No secrets live
+ * here — every RPC URL is a public read endpoint. Mainnet Greenfield hub
+ * addresses are copied verbatim from `prompts/bnb-chain/00-CONTEXT.md` (bytecode
+ * verified 2026-07-07); never invent an address.
+ *
+ * Verified facts this module encodes (do not overstate elsewhere): BSC mainnet
+ * runs ~0.45s blocks (Fermi hardfork, live 2026-07-07); testnet block time is
+ * not a marketing claim, so `probeBlockTime` returns `target: null` there.
+ */
+
+import { createPublicClient, fallback, http, getAddress, isAddress } from 'viem';
+
+/**
+ * Typed error thrown when every RPC URL for a network is unreachable. Carries
+ * the list of URLs tried so a caller can surface a precise 503.
+ */
+export class BnbRpcError extends Error {
+ /** @param {string} message @param {{ network?: string, tried?: string[], cause?: unknown }} [info] */
+ constructor(message, info = {}) {
+ super(message);
+ this.name = 'BnbRpcError';
+ this.network = info.network;
+ this.tried = info.tried || [];
+ if (info.cause) this.cause = info.cause;
+ }
+}
+
+/**
+ * Chain metadata. Two public RPCs minimum per network for failover. Greenfield
+ * cross-chain hub addresses are BSC-mainnet-only (verbatim from 00-CONTEXT).
+ */
+export const BNB_CHAINS = {
+ bscMainnet: {
+ id: 56,
+ name: 'BNB Smart Chain',
+ testnet: false,
+ nativeCurrency: { name: 'BNB', symbol: 'BNB', decimals: 18 },
+ explorer: 'https://bscscan.com',
+ rpcs: [
+ 'https://bsc-dataseed.bnbchain.org',
+ 'https://bsc-dataseed1.binance.org',
+ 'https://bsc.drpc.org',
+ 'https://bsc-rpc.publicnode.com',
+ 'https://rpc.ankr.com/bsc',
+ ],
+ // Greenfield cross-chain hubs on BSC(56) — bytecode-verified 2026-07-07.
+ greenfieldHubs: {
+ crossChain: '0x77e719b714be09F70D484AB81F70D02B0E182f7d',
+ tokenHub: '0xeA97dF87E6c7F68C9f95A69dA79E19B834823F25',
+ bucketHub: '0xE909754263572F71bc6aFAc837646A93f5818573',
+ objectHub: '0x634eB9c438b8378bbdd8D0e10970Ec88db0b4d0f',
+ groupHub: '0xDd9af4573D64324125fCa5Ce13407be79331B7F7',
+ multiMessage: '0x26204702935e2D617EE75B795152B9623a7d9809',
+ },
+ },
+ bscTestnet: {
+ id: 97,
+ name: 'BNB Smart Chain Testnet',
+ testnet: true,
+ nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 },
+ explorer: 'https://testnet.bscscan.com',
+ rpcs: [
+ 'https://data-seed-prebsc-1-s1.bnbchain.org:8545',
+ 'https://data-seed-prebsc-2-s1.bnbchain.org:8545',
+ 'https://bsc-testnet.drpc.org',
+ 'https://bsc-testnet-rpc.publicnode.com',
+ ],
+ },
+};
+
+const DEFAULT_TIMEOUT_MS = 5000;
+
+/** @returns {'bscMainnet'|'bscTestnet'} normalized network key. Accepts id 56/97 or aliases. */
+function normalizeNetwork(network) {
+ if (network === 56 || network === '56' || network === 'bsc' || network === 'mainnet') return 'bscMainnet';
+ if (network === 97 || network === '97' || network === 'testnet') return 'bscTestnet';
+ if (network === 'bscMainnet' || network === 'bscTestnet') return network;
+ if (network == null) return 'bscTestnet';
+ throw new BnbRpcError(`Unknown BNB network: ${network}`, { tried: [] });
+}
+
+/** Build a viem `chain` object from our metadata (no dependency on viem/chains). */
+function toViemChain(meta) {
+ return {
+ id: meta.id,
+ name: meta.name,
+ nativeCurrency: meta.nativeCurrency,
+ rpcUrls: { default: { http: meta.rpcs }, public: { http: meta.rpcs } },
+ blockExplorers: { default: { name: 'Explorer', url: meta.explorer } },
+ testnet: meta.testnet,
+ };
+}
+
+const clientCache = new Map();
+
+/**
+ * viem public client with ordered RPC failover: requests hit the first healthy
+ * URL and only advance on error (viem `fallback`, `rank:false` → deterministic
+ * order). Clients are cached per network. Default network `bscTestnet`.
+ *
+ * @param {'bscMainnet'|'bscTestnet'|56|97} [network]
+ * @param {{ rpcs?: string[], transports?: any[], timeoutMs?: number, cache?: boolean }} [opts]
+ * `transports` injects custom viem transports (tests); `rpcs` overrides URLs.
+ * @returns {import('viem').PublicClient}
+ */
+export function getPublicClient(network = 'bscTestnet', opts = {}) {
+ const key = normalizeNetwork(network);
+ const meta = BNB_CHAINS[key];
+ const useCache = opts.cache !== false && !opts.transports && !opts.rpcs;
+ if (useCache && clientCache.has(key)) return clientCache.get(key);
+
+ const rpcs = opts.rpcs || meta.rpcs;
+ const timeout = opts.timeoutMs || DEFAULT_TIMEOUT_MS;
+ const transports = opts.transports || rpcs.map((url) => http(url, { timeout, retryCount: 0 }));
+
+ const client = createPublicClient({
+ chain: toViemChain(meta),
+ transport: fallback(transports, { rank: false, retryCount: 0 }),
+ });
+ client.bnbNetwork = key;
+ client.bnbRpcs = rpcs;
+ if (useCache) clientCache.set(key, client);
+ return client;
+}
+
+/**
+ * Measure the observed block time by sampling two blocks `sampleBlocks` apart.
+ * Iterates the RPC list manually so total RPC failure raises a typed
+ * `BnbRpcError` with every URL tried. `target` is the marketing reference for
+ * the network (mainnet 450ms; testnet has no published target → null).
+ *
+ * @param {'bscMainnet'|'bscTestnet'|56|97} [network]
+ * @param {number} [sampleBlocks]
+ * @param {{ rpcs?: string[], client?: import('viem').PublicClient, timeoutMs?: number }} [opts]
+ * @returns {Promise<{ network:string, avgBlockTimeMs:number, latestBlock:number, sampleBlocks:number, target:number|null, measuredAt:string }>}
+ */
+export async function probeBlockTime(network = 'bscTestnet', sampleBlocks = 200, opts = {}) {
+ const key = normalizeNetwork(network);
+ const meta = BNB_CHAINS[key];
+ const span = Math.max(1, Math.floor(sampleBlocks));
+ const rpcs = opts.rpcs || meta.rpcs;
+ const tried = [];
+ let lastErr;
+
+ // A caller-provided client (or the injected list) is tried first; otherwise
+ // walk each RPC in its own single-transport client so a dead URL is isolated.
+ const candidates = opts.client
+ ? [{ url: opts.client.bnbRpcs?.[0] || 'injected', client: opts.client }]
+ : rpcs.map((url) => ({ url, client: getPublicClient(key, { rpcs: [url], timeoutMs: opts.timeoutMs, cache: false }) }));
+
+ for (const { url, client } of candidates) {
+ tried.push(url);
+ try {
+ const latest = await client.getBlock({ blockTag: 'latest' });
+ const latestNumber = Number(latest.number);
+ const olderNumber = BigInt(Math.max(0, latestNumber - span));
+ const older = await client.getBlock({ blockNumber: olderNumber });
+ const blocks = latestNumber - Number(older.number);
+ const deltaMs = (Number(latest.timestamp) - Number(older.timestamp)) * 1000;
+ const avgBlockTimeMs = blocks > 0 ? Math.round((deltaMs / blocks) * 100) / 100 : 0;
+ return {
+ network: key,
+ avgBlockTimeMs,
+ latestBlock: latestNumber,
+ sampleBlocks: blocks,
+ target: key === 'bscMainnet' ? 450 : null,
+ measuredAt: new Date().toISOString(),
+ };
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw new BnbRpcError(`All BNB RPCs failed for ${key}`, { network: key, tried, cause: lastErr });
+}
+
+/** True for a syntactically valid 0x-prefixed 20-byte EVM address (checksum-agnostic). */
+export function isEvmAddress(s) {
+ return typeof s === 'string' && isAddress(s, { strict: false });
+}
+
+/**
+ * Assert `s` is a valid EVM address and return it checksummed. Throws a typed
+ * `BnbRpcError`-adjacent TypeError on junk / Solana base58 input.
+ * @returns {`0x${string}`}
+ */
+export function assertBscAddress(s) {
+ if (!isEvmAddress(s)) {
+ throw new TypeError(`Not a valid BSC/EVM address: ${String(s).slice(0, 64)}`);
+ }
+ return getAddress(s);
+}
diff --git a/prompts/bnb-chain/PROGRESS.md b/prompts/bnb-chain/PROGRESS.md
index 8b64652f0..63d33dde0 100644
--- a/prompts/bnb-chain/PROGRESS.md
+++ b/prompts/bnb-chain/PROGRESS.md
@@ -10,3 +10,34 @@ Append-only. Each completing agent adds a dated entry: prompt #, what shipped, r
Research basis: 101-agent deep-research run + bnb-chain org repo dig (verified facts and
refuted claims recorded in `00-CONTEXT.md`). Owner approved all three tracks. No prompt
executed yet.
+
+---
+
+## 2026-07-08 — Prompt 01: BNB chain constants + RPC failover lib — SHIPPED, verified live
+
+**Outcome: `api/_lib/bnb/chains.js` done and proven.** Built by a concurrent agent sharing
+this worktree; independently re-verified line-by-line against `00-CONTEXT.md` and the spec
+rather than trusted as-is (untracked, not yet committed).
+
+- `BNB_CHAINS.bscMainnet.greenfieldHubs` — all six hub addresses (crossChain, tokenHub,
+ bucketHub, objectHub, groupHub, multiMessage) match `00-CONTEXT.md` verbatim.
+ `bscMainnet.id=56` (5 public RPCs), `bscTestnet.id=97` (4 public RPCs, default network).
+- `getPublicClient(network, opts)` — viem `fallback()` transport (deterministic order,
+ `rank:false`), 5s per-RPC timeout, cached per network. Accepts numeric ids and string
+ aliases (`'bsc'`/`'mainnet'`/`'testnet'`) beyond the spec's literal names — ergonomic
+ superset, not a deviation.
+- `probeBlockTime(network, sampleBlocks=200)` — `{network, avgBlockTimeMs, latestBlock,
+ sampleBlocks, target, measuredAt}`; throws typed `BnbRpcError{tried:[...]}` on total
+ failure. `isEvmAddress`/`assertBscAddress` reuse viem's `isAddress`/`getAddress`.
+- **Tests:** `tests/bnb-chains.test.js` — 12 passed + 1 skipped (BNB_LIVE_RPC-gated) by
+ default; with `BNB_LIVE_RPC=1` → **13/13 passed**, live smoke test asserted
+ `avgBlockTimeMs < 700ms` for real.
+
+**Live proof the 0.45s block-time claim holds today** (real public RPC, not mocked):
+```json
+{ "network": "bscMainnet", "avgBlockTimeMs": 450, "latestBlock": 108693266,
+ "sampleBlocks": 200, "target": 450, "measuredAt": "2026-07-08T00:39:03.963Z" }
+```
+
+**Status: DONE.** Every other BNB prompt can now import this lib. Not yet committed —
+still untracked in the shared worktree pending an explicit commit pass.
diff --git a/tests/bnb-chains.test.js b/tests/bnb-chains.test.js
new file mode 100644
index 000000000..c2c274d06
--- /dev/null
+++ b/tests/bnb-chains.test.js
@@ -0,0 +1,134 @@
+/**
+ * BNB chain foundation lib — unit tests.
+ *
+ * Address constants are asserted verbatim against 00-CONTEXT. RPC failover and
+ * probeBlockTime are exercised with injected/mocked transports so the suite is
+ * deterministic (no live network). One live smoke test is guarded behind
+ * BNB_LIVE_RPC for opt-in real-RPC verification.
+ */
+
+import { describe, it, expect } from 'vitest';
+import { custom } from 'viem';
+import {
+ BNB_CHAINS,
+ BnbRpcError,
+ getPublicClient,
+ probeBlockTime,
+ isEvmAddress,
+ assertBscAddress,
+} from '../api/_lib/bnb/chains.js';
+
+describe('BNB_CHAINS constants', () => {
+ it('mainnet Greenfield crossChain hub matches 00-CONTEXT verbatim', () => {
+ expect(BNB_CHAINS.bscMainnet.greenfieldHubs.crossChain).toBe(
+ '0x77e719b714be09F70D484AB81F70D02B0E182f7d',
+ );
+ expect(BNB_CHAINS.bscMainnet.greenfieldHubs.multiMessage).toBe(
+ '0x26204702935e2D617EE75B795152B9623a7d9809',
+ );
+ });
+
+ it('has >=2 RPCs per network for failover', () => {
+ expect(BNB_CHAINS.bscMainnet.rpcs.length).toBeGreaterThanOrEqual(2);
+ expect(BNB_CHAINS.bscTestnet.rpcs.length).toBeGreaterThanOrEqual(2);
+ });
+
+ it('mainnet is 56, testnet is 97', () => {
+ expect(BNB_CHAINS.bscMainnet.id).toBe(56);
+ expect(BNB_CHAINS.bscTestnet.id).toBe(97);
+ });
+});
+
+describe('isEvmAddress / assertBscAddress', () => {
+ it('accepts a valid 0x 20-byte address', () => {
+ expect(isEvmAddress('0x77e719b714be09F70D484AB81F70D02B0E182f7d')).toBe(true);
+ });
+
+ it('rejects a Solana base58 mint and junk', () => {
+ expect(isEvmAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toBe(false);
+ expect(isEvmAddress('not-an-address')).toBe(false);
+ expect(isEvmAddress('0x123')).toBe(false);
+ expect(isEvmAddress(null)).toBe(false);
+ });
+
+ it('assertBscAddress returns a checksummed address', () => {
+ const out = assertBscAddress('0x77e719b714be09f70d484ab81f70d02b0e182f7d');
+ expect(out).toBe('0x77e719b714be09F70D484AB81F70D02B0E182f7d');
+ });
+
+ it('assertBscAddress throws on a Solana address', () => {
+ expect(() => assertBscAddress('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump')).toThrow(TypeError);
+ });
+});
+
+describe('getPublicClient failover', () => {
+ it('advances to the second transport when the first throws', async () => {
+ const t1 = custom({
+ async request() {
+ throw new Error('rpc-1 down');
+ },
+ });
+ const t2 = custom({
+ async request({ method }) {
+ if (method === 'eth_blockNumber') return '0x2a'; // 42
+ return null;
+ },
+ });
+ const client = getPublicClient('bscTestnet', { transports: [t1, t2] });
+ const bn = await client.getBlockNumber();
+ expect(bn).toBe(42n);
+ });
+});
+
+describe('probeBlockTime', () => {
+ it('computes avgBlockTimeMs from a mocked block pair (deterministic)', async () => {
+ // latest #1000 @ t=1450s, older #800 @ t=1360s → 200 blocks / 90s = 450ms/block.
+ const fakeClient = {
+ bnbRpcs: ['mock'],
+ async getBlock({ blockTag }) {
+ if (blockTag === 'latest') return { number: 1000n, timestamp: 1450n };
+ return { number: 800n, timestamp: 1360n };
+ },
+ };
+ const out = await probeBlockTime('bscMainnet', 200, { client: fakeClient });
+ expect(out.avgBlockTimeMs).toBe(450);
+ expect(out.latestBlock).toBe(1000);
+ expect(out.sampleBlocks).toBe(200);
+ expect(out.target).toBe(450);
+ expect(typeof out.measuredAt).toBe('string');
+ });
+
+ it('testnet probe reports target=null', async () => {
+ const fakeClient = {
+ bnbRpcs: ['mock'],
+ async getBlock({ blockTag }) {
+ if (blockTag === 'latest') return { number: 500n, timestamp: 1000n };
+ return { number: 300n, timestamp: 910n };
+ },
+ };
+ const out = await probeBlockTime('bscTestnet', 200, { client: fakeClient });
+ expect(out.target).toBeNull();
+ });
+
+ it('throws BnbRpcError listing tried URLs when all RPCs fail', async () => {
+ await expect(
+ probeBlockTime('bscTestnet', 10, { rpcs: ['http://127.0.0.1:1/dead'], timeoutMs: 300 }),
+ ).rejects.toMatchObject({ name: 'BnbRpcError' });
+ });
+
+ // Opt-in live smoke test — asserts the 0.45s claim holds on mainnet today.
+ const liveTest = process.env.BNB_LIVE_RPC ? it : it.skip;
+ liveTest('mainnet avg block time < 700ms (live RPC)', async () => {
+ const out = await probeBlockTime('bscMainnet', 200);
+ expect(out.avgBlockTimeMs).toBeGreaterThan(0);
+ expect(out.avgBlockTimeMs).toBeLessThan(700);
+ }, 20000);
+});
+
+describe('BnbRpcError', () => {
+ it('carries the tried URL list', () => {
+ const e = new BnbRpcError('boom', { network: 'bscTestnet', tried: ['a', 'b'] });
+ expect(e.name).toBe('BnbRpcError');
+ expect(e.tried).toEqual(['a', 'b']);
+ });
+});