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
feat(bnb): MegaFuel gasless-send client with self-pay fallback (prompt 02)
fudjiafbcce679d3a9
diff --git a/.env.example b/.env.exampleindex 8215e7b79..e506fde93 100644--- a/.env.example+++ b/.env.example@@ -338,6 +338,24 @@ SDP_API_BASE=https://api.solana.com# Per-network payTo wallets that receive USDC for paid MCP calls.X402_PAY_TO_SOLANA=wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrUX402_PAY_TO_BASE=0x4022de2d36c334e73c7a108805cea11c0564f402++# ── BNB Chain gasless sends (MegaFuel) ─────────────────────────────────────+# Optional NodeReal MegaFuel API key. NOT used by api/_lib/bnb/megafuel.js at+# send time — pm_isSponsorable / eth_sendRawTransaction run unauthenticated+# against the public bsc-megafuel(-testnet).nodereal.io endpoints; sponsorship+# is resolved server-side purely by matching the tx's `from` address against a+# pre-provisioned sponsor policy. This key is only needed for the separate+# ONE-TIME policy-management step (pm_createPolicy/pm_updatePolicy against+# open-platform-ap.nodereal.io/{key}/megafuel(-testnet), not yet implemented+# here) that whitelists a sender/contract. Until a policy exists for your+# sender, every send transparently self-pays — the feature works end-to-end+# without this key. Provision at https://dashboard.nodereal.io (MegaFuel+# product). Never commit a real key.+NODEREAL_MEGAFUEL_KEY=+# Funded BSC testnet (chainId 97) deployer/sender key for live gasless + contract+# proofs. Generate a throwaway: node -e "console.log(require('viem/accounts').generatePrivateKey())"+# then fund the address from https://www.bnbchain.org/en/testnet-faucet. Never commit a real key.+BNB_TESTNET_DEPLOYER_KEY=# Dedicated EIP-712 signing key for signed offers and payment receipts (USE-17).# This is a dedicated signing key, NOT a wallet that holds funds. Generate with:# node -e "console.log(require('viem/accounts').generatePrivateKey())"diff --git a/api/_lib/bnb/megafuel.js b/api/_lib/bnb/megafuel.jsnew file mode 100644index 000000000..9dfa79287--- /dev/null+++ b/api/_lib/bnb/megafuel.js@@ -0,0 +1,216 @@+/**+ * MegaFuel gasless-send client for BNB Chain, with a mandatory self-pay fallback.+ *+ * The crown-jewel BNB capability: a plain private-key EOA can send a transaction+ * that pays ZERO gas, sponsored at the block-building layer (BEP-414 paymaster ++ * BEP-322 atomic bundles), operated by NodeReal's MegaFuel. No smart account, no+ * 7702 delegation — mechanically impossible on Ethereum L1 / Base.+ *+ * Two RPC methods do the whole job (`pm_isSponsorable`, `eth_sendRawTransaction`+ * against the paymaster endpoint), so rather than pull `megafuel-js-sdk` into the+ * serverless bundle we call them directly via `fetch` — same rationale as+ * `erc8004-chains.js` keeping the bundle lean. If MegaFuel declines or is down we+ * self-pay through the prompt-01 public client, so a send NEVER hard-fails on the+ * sponsorship path alone (00-CONTEXT: outage → self-pay).+ *+ * This module never reads a private key. The caller passes a viem account+ * (built from its own signer), and signing happens through that account.+ */++import { getPublicClient } from './chains.js';++/** MegaFuel paymaster endpoints (00-CONTEXT). No secret required for reads/self-pay. */+export const MEGAFUEL_ENDPOINTS = {+ bscMainnet: 'https://bsc-megafuel.nodereal.io',+ bscTestnet: 'https://bsc-megafuel-testnet.nodereal.io',+};++const DEFAULT_TIMEOUT_MS = 8000;++/** Typed error for MegaFuel/self-pay failures. `code` disambiguates the stage. */+export class MegaFuelError extends Error {+ /** @param {string} message @param {{ code?: string, cause?: unknown, mode?: string }} [info] */+ constructor(message, info = {}) {+ super(message);+ this.name = 'MegaFuelError';+ this.code = info.code || 'megafuel_error';+ this.mode = info.mode;+ if (info.cause) this.cause = info.cause;+ }+}++function normalizeNetwork(network) {+ if (network === 56 || network === '56' || network === 'bsc' || network === 'mainnet' || network === 'bscMainnet') return 'bscMainnet';+ return 'bscTestnet';+}++/**+ * Resolve the MegaFuel endpoint for `pm_isSponsorable` / `eth_sendRawTransaction`.+ * Per NodeReal's docs these two RPC methods live at the plain `bsc-megafuel(-testnet)`+ * base URL always — there is no API-key path segment for them. `NODEREAL_MEGAFUEL_KEY`+ * is only used by the separate policy-*management* endpoint+ * (`open-platform-ap.nodereal.io/{apikey}/megafuel(-testnet)`, `pm_createPolicy` /+ * `pm_updatePolicy` — a one-time sponsor setup step, not implemented here).+ * Sponsorship itself is resolved server-side purely by matching the tx's `from`+ * address against an already-provisioned policy, so this send path needs no key.+ */+export function megafuelEndpoint(network) {+ const key = normalizeNetwork(network);+ return MEGAFUEL_ENDPOINTS[key];+}++/** Low-level JSON-RPC POST with a bounded timeout. Injectable `fetchImpl` for tests. */+async function rpc(url, method, params, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS } = {}) {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);+ try {+ const res = await fetchImpl(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ signal: controller.signal,+ });+ if (!res.ok) throw new MegaFuelError(`MegaFuel HTTP ${res.status}`, { code: 'http_error' });+ const json = await res.json();+ if (json.error) throw new MegaFuelError(json.error.message || 'rpc error', { code: 'rpc_error', cause: json.error });+ return json.result;+ } finally {+ clearTimeout(timer);+ }+}++/** Shape a viem tx request into the paymaster's expected JSON tx object. */+function toPaymasterTx(tx, from) {+ const hex = (v) => (v == null ? undefined : typeof v === 'bigint' ? `0x${v.toString(16)}` : v);+ return {+ from,+ to: tx.to,+ value: hex(tx.value ?? 0n) ?? '0x0',+ gas: hex(tx.gas),+ data: tx.data || '0x',+ };+}++/**+ * Ask MegaFuel whether it will sponsor a tx. A policy "no" is a NORMAL answer,+ * not an error — this never throws on a decline.+ *+ * @param {'bscMainnet'|'bscTestnet'|56|97} network+ * @param {{ to:string, from?:string, value?:bigint|string, gas?:bigint|string, data?:string }} txRequest+ * @param {{ fetchImpl?:Function, timeoutMs?:number, megafuelRpc?:Function }} [opts]+ * @returns {Promise<{ sponsorable:boolean, sponsorInfo:object|null, reason:string|null }>}+ */+export async function isSponsorable(network, txRequest, opts = {}) {+ const key = normalizeNetwork(network);+ const call = opts.megafuelRpc+ ? (method, params) => opts.megafuelRpc(method, params)+ : (method, params) => rpc(megafuelEndpoint(key), method, params, opts);+ try {+ const result = await call('pm_isSponsorable', [toPaymasterTx(txRequest, txRequest.from)]);+ const sponsorable = !!(result && result.sponsorable);+ return {+ sponsorable,+ sponsorInfo: sponsorable ? result : null,+ reason: sponsorable ? null : result?.reason || result?.message || 'not sponsorable',+ };+ } catch (err) {+ // Wire/endpoint failure is treated as "not sponsorable" so the caller+ // silently self-pays. The reason is surfaced for observability.+ return { sponsorable: false, sponsorInfo: null, reason: `probe failed: ${err.message}` };+ }+}++/**+ * Send a transaction gaslessly via MegaFuel when sponsorable, else self-pay.+ * The self-pay fallback is mandatory: a policy decline, a MegaFuel 5xx, or a+ * timeout all resolve to a normal self-paid send. Only a genuinely failed+ * self-pay (no gas / revert) raises a typed error.+ *+ * @param {'bscMainnet'|'bscTestnet'|56|97} network+ * @param {{ account: import('viem').Account, tx: { to:string, value?:bigint, data?:string, gas?:bigint } }} params+ * `account` is a viem account (caller-owned signer); no key is read here.+ * @param {{+ * publicClient?: import('viem').PublicClient,+ * walletClient?: import('viem').WalletClient,+ * megafuelRpc?: Function, fetchImpl?: Function, timeoutMs?: number,+ * }} [opts]+ * @returns {Promise<{ hash:`0x${string}`, mode:'sponsored'|'self-pay', sponsor?:object|null, reason?:string|null }>}+ */+export async function sendGasless(network, { account, tx }, opts = {}) {+ const key = normalizeNetwork(network);+ if (!account || typeof account.signTransaction !== 'function') {+ throw new MegaFuelError('sendGasless requires a viem account with signTransaction', { code: 'bad_signer' });+ }+ if (!tx || !tx.to || !/^0x[0-9a-fA-F]{40}$/.test(tx.to)) {+ throw new MegaFuelError('sendGasless requires tx.to to be a valid address', { code: 'bad_tx' });+ }++ const publicClient = opts.publicClient || getPublicClient(key);+ const chainId = BNB_CHAIN_ID[key];++ // Try the sponsored path first.+ const probe = await isSponsorable(+ key,+ { to: tx.to, from: account.address, value: tx.value, gas: tx.gas, data: tx.data },+ opts,+ );++ if (probe.sponsorable) {+ try {+ const nonce = await publicClient.getTransactionCount({ address: account.address, blockTag: 'pending' });+ const gas = tx.gas ?? (await publicClient.estimateGas({ account, to: tx.to, value: tx.value ?? 0n, data: tx.data }));+ // gasPrice: 0 is the whole trick — the sponsor tx pays for inclusion.+ const signed = await account.signTransaction({+ to: tx.to,+ value: tx.value ?? 0n,+ data: tx.data || '0x',+ gas,+ gasPrice: 0n,+ nonce,+ chainId,+ });+ const call = opts.megafuelRpc+ ? (m, p) => opts.megafuelRpc(m, p)+ : (m, p) => rpc(megafuelEndpoint(key), m, p, opts);+ const hash = await call('eth_sendRawTransaction', [signed]);+ return { hash, mode: 'sponsored', sponsor: probe.sponsorInfo };+ } catch (err) {+ // MegaFuel accepted the probe but the raw send failed → fall through+ // to self-pay rather than hard-failing.+ return selfPay(key, { account, tx }, publicClient, opts, `sponsored send failed: ${err.message}`);+ }+ }++ return selfPay(key, { account, tx }, publicClient, opts, probe.reason);+}++/** Self-pay path: a normal, gas-paying send via the standard public/wallet client. */+async function selfPay(network, { account, tx }, publicClient, opts, reason) {+ try {+ let walletClient = opts.walletClient;+ if (!walletClient) {+ const { createWalletClient, http } = await import('viem');+ walletClient = createWalletClient({+ account,+ chain: publicClient.chain,+ transport: http(publicClient.bnbRpcs?.[0]),+ });+ }+ const hash = await walletClient.sendTransaction({+ account,+ to: tx.to,+ value: tx.value ?? 0n,+ data: tx.data || '0x',+ gas: tx.gas,+ });+ return { hash, mode: 'self-pay', reason };+ } catch (err) {+ throw new MegaFuelError(`self-pay send failed: ${err.shortMessage || err.message}`, {+ code: 'self_pay_failed',+ mode: 'self-pay',+ cause: err,+ });+ }+}++const BNB_CHAIN_ID = { bscMainnet: 56, bscTestnet: 97 };diff --git a/tests/bnb-megafuel.test.js b/tests/bnb-megafuel.test.jsnew file mode 100644index 000000000..f5f942d67--- /dev/null+++ b/tests/bnb-megafuel.test.js@@ -0,0 +1,181 @@+/**+ * MegaFuel gasless-send client — unit tests.+ *+ * Every path is exercised with injected mocks (megafuelRpc, publicClient,+ * walletClient) and a SYNTHETIC throwaway account — no live network, no real+ * key. The self-pay fallback is the load-bearing behaviour and gets the most+ * coverage: policy decline, MegaFuel throwing, and sponsored-send failure must+ * all resolve to a self-paid send rather than a hard failure.+ */++import { readFileSync } from 'node:fs';+import { describe, it, expect } from 'vitest';+import { generatePrivateKey, privateKeyToAccount } from 'viem/accounts';+import {+ isSponsorable,+ sendGasless,+ megafuelEndpoint,+ MegaFuelError,+ MEGAFUEL_ENDPOINTS,+} from '../api/_lib/bnb/megafuel.js';++// Synthetic throwaway account — generated per run, never a real third-party key.+const account = privateKeyToAccount(generatePrivateKey());+const TO = '0x000000000000000000000000000000000000dEaD';++function mockPublicClient() {+ return {+ chain: { id: 97, name: 'BNB Smart Chain Testnet', nativeCurrency: { name: 'tBNB', symbol: 'tBNB', decimals: 18 } },+ bnbRpcs: ['https://data-seed-prebsc-1-s1.bnbchain.org:8545'],+ async getTransactionCount() {+ return 0;+ },+ async estimateGas() {+ return 21000n;+ },+ };+}++describe('megafuelEndpoint', () => {+ // pm_isSponsorable / eth_sendRawTransaction run unauthenticated at the plain+ // base URL always (verified against docs.nodereal.io/reference/pm-issponsorable+ // and .../eth-sendrawtransaction-megafuel) — no API-key path segment. The key+ // only applies to the separate policy-management endpoint (not implemented here).+ it('returns the public testnet endpoint', () => {+ expect(megafuelEndpoint('bscTestnet')).toBe(MEGAFUEL_ENDPOINTS.bscTestnet);+ });+ it('returns the public mainnet endpoint regardless of NODEREAL_MEGAFUEL_KEY', () => {+ process.env.NODEREAL_MEGAFUEL_KEY = 'testkey';+ expect(megafuelEndpoint('bscMainnet')).toBe(MEGAFUEL_ENDPOINTS.bscMainnet);+ delete process.env.NODEREAL_MEGAFUEL_KEY;+ });+});++describe('isSponsorable', () => {+ it('maps a sponsorable:true reply', async () => {+ const out = await isSponsorable('bscTestnet', { to: TO, from: account.address }, {+ megafuelRpc: async () => ({ sponsorable: true, sponsorAddress: '0xabc' }),+ });+ expect(out.sponsorable).toBe(true);+ expect(out.sponsorInfo).toMatchObject({ sponsorable: true });+ expect(out.reason).toBeNull();+ });++ it('maps a sponsorable:false reply with a reason (does not throw)', async () => {+ const out = await isSponsorable('bscTestnet', { to: TO, from: account.address }, {+ megafuelRpc: async () => ({ sponsorable: false, reason: 'no policy' }),+ });+ expect(out.sponsorable).toBe(false);+ expect(out.reason).toBe('no policy');+ });++ it('treats a probe error as not-sponsorable (never throws)', async () => {+ const out = await isSponsorable('bscTestnet', { to: TO, from: account.address }, {+ megafuelRpc: async () => {+ throw new Error('endpoint down');+ },+ });+ expect(out.sponsorable).toBe(false);+ expect(out.reason).toMatch(/probe failed/);+ });+});++describe('sendGasless — sponsored path', () => {+ it('signs with gasPrice 0 and submits via MegaFuel → mode:sponsored', async () => {+ const calls = [];+ const out = await sendGasless('bscTestnet', { account, tx: { to: TO } }, {+ publicClient: mockPublicClient(),+ megafuelRpc: async (method, params) => {+ calls.push(method);+ if (method === 'pm_isSponsorable') return { sponsorable: true, sponsorAddress: '0xspon' };+ if (method === 'eth_sendRawTransaction') {+ expect(typeof params[0]).toBe('string'); // a signed raw tx+ return '0x' + 'a'.repeat(64);+ }+ return null;+ },+ });+ expect(out.mode).toBe('sponsored');+ expect(out.hash).toBe('0x' + 'a'.repeat(64));+ expect(calls).toContain('pm_isSponsorable');+ expect(calls).toContain('eth_sendRawTransaction');+ });+});++describe('sendGasless — self-pay fallback (load-bearing)', () => {+ it('policy declines → self-pays via walletClient → mode:self-pay', async () => {+ let sent = false;+ const out = await sendGasless('bscTestnet', { account, tx: { to: TO } }, {+ publicClient: mockPublicClient(),+ megafuelRpc: async () => ({ sponsorable: false, reason: 'no policy for sender' }),+ walletClient: {+ async sendTransaction() {+ sent = true;+ return '0x' + 'b'.repeat(64);+ },+ },+ });+ expect(sent).toBe(true);+ expect(out.mode).toBe('self-pay');+ expect(out.hash).toBe('0x' + 'b'.repeat(64));+ expect(out.reason).toMatch(/no policy/);+ });++ it('MegaFuel throwing on the probe → still self-pays', async () => {+ const out = await sendGasless('bscTestnet', { account, tx: { to: TO } }, {+ publicClient: mockPublicClient(),+ megafuelRpc: async () => {+ throw new Error('megafuel 503');+ },+ walletClient: { async sendTransaction() { return '0x' + 'c'.repeat(64); } },+ });+ expect(out.mode).toBe('self-pay');+ });++ it('sponsored send failing after an accepted probe → self-pays', async () => {+ const out = await sendGasless('bscTestnet', { account, tx: { to: TO } }, {+ publicClient: mockPublicClient(),+ megafuelRpc: async (method) => {+ if (method === 'pm_isSponsorable') return { sponsorable: true };+ throw new Error('raw send rejected');+ },+ walletClient: { async sendTransaction() { return '0x' + 'd'.repeat(64); } },+ });+ expect(out.mode).toBe('self-pay');+ });++ it('self-pay also failing → typed MegaFuelError', async () => {+ await expect(+ sendGasless('bscTestnet', { account, tx: { to: TO } }, {+ publicClient: mockPublicClient(),+ megafuelRpc: async () => ({ sponsorable: false }),+ walletClient: { async sendTransaction() { throw new Error('insufficient funds'); } },+ }),+ ).rejects.toBeInstanceOf(MegaFuelError);+ });+});++describe('sendGasless — input validation', () => {+ it('rejects a malformed tx.to before any network call', async () => {+ await expect(+ sendGasless('bscTestnet', { account, tx: { to: 'not-an-address' } }, {}),+ ).rejects.toMatchObject({ code: 'bad_tx' });+ });+ it('rejects a non-signer account', async () => {+ await expect(+ sendGasless('bscTestnet', { account: {}, tx: { to: TO } }, {}),+ ).rejects.toMatchObject({ code: 'bad_signer' });+ });+});++describe('no private key is read inside the module', () => {+ it('source reads no private key / mnemonic / raw key literal', () => {+ const src = readFileSync(new URL('../api/_lib/bnb/megafuel.js', import.meta.url), 'utf8');+ // The NodeReal API-key path (NODEREAL_MEGAFUEL_KEY) is a public endpoint+ // segment, not a signing key — the checks below target signing material.+ expect(src).not.toMatch(/PRIVATE_KEY/i);+ expect(src).not.toMatch(/privateKeyToAccount/);+ expect(src).not.toMatch(/mnemonic/i);+ expect(src).not.toMatch(/0x[0-9a-fA-F]{64}/); // no raw 32-byte key literal+ });+});