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.

Agent payments SDK EVM updates, a2a + trade handler hardening, sniper executor fixes

nirholasd88adcc00676
diff --git a/agent-payments-sdk/src/evm/EvmAgentOffline.ts b/agent-payments-sdk/src/evm/EvmAgentOffline.ts
index 4964119f9..1b4943ba8 100644
--- a/agent-payments-sdk/src/evm/EvmAgentOffline.ts
+++ b/agent-payments-sdk/src/evm/EvmAgentOffline.ts
@@ -9,7 +9,7 @@ import {
type Hex,
} from "viem";
import { AGENT_PAYMENTS_ABI, ERC20_ABI } from "./abi.js";
-import { getEvmChain, NATIVE_TOKEN_ADDRESS, type EvmChainId } from "./addresses.js";
+import { getEvmChain, isAgentPaymentsDeployed, NATIVE_TOKEN_ADDRESS, type EvmChainId } from "./addresses.js";
import { getInvoiceId, buildInvoiceWindow, generateMemo } from "./invoice.js";
import type {
EvmAcceptPaymentParams,
@@ -38,6 +38,18 @@ export class EvmAgentOffline {
readonly contractAddress: Address;
constructor(agentToken: Address, chainId: EvmChainId) {
+ // Fail loudly when the AgentPayments contract is not deployed on this chain.
+ // Without this guard every build*Tx() would silently emit a transaction
+ // addressed to 0x000…000 (funds/approvals lost), because the address table
+ // ships zero-address placeholders until the contract is live. Throwing here
+ // surfaces the real state — EVM agent payments are not yet operational — at
+ // construction, before any tx is built or signed.
+ if (!isAgentPaymentsDeployed(chainId)) {
+ throw new Error(
+ `AgentPayments contract is not deployed on chain ${chainId}. ` +
+ `EVM agent payments are not available yet on this chain; use the Solana payment path.`,
+ );
+ }
this.agentToken = agentToken;
this.chainId = chainId;
this.contractAddress = getEvmChain(chainId).agentPayments;
diff --git a/agent-payments-sdk/src/evm/addresses.ts b/agent-payments-sdk/src/evm/addresses.ts
index b45658042..c398a8ac3 100644
--- a/agent-payments-sdk/src/evm/addresses.ts
+++ b/agent-payments-sdk/src/evm/addresses.ts
@@ -20,8 +20,10 @@ export interface EvmChainConfig {
agentPayments: Address;
}
-/** Placeholder — replace with deployed contract addresses post-deployment */
-const UNDEPLOYED = "0x0000000000000000000000000000000000000000" as Address;
+/** The zero address. The AgentPayments contract is not yet deployed on any EVM
+ * chain, so every `agentPayments` below is this placeholder until deployment. */
+export const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000" as Address;
+const UNDEPLOYED = ZERO_ADDRESS;
export const EVM_CHAINS: Record<EvmChainId, EvmChainConfig> = {
1: {
@@ -98,5 +100,14 @@ export function isEvmChainSupported(chainId: number): chainId is EvmChainId {
return chainId in EVM_CHAINS;
}
+/** Whether the AgentPayments contract is actually deployed on this chain (i.e.
+ * its address is not the zero-address placeholder). Until deployment this is
+ * false for every chain, and constructing an EVM agent against it throws rather
+ * than silently handing the caller a transaction addressed to 0x000…000. */
+export function isAgentPaymentsDeployed(chainId: EvmChainId): boolean {
+ const chain = EVM_CHAINS[chainId];
+ return !!chain && chain.agentPayments.toLowerCase() !== ZERO_ADDRESS;
+}
+
/** Native ETH/BNB/AVAX sentinel address (matches EIP-7528) */
export const NATIVE_TOKEN_ADDRESS = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" as Address;
diff --git a/agent-payments-sdk/src/evm/transaction.ts b/agent-payments-sdk/src/evm/transaction.ts
index b5dce9e01..198c114e1 100644
--- a/agent-payments-sdk/src/evm/transaction.ts
+++ b/agent-payments-sdk/src/evm/transaction.ts
@@ -132,7 +132,19 @@ export async function checkAllowance(
body: JSON.stringify(body),
});
- const json: { result: Hex } = await res.json();
+ if (!res.ok) {
+ throw new Error(`Allowance check failed: RPC returned HTTP ${res.status}`);
+ }
+
+ const json: { result?: Hex; error?: { code: number; message: string } } =
+ await res.json();
+ if (json.error) {
+ throw new Error(`Allowance check failed: ${json.error.message}`);
+ }
+ if (typeof json.result !== "string") {
+ throw new Error("Allowance check failed: RPC returned no result");
+ }
+
const allowance = BigInt(json.result);
return allowance >= amount;
}
diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.js
index 0ddb7b5f1..b6de4cdce 100644
--- a/api/_lib/rate-limit.js
+++ b/api/_lib/rate-limit.js
@@ -255,6 +255,12 @@ export const limits = {
),
mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),
mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),
+ // Per-principal ceiling on the expensive/gated pump-fun MCP tools (vanity grind,
+ // whale/claim watches, metadata upload that burns shared IPFS pinning credits).
+ // A bearer authorizes these for free, so without a per-principal cap one account
+ // could drive unlimited expensive calls. Critical — fail closed in prod.
+ mcpPumpGated: (principal) =>
+ getLimiter('mcp:pump:gated', { limit: 30, window: '1 m', critical: true }).limit(principal),
// Paid MCP tools — each call runs real compute (glTF validation / inspection
// / optimization on a fetched model). Marked critical so they fail closed in
// prod without Redis rather than allowing unbounded paid work per instance.
diff --git a/api/agents/a2a-call.js b/api/agents/a2a-call.js
index 25e3615d0..02f94e20e 100644
--- a/api/agents/a2a-call.js
+++ b/api/agents/a2a-call.js
@@ -19,7 +19,7 @@
// co-signed by the peer's facilitator fee payer — with EVM EIP-3009 as fallback.
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
-import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';
+import { cors, error, json, method, rateLimited, readJson, respondError, serverError, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { env } from '../_lib/env.js';
import { assertSafePublicUrl, SsrfBlockedError } from '../_lib/ssrf-guard.js';
@@ -115,7 +115,7 @@ export default wrap(async (req, res) => {
try {
mandate = await verifyIntentMandate(mandateJws);
} catch (err) {
- if (err instanceof MandateError) return error(res, err.status, err.code, err.message);
+ if (err instanceof MandateError) return respondError(res, err.status, err.code, err);
throw err;
}
if (mandate.ownerUserId !== userId) {
@@ -128,7 +128,8 @@ export default wrap(async (req, res) => {
quote = await requestQuote({ endpoint: safeEndpoint, text });
} catch (err) {
if (err instanceof A2AClientError) {
- return error(res, 502, 'quote_failed', `could not get a quote from peer: ${err.message}`);
+ console.error('[agents/a2a-call] peer quote failed', err?.message);
+ return serverError(res, 502, 'quote_failed', err);
}
throw err;
}
@@ -152,7 +153,7 @@ export default wrap(async (req, res) => {
currency: currencyOf(accept),
});
} catch (err) {
- if (err instanceof MandateError) return error(res, err.status, err.code, err.message);
+ if (err instanceof MandateError) return respondError(res, err.status, err.code, err);
throw err;
}
@@ -256,7 +257,8 @@ export default wrap(async (req, res) => {
// release the hold so the mandate's budget isn't silently consumed.
await release(mandate.mandateId, amount);
if (err instanceof A2AClientError) {
- return error(res, 502, err.code || 'payment_failed', err.message, { details: err.details });
+ console.error('[agents/a2a-call] peer payment failed', err?.code, err?.message);
+ return serverError(res, 502, err.code || 'payment_failed', err);
}
return respondError(res, err.status || 502, 'payment_failed', err);
}
diff --git a/api/agents/a2a-mandate.js b/api/agents/a2a-mandate.js
index f9e8a2847..34a5a9c76 100644
--- a/api/agents/a2a-mandate.js
+++ b/api/agents/a2a-mandate.js
@@ -10,7 +10,7 @@
// that the user authorized this class of spend before any autonomous payment.
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
-import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';
+import { cors, error, json, method, rateLimited, readJson, respondError, wrap } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { DEFAULT_NETWORK, issueIntentMandate, MandateError, MAX_TTL_SECONDS, SUPPORTED_NETWORKS } from '../_lib/a2a/mandate.js';
@@ -58,7 +58,7 @@ export default wrap(async (req, res) => {
max_ttl_seconds: MAX_TTL_SECONDS,
});
} catch (err) {
- if (err instanceof MandateError) return error(res, err.status, err.code, err.message);
+ if (err instanceof MandateError) return respondError(res, err.status, err.code, err);
throw err;
}
});
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index 5fab8de31..b963e1d64 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -21,7 +21,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
-import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
import { getPumpTradeClient } from '../_lib/pump.js';
@@ -139,7 +139,8 @@ async function quoteTrade({ ctx, side, mintPk, amount, isMax, slippagePct, netwo
if (isGraduatedErr(err)) {
throw boundary(409, 'graduated', 'This coin has graduated off the bonding curve. Buying it from the agent wallet via the AMM isn’t supported on this path yet.');
}
- throw boundary(502, 'quote_failed', `could not price the buy: ${err?.message || 'unknown error'}`);
+ console.error('[agents/agent-trade] buy quote failed', err?.message);
+ throw boundary(502, 'quote_failed', 'could not price the buy — try again');
}
requireSolQuote(ctx, q.quoteMint);
const expectedBase = BigInt(q.expectedBaseTokens.toString());
@@ -178,7 +179,8 @@ async function quoteTrade({ ctx, side, mintPk, amount, isMax, slippagePct, netwo
} catch (err) {
if (!isGraduatedErr(err)) {
if (err?.isBoundary) throw err;
- throw boundary(502, 'quote_failed', `could not price the sell: ${err?.message || 'unknown error'}`);
+ console.error('[agents/agent-trade] sell quote failed', err?.message);
+ throw boundary(502, 'quote_failed', 'could not price the sell — try again');
}
// Graduated: route the quote through the canonical AMM pool.
const a = await quoteAmmSell({ network, mint: mintPk.toBase58(), baseAmount: baseBn, slippagePct });
@@ -428,7 +430,8 @@ async function handleExecute(req, res, id) {
if (isGraduatedErr(e)) {
return error(res, 409, 'graduated', 'This coin graduated mid-trade — refresh the quote and retry.');
}
- return error(res, 502, 'build_failed', `could not build the trade: ${e?.message || 'unknown error'}`);
+ console.error('[agents/agent-trade] build failed', e?.message);
+ return error(res, 502, 'build_failed', 'could not build the trade — try again');
}
const ledgerMeta = {
@@ -447,7 +450,8 @@ async function handleExecute(req, res, id) {
try {
sim = await conn.simulateTransaction(vtx, { sigVerify: false, replaceRecentBlockhash: true });
} catch (e) {
- return error(res, 502, 'simulation_failed', e?.message || 'simulation failed');
+ console.error('[agents/agent-trade] simulation failed', e?.message);
+ return serverError(res, 502, 'simulation_failed', e);
}
return json(res, 200, {
data: {
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
index 3f1178c0b..8e3ca17fc 100644
--- a/api/agents/pumpfun/[action].js
+++ b/api/agents/pumpfun/[action].js
@@ -13,7 +13,7 @@
*/
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
+import { cors, json, method, readJson, wrap, error, rateLimited, serverError, respondError } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
import { reserveSpend, finalizeSpend, releaseSpend } from '../../_lib/agent-spend-policy.js';
@@ -279,7 +279,7 @@ async function handleBuy(req, res, id) {
} catch (err) {
console.error('[pumpfun/buy] send failed', err);
if (reservation) await releaseSpend(reservation.reservationId);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ return serverError(res, 502, 'rpc_error', err);
}
if (reservation) {
@@ -501,7 +501,7 @@ async function handleLaunch(req, res, id) {
} catch (err) {
console.error('[pumpfun/launch] send failed', err);
await releaseSpend(reservation.reservationId);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ return serverError(res, 502, 'rpc_error', err);
}
await finalizeSpend(reservation.reservationId, { mint: mintAddr, signature });
@@ -623,7 +623,7 @@ async function handlePay(req, res, id) {
});
} catch (err) {
console.error('[pumpfun/pay] balances failed', err);
- return error(res, 502, 'rpc_error', err.message || 'balance fetch failed');
+ return serverError(res, 502, 'rpc_error', err);
}
}
@@ -734,7 +734,7 @@ async function handlePay(req, res, id) {
await conn.confirmTransaction(signature, 'confirmed');
} catch (err) {
console.error(`[pumpfun/pay] ${body.action} send failed`, err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ return serverError(res, 502, 'rpc_error', err);
}
await sql`
@@ -1137,7 +1137,7 @@ async function handleSell(req, res, id) {
await conn.confirmTransaction(signature, 'confirmed');
} catch (err) {
console.error('[pumpfun/sell] send failed', err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ return serverError(res, 502, 'rpc_error', err);
}
await sql`
@@ -1398,7 +1398,7 @@ async function handleSwap(req, res, id) {
} catch (err) {
console.error('[pumpfun/swap] send failed', err);
if (reservation) await releaseSpend(reservation.reservationId);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ return serverError(res, 502, 'rpc_error', err);
}
if (reservation) {
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index 20beaaa41..91ef2aedc 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -8,7 +8,7 @@ import { z } from 'zod';
import { PublicKey } from '@solana/web3.js';
import { solanaConnection, solanaRpcEndpoints, isEndpointCooling } from '../../_lib/solana/connection.js';
import { sql } from '../../_lib/db.js';
-import { cors, json, method, wrap, error, readJson, rateLimited } from '../../_lib/http.js';
+import { cors, json, method, wrap, error, readJson, rateLimited, serverError, respondError } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { getSessionUser } from '../../_lib/auth.js';
import { parse } from '../../_lib/validate.js';
@@ -228,7 +228,9 @@ export const handleValidate = wrap(async (req, res) => {
});
} catch (e) {
if (e instanceof SolanaAttestError) {
- return error(res, SOLANA_ATTEST_ERROR_STATUS[e.code] || 500, e.code, e.message);
+ const status = SOLANA_ATTEST_ERROR_STATUS[e.code] || 500;
+ if (status >= 500) console.error('[agents/solana] attest failed', e.code, e?.message);
+ return respondError(res, status, e.code, e);
}
throw e;
}
@@ -395,6 +397,12 @@ export const handleCard = wrap(async (req, res) => {
const network = a.meta?.network || 'mainnet';
const origin = env.APP_ORIGIN;
+ // Sections sourced from independent reads below. A read that throws on a
+ // transient DB error is recorded here so the response can tell the client
+ // "temporarily unavailable" apart from a genuine "no data" (null), instead of
+ // silently conflating the two.
+ const degraded = [];
+
let pumpfun = null;
try {
const rows = await sql`select kind, count(*)::int as n, max(seen_at) as last_seen from pumpfun_signals where agent_asset = ${asset} group by kind`;
@@ -408,19 +416,28 @@ export const handleCard = wrap(async (req, res) => {
}
pumpfun = { signal_count: total, by_kind: byKind, last_seen: last, feed_url: `${origin}/api/agents/pumpfun-feed` };
}
- } catch {}
+ } catch (err) {
+ degraded.push('pumpfun');
+ console.warn('[agent-card] pumpfun signals read failed:', err?.message || err);
+ }
let token_stats = null;
try {
const [s] = await sql`select s.graduated, s.bonding_curve, s.amm, s.last_signature, s.last_signature_at, s.recent_tx_count, s.refreshed_at, m.mint, m.network from pump_agent_stats s join pump_agent_mints m on m.id = s.mint_id where m.mint = ${asset} limit 1`;
if (s) token_stats = { mint: s.mint, network: s.network, graduated: s.graduated, bonding_curve: s.bonding_curve, amm: s.amm, last_signature: s.last_signature, last_signature_at: s.last_signature_at, recent_tx_count: s.recent_tx_count, refreshed_at: s.refreshed_at };
- } catch {}
+ } catch (err) {
+ degraded.push('token_stats');
+ console.warn('[agent-card] token_stats read failed:', err?.message || err);
+ }
let validation = null;
try {
const [v] = await sql`select signature, attester, payload, block_time from solana_attestations where agent_asset = ${asset} and network = ${network} and kind = 'threews.validation.v1' and payload->>'subkind' = ${SUBKIND_GLB_SCHEMA} and revoked = false order by slot desc nulls first, block_time desc limit 1`;
if (v) validation = { passed: v.payload?.passed === true, proof_hash: v.payload?.proof_hash || null, proof_uri: v.payload?.proof_uri || null, validator: v.attester, signature: v.signature, validated_at: v.block_time };
- } catch {}
+ } catch (err) {
+ degraded.push('validation');
+ console.warn('[agent-card] validation read failed:', err?.message || err);
+ }
return json(res, 200, {
schema_version: '1.0',
@@ -459,7 +476,8 @@ export const handleCard = wrap(async (req, res) => {
...(validation ? { validation } : {}),
...(pumpfun ? { pumpfun } : {}),
...(token_stats ? { token_stats } : {}),
- }, { 'cache-control': 'public, max-age=120', 'access-control-allow-origin': '*' });
+ ...(degraded.length ? { degraded } : {}),
+ }, { 'cache-control': degraded.length ? 'no-store' : 'public, max-age=120', 'access-control-allow-origin': '*' });
});
// ── solana-price-history ──────────────────────────────────────────────────────
@@ -948,7 +966,8 @@ export const handleEdit = wrap(async (req, res) => {
umi = createUmi(rpc).use(mplCore());
umi.use(signerIdentity(collectionAuthoritySigner(umi)));
} catch (e) {
- return error(res, 500, 'authority_unconfigured', e.message);
+ console.error('[agents/solana] authority/umi init failed', e?.message);
+ return serverError(res, 500, 'authority_unconfigured', e);
}
const assetPk = umiPublicKey(asset_pubkey);
@@ -997,7 +1016,8 @@ export const handleEdit = wrap(async (req, res) => {
signatures.name = base58Sig(nameRes.signature);
}
} catch (e) {
- return error(res, 502, 'onchain_edit_failed', `on-chain edit failed: ${e?.message || e}`);
+ console.error('[agents/solana] on-chain edit failed', e?.message || e);
+ return serverError(res, 502, 'onchain_edit_failed', e);
}
}
diff --git a/api/forever/inscribe.js b/api/forever/inscribe.js
index 99ac6683d..7e1e681a9 100644
--- a/api/forever/inscribe.js
+++ b/api/forever/inscribe.js
@@ -158,6 +158,20 @@ export default async function handler(req, res) {
if (cors(req, res, { origins: '*', methods: 'POST,OPTIONS' })) return;
if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');
+ // Creating an OrdinalsBot order spends the platform's API key/quota. Require a
+ // signed-in user or a valid bearer token, and rate-limit per IP, so the endpoint
+ // can't be scripted anonymously to spam third-party order creation.
+ const session = await getSessionUser(req).catch(() => null);
+ let authed = !!session;
+ if (!authed) {
+ const bearer = extractBearer(req);
+ if (bearer) authed = !!(await authenticateBearer(bearer).catch(() => null));
+ }
+ if (!authed) return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');
+
+ const rl = await limits.inscribeIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
let body;
try {
body = await readJson(req);
diff --git a/api/ibm/attest.js b/api/ibm/attest.js
index 646a76d08..08ead4a76 100644
--- a/api/ibm/attest.js
+++ b/api/ibm/attest.js
@@ -23,6 +23,7 @@ import { createHash } from 'node:crypto';
import { cors, json, method, wrap, error, readJson, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { watsonxForecast, forecastModelFor } from '../_lib/watsonx-forecast.js';
import { fetchOhlcv, topPoolForToken, trendingPools } from '../_lib/market/ohlcv.js';
@@ -474,6 +475,23 @@ export default wrap(async (req, res) => {
// POST with submit:true actually writes the proof on-chain (server is
// authoritative — it re-derives the digest and never trusts a client value).
if (submit && req.method === 'POST') {
+ // Broadcasting pays a real network fee from the shared attester wallet, so
+ // gate it: require a signed-in user or bearer token (read-only attestation
+ // stays open), plus a per-attester-pubkey daily ceiling so concurrent calls
+ // can't drain the wallet's SOL via fees.
+ const session = await getSessionUser(req).catch(() => null);
+ let authed = !!session;
+ if (!authed) {
+ const bearer = extractBearer(req);
+ if (bearer) authed = !!(await authenticateBearer(bearer).catch(() => null));
+ }
+ if (!authed) {
+ out.onchain.error = 'on-chain submission requires sign-in or a valid bearer token';
+ return json(res, 401, out, { 'cache-control': 'no-store' });
+ }
+ const submitRl = await limits.attestSubmitDaily(wallet.address || 'unconfigured');
+ if (!submitRl.success) return rateLimited(res, submitRl, 'daily on-chain attestation limit reached');
+
if (!out.proof) {
out.onchain.error = 'nothing to notarize: ' + (out.onchain.reason || 'no forecast');
} else if (out.governance?.passed === false) {
diff --git a/api/pump-fun-mcp.js b/api/pump-fun-mcp.js
index 36d6daabe..bffe937b1 100644
--- a/api/pump-fun-mcp.js
+++ b/api/pump-fun-mcp.js
@@ -28,6 +28,7 @@
import { cors, json, method, wrap, readJson, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { extractBearer, authenticateBearer } from './_lib/auth.js';
+import { fetchSafePublicUrlPinned, SsrfBlockedError } from './_lib/ssrf-guard.js';
import {
verifyPayment,
settlePayment,
@@ -1035,7 +1036,15 @@ async function _fetchImgBuf(imageUrl) {
const ctrl = new AbortController();
const tid = setTimeout(() => ctrl.abort(), META_IMG_TIMEOUT_MS);
try {
- const r = await fetch(imageUrl, { signal: ctrl.signal });
+ // image_url is fully caller-supplied; guard against SSRF (internal hosts /
+ // cloud metadata) before fetching. Pinned variant closes the DNS-rebind window.
+ let r;
+ try {
+ r = await fetchSafePublicUrlPinned(imageUrl, { signal: ctrl.signal }, { allowHttp: true });
+ } catch (err) {
+ if (err instanceof SsrfBlockedError) throw rpcError(-32602, 'image_url is not an allowed public URL');
+ throw err;
+ }
if (!r.ok) throw rpcError(-32004, `image fetch failed: HTTP ${r.status}`);
const buf = Buffer.from(await r.arrayBuffer());
if (buf.byteLength > IMG_MAX_BYTES) throw rpcError(-32602, 'image exceeds 5 MB');
@@ -1370,8 +1379,10 @@ const AUTH_REQUIRED_TOOLS = new Set([
]);
// Resolve the caller's credentials for a gated tool, once per request. Returns
-// { ok: true, x402Ctx } x402Ctx null for bearer auth, or the
-// verified payment envelope to settle later
+// { ok: true, x402Ctx, principal } x402Ctx null for bearer auth, or the
+// verified payment envelope to settle later;
+// principal is a stable per-caller key used for
+// the per-principal rate limit on gated tools
// { ok: false, failure } failure.kind ∈ bad_bearer | bad_payment |
// no_credentials (+ message, envelope)
// The result is memoized so a batch carrying several gated calls verifies the
@@ -1380,7 +1391,16 @@ async function resolveGatedAuth(req) {
const bearer = extractBearer(req);
if (bearer) {
const auth = await authenticateBearer(bearer).catch(() => null);
- if (auth) return { ok: true, x402Ctx: null };
+ if (auth) {
+ // A valid bearer authorizes the gated tools for free, so bind a stable
+ // principal (api key id / oauth subject) for the per-principal rate limit
+ // — otherwise one account could drive unlimited expensive/credit-burning
+ // calls.
+ const principal = auth.apiKeyId
+ ? `apikey:${auth.apiKeyId}`
+ : `user:${auth.userId || 'unknown'}`;
+ return { ok: true, x402Ctx: null, principal };
+ }
return {
ok: false,
failure: {
@@ -1396,7 +1416,12 @@ async function resolveGatedAuth(req) {
const requirements = paymentRequirements(resourceUrl);
try {
const verified = await verifyPayment({ paymentHeader, requirements });
- return { ok: true, x402Ctx: { resourceUrl, requirements, verified } };
+ const payer = verified?.payer || verified?.payload?.payer || null;
+ return {
+ ok: true,
+ x402Ctx: { resourceUrl, requirements, verified },
+ principal: payer ? `payer:${payer}` : `ip:${clientIp(req)}`,
+ };
} catch (err) {
return {
ok: false,
@@ -1544,6 +1569,19 @@ async function dispatchRpc(msg, ctx) {
return gatedAuthFailureEnvelope(ctx.res, id, authz.failure);
}
ctx.x402Ctx = authz.x402Ctx;
+ // Per-principal ceiling on expensive/gated tools so a single bearer (which
+ // pays nothing) or payer can't drive unlimited grind/credit-burning work.
+ const gatedRl = await limits.mcpPumpGated(authz.principal || `ip:${clientIp(ctx.req)}`);
+ if (!gatedRl.success) {
+ if (!ctx.batch) {
+ ctx.gateDenied = {
+ id,
+ failure: { kind: 'rate_limited', code: -32029, message: 'rate limit exceeded for gated tools' },
+ };
+ return null;
+ }
+ return rpcEnvelope(id, null, { code: -32029, message: 'rate limit exceeded for gated tools' });
+ }
try {
const data = await handler(params?.arguments || {});
ctx.gatedSuccess = true;
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 6a49ba1a8..4e824cf73 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -70,9 +70,13 @@ async function enforceSharedSpendPolicy(agentId, network, perTradeLamports) {
// Record a confirmed/simulated snipe buy into the shared custody ledger so it
// counts toward the per-agent daily ceiling and shows in the audit trail.
-// Fire-and-forget — prices the SOL spend best-effort, never blocks the trade.
-function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode, mint }) {
- (async () => {
+// Awaited by the caller (not fire-and-forget): the on-chain buy has already
+// settled, so a ledger-write failure must never throw the trade away — but we
+// must finish the write before returning so a rapid next snipe sees this spend
+// against the ceiling rather than racing an unwritten record. Prices the SOL
+// spend best-effort; a pricing hiccup records lamports with a null USD value.
+async function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode, mint }) {
+ try {
let usd = null;
try { usd = await lamportsToUsd(lamports); } catch { usd = null; }
await recordSpend({
@@ -82,7 +86,9 @@ function recordSnipeSpend({ agentId, userId, network, lamports, signature, mode,
status: mode === 'live' ? 'confirmed' : 'ok',
meta: { mint, mode },
});
- })().catch((err) => log.warn?.('snipe_spend_record_failed', { agent: agentId, message: err?.message }));
+ } catch (err) {
+ log.warn?.('snipe_spend_record_failed', { agent: agentId, message: err?.message });
+ }
}
/**
@@ -179,7 +185,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
`;
log.trade('buy', { ...tag, mode: cfg.mode, sig, sol: lamportsToSol(perTrade), base: baseAmount.toString(), impact: Number(quote.priceImpactPct).toFixed(2) });
notifyBuy({ agentName: strat.agent_name || strat.agent_id, symbol: mint.symbol, mint: mint.mint, solSpent: lamportsToSol(perTrade), mode: cfg.mode, sig, chatId: strat.telegram_chat_id || null });
- recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint });
+ await recordSnipeSpend({ agentId: strat.agent_id, userId: strat.user_id, network: cfg.network, lamports: perTrade, signature: sig, mode: cfg.mode, mint: mint.mint });
return { status: 'open', sig };
} catch (err) {
return await fail(posId, tag, errCode(err), err);