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(api): implement widget action dispatcher with chat, duplicate, and stats handlers

nirholas36f33e53cd0e
diff --git a/.claude/scheduled_tasks.lock b/.claude/scheduled_tasks.lock
new file mode 100644
index 000000000..c87f9c3a0
--- /dev/null
+++ b/.claude/scheduled_tasks.lock
@@ -0,0 +1 @@
+{"sessionId":"ff218225-df62-4fb1-96c3-b4778c2e8199","pid":46515,"procStart":"128323","acquiredAt":1777482302265}
\ No newline at end of file
diff --git a/api/agents/onchain/prep.js b/api/agents/onchain/[action].js
similarity index 50%
rename from api/agents/onchain/prep.js
rename to api/agents/onchain/[action].js
index 7d2c98d8c..8d6cb51f7 100644
--- a/api/agents/onchain/prep.js
+++ b/api/agents/onchain/[action].js
@@ -1,27 +1,16 @@
/**
+ * Agent Onchain Dispatcher
+ * ------------------------
* POST /api/agents/onchain/prep
+ * POST /api/agents/onchain/confirm
*
- * Unified prep endpoint covering all chain families. Replaces:
- * • /api/agents/register-prep (EVM)
- * • /api/agents/solana-register-prep (Solana)
- *
- * Single payload shape, single CAIP-2 chain selector. The metadata manifest is
- * pinned once (IPFS) regardless of family, so EVM and Solana point at the same
- * canonical content.
- *
- * Returns a `prepId` that the confirm endpoint validates against. Persistence
- * uses `agent_registrations_pending` (existing table) with a unified payload.
- *
- * Wallet-ownership rule: if the wallet isn't yet linked to the user, prep
- * still succeeds — the SolanaAdapter runs SIWS on the client before calling
- * here, and EVM uses signed-tx ownership at confirm time. We re-verify on
- * confirm; prep only requires the wallet to *belong* to no other user.
+ * Single Vercel function that dispatches on req.query.action (auto-populated
+ * from the [action] filename). Consolidated to reduce function count and
+ * avoid bundling heavy Solana/Metaplex/EVM SDKs twice.
*/
import { z } from 'zod';
-import {
- createUmi,
-} from '@metaplex-foundation/umi-bundle-defaults';
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
import { mplCore, createV1 } from '@metaplex-foundation/mpl-core';
import {
generateSigner,
@@ -29,6 +18,10 @@ import {
signerIdentity,
createNoopSigner,
} from '@metaplex-foundation/umi';
+import { Connection } from '@solana/web3.js';
+import { JsonRpcProvider } from 'ethers';
+import { createHash } from 'crypto';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
@@ -36,6 +29,19 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
import { env } from '../../_lib/env.js';
+import { r2 } from '../../_lib/r2.js';
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'prep':
+ return handlePrep(req, res);
+ case 'confirm':
+ return handleConfirm(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown onchain action');
+ }
+});
// ── Chain parsing ────────────────────────────────────────────────────────────
@@ -63,9 +69,9 @@ function parseChain(caip2) {
throw new Error(`unsupported namespace: ${ns}`);
}
-// ── Request schema ───────────────────────────────────────────────────────────
+// ── prep ─────────────────────────────────────────────────────────────────────
-const bodySchema = z.object({
+const prepBodySchema = z.object({
agent_id: z.string().min(1).max(80),
chain: z.string().min(8).max(120),
wallet_address: z.string().min(20).max(80),
@@ -78,12 +84,6 @@ const bodySchema = z.object({
.optional(),
});
-// ── Manifest pinning (shared across families) ────────────────────────────────
-
-import { createHash } from 'crypto';
-import { r2 } from '../../_lib/r2.js';
-import { PutObjectCommand } from '@aws-sdk/client-s3';
-
async function pinManifest(manifest) {
const bytes = Buffer.from(JSON.stringify(manifest), 'utf-8');
const token = process.env.WEB3_STORAGE_TOKEN;
@@ -133,8 +133,6 @@ function buildManifest({ name, description, avatar_id, skills }) {
};
}
-// ── Family-specific tx prep ──────────────────────────────────────────────────
-
async function prepEvm({ chainId, metadataUri }) {
// EVM: client builds its own tx via ethers; we just hand back the metadata
// URI and the registry address (looked up from the existing chain config).
@@ -170,9 +168,7 @@ async function prepSolana({ cluster, metadataUri, walletAddress, name }) {
};
}
-// ── Endpoint ─────────────────────────────────────────────────────────────────
-
-export default wrap(async (req, res) => {
+async function handlePrep(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -182,7 +178,7 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const body = parse(bodySchema, await readJson(req));
+ const body = parse(prepBodySchema, await readJson(req));
let chain;
try {
@@ -270,4 +266,219 @@ export default wrap(async (req, res) => {
}),
expiresAt: expiresAt.toISOString(),
});
+}
+
+// ── confirm ──────────────────────────────────────────────────────────────────
+
+const confirmBodySchema = z.object({
+ prep_id: z.string().min(8).max(80),
+ tx_hash: z.string().min(8).max(120),
+ onchain_id: z.string().nullable().optional(),
+ wallet_address: z.string().min(20).max(80),
});
+
+async function verifyEvm({ chainId, txHash, expectedContract, expectedOwner }) {
+ const { CHAIN_BY_ID } = await import('../../_lib/erc8004-chains.js');
+ const cfg = CHAIN_BY_ID[chainId];
+ if (!cfg?.rpcUrl) throw new Error(`no RPC for chainId ${chainId}`);
+
+ const provider = new JsonRpcProvider(cfg.rpcUrl);
+ const receipt = await provider.getTransactionReceipt(txHash);
+ if (!receipt) {
+ const e = new Error('Transaction not found yet — try again in a few seconds.');
+ e.code = 'tx_not_found';
+ e.status = 422;
+ throw e;
+ }
+ if (receipt.status !== 1) {
+ const e = new Error('Transaction failed on-chain.');
+ e.code = 'tx_failed';
+ e.status = 422;
+ throw e;
+ }
+ if (
+ expectedContract &&
+ receipt.to &&
+ receipt.to.toLowerCase() !== expectedContract.toLowerCase()
+ ) {
+ const e = new Error('tx target does not match expected registry.');
+ e.code = 'tx_wrong_target';
+ e.status = 422;
+ throw e;
+ }
+ if (receipt.from.toLowerCase() !== expectedOwner.toLowerCase()) {
+ const e = new Error('tx sender does not match wallet_address.');
+ e.code = 'tx_wrong_sender';
+ e.status = 422;
+ throw e;
+ }
+ return { blockNumber: receipt.blockNumber };
+}
+
+async function verifySolana({ cluster, txSig, expectedAsset, expectedOwner }) {
+ const rpc =
+ cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+ const conn = new Connection(rpc, 'confirmed');
+
+ // Bounded poll — RPC may not have indexed the tx yet, especially on devnet.
+ const deadline = Date.now() + 20_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(txSig, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) {
+ const e = new Error('Transaction not found on Solana RPC.');
+ e.code = 'tx_not_found';
+ e.status = 422;
+ throw e;
+ }
+ if (tx.meta?.err) {
+ const e = new Error('Transaction failed on-chain.');
+ e.code = 'tx_failed';
+ e.status = 422;
+ throw e;
+ }
+
+ const accountKeys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
+ if (expectedAsset && !accountKeys.includes(expectedAsset)) {
+ const e = new Error('Asset pubkey not found in transaction.');
+ e.code = 'asset_not_in_tx';
+ e.status = 422;
+ throw e;
+ }
+ if (!accountKeys.includes(expectedOwner)) {
+ const e = new Error('Wallet address not in transaction signers.');
+ e.code = 'wrong_signer';
+ e.status = 422;
+ throw e;
+ }
+ return { slot: tx.slot };
+}
+
+async function handleConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(confirmBodySchema, await readJson(req));
+
+ const [prep] = await sql`
+ select id, payload, metadata_uri, cid
+ from agent_registrations_pending
+ where user_id = ${user.id}
+ and payload->>'prep_id' = ${body.prep_id}
+ and expires_at > now()
+ limit 1
+ `;
+ if (!prep) return error(res, 404, 'not_found', 'prep record expired or not found');
+
+ const p = prep.payload;
+ if (p.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet_address mismatch with prep record');
+ }
+
+ // Verify on-chain
+ try {
+ if (p.chain_family === 'evm') {
+ const chainId = Number(p.chain.split(':')[1]);
+ await verifyEvm({
+ chainId,
+ txHash: body.tx_hash,
+ expectedContract: p.contract_address,
+ expectedOwner: body.wallet_address,
+ });
+ } else if (p.chain_family === 'solana') {
+ await verifySolana({
+ cluster: p.cluster,
+ txSig: body.tx_hash,
+ expectedAsset: p.asset_pubkey,
+ expectedOwner: body.wallet_address,
+ });
+ } else {
+ return error(res, 400, 'validation_error', `unknown chain family: ${p.chain_family}`);
+ }
+ } catch (e) {
+ return error(res, e.status || 500, e.code || 'verify_failed', e.message);
+ }
+
+ // Link wallet to user (idempotent — confirm time, since tx is ownership proof).
+ await sql`
+ insert into user_wallets (user_id, address, chain_type, is_primary)
+ values (${user.id}, ${body.wallet_address}, ${p.chain_family === 'solana' ? 'solana' : 'evm'}, false)
+ on conflict do nothing
+ `;
+
+ // Build the unified onchain block.
+ const onchain = {
+ chain: p.chain,
+ family: p.chain_family,
+ tx_hash: body.tx_hash,
+ onchain_id: body.onchain_id || null,
+ contract_or_mint: p.contract_address || p.asset_pubkey || null,
+ wallet: body.wallet_address,
+ metadata_uri: prep.metadata_uri,
+ confirmed_at: new Date().toISOString(),
+ ...(p.chain_family === 'solana' ? { cluster: p.cluster } : {}),
+ };
+
+ // Upsert agent_identities. If a row already exists for (user, agent), we
+ // merge the new onchain block in — supports redeploying across chains.
+ const [existing] = await sql`
+ select id, meta from agent_identities
+ where user_id = ${user.id}
+ and (id::text = ${p.agent_id} or name = ${p.name})
+ and deleted_at is null
+ limit 1
+ `;
+
+ let agent;
+ if (existing) {
+ const mergedMeta = { ...(existing.meta || {}), onchain };
+ [agent] = await sql`
+ update agent_identities
+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ wallet_address = ${body.wallet_address},
+ updated_at = now()
+ where id = ${existing.id}
+ returning id, name, description, wallet_address, meta, created_at
+ `;
+ } else {
+ [agent] = await sql`
+ insert into agent_identities
+ (user_id, name, description, avatar_id, wallet_address, meta)
+ values (
+ ${user.id},
+ ${p.name},
+ ${p.description},
+ ${p.avatar_id},
+ ${body.wallet_address},
+ ${JSON.stringify({ onchain })}::jsonb
+ )
+ returning id, name, description, wallet_address, meta, created_at
+ `;
+ }
+
+ // Cleanup prep
+ await sql`delete from agent_registrations_pending where id = ${prep.id}`;
+
+ return json(res, 201, {
+ ok: true,
+ agent: {
+ ...agent,
+ onchain,
+ home_url: `${env.APP_ORIGIN}/agent/${agent.id}`,
+ },
+ });
+}
diff --git a/api/agents/onchain/confirm.js b/api/agents/onchain/confirm.js
deleted file mode 100644
index d2c5eb382..000000000
--- a/api/agents/onchain/confirm.js
+++ /dev/null
@@ -1,254 +0,0 @@
-/**
- * POST /api/agents/onchain/confirm
- *
- * Unified confirm endpoint. Replaces:
- * • /api/agents/register-confirm (EVM)
- * • /api/agents/solana-register-confirm (Solana)
- *
- * Verifies the on-chain transaction and writes a *unified* `meta.onchain`
- * block to `agent_identities` so downstream queries don't need to fork on
- * chain family. Persists the wallet linkage as a side effect (it was already
- * pre-checked at prep, but we re-verify here using the tx as ownership proof).
- *
- * Unified onchain shape stored in agent_identities.meta:
- * {
- * onchain: {
- * chain: "eip155:8453" | "solana:5eyk...", // CAIP-2
- * family: "evm" | "solana",
- * tx_hash: "0xabc..." | "<base58 sig>",
- * onchain_id: "<EVM agentId>" | null, // null on Solana
- * contract_or_mint:"<EVM registry addr>" | "<Solana mint pubkey>",
- * wallet: "<owner address>",
- * metadata_uri: "ipfs://...",
- * confirmed_at: "<ISO timestamp>",
- * ... family-specific extras
- * }
- * }
- */
-
-import { z } from 'zod';
-import { Connection } from '@solana/web3.js';
-import { JsonRpcProvider } from 'ethers';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { env } from '../../_lib/env.js';
-
-const bodySchema = z.object({
- prep_id: z.string().min(8).max(80),
- tx_hash: z.string().min(8).max(120),
- onchain_id: z.string().nullable().optional(),
- wallet_address: z.string().min(20).max(80),
-});
-
-// ── Verifiers ────────────────────────────────────────────────────────────────
-
-async function verifyEvm({ chainId, txHash, expectedContract, expectedOwner }) {
- const { CHAIN_BY_ID } = await import('../../_lib/erc8004-chains.js');
- const cfg = CHAIN_BY_ID[chainId];
- if (!cfg?.rpcUrl) throw new Error(`no RPC for chainId ${chainId}`);
-
- const provider = new JsonRpcProvider(cfg.rpcUrl);
- const receipt = await provider.getTransactionReceipt(txHash);
- if (!receipt) {
- const e = new Error('Transaction not found yet — try again in a few seconds.');
- e.code = 'tx_not_found';
- e.status = 422;
- throw e;
- }
- if (receipt.status !== 1) {
- const e = new Error('Transaction failed on-chain.');
- e.code = 'tx_failed';
- e.status = 422;
- throw e;
- }
- if (
- expectedContract &&
- receipt.to &&
- receipt.to.toLowerCase() !== expectedContract.toLowerCase()
- ) {
- const e = new Error('tx target does not match expected registry.');
- e.code = 'tx_wrong_target';
- e.status = 422;
- throw e;
- }
- if (receipt.from.toLowerCase() !== expectedOwner.toLowerCase()) {
- const e = new Error('tx sender does not match wallet_address.');
- e.code = 'tx_wrong_sender';
- e.status = 422;
- throw e;
- }
- return { blockNumber: receipt.blockNumber };
-}
-
-async function verifySolana({ cluster, txSig, expectedAsset, expectedOwner }) {
- const rpc =
- cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
- const conn = new Connection(rpc, 'confirmed');
-
- // Bounded poll — RPC may not have indexed the tx yet, especially on devnet.
- const deadline = Date.now() + 20_000;
- let tx;
- while (Date.now() < deadline) {
- tx = await conn.getParsedTransaction(txSig, {
- maxSupportedTransactionVersion: 0,
- commitment: 'confirmed',
- });
- if (tx) break;
- await new Promise((r) => setTimeout(r, 1500));
- }
- if (!tx) {
- const e = new Error('Transaction not found on Solana RPC.');
- e.code = 'tx_not_found';
- e.status = 422;
- throw e;
- }
- if (tx.meta?.err) {
- const e = new Error('Transaction failed on-chain.');
- e.code = 'tx_failed';
- e.status = 422;
- throw e;
- }
-
- const accountKeys = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
- if (expectedAsset && !accountKeys.includes(expectedAsset)) {
- const e = new Error('Asset pubkey not found in transaction.');
- e.code = 'asset_not_in_tx';
- e.status = 422;
- throw e;
- }
- if (!accountKeys.includes(expectedOwner)) {
- const e = new Error('Wallet address not in transaction signers.');
- e.code = 'wrong_signer';
- e.status = 422;
- throw e;
- }
- return { slot: tx.slot };
-}
-
-// ── Endpoint ─────────────────────────────────────────────────────────────────
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [prep] = await sql`
- select id, payload, metadata_uri, cid
- from agent_registrations_pending
- where user_id = ${user.id}
- and payload->>'prep_id' = ${body.prep_id}
- and expires_at > now()
- limit 1
- `;
- if (!prep) return error(res, 404, 'not_found', 'prep record expired or not found');
-
- const p = prep.payload;
- if (p.wallet_address !== body.wallet_address) {
- return error(res, 400, 'validation_error', 'wallet_address mismatch with prep record');
- }
-
- // Verify on-chain
- try {
- if (p.chain_family === 'evm') {
- const chainId = Number(p.chain.split(':')[1]);
- await verifyEvm({
- chainId,
- txHash: body.tx_hash,
- expectedContract: p.contract_address,
- expectedOwner: body.wallet_address,
- });
- } else if (p.chain_family === 'solana') {
- await verifySolana({
- cluster: p.cluster,
- txSig: body.tx_hash,
- expectedAsset: p.asset_pubkey,
- expectedOwner: body.wallet_address,
- });
- } else {
- return error(res, 400, 'validation_error', `unknown chain family: ${p.chain_family}`);
- }
- } catch (e) {
- return error(res, e.status || 500, e.code || 'verify_failed', e.message);
- }
-
- // Link wallet to user (idempotent — confirm time, since tx is ownership proof).
- await sql`
- insert into user_wallets (user_id, address, chain_type, is_primary)
- values (${user.id}, ${body.wallet_address}, ${p.chain_family === 'solana' ? 'solana' : 'evm'}, false)
- on conflict do nothing
- `;
-
- // Build the unified onchain block.
- const onchain = {
- chain: p.chain,
- family: p.chain_family,
- tx_hash: body.tx_hash,
- onchain_id: body.onchain_id || null,
- contract_or_mint: p.contract_address || p.asset_pubkey || null,
- wallet: body.wallet_address,
- metadata_uri: prep.metadata_uri,
- confirmed_at: new Date().toISOString(),
- ...(p.chain_family === 'solana' ? { cluster: p.cluster } : {}),
- };
-
- // Upsert agent_identities. If a row already exists for (user, agent), we
- // merge the new onchain block in — supports redeploying across chains.
- const [existing] = await sql`
- select id, meta from agent_identities
- where user_id = ${user.id}
- and (id::text = ${p.agent_id} or name = ${p.name})
- and deleted_at is null
- limit 1
- `;
-
- let agent;
- if (existing) {
- const mergedMeta = { ...(existing.meta || {}), onchain };
- [agent] = await sql`
- update agent_identities
- set meta = ${JSON.stringify(mergedMeta)}::jsonb,
- wallet_address = ${body.wallet_address},
- updated_at = now()
- where id = ${existing.id}
- returning id, name, description, wallet_address, meta, created_at
- `;
- } else {
- [agent] = await sql`
- insert into agent_identities
- (user_id, name, description, avatar_id, wallet_address, meta)
- values (
- ${user.id},
- ${p.name},
- ${p.description},
- ${p.avatar_id},
- ${body.wallet_address},
- ${JSON.stringify({ onchain })}::jsonb
- )
- returning id, name, description, wallet_address, meta, created_at
- `;
- }
-
- // Cleanup prep
- await sql`delete from agent_registrations_pending where id = ${prep.id}`;
-
- return json(res, 201, {
- ok: true,
- agent: {
- ...agent,
- onchain,
- home_url: `${env.APP_ORIGIN}/agent/${agent.id}`,
- },
- });
-});
diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].js
new file mode 100644
index 000000000..87fc15e8f
--- /dev/null
+++ b/api/agents/payments/[action].js
@@ -0,0 +1,413 @@
+/**
+ * Agent Payments Dispatcher
+ * -------------------------
+ * POST /api/agents/payments/create-prep
+ * POST /api/agents/payments/create-confirm
+ * POST /api/agents/payments/pay-prep
+ * POST /api/agents/payments/pay-confirm
+ *
+ * Single Vercel function that dispatches on req.query.action (auto-populated
+ * from the [action] filename). Consolidated to reduce function count and
+ * avoid bundling heavy Solana/Anchor SDKs four times.
+ */
+
+import { z } from 'zod';
+import {
+ Connection,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+} from '@solana/web3.js';
+import {
+ PumpAgentOffline,
+ PumpAgent,
+ PUMP_AGENT_PAYMENTS_PROGRAM_ID,
+ getTokenAgentPaymentsPDA,
+} from '@pump-fun/agent-payments-sdk';
+import BN from 'bn.js';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { randomToken } from '../../_lib/crypto.js';
+
+function rpcUrl(cluster) {
+ return cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'create-prep':
+ return handleCreatePrep(req, res);
+ case 'create-confirm':
+ return handleCreateConfirm(req, res);
+ case 'pay-prep':
+ return handlePayPrep(req, res);
+ case 'pay-confirm':
+ return handlePayConfirm(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown payments action');
+ }
+});
+
+// ── create-prep ──────────────────────────────────────────────────────────────
+
+const createPrepSchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ wallet_address: z.string().min(32).max(44),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleCreatePrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(createPrepSchema, await readJson(req));
+
+ const [agent] = await sql`
+ select id, user_id, meta
+ from agent_identities
+ where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const tokenMint = agent.meta?.token?.mint;
+ if (!tokenMint) {
+ return error(res, 409, 'precondition_failed', 'agent has no launched token yet');
+ }
+ if (agent.meta?.payments?.configured) {
+ return error(res, 409, 'conflict', 'payments already configured for this agent');
+ }
+ if (agent.meta?.onchain?.wallet !== body.wallet_address) {
+ return error(res, 403, 'forbidden', 'wallet does not match agent owner');
+ }
+
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const mint = new PublicKey(tokenMint);
+ const owner = new PublicKey(body.wallet_address);
+ const offline = PumpAgentOffline.load(mint, conn);
+
+ // `create` registers the TokenAgentPayments PDA. Authority defaults to the
+ // caller (owner). Buyback bps + sharing config can be configured later via
+ // updateBuybackBps; for the initial config we accept defaults so a single
+ // click enables payments.
+ const createIx = await offline.create({
+ user: owner,
+ authority: owner,
+ });
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({ feePayer: owner, blockhash, lastValidBlockHeight }).add(
+ ComputeBudgetProgram.setComputeUnitLimit({
+ units: PumpAgentOffline.DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS,
+ }),
+ ComputeBudgetProgram.setComputeUnitPrice({
+ microLamports: PumpAgentOffline.DEFAULT_PRIORITY_FEE_MICRO_LAMPORTS,
+ }),
+ createIx,
+ );
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into payment_configs_pending
+ (id, user_id, agent_id, cluster, mint, payload, expires_at)
+ values (
+ ${prepId},
+ ${user.id},
+ ${agent.id},
+ ${body.cluster},
+ ${tokenMint},
+ ${JSON.stringify({
+ wallet_address: body.wallet_address,
+ program_id: PUMP_AGENT_PAYMENTS_PROGRAM_ID.toString(),
+ })}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (id) do nothing
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: tokenMint,
+ tx_base64: txBase64,
+ cluster: body.cluster,
+ expires_at: expiresAt.toISOString(),
+ });
+}
+
+// ── create-confirm ───────────────────────────────────────────────────────────
+
+const createConfirmSchema = z.object({
+ prep_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+async function handleCreateConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(createConfirmSchema, await readJson(req));
+
+ const [prep] = await sql`
+ select id, agent_id, mint, cluster, payload
+ from payment_configs_pending
+ where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
+ limit 1
+ `;
+ if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
+ if (prep.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch with prep');
+ }
+
+ const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
+ const [pda] = getTokenAgentPaymentsPDA(new PublicKey(prep.mint));
+ if (!accounts.includes(pda.toString())) {
+ return error(res, 422, 'pda_not_in_tx', 'expected agent payments PDA not in tx');
+ }
+ if (!accounts.includes(body.wallet_address)) {
+ return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
+ }
+
+ const [agent] = await sql`
+ select id, meta from agent_identities
+ where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const payments = {
+ configured: true,
+ provider: 'pumpfun',
+ mint: prep.mint,
+ token_agent_pda: pda.toString(),
+ receiver: body.wallet_address,
+ cluster: prep.cluster,
+ tx_signature: body.tx_signature,
+ configured_at: new Date().toISOString(),
+ accepted_tokens: [], // reserved — populate via updateBuybackBps later
+ };
+
+ const mergedMeta = { ...(agent.meta || {}), payments };
+ const [updated] = await sql`
+ update agent_identities
+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ updated_at = now()
+ where id = ${agent.id}
+ returning id, name, meta
+ `;
+ await sql`delete from payment_configs_pending where id = ${prep.id}`;
+
+ return json(res, 201, { ok: true, agent: updated, payments });
+}
+
+// ── pay-prep ─────────────────────────────────────────────────────────────────
+
+const payPrepSchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ currency_mint: z.string().min(32).max(44),
+ amount: z.string().regex(/^\d+$/),
+ memo: z.string().regex(/^\d+$/).optional(),
+ wallet_address: z.string().min(32).max(44),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handlePayPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(payPrepSchema, await readJson(req));
+
+ const [agent] = await sql`
+ select id, name, meta from agent_identities
+ where id = ${body.agent_id} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (!agent.meta?.payments?.configured) {
+ return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
+ }
+ const tokenMint = agent.meta.payments.mint;
+
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const pumpAgent = new PumpAgent(
+ new PublicKey(tokenMint),
+ body.cluster === 'devnet' ? 'devnet' : 'mainnet',
+ conn,
+ );
+
+ const memo = body.memo || String(Math.floor(Date.now() / 1000));
+ const startTime = Math.floor(Date.now() / 1000);
+ const endTime = startTime + 60 * 60 * 24; // 24h validity window for the invoice
+
+ const ixs = await pumpAgent.buildAcceptPaymentInstructions({
+ user: new PublicKey(body.wallet_address),
+ currencyMint: new PublicKey(body.currency_mint),
+ amount: new BN(body.amount),
+ memo: new BN(memo),
+ startTime: new BN(startTime),
+ endTime: new BN(endTime),
+ });
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({
+ feePayer: new PublicKey(body.wallet_address),
+ blockhash,
+ lastValidBlockHeight,
+ }).add(
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1000 }),
+ ...ixs,
+ );
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ const intentId = await randomToken(24);
+ const expiresAt = new Date(endTime * 1000);
+
+ await sql`
+ insert into agent_payment_intents
+ (id, payer_user_id, agent_id, currency_mint, amount, memo, start_time, end_time,
+ status, cluster, payload, expires_at)
+ values (
+ ${intentId}, ${user.id}, ${agent.id}, ${body.currency_mint}, ${body.amount},
+ ${memo}, ${new Date(startTime * 1000)}, ${new Date(endTime * 1000)},
+ 'pending', ${body.cluster},
+ ${JSON.stringify({
+ wallet_address: body.wallet_address,
+ token_mint: tokenMint,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ `;
+
+ return json(res, 201, {
+ intent_id: intentId,
+ tx_base64: txBase64,
+ memo,
+ start_time: startTime,
+ end_time: endTime,
+ expires_at: expiresAt.toISOString(),
+ });
+}
+
+// ── pay-confirm ──────────────────────────────────────────────────────────────
+
+const payConfirmSchema = z.object({
+ intent_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+async function handlePayConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(payConfirmSchema, await readJson(req));
+
+ const [intent] = await sql`
+ select id, payer_user_id, agent_id, currency_mint, amount, memo,
+ extract(epoch from start_time)::bigint as start_time,
+ extract(epoch from end_time)::bigint as end_time,
+ status, cluster, payload
+ from agent_payment_intents
+ where id = ${body.intent_id} and payer_user_id = ${user.id} limit 1
+ `;
+ if (!intent) return error(res, 404, 'not_found', 'intent not found');
+ if (intent.status === 'paid') return json(res, 200, { ok: true, intent_id: intent.id, status: 'paid' });
+ if (intent.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch');
+ }
+
+ const conn = new Connection(rpcUrl(intent.cluster), 'confirmed');
+ const pumpAgent = new PumpAgent(
+ new PublicKey(intent.payload.token_mint),
+ intent.cluster === 'devnet' ? 'devnet' : 'mainnet',
+ conn,
+ );
+
+ // Wait briefly for the tx to land before SDK lookup.
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const ok = await pumpAgent.validateInvoicePayment({
+ user: new PublicKey(body.wallet_address),
+ currencyMint: new PublicKey(intent.currency_mint),
+ amount: Number(intent.amount),
+ memo: Number(intent.memo),
+ startTime: Number(intent.start_time),
+ endTime: Number(intent.end_time),
+ });
+ if (!ok) {
+ return error(res, 422, 'invoice_not_found', 'on-chain invoice not found for this intent');
+ }
+
+ const [updated] = await sql`
+ update agent_payment_intents
+ set status = 'paid', tx_signature = ${body.tx_signature}, paid_at = now()
+ where id = ${intent.id}
+ returning id, agent_id, amount, currency_mint, paid_at
+ `;
+
+ return json(res, 200, { ok: true, intent: updated });
+}
diff --git a/api/agents/payments/create-confirm.js b/api/agents/payments/create-confirm.js
deleted file mode 100644
index c5c028b17..000000000
--- a/api/agents/payments/create-confirm.js
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * POST /api/agents/payments/create-confirm
- *
- * Verify the PumpAgentPayments create tx landed and write meta.payments on
- * the agent so the UI can flip into "Pay agent" mode.
- */
-
-import { z } from 'zod';
-import { Connection, PublicKey } from '@solana/web3.js';
-import { getTokenAgentPaymentsPDA } from '@pump-fun/agent-payments-sdk';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-
-const bodySchema = z.object({
- prep_id: z.string().min(8).max(80),
- tx_signature: z.string().min(40).max(120),
- wallet_address: z.string().min(32).max(44),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [prep] = await sql`
- select id, agent_id, mint, cluster, payload
- from payment_configs_pending
- where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
- limit 1
- `;
- if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
- if (prep.payload?.wallet_address !== body.wallet_address) {
- return error(res, 400, 'validation_error', 'wallet mismatch with prep');
- }
-
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
- const deadline = Date.now() + 30_000;
- let tx;
- while (Date.now() < deadline) {
- tx = await conn.getParsedTransaction(body.tx_signature, {
- maxSupportedTransactionVersion: 0,
- commitment: 'confirmed',
- });
- if (tx) break;
- await new Promise((r) => setTimeout(r, 1500));
- }
- if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
- if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
-
- const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
- const [pda] = getTokenAgentPaymentsPDA(new PublicKey(prep.mint));
- if (!accounts.includes(pda.toString())) {
- return error(res, 422, 'pda_not_in_tx', 'expected agent payments PDA not in tx');
- }
- if (!accounts.includes(body.wallet_address)) {
- return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
- }
-
- const [agent] = await sql`
- select id, meta from agent_identities
- where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
- limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
-
- const payments = {
- configured: true,
- provider: 'pumpfun',
- mint: prep.mint,
- token_agent_pda: pda.toString(),
- receiver: body.wallet_address,
- cluster: prep.cluster,
- tx_signature: body.tx_signature,
- configured_at: new Date().toISOString(),
- accepted_tokens: [], // reserved — populate via updateBuybackBps later
- };
-
- const mergedMeta = { ...(agent.meta || {}), payments };
- const [updated] = await sql`
- update agent_identities
- set meta = ${JSON.stringify(mergedMeta)}::jsonb,
- updated_at = now()
- where id = ${agent.id}
- returning id, name, meta
- `;
- await sql`delete from payment_configs_pending where id = ${prep.id}`;
-
- return json(res, 201, { ok: true, agent: updated, payments });
-});
diff --git a/api/agents/payments/create-prep.js b/api/agents/payments/create-prep.js
deleted file mode 100644
index 3ceb5d17c..000000000
--- a/api/agents/payments/create-prep.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * POST /api/agents/payments/create-prep
- *
- * Build the unsigned PumpAgentPayments `create` transaction that registers
- * an agent's launched token to accept payments. Owner-only. Pre-conditions:
- * • Agent must already have meta.token.mint set (Pump.fun token launched).
- * • Caller must own the agent and the wallet they're using.
- *
- * Returns a base64 partially-built tx the user signs in their wallet. The
- * confirm endpoint persists `meta.payments` once the tx lands on-chain.
- */
-
-import { z } from 'zod';
-import {
- Connection,
- PublicKey,
- Transaction,
- ComputeBudgetProgram,
-} from '@solana/web3.js';
-import { PumpAgentOffline, PUMP_AGENT_PAYMENTS_PROGRAM_ID } from '@pump-fun/agent-payments-sdk';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { randomToken } from '../../_lib/crypto.js';
-
-const bodySchema = z.object({
- agent_id: z.string().min(1).max(80),
- wallet_address: z.string().min(32).max(44),
- cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [agent] = await sql`
- select id, user_id, meta
- from agent_identities
- where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null
- limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
-
- const tokenMint = agent.meta?.token?.mint;
- if (!tokenMint) {
- return error(res, 409, 'precondition_failed', 'agent has no launched token yet');
- }
- if (agent.meta?.payments?.configured) {
- return error(res, 409, 'conflict', 'payments already configured for this agent');
- }
- if (agent.meta?.onchain?.wallet !== body.wallet_address) {
- return error(res, 403, 'forbidden', 'wallet does not match agent owner');
- }
-
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
- const mint = new PublicKey(tokenMint);
- const owner = new PublicKey(body.wallet_address);
- const offline = PumpAgentOffline.load(mint, conn);
-
- // `create` registers the TokenAgentPayments PDA. Authority defaults to the
- // caller (owner). Buyback bps + sharing config can be configured later via
- // updateBuybackBps; for the initial config we accept defaults so a single
- // click enables payments.
- const createIx = await offline.create({
- user: owner,
- authority: owner,
- });
-
- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
- const tx = new Transaction({ feePayer: owner, blockhash, lastValidBlockHeight }).add(
- ComputeBudgetProgram.setComputeUnitLimit({
- units: PumpAgentOffline.DEFAULT_COMPUTE_UNIT_LIMIT_FOR_AGENT_PAYMENTS,
- }),
- ComputeBudgetProgram.setComputeUnitPrice({
- microLamports: PumpAgentOffline.DEFAULT_PRIORITY_FEE_MICRO_LAMPORTS,
- }),
- createIx,
- );
-
- const txBase64 = tx
- .serialize({ requireAllSignatures: false, verifySignatures: false })
- .toString('base64');
-
- const prepId = await randomToken(24);
- const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
-
- await sql`
- insert into payment_configs_pending
- (id, user_id, agent_id, cluster, mint, payload, expires_at)
- values (
- ${prepId},
- ${user.id},
- ${agent.id},
- ${body.cluster},
- ${tokenMint},
- ${JSON.stringify({
- wallet_address: body.wallet_address,
- program_id: PUMP_AGENT_PAYMENTS_PROGRAM_ID.toString(),
- })}::jsonb,
- ${expiresAt}
- )
- on conflict (id) do nothing
- `;
-
- return json(res, 201, {
- prep_id: prepId,
- mint: tokenMint,
- tx_base64: txBase64,
- cluster: body.cluster,
- expires_at: expiresAt.toISOString(),
- });
-});
diff --git a/api/agents/payments/pay-confirm.js b/api/agents/payments/pay-confirm.js
deleted file mode 100644
index a81fa1e59..000000000
--- a/api/agents/payments/pay-confirm.js
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * POST /api/agents/payments/pay-confirm
- *
- * Verify the user paid via PumpAgentPayments. Marks the intent as paid and
- * surfaces a credit row the runtime can consume.
- *
- * The PumpAgent SDK exposes `validateInvoicePayment` which checks the on-chain
- * receipt by event log + invoice PDA. We call it for canonical verification.
- */
-
-import { z } from 'zod';
-import { Connection, PublicKey } from '@solana/web3.js';
-import { PumpAgent } from '@pump-fun/agent-payments-sdk';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-
-const bodySchema = z.object({
- intent_id: z.string().min(8).max(80),
- tx_signature: z.string().min(40).max(120),
- wallet_address: z.string().min(32).max(44),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [intent] = await sql`
- select id, payer_user_id, agent_id, currency_mint, amount, memo,
- extract(epoch from start_time)::bigint as start_time,
- extract(epoch from end_time)::bigint as end_time,
- status, cluster, payload
- from agent_payment_intents
- where id = ${body.intent_id} and payer_user_id = ${user.id} limit 1
- `;
- if (!intent) return error(res, 404, 'not_found', 'intent not found');
- if (intent.status === 'paid') return json(res, 200, { ok: true, intent_id: intent.id, status: 'paid' });
- if (intent.payload?.wallet_address !== body.wallet_address) {
- return error(res, 400, 'validation_error', 'wallet mismatch');
- }
-
- const conn = new Connection(rpcUrl(intent.cluster), 'confirmed');
- const pumpAgent = new PumpAgent(
- new PublicKey(intent.payload.token_mint),
- intent.cluster === 'devnet' ? 'devnet' : 'mainnet',
- conn,
- );
-
- // Wait briefly for the tx to land before SDK lookup.
- const deadline = Date.now() + 30_000;
- let tx;
- while (Date.now() < deadline) {
- tx = await conn.getParsedTransaction(body.tx_signature, {
- maxSupportedTransactionVersion: 0,
- commitment: 'confirmed',
- });
- if (tx) break;
- await new Promise((r) => setTimeout(r, 1500));
- }
- if (!tx) return error(res, 422, 'tx_not_found', 'tx not found');
- if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
-
- const ok = await pumpAgent.validateInvoicePayment({
- user: new PublicKey(body.wallet_address),
- currencyMint: new PublicKey(intent.currency_mint),
- amount: Number(intent.amount),
- memo: Number(intent.memo),
- startTime: Number(intent.start_time),
- endTime: Number(intent.end_time),
- });
- if (!ok) {
- return error(res, 422, 'invoice_not_found', 'on-chain invoice not found for this intent');
- }
-
- const [updated] = await sql`
- update agent_payment_intents
- set status = 'paid', tx_signature = ${body.tx_signature}, paid_at = now()
- where id = ${intent.id}
- returning id, agent_id, amount, currency_mint, paid_at
- `;
-
- return json(res, 200, { ok: true, intent: updated });
-});
diff --git a/api/agents/payments/pay-prep.js b/api/agents/payments/pay-prep.js
deleted file mode 100644
index 592905500..000000000
--- a/api/agents/payments/pay-prep.js
+++ /dev/null
@@ -1,131 +0,0 @@
-/**
- * POST /api/agents/payments/pay-prep
- *
- * Build an unsigned `agent_accept_payment` transaction for any signed-in user
- * to pay an agent. Caller signs with their own Solana wallet.
- *
- * Body:
- * { agent_id, currency_mint, amount, memo?, wallet_address, cluster? }
- *
- * - amount raw token units as a numeric string (caller does decimals)
- * - currency_mint mint of the token used to pay (e.g. USDC)
- * - memo optional u64-castable string (Pump.fun uses memo as the
- * invoice id seed; we synthesize one if not provided)
- */
-
-import { z } from 'zod';
-import {
- Connection,
- PublicKey,
- Transaction,
- ComputeBudgetProgram,
-} from '@solana/web3.js';
-import { PumpAgent } from '@pump-fun/agent-payments-sdk';
-import BN from 'bn.js';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { randomToken } from '../../_lib/crypto.js';
-
-const bodySchema = z.object({
- agent_id: z.string().min(1).max(80),
- currency_mint: z.string().min(32).max(44),
- amount: z.string().regex(/^\d+$/),
- memo: z.string().regex(/^\d+$/).optional(),
- wallet_address: z.string().min(32).max(44),
- cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [agent] = await sql`
- select id, name, meta from agent_identities
- where id = ${body.agent_id} and deleted_at is null limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (!agent.meta?.payments?.configured) {
- return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
- }
- const tokenMint = agent.meta.payments.mint;
-
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
- const pumpAgent = new PumpAgent(
- new PublicKey(tokenMint),
- body.cluster === 'devnet' ? 'devnet' : 'mainnet',
- conn,
- );
-
- const memo = body.memo || String(Math.floor(Date.now() / 1000));
- const startTime = Math.floor(Date.now() / 1000);
- const endTime = startTime + 60 * 60 * 24; // 24h validity window for the invoice
-
- const ixs = await pumpAgent.buildAcceptPaymentInstructions({
- user: new PublicKey(body.wallet_address),
- currencyMint: new PublicKey(body.currency_mint),
- amount: new BN(body.amount),
- memo: new BN(memo),
- startTime: new BN(startTime),
- endTime: new BN(endTime),
- });
-
- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
- const tx = new Transaction({
- feePayer: new PublicKey(body.wallet_address),
- blockhash,
- lastValidBlockHeight,
- }).add(
- ComputeBudgetProgram.setComputeUnitLimit({ units: 200_000 }),
- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 1000 }),
- ...ixs,
- );
-
- const txBase64 = tx
- .serialize({ requireAllSignatures: false, verifySignatures: false })
- .toString('base64');
-
- const intentId = await randomToken(24);
- const expiresAt = new Date(endTime * 1000);
-
- await sql`
- insert into agent_payment_intents
- (id, payer_user_id, agent_id, currency_mint, amount, memo, start_time, end_time,
- status, cluster, payload, expires_at)
- values (
- ${intentId}, ${user.id}, ${agent.id}, ${body.currency_mint}, ${body.amount},
- ${memo}, ${new Date(startTime * 1000)}, ${new Date(endTime * 1000)},
- 'pending', ${body.cluster},
- ${JSON.stringify({
- wallet_address: body.wallet_address,
- token_mint: tokenMint,
- })}::jsonb,
- ${expiresAt}
- )
- `;
-
- return json(res, 201, {
- intent_id: intentId,
- tx_base64: txBase64,
- memo,
- start_time: startTime,
- end_time: endTime,
- expires_at: expiresAt.toISOString(),
- });
-});
diff --git a/api/agents/pumpfun/[action].js b/api/agents/pumpfun/[action].js
new file mode 100644
index 000000000..75b16261d
--- /dev/null
+++ b/api/agents/pumpfun/[action].js
@@ -0,0 +1,1082 @@
+/**
+ * Consolidated pumpfun action dispatcher.
+ *
+ * Routes (via vercel.json rewrites):
+ * POST /api/agents/:id/pumpfun/launch — create a pump.fun token from this agent
+ * POST /api/agents/:id/pumpfun/buy — bonding-curve buy
+ * POST /api/agents/:id/pumpfun/sell — bonding-curve sell
+ * GET /api/agents/:id/pumpfun/portfolio — aggregated positions + live PnL
+ * POST /api/agents/:id/pumpfun/swap — AMM swap (graduated tokens)
+ * POST /api/agents/:id/pumpfun/pay — @pump-fun/agent-payments-sdk surface
+ *
+ * One bundle so Vercel doesn't re-bundle @solana/web3.js + @pump-fun/* per file.
+ */
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
+import { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';
+import { grindMintKeypair } from '../../_lib/pump-vanity.js';
+import { sql } from '../../_lib/db.js';
+import { Keypair, PublicKey, Transaction } from '@solana/web3.js';
+import { z } from 'zod';
+
+const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+function extractAgentId(req) {
+ // Original URL pattern: /api/agents/:id/pumpfun/:action — id at parts[2].
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ if (parts[1] === 'agents' && parts[3] === 'pumpfun') return parts[2];
+ // Fallback: query string (in case vercel.json passes it that way).
+ return req.query?.id || null;
+}
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ const id = extractAgentId(req);
+
+ if (!id) {
+ if (cors(req, res)) return;
+ return error(res, 400, 'bad_request', 'missing agent id');
+ }
+
+ if (action === 'buy') return handleBuy(req, res, id);
+ if (action === 'launch') return handleLaunch(req, res, id);
+ if (action === 'pay') return handlePay(req, res, id);
+ if (action === 'portfolio') return handlePortfolio(req, res, id);
+ if (action === 'sell') return handleSell(req, res, id);
+ if (action === 'swap') return handleSwap(req, res, id);
+
+ if (cors(req, res)) return;
+ return error(res, 404, 'not_found', 'unknown pumpfun action');
+});
+
+// ── buy ────────────────────────────────────────────────────────────────────
+
+const buyBodySchema = z.object({
+ mint: z.string().min(32).max(64),
+ solAmount: z.number().positive().max(1000),
+ slippageBps: z.number().int().min(0).max(10_000).default(500),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleBuy(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = buyBodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair, meta } = loaded;
+
+ const blocked = await checkBuyAllowed({
+ agentId: id,
+ meta,
+ mint: body.mint,
+ solAmount: body.solAmount,
+ });
+ if (blocked) return error(res, blocked.status, blocked.code, blocked.msg);
+
+ const [{ PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount }, BN, splToken] =
+ await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('bn.js').then((m) => m.default || m),
+ import('@solana/spl-token'),
+ ]);
+
+ const conn = solanaConnection(body.network);
+ const online = new OnlinePumpSdk(conn);
+ const sdk = new PumpSdk();
+ const mint = new PublicKey(body.mint);
+ const solLamports = new BN(Math.floor(body.solAmount * 1e9));
+
+ let instructions;
+ try {
+ const [global, state] = await Promise.all([
+ online.fetchGlobal(),
+ online.fetchBuyState(mint, keypair.publicKey),
+ ]);
+ const expected = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: state.bondingCurve.tokenTotalSupply,
+ bondingCurve: state.bondingCurve,
+ amount: solLamports,
+ });
+ instructions = await sdk.buyInstructions({
+ global,
+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,
+ bondingCurve: state.bondingCurve,
+ associatedUserAccountInfo: state.associatedUserAccountInfo,
+ mint,
+ user: keypair.publicKey,
+ amount: expected,
+ solAmount: solLamports,
+ slippage: body.slippageBps / 10_000,
+ tokenProgram: splToken.TOKEN_PROGRAM_ID,
+ });
+ } catch (err) {
+ console.error('[pumpfun/buy] build failed', err);
+ return error(res, 422, 'build_failed', err.message || 'could not build buy ix');
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/buy] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${'pumpfun.buy'},
+ ${JSON.stringify({
+ mint: body.mint,
+ solAmount: body.solAmount,
+ slippageBps: body.slippageBps,
+ signature,
+ network: body.network,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/buy] log failed', e));
+
+ // Mirror into pump_agent_trades for cross-feature analytics (reputation,
+ // admin health, strategy backtests). Best-effort — agent may not have a
+ // pump_agent_mints row yet if the mint was launched outside three.ws.
+ try {
+ const [m] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (m) {
+ const lamports = BigInt(Math.floor(body.solAmount * 1_000_000_000));
+ await sql`
+ INSERT INTO pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
+ VALUES
+ (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'buy',
+ 'bonding_curve', ${lamports.toString()}, ${body.slippageBps || null},
+ ${signature}, ${body.network})
+ ON CONFLICT (tx_signature, network) DO NOTHING
+ `;
+ }
+ } catch (e) {
+ console.error('[pumpfun/buy] trade index failed', e);
+ }
+
+ return json(res, 200, {
+ data: {
+ signature,
+ mint: body.mint,
+ solAmount: body.solAmount,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ },
+ });
+}
+
+// ── launch ─────────────────────────────────────────────────────────────────
+
+const launchBodySchema = z.object({
+ name: z.string().trim().min(1).max(32),
+ symbol: z.string().trim().min(1).max(10),
+ uri: z.string().url().max(2048),
+ solAmount: z.number().nonnegative().max(1000).optional(),
+ tokenAmount: z.number().nonnegative().optional(),
+ vanityPrefix: z.string().min(1).max(6).optional(),
+ vanitySuffix: z.string().min(1).max(6).optional(),
+ vanityIgnoreCase: z.boolean().optional(),
+ mintSecretKey: z.array(z.number().int().min(0).max(255)).length(64).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleLaunch(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = launchBodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const { PumpSdk, OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
+ const BN = (await import('bn.js')).default;
+ const conn = solanaConnection(body.network);
+ const online = new OnlinePumpSdk(conn);
+ const sdk = new PumpSdk();
+
+ let mint;
+ let vanityIterations = 1;
+ let vanityDurationMs = 0;
+ if (body.mintSecretKey) {
+ try {
+ mint = Keypair.fromSecretKey(Uint8Array.from(body.mintSecretKey));
+ } catch (e) {
+ return error(res, 400, 'validation_error', 'mintSecretKey did not parse as a valid Solana keypair');
+ }
+ const addr = mint.publicKey.toBase58();
+ const ic = !!body.vanityIgnoreCase;
+ const cmp = (a, b) => (ic ? a.toLowerCase() === b.toLowerCase() : a === b);
+ if (body.vanityPrefix && !cmp(addr.slice(0, body.vanityPrefix.length), body.vanityPrefix)) {
+ return error(res, 400, 'validation_error', 'mintSecretKey does not match vanityPrefix');
+ }
+ if (body.vanitySuffix && !cmp(addr.slice(-body.vanitySuffix.length), body.vanitySuffix)) {
+ return error(res, 400, 'validation_error', 'mintSecretKey does not match vanitySuffix');
+ }
+ } else {
+ try {
+ const ground = await grindMintKeypair({
+ prefix: body.vanityPrefix,
+ suffix: body.vanitySuffix,
+ ignoreCase: body.vanityIgnoreCase,
+ });
+ mint = ground.keypair;
+ vanityIterations = ground.iterations;
+ vanityDurationMs = ground.durationMs;
+ } catch (err) {
+ return error(res, err.status || 500, err.code || 'internal', err.message);
+ }
+ }
+ const solLamports = new BN(Math.floor((body.solAmount || 0) * 1e9));
+ const tokenAmount = new BN(body.tokenAmount || 0);
+
+ let instructions;
+ if (solLamports.gtn(0)) {
+ const global = await online.fetchGlobal();
+ instructions = await sdk.createV2AndBuyInstructions({
+ global,
+ mint: mint.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator: keypair.publicKey,
+ user: keypair.publicKey,
+ amount: tokenAmount,
+ solAmount: solLamports,
+ mayhemMode: false,
+ });
+ } else {
+ const ix = await sdk.createV2Instruction({
+ mint: mint.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator: keypair.publicKey,
+ user: keypair.publicKey,
+ mayhemMode: false,
+ });
+ instructions = [ix];
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair, mint);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/launch] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ const mintAddr = mint.publicKey.toBase58();
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${'pumpfun.launch'},
+ ${JSON.stringify({
+ mint: mintAddr,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ signature,
+ network: body.network,
+ solAmount: body.solAmount || 0,
+ vanity_prefix: body.vanityPrefix || null,
+ vanity_suffix: body.vanitySuffix || null,
+ vanity_ignore_case: body.vanityIgnoreCase || false,
+ vanity_iterations: vanityIterations,
+ vanity_duration_ms: vanityDurationMs,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/launch] log failed', e));
+
+ // Register the mint in the indexer table so pump-agent-stats cron picks it up.
+ await sql`
+ INSERT INTO pump_agent_mints
+ (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority)
+ VALUES
+ (${id}, ${auth.userId}, ${body.network}, ${mintAddr},
+ ${body.name}, ${body.symbol}, ${body.uri}, ${keypair.publicKey.toBase58()})
+ ON CONFLICT (mint, network) DO NOTHING
+ `.catch((e) => console.error('[pumpfun/launch] mint index failed', e));
+
+ return json(res, 201, {
+ data: {
+ mint: mint.publicKey.toBase58(),
+ signature,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ pumpfun_url: `https://pump.fun/${mint.publicKey.toBase58()}`,
+ vanity_prefix: body.vanityPrefix || null,
+ vanity_suffix: body.vanitySuffix || null,
+ vanity_iterations: vanityIterations,
+ vanity_duration_ms: vanityDurationMs,
+ },
+ });
+}
+
+// ── pay ────────────────────────────────────────────────────────────────────
+
+const payBodySchema = z.object({
+ action: z.enum([
+ 'create',
+ 'accept',
+ 'withdraw',
+ 'distribute',
+ 'extend_account',
+ 'update_authority',
+ 'update_buyback',
+ 'balances',
+ ]),
+ tokenMint: z.string().min(32).max(64),
+ currencyMint: z.string().min(32).max(64).default(NATIVE_SOL_MINT),
+ amount: z.string().regex(/^\d+$/).optional(),
+ memo: z.string().regex(/^\d+$/).optional(),
+ startTime: z.number().int().nonnegative().optional(),
+ endTime: z.number().int().nonnegative().optional(),
+ receiverAta: z.string().min(32).max(64).optional(),
+ userTokenAccount: z.string().min(32).max(64).optional(),
+ account: z.string().min(32).max(64).optional(),
+ newAuthority: z.string().min(32).max(64).optional(),
+ buybackBps: z.number().int().min(0).max(10_000).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+function payNeed(body, ...fields) {
+ const missing = fields.filter((f) => body[f] == null || body[f] === '');
+ if (missing.length)
+ return { status: 400, code: 'validation_error', msg: `missing: ${missing.join(', ')}` };
+ return null;
+}
+
+function explorerUrl(sig, network) {
+ return `https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}`;
+}
+
+async function handlePay(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = payBodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId, {
+ reason: `pumpfun.pay.${body.action}`,
+ meta: { tokenMint: body.tokenMint, network: body.network },
+ });
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const conn = solanaConnection(body.network);
+ const tokenMint = new PublicKey(body.tokenMint);
+ const currencyMint = new PublicKey(body.currencyMint);
+ const { PumpAgent } = await import('@pump-fun/agent-payments-sdk');
+ const agent = new PumpAgent(tokenMint, body.network, conn);
+
+ // ── Read-only ──────────────────────────────────────────────────────────
+ if (body.action === 'balances') {
+ try {
+ const balances = await agent.getBalances(currencyMint);
+ return json(res, 200, {
+ data: {
+ tokenMint: body.tokenMint,
+ currencyMint: body.currencyMint,
+ balances: {
+ paymentVault: {
+ address: balances.paymentVault.address.toBase58(),
+ balance: balances.paymentVault.balance.toString(),
+ },
+ buybackVault: {
+ address: balances.buybackVault.address.toBase58(),
+ balance: balances.buybackVault.balance.toString(),
+ },
+ withdrawVault: {
+ address: balances.withdrawVault.address.toBase58(),
+ balance: balances.withdrawVault.balance.toString(),
+ },
+ },
+ },
+ });
+ } catch (err) {
+ console.error('[pumpfun/pay] balances failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'balance fetch failed');
+ }
+ }
+
+ // ── Build instructions per action ──────────────────────────────────────
+ let instructions;
+ let extra = {};
+ try {
+ switch (body.action) {
+ case 'create': {
+ const miss = payNeed(body, 'buybackBps');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.create({
+ authority: keypair.publicKey,
+ mint: tokenMint,
+ agentAuthority: keypair.publicKey,
+ buybackBps: body.buybackBps,
+ });
+ instructions = [ix];
+ extra = { buybackBps: body.buybackBps };
+ break;
+ }
+ case 'accept': {
+ const miss = payNeed(body, 'amount', 'memo', 'startTime', 'endTime');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ instructions = await agent.buildAcceptPaymentInstructions({
+ user: keypair.publicKey,
+ currencyMint,
+ amount: body.amount,
+ memo: body.memo,
+ startTime: body.startTime,
+ endTime: body.endTime,
+ });
+ extra = {
+ amount: body.amount,
+ memo: body.memo,
+ startTime: body.startTime,
+ endTime: body.endTime,
+ };
+ break;
+ }
+ case 'withdraw': {
+ const miss = payNeed(body, 'receiverAta');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.withdraw({
+ authority: keypair.publicKey,
+ currencyMint,
+ receiverAta: new PublicKey(body.receiverAta),
+ });
+ instructions = [ix];
+ extra = { receiverAta: body.receiverAta };
+ break;
+ }
+ case 'distribute': {
+ instructions = await agent.distributePayments({
+ user: keypair.publicKey,
+ currencyMint,
+ });
+ break;
+ }
+ case 'extend_account': {
+ const miss = payNeed(body, 'account');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.extendAccount({
+ account: new PublicKey(body.account),
+ user: keypair.publicKey,
+ });
+ instructions = [ix];
+ extra = { account: body.account };
+ break;
+ }
+ case 'update_authority': {
+ const miss = payNeed(body, 'newAuthority');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.updateAuthority({
+ authority: keypair.publicKey,
+ newAuthority: new PublicKey(body.newAuthority),
+ });
+ instructions = [ix];
+ extra = { newAuthority: body.newAuthority };
+ break;
+ }
+ case 'update_buyback': {
+ const miss = payNeed(body, 'buybackBps');
+ if (miss) return error(res, miss.status, miss.code, miss.msg);
+ const ix = await agent.updateBuybackBps({
+ authority: keypair.publicKey,
+ buybackBps: body.buybackBps,
+ });
+ instructions = [ix];
+ extra = { buybackBps: body.buybackBps };
+ break;
+ }
+ }
+ } catch (err) {
+ console.error(`[pumpfun/pay] ${body.action} build failed`, err);
+ return error(res, 422, 'build_failed', err.message || 'could not build instruction');
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ 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');
+ }
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${`pumpfun.pay.${body.action}`},
+ ${JSON.stringify({
+ tokenMint: body.tokenMint,
+ currencyMint: body.currencyMint,
+ signature,
+ network: body.network,
+ ...extra,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/pay] log failed', e));
+
+ return json(res, 200, {
+ data: {
+ signature,
+ action: body.action,
+ tokenMint: body.tokenMint,
+ currencyMint: body.currencyMint,
+ explorer: explorerUrl(signature, body.network),
+ ...extra,
+ },
+ });
+}
+
+// ── portfolio ──────────────────────────────────────────────────────────────
+
+function lamportsToSol(bnLike) {
+ if (!bnLike) return 0;
+ const s = typeof bnLike === 'string' ? bnLike : bnLike.toString();
+ return Number(s) / 1e9;
+}
+
+async function handlePortfolio(req, res, id) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair, meta } = loaded;
+
+ const rows = await sql`
+ SELECT type, payload
+ FROM agent_actions
+ WHERE agent_id = ${id}
+ AND type IN ('pumpfun.buy', 'pumpfun.sell', 'pumpfun.launch',
+ 'pumpfun.swap.buy', 'pumpfun.swap.sell')
+ AND (payload->>'network') = ${network}
+ `;
+
+ // Aggregate per mint
+ const byMint = new Map();
+ for (const row of rows) {
+ const p = row.payload || {};
+ const mint = p.mint;
+ if (!mint) continue;
+ const e = byMint.get(mint) || { mint, sol_in: 0, sol_out: 0 };
+ if (row.type === 'pumpfun.buy' || row.type === 'pumpfun.launch' || row.type === 'pumpfun.swap.buy') {
+ e.sol_in += Number(p.solAmount) || 0;
+ } else if (row.type === 'pumpfun.sell' || row.type === 'pumpfun.swap.sell') {
+ e.sol_out += lamportsToSol(p.expectedSolLamports);
+ }
+ byMint.set(mint, e);
+ }
+
+ if (byMint.size === 0) {
+ return json(res, 200, {
+ data: {
+ wallet: meta.solana_address,
+ network,
+ positions: [],
+ totals: { sol_in: 0, sol_out: 0, estimated_value_sol: 0, unrealized_pnl_sol: 0 },
+ },
+ });
+ }
+
+ const conn = solanaConnection(network);
+ const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, ammMod, splToken, BN] =
+ await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('@pump-fun/pump-swap-sdk'),
+ import('@solana/spl-token'),
+ import('bn.js').then((m) => m.default || m),
+ ]);
+ const online = new OnlinePumpSdk(conn);
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(conn);
+ const ammSdk = new ammMod.PumpAmmSdk();
+ let global;
+ try {
+ global = await online.fetchGlobal();
+ } catch (err) {
+ console.error('[pumpfun/portfolio] fetchGlobal failed', err);
+ global = null;
+ }
+
+ const positions = await Promise.all(
+ [...byMint.values()].map(async (pos) => {
+ const out = { ...pos, token_balance: '0', estimated_sol_value: null, unrealized_pnl_sol: null, graduated: null };
+ let mintPk;
+ try {
+ mintPk = new PublicKey(pos.mint);
+ } catch {
+ out.error = 'invalid_mint';
+ return out;
+ }
+
+ try {
+ const ata = await splToken.getAssociatedTokenAddress(mintPk, keypair.publicKey);
+ const bal = await conn.getTokenAccountBalance(ata).catch(() => null);
+ out.token_balance = bal?.value?.amount || '0';
+ } catch (err) {
+ out.error = 'balance_fetch_failed';
+ }
+
+ if (out.token_balance === '0' || !global) {
+ out.unrealized_pnl_sol = out.sol_out - out.sol_in;
+ out.estimated_sol_value = 0;
+ return out;
+ }
+
+ try {
+ const state = await online.fetchSellState(mintPk, keypair.publicKey);
+ out.graduated = !!state.bondingCurve.complete;
+ if (!out.graduated) {
+ const expectedSol = getSellSolAmountFromTokenAmount({
+ global,
+ feeConfig: null,
+ mintSupply: state.bondingCurve.tokenTotalSupply,
+ bondingCurve: state.bondingCurve,
+ amount: new BN(out.token_balance),
+ });
+ out.estimated_sol_value = lamportsToSol(expectedSol);
+ out.venue = 'curve';
+ } else {
+ // AMM quote: simulate sellBaseInput to get expected SOL out.
+ try {
+ const poolKey = ammMod.canonicalPumpPoolPda(mintPk);
+ const swapState = await onlineAmm.swapSolanaState(poolKey, keypair.publicKey);
+ const result = ammSdk.sellAutocompleteQuoteFromBase
+ ? ammSdk.sellAutocompleteQuoteFromBase(swapState, new BN(out.token_balance), 0)
+ : null;
+ if (result && result.uiQuote != null) {
+ out.estimated_sol_value = lamportsToSol(result.uiQuote);
+ } else {
+ const pool = swapState.pool;
+ const baseReserve = pool.baseReserve || pool.virtualBaseReserves;
+ const quoteReserve = pool.quoteReserve || pool.virtualQuoteReserves;
+ if (baseReserve && quoteReserve) {
+ const bal = new BN(out.token_balance);
+ const out_q = bal.mul(quoteReserve).div(baseReserve.add(bal));
+ out.estimated_sol_value = lamportsToSol(out_q);
+ } else {
+ out.estimated_sol_value = null;
+ }
+ }
+ out.venue = 'amm';
+ out.pool = poolKey.toBase58();
+ } catch (e) {
+ console.error('[pumpfun/portfolio] amm quote failed', e);
+ out.estimated_sol_value = null;
+ out.error = 'amm_quote_failed';
+ }
+ }
+ if (typeof out.estimated_sol_value === 'number') {
+ out.unrealized_pnl_sol = out.estimated_sol_value + out.sol_out - out.sol_in;
+ } else {
+ out.unrealized_pnl_sol = null;
+ }
+ } catch (err) {
+ out.error = out.error || 'curve_quote_failed';
+ }
+
+ return out;
+ }),
+ );
+
+ const totals = positions.reduce(
+ (acc, p) => {
+ acc.sol_in += p.sol_in;
+ acc.sol_out += p.sol_out;
+ if (typeof p.estimated_sol_value === 'number') acc.estimated_value_sol += p.estimated_sol_value;
+ return acc;
+ },
+ { sol_in: 0, sol_out: 0, estimated_value_sol: 0 },
+ );
+ totals.unrealized_pnl_sol = totals.estimated_value_sol + totals.sol_out - totals.sol_in;
+
+ return json(res, 200, {
+ data: {
+ wallet: meta.solana_address,
+ network,
+ positions,
+ totals,
+ },
+ });
+}
+
+// ── sell ───────────────────────────────────────────────────────────────────
+
+const sellBodySchema = z.object({
+ mint: z.string().min(32).max(64),
+ tokenAmount: z.string().regex(/^\d+$/, 'must be a base-unit integer string'),
+ slippageBps: z.number().int().min(0).max(10_000).default(500),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleSell(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = sellBodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+
+ const loaded = await loadAgentForSigning(id, auth.userId);
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair } = loaded;
+
+ const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, BN, splToken] =
+ await Promise.all([
+ import('@pump-fun/pump-sdk'),
+ import('bn.js').then((m) => m.default || m),
+ import('@solana/spl-token'),
+ ]);
+
+ const conn = solanaConnection(body.network);
+ const online = new OnlinePumpSdk(conn);
+ const sdk = new PumpSdk();
+ const mint = new PublicKey(body.mint);
+ const tokenAmount = new BN(body.tokenAmount);
+
+ let instructions;
+ let expectedSolStr;
+ try {
+ const [global, state] = await Promise.all([
+ online.fetchGlobal(),
+ online.fetchSellState(mint, keypair.publicKey),
+ ]);
+ const expectedSol = getSellSolAmountFromTokenAmount({
+ global,
+ feeConfig: null,
+ mintSupply: state.bondingCurve.tokenTotalSupply,
+ bondingCurve: state.bondingCurve,
+ amount: tokenAmount,
+ });
+ expectedSolStr = expectedSol.toString();
+ instructions = await sdk.sellInstructions({
+ global,
+ bondingCurveAccountInfo: state.bondingCurveAccountInfo,
+ bondingCurve: state.bondingCurve,
+ mint,
+ user: keypair.publicKey,
+ amount: tokenAmount,
+ solAmount: expectedSol,
+ slippage: body.slippageBps / 10_000,
+ tokenProgram: splToken.TOKEN_PROGRAM_ID,
+ mayhemMode: false,
+ });
+ } catch (err) {
+ console.error('[pumpfun/sell] build failed', err);
+ return error(res, 422, 'build_failed', err.message || 'could not build sell ix');
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/sell] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${'pumpfun.sell'},
+ ${JSON.stringify({
+ mint: body.mint,
+ tokenAmount: body.tokenAmount,
+ expectedSolLamports: expectedSolStr,
+ slippageBps: body.slippageBps,
+ signature,
+ network: body.network,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/sell] log failed', e));
+
+ try {
+ const [m] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (m) {
+ await sql`
+ INSERT INTO pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, sol_amount, token_amount, slippage_bps, tx_signature, network)
+ VALUES
+ (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'sell',
+ 'bonding_curve', ${expectedSolStr || null}, ${body.tokenAmount},
+ ${body.slippageBps || null}, ${signature}, ${body.network})
+ ON CONFLICT (tx_signature, network) DO NOTHING
+ `;
+ }
+ } catch (e) {
+ console.error('[pumpfun/sell] trade index failed', e);
+ }
+
+ return json(res, 200, {
+ data: {
+ signature,
+ mint: body.mint,
+ tokenAmount: body.tokenAmount,
+ expectedSolLamports: expectedSolStr,
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ },
+ });
+}
+
+// ── swap ───────────────────────────────────────────────────────────────────
+
+const swapBodySchema = z.object({
+ mint: z.string().min(32).max(64),
+ side: z.enum(['buy', 'sell']),
+ solAmount: z.number().nonnegative().max(1000).optional(),
+ tokenAmount: z.string().regex(/^\d+$/).optional(),
+ slippageBps: z.number().int().min(0).max(10_000).default(500),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleSwap(req, res, id) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try {
+ body = swapBodySchema.parse(await readJson(req));
+ } catch (e) {
+ return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
+ }
+ if (body.side === 'buy' && !body.solAmount)
+ return error(res, 400, 'validation_error', 'side=buy requires solAmount');
+ if (body.side === 'sell' && !body.tokenAmount)
+ return error(res, 400, 'validation_error', 'side=sell requires tokenAmount');
+
+ const loaded = await loadAgentForSigning(id, auth.userId, {
+ reason: `pumpfun.swap.${body.side}`,
+ meta: { mint: body.mint, network: body.network },
+ });
+ if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
+ const { keypair, meta } = loaded;
+
+ if (body.side === 'buy') {
+ const blocked = await checkBuyAllowed({
+ agentId: id, meta, mint: body.mint, solAmount: body.solAmount,
+ });
+ if (blocked) return error(res, blocked.status, blocked.code, blocked.msg);
+ }
+
+ const conn = solanaConnection(body.network);
+ const mint = new PublicKey(body.mint);
+
+ // Detect graduation. If still on bonding curve, delegate to /buy or /sell.
+ const { PumpSdk, bondingCurvePda } = await import('@pump-fun/pump-sdk');
+ const pumpSdk = new PumpSdk();
+ const bcInfo = await conn.getAccountInfo(bondingCurvePda(mint));
+ const bc = bcInfo ? pumpSdk.decodeBondingCurveNullable(bcInfo) : null;
+ const graduated = !bc || bc.complete;
+
+ if (!graduated) {
+ return error(
+ res,
+ 409,
+ 'not_graduated',
+ `mint is still on the bonding curve — use /api/agents/${id}/pumpfun/${body.side} instead`,
+ );
+ }
+
+ // AMM path.
+ const { PumpAmmSdk, OnlinePumpAmmSdk, canonicalPumpPoolPda } = await import(
+ '@pump-fun/pump-swap-sdk'
+ );
+ const BN = (await import('bn.js')).default;
+ const amm = new PumpAmmSdk();
+ const online = new OnlinePumpAmmSdk(conn);
+
+ const poolKey = canonicalPumpPoolPda(mint);
+ const swapState = await online.swapSolanaState(poolKey, keypair.publicKey).catch(async (err) => {
+ // Fall back: pool account may not be initialized (race after graduation).
+ console.error('[pumpfun/swap] swapSolanaState failed', err);
+ return online.swapSolanaStateNoPool(poolKey, keypair.publicKey);
+ });
+
+ const slippage = body.slippageBps / 10_000;
+
+ let instructions;
+ let quotedAmount;
+ try {
+ if (body.side === 'buy') {
+ const quoteLamports = new BN(Math.floor(body.solAmount * 1e9));
+ instructions = await amm.buyQuoteInput(swapState, quoteLamports, slippage);
+ quotedAmount = { quote_lamports: quoteLamports.toString() };
+ } else {
+ const baseAmount = new BN(body.tokenAmount);
+ instructions = await amm.sellBaseInput(swapState, baseAmount, slippage);
+ quotedAmount = { base_amount: baseAmount.toString() };
+ // Best-effort expected-SOL-out via constant-product on pool reserves.
+ try {
+ const pool = swapState.pool || {};
+ const baseReserve = pool.baseReserve || pool.virtualBaseReserves;
+ const quoteReserve = pool.quoteReserve || pool.virtualQuoteReserves;
+ if (baseReserve && quoteReserve) {
+ const out = baseAmount.mul(quoteReserve).div(baseReserve.add(baseAmount));
+ quotedAmount.expectedSolLamports = out.toString();
+ }
+ } catch (e) {
+ console.error('[pumpfun/swap] sell quote failed', e);
+ }
+ }
+ } catch (err) {
+ console.error('[pumpfun/swap] build failed', err);
+ return error(res, 422, 'build_failed', err.message || 'could not build swap ix');
+ }
+
+ const tx = new Transaction().add(...instructions);
+ tx.feePayer = keypair.publicKey;
+ const { blockhash } = await conn.getLatestBlockhash();
+ tx.recentBlockhash = blockhash;
+ tx.sign(keypair);
+
+ let signature;
+ try {
+ signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await conn.confirmTransaction(signature, 'confirmed');
+ } catch (err) {
+ console.error('[pumpfun/swap] send failed', err);
+ return error(res, 502, 'rpc_error', err.message || 'transaction failed');
+ }
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${id},
+ ${`pumpfun.swap.${body.side}`},
+ ${JSON.stringify({
+ mint: body.mint,
+ side: body.side,
+ ...(body.side === 'buy'
+ ? { solAmount: body.solAmount }
+ : { tokenAmount: body.tokenAmount }),
+ slippageBps: body.slippageBps,
+ signature,
+ network: body.network,
+ venue: 'amm',
+ ...quotedAmount,
+ })}::jsonb,
+ ${'pumpfun'}
+ )
+ `.catch((e) => console.error('[pumpfun/swap] log failed', e));
+
+ return json(res, 200, {
+ data: {
+ signature,
+ mint: body.mint,
+ side: body.side,
+ venue: 'amm',
+ pool: poolKey.toBase58(),
+ explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ },
+ });
+}
diff --git a/api/agents/pumpfun/buy.js b/api/agents/pumpfun/buy.js
deleted file mode 100644
index 771fef9df..000000000
--- a/api/agents/pumpfun/buy.js
+++ /dev/null
@@ -1,164 +0,0 @@
-// POST /api/agents/:id/pumpfun/buy
-// Bonding-curve buy: agent's Solana wallet spends SOL to acquire `mint`.
-// Reverts if the token has graduated — use the AMM swap endpoint after that.
-//
-// Body: { mint, solAmount, slippageBps?, network? }
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';
-import { sql } from '../../_lib/db.js';
-import { Transaction, PublicKey } from '@solana/web3.js';
-import { z } from 'zod';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(64),
- solAmount: z.number().positive().max(1000),
- slippageBps: z.number().int().min(0).max(10_000).default(500),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try {
- body = bodySchema.parse(await readJson(req));
- } catch (e) {
- return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
- }
-
- const loaded = await loadAgentForSigning(id, auth.userId);
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair, meta } = loaded;
-
- const blocked = await checkBuyAllowed({
- agentId: id,
- meta,
- mint: body.mint,
- solAmount: body.solAmount,
- });
- if (blocked) return error(res, blocked.status, blocked.code, blocked.msg);
-
- const [{ PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount }, BN, splToken] =
- await Promise.all([
- import('@pump-fun/pump-sdk'),
- import('bn.js').then((m) => m.default || m),
- import('@solana/spl-token'),
- ]);
-
- const conn = solanaConnection(body.network);
- const online = new OnlinePumpSdk(conn);
- const sdk = new PumpSdk();
- const mint = new PublicKey(body.mint);
- const solLamports = new BN(Math.floor(body.solAmount * 1e9));
-
- let instructions;
- try {
- const [global, state] = await Promise.all([
- online.fetchGlobal(),
- online.fetchBuyState(mint, keypair.publicKey),
- ]);
- const expected = getBuyTokenAmountFromSolAmount({
- global,
- feeConfig: null,
- mintSupply: state.bondingCurve.tokenTotalSupply,
- bondingCurve: state.bondingCurve,
- amount: solLamports,
- });
- instructions = await sdk.buyInstructions({
- global,
- bondingCurveAccountInfo: state.bondingCurveAccountInfo,
- bondingCurve: state.bondingCurve,
- associatedUserAccountInfo: state.associatedUserAccountInfo,
- mint,
- user: keypair.publicKey,
- amount: expected,
- solAmount: solLamports,
- slippage: body.slippageBps / 10_000,
- tokenProgram: splToken.TOKEN_PROGRAM_ID,
- });
- } catch (err) {
- console.error('[pumpfun/buy] build failed', err);
- return error(res, 422, 'build_failed', err.message || 'could not build buy ix');
- }
-
- const tx = new Transaction().add(...instructions);
- tx.feePayer = keypair.publicKey;
- const { blockhash } = await conn.getLatestBlockhash();
- tx.recentBlockhash = blockhash;
- tx.sign(keypair);
-
- let signature;
- try {
- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
- } catch (err) {
- console.error('[pumpfun/buy] send failed', err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
- }
-
- await sql`
- INSERT INTO agent_actions (agent_id, type, payload, source_skill)
- VALUES (
- ${id},
- ${'pumpfun.buy'},
- ${JSON.stringify({
- mint: body.mint,
- solAmount: body.solAmount,
- slippageBps: body.slippageBps,
- signature,
- network: body.network,
- })}::jsonb,
- ${'pumpfun'}
- )
- `.catch((e) => console.error('[pumpfun/buy] log failed', e));
-
- // Mirror into pump_agent_trades for cross-feature analytics (reputation,
- // admin health, strategy backtests). Best-effort — agent may not have a
- // pump_agent_mints row yet if the mint was launched outside three.ws.
- try {
- const [m] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
- `;
- if (m) {
- const lamports = BigInt(Math.floor(body.solAmount * 1_000_000_000));
- await sql`
- INSERT INTO pump_agent_trades
- (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
- VALUES
- (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'buy',
- 'bonding_curve', ${lamports.toString()}, ${body.slippageBps || null},
- ${signature}, ${body.network})
- ON CONFLICT (tx_signature, network) DO NOTHING
- `;
- }
- } catch (e) {
- console.error('[pumpfun/buy] trade index failed', e);
- }
-
- return json(res, 200, {
- data: {
- signature,
- mint: body.mint,
- solAmount: body.solAmount,
- explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
- },
- });
-}
diff --git a/api/agents/pumpfun/launch.js b/api/agents/pumpfun/launch.js
deleted file mode 100644
index a98e2d051..000000000
--- a/api/agents/pumpfun/launch.js
+++ /dev/null
@@ -1,194 +0,0 @@
-// POST /api/agents/:id/pumpfun/launch
-// Create a new pump.fun token whose creator is the agent's Solana wallet.
-// Optional `solAmount` immediately buys an initial supply for the agent.
-//
-// Body: { name, symbol, uri, solAmount?, network? }
-// - uri: already-hosted JSON metadata URL (caller is responsible for upload)
-// - solAmount: optional initial buy in SOL (decimal); creates+buys atomically
-// - network: 'mainnet' | 'devnet' (default mainnet)
-//
-// The agent signs as creator/user. A fresh mint Keypair is generated and also
-// signs the create transaction. We return the new mint, transaction signature,
-// and explorer URL.
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { grindMintKeypair } from '../../_lib/pump-vanity.js';
-import { sql } from '../../_lib/db.js';
-import { Keypair, Transaction, SystemProgram } from '@solana/web3.js';
-import { z } from 'zod';
-
-const bodySchema = z.object({
- name: z.string().trim().min(1).max(32),
- symbol: z.string().trim().min(1).max(10),
- uri: z.string().url().max(2048),
- solAmount: z.number().nonnegative().max(1000).optional(),
- tokenAmount: z.number().nonnegative().optional(),
- vanityPrefix: z.string().min(1).max(6).optional(),
- vanitySuffix: z.string().min(1).max(6).optional(),
- vanityIgnoreCase: z.boolean().optional(),
- mintSecretKey: z.array(z.number().int().min(0).max(255)).length(64).optional(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try {
- body = bodySchema.parse(await readJson(req));
- } catch (e) {
- return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
- }
-
- const loaded = await loadAgentForSigning(id, auth.userId);
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair } = loaded;
-
- const { PumpSdk, OnlinePumpSdk } = await import('@pump-fun/pump-sdk');
- const BN = (await import('bn.js')).default;
- const conn = solanaConnection(body.network);
- const online = new OnlinePumpSdk(conn);
- const sdk = new PumpSdk();
-
- let mint;
- let vanityIterations = 1;
- let vanityDurationMs = 0;
- if (body.mintSecretKey) {
- try {
- mint = Keypair.fromSecretKey(Uint8Array.from(body.mintSecretKey));
- } catch (e) {
- return error(res, 400, 'validation_error', 'mintSecretKey did not parse as a valid Solana keypair');
- }
- const addr = mint.publicKey.toBase58();
- const ic = !!body.vanityIgnoreCase;
- const cmp = (a, b) => (ic ? a.toLowerCase() === b.toLowerCase() : a === b);
- if (body.vanityPrefix && !cmp(addr.slice(0, body.vanityPrefix.length), body.vanityPrefix)) {
- return error(res, 400, 'validation_error', 'mintSecretKey does not match vanityPrefix');
- }
- if (body.vanitySuffix && !cmp(addr.slice(-body.vanitySuffix.length), body.vanitySuffix)) {
- return error(res, 400, 'validation_error', 'mintSecretKey does not match vanitySuffix');
- }
- } else {
- try {
- const ground = await grindMintKeypair({
- prefix: body.vanityPrefix,
- suffix: body.vanitySuffix,
- ignoreCase: body.vanityIgnoreCase,
- });
- mint = ground.keypair;
- vanityIterations = ground.iterations;
- vanityDurationMs = ground.durationMs;
- } catch (err) {
- return error(res, err.status || 500, err.code || 'internal', err.message);
- }
- }
- const solLamports = new BN(Math.floor((body.solAmount || 0) * 1e9));
- const tokenAmount = new BN(body.tokenAmount || 0);
-
- let instructions;
- if (solLamports.gtn(0)) {
- const global = await online.fetchGlobal();
- instructions = await sdk.createV2AndBuyInstructions({
- global,
- mint: mint.publicKey,
- name: body.name,
- symbol: body.symbol,
- uri: body.uri,
- creator: keypair.publicKey,
- user: keypair.publicKey,
- amount: tokenAmount,
- solAmount: solLamports,
- mayhemMode: false,
- });
- } else {
- const ix = await sdk.createV2Instruction({
- mint: mint.publicKey,
- name: body.name,
- symbol: body.symbol,
- uri: body.uri,
- creator: keypair.publicKey,
- user: keypair.publicKey,
- mayhemMode: false,
- });
- instructions = [ix];
- }
-
- const tx = new Transaction().add(...instructions);
- tx.feePayer = keypair.publicKey;
- const { blockhash } = await conn.getLatestBlockhash();
- tx.recentBlockhash = blockhash;
- tx.sign(keypair, mint);
-
- let signature;
- try {
- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
- } catch (err) {
- console.error('[pumpfun/launch] send failed', err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
- }
-
- const mintAddr = mint.publicKey.toBase58();
- await sql`
- INSERT INTO agent_actions (agent_id, type, payload, source_skill)
- VALUES (
- ${id},
- ${'pumpfun.launch'},
- ${JSON.stringify({
- mint: mintAddr,
- name: body.name,
- symbol: body.symbol,
- uri: body.uri,
- signature,
- network: body.network,
- solAmount: body.solAmount || 0,
- vanity_prefix: body.vanityPrefix || null,
- vanity_suffix: body.vanitySuffix || null,
- vanity_ignore_case: body.vanityIgnoreCase || false,
- vanity_iterations: vanityIterations,
- vanity_duration_ms: vanityDurationMs,
- })}::jsonb,
- ${'pumpfun'}
- )
- `.catch((e) => console.error('[pumpfun/launch] log failed', e));
-
- // Register the mint in the indexer table so pump-agent-stats cron picks it up.
- await sql`
- INSERT INTO pump_agent_mints
- (agent_id, user_id, network, mint, name, symbol, metadata_uri, agent_authority)
- VALUES
- (${id}, ${auth.userId}, ${body.network}, ${mintAddr},
- ${body.name}, ${body.symbol}, ${body.uri}, ${keypair.publicKey.toBase58()})
- ON CONFLICT (mint, network) DO NOTHING
- `.catch((e) => console.error('[pumpfun/launch] mint index failed', e));
-
- return json(res, 201, {
- data: {
- mint: mint.publicKey.toBase58(),
- signature,
- explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
- pumpfun_url: `https://pump.fun/${mint.publicKey.toBase58()}`,
- vanity_prefix: body.vanityPrefix || null,
- vanity_suffix: body.vanitySuffix || null,
- vanity_iterations: vanityIterations,
- vanity_duration_ms: vanityDurationMs,
- },
- });
-}
diff --git a/api/agents/pumpfun/pay.js b/api/agents/pumpfun/pay.js
deleted file mode 100644
index b1561d8e8..000000000
--- a/api/agents/pumpfun/pay.js
+++ /dev/null
@@ -1,277 +0,0 @@
-// POST /api/agents/:id/pumpfun/pay
-//
-// Full @pump-fun/agent-payments-sdk surface, signed by the agent's wallet.
-//
-// Body: { action, tokenMint, currencyMint, ...params, network? }
-//
-// Actions (all return { signature, action, ... } except `balances`):
-// create — register the agent's wallet as authority for tokenMint.
-// Requires: buybackBps (0–10_000).
-// The agent must already be the bonding-curve creator
-// of `tokenMint`; otherwise the program rejects.
-// accept — agent pays the token's payment vault for an invoice.
-// Requires: amount (raw units, string), memo (string),
-// startTime, endTime (unix seconds).
-// withdraw — agent withdraws collected payments for tokenMint.
-// Requires: receiverAta. The ATA must already exist;
-// create it client-side or via /accept-payment first.
-// distribute — permissionless distribution from payment vault to the
-// buyback + withdraw vaults. Anyone can call.
-// extend_account — pay rent to extend a program account.
-// Requires: account.
-// update_authority — rotate the agent authority. Requires: newAuthority.
-// update_buyback — change buyback bps. Requires: buybackBps.
-// balances — read-only; returns vault balances for currencyMint.
-//
-// Spend-policy is enforced on `accept` (it spends agent SOL/SPL).
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { sql } from '../../_lib/db.js';
-import { PublicKey, Transaction } from '@solana/web3.js';
-import { z } from 'zod';
-
-const NATIVE_SOL_MINT = 'So11111111111111111111111111111111111111112';
-
-const bodySchema = z.object({
- action: z.enum([
- 'create',
- 'accept',
- 'withdraw',
- 'distribute',
- 'extend_account',
- 'update_authority',
- 'update_buyback',
- 'balances',
- ]),
- tokenMint: z.string().min(32).max(64),
- currencyMint: z.string().min(32).max(64).default(NATIVE_SOL_MINT),
- amount: z.string().regex(/^\d+$/).optional(),
- memo: z.string().regex(/^\d+$/).optional(),
- startTime: z.number().int().nonnegative().optional(),
- endTime: z.number().int().nonnegative().optional(),
- receiverAta: z.string().min(32).max(64).optional(),
- userTokenAccount: z.string().min(32).max(64).optional(),
- account: z.string().min(32).max(64).optional(),
- newAuthority: z.string().min(32).max(64).optional(),
- buybackBps: z.number().int().min(0).max(10_000).optional(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-function need(body, ...fields) {
- const missing = fields.filter((f) => body[f] == null || body[f] === '');
- if (missing.length)
- return { status: 400, code: 'validation_error', msg: `missing: ${missing.join(', ')}` };
- return null;
-}
-
-function explorerUrl(sig, network) {
- return `https://solscan.io/tx/${sig}${network === 'devnet' ? '?cluster=devnet' : ''}`;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try {
- body = bodySchema.parse(await readJson(req));
- } catch (e) {
- return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
- }
-
- const loaded = await loadAgentForSigning(id, auth.userId, {
- reason: `pumpfun.pay.${body.action}`,
- meta: { tokenMint: body.tokenMint, network: body.network },
- });
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair } = loaded;
-
- const conn = solanaConnection(body.network);
- const tokenMint = new PublicKey(body.tokenMint);
- const currencyMint = new PublicKey(body.currencyMint);
- const { PumpAgent } = await import('@pump-fun/agent-payments-sdk');
- const agent = new PumpAgent(tokenMint, body.network, conn);
-
- // ── Read-only ──────────────────────────────────────────────────────────
- if (body.action === 'balances') {
- try {
- const balances = await agent.getBalances(currencyMint);
- return json(res, 200, {
- data: {
- tokenMint: body.tokenMint,
- currencyMint: body.currencyMint,
- balances: {
- paymentVault: {
- address: balances.paymentVault.address.toBase58(),
- balance: balances.paymentVault.balance.toString(),
- },
- buybackVault: {
- address: balances.buybackVault.address.toBase58(),
- balance: balances.buybackVault.balance.toString(),
- },
- withdrawVault: {
- address: balances.withdrawVault.address.toBase58(),
- balance: balances.withdrawVault.balance.toString(),
- },
- },
- },
- });
- } catch (err) {
- console.error('[pumpfun/pay] balances failed', err);
- return error(res, 502, 'rpc_error', err.message || 'balance fetch failed');
- }
- }
-
- // ── Build instructions per action ──────────────────────────────────────
- let instructions;
- let extra = {};
- try {
- switch (body.action) {
- case 'create': {
- const miss = need(body, 'buybackBps');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- const ix = await agent.create({
- authority: keypair.publicKey,
- mint: tokenMint,
- agentAuthority: keypair.publicKey,
- buybackBps: body.buybackBps,
- });
- instructions = [ix];
- extra = { buybackBps: body.buybackBps };
- break;
- }
- case 'accept': {
- const miss = need(body, 'amount', 'memo', 'startTime', 'endTime');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- instructions = await agent.buildAcceptPaymentInstructions({
- user: keypair.publicKey,
- currencyMint,
- amount: body.amount,
- memo: body.memo,
- startTime: body.startTime,
- endTime: body.endTime,
- });
- extra = {
- amount: body.amount,
- memo: body.memo,
- startTime: body.startTime,
- endTime: body.endTime,
- };
- break;
- }
- case 'withdraw': {
- const miss = need(body, 'receiverAta');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- const ix = await agent.withdraw({
- authority: keypair.publicKey,
- currencyMint,
- receiverAta: new PublicKey(body.receiverAta),
- });
- instructions = [ix];
- extra = { receiverAta: body.receiverAta };
- break;
- }
- case 'distribute': {
- instructions = await agent.distributePayments({
- user: keypair.publicKey,
- currencyMint,
- });
- break;
- }
- case 'extend_account': {
- const miss = need(body, 'account');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- const ix = await agent.extendAccount({
- account: new PublicKey(body.account),
- user: keypair.publicKey,
- });
- instructions = [ix];
- extra = { account: body.account };
- break;
- }
- case 'update_authority': {
- const miss = need(body, 'newAuthority');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- const ix = await agent.updateAuthority({
- authority: keypair.publicKey,
- newAuthority: new PublicKey(body.newAuthority),
- });
- instructions = [ix];
- extra = { newAuthority: body.newAuthority };
- break;
- }
- case 'update_buyback': {
- const miss = need(body, 'buybackBps');
- if (miss) return error(res, miss.status, miss.code, miss.msg);
- const ix = await agent.updateBuybackBps({
- authority: keypair.publicKey,
- buybackBps: body.buybackBps,
- });
- instructions = [ix];
- extra = { buybackBps: body.buybackBps };
- break;
- }
- }
- } catch (err) {
- console.error(`[pumpfun/pay] ${body.action} build failed`, err);
- return error(res, 422, 'build_failed', err.message || 'could not build instruction');
- }
-
- const tx = new Transaction().add(...instructions);
- tx.feePayer = keypair.publicKey;
- const { blockhash } = await conn.getLatestBlockhash();
- tx.recentBlockhash = blockhash;
- tx.sign(keypair);
-
- let signature;
- try {
- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- 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');
- }
-
- await sql`
- INSERT INTO agent_actions (agent_id, type, payload, source_skill)
- VALUES (
- ${id},
- ${`pumpfun.pay.${body.action}`},
- ${JSON.stringify({
- tokenMint: body.tokenMint,
- currencyMint: body.currencyMint,
- signature,
- network: body.network,
- ...extra,
- })}::jsonb,
- ${'pumpfun'}
- )
- `.catch((e) => console.error('[pumpfun/pay] log failed', e));
-
- return json(res, 200, {
- data: {
- signature,
- action: body.action,
- tokenMint: body.tokenMint,
- currencyMint: body.currencyMint,
- explorer: explorerUrl(signature, body.network),
- ...extra,
- },
- });
-}
diff --git a/api/agents/pumpfun/portfolio.js b/api/agents/pumpfun/portfolio.js
deleted file mode 100644
index 4ad80212a..000000000
--- a/api/agents/pumpfun/portfolio.js
+++ /dev/null
@@ -1,220 +0,0 @@
-// GET /api/agents/:id/pumpfun/portfolio?network=mainnet|devnet
-//
-// Aggregates pumpfun.buy / pumpfun.sell rows from agent_actions into per-mint
-// positions. For each mint with a non-zero token balance, fetches the current
-// SPL token amount from chain and quotes a sell-back to estimate live value.
-//
-// Response shape:
-// {
-// data: {
-// wallet, // agent's solana_address
-// network,
-// positions: [{
-// mint,
-// sol_in, // total SOL spent buying
-// sol_out, // total SOL received selling
-// realized_pnl_sol, // sol_out - matched-cost portion (FIFO not modeled; = sol_out)
-// token_balance, // base-unit string from chain
-// estimated_sol_value, // sell-back quote in SOL (decimal), null if graduated/curve missing
-// unrealized_pnl_sol, // estimated_sol_value - sol_in + sol_out
-// graduated, // bondingCurve.complete
-// }],
-// totals: { sol_in, sol_out, estimated_value_sol, unrealized_pnl_sol },
-// }
-// }
-//
-// Pricing is best-effort — RPC failures per mint are surfaced as
-// `error: <code>` on the position, not a 5xx for the whole call.
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { sql } from '../../_lib/db.js';
-import { PublicKey } from '@solana/web3.js';
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-function lamportsToSol(bnLike) {
- if (!bnLike) return 0;
- const s = typeof bnLike === 'string' ? bnLike : bnLike.toString();
- return Number(s) / 1e9;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
-
- const loaded = await loadAgentForSigning(id, auth.userId);
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair, meta } = loaded;
-
- const rows = await sql`
- SELECT type, payload
- FROM agent_actions
- WHERE agent_id = ${id}
- AND type IN ('pumpfun.buy', 'pumpfun.sell', 'pumpfun.launch',
- 'pumpfun.swap.buy', 'pumpfun.swap.sell')
- AND (payload->>'network') = ${network}
- `;
-
- // Aggregate per mint
- const byMint = new Map();
- for (const row of rows) {
- const p = row.payload || {};
- const mint = p.mint;
- if (!mint) continue;
- const e = byMint.get(mint) || { mint, sol_in: 0, sol_out: 0 };
- if (row.type === 'pumpfun.buy' || row.type === 'pumpfun.launch' || row.type === 'pumpfun.swap.buy') {
- e.sol_in += Number(p.solAmount) || 0;
- } else if (row.type === 'pumpfun.sell' || row.type === 'pumpfun.swap.sell') {
- e.sol_out += lamportsToSol(p.expectedSolLamports);
- }
- byMint.set(mint, e);
- }
-
- if (byMint.size === 0) {
- return json(res, 200, {
- data: {
- wallet: meta.solana_address,
- network,
- positions: [],
- totals: { sol_in: 0, sol_out: 0, estimated_value_sol: 0, unrealized_pnl_sol: 0 },
- },
- });
- }
-
- const conn = solanaConnection(network);
- const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, ammMod, splToken, BN] =
- await Promise.all([
- import('@pump-fun/pump-sdk'),
- import('@pump-fun/pump-swap-sdk'),
- import('@solana/spl-token'),
- import('bn.js').then((m) => m.default || m),
- ]);
- const online = new OnlinePumpSdk(conn);
- const onlineAmm = new ammMod.OnlinePumpAmmSdk(conn);
- const ammSdk = new ammMod.PumpAmmSdk();
- let global;
- try {
- global = await online.fetchGlobal();
- } catch (err) {
- console.error('[pumpfun/portfolio] fetchGlobal failed', err);
- global = null;
- }
-
- const positions = await Promise.all(
- [...byMint.values()].map(async (pos) => {
- const out = { ...pos, token_balance: '0', estimated_sol_value: null, unrealized_pnl_sol: null, graduated: null };
- let mintPk;
- try {
- mintPk = new PublicKey(pos.mint);
- } catch {
- out.error = 'invalid_mint';
- return out;
- }
-
- try {
- const ata = await splToken.getAssociatedTokenAddress(mintPk, keypair.publicKey);
- const bal = await conn.getTokenAccountBalance(ata).catch(() => null);
- out.token_balance = bal?.value?.amount || '0';
- } catch (err) {
- out.error = 'balance_fetch_failed';
- }
-
- if (out.token_balance === '0' || !global) {
- out.unrealized_pnl_sol = out.sol_out - out.sol_in;
- out.estimated_sol_value = 0;
- return out;
- }
-
- try {
- const state = await online.fetchSellState(mintPk, keypair.publicKey);
- out.graduated = !!state.bondingCurve.complete;
- if (!out.graduated) {
- const expectedSol = getSellSolAmountFromTokenAmount({
- global,
- feeConfig: null,
- mintSupply: state.bondingCurve.tokenTotalSupply,
- bondingCurve: state.bondingCurve,
- amount: new BN(out.token_balance),
- });
- out.estimated_sol_value = lamportsToSol(expectedSol);
- out.venue = 'curve';
- } else {
- // AMM quote: simulate sellBaseInput to get expected SOL out.
- try {
- const poolKey = ammMod.canonicalPumpPoolPda(mintPk);
- const swapState = await onlineAmm.swapSolanaState(poolKey, keypair.publicKey);
- const result = ammSdk.sellAutocompleteQuoteFromBase
- ? ammSdk.sellAutocompleteQuoteFromBase(swapState, new BN(out.token_balance), 0)
- : null;
- if (result && result.uiQuote != null) {
- out.estimated_sol_value = lamportsToSol(result.uiQuote);
- } else {
- const pool = swapState.pool;
- const baseReserve = pool.baseReserve || pool.virtualBaseReserves;
- const quoteReserve = pool.quoteReserve || pool.virtualQuoteReserves;
- if (baseReserve && quoteReserve) {
- const bal = new BN(out.token_balance);
- const out_q = bal.mul(quoteReserve).div(baseReserve.add(bal));
- out.estimated_sol_value = lamportsToSol(out_q);
- } else {
- out.estimated_sol_value = null;
- }
- }
- out.venue = 'amm';
- out.pool = poolKey.toBase58();
- } catch (e) {
- console.error('[pumpfun/portfolio] amm quote failed', e);
- out.estimated_sol_value = null;
- out.error = 'amm_quote_failed';
- }
- }
- if (typeof out.estimated_sol_value === 'number') {
- out.unrealized_pnl_sol = out.estimated_sol_value + out.sol_out - out.sol_in;
- } else {
- out.unrealized_pnl_sol = null;
- }
- } catch (err) {
- out.error = out.error || 'curve_quote_failed';
- }
-
- return out;
- }),
- );
-
- const totals = positions.reduce(
- (acc, p) => {
- acc.sol_in += p.sol_in;
- acc.sol_out += p.sol_out;
- if (typeof p.estimated_sol_value === 'number') acc.estimated_value_sol += p.estimated_sol_value;
- return acc;
- },
- { sol_in: 0, sol_out: 0, estimated_value_sol: 0 },
- );
- totals.unrealized_pnl_sol = totals.estimated_value_sol + totals.sol_out - totals.sol_in;
-
- return json(res, 200, {
- data: {
- wallet: meta.solana_address,
- network,
- positions,
- totals,
- },
- });
-}
diff --git a/api/agents/pumpfun/sell.js b/api/agents/pumpfun/sell.js
deleted file mode 100644
index c4d67d26c..000000000
--- a/api/agents/pumpfun/sell.js
+++ /dev/null
@@ -1,156 +0,0 @@
-// POST /api/agents/:id/pumpfun/sell
-// Bonding-curve sell: agent's Solana wallet returns tokens to the curve for SOL.
-// Reverts if the token has graduated — use the AMM swap endpoint after that.
-//
-// Body: { mint, tokenAmount, slippageBps?, network? }
-// - tokenAmount: base-unit integer string (BN), not human decimals
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { sql } from '../../_lib/db.js';
-import { Transaction, PublicKey } from '@solana/web3.js';
-import { z } from 'zod';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(64),
- tokenAmount: z.string().regex(/^\d+$/, 'must be a base-unit integer string'),
- slippageBps: z.number().int().min(0).max(10_000).default(500),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try {
- body = bodySchema.parse(await readJson(req));
- } catch (e) {
- return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
- }
-
- const loaded = await loadAgentForSigning(id, auth.userId);
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair } = loaded;
-
- const [{ PumpSdk, OnlinePumpSdk, getSellSolAmountFromTokenAmount }, BN, splToken] =
- await Promise.all([
- import('@pump-fun/pump-sdk'),
- import('bn.js').then((m) => m.default || m),
- import('@solana/spl-token'),
- ]);
-
- const conn = solanaConnection(body.network);
- const online = new OnlinePumpSdk(conn);
- const sdk = new PumpSdk();
- const mint = new PublicKey(body.mint);
- const tokenAmount = new BN(body.tokenAmount);
-
- let instructions;
- let expectedSolStr;
- try {
- const [global, state] = await Promise.all([
- online.fetchGlobal(),
- online.fetchSellState(mint, keypair.publicKey),
- ]);
- const expectedSol = getSellSolAmountFromTokenAmount({
- global,
- feeConfig: null,
- mintSupply: state.bondingCurve.tokenTotalSupply,
- bondingCurve: state.bondingCurve,
- amount: tokenAmount,
- });
- expectedSolStr = expectedSol.toString();
- instructions = await sdk.sellInstructions({
- global,
- bondingCurveAccountInfo: state.bondingCurveAccountInfo,
- bondingCurve: state.bondingCurve,
- mint,
- user: keypair.publicKey,
- amount: tokenAmount,
- solAmount: expectedSol,
- slippage: body.slippageBps / 10_000,
- tokenProgram: splToken.TOKEN_PROGRAM_ID,
- mayhemMode: false,
- });
- } catch (err) {
- console.error('[pumpfun/sell] build failed', err);
- return error(res, 422, 'build_failed', err.message || 'could not build sell ix');
- }
-
- const tx = new Transaction().add(...instructions);
- tx.feePayer = keypair.publicKey;
- const { blockhash } = await conn.getLatestBlockhash();
- tx.recentBlockhash = blockhash;
- tx.sign(keypair);
-
- let signature;
- try {
- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
- } catch (err) {
- console.error('[pumpfun/sell] send failed', err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
- }
-
- await sql`
- INSERT INTO agent_actions (agent_id, type, payload, source_skill)
- VALUES (
- ${id},
- ${'pumpfun.sell'},
- ${JSON.stringify({
- mint: body.mint,
- tokenAmount: body.tokenAmount,
- expectedSolLamports: expectedSolStr,
- slippageBps: body.slippageBps,
- signature,
- network: body.network,
- })}::jsonb,
- ${'pumpfun'}
- )
- `.catch((e) => console.error('[pumpfun/sell] log failed', e));
-
- try {
- const [m] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
- `;
- if (m) {
- await sql`
- INSERT INTO pump_agent_trades
- (mint_id, user_id, wallet, direction, route, sol_amount, token_amount, slippage_bps, tx_signature, network)
- VALUES
- (${m.id}, ${auth.userId}, ${keypair.publicKey.toBase58()}, 'sell',
- 'bonding_curve', ${expectedSolStr || null}, ${body.tokenAmount},
- ${body.slippageBps || null}, ${signature}, ${body.network})
- ON CONFLICT (tx_signature, network) DO NOTHING
- `;
- }
- } catch (e) {
- console.error('[pumpfun/sell] trade index failed', e);
- }
-
- return json(res, 200, {
- data: {
- signature,
- mint: body.mint,
- tokenAmount: body.tokenAmount,
- expectedSolLamports: expectedSolStr,
- explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
- },
- });
-}
diff --git a/api/agents/pumpfun/swap.js b/api/agents/pumpfun/swap.js
deleted file mode 100644
index 7ccd207fb..000000000
--- a/api/agents/pumpfun/swap.js
+++ /dev/null
@@ -1,182 +0,0 @@
-// POST /api/agents/:id/pumpfun/swap
-// AMM swap for graduated pump.fun tokens via @pump-fun/pump-swap-sdk.
-// If the requested mint has not graduated yet, the request is auto-routed
-// to the bonding-curve buy/sell endpoint so callers don't need to know.
-//
-// Body: { mint, side: 'buy'|'sell', solAmount?, tokenAmount?, slippageBps?, network? }
-// side='buy' → spend `solAmount` SOL (decimal) for `mint`
-// side='sell' → sell `tokenAmount` (base-unit integer string) for SOL
-// slippageBps: 0–10_000 (default 500 = 5%)
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { cors, json, method, readJson, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { loadAgentForSigning, solanaConnection } from '../../_lib/agent-pumpfun.js';
-import { checkBuyAllowed } from '../../_lib/agent-spend-policy.js';
-import { sql } from '../../_lib/db.js';
-import { Transaction, PublicKey } from '@solana/web3.js';
-import { z } from 'zod';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(64),
- side: z.enum(['buy', 'sell']),
- solAmount: z.number().nonnegative().max(1000).optional(),
- tokenAmount: z.string().regex(/^\d+$/).optional(),
- slippageBps: z.number().int().min(0).max(10_000).default(500),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try {
- body = bodySchema.parse(await readJson(req));
- } catch (e) {
- return error(res, 400, 'validation_error', e.errors?.[0]?.message || 'invalid body');
- }
- if (body.side === 'buy' && !body.solAmount)
- return error(res, 400, 'validation_error', 'side=buy requires solAmount');
- if (body.side === 'sell' && !body.tokenAmount)
- return error(res, 400, 'validation_error', 'side=sell requires tokenAmount');
-
- const loaded = await loadAgentForSigning(id, auth.userId, {
- reason: `pumpfun.swap.${body.side}`,
- meta: { mint: body.mint, network: body.network },
- });
- if (loaded.error) return error(res, loaded.error.status, loaded.error.code, loaded.error.msg);
- const { keypair, meta } = loaded;
-
- if (body.side === 'buy') {
- const blocked = await checkBuyAllowed({
- agentId: id, meta, mint: body.mint, solAmount: body.solAmount,
- });
- if (blocked) return error(res, blocked.status, blocked.code, blocked.msg);
- }
-
- const conn = solanaConnection(body.network);
- const mint = new PublicKey(body.mint);
-
- // Detect graduation. If still on bonding curve, delegate to /buy or /sell.
- const { PumpSdk, bondingCurvePda } = await import('@pump-fun/pump-sdk');
- const pumpSdk = new PumpSdk();
- const bcInfo = await conn.getAccountInfo(bondingCurvePda(mint));
- const bc = bcInfo ? pumpSdk.decodeBondingCurveNullable(bcInfo) : null;
- const graduated = !bc || bc.complete;
-
- if (!graduated) {
- return error(
- res,
- 409,
- 'not_graduated',
- `mint is still on the bonding curve — use /api/agents/${id}/pumpfun/${body.side} instead`,
- );
- }
-
- // AMM path.
- const { PumpAmmSdk, OnlinePumpAmmSdk, canonicalPumpPoolPda } = await import(
- '@pump-fun/pump-swap-sdk'
- );
- const BN = (await import('bn.js')).default;
- const amm = new PumpAmmSdk();
- const online = new OnlinePumpAmmSdk(conn);
-
- const poolKey = canonicalPumpPoolPda(mint);
- const swapState = await online.swapSolanaState(poolKey, keypair.publicKey).catch(async (err) => {
- // Fall back: pool account may not be initialized (race after graduation).
- console.error('[pumpfun/swap] swapSolanaState failed', err);
- return online.swapSolanaStateNoPool(poolKey, keypair.publicKey);
- });
-
- const slippage = body.slippageBps / 10_000;
-
- let instructions;
- let quotedAmount;
- try {
- if (body.side === 'buy') {
- const quoteLamports = new BN(Math.floor(body.solAmount * 1e9));
- instructions = await amm.buyQuoteInput(swapState, quoteLamports, slippage);
- quotedAmount = { quote_lamports: quoteLamports.toString() };
- } else {
- const baseAmount = new BN(body.tokenAmount);
- instructions = await amm.sellBaseInput(swapState, baseAmount, slippage);
- quotedAmount = { base_amount: baseAmount.toString() };
- // Best-effort expected-SOL-out via constant-product on pool reserves.
- try {
- const pool = swapState.pool || {};
- const baseReserve = pool.baseReserve || pool.virtualBaseReserves;
- const quoteReserve = pool.quoteReserve || pool.virtualQuoteReserves;
- if (baseReserve && quoteReserve) {
- const out = baseAmount.mul(quoteReserve).div(baseReserve.add(baseAmount));
- quotedAmount.expectedSolLamports = out.toString();
- }
- } catch (e) {
- console.error('[pumpfun/swap] sell quote failed', e);
- }
- }
- } catch (err) {
- console.error('[pumpfun/swap] build failed', err);
- return error(res, 422, 'build_failed', err.message || 'could not build swap ix');
- }
-
- const tx = new Transaction().add(...instructions);
- tx.feePayer = keypair.publicKey;
- const { blockhash } = await conn.getLatestBlockhash();
- tx.recentBlockhash = blockhash;
- tx.sign(keypair);
-
- let signature;
- try {
- signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false });
- await conn.confirmTransaction(signature, 'confirmed');
- } catch (err) {
- console.error('[pumpfun/swap] send failed', err);
- return error(res, 502, 'rpc_error', err.message || 'transaction failed');
- }
-
- await sql`
- INSERT INTO agent_actions (agent_id, type, payload, source_skill)
- VALUES (
- ${id},
- ${`pumpfun.swap.${body.side}`},
- ${JSON.stringify({
- mint: body.mint,
- side: body.side,
- ...(body.side === 'buy'
- ? { solAmount: body.solAmount }
- : { tokenAmount: body.tokenAmount }),
- slippageBps: body.slippageBps,
- signature,
- network: body.network,
- venue: 'amm',
- ...quotedAmount,
- })}::jsonb,
- ${'pumpfun'}
- )
- `.catch((e) => console.error('[pumpfun/swap] log failed', e));
-
- return json(res, 200, {
- data: {
- signature,
- mint: body.mint,
- side: body.side,
- venue: 'amm',
- pool: poolKey.toBase58(),
- explorer: `https://solscan.io/tx/${signature}${body.network === 'devnet' ? '?cluster=devnet' : ''}`,
- },
- });
-}
diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].js
new file mode 100644
index 000000000..d5b606b97
--- /dev/null
+++ b/api/agents/tokens/[action].js
@@ -0,0 +1,453 @@
+/**
+ * Agent Tokens Dispatcher
+ * -----------------------
+ * POST /api/agents/tokens/launch-prep
+ * POST /api/agents/tokens/launch-confirm
+ * GET /api/agents/tokens/launch-quote
+ *
+ * Single Vercel function that dispatches on req.query.action (auto-populated
+ * from the [action] filename). Consolidated to reduce function count and
+ * avoid bundling the heavy Pump.fun/Solana SDKs three times.
+ */
+
+import { z } from 'zod';
+import {
+ Connection,
+ Keypair,
+ PublicKey,
+ Transaction,
+ ComputeBudgetProgram,
+ SystemProgram,
+} from '@solana/web3.js';
+import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
+import BN from 'bn.js';
+import { createHash } from 'crypto';
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import { randomToken } from '../../_lib/crypto.js';
+import { env } from '../../_lib/env.js';
+import { r2 } from '../../_lib/r2.js';
+
+function rpcUrl(cluster) {
+ return cluster === 'devnet'
+ ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+}
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'launch-prep':
+ return handleLaunchPrep(req, res);
+ case 'launch-confirm':
+ return handleLaunchConfirm(req, res);
+ case 'launch-quote':
+ return handleLaunchQuote(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown tokens action');
+ }
+});
+
+// ── launch-prep ──────────────────────────────────────────────────────────────
+
+const launchPrepSchema = z.object({
+ agent_id: z.string().min(1).max(80),
+ provider: z.literal('pumpfun'),
+ cluster: z.enum(['mainnet', 'devnet']),
+ wallet_address: z.string().min(32).max(44),
+ name: z.string().trim().min(1).max(32),
+ // Pump.fun caps symbols at ~10 chars; let's be permissive but clamped.
+ symbol: z
+ .string()
+ .trim()
+ .min(2)
+ .max(10)
+ .regex(/^[A-Za-z0-9]+$/, 'symbol must be alphanumeric'),
+ description: z.string().trim().max(280).default(''),
+ image: z.string().url().or(z.literal('')).default(''),
+ initial_buy_sol: z.number().min(0).max(50).default(0),
+});
+
+async function pinTokenMetadata({ name, symbol, description, image }) {
+ const json = {
+ name,
+ symbol,
+ description,
+ image,
+ showName: true,
+ createdOn: 'three.ws',
+ };
+ const bytes = Buffer.from(JSON.stringify(json), 'utf-8');
+ const token = process.env.WEB3_STORAGE_TOKEN;
+ if (token) {
+ try {
+ const r = await fetch('https://api.web3.storage/upload', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ body: bytes,
+ });
+ if (r.ok) {
+ const data = await r.json();
+ if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };
+ }
+ } catch (e) {
+ console.warn('[token launch-prep] web3.storage pin failed:', e.message);
+ }
+ }
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ const stub = `bafkreigenerated${hash.slice(0, 40)}`;
+ const key = `token-metadata/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ Body: bytes,
+ ContentType: 'application/json',
+ }),
+ );
+ return { cid: stub, uri: `ipfs://${stub}` };
+}
+
+async function handleLaunchPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(launchPrepSchema, await readJson(req));
+
+ // Resolve agent + ownership + Solana deploy state
+ const [agent] = await sql`
+ select id, name, user_id, wallet_address, meta
+ from agent_identities
+ where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const onchain = agent.meta?.onchain;
+ if (!onchain || onchain.family !== 'solana') {
+ return error(
+ res,
+ 409,
+ 'precondition_failed',
+ 'agent must be deployed on Solana before launching a token',
+ );
+ }
+ if (onchain.wallet?.toLowerCase?.() !== body.wallet_address.toLowerCase?.()) {
+ // Solana addresses are case-sensitive; equality check is exact.
+ if (onchain.wallet !== body.wallet_address) {
+ return error(res, 403, 'forbidden', 'wallet does not match agent owner');
+ }
+ }
+ if (agent.meta?.token?.mint) {
+ return error(res, 409, 'conflict', 'agent already has a launched token');
+ }
+
+ // 3. Pin token metadata
+ const { cid, uri: metadataUri } = await pinTokenMetadata({
+ name: body.name,
+ symbol: body.symbol,
+ description: body.description,
+ image: body.image,
+ });
+
+ // 4. Build the launch tx
+ const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const sdk = new PumpSdk(conn);
+
+ const mintKeypair = Keypair.generate();
+ const creator = new PublicKey(body.wallet_address);
+ const userPk = creator;
+
+ const ixs = [
+ // Bump compute budget — coin creation routinely exceeds the 200k default.
+ ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 100_000 }),
+ ];
+
+ if (body.initial_buy_sol > 0) {
+ const global = await sdk.fetchGlobal();
+ const lamports = new BN(Math.floor(body.initial_buy_sol * 1_000_000_000));
+ const tokenAmount = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: null,
+ bondingCurve: null,
+ amount: lamports,
+ });
+ const launchIxs = await sdk.createAndBuyInstructions({
+ global,
+ mint: mintKeypair.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: metadataUri,
+ creator,
+ user: userPk,
+ amount: tokenAmount,
+ solAmount: lamports,
+ });
+ ixs.push(...launchIxs);
+ } else {
+ const ix = await sdk.createV2Instruction({
+ mint: mintKeypair.publicKey,
+ name: body.name,
+ symbol: body.symbol,
+ uri: metadataUri,
+ creator,
+ user: userPk,
+ mayhemMode: false,
+ });
+ ixs.push(ix);
+ }
+
+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ const tx = new Transaction({
+ feePayer: creator,
+ blockhash,
+ lastValidBlockHeight,
+ }).add(...ixs);
+
+ // Partial-sign with the mint keypair. The user's wallet adds the creator
+ // signature client-side before submission. After this serialize, the mint
+ // secret key is no longer needed and goes out of scope.
+ tx.partialSign(mintKeypair);
+
+ const txBase64 = tx
+ .serialize({ requireAllSignatures: false, verifySignatures: false })
+ .toString('base64');
+
+ // 5. Persist prep
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into token_launches_pending
+ (id, user_id, agent_id, provider, cluster, mint, metadata_uri, cid, payload, expires_at)
+ values (
+ ${prepId},
+ ${user.id},
+ ${agent.id},
+ 'pumpfun',
+ ${body.cluster},
+ ${mintKeypair.publicKey.toBase58()},
+ ${metadataUri},
+ ${cid},
+ ${JSON.stringify({
+ name: body.name,
+ symbol: body.symbol,
+ description: body.description,
+ image: body.image,
+ initial_buy_sol: body.initial_buy_sol,
+ wallet_address: body.wallet_address,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (id) do nothing
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: mintKeypair.publicKey.toBase58(),
+ tx_base64: txBase64,
+ metadata_uri: metadataUri,
+ cluster: body.cluster,
+ expires_at: expiresAt.toISOString(),
+ });
+}
+
+// Make sure SystemProgram import isn't tree-shaken away (some bundlers complain
+// about unused imports). It's a peer for compute-budget instructions on some
+// Pump.fun program versions.
+void SystemProgram;
+
+// ── launch-confirm ───────────────────────────────────────────────────────────
+
+const launchConfirmSchema = z.object({
+ prep_id: z.string().min(8).max(80),
+ tx_signature: z.string().min(40).max(120),
+ wallet_address: z.string().min(32).max(44),
+});
+
+async function handleLaunchConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(launchConfirmSchema, await readJson(req));
+
+ const [prep] = await sql`
+ select id, agent_id, mint, metadata_uri, cluster, payload
+ from token_launches_pending
+ where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
+ limit 1
+ `;
+ if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
+
+ if (prep.payload?.wallet_address !== body.wallet_address) {
+ return error(res, 400, 'validation_error', 'wallet mismatch with prep');
+ }
+
+ // Verify on-chain
+ const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+
+ const deadline = Date.now() + 30_000;
+ let tx;
+ while (Date.now() < deadline) {
+ tx = await conn.getParsedTransaction(body.tx_signature, {
+ maxSupportedTransactionVersion: 0,
+ commitment: 'confirmed',
+ });
+ if (tx) break;
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
+ if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
+
+ const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
+ if (!accounts.includes(prep.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'expected mint not in tx');
+ }
+ if (!accounts.includes(body.wallet_address)) {
+ return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
+ }
+
+ // Resolve agent (re-check ownership + still no token)
+ const [agent] = await sql`
+ select id, meta from agent_identities
+ where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.meta?.token?.mint) {
+ return error(res, 409, 'conflict', 'agent already has a launched token');
+ }
+
+ const token = {
+ provider: 'pumpfun',
+ mint: prep.mint,
+ name: prep.payload.name,
+ symbol: prep.payload.symbol,
+ description: prep.payload.description,
+ image: prep.payload.image,
+ metadata_uri: prep.metadata_uri,
+ cluster: prep.cluster,
+ creator: body.wallet_address,
+ tx_signature: body.tx_signature,
+ launched_at: new Date().toISOString(),
+ ...(prep.cluster === 'mainnet'
+ ? { pumpfun_url: `https://pump.fun/${prep.mint}` }
+ : {
+ explorer_url: `https://explorer.solana.com/address/${prep.mint}?cluster=devnet`,
+ }),
+ ...(prep.payload.initial_buy_sol > 0
+ ? { initial_buy_sol: prep.payload.initial_buy_sol }
+ : {}),
+ };
+
+ const mergedMeta = { ...(agent.meta || {}), token };
+ const [updated] = await sql`
+ update agent_identities
+ set meta = ${JSON.stringify(mergedMeta)}::jsonb,
+ updated_at = now()
+ where id = ${agent.id}
+ returning id, name, description, wallet_address, meta, created_at
+ `;
+
+ await sql`delete from token_launches_pending where id = ${prep.id}`;
+
+ return json(res, 201, {
+ ok: true,
+ agent: { ...updated, token, home_url: `${env.APP_ORIGIN}/agent/${updated.id}` },
+ });
+}
+
+// ── launch-quote ─────────────────────────────────────────────────────────────
+
+const launchQuoteSchema = z.object({
+ initial_buy_sol: z.coerce.number().min(0).max(50).default(0),
+ cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+// Conservative upper bounds, in SOL.
+const FIXED_LAUNCH_COST = {
+ mintRent: 0.00146,
+ bondingCurveRent: 0.00203,
+ metadataRent: 0.00561,
+ txFee: 0.000005,
+};
+const FIXED_LAUNCH_TOTAL =
+ FIXED_LAUNCH_COST.mintRent +
+ FIXED_LAUNCH_COST.bondingCurveRent +
+ FIXED_LAUNCH_COST.metadataRent +
+ FIXED_LAUNCH_COST.txFee;
+
+async function handleLaunchQuote(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const q = launchQuoteSchema.parse({
+ initial_buy_sol: url.searchParams.get('initial_buy_sol'),
+ cluster: url.searchParams.get('cluster') || undefined,
+ });
+
+ let buyEstimate = null;
+ if (q.initial_buy_sol > 0) {
+ try {
+ const conn = new Connection(rpcUrl(q.cluster), 'confirmed');
+ const sdk = new PumpSdk(conn);
+ const global = await sdk.fetchGlobal();
+ const lamports = new BN(Math.floor(q.initial_buy_sol * 1_000_000_000));
+ const tokensOut = getBuyTokenAmountFromSolAmount({
+ global,
+ feeConfig: null,
+ mintSupply: null,
+ bondingCurve: null,
+ amount: lamports,
+ });
+ // Pump.fun protocol fee on initial buy is ~1%; surface as a separate
+ // line so the user sees what's spent vs what funds the curve.
+ buyEstimate = {
+ sol: q.initial_buy_sol,
+ tokens_out: tokensOut.toString(),
+ protocol_fee_sol: q.initial_buy_sol * 0.01,
+ };
+ } catch (e) {
+ // If RPC is unhealthy, return the structural estimate without the
+ // curve quote — the UI can still show launch costs.
+ console.warn('[launch-quote] RPC fetch failed:', e.message);
+ }
+ }
+
+ const totalSol =
+ FIXED_LAUNCH_TOTAL + q.initial_buy_sol + (buyEstimate?.protocol_fee_sol || 0);
+
+ return json(res, 200, {
+ cluster: q.cluster,
+ fixed: FIXED_LAUNCH_COST,
+ fixed_total_sol: FIXED_LAUNCH_TOTAL,
+ initial_buy: buyEstimate,
+ total_sol: totalSol,
+ });
+}
diff --git a/api/agents/tokens/launch-confirm.js b/api/agents/tokens/launch-confirm.js
deleted file mode 100644
index 61105353d..000000000
--- a/api/agents/tokens/launch-confirm.js
+++ /dev/null
@@ -1,136 +0,0 @@
-/**
- * POST /api/agents/tokens/launch-confirm
- *
- * Verify the Pump.fun coin-creation transaction landed on Solana and write
- * the canonical token block onto agent_identities.meta.token:
- *
- * meta.token = {
- * provider: 'pumpfun',
- * mint: '<base58>',
- * symbol, name, metadata_uri,
- * cluster: 'mainnet' | 'devnet',
- * creator: '<base58>',
- * tx_signature: '<base58>',
- * launched_at: ISO,
- * pumpfun_url: 'https://pump.fun/<mint>' (mainnet only)
- * }
- */
-
-import { z } from 'zod';
-import { Connection } from '@solana/web3.js';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { env } from '../../_lib/env.js';
-
-const bodySchema = z.object({
- prep_id: z.string().min(8).max(80),
- tx_signature: z.string().min(40).max(120),
- wallet_address: z.string().min(32).max(44),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [prep] = await sql`
- select id, agent_id, mint, metadata_uri, cluster, payload
- from token_launches_pending
- where id = ${body.prep_id} and user_id = ${user.id} and expires_at > now()
- limit 1
- `;
- if (!prep) return error(res, 404, 'not_found', 'prep expired or not found');
-
- if (prep.payload?.wallet_address !== body.wallet_address) {
- return error(res, 400, 'validation_error', 'wallet mismatch with prep');
- }
-
- // Verify on-chain
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
-
- const deadline = Date.now() + 30_000;
- let tx;
- while (Date.now() < deadline) {
- tx = await conn.getParsedTransaction(body.tx_signature, {
- maxSupportedTransactionVersion: 0,
- commitment: 'confirmed',
- });
- if (tx) break;
- await new Promise((r) => setTimeout(r, 1500));
- }
- if (!tx) return error(res, 422, 'tx_not_found', 'tx not found on Solana RPC');
- if (tx.meta?.err) return error(res, 422, 'tx_failed', 'tx failed on-chain');
-
- const accounts = tx.transaction.message.accountKeys.map((k) => k.pubkey?.toString());
- if (!accounts.includes(prep.mint)) {
- return error(res, 422, 'mint_not_in_tx', 'expected mint not in tx');
- }
- if (!accounts.includes(body.wallet_address)) {
- return error(res, 422, 'wrong_signer', 'wallet not in tx signers');
- }
-
- // Resolve agent (re-check ownership + still no token)
- const [agent] = await sql`
- select id, meta from agent_identities
- where id = ${prep.agent_id} and user_id = ${user.id} and deleted_at is null
- limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.meta?.token?.mint) {
- return error(res, 409, 'conflict', 'agent already has a launched token');
- }
-
- const token = {
- provider: 'pumpfun',
- mint: prep.mint,
- name: prep.payload.name,
- symbol: prep.payload.symbol,
- description: prep.payload.description,
- image: prep.payload.image,
- metadata_uri: prep.metadata_uri,
- cluster: prep.cluster,
- creator: body.wallet_address,
- tx_signature: body.tx_signature,
- launched_at: new Date().toISOString(),
- ...(prep.cluster === 'mainnet'
- ? { pumpfun_url: `https://pump.fun/${prep.mint}` }
- : {
- explorer_url: `https://explorer.solana.com/address/${prep.mint}?cluster=devnet`,
- }),
- ...(prep.payload.initial_buy_sol > 0
- ? { initial_buy_sol: prep.payload.initial_buy_sol }
- : {}),
- };
-
- const mergedMeta = { ...(agent.meta || {}), token };
- const [updated] = await sql`
- update agent_identities
- set meta = ${JSON.stringify(mergedMeta)}::jsonb,
- updated_at = now()
- where id = ${agent.id}
- returning id, name, description, wallet_address, meta, created_at
- `;
-
- await sql`delete from token_launches_pending where id = ${prep.id}`;
-
- return json(res, 201, {
- ok: true,
- agent: { ...updated, token, home_url: `${env.APP_ORIGIN}/agent/${updated.id}` },
- });
-});
diff --git a/api/agents/tokens/launch-prep.js b/api/agents/tokens/launch-prep.js
deleted file mode 100644
index 9d4ab1384..000000000
--- a/api/agents/tokens/launch-prep.js
+++ /dev/null
@@ -1,261 +0,0 @@
-/**
- * POST /api/agents/tokens/launch-prep
- *
- * Build an unsigned Pump.fun coin-creation transaction for the user to sign.
- *
- * Flow:
- * 1. Verify the agent belongs to caller and was deployed on Solana.
- * 2. Verify caller's wallet matches the agent's owner wallet.
- * 3. Pin token metadata JSON (name/symbol/description/image) to IPFS.
- * 4. Generate a fresh mint Keypair, build the create instruction via
- * @pump-fun/pump-sdk, partial-sign with the mint, return base64.
- * 5. Persist a prep record (`token_launches_pending`) the confirm endpoint
- * validates against.
- *
- * The mint Keypair is destroyed after partial-signing — its signature is now
- * embedded in the serialized tx bytes, so we never need to retain the secret.
- */
-
-import { z } from 'zod';
-import {
- Connection,
- Keypair,
- PublicKey,
- Transaction,
- ComputeBudgetProgram,
- SystemProgram,
-} from '@solana/web3.js';
-import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
-import BN from 'bn.js';
-
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { parse } from '../../_lib/validate.js';
-import { randomToken } from '../../_lib/crypto.js';
-import { env } from '../../_lib/env.js';
-import { r2 } from '../../_lib/r2.js';
-import { PutObjectCommand } from '@aws-sdk/client-s3';
-import { createHash } from 'crypto';
-
-const bodySchema = z.object({
- agent_id: z.string().min(1).max(80),
- provider: z.literal('pumpfun'),
- cluster: z.enum(['mainnet', 'devnet']),
- wallet_address: z.string().min(32).max(44),
- name: z.string().trim().min(1).max(32),
- // Pump.fun caps symbols at ~10 chars; let's be permissive but clamped.
- symbol: z
- .string()
- .trim()
- .min(2)
- .max(10)
- .regex(/^[A-Za-z0-9]+$/, 'symbol must be alphanumeric'),
- description: z.string().trim().max(280).default(''),
- image: z.string().url().or(z.literal('')).default(''),
- initial_buy_sol: z.number().min(0).max(50).default(0),
-});
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-async function pinTokenMetadata({ name, symbol, description, image }) {
- const json = {
- name,
- symbol,
- description,
- image,
- showName: true,
- createdOn: 'three.ws',
- };
- const bytes = Buffer.from(JSON.stringify(json), 'utf-8');
- const token = process.env.WEB3_STORAGE_TOKEN;
- if (token) {
- try {
- const r = await fetch('https://api.web3.storage/upload', {
- method: 'POST',
- headers: { Authorization: `Bearer ${token}` },
- body: bytes,
- });
- if (r.ok) {
- const data = await r.json();
- if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };
- }
- } catch (e) {
- console.warn('[token launch-prep] web3.storage pin failed:', e.message);
- }
- }
- const hash = createHash('sha256').update(bytes).digest('hex');
- const stub = `bafkreigenerated${hash.slice(0, 40)}`;
- const key = `token-metadata/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
- await r2.send(
- new PutObjectCommand({
- Bucket: env.S3_BUCKET,
- Key: key,
- Body: bytes,
- ContentType: 'application/json',
- }),
- );
- return { cid: stub, uri: `ipfs://${stub}` };
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- // Resolve agent + ownership + Solana deploy state
- const [agent] = await sql`
- select id, name, user_id, wallet_address, meta
- from agent_identities
- where id = ${body.agent_id} and user_id = ${user.id} and deleted_at is null
- limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
-
- const onchain = agent.meta?.onchain;
- if (!onchain || onchain.family !== 'solana') {
- return error(
- res,
- 409,
- 'precondition_failed',
- 'agent must be deployed on Solana before launching a token',
- );
- }
- if (onchain.wallet?.toLowerCase?.() !== body.wallet_address.toLowerCase?.()) {
- // Solana addresses are case-sensitive; equality check is exact.
- if (onchain.wallet !== body.wallet_address) {
- return error(res, 403, 'forbidden', 'wallet does not match agent owner');
- }
- }
- if (agent.meta?.token?.mint) {
- return error(res, 409, 'conflict', 'agent already has a launched token');
- }
-
- // 3. Pin token metadata
- const { cid, uri: metadataUri } = await pinTokenMetadata({
- name: body.name,
- symbol: body.symbol,
- description: body.description,
- image: body.image,
- });
-
- // 4. Build the launch tx
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
- const sdk = new PumpSdk(conn);
-
- const mintKeypair = Keypair.generate();
- const creator = new PublicKey(body.wallet_address);
- const userPk = creator;
-
- const ixs = [
- // Bump compute budget — coin creation routinely exceeds the 200k default.
- ComputeBudgetProgram.setComputeUnitLimit({ units: 350_000 }),
- ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 100_000 }),
- ];
-
- if (body.initial_buy_sol > 0) {
- const global = await sdk.fetchGlobal();
- const lamports = new BN(Math.floor(body.initial_buy_sol * 1_000_000_000));
- const tokenAmount = getBuyTokenAmountFromSolAmount({
- global,
- feeConfig: null,
- mintSupply: null,
- bondingCurve: null,
- amount: lamports,
- });
- const launchIxs = await sdk.createAndBuyInstructions({
- global,
- mint: mintKeypair.publicKey,
- name: body.name,
- symbol: body.symbol,
- uri: metadataUri,
- creator,
- user: userPk,
- amount: tokenAmount,
- solAmount: lamports,
- });
- ixs.push(...launchIxs);
- } else {
- const ix = await sdk.createV2Instruction({
- mint: mintKeypair.publicKey,
- name: body.name,
- symbol: body.symbol,
- uri: metadataUri,
- creator,
- user: userPk,
- mayhemMode: false,
- });
- ixs.push(ix);
- }
-
- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
- const tx = new Transaction({
- feePayer: creator,
- blockhash,
- lastValidBlockHeight,
- }).add(...ixs);
-
- // Partial-sign with the mint keypair. The user's wallet adds the creator
- // signature client-side before submission. After this serialize, the mint
- // secret key is no longer needed and goes out of scope.
- tx.partialSign(mintKeypair);
-
- const txBase64 = tx
- .serialize({ requireAllSignatures: false, verifySignatures: false })
- .toString('base64');
-
- // 5. Persist prep
- const prepId = await randomToken(24);
- const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
-
- await sql`
- insert into token_launches_pending
- (id, user_id, agent_id, provider, cluster, mint, metadata_uri, cid, payload, expires_at)
- values (
- ${prepId},
- ${user.id},
- ${agent.id},
- 'pumpfun',
- ${body.cluster},
- ${mintKeypair.publicKey.toBase58()},
- ${metadataUri},
- ${cid},
- ${JSON.stringify({
- name: body.name,
- symbol: body.symbol,
- description: body.description,
- image: body.image,
- initial_buy_sol: body.initial_buy_sol,
- wallet_address: body.wallet_address,
- })}::jsonb,
- ${expiresAt}
- )
- on conflict (id) do nothing
- `;
-
- return json(res, 201, {
- prep_id: prepId,
- mint: mintKeypair.publicKey.toBase58(),
- tx_base64: txBase64,
- metadata_uri: metadataUri,
- cluster: body.cluster,
- expires_at: expiresAt.toISOString(),
- });
-});
-
-// Make sure SystemProgram import isn't tree-shaken away (some bundlers complain
-// about unused imports). It's a peer for compute-budget instructions on some
-// Pump.fun program versions.
-void SystemProgram;
diff --git a/api/agents/tokens/launch-quote.js b/api/agents/tokens/launch-quote.js
deleted file mode 100644
index 331d1edc2..000000000
--- a/api/agents/tokens/launch-quote.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/**
- * GET /api/agents/tokens/launch-quote?initial_buy_sol=0.5&cluster=mainnet
- *
- * Pre-flight cost estimate for a Pump.fun coin launch. Returned to the UI
- * before the user clicks "Launch" so they can see what the transaction will
- * cost from their wallet.
- *
- * Costs:
- * • Mint account rent ~ 0.00146 SOL (fixed; SystemProgram.createAccount)
- * • Bonding curve PDA rent ~ 0.00203 SOL (Pump.fun create instruction)
- * • Metadata account ~ 0.00561 SOL (Metaplex CPI inside create)
- * • Tx fee (1 sig) ~ 0.000005 SOL
- * • Initial buy user-provided lamports + ~1% protocol fee
- *
- * The exact rent numbers come from Pump.fun's program; we use conservative
- * upper bounds rather than fetching them per-request — they don't change.
- */
-
-import { z } from 'zod';
-import BN from 'bn.js';
-import { Connection } from '@solana/web3.js';
-import { PumpSdk, getBuyTokenAmountFromSolAmount } from '@pump-fun/pump-sdk';
-
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-
-const querySchema = z.object({
- initial_buy_sol: z.coerce.number().min(0).max(50).default(0),
- cluster: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-// Conservative upper bounds, in SOL.
-const FIXED_LAUNCH_COST = {
- mintRent: 0.00146,
- bondingCurveRent: 0.00203,
- metadataRent: 0.00561,
- txFee: 0.000005,
-};
-const FIXED_LAUNCH_TOTAL =
- FIXED_LAUNCH_COST.mintRent +
- FIXED_LAUNCH_COST.bondingCurveRent +
- FIXED_LAUNCH_COST.metadataRent +
- FIXED_LAUNCH_COST.txFee;
-
-function rpcUrl(cluster) {
- return cluster === 'devnet'
- ? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
- : process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const q = querySchema.parse({
- initial_buy_sol: url.searchParams.get('initial_buy_sol'),
- cluster: url.searchParams.get('cluster') || undefined,
- });
-
- let buyEstimate = null;
- if (q.initial_buy_sol > 0) {
- try {
- const conn = new Connection(rpcUrl(q.cluster), 'confirmed');
- const sdk = new PumpSdk(conn);
- const global = await sdk.fetchGlobal();
- const lamports = new BN(Math.floor(q.initial_buy_sol * 1_000_000_000));
- const tokensOut = getBuyTokenAmountFromSolAmount({
- global,
- feeConfig: null,
- mintSupply: null,
- bondingCurve: null,
- amount: lamports,
- });
- // Pump.fun protocol fee on initial buy is ~1%; surface as a separate
- // line so the user sees what's spent vs what funds the curve.
- buyEstimate = {
- sol: q.initial_buy_sol,
- tokens_out: tokensOut.toString(),
- protocol_fee_sol: q.initial_buy_sol * 0.01,
- };
- } catch (e) {
- // If RPC is unhealthy, return the structural estimate without the
- // curve quote — the UI can still show launch costs.
- console.warn('[launch-quote] RPC fetch failed:', e.message);
- }
- }
-
- const totalSol =
- FIXED_LAUNCH_TOTAL + q.initial_buy_sol + (buyEstimate?.protocol_fee_sol || 0);
-
- return json(res, 200, {
- cluster: q.cluster,
- fixed: FIXED_LAUNCH_COST,
- fixed_total_sol: FIXED_LAUNCH_TOTAL,
- initial_buy: buyEstimate,
- total_sol: totalSol,
- });
-});
diff --git a/api/auth/sessions/[action].js b/api/auth/sessions/[action].js
new file mode 100644
index 000000000..8c296948b
--- /dev/null
+++ b/api/auth/sessions/[action].js
@@ -0,0 +1,117 @@
+// Session endpoints — dispatched by req.query.action.
+// GET /api/auth/sessions → handleList (action undefined)
+// DELETE /api/auth/sessions → handleRevokeOthers (action undefined)
+// DELETE /api/auth/sessions/<uuid> → handleRevokeOne (action === <uuid>)
+//
+// Dispatcher convention: undefined action → index (GET list / DELETE
+// revoke-others-and-rotate), and any other action is treated as a session id
+// for individual revoke.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser, rotateSession, sessionCookie } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+
+ if (action === undefined || action === '' || action === null) {
+ return handleIndex(req, res);
+ }
+
+ return handleRevokeOne(req, res, action);
+});
+
+// ── Index: list (GET) and revoke-others (DELETE) ──────────────────────────
+
+async function handleIndex(req, res) {
+ if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'DELETE'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const rows = await sql`
+ select id, user_agent, ip, created_at, last_seen_at, expires_at
+ from sessions
+ where user_id = ${user.id}
+ and revoked_at is null
+ and expires_at > now()
+ order by last_seen_at desc nulls last
+ `;
+ const sessions = rows.map((s) => ({
+ id: s.id,
+ user_agent: s.user_agent,
+ ip: s.ip,
+ created_at: s.created_at,
+ last_seen_at: s.last_seen_at,
+ expires_at: s.expires_at,
+ is_current: s.id === user.sid,
+ }));
+ return json(res, 200, { sessions });
+ }
+
+ // DELETE — revoke all other sessions, then rotate the current one so the user
+ // stays signed in on this device with a fresh cookie ("log out everywhere else").
+ const ua = req.headers['user-agent'] || null;
+ const result = await sql`
+ update sessions
+ set revoked_at = now()
+ where user_id = ${user.id}
+ and revoked_at is null
+ and id != ${user.sid}
+ `;
+
+ // Rotate the current session so any stolen copy of this cookie is invalidated.
+ const newToken = await rotateSession({
+ currentSid: user.sid,
+ userId: user.id,
+ userAgent: ua,
+ ip,
+ });
+ const existing = res.getHeader('set-cookie') || [];
+ const arr = Array.isArray(existing) ? existing : [existing];
+ res.setHeader('set-cookie', [...arr, sessionCookie(newToken)]);
+
+ return json(res, 200, { revoked: result.count });
+}
+
+// ── Revoke one session by id ──────────────────────────────────────────────
+
+async function handleRevokeOne(req, res, sessionIdFromAction) {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthenticated', 'not signed in');
+
+ const sessionId = req.query.id || sessionIdFromAction || req.url.split('/').pop();
+ if (!UUID_REGEX.test(sessionId))
+ return error(res, 400, 'invalid_id', 'session id must be a valid UUID');
+
+ const rows = await sql`
+ select id from sessions
+ where id = ${sessionId} and user_id = ${user.id}
+ limit 1
+ `;
+
+ if (!rows[0]) return error(res, 404, 'not_found', 'session not found');
+
+ if (sessionId === user.sid)
+ return error(
+ res,
+ 409,
+ 'cannot_revoke_current',
+ 'use POST /api/auth/logout to end the current session',
+ );
+
+ await sql`update sessions set revoked_at = now() where id = ${sessionId}`;
+ return json(res, 200, { revoked: 1 });
+}
diff --git a/api/auth/sessions/[id].js b/api/auth/sessions/[id].js
deleted file mode 100644
index c16190744..000000000
--- a/api/auth/sessions/[id].js
+++ /dev/null
@@ -1,36 +0,0 @@
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-
-const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['DELETE'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthenticated', 'not signed in');
-
- const sessionId = req.query.id || req.url.split('/').pop();
- if (!UUID_REGEX.test(sessionId))
- return error(res, 400, 'invalid_id', 'session id must be a valid UUID');
-
- const rows = await sql`
- select id from sessions
- where id = ${sessionId} and user_id = ${user.id}
- limit 1
- `;
-
- if (!rows[0]) return error(res, 404, 'not_found', 'session not found');
-
- if (sessionId === user.sid)
- return error(
- res,
- 409,
- 'cannot_revoke_current',
- 'use POST /api/auth/logout to end the current session',
- );
-
- await sql`update sessions set revoked_at = now() where id = ${sessionId}`;
- return json(res, 200, { revoked: 1 });
-});
diff --git a/api/auth/sessions/index.js b/api/auth/sessions/index.js
deleted file mode 100644
index a6f8d4af0..000000000
--- a/api/auth/sessions/index.js
+++ /dev/null
@@ -1,61 +0,0 @@
-import { sql } from '../../_lib/db.js';
-import { getSessionUser, rotateSession, sessionCookie } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'DELETE'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthenticated', 'not signed in');
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- if (req.method === 'GET') {
- const rows = await sql`
- select id, user_agent, ip, created_at, last_seen_at, expires_at
- from sessions
- where user_id = ${user.id}
- and revoked_at is null
- and expires_at > now()
- order by last_seen_at desc nulls last
- `;
- const sessions = rows.map((s) => ({
- id: s.id,
- user_agent: s.user_agent,
- ip: s.ip,
- created_at: s.created_at,
- last_seen_at: s.last_seen_at,
- expires_at: s.expires_at,
- is_current: s.id === user.sid,
- }));
- return json(res, 200, { sessions });
- }
-
- // DELETE — revoke all other sessions, then rotate the current one so the user
- // stays signed in on this device with a fresh cookie ("log out everywhere else").
- const ua = req.headers['user-agent'] || null;
- const result = await sql`
- update sessions
- set revoked_at = now()
- where user_id = ${user.id}
- and revoked_at is null
- and id != ${user.sid}
- `;
-
- // Rotate the current session so any stolen copy of this cookie is invalidated.
- const newToken = await rotateSession({
- currentSid: user.sid,
- userId: user.id,
- userAgent: ua,
- ip,
- });
- const existing = res.getHeader('set-cookie') || [];
- const arr = Array.isArray(existing) ? existing : [existing];
- res.setHeader('set-cookie', [...arr, sessionCookie(newToken)]);
-
- return json(res, 200, { revoked: result.count });
-});
diff --git a/api/auth/siwe/verify.js b/api/auth/siwe/[action].js
similarity index 80%
rename from api/auth/siwe/verify.js
rename to api/auth/siwe/[action].js
index 09adf5a41..fde6da231 100644
--- a/api/auth/siwe/verify.js
+++ b/api/auth/siwe/[action].js
@@ -1,5 +1,6 @@
-// Verify an EIP-4361 (Sign-In with Ethereum) message + signature.
-// On success: create or link a user, issue a browser session cookie.
+// SIWE (Sign-In with Ethereum) endpoints — dispatched by req.query.action.
+// GET /api/auth/siwe/nonce → handleNonce
+// POST /api/auth/siwe/verify → handleVerify
import { verifyMessage, getAddress } from 'ethers';
import { z } from 'zod';
@@ -7,19 +8,70 @@ import { sql } from '../../_lib/db.js';
import { createSession, sessionCookie, destroySession } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { randomToken, hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { env } from '../../_lib/env.js';
import { parse } from '../../_lib/validate.js';
-import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { sendWelcomeEmail } from '../../_lib/email.js';
+const NONCE_TTL_SEC = 5 * 60;
+const CSRF_COOKIE = '__Host-csrf-siwe';
+
const verifyBody = z.object({
message: z.string().min(64).max(4000),
signature: z.string().regex(/^0x[a-fA-F0-9]+$/),
});
-const CSRF_COOKIE = '__Host-csrf-siwe';
-
export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ if (action === 'nonce') return handleNonce(req, res);
+ if (action === 'verify') return handleVerify(req, res);
+ return error(res, 404, 'not_found', 'unknown siwe action');
+});
+
+// ── Nonce ──────────────────────────────────────────────────────────────────
+// Issue a one-time nonce for Sign-In with Ethereum (EIP-4361).
+// The client includes this nonce in the message they sign; /verify burns it.
+
+async function handleNonce(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');
+
+ // EIP-4361 requires ≥8 alphanumeric chars. Strip base64url's - and _.
+ // 22 chars ≈ 131 bits of entropy (log2(62^22) ≈ 131).
+ let nonce = '';
+ while (nonce.length < 22) {
+ nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');
+ }
+ nonce = nonce.slice(0, 22);
+
+ await sql`
+ insert into siwe_nonces (nonce, expires_at)
+ values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)
+ `;
+
+ // Issue a CSRF token tied to a temporary cookie (not session-based).
+ const csrfRaw = randomToken(32);
+ const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siwe:${csrfRaw}`);
+ res.setHeader(
+ 'set-cookie',
+ `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${NONCE_TTL_SEC}`,
+ );
+
+ const issuedAt = new Date().toISOString();
+ const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
+
+ return json(res, 200, { nonce, issuedAt, expiresAt, csrf, ttl: NONCE_TTL_SEC });
+}
+
+// ── Verify ─────────────────────────────────────────────────────────────────
+// Verify an EIP-4361 (Sign-In with Ethereum) message + signature.
+// On success: create or link a user, issue a browser session cookie.
+
+async function handleVerify(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -217,7 +269,7 @@ export default wrap(async (req, res) => {
user: userRow,
wallet: { address: claimed, chain_id: chainId },
});
-});
+}
// ─── EIP-4361 parser ────────────────────────────────────────────────────────
// Minimal hand-rolled parser. We only need the fields we actually verify.
diff --git a/api/auth/siwe/nonce.js b/api/auth/siwe/nonce.js
deleted file mode 100644
index cdc5b9291..000000000
--- a/api/auth/siwe/nonce.js
+++ /dev/null
@@ -1,47 +0,0 @@
-// Issue a one-time nonce for Sign-In with Ethereum (EIP-4361).
-// The client includes this nonce in the message they sign; /verify burns it.
-
-import { sql } from '../../_lib/db.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { randomToken } from '../../_lib/crypto.js';
-import { hmacSha256 } from '../../_lib/crypto.js';
-import { env } from '../../_lib/env.js';
-
-const NONCE_TTL_SEC = 5 * 60;
-const CSRF_COOKIE = '__Host-csrf-siwe';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');
-
- // EIP-4361 requires ≥8 alphanumeric chars. Strip base64url's - and _.
- // 22 chars ≈ 131 bits of entropy (log2(62^22) ≈ 131).
- let nonce = '';
- while (nonce.length < 22) {
- nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');
- }
- nonce = nonce.slice(0, 22);
-
- await sql`
- insert into siwe_nonces (nonce, expires_at)
- values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)
- `;
-
- // Issue a CSRF token tied to a temporary cookie (not session-based).
- const csrfRaw = randomToken(32);
- const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siwe:${csrfRaw}`);
- res.setHeader(
- 'set-cookie',
- `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${NONCE_TTL_SEC}`,
- );
-
- const issuedAt = new Date().toISOString();
- const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
-
- return json(res, 200, { nonce, issuedAt, expiresAt, csrf, ttl: NONCE_TTL_SEC });
-});
diff --git a/api/auth/siws/verify.js b/api/auth/siws/[action].js
similarity index 76%
rename from api/auth/siws/verify.js
rename to api/auth/siws/[action].js
index 1517bb34f..44e4962a3 100644
--- a/api/auth/siws/verify.js
+++ b/api/auth/siws/[action].js
@@ -1,6 +1,6 @@
-// Verify a Sign-In with Solana (CAIP-122 / SIP-0) message + ed25519 signature.
-// On success: create or link a user, issue a browser session cookie.
-// Mirrors /api/auth/siwe/verify.js — same session/user logic, different sig check.
+// SIWS (Sign-In with Solana) endpoints — dispatched by req.query.action.
+// GET /api/auth/siws/nonce → handleNonce
+// POST /api/auth/siws/verify → handleVerify
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
@@ -9,20 +9,70 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
import { parse } from '../../_lib/validate.js';
-import { hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
+import { randomToken, hmacSha256, constantTimeEquals } from '../../_lib/crypto.js';
import { parseSiwsMessage, verifySiwsSignature } from '../../_lib/siws.js';
import { sendWelcomeEmail } from '../../_lib/email.js';
+const NONCE_TTL_SEC = 5 * 60;
+const CSRF_COOKIE = '__Host-csrf-siws';
+const ALLOWED_CHAIN_IDS = new Set(['mainnet', 'devnet', 'testnet']);
+
const verifyBody = z.object({
message: z.string().min(32).max(4000),
// base58 (Phantom) or base64 (other wallets) encoded 64-byte ed25519 signature
signature: z.string().min(1).max(256),
});
-const CSRF_COOKIE = '__Host-csrf-siws';
-const ALLOWED_CHAIN_IDS = new Set(['mainnet', 'devnet', 'testnet']);
-
export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ if (action === 'nonce') return handleNonce(req, res);
+ if (action === 'verify') return handleVerify(req, res);
+ return error(res, 404, 'not_found', 'unknown siws action');
+});
+
+// ── Nonce ──────────────────────────────────────────────────────────────────
+// Issue a one-time nonce for Sign-In with Solana (CAIP-122 / SIP-0).
+// Mirrors /api/auth/siwe/nonce.js — same burn-on-verify replay protection.
+
+async function handleNonce(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');
+
+ // 22 alphanumeric chars ≈ 131 bits of entropy.
+ let nonce = '';
+ while (nonce.length < 22) {
+ nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');
+ }
+ nonce = nonce.slice(0, 22);
+
+ await sql`
+ insert into siws_nonces (nonce, expires_at)
+ values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)
+ `;
+
+ const csrfRaw = randomToken(32);
+ const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siws:${csrfRaw}`);
+ res.setHeader(
+ 'set-cookie',
+ `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${NONCE_TTL_SEC}`,
+ );
+
+ const issuedAt = new Date().toISOString();
+ const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
+
+ return json(res, 200, { nonce, issuedAt, expiresAt, csrf, ttl: NONCE_TTL_SEC });
+}
+
+// ── Verify ─────────────────────────────────────────────────────────────────
+// Verify a Sign-In with Solana (CAIP-122 / SIP-0) message + ed25519 signature.
+// On success: create or link a user, issue a browser session cookie.
+// Mirrors /api/auth/siwe/verify.js — same session/user logic, different sig check.
+
+async function handleVerify(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
@@ -198,7 +248,7 @@ export default wrap(async (req, res) => {
user: userRow,
wallet: { address: addr, chain_type: 'solana', chain_id: fields.chainId || 'mainnet' },
});
-});
+}
function shortAddr(addr) {
return `${addr.slice(0, 4)}…${addr.slice(-4)}`;
diff --git a/api/auth/siws/nonce.js b/api/auth/siws/nonce.js
deleted file mode 100644
index 9ef735a49..000000000
--- a/api/auth/siws/nonce.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// Issue a one-time nonce for Sign-In with Solana (CAIP-122 / SIP-0).
-// Mirrors /api/auth/siwe/nonce.js — same burn-on-verify replay protection.
-
-import { sql } from '../../_lib/db.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { randomToken, hmacSha256 } from '../../_lib/crypto.js';
-import { env } from '../../_lib/env.js';
-
-const NONCE_TTL_SEC = 5 * 60;
-const CSRF_COOKIE = '__Host-csrf-siws';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many nonce requests');
-
- // 22 alphanumeric chars ≈ 131 bits of entropy.
- let nonce = '';
- while (nonce.length < 22) {
- nonce += randomToken(24).replace(/[^A-Za-z0-9]/g, '');
- }
- nonce = nonce.slice(0, 22);
-
- await sql`
- insert into siws_nonces (nonce, expires_at)
- values (${nonce}, now() + ${`${NONCE_TTL_SEC} seconds`}::interval)
- `;
-
- const csrfRaw = randomToken(32);
- const csrf = await hmacSha256(env.JWT_SECRET, `csrf-siws:${csrfRaw}`);
- res.setHeader(
- 'set-cookie',
- `${CSRF_COOKIE}=${csrfRaw}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${NONCE_TTL_SEC}`,
- );
-
- const issuedAt = new Date().toISOString();
- const expiresAt = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
-
- return json(res, 200, { nonce, issuedAt, expiresAt, csrf, ttl: NONCE_TTL_SEC });
-});
diff --git a/api/auth/wallets/index.js b/api/auth/wallets/[action].js
similarity index 50%
rename from api/auth/wallets/index.js
rename to api/auth/wallets/[action].js
index d2e442132..ee7fc0d7f 100644
--- a/api/auth/wallets/index.js
+++ b/api/auth/wallets/[action].js
@@ -1,4 +1,13 @@
-// Link new wallets to authenticated user + list existing wallets.
+// Wallet endpoints — dispatched by req.query.action.
+// GET /api/auth/wallets → handleListWallets (action undefined)
+// POST /api/auth/wallets → handleLinkWallet (action undefined)
+// POST /api/auth/wallets/nonce → handleNonce (action === 'nonce')
+// DELETE /api/auth/wallets/<address> → handleUnlinkWallet (action === <address>)
+//
+// Dispatcher convention: undefined action → index (GET/POST), the literal
+// "nonce" → nonce issuance, and anything else is treated as an address for
+// DELETE. _link-nonces.js remains a separate helper (underscore-prefixed,
+// not file-routed by Vercel).
import { verifyMessage, getAddress } from 'ethers';
import { z } from 'zod';
@@ -8,14 +17,39 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
import { parseSiweMessage } from '../../_lib/siwe.js';
import { env } from '../../_lib/env.js';
-import { consumeNonce } from './_link-nonces.js';
+import { issueNonce, consumeNonce, NONCE_TTL_SEC } from './_link-nonces.js';
const linkBody = z.object({
message: z.string().min(64).max(4000),
signature: z.string().regex(/^0x[a-fA-F0-9]+$/),
});
+const nonceBody = z.object({
+ address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),
+ chainId: z.number().int().positive(),
+});
+
export default wrap(async (req, res) => {
+ const action = req.query?.action;
+
+ // /api/auth/wallets — list (GET) or link (POST)
+ if (action === undefined || action === '' || action === null) {
+ return handleIndex(req, res);
+ }
+
+ // /api/auth/wallets/nonce — issue link nonce
+ if (action === 'nonce') {
+ return handleNonce(req, res);
+ }
+
+ // /api/auth/wallets/<address> — unlink wallet (action carries the address)
+ return handleUnlinkWallet(req, res, action);
+});
+
+// ── Index: list (GET) and link (POST) ──────────────────────────────────────
+// Link new wallets to authenticated user + list existing wallets.
+
+async function handleIndex(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
const session = await getSessionUser(req);
@@ -26,7 +60,7 @@ export default wrap(async (req, res) => {
} else if (req.method === 'POST') {
return handleLinkWallet(session.id, req, res);
} else if (!method(req, res, ['GET', 'POST'])) return;
-});
+}
async function handleListWallets(userId, res) {
const rows = await sql`
@@ -142,3 +176,92 @@ async function handleLinkWallet(userId, req, res) {
return json(res, 201, { wallet: { address: claimed, chain_id: chainId } });
}
+
+// ── Nonce ──────────────────────────────────────────────────────────────────
+// Issue a nonce + EIP-4361 (SIWE) message for wallet linking.
+// Caller must already be authenticated; the resulting message ties the wallet
+// signature to the active session's user.
+
+async function handleNonce(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const { address, chainId } = parse(nonceBody, await readJson(req));
+
+ const nonce = issueNonce(session.id);
+
+ const appOrigin = env.APP_ORIGIN;
+ const domain = new URL(appOrigin).host;
+ const issuedAt = new Date().toISOString();
+ const expirationTime = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
+
+ const message = [
+ `${domain} wants you to sign in with your Ethereum account:`,
+ address,
+ ``,
+ `Link this wallet to three.ws account ${session.email}`,
+ ``,
+ `URI: ${appOrigin}`,
+ `Version: 1`,
+ `Chain ID: ${chainId}`,
+ `Nonce: ${nonce}`,
+ `Issued At: ${issuedAt}`,
+ `Expiration Time: ${expirationTime}`,
+ ].join('\n');
+
+ return json(res, 200, { nonce, message, ttl: NONCE_TTL_SEC });
+}
+
+// ── Unlink ─────────────────────────────────────────────────────────────────
+// Unlink a wallet from authenticated user.
+// Refuse if it's the only wallet AND user has no email+password.
+
+async function handleUnlinkWallet(req, res, address) {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ if (!address) return error(res, 400, 'missing_address', 'address required');
+
+ const addrLower = address.toLowerCase();
+
+ // 1. Check that this wallet belongs to the user.
+ const [wallet] = await sql`
+ select id from user_wallets
+ where user_id = ${session.id} and address = ${addrLower}
+ limit 1
+ `;
+ if (!wallet) return error(res, 404, 'not_found', 'wallet not found');
+
+ // 2. Check if this is the only wallet.
+ const [count] = await sql`
+ select count(*) as n from user_wallets
+ where user_id = ${session.id}
+ `;
+ const walletCount = count.n;
+
+ if (walletCount === 1) {
+ // 3. If only wallet, check if user has password-based auth.
+ const [user] = await sql`
+ select password_hash from users where id = ${session.id} limit 1
+ `;
+ if (!user.password_hash) {
+ return error(
+ res,
+ 400,
+ 'cannot_remove_last_wallet',
+ 'cannot remove the last wallet if account has no password',
+ );
+ }
+ }
+
+ // 4. Delete the wallet.
+ await sql`delete from user_wallets where user_id = ${session.id} and address = ${addrLower}`;
+
+ return json(res, 200, { removed: true });
+}
diff --git a/api/auth/wallets/[address].js b/api/auth/wallets/[address].js
deleted file mode 100644
index 805e28f6f..000000000
--- a/api/auth/wallets/[address].js
+++ /dev/null
@@ -1,54 +0,0 @@
-// Unlink a wallet from authenticated user.
-// Refuse if it's the only wallet AND user has no email+password.
-
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['DELETE'])) return;
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const { address } = req.query;
- if (!address) return error(res, 400, 'missing_address', 'address required');
-
- const addrLower = address.toLowerCase();
-
- // 1. Check that this wallet belongs to the user.
- const [wallet] = await sql`
- select id from user_wallets
- where user_id = ${session.id} and address = ${addrLower}
- limit 1
- `;
- if (!wallet) return error(res, 404, 'not_found', 'wallet not found');
-
- // 2. Check if this is the only wallet.
- const [count] = await sql`
- select count(*) as n from user_wallets
- where user_id = ${session.id}
- `;
- const walletCount = count.n;
-
- if (walletCount === 1) {
- // 3. If only wallet, check if user has password-based auth.
- const [user] = await sql`
- select password_hash from users where id = ${session.id} limit 1
- `;
- if (!user.password_hash) {
- return error(
- res,
- 400,
- 'cannot_remove_last_wallet',
- 'cannot remove the last wallet if account has no password',
- );
- }
- }
-
- // 4. Delete the wallet.
- await sql`delete from user_wallets where user_id = ${session.id} and address = ${addrLower}`;
-
- return json(res, 200, { removed: true });
-});
diff --git a/api/auth/wallets/nonce.js b/api/auth/wallets/nonce.js
deleted file mode 100644
index 69e1ad67b..000000000
--- a/api/auth/wallets/nonce.js
+++ /dev/null
@@ -1,48 +0,0 @@
-// Issue a nonce + EIP-4361 (SIWE) message for wallet linking.
-// Caller must already be authenticated; the resulting message ties the wallet
-// signature to the active session's user.
-
-import { z } from 'zod';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { parse } from '../../_lib/validate.js';
-import { env } from '../../_lib/env.js';
-import { issueNonce, NONCE_TTL_SEC } from './_link-nonces.js';
-
-const nonceBody = z.object({
- address: z.string().regex(/^0x[a-fA-F0-9]{40}$/),
- chainId: z.number().int().positive(),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const { address, chainId } = parse(nonceBody, await readJson(req));
-
- const nonce = issueNonce(session.id);
-
- const appOrigin = env.APP_ORIGIN;
- const domain = new URL(appOrigin).host;
- const issuedAt = new Date().toISOString();
- const expirationTime = new Date(Date.now() + NONCE_TTL_SEC * 1000).toISOString();
-
- const message = [
- `${domain} wants you to sign in with your Ethereum account:`,
- address,
- ``,
- `Link this wallet to three.ws account ${session.email}`,
- ``,
- `URI: ${appOrigin}`,
- `Version: 1`,
- `Chain ID: ${chainId}`,
- `Nonce: ${nonce}`,
- `Issued At: ${issuedAt}`,
- `Expiration Time: ${expirationTime}`,
- ].join('\n');
-
- return json(res, 200, { nonce, message, ttl: NONCE_TTL_SEC });
-});
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
new file mode 100644
index 000000000..1f591d23e
--- /dev/null
+++ b/api/avatars/[id]/[action].js
@@ -0,0 +1,452 @@
+// Dispatcher for /api/avatars/:id/:action
+// Vercel populates req.query.id (from [id] parent dir) and req.query.action
+// (from [action] filename) automatically. Each handler below is unchanged
+// from its prior single-file form.
+
+import { GetObjectCommand } from '@aws-sdk/client-s3';
+import { z } from 'zod';
+
+import {
+ getSessionUser,
+ authenticateBearer,
+ extractBearer,
+ hasScope,
+} from '../../_lib/auth.js';
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+import {
+ readStorageMode,
+ storageModeSchema,
+ defaultStorageMode,
+} from '../../_lib/storage-mode.js';
+import { getAvatar, resolveAvatarUrl } from '../../_lib/avatars.js';
+import { r2 } from '../../_lib/r2.js';
+import { env } from '../../_lib/env.js';
+
+const PINATA_ENDPOINT = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'glb-versions':
+ return handleGlbVersions(req, res);
+ case 'pin-ipfs':
+ return handlePinIpfs(req, res);
+ case 'rollback':
+ return handleRollback(req, res);
+ case 'session':
+ return handleSession(req, res);
+ case 'storage-mode':
+ return handleStorageMode(req, res);
+ case 'versions':
+ return handleVersions(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown avatar action');
+ }
+});
+
+// ── glb-versions ───────────────────────────────────────────────────────────
+
+async function handleGlbVersions(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
+ const [avatar] = await sql`
+ select id from avatars
+ where id = ${id} and owner_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
+
+ const rows = await sql`
+ select id, glb_url, created_at, metadata
+ from avatar_versions
+ where avatar_id = ${id}
+ order by created_at desc
+ limit 50
+ `;
+
+ return json(res, 200, {
+ versions: rows.map((v) => ({
+ id: v.id,
+ glbUrl: v.glb_url,
+ createdAt: v.created_at,
+ metadata: v.metadata ?? null,
+ })),
+ });
+}
+
+// ── pin-ipfs ───────────────────────────────────────────────────────────────
+
+async function handlePinIpfs(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id =
+ req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [row] = await sql`
+ SELECT id, owner_id, checksum_sha256, storage_key, content_type, name
+ FROM avatars WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+ if (row.owner_id !== session.id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const mode = await readStorageMode(id);
+ if (!mode) return error(res, 500, 'internal', 'storage_mode unavailable');
+
+ const pinataJwt = env.PINATA_JWT;
+ let cid;
+ let isStub = false;
+
+ if (pinataJwt && row.storage_key) {
+ try {
+ cid = await pinToPinata({
+ jwt: pinataJwt,
+ key: row.storage_key,
+ name: row.name || `avatar-${id}`,
+ contentType: row.content_type || 'model/gltf-binary',
+ });
+ } catch (err) {
+ return error(res, 502, 'upstream_error', `Pinata upload failed: ${err.message}`);
+ }
+ } else {
+ isStub = true;
+ cid = row.checksum_sha256 ? `stub:sha256-${row.checksum_sha256}` : `stub:no-hash-${id}`;
+ }
+
+ const next = {
+ ...mode,
+ ipfs: { pinned: true, cid, pinned_at: new Date().toISOString() },
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(next)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: next, stub: isStub });
+}
+
+async function pinToPinata({ jwt, key, name, contentType }) {
+ const obj = await r2.send(new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }));
+ const bytes = await streamToBuffer(obj.Body);
+ const blob = new Blob([bytes], { type: contentType });
+
+ const form = new FormData();
+ form.append('file', blob, name);
+ form.append('pinataMetadata', JSON.stringify({ name }));
+
+ const res = await fetch(PINATA_ENDPOINT, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${jwt}` },
+ body: form,
+ });
+ if (!res.ok) {
+ const body = await res.text().catch(() => '');
+ throw new Error(`HTTP ${res.status} ${body.slice(0, 200)}`);
+ }
+ const data = await res.json();
+ if (!data?.IpfsHash) throw new Error('no IpfsHash in Pinata response');
+ return data.IpfsHash;
+}
+
+async function streamToBuffer(stream) {
+ if (stream instanceof Uint8Array) return stream;
+ if (typeof stream?.transformToByteArray === 'function') {
+ return stream.transformToByteArray();
+ }
+ const chunks = [];
+ for await (const chunk of stream) chunks.push(chunk);
+ return Buffer.concat(chunks);
+}
+
+// ── rollback ───────────────────────────────────────────────────────────────
+
+const rollbackBodySchema = z.object({
+ versionId: z.coerce.number().int().positive(),
+});
+
+async function handleRollback(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
+ const userId = session?.id ?? bearer.userId;
+
+ const rl = await limits.avatarRollback(userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const { versionId } = parse(rollbackBodySchema, await readJson(req));
+
+ const [avatar] = await sql`
+ select id from avatars
+ where id = ${id} and owner_id = ${userId} and deleted_at is null
+ limit 1
+ `;
+ if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
+
+ const [ver] = await sql`
+ select id, glb_url from avatar_versions
+ where id = ${versionId} and avatar_id = ${id}
+ limit 1
+ `;
+ if (!ver) return error(res, 404, 'not_found', 'version not found');
+
+ const [updated] = await sql`
+ update avatars
+ set storage_key = ${ver.glb_url}, updated_at = now()
+ where id = ${id} and owner_id = ${userId}
+ returning id, owner_id, slug, name, description, storage_key, size_bytes,
+ content_type, source, visibility, tags, version, created_at, updated_at
+ `;
+
+ await sql`
+ insert into avatar_versions (avatar_id, glb_url, metadata, created_by)
+ values (
+ ${id},
+ ${ver.glb_url},
+ ${JSON.stringify({ rollback_of: versionId })}::jsonb,
+ ${userId}
+ )
+ `;
+
+ return json(res, 200, { ok: true, avatar: updated });
+}
+
+// ── session ────────────────────────────────────────────────────────────────
+
+async function handleSession(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveSessionAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.upload(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests, try again later');
+
+ // 404 (not 403) when not found or not owned — mirrors [id].js.
+ const avatar = await getAvatar({ id, requesterId: auth.userId });
+ if (!avatar || avatar.owner_id !== auth.userId) {
+ return error(res, 404, 'not_found', 'avatar not found');
+ }
+
+ if (!env.AVATURN_API_KEY) {
+ return error(
+ res,
+ 501,
+ 'not_configured',
+ 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',
+ );
+ }
+
+ // Resolve a time-limited URL the Avaturn upstream can fetch (works for private too).
+ const { url: glbUrl } = await resolveAvatarUrl(avatar, { expiresIn: 3600 });
+
+ try {
+ const result = await createAvaturnEditSession({
+ apiKey: env.AVATURN_API_KEY,
+ apiUrl: env.AVATURN_API_URL,
+ userId: auth.userId,
+ avatarUrl: glbUrl,
+ });
+ return json(res, 200, result);
+ } catch (err) {
+ const status = err?.status || 502;
+ const code = err?.code || 'upstream_error';
+ const message = err?.message || 'avatar provider rejected request';
+ if (status >= 500) console.error('[avatars/session] upstream failure:', err);
+ return error(res, status >= 500 ? 502 : status, code, message);
+ }
+}
+
+async function resolveSessionAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) return null;
+ if (!hasScope(bearer.scope, 'avatars:write')) return null;
+ return { userId: bearer.userId };
+}
+
+/**
+ * Opens an existing avatar in Avaturn for editing.
+ * Passes `avatar_url` so Avaturn pre-populates the editor with the existing mesh.
+ * If Avaturn's API uses a different field (e.g. `avatarUrl`, `model_url`), update
+ * the payload mapping below and the AVATURN_API_URL env var accordingly.
+ */
+async function createAvaturnEditSession({ apiKey, apiUrl, userId, avatarUrl }) {
+ const url = `${apiUrl}/api/v1/sessions`;
+ const payload = {
+ external_user_id: userId,
+ avatar_url: avatarUrl,
+ };
+
+ const upstream = await fetch(url, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ },
+ body: JSON.stringify(payload),
+ });
+
+ if (!upstream.ok) {
+ const text = await upstream.text().catch(() => '');
+ const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);
+ err.status = upstream.status >= 500 ? 502 : upstream.status;
+ err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';
+ throw err;
+ }
+
+ const data = await upstream.json();
+ const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
+ if (!sessionUrl) {
+ const err = new Error('avaturn response missing session_url');
+ err.status = 502;
+ err.code = 'upstream_error';
+ throw err;
+ }
+ return { session_url: sessionUrl, expires_at: data.expires_at ?? null };
+}
+
+// ── storage-mode ───────────────────────────────────────────────────────────
+
+async function handleStorageMode(req, res) {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const id =
+ req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
+ if (!id) return error(res, 400, 'validation_error', 'avatar id required');
+
+ const [row] = await sql`
+ SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'avatar not found');
+
+ if (req.method === 'GET') {
+ if (row.visibility === 'private') {
+ const session = await getSessionUser(req);
+ if (!session || session.id !== row.owner_id)
+ return error(res, 403, 'forbidden', 'private avatar');
+ }
+ const mode = await readStorageMode(id);
+ return json(res, 200, { storage_mode: mode });
+ }
+
+ // PUT — owner only
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+ if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
+
+ const body = parse(storageModeSchema, await readJson(req));
+
+ // Read current stored mode to preserve attestation fields — clients must not
+ // be able to forge tx_hash / chain_id / attested_at from the UI.
+ const current = await readStorageMode(id);
+ const safeBody = {
+ ...body,
+ attestation: current?.attestation ?? defaultStorageMode().attestation,
+ };
+
+ await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { storage_mode: safeBody });
+}
+
+// ── versions ───────────────────────────────────────────────────────────────
+
+async function handleVersions(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveVersionsAuth(req);
+
+ // Walk upward through parent_avatar_id to collect the full ancestor chain,
+ // then walk downward from the root to collect all descendants.
+ // Two-phase CTE keeps the query readable and avoids a self-join cycle.
+ const rows = await sql`
+ WITH RECURSIVE
+ ancestors AS (
+ SELECT id, parent_avatar_id, created_at
+ FROM avatars
+ WHERE id = ${id} AND deleted_at IS NULL
+ UNION ALL
+ SELECT a.id, a.parent_avatar_id, a.created_at
+ FROM avatars a
+ JOIN ancestors anc ON a.id = anc.parent_avatar_id
+ WHERE a.deleted_at IS NULL
+ ),
+ root AS (
+ SELECT id FROM ancestors WHERE parent_avatar_id IS NULL LIMIT 1
+ ),
+ chain AS (
+ SELECT a.id, a.parent_avatar_id, a.created_at
+ FROM avatars a
+ JOIN root r ON a.id = r.id
+ WHERE a.deleted_at IS NULL
+ UNION ALL
+ SELECT a.id, a.parent_avatar_id, a.created_at
+ FROM avatars a
+ JOIN chain c ON a.parent_avatar_id = c.id
+ WHERE a.deleted_at IS NULL
+ )
+ SELECT id, created_at FROM chain ORDER BY created_at ASC
+ `;
+
+ // If the seed avatar wasn't found (deleted or wrong id), the ancestor CTE
+ // returns empty → chain is also empty.
+ if (!rows.length) return error(res, 404, 'not_found', 'avatar not found');
+
+ // Determine the caller's current avatar so is_current can be set.
+ let currentAvatarId = null;
+ if (auth?.userId) {
+ const [agent] = await sql`
+ SELECT avatar_id FROM agent_identities
+ WHERE user_id = ${auth.userId} AND deleted_at IS NULL
+ ORDER BY created_at ASC LIMIT 1
+ `;
+ currentAvatarId = agent?.avatar_id ?? null;
+ }
+
+ const total = rows.length;
+ const versions = rows.map((row, i) => ({
+ id: row.id,
+ version: i + 1,
+ total,
+ created_at: row.created_at,
+ is_current: row.id === currentAvatarId,
+ }));
+
+ return json(res, 200, { versions });
+}
+
+async function resolveVersionsAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ return bearer ? { userId: bearer.userId } : null;
+}
diff --git a/api/avatars/[id]/glb-versions.js b/api/avatars/[id]/glb-versions.js
deleted file mode 100644
index 3d0151b68..000000000
--- a/api/avatars/[id]/glb-versions.js
+++ /dev/null
@@ -1,44 +0,0 @@
-// GET /api/avatars/:id/glb-versions
-// Lists explicit GLB save-back snapshots for an avatar, newest first (limit 50).
-// Requires auth + ownership. Distinct from /versions (parent_avatar_id lineage chain).
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { sql } from '../../_lib/db.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const id = req.query?.id;
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
- const userId = session?.id ?? bearer.userId;
-
- const [avatar] = await sql`
- select id from avatars
- where id = ${id} and owner_id = ${userId} and deleted_at is null
- limit 1
- `;
- if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
-
- const rows = await sql`
- select id, glb_url, created_at, metadata
- from avatar_versions
- where avatar_id = ${id}
- order by created_at desc
- limit 50
- `;
-
- return json(res, 200, {
- versions: rows.map((v) => ({
- id: v.id,
- glbUrl: v.glb_url,
- createdAt: v.created_at,
- metadata: v.metadata ?? null,
- })),
- });
-});
diff --git a/api/avatars/[id]/pin-ipfs.js b/api/avatars/[id]/pin-ipfs.js
deleted file mode 100644
index 63eff1c64..000000000
--- a/api/avatars/[id]/pin-ipfs.js
+++ /dev/null
@@ -1,95 +0,0 @@
-// Pin an avatar's GLB to IPFS. Uses Pinata when PINATA_JWT is configured;
-// otherwise falls back to a content-hash stub CID so dev environments still
-// flip the pinned flag.
-
-import { GetObjectCommand } from '@aws-sdk/client-s3';
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { readStorageMode } from '../../_lib/storage-mode.js';
-import { r2 } from '../../_lib/r2.js';
-import { env } from '../../_lib/env.js';
-
-const PINATA_ENDPOINT = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
- if (!id) return error(res, 400, 'validation_error', 'avatar id required');
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const [row] = await sql`
- SELECT id, owner_id, checksum_sha256, storage_key, content_type, name
- FROM avatars WHERE id = ${id} AND deleted_at IS NULL
- `;
- if (!row) return error(res, 404, 'not_found', 'avatar not found');
- if (row.owner_id !== session.id) return error(res, 403, 'forbidden', 'not your avatar');
-
- const mode = await readStorageMode(id);
- if (!mode) return error(res, 500, 'internal', 'storage_mode unavailable');
-
- const pinataJwt = env.PINATA_JWT;
- let cid;
- let isStub = false;
-
- if (pinataJwt && row.storage_key) {
- try {
- cid = await pinToPinata({
- jwt: pinataJwt,
- key: row.storage_key,
- name: row.name || `avatar-${id}`,
- contentType: row.content_type || 'model/gltf-binary',
- });
- } catch (err) {
- return error(res, 502, 'upstream_error', `Pinata upload failed: ${err.message}`);
- }
- } else {
- isStub = true;
- cid = row.checksum_sha256 ? `stub:sha256-${row.checksum_sha256}` : `stub:no-hash-${id}`;
- }
-
- const next = {
- ...mode,
- ipfs: { pinned: true, cid, pinned_at: new Date().toISOString() },
- };
-
- await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(next)}::jsonb WHERE id = ${id}`;
- return json(res, 200, { storage_mode: next, stub: isStub });
-});
-
-async function pinToPinata({ jwt, key, name, contentType }) {
- const obj = await r2.send(new GetObjectCommand({ Bucket: env.S3_BUCKET, Key: key }));
- const bytes = await streamToBuffer(obj.Body);
- const blob = new Blob([bytes], { type: contentType });
-
- const form = new FormData();
- form.append('file', blob, name);
- form.append('pinataMetadata', JSON.stringify({ name }));
-
- const res = await fetch(PINATA_ENDPOINT, {
- method: 'POST',
- headers: { Authorization: `Bearer ${jwt}` },
- body: form,
- });
- if (!res.ok) {
- const body = await res.text().catch(() => '');
- throw new Error(`HTTP ${res.status} ${body.slice(0, 200)}`);
- }
- const data = await res.json();
- if (!data?.IpfsHash) throw new Error('no IpfsHash in Pinata response');
- return data.IpfsHash;
-}
-
-async function streamToBuffer(stream) {
- if (stream instanceof Uint8Array) return stream;
- if (typeof stream?.transformToByteArray === 'function') {
- return stream.transformToByteArray();
- }
- const chunks = [];
- for await (const chunk of stream) chunks.push(chunk);
- return Buffer.concat(chunks);
-}
diff --git a/api/avatars/[id]/rollback.js b/api/avatars/[id]/rollback.js
deleted file mode 100644
index 4c3ecb8e8..000000000
--- a/api/avatars/[id]/rollback.js
+++ /dev/null
@@ -1,67 +0,0 @@
-// POST /api/avatars/:id/rollback
-// Restores avatars.storage_key from a saved avatar_versions snapshot,
-// then records the rollback as a new version row.
-// Rate-limited to 10 / hour per user.
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { sql } from '../../_lib/db.js';
-import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { z } from 'zod';
-import { parse } from '../../_lib/validate.js';
-
-const bodySchema = z.object({
- versionId: z.coerce.number().int().positive(),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const id = req.query?.id;
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');
- const userId = session?.id ?? bearer.userId;
-
- const rl = await limits.avatarRollback(userId);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const { versionId } = parse(bodySchema, await readJson(req));
-
- const [avatar] = await sql`
- select id from avatars
- where id = ${id} and owner_id = ${userId} and deleted_at is null
- limit 1
- `;
- if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
-
- const [ver] = await sql`
- select id, glb_url from avatar_versions
- where id = ${versionId} and avatar_id = ${id}
- limit 1
- `;
- if (!ver) return error(res, 404, 'not_found', 'version not found');
-
- const [updated] = await sql`
- update avatars
- set storage_key = ${ver.glb_url}, updated_at = now()
- where id = ${id} and owner_id = ${userId}
- returning id, owner_id, slug, name, description, storage_key, size_bytes,
- content_type, source, visibility, tags, version, created_at, updated_at
- `;
-
- await sql`
- insert into avatar_versions (avatar_id, glb_url, metadata, created_by)
- values (
- ${id},
- ${ver.glb_url},
- ${JSON.stringify({ rollback_of: versionId })}::jsonb,
- ${userId}
- )
- `;
-
- return json(res, 200, { ok: true, avatar: updated });
-});
diff --git a/api/avatars/[id]/session.js b/api/avatars/[id]/session.js
deleted file mode 100644
index b069e17aa..000000000
--- a/api/avatars/[id]/session.js
+++ /dev/null
@@ -1,118 +0,0 @@
-// POST /api/avatars/:id/session
-// Creates an Avaturn edit session for an existing avatar the caller owns.
-// Returns { session_url } — embed in the AvatarCreator modal to preload the
-// existing avatar so the user can tweak it and export a new version.
-//
-// Avaturn API shape (verify against https://docs.avaturn.me):
-// POST {AVATURN_API_URL}/api/v1/sessions
-// Authorization: Bearer {apiKey}
-// { external_user_id, avatar_url }
-// → 200 { session_url, expires_at? }
-//
-// If AVATURN_API_KEY is unset → 501.
-// If the avatar is not found / not owned by caller → 404 (mirrors [id].js pattern).
-
-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
-import { getAvatar, resolveAvatarUrl } from '../../_lib/avatars.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { env } from '../../_lib/env.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const id = req.query?.id;
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.upload(auth.userId);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests, try again later');
-
- // 404 (not 403) when not found or not owned — mirrors [id].js.
- const avatar = await getAvatar({ id, requesterId: auth.userId });
- if (!avatar || avatar.owner_id !== auth.userId) {
- return error(res, 404, 'not_found', 'avatar not found');
- }
-
- if (!env.AVATURN_API_KEY) {
- return error(
- res,
- 501,
- 'not_configured',
- 'Avaturn is not configured on this deployment. Set AVATURN_API_KEY.',
- );
- }
-
- // Resolve a time-limited URL the Avaturn upstream can fetch (works for private too).
- const { url: glbUrl } = await resolveAvatarUrl(avatar, { expiresIn: 3600 });
-
- try {
- const result = await createAvaturnEditSession({
- apiKey: env.AVATURN_API_KEY,
- apiUrl: env.AVATURN_API_URL,
- userId: auth.userId,
- avatarUrl: glbUrl,
- });
- return json(res, 200, result);
- } catch (err) {
- const status = err?.status || 502;
- const code = err?.code || 'upstream_error';
- const message = err?.message || 'avatar provider rejected request';
- if (status >= 500) console.error('[avatars/session] upstream failure:', err);
- return error(res, status >= 500 ? 502 : status, code, message);
- }
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (!bearer) return null;
- if (!hasScope(bearer.scope, 'avatars:write')) return null;
- return { userId: bearer.userId };
-}
-
-/**
- * Opens an existing avatar in Avaturn for editing.
- * Passes `avatar_url` so Avaturn pre-populates the editor with the existing mesh.
- * If Avaturn's API uses a different field (e.g. `avatarUrl`, `model_url`), update
- * the payload mapping below and the AVATURN_API_URL env var accordingly.
- */
-async function createAvaturnEditSession({ apiKey, apiUrl, userId, avatarUrl }) {
- const url = `${apiUrl}/api/v1/sessions`;
- const payload = {
- external_user_id: userId,
- avatar_url: avatarUrl,
- };
-
- const upstream = await fetch(url, {
- method: 'POST',
- headers: {
- authorization: `Bearer ${apiKey}`,
- 'content-type': 'application/json',
- accept: 'application/json',
- },
- body: JSON.stringify(payload),
- });
-
- if (!upstream.ok) {
- const text = await upstream.text().catch(() => '');
- const err = new Error(`avaturn upstream ${upstream.status}: ${text.slice(0, 200)}`);
- err.status = upstream.status >= 500 ? 502 : upstream.status;
- err.code = upstream.status === 401 ? 'upstream_auth' : 'upstream_error';
- throw err;
- }
-
- const data = await upstream.json();
- const sessionUrl = data?.session_url || data?.url || data?.iframe_url;
- if (!sessionUrl) {
- const err = new Error('avaturn response missing session_url');
- err.status = 502;
- err.code = 'upstream_error';
- throw err;
- }
- return { session_url: sessionUrl, expires_at: data.expires_at ?? null };
-}
diff --git a/api/avatars/[id]/storage-mode.js b/api/avatars/[id]/storage-mode.js
deleted file mode 100644
index 43e58269d..000000000
--- a/api/avatars/[id]/storage-mode.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
-import { parse } from '../../_lib/validate.js';
-import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_lib/storage-mode.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'PUT'])) return;
-
- const id = req.query?.id || new URL(req.url, 'http://x').pathname.split('/').filter(Boolean)[2];
- if (!id) return error(res, 400, 'validation_error', 'avatar id required');
-
- const [row] = await sql`
- SELECT id, owner_id, visibility FROM avatars WHERE id = ${id} AND deleted_at IS NULL
- `;
- if (!row) return error(res, 404, 'not_found', 'avatar not found');
-
- if (req.method === 'GET') {
- if (row.visibility === 'private') {
- const session = await getSessionUser(req);
- if (!session || session.id !== row.owner_id)
- return error(res, 403, 'forbidden', 'private avatar');
- }
- const mode = await readStorageMode(id);
- return json(res, 200, { storage_mode: mode });
- }
-
- // PUT — owner only
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
- if (session.id !== row.owner_id) return error(res, 403, 'forbidden', 'not your avatar');
-
- const body = parse(storageModeSchema, await readJson(req));
-
- // Read current stored mode to preserve attestation fields — clients must not
- // be able to forge tx_hash / chain_id / attested_at from the UI.
- const current = await readStorageMode(id);
- const safeBody = {
- ...body,
- attestation: current?.attestation ?? defaultStorageMode().attestation,
- };
-
- await sql`UPDATE avatars SET storage_mode = ${JSON.stringify(safeBody)}::jsonb WHERE id = ${id}`;
- return json(res, 200, { storage_mode: safeBody });
-});
diff --git a/api/avatars/[id]/versions.js b/api/avatars/[id]/versions.js
deleted file mode 100644
index 8286ad0ce..000000000
--- a/api/avatars/[id]/versions.js
+++ /dev/null
@@ -1,88 +0,0 @@
-// GET /api/avatars/:id/versions
-// Walks parent_avatar_id upward from the given avatar to collect all ancestors
-// (including self), ordered oldest first. Also includes newer versions by
-// walking the full chain from the root.
-//
-// Response: { versions: [{ id, version, total, created_at, is_current }] }
-// is_current — true when this avatar row is the caller's agent's current avatar.
-//
-// Auth: optional. Unauthenticated callers get is_current: false for all rows.
-
-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
-import { sql } from '../../_lib/db.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const id = req.query?.id;
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const auth = await resolveAuth(req);
-
- // Walk upward through parent_avatar_id to collect the full ancestor chain,
- // then walk downward from the root to collect all descendants.
- // Two-phase CTE keeps the query readable and avoids a self-join cycle.
- const rows = await sql`
- WITH RECURSIVE
- ancestors AS (
- SELECT id, parent_avatar_id, created_at
- FROM avatars
- WHERE id = ${id} AND deleted_at IS NULL
- UNION ALL
- SELECT a.id, a.parent_avatar_id, a.created_at
- FROM avatars a
- JOIN ancestors anc ON a.id = anc.parent_avatar_id
- WHERE a.deleted_at IS NULL
- ),
- root AS (
- SELECT id FROM ancestors WHERE parent_avatar_id IS NULL LIMIT 1
- ),
- chain AS (
- SELECT a.id, a.parent_avatar_id, a.created_at
- FROM avatars a
- JOIN root r ON a.id = r.id
- WHERE a.deleted_at IS NULL
- UNION ALL
- SELECT a.id, a.parent_avatar_id, a.created_at
- FROM avatars a
- JOIN chain c ON a.parent_avatar_id = c.id
- WHERE a.deleted_at IS NULL
- )
- SELECT id, created_at FROM chain ORDER BY created_at ASC
- `;
-
- // If the seed avatar wasn't found (deleted or wrong id), the ancestor CTE
- // returns empty → chain is also empty.
- if (!rows.length) return error(res, 404, 'not_found', 'avatar not found');
-
- // Determine the caller's current avatar so is_current can be set.
- let currentAvatarId = null;
- if (auth?.userId) {
- const [agent] = await sql`
- SELECT avatar_id FROM agent_identities
- WHERE user_id = ${auth.userId} AND deleted_at IS NULL
- ORDER BY created_at ASC LIMIT 1
- `;
- currentAvatarId = agent?.avatar_id ?? null;
- }
-
- const total = rows.length;
- const versions = rows.map((row, i) => ({
- id: row.id,
- version: i + 1,
- total,
- created_at: row.created_at,
- is_current: row.id === currentAvatarId,
- }));
-
- return json(res, 200, { versions });
-});
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- return bearer ? { userId: bearer.userId } : null;
-}
diff --git a/api/cron/[name].js b/api/cron/[name].js
new file mode 100644
index 000000000..f10cddcfc
--- /dev/null
+++ b/api/cron/[name].js
@@ -0,0 +1,2150 @@
+/**
+ * Cron dispatcher — single Vercel serverless function for every /api/cron/* job.
+ *
+ * Vercel routes /api/cron/<name> to this file via the [name] dynamic segment;
+ * `req.query.name` carries the kebab-case job id. Each branch below is a
+ * verbatim move of the original per-file handler body — no logic changes,
+ * especially around auth / CRON_SECRET checks.
+ *
+ * Cron paths handled (kebab-case → handler):
+ * erc8004-crawl → handleErc8004Crawl
+ * index-delegations → handleIndexDelegations
+ * pump-agent-stats → handlePumpAgentStats
+ * pumpfun-monitor → handlePumpfunMonitor
+ * pumpfun-signals → handlePumpfunSignals
+ * run-buyback → handleRunBuyback
+ * run-dca → handleRunDca
+ * run-distribute-payments → handleRunDistributePayments
+ * run-subscriptions → handleRunSubscriptions
+ * solana-attest-event-cleanup → handleSolanaAttestEventCleanup
+ * solana-attestations-crawl → handleSolanaAttestationsCrawl
+ */
+
+import { id as keccakId, AbiCoder, getAddress } from 'ethers';
+import { createPublicClient, http, encodeFunctionData, parseAbi } from 'viem';
+import { baseSepolia, base } from 'viem/chains';
+
+import { sql } from '../_lib/db.js';
+import { cors, error, json, method, wrap } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { CHAINS } from '../_lib/erc8004-chains.js';
+import { DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';
+import {
+ getPumpAgent,
+ getPumpAgentOffline,
+ getConnection,
+ getPumpSdk,
+ getAmmPoolState,
+ buildUnsignedTxBase64,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/attest-event.js';
+import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
+import { crawlAgentAttestations } from '../_lib/solana-attestations.js';
+import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
+
+// ─── Dispatcher ──────────────────────────────────────────────────────────────
+
+const HANDLERS = {
+ 'erc8004-crawl': handleErc8004Crawl,
+ 'index-delegations': handleIndexDelegations,
+ 'pump-agent-stats': handlePumpAgentStats,
+ 'pumpfun-monitor': handlePumpfunMonitor,
+ 'pumpfun-signals': handlePumpfunSignals,
+ 'run-buyback': handleRunBuyback,
+ 'run-dca': handleRunDca,
+ 'run-distribute-payments': handleRunDistributePayments,
+ 'run-subscriptions': handleRunSubscriptions,
+ 'solana-attest-event-cleanup': handleSolanaAttestEventCleanup,
+ 'solana-attestations-crawl': handleSolanaAttestationsCrawl,
+};
+
+export default wrap(async (req, res) => {
+ const name = req.query?.name;
+ const handler = typeof name === 'string' ? HANDLERS[name] : null;
+ if (!handler) return error(res, 404, 'not_found', 'unknown cron');
+ return handler(req, res);
+});
+
+// ═══════════════════════════════════════════════════════════════════════════
+// erc8004-crawl
+// ═══════════════════════════════════════════════════════════════════════════
+
+const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');
+const ABI_CODER = AbiCoder.defaultAbiCoder();
+
+// Blocks scanned per chain per cron invocation. Public RPCs typically allow
+// 2000-block ranges; lower this if a chain's RPC rejects with "block range".
+const ERC8004_BLOCK_CHUNK = 2_000;
+
+// On first run (no cursor), scan this many recent blocks. Set
+// ERC8004_CRAWL_LOOKBACK env var to override (e.g. larger for backfill).
+const ERC8004_DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);
+
+// Metadata enrichment per invocation.
+const ERC8004_METADATA_BATCH = 25;
+
+const ERC8004_FETCH_TIMEOUT_MS = 10_000;
+
+async function handleErc8004Crawl(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const report = { chains: [], enriched: 0, errors: [] };
+
+ for (const chain of CHAINS) {
+ try {
+ const r = await erc8004CrawlChain(chain);
+ report.chains.push({ chainId: chain.id, name: chain.name, ...r });
+ } catch (err) {
+ report.errors.push({ chainId: chain.id, error: err.message || String(err) });
+ }
+ }
+
+ try {
+ report.enriched = await erc8004EnrichMetadata(ERC8004_METADATA_BATCH);
+ } catch (err) {
+ report.errors.push({ stage: 'metadata', error: err.message || String(err) });
+ }
+
+ return json(res, 200, report);
+}
+
+async function erc8004CrawlChain(chain) {
+ const [cursor] = await sql`
+ SELECT last_block FROM erc8004_crawl_cursor WHERE chain_id = ${chain.id}
+ `;
+
+ const latestHex = await erc8004RpcCall(chain.rpcUrl, 'eth_blockNumber', []);
+ const latestBlock = Number.parseInt(latestHex, 16);
+
+ const fromBlock = cursor
+ ? Number(cursor.last_block) + 1
+ : Math.max(0, latestBlock - ERC8004_DEFAULT_LOOKBACK);
+
+ if (fromBlock > latestBlock) {
+ return { inserted: 0, scanned: 0, lastBlock: latestBlock, fromBlock };
+ }
+
+ const toBlock = Math.min(fromBlock + ERC8004_BLOCK_CHUNK - 1, latestBlock);
+
+ const logs = await erc8004RpcCall(chain.rpcUrl, 'eth_getLogs', [
+ {
+ address: chain.registry,
+ topics: [REGISTERED_TOPIC],
+ fromBlock: '0x' + fromBlock.toString(16),
+ toBlock: '0x' + toBlock.toString(16),
+ },
+ ]);
+
+ // Fetch block timestamps for any blocks that produced events.
+ const blockTimes = {};
+ if (logs.length > 0) {
+ const uniqueBlockHexes = [...new Set(logs.map((l) => l.blockNumber))];
+ await Promise.all(
+ uniqueBlockHexes.map(async (bn) => {
+ try {
+ const block = await erc8004RpcCall(chain.rpcUrl, 'eth_getBlockByNumber', [bn, false]);
+ blockTimes[bn] = block ? Number.parseInt(block.timestamp, 16) : null;
+ } catch {
+ // registered_at will be null for this block
+ }
+ }),
+ );
+ }
+
+ let inserted = 0;
+ for (const log of logs) {
+ try {
+ const agentId = BigInt(log.topics[1]).toString();
+ const ownerHex = '0x' + log.topics[2].slice(-40);
+ const owner = getAddress(ownerHex).toLowerCase();
+ const [agentURI] = ABI_CODER.decode(['string'], log.data);
+ const blockNumber = Number.parseInt(log.blockNumber, 16);
+ const ts = blockTimes[log.blockNumber];
+ const registeredAt = ts ? new Date(ts * 1000).toISOString() : null;
+
+ await sql`
+ INSERT INTO erc8004_agents_index
+ (chain_id, agent_id, owner, registry, agent_uri,
+ registered_block, registered_tx, registered_at, last_seen_at)
+ VALUES
+ (${chain.id}, ${agentId}, ${owner}, ${chain.registry.toLowerCase()},
+ ${agentURI || null}, ${blockNumber}, ${log.transactionHash},
+ ${registeredAt}, now())
+ ON CONFLICT (chain_id, agent_id) DO UPDATE SET
+ owner = excluded.owner,
+ agent_uri = COALESCE(excluded.agent_uri, erc8004_agents_index.agent_uri),
+ last_seen_at = now()
+ `;
+ inserted += 1;
+ } catch (decodeErr) {
+ console.warn('[crawl] decode failed', chain.id, log.transactionHash, decodeErr.message);
+ }
+ }
+
+ // Always advance cursor to toBlock so the next run continues from here.
+ await sql`
+ INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at)
+ VALUES (${chain.id}, ${toBlock}, now())
+ ON CONFLICT (chain_id) DO UPDATE SET
+ last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),
+ updated_at = now()
+ `;
+
+ return { inserted, scanned: toBlock - fromBlock + 1, lastBlock: toBlock, fromBlock };
+}
+
+async function erc8004EnrichMetadata(limit) {
+ const rows = await sql`
+ SELECT chain_id, agent_id, agent_uri
+ FROM erc8004_agents_index
+ WHERE agent_uri IS NOT NULL
+ AND (last_metadata_at IS NULL OR last_metadata_at < now() - interval '7 days')
+ ORDER BY last_metadata_at NULLS FIRST, registered_at DESC NULLS LAST
+ LIMIT ${limit}
+ `;
+
+ let done = 0;
+ for (const row of rows) {
+ try {
+ const meta = await erc8004FetchAgentMetadata(row.agent_uri);
+ if (!meta) {
+ await sql`
+ UPDATE erc8004_agents_index
+ SET metadata_error = 'fetch failed',
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ continue;
+ }
+ const name = erc8004Truncate(meta.name || '', 200);
+ const description = erc8004Truncate(meta.description || '', 1000);
+ const image = erc8004ResolveGateway(meta.image || '');
+ const services = Array.isArray(meta.services) ? meta.services : [];
+ const avatarSvc = services.find(
+ (s) => String(s?.name || '').toLowerCase() === 'avatar' && s?.endpoint,
+ );
+ const glbUrl = avatarSvc ? erc8004ResolveGateway(avatarSvc.endpoint) : null;
+ const has3d = !!glbUrl;
+ const active = meta.active !== false;
+ const x402 = !!(meta.x402Support || meta.x402);
+
+ await sql`
+ UPDATE erc8004_agents_index
+ SET name = ${name || null},
+ description = ${description || null},
+ image = ${image || null},
+ glb_url = ${glbUrl},
+ services = ${JSON.stringify(services)}::jsonb,
+ has_3d = ${has3d},
+ active = ${active},
+ x402_support = ${x402},
+ metadata_error = null,
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ done += 1;
+ } catch (err) {
+ await sql`
+ UPDATE erc8004_agents_index
+ SET metadata_error = ${erc8004Truncate(err.message || String(err), 500)},
+ last_metadata_at = now()
+ WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
+ `;
+ }
+ }
+ return done;
+}
+
+async function erc8004RpcCall(url, method, params) {
+ const ac = new AbortController();
+ const t = setTimeout(() => ac.abort(), ERC8004_FETCH_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: ac.signal,
+ });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ if (data.error) throw new Error(`RPC ${data.error.code}: ${data.error.message}`);
+ return data.result;
+ } finally {
+ clearTimeout(t);
+ }
+}
+
+async function erc8004FetchAgentMetadata(uri) {
+ const url = erc8004ResolveGateway(uri);
+ if (!url) return null;
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(ERC8004_FETCH_TIMEOUT_MS) });
+ if (!res.ok) return null;
+ return await res.json();
+ } catch {
+ return null;
+ }
+}
+
+function erc8004ResolveGateway(uri) {
+ if (!uri || typeof uri !== 'string') return '';
+ if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);
+ if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);
+ if (uri.startsWith('http://') || uri.startsWith('https://')) return uri;
+ return '';
+}
+
+function erc8004Truncate(s, max) {
+ if (!s) return '';
+ return s.length > max ? s.slice(0, max) : s;
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// index-delegations
+// ═══════════════════════════════════════════════════════════════════════════
+
+const DISABLED_TOPIC = keccakId('DelegationDisabled(address,bytes32)');
+const REDEEMED_TOPIC = keccakId('DelegationRedeemed(address,bytes32)');
+
+// Max blocks per eth_getLogs call. Public RPCs 429 above ~2000.
+const IDX_BLOCK_CAP = 2000;
+const IDX_RPC_TIMEOUT_MS = 10_000;
+
+// Approximate blocks per day, used only to seed the cursor on first run.
+const BLOCKS_PER_DAY = {
+ 84532: 43200, // Base Sepolia ~2 s/block
+ 11155111: 7200, // Sepolia ~12 s/block
+};
+
+// Public RPC fallbacks per chain — tried in order. Override primary via env RPC_<chainId>.
+const PUBLIC_RPCS = {
+ 1: [
+ 'https://cloudflare-eth.com',
+ 'https://eth.llamarpc.com',
+ 'https://rpc.ankr.com/eth',
+ 'https://ethereum.publicnode.com',
+ 'https://1rpc.io/eth',
+ ],
+ 8453: [
+ 'https://mainnet.base.org',
+ 'https://base.llamarpc.com',
+ 'https://rpc.ankr.com/base',
+ 'https://base.publicnode.com',
+ 'https://1rpc.io/base',
+ ],
+ 84532: [
+ 'https://sepolia.base.org',
+ 'https://base-sepolia-rpc.publicnode.com',
+ 'https://rpc.ankr.com/base_sepolia',
+ ],
+ 11155111: [
+ 'https://rpc.sepolia.org',
+ 'https://ethereum-sepolia-rpc.publicnode.com',
+ 'https://rpc.ankr.com/eth_sepolia',
+ 'https://1rpc.io/sepolia',
+ ],
+ 421614: [
+ 'https://sepolia-rollup.arbitrum.io/rpc',
+ 'https://arbitrum-sepolia.publicnode.com',
+ 'https://rpc.ankr.com/arbitrum_sepolia',
+ ],
+ 11155420: [
+ 'https://sepolia.optimism.io',
+ 'https://optimism-sepolia.publicnode.com',
+ 'https://rpc.ankr.com/optimism_sepolia',
+ ],
+};
+
+function idxRpcUrls(chainId) {
+ const envUrl = process.env[`RPC_${chainId}`];
+ const fallbacks = PUBLIC_RPCS[chainId] ?? [];
+ return envUrl ? [envUrl, ...fallbacks] : fallbacks;
+}
+
+async function handleIndexDelegations(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const started = Date.now();
+ const report = { chains: [], expiredSwept: 0, errors: [] };
+
+ // Index each chain independently — one chain's RPC failure must not abort others.
+ for (const [chainIdStr, contract] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {
+ const chainId = Number(chainIdStr);
+ const t0 = Date.now();
+ try {
+ const r = await idxIndexChain(chainId, contract);
+ const summary = { chainId, ...r, elapsedMs: Date.now() - t0 };
+ report.chains.push(summary);
+ console.log(JSON.stringify({ stage: 'index-delegations', ...summary }));
+ } catch (err) {
+ const entry = { chainId, error: err.message || String(err) };
+ report.errors.push(entry);
+ console.error(JSON.stringify({ stage: 'index-delegations', ...entry }));
+ }
+ }
+
+ // Expiry sweep — idempotent, catches expirations missed between grant and indexer.
+ try {
+ const swept = await sql`
+ UPDATE agent_delegations
+ SET status = 'expired'
+ WHERE status = 'active' AND expires_at < NOW()
+ RETURNING id
+ `;
+ report.expiredSwept = swept.length;
+ } catch (err) {
+ report.errors.push({ stage: 'expiry-sweep', error: err.message || String(err) });
+ console.error(JSON.stringify({ stage: 'expiry-sweep', error: err.message }));
+ }
+
+ // Emit summary to usage_events (best-effort — non-fatal if table shape differs).
+ try {
+ await sql`
+ INSERT INTO usage_events (kind, tool, status, latency_ms)
+ VALUES ('permissions.indexer.tick', 'index-delegations', 'ok', ${Date.now() - started})
+ `;
+ } catch {
+ /* non-fatal */
+ }
+
+ return json(res, 200, report);
+}
+
+async function idxIndexChain(chainId, contract) {
+ const urls = idxRpcUrls(chainId);
+ if (!urls.length) throw new Error(`no RPC URL configured for chain ${chainId}`);
+
+ const latestHex = await idxRpc(urls, 'eth_blockNumber', []);
+ const latestBlock = parseInt(latestHex, 16);
+
+ const [cursor] = await sql`
+ SELECT last_indexed_block FROM indexer_state
+ WHERE contract = ${contract.toLowerCase()} AND chain_id = ${chainId}
+ `;
+ const initialFrom = cursor
+ ? Number(cursor.last_indexed_block) + 1
+ : Math.max(0, latestBlock - (BLOCKS_PER_DAY[chainId] ?? 7200));
+
+ let fromBlock = initialFrom;
+ let toBlock = latestBlock; // updated each iteration; reflects final processed range
+ let revokedCount = 0;
+ let redeemedCount = 0;
+
+ while (fromBlock <= latestBlock) {
+ toBlock = Math.min(fromBlock + IDX_BLOCK_CAP - 1, latestBlock);
+
+ const logs = await idxRpc(urls, 'eth_getLogs', [
+ {
+ address: contract,
+ topics: [[DISABLED_TOPIC, REDEEMED_TOPIC]],
+ fromBlock: '0x' + fromBlock.toString(16),
+ toBlock: '0x' + toBlock.toString(16),
+ },
+ ]);
+
+ if (logs.length > 0) {
+ // Fetch block timestamps only for blocks that have events.
+ const uniqueBlocks = [...new Set(logs.map((l) => l.blockNumber))];
+ const blockTs = {};
+ for (const bn of uniqueBlocks) {
+ const block = await idxRpc(urls, 'eth_getBlockByNumber', [bn, false]);
+ blockTs[bn] = new Date(parseInt(block.timestamp, 16) * 1000).toISOString();
+ }
+
+ for (const log of logs) {
+ // topics[2] is the bytes32 delegationHash (indexed param, 0x-prefixed, 64 hex chars).
+ const delegationHash = log.topics[2];
+ const ts = blockTs[log.blockNumber];
+
+ if (log.topics[0] === DISABLED_TOPIC) {
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET status = 'revoked',
+ revoked_at = ${ts}::timestamptz,
+ tx_hash_revoke = ${log.transactionHash}
+ WHERE delegation_hash = ${delegationHash} AND status = 'active'
+ RETURNING id
+ `;
+ revokedCount += rows.length;
+ } else {
+ const rows = await sql`
+ UPDATE agent_delegations
+ SET redemption_count = redemption_count + 1,
+ last_redeemed_at = ${ts}::timestamptz
+ WHERE delegation_hash = ${delegationHash}
+ RETURNING id
+ `;
+ redeemedCount += rows.length;
+ }
+ }
+ }
+
+ // Advance cursor after each batch so a timeout preserves partial progress.
+ await sql`
+ INSERT INTO indexer_state (contract, chain_id, last_indexed_block, updated_at)
+ VALUES (${contract.toLowerCase()}, ${chainId}, ${toBlock}, NOW())
+ ON CONFLICT (contract, chain_id) DO UPDATE SET
+ last_indexed_block = GREATEST(indexer_state.last_indexed_block, excluded.last_indexed_block),
+ updated_at = NOW()
+ `;
+
+ fromBlock = toBlock + 1;
+ }
+
+ return { fromBlock: initialFrom, toBlock, revokedCount, redeemedCount };
+}
+
+async function idxRpc(urls, method, params) {
+ let lastErr;
+ for (const url of urls) {
+ const ac = new AbortController();
+ const t = setTimeout(() => ac.abort(), IDX_RPC_TIMEOUT_MS);
+ try {
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: ac.signal,
+ });
+ if (!res.ok) throw new Error(`RPC HTTP ${res.status} from ${url}`);
+ const data = await res.json();
+ if (data.error) {
+ throw new Error(
+ `RPC ${method} error: ${data.error.message ?? JSON.stringify(data.error)}`,
+ );
+ }
+ return data.result;
+ } catch (err) {
+ lastErr = err;
+ } finally {
+ clearTimeout(t);
+ }
+ }
+ throw lastErr;
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// pump-agent-stats
+// ═══════════════════════════════════════════════════════════════════════════
+
+const PUMP_STATS_MAX_PER_RUN = 100;
+
+// Pump.fun graduation threshold (mainnet curve). Used only as a UI hint —
+// progress_pct is a coarse bar, not financial advice.
+const GRADUATION_REAL_SOL = 85_000_000_000n; // ~85 SOL in lamports
+
+async function handlePumpAgentStats(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers.authorization || '';
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron) {
+ if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${env.CRON_SECRET}`)
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ const mints = await sql`
+ select id, mint, network from pump_agent_mints
+ order by id limit ${PUMP_STATS_MAX_PER_RUN}
+ `;
+
+ const report = { scanned: mints.length, updated: 0, errors: 0, graduations: 0 };
+ for (const m of mints) {
+ try {
+ const stats = await pumpStatsSnapshotMint(m);
+
+ // Detect graduation flip false→true vs prior snapshot.
+ const [prior] = await sql`
+ select graduated from pump_agent_stats where mint_id=${m.id} limit 1
+ `;
+ const justGraduated = stats.graduated && prior && !prior.graduated;
+
+ await sql`
+ insert into pump_agent_stats
+ (mint_id, network, mint, graduated, bonding_curve, amm,
+ last_signature, last_signature_at, recent_tx_count, refreshed_at, error)
+ values (
+ ${m.id}, ${m.network}, ${m.mint}, ${stats.graduated},
+ ${stats.bonding_curve ? JSON.stringify(stats.bonding_curve) : null}::jsonb,
+ ${stats.amm ? JSON.stringify(stats.amm) : null}::jsonb,
+ ${stats.last_signature}, ${stats.last_signature_at},
+ ${stats.recent_tx_count}, now(), null
+ )
+ on conflict (mint_id) do update set
+ graduated = excluded.graduated,
+ bonding_curve = excluded.bonding_curve,
+ amm = excluded.amm,
+ last_signature = excluded.last_signature,
+ last_signature_at = excluded.last_signature_at,
+ recent_tx_count = excluded.recent_tx_count,
+ refreshed_at = now(),
+ error = null
+ `;
+
+ // Price-point time series.
+ const price = pumpStatsDerivePrice(stats);
+ if (price) {
+ await sql`
+ insert into pump_agent_price_points (mint_id, sol_per_token, market_cap_lamports, source)
+ values (${m.id}, ${price.sol_per_token}, ${price.market_cap_lamports?.toString() ?? null}, ${price.source})
+ `;
+ }
+
+ // Emit a self-sourced graduation signal (no upstream bot needed).
+ if (justGraduated) {
+ report.graduations++;
+ try {
+ await sql`
+ insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)
+ values (
+ null, ${m.mint}, 'graduation', 0.3,
+ ${JSON.stringify({ source: 'pump-agent-stats', network: m.network })}::jsonb,
+ ${`graduated:${m.mint}:${Date.now()}`}
+ )
+ on conflict (tx_signature) do nothing
+ `;
+ } catch {
+ // pumpfun_signals table optional
+ }
+ }
+
+ report.updated++;
+ } catch (e) {
+ report.errors++;
+ await sql`
+ insert into pump_agent_stats (mint_id, network, mint, error, refreshed_at)
+ values (${m.id}, ${m.network}, ${m.mint}, ${e.message || 'snapshot failed'}, now())
+ on conflict (mint_id) do update set error = excluded.error, refreshed_at = now()
+ `;
+ }
+ }
+
+ return json(res, 200, report);
+}
+
+async function pumpStatsSnapshotMint({ network, mint }) {
+ const mintPk = solanaPubkey(mint);
+ if (!mintPk) throw new Error('invalid mint pubkey');
+
+ const out = {
+ graduated: false,
+ bonding_curve: null,
+ amm: null,
+ last_signature: null,
+ last_signature_at: null,
+ recent_tx_count: 0,
+ };
+
+ // Bonding curve
+ let curve = null;
+ try {
+ const { sdk } = await getPumpSdk({ network });
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(mintPk, mintPk);
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.fetchBondingCurve(mintPk);
+ }
+ } catch {
+ curve = null;
+ }
+
+ if (curve && !curve.complete) {
+ const realSol = BigInt(curve.realSolReserves?.toString?.() ?? '0');
+ const pct =
+ GRADUATION_REAL_SOL > 0n
+ ? Number((realSol * 10000n) / GRADUATION_REAL_SOL) / 100
+ : null;
+ out.bonding_curve = {
+ real_sol: realSol.toString(),
+ real_token: curve.realTokenReserves?.toString?.() ?? null,
+ virtual_sol: curve.virtualSolReserves?.toString?.() ?? null,
+ virtual_token: curve.virtualTokenReserves?.toString?.() ?? null,
+ complete: curve.complete ?? false,
+ progress_pct: pct != null ? Math.min(100, Math.max(0, pct)) : null,
+ };
+ } else {
+ // Try AMM pool
+ try {
+ const amm = await getAmmPoolState({ network, mint: mintPk });
+ out.graduated = true;
+ out.amm = {
+ pool: amm.poolKey.toString(),
+ base_reserve: amm.baseReserve.toString(),
+ quote_reserve: amm.quoteReserve.toString(),
+ lp_supply: amm.pool.lpSupply?.toString?.() ?? null,
+ };
+ } catch (e) {
+ if (e.code !== 'pool_not_found') throw e;
+ // graduated state inferred from curve.complete only
+ if (curve?.complete) out.graduated = true;
+ }
+ }
+
+ // Recent activity snapshot via RPC
+ try {
+ const conn = getConnection({ network });
+ const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 });
+ out.recent_tx_count = sigs.length;
+ if (sigs.length > 0) {
+ out.last_signature = sigs[0].signature;
+ if (sigs[0].blockTime) {
+ out.last_signature_at = new Date(sigs[0].blockTime * 1000).toISOString();
+ }
+ }
+ } catch {
+ // RPC hiccup — leave activity fields null
+ }
+
+ return out;
+}
+
+// Compute coarse sol-per-token + market_cap_lamports from a stats snapshot.
+// Bonding curve: virtual_sol / virtual_token (the AMM-style invariant pump uses).
+// AMM: quote_reserve / base_reserve.
+function pumpStatsDerivePrice(stats) {
+ if (stats.bonding_curve) {
+ const vSol = Number(stats.bonding_curve.virtual_sol || 0);
+ const vTok = Number(stats.bonding_curve.virtual_token || 0);
+ if (vSol > 0 && vTok > 0) {
+ const sol_per_token = vSol / vTok;
+ // total supply ≈ virtual_token + real_token (heuristic, sufficient for charting)
+ const totalTok =
+ BigInt(stats.bonding_curve.virtual_token || 0) +
+ BigInt(stats.bonding_curve.real_token || 0);
+ const market_cap_lamports =
+ totalTok > 0n ? BigInt(Math.floor(sol_per_token * Number(totalTok))) : null;
+ return { sol_per_token, market_cap_lamports, source: 'bonding_curve' };
+ }
+ }
+ if (stats.amm) {
+ const q = Number(stats.amm.quote_reserve || 0);
+ const b = Number(stats.amm.base_reserve || 0);
+ if (q > 0 && b > 0) {
+ return { sol_per_token: q / b, market_cap_lamports: null, source: 'amm' };
+ }
+ }
+ return null;
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// pumpfun-monitor
+// ═══════════════════════════════════════════════════════════════════════════
+
+const PUMPFUN_MONITOR_MAX_PER_RUN = 50;
+const WHALE_TRADE_USD_FLOOR = 1_000;
+
+async function handlePumpfunMonitor(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ if (!process.env.ATTEST_AGENT_SECRET_KEY) {
+ // Skip cleanly when the attester key isn't provisioned — returning 503
+ // every 3 min would mark the cron job as failing in the dashboard.
+ return json(res, 200, { skipped: true, reason: 'attester_not_configured' });
+ }
+
+ // Pull the latest stats joined with the agent's Metaplex Core asset and
+ // the prior cursor state. Only consider mints whose stats have changed
+ // since the last cursor checkpoint.
+ const rows = await sql`
+ select
+ m.id as mint_id,
+ m.mint as token_mint,
+ m.network,
+ m.agent_id,
+ m.agent_authority,
+ s.graduated,
+ s.last_signature,
+ s.last_signature_at,
+ a.id as agent_row_id,
+ a.user_id,
+ coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') as agent_asset,
+ c.last_graduated,
+ c.last_authority,
+ c.last_trade_signature
+ from pump_agent_mints m
+ join pump_agent_stats s on s.mint_id = m.id
+ join agent_identities a on a.id = m.agent_id
+ left join pumpfun_monitor_cursor c on c.mint_id = m.id
+ where coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') is not null
+ and (
+ c.mint_id is null
+ or c.last_graduated is distinct from s.graduated
+ or c.last_authority is distinct from m.agent_authority
+ or c.last_trade_signature is distinct from s.last_signature
+ )
+ order by s.refreshed_at desc nulls last
+ limit ${PUMPFUN_MONITOR_MAX_PER_RUN}
+ `;
+
+ const attester = loadAttesterKeypair();
+ const report = { scanned: rows.length, minted: 0, deduped: 0, in_progress: 0, errors: 0, events: [] };
+
+ for (const r of rows) {
+ const events = detectEvents(r);
+ for (const ev of events) {
+ try {
+ const result = await mintAttestation({
+ ...ev,
+ agent_asset: r.agent_asset,
+ network: r.network,
+ token_mint: r.token_mint,
+ attester,
+ });
+ report[result.status === 'minted' ? 'minted'
+ : result.status === 'deduped' ? 'deduped' : 'in_progress']++;
+ report.events.push({
+ mint: r.token_mint, type: ev.event_type, status: result.status,
+ signature: result.signature,
+ });
+ } catch (e) {
+ report.errors++;
+ report.events.push({
+ mint: r.token_mint, type: ev.event_type,
+ status: 'error', error: e?.message || String(e),
+ });
+ }
+ }
+
+ // Always update the cursor — even when nothing was emitted — so we
+ // don't re-scan unchanged rows next tick.
+ await sql`
+ insert into pumpfun_monitor_cursor (mint_id, last_graduated, last_authority, last_trade_signature, last_processed_at)
+ values (${r.mint_id}, ${r.graduated}, ${r.agent_authority}, ${r.last_signature}, now())
+ on conflict (mint_id) do update set
+ last_graduated = excluded.last_graduated,
+ last_authority = excluded.last_authority,
+ last_trade_signature = excluded.last_trade_signature,
+ last_processed_at = now()
+ `;
+ }
+
+ return json(res, 200, report);
+}
+
+/** Map a single (stats, cursor) row to the attestation events to emit. */
+function detectEvents(r) {
+ const out = [];
+ const slot_or_ts = r.last_signature_at
+ ? new Date(r.last_signature_at).getTime()
+ : Date.now();
+
+ // Graduation flip false -> true.
+ if (r.graduated === true && r.last_graduated !== true) {
+ out.push({
+ event_type: 'graduation',
+ source: 'pumpfun.graduation',
+ event_id: deriveEventId({ event_type: 'graduation', mint: r.token_mint, slot_or_ts: 'final' }),
+ task_id: `pumpfun:${r.token_mint}:graduation`,
+ detail: { network: r.network },
+ });
+ }
+
+ // CTO: agent_authority changed (creator takeover).
+ if (r.agent_authority && r.last_authority && r.agent_authority !== r.last_authority) {
+ out.push({
+ event_type: 'cto_detected',
+ source: 'pumpfun.cto',
+ event_id: deriveEventId({
+ event_type: 'cto',
+ mint: r.token_mint,
+ slot_or_ts: `${r.last_authority}->${r.agent_authority}`,
+ }),
+ task_id: `pumpfun:${r.token_mint}:cto:${slot_or_ts}`,
+ detail: { from: r.last_authority, to: r.agent_authority, network: r.network },
+ });
+ }
+
+ return out;
+}
+
+// Exported for tests.
+export { detectEvents, WHALE_TRADE_USD_FLOOR };
+
+// ═══════════════════════════════════════════════════════════════════════════
+// pumpfun-signals
+// ═══════════════════════════════════════════════════════════════════════════
+
+const CLAIMS_PER_RUN = 200;
+const GRADS_PER_RUN = 50;
+
+const SIGNAL_WEIGHT = {
+ first_claim: +0.2,
+ graduation: +0.3,
+ influencer: +0.2,
+ fake_claim: -0.6,
+ new_account: -0.2,
+};
+
+async function handlePumpfunSignals(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ if (!pumpfunBotEnabled()) {
+ return json(res, 200, { skipped: 'pumpfun bot not configured' });
+ }
+
+ const [claims, grads] = await Promise.all([
+ pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN }),
+ pumpfunMcp.graduations({ limit: GRADS_PER_RUN }),
+ ]);
+
+ const report = { claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };
+
+ const claimItems = pumpfunArr(claims.ok ? claims.data : null);
+ const gradItems = pumpfunArr(grads.ok ? grads.data : null);
+ report.claims = claimItems.length;
+ report.graduations = gradItems.length;
+
+ const wallets = pumpfunCollectWallets(claimItems, gradItems);
+ const linked = await pumpfunLinkedWalletMap(wallets);
+
+ for (const ev of claimItems) {
+ const wallet = ev.claimer || ev.github_wallet;
+ if (!wallet || !linked.has(wallet)) {
+ report.skipped++;
+ continue;
+ }
+ try {
+ const inserts = pumpfunSignalsFromClaim(ev);
+ for (const sig of inserts) {
+ const ok = await pumpfunInsertSignal({
+ wallet,
+ agent_asset: linked.get(wallet) || null,
+ kind: sig.kind,
+ weight: SIGNAL_WEIGHT[sig.kind] ?? 0,
+ payload: sig.payload,
+ tx_signature: sig.tx_signature,
+ });
+ if (ok) report.inserted++;
+ }
+ } catch (err) {
+ report.errors.push({ tx: ev.tx_signature, error: err.message });
+ }
+ }
+
+ for (const ev of gradItems) {
+ const wallet = ev.creator || ev.dev_wallet;
+ if (!wallet || !linked.has(wallet)) {
+ report.skipped++;
+ continue;
+ }
+ try {
+ const ok = await pumpfunInsertSignal({
+ wallet,
+ agent_asset: linked.get(wallet) || null,
+ kind: 'graduation',
+ weight: SIGNAL_WEIGHT.graduation,
+ payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },
+ tx_signature: ev.tx_signature || ev.signature,
+ });
+ if (ok) report.inserted++;
+ } catch (err) {
+ report.errors.push({ tx: ev.tx_signature, error: err.message });
+ }
+ }
+
+ return json(res, 200, report);
+}
+
+function pumpfunArr(x) {
+ if (!x) return [];
+ return Array.isArray(x) ? x : x.items || [];
+}
+
+function pumpfunCollectWallets(claims, grads) {
+ const out = new Set();
+ for (const c of claims) {
+ if (c.claimer) out.add(c.claimer);
+ if (c.github_wallet) out.add(c.github_wallet);
+ }
+ for (const g of grads) {
+ if (g.creator) out.add(g.creator);
+ if (g.dev_wallet) out.add(g.dev_wallet);
+ }
+ return [...out];
+}
+
+async function pumpfunLinkedWalletMap(wallets) {
+ const map = new Map();
+ if (wallets.length === 0) return map;
+ const rows = await sql`
+ select uw.address, ai.meta->>'sol_mint_address' as agent_asset
+ from user_wallets uw
+ left join agent_identities ai
+ on ai.user_id = uw.user_id
+ and ai.deleted_at is null
+ and ai.meta->>'chain_type' = 'solana'
+ where uw.chain_type = 'solana'
+ and uw.address = any(${wallets})
+ `;
+ for (const r of rows) map.set(r.address, r.agent_asset);
+ return map;
+}
+
+function pumpfunSignalsFromClaim(ev) {
+ const out = [];
+ const base = { tx_signature: ev.tx_signature, payload: ev };
+ if (ev.first_time_claim) out.push({ kind: 'first_claim', ...base });
+ if (ev.fake_claim) out.push({ kind: 'fake_claim', ...base });
+ if (ev.tier === 'mega' || ev.tier === 'influencer') out.push({ kind: 'influencer', ...base });
+ if (ev.github_account_age_days != null && ev.github_account_age_days < 30) {
+ out.push({ kind: 'new_account', ...base });
+ }
+ return out;
+}
+
+async function pumpfunInsertSignal({ wallet, agent_asset, kind, weight, payload, tx_signature }) {
+ if (!tx_signature) return false;
+ const result = await sql`
+ insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)
+ values (${wallet}, ${agent_asset}, ${kind}, ${weight}, ${JSON.stringify(payload)}::jsonb, ${tx_signature})
+ on conflict (tx_signature) do nothing
+ returning id
+ `;
+ return result.length > 0;
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-buyback
+// ═══════════════════════════════════════════════════════════════════════════
+
+async function buybackLoadRelayer() {
+ const b64 = process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64;
+ if (!b64) return null;
+ const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
+ return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
+}
+
+async function handleRunBuyback(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const auth = req.headers.authorization || '';
+ if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${env.CRON_SECRET}`) {
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ const fullSwap = process.env.PUMP_BUYBACK_FULL_SWAP === 'true';
+ const relayer = await buybackLoadRelayer();
+
+ const mints = await sql`
+ select id, mint, network from pump_agent_mints limit 200
+ `;
+
+ const results = [];
+ for (const m of mints) {
+ const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ const currency = solanaPubkey(currencyStr);
+
+ try {
+ const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
+ const balances = await agent.getBalances(currency);
+ const buyback = BigInt(balances.buybackVault?.balance ?? 0);
+
+ if (buyback === 0n) {
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status)
+ values (${m.id}, ${currencyStr}, 'skipped') returning id
+ `;
+ results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
+ continue;
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
+ const [{ PUMP_PROGRAM_ID }] = await Promise.all([
+ import('@pump-fun/agent-payments-sdk'),
+ ]);
+
+ const payerPk = relayer ? relayer.publicKey : solanaPubkey(m.mint);
+ const params = {
+ globalBuybackAuthority: payerPk, // gated by globalConfig — for skipped-swap form, can be relayer
+ currencyMint: currency,
+ swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel program for skip-swap path
+ swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
+ remainingAccounts: [],
+ };
+
+ if (fullSwap) {
+ // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
+ // keepers should supply this off-chain until tested on devnet.
+ }
+
+ let ix;
+ try {
+ ix = await offline.buybackTrigger(params);
+ } catch (e) {
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${'buybackTrigger build failed: ' + e.message})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: e.message, run_id: run.id });
+ continue;
+ }
+
+ if (!relayer) {
+ const txBase64 = await buildUnsignedTxBase64({
+ network: m.network,
+ payer: payerPk,
+ instructions: [ix],
+ });
+ const [run] = await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, burn_amount)
+ values (${m.id}, ${currencyStr}, 'pending', ${buyback.toString()})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
+ continue;
+ }
+
+ const connection = getConnection({ network: m.network });
+ const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
+ const tx = new Transaction();
+ tx.add(ix);
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.feePayer = relayer.publicKey;
+ tx.sign(relayer);
+ const sig = await connection.sendRawTransaction(tx.serialize());
+ await connection.confirmTransaction(sig, 'confirmed');
+
+ const [run] = await sql`
+ insert into pump_buyback_runs
+ (mint_id, currency_mint, tx_signature, status, burn_amount)
+ values
+ (${m.id}, ${currencyStr}, ${sig}, 'confirmed', ${buyback.toString()})
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
+ } catch (err) {
+ await sql`
+ insert into pump_buyback_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: err.message });
+ }
+ }
+
+ return json(res, 200, { ok: true, processed: results.length, results });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-dca
+// ═══════════════════════════════════════════════════════════════════════════
+
+const DCA_CHAIN_CONFIG = {
+ 84532: {
+ chain: baseSepolia,
+ swap_router: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
+ quoter_v2: '0xC5290058841028F1614F3A6F0F5816cAd0df5E27',
+ },
+ 8453: {
+ chain: base,
+ swap_router: '0x2626664c2603336E57B271c5C0b26F421741e481',
+ quoter_v2: '0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a',
+ },
+};
+
+const QUOTER_V2_ABI = parseAbi([
+ 'function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)',
+]);
+
+const SWAP_ROUTER_ABI = parseAbi([
+ 'function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) external payable returns (uint256 amountOut)',
+]);
+
+const ERC20_ABI = parseAbi([
+ 'function approve(address spender, uint256 amount) external returns (bool)',
+]);
+
+// Uniswap V3 standard fee tier — 0.3% pool is the most liquid USDC/WETH tier
+const FEE_TIER = 3000;
+
+const DCA_RPC_TIMEOUT_MS = 10_000;
+const DCA_RPC_MAX_RETRIES = 2; // total attempts = 1 + retries
+const DCA_RELAYER_TIMEOUT_MS = 30_000;
+const DCA_RELAYER_MAX_RETRIES = 1;
+const DCA_RELAYER_RETRY_BACKOFF_MS = 1_500;
+
+function dcaLog(level, event, fields = {}) {
+ const line = JSON.stringify({
+ level,
+ event,
+ ts: new Date().toISOString(),
+ component: 'cron/run-dca',
+ ...fields,
+ });
+ if (level === 'error') console.error(line);
+ else console.log(line);
+}
+
+function dcaIsTransient(err) {
+ // Network-level & RPC transport errors
+ const code = err?.code;
+ const name = err?.name;
+ const status = err?.status;
+ if (name === 'AbortError' || name === 'TimeoutError') return true;
+ if (
+ code === 'ETIMEDOUT' ||
+ code === 'ECONNRESET' ||
+ code === 'ECONNREFUSED' ||
+ code === 'ENOTFOUND' ||
+ code === 'EAI_AGAIN'
+ )
+ return true;
+ if (typeof status === 'number' && status >= 500 && status < 600) return true;
+ // viem transport errors
+ const msg = String(err?.message || '');
+ if (/HttpRequestError|TimeoutError|fetch failed|network|socket hang up/i.test(msg)) return true;
+ return false;
+}
+
+async function dcaWithRetry(fn, { retries, backoffMs = 500, label }) {
+ let attempt = 0;
+ // eslint-disable-next-line no-constant-condition
+ while (true) {
+ try {
+ return await fn();
+ } catch (err) {
+ attempt++;
+ if (attempt > retries || !dcaIsTransient(err)) throw err;
+ const delay = backoffMs * 2 ** (attempt - 1);
+ dcaLog('warn', 'retry', {
+ label,
+ attempt,
+ delay_ms: delay,
+ message: err?.message,
+ code: err?.code,
+ });
+ await new Promise((r) => setTimeout(r, delay));
+ }
+ }
+}
+
+function dcaGetViemClient(chainId) {
+ const cfg = DCA_CHAIN_CONFIG[chainId];
+ if (!cfg) throw new Error(`Unsupported chainId: ${chainId}`);
+ const rpcUrl = env.getRpcUrl(chainId);
+ const transport = rpcUrl
+ ? http(rpcUrl, { timeout: DCA_RPC_TIMEOUT_MS, retryCount: 0 })
+ : http(undefined, { timeout: DCA_RPC_TIMEOUT_MS, retryCount: 0 });
+ return createPublicClient({ chain: cfg.chain, transport });
+}
+
+/**
+ * Fetch a quote twice 15s apart; abort if they diverge by more than 0.5%.
+ * Returns { amountOut, divergenceBps } or throws if divergence exceeds limit.
+ */
+async function dcaGetVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amountIn, logCtx) {
+ const params = {
+ tokenIn,
+ tokenOut,
+ amountIn: BigInt(amountIn),
+ fee: FEE_TIER,
+ sqrtPriceLimitX96: 0n,
+ };
+
+ const readQuote = () =>
+ client.readContract({
+ address: quoterAddress,
+ abi: QUOTER_V2_ABI,
+ functionName: 'quoteExactInputSingle',
+ args: [params],
+ });
+
+ // First quote (with retry on transient RPC failures)
+ const [q1] = await dcaWithRetry(readQuote, {
+ retries: DCA_RPC_MAX_RETRIES,
+ backoffMs: 500,
+ label: `quote1:${logCtx?.strategy_id ?? ''}`,
+ });
+
+ // Wait 15s then quote again
+ await new Promise((r) => setTimeout(r, 15_000));
+
+ const [q2] = await dcaWithRetry(readQuote, {
+ retries: DCA_RPC_MAX_RETRIES,
+ backoffMs: 500,
+ label: `quote2:${logCtx?.strategy_id ?? ''}`,
+ });
+
+ // Divergence in basis points: |q2-q1| / q1 * 10000
+ const divergenceBps = q1 === 0n ? 0 : Number(((q2 > q1 ? q2 - q1 : q1 - q2) * 10000n) / q1);
+
+ if (divergenceBps > 50) {
+ throw Object.assign(
+ new Error(`Quote divergence ${divergenceBps}bps exceeds 50bps limit — aborting`),
+ { code: 'quote_divergence', divergenceBps },
+ );
+ }
+
+ // Use the more conservative (lower) of the two quotes
+ const amountOut = q1 < q2 ? q1 : q2;
+ return { amountOut, divergenceBps };
+}
+
+function dcaBuildApproveCalldata(spender, amount) {
+ return encodeFunctionData({
+ abi: ERC20_ABI,
+ functionName: 'approve',
+ args: [spender, BigInt(amount)],
+ });
+}
+
+function dcaBuildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum) {
+ return encodeFunctionData({
+ abi: SWAP_ROUTER_ABI,
+ functionName: 'exactInputSingle',
+ args: [
+ {
+ tokenIn,
+ tokenOut,
+ fee: FEE_TIER,
+ recipient,
+ amountIn: BigInt(amountIn),
+ amountOutMinimum: BigInt(amountOutMinimum),
+ sqrtPriceLimitX96: 0n,
+ },
+ ],
+ });
+}
+
+async function dcaRedeemViaRelayer(delegationId, calls, logCtx) {
+ const relayerUrl = `${env.APP_ORIGIN}/api/permissions/redeem`;
+
+ const doFetch = async () => {
+ const res = await fetch(relayerUrl, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ authorization: `Bearer ${env.CRON_SECRET}`,
+ },
+ body: JSON.stringify({ id: delegationId, calls }),
+ signal: AbortSignal.timeout(DCA_RELAYER_TIMEOUT_MS),
+ });
+
+ if (!res.ok) {
+ const body = await res.json().catch(() => ({ message: res.statusText }));
+ throw Object.assign(
+ new Error(body.error_description || body.message || `Relayer ${res.status}`),
+ { code: body.error || 'relayer_error', status: res.status },
+ );
+ }
+ return res.json();
+ };
+
+ return dcaWithRetry(doFetch, {
+ retries: DCA_RELAYER_MAX_RETRIES,
+ backoffMs: DCA_RELAYER_RETRY_BACKOFF_MS,
+ label: `relayer:${logCtx?.strategy_id ?? ''}`,
+ });
+}
+
+async function dcaOnPeriod(strategy) {
+ const {
+ id: strategyId,
+ delegation_id: delegationId,
+ chain_id: chainId,
+ token_in: tokenIn,
+ token_out: tokenOut,
+ amount_per_execution: amountIn,
+ slippage_bps: slippageBps,
+ } = strategy;
+
+ const cfg = DCA_CHAIN_CONFIG[chainId];
+ if (!cfg)
+ throw Object.assign(new Error(`No config for chainId ${chainId}`), {
+ code: 'unsupported_chain',
+ });
+
+ const client = dcaGetViemClient(chainId);
+ const logCtx = { strategy_id: strategyId, chain_id: chainId };
+
+ // Get verified quote
+ const { amountOut, divergenceBps } = await dcaGetVerifiedQuote(
+ client,
+ cfg.quoter_v2,
+ tokenIn,
+ tokenOut,
+ amountIn,
+ logCtx,
+ );
+
+ // Apply slippage: amountOutMinimum = amountOut * (10000 - slippageBps) / 10000
+ const amountOutMinimum = (amountOut * BigInt(10000 - slippageBps)) / 10000n;
+
+ // Resolve recipient — use the delegator address from the delegation row
+ const [delegationRow] = await sql`
+ SELECT delegator_address FROM agent_delegations
+ WHERE id = ${delegationId} AND status = 'active'
+ LIMIT 1
+ `;
+ if (!delegationRow) {
+ throw Object.assign(new Error('Delegation not found or no longer active'), {
+ code: 'delegation_gone',
+ });
+ }
+ const recipient = delegationRow.delegator_address;
+
+ // Build calls: [approve USDC → SwapRouter, exactInputSingle]
+ const calls = [
+ {
+ to: tokenIn,
+ value: '0',
+ data: dcaBuildApproveCalldata(cfg.swap_router, amountIn),
+ },
+ {
+ to: cfg.swap_router,
+ value: '0',
+ data: dcaBuildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum),
+ },
+ ];
+
+ // Submit via relayer
+ const result = await dcaRedeemViaRelayer(delegationId, calls, logCtx);
+
+ return { txHash: result.txHash, quoteAmountOut: amountOut.toString(), divergenceBps };
+}
+
+async function handleRunDca(req, res) {
+ // Vercel cron passes Authorization: Bearer $CRON_SECRET
+ const cronSecret = env.CRON_SECRET;
+ if (cronSecret) {
+ const auth = req.headers.authorization || '';
+ if (auth !== `Bearer ${cronSecret}`) {
+ return error(res, 401, 'unauthorized', 'invalid cron secret');
+ }
+ }
+
+ const runId = globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`;
+ dcaLog('info', 'tick_start', { run_id: runId });
+
+ // Fetch all due active strategies
+ let strategies;
+ try {
+ strategies = await sql`
+ SELECT
+ s.id, s.delegation_id, s.chain_id,
+ s.token_in, s.token_out, s.amount_per_execution,
+ s.period_seconds, s.slippage_bps, s.agent_id,
+ ad.status AS delegation_status, ad.expires_at AS delegation_expires_at
+ FROM dca_strategies s
+ JOIN agent_delegations ad ON ad.id = s.delegation_id
+ WHERE s.status = 'active'
+ AND s.next_execution_at <= NOW()
+ ORDER BY s.next_execution_at ASC
+ LIMIT 50
+ `;
+ } catch (err) {
+ dcaLog('error', 'fetch_due_failed', { run_id: runId, message: err?.message });
+ throw err;
+ }
+
+ const results = [];
+ for (const strategy of strategies) {
+ const logCtx = { run_id: runId, strategy_id: strategy.id, chain_id: strategy.chain_id };
+
+ const execRow = {
+ strategy_id: strategy.id,
+ chain_id: strategy.chain_id,
+ amount_in: strategy.amount_per_execution,
+ slippage_bps_used: strategy.slippage_bps,
+ status: 'pending',
+ };
+
+ // Check delegation is still alive before spending gas on a quote
+ if (strategy.delegation_status !== 'active') {
+ await sql`
+ UPDATE dca_strategies SET status = 'paused' WHERE id = ${strategy.id}
+ `;
+ execRow.status = 'aborted';
+ execRow.error = `Delegation ${strategy.delegation_status}`;
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
+ );
+ dcaLog('info', 'skipped', { ...logCtx, reason: execRow.error });
+ results.push({ id: strategy.id, skipped: true, reason: execRow.error });
+ continue;
+ }
+
+ if (new Date(strategy.delegation_expires_at) <= new Date()) {
+ await sql`
+ UPDATE dca_strategies SET status = 'expired' WHERE id = ${strategy.id}
+ `;
+ execRow.status = 'aborted';
+ execRow.error = 'Delegation expired';
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
+ );
+ dcaLog('info', 'skipped', { ...logCtx, reason: execRow.error });
+ results.push({ id: strategy.id, skipped: true, reason: execRow.error });
+ continue;
+ }
+
+ // ── Idempotency claim ───────────────────────────────────────────────
+ // Atomically advance next_execution_at so a concurrent tick (or a retry
+ // of this tick) will not re-pick this row. We advance by period_seconds
+ // provisionally; on success we leave it; on failure we reset to NOW so
+ // the next tick retries it.
+ const nowIso = new Date().toISOString();
+ const provisionalNextIso = new Date(
+ Date.now() + strategy.period_seconds * 1000,
+ ).toISOString();
+
+ const claim = await sql`
+ UPDATE dca_strategies
+ SET next_execution_at = ${provisionalNextIso}
+ WHERE id = ${strategy.id}
+ AND status = 'active'
+ AND next_execution_at <= ${nowIso}
+ RETURNING id
+ `;
+ if (claim.length === 0) {
+ dcaLog('info', 'claim_lost', { ...logCtx });
+ results.push({ id: strategy.id, skipped: true, reason: 'claim_lost' });
+ continue;
+ }
+
+ dcaLog('info', 'execute_start', { ...logCtx });
+
+ try {
+ const { txHash, quoteAmountOut, divergenceBps } = await dcaOnPeriod(strategy);
+
+ execRow.tx_hash = txHash;
+ execRow.quote_amount_out = quoteAmountOut;
+ execRow.quote_divergence_bps = divergenceBps;
+ execRow.status = 'success';
+
+ await sql`
+ UPDATE dca_strategies
+ SET last_execution_at = NOW()
+ WHERE id = ${strategy.id}
+ `;
+
+ dcaLog('info', 'execute_success', {
+ ...logCtx,
+ tx_hash: txHash,
+ divergence_bps: divergenceBps,
+ });
+ results.push({ id: strategy.id, txHash, quoteAmountOut });
+ } catch (err) {
+ execRow.status = err.code === 'quote_divergence' ? 'aborted' : 'failed';
+ execRow.error = err.message;
+ execRow.quote_divergence_bps = err.divergenceBps ?? null;
+
+ // Release the idempotency claim so the next tick can retry this
+ // strategy — but only for transient / recoverable failures. For
+ // aborts (quote_divergence, delegation_gone) leave the advanced
+ // next_execution_at in place so we wait the full period.
+ const shouldRetryNextTick =
+ err.code !== 'quote_divergence' &&
+ err.code !== 'delegation_gone' &&
+ err.code !== 'unsupported_chain';
+ if (shouldRetryNextTick) {
+ await sql`
+ UPDATE dca_strategies
+ SET next_execution_at = ${nowIso}
+ WHERE id = ${strategy.id}
+ `.catch((e) => dcaLog('error', 'claim_release_failed', { ...logCtx, message: e?.message }));
+ }
+
+ dcaLog('error', 'execute_failed', {
+ ...logCtx,
+ code: err.code,
+ message: err.message,
+ status: err.status,
+ will_retry_next_tick: shouldRetryNextTick,
+ });
+ results.push({ id: strategy.id, error: err.message, code: err.code });
+ }
+
+ // Insert execution record regardless of outcome
+ await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
+ );
+ }
+
+ dcaLog('info', 'tick_done', { run_id: runId, processed: strategies.length });
+
+ return json(res, 200, {
+ ok: true,
+ processed: strategies.length,
+ results,
+ });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-distribute-payments
+// ═══════════════════════════════════════════════════════════════════════════
+
+const DISTRIBUTE_CRON_RELAYER_SECRET_KEY_B64 = () =>
+ process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64 || null;
+
+async function distributeLoadRelayer() {
+ const b64 = DISTRIBUTE_CRON_RELAYER_SECRET_KEY_B64();
+ if (!b64) return null;
+ const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
+ return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
+}
+
+async function handleRunDistributePayments(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ // Auth: cron secret OR admin bearer.
+ const auth = req.headers.authorization || '';
+ const cronSecret = env.CRON_SECRET;
+ if (!cronSecret) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
+ if (auth !== `Bearer ${cronSecret}`) {
+ return error(res, 401, 'unauthorized', 'cron auth required');
+ }
+
+ // Pick mints to consider: those with confirmed payments since last
+ // distribute run, or never run before.
+ const mints = await sql`
+ select m.id, m.mint, m.network, m.buyback_bps
+ from pump_agent_mints m
+ where exists (
+ select 1 from pump_agent_payments p
+ where p.mint_id = m.id and p.status = 'confirmed'
+ and (
+ p.confirmed_at > coalesce(
+ (select max(created_at) from pump_distribute_runs r where r.mint_id = m.id),
+ 'epoch'::timestamptz
+ )
+ )
+ )
+ limit 200
+ `;
+
+ const relayer = await distributeLoadRelayer();
+ const results = [];
+
+ for (const m of mints) {
+ const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
+ const currency = solanaPubkey(currencyStr);
+
+ try {
+ const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
+ const balancesBefore = await agent.getBalances(currency);
+ const paymentBalance = BigInt(balancesBefore.paymentVault.balance ?? 0);
+
+ if (paymentBalance === 0n) {
+ const [run] = await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
+ values (${m.id}, ${currencyStr}, 'skipped', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
+ continue;
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
+
+ if (!relayer) {
+ // No relayer: build unsigned tx for an external keeper. Persist run as 'pending'.
+ const ixs = await offline.distributePayments({
+ user: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
+ currencyMint: currency,
+ });
+ const txBase64 = await buildUnsignedTxBase64({
+ network: m.network,
+ payer: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
+ instructions: Array.isArray(ixs) ? ixs : [ixs],
+ });
+ const [run] = await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
+ values (${m.id}, ${currencyStr}, 'pending', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
+ continue;
+ }
+
+ // Relayer path: sign + send.
+ const ixs = await offline.distributePayments({
+ user: relayer.publicKey,
+ currencyMint: currency,
+ });
+ const connection = getConnection({ network: m.network });
+ const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
+ const tx = new Transaction();
+ tx.add(...(Array.isArray(ixs) ? ixs : [ixs]));
+ const { blockhash } = await connection.getLatestBlockhash('confirmed');
+ tx.recentBlockhash = blockhash;
+ tx.feePayer = relayer.publicKey;
+ tx.sign(relayer);
+ const sig = await connection.sendRawTransaction(tx.serialize(), {
+ skipPreflight: false,
+ });
+ await connection.confirmTransaction(sig, 'confirmed');
+
+ const balancesAfter = await agent.getBalances(currency);
+ const [run] = await sql`
+ insert into pump_distribute_runs
+ (mint_id, currency_mint, tx_signature, status, balances_before, balances_after)
+ values
+ (${m.id}, ${currencyStr}, ${sig}, 'confirmed',
+ ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb,
+ ${JSON.stringify({
+ buyback: balancesAfter.buybackVault?.balance?.toString?.(),
+ withdraw: balancesAfter.withdrawVault?.balance?.toString?.(),
+ })}::jsonb)
+ returning id
+ `;
+ results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
+ } catch (err) {
+ await sql`
+ insert into pump_distribute_runs (mint_id, currency_mint, status, error)
+ values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
+ `;
+ results.push({ mint: m.mint, status: 'failed', error: err.message });
+ }
+ }
+
+ return json(res, 200, {
+ ok: true,
+ processed: results.length,
+ relayer: relayer ? relayer.publicKey.toBase58() : null,
+ results,
+ });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// run-subscriptions
+// ═══════════════════════════════════════════════════════════════════════════
+
+// USDC contract addresses by chain ID.
+const USDC_BY_CHAIN = {
+ 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
+ 11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
+};
+
+// Max time we'll wait for the skill's onPeriod (which fetches the relayer).
+// Override via SUBSCRIPTION_CHARGE_TIMEOUT_MS.
+const ONPERIOD_TIMEOUT_MS = parseInt(process.env.SUBSCRIPTION_CHARGE_TIMEOUT_MS ?? '30000', 10);
+
+// Structured log helper — single-line JSON so Vercel log drains can parse it.
+function subLog(event, fields = {}) {
+ try {
+ console.log(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
+ } catch {
+ // Never let logging throw.
+ }
+}
+
+function subLogError(event, fields = {}) {
+ try {
+ console.error(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
+ } catch {
+ // Never let logging throw.
+ }
+}
+
+// Race a promise against a timeout. Rejects with a tagged error on timeout.
+function subWithTimeout(promise, ms, label) {
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => {
+ const err = new Error(`${label} timed out after ${ms}ms`);
+ err.code = 'timeout';
+ reject(err);
+ }, ms);
+ Promise.resolve(promise).then(
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
+ );
+ });
+}
+
+async function handleRunSubscriptions(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ // Auth: Vercel Cron header OR explicit Bearer $CRON_SECRET.
+ // If neither is configured AND no Vercel cron header is present, reject.
+ const auth = req.headers['authorization'] ?? '';
+ const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
+ const fromVercelCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromVercelCron) {
+ if (!expected || auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+ }
+
+ const runId = `sub-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
+ const runStart = Date.now();
+ subLog('subscription_cron.start', { runId, fromVercelCron });
+
+ const origin = env.APP_ORIGIN;
+ const relayerToken = env.CRON_SECRET ?? '';
+
+ const report = {
+ runId,
+ processed: 0,
+ charged: 0,
+ skipped: 0,
+ paused: 0,
+ claimLost: 0,
+ errors: [],
+ };
+
+ // Load the skill's onPeriod handler once per invocation.
+ let onPeriod;
+ try {
+ ({ onPeriod } = await import('../../public/skills/subscription/skill.js'));
+ } catch (err) {
+ subLogError('subscription_cron.skill_load_failed', { runId, message: err.message });
+ return error(res, 500, 'internal_error', 'failed to load subscription skill');
+ }
+
+ // Select all active subscriptions whose charge window has arrived.
+ let rows;
+ try {
+ rows = await sql`
+ SELECT
+ s.id,
+ s.user_id,
+ s.agent_id,
+ s.delegation_id,
+ s.period_seconds,
+ s.amount_per_period,
+ s.next_charge_at,
+ s.last_charge_at,
+ d.status AS delegation_status,
+ d.expires_at AS delegation_expires_at,
+ d.chain_id,
+ ai.wallet_address AS owner_address
+ FROM agent_subscriptions s
+ JOIN agent_delegations d ON d.id = s.delegation_id
+ JOIN agent_identities ai ON ai.id = s.agent_id
+ WHERE s.status = 'active'
+ AND s.next_charge_at <= NOW()
+ `;
+ } catch (err) {
+ subLogError('subscription_cron.select_failed', { runId, message: err.message });
+ return error(res, 500, 'internal_error', 'failed to load subscriptions');
+ }
+
+ subLog('subscription_cron.selected', { runId, count: rows.length });
+
+ for (const row of rows) {
+ report.processed++;
+ const rowStart = Date.now();
+ const ctx = { runId, subscriptionId: row.id, agentId: row.agent_id };
+
+ try {
+ // Guard: delegation must still be active.
+ if (row.delegation_status !== 'active') {
+ await subPause(row.id, `delegation_${row.delegation_status}`);
+ report.paused++;
+ report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });
+ subLog('subscription_cron.paused', {
+ ...ctx,
+ reason: `delegation_${row.delegation_status}`,
+ });
+ continue;
+ }
+
+ // Guard: delegation must not be expired.
+ if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {
+ await subPause(row.id, 'delegation_expired');
+ report.paused++;
+ report.errors.push({ id: row.id, reason: 'delegation_expired' });
+ subLog('subscription_cron.paused', { ...ctx, reason: 'delegation_expired' });
+ continue;
+ }
+
+ const usdcAddress = USDC_BY_CHAIN[row.chain_id];
+ if (!usdcAddress) {
+ await subPause(row.id, `chain_${row.chain_id}_unsupported`);
+ report.skipped++;
+ report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });
+ subLog('subscription_cron.skipped', {
+ ...ctx,
+ reason: `chain_${row.chain_id}_unsupported`,
+ });
+ continue;
+ }
+
+ // Atomic claim: mark this period as being processed by writing
+ // last_charge_at = NOW(). Matches only if:
+ // - next_charge_at hasn't moved (no racing writer),
+ // - status is still active,
+ // - last_charge_at is NULL OR < next_charge_at (not already claimed for this period).
+ // If 0 rows returned, another worker claimed this period — skip.
+ const claim = await sql`
+ UPDATE agent_subscriptions
+ SET last_charge_at = NOW()
+ WHERE id = ${row.id}
+ AND status = 'active'
+ AND next_charge_at = ${row.next_charge_at}
+ AND (last_charge_at IS NULL OR last_charge_at < next_charge_at)
+ RETURNING id
+ `;
+ if (claim.length === 0) {
+ report.claimLost++;
+ subLog('subscription_cron.claim_lost', ctx);
+ continue;
+ }
+
+ let result;
+ try {
+ result = await subWithTimeout(
+ onPeriod({
+ agent: {
+ agentId: row.agent_id,
+ chainId: row.chain_id,
+ ownerAddress: row.owner_address,
+ usdcAddress,
+ relayerToken,
+ origin,
+ },
+ subscription: {
+ id: row.id,
+ delegationId: row.delegation_id,
+ amountPerPeriod: row.amount_per_period,
+ },
+ }),
+ ONPERIOD_TIMEOUT_MS,
+ 'onPeriod',
+ );
+ } catch (err) {
+ const reason =
+ (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');
+ await subSafePause(row.id, reason, ctx);
+ report.paused++;
+ report.errors.push({ id: row.id, reason });
+ subLogError('subscription_cron.onperiod_threw', {
+ ...ctx,
+ code: err.code ?? 'unknown',
+ message: err.message ?? 'unknown',
+ durationMs: Date.now() - rowStart,
+ });
+ continue;
+ }
+
+ if (result && result.ok) {
+ // Advance next_charge_at by exactly one period to enforce idempotency.
+ const nextChargeAt = new Date(
+ Date.parse(row.next_charge_at) + row.period_seconds * 1000,
+ );
+ try {
+ await sql`
+ UPDATE agent_subscriptions
+ SET next_charge_at = ${nextChargeAt.toISOString()},
+ last_error = NULL
+ WHERE id = ${row.id}
+ `;
+ } catch (err) {
+ // Charge succeeded on-chain but we failed to advance — log loudly.
+ // Do NOT pause: next run's claim guard will prevent double-charge
+ // since last_charge_at >= next_charge_at for this period.
+ subLogError('subscription_cron.advance_failed', {
+ ...ctx,
+ message: err.message,
+ txHash: result.txHash,
+ });
+ report.errors.push({
+ id: row.id,
+ reason: 'advance_failed',
+ message: err.message,
+ });
+ continue;
+ }
+
+ // Emit usage event — non-fatal if the table schema differs.
+ await sql`
+ INSERT INTO usage_events (user_id, kind, tool, status)
+ VALUES (${row.user_id}, 'subscription_charge', 'subscription', 'success')
+ `.catch((err) =>
+ subLogError('subscription_cron.usage_event_failed', {
+ ...ctx,
+ message: err.message,
+ }),
+ );
+
+ report.charged++;
+ subLog('subscription_cron.charged', {
+ ...ctx,
+ txHash: result.txHash,
+ durationMs: Date.now() - rowStart,
+ });
+ } else {
+ const code = result?.code ?? 'unknown';
+ const message = result?.message ?? '';
+ await subSafePause(row.id, `${code}: ${message}`.slice(0, 500), ctx);
+ report.paused++;
+ report.errors.push({ id: row.id, code, message });
+ subLog('subscription_cron.paused', {
+ ...ctx,
+ code,
+ message,
+ durationMs: Date.now() - rowStart,
+ });
+ }
+ } catch (err) {
+ // Catch-all so one bad row can't kill the run.
+ subLogError('subscription_cron.row_unhandled', {
+ ...ctx,
+ message: err.message ?? 'unknown',
+ stack: err.stack,
+ });
+ report.errors.push({ id: row.id, reason: 'unhandled', message: err.message });
+ // Best-effort pause so we don't loop on the same broken row next hour.
+ await subSafePause(row.id, `unhandled: ${(err.message ?? 'unknown').slice(0, 480)}`, ctx);
+ report.paused++;
+ }
+ }
+
+ subLog('subscription_cron.done', {
+ runId,
+ durationMs: Date.now() - runStart,
+ processed: report.processed,
+ charged: report.charged,
+ paused: report.paused,
+ skipped: report.skipped,
+ claimLost: report.claimLost,
+ errorCount: report.errors.length,
+ });
+
+ return json(res, 200, report);
+}
+
+async function subPause(id, lastError) {
+ await sql`
+ UPDATE agent_subscriptions
+ SET status = 'paused', last_error = ${lastError}
+ WHERE id = ${id}
+ `;
+}
+
+// Like subPause but swallows its own errors so a DB hiccup during pause doesn't
+// propagate out of the per-row handler. Logs the failure for ops visibility.
+async function subSafePause(id, lastError, ctx) {
+ try {
+ await subPause(id, lastError);
+ } catch (err) {
+ subLogError('subscription_cron.pause_failed', {
+ ...ctx,
+ lastError,
+ message: err.message,
+ });
+ }
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// solana-attest-event-cleanup
+// ═══════════════════════════════════════════════════════════════════════════
+
+const STALE_AFTER_SECS = 60 * 60; // 1 hour
+
+async function handleSolanaAttestEventCleanup(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ const result = await sql`
+ delete from solana_attest_event_claims
+ where signature is null
+ and claimed_at < now() - (${STALE_AFTER_SECS} || ' seconds')::interval
+ returning agent_asset, network, event_id, claimed_at
+ `;
+
+ return json(res, 200, {
+ deleted: result.length,
+ stale_after_secs: STALE_AFTER_SECS,
+ samples: result.slice(0, 10),
+ });
+}
+
+// ═══════════════════════════════════════════════════════════════════════════
+// solana-attestations-crawl
+// ═══════════════════════════════════════════════════════════════════════════
+
+const SOL_ATTEST_PER_RUN_MAX = 50; // bound RPC fan-out per cron tick
+
+async function handleSolanaAttestationsCrawl(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ const auth = req.headers['authorization'] || '';
+ const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
+ const fromCron = req.headers['x-vercel-cron'] === '1';
+ if (!fromCron && expected && auth !== expected) {
+ return error(res, 401, 'unauthorized', 'cron secret required');
+ }
+
+ // Pull Solana agents, oldest-cursor first.
+ const agents = await sql`
+ select
+ a.id,
+ a.meta->>'sol_mint_address' as agent_asset,
+ coalesce(a.meta->>'network', 'mainnet') as network,
+ a.wallet_address as owner_wallet,
+ c.last_indexed_at
+ from agent_identities a
+ left join solana_attestations_cursor c
+ on c.agent_asset = a.meta->>'sol_mint_address'
+ where a.deleted_at is null
+ and a.meta ? 'sol_mint_address'
+ order by c.last_indexed_at nulls first
+ limit ${SOL_ATTEST_PER_RUN_MAX}
+ `;
+
+ const report = { agents: [], errors: [] };
+ for (const row of agents) {
+ try {
+ const r = await crawlAgentAttestations({
+ agentAsset: row.agent_asset,
+ network: row.network,
+ ownerWallet: row.owner_wallet,
+ });
+ report.agents.push({ asset: row.agent_asset, ...r });
+ } catch (err) {
+ report.errors.push({ asset: row.agent_asset, error: err.message || String(err) });
+ }
+ }
+
+ return json(res, 200, report);
+}
diff --git a/api/cron/erc8004-crawl.js b/api/cron/erc8004-crawl.js
deleted file mode 100644
index 494a29591..000000000
--- a/api/cron/erc8004-crawl.js
+++ /dev/null
@@ -1,267 +0,0 @@
-/**
- * ERC-8004 directory crawler — indexes every `Registered` event from every
- * chain in CHAINS into the `erc8004_agents_index` table, then enriches a
- * batch of rows with their agentURI metadata (name, image, GLB, services).
- *
- * Runs on Vercel Cron every 15 minutes (see vercel.json crons). Also callable
- * manually via `POST /api/cron/erc8004-crawl` with `Authorization: Bearer
- * $CRON_SECRET` for on-demand refreshes.
- *
- * Flow per chain:
- * 1. Read last scanned block from erc8004_crawl_cursor.
- * 2. eth_getLogs over the next BLOCK_CHUNK blocks via the chain's public RPC.
- * 3. Decode agentId (topic1), owner (topic2), agentURI (data) and upsert.
- * 4. Fetch block timestamps for events found (eth_getBlockByNumber).
- * 5. Advance cursor to end of scanned range.
- *
- * Metadata pass: pick the 20 oldest-metadata rows, fetch JSON, extract
- * name/description/image/services/has_3d, write back.
- */
-
-import { id as keccakId, AbiCoder, getAddress } from 'ethers';
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { CHAINS } from '../_lib/erc8004-chains.js';
-
-const REGISTERED_TOPIC = keccakId('Registered(uint256,string,address)');
-const ABI_CODER = AbiCoder.defaultAbiCoder();
-
-// Blocks scanned per chain per cron invocation. Public RPCs typically allow
-// 2000-block ranges; lower this if a chain's RPC rejects with "block range".
-const BLOCK_CHUNK = 2_000;
-
-// On first run (no cursor), scan this many recent blocks. Set
-// ERC8004_CRAWL_LOOKBACK env var to override (e.g. larger for backfill).
-const DEFAULT_LOOKBACK = parseInt(process.env.ERC8004_CRAWL_LOOKBACK || '50000', 10);
-
-// Metadata enrichment per invocation.
-const METADATA_BATCH = 25;
-
-const FETCH_TIMEOUT_MS = 10_000;
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- const report = { chains: [], enriched: 0, errors: [] };
-
- for (const chain of CHAINS) {
- try {
- const r = await crawlChain(chain);
- report.chains.push({ chainId: chain.id, name: chain.name, ...r });
- } catch (err) {
- report.errors.push({ chainId: chain.id, error: err.message || String(err) });
- }
- }
-
- try {
- report.enriched = await enrichMetadata(METADATA_BATCH);
- } catch (err) {
- report.errors.push({ stage: 'metadata', error: err.message || String(err) });
- }
-
- return json(res, 200, report);
-});
-
-// ─── Log crawl ───────────────────────────────────────────────────────────
-
-async function crawlChain(chain) {
- const [cursor] = await sql`
- SELECT last_block FROM erc8004_crawl_cursor WHERE chain_id = ${chain.id}
- `;
-
- const latestHex = await rpcCall(chain.rpcUrl, 'eth_blockNumber', []);
- const latestBlock = Number.parseInt(latestHex, 16);
-
- const fromBlock = cursor
- ? Number(cursor.last_block) + 1
- : Math.max(0, latestBlock - DEFAULT_LOOKBACK);
-
- if (fromBlock > latestBlock) {
- return { inserted: 0, scanned: 0, lastBlock: latestBlock, fromBlock };
- }
-
- const toBlock = Math.min(fromBlock + BLOCK_CHUNK - 1, latestBlock);
-
- const logs = await rpcCall(chain.rpcUrl, 'eth_getLogs', [
- {
- address: chain.registry,
- topics: [REGISTERED_TOPIC],
- fromBlock: '0x' + fromBlock.toString(16),
- toBlock: '0x' + toBlock.toString(16),
- },
- ]);
-
- // Fetch block timestamps for any blocks that produced events.
- const blockTimes = {};
- if (logs.length > 0) {
- const uniqueBlockHexes = [...new Set(logs.map((l) => l.blockNumber))];
- await Promise.all(
- uniqueBlockHexes.map(async (bn) => {
- try {
- const block = await rpcCall(chain.rpcUrl, 'eth_getBlockByNumber', [bn, false]);
- blockTimes[bn] = block ? Number.parseInt(block.timestamp, 16) : null;
- } catch {
- // registered_at will be null for this block
- }
- }),
- );
- }
-
- let inserted = 0;
- for (const log of logs) {
- try {
- const agentId = BigInt(log.topics[1]).toString();
- const ownerHex = '0x' + log.topics[2].slice(-40);
- const owner = getAddress(ownerHex).toLowerCase();
- const [agentURI] = ABI_CODER.decode(['string'], log.data);
- const blockNumber = Number.parseInt(log.blockNumber, 16);
- const ts = blockTimes[log.blockNumber];
- const registeredAt = ts ? new Date(ts * 1000).toISOString() : null;
-
- await sql`
- INSERT INTO erc8004_agents_index
- (chain_id, agent_id, owner, registry, agent_uri,
- registered_block, registered_tx, registered_at, last_seen_at)
- VALUES
- (${chain.id}, ${agentId}, ${owner}, ${chain.registry.toLowerCase()},
- ${agentURI || null}, ${blockNumber}, ${log.transactionHash},
- ${registeredAt}, now())
- ON CONFLICT (chain_id, agent_id) DO UPDATE SET
- owner = excluded.owner,
- agent_uri = COALESCE(excluded.agent_uri, erc8004_agents_index.agent_uri),
- last_seen_at = now()
- `;
- inserted += 1;
- } catch (decodeErr) {
- console.warn('[crawl] decode failed', chain.id, log.transactionHash, decodeErr.message);
- }
- }
-
- // Always advance cursor to toBlock so the next run continues from here.
- await sql`
- INSERT INTO erc8004_crawl_cursor (chain_id, last_block, updated_at)
- VALUES (${chain.id}, ${toBlock}, now())
- ON CONFLICT (chain_id) DO UPDATE SET
- last_block = GREATEST(erc8004_crawl_cursor.last_block, ${toBlock}),
- updated_at = now()
- `;
-
- return { inserted, scanned: toBlock - fromBlock + 1, lastBlock: toBlock, fromBlock };
-}
-
-// ─── Metadata enrichment ─────────────────────────────────────────────────
-
-async function enrichMetadata(limit) {
- const rows = await sql`
- SELECT chain_id, agent_id, agent_uri
- FROM erc8004_agents_index
- WHERE agent_uri IS NOT NULL
- AND (last_metadata_at IS NULL OR last_metadata_at < now() - interval '7 days')
- ORDER BY last_metadata_at NULLS FIRST, registered_at DESC NULLS LAST
- LIMIT ${limit}
- `;
-
- let done = 0;
- for (const row of rows) {
- try {
- const meta = await fetchAgentMetadata(row.agent_uri);
- if (!meta) {
- await sql`
- UPDATE erc8004_agents_index
- SET metadata_error = 'fetch failed',
- last_metadata_at = now()
- WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
- `;
- continue;
- }
- const name = truncate(meta.name || '', 200);
- const description = truncate(meta.description || '', 1000);
- const image = resolveGateway(meta.image || '');
- const services = Array.isArray(meta.services) ? meta.services : [];
- const avatarSvc = services.find(
- (s) => String(s?.name || '').toLowerCase() === 'avatar' && s?.endpoint,
- );
- const glbUrl = avatarSvc ? resolveGateway(avatarSvc.endpoint) : null;
- const has3d = !!glbUrl;
- const active = meta.active !== false;
- const x402 = !!(meta.x402Support || meta.x402);
-
- await sql`
- UPDATE erc8004_agents_index
- SET name = ${name || null},
- description = ${description || null},
- image = ${image || null},
- glb_url = ${glbUrl},
- services = ${JSON.stringify(services)}::jsonb,
- has_3d = ${has3d},
- active = ${active},
- x402_support = ${x402},
- metadata_error = null,
- last_metadata_at = now()
- WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
- `;
- done += 1;
- } catch (err) {
- await sql`
- UPDATE erc8004_agents_index
- SET metadata_error = ${truncate(err.message || String(err), 500)},
- last_metadata_at = now()
- WHERE chain_id = ${row.chain_id} AND agent_id = ${row.agent_id}
- `;
- }
- }
- return done;
-}
-
-// ─── Helpers ─────────────────────────────────────────────────────────────
-
-async function rpcCall(url, method, params) {
- const ac = new AbortController();
- const t = setTimeout(() => ac.abort(), FETCH_TIMEOUT_MS);
- try {
- const res = await fetch(url, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- signal: ac.signal,
- });
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
- const data = await res.json();
- if (data.error) throw new Error(`RPC ${data.error.code}: ${data.error.message}`);
- return data.result;
- } finally {
- clearTimeout(t);
- }
-}
-
-async function fetchAgentMetadata(uri) {
- const url = resolveGateway(uri);
- if (!url) return null;
- try {
- const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
- if (!res.ok) return null;
- return await res.json();
- } catch {
- return null;
- }
-}
-
-function resolveGateway(uri) {
- if (!uri || typeof uri !== 'string') return '';
- if (uri.startsWith('ipfs://')) return 'https://ipfs.io/ipfs/' + uri.slice(7);
- if (uri.startsWith('ar://')) return 'https://arweave.net/' + uri.slice(5);
- if (uri.startsWith('http://') || uri.startsWith('https://')) return uri;
- return '';
-}
-
-function truncate(s, max) {
- if (!s) return '';
- return s.length > max ? s.slice(0, max) : s;
-}
diff --git a/api/cron/index-delegations.js b/api/cron/index-delegations.js
deleted file mode 100644
index 38f489490..000000000
--- a/api/cron/index-delegations.js
+++ /dev/null
@@ -1,253 +0,0 @@
-/**
- * Delegation event indexer — polls each supported chain for DelegationDisabled
- * and DelegationRedeemed events, reconciles against agent_delegations, and
- * updates status / redemption_count / last_redeemed_at.
- *
- * Also sweeps expired rows (expires_at < NOW()) in a single idempotent UPDATE.
- *
- * Runs on Vercel Cron every 5 minutes (see vercel.json). Also callable manually
- * via `POST /api/cron/index-delegations` with `Authorization: Bearer $CRON_SECRET`.
- *
- * Protocol-bus note: a future enhancement can emit a lightweight DB NOTIFY after
- * a revoke sync so that task-13's runtime cache (src/runtime/delegation-redeem.js)
- * invalidates without waiting for the next cron tick. Today the cache TTL covers
- * the gap. Plumbing: NOTIFY would fire here → a LISTEN connection in a persistent
- * worker picks it up → invalidates the in-memory delegation map keyed by agentId.
- */
-
-import { id as keccakId } from 'ethers';
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-import { DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';
-
-const DISABLED_TOPIC = keccakId('DelegationDisabled(address,bytes32)');
-const REDEEMED_TOPIC = keccakId('DelegationRedeemed(address,bytes32)');
-
-// Max blocks per eth_getLogs call. Public RPCs 429 above ~2000.
-const BLOCK_CAP = 2000;
-const RPC_TIMEOUT_MS = 10_000;
-
-// Approximate blocks per day, used only to seed the cursor on first run.
-const BLOCKS_PER_DAY = {
- 84532: 43200, // Base Sepolia ~2 s/block
- 11155111: 7200, // Sepolia ~12 s/block
-};
-
-// Public RPC fallbacks per chain — tried in order. Override primary via env RPC_<chainId>.
-const PUBLIC_RPCS = {
- 1: [
- 'https://cloudflare-eth.com',
- 'https://eth.llamarpc.com',
- 'https://rpc.ankr.com/eth',
- 'https://ethereum.publicnode.com',
- 'https://1rpc.io/eth',
- ],
- 8453: [
- 'https://mainnet.base.org',
- 'https://base.llamarpc.com',
- 'https://rpc.ankr.com/base',
- 'https://base.publicnode.com',
- 'https://1rpc.io/base',
- ],
- 84532: [
- 'https://sepolia.base.org',
- 'https://base-sepolia-rpc.publicnode.com',
- 'https://rpc.ankr.com/base_sepolia',
- ],
- 11155111: [
- 'https://rpc.sepolia.org',
- 'https://ethereum-sepolia-rpc.publicnode.com',
- 'https://rpc.ankr.com/eth_sepolia',
- 'https://1rpc.io/sepolia',
- ],
- 421614: [
- 'https://sepolia-rollup.arbitrum.io/rpc',
- 'https://arbitrum-sepolia.publicnode.com',
- 'https://rpc.ankr.com/arbitrum_sepolia',
- ],
- 11155420: [
- 'https://sepolia.optimism.io',
- 'https://optimism-sepolia.publicnode.com',
- 'https://rpc.ankr.com/optimism_sepolia',
- ],
-};
-
-function rpcUrls(chainId) {
- const envUrl = process.env[`RPC_${chainId}`];
- const fallbacks = PUBLIC_RPCS[chainId] ?? [];
- return envUrl ? [envUrl, ...fallbacks] : fallbacks;
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- const started = Date.now();
- const report = { chains: [], expiredSwept: 0, errors: [] };
-
- // Index each chain independently — one chain's RPC failure must not abort others.
- for (const [chainIdStr, contract] of Object.entries(DELEGATION_MANAGER_DEPLOYMENTS)) {
- const chainId = Number(chainIdStr);
- const t0 = Date.now();
- try {
- const r = await indexChain(chainId, contract);
- const summary = { chainId, ...r, elapsedMs: Date.now() - t0 };
- report.chains.push(summary);
- console.log(JSON.stringify({ stage: 'index-delegations', ...summary }));
- } catch (err) {
- const entry = { chainId, error: err.message || String(err) };
- report.errors.push(entry);
- console.error(JSON.stringify({ stage: 'index-delegations', ...entry }));
- }
- }
-
- // Expiry sweep — idempotent, catches expirations missed between grant and indexer.
- try {
- const swept = await sql`
- UPDATE agent_delegations
- SET status = 'expired'
- WHERE status = 'active' AND expires_at < NOW()
- RETURNING id
- `;
- report.expiredSwept = swept.length;
- } catch (err) {
- report.errors.push({ stage: 'expiry-sweep', error: err.message || String(err) });
- console.error(JSON.stringify({ stage: 'expiry-sweep', error: err.message }));
- }
-
- // Emit summary to usage_events (best-effort — non-fatal if table shape differs).
- try {
- await sql`
- INSERT INTO usage_events (kind, tool, status, latency_ms)
- VALUES ('permissions.indexer.tick', 'index-delegations', 'ok', ${Date.now() - started})
- `;
- } catch {
- /* non-fatal */
- }
-
- return json(res, 200, report);
-});
-
-// ─── Chain indexer ────────────────────────────────────────────────────────────
-
-async function indexChain(chainId, contract) {
- const urls = rpcUrls(chainId);
- if (!urls.length) throw new Error(`no RPC URL configured for chain ${chainId}`);
-
- const latestHex = await rpc(urls, 'eth_blockNumber', []);
- const latestBlock = parseInt(latestHex, 16);
-
- const [cursor] = await sql`
- SELECT last_indexed_block FROM indexer_state
- WHERE contract = ${contract.toLowerCase()} AND chain_id = ${chainId}
- `;
- const initialFrom = cursor
- ? Number(cursor.last_indexed_block) + 1
- : Math.max(0, latestBlock - (BLOCKS_PER_DAY[chainId] ?? 7200));
-
- let fromBlock = initialFrom;
- let toBlock = latestBlock; // updated each iteration; reflects final processed range
- let revokedCount = 0;
- let redeemedCount = 0;
-
- while (fromBlock <= latestBlock) {
- toBlock = Math.min(fromBlock + BLOCK_CAP - 1, latestBlock);
-
- const logs = await rpc(urls, 'eth_getLogs', [
- {
- address: contract,
- topics: [[DISABLED_TOPIC, REDEEMED_TOPIC]],
- fromBlock: '0x' + fromBlock.toString(16),
- toBlock: '0x' + toBlock.toString(16),
- },
- ]);
-
- if (logs.length > 0) {
- // Fetch block timestamps only for blocks that have events.
- const uniqueBlocks = [...new Set(logs.map((l) => l.blockNumber))];
- const blockTs = {};
- for (const bn of uniqueBlocks) {
- const block = await rpc(urls, 'eth_getBlockByNumber', [bn, false]);
- blockTs[bn] = new Date(parseInt(block.timestamp, 16) * 1000).toISOString();
- }
-
- for (const log of logs) {
- // topics[2] is the bytes32 delegationHash (indexed param, 0x-prefixed, 64 hex chars).
- const delegationHash = log.topics[2];
- const ts = blockTs[log.blockNumber];
-
- if (log.topics[0] === DISABLED_TOPIC) {
- const rows = await sql`
- UPDATE agent_delegations
- SET status = 'revoked',
- revoked_at = ${ts}::timestamptz,
- tx_hash_revoke = ${log.transactionHash}
- WHERE delegation_hash = ${delegationHash} AND status = 'active'
- RETURNING id
- `;
- revokedCount += rows.length;
- } else {
- const rows = await sql`
- UPDATE agent_delegations
- SET redemption_count = redemption_count + 1,
- last_redeemed_at = ${ts}::timestamptz
- WHERE delegation_hash = ${delegationHash}
- RETURNING id
- `;
- redeemedCount += rows.length;
- }
- }
- }
-
- // Advance cursor after each batch so a timeout preserves partial progress.
- await sql`
- INSERT INTO indexer_state (contract, chain_id, last_indexed_block, updated_at)
- VALUES (${contract.toLowerCase()}, ${chainId}, ${toBlock}, NOW())
- ON CONFLICT (contract, chain_id) DO UPDATE SET
- last_indexed_block = GREATEST(indexer_state.last_indexed_block, excluded.last_indexed_block),
- updated_at = NOW()
- `;
-
- fromBlock = toBlock + 1;
- }
-
- return { fromBlock: initialFrom, toBlock, revokedCount, redeemedCount };
-}
-
-// ─── RPC helper ──────────────────────────────────────────────────────────────
-
-async function rpc(urls, method, params) {
- let lastErr;
- for (const url of urls) {
- const ac = new AbortController();
- const t = setTimeout(() => ac.abort(), RPC_TIMEOUT_MS);
- try {
- const res = await fetch(url, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
- signal: ac.signal,
- });
- if (!res.ok) throw new Error(`RPC HTTP ${res.status} from ${url}`);
- const data = await res.json();
- if (data.error) {
- throw new Error(
- `RPC ${method} error: ${data.error.message ?? JSON.stringify(data.error)}`,
- );
- }
- return data.result;
- } catch (err) {
- lastErr = err;
- } finally {
- clearTimeout(t);
- }
- }
- throw lastErr;
-}
diff --git a/api/cron/pump-agent-stats.js b/api/cron/pump-agent-stats.js
deleted file mode 100644
index ba0d85299..000000000
--- a/api/cron/pump-agent-stats.js
+++ /dev/null
@@ -1,215 +0,0 @@
-// GET/POST /api/cron/pump-agent-stats
-//
-// For every pump_agent_mints row, fetch the bonding curve (pre-graduation) or
-// canonical AMM pool (post-graduation) state plus a recent-tx snapshot, and
-// upsert into pump_agent_stats. Read endpoints (solana-card, passport) join
-// against this table instead of hitting RPC on every page load.
-//
-// Auth: `Bearer $CRON_SECRET` or Vercel cron header.
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-import { getConnection, getPumpSdk, getAmmPoolState, solanaPubkey } from '../_lib/pump.js';
-
-const MAX_PER_RUN = 100;
-
-// Pump.fun graduation threshold (mainnet curve). Used only as a UI hint —
-// progress_pct is a coarse bar, not financial advice.
-const GRADUATION_REAL_SOL = 85_000_000_000n; // ~85 SOL in lamports
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
- if (!method(req, res, ['GET', 'POST'])) return;
-
- const auth = req.headers.authorization || '';
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron) {
- if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${env.CRON_SECRET}`)
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
-
- const mints = await sql`
- select id, mint, network from pump_agent_mints
- order by id limit ${MAX_PER_RUN}
- `;
-
- const report = { scanned: mints.length, updated: 0, errors: 0, graduations: 0 };
- for (const m of mints) {
- try {
- const stats = await snapshotMint(m);
-
- // Detect graduation flip false→true vs prior snapshot.
- const [prior] = await sql`
- select graduated from pump_agent_stats where mint_id=${m.id} limit 1
- `;
- const justGraduated = stats.graduated && prior && !prior.graduated;
-
- await sql`
- insert into pump_agent_stats
- (mint_id, network, mint, graduated, bonding_curve, amm,
- last_signature, last_signature_at, recent_tx_count, refreshed_at, error)
- values (
- ${m.id}, ${m.network}, ${m.mint}, ${stats.graduated},
- ${stats.bonding_curve ? JSON.stringify(stats.bonding_curve) : null}::jsonb,
- ${stats.amm ? JSON.stringify(stats.amm) : null}::jsonb,
- ${stats.last_signature}, ${stats.last_signature_at},
- ${stats.recent_tx_count}, now(), null
- )
- on conflict (mint_id) do update set
- graduated = excluded.graduated,
- bonding_curve = excluded.bonding_curve,
- amm = excluded.amm,
- last_signature = excluded.last_signature,
- last_signature_at = excluded.last_signature_at,
- recent_tx_count = excluded.recent_tx_count,
- refreshed_at = now(),
- error = null
- `;
-
- // Price-point time series.
- const price = derivePrice(stats);
- if (price) {
- await sql`
- insert into pump_agent_price_points (mint_id, sol_per_token, market_cap_lamports, source)
- values (${m.id}, ${price.sol_per_token}, ${price.market_cap_lamports?.toString() ?? null}, ${price.source})
- `;
- }
-
- // Emit a self-sourced graduation signal (no upstream bot needed).
- if (justGraduated) {
- report.graduations++;
- try {
- await sql`
- insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)
- values (
- null, ${m.mint}, 'graduation', 0.3,
- ${JSON.stringify({ source: 'pump-agent-stats', network: m.network })}::jsonb,
- ${`graduated:${m.mint}:${Date.now()}`}
- )
- on conflict (tx_signature) do nothing
- `;
- } catch {
- // pumpfun_signals table optional
- }
- }
-
- report.updated++;
- } catch (e) {
- report.errors++;
- await sql`
- insert into pump_agent_stats (mint_id, network, mint, error, refreshed_at)
- values (${m.id}, ${m.network}, ${m.mint}, ${e.message || 'snapshot failed'}, now())
- on conflict (mint_id) do update set error = excluded.error, refreshed_at = now()
- `;
- }
- }
-
- return json(res, 200, report);
-});
-
-async function snapshotMint({ network, mint }) {
- const mintPk = solanaPubkey(mint);
- if (!mintPk) throw new Error('invalid mint pubkey');
-
- const out = {
- graduated: false,
- bonding_curve: null,
- amm: null,
- last_signature: null,
- last_signature_at: null,
- recent_tx_count: 0,
- };
-
- // Bonding curve
- let curve = null;
- try {
- const { sdk } = await getPumpSdk({ network });
- if (sdk.fetchBuyState) {
- const state = await sdk.fetchBuyState(mintPk, mintPk);
- curve = state.bondingCurve;
- } else if (sdk.fetchBondingCurve) {
- curve = await sdk.fetchBondingCurve(mintPk);
- }
- } catch {
- curve = null;
- }
-
- if (curve && !curve.complete) {
- const realSol = BigInt(curve.realSolReserves?.toString?.() ?? '0');
- const pct =
- GRADUATION_REAL_SOL > 0n
- ? Number((realSol * 10000n) / GRADUATION_REAL_SOL) / 100
- : null;
- out.bonding_curve = {
- real_sol: realSol.toString(),
- real_token: curve.realTokenReserves?.toString?.() ?? null,
- virtual_sol: curve.virtualSolReserves?.toString?.() ?? null,
- virtual_token: curve.virtualTokenReserves?.toString?.() ?? null,
- complete: curve.complete ?? false,
- progress_pct: pct != null ? Math.min(100, Math.max(0, pct)) : null,
- };
- } else {
- // Try AMM pool
- try {
- const amm = await getAmmPoolState({ network, mint: mintPk });
- out.graduated = true;
- out.amm = {
- pool: amm.poolKey.toString(),
- base_reserve: amm.baseReserve.toString(),
- quote_reserve: amm.quoteReserve.toString(),
- lp_supply: amm.pool.lpSupply?.toString?.() ?? null,
- };
- } catch (e) {
- if (e.code !== 'pool_not_found') throw e;
- // graduated state inferred from curve.complete only
- if (curve?.complete) out.graduated = true;
- }
- }
-
- // Recent activity snapshot via RPC
- try {
- const conn = getConnection({ network });
- const sigs = await conn.getSignaturesForAddress(mintPk, { limit: 50 });
- out.recent_tx_count = sigs.length;
- if (sigs.length > 0) {
- out.last_signature = sigs[0].signature;
- if (sigs[0].blockTime) {
- out.last_signature_at = new Date(sigs[0].blockTime * 1000).toISOString();
- }
- }
- } catch {
- // RPC hiccup — leave activity fields null
- }
-
- return out;
-}
-
-// Compute coarse sol-per-token + market_cap_lamports from a stats snapshot.
-// Bonding curve: virtual_sol / virtual_token (the AMM-style invariant pump uses).
-// AMM: quote_reserve / base_reserve.
-function derivePrice(stats) {
- if (stats.bonding_curve) {
- const vSol = Number(stats.bonding_curve.virtual_sol || 0);
- const vTok = Number(stats.bonding_curve.virtual_token || 0);
- if (vSol > 0 && vTok > 0) {
- const sol_per_token = vSol / vTok;
- // total supply ≈ virtual_token + real_token (heuristic, sufficient for charting)
- const totalTok =
- BigInt(stats.bonding_curve.virtual_token || 0) +
- BigInt(stats.bonding_curve.real_token || 0);
- const market_cap_lamports =
- totalTok > 0n ? BigInt(Math.floor(sol_per_token * Number(totalTok))) : null;
- return { sol_per_token, market_cap_lamports, source: 'bonding_curve' };
- }
- }
- if (stats.amm) {
- const q = Number(stats.amm.quote_reserve || 0);
- const b = Number(stats.amm.base_reserve || 0);
- if (q > 0 && b > 0) {
- return { sol_per_token: q / b, market_cap_lamports: null, source: 'amm' };
- }
- }
- return null;
-}
diff --git a/api/cron/pumpfun-monitor.js b/api/cron/pumpfun-monitor.js
deleted file mode 100644
index 1400c98f9..000000000
--- a/api/cron/pumpfun-monitor.js
+++ /dev/null
@@ -1,158 +0,0 @@
-/**
- * In-house pumpfun -> attestation monitor.
- *
- * Reads the live state already maintained by `/api/cron/pump-agent-stats`
- * (graduation flag, AMM/curve snapshots, recent trades) and emits real
- * on-chain threews.* SPL Memo attestations whenever a tracked condition
- * flips. This makes the event-attested reputation tier work *without*
- * any external pumpkit/MCP bot configured.
- *
- * Runs every 3 minutes via Vercel Cron (vercel.json). Manually triggerable
- * with `Authorization: Bearer $CRON_SECRET`.
- *
- * Source taxonomy: emits with `payload.source = 'pumpfun.<event>'` so the
- * reputation reads `payload.source like 'pumpkit.%'` continue to recognise
- * pumpkit-sourced events; we extend the read query in solana-reputation.js
- * to also count `pumpfun.%`.
- */
-
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { mintAttestation, deriveEventId, loadAttesterKeypair } from '../_lib/attest-event.js';
-
-const MAX_PER_RUN = 50;
-const WHALE_TRADE_USD_FLOOR = 1_000;
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- if (!process.env.ATTEST_AGENT_SECRET_KEY) {
- // Skip cleanly when the attester key isn't provisioned — returning 503
- // every 3 min would mark the cron job as failing in the dashboard.
- return json(res, 200, { skipped: true, reason: 'attester_not_configured' });
- }
-
- // Pull the latest stats joined with the agent's Metaplex Core asset and
- // the prior cursor state. Only consider mints whose stats have changed
- // since the last cursor checkpoint.
- const rows = await sql`
- select
- m.id as mint_id,
- m.mint as token_mint,
- m.network,
- m.agent_id,
- m.agent_authority,
- s.graduated,
- s.last_signature,
- s.last_signature_at,
- a.id as agent_row_id,
- a.user_id,
- coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') as agent_asset,
- c.last_graduated,
- c.last_authority,
- c.last_trade_signature
- from pump_agent_mints m
- join pump_agent_stats s on s.mint_id = m.id
- join agent_identities a on a.id = m.agent_id
- left join pumpfun_monitor_cursor c on c.mint_id = m.id
- where coalesce(a.meta->'onchain'->>'sol_asset', a.meta->>'sol_mint_address') is not null
- and (
- c.mint_id is null
- or c.last_graduated is distinct from s.graduated
- or c.last_authority is distinct from m.agent_authority
- or c.last_trade_signature is distinct from s.last_signature
- )
- order by s.refreshed_at desc nulls last
- limit ${MAX_PER_RUN}
- `;
-
- const attester = loadAttesterKeypair();
- const report = { scanned: rows.length, minted: 0, deduped: 0, in_progress: 0, errors: 0, events: [] };
-
- for (const r of rows) {
- const events = detectEvents(r);
- for (const ev of events) {
- try {
- const result = await mintAttestation({
- ...ev,
- agent_asset: r.agent_asset,
- network: r.network,
- token_mint: r.token_mint,
- attester,
- });
- report[result.status === 'minted' ? 'minted'
- : result.status === 'deduped' ? 'deduped' : 'in_progress']++;
- report.events.push({
- mint: r.token_mint, type: ev.event_type, status: result.status,
- signature: result.signature,
- });
- } catch (e) {
- report.errors++;
- report.events.push({
- mint: r.token_mint, type: ev.event_type,
- status: 'error', error: e?.message || String(e),
- });
- }
- }
-
- // Always update the cursor — even when nothing was emitted — so we
- // don't re-scan unchanged rows next tick.
- await sql`
- insert into pumpfun_monitor_cursor (mint_id, last_graduated, last_authority, last_trade_signature, last_processed_at)
- values (${r.mint_id}, ${r.graduated}, ${r.agent_authority}, ${r.last_signature}, now())
- on conflict (mint_id) do update set
- last_graduated = excluded.last_graduated,
- last_authority = excluded.last_authority,
- last_trade_signature = excluded.last_trade_signature,
- last_processed_at = now()
- `;
- }
-
- return json(res, 200, report);
-});
-
-/** Map a single (stats, cursor) row to the attestation events to emit. */
-function detectEvents(r) {
- const out = [];
- const slot_or_ts = r.last_signature_at
- ? new Date(r.last_signature_at).getTime()
- : Date.now();
-
- // Graduation flip false -> true.
- if (r.graduated === true && r.last_graduated !== true) {
- out.push({
- event_type: 'graduation',
- source: 'pumpfun.graduation',
- event_id: deriveEventId({ event_type: 'graduation', mint: r.token_mint, slot_or_ts: 'final' }),
- task_id: `pumpfun:${r.token_mint}:graduation`,
- detail: { network: r.network },
- });
- }
-
- // CTO: agent_authority changed (creator takeover).
- if (r.agent_authority && r.last_authority && r.agent_authority !== r.last_authority) {
- out.push({
- event_type: 'cto_detected',
- source: 'pumpfun.cto',
- event_id: deriveEventId({
- event_type: 'cto',
- mint: r.token_mint,
- slot_or_ts: `${r.last_authority}->${r.agent_authority}`,
- }),
- task_id: `pumpfun:${r.token_mint}:cto:${slot_or_ts}`,
- detail: { from: r.last_authority, to: r.agent_authority, network: r.network },
- });
- }
-
- return out;
-}
-
-// Exported for tests.
-export { detectEvents, WHALE_TRADE_USD_FLOOR };
diff --git a/api/cron/pumpfun-signals.js b/api/cron/pumpfun-signals.js
deleted file mode 100644
index 037d32b22..000000000
--- a/api/cron/pumpfun-signals.js
+++ /dev/null
@@ -1,164 +0,0 @@
-/**
- * Pump.fun signals crawler.
- *
- * Periodically pulls recent claim activity from the upstream pumpfun-claims-bot
- * MCP server, filters to claims/graduations whose creator or claimer wallet is
- * linked to a `user_wallets` row (chain_type='solana'), and writes typed signals
- * to `pumpfun_signals`. The `solana-reputation` endpoint reads these to weight
- * the Solana agent reputation score.
- *
- * Runs every 15 minutes via Vercel Cron (see vercel.json). Manually triggerable
- * with `Authorization: Bearer $CRON_SECRET`.
- *
- * Idempotent: tx_signature is unique; duplicate inserts are skipped.
- */
-
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { pumpfunMcp, pumpfunBotEnabled } from '../_lib/pumpfun-mcp.js';
-
-const CLAIMS_PER_RUN = 200;
-const GRADS_PER_RUN = 50;
-
-const SIGNAL_WEIGHT = {
- first_claim: +0.2,
- graduation: +0.3,
- influencer: +0.2,
- fake_claim: -0.6,
- new_account: -0.2,
-};
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- if (!pumpfunBotEnabled()) {
- return json(res, 200, { skipped: 'pumpfun bot not configured' });
- }
-
- const [claims, grads] = await Promise.all([
- pumpfunMcp.recentClaims({ limit: CLAIMS_PER_RUN }),
- pumpfunMcp.graduations({ limit: GRADS_PER_RUN }),
- ]);
-
- const report = { claims: 0, graduations: 0, inserted: 0, skipped: 0, errors: [] };
-
- const claimItems = arr(claims.ok ? claims.data : null);
- const gradItems = arr(grads.ok ? grads.data : null);
- report.claims = claimItems.length;
- report.graduations = gradItems.length;
-
- const wallets = collectWallets(claimItems, gradItems);
- const linked = await linkedWalletMap(wallets);
-
- for (const ev of claimItems) {
- const wallet = ev.claimer || ev.github_wallet;
- if (!wallet || !linked.has(wallet)) {
- report.skipped++;
- continue;
- }
- try {
- const inserts = signalsFromClaim(ev);
- for (const sig of inserts) {
- const ok = await insertSignal({
- wallet,
- agent_asset: linked.get(wallet) || null,
- kind: sig.kind,
- weight: SIGNAL_WEIGHT[sig.kind] ?? 0,
- payload: sig.payload,
- tx_signature: sig.tx_signature,
- });
- if (ok) report.inserted++;
- }
- } catch (err) {
- report.errors.push({ tx: ev.tx_signature, error: err.message });
- }
- }
-
- for (const ev of gradItems) {
- const wallet = ev.creator || ev.dev_wallet;
- if (!wallet || !linked.has(wallet)) {
- report.skipped++;
- continue;
- }
- try {
- const ok = await insertSignal({
- wallet,
- agent_asset: linked.get(wallet) || null,
- kind: 'graduation',
- weight: SIGNAL_WEIGHT.graduation,
- payload: { mint: ev.mint, symbol: ev.symbol, name: ev.name },
- tx_signature: ev.tx_signature || ev.signature,
- });
- if (ok) report.inserted++;
- } catch (err) {
- report.errors.push({ tx: ev.tx_signature, error: err.message });
- }
- }
-
- return json(res, 200, report);
-});
-
-function arr(x) {
- if (!x) return [];
- return Array.isArray(x) ? x : x.items || [];
-}
-
-function collectWallets(claims, grads) {
- const out = new Set();
- for (const c of claims) {
- if (c.claimer) out.add(c.claimer);
- if (c.github_wallet) out.add(c.github_wallet);
- }
- for (const g of grads) {
- if (g.creator) out.add(g.creator);
- if (g.dev_wallet) out.add(g.dev_wallet);
- }
- return [...out];
-}
-
-async function linkedWalletMap(wallets) {
- const map = new Map();
- if (wallets.length === 0) return map;
- const rows = await sql`
- select uw.address, ai.meta->>'sol_mint_address' as agent_asset
- from user_wallets uw
- left join agent_identities ai
- on ai.user_id = uw.user_id
- and ai.deleted_at is null
- and ai.meta->>'chain_type' = 'solana'
- where uw.chain_type = 'solana'
- and uw.address = any(${wallets})
- `;
- for (const r of rows) map.set(r.address, r.agent_asset);
- return map;
-}
-
-function signalsFromClaim(ev) {
- const out = [];
- const base = { tx_signature: ev.tx_signature, payload: ev };
- if (ev.first_time_claim) out.push({ kind: 'first_claim', ...base });
- if (ev.fake_claim) out.push({ kind: 'fake_claim', ...base });
- if (ev.tier === 'mega' || ev.tier === 'influencer') out.push({ kind: 'influencer', ...base });
- if (ev.github_account_age_days != null && ev.github_account_age_days < 30) {
- out.push({ kind: 'new_account', ...base });
- }
- return out;
-}
-
-async function insertSignal({ wallet, agent_asset, kind, weight, payload, tx_signature }) {
- if (!tx_signature) return false;
- const result = await sql`
- insert into pumpfun_signals (wallet, agent_asset, kind, weight, payload, tx_signature)
- values (${wallet}, ${agent_asset}, ${kind}, ${weight}, ${JSON.stringify(payload)}::jsonb, ${tx_signature})
- on conflict (tx_signature) do nothing
- returning id
- `;
- return result.length > 0;
-}
diff --git a/api/cron/run-buyback.js b/api/cron/run-buyback.js
deleted file mode 100644
index 73ad3e56e..000000000
--- a/api/cron/run-buyback.js
+++ /dev/null
@@ -1,148 +0,0 @@
-// GET /api/cron/run-buyback
-//
-// For every agent mint with non-zero buybackVault balance, builds a
-// `buybackTrigger` ix that CPIs into pump-swap to swap currency → agent token
-// then burn. If PUMP_CRON_RELAYER_SECRET_KEY_B64 is set, signs + lands the tx;
-// otherwise persists unsigned txs for an external keeper.
-//
-// Auth: `Bearer $CRON_SECRET`.
-//
-// NOTE: swapInstructionData / remainingAccounts construction is swap-program-
-// specific. This implementation supports the empty-data "burn-only" form
-// (which the SDK accepts to skip the swap and just burn whatever is already
-// in the buyback vault denominated in the agent token). Full swap path is
-// gated behind PUMP_BUYBACK_FULL_SWAP=true and uses pump-swap-sdk to build
-// the inner ix.
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-import {
- getPumpAgent,
- getPumpAgentOffline,
- getConnection,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
-
-async function loadRelayer() {
- const b64 = process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64;
- if (!b64) return null;
- const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
- return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET', 'POST'])) return;
-
- const auth = req.headers.authorization || '';
- if (!env.CRON_SECRET) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${env.CRON_SECRET}`) {
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
-
- const fullSwap = process.env.PUMP_BUYBACK_FULL_SWAP === 'true';
- const relayer = await loadRelayer();
-
- const mints = await sql`
- select id, mint, network from pump_agent_mints limit 200
- `;
-
- const results = [];
- for (const m of mints) {
- const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
- const currency = solanaPubkey(currencyStr);
-
- try {
- const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
- const balances = await agent.getBalances(currency);
- const buyback = BigInt(balances.buybackVault?.balance ?? 0);
-
- if (buyback === 0n) {
- const [run] = await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status)
- values (${m.id}, ${currencyStr}, 'skipped') returning id
- `;
- results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
- continue;
- }
-
- const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
- const [{ PUMP_PROGRAM_ID }] = await Promise.all([
- import('@pump-fun/agent-payments-sdk'),
- ]);
-
- const payerPk = relayer ? relayer.publicKey : solanaPubkey(m.mint);
- const params = {
- globalBuybackAuthority: payerPk, // gated by globalConfig — for skipped-swap form, can be relayer
- currencyMint: currency,
- swapProgramToInvoke: PUMP_PROGRAM_ID || payerPk, // sentinel program for skip-swap path
- swapInstructionData: Buffer.alloc(0), // empty = skip swap, just burn
- remainingAccounts: [],
- };
-
- if (fullSwap) {
- // TODO(Phase 3.1): build pump-swap inner ix here. Skipping for safety;
- // keepers should supply this off-chain until tested on devnet.
- }
-
- let ix;
- try {
- ix = await offline.buybackTrigger(params);
- } catch (e) {
- const [run] = await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status, error)
- values (${m.id}, ${currencyStr}, 'failed', ${'buybackTrigger build failed: ' + e.message})
- returning id
- `;
- results.push({ mint: m.mint, status: 'failed', error: e.message, run_id: run.id });
- continue;
- }
-
- if (!relayer) {
- const txBase64 = await buildUnsignedTxBase64({
- network: m.network,
- payer: payerPk,
- instructions: [ix],
- });
- const [run] = await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status, burn_amount)
- values (${m.id}, ${currencyStr}, 'pending', ${buyback.toString()})
- returning id
- `;
- results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
- continue;
- }
-
- const connection = getConnection({ network: m.network });
- const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
- const tx = new Transaction();
- tx.add(ix);
- const { blockhash } = await connection.getLatestBlockhash('confirmed');
- tx.recentBlockhash = blockhash;
- tx.feePayer = relayer.publicKey;
- tx.sign(relayer);
- const sig = await connection.sendRawTransaction(tx.serialize());
- await connection.confirmTransaction(sig, 'confirmed');
-
- const [run] = await sql`
- insert into pump_buyback_runs
- (mint_id, currency_mint, tx_signature, status, burn_amount)
- values
- (${m.id}, ${currencyStr}, ${sig}, 'confirmed', ${buyback.toString()})
- returning id
- `;
- results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
- } catch (err) {
- await sql`
- insert into pump_buyback_runs (mint_id, currency_mint, status, error)
- values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
- `;
- results.push({ mint: m.mint, status: 'failed', error: err.message });
- }
- }
-
- return json(res, 200, { ok: true, processed: results.length, results });
-});
diff --git a/api/cron/run-dca.js b/api/cron/run-dca.js
deleted file mode 100644
index 8448039a8..000000000
--- a/api/cron/run-dca.js
+++ /dev/null
@@ -1,473 +0,0 @@
-// GET /api/cron/run-dca
-// Hourly cron: executes pending DCA strategies via Uniswap V3 SwapRouter.
-// Scheduled in vercel.json: "0 * * * *"
-
-import { createPublicClient, http, encodeFunctionData, parseAbi } from 'viem';
-import { baseSepolia, base } from 'viem/chains';
-
-import { sql } from '../_lib/db.js';
-import { env } from '../_lib/env.js';
-import { json, error, wrap } from '../_lib/http.js';
-
-// ── Chain config ──────────────────────────────────────────────────────────────
-
-const CHAIN_CONFIG = {
- 84532: {
- chain: baseSepolia,
- swap_router: '0x94cC0AaC535CCDB3C01d6787D6413C739ae12bc4',
- quoter_v2: '0xC5290058841028F1614F3A6F0F5816cAd0df5E27',
- },
- 8453: {
- chain: base,
- swap_router: '0x2626664c2603336E57B271c5C0b26F421741e481',
- quoter_v2: '0x3d4e44Eb1374240CE5F1B871ab261CD16335B76a',
- },
-};
-
-// ── ABIs (minimal) ────────────────────────────────────────────────────────────
-
-const QUOTER_V2_ABI = parseAbi([
- 'function quoteExactInputSingle((address tokenIn, address tokenOut, uint256 amountIn, uint24 fee, uint160 sqrtPriceLimitX96) params) external returns (uint256 amountOut, uint160 sqrtPriceX96After, uint32 initializedTicksCrossed, uint256 gasEstimate)',
-]);
-
-const SWAP_ROUTER_ABI = parseAbi([
- 'function exactInputSingle((address tokenIn, address tokenOut, uint24 fee, address recipient, uint256 amountIn, uint256 amountOutMinimum, uint160 sqrtPriceLimitX96) params) external payable returns (uint256 amountOut)',
-]);
-
-const ERC20_ABI = parseAbi([
- 'function approve(address spender, uint256 amount) external returns (bool)',
-]);
-
-// Uniswap V3 standard fee tier — 0.3% pool is the most liquid USDC/WETH tier
-const FEE_TIER = 3000;
-
-// ── Operational tunables ──────────────────────────────────────────────────────
-
-const RPC_TIMEOUT_MS = 10_000;
-const RPC_MAX_RETRIES = 2; // total attempts = 1 + retries
-const RELAYER_TIMEOUT_MS = 30_000;
-const RELAYER_MAX_RETRIES = 1;
-const RELAYER_RETRY_BACKOFF_MS = 1_500;
-
-// ── Structured logging ────────────────────────────────────────────────────────
-
-function log(level, event, fields = {}) {
- const line = JSON.stringify({
- level,
- event,
- ts: new Date().toISOString(),
- component: 'cron/run-dca',
- ...fields,
- });
- if (level === 'error') console.error(line);
- else console.log(line);
-}
-
-// ── Retry helper for transient failures ───────────────────────────────────────
-
-function isTransient(err) {
- // Network-level & RPC transport errors
- const code = err?.code;
- const name = err?.name;
- const status = err?.status;
- if (name === 'AbortError' || name === 'TimeoutError') return true;
- if (
- code === 'ETIMEDOUT' ||
- code === 'ECONNRESET' ||
- code === 'ECONNREFUSED' ||
- code === 'ENOTFOUND' ||
- code === 'EAI_AGAIN'
- )
- return true;
- if (typeof status === 'number' && status >= 500 && status < 600) return true;
- // viem transport errors
- const msg = String(err?.message || '');
- if (/HttpRequestError|TimeoutError|fetch failed|network|socket hang up/i.test(msg)) return true;
- return false;
-}
-
-async function withRetry(fn, { retries, backoffMs = 500, label }) {
- let attempt = 0;
- // eslint-disable-next-line no-constant-condition
- while (true) {
- try {
- return await fn();
- } catch (err) {
- attempt++;
- if (attempt > retries || !isTransient(err)) throw err;
- const delay = backoffMs * 2 ** (attempt - 1);
- log('warn', 'retry', {
- label,
- attempt,
- delay_ms: delay,
- message: err?.message,
- code: err?.code,
- });
- await new Promise((r) => setTimeout(r, delay));
- }
- }
-}
-
-// ── RPC client factory ────────────────────────────────────────────────────────
-
-function getViemClient(chainId) {
- const cfg = CHAIN_CONFIG[chainId];
- if (!cfg) throw new Error(`Unsupported chainId: ${chainId}`);
- const rpcUrl = env.getRpcUrl(chainId);
- const transport = rpcUrl
- ? http(rpcUrl, { timeout: RPC_TIMEOUT_MS, retryCount: 0 })
- : http(undefined, { timeout: RPC_TIMEOUT_MS, retryCount: 0 });
- return createPublicClient({ chain: cfg.chain, transport });
-}
-
-// ── Quote with divergence check ───────────────────────────────────────────────
-
-/**
- * Fetch a quote twice 15s apart; abort if they diverge by more than 0.5%.
- * Returns { amountOut, divergenceBps } or throws if divergence exceeds limit.
- */
-async function getVerifiedQuote(client, quoterAddress, tokenIn, tokenOut, amountIn, logCtx) {
- const params = {
- tokenIn,
- tokenOut,
- amountIn: BigInt(amountIn),
- fee: FEE_TIER,
- sqrtPriceLimitX96: 0n,
- };
-
- const readQuote = () =>
- client.readContract({
- address: quoterAddress,
- abi: QUOTER_V2_ABI,
- functionName: 'quoteExactInputSingle',
- args: [params],
- });
-
- // First quote (with retry on transient RPC failures)
- const [q1] = await withRetry(readQuote, {
- retries: RPC_MAX_RETRIES,
- backoffMs: 500,
- label: `quote1:${logCtx?.strategy_id ?? ''}`,
- });
-
- // Wait 15s then quote again
- await new Promise((r) => setTimeout(r, 15_000));
-
- const [q2] = await withRetry(readQuote, {
- retries: RPC_MAX_RETRIES,
- backoffMs: 500,
- label: `quote2:${logCtx?.strategy_id ?? ''}`,
- });
-
- // Divergence in basis points: |q2-q1| / q1 * 10000
- const divergenceBps = q1 === 0n ? 0 : Number(((q2 > q1 ? q2 - q1 : q1 - q2) * 10000n) / q1);
-
- if (divergenceBps > 50) {
- throw Object.assign(
- new Error(`Quote divergence ${divergenceBps}bps exceeds 50bps limit — aborting`),
- { code: 'quote_divergence', divergenceBps },
- );
- }
-
- // Use the more conservative (lower) of the two quotes
- const amountOut = q1 < q2 ? q1 : q2;
- return { amountOut, divergenceBps };
-}
-
-// ── Calldata builders ─────────────────────────────────────────────────────────
-
-function buildApproveCalldata(spender, amount) {
- return encodeFunctionData({
- abi: ERC20_ABI,
- functionName: 'approve',
- args: [spender, BigInt(amount)],
- });
-}
-
-function buildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum) {
- return encodeFunctionData({
- abi: SWAP_ROUTER_ABI,
- functionName: 'exactInputSingle',
- args: [
- {
- tokenIn,
- tokenOut,
- fee: FEE_TIER,
- recipient,
- amountIn: BigInt(amountIn),
- amountOutMinimum: BigInt(amountOutMinimum),
- sqrtPriceLimitX96: 0n,
- },
- ],
- });
-}
-
-// ── Relayer redemption ────────────────────────────────────────────────────────
-
-async function redeemViaRelayer(delegationId, calls, logCtx) {
- const relayerUrl = `${env.APP_ORIGIN}/api/permissions/redeem`;
-
- const doFetch = async () => {
- const res = await fetch(relayerUrl, {
- method: 'POST',
- headers: {
- 'content-type': 'application/json',
- authorization: `Bearer ${env.CRON_SECRET}`,
- },
- body: JSON.stringify({ id: delegationId, calls }),
- signal: AbortSignal.timeout(RELAYER_TIMEOUT_MS),
- });
-
- if (!res.ok) {
- const body = await res.json().catch(() => ({ message: res.statusText }));
- throw Object.assign(
- new Error(body.error_description || body.message || `Relayer ${res.status}`),
- { code: body.error || 'relayer_error', status: res.status },
- );
- }
- return res.json();
- };
-
- return withRetry(doFetch, {
- retries: RELAYER_MAX_RETRIES,
- backoffMs: RELAYER_RETRY_BACKOFF_MS,
- label: `relayer:${logCtx?.strategy_id ?? ''}`,
- });
-}
-
-// ── onPeriod — process one strategy ──────────────────────────────────────────
-
-async function onPeriod(strategy) {
- const {
- id: strategyId,
- delegation_id: delegationId,
- chain_id: chainId,
- token_in: tokenIn,
- token_out: tokenOut,
- amount_per_execution: amountIn,
- slippage_bps: slippageBps,
- } = strategy;
-
- const cfg = CHAIN_CONFIG[chainId];
- if (!cfg)
- throw Object.assign(new Error(`No config for chainId ${chainId}`), {
- code: 'unsupported_chain',
- });
-
- const client = getViemClient(chainId);
- const logCtx = { strategy_id: strategyId, chain_id: chainId };
-
- // Get verified quote
- const { amountOut, divergenceBps } = await getVerifiedQuote(
- client,
- cfg.quoter_v2,
- tokenIn,
- tokenOut,
- amountIn,
- logCtx,
- );
-
- // Apply slippage: amountOutMinimum = amountOut * (10000 - slippageBps) / 10000
- const amountOutMinimum = (amountOut * BigInt(10000 - slippageBps)) / 10000n;
-
- // Resolve recipient — use the delegator address from the delegation row
- const [delegationRow] = await sql`
- SELECT delegator_address FROM agent_delegations
- WHERE id = ${delegationId} AND status = 'active'
- LIMIT 1
- `;
- if (!delegationRow) {
- throw Object.assign(new Error('Delegation not found or no longer active'), {
- code: 'delegation_gone',
- });
- }
- const recipient = delegationRow.delegator_address;
-
- // Build calls: [approve USDC → SwapRouter, exactInputSingle]
- const calls = [
- {
- to: tokenIn,
- value: '0',
- data: buildApproveCalldata(cfg.swap_router, amountIn),
- },
- {
- to: cfg.swap_router,
- value: '0',
- data: buildSwapCalldata(tokenIn, tokenOut, recipient, amountIn, amountOutMinimum),
- },
- ];
-
- // Submit via relayer
- const result = await redeemViaRelayer(delegationId, calls, logCtx);
-
- return { txHash: result.txHash, quoteAmountOut: amountOut.toString(), divergenceBps };
-}
-
-// ── Cron handler ──────────────────────────────────────────────────────────────
-
-export default wrap(async (req, res) => {
- // Vercel cron passes Authorization: Bearer $CRON_SECRET
- const cronSecret = env.CRON_SECRET;
- if (cronSecret) {
- const auth = req.headers.authorization || '';
- if (auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'invalid cron secret');
- }
- }
-
- const runId = globalThis.crypto?.randomUUID?.() ?? `run_${Date.now()}`;
- log('info', 'tick_start', { run_id: runId });
-
- // Fetch all due active strategies
- let strategies;
- try {
- strategies = await sql`
- SELECT
- s.id, s.delegation_id, s.chain_id,
- s.token_in, s.token_out, s.amount_per_execution,
- s.period_seconds, s.slippage_bps, s.agent_id,
- ad.status AS delegation_status, ad.expires_at AS delegation_expires_at
- FROM dca_strategies s
- JOIN agent_delegations ad ON ad.id = s.delegation_id
- WHERE s.status = 'active'
- AND s.next_execution_at <= NOW()
- ORDER BY s.next_execution_at ASC
- LIMIT 50
- `;
- } catch (err) {
- log('error', 'fetch_due_failed', { run_id: runId, message: err?.message });
- throw err;
- }
-
- const results = [];
- for (const strategy of strategies) {
- const logCtx = { run_id: runId, strategy_id: strategy.id, chain_id: strategy.chain_id };
-
- const execRow = {
- strategy_id: strategy.id,
- chain_id: strategy.chain_id,
- amount_in: strategy.amount_per_execution,
- slippage_bps_used: strategy.slippage_bps,
- status: 'pending',
- };
-
- // Check delegation is still alive before spending gas on a quote
- if (strategy.delegation_status !== 'active') {
- await sql`
- UPDATE dca_strategies SET status = 'paused' WHERE id = ${strategy.id}
- `;
- execRow.status = 'aborted';
- execRow.error = `Delegation ${strategy.delegation_status}`;
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
- log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
- );
- log('info', 'skipped', { ...logCtx, reason: execRow.error });
- results.push({ id: strategy.id, skipped: true, reason: execRow.error });
- continue;
- }
-
- if (new Date(strategy.delegation_expires_at) <= new Date()) {
- await sql`
- UPDATE dca_strategies SET status = 'expired' WHERE id = ${strategy.id}
- `;
- execRow.status = 'aborted';
- execRow.error = 'Delegation expired';
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
- log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
- );
- log('info', 'skipped', { ...logCtx, reason: execRow.error });
- results.push({ id: strategy.id, skipped: true, reason: execRow.error });
- continue;
- }
-
- // ── Idempotency claim ───────────────────────────────────────────────
- // Atomically advance next_execution_at so a concurrent tick (or a retry
- // of this tick) will not re-pick this row. We advance by period_seconds
- // provisionally; on success we leave it; on failure we reset to NOW so
- // the next tick retries it.
- const nowIso = new Date().toISOString();
- const provisionalNextIso = new Date(
- Date.now() + strategy.period_seconds * 1000,
- ).toISOString();
-
- const claim = await sql`
- UPDATE dca_strategies
- SET next_execution_at = ${provisionalNextIso}
- WHERE id = ${strategy.id}
- AND status = 'active'
- AND next_execution_at <= ${nowIso}
- RETURNING id
- `;
- if (claim.length === 0) {
- log('info', 'claim_lost', { ...logCtx });
- results.push({ id: strategy.id, skipped: true, reason: 'claim_lost' });
- continue;
- }
-
- log('info', 'execute_start', { ...logCtx });
-
- try {
- const { txHash, quoteAmountOut, divergenceBps } = await onPeriod(strategy);
-
- execRow.tx_hash = txHash;
- execRow.quote_amount_out = quoteAmountOut;
- execRow.quote_divergence_bps = divergenceBps;
- execRow.status = 'success';
-
- await sql`
- UPDATE dca_strategies
- SET last_execution_at = NOW()
- WHERE id = ${strategy.id}
- `;
-
- log('info', 'execute_success', {
- ...logCtx,
- tx_hash: txHash,
- divergence_bps: divergenceBps,
- });
- results.push({ id: strategy.id, txHash, quoteAmountOut });
- } catch (err) {
- execRow.status = err.code === 'quote_divergence' ? 'aborted' : 'failed';
- execRow.error = err.message;
- execRow.quote_divergence_bps = err.divergenceBps ?? null;
-
- // Release the idempotency claim so the next tick can retry this
- // strategy — but only for transient / recoverable failures. For
- // aborts (quote_divergence, delegation_gone) leave the advanced
- // next_execution_at in place so we wait the full period.
- const shouldRetryNextTick =
- err.code !== 'quote_divergence' &&
- err.code !== 'delegation_gone' &&
- err.code !== 'unsupported_chain';
- if (shouldRetryNextTick) {
- await sql`
- UPDATE dca_strategies
- SET next_execution_at = ${nowIso}
- WHERE id = ${strategy.id}
- `.catch((e) => log('error', 'claim_release_failed', { ...logCtx, message: e?.message }));
- }
-
- log('error', 'execute_failed', {
- ...logCtx,
- code: err.code,
- message: err.message,
- status: err.status,
- will_retry_next_tick: shouldRetryNextTick,
- });
- results.push({ id: strategy.id, error: err.message, code: err.code });
- }
-
- // Insert execution record regardless of outcome
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
- log('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
- );
- }
-
- log('info', 'tick_done', { run_id: runId, processed: strategies.length });
-
- return json(res, 200, {
- ok: true,
- processed: strategies.length,
- results,
- });
-});
diff --git a/api/cron/run-distribute-payments.js b/api/cron/run-distribute-payments.js
deleted file mode 100644
index 897c38e68..000000000
--- a/api/cron/run-distribute-payments.js
+++ /dev/null
@@ -1,153 +0,0 @@
-// GET /api/cron/run-distribute-payments
-//
-// Permissionless: builds + (optionally) submits `distributePayments` for every
-// agent mint that has unrouted paymentVault balance. distribute is permissionless
-// per the SDK, so any signer works — we use the cron relayer keypair if set,
-// otherwise we just *prepare* and persist the unsigned tx for an external
-// keeper to land.
-//
-// Authorized via Vercel Cron `Bearer $CRON_SECRET` (see env.CRON_SECRET).
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-import {
- getPumpAgent,
- getPumpAgentOffline,
- getConnection,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
-
-const CRON_RELAYER_SECRET_KEY_B64 = () => process.env.PUMP_CRON_RELAYER_SECRET_KEY_B64 || null;
-
-async function loadRelayer() {
- const b64 = CRON_RELAYER_SECRET_KEY_B64();
- if (!b64) return null;
- const [{ Keypair }] = await Promise.all([import('@solana/web3.js')]);
- return Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET', 'POST'])) return;
-
- // Auth: cron secret OR admin bearer.
- const auth = req.headers.authorization || '';
- const cronSecret = env.CRON_SECRET;
- if (!cronSecret) return error(res, 503, 'not_configured', 'CRON_SECRET unset');
- if (auth !== `Bearer ${cronSecret}`) {
- return error(res, 401, 'unauthorized', 'cron auth required');
- }
-
- // Pick mints to consider: those with confirmed payments since last
- // distribute run, or never run before.
- const mints = await sql`
- select m.id, m.mint, m.network, m.buyback_bps
- from pump_agent_mints m
- where exists (
- select 1 from pump_agent_payments p
- where p.mint_id = m.id and p.status = 'confirmed'
- and (
- p.confirmed_at > coalesce(
- (select max(created_at) from pump_distribute_runs r where r.mint_id = m.id),
- 'epoch'::timestamptz
- )
- )
- )
- limit 200
- `;
-
- const relayer = await loadRelayer();
- const results = [];
-
- for (const m of mints) {
- const currencyStr = m.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT;
- const currency = solanaPubkey(currencyStr);
-
- try {
- const { agent } = await getPumpAgent({ network: m.network, mint: m.mint });
- const balancesBefore = await agent.getBalances(currency);
- const paymentBalance = BigInt(balancesBefore.paymentVault.balance ?? 0);
-
- if (paymentBalance === 0n) {
- const [run] = await sql`
- insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
- values (${m.id}, ${currencyStr}, 'skipped', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
- returning id
- `;
- results.push({ mint: m.mint, status: 'skipped', run_id: run.id });
- continue;
- }
-
- const { offline } = await getPumpAgentOffline({ network: m.network, mint: m.mint });
-
- if (!relayer) {
- // No relayer: build unsigned tx for an external keeper. Persist run as 'pending'.
- const ixs = await offline.distributePayments({
- user: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
- currencyMint: currency,
- });
- const txBase64 = await buildUnsignedTxBase64({
- network: m.network,
- payer: solanaPubkey(process.env.PUMP_DISTRIBUTE_FALLBACK_PAYER || m.mint),
- instructions: Array.isArray(ixs) ? ixs : [ixs],
- });
- const [run] = await sql`
- insert into pump_distribute_runs (mint_id, currency_mint, status, balances_before)
- values (${m.id}, ${currencyStr}, 'pending', ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb)
- returning id
- `;
- results.push({ mint: m.mint, status: 'pending', run_id: run.id, tx_base64: txBase64 });
- continue;
- }
-
- // Relayer path: sign + send.
- const ixs = await offline.distributePayments({
- user: relayer.publicKey,
- currencyMint: currency,
- });
- const connection = getConnection({ network: m.network });
- const [{ Transaction }] = await Promise.all([import('@solana/web3.js')]);
- const tx = new Transaction();
- tx.add(...(Array.isArray(ixs) ? ixs : [ixs]));
- const { blockhash } = await connection.getLatestBlockhash('confirmed');
- tx.recentBlockhash = blockhash;
- tx.feePayer = relayer.publicKey;
- tx.sign(relayer);
- const sig = await connection.sendRawTransaction(tx.serialize(), {
- skipPreflight: false,
- });
- await connection.confirmTransaction(sig, 'confirmed');
-
- const balancesAfter = await agent.getBalances(currency);
- const [run] = await sql`
- insert into pump_distribute_runs
- (mint_id, currency_mint, tx_signature, status, balances_before, balances_after)
- values
- (${m.id}, ${currencyStr}, ${sig}, 'confirmed',
- ${JSON.stringify({ payment: paymentBalance.toString() })}::jsonb,
- ${JSON.stringify({
- buyback: balancesAfter.buybackVault?.balance?.toString?.(),
- withdraw: balancesAfter.withdrawVault?.balance?.toString?.(),
- })}::jsonb)
- returning id
- `;
- results.push({ mint: m.mint, status: 'confirmed', tx_signature: sig, run_id: run.id });
- } catch (err) {
- await sql`
- insert into pump_distribute_runs (mint_id, currency_mint, status, error)
- values (${m.id}, ${currencyStr}, 'failed', ${err.message || String(err)})
- `;
- results.push({ mint: m.mint, status: 'failed', error: err.message });
- }
- }
-
- return json(res, 200, {
- ok: true,
- processed: results.length,
- relayer: relayer ? relayer.publicKey.toBase58() : null,
- results,
- });
-});
diff --git a/api/cron/run-subscriptions.js b/api/cron/run-subscriptions.js
deleted file mode 100644
index 5e7af244c..000000000
--- a/api/cron/run-subscriptions.js
+++ /dev/null
@@ -1,343 +0,0 @@
-/**
- * Hourly cron — process due subscription charges.
- *
- * Selects agent_subscriptions WHERE status='active' AND next_charge_at <= NOW(),
- * verifies the backing delegation is still active, calls the skill's onPeriod
- * handler (imported dynamically from public/skills/subscription/skill.js), then
- * either advances next_charge_at on success or flips status to 'paused' on failure.
- *
- * Idempotent: re-running within the same period is a no-op because next_charge_at
- * is only reached once per period. Concurrent runs are additionally guarded by an
- * atomic conditional claim that marks the row with last_charge_at = NOW() before
- * invoking onPeriod; the claim fails (0 rows) if another worker already claimed
- * this period, so onPeriod is called at most once per (subscription, period).
- *
- * Scheduled via vercel.json crons — "0 * * * *" (every hour on the hour).
- */
-
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
-
-// USDC contract addresses by chain ID.
-const USDC_BY_CHAIN = {
- 84532: '0x036CbD53842c5426634e7929541eC2318f3dCF7e', // Base Sepolia
- 11155111: '0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238', // Sepolia
-};
-
-// Max time we'll wait for the skill's onPeriod (which fetches the relayer).
-// Override via SUBSCRIPTION_CHARGE_TIMEOUT_MS.
-const ONPERIOD_TIMEOUT_MS = parseInt(process.env.SUBSCRIPTION_CHARGE_TIMEOUT_MS ?? '30000', 10);
-
-// Structured log helper — single-line JSON so Vercel log drains can parse it.
-function log(event, fields = {}) {
- try {
- console.log(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
- } catch {
- // Never let logging throw.
- }
-}
-
-function logError(event, fields = {}) {
- try {
- console.error(JSON.stringify({ ts: new Date().toISOString(), event, ...fields }));
- } catch {
- // Never let logging throw.
- }
-}
-
-// Race a promise against a timeout. Rejects with a tagged error on timeout.
-function withTimeout(promise, ms, label) {
- return new Promise((resolve, reject) => {
- const t = setTimeout(() => {
- const err = new Error(`${label} timed out after ${ms}ms`);
- err.code = 'timeout';
- reject(err);
- }, ms);
- Promise.resolve(promise).then(
- (v) => {
- clearTimeout(t);
- resolve(v);
- },
- (e) => {
- clearTimeout(t);
- reject(e);
- },
- );
- });
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- // Auth: Vercel Cron header OR explicit Bearer $CRON_SECRET.
- // If neither is configured AND no Vercel cron header is present, reject.
- const auth = req.headers['authorization'] ?? '';
- const expected = env.CRON_SECRET ? `Bearer ${env.CRON_SECRET}` : null;
- const fromVercelCron = req.headers['x-vercel-cron'] === '1';
- if (!fromVercelCron) {
- if (!expected || auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
- }
-
- const runId = `sub-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
- const runStart = Date.now();
- log('subscription_cron.start', { runId, fromVercelCron });
-
- const origin = env.APP_ORIGIN;
- const relayerToken = env.CRON_SECRET ?? '';
-
- const report = {
- runId,
- processed: 0,
- charged: 0,
- skipped: 0,
- paused: 0,
- claimLost: 0,
- errors: [],
- };
-
- // Load the skill's onPeriod handler once per invocation.
- let onPeriod;
- try {
- ({ onPeriod } = await import('../../public/skills/subscription/skill.js'));
- } catch (err) {
- logError('subscription_cron.skill_load_failed', { runId, message: err.message });
- return error(res, 500, 'internal_error', 'failed to load subscription skill');
- }
-
- // Select all active subscriptions whose charge window has arrived.
- let rows;
- try {
- rows = await sql`
- SELECT
- s.id,
- s.user_id,
- s.agent_id,
- s.delegation_id,
- s.period_seconds,
- s.amount_per_period,
- s.next_charge_at,
- s.last_charge_at,
- d.status AS delegation_status,
- d.expires_at AS delegation_expires_at,
- d.chain_id,
- ai.wallet_address AS owner_address
- FROM agent_subscriptions s
- JOIN agent_delegations d ON d.id = s.delegation_id
- JOIN agent_identities ai ON ai.id = s.agent_id
- WHERE s.status = 'active'
- AND s.next_charge_at <= NOW()
- `;
- } catch (err) {
- logError('subscription_cron.select_failed', { runId, message: err.message });
- return error(res, 500, 'internal_error', 'failed to load subscriptions');
- }
-
- log('subscription_cron.selected', { runId, count: rows.length });
-
- for (const row of rows) {
- report.processed++;
- const rowStart = Date.now();
- const ctx = { runId, subscriptionId: row.id, agentId: row.agent_id };
-
- try {
- // Guard: delegation must still be active.
- if (row.delegation_status !== 'active') {
- await _pause(row.id, `delegation_${row.delegation_status}`);
- report.paused++;
- report.errors.push({ id: row.id, reason: `delegation_${row.delegation_status}` });
- log('subscription_cron.paused', {
- ...ctx,
- reason: `delegation_${row.delegation_status}`,
- });
- continue;
- }
-
- // Guard: delegation must not be expired.
- if (row.delegation_expires_at && new Date(row.delegation_expires_at) <= new Date()) {
- await _pause(row.id, 'delegation_expired');
- report.paused++;
- report.errors.push({ id: row.id, reason: 'delegation_expired' });
- log('subscription_cron.paused', { ...ctx, reason: 'delegation_expired' });
- continue;
- }
-
- const usdcAddress = USDC_BY_CHAIN[row.chain_id];
- if (!usdcAddress) {
- await _pause(row.id, `chain_${row.chain_id}_unsupported`);
- report.skipped++;
- report.errors.push({ id: row.id, reason: `chain_${row.chain_id}_unsupported` });
- log('subscription_cron.skipped', {
- ...ctx,
- reason: `chain_${row.chain_id}_unsupported`,
- });
- continue;
- }
-
- // Atomic claim: mark this period as being processed by writing
- // last_charge_at = NOW(). Matches only if:
- // - next_charge_at hasn't moved (no racing writer),
- // - status is still active,
- // - last_charge_at is NULL OR < next_charge_at (not already claimed for this period).
- // If 0 rows returned, another worker claimed this period — skip.
- const claim = await sql`
- UPDATE agent_subscriptions
- SET last_charge_at = NOW()
- WHERE id = ${row.id}
- AND status = 'active'
- AND next_charge_at = ${row.next_charge_at}
- AND (last_charge_at IS NULL OR last_charge_at < next_charge_at)
- RETURNING id
- `;
- if (claim.length === 0) {
- report.claimLost++;
- log('subscription_cron.claim_lost', ctx);
- continue;
- }
-
- let result;
- try {
- result = await withTimeout(
- onPeriod({
- agent: {
- agentId: row.agent_id,
- chainId: row.chain_id,
- ownerAddress: row.owner_address,
- usdcAddress,
- relayerToken,
- origin,
- },
- subscription: {
- id: row.id,
- delegationId: row.delegation_id,
- amountPerPeriod: row.amount_per_period,
- },
- }),
- ONPERIOD_TIMEOUT_MS,
- 'onPeriod',
- );
- } catch (err) {
- const reason =
- (err.code === 'timeout' ? 'timeout: ' : '') + (err.message ?? 'unknown');
- await _safePause(row.id, reason, ctx);
- report.paused++;
- report.errors.push({ id: row.id, reason });
- logError('subscription_cron.onperiod_threw', {
- ...ctx,
- code: err.code ?? 'unknown',
- message: err.message ?? 'unknown',
- durationMs: Date.now() - rowStart,
- });
- continue;
- }
-
- if (result && result.ok) {
- // Advance next_charge_at by exactly one period to enforce idempotency.
- const nextChargeAt = new Date(
- Date.parse(row.next_charge_at) + row.period_seconds * 1000,
- );
- try {
- await sql`
- UPDATE agent_subscriptions
- SET next_charge_at = ${nextChargeAt.toISOString()},
- last_error = NULL
- WHERE id = ${row.id}
- `;
- } catch (err) {
- // Charge succeeded on-chain but we failed to advance — log loudly.
- // Do NOT pause: next run's claim guard will prevent double-charge
- // since last_charge_at >= next_charge_at for this period.
- logError('subscription_cron.advance_failed', {
- ...ctx,
- message: err.message,
- txHash: result.txHash,
- });
- report.errors.push({
- id: row.id,
- reason: 'advance_failed',
- message: err.message,
- });
- continue;
- }
-
- // Emit usage event — non-fatal if the table schema differs.
- await sql`
- INSERT INTO usage_events (user_id, kind, tool, status)
- VALUES (${row.user_id}, 'subscription_charge', 'subscription', 'success')
- `.catch((err) =>
- logError('subscription_cron.usage_event_failed', {
- ...ctx,
- message: err.message,
- }),
- );
-
- report.charged++;
- log('subscription_cron.charged', {
- ...ctx,
- txHash: result.txHash,
- durationMs: Date.now() - rowStart,
- });
- } else {
- const code = result?.code ?? 'unknown';
- const message = result?.message ?? '';
- await _safePause(row.id, `${code}: ${message}`.slice(0, 500), ctx);
- report.paused++;
- report.errors.push({ id: row.id, code, message });
- log('subscription_cron.paused', {
- ...ctx,
- code,
- message,
- durationMs: Date.now() - rowStart,
- });
- }
- } catch (err) {
- // Catch-all so one bad row can't kill the run.
- logError('subscription_cron.row_unhandled', {
- ...ctx,
- message: err.message ?? 'unknown',
- stack: err.stack,
- });
- report.errors.push({ id: row.id, reason: 'unhandled', message: err.message });
- // Best-effort pause so we don't loop on the same broken row next hour.
- await _safePause(row.id, `unhandled: ${(err.message ?? 'unknown').slice(0, 480)}`, ctx);
- report.paused++;
- }
- }
-
- log('subscription_cron.done', {
- runId,
- durationMs: Date.now() - runStart,
- processed: report.processed,
- charged: report.charged,
- paused: report.paused,
- skipped: report.skipped,
- claimLost: report.claimLost,
- errorCount: report.errors.length,
- });
-
- return json(res, 200, report);
-});
-
-async function _pause(id, lastError) {
- await sql`
- UPDATE agent_subscriptions
- SET status = 'paused', last_error = ${lastError}
- WHERE id = ${id}
- `;
-}
-
-// Like _pause but swallows its own errors so a DB hiccup during pause doesn't
-// propagate out of the per-row handler. Logs the failure for ops visibility.
-async function _safePause(id, lastError, ctx) {
- try {
- await _pause(id, lastError);
- } catch (err) {
- logError('subscription_cron.pause_failed', {
- ...ctx,
- lastError,
- message: err.message,
- });
- }
-}
diff --git a/api/cron/solana-attest-event-cleanup.js b/api/cron/solana-attest-event-cleanup.js
deleted file mode 100644
index c52b56541..000000000
--- a/api/cron/solana-attest-event-cleanup.js
+++ /dev/null
@@ -1,41 +0,0 @@
-/**
- * Stale-claim reaper for the pumpkit -> attestation bridge.
- *
- * Drops solana_attest_event_claims rows where the leader crashed or the
- * Solana RPC timed out before a signature could be recorded. The handler
- * deletes its own claim on tx-send failure, but a process crash between
- * `INSERT claim` and `delete on throw` leaves an orphan that would block
- * future retries forever.
- *
- * Runs every 10 minutes via Vercel Cron (vercel.json). Manually triggerable
- * with `Authorization: Bearer $CRON_SECRET`.
- */
-
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-
-const STALE_AFTER_SECS = 60 * 60; // 1 hour
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- const result = await sql`
- delete from solana_attest_event_claims
- where signature is null
- and claimed_at < now() - (${STALE_AFTER_SECS} || ' seconds')::interval
- returning agent_asset, network, event_id, claimed_at
- `;
-
- return json(res, 200, {
- deleted: result.length,
- stale_after_secs: STALE_AFTER_SECS,
- samples: result.slice(0, 10),
- });
-});
diff --git a/api/cron/solana-attestations-crawl.js b/api/cron/solana-attestations-crawl.js
deleted file mode 100644
index 52f6a89de..000000000
--- a/api/cron/solana-attestations-crawl.js
+++ /dev/null
@@ -1,60 +0,0 @@
-/**
- * Solana attestations crawler.
- *
- * For every Solana-registered agent in `agent_identities`, pulls recent SPL
- * Memo attestations referencing the agent's Metaplex Core asset pubkey and
- * upserts them into `solana_attestations`. Applies revoke/dispute flags.
- *
- * Runs on Vercel Cron every 5 minutes (see vercel.json). Manually triggerable
- * with `Authorization: Bearer $CRON_SECRET`.
- */
-
-import { sql } from '../_lib/db.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { crawlAgentAttestations } from '../_lib/solana-attestations.js';
-
-const PER_RUN_MAX = 50; // bound RPC fan-out per cron tick
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- const auth = req.headers['authorization'] || '';
- const expected = process.env.CRON_SECRET ? `Bearer ${process.env.CRON_SECRET}` : null;
- const fromCron = req.headers['x-vercel-cron'] === '1';
- if (!fromCron && expected && auth !== expected) {
- return error(res, 401, 'unauthorized', 'cron secret required');
- }
-
- // Pull Solana agents, oldest-cursor first.
- const agents = await sql`
- select
- a.id,
- a.meta->>'sol_mint_address' as agent_asset,
- coalesce(a.meta->>'network', 'mainnet') as network,
- a.wallet_address as owner_wallet,
- c.last_indexed_at
- from agent_identities a
- left join solana_attestations_cursor c
- on c.agent_asset = a.meta->>'sol_mint_address'
- where a.deleted_at is null
- and a.meta ? 'sol_mint_address'
- order by c.last_indexed_at nulls first
- limit ${PER_RUN_MAX}
- `;
-
- const report = { agents: [], errors: [] };
- for (const row of agents) {
- try {
- const r = await crawlAgentAttestations({
- agentAsset: row.agent_asset,
- network: row.network,
- ownerWallet: row.owner_wallet,
- });
- report.agents.push({ asset: row.agent_asset, ...r });
- } catch (err) {
- report.errors.push({ asset: row.agent_asset, error: err.message || String(err) });
- }
- }
-
- return json(res, 200, report);
-});
diff --git a/api/erc8004/[action].js b/api/erc8004/[action].js
new file mode 100644
index 000000000..b8167a869
--- /dev/null
+++ b/api/erc8004/[action].js
@@ -0,0 +1,372 @@
+/**
+ * ERC-8004 API dispatcher
+ * -----------------------
+ * GET /api/erc8004/hydrate
+ * POST /api/erc8004/import
+ * POST /api/erc8004/pin
+ *
+ * Routed via vercel.json — see top of file path patterns.
+ */
+
+import { PutObjectCommand } from '@aws-sdk/client-s3';
+import { z } from 'zod';
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
+import { parse } from '../_lib/validate.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';
+import { r2, publicUrl } from '../_lib/r2.js';
+import { env } from '../_lib/env.js';
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+
+ switch (action) {
+ case 'hydrate':
+ return handleHydrate(req, res);
+ case 'import':
+ return handleImport(req, res);
+ case 'pin':
+ return handlePin(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown erc8004 action');
+ }
+});
+
+// ── hydrate ────────────────────────────────────────────────────────────────
+
+async function handleHydrate(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // Get user's linked wallets.
+ const wallets = await sql`
+ SELECT address FROM user_wallets
+ WHERE user_id = ${session.id}
+ `;
+
+ if (wallets.length === 0) {
+ return json(res, 200, { agents: [] });
+ }
+
+ const walletAddresses = wallets.map((w) => w.address.toLowerCase());
+
+ // Query erc8004_agents_index for agents owned by these wallets.
+ const indexRows = await sql`
+ SELECT chain_id, agent_id, owner, name, description, image, glb_url
+ FROM erc8004_agents_index
+ WHERE lower(owner) = ANY(${walletAddresses})
+ AND active = true
+ ORDER BY registered_at DESC NULLS LAST
+ `;
+
+ // For each index row, check if already imported by this user.
+ const agents = [];
+ for (const row of indexRows) {
+ const [imported] = await sql`
+ SELECT id FROM agent_identities
+ WHERE user_id = ${session.id}
+ AND erc8004_agent_id = ${BigInt(row.agent_id)}
+ AND chain_id = ${row.chain_id}
+ AND deleted_at IS NULL
+ `;
+
+ agents.push({
+ chainId: row.chain_id,
+ agentId: row.agent_id,
+ name: row.name || `Agent #${row.agent_id}`,
+ description: row.description || '',
+ image: row.image || null,
+ glbUrl: row.glb_url || null,
+ owner: row.owner,
+ alreadyImported: !!imported,
+ });
+ }
+
+ return json(res, 200, { agents });
+}
+
+// ── import ─────────────────────────────────────────────────────────────────
+
+// agentId is a uint256 on-chain but we cap the decimal string length to 78
+// (max digits for uint256) and require digits only so BigInt() can't throw.
+const agentIdSchema = z
+ .union([z.string(), z.number()])
+ .transform((v) => (typeof v === 'number' ? String(v) : v.trim()))
+ .refine((v) => /^\d{1,78}$/.test(v), { message: 'agentId must be a non-negative integer' });
+
+const importBodySchema = z.object({
+ chainId: z.number().int().positive().max(2_147_483_647),
+ agentId: agentIdSchema,
+});
+
+async function handleImport(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(importBodySchema, await readJson(req));
+ const chainMeta = SERVER_CHAIN_META[body.chainId];
+ if (!chainMeta) {
+ return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
+ }
+
+ const agentId = body.agentId;
+
+ // Check if already imported by this user.
+ const [existing] = await sql`
+ SELECT id FROM agent_identities
+ WHERE user_id = ${session.id}
+ AND erc8004_agent_id = ${BigInt(agentId)}
+ AND chain_id = ${body.chainId}
+ AND deleted_at IS NULL
+ `;
+
+ if (existing) {
+ return error(res, 409, 'conflict', 'agent already imported for this user');
+ }
+
+ // Look up the index row.
+ const [indexRow] = await sql`
+ SELECT owner, agent_uri FROM erc8004_agents_index
+ WHERE chain_id = ${body.chainId} AND agent_id = ${agentId}
+ `;
+
+ if (!indexRow) {
+ return error(res, 404, 'not_found', 'agent not found in index');
+ }
+
+ // Verify owner matches one of user's wallets.
+ const wallets = await sql`
+ SELECT address FROM user_wallets WHERE user_id = ${session.id}
+ `;
+
+ const userWallets = wallets.map((w) => w.address.toLowerCase());
+ if (!userWallets.includes(indexRow.owner.toLowerCase())) {
+ return error(res, 403, 'forbidden', 'you do not own this agent');
+ }
+
+ // Resolve on-chain agent metadata.
+ let resolved;
+ try {
+ resolved = await resolveOnChainAgent({
+ chainId: body.chainId,
+ agentId,
+ fetchManifest: true,
+ timeoutMs: 5000,
+ });
+ } catch (err) {
+ return error(res, 500, 'internal', `failed to resolve agent: ${err.message}`);
+ }
+
+ if (resolved.error) {
+ return error(res, 400, 'bad_request', `failed to resolve agent: ${resolved.error}`);
+ }
+
+ const name = (resolved.name || `Agent #${agentId}`).slice(0, 255);
+ const description = (resolved.description || '').slice(0, 1000);
+
+ // Insert agent_identities row.
+ const [inserted] = await sql`
+ INSERT INTO agent_identities (
+ user_id, name, description, avatar_id,
+ chain_id, erc8004_agent_id, erc8004_registry, registration_cid
+ )
+ VALUES (
+ ${session.id},
+ ${name},
+ ${description},
+ null,
+ ${body.chainId},
+ ${BigInt(agentId)},
+ ${chainMeta.registry},
+ null
+ )
+ RETURNING id
+ `;
+
+ return json(res, 201, {
+ agent: {
+ id: inserted.id,
+ erc8004_agent_id: agentId,
+ erc8004_agent_id_chain_id: body.chainId,
+ name,
+ avatar_url: resolved.image,
+ },
+ });
+}
+
+// ── pin ────────────────────────────────────────────────────────────────────
+
+const ALLOWED = new Set([
+ 'model/gltf-binary',
+ 'model/gltf+json',
+ 'application/json',
+ 'application/octet-stream',
+ 'image/png',
+ 'image/jpeg',
+ 'image/webp',
+]);
+
+const MAX_SIZE = 25 * 1024 * 1024; // 25 MB
+
+async function handlePin(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');
+
+ const session = await getSessionUser(req);
+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const ip = clientIp(req);
+ const rl = await limits.authIp(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads');
+
+ const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();
+ if (!ALLOWED.has(ct))
+ return error(res, 415, 'unsupported_media_type', 'unsupported content-type');
+
+ const body = await readRaw(req, MAX_SIZE);
+
+ // Determine extension from content-type
+ const ext = getExt(ct);
+
+ // Try IPFS first (web3.storage or nft.storage)
+ const web3Token = process.env.WEB3_STORAGE_TOKEN;
+ const nftToken = process.env.NFT_STORAGE_TOKEN;
+
+ if (web3Token) {
+ const result = await uploadToWeb3Storage(web3Token, ext, body, ct);
+ return json(res, 200, result);
+ }
+
+ if (nftToken) {
+ const result = await uploadToNftStorage(nftToken, ext, body, ct);
+ return json(res, 200, result);
+ }
+
+ // Fallback to R2 with warning
+ const key = `erc8004/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
+ await r2.send(
+ new PutObjectCommand({
+ Bucket: env.S3_BUCKET,
+ Key: key,
+ Body: body,
+ ContentType: ct,
+ }),
+ );
+
+ const url = publicUrl(key);
+ return json(res, 200, {
+ cid: null,
+ uri: url,
+ url,
+ warning: 'R2-only pin — not decentralized',
+ });
+}
+
+function getExt(ct) {
+ switch (ct) {
+ case 'application/json':
+ return 'json';
+ case 'model/gltf-binary':
+ return 'glb';
+ case 'image/png':
+ return 'png';
+ case 'image/jpeg':
+ return 'jpg';
+ case 'image/webp':
+ return 'webp';
+ default:
+ return 'bin';
+ }
+}
+
+async function uploadToWeb3Storage(token, ext, body, ct) {
+ const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
+ const formData = new FormData();
+ const blob = new Blob([body], { type: ct });
+ formData.append('file', blob, filename);
+
+ const response = await fetch('https://api.web3.storage/upload', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ throw new Error(`web3.storage upload failed: ${response.status} ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ const cid = data.cid;
+
+ // web3.storage and nft.storage guarantee content-addressable uploads:
+ // same bytes → same CID every time, idempotent by design.
+ const uri = `ipfs://${cid}/${filename}`;
+ const url = `https://w3s.link/ipfs/${cid}/${filename}`;
+
+ return { cid, uri, url };
+}
+
+async function uploadToNftStorage(token, ext, body, ct) {
+ const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
+ const formData = new FormData();
+ const blob = new Blob([body], { type: ct });
+ formData.append('file', blob, filename);
+
+ const response = await fetch('https://api.nft.storage/upload', {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ },
+ body: formData,
+ });
+
+ if (!response.ok) {
+ throw new Error(`nft.storage upload failed: ${response.status} ${response.statusText}`);
+ }
+
+ const data = await response.json();
+ const cid = data.value.cid;
+
+ // nft.storage guarantees content-addressable uploads: same bytes → same CID.
+ const uri = `ipfs://${cid}/${filename}`;
+ const url = `https://w3s.link/ipfs/${cid}/${filename}`;
+
+ return { cid, uri, url };
+}
+
+function readRaw(req, limit) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (chunk) => {
+ total += chunk.length;
+ if (total > limit) {
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(chunk);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks)));
+ req.on('error', reject);
+ });
+}
diff --git a/api/erc8004/hydrate.js b/api/erc8004/hydrate.js
deleted file mode 100644
index b1325335e..000000000
--- a/api/erc8004/hydrate.js
+++ /dev/null
@@ -1,68 +0,0 @@
-/**
- * GET /api/erc8004/hydrate
- * Fetch all on-chain agents owned by the user's linked wallets.
- * Returns list of discovered agents with alreadyImported flag.
- */
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- // Get user's linked wallets.
- const wallets = await sql`
- SELECT address FROM user_wallets
- WHERE user_id = ${session.id}
- `;
-
- if (wallets.length === 0) {
- return json(res, 200, { agents: [] });
- }
-
- const walletAddresses = wallets.map((w) => w.address.toLowerCase());
-
- // Query erc8004_agents_index for agents owned by these wallets.
- const indexRows = await sql`
- SELECT chain_id, agent_id, owner, name, description, image, glb_url
- FROM erc8004_agents_index
- WHERE lower(owner) = ANY(${walletAddresses})
- AND active = true
- ORDER BY registered_at DESC NULLS LAST
- `;
-
- // For each index row, check if already imported by this user.
- const agents = [];
- for (const row of indexRows) {
- const [imported] = await sql`
- SELECT id FROM agent_identities
- WHERE user_id = ${session.id}
- AND erc8004_agent_id = ${BigInt(row.agent_id)}
- AND chain_id = ${row.chain_id}
- AND deleted_at IS NULL
- `;
-
- agents.push({
- chainId: row.chain_id,
- agentId: row.agent_id,
- name: row.name || `Agent #${row.agent_id}`,
- description: row.description || '',
- image: row.image || null,
- glbUrl: row.glb_url || null,
- owner: row.owner,
- alreadyImported: !!imported,
- });
- }
-
- return json(res, 200, { agents });
-});
diff --git a/api/erc8004/import.js b/api/erc8004/import.js
deleted file mode 100644
index b941a8604..000000000
--- a/api/erc8004/import.js
+++ /dev/null
@@ -1,128 +0,0 @@
-/**
- * POST /api/erc8004/import
- * Import an on-chain agent for the authenticated user.
- * Creates a local agent_identities row pointing at the on-chain record.
- * Idempotent: 409 if already imported for this user.
- */
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
-import { parse } from '../_lib/validate.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { resolveOnChainAgent, SERVER_CHAIN_META } from '../_lib/onchain.js';
-import { z } from 'zod';
-
-// agentId is a uint256 on-chain but we cap the decimal string length to 78
-// (max digits for uint256) and require digits only so BigInt() can't throw.
-const agentIdSchema = z
- .union([z.string(), z.number()])
- .transform((v) => (typeof v === 'number' ? String(v) : v.trim()))
- .refine((v) => /^\d{1,78}$/.test(v), { message: 'agentId must be a non-negative integer' });
-
-const bodySchema = z.object({
- chainId: z.number().int().positive().max(2_147_483_647),
- agentId: agentIdSchema,
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const chainMeta = SERVER_CHAIN_META[body.chainId];
- if (!chainMeta) {
- return error(res, 400, 'bad_request', `unsupported chain ${body.chainId}`);
- }
-
- const agentId = body.agentId;
-
- // Check if already imported by this user.
- const [existing] = await sql`
- SELECT id FROM agent_identities
- WHERE user_id = ${session.id}
- AND erc8004_agent_id = ${BigInt(agentId)}
- AND chain_id = ${body.chainId}
- AND deleted_at IS NULL
- `;
-
- if (existing) {
- return error(res, 409, 'conflict', 'agent already imported for this user');
- }
-
- // Look up the index row.
- const [indexRow] = await sql`
- SELECT owner, agent_uri FROM erc8004_agents_index
- WHERE chain_id = ${body.chainId} AND agent_id = ${agentId}
- `;
-
- if (!indexRow) {
- return error(res, 404, 'not_found', 'agent not found in index');
- }
-
- // Verify owner matches one of user's wallets.
- const wallets = await sql`
- SELECT address FROM user_wallets WHERE user_id = ${session.id}
- `;
-
- const userWallets = wallets.map((w) => w.address.toLowerCase());
- if (!userWallets.includes(indexRow.owner.toLowerCase())) {
- return error(res, 403, 'forbidden', 'you do not own this agent');
- }
-
- // Resolve on-chain agent metadata.
- let resolved;
- try {
- resolved = await resolveOnChainAgent({
- chainId: body.chainId,
- agentId,
- fetchManifest: true,
- timeoutMs: 5000,
- });
- } catch (err) {
- return error(res, 500, 'internal', `failed to resolve agent: ${err.message}`);
- }
-
- if (resolved.error) {
- return error(res, 400, 'bad_request', `failed to resolve agent: ${resolved.error}`);
- }
-
- const name = (resolved.name || `Agent #${agentId}`).slice(0, 255);
- const description = (resolved.description || '').slice(0, 1000);
-
- // Insert agent_identities row.
- const [inserted] = await sql`
- INSERT INTO agent_identities (
- user_id, name, description, avatar_id,
- chain_id, erc8004_agent_id, erc8004_registry, registration_cid
- )
- VALUES (
- ${session.id},
- ${name},
- ${description},
- null,
- ${body.chainId},
- ${BigInt(agentId)},
- ${chainMeta.registry},
- null
- )
- RETURNING id
- `;
-
- return json(res, 201, {
- agent: {
- id: inserted.id,
- erc8004_agent_id: agentId,
- erc8004_agent_id_chain_id: body.chainId,
- name,
- avatar_url: resolved.image,
- },
- });
-});
diff --git a/api/erc8004/pin.js b/api/erc8004/pin.js
deleted file mode 100644
index 3670c921c..000000000
--- a/api/erc8004/pin.js
+++ /dev/null
@@ -1,164 +0,0 @@
-import { PutObjectCommand } from '@aws-sdk/client-s3';
-import { r2, publicUrl } from '../_lib/r2.js';
-import { cors, error, json, wrap } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { env } from '../_lib/env.js';
-
-const ALLOWED = new Set([
- 'model/gltf-binary',
- 'model/gltf+json',
- 'application/json',
- 'application/octet-stream',
- 'image/png',
- 'image/jpeg',
- 'image/webp',
-]);
-
-const MAX_SIZE = 25 * 1024 * 1024; // 25 MB
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (req.method !== 'POST') return error(res, 405, 'method_not_allowed', 'POST only');
-
- const session = await getSessionUser(req);
- if (!session) return error(res, 401, 'unauthorized', 'sign in required');
-
- const ip = clientIp(req);
- const rl = await limits.authIp(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads');
-
- const ct = (req.headers['content-type'] || 'application/octet-stream').split(';')[0].trim();
- if (!ALLOWED.has(ct))
- return error(res, 415, 'unsupported_media_type', 'unsupported content-type');
-
- const body = await readRaw(req, MAX_SIZE);
-
- // Determine extension from content-type
- const ext = getExt(ct);
-
- // Try IPFS first (web3.storage or nft.storage)
- const web3Token = process.env.WEB3_STORAGE_TOKEN;
- const nftToken = process.env.NFT_STORAGE_TOKEN;
-
- if (web3Token) {
- const result = await uploadToWeb3Storage(web3Token, ext, body, ct);
- return json(res, 200, result);
- }
-
- if (nftToken) {
- const result = await uploadToNftStorage(nftToken, ext, body, ct);
- return json(res, 200, result);
- }
-
- // Fallback to R2 with warning
- const key = `erc8004/${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
- await r2.send(
- new PutObjectCommand({
- Bucket: env.S3_BUCKET,
- Key: key,
- Body: body,
- ContentType: ct,
- }),
- );
-
- const url = publicUrl(key);
- return json(res, 200, {
- cid: null,
- uri: url,
- url,
- warning: 'R2-only pin — not decentralized',
- });
-});
-
-function getExt(ct) {
- switch (ct) {
- case 'application/json':
- return 'json';
- case 'model/gltf-binary':
- return 'glb';
- case 'image/png':
- return 'png';
- case 'image/jpeg':
- return 'jpg';
- case 'image/webp':
- return 'webp';
- default:
- return 'bin';
- }
-}
-
-async function uploadToWeb3Storage(token, ext, body, ct) {
- const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
- const formData = new FormData();
- const blob = new Blob([body], { type: ct });
- formData.append('file', blob, filename);
-
- const response = await fetch('https://api.web3.storage/upload', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${token}`,
- },
- body: formData,
- });
-
- if (!response.ok) {
- throw new Error(`web3.storage upload failed: ${response.status} ${response.statusText}`);
- }
-
- const data = await response.json();
- const cid = data.cid;
-
- // web3.storage and nft.storage guarantee content-addressable uploads:
- // same bytes → same CID every time, idempotent by design.
- const uri = `ipfs://${cid}/${filename}`;
- const url = `https://w3s.link/ipfs/${cid}/${filename}`;
-
- return { cid, uri, url };
-}
-
-async function uploadToNftStorage(token, ext, body, ct) {
- const filename = `${Date.now()}-${Math.random().toString(36).slice(2)}.${ext}`;
- const formData = new FormData();
- const blob = new Blob([body], { type: ct });
- formData.append('file', blob, filename);
-
- const response = await fetch('https://api.nft.storage/upload', {
- method: 'POST',
- headers: {
- Authorization: `Bearer ${token}`,
- },
- body: formData,
- });
-
- if (!response.ok) {
- throw new Error(`nft.storage upload failed: ${response.status} ${response.statusText}`);
- }
-
- const data = await response.json();
- const cid = data.value.cid;
-
- // nft.storage guarantees content-addressable uploads: same bytes → same CID.
- const uri = `ipfs://${cid}/${filename}`;
- const url = `https://w3s.link/ipfs/${cid}/${filename}`;
-
- return { cid, uri, url };
-}
-
-function readRaw(req, limit) {
- return new Promise((resolve, reject) => {
- const chunks = [];
- let total = 0;
- req.on('data', (chunk) => {
- total += chunk.length;
- if (total > limit) {
- reject(Object.assign(new Error('payload too large'), { status: 413 }));
- req.destroy();
- return;
- }
- chunks.push(chunk);
- });
- req.on('end', () => resolve(Buffer.concat(chunks)));
- req.on('error', reject);
- });
-}
diff --git a/api/permissions/[action].js b/api/permissions/[action].js
new file mode 100644
index 000000000..b45fc18b5
--- /dev/null
+++ b/api/permissions/[action].js
@@ -0,0 +1,1191 @@
+/**
+ * Permissions API dispatcher
+ * --------------------------
+ * POST /api/permissions/grant
+ * GET /api/permissions/list
+ * GET /api/permissions/metadata
+ * POST /api/permissions/redeem
+ * POST /api/permissions/revoke
+ * GET /api/permissions/verify
+ *
+ * Routed via vercel.json — see top of file path patterns.
+ */
+
+import { createHash } from 'node:crypto';
+import { z } from 'zod';
+import { ethers, Wallet, JsonRpcProvider, Contract, Interface, getAddress, isAddress } from 'ethers';
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { env } from '../_lib/env.js';
+import { recordEvent } from '../_lib/usage.js';
+import { SERVER_CHAIN_META } from '../_lib/onchain.js';
+import {
+ DELEGATION_MANAGER_DEPLOYMENTS,
+ DELEGATION_MANAGER_ABI,
+ EIP712_DOMAIN,
+ DELEGATION_TYPES,
+} from '../../src/erc7710/abi.js';
+import {
+ isDelegationValid,
+ redeemDelegation,
+ PermissionError,
+} from '../../src/permissions/toolkit.js';
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+
+ switch (action) {
+ case 'grant':
+ return handleGrant(req, res);
+ case 'list':
+ return handleList(req, res);
+ case 'metadata':
+ return handleMetadata(req, res);
+ case 'redeem':
+ return handleRedeem(req, res);
+ case 'revoke':
+ return handleRevoke(req, res);
+ case 'verify':
+ return handleVerify(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown permissions action');
+ }
+});
+
+// ── grant ──────────────────────────────────────────────────────────────────
+
+const ROOT_AUTHORITY = '0x0000000000000000000000000000000000000000000000000000000000000000';
+
+const hexAddr = z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address');
+const hexBytes = z.string().regex(/^0x([0-9a-fA-F]{2})*$/, 'must be 0x-prefixed hex bytes');
+const hexBytes32 = z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 32-byte hex value');
+
+const caveatSchema = z.object({
+ enforcer: hexAddr,
+ terms: hexBytes.default('0x'),
+ args: hexBytes.default('0x'),
+});
+
+const delegationSchema = z.object({
+ delegator: hexAddr,
+ delegate: hexAddr,
+ authority: hexBytes32.optional(),
+ caveats: z.array(caveatSchema).default([]),
+ salt: z.union([
+ z
+ .string()
+ .regex(/^(0x[0-9a-fA-F]+|\d+)$/, 'salt must be a decimal or 0x-prefixed hex integer'),
+ z.number().int().nonnegative(),
+ ]),
+ signature: hexBytes,
+ hash: hexBytes32,
+});
+
+const scopeSchema = z.object({
+ token: z.string().min(1),
+ maxAmount: z.string().min(1),
+ period: z.enum(['daily', 'weekly', 'once']),
+ targets: z.array(hexAddr).min(1),
+ expiry: z.number().int().positive(),
+});
+
+const grantBodySchema = z.object({
+ agentId: z.string().uuid(),
+ chainId: z.number().int().positive(),
+ delegation: delegationSchema,
+ scope: scopeSchema,
+});
+
+async function handleGrant(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.permissionsGrant(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = await readJson(req);
+ const parsed = grantBodySchema.safeParse(raw);
+ if (!parsed.success) {
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
+ return error(res, 400, 'validation_error', msg);
+ }
+ const { agentId, chainId, delegation, scope } = parsed.data;
+
+ // chainId must be a supported DelegationManager deployment
+ if (!(chainId in DELEGATION_MANAGER_DEPLOYMENTS)) {
+ return error(res, 400, 'chain_not_supported', `chainId ${chainId} is not supported`);
+ }
+
+ // Owner gate: agent must exist and belong to the authenticated user
+ const [agent] = await sql`
+ select id, user_id from agent_identities
+ where id = ${agentId} and deleted_at is null
+ limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== user.id) return error(res, 403, 'not_owner', 'you do not own this agent');
+
+ // Wallet linkage: delegation.delegator must be a wallet linked to the authenticated user
+ const delegatorLower = delegation.delegator.toLowerCase();
+ const [linkedWallet] = await sql`
+ select address from user_wallets
+ where user_id = ${user.id} and address = ${delegatorLower}
+ limit 1
+ `;
+ if (!linkedWallet) {
+ return error(
+ res,
+ 409,
+ 'wallet_not_linked',
+ 'delegation.delegator is not linked to your account',
+ );
+ }
+
+ // Signature verification — two steps:
+ // 1. Re-derive the EIP-712 hash from delegation fields and compare with delegation.hash
+ // (prevents chain-hop replay: different contract address → different hash).
+ // 2. Recover the signer from the signature and verify it matches delegation.delegator.
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
+ const eip712Domain = EIP712_DOMAIN({ chainId, verifyingContract: managerAddr });
+ let derivedHash;
+ try {
+ const structValue = {
+ delegate: delegation.delegate,
+ delegator: delegation.delegator,
+ authority: delegation.authority || ROOT_AUTHORITY,
+ caveats: delegation.caveats.map((c) => ({
+ enforcer: c.enforcer,
+ terms: c.terms,
+ args: c.args,
+ })),
+ salt: BigInt(delegation.salt),
+ };
+
+ derivedHash = ethers.TypedDataEncoder.hash(eip712Domain, DELEGATION_TYPES, structValue);
+
+ if (derivedHash.toLowerCase() !== delegation.hash.toLowerCase()) {
+ return error(
+ res,
+ 400,
+ 'hash_mismatch',
+ 'delegation.hash does not match the delegation fields',
+ );
+ }
+
+ const recovered = ethers.verifyTypedData(
+ eip712Domain,
+ DELEGATION_TYPES,
+ structValue,
+ delegation.signature,
+ );
+ if (recovered.toLowerCase() !== delegatorLower) {
+ return error(
+ res,
+ 400,
+ 'signature_invalid',
+ 'signature does not match delegation.delegator',
+ );
+ }
+ } catch (err) {
+ if (err instanceof PermissionError) {
+ return error(res, 400, err.code || 'signature_invalid', err.message);
+ }
+ return error(res, 400, 'signature_invalid', err.message || 'invalid delegation signature');
+ }
+
+ // On-chain revocation check (isDelegationValid from task 04)
+ const rpcUrl = SERVER_CHAIN_META[chainId]?.rpc;
+ const validity = await isDelegationValid({ hash: delegation.hash, chainId, rpcUrl }).catch(
+ (err) => {
+ if (err instanceof PermissionError) return { valid: false, reason: err.code };
+ console.warn('[grant] isDelegationValid error', err?.message);
+ return { valid: true }; // RPC unavailable; proceed and rely on indexer for revocation
+ },
+ );
+ if (!validity.valid) {
+ return error(
+ res,
+ 400,
+ validity.reason || 'signature_invalid',
+ 'delegation is not valid on-chain',
+ );
+ }
+
+ // Scope sanity checks
+ const nowSec = Math.floor(Date.now() / 1000);
+ if (scope.expiry <= nowSec + 60) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'scope.expiry must be at least 60 seconds in the future',
+ );
+ }
+ if (scope.expiry > nowSec + 365 * 24 * 3600) {
+ return error(res, 400, 'validation_error', 'scope.expiry must be within 365 days');
+ }
+ let maxAmountBig;
+ try {
+ maxAmountBig = BigInt(scope.maxAmount);
+ } catch {
+ return error(res, 400, 'validation_error', 'scope.maxAmount must be a numeric string');
+ }
+ if (maxAmountBig <= 0n) {
+ return error(res, 400, 'validation_error', 'scope.maxAmount must be positive');
+ }
+ let targets;
+ try {
+ targets = scope.targets.map((t) => ethers.getAddress(t));
+ } catch {
+ return error(res, 400, 'validation_error', 'scope.targets contains an invalid address');
+ }
+
+ const delegationHash = derivedHash;
+ const expiresAt = new Date(scope.expiry * 1000).toISOString();
+ const delegatorAddr = ethers.getAddress(delegation.delegator);
+ const delegateAddr = ethers.getAddress(delegation.delegate);
+
+ const delegationJson = {
+ delegator: delegation.delegator,
+ delegate: delegation.delegate,
+ authority: delegation.authority || ROOT_AUTHORITY,
+ caveats: delegation.caveats,
+ salt: String(delegation.salt),
+ // signature stored as part of the envelope; not logged separately
+ signature: delegation.signature,
+ hash: delegationHash,
+ };
+ const scopeJson = { ...scope, targets };
+
+ // Persist — delegation_hash is UNIQUE; on conflict return 409
+ const rows = await sql`
+ insert into agent_delegations (
+ agent_id, chain_id, delegator_address, delegate_address,
+ delegation_hash, delegation_json, scope, expires_at
+ )
+ values (
+ ${agentId},
+ ${chainId},
+ ${delegatorAddr.toLowerCase()},
+ ${delegateAddr.toLowerCase()},
+ ${delegationHash},
+ ${JSON.stringify(delegationJson)}::jsonb,
+ ${JSON.stringify(scopeJson)}::jsonb,
+ ${expiresAt}
+ )
+ on conflict (delegation_hash) do nothing
+ returning id
+ `;
+
+ if (!rows || rows.length === 0) {
+ const [existing] = await sql`
+ select id from agent_delegations where delegation_hash = ${delegationHash} limit 1
+ `;
+ return error(res, 409, 'duplicate_delegation', 'this delegation has already been granted', {
+ id: existing?.id,
+ });
+ }
+
+ const { id } = rows[0];
+
+ recordEvent({ userId: user.id, agentId, kind: 'permissions.grant' });
+
+ return json(res, 200, { ok: true, id, delegationHash, expiresAt });
+}
+
+// ── list ───────────────────────────────────────────────────────────────────
+
+const LIST_PUBLIC_CACHE = 'public, max-age=30, s-maxage=60';
+const VALID_STATUSES = new Set(['active', 'revoked', 'expired', 'all']);
+
+async function handleList(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId') || null;
+ const delegator = url.searchParams.get('delegator') || null;
+
+ if (!agentId && !delegator) {
+ return error(res, 400, 'missing_filter', 'agentId or delegator query param is required');
+ }
+
+ const statusParam = url.searchParams.get('status') || 'active';
+ if (!VALID_STATUSES.has(statusParam)) {
+ return error(
+ res,
+ 400,
+ 'validation_error',
+ 'status must be active, revoked, expired, or all',
+ );
+ }
+
+ const chainIdParam = url.searchParams.get('chainId');
+ const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
+ if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ }
+
+ const limitParam = Math.min(
+ 200,
+ Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)),
+ );
+ const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10));
+
+ // agentId-only path: public, no auth required
+ if (agentId && !delegator) {
+ const rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE agent_id = ${agentId}
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+
+ const delegations = rows.map(toListPublicShape);
+ const body = { ok: true, delegations };
+ if (rows.length === limitParam) body.nextOffset = offset + limitParam;
+
+ return json(res, 200, body, { 'cache-control': LIST_PUBLIC_CACHE });
+ }
+
+ // delegator path (or both provided): session required
+ const session = await getSessionUser(req, res);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) {
+ return error(res, 401, 'unauthorized', 'sign in required to list delegations by delegator');
+ }
+ const userId = session?.id ?? bearer?.userId;
+
+ // Verify the session user owns this delegator address
+ const targetDelegator = delegator || null;
+ if (targetDelegator) {
+ const [wallet] = await sql`
+ SELECT 1 FROM user_wallets
+ WHERE user_id = ${userId}
+ AND lower(address) = lower(${targetDelegator})
+ LIMIT 1
+ `;
+ if (!wallet) {
+ return error(
+ res,
+ 403,
+ 'forbidden',
+ 'delegator address does not belong to your account',
+ );
+ }
+ }
+
+ const whereAgentId = agentId;
+ const rows = await sql`
+ SELECT
+ id, chain_id, delegator_address, delegate_address, delegation_hash,
+ delegation_json, scope, status, expires_at, created_at, last_redeemed_at, redemption_count
+ FROM agent_delegations
+ WHERE (${whereAgentId}::uuid IS NULL OR agent_id = ${whereAgentId}::uuid)
+ AND (${targetDelegator}::text IS NULL OR lower(delegator_address) = lower(${targetDelegator}::text))
+ AND (${statusParam} = 'all' OR status = ${statusParam})
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY created_at DESC
+ LIMIT ${limitParam} OFFSET ${offset}
+ `;
+
+ const delegations = rows.map(toListAuthShape);
+ const body = { ok: true, delegations };
+ if (rows.length === limitParam) body.nextOffset = offset + limitParam;
+
+ return json(res, 200, body);
+}
+
+function toListPublicShape(row) {
+ return {
+ id: row.id,
+ chainId: row.chain_id,
+ delegator: row.delegator_address,
+ delegate: row.delegate_address,
+ delegationHash: row.delegation_hash,
+ scope: row.scope,
+ status: row.status,
+ expiresAt: row.expires_at,
+ createdAt: row.created_at,
+ lastRedeemedAt: row.last_redeemed_at,
+ redemptionCount: row.redemption_count,
+ };
+}
+
+function toListAuthShape(row) {
+ return {
+ ...toListPublicShape(row),
+ delegationJson: row.delegation_json,
+ };
+}
+
+// ── metadata ───────────────────────────────────────────────────────────────
+
+function metadataCorsHeaders(res) {
+ res.setHeader('access-control-allow-origin', '*');
+ res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
+ res.setHeader('access-control-allow-headers', 'content-type');
+ res.setHeader('access-control-max-age', '86400');
+}
+
+async function handleMetadata(req, res) {
+ if (req.method === 'OPTIONS') {
+ metadataCorsHeaders(res);
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ metadataCorsHeaders(res);
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = url.searchParams.get('agentId');
+ if (!agentId) return error(res, 400, 'missing_param', 'agentId is required');
+
+ const chainIdParam = url.searchParams.get('chainId');
+ const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
+ if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ }
+
+ // Verify agent exists
+ const [agent] = await sql`
+ SELECT id FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ LIMIT 1
+ `;
+ if (!agent) {
+ return json(res, 404, { ok: false, error: 'agent_not_found' });
+ }
+
+ const rows = await sql`
+ SELECT
+ chain_id, delegator_address, delegate_address, delegation_hash,
+ delegation_json, scope, expires_at, created_at, revoked_at
+ FROM agent_delegations
+ WHERE agent_id = ${agentId}
+ AND status = 'active'
+ AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
+ ORDER BY expires_at DESC
+ `;
+
+ const delegations = rows.map((r) => ({
+ chainId: r.chain_id,
+ delegator: r.delegator_address,
+ delegate: r.delegate_address,
+ hash: r.delegation_hash,
+ scope: r.scope,
+ expiresAt: r.expires_at,
+ createdAt: r.created_at,
+ envelope: r.delegation_json,
+ }));
+
+ // delegationManager: use the filtered chain if provided, otherwise first delegation's chain
+ const resolveChain = chainId ?? rows[0]?.chain_id ?? null;
+ const delegationManager = resolveChain
+ ? (DELEGATION_MANAGER_DEPLOYMENTS[resolveChain] ?? null)
+ : null;
+
+ // Last-Modified: max of created_at and revoked_at across returned rows
+ let lastModified = null;
+ for (const r of rows) {
+ const candidates = [r.created_at, r.revoked_at].filter(Boolean);
+ for (const d of candidates) {
+ if (!lastModified || d > lastModified) lastModified = d;
+ }
+ }
+
+ const body = {
+ ok: true,
+ agentId,
+ spec: 'erc-7715/0.1',
+ delegationManager,
+ delegations,
+ };
+
+ const bodyStr = JSON.stringify(body);
+ const etag = `"${createHash('sha256').update(bodyStr).digest('hex').slice(0, 32)}"`;
+
+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');
+ res.setHeader('etag', etag);
+ if (lastModified) res.setHeader('last-modified', new Date(lastModified).toUTCString());
+
+ // ETag short-circuit
+ if (req.headers['if-none-match'] === etag) {
+ res.statusCode = 304;
+ res.end();
+ return;
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.end(bodyStr);
+}
+
+// ── redeem ─────────────────────────────────────────────────────────────────
+
+// Idempotency cache (in-memory, 10-minute TTL)
+const idempotencyCache = new Map();
+const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
+
+function idempotencyGet(key) {
+ const entry = idempotencyCache.get(key);
+ if (!entry) return null;
+ if (Date.now() > entry.expiresAt) {
+ idempotencyCache.delete(key);
+ return null;
+ }
+ return entry.result;
+}
+
+function idempotencySet(key, result) {
+ // Purge expired entries opportunistically.
+ const now = Date.now();
+ for (const [k, v] of idempotencyCache) {
+ if (now > v.expiresAt) idempotencyCache.delete(k);
+ }
+ idempotencyCache.set(key, { result, expiresAt: now + IDEMPOTENCY_TTL_MS });
+}
+
+const hexData = z.string().regex(/^0x[0-9a-fA-F]*$/, 'must be 0x-prefixed hex');
+const weiValue = z.string().regex(/^\d+$/, 'value must be a decimal integer string');
+
+const callSchema = z.object({
+ to: z.string().refine((v) => isAddress(v), 'to must be a valid EIP-55 address'),
+ value: weiValue.default('0'),
+ data: hexData.default('0x'),
+});
+
+const redeemBodySchema = z.object({
+ id: z.string().uuid(),
+ calls: z.array(callSchema).min(1).max(4),
+});
+
+// ERC-20 selector helpers
+const TRANSFER_SELECTOR = '0xa9059cbb';
+const TRANSFER_FROM_SELECTOR = '0x23b872dd';
+
+// Decode token amount from ERC-20 transfer/transferFrom calldata.
+// Param slots (0-indexed) start at hex[8 + n*64]. Returns null if unrecognised.
+function decodeErc20AmountFixed(data) {
+ if (!data || data.length < 10) return null;
+ const hex = data.startsWith('0x') ? data.slice(2) : data;
+ const sel = '0x' + hex.slice(0, 8).toLowerCase();
+ try {
+ if (sel === TRANSFER_SELECTOR && hex.length >= 8 + 64 + 64) {
+ // slot 1 (0-indexed) = amount
+ return BigInt('0x' + hex.slice(8 + 64, 8 + 64 + 64));
+ }
+ if (sel === TRANSFER_FROM_SELECTOR && hex.length >= 8 + 64 + 64 + 64) {
+ // slot 2 (0-indexed) = amount
+ return BigInt('0x' + hex.slice(8 + 64 + 64, 8 + 64 + 64 + 64));
+ }
+ } catch {
+ return null;
+ }
+ return null;
+}
+
+function periodStart(period) {
+ const now = new Date();
+ if (period === 'daily') {
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
+ }
+ if (period === 'weekly') {
+ const day = now.getUTCDay(); // 0=Sun
+ const diff = day === 0 ? -6 : 1 - day; // back to Monday
+ const monday = new Date(now);
+ monday.setUTCDate(now.getUTCDate() + diff);
+ monday.setUTCHours(0, 0, 0, 0);
+ return monday;
+ }
+ // 'once' or unknown: entire history counts
+ return new Date(0);
+}
+
+function getRpcUrl(chainId) {
+ return (
+ process.env[`RPC_URL_${chainId}`] ||
+ // Shared fallback names that might already exist in the project
+ (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||
+ (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||
+ null
+ );
+}
+
+async function handleRedeem(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Feature flag — 503 when disabled
+ if (!env.PERMISSIONS_RELAYER_ENABLED) {
+ return error(res, 503, 'feature_disabled', 'relayer not enabled on this deployment');
+ }
+
+ // Rate limit — strict bucket since each request costs gas
+ const ip = clientIp(req);
+ const rl = await limits.strict(ip);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ // Auth — agent bearer only (no user sessions on this machine endpoint)
+ const token = extractBearer(req);
+ const bearer = await authenticateBearer(token);
+ if (!bearer) return error(res, 401, 'unauthorized', 'valid bearer token required');
+ if (!hasScope(bearer.scope, 'permissions:redeem')) {
+ return error(
+ res,
+ 403,
+ 'insufficient_scope',
+ "token must include 'permissions:redeem' scope",
+ );
+ }
+
+ // Idempotency-Key check (before parsing body — key is in header)
+ const idempotencyKey = req.headers['idempotency-key'] || null;
+
+ // Parse body
+ let body;
+ try {
+ body = parse(redeemBodySchema, await readJson(req));
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'validation_error', err.message);
+ }
+ const { id, calls } = body;
+
+ // Idempotency-Key early return
+ if (idempotencyKey) {
+ const cached = idempotencyGet(`${id}:${idempotencyKey}`);
+ if (cached) return json(res, 200, cached);
+ }
+
+ // Load delegation row
+ const [row] = await sql`
+ SELECT id, agent_id, chain_id, delegation_hash, delegation_json, scope,
+ status, expires_at, redemption_count, last_redeemed_at
+ FROM agent_delegations
+ WHERE id = ${id}
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
+
+ // Check status
+ if (row.status === 'revoked') {
+ return error(res, 409, 'delegation_revoked', 'delegation has been revoked');
+ }
+
+ // Check expiry; auto-flip status if expired
+ const now = new Date();
+ if (new Date(row.expires_at) <= now) {
+ // Side-effect: mark as expired without blocking
+ sql`UPDATE agent_delegations SET status = 'expired' WHERE id = ${id}`.catch(() => {});
+ return error(res, 409, 'delegation_expired', 'delegation has expired');
+ }
+
+ if (row.status !== 'active') {
+ return error(res, 409, 'delegation_expired', `delegation status is '${row.status}'`);
+ }
+
+ const scope = row.scope;
+ const chainId = row.chain_id;
+
+ // ── Server-side scope checks (cheap, prevent paying gas on doomed tx) ────
+
+ // 1. Target allow-list
+ const allowedTargets = new Set((scope.targets || []).map((t) => t.toLowerCase()));
+ for (const call of calls) {
+ if (!allowedTargets.has(call.to.toLowerCase())) {
+ return error(
+ res,
+ 403,
+ 'target_not_allowed',
+ `call target ${call.to} is not in scope.targets`,
+ );
+ }
+ }
+
+ // 2. Native ETH: reject non-zero value if token is ERC-20
+ const isNative = scope.token === 'native';
+ if (!isNative) {
+ for (const call of calls) {
+ if (BigInt(call.value) > 0n) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'non-zero ETH value not allowed for ERC-20 scoped delegation',
+ );
+ }
+ }
+ }
+
+ // 3. Amount cap: compute period spend from usage_events history
+ const maxAmount = BigInt(scope.maxAmount || '0');
+ const pStart = periodStart(scope.period || 'daily');
+
+ if (isNative) {
+ // Sum ETH values in this request
+ const requestAmount = calls.reduce((s, c) => s + BigInt(c.value), 0n);
+
+ // Query period history
+ const [histRow] = await sql`
+ SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
+ FROM usage_events
+ WHERE kind = 'permissions.redeem'
+ AND meta->>'delegation_id' = ${id}
+ AND created_at >= ${pStart.toISOString()}
+ `;
+ const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
+
+ if (requestAmount + historicalSpend > maxAmount) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'ETH spend would exceed scope.maxAmount for this period',
+ {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ },
+ );
+ }
+ } else {
+ // ERC-20: decode transfer amounts from call data
+ let requestAmount = 0n;
+ for (const call of calls) {
+ const decoded = decodeErc20AmountFixed(call.data);
+ if (decoded === null) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ `call to ${call.to} does not look like an ERC-20 transfer or transferFrom`,
+ );
+ }
+ requestAmount += decoded;
+ }
+
+ const [histRow] = await sql`
+ SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
+ FROM usage_events
+ WHERE kind = 'permissions.redeem'
+ AND meta->>'delegation_id' = ${id}
+ AND created_at >= ${pStart.toISOString()}
+ `;
+ const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
+
+ if (requestAmount + historicalSpend > maxAmount) {
+ return error(
+ res,
+ 403,
+ 'scope_exceeded',
+ 'token spend would exceed scope.maxAmount for this period',
+ {
+ maxAmount: scope.maxAmount,
+ periodSpent: historicalSpend.toString(),
+ requested: requestAmount.toString(),
+ },
+ );
+ }
+ }
+
+ // ── Build signer ───────────────────────────────────────────────────────
+ const rpcUrl = getRpcUrl(chainId);
+ if (!rpcUrl) {
+ return error(
+ res,
+ 502,
+ 'rpc_error',
+ `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`,
+ );
+ }
+
+ let signer;
+ try {
+ const provider = new JsonRpcProvider(rpcUrl);
+ // AGENT_RELAYER_KEY is never logged — only use it to construct the Wallet
+ signer = new Wallet(env.AGENT_RELAYER_KEY, provider);
+ } catch {
+ return error(res, 500, 'internal_error', 'failed to initialise relayer signer');
+ }
+
+ // ── Submit on-chain ────────────────────────────────────────────────────
+ let txHash, receipt;
+ try {
+ ({ txHash, receipt } = await redeemDelegation({
+ delegation: row.delegation_json,
+ delegationHash: row.delegation_hash,
+ calls,
+ signer,
+ chainId,
+ }));
+ } catch (err) {
+ if (err instanceof PermissionError && err.code === 'delegation_revoked') {
+ // Auto-sync status in DB
+ sql`UPDATE agent_delegations SET status = 'revoked' WHERE id = ${id}`.catch(() => {});
+ return error(res, 409, 'delegation_revoked', err.message);
+ }
+ // RPC or provider error
+ console.error('[permissions/redeem] on-chain error', err?.code, err?.message);
+ return error(res, 502, 'rpc_error', err?.message || 'on-chain call failed');
+ }
+
+ // ── Update DB ──────────────────────────────────────────────────────────
+ await sql`
+ UPDATE agent_delegations
+ SET redemption_count = redemption_count + 1,
+ last_redeemed_at = NOW()
+ WHERE id = ${id}
+ `;
+
+ // Compute amount redeemed for usage tracking
+ const redeemAmount = isNative
+ ? calls.reduce((s, c) => s + BigInt(c.value), 0n).toString()
+ : calls
+ .reduce((s, c) => {
+ const a = decodeErc20AmountFixed(c.data);
+ return s + (a ?? 0n);
+ }, 0n)
+ .toString();
+
+ recordEvent({
+ userId: bearer.userId,
+ apiKeyId: bearer.apiKeyId ?? null,
+ agentId: row.agent_id,
+ kind: 'permissions.redeem',
+ status: 'ok',
+ meta: {
+ delegation_id: id,
+ chain_id: chainId,
+ tx_hash: txHash,
+ gas_used: receipt.gasUsed,
+ amount: redeemAmount,
+ },
+ });
+
+ const result = { ok: true, txHash, receipt };
+
+ if (idempotencyKey) {
+ idempotencySet(`${id}:${idempotencyKey}`, result);
+ }
+
+ return json(res, 200, result);
+}
+
+// ── revoke ─────────────────────────────────────────────────────────────────
+
+const revokeBodySchema = z.object({
+ id: z.string().uuid(),
+ txHash: z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 66-char 0x-prefixed hex string'),
+});
+
+const revokeIface = new Interface(DELEGATION_MANAGER_ABI);
+const DISABLED_TOPIC = revokeIface.getEvent('DelegationDisabled').topicHash;
+
+const RPC_TIMEOUT_MS = 5000;
+
+function withTimeout(promise, ms) {
+ return new Promise((resolve, reject) => {
+ const t = setTimeout(() => reject(new Error(`rpc timeout after ${ms}ms`)), ms);
+ Promise.resolve(promise).then(
+ (v) => {
+ clearTimeout(t);
+ resolve(v);
+ },
+ (e) => {
+ clearTimeout(t);
+ reject(e);
+ },
+ );
+ });
+}
+
+async function handleRevoke(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req, res);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.permissionsRevoke(user.id);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const raw = await readJson(req);
+ const parsed = revokeBodySchema.safeParse(raw);
+ if (!parsed.success) {
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
+ return error(res, 400, 'validation_error', msg);
+ }
+ const { id, txHash } = parsed.data;
+
+ // Lookup delegation + agent owner in one join
+ const [row] = await sql`
+ SELECT d.*, a.user_id AS agent_owner_user_id
+ FROM agent_delegations d
+ JOIN agent_identities a ON a.id = d.agent_id AND a.deleted_at IS NULL
+ WHERE d.id = ${id}
+ LIMIT 1
+ `;
+ if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
+
+ // Authorization: agent owner OR the delegator wallet linked to this user
+ const isAgentOwner = row.agent_owner_user_id === user.id;
+ let isDelegator = false;
+ if (!isAgentOwner) {
+ const [wallet] = await sql`
+ SELECT address FROM user_wallets
+ WHERE user_id = ${user.id} AND address = ${row.delegator_address}
+ LIMIT 1
+ `;
+ isDelegator = !!wallet;
+ }
+ if (!isAgentOwner && !isDelegator) {
+ return error(res, 403, 'forbidden', 'you are not authorized to revoke this delegation');
+ }
+
+ // Build a read-only provider for the delegation's chain
+ const chainMeta = SERVER_CHAIN_META[row.chain_id];
+ if (!chainMeta) {
+ return error(res, 400, 'chain_not_supported', `chainId ${row.chain_id} is not supported`);
+ }
+ const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[row.chain_id];
+ if (!managerAddr) {
+ return error(
+ res,
+ 400,
+ 'chain_not_supported',
+ `no DelegationManager for chainId ${row.chain_id}`,
+ );
+ }
+
+ const provider = new JsonRpcProvider(chainMeta.rpc, row.chain_id, { staticNetwork: true });
+
+ // Fetch receipt (up to 3 attempts with short back-off for propagation lag)
+ let receipt = null;
+ for (let attempt = 0; attempt < 3 && !receipt; attempt++) {
+ if (attempt > 0) await new Promise((r) => setTimeout(r, 800));
+ receipt = await withTimeout(provider.getTransactionReceipt(txHash), RPC_TIMEOUT_MS).catch(
+ () => null,
+ );
+ }
+ if (!receipt) return error(res, 400, 'tx_not_found', 'transaction receipt not found');
+
+ if (receipt.status === 0) {
+ return error(res, 400, 'tx_reverted', 'transaction was reverted on-chain');
+ }
+
+ // Decode DelegationDisabled event: (address indexed delegationManager, bytes32 indexed delegationHash)
+ // topics[0] = event sig, topics[1] = delegationManager, topics[2] = delegationHash
+ const disabledLog = receipt.logs.find((log) => log.topics[0] === DISABLED_TOPIC);
+ if (!disabledLog) {
+ return error(res, 400, 'tx_mismatch', 'transaction contains no DelegationDisabled event');
+ }
+
+ const loggedHash = disabledLog.topics[2]; // bytes32 indexed — raw topic IS the value
+ if (loggedHash.toLowerCase() !== row.delegation_hash.toLowerCase()) {
+ return error(res, 400, 'tx_mismatch', 'transaction revoked a different delegation hash');
+ }
+
+ // Second confirmation: call disabledDelegations(hash) on-chain
+ const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, provider);
+ const isDisabled = await withTimeout(
+ manager.disabledDelegations(row.delegation_hash),
+ RPC_TIMEOUT_MS,
+ ).catch(() => null);
+ if (!isDisabled) {
+ return error(
+ res,
+ 400,
+ 'not_yet_disabled',
+ 'delegation is not yet marked disabled on-chain',
+ );
+ }
+
+ // Flip status active → revoked; 0 rows = already revoked / never active
+ const updated = await sql`
+ UPDATE agent_delegations
+ SET status = 'revoked', revoked_at = NOW(), tx_hash_revoke = ${txHash}
+ WHERE id = ${id} AND status = 'active'
+ RETURNING revoked_at
+ `;
+ if (!updated || updated.length === 0) {
+ const [current] = await sql`SELECT status FROM agent_delegations WHERE id = ${id} LIMIT 1`;
+ const currentStatus = current?.status ?? 'unknown';
+ return error(
+ res,
+ 409,
+ 'already_revoked',
+ `delegation cannot be revoked (current status: ${currentStatus})`,
+ );
+ }
+
+ const revokedAt = updated[0].revoked_at;
+
+ recordEvent({ userId: user.id, agentId: row.agent_id, kind: 'permissions.revoke' });
+
+ return json(res, 200, { ok: true, status: 'revoked', revokedAt });
+}
+
+// ── verify ─────────────────────────────────────────────────────────────────
+
+const HASH_RE = /^0x[0-9a-fA-F]{64}$/;
+const CACHE_VALID = 'public, max-age=30, s-maxage=60';
+const CACHE_INVALID = 'public, max-age=300, s-maxage=600';
+
+async function handleVerify(req, res) {
+ res.setHeader('access-control-allow-origin', '*');
+ res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
+ res.setHeader('access-control-allow-headers', 'content-type');
+ res.setHeader('access-control-max-age', '86400');
+ if (req.method === 'OPTIONS') {
+ res.statusCode = 204;
+ res.end();
+ return;
+ }
+
+ if (req.method !== 'GET') {
+ res.setHeader('allow', 'GET, OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'method not allowed');
+ }
+
+ const rl = await limits.read(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const hash = url.searchParams.get('hash');
+ const chainIdRaw = url.searchParams.get('chainId');
+
+ if (!hash) return error(res, 400, 'validation_error', 'hash query param is required');
+ if (!HASH_RE.test(hash))
+ return error(res, 400, 'validation_error', 'hash must be 0x + 64 hex chars');
+ if (!chainIdRaw) return error(res, 400, 'validation_error', 'chainId query param is required');
+
+ const chainId = parseInt(chainIdRaw, 10);
+ if (Number.isNaN(chainId) || chainId <= 0)
+ return error(res, 400, 'validation_error', 'chainId must be a positive integer');
+ if (!DELEGATION_MANAGER_DEPLOYMENTS[chainId])
+ return error(res, 400, 'validation_error', `chainId ${chainId} is not supported`);
+
+ const checkedAt = new Date().toISOString();
+
+ const [row] = await sql`
+ SELECT status, expires_at
+ FROM agent_delegations
+ WHERE delegation_hash = ${hash} AND chain_id = ${chainId}
+ LIMIT 1
+ `;
+
+ if (row?.status === 'revoked') {
+ return verifyRespond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
+ }
+
+ if (row?.status === 'expired' || (row?.expires_at && new Date(row.expires_at) <= new Date())) {
+ return verifyRespond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_expired', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
+ }
+
+ // On-chain check — 5 s timeout
+ let disabled;
+ try {
+ disabled = await verifyWithTimeout(verifyCheckDisabled(hash, chainId), 5000);
+ } catch (err) {
+ console.error('[verify] rpc error', err);
+ res.statusCode = 502;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', 'no-store');
+ res.end(JSON.stringify({ ok: false, error: 'rpc_error', message: err.message }));
+ return;
+ }
+
+ if (disabled) {
+ // Self-heal: if DB still tracks it as active, flip to revoked without blocking the response.
+ if (row?.status === 'active') {
+ console.log(`[verify] self-heal queued for ${hash}`);
+ queueMicrotask(() => {
+ sql`
+ UPDATE agent_delegations
+ SET status = 'revoked', revoked_at = NOW()
+ WHERE delegation_hash = ${hash} AND status = 'active'
+ `.catch((e) => console.error('[verify] self-heal failed', e));
+ });
+ }
+ return verifyRespond(
+ res,
+ { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
+ CACHE_INVALID,
+ );
+ }
+
+ const body = { ok: true, valid: true, checkedAt, chainId, hash };
+ if (!row) body.reason = 'unknown_to_platform';
+ return verifyRespond(res, body, CACHE_VALID);
+}
+
+async function verifyCheckDisabled(hash, chainId) {
+ const rpcUrl = process.env[`RPC_URL_${chainId}`];
+ if (!rpcUrl) throw new Error(`no RPC configured for chainId ${chainId}`);
+ const provider = new JsonRpcProvider(rpcUrl);
+ const manager = new Contract(
+ DELEGATION_MANAGER_DEPLOYMENTS[chainId],
+ DELEGATION_MANAGER_ABI,
+ provider,
+ );
+ return manager.isDelegationDisabled(hash);
+}
+
+function verifyWithTimeout(promise, ms) {
+ return Promise.race([
+ promise,
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`RPC timeout after ${ms}ms`)), ms),
+ ),
+ ]);
+}
+
+function verifyRespond(res, body, cacheControl) {
+ const str = JSON.stringify(body);
+ const etag = `"${createHash('sha256').update(str).digest('hex').slice(0, 16)}"`;
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json; charset=utf-8');
+ res.setHeader('cache-control', cacheControl);
+ res.setHeader('etag', etag);
+ res.end(str);
+}
diff --git a/api/permissions/grant.js b/api/permissions/grant.js
deleted file mode 100644
index db066878e..000000000
--- a/api/permissions/grant.js
+++ /dev/null
@@ -1,261 +0,0 @@
-// POST /api/permissions/grant
-// Accepts a signed ERC-7710 delegation, verifies it, and persists it.
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits } from '../_lib/rate-limit.js';
-import { recordEvent } from '../_lib/usage.js';
-import { SERVER_CHAIN_META } from '../_lib/onchain.js';
-import { z } from 'zod';
-import { ethers } from 'ethers';
-import {
- DELEGATION_MANAGER_DEPLOYMENTS,
- EIP712_DOMAIN,
- DELEGATION_TYPES,
-} from '../../src/erc7710/abi.js';
-import { isDelegationValid, PermissionError } from '../../src/permissions/toolkit.js';
-
-const ROOT_AUTHORITY = '0x0000000000000000000000000000000000000000000000000000000000000000';
-
-const hexAddr = z.string().regex(/^0x[0-9a-fA-F]{40}$/, 'must be a 20-byte hex address');
-const hexBytes = z.string().regex(/^0x([0-9a-fA-F]{2})*$/, 'must be 0x-prefixed hex bytes');
-const hexBytes32 = z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 32-byte hex value');
-
-const caveatSchema = z.object({
- enforcer: hexAddr,
- terms: hexBytes.default('0x'),
- args: hexBytes.default('0x'),
-});
-
-const delegationSchema = z.object({
- delegator: hexAddr,
- delegate: hexAddr,
- authority: hexBytes32.optional(),
- caveats: z.array(caveatSchema).default([]),
- salt: z.union([
- z
- .string()
- .regex(/^(0x[0-9a-fA-F]+|\d+)$/, 'salt must be a decimal or 0x-prefixed hex integer'),
- z.number().int().nonnegative(),
- ]),
- signature: hexBytes,
- hash: hexBytes32,
-});
-
-const scopeSchema = z.object({
- token: z.string().min(1),
- maxAmount: z.string().min(1),
- period: z.enum(['daily', 'weekly', 'once']),
- targets: z.array(hexAddr).min(1),
- expiry: z.number().int().positive(),
-});
-
-const bodySchema = z.object({
- agentId: z.string().uuid(),
- chainId: z.number().int().positive(),
- delegation: delegationSchema,
- scope: scopeSchema,
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.permissionsGrant(user.id);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const raw = await readJson(req);
- const parsed = bodySchema.safeParse(raw);
- if (!parsed.success) {
- const msg = parsed.error.issues
- .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
- .join('; ');
- return error(res, 400, 'validation_error', msg);
- }
- const { agentId, chainId, delegation, scope } = parsed.data;
-
- // chainId must be a supported DelegationManager deployment
- if (!(chainId in DELEGATION_MANAGER_DEPLOYMENTS)) {
- return error(res, 400, 'chain_not_supported', `chainId ${chainId} is not supported`);
- }
-
- // Owner gate: agent must exist and belong to the authenticated user
- const [agent] = await sql`
- select id, user_id from agent_identities
- where id = ${agentId} and deleted_at is null
- limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== user.id) return error(res, 403, 'not_owner', 'you do not own this agent');
-
- // Wallet linkage: delegation.delegator must be a wallet linked to the authenticated user
- const delegatorLower = delegation.delegator.toLowerCase();
- const [linkedWallet] = await sql`
- select address from user_wallets
- where user_id = ${user.id} and address = ${delegatorLower}
- limit 1
- `;
- if (!linkedWallet) {
- return error(
- res,
- 409,
- 'wallet_not_linked',
- 'delegation.delegator is not linked to your account',
- );
- }
-
- // Signature verification — two steps:
- // 1. Re-derive the EIP-712 hash from delegation fields and compare with delegation.hash
- // (prevents chain-hop replay: different contract address → different hash).
- // 2. Recover the signer from the signature and verify it matches delegation.delegator.
- const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[chainId];
- const eip712Domain = EIP712_DOMAIN({ chainId, verifyingContract: managerAddr });
- let derivedHash;
- try {
- const structValue = {
- delegate: delegation.delegate,
- delegator: delegation.delegator,
- authority: delegation.authority || ROOT_AUTHORITY,
- caveats: delegation.caveats.map((c) => ({
- enforcer: c.enforcer,
- terms: c.terms,
- args: c.args,
- })),
- salt: BigInt(delegation.salt),
- };
-
- derivedHash = ethers.TypedDataEncoder.hash(eip712Domain, DELEGATION_TYPES, structValue);
-
- if (derivedHash.toLowerCase() !== delegation.hash.toLowerCase()) {
- return error(
- res,
- 400,
- 'hash_mismatch',
- 'delegation.hash does not match the delegation fields',
- );
- }
-
- const recovered = ethers.verifyTypedData(
- eip712Domain,
- DELEGATION_TYPES,
- structValue,
- delegation.signature,
- );
- if (recovered.toLowerCase() !== delegatorLower) {
- return error(
- res,
- 400,
- 'signature_invalid',
- 'signature does not match delegation.delegator',
- );
- }
- } catch (err) {
- if (err instanceof PermissionError) {
- return error(res, 400, err.code || 'signature_invalid', err.message);
- }
- return error(res, 400, 'signature_invalid', err.message || 'invalid delegation signature');
- }
-
- // On-chain revocation check (isDelegationValid from task 04)
- const rpcUrl = SERVER_CHAIN_META[chainId]?.rpc;
- const validity = await isDelegationValid({ hash: delegation.hash, chainId, rpcUrl }).catch(
- (err) => {
- if (err instanceof PermissionError) return { valid: false, reason: err.code };
- console.warn('[grant] isDelegationValid error', err?.message);
- return { valid: true }; // RPC unavailable; proceed and rely on indexer for revocation
- },
- );
- if (!validity.valid) {
- return error(
- res,
- 400,
- validity.reason || 'signature_invalid',
- 'delegation is not valid on-chain',
- );
- }
-
- // Scope sanity checks
- const nowSec = Math.floor(Date.now() / 1000);
- if (scope.expiry <= nowSec + 60) {
- return error(
- res,
- 400,
- 'validation_error',
- 'scope.expiry must be at least 60 seconds in the future',
- );
- }
- if (scope.expiry > nowSec + 365 * 24 * 3600) {
- return error(res, 400, 'validation_error', 'scope.expiry must be within 365 days');
- }
- let maxAmountBig;
- try {
- maxAmountBig = BigInt(scope.maxAmount);
- } catch {
- return error(res, 400, 'validation_error', 'scope.maxAmount must be a numeric string');
- }
- if (maxAmountBig <= 0n) {
- return error(res, 400, 'validation_error', 'scope.maxAmount must be positive');
- }
- let targets;
- try {
- targets = scope.targets.map((t) => ethers.getAddress(t));
- } catch {
- return error(res, 400, 'validation_error', 'scope.targets contains an invalid address');
- }
-
- const delegationHash = derivedHash;
- const expiresAt = new Date(scope.expiry * 1000).toISOString();
- const delegatorAddr = ethers.getAddress(delegation.delegator);
- const delegateAddr = ethers.getAddress(delegation.delegate);
-
- const delegationJson = {
- delegator: delegation.delegator,
- delegate: delegation.delegate,
- authority: delegation.authority || ROOT_AUTHORITY,
- caveats: delegation.caveats,
- salt: String(delegation.salt),
- // signature stored as part of the envelope; not logged separately
- signature: delegation.signature,
- hash: delegationHash,
- };
- const scopeJson = { ...scope, targets };
-
- // Persist — delegation_hash is UNIQUE; on conflict return 409
- const rows = await sql`
- insert into agent_delegations (
- agent_id, chain_id, delegator_address, delegate_address,
- delegation_hash, delegation_json, scope, expires_at
- )
- values (
- ${agentId},
- ${chainId},
- ${delegatorAddr.toLowerCase()},
- ${delegateAddr.toLowerCase()},
- ${delegationHash},
- ${JSON.stringify(delegationJson)}::jsonb,
- ${JSON.stringify(scopeJson)}::jsonb,
- ${expiresAt}
- )
- on conflict (delegation_hash) do nothing
- returning id
- `;
-
- if (!rows || rows.length === 0) {
- const [existing] = await sql`
- select id from agent_delegations where delegation_hash = ${delegationHash} limit 1
- `;
- return error(res, 409, 'duplicate_delegation', 'this delegation has already been granted', {
- id: existing?.id,
- });
- }
-
- const { id } = rows[0];
-
- recordEvent({ userId: user.id, agentId, kind: 'permissions.grant' });
-
- return json(res, 200, { ok: true, id, delegationHash, expiresAt });
-});
diff --git a/api/permissions/list.js b/api/permissions/list.js
deleted file mode 100644
index 90b524fe1..000000000
--- a/api/permissions/list.js
+++ /dev/null
@@ -1,141 +0,0 @@
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, error, wrap } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-
-const PUBLIC_CACHE = 'public, max-age=30, s-maxage=60';
-
-const VALID_STATUSES = new Set(['active', 'revoked', 'expired', 'all']);
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
-
- if (req.method !== 'GET') {
- res.setHeader('allow', 'GET, OPTIONS');
- return error(res, 405, 'method_not_allowed', 'method not allowed');
- }
-
- const rl = await limits.read(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const agentId = url.searchParams.get('agentId') || null;
- const delegator = url.searchParams.get('delegator') || null;
-
- if (!agentId && !delegator) {
- return error(res, 400, 'missing_filter', 'agentId or delegator query param is required');
- }
-
- const statusParam = url.searchParams.get('status') || 'active';
- if (!VALID_STATUSES.has(statusParam)) {
- return error(
- res,
- 400,
- 'validation_error',
- 'status must be active, revoked, expired, or all',
- );
- }
-
- const chainIdParam = url.searchParams.get('chainId');
- const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
- if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
- return error(res, 400, 'validation_error', 'chainId must be a positive integer');
- }
-
- const limitParam = Math.min(
- 200,
- Math.max(1, parseInt(url.searchParams.get('limit') || '50', 10)),
- );
- const offset = Math.max(0, parseInt(url.searchParams.get('offset') || '0', 10));
-
- // agentId-only path: public, no auth required
- if (agentId && !delegator) {
- const rows = await sql`
- SELECT
- id, chain_id, delegator_address, delegate_address, delegation_hash,
- scope, status, expires_at, created_at, last_redeemed_at, redemption_count
- FROM agent_delegations
- WHERE agent_id = ${agentId}
- AND (${statusParam} = 'all' OR status = ${statusParam})
- AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
- ORDER BY created_at DESC
- LIMIT ${limitParam} OFFSET ${offset}
- `;
-
- const delegations = rows.map(toPublicShape);
- const body = { ok: true, delegations };
- if (rows.length === limitParam) body.nextOffset = offset + limitParam;
-
- return json(res, 200, body, { 'cache-control': PUBLIC_CACHE });
- }
-
- // delegator path (or both provided): session required
- const session = await getSessionUser(req, res);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) {
- return error(res, 401, 'unauthorized', 'sign in required to list delegations by delegator');
- }
- const userId = session?.id ?? bearer?.userId;
-
- // Verify the session user owns this delegator address
- const targetDelegator = delegator || null;
- if (targetDelegator) {
- const [wallet] = await sql`
- SELECT 1 FROM user_wallets
- WHERE user_id = ${userId}
- AND lower(address) = lower(${targetDelegator})
- LIMIT 1
- `;
- if (!wallet) {
- return error(
- res,
- 403,
- 'forbidden',
- 'delegator address does not belong to your account',
- );
- }
- }
-
- const whereAgentId = agentId;
- const rows = await sql`
- SELECT
- id, chain_id, delegator_address, delegate_address, delegation_hash,
- delegation_json, scope, status, expires_at, created_at, last_redeemed_at, redemption_count
- FROM agent_delegations
- WHERE (${whereAgentId}::uuid IS NULL OR agent_id = ${whereAgentId}::uuid)
- AND (${targetDelegator}::text IS NULL OR lower(delegator_address) = lower(${targetDelegator}::text))
- AND (${statusParam} = 'all' OR status = ${statusParam})
- AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
- ORDER BY created_at DESC
- LIMIT ${limitParam} OFFSET ${offset}
- `;
-
- const delegations = rows.map(toAuthShape);
- const body = { ok: true, delegations };
- if (rows.length === limitParam) body.nextOffset = offset + limitParam;
-
- return json(res, 200, body);
-});
-
-function toPublicShape(row) {
- return {
- id: row.id,
- chainId: row.chain_id,
- delegator: row.delegator_address,
- delegate: row.delegate_address,
- delegationHash: row.delegation_hash,
- scope: row.scope,
- status: row.status,
- expiresAt: row.expires_at,
- createdAt: row.created_at,
- lastRedeemedAt: row.last_redeemed_at,
- redemptionCount: row.redemption_count,
- };
-}
-
-function toAuthShape(row) {
- return {
- ...toPublicShape(row),
- delegationJson: row.delegation_json,
- };
-}
diff --git a/api/permissions/metadata.js b/api/permissions/metadata.js
deleted file mode 100644
index 75e259b70..000000000
--- a/api/permissions/metadata.js
+++ /dev/null
@@ -1,122 +0,0 @@
-import { createHash } from 'node:crypto';
-import { sql } from '../_lib/db.js';
-import { json, error, wrap } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-
-// Populated by task 03 (src/erc7710/abi.js). Until that ships, unknown chains get null.
-let DELEGATION_MANAGER_DEPLOYMENTS = {};
-try {
- const mod = await import('../../src/erc7710/abi.js');
- DELEGATION_MANAGER_DEPLOYMENTS = mod.DELEGATION_MANAGER_DEPLOYMENTS ?? {};
-} catch {
- // abi.js not yet present — delegationManager will be null
-}
-
-function corsHeaders(res) {
- res.setHeader('access-control-allow-origin', '*');
- res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
- res.setHeader('access-control-allow-headers', 'content-type');
- res.setHeader('access-control-max-age', '86400');
-}
-
-export default wrap(async (req, res) => {
- if (req.method === 'OPTIONS') {
- corsHeaders(res);
- res.statusCode = 204;
- res.end();
- return;
- }
-
- corsHeaders(res);
-
- if (req.method !== 'GET') {
- res.setHeader('allow', 'GET, OPTIONS');
- return error(res, 405, 'method_not_allowed', 'method not allowed');
- }
-
- const rl = await limits.read(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const agentId = url.searchParams.get('agentId');
- if (!agentId) return error(res, 400, 'missing_param', 'agentId is required');
-
- const chainIdParam = url.searchParams.get('chainId');
- const chainId = chainIdParam ? parseInt(chainIdParam, 10) : null;
- if (chainIdParam && (Number.isNaN(chainId) || chainId <= 0)) {
- return error(res, 400, 'validation_error', 'chainId must be a positive integer');
- }
-
- // Verify agent exists
- const [agent] = await sql`
- SELECT id FROM agent_identities
- WHERE id = ${agentId} AND deleted_at IS NULL
- LIMIT 1
- `;
- if (!agent) {
- return json(res, 404, { ok: false, error: 'agent_not_found' });
- }
-
- const rows = await sql`
- SELECT
- chain_id, delegator_address, delegate_address, delegation_hash,
- delegation_json, scope, expires_at, created_at, revoked_at
- FROM agent_delegations
- WHERE agent_id = ${agentId}
- AND status = 'active'
- AND (${chainId}::integer IS NULL OR chain_id = ${chainId}::integer)
- ORDER BY expires_at DESC
- `;
-
- const delegations = rows.map((r) => ({
- chainId: r.chain_id,
- delegator: r.delegator_address,
- delegate: r.delegate_address,
- hash: r.delegation_hash,
- scope: r.scope,
- expiresAt: r.expires_at,
- createdAt: r.created_at,
- envelope: r.delegation_json,
- }));
-
- // delegationManager: use the filtered chain if provided, otherwise first delegation's chain
- const resolveChain = chainId ?? rows[0]?.chain_id ?? null;
- const delegationManager = resolveChain
- ? (DELEGATION_MANAGER_DEPLOYMENTS[resolveChain] ?? null)
- : null;
-
- // Last-Modified: max of created_at and revoked_at across returned rows
- let lastModified = null;
- for (const r of rows) {
- const candidates = [r.created_at, r.revoked_at].filter(Boolean);
- for (const d of candidates) {
- if (!lastModified || d > lastModified) lastModified = d;
- }
- }
-
- const body = {
- ok: true,
- agentId,
- spec: 'erc-7715/0.1',
- delegationManager,
- delegations,
- };
-
- const bodyStr = JSON.stringify(body);
- const etag = `"${createHash('sha256').update(bodyStr).digest('hex').slice(0, 32)}"`;
-
- res.setHeader('cache-control', 'public, max-age=60, s-maxage=300, stale-while-revalidate=600');
- res.setHeader('etag', etag);
- if (lastModified) res.setHeader('last-modified', new Date(lastModified).toUTCString());
-
- // ETag short-circuit
- if (req.headers['if-none-match'] === etag) {
- res.statusCode = 304;
- res.end();
- return;
- }
-
- res.statusCode = 200;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.end(bodyStr);
-});
diff --git a/api/permissions/redeem.js b/api/permissions/redeem.js
deleted file mode 100644
index 86ca737e8..000000000
--- a/api/permissions/redeem.js
+++ /dev/null
@@ -1,368 +0,0 @@
-// POST /api/permissions/redeem
-// Server-side delegation relayer: pays gas on behalf of the agent's smart account.
-// Auth: agent bearer token with scope `permissions:redeem`.
-// Feature-flagged via PERMISSIONS_RELAYER_ENABLED env var (default: false).
-
-import { Wallet, JsonRpcProvider, getAddress, isAddress } from 'ethers';
-import { z } from 'zod';
-
-import { sql } from '../_lib/db.js';
-import { authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
-import { cors, json, error, wrap, readJson, method } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { env } from '../_lib/env.js';
-import { recordEvent } from '../_lib/usage.js';
-import { redeemDelegation, PermissionError } from '../../src/permissions/toolkit.js';
-
-// ── Idempotency cache (in-memory, 10-minute TTL) ───────────────────────────
-const idempotencyCache = new Map();
-const IDEMPOTENCY_TTL_MS = 10 * 60 * 1000;
-
-function idempotencyGet(key) {
- const entry = idempotencyCache.get(key);
- if (!entry) return null;
- if (Date.now() > entry.expiresAt) {
- idempotencyCache.delete(key);
- return null;
- }
- return entry.result;
-}
-
-function idempotencySet(key, result) {
- // Purge expired entries opportunistically.
- const now = Date.now();
- for (const [k, v] of idempotencyCache) {
- if (now > v.expiresAt) idempotencyCache.delete(k);
- }
- idempotencyCache.set(key, { result, expiresAt: now + IDEMPOTENCY_TTL_MS });
-}
-
-// ── Validation schemas ─────────────────────────────────────────────────────
-const hexData = z.string().regex(/^0x[0-9a-fA-F]*$/, 'must be 0x-prefixed hex');
-const weiValue = z.string().regex(/^\d+$/, 'value must be a decimal integer string');
-
-const callSchema = z.object({
- to: z.string().refine((v) => isAddress(v), 'to must be a valid EIP-55 address'),
- value: weiValue.default('0'),
- data: hexData.default('0x'),
-});
-
-const bodySchema = z.object({
- id: z.string().uuid(),
- calls: z.array(callSchema).min(1).max(4),
-});
-
-// ── ERC-20 selector helpers ────────────────────────────────────────────────
-const TRANSFER_SELECTOR = '0xa9059cbb';
-const TRANSFER_FROM_SELECTOR = '0x23b872dd';
-
-// Decode token amount from ERC-20 transfer/transferFrom calldata.
-// Param slots (0-indexed) start at hex[8 + n*64]. Returns null if unrecognised.
-function decodeErc20AmountFixed(data) {
- if (!data || data.length < 10) return null;
- const hex = data.startsWith('0x') ? data.slice(2) : data;
- const sel = '0x' + hex.slice(0, 8).toLowerCase();
- try {
- if (sel === TRANSFER_SELECTOR && hex.length >= 8 + 64 + 64) {
- // slot 1 (0-indexed) = amount
- return BigInt('0x' + hex.slice(8 + 64, 8 + 64 + 64));
- }
- if (sel === TRANSFER_FROM_SELECTOR && hex.length >= 8 + 64 + 64 + 64) {
- // slot 2 (0-indexed) = amount
- return BigInt('0x' + hex.slice(8 + 64 + 64, 8 + 64 + 64 + 64));
- }
- } catch {
- return null;
- }
- return null;
-}
-
-// ── Period window helper ───────────────────────────────────────────────────
-function periodStart(period) {
- const now = new Date();
- if (period === 'daily') {
- return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
- }
- if (period === 'weekly') {
- const day = now.getUTCDay(); // 0=Sun
- const diff = day === 0 ? -6 : 1 - day; // back to Monday
- const monday = new Date(now);
- monday.setUTCDate(now.getUTCDate() + diff);
- monday.setUTCHours(0, 0, 0, 0);
- return monday;
- }
- // 'once' or unknown: entire history counts
- return new Date(0);
-}
-
-// ── RPC URL resolution ─────────────────────────────────────────────────────
-function getRpcUrl(chainId) {
- return (
- process.env[`RPC_URL_${chainId}`] ||
- // Shared fallback names that might already exist in the project
- (chainId === 84532 ? process.env.BASE_SEPOLIA_RPC_URL : null) ||
- (chainId === 11155111 ? process.env.SEPOLIA_RPC_URL : null) ||
- null
- );
-}
-
-// ── Handler ────────────────────────────────────────────────────────────────
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
- if (!method(req, res, ['POST'])) return;
-
- // Feature flag — 503 when disabled
- if (!env.PERMISSIONS_RELAYER_ENABLED) {
- return error(res, 503, 'feature_disabled', 'relayer not enabled on this deployment');
- }
-
- // Rate limit — strict bucket since each request costs gas
- const ip = clientIp(req);
- const rl = await limits.strict(ip);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- // Auth — agent bearer only (no user sessions on this machine endpoint)
- const token = extractBearer(req);
- const bearer = await authenticateBearer(token);
- if (!bearer) return error(res, 401, 'unauthorized', 'valid bearer token required');
- if (!hasScope(bearer.scope, 'permissions:redeem')) {
- return error(
- res,
- 403,
- 'insufficient_scope',
- "token must include 'permissions:redeem' scope",
- );
- }
-
- // Idempotency-Key check (before parsing body — key is in header)
- const idempotencyKey = req.headers['idempotency-key'] || null;
-
- // Parse body
- let body;
- try {
- body = parse(bodySchema, await readJson(req));
- } catch (err) {
- return error(res, err.status || 400, err.code || 'validation_error', err.message);
- }
- const { id, calls } = body;
-
- // Idempotency-Key early return
- if (idempotencyKey) {
- const cached = idempotencyGet(`${id}:${idempotencyKey}`);
- if (cached) return json(res, 200, cached);
- }
-
- // Load delegation row
- const [row] = await sql`
- SELECT id, agent_id, chain_id, delegation_hash, delegation_json, scope,
- status, expires_at, redemption_count, last_redeemed_at
- FROM agent_delegations
- WHERE id = ${id}
- LIMIT 1
- `;
- if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
-
- // Check status
- if (row.status === 'revoked') {
- return error(res, 409, 'delegation_revoked', 'delegation has been revoked');
- }
-
- // Check expiry; auto-flip status if expired
- const now = new Date();
- if (new Date(row.expires_at) <= now) {
- // Side-effect: mark as expired without blocking
- sql`UPDATE agent_delegations SET status = 'expired' WHERE id = ${id}`.catch(() => {});
- return error(res, 409, 'delegation_expired', 'delegation has expired');
- }
-
- if (row.status !== 'active') {
- return error(res, 409, 'delegation_expired', `delegation status is '${row.status}'`);
- }
-
- const scope = row.scope;
- const chainId = row.chain_id;
-
- // ── Server-side scope checks (cheap, prevent paying gas on doomed tx) ────
-
- // 1. Target allow-list
- const allowedTargets = new Set((scope.targets || []).map((t) => t.toLowerCase()));
- for (const call of calls) {
- if (!allowedTargets.has(call.to.toLowerCase())) {
- return error(
- res,
- 403,
- 'target_not_allowed',
- `call target ${call.to} is not in scope.targets`,
- );
- }
- }
-
- // 2. Native ETH: reject non-zero value if token is ERC-20
- const isNative = scope.token === 'native';
- if (!isNative) {
- for (const call of calls) {
- if (BigInt(call.value) > 0n) {
- return error(
- res,
- 403,
- 'scope_exceeded',
- 'non-zero ETH value not allowed for ERC-20 scoped delegation',
- );
- }
- }
- }
-
- // 3. Amount cap: compute period spend from usage_events history
- const maxAmount = BigInt(scope.maxAmount || '0');
- const pStart = periodStart(scope.period || 'daily');
-
- if (isNative) {
- // Sum ETH values in this request
- const requestAmount = calls.reduce((s, c) => s + BigInt(c.value), 0n);
-
- // Query period history
- const [histRow] = await sql`
- SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
- FROM usage_events
- WHERE kind = 'permissions.redeem'
- AND meta->>'delegation_id' = ${id}
- AND created_at >= ${pStart.toISOString()}
- `;
- const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
-
- if (requestAmount + historicalSpend > maxAmount) {
- return error(
- res,
- 403,
- 'scope_exceeded',
- 'ETH spend would exceed scope.maxAmount for this period',
- {
- maxAmount: scope.maxAmount,
- periodSpent: historicalSpend.toString(),
- requested: requestAmount.toString(),
- },
- );
- }
- } else {
- // ERC-20: decode transfer amounts from call data
- let requestAmount = 0n;
- for (const call of calls) {
- const decoded = decodeErc20AmountFixed(call.data);
- if (decoded === null) {
- return error(
- res,
- 403,
- 'scope_exceeded',
- `call to ${call.to} does not look like an ERC-20 transfer or transferFrom`,
- );
- }
- requestAmount += decoded;
- }
-
- const [histRow] = await sql`
- SELECT COALESCE(SUM((meta->>'amount')::numeric), 0) AS spent
- FROM usage_events
- WHERE kind = 'permissions.redeem'
- AND meta->>'delegation_id' = ${id}
- AND created_at >= ${pStart.toISOString()}
- `;
- const historicalSpend = BigInt(Math.floor(Number(histRow?.spent ?? '0')));
-
- if (requestAmount + historicalSpend > maxAmount) {
- return error(
- res,
- 403,
- 'scope_exceeded',
- 'token spend would exceed scope.maxAmount for this period',
- {
- maxAmount: scope.maxAmount,
- periodSpent: historicalSpend.toString(),
- requested: requestAmount.toString(),
- },
- );
- }
- }
-
- // ── Build signer ───────────────────────────────────────────────────────
- const rpcUrl = getRpcUrl(chainId);
- if (!rpcUrl) {
- return error(
- res,
- 502,
- 'rpc_error',
- `no RPC URL configured for chain ${chainId} (set RPC_URL_${chainId})`,
- );
- }
-
- let signer;
- try {
- const provider = new JsonRpcProvider(rpcUrl);
- // AGENT_RELAYER_KEY is never logged — only use it to construct the Wallet
- signer = new Wallet(env.AGENT_RELAYER_KEY, provider);
- } catch {
- return error(res, 500, 'internal_error', 'failed to initialise relayer signer');
- }
-
- // ── Submit on-chain ────────────────────────────────────────────────────
- let txHash, receipt;
- try {
- ({ txHash, receipt } = await redeemDelegation({
- delegation: row.delegation_json,
- delegationHash: row.delegation_hash,
- calls,
- signer,
- chainId,
- }));
- } catch (err) {
- if (err instanceof PermissionError && err.code === 'delegation_revoked') {
- // Auto-sync status in DB
- sql`UPDATE agent_delegations SET status = 'revoked' WHERE id = ${id}`.catch(() => {});
- return error(res, 409, 'delegation_revoked', err.message);
- }
- // RPC or provider error
- console.error('[permissions/redeem] on-chain error', err?.code, err?.message);
- return error(res, 502, 'rpc_error', err?.message || 'on-chain call failed');
- }
-
- // ── Update DB ──────────────────────────────────────────────────────────
- await sql`
- UPDATE agent_delegations
- SET redemption_count = redemption_count + 1,
- last_redeemed_at = NOW()
- WHERE id = ${id}
- `;
-
- // Compute amount redeemed for usage tracking
- const redeemAmount = isNative
- ? calls.reduce((s, c) => s + BigInt(c.value), 0n).toString()
- : calls
- .reduce((s, c) => {
- const a = decodeErc20AmountFixed(c.data);
- return s + (a ?? 0n);
- }, 0n)
- .toString();
-
- recordEvent({
- userId: bearer.userId,
- apiKeyId: bearer.apiKeyId ?? null,
- agentId: row.agent_id,
- kind: 'permissions.redeem',
- status: 'ok',
- meta: {
- delegation_id: id,
- chain_id: chainId,
- tx_hash: txHash,
- gas_used: receipt.gasUsed,
- amount: redeemAmount,
- },
- });
-
- const result = { ok: true, txHash, receipt };
-
- if (idempotencyKey) {
- idempotencySet(`${id}:${idempotencyKey}`, result);
- }
-
- return json(res, 200, result);
-});
diff --git a/api/permissions/revoke.js b/api/permissions/revoke.js
deleted file mode 100644
index 9d9bb1681..000000000
--- a/api/permissions/revoke.js
+++ /dev/null
@@ -1,166 +0,0 @@
-// POST /api/permissions/revoke
-// Mirrors an on-chain DelegationManager.disableDelegation() call into the DB.
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, method, readJson, wrap, error, json } from '../_lib/http.js';
-import { limits } from '../_lib/rate-limit.js';
-import { recordEvent } from '../_lib/usage.js';
-import { SERVER_CHAIN_META } from '../_lib/onchain.js';
-import { DELEGATION_MANAGER_ABI, DELEGATION_MANAGER_DEPLOYMENTS } from '../../src/erc7710/abi.js';
-import { z } from 'zod';
-import { JsonRpcProvider, Contract, Interface } from 'ethers';
-
-const bodySchema = z.object({
- id: z.string().uuid(),
- txHash: z.string().regex(/^0x[0-9a-fA-F]{64}$/, 'must be a 66-char 0x-prefixed hex string'),
-});
-
-const iface = new Interface(DELEGATION_MANAGER_ABI);
-const DISABLED_TOPIC = iface.getEvent('DelegationDisabled').topicHash;
-
-const RPC_TIMEOUT_MS = 5000;
-
-function withTimeout(promise, ms) {
- return new Promise((resolve, reject) => {
- const t = setTimeout(() => reject(new Error(`rpc timeout after ${ms}ms`)), ms);
- Promise.resolve(promise).then(
- (v) => {
- clearTimeout(t);
- resolve(v);
- },
- (e) => {
- clearTimeout(t);
- reject(e);
- },
- );
- });
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req, res);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.permissionsRevoke(user.id);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const raw = await readJson(req);
- const parsed = bodySchema.safeParse(raw);
- if (!parsed.success) {
- const msg = parsed.error.issues
- .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
- .join('; ');
- return error(res, 400, 'validation_error', msg);
- }
- const { id, txHash } = parsed.data;
-
- // Lookup delegation + agent owner in one join
- const [row] = await sql`
- SELECT d.*, a.user_id AS agent_owner_user_id
- FROM agent_delegations d
- JOIN agent_identities a ON a.id = d.agent_id AND a.deleted_at IS NULL
- WHERE d.id = ${id}
- LIMIT 1
- `;
- if (!row) return error(res, 404, 'delegation_not_found', 'delegation not found');
-
- // Authorization: agent owner OR the delegator wallet linked to this user
- const isAgentOwner = row.agent_owner_user_id === user.id;
- let isDelegator = false;
- if (!isAgentOwner) {
- const [wallet] = await sql`
- SELECT address FROM user_wallets
- WHERE user_id = ${user.id} AND address = ${row.delegator_address}
- LIMIT 1
- `;
- isDelegator = !!wallet;
- }
- if (!isAgentOwner && !isDelegator) {
- return error(res, 403, 'forbidden', 'you are not authorized to revoke this delegation');
- }
-
- // Build a read-only provider for the delegation's chain
- const chainMeta = SERVER_CHAIN_META[row.chain_id];
- if (!chainMeta) {
- return error(res, 400, 'chain_not_supported', `chainId ${row.chain_id} is not supported`);
- }
- const managerAddr = DELEGATION_MANAGER_DEPLOYMENTS[row.chain_id];
- if (!managerAddr) {
- return error(
- res,
- 400,
- 'chain_not_supported',
- `no DelegationManager for chainId ${row.chain_id}`,
- );
- }
-
- const provider = new JsonRpcProvider(chainMeta.rpc, row.chain_id, { staticNetwork: true });
-
- // Fetch receipt (up to 3 attempts with short back-off for propagation lag)
- let receipt = null;
- for (let attempt = 0; attempt < 3 && !receipt; attempt++) {
- if (attempt > 0) await new Promise((r) => setTimeout(r, 800));
- receipt = await withTimeout(provider.getTransactionReceipt(txHash), RPC_TIMEOUT_MS).catch(
- () => null,
- );
- }
- if (!receipt) return error(res, 400, 'tx_not_found', 'transaction receipt not found');
-
- if (receipt.status === 0) {
- return error(res, 400, 'tx_reverted', 'transaction was reverted on-chain');
- }
-
- // Decode DelegationDisabled event: (address indexed delegationManager, bytes32 indexed delegationHash)
- // topics[0] = event sig, topics[1] = delegationManager, topics[2] = delegationHash
- const disabledLog = receipt.logs.find((log) => log.topics[0] === DISABLED_TOPIC);
- if (!disabledLog) {
- return error(res, 400, 'tx_mismatch', 'transaction contains no DelegationDisabled event');
- }
-
- const loggedHash = disabledLog.topics[2]; // bytes32 indexed — raw topic IS the value
- if (loggedHash.toLowerCase() !== row.delegation_hash.toLowerCase()) {
- return error(res, 400, 'tx_mismatch', 'transaction revoked a different delegation hash');
- }
-
- // Second confirmation: call disabledDelegations(hash) on-chain
- const manager = new Contract(managerAddr, DELEGATION_MANAGER_ABI, provider);
- const isDisabled = await withTimeout(
- manager.disabledDelegations(row.delegation_hash),
- RPC_TIMEOUT_MS,
- ).catch(() => null);
- if (!isDisabled) {
- return error(
- res,
- 400,
- 'not_yet_disabled',
- 'delegation is not yet marked disabled on-chain',
- );
- }
-
- // Flip status active → revoked; 0 rows = already revoked / never active
- const updated = await sql`
- UPDATE agent_delegations
- SET status = 'revoked', revoked_at = NOW(), tx_hash_revoke = ${txHash}
- WHERE id = ${id} AND status = 'active'
- RETURNING revoked_at
- `;
- if (!updated || updated.length === 0) {
- const [current] = await sql`SELECT status FROM agent_delegations WHERE id = ${id} LIMIT 1`;
- const currentStatus = current?.status ?? 'unknown';
- return error(
- res,
- 409,
- 'already_revoked',
- `delegation cannot be revoked (current status: ${currentStatus})`,
- );
- }
-
- const revokedAt = updated[0].revoked_at;
-
- recordEvent({ userId: user.id, agentId: row.agent_id, kind: 'permissions.revoke' });
-
- return json(res, 200, { ok: true, status: 'revoked', revokedAt });
-});
diff --git a/api/permissions/verify.js b/api/permissions/verify.js
deleted file mode 100644
index 5770b3538..000000000
--- a/api/permissions/verify.js
+++ /dev/null
@@ -1,137 +0,0 @@
-import { createHash } from 'node:crypto';
-import { Contract, JsonRpcProvider } from 'ethers';
-import { sql } from '../_lib/db.js';
-import { error, wrap } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { DELEGATION_MANAGER_DEPLOYMENTS, DELEGATION_MANAGER_ABI } from '../../src/erc7710/abi.js';
-
-const HASH_RE = /^0x[0-9a-fA-F]{64}$/;
-const CACHE_VALID = 'public, max-age=30, s-maxage=60';
-const CACHE_INVALID = 'public, max-age=300, s-maxage=600';
-
-export default wrap(async (req, res) => {
- res.setHeader('access-control-allow-origin', '*');
- res.setHeader('access-control-allow-methods', 'GET, OPTIONS');
- res.setHeader('access-control-allow-headers', 'content-type');
- res.setHeader('access-control-max-age', '86400');
- if (req.method === 'OPTIONS') {
- res.statusCode = 204;
- res.end();
- return;
- }
-
- if (req.method !== 'GET') {
- res.setHeader('allow', 'GET, OPTIONS');
- return error(res, 405, 'method_not_allowed', 'method not allowed');
- }
-
- const rl = await limits.read(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const hash = url.searchParams.get('hash');
- const chainIdRaw = url.searchParams.get('chainId');
-
- if (!hash) return error(res, 400, 'validation_error', 'hash query param is required');
- if (!HASH_RE.test(hash))
- return error(res, 400, 'validation_error', 'hash must be 0x + 64 hex chars');
- if (!chainIdRaw) return error(res, 400, 'validation_error', 'chainId query param is required');
-
- const chainId = parseInt(chainIdRaw, 10);
- if (Number.isNaN(chainId) || chainId <= 0)
- return error(res, 400, 'validation_error', 'chainId must be a positive integer');
- if (!DELEGATION_MANAGER_DEPLOYMENTS[chainId])
- return error(res, 400, 'validation_error', `chainId ${chainId} is not supported`);
-
- const checkedAt = new Date().toISOString();
-
- const [row] = await sql`
- SELECT status, expires_at
- FROM agent_delegations
- WHERE delegation_hash = ${hash} AND chain_id = ${chainId}
- LIMIT 1
- `;
-
- if (row?.status === 'revoked') {
- return respond(
- res,
- { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
- CACHE_INVALID,
- );
- }
-
- if (row?.status === 'expired' || (row?.expires_at && new Date(row.expires_at) <= new Date())) {
- return respond(
- res,
- { ok: true, valid: false, reason: 'delegation_expired', checkedAt, chainId, hash },
- CACHE_INVALID,
- );
- }
-
- // On-chain check — 5 s timeout
- let disabled;
- try {
- disabled = await withTimeout(checkDisabled(hash, chainId), 5000);
- } catch (err) {
- console.error('[verify] rpc error', err);
- res.statusCode = 502;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('cache-control', 'no-store');
- res.end(JSON.stringify({ ok: false, error: 'rpc_error', message: err.message }));
- return;
- }
-
- if (disabled) {
- // Self-heal: if DB still tracks it as active, flip to revoked without blocking the response.
- if (row?.status === 'active') {
- console.log(`[verify] self-heal queued for ${hash}`);
- queueMicrotask(() => {
- sql`
- UPDATE agent_delegations
- SET status = 'revoked', revoked_at = NOW()
- WHERE delegation_hash = ${hash} AND status = 'active'
- `.catch((e) => console.error('[verify] self-heal failed', e));
- });
- }
- return respond(
- res,
- { ok: true, valid: false, reason: 'delegation_revoked', checkedAt, chainId, hash },
- CACHE_INVALID,
- );
- }
-
- const body = { ok: true, valid: true, checkedAt, chainId, hash };
- if (!row) body.reason = 'unknown_to_platform';
- return respond(res, body, CACHE_VALID);
-});
-
-async function checkDisabled(hash, chainId) {
- const rpcUrl = process.env[`RPC_URL_${chainId}`];
- if (!rpcUrl) throw new Error(`no RPC configured for chainId ${chainId}`);
- const provider = new JsonRpcProvider(rpcUrl);
- const manager = new Contract(
- DELEGATION_MANAGER_DEPLOYMENTS[chainId],
- DELEGATION_MANAGER_ABI,
- provider,
- );
- return manager.isDelegationDisabled(hash);
-}
-
-function withTimeout(promise, ms) {
- return Promise.race([
- promise,
- new Promise((_, reject) =>
- setTimeout(() => reject(new Error(`RPC timeout after ${ms}ms`)), ms),
- ),
- ]);
-}
-
-function respond(res, body, cacheControl) {
- const str = JSON.stringify(body);
- const etag = `"${createHash('sha256').update(str).digest('hex').slice(0, 16)}"`;
- res.statusCode = 200;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('cache-control', cacheControl);
- res.setHeader('etag', etag);
- res.end(str);
-}
diff --git a/api/pump/[action].js b/api/pump/[action].js
new file mode 100644
index 000000000..159515f59
--- /dev/null
+++ b/api/pump/[action].js
@@ -0,0 +1,1684 @@
+// Consolidated pump.fun API dispatcher.
+//
+// Routes via Vercel's [action] file param. Single bundle replaces 22 separate
+// serverless functions, each of which used to import @solana/web3.js and the
+// @pump-fun/* SDKs from scratch.
+//
+// Action map:
+// balances -> handleBalances
+// buy-prep -> handleBuyPrep
+// buy-confirm -> handleBuyConfirm
+// sell-prep -> handleSellPrep
+// sell-confirm -> handleSellConfirm
+// launch-prep -> handleLaunchPrep
+// launch-confirm -> handleLaunchConfirm
+// accept-payment-prep -> handleAcceptPaymentPrep
+// accept-payment-confirm -> handleAcceptPaymentConfirm
+// payments-list -> handlePaymentsList
+// portfolio -> handlePortfolio
+// by-agent -> handleByAgent
+// quote -> handleQuote
+// governance-prep -> handleGovernancePrep
+// withdraw-prep -> handleWithdrawPrep
+// withdraw-confirm -> handleWithdrawConfirm
+// strategy-backtest -> handleStrategyBacktest
+// strategy-close-all -> handleStrategyCloseAll
+// strategy-run -> handleStrategyRun (SSE; bypasses wrap())
+// strategy-validate -> handleStrategyValidate
+
+import { z } from 'zod';
+import { Keypair, PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import { sql } from '../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { parse } from '../_lib/validate.js';
+import { randomToken } from '../_lib/crypto.js';
+import {
+ getConnection,
+ getPumpSdk,
+ getPumpAgent,
+ getPumpAgentOffline,
+ getAmmPoolState,
+ buildUnsignedTxBase64,
+ verifySignature,
+ solanaPubkey,
+} from '../_lib/pump.js';
+import { solanaConnection } from '../_lib/agent-pumpfun.js';
+import { makeRuntime } from '../_lib/skill-runtime.js';
+import { loadWallet } from '../_lib/solana-wallet.js';
+import { checkBuyAllowed } from '../_lib/agent-spend-policy.js';
+import {
+ SOLANA_USDC_MINT,
+ SOLANA_USDC_MINT_DEVNET,
+ toUsdcAtomics,
+} from '../payments/_config.js';
+
+const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
+
+const RPC = {
+ mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',
+ devnet: process.env.SOLANA_DEVNET_RPC || 'https://api.devnet.solana.com',
+};
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+const wrapped = wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'balances': return handleBalances(req, res);
+ case 'buy-prep': return handleBuyPrep(req, res);
+ case 'buy-confirm': return handleBuyConfirm(req, res);
+ case 'sell-prep': return handleSellPrep(req, res);
+ case 'sell-confirm': return handleSellConfirm(req, res);
+ case 'launch-prep': return handleLaunchPrep(req, res);
+ case 'launch-confirm': return handleLaunchConfirm(req, res);
+ case 'accept-payment-prep': return handleAcceptPaymentPrep(req, res);
+ case 'accept-payment-confirm': return handleAcceptPaymentConfirm(req, res);
+ case 'payments-list': return handlePaymentsList(req, res);
+ case 'portfolio': return handlePortfolio(req, res);
+ case 'by-agent': return handleByAgent(req, res);
+ case 'quote': return handleQuote(req, res);
+ case 'governance-prep': return handleGovernancePrep(req, res);
+ case 'withdraw-prep': return handleWithdrawPrep(req, res);
+ case 'withdraw-confirm': return handleWithdrawConfirm(req, res);
+ case 'strategy-backtest': return handleStrategyBacktest(req, res);
+ case 'strategy-close-all': return handleStrategyCloseAll(req, res);
+ case 'strategy-validate': return handleStrategyValidate(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown pump action');
+ }
+});
+
+// strategy-run is SSE — it manages its own response writes and must bypass
+// wrap()'s JSON-error fallback once the stream is open. Route it before the
+// wrapped dispatcher to preserve the original endpoint's exported shape
+// (default async function handler).
+export default async function dispatcher(req, res) {
+ if (req.query?.action === 'strategy-run') {
+ return handleStrategyRun(req, res);
+ }
+ return wrapped(req, res);
+}
+
+// ── balances ───────────────────────────────────────────────────────────────
+
+async function handleBalances(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mintStr = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const currencyArg = url.searchParams.get('currency');
+
+ const mint = solanaPubkey(mintStr);
+ if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
+
+ const currencyStr =
+ currencyArg || (network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency');
+
+ try {
+ const { agent, agentPda } = await getPumpAgent({ network, mint });
+ const balances = await agent.getBalances(currency);
+ const fmt = (v) =>
+ v && {
+ address: v.address?.toString?.() ?? String(v.address),
+ balance: v.balance?.toString?.() ?? String(v.balance ?? 0),
+ };
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ currency: currencyStr,
+ agent_pda: agentPda?.toString?.() ?? null,
+ balances: {
+ payment: fmt(balances.paymentVault),
+ buyback: fmt(balances.buybackVault),
+ withdraw: fmt(balances.withdrawVault),
+ },
+ });
+ } catch (err) {
+ // Most common: agent not yet bound to mint → PDA missing.
+ return error(res, 502, 'pump_agent_error', err.message || 'pump-agent SDK error');
+ }
+}
+
+// ── buy-prep ───────────────────────────────────────────────────────────────
+
+const buyPrepSchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ sol: z.number().positive().max(50),
+ slippage_bps: z.number().int().min(0).max(5000).default(100),
+ wallet_address: z.string().min(32).max(44),
+});
+
+async function handleBuyPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(buyPrepSchema, await readJson(req));
+ const userPk = solanaPubkey(body.wallet_address);
+ const mintPk = solanaPubkey(body.mint);
+ if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ try {
+ const { sdk, BN, web3 } = await getPumpSdk({ network: body.network });
+ const lamports = new BN(Math.floor(body.sol * web3.LAMPORTS_PER_SOL));
+ const slippage = body.slippage_bps / 10_000;
+
+ // Try bonding curve.
+ let buyState = null;
+ try {
+ if (sdk.fetchBuyState) buyState = await sdk.fetchBuyState(mintPk, userPk);
+ } catch {
+ buyState = null;
+ }
+
+ if (buyState && buyState.bondingCurve && !buyState.bondingCurve.complete) {
+ const global = await sdk.fetchGlobal();
+ const ixs = await sdk.buyInstructions({
+ global,
+ bondingCurveAccountInfo: buyState.bondingCurveAccountInfo,
+ bondingCurve: buyState.bondingCurve,
+ associatedUserAccountInfo: buyState.associatedUserAccountInfo,
+ mint: mintPk,
+ user: userPk,
+ amount: new BN(0),
+ solAmount: lamports,
+ slippage,
+ });
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'bonding_curve',
+ mint: body.mint,
+ network: body.network,
+ sol_in: body.sol,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ }
+
+ // AMM
+ const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
+ const ammMod = await import('@pump-fun/pump-swap-sdk');
+ const offline = new ammMod.PumpAmmSdk();
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
+ const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
+ const ixs = await offline.buyQuoteInput(swapState, lamports, slippage);
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'amm',
+ pool: amm.poolKey.toString(),
+ mint: body.mint,
+ network: body.network,
+ sol_in: body.sol,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ } catch (e) {
+ return error(
+ res,
+ e.status || 502,
+ e.code || 'pump_sdk_error',
+ e.message || 'failed to build buy tx',
+ );
+ }
+}
+
+// ── buy-confirm ────────────────────────────────────────────────────────────
+
+const buyConfirmSchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ tx_signature: z.string().min(80).max(100),
+ wallet_address: z.string().min(32).max(44),
+ sol: z.number().positive().max(50),
+ route: z.enum(['bonding_curve', 'amm']),
+ slippage_bps: z.number().int().min(0).max(5000).optional(),
+});
+
+async function handleBuyConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(buyConfirmSchema, await readJson(req));
+
+ const [mintRow] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ const mintId = mintRow?.id ?? null;
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: body.network, signature: body.tx_signature });
+ } catch (e) {
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+ const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
+ if (!accountKeys.includes(body.mint))
+ return error(res, 422, 'mint_not_in_tx', 'mint not in tx');
+ if (!accountKeys.includes(body.wallet_address))
+ return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
+
+ if (mintId) {
+ const lamports = BigInt(Math.floor(body.sol * 1_000_000_000));
+ await sql`
+ insert into pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
+ values
+ (${mintId}, ${user.id}, ${body.wallet_address}, 'buy', ${body.route},
+ ${lamports.toString()}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
+ on conflict (tx_signature, network) do nothing
+ `;
+ }
+
+ return json(res, 200, {
+ ok: true,
+ tracked: !!mintId,
+ mint: body.mint,
+ network: body.network,
+ tx_signature: body.tx_signature,
+ });
+}
+
+// ── sell-prep ──────────────────────────────────────────────────────────────
+
+const sellPrepSchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ tokens: z.string().regex(/^\d+$/, 'tokens must be a base-units integer string'),
+ slippage_bps: z.number().int().min(0).max(5000).default(100),
+ wallet_address: z.string().min(32).max(44),
+});
+
+async function handleSellPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(sellPrepSchema, await readJson(req));
+ const userPk = solanaPubkey(body.wallet_address);
+ const mintPk = solanaPubkey(body.mint);
+ if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ try {
+ const { sdk, BN } = await getPumpSdk({ network: body.network });
+ const tokens = new BN(body.tokens);
+ const slippage = body.slippage_bps / 10_000;
+
+ let sellState = null;
+ try {
+ if (sdk.fetchSellState) sellState = await sdk.fetchSellState(mintPk, userPk);
+ } catch {
+ sellState = null;
+ }
+
+ if (sellState && sellState.bondingCurve && !sellState.bondingCurve.complete) {
+ const global = await sdk.fetchGlobal();
+ const ixs = await sdk.sellInstructions({
+ global,
+ bondingCurveAccountInfo: sellState.bondingCurveAccountInfo,
+ bondingCurve: sellState.bondingCurve,
+ mint: mintPk,
+ user: userPk,
+ amount: tokens,
+ solAmount: new BN(0),
+ slippage,
+ });
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'bonding_curve',
+ mint: body.mint,
+ network: body.network,
+ tokens_in: body.tokens,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ }
+
+ const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
+ const ammMod = await import('@pump-fun/pump-swap-sdk');
+ const offline = new ammMod.PumpAmmSdk();
+ const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
+ const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
+ const ixs = await offline.sellBaseInput(swapState, tokens, slippage);
+ const tx_base64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: userPk,
+ instructions: ixs,
+ });
+ return json(res, 201, {
+ route: 'amm',
+ pool: amm.poolKey.toString(),
+ mint: body.mint,
+ network: body.network,
+ tokens_in: body.tokens,
+ slippage_bps: body.slippage_bps,
+ tx_base64,
+ });
+ } catch (e) {
+ return error(
+ res,
+ e.status || 502,
+ e.code || 'pump_sdk_error',
+ e.message || 'failed to build sell tx',
+ );
+ }
+}
+
+// ── sell-confirm ───────────────────────────────────────────────────────────
+
+const sellConfirmSchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ tx_signature: z.string().min(80).max(100),
+ wallet_address: z.string().min(32).max(44),
+ tokens: z.string().regex(/^\d+$/),
+ route: z.enum(['bonding_curve', 'amm']),
+ slippage_bps: z.number().int().min(0).max(5000).optional(),
+});
+
+async function handleSellConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(sellConfirmSchema, await readJson(req));
+
+ const [mintRow] = await sql`
+ select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ const mintId = mintRow?.id ?? null;
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: body.network, signature: body.tx_signature });
+ } catch (e) {
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+ const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
+ if (!accountKeys.includes(body.mint))
+ return error(res, 422, 'mint_not_in_tx', 'mint not in tx');
+ if (!accountKeys.includes(body.wallet_address))
+ return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
+
+ if (mintId) {
+ await sql`
+ insert into pump_agent_trades
+ (mint_id, user_id, wallet, direction, route, token_amount, slippage_bps, tx_signature, network)
+ values
+ (${mintId}, ${user.id}, ${body.wallet_address}, 'sell', ${body.route},
+ ${body.tokens}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
+ on conflict (tx_signature, network) do nothing
+ `;
+ }
+
+ return json(res, 200, {
+ ok: true,
+ tracked: !!mintId,
+ mint: body.mint,
+ network: body.network,
+ tx_signature: body.tx_signature,
+ });
+}
+
+// ── launch-prep ────────────────────────────────────────────────────────────
+
+const launchPrepSchema = z.object({
+ agent_id: z.string().uuid(),
+ wallet_address: z.string().min(32).max(44),
+ name: z.string().trim().min(1).max(32),
+ symbol: z.string().trim().min(1).max(10),
+ uri: z.string().url(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ buyback_bps: z.number().int().min(0).max(10_000).default(0),
+ sol_buy_in: z.number().nonnegative().max(50).default(0), // optional creator initial buy, capped 50 SOL
+ // Optional client-ground vanity mint address. When provided, the client
+ // already holds the secret key locally and will co-sign in the wallet —
+ // the server never sees the secret. When omitted, the server falls back
+ // to a fresh Keypair.generate() and returns the secret key for co-sign.
+ mint_address: z.string().min(32).max(44).optional(),
+});
+
+async function handleLaunchPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(launchPrepSchema, await readJson(req));
+ const creator = solanaPubkey(body.wallet_address);
+ if (!creator) return error(res, 400, 'validation_error', 'invalid wallet_address');
+
+ // Verify wallet linked to user.
+ const [walletRow] = await sql`
+ select id from user_wallets
+ where user_id=${user.id} and address=${body.wallet_address} and chain_type='solana'
+ limit 1
+ `;
+ if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');
+
+ // Verify the agent belongs to this user.
+ const [agent] = await sql`
+ select id, name from agent_identities
+ where id=${body.agent_id} and user_id=${user.id} and deleted_at is null limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ // Mint pubkey: client-supplied (vanity-ground) or freshly generated.
+ let mintKeypair = null;
+ let mint;
+ if (body.mint_address) {
+ const supplied = solanaPubkey(body.mint_address);
+ if (!supplied) return error(res, 400, 'validation_error', 'invalid mint_address');
+ mint = supplied;
+ } else {
+ mintKeypair = Keypair.generate();
+ mint = mintKeypair.publicKey;
+ }
+
+ const { sdk, BN } = await getPumpSdk({ network: body.network });
+ const LAMPORTS_PER_SOL_LAUNCH = 1_000_000_000;
+
+ const instructions = [];
+ if (body.sol_buy_in > 0 && sdk.createAndBuyInstructions) {
+ const global = await sdk.fetchGlobal();
+ const solAmount = new BN(Math.floor(body.sol_buy_in * LAMPORTS_PER_SOL_LAUNCH));
+ const pumpSdk = await import('@pump-fun/pump-sdk');
+ const tokenAmount = pumpSdk.getBuyTokenAmountFromSolAmount(global, null, solAmount);
+ const ixs = await sdk.createAndBuyInstructions({
+ global,
+ mint,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator,
+ user: creator,
+ solAmount,
+ amount: tokenAmount,
+ });
+ instructions.push(...(Array.isArray(ixs) ? ixs : [ixs]));
+ } else {
+ const ix = await sdk.createInstruction({
+ mint,
+ name: body.name,
+ symbol: body.symbol,
+ uri: body.uri,
+ creator,
+ user: creator,
+ });
+ instructions.push(ix);
+ }
+
+ // Bind PumpAgent.create.
+ if (body.buyback_bps > 0) {
+ const { offline } = await getPumpAgentOffline({ network: body.network, mint });
+ const createIx = await offline.create({
+ authority: creator,
+ mint,
+ agentAuthority: creator,
+ buybackBps: body.buyback_bps,
+ });
+ instructions.push(createIx);
+ }
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: creator,
+ instructions,
+ });
+
+ const prepId = await randomToken(24);
+ const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
+
+ await sql`
+ insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at)
+ values (
+ ${user.id},
+ ${mint.toBase58()},
+ ${body.uri},
+ ${JSON.stringify({
+ kind: 'pump_launch',
+ agent_id: body.agent_id,
+ wallet_address: body.wallet_address,
+ mint: mint.toBase58(),
+ name: body.name,
+ symbol: body.symbol,
+ network: body.network,
+ buyback_bps: body.buyback_bps,
+ prep_id: prepId,
+ })}::jsonb,
+ ${expiresAt}
+ )
+ `;
+
+ return json(res, 201, {
+ prep_id: prepId,
+ mint: mint.toBase58(),
+ // Mint keypair must co-sign the tx. When server-generated, we hand
+ // the secret to the frontend; when client-supplied (vanity), the
+ // client already holds it and the server never sees it.
+ mint_secret_key_b64: mintKeypair ? Buffer.from(mintKeypair.secretKey).toString('base64') : null,
+ client_supplied_mint: !mintKeypair,
+ tx_base64: txBase64,
+ network: body.network,
+ buyback_bps: body.buyback_bps,
+ expires_at: expiresAt.toISOString(),
+ instructions: mintKeypair
+ ? 'Decode tx_base64 as VersionedTransaction. Sign with the mint keypair (mint_secret_key_b64) AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.'
+ : 'Decode tx_base64 as VersionedTransaction. Sign with your locally-held vanity mint keypair AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.',
+ });
+}
+
+// ── launch-confirm ─────────────────────────────────────────────────────────
+
+const launchConfirmSchema = z.object({
+ prep_id: z.string().min(8),
+ tx_signature: z.string().min(80).max(100),
+});
+
+async function handleLaunchConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(launchConfirmSchema, await readJson(req));
+
+ const [pending] = await sql`
+ select id, payload from agent_registrations_pending
+ where user_id=${user.id} and payload->>'prep_id'=${body.prep_id}
+ and expires_at > now()
+ order by created_at desc limit 1
+ `;
+ if (!pending) return error(res, 404, 'not_found', 'prep not found or expired');
+ const p = pending.payload;
+ if (p.kind !== 'pump_launch') return error(res, 400, 'wrong_kind', 'prep is not a pump launch');
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: p.network, signature: body.tx_signature });
+ } catch (e) {
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+ const accountKeys = tx.transaction.message.accountKeys.map((k) =>
+ (k.pubkey || k).toString(),
+ );
+ if (!accountKeys.includes(p.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'mint pubkey not present in tx');
+ }
+
+ const [existing] = await sql`
+ select id from pump_agent_mints where mint=${p.mint} and network=${p.network} limit 1
+ `;
+ if (existing) return error(res, 409, 'conflict', 'mint already registered');
+
+ const [row] = await sql`
+ insert into pump_agent_mints
+ (agent_id, user_id, network, mint, name, symbol, agent_authority, buyback_bps)
+ values
+ (${p.agent_id}, ${user.id}, ${p.network}, ${p.mint},
+ ${p.name}, ${p.symbol}, ${p.wallet_address}, ${p.buyback_bps})
+ returning id, mint, network, buyback_bps, created_at
+ `;
+
+ await sql`delete from agent_registrations_pending where id=${pending.id}`;
+
+ return json(res, 201, {
+ ok: true,
+ pump_agent_mint: row,
+ tx_signature: body.tx_signature,
+ });
+}
+
+// ── accept-payment-prep ────────────────────────────────────────────────────
+
+const acceptPaymentPrepSchema = z.object({
+ mint: z.string().min(32).max(44), // pump.fun token mint = agent token
+ payer_wallet: z.string().min(32).max(44),
+ amount_usdc: z.number().positive().max(100_000),
+ currency_mint: z.string().min(32).max(44).optional(), // defaults to USDC
+ currency_token_program: z.string().min(32).max(44).optional(),
+ user_token_account: z.string().min(32).max(44), // payer ATA
+ skill_id: z.string().max(100).optional(),
+ tool_name: z.string().max(100).optional(),
+ duration_seconds: z.number().int().positive().max(60 * 60 * 24 * 365).default(60),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+function bnFromBigint(BN, v) {
+ return new BN(v.toString());
+}
+
+async function handleAcceptPaymentPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Allow both session users (browser) and bearer (MCP / agent) callers.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer)
+ return error(res, 401, 'unauthorized', 'sign in or supply a bearer token');
+ const userId = session?.id ?? bearer?.userId ?? null;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(acceptPaymentPrepSchema, await readJson(req));
+ const payer = solanaPubkey(body.payer_wallet);
+ const userAta = solanaPubkey(body.user_token_account);
+ if (!payer) return error(res, 400, 'validation_error', 'invalid payer_wallet');
+ if (!userAta) return error(res, 400, 'validation_error', 'invalid user_token_account');
+
+ const [agent] = await sql`
+ select id, mint, network, buyback_bps from pump_agent_mints
+ where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
+
+ const currencyStr =
+ body.currency_mint ||
+ (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
+
+ const { offline, BN } = await getPumpAgentOffline({
+ network: body.network,
+ mint: body.mint,
+ });
+
+ // Invoice ID = random 64-bit unsigned (memo BN). Used as the PDA seed and
+ // as the X402 receipt identifier downstream.
+ const invoiceIdHex = (await randomToken(8)).slice(0, 16);
+ const invoiceId = new BN(invoiceIdHex, 16);
+
+ const startTime = Math.floor(Date.now() / 1000);
+ const endTime = startTime + body.duration_seconds;
+
+ const amountAtomics = toUsdcAtomics(body.amount_usdc); // bigint, USDC = 6 dp
+
+ const tokenProgram = body.currency_token_program
+ ? solanaPubkey(body.currency_token_program)
+ : undefined;
+
+ const ix = await offline.acceptPayment({
+ user: payer,
+ userTokenAccount: userAta,
+ currencyMint: currency,
+ amount: bnFromBigint(BN, amountAtomics),
+ memo: invoiceId,
+ startTime: new BN(startTime),
+ endTime: new BN(endTime),
+ ...(tokenProgram ? { tokenProgram } : {}),
+ });
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer,
+ instructions: [ix],
+ });
+
+ const [row] = await sql`
+ insert into pump_agent_payments
+ (mint_id, user_id, payer_wallet, currency_mint, amount_atomics,
+ invoice_id, start_time, end_time, status, skill_id, tool_name)
+ values
+ (${agent.id}, ${userId}, ${body.payer_wallet}, ${currencyStr},
+ ${amountAtomics.toString()}, ${invoiceId.toString()},
+ to_timestamp(${startTime}), to_timestamp(${endTime}),
+ 'pending', ${body.skill_id || null}, ${body.tool_name || null})
+ returning id, invoice_id, start_time, end_time, status
+ `;
+
+ return json(res, 201, {
+ payment_id: row.id,
+ mint: body.mint,
+ invoice_id: invoiceId.toString(),
+ amount_usdc: body.amount_usdc,
+ amount_atomics: amountAtomics.toString(),
+ currency_mint: currencyStr,
+ start_time: row.start_time,
+ end_time: row.end_time,
+ network: body.network,
+ tx_base64: txBase64,
+ instructions:
+ 'Decode tx_base64, sign with payer wallet, submit, then call /api/pump/accept-payment-confirm with the tx_signature and payment_id.',
+ });
+}
+
+// ── accept-payment-confirm ─────────────────────────────────────────────────
+
+const acceptPaymentConfirmSchema = z.object({
+ payment_id: z.string().uuid(),
+ tx_signature: z.string().min(80).max(100),
+});
+
+async function handleAcceptPaymentConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ if (!session && !bearer) return error(res, 401, 'unauthorized', 'auth required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(acceptPaymentConfirmSchema, await readJson(req));
+ const [payment] = await sql`
+ select p.*, m.mint, m.network from pump_agent_payments p
+ join pump_agent_mints m on m.id = p.mint_id
+ where p.id=${body.payment_id} limit 1
+ `;
+ if (!payment) return error(res, 404, 'not_found', 'payment not found');
+ if (payment.status === 'confirmed')
+ return error(res, 409, 'already_confirmed', 'payment already confirmed');
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: payment.network, signature: body.tx_signature });
+ } catch (e) {
+ await sql`update pump_agent_payments set status='failed' where id=${payment.id}`;
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+
+ const accountKeys = tx.transaction.message.accountKeys.map((k) =>
+ (k.pubkey || k).toString(),
+ );
+ if (!accountKeys.includes(payment.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'agent mint not in tx accounts');
+ }
+
+ await sql`
+ update pump_agent_payments
+ set status='confirmed', tx_signature=${body.tx_signature}, confirmed_at=now()
+ where id=${payment.id}
+ `;
+
+ return json(res, 200, {
+ ok: true,
+ payment_id: payment.id,
+ invoice_id: payment.invoice_id,
+ tx_signature: body.tx_signature,
+ });
+}
+
+// ── payments-list ──────────────────────────────────────────────────────────
+
+async function handlePaymentsList(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mint = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const limit = Math.min(Number(url.searchParams.get('limit') || 50), 500);
+ const includePending = url.searchParams.get('include_pending') === '1';
+
+ if (!mint) return error(res, 400, 'validation_error', 'mint required');
+
+ const [agent] = await sql`
+ select id, mint, network, buyback_bps from pump_agent_mints
+ where mint=${mint} and network=${network} limit 1
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
+
+ const rows = includePending
+ ? await sql`
+ select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
+ start_time, end_time, status, skill_id, tool_name,
+ invoice_pda, tx_signature, created_at, confirmed_at
+ from pump_agent_payments
+ where mint_id=${agent.id}
+ order by created_at desc limit ${limit}
+ `
+ : await sql`
+ select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
+ start_time, end_time, status, skill_id, tool_name,
+ invoice_pda, tx_signature, created_at, confirmed_at
+ from pump_agent_payments
+ where mint_id=${agent.id} and status='confirmed'
+ order by confirmed_at desc nulls last limit ${limit}
+ `;
+
+ // Derive invoice PDAs for any rows that lack one (older rows pre-PDA backfill).
+ // We do it lazily here so the widget can deep-link without a backfill cron.
+ let pdaErrored = false;
+ const needsPda = rows.filter((r) => !r.invoice_pda && r.invoice_id);
+ if (needsPda.length > 0) {
+ try {
+ const [{ getInvoiceIdPDA }, { PublicKey }] = await Promise.all([
+ import('@pump-fun/agent-payments-sdk'),
+ import('@solana/web3.js'),
+ ]);
+ const BN = (await import('bn.js')).default || (await import('bn.js'));
+ const mintPk = new PublicKey(mint);
+ for (const r of needsPda) {
+ try {
+ const [pda] = getInvoiceIdPDA(mintPk, new BN(r.invoice_id));
+ r.invoice_pda = pda.toBase58();
+ } catch {
+ /* skip individual failures */
+ }
+ }
+ } catch {
+ pdaErrored = true;
+ }
+ }
+
+ const [agg] = await sql`
+ select
+ count(*)::int as total,
+ count(*) filter (where status='confirmed')::int as confirmed,
+ count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
+ coalesce(sum(amount_atomics) filter (where status='confirmed'), 0)::text as total_atomics
+ from pump_agent_payments where mint_id=${agent.id}
+ `;
+
+ return json(res, 200, {
+ mint,
+ network,
+ buyback_bps: agent.buyback_bps,
+ summary: agg,
+ data: rows,
+ });
+}
+
+// ── portfolio ──────────────────────────────────────────────────────────────
+
+async function handlePortfolio(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const agentId = url.searchParams.get('agentId');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+
+ const [agent] = await sql`
+ SELECT user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ const address = agent.meta?.solana_address;
+ if (!address) return error(res, 409, 'conflict', 'agent has no solana wallet');
+
+ const conn = solanaConnection(network);
+ const owner = new PublicKey(address);
+
+ const [lamports, tokenResp, recentBuys] = await Promise.all([
+ conn.getBalance(owner),
+ conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID }),
+ sql`
+ SELECT payload, created_at FROM agent_actions
+ WHERE agent_id = ${agentId}
+ AND type IN ('pumpfun.buy', 'buy')
+ ORDER BY created_at DESC
+ LIMIT 500
+ `.catch(() => []),
+ ]);
+
+ const holdings = tokenResp.value
+ .map((acc) => {
+ const info = acc.account.data.parsed.info;
+ return {
+ mint: info.mint,
+ amount: info.tokenAmount.uiAmount ?? 0,
+ decimals: info.tokenAmount.decimals,
+ };
+ })
+ .filter((h) => h.amount > 0);
+
+ // Cost basis from recorded buys.
+ const basisByMint = new Map();
+ for (const row of recentBuys) {
+ const p = row.payload || {};
+ if (!p.mint) continue;
+ const prev = basisByMint.get(p.mint) ?? { sol: 0, tokens: 0 };
+ prev.sol += Number(p.amountSol) || 0;
+ prev.tokens += Number(p.amountTokens) || 0;
+ basisByMint.set(p.mint, prev);
+ }
+
+ // Live price per holding via the read-only pump-fun MCP (parallelized).
+ const rt = makeRuntime();
+ const priced = await Promise.all(holdings.map(async (h) => {
+ const [curve, basis] = [
+ await rt.invoke('pump-fun.getBondingCurve', { mint: h.mint }).catch(() => ({ ok: false })),
+ basisByMint.get(h.mint),
+ ];
+ const priceSol = curve?.ok ? (curve.data?.priceSol ?? curve.data?.price ?? null) : null;
+ const valueSol = priceSol != null ? priceSol * h.amount : null;
+ const costBasisSol = basis ? basis.sol : null;
+ const unrealizedSol = valueSol != null && costBasisSol != null ? valueSol - costBasisSol : null;
+ return {
+ ...h,
+ priceSol,
+ valueSol,
+ costBasisSol,
+ unrealizedPnlSol: unrealizedSol,
+ unrealizedPnlPct: unrealizedSol != null && costBasisSol > 0 ? (unrealizedSol / costBasisSol) * 100 : null,
+ };
+ }));
+
+ const totalValueSol = priced.reduce((s, p) => s + (p.valueSol ?? 0), 0);
+ const totalCostBasisSol = priced.reduce((s, p) => s + (p.costBasisSol ?? 0), 0);
+ const unrealizedPnlSol = totalValueSol - totalCostBasisSol;
+
+ return json(res, 200, {
+ data: {
+ address,
+ network,
+ lamports,
+ sol: lamports / LAMPORTS_PER_SOL,
+ holdings: priced,
+ totalValueSol,
+ totalCostBasisSol,
+ unrealizedPnlSol,
+ unrealizedPnlPct: totalCostBasisSol > 0 ? (unrealizedPnlSol / totalCostBasisSol) * 100 : null,
+ },
+ });
+}
+
+// ── by-agent ───────────────────────────────────────────────────────────────
+
+async function handleByAgent(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const agentId = url.searchParams.get('agent_id');
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id required');
+
+ const [row] = await sql`
+ select id, mint, network, name, symbol, buyback_bps, agent_authority,
+ metadata_uri, sharing_config, created_at
+ from pump_agent_mints
+ where agent_id=${agentId}
+ order by created_at desc limit 1
+ `;
+ if (!row) return json(res, 200, { data: null });
+
+ const [stats] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as confirmed_payments,
+ count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
+ coalesce(sum(amount_atomics) filter (where status='confirmed'),0)::text as total_atomics,
+ max(confirmed_at) filter (where status='confirmed') as last_payment_at
+ from pump_agent_payments where mint_id=${row.id}
+ `;
+
+ const [burnRow] = await sql`
+ select
+ count(*) filter (where status='confirmed')::int as runs,
+ coalesce(sum(burn_amount) filter (where status='confirmed'),0)::text as total_burned,
+ max(created_at) as last_burn_at
+ from pump_buyback_runs where mint_id=${row.id}
+ `;
+
+ // Burns feed (separate from payments feed) — recent confirmed buyback runs
+ // for the dashboard / passport "🔥 burns" stream.
+ const burnsFeed = await sql`
+ select id, currency_mint, tx_signature, burn_amount, created_at
+ from pump_buyback_runs
+ where mint_id=${row.id} and status='confirmed'
+ order by created_at desc
+ limit 10
+ `;
+
+ return json(res, 200, {
+ data: {
+ ...row,
+ stats: stats || { confirmed_payments: 0, unique_payers: 0, total_atomics: '0' },
+ burns: burnRow || { runs: 0, total_burned: '0' },
+ burns_feed: burnsFeed,
+ },
+ });
+}
+
+// ── quote ──────────────────────────────────────────────────────────────────
+
+async function handleQuote(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const mintStr = url.searchParams.get('mint');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const direction = url.searchParams.get('direction') === 'sell' ? 'sell' : 'buy';
+ const solRaw = url.searchParams.get('sol');
+ const tokenRaw = url.searchParams.get('token');
+ const slippageRaw = url.searchParams.get('slippage_bps');
+ const slippageBps = Number.isFinite(Number(slippageRaw))
+ ? Math.max(0, Math.min(5000, Number(slippageRaw)))
+ : 100;
+ const slippage = slippageBps / 10_000;
+
+ const mint = solanaPubkey(mintStr);
+ if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
+
+ try {
+ // Try bonding curve first.
+ const { sdk, BN, web3 } = await getPumpSdk({ network });
+ const LAMPORTS_PER_SOL_Q = web3.LAMPORTS_PER_SOL || 1_000_000_000;
+
+ let curve = null;
+ try {
+ if (sdk.fetchBuyState) {
+ const state = await sdk.fetchBuyState(mint, mint); // any pubkey works for read
+ curve = state.bondingCurve;
+ } else if (sdk.fetchBondingCurve) {
+ curve = await sdk.fetchBondingCurve(mint);
+ }
+ } catch {
+ curve = null;
+ }
+
+ if (curve && !curve.complete) {
+ const global = typeof sdk.fetchGlobal === 'function' ? await sdk.fetchGlobal() : null;
+ const pumpSdk = await import('@pump-fun/pump-sdk');
+ let quote = null;
+
+ if (direction === 'buy' && solRaw) {
+ const sol = Number(solRaw);
+ if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');
+ const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL_Q));
+ const tokens = pumpSdk.getBuyTokenAmountFromSolAmount(global, curve, lamports);
+ quote = { sol_in: sol, tokens_out: tokens.toString(), source: 'bonding_curve' };
+ } else if (direction === 'sell' && tokenRaw) {
+ const tokens = new BN(tokenRaw);
+ const lamports = pumpSdk.getSellSolAmountFromTokenAmount(global, curve, tokens);
+ quote = {
+ tokens_in: tokenRaw,
+ sol_out: Number(lamports.toString()) / LAMPORTS_PER_SOL_Q,
+ source: 'bonding_curve',
+ };
+ }
+
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ graduated: false,
+ bonding_curve: {
+ real_sol_reserves: curve.realSolReserves?.toString?.() ?? null,
+ real_token_reserves: curve.realTokenReserves?.toString?.() ?? null,
+ virtual_sol_reserves: curve.virtualSolReserves?.toString?.() ?? null,
+ virtual_token_reserves: curve.virtualTokenReserves?.toString?.() ?? null,
+ complete: curve.complete ?? false,
+ },
+ quote,
+ });
+ }
+
+ // Post-graduation: AMM via canonical pump.fun pool (quote = WSOL).
+ let amm;
+ try {
+ amm = await getAmmPoolState({ network, mint });
+ } catch (e) {
+ if (e.code === 'pool_not_found') {
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ graduated: true,
+ pool: null,
+ quote: null,
+ note: 'No bonding curve and no canonical AMM pool — token may not be a pump.fun mint or has not graduated yet',
+ });
+ }
+ throw e;
+ }
+
+ const {
+ pool,
+ poolKey,
+ baseReserve,
+ quoteReserve,
+ baseMintAccount,
+ globalConfig,
+ feeConfig,
+ } = amm;
+ const LAMPORTS_PER_SOL_AMM = 1_000_000_000;
+ const ammSdk = await import('@pump-fun/pump-swap-sdk');
+ let quote = null;
+
+ if (direction === 'buy' && solRaw) {
+ const sol = Number(solRaw);
+ if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');
+ const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL_AMM));
+ const r = ammSdk.buyQuoteInput({
+ quote: lamports,
+ slippage,
+ baseReserve,
+ quoteReserve,
+ globalConfig,
+ baseMintAccount,
+ baseMint: pool.baseMint,
+ coinCreator: pool.coinCreator,
+ creator: pool.creator,
+ feeConfig,
+ });
+ quote = {
+ sol_in: sol,
+ tokens_out: r.base?.toString?.() ?? null,
+ min_tokens_out: r.uiBase?.toString?.() ?? r.minBase?.toString?.() ?? null,
+ slippage_bps: slippageBps,
+ source: 'amm',
+ };
+ } else if (direction === 'sell' && tokenRaw) {
+ const tokens = new BN(tokenRaw);
+ const r = ammSdk.sellBaseInput({
+ base: tokens,
+ slippage,
+ baseReserve,
+ quoteReserve,
+ globalConfig,
+ baseMintAccount,
+ baseMint: pool.baseMint,
+ coinCreator: pool.coinCreator,
+ creator: pool.creator,
+ feeConfig,
+ });
+ const lamportsOut = r.quote ?? r.uiQuote ?? r.minQuote;
+ quote = {
+ tokens_in: tokenRaw,
+ sol_out:
+ lamportsOut != null
+ ? Number(lamportsOut.toString()) / LAMPORTS_PER_SOL_AMM
+ : null,
+ min_sol_out: (r.minQuote ?? r.uiQuote)?.toString
+ ? Number((r.minQuote ?? r.uiQuote).toString()) / LAMPORTS_PER_SOL_AMM
+ : null,
+ slippage_bps: slippageBps,
+ source: 'amm',
+ };
+ }
+
+ return json(res, 200, {
+ mint: mintStr,
+ network,
+ graduated: true,
+ pool: {
+ address: poolKey.toString(),
+ base: pool.baseMint.toString(),
+ quote: pool.quoteMint.toString(),
+ base_reserve: baseReserve.toString(),
+ quote_reserve: quoteReserve.toString(),
+ lp_supply: pool.lpSupply?.toString?.() ?? null,
+ },
+ quote,
+ });
+ } catch (err) {
+ return error(
+ res,
+ err.status || 502,
+ err.code || 'pump_sdk_error',
+ err.message || 'pump.fun SDK error',
+ );
+ }
+}
+
+// ── governance-prep ────────────────────────────────────────────────────────
+
+const governancePrepSchema = z.object({
+ mint: z.string().min(32).max(44),
+ authority_wallet: z.string().min(32).max(44),
+ new_buyback_bps: z.number().int().min(0).max(10_000),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleGovernancePrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(governancePrepSchema, await readJson(req));
+ const authority = solanaPubkey(body.authority_wallet);
+ if (!authority) return error(res, 400, 'validation_error', 'invalid authority_wallet');
+
+ const [row] = await sql`
+ select id, user_id, agent_authority from pump_agent_mints
+ where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
+ return error(res, 403, 'forbidden', 'authority does not match');
+ }
+
+ const { offline } = await getPumpAgentOffline({ network: body.network, mint: body.mint });
+ const ix = await offline.updateBuybackBps(
+ { authority, buybackBps: body.new_buyback_bps },
+ {}, // UpdateBuybackBpsOptions — empty default
+ );
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: authority,
+ instructions: [ix],
+ });
+
+ return json(res, 201, {
+ mint: body.mint,
+ network: body.network,
+ new_buyback_bps: body.new_buyback_bps,
+ tx_base64: txBase64,
+ instructions:
+ 'Sign with the agent authority wallet, submit, then optionally PATCH the local row via /api/agents/:id to refresh display.',
+ });
+}
+
+// ── withdraw-prep ──────────────────────────────────────────────────────────
+
+const withdrawPrepSchema = z.object({
+ mint: z.string().min(32).max(44),
+ authority_wallet: z.string().min(32).max(44),
+ receiver_ata: z.string().min(32).max(44),
+ currency_mint: z.string().min(32).max(44).optional(),
+ currency_token_program: z.string().min(32).max(44).optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleWithdrawPrep(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(withdrawPrepSchema, await readJson(req));
+ const authority = solanaPubkey(body.authority_wallet);
+ const receiverAta = solanaPubkey(body.receiver_ata);
+ if (!authority || !receiverAta)
+ return error(res, 400, 'validation_error', 'invalid pubkeys');
+
+ const [row] = await sql`
+ select m.id, m.mint, m.user_id, m.agent_authority, m.network from pump_agent_mints m
+ where m.mint=${body.mint} and m.network=${body.network} limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+ if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
+ return error(res, 403, 'forbidden', 'authority does not match');
+ }
+
+ const currencyStr =
+ body.currency_mint ||
+ (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
+ const currency = solanaPubkey(currencyStr);
+ if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
+
+ const { offline } = await getPumpAgentOffline({
+ network: body.network,
+ mint: body.mint,
+ });
+
+ const tokenProgram = body.currency_token_program
+ ? solanaPubkey(body.currency_token_program)
+ : undefined;
+
+ const ix = await offline.withdraw({
+ authority,
+ currencyMint: currency,
+ receiverAta,
+ ...(tokenProgram ? { tokenProgram } : {}),
+ });
+
+ const txBase64 = await buildUnsignedTxBase64({
+ network: body.network,
+ payer: authority,
+ instructions: [ix],
+ });
+
+ return json(res, 201, {
+ mint: body.mint,
+ network: body.network,
+ currency_mint: currencyStr,
+ tx_base64: txBase64,
+ });
+}
+
+// ── withdraw-confirm ───────────────────────────────────────────────────────
+
+const withdrawConfirmSchema = z.object({
+ mint: z.string().min(32).max(44),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ tx_signature: z.string().min(80).max(100),
+});
+
+async function handleWithdrawConfirm(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = parse(withdrawConfirmSchema, await readJson(req));
+
+ const [row] = await sql`
+ select id, mint, user_id, agent_authority, network from pump_agent_mints
+ where mint=${body.mint} and network=${body.network} limit 1
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
+ if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
+
+ let tx;
+ try {
+ tx = await verifySignature({ network: body.network, signature: body.tx_signature });
+ } catch (e) {
+ return error(res, e.status || 422, e.code || 'tx_failed', e.message);
+ }
+
+ const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
+ if (!accountKeys.includes(body.mint)) {
+ return error(res, 422, 'mint_not_in_tx', 'mint not present in tx accounts');
+ }
+ if (row.agent_authority && !accountKeys.includes(row.agent_authority)) {
+ return error(res, 422, 'authority_not_in_tx', 'agent authority not present in tx');
+ }
+
+ return json(res, 200, {
+ ok: true,
+ mint: body.mint,
+ network: body.network,
+ tx_signature: body.tx_signature,
+ slot: tx.slot ?? null,
+ block_time: tx.blockTime ?? null,
+ });
+}
+
+// ── strategy-backtest ──────────────────────────────────────────────────────
+
+async function resolveStrategyMints(invoke, strategy, explicit, limit) {
+ if (Array.isArray(explicit) && explicit.length) return explicit;
+ const scan = strategy?.scan ?? {};
+ if (scan.kind === 'mintList' && Array.isArray(scan.mints)) return scan.mints;
+ const tool = scan.kind === 'trending' ? 'pump-fun.getTrendingTokens' : 'pump-fun.getNewTokens';
+ const r = await invoke(tool, { limit: limit ?? scan.limit ?? 20 });
+ if (!r.ok) throw new Error(`scan failed: ${r.error}`);
+ const items = r.data?.tokens ?? r.data ?? [];
+ return items.map((t) => t.mint ?? t.address).filter(Boolean);
+}
+
+async function handleStrategyBacktest(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req);
+ if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
+
+ const rt = makeRuntime();
+ let mints;
+ try {
+ mints = await resolveStrategyMints(rt.invoke, body.strategy, body.mints, body.limit);
+ } catch (e) {
+ return error(res, 502, 'upstream_error', e.message);
+ }
+ if (!mints.length) return error(res, 422, 'no_candidates', 'no mints to backtest');
+
+ const { backtestStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
+ const result = await backtestStrategy(
+ { strategy: body.strategy, mints, sinceMs: body.sinceMs ?? 0 },
+ { skills: { invoke: rt.invoke }, memory: { note: () => {} } },
+ );
+ if (!result.ok) return error(res, 400, 'validation_error', result.error);
+ return json(res, 200, { data: { ...result.data, mintsUsed: mints } });
+}
+
+// ── strategy-close-all ─────────────────────────────────────────────────────
+
+async function handleStrategyCloseAll(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req);
+ if (!body?.agentId) return error(res, 400, 'validation_error', 'agentId required');
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ const [row] = await sql`
+ SELECT user_id, meta FROM agent_identities
+ WHERE id = ${body.agentId} AND deleted_at IS NULL
+ `;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+ if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
+ const enc = row.meta?.encrypted_solana_secret;
+ if (!enc) return error(res, 409, 'conflict', 'agent has no solana wallet');
+
+ const wallet = await loadWallet(enc);
+ const rt = makeRuntime({
+ wallet,
+ agentId: body.agentId,
+ signerAddress: wallet.publicKey.toBase58(),
+ configOverrides: {
+ 'pump-fun-trade': { rpc: RPC[network] },
+ 'solana-wallet': { rpc: RPC[network] },
+ },
+ });
+
+ const { closeAllPositions } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
+ const result = await closeAllPositions(
+ { mints: body.mints, simulate: !!body.simulate },
+ { skills: { invoke: rt.invoke }, wallet, memory: { note: () => {} } },
+ );
+ if (!result.ok) return error(res, 400, 'sell_failed', result.error);
+ return json(res, 200, { data: result.data });
+}
+
+// ── strategy-run ───────────────────────────────────────────────────────────
+// SSE — manages its own response writes; routed before wrap() above.
+
+async function loadAgentWalletForStrategy(agentId, userId) {
+ const [row] = await sql`
+ SELECT user_id, meta FROM agent_identities
+ WHERE id = ${agentId} AND deleted_at IS NULL
+ `;
+ if (!row) throw Object.assign(new Error('agent not found'), { status: 404 });
+ if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403 });
+ const enc = row.meta?.encrypted_solana_secret;
+ if (!enc) throw Object.assign(new Error('agent has no solana wallet — provision via /api/agents/:id/solana'), { status: 409 });
+ const wallet = await loadWallet(enc);
+ return { wallet, address: wallet.publicKey.toBase58(), meta: row.meta };
+}
+
+async function handleStrategyRun(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ let body;
+ try { body = await readJson(req); }
+ catch (e) { return error(res, 400, 'validation_error', e.message); }
+
+ if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
+ const durationSec = Math.max(5, Math.min(600, Number(body.durationSec) || 30));
+ const mode = body.mode === 'live' ? 'live' : 'simulate';
+ const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
+
+ let wallet = null, walletAddress = null, agentMeta = null;
+ if (mode === 'live') {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');
+ if (!body.agentId) return error(res, 400, 'validation_error', 'agentId required for live mode');
+ try {
+ const r = await loadAgentWalletForStrategy(body.agentId, auth.userId);
+ wallet = r.wallet;
+ walletAddress = r.address;
+ agentMeta = r.meta;
+ } catch (e) {
+ return error(res, e.status ?? 500, e.status === 409 ? 'conflict' : 'unauthorized', e.message);
+ }
+ }
+
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream');
+ res.setHeader('cache-control', 'no-cache, no-transform');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('access-control-allow-origin', '*');
+ const send = (event, data) => {
+ res.write(`event: ${event}\n`);
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
+ };
+
+ let aborted = false;
+ req.on('close', () => { aborted = true; });
+
+ const rt = makeRuntime({
+ wallet,
+ agentId: mode === 'live' ? body.agentId : undefined,
+ signerAddress: walletAddress,
+ configOverrides: {
+ 'pump-fun-trade': { rpc: RPC[network] },
+ 'solana-wallet': { rpc: RPC[network] },
+ },
+ onEvent: (e) => send('memory', e),
+ });
+
+ send('start', { durationSec, mode, network, walletAddress });
+
+ const { runStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
+ const ctx = {
+ skills: { invoke: rt.invoke },
+ skillConfig: { defaultPollMs: Math.max(1500, Number(body.pollMs) || 3000) },
+ memory: { note: (tag, value) => send('memory', { tag, value }) },
+ wallet,
+ };
+
+ const policyGuard = mode === 'live'
+ ? async ({ mint, amountSol }) => {
+ const block = await checkBuyAllowed({ agentId: body.agentId, meta: agentMeta, mint, solAmount: amountSol });
+ return block ? { code: block.code, msg: block.msg } : null;
+ }
+ : null;
+
+ const abortController = new AbortController();
+ req.on('close', () => abortController.abort());
+
+ try {
+ const result = await runStrategy(
+ {
+ strategy: body.strategy,
+ durationSec,
+ simulate: mode === 'simulate',
+ onLog: (entry) => { if (!aborted) send('log', entry); },
+ policyGuard,
+ abortSignal: abortController.signal,
+ },
+ ctx,
+ );
+ send('done', result.data);
+ } catch (e) {
+ send('error', { message: e.message });
+ }
+ res.end();
+}
+
+// ── strategy-validate ──────────────────────────────────────────────────────
+
+async function handleStrategyValidate(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req);
+ if (!body?.strategy || typeof body.strategy !== 'object') {
+ return error(res, 400, 'validation_error', 'strategy required');
+ }
+
+ const rt = makeRuntime();
+ const r = await rt.invoke('pump-fun-strategy.validateStrategy', { strategy: body.strategy });
+ if (!r.ok) return error(res, 400, 'validation_error', r.error);
+ return json(res, 200, { data: r.data });
+}
diff --git a/api/pump/accept-payment-confirm.js b/api/pump/accept-payment-confirm.js
deleted file mode 100644
index 436db819b..000000000
--- a/api/pump/accept-payment-confirm.js
+++ /dev/null
@@ -1,65 +0,0 @@
-// POST /api/pump/accept-payment-confirm
-// Verify the acceptPayment tx landed; mark the payment row confirmed.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { verifySignature } from '../_lib/pump.js';
-
-const bodySchema = z.object({
- payment_id: z.string().uuid(),
- tx_signature: z.string().min(80).max(100),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer) return error(res, 401, 'unauthorized', 'auth required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const [payment] = await sql`
- select p.*, m.mint, m.network from pump_agent_payments p
- join pump_agent_mints m on m.id = p.mint_id
- where p.id=${body.payment_id} limit 1
- `;
- if (!payment) return error(res, 404, 'not_found', 'payment not found');
- if (payment.status === 'confirmed')
- return error(res, 409, 'already_confirmed', 'payment already confirmed');
-
- let tx;
- try {
- tx = await verifySignature({ network: payment.network, signature: body.tx_signature });
- } catch (e) {
- await sql`update pump_agent_payments set status='failed' where id=${payment.id}`;
- return error(res, e.status || 422, e.code || 'tx_failed', e.message);
- }
-
- const accountKeys = tx.transaction.message.accountKeys.map((k) =>
- (k.pubkey || k).toString(),
- );
- if (!accountKeys.includes(payment.mint)) {
- return error(res, 422, 'mint_not_in_tx', 'agent mint not in tx accounts');
- }
-
- await sql`
- update pump_agent_payments
- set status='confirmed', tx_signature=${body.tx_signature}, confirmed_at=now()
- where id=${payment.id}
- `;
-
- return json(res, 200, {
- ok: true,
- payment_id: payment.id,
- invoice_id: payment.invoice_id,
- tx_signature: body.tx_signature,
- });
-});
diff --git a/api/pump/accept-payment-prep.js b/api/pump/accept-payment-prep.js
deleted file mode 100644
index 18388c421..000000000
--- a/api/pump/accept-payment-prep.js
+++ /dev/null
@@ -1,136 +0,0 @@
-// POST /api/pump/accept-payment-prep
-//
-// Builds the unsigned tx for `acceptPayment` against an agent's
-// pump-agent-payments PDA. Caller (the payer) signs + submits. Used as the
-// pump-native settle step for X402-gated resources (see /.well-known/x402).
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { randomToken } from '../_lib/crypto.js';
-import {
- getPumpAgentOffline,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-import {
- SOLANA_USDC_MINT,
- SOLANA_USDC_MINT_DEVNET,
- toUsdcAtomics,
-} from '../payments/_config.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44), // pump.fun token mint = agent token
- payer_wallet: z.string().min(32).max(44),
- amount_usdc: z.number().positive().max(100_000),
- currency_mint: z.string().min(32).max(44).optional(), // defaults to USDC
- currency_token_program: z.string().min(32).max(44).optional(),
- user_token_account: z.string().min(32).max(44), // payer ATA
- skill_id: z.string().max(100).optional(),
- tool_name: z.string().max(100).optional(),
- duration_seconds: z.number().int().positive().max(60 * 60 * 24 * 365).default(60),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-function bnFromBigint(BN, v) {
- return new BN(v.toString());
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- // Allow both session users (browser) and bearer (MCP / agent) callers.
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- if (!session && !bearer)
- return error(res, 401, 'unauthorized', 'sign in or supply a bearer token');
- const userId = session?.id ?? bearer?.userId ?? null;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const payer = solanaPubkey(body.payer_wallet);
- const userAta = solanaPubkey(body.user_token_account);
- if (!payer) return error(res, 400, 'validation_error', 'invalid payer_wallet');
- if (!userAta) return error(res, 400, 'validation_error', 'invalid user_token_account');
-
- const [agent] = await sql`
- select id, mint, network, buyback_bps from pump_agent_mints
- where mint=${body.mint} and network=${body.network} limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
-
- const currencyStr =
- body.currency_mint ||
- (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
- const currency = solanaPubkey(currencyStr);
- if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
-
- const { offline, BN } = await getPumpAgentOffline({
- network: body.network,
- mint: body.mint,
- });
-
- // Invoice ID = random 64-bit unsigned (memo BN). Used as the PDA seed and
- // as the X402 receipt identifier downstream.
- const invoiceIdHex = (await randomToken(8)).slice(0, 16);
- const invoiceId = new BN(invoiceIdHex, 16);
-
- const startTime = Math.floor(Date.now() / 1000);
- const endTime = startTime + body.duration_seconds;
-
- const amountAtomics = toUsdcAtomics(body.amount_usdc); // bigint, USDC = 6 dp
-
- const tokenProgram = body.currency_token_program
- ? solanaPubkey(body.currency_token_program)
- : undefined;
-
- const ix = await offline.acceptPayment({
- user: payer,
- userTokenAccount: userAta,
- currencyMint: currency,
- amount: bnFromBigint(BN, amountAtomics),
- memo: invoiceId,
- startTime: new BN(startTime),
- endTime: new BN(endTime),
- ...(tokenProgram ? { tokenProgram } : {}),
- });
-
- const txBase64 = await buildUnsignedTxBase64({
- network: body.network,
- payer,
- instructions: [ix],
- });
-
- const [row] = await sql`
- insert into pump_agent_payments
- (mint_id, user_id, payer_wallet, currency_mint, amount_atomics,
- invoice_id, start_time, end_time, status, skill_id, tool_name)
- values
- (${agent.id}, ${userId}, ${body.payer_wallet}, ${currencyStr},
- ${amountAtomics.toString()}, ${invoiceId.toString()},
- to_timestamp(${startTime}), to_timestamp(${endTime}),
- 'pending', ${body.skill_id || null}, ${body.tool_name || null})
- returning id, invoice_id, start_time, end_time, status
- `;
-
- return json(res, 201, {
- payment_id: row.id,
- mint: body.mint,
- invoice_id: invoiceId.toString(),
- amount_usdc: body.amount_usdc,
- amount_atomics: amountAtomics.toString(),
- currency_mint: currencyStr,
- start_time: row.start_time,
- end_time: row.end_time,
- network: body.network,
- tx_base64: txBase64,
- instructions:
- 'Decode tx_base64, sign with payer wallet, submit, then call /api/pump/accept-payment-confirm with the tx_signature and payment_id.',
- });
-});
diff --git a/api/pump/balances.js b/api/pump/balances.js
deleted file mode 100644
index 8d9411d3d..000000000
--- a/api/pump/balances.js
+++ /dev/null
@@ -1,57 +0,0 @@
-// GET /api/pump/balances?mint=<pubkey>&currency=<mint>&network=...
-//
-// Three vault balances for an agent that has been bound to pump-agent-payments:
-// paymentVault — incoming counterparty payments
-// buybackVault — share routed to buyback (deflationary)
-// withdrawVault — share the agent owner can sweep
-// All denominated in `currency` (USDC by default).
-
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { getPumpAgent, solanaPubkey } from '../_lib/pump.js';
-import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, `http://${req.headers.host}`);
- const mintStr = url.searchParams.get('mint');
- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
- const currencyArg = url.searchParams.get('currency');
-
- const mint = solanaPubkey(mintStr);
- if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
-
- const currencyStr =
- currencyArg || (network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
- const currency = solanaPubkey(currencyStr);
- if (!currency) return error(res, 400, 'validation_error', 'invalid currency');
-
- try {
- const { agent, agentPda } = await getPumpAgent({ network, mint });
- const balances = await agent.getBalances(currency);
- const fmt = (v) =>
- v && {
- address: v.address?.toString?.() ?? String(v.address),
- balance: v.balance?.toString?.() ?? String(v.balance ?? 0),
- };
- return json(res, 200, {
- mint: mintStr,
- network,
- currency: currencyStr,
- agent_pda: agentPda?.toString?.() ?? null,
- balances: {
- payment: fmt(balances.paymentVault),
- buyback: fmt(balances.buybackVault),
- withdraw: fmt(balances.withdrawVault),
- },
- });
- } catch (err) {
- // Most common: agent not yet bound to mint → PDA missing.
- return error(res, 502, 'pump_agent_error', err.message || 'pump-agent SDK error');
- }
-});
diff --git a/api/pump/buy-confirm.js b/api/pump/buy-confirm.js
deleted file mode 100644
index 5b5aa20be..000000000
--- a/api/pump/buy-confirm.js
+++ /dev/null
@@ -1,70 +0,0 @@
-// POST /api/pump/buy-confirm
-// Verify a buy tx (built via /api/pump/buy-prep) and persist to pump_agent_trades.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { verifySignature } from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- tx_signature: z.string().min(80).max(100),
- wallet_address: z.string().min(32).max(44),
- sol: z.number().positive().max(50),
- route: z.enum(['bonding_curve', 'amm']),
- slippage_bps: z.number().int().min(0).max(5000).optional(),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [mintRow] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
- `;
- const mintId = mintRow?.id ?? null;
-
- let tx;
- try {
- tx = await verifySignature({ network: body.network, signature: body.tx_signature });
- } catch (e) {
- return error(res, e.status || 422, e.code || 'tx_failed', e.message);
- }
- const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
- if (!accountKeys.includes(body.mint))
- return error(res, 422, 'mint_not_in_tx', 'mint not in tx');
- if (!accountKeys.includes(body.wallet_address))
- return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
-
- if (mintId) {
- const lamports = BigInt(Math.floor(body.sol * 1_000_000_000));
- await sql`
- insert into pump_agent_trades
- (mint_id, user_id, wallet, direction, route, sol_amount, slippage_bps, tx_signature, network)
- values
- (${mintId}, ${user.id}, ${body.wallet_address}, 'buy', ${body.route},
- ${lamports.toString()}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
- on conflict (tx_signature, network) do nothing
- `;
- }
-
- return json(res, 200, {
- ok: true,
- tracked: !!mintId,
- mint: body.mint,
- network: body.network,
- tx_signature: body.tx_signature,
- });
-});
diff --git a/api/pump/buy-prep.js b/api/pump/buy-prep.js
deleted file mode 100644
index 3d55e2895..000000000
--- a/api/pump/buy-prep.js
+++ /dev/null
@@ -1,113 +0,0 @@
-// POST /api/pump/buy-prep
-//
-// Auto-routes between bonding-curve buy (pre-graduation) and AMM buy
-// (post-graduation), returning an unsigned tx the wallet signs and submits.
-// Body: { mint, network, sol, slippage_bps?, wallet_address }
-
-import { z } from 'zod';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import {
- getConnection,
- getPumpSdk,
- getAmmPoolState,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- sol: z.number().positive().max(50),
- slippage_bps: z.number().int().min(0).max(5000).default(100),
- wallet_address: z.string().min(32).max(44),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const userPk = solanaPubkey(body.wallet_address);
- const mintPk = solanaPubkey(body.mint);
- if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
-
- try {
- const { sdk, BN, web3 } = await getPumpSdk({ network: body.network });
- const lamports = new BN(Math.floor(body.sol * web3.LAMPORTS_PER_SOL));
- const slippage = body.slippage_bps / 10_000;
-
- // Try bonding curve.
- let buyState = null;
- try {
- if (sdk.fetchBuyState) buyState = await sdk.fetchBuyState(mintPk, userPk);
- } catch {
- buyState = null;
- }
-
- if (buyState && buyState.bondingCurve && !buyState.bondingCurve.complete) {
- const global = await sdk.fetchGlobal();
- const ixs = await sdk.buyInstructions({
- global,
- bondingCurveAccountInfo: buyState.bondingCurveAccountInfo,
- bondingCurve: buyState.bondingCurve,
- associatedUserAccountInfo: buyState.associatedUserAccountInfo,
- mint: mintPk,
- user: userPk,
- amount: new BN(0),
- solAmount: lamports,
- slippage,
- });
- const tx_base64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: userPk,
- instructions: ixs,
- });
- return json(res, 201, {
- route: 'bonding_curve',
- mint: body.mint,
- network: body.network,
- sol_in: body.sol,
- slippage_bps: body.slippage_bps,
- tx_base64,
- });
- }
-
- // AMM
- const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
- const ammMod = await import('@pump-fun/pump-swap-sdk');
- const offline = new ammMod.PumpAmmSdk();
- const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
- const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
- const ixs = await offline.buyQuoteInput(swapState, lamports, slippage);
- const tx_base64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: userPk,
- instructions: ixs,
- });
- return json(res, 201, {
- route: 'amm',
- pool: amm.poolKey.toString(),
- mint: body.mint,
- network: body.network,
- sol_in: body.sol,
- slippage_bps: body.slippage_bps,
- tx_base64,
- });
- } catch (e) {
- return error(
- res,
- e.status || 502,
- e.code || 'pump_sdk_error',
- e.message || 'failed to build buy tx',
- );
- }
-});
diff --git a/api/pump/by-agent.js b/api/pump/by-agent.js
deleted file mode 100644
index 37b93c81e..000000000
--- a/api/pump/by-agent.js
+++ /dev/null
@@ -1,63 +0,0 @@
-// GET /api/pump/by-agent?agent_id=<uuid>
-// Resolves an agent's pump mint (if launched) for the passport widget.
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, `http://${req.headers.host}`);
- const agentId = url.searchParams.get('agent_id');
- if (!agentId) return error(res, 400, 'validation_error', 'agent_id required');
-
- const [row] = await sql`
- select id, mint, network, name, symbol, buyback_bps, agent_authority,
- metadata_uri, sharing_config, created_at
- from pump_agent_mints
- where agent_id=${agentId}
- order by created_at desc limit 1
- `;
- if (!row) return json(res, 200, { data: null });
-
- const [stats] = await sql`
- select
- count(*) filter (where status='confirmed')::int as confirmed_payments,
- count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
- coalesce(sum(amount_atomics) filter (where status='confirmed'),0)::text as total_atomics,
- max(confirmed_at) filter (where status='confirmed') as last_payment_at
- from pump_agent_payments where mint_id=${row.id}
- `;
-
- const [burnRow] = await sql`
- select
- count(*) filter (where status='confirmed')::int as runs,
- coalesce(sum(burn_amount) filter (where status='confirmed'),0)::text as total_burned,
- max(created_at) as last_burn_at
- from pump_buyback_runs where mint_id=${row.id}
- `;
-
- // Burns feed (separate from payments feed) — recent confirmed buyback runs
- // for the dashboard / passport "🔥 burns" stream.
- const burnsFeed = await sql`
- select id, currency_mint, tx_signature, burn_amount, created_at
- from pump_buyback_runs
- where mint_id=${row.id} and status='confirmed'
- order by created_at desc
- limit 10
- `;
-
- return json(res, 200, {
- data: {
- ...row,
- stats: stats || { confirmed_payments: 0, unique_payers: 0, total_atomics: '0' },
- burns: burnRow || { runs: 0, total_burned: '0' },
- burns_feed: burnsFeed,
- },
- });
-});
diff --git a/api/pump/governance-prep.js b/api/pump/governance-prep.js
deleted file mode 100644
index 6136d87b2..000000000
--- a/api/pump/governance-prep.js
+++ /dev/null
@@ -1,72 +0,0 @@
-// POST /api/pump/governance-prep
-//
-// Builds an unsigned `updateBuybackBps` ix for the agent owner. Frontend signs
-// + submits with the agent authority wallet. Reputation-tied governance hook:
-// admins can also drive this from server via PUMP_GOVERNANCE_RELAYER_KEY (off
-// by default) when an agent's reputation drops below threshold — we expose
-// that path as POST /api/admin/pump/governance instead, separately.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import {
- getPumpAgentOffline,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- authority_wallet: z.string().min(32).max(44),
- new_buyback_bps: z.number().int().min(0).max(10_000),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const authority = solanaPubkey(body.authority_wallet);
- if (!authority) return error(res, 400, 'validation_error', 'invalid authority_wallet');
-
- const [row] = await sql`
- select id, user_id, agent_authority from pump_agent_mints
- where mint=${body.mint} and network=${body.network} limit 1
- `;
- if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
- if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
- if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
- return error(res, 403, 'forbidden', 'authority does not match');
- }
-
- const { offline } = await getPumpAgentOffline({ network: body.network, mint: body.mint });
- const ix = await offline.updateBuybackBps(
- { authority, buybackBps: body.new_buyback_bps },
- {}, // UpdateBuybackBpsOptions — empty default
- );
-
- const txBase64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: authority,
- instructions: [ix],
- });
-
- return json(res, 201, {
- mint: body.mint,
- network: body.network,
- new_buyback_bps: body.new_buyback_bps,
- tx_base64: txBase64,
- instructions:
- 'Sign with the agent authority wallet, submit, then optionally PATCH the local row via /api/agents/:id to refresh display.',
- });
-});
diff --git a/api/pump/launch-confirm.js b/api/pump/launch-confirm.js
deleted file mode 100644
index 2b697830b..000000000
--- a/api/pump/launch-confirm.js
+++ /dev/null
@@ -1,73 +0,0 @@
-// POST /api/pump/launch-confirm
-// Verifies the launch tx landed and persists the pump_agent_mints row.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { verifySignature } from '../_lib/pump.js';
-
-const bodySchema = z.object({
- prep_id: z.string().min(8),
- tx_signature: z.string().min(80).max(100),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [pending] = await sql`
- select id, payload from agent_registrations_pending
- where user_id=${user.id} and payload->>'prep_id'=${body.prep_id}
- and expires_at > now()
- order by created_at desc limit 1
- `;
- if (!pending) return error(res, 404, 'not_found', 'prep not found or expired');
- const p = pending.payload;
- if (p.kind !== 'pump_launch') return error(res, 400, 'wrong_kind', 'prep is not a pump launch');
-
- let tx;
- try {
- tx = await verifySignature({ network: p.network, signature: body.tx_signature });
- } catch (e) {
- return error(res, e.status || 422, e.code || 'tx_failed', e.message);
- }
- const accountKeys = tx.transaction.message.accountKeys.map((k) =>
- (k.pubkey || k).toString(),
- );
- if (!accountKeys.includes(p.mint)) {
- return error(res, 422, 'mint_not_in_tx', 'mint pubkey not present in tx');
- }
-
- const [existing] = await sql`
- select id from pump_agent_mints where mint=${p.mint} and network=${p.network} limit 1
- `;
- if (existing) return error(res, 409, 'conflict', 'mint already registered');
-
- const [row] = await sql`
- insert into pump_agent_mints
- (agent_id, user_id, network, mint, name, symbol, agent_authority, buyback_bps)
- values
- (${p.agent_id}, ${user.id}, ${p.network}, ${p.mint},
- ${p.name}, ${p.symbol}, ${p.wallet_address}, ${p.buyback_bps})
- returning id, mint, network, buyback_bps, created_at
- `;
-
- await sql`delete from agent_registrations_pending where id=${pending.id}`;
-
- return json(res, 201, {
- ok: true,
- pump_agent_mint: row,
- tx_signature: body.tx_signature,
- });
-});
diff --git a/api/pump/launch-prep.js b/api/pump/launch-prep.js
deleted file mode 100644
index 638d80ccb..000000000
--- a/api/pump/launch-prep.js
+++ /dev/null
@@ -1,174 +0,0 @@
-// POST /api/pump/launch-prep
-//
-// Builds an unsigned transaction that:
-// 1. creates a pump.fun bonding-curve token (createInstruction or
-// createAndBuyInstructions if `sol_buy_in` > 0)
-// 2. binds it to a pump-agent-payments PDA via PumpAgent.create with the
-// caller's chosen buybackBps
-//
-// The user signs + submits in their wallet, then calls launch-confirm.
-
-import { z } from 'zod';
-import { Keypair } from '@solana/web3.js';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { randomToken } from '../_lib/crypto.js';
-import {
- getPumpSdk,
- getPumpAgentOffline,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-
-const bodySchema = z.object({
- agent_id: z.string().uuid(),
- wallet_address: z.string().min(32).max(44),
- name: z.string().trim().min(1).max(32),
- symbol: z.string().trim().min(1).max(10),
- uri: z.string().url(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- buyback_bps: z.number().int().min(0).max(10_000).default(0),
- sol_buy_in: z.number().nonnegative().max(50).default(0), // optional creator initial buy, capped 50 SOL
- // Optional client-ground vanity mint address. When provided, the client
- // already holds the secret key locally and will co-sign in the wallet —
- // the server never sees the secret. When omitted, the server falls back
- // to a fresh Keypair.generate() and returns the secret key for co-sign.
- mint_address: z.string().min(32).max(44).optional(),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const creator = solanaPubkey(body.wallet_address);
- if (!creator) return error(res, 400, 'validation_error', 'invalid wallet_address');
-
- // Verify wallet linked to user.
- const [walletRow] = await sql`
- select id from user_wallets
- where user_id=${user.id} and address=${body.wallet_address} and chain_type='solana'
- limit 1
- `;
- if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');
-
- // Verify the agent belongs to this user.
- const [agent] = await sql`
- select id, name from agent_identities
- where id=${body.agent_id} and user_id=${user.id} and deleted_at is null limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
-
- // Mint pubkey: client-supplied (vanity-ground) or freshly generated.
- let mintKeypair = null;
- let mint;
- if (body.mint_address) {
- const supplied = solanaPubkey(body.mint_address);
- if (!supplied) return error(res, 400, 'validation_error', 'invalid mint_address');
- mint = supplied;
- } else {
- mintKeypair = Keypair.generate();
- mint = mintKeypair.publicKey;
- }
-
- const { sdk, BN } = await getPumpSdk({ network: body.network });
- const LAMPORTS_PER_SOL = 1_000_000_000;
-
- const instructions = [];
- if (body.sol_buy_in > 0 && sdk.createAndBuyInstructions) {
- const global = await sdk.fetchGlobal();
- const solAmount = new BN(Math.floor(body.sol_buy_in * LAMPORTS_PER_SOL));
- const pumpSdk = await import('@pump-fun/pump-sdk');
- const tokenAmount = pumpSdk.getBuyTokenAmountFromSolAmount(global, null, solAmount);
- const ixs = await sdk.createAndBuyInstructions({
- global,
- mint,
- name: body.name,
- symbol: body.symbol,
- uri: body.uri,
- creator,
- user: creator,
- solAmount,
- amount: tokenAmount,
- });
- instructions.push(...(Array.isArray(ixs) ? ixs : [ixs]));
- } else {
- const ix = await sdk.createInstruction({
- mint,
- name: body.name,
- symbol: body.symbol,
- uri: body.uri,
- creator,
- user: creator,
- });
- instructions.push(ix);
- }
-
- // Bind PumpAgent.create.
- if (body.buyback_bps > 0) {
- const { offline } = await getPumpAgentOffline({ network: body.network, mint });
- const createIx = await offline.create({
- authority: creator,
- mint,
- agentAuthority: creator,
- buybackBps: body.buyback_bps,
- });
- instructions.push(createIx);
- }
-
- const txBase64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: creator,
- instructions,
- });
-
- const prepId = await randomToken(24);
- const expiresAt = new Date(Date.now() + 30 * 60 * 1000);
-
- await sql`
- insert into agent_registrations_pending (user_id, cid, metadata_uri, payload, expires_at)
- values (
- ${user.id},
- ${mint.toBase58()},
- ${body.uri},
- ${JSON.stringify({
- kind: 'pump_launch',
- agent_id: body.agent_id,
- wallet_address: body.wallet_address,
- mint: mint.toBase58(),
- name: body.name,
- symbol: body.symbol,
- network: body.network,
- buyback_bps: body.buyback_bps,
- prep_id: prepId,
- })}::jsonb,
- ${expiresAt}
- )
- `;
-
- return json(res, 201, {
- prep_id: prepId,
- mint: mint.toBase58(),
- // Mint keypair must co-sign the tx. When server-generated, we hand
- // the secret to the frontend; when client-supplied (vanity), the
- // client already holds it and the server never sees it.
- mint_secret_key_b64: mintKeypair ? Buffer.from(mintKeypair.secretKey).toString('base64') : null,
- client_supplied_mint: !mintKeypair,
- tx_base64: txBase64,
- network: body.network,
- buyback_bps: body.buyback_bps,
- expires_at: expiresAt.toISOString(),
- instructions: mintKeypair
- ? 'Decode tx_base64 as VersionedTransaction. Sign with the mint keypair (mint_secret_key_b64) AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.'
- : 'Decode tx_base64 as VersionedTransaction. Sign with your locally-held vanity mint keypair AND the user wallet, submit, then POST /api/pump/launch-confirm with the tx_signature.',
- });
-});
diff --git a/api/pump/payments-list.js b/api/pump/payments-list.js
deleted file mode 100644
index 016c2b65b..000000000
--- a/api/pump/payments-list.js
+++ /dev/null
@@ -1,92 +0,0 @@
-// GET /api/pump/payments-list?mint=<pubkey>&network=...&limit=...
-//
-// Public read of the local pump_agent_payments index for an agent. The
-// on-chain TokenAgentPaymentInCurrency PDAs are the source of truth; this
-// endpoint exposes the cached view used by the dashboard / passport / and
-// reputation engine. Confirmed payments only by default.
-
-import { sql } from '../_lib/db.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, `http://${req.headers.host}`);
- const mint = url.searchParams.get('mint');
- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
- const limit = Math.min(Number(url.searchParams.get('limit') || 50), 500);
- const includePending = url.searchParams.get('include_pending') === '1';
-
- if (!mint) return error(res, 400, 'validation_error', 'mint required');
-
- const [agent] = await sql`
- select id, mint, network, buyback_bps from pump_agent_mints
- where mint=${mint} and network=${network} limit 1
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent mint not registered');
-
- const rows = includePending
- ? await sql`
- select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
- start_time, end_time, status, skill_id, tool_name,
- invoice_pda, tx_signature, created_at, confirmed_at
- from pump_agent_payments
- where mint_id=${agent.id}
- order by created_at desc limit ${limit}
- `
- : await sql`
- select id, payer_wallet, currency_mint, amount_atomics, invoice_id,
- start_time, end_time, status, skill_id, tool_name,
- invoice_pda, tx_signature, created_at, confirmed_at
- from pump_agent_payments
- where mint_id=${agent.id} and status='confirmed'
- order by confirmed_at desc nulls last limit ${limit}
- `;
-
- // Derive invoice PDAs for any rows that lack one (older rows pre-PDA backfill).
- // We do it lazily here so the widget can deep-link without a backfill cron.
- let pdaErrored = false;
- const needsPda = rows.filter((r) => !r.invoice_pda && r.invoice_id);
- if (needsPda.length > 0) {
- try {
- const [{ getInvoiceIdPDA }, { PublicKey }] = await Promise.all([
- import('@pump-fun/agent-payments-sdk'),
- import('@solana/web3.js'),
- ]);
- const BN = (await import('bn.js')).default || (await import('bn.js'));
- const mintPk = new PublicKey(mint);
- for (const r of needsPda) {
- try {
- const [pda] = getInvoiceIdPDA(mintPk, new BN(r.invoice_id));
- r.invoice_pda = pda.toBase58();
- } catch {
- /* skip individual failures */
- }
- }
- } catch {
- pdaErrored = true;
- }
- }
-
- const [agg] = await sql`
- select
- count(*)::int as total,
- count(*) filter (where status='confirmed')::int as confirmed,
- count(distinct payer_wallet) filter (where status='confirmed')::int as unique_payers,
- coalesce(sum(amount_atomics) filter (where status='confirmed'), 0)::text as total_atomics
- from pump_agent_payments where mint_id=${agent.id}
- `;
-
- return json(res, 200, {
- mint,
- network,
- buyback_bps: agent.buyback_bps,
- summary: agg,
- data: rows,
- });
-});
diff --git a/api/pump/portfolio.js b/api/pump/portfolio.js
deleted file mode 100644
index ab9e7ecf5..000000000
--- a/api/pump/portfolio.js
+++ /dev/null
@@ -1,137 +0,0 @@
-// GET /api/pump/portfolio?agentId=<uuid>&network=mainnet|devnet
-//
-// Real chain-direct portfolio for an agent's hot wallet. No third-party API,
-// no caching layer beyond the underlying RPC — every call queries the chain.
-//
-// Response:
-// {
-// data: {
-// address, network, lamports, sol,
-// holdings: [{ mint, amount, decimals, valueSol, priceSol }],
-// totalValueSol, totalCostBasisSol, unrealizedPnlSol, unrealizedPnlPct,
-// openPositions: [...] // joined with strategy ledger if available
-// }
-// }
-//
-// Cost-basis is read from agent_actions where source_skill='pump-fun-trade'
-// and type='buy'. If there's no recorded entry, that holding is reported with
-// costBasisSol = null (not zero — to avoid lying about PnL).
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { solanaConnection } from '../_lib/agent-pumpfun.js';
-import { PublicKey, LAMPORTS_PER_SOL } from '@solana/web3.js';
-import { makeRuntime } from '../_lib/skill-runtime.js';
-
-const TOKEN_PROGRAM_ID = new PublicKey('TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA');
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, `http://${req.headers.host}`);
- const agentId = url.searchParams.get('agentId');
- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
- if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
-
- const [agent] = await sql`
- SELECT user_id, meta FROM agent_identities
- WHERE id = ${agentId} AND deleted_at IS NULL
- `;
- if (!agent) return error(res, 404, 'not_found', 'agent not found');
- if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
- const address = agent.meta?.solana_address;
- if (!address) return error(res, 409, 'conflict', 'agent has no solana wallet');
-
- const conn = solanaConnection(network);
- const owner = new PublicKey(address);
-
- const [lamports, tokenResp, recentBuys] = await Promise.all([
- conn.getBalance(owner),
- conn.getParsedTokenAccountsByOwner(owner, { programId: TOKEN_PROGRAM_ID }),
- sql`
- SELECT payload, created_at FROM agent_actions
- WHERE agent_id = ${agentId}
- AND type IN ('pumpfun.buy', 'buy')
- ORDER BY created_at DESC
- LIMIT 500
- `.catch(() => []),
- ]);
-
- const holdings = tokenResp.value
- .map((acc) => {
- const info = acc.account.data.parsed.info;
- return {
- mint: info.mint,
- amount: info.tokenAmount.uiAmount ?? 0,
- decimals: info.tokenAmount.decimals,
- };
- })
- .filter((h) => h.amount > 0);
-
- // Cost basis from recorded buys.
- const basisByMint = new Map();
- for (const row of recentBuys) {
- const p = row.payload || {};
- if (!p.mint) continue;
- const prev = basisByMint.get(p.mint) ?? { sol: 0, tokens: 0 };
- prev.sol += Number(p.amountSol) || 0;
- prev.tokens += Number(p.amountTokens) || 0;
- basisByMint.set(p.mint, prev);
- }
-
- // Live price per holding via the read-only pump-fun MCP (parallelized).
- const rt = makeRuntime();
- const priced = await Promise.all(holdings.map(async (h) => {
- const [curve, basis] = [
- await rt.invoke('pump-fun.getBondingCurve', { mint: h.mint }).catch(() => ({ ok: false })),
- basisByMint.get(h.mint),
- ];
- const priceSol = curve?.ok ? (curve.data?.priceSol ?? curve.data?.price ?? null) : null;
- const valueSol = priceSol != null ? priceSol * h.amount : null;
- const costBasisSol = basis ? basis.sol : null;
- const unrealizedSol = valueSol != null && costBasisSol != null ? valueSol - costBasisSol : null;
- return {
- ...h,
- priceSol,
- valueSol,
- costBasisSol,
- unrealizedPnlSol: unrealizedSol,
- unrealizedPnlPct: unrealizedSol != null && costBasisSol > 0 ? (unrealizedSol / costBasisSol) * 100 : null,
- };
- }));
-
- const totalValueSol = priced.reduce((s, p) => s + (p.valueSol ?? 0), 0);
- const totalCostBasisSol = priced.reduce((s, p) => s + (p.costBasisSol ?? 0), 0);
- const unrealizedPnlSol = totalValueSol - totalCostBasisSol;
-
- return json(res, 200, {
- data: {
- address,
- network,
- lamports,
- sol: lamports / LAMPORTS_PER_SOL,
- holdings: priced,
- totalValueSol,
- totalCostBasisSol,
- unrealizedPnlSol,
- unrealizedPnlPct: totalCostBasisSol > 0 ? (unrealizedPnlSol / totalCostBasisSol) * 100 : null,
- },
- });
-});
diff --git a/api/pump/quote.js b/api/pump/quote.js
deleted file mode 100644
index 0784f8a43..000000000
--- a/api/pump/quote.js
+++ /dev/null
@@ -1,191 +0,0 @@
-// GET /api/pump/quote?mint=<pubkey>&network=mainnet|devnet&sol=<amount>&direction=buy|sell
-//
-// Read-only price/quote for a pump.fun token. Auto-routes between bonding-curve
-// (pre-graduation) via @pump-fun/pump-sdk and AMM (post-graduation) via
-// @pump-fun/pump-swap-sdk. No wallet, no signing.
-
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { getPumpSdk, getAmmPoolState, solanaPubkey } from '../_lib/pump.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, `http://${req.headers.host}`);
- const mintStr = url.searchParams.get('mint');
- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
- const direction = url.searchParams.get('direction') === 'sell' ? 'sell' : 'buy';
- const solRaw = url.searchParams.get('sol');
- const tokenRaw = url.searchParams.get('token');
- const slippageRaw = url.searchParams.get('slippage_bps');
- const slippageBps = Number.isFinite(Number(slippageRaw))
- ? Math.max(0, Math.min(5000, Number(slippageRaw)))
- : 100;
- const slippage = slippageBps / 10_000;
-
- const mint = solanaPubkey(mintStr);
- if (!mint) return error(res, 400, 'validation_error', 'invalid mint');
-
- try {
- // Try bonding curve first.
- const { sdk, BN, web3 } = await getPumpSdk({ network });
- const LAMPORTS_PER_SOL = web3.LAMPORTS_PER_SOL || 1_000_000_000;
-
- let curve = null;
- try {
- if (sdk.fetchBuyState) {
- const state = await sdk.fetchBuyState(mint, mint); // any pubkey works for read
- curve = state.bondingCurve;
- } else if (sdk.fetchBondingCurve) {
- curve = await sdk.fetchBondingCurve(mint);
- }
- } catch {
- curve = null;
- }
-
- if (curve && !curve.complete) {
- const global = typeof sdk.fetchGlobal === 'function' ? await sdk.fetchGlobal() : null;
- const pumpSdk = await import('@pump-fun/pump-sdk');
- let quote = null;
-
- if (direction === 'buy' && solRaw) {
- const sol = Number(solRaw);
- if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');
- const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL));
- const tokens = pumpSdk.getBuyTokenAmountFromSolAmount(global, curve, lamports);
- quote = { sol_in: sol, tokens_out: tokens.toString(), source: 'bonding_curve' };
- } else if (direction === 'sell' && tokenRaw) {
- const tokens = new BN(tokenRaw);
- const lamports = pumpSdk.getSellSolAmountFromTokenAmount(global, curve, tokens);
- quote = {
- tokens_in: tokenRaw,
- sol_out: Number(lamports.toString()) / LAMPORTS_PER_SOL,
- source: 'bonding_curve',
- };
- }
-
- return json(res, 200, {
- mint: mintStr,
- network,
- graduated: false,
- bonding_curve: {
- real_sol_reserves: curve.realSolReserves?.toString?.() ?? null,
- real_token_reserves: curve.realTokenReserves?.toString?.() ?? null,
- virtual_sol_reserves: curve.virtualSolReserves?.toString?.() ?? null,
- virtual_token_reserves: curve.virtualTokenReserves?.toString?.() ?? null,
- complete: curve.complete ?? false,
- },
- quote,
- });
- }
-
- // Post-graduation: AMM via canonical pump.fun pool (quote = WSOL).
- let amm;
- try {
- amm = await getAmmPoolState({ network, mint });
- } catch (e) {
- if (e.code === 'pool_not_found') {
- return json(res, 200, {
- mint: mintStr,
- network,
- graduated: true,
- pool: null,
- quote: null,
- note: 'No bonding curve and no canonical AMM pool — token may not be a pump.fun mint or has not graduated yet',
- });
- }
- throw e;
- }
-
- const {
- pool,
- poolKey,
- baseReserve,
- quoteReserve,
- baseMintAccount,
- globalConfig,
- feeConfig,
- } = amm;
- const LAMPORTS_PER_SOL_AMM = 1_000_000_000;
- const ammSdk = await import('@pump-fun/pump-swap-sdk');
- let quote = null;
-
- if (direction === 'buy' && solRaw) {
- const sol = Number(solRaw);
- if (!(sol > 0)) return error(res, 400, 'validation_error', 'sol must be > 0');
- const lamports = new BN(Math.floor(sol * LAMPORTS_PER_SOL_AMM));
- const r = ammSdk.buyQuoteInput({
- quote: lamports,
- slippage,
- baseReserve,
- quoteReserve,
- globalConfig,
- baseMintAccount,
- baseMint: pool.baseMint,
- coinCreator: pool.coinCreator,
- creator: pool.creator,
- feeConfig,
- });
- quote = {
- sol_in: sol,
- tokens_out: r.base?.toString?.() ?? null,
- min_tokens_out: r.uiBase?.toString?.() ?? r.minBase?.toString?.() ?? null,
- slippage_bps: slippageBps,
- source: 'amm',
- };
- } else if (direction === 'sell' && tokenRaw) {
- const tokens = new BN(tokenRaw);
- const r = ammSdk.sellBaseInput({
- base: tokens,
- slippage,
- baseReserve,
- quoteReserve,
- globalConfig,
- baseMintAccount,
- baseMint: pool.baseMint,
- coinCreator: pool.coinCreator,
- creator: pool.creator,
- feeConfig,
- });
- const lamportsOut = r.quote ?? r.uiQuote ?? r.minQuote;
- quote = {
- tokens_in: tokenRaw,
- sol_out:
- lamportsOut != null
- ? Number(lamportsOut.toString()) / LAMPORTS_PER_SOL_AMM
- : null,
- min_sol_out: (r.minQuote ?? r.uiQuote)?.toString
- ? Number((r.minQuote ?? r.uiQuote).toString()) / LAMPORTS_PER_SOL_AMM
- : null,
- slippage_bps: slippageBps,
- source: 'amm',
- };
- }
-
- return json(res, 200, {
- mint: mintStr,
- network,
- graduated: true,
- pool: {
- address: poolKey.toString(),
- base: pool.baseMint.toString(),
- quote: pool.quoteMint.toString(),
- base_reserve: baseReserve.toString(),
- quote_reserve: quoteReserve.toString(),
- lp_supply: pool.lpSupply?.toString?.() ?? null,
- },
- quote,
- });
- } catch (err) {
- return error(
- res,
- err.status || 502,
- err.code || 'pump_sdk_error',
- err.message || 'pump.fun SDK error',
- );
- }
-});
diff --git a/api/pump/sell-confirm.js b/api/pump/sell-confirm.js
deleted file mode 100644
index cb78fbd24..000000000
--- a/api/pump/sell-confirm.js
+++ /dev/null
@@ -1,69 +0,0 @@
-// POST /api/pump/sell-confirm
-// Verify a sell tx (built via /api/pump/sell-prep) and persist to pump_agent_trades.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { verifySignature } from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- tx_signature: z.string().min(80).max(100),
- wallet_address: z.string().min(32).max(44),
- tokens: z.string().regex(/^\d+$/),
- route: z.enum(['bonding_curve', 'amm']),
- slippage_bps: z.number().int().min(0).max(5000).optional(),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [mintRow] = await sql`
- select id from pump_agent_mints where mint=${body.mint} and network=${body.network} limit 1
- `;
- const mintId = mintRow?.id ?? null;
-
- let tx;
- try {
- tx = await verifySignature({ network: body.network, signature: body.tx_signature });
- } catch (e) {
- return error(res, e.status || 422, e.code || 'tx_failed', e.message);
- }
- const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
- if (!accountKeys.includes(body.mint))
- return error(res, 422, 'mint_not_in_tx', 'mint not in tx');
- if (!accountKeys.includes(body.wallet_address))
- return error(res, 422, 'wallet_not_in_tx', 'wallet not in tx');
-
- if (mintId) {
- await sql`
- insert into pump_agent_trades
- (mint_id, user_id, wallet, direction, route, token_amount, slippage_bps, tx_signature, network)
- values
- (${mintId}, ${user.id}, ${body.wallet_address}, 'sell', ${body.route},
- ${body.tokens}, ${body.slippage_bps ?? null}, ${body.tx_signature}, ${body.network})
- on conflict (tx_signature, network) do nothing
- `;
- }
-
- return json(res, 200, {
- ok: true,
- tracked: !!mintId,
- mint: body.mint,
- network: body.network,
- tx_signature: body.tx_signature,
- });
-});
diff --git a/api/pump/sell-prep.js b/api/pump/sell-prep.js
deleted file mode 100644
index eecb336d9..000000000
--- a/api/pump/sell-prep.js
+++ /dev/null
@@ -1,109 +0,0 @@
-// POST /api/pump/sell-prep
-//
-// Auto-routes between bonding-curve sell and AMM sell. Returns unsigned tx.
-// Body: { mint, network, tokens, slippage_bps?, wallet_address }
-
-import { z } from 'zod';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import {
- getConnection,
- getPumpSdk,
- getAmmPoolState,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- tokens: z.string().regex(/^\d+$/, 'tokens must be a base-units integer string'),
- slippage_bps: z.number().int().min(0).max(5000).default(100),
- wallet_address: z.string().min(32).max(44),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const userPk = solanaPubkey(body.wallet_address);
- const mintPk = solanaPubkey(body.mint);
- if (!userPk || !mintPk) return error(res, 400, 'validation_error', 'invalid pubkeys');
-
- try {
- const { sdk, BN } = await getPumpSdk({ network: body.network });
- const tokens = new BN(body.tokens);
- const slippage = body.slippage_bps / 10_000;
-
- let sellState = null;
- try {
- if (sdk.fetchSellState) sellState = await sdk.fetchSellState(mintPk, userPk);
- } catch {
- sellState = null;
- }
-
- if (sellState && sellState.bondingCurve && !sellState.bondingCurve.complete) {
- const global = await sdk.fetchGlobal();
- const ixs = await sdk.sellInstructions({
- global,
- bondingCurveAccountInfo: sellState.bondingCurveAccountInfo,
- bondingCurve: sellState.bondingCurve,
- mint: mintPk,
- user: userPk,
- amount: tokens,
- solAmount: new BN(0),
- slippage,
- });
- const tx_base64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: userPk,
- instructions: ixs,
- });
- return json(res, 201, {
- route: 'bonding_curve',
- mint: body.mint,
- network: body.network,
- tokens_in: body.tokens,
- slippage_bps: body.slippage_bps,
- tx_base64,
- });
- }
-
- const amm = await getAmmPoolState({ network: body.network, mint: mintPk });
- const ammMod = await import('@pump-fun/pump-swap-sdk');
- const offline = new ammMod.PumpAmmSdk();
- const onlineAmm = new ammMod.OnlinePumpAmmSdk(getConnection({ network: body.network }));
- const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
- const ixs = await offline.sellBaseInput(swapState, tokens, slippage);
- const tx_base64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: userPk,
- instructions: ixs,
- });
- return json(res, 201, {
- route: 'amm',
- pool: amm.poolKey.toString(),
- mint: body.mint,
- network: body.network,
- tokens_in: body.tokens,
- slippage_bps: body.slippage_bps,
- tx_base64,
- });
- } catch (e) {
- return error(
- res,
- e.status || 502,
- e.code || 'pump_sdk_error',
- e.message || 'failed to build sell tx',
- );
- }
-});
diff --git a/api/pump/strategy-backtest.js b/api/pump/strategy-backtest.js
deleted file mode 100644
index 6118b102a..000000000
--- a/api/pump/strategy-backtest.js
+++ /dev/null
@@ -1,50 +0,0 @@
-// POST /api/pump/strategy-backtest
-// Body: { strategy, mints?: string[], sinceMs?: number, limit?: number }
-//
-// Replays a strategy against historical pump.fun trade data via the read-only
-// pump-fun skill (which proxies a public MCP — no env vars required). When
-// `mints` is omitted, the candidate set is sourced from the strategy's
-// `scan.kind` (newTokens | trending | mintList).
-
-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { makeRuntime } from '../_lib/skill-runtime.js';
-
-async function resolveMints(invoke, strategy, explicit, limit) {
- if (Array.isArray(explicit) && explicit.length) return explicit;
- const scan = strategy?.scan ?? {};
- if (scan.kind === 'mintList' && Array.isArray(scan.mints)) return scan.mints;
- const tool = scan.kind === 'trending' ? 'pump-fun.getTrendingTokens' : 'pump-fun.getNewTokens';
- const r = await invoke(tool, { limit: limit ?? scan.limit ?? 20 });
- if (!r.ok) throw new Error(`scan failed: ${r.error}`);
- const items = r.data?.tokens ?? r.data ?? [];
- return items.map((t) => t.mint ?? t.address).filter(Boolean);
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['POST'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = await readJson(req);
- if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
-
- const rt = makeRuntime();
- let mints;
- try {
- mints = await resolveMints(rt.invoke, body.strategy, body.mints, body.limit);
- } catch (e) {
- return error(res, 502, 'upstream_error', e.message);
- }
- if (!mints.length) return error(res, 422, 'no_candidates', 'no mints to backtest');
-
- const { backtestStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
- const result = await backtestStrategy(
- { strategy: body.strategy, mints, sinceMs: body.sinceMs ?? 0 },
- { skills: { invoke: rt.invoke }, memory: { note: () => {} } },
- );
- if (!result.ok) return error(res, 400, 'validation_error', result.error);
- return json(res, 200, { data: { ...result.data, mintsUsed: mints } });
-});
diff --git a/api/pump/strategy-close-all.js b/api/pump/strategy-close-all.js
deleted file mode 100644
index d7cf9dea4..000000000
--- a/api/pump/strategy-close-all.js
+++ /dev/null
@@ -1,73 +0,0 @@
-// POST /api/pump/strategy-close-all
-//
-// Body:
-// agentId: string required
-// network: 'mainnet' | 'devnet' default 'mainnet'
-// mints?: string[] optional: only close these mints
-// simulate?: boolean dry-run; emit intended sells
-//
-// Loads the agent's hot wallet, enumerates SPL holdings, and sells each
-// position 100% via pump-fun-trade.sellToken. Returns per-mint result.
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { makeRuntime } from '../_lib/skill-runtime.js';
-import { loadWallet } from '../_lib/solana-wallet.js';
-
-const RPC = {
- mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',
- devnet: process.env.SOLANA_DEVNET_RPC || 'https://api.devnet.solana.com',
-};
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = await readJson(req);
- if (!body?.agentId) return error(res, 400, 'validation_error', 'agentId required');
- const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
-
- const [row] = await sql`
- SELECT user_id, meta FROM agent_identities
- WHERE id = ${body.agentId} AND deleted_at IS NULL
- `;
- if (!row) return error(res, 404, 'not_found', 'agent not found');
- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');
- const enc = row.meta?.encrypted_solana_secret;
- if (!enc) return error(res, 409, 'conflict', 'agent has no solana wallet');
-
- const wallet = await loadWallet(enc);
- const rt = makeRuntime({
- wallet,
- agentId: body.agentId,
- signerAddress: wallet.publicKey.toBase58(),
- configOverrides: {
- 'pump-fun-trade': { rpc: RPC[network] },
- 'solana-wallet': { rpc: RPC[network] },
- },
- });
-
- const { closeAllPositions } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
- const result = await closeAllPositions(
- { mints: body.mints, simulate: !!body.simulate },
- { skills: { invoke: rt.invoke }, wallet, memory: { note: () => {} } },
- );
- if (!result.ok) return error(res, 400, 'sell_failed', result.error);
- return json(res, 200, { data: result.data });
-});
diff --git a/api/pump/strategy-run.js b/api/pump/strategy-run.js
deleted file mode 100644
index 64a1bbcb6..000000000
--- a/api/pump/strategy-run.js
+++ /dev/null
@@ -1,149 +0,0 @@
-// POST /api/pump/strategy-run (Server-Sent Events)
-//
-// Body:
-// strategy: <spec> required
-// durationSec: number 5..600
-// mode: 'simulate' | 'live' default 'simulate'
-// agentId: string required when mode='live'
-// network: 'mainnet' | 'devnet' default 'mainnet'
-//
-// In 'simulate' mode the read-only pump-fun MCP is queried for real holder /
-// curve / creator data, but trades are not signed (a SIMULATED:* sig is
-// returned so the orchestrator state machine still progresses). This is a
-// genuine dry-run against live chain state.
-//
-// In 'live' mode the caller must own an agent identity with a provisioned
-// Solana wallet (see /api/agents/:id/solana). The encrypted secret is loaded
-// server-side and used to actually sign + send buys/sells via the
-// pump-fun-trade skill.
-//
-// Each scan/exit/entry decision is streamed as it happens via SSE. A final
-// `event: done` carries the summary.
-
-import { sql } from '../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
-import { cors, method, error, readJson } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { makeRuntime } from '../_lib/skill-runtime.js';
-import { loadWallet } from '../_lib/solana-wallet.js';
-import { checkBuyAllowed } from '../_lib/agent-spend-policy.js';
-
-const RPC = {
- mainnet: process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com',
- devnet: process.env.SOLANA_DEVNET_RPC || 'https://api.devnet.solana.com',
-};
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) return { userId: session.id };
- const bearer = await authenticateBearer(extractBearer(req));
- if (bearer) return { userId: bearer.userId };
- return null;
-}
-
-async function loadAgentWallet(agentId, userId) {
- const [row] = await sql`
- SELECT user_id, meta FROM agent_identities
- WHERE id = ${agentId} AND deleted_at IS NULL
- `;
- if (!row) throw Object.assign(new Error('agent not found'), { status: 404 });
- if (row.user_id !== userId) throw Object.assign(new Error('not your agent'), { status: 403 });
- const enc = row.meta?.encrypted_solana_secret;
- if (!enc) throw Object.assign(new Error('agent has no solana wallet — provision via /api/agents/:id/solana'), { status: 409 });
- const wallet = await loadWallet(enc);
- return { wallet, address: wallet.publicKey.toBase58(), meta: row.meta };
-}
-
-export default async function handler(req, res) {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- let body;
- try { body = await readJson(req); }
- catch (e) { return error(res, 400, 'validation_error', e.message); }
-
- if (!body?.strategy) return error(res, 400, 'validation_error', 'strategy required');
- const durationSec = Math.max(5, Math.min(600, Number(body.durationSec) || 30));
- const mode = body.mode === 'live' ? 'live' : 'simulate';
- const network = body.network === 'devnet' ? 'devnet' : 'mainnet';
-
- let wallet = null, walletAddress = null, agentMeta = null;
- if (mode === 'live') {
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required for live mode');
- if (!body.agentId) return error(res, 400, 'validation_error', 'agentId required for live mode');
- try {
- const r = await loadAgentWallet(body.agentId, auth.userId);
- wallet = r.wallet;
- walletAddress = r.address;
- agentMeta = r.meta;
- } catch (e) {
- return error(res, e.status ?? 500, e.status === 409 ? 'conflict' : 'unauthorized', e.message);
- }
- }
-
- res.statusCode = 200;
- res.setHeader('content-type', 'text/event-stream');
- res.setHeader('cache-control', 'no-cache, no-transform');
- res.setHeader('connection', 'keep-alive');
- res.setHeader('access-control-allow-origin', '*');
- const send = (event, data) => {
- res.write(`event: ${event}\n`);
- res.write(`data: ${JSON.stringify(data)}\n\n`);
- };
-
- let aborted = false;
- req.on('close', () => { aborted = true; });
-
- const rt = makeRuntime({
- wallet,
- agentId: mode === 'live' ? body.agentId : undefined,
- signerAddress: walletAddress,
- configOverrides: {
- 'pump-fun-trade': { rpc: RPC[network] },
- 'solana-wallet': { rpc: RPC[network] },
- },
- onEvent: (e) => send('memory', e),
- });
-
- send('start', { durationSec, mode, network, walletAddress });
-
- const { runStrategy } = await import('../../examples/skills/pump-fun-strategy/handlers.js');
- const ctx = {
- skills: { invoke: rt.invoke },
- skillConfig: { defaultPollMs: Math.max(1500, Number(body.pollMs) || 3000) },
- memory: { note: (tag, value) => send('memory', { tag, value }) },
- wallet,
- };
-
- const policyGuard = mode === 'live'
- ? async ({ mint, amountSol }) => {
- const block = await checkBuyAllowed({ agentId: body.agentId, meta: agentMeta, mint, solAmount: amountSol });
- return block ? { code: block.code, msg: block.msg } : null;
- }
- : null;
-
- const abortController = new AbortController();
- req.on('close', () => abortController.abort());
-
- try {
- const result = await runStrategy(
- {
- strategy: body.strategy,
- durationSec,
- simulate: mode === 'simulate',
- onLog: (entry) => { if (!aborted) send('log', entry); },
- policyGuard,
- abortSignal: abortController.signal,
- },
- ctx,
- );
- send('done', result.data);
- } catch (e) {
- send('error', { message: e.message });
- }
- res.end();
-}
diff --git a/api/pump/strategy-validate.js b/api/pump/strategy-validate.js
deleted file mode 100644
index ac2a36d36..000000000
--- a/api/pump/strategy-validate.js
+++ /dev/null
@@ -1,25 +0,0 @@
-// POST /api/pump/strategy-validate
-// Body: { strategy: <spec> }
-// Returns: { data: { filterCount, exitCount, filters[], exits[] } } or 400 with parse error.
-
-import { cors, json, method, wrap, error, readJson } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { makeRuntime } from '../_lib/skill-runtime.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['POST'])) return;
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = await readJson(req);
- if (!body?.strategy || typeof body.strategy !== 'object') {
- return error(res, 400, 'validation_error', 'strategy required');
- }
-
- const rt = makeRuntime();
- const r = await rt.invoke('pump-fun-strategy.validateStrategy', { strategy: body.strategy });
- if (!r.ok) return error(res, 400, 'validation_error', r.error);
- return json(res, 200, { data: r.data });
-});
diff --git a/api/pump/withdraw-confirm.js b/api/pump/withdraw-confirm.js
deleted file mode 100644
index 76b8b35c8..000000000
--- a/api/pump/withdraw-confirm.js
+++ /dev/null
@@ -1,62 +0,0 @@
-// POST /api/pump/withdraw-confirm
-// Verify the withdraw tx landed and acknowledge it. Symmetric with
-// accept-payment-confirm / launch-confirm. The on-chain tx is the canonical
-// receipt — we do not persist a row, only verify ownership + tx success.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import { verifySignature } from '../_lib/pump.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- tx_signature: z.string().min(80).max(100),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
-
- const [row] = await sql`
- select id, mint, user_id, agent_authority, network from pump_agent_mints
- where mint=${body.mint} and network=${body.network} limit 1
- `;
- if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
- if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
-
- let tx;
- try {
- tx = await verifySignature({ network: body.network, signature: body.tx_signature });
- } catch (e) {
- return error(res, e.status || 422, e.code || 'tx_failed', e.message);
- }
-
- const accountKeys = tx.transaction.message.accountKeys.map((k) => (k.pubkey || k).toString());
- if (!accountKeys.includes(body.mint)) {
- return error(res, 422, 'mint_not_in_tx', 'mint not present in tx accounts');
- }
- if (row.agent_authority && !accountKeys.includes(row.agent_authority)) {
- return error(res, 422, 'authority_not_in_tx', 'agent authority not present in tx');
- }
-
- return json(res, 200, {
- ok: true,
- mint: body.mint,
- network: body.network,
- tx_signature: body.tx_signature,
- slot: tx.slot ?? null,
- block_time: tx.blockTime ?? null,
- });
-});
diff --git a/api/pump/withdraw-prep.js b/api/pump/withdraw-prep.js
deleted file mode 100644
index 3cf09f26a..000000000
--- a/api/pump/withdraw-prep.js
+++ /dev/null
@@ -1,86 +0,0 @@
-// POST /api/pump/withdraw-prep
-// Builds an unsigned `withdraw` ix the agent owner signs to sweep withdrawVault.
-
-import { z } from 'zod';
-import { sql } from '../_lib/db.js';
-import { getSessionUser } from '../_lib/auth.js';
-import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { limits, clientIp } from '../_lib/rate-limit.js';
-import { parse } from '../_lib/validate.js';
-import {
- getPumpAgentOffline,
- buildUnsignedTxBase64,
- solanaPubkey,
-} from '../_lib/pump.js';
-import { SOLANA_USDC_MINT, SOLANA_USDC_MINT_DEVNET } from '../payments/_config.js';
-
-const bodySchema = z.object({
- mint: z.string().min(32).max(44),
- authority_wallet: z.string().min(32).max(44),
- receiver_ata: z.string().min(32).max(44),
- currency_mint: z.string().min(32).max(44).optional(),
- currency_token_program: z.string().min(32).max(44).optional(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
-});
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const user = await getSessionUser(req);
- if (!user) return error(res, 401, 'unauthorized', 'sign in required');
-
- const rl = await limits.authIp(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const body = parse(bodySchema, await readJson(req));
- const authority = solanaPubkey(body.authority_wallet);
- const receiverAta = solanaPubkey(body.receiver_ata);
- if (!authority || !receiverAta)
- return error(res, 400, 'validation_error', 'invalid pubkeys');
-
- const [row] = await sql`
- select m.id, m.mint, m.user_id, m.agent_authority, m.network from pump_agent_mints m
- where m.mint=${body.mint} and m.network=${body.network} limit 1
- `;
- if (!row) return error(res, 404, 'not_found', 'agent mint not registered');
- if (row.user_id !== user.id) return error(res, 403, 'forbidden', 'not your agent');
- if (row.agent_authority && row.agent_authority !== body.authority_wallet) {
- return error(res, 403, 'forbidden', 'authority does not match');
- }
-
- const currencyStr =
- body.currency_mint ||
- (body.network === 'devnet' ? SOLANA_USDC_MINT_DEVNET : SOLANA_USDC_MINT);
- const currency = solanaPubkey(currencyStr);
- if (!currency) return error(res, 400, 'validation_error', 'invalid currency_mint');
-
- const { offline } = await getPumpAgentOffline({
- network: body.network,
- mint: body.mint,
- });
-
- const tokenProgram = body.currency_token_program
- ? solanaPubkey(body.currency_token_program)
- : undefined;
-
- const ix = await offline.withdraw({
- authority,
- currencyMint: currency,
- receiverAta,
- ...(tokenProgram ? { tokenProgram } : {}),
- });
-
- const txBase64 = await buildUnsignedTxBase64({
- network: body.network,
- payer: authority,
- instructions: [ix],
- });
-
- return json(res, 201, {
- mint: body.mint,
- network: body.network,
- currency_mint: currencyStr,
- tx_base64: txBase64,
- });
-});
diff --git a/api/widgets/[id]/chat.js b/api/widgets/[id]/[action].js
similarity index 58%
rename from api/widgets/[id]/chat.js
rename to api/widgets/[id]/[action].js
index c494368ea..e222365a5 100644
--- a/api/widgets/[id]/chat.js
+++ b/api/widgets/[id]/[action].js
@@ -1,33 +1,41 @@
-/**
- * POST /api/widgets/:id/chat
- * --------------------------
- * Public visitor chat for a Talking Agent widget. The widget owner authors
- * the system prompt and brain config; the visitor never sees an API key.
- *
- * Body: { message: string, history?: [{ role: 'user'|'assistant', content }] }
- * Response: SSE stream with `event: message` chunks ({ reply, actions }) and
- * a final `event: done`. Single-shot for now (Anthropic call is
- * non-streaming) but the SSE shape lets us upgrade later without
- * breaking the client.
- *
- * Brain modes:
- * - none → server returns a polite "no brain configured" reply
- * - anthropic→ server calls Anthropic with `process.env.ANTHROPIC_API_KEY`
- * - custom → server POSTs to widget owner's HTTPS proxyURL
- *
- * Owner previewing in Studio (session matches widget.user_id) bypasses the
- * visitor rate limit so live testing isn't throttled.
- */
+// Dispatcher for /api/widgets/:id/:action
+// Vercel populates req.query.id (from [id] parent dir, or via vercel.json
+// rewrites) and req.query.action (from [action] filename) automatically.
+// Each handler below is unchanged from its prior single-file form.
+
+import crypto from 'node:crypto';
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
-import { getSessionUser } from '../../_lib/auth.js';
+import {
+ getSessionUser,
+ authenticateBearer,
+ extractBearer,
+ hasScope,
+} from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { captureException } from '../../_lib/sentry.js';
import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
+import { decorate } from '../index.js';
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action;
+ switch (action) {
+ case 'chat':
+ return handleChat(req, res);
+ case 'duplicate':
+ return handleDuplicate(req, res);
+ case 'stats':
+ return handleStats(req, res);
+ default:
+ return error(res, 404, 'not_found', 'unknown widget action');
+ }
+});
+
+// ── chat ───────────────────────────────────────────────────────────────────
const ANTHROPIC_URL = 'https://api.anthropic.com/v1/messages';
const DEFAULT_MODEL = 'claude-sonnet-4-6';
@@ -84,11 +92,11 @@ const SKILL_TOOLS = [
},
];
-export default wrap(async (req, res) => {
+async function handleChat(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
- const widgetId = idFromReq(req);
+ const widgetId = chatIdFromReq(req);
if (!widgetId) return error(res, 400, 'invalid_request', 'id required');
const widget = await loadWidget(widgetId);
@@ -168,7 +176,7 @@ export default wrap(async (req, res) => {
// Best-effort telemetry — count only, never content.
logChatEvent(widgetId).catch(() => {});
-});
+}
// ── Brain dispatchers ──────────────────────────────────────────────────────
@@ -353,7 +361,7 @@ function writeSse(res, event, data) {
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
-function idFromReq(req) {
+function chatIdFromReq(req) {
const fromQuery = req.query?.id;
if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
const path = new URL(req.url, 'http://x').pathname;
@@ -364,3 +372,192 @@ function idFromReq(req) {
function clampInt(n, min, max) {
return Math.min(max, Math.max(min, n));
}
+
+// ── duplicate ──────────────────────────────────────────────────────────────
+
+async function handleDuplicate(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const id = duplicateIdFromReq(req);
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveDuplicateAuth(req);
+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:write'))
+ return error(res, 403, 'insufficient_scope', 'avatars:write required');
+ }
+
+ const rl = await limits.widgetWrite(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [src] = await sql`
+ select id, type, name, config, avatar_id, is_public
+ from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!src) return error(res, 404, 'not_found', 'widget not found or not yours');
+
+ const newId = 'wdgt_' + crypto.randomBytes(9).toString('base64url');
+ const newName = trim(`${src.name} (copy)`, 120);
+
+ const [row] = await sql`
+ insert into widgets (id, user_id, avatar_id, type, name, config, is_public)
+ values (${newId}, ${auth.userId}, ${src.avatar_id}, ${src.type}, ${newName},
+ ${JSON.stringify(src.config || {})}::jsonb, ${src.is_public})
+ returning id, user_id, avatar_id, type, name, config, is_public, view_count, created_at, updated_at
+ `;
+
+ return json(res, 201, { widget: decorate(row) });
+}
+
+function trim(s, max) {
+ return s.length <= max ? s : s.slice(0, max);
+}
+
+function duplicateIdFromReq(req) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const m = path.match(/\/api\/widgets\/([^/]+)\/duplicate/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveDuplicateAuth(req) {
+ const session = await getSessionUser(req);
+ if (session)
+ return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ return await authenticateBearer(extractBearer(req));
+}
+
+// ── stats ──────────────────────────────────────────────────────────────────
+
+async function handleStats(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const id = statsIdFromReq(req);
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveStatsAuth(req);
+ if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
+ if (auth.source === 'oauth' || auth.source === 'apikey') {
+ if (!hasScope(auth.scope, 'avatars:read'))
+ return error(res, 403, 'insufficient_scope', 'avatars:read required');
+ }
+
+ // Ownership check — never 404 vs 403 leak: collapse to 404 either way.
+ const [w] = await sql`
+ select id, type, view_count
+ from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null
+ limit 1
+ `;
+ if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');
+
+ const [recentViews, topReferers, topCountries, lastViewed, chatCount] = await Promise.all([
+ recentViewsByDay(id),
+ topAggregates(id, 'referer_host'),
+ topAggregates(id, 'country'),
+ lastViewedAt(id),
+ chatCountFor(id, w.type),
+ ]);
+
+ res.setHeader('cache-control', 'private, max-age=30');
+ return json(res, 200, {
+ stats: {
+ view_count: Number(w.view_count || 0),
+ last_viewed_at: lastViewed,
+ recent_views_7d: recentViews,
+ top_referers: topReferers,
+ top_countries: topCountries,
+ chat_count: chatCount,
+ },
+ });
+}
+
+async function recentViewsByDay(id) {
+ // Always return 8 days (today + previous 7) so the sparkline doesn't have
+ // to reason about gaps. 0-fill missing days from the actual rows.
+ const days = [];
+ const today = startOfUtcDay(new Date());
+ for (let i = 7; i >= 0; i--) {
+ const d = new Date(today.getTime() - i * 86400_000);
+ days.push({ day: d.toISOString().slice(0, 10), count: 0 });
+ }
+ try {
+ const rows = await sql`
+ select date_trunc('day', created_at)::date::text as day, count(*)::bigint as count
+ from widget_views
+ where widget_id = ${id} and created_at >= ${days[0].day}::date
+ group by 1 order by 1
+ `;
+ const idx = new Map(days.map((d, i) => [d.day, i]));
+ for (const r of rows) {
+ const i = idx.get(r.day);
+ if (i !== undefined) days[i].count = Number(r.count);
+ }
+ } catch (err) {
+ if (!/relation .* does not exist/i.test(err?.message || '')) throw err;
+ }
+ return days;
+}
+
+async function topAggregates(id, column) {
+ try {
+ const rows = await sql(
+ `select coalesce(${column}, '') as key, count(*)::bigint as count
+ from widget_views
+ where widget_id = $1 and ${column} is not null
+ group by 1 order by count desc limit 5`,
+ [id],
+ );
+ return rows.map((r) => ({
+ [column === 'referer_host' ? 'host' : 'country']: r.key,
+ count: Number(r.count),
+ }));
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return [];
+ throw err;
+ }
+}
+
+async function lastViewedAt(id) {
+ try {
+ const rows =
+ await sql`select max(created_at) as t from widget_views where widget_id = ${id}`;
+ return rows[0]?.t || null;
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return null;
+ throw err;
+ }
+}
+
+// Talking-agent widget chats live in agent_actions (Prompt 03 will wire this).
+// Until that table-or-source is finalized, return null so the UI knows to hide
+// the chat stat line for non-talking-agent types and for un-instrumented ones.
+async function chatCountFor(_id, type) {
+ if (type !== 'talking-agent') return null;
+ return null;
+}
+
+function startOfUtcDay(d) {
+ return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
+}
+
+function statsIdFromReq(req) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const m = path.match(/\/api\/widgets\/([^/]+)\/stats/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveStatsAuth(req) {
+ const session = await getSessionUser(req);
+ if (session)
+ return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
+ return await authenticateBearer(extractBearer(req));
+}
diff --git a/api/widgets/[id]/duplicate.js b/api/widgets/[id]/duplicate.js
deleted file mode 100644
index e8ad64778..000000000
--- a/api/widgets/[id]/duplicate.js
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * POST /api/widgets/:id/duplicate
- * -------------------------------
- * Owner-only. Clones a widget (config, type, avatar_id, is_public) under a new
- * id with name "<original> (copy)". Returns the new widget so the dashboard
- * can prepend it to the grid without re-fetching.
- */
-
-import crypto from 'node:crypto';
-
-import { sql } from '../../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { limits } from '../../_lib/rate-limit.js';
-import { decorate } from '../index.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['POST'])) return;
-
- const id = idFromReq(req);
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const auth = await resolveAuth(req);
- if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
- if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:write'))
- return error(res, 403, 'insufficient_scope', 'avatars:write required');
- }
-
- const rl = await limits.widgetWrite(auth.userId);
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const [src] = await sql`
- select id, type, name, config, avatar_id, is_public
- from widgets
- where id = ${id} and user_id = ${auth.userId} and deleted_at is null
- limit 1
- `;
- if (!src) return error(res, 404, 'not_found', 'widget not found or not yours');
-
- const newId = 'wdgt_' + crypto.randomBytes(9).toString('base64url');
- const newName = trim(`${src.name} (copy)`, 120);
-
- const [row] = await sql`
- insert into widgets (id, user_id, avatar_id, type, name, config, is_public)
- values (${newId}, ${auth.userId}, ${src.avatar_id}, ${src.type}, ${newName},
- ${JSON.stringify(src.config || {})}::jsonb, ${src.is_public})
- returning id, user_id, avatar_id, type, name, config, is_public, view_count, created_at, updated_at
- `;
-
- return json(res, 201, { widget: decorate(row) });
-});
-
-function trim(s, max) {
- return s.length <= max ? s : s.slice(0, max);
-}
-
-function idFromReq(req) {
- const fromQuery = req.query?.id;
- if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
- const path = new URL(req.url, 'http://x').pathname;
- const m = path.match(/\/api\/widgets\/([^/]+)\/duplicate/);
- return m ? decodeURIComponent(m[1]) : null;
-}
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session)
- return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
- return await authenticateBearer(extractBearer(req));
-}
diff --git a/api/widgets/[id]/stats.js b/api/widgets/[id]/stats.js
deleted file mode 100644
index d1059206d..000000000
--- a/api/widgets/[id]/stats.js
+++ /dev/null
@@ -1,149 +0,0 @@
-/**
- * GET /api/widgets/:id/stats
- * --------------------------
- * Owner-only. Returns aggregate analytics for the widget:
- * {
- * view_count: <bigint cumulative>,
- * last_viewed_at: <iso|null>,
- * recent_views_7d:[ { day, count }, … 8 entries ascending — UTC ],
- * top_referers: [ { host, count }, … up to 5 ],
- * top_countries: [ { country, count }, … up to 5 ],
- * chat_count: <int|null> // best-effort, null when unsupported
- * }
- *
- * Best-effort throughout: missing widget_views or chat tables don't 500 — they
- * return zero/empty arrays so the dashboard's sparkline can still render an
- * "all-zero" state without special casing.
- */
-
-import { sql } from '../../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
-import { cors, json, method, wrap, error } from '../../_lib/http.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const id = idFromReq(req);
- if (!id) return error(res, 400, 'invalid_request', 'id required');
-
- const auth = await resolveAuth(req);
- if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
- if (auth.source === 'oauth' || auth.source === 'apikey') {
- if (!hasScope(auth.scope, 'avatars:read'))
- return error(res, 403, 'insufficient_scope', 'avatars:read required');
- }
-
- // Ownership check — never 404 vs 403 leak: collapse to 404 either way.
- const [w] = await sql`
- select id, type, view_count
- from widgets
- where id = ${id} and user_id = ${auth.userId} and deleted_at is null
- limit 1
- `;
- if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');
-
- const [recentViews, topReferers, topCountries, lastViewed, chatCount] = await Promise.all([
- recentViewsByDay(id),
- topAggregates(id, 'referer_host'),
- topAggregates(id, 'country'),
- lastViewedAt(id),
- chatCountFor(id, w.type),
- ]);
-
- res.setHeader('cache-control', 'private, max-age=30');
- return json(res, 200, {
- stats: {
- view_count: Number(w.view_count || 0),
- last_viewed_at: lastViewed,
- recent_views_7d: recentViews,
- top_referers: topReferers,
- top_countries: topCountries,
- chat_count: chatCount,
- },
- });
-});
-
-async function recentViewsByDay(id) {
- // Always return 8 days (today + previous 7) so the sparkline doesn't have
- // to reason about gaps. 0-fill missing days from the actual rows.
- const days = [];
- const today = startOfUtcDay(new Date());
- for (let i = 7; i >= 0; i--) {
- const d = new Date(today.getTime() - i * 86400_000);
- days.push({ day: d.toISOString().slice(0, 10), count: 0 });
- }
- try {
- const rows = await sql`
- select date_trunc('day', created_at)::date::text as day, count(*)::bigint as count
- from widget_views
- where widget_id = ${id} and created_at >= ${days[0].day}::date
- group by 1 order by 1
- `;
- const idx = new Map(days.map((d, i) => [d.day, i]));
- for (const r of rows) {
- const i = idx.get(r.day);
- if (i !== undefined) days[i].count = Number(r.count);
- }
- } catch (err) {
- if (!/relation .* does not exist/i.test(err?.message || '')) throw err;
- }
- return days;
-}
-
-async function topAggregates(id, column) {
- try {
- const rows = await sql(
- `select coalesce(${column}, '') as key, count(*)::bigint as count
- from widget_views
- where widget_id = $1 and ${column} is not null
- group by 1 order by count desc limit 5`,
- [id],
- );
- return rows.map((r) => ({
- [column === 'referer_host' ? 'host' : 'country']: r.key,
- count: Number(r.count),
- }));
- } catch (err) {
- if (/relation .* does not exist/i.test(err?.message || '')) return [];
- throw err;
- }
-}
-
-async function lastViewedAt(id) {
- try {
- const rows =
- await sql`select max(created_at) as t from widget_views where widget_id = ${id}`;
- return rows[0]?.t || null;
- } catch (err) {
- if (/relation .* does not exist/i.test(err?.message || '')) return null;
- throw err;
- }
-}
-
-// Talking-agent widget chats live in agent_actions (Prompt 03 will wire this).
-// Until that table-or-source is finalized, return null so the UI knows to hide
-// the chat stat line for non-talking-agent types and for un-instrumented ones.
-async function chatCountFor(_id, type) {
- if (type !== 'talking-agent') return null;
- return null;
-}
-
-function startOfUtcDay(d) {
- return new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
-}
-
-function idFromReq(req) {
- const fromQuery = req.query?.id;
- if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
- const path = new URL(req.url, 'http://x').pathname;
- const m = path.match(/\/api\/widgets\/([^/]+)\/stats/);
- return m ? decodeURIComponent(m[1]) : null;
-}
-
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session)
- return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
- return await authenticateBearer(extractBearer(req));
-}
diff --git a/src/agent-home.js b/src/agent-home.js
index d4b88a2e1..11ea4903f 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -129,6 +129,9 @@ export class AgentHome {
<button class="agent-home-btn" id="agent-copy-link" title="Copy agent link">
<svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/></svg>
</button>
+ <button class="agent-home-btn" id="agent-home-hide" title="Hide panel" aria-label="Hide agent panel">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="currentColor"><path d="M19 13H5v-2h14v2z"/></svg>
+ </button>
</div>
${
@@ -236,6 +239,10 @@ export class AgentHome {
this._flashBtn(panel.querySelector('#agent-copy-link'), '✓');
});
+ // Hide / show toggle — collapses the whole sidebar to a small pill.
+ // Preference persisted in localStorage so it sticks across reloads.
+ this._wireHideToggle(panel);
+
// Wallet CTA button — fire a document event so app.js can handle it.
panel.querySelector('.agent-home-address--cta')?.addEventListener('click', () => {
document.dispatchEvent(new CustomEvent('agent-home:connect-wallet', { bubbles: true }));
@@ -247,6 +254,45 @@ export class AgentHome {
});
}
+ _wireHideToggle(panel) {
+ const sidebar = this.container.closest('.agent-presence-sidebar') || this.container.parentElement;
+ if (!sidebar) return;
+
+ const STORAGE_KEY = 'agent3d:home-hidden';
+
+ // Show-pill — appears only when sidebar is collapsed. Click to restore.
+ let pill = sidebar.querySelector('.agent-home-show-pill');
+ if (!pill) {
+ pill = document.createElement('button');
+ pill.type = 'button';
+ pill.className = 'agent-home-show-pill';
+ pill.title = 'Show agent panel';
+ pill.setAttribute('aria-label', 'Show agent panel');
+ pill.innerHTML = '<span aria-hidden="true">◎</span>';
+ sidebar.appendChild(pill);
+ }
+
+ const apply = (hidden) => {
+ sidebar.dataset.collapsed = hidden ? 'true' : 'false';
+ };
+
+ try {
+ apply(localStorage.getItem(STORAGE_KEY) === '1');
+ } catch {
+ apply(false);
+ }
+
+ panel.querySelector('#agent-home-hide')?.addEventListener('click', () => {
+ apply(true);
+ try { localStorage.setItem(STORAGE_KEY, '1'); } catch {}
+ });
+
+ pill.addEventListener('click', () => {
+ apply(false);
+ try { localStorage.setItem(STORAGE_KEY, '0'); } catch {}
+ });
+ }
+
_wireInlineEdit(el) {
if (!el) return;
const field = el.dataset.field;
diff --git a/style.css b/style.css
index 08ab789d6..526dfa7fd 100644
--- a/style.css
+++ b/style.css
@@ -3191,6 +3191,41 @@ body.explore-page {
pointer-events: none;
}
+/* Collapsed state — panel hidden, only show-pill visible */
+.agent-presence-sidebar[data-collapsed='true'] .agent-home-panel {
+ display: none;
+}
+
+.agent-home-show-pill {
+ display: none;
+ pointer-events: all;
+ width: 36px;
+ height: 36px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ background: linear-gradient(180deg, rgba(18, 18, 26, 0.92) 0%, rgba(10, 10, 16, 0.92) 100%);
+ color: #e0e0e0;
+ font-size: 16px;
+ cursor: pointer;
+ align-items: center;
+ justify-content: center;
+ backdrop-filter: blur(16px);
+ -webkit-backdrop-filter: blur(16px);
+ box-shadow:
+ 0 4px 16px rgba(0, 0, 0, 0.4),
+ inset 0 1px 0 rgba(255, 255, 255, 0.04);
+ transition: transform 0.15s ease, border-color 0.15s ease;
+}
+
+.agent-home-show-pill:hover {
+ transform: scale(1.06);
+ border-color: rgba(255, 255, 255, 0.25);
+}
+
+.agent-presence-sidebar[data-collapsed='true'] .agent-home-show-pill {
+ display: flex;
+}
+
.agent-home-panel {
background: linear-gradient(180deg, rgba(18, 18, 26, 0.92) 0%, rgba(10, 10, 16, 0.92) 100%);
border: 1px solid rgba(255, 255, 255, 0.08);