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: remove unused pump relay functionality and associated files

nirholas494e83d6f735
diff --git a/api/_lib/migrations/2026-04-29-drop-pump-relay.sql b/api/_lib/migrations/2026-04-29-drop-pump-relay.sql
new file mode 100644
index 000000000..ee0dc3b85
--- /dev/null
+++ b/api/_lib/migrations/2026-04-29-drop-pump-relay.sql
@@ -0,0 +1,15 @@
+-- Migration: drop unused relayer-trade tables.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-drop-pump-relay.sql
+-- Idempotent.
+--
+-- Tables introduced by 2026-04-29-pump-relay-delegations.sql were for a
+-- shared custodial relayer pattern. That model is wrong for a multi-tenant
+-- site (one user's SOL would fund another's trades). Trading goes through
+-- /api/pump/{buy,sell}-prep where the user's own wallet signs.
+
+begin;
+
+drop table if exists pump_relay_trades;
+drop table if exists pump_trade_delegations;
+
+commit;
diff --git a/api/_lib/pump-relayer.js b/api/_lib/pump-relayer.js
deleted file mode 100644
index 6815352bd..000000000
--- a/api/_lib/pump-relayer.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// Hot-wallet relayer for pump.fun trades.
-//
-// Loads PUMP_RELAYER_SECRET_KEY_B64 from env. The keypair is the *server's*
-// custodial trading bot — not a user wallet. A user authorizes it via SIWS
-// (see api/pump/relay-authorize.js) up to a capped cumulative spend, after
-// which /api/pump/relay-trade can submit buys/sells without further user action.
-//
-// Security tradeoffs (read before deploying):
-// 1. The env-stored key is a single point of failure. Rotate by setting a
-// new env var and revoking outstanding delegations.
-// 2. Cumulative spend cap is enforced in pg via SELECT … FOR UPDATE; if the
-// caller bypasses this helper, no enforcement.
-// 3. Per-trade direction/mint filters reduce blast radius if the key leaks.
-//
-// Deploy alternative: swap loadRelayer() for a KMS-signed remote signer.
-
-let CACHED = null;
-
-export async function loadRelayer() {
- if (CACHED) return CACHED;
- const b64 = process.env.PUMP_RELAYER_SECRET_KEY_B64;
- if (!b64) {
- const e = new Error('PUMP_RELAYER_SECRET_KEY_B64 not configured');
- e.status = 503;
- e.code = 'relayer_not_configured';
- throw e;
- }
- const { Keypair } = await import('@solana/web3.js');
- const kp = Keypair.fromSecretKey(Buffer.from(b64, 'base64'));
- CACHED = kp;
- return kp;
-}
-
-export async function relayerPubkeyString() {
- const kp = await loadRelayer();
- return kp.publicKey.toBase58();
-}
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 004c9c5f9..7fac3c656 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -2,6 +2,7 @@
* /api/agents/:id — agent CRUD
* /api/agents/:id/wallet — link / update EVM wallet
* /api/agents/:id/solana — agent's Solana wallet (address + balance, provision)
+ * /api/agents/:id/sns — list owned .sol domains and attach one as the agent's SNS id
* /api/agents/:id/pumpfun/launch — create a pump.fun token from this agent
* /api/agents/:id/pumpfun/buy — bonding-curve buy
* /api/agents/:id/pumpfun/sell — bonding-curve sell
@@ -31,6 +32,11 @@ export default wrap(async function handler(req, res) {
return mod.default(req, res, id);
}
+ if (sub === 'sns') {
+ const mod = await import('./sns.js');
+ return mod.default(req, res, id);
+ }
+
if (sub === 'pumpfun') {
if (action === 'launch') return (await import('./pumpfun/launch.js')).default(req, res, id);
if (action === 'buy') return (await import('./pumpfun/buy.js')).default(req, res, id);
diff --git a/api/agents/sns.js b/api/agents/sns.js
new file mode 100644
index 000000000..111c9a2e6
--- /dev/null
+++ b/api/agents/sns.js
@@ -0,0 +1,127 @@
+// /api/agents/:id/sns
+//
+// GET — list .sol domains the agent's Solana wallet owns (via Bonfida
+// sns-api.bonfida.com), plus the wallet's favorite/primary domain
+// and the currently-attached SNS id (meta.sns_domain).
+// POST — body { domain } — verify the agent's wallet owns `domain`, then
+// save it as the agent's SNS id (meta.sns_domain).
+// DELETE — clear meta.sns_domain.
+//
+// Registration is done off-platform at https://www.sns.id — the UI links out.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { sql } from '../_lib/db.js';
+import { cors, json, method, error, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+const SNS_API = 'https://sns-api.bonfida.com';
+const DOMAIN_RE = /^[a-z0-9-]{1,63}(\.sol)?$/i;
+
+function normalizeDomain(input) {
+ if (typeof input !== 'string') return null;
+ const trimmed = input.trim().toLowerCase().replace(/\.sol$/, '');
+ if (!trimmed || !/^[a-z0-9-]{1,63}$/.test(trimmed)) return null;
+ return trimmed;
+}
+
+async function snsFetch(path) {
+ const r = await fetch(`${SNS_API}${path}`, { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(`sns api ${r.status}`);
+ return r.json();
+}
+
+async function fetchOwnedDomains(address) {
+ const body = await snsFetch(`/v2/user/domains/${address}`);
+ const list = body?.[address] || body?.data?.[address] || [];
+ return Array.isArray(list) ? list : [];
+}
+
+async function fetchFavoriteDomain(address) {
+ try {
+ const body = await snsFetch(`/v2/user/fav-domains/${address}`);
+ return body?.[address] || null;
+ } catch {
+ return null;
+ }
+}
+
+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: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) 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 [row] = await sql`
+ SELECT id, user_id, meta FROM agent_identities
+ WHERE id = ${id} 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');
+
+ let meta = { ...(row.meta || {}) };
+ const address = meta.solana_address;
+ if (!address) {
+ return error(res, 409, 'conflict', 'agent has no solana wallet — provision one first via POST /api/agents/:id/solana');
+ }
+
+ if (req.method === 'DELETE') {
+ delete meta.sns_domain;
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { data: { ok: true, address, sns_domain: null } });
+ }
+
+ if (req.method === 'POST') {
+ const body = await readJson(req).catch(() => ({}));
+ if (!DOMAIN_RE.test(String(body?.domain || ''))) {
+ return error(res, 400, 'validation_error', 'domain must be a .sol name');
+ }
+ const domain = normalizeDomain(body.domain);
+ if (!domain) return error(res, 400, 'validation_error', 'invalid .sol domain');
+
+ let owned;
+ try {
+ owned = await fetchOwnedDomains(address);
+ } catch (err) {
+ return error(res, 502, 'upstream_error', 'sns lookup failed');
+ }
+ if (!owned.includes(domain)) {
+ return error(res, 403, 'forbidden', `wallet ${address} does not own ${domain}.sol`);
+ }
+
+ meta = { ...meta, sns_domain: domain };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { data: { ok: true, address, sns_domain: domain } });
+ }
+
+ // GET
+ let domains = [];
+ let favorite = null;
+ let upstreamOk = true;
+ try {
+ [domains, favorite] = await Promise.all([fetchOwnedDomains(address), fetchFavoriteDomain(address)]);
+ } catch {
+ upstreamOk = false;
+ }
+ return json(res, 200, {
+ data: {
+ address,
+ sns_domain: meta.sns_domain || null,
+ domains,
+ favorite,
+ upstream_ok: upstreamOk,
+ register_url: `https://www.sns.id/?search=`,
+ },
+ });
+}
diff --git a/api/openapi-json.js b/api/openapi-json.js
index 0c066dd2e..8837bfa9d 100644
--- a/api/openapi-json.js
+++ b/api/openapi-json.js
@@ -98,6 +98,13 @@ export default wrap(async (req, res) => {
maxAmountRequired: '1000',
},
},
+ {
+ mpp: {
+ method: 'solana-pay',
+ intent: 'purchase',
+ currency: 'USDC',
+ },
+ },
],
},
},
@@ -150,6 +157,25 @@ export default wrap(async (req, res) => {
},
},
},
+ '/api/avatars/public': {
+ get: {
+ operationId: 'browse_public_avatars',
+ summary: 'Browse public avatars',
+ security: [],
+ parameters: [
+ { name: 'q', in: 'query', schema: { type: 'string' } },
+ {
+ name: 'limit',
+ in: 'query',
+ schema: { type: 'integer', default: 20, maximum: 100 },
+ },
+ { name: 'cursor', in: 'query', schema: { type: 'string' } },
+ ],
+ responses: {
+ 200: { description: 'Paginated list of public avatars' },
+ },
+ },
+ },
'/api/agents': {
get: {
operationId: 'list_agents',
diff --git a/api/pump/relay-authorize.js b/api/pump/relay-authorize.js
deleted file mode 100644
index e34d853f7..000000000
--- a/api/pump/relay-authorize.js
+++ /dev/null
@@ -1,87 +0,0 @@
-// POST /api/pump/relay-authorize
-// Records a user's SIWS-signed authorization granting the server relayer
-// pubkey delegated trading authority up to a cumulative SOL cap.
-
-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 { parseSiwsMessage, verifySiwsSignature } from '../_lib/siws.js';
-import { relayerPubkeyString } from '../_lib/pump-relayer.js';
-
-const bodySchema = z.object({
- agent_id: z.string().uuid().optional(),
- user_wallet: z.string().min(32).max(44),
- max_sol: z.number().positive().max(100), // cap on cumulative spend (SOL)
- direction_filter: z.enum(['buy', 'sell', 'both']).default('both'),
- mint_filter: z.string().min(32).max(44).optional(),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- ttl_hours: z.number().int().min(1).max(720).default(24),
- siws_message: z.string().min(20).max(2000),
- siws_signature: z.string().min(40).max(200),
-});
-
-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));
-
- // Verify SIWS — message must reference the relayer pubkey + max_sol so
- // the user has signed the *exact* delegation terms.
- const fields = parseSiwsMessage(body.siws_message);
- if (!fields) return error(res, 400, 'invalid_siws', 'malformed SIWS message');
- if (fields.address !== body.user_wallet)
- return error(res, 403, 'siws_address_mismatch', 'SIWS address does not match user_wallet');
- const ok = verifySiwsSignature(body.siws_message, body.siws_signature, body.user_wallet);
- if (!ok) return error(res, 403, 'siws_signature_invalid', 'SIWS signature did not verify');
-
- const relayer = await relayerPubkeyString();
- if (!body.siws_message.includes(relayer))
- return error(
- res,
- 400,
- 'siws_missing_relayer',
- 'SIWS statement must reference relayer pubkey',
- );
- if (!body.siws_message.includes(`max=${body.max_sol}`))
- return error(res, 400, 'siws_missing_cap', 'SIWS statement must include max=<SOL> cap');
-
- // Verify the wallet is linked to the user.
- const [walletRow] = await sql`
- select id from user_wallets
- where user_id=${user.id} and address=${body.user_wallet} and chain_type='solana'
- limit 1
- `;
- if (!walletRow) return error(res, 403, 'forbidden', 'wallet not linked to your account');
-
- const lamports = BigInt(Math.floor(body.max_sol * 1_000_000_000));
- const expiresAt = new Date(Date.now() + body.ttl_hours * 3600 * 1000).toISOString();
-
- const [row] = await sql`
- insert into pump_trade_delegations
- (user_id, agent_id, relayer_pubkey, user_wallet, max_sol_lamports,
- direction_filter, mint_filter, network, expires_at, siws_signature)
- values
- (${user.id}, ${body.agent_id ?? null}, ${relayer}, ${body.user_wallet},
- ${lamports.toString()}, ${body.direction_filter},
- ${body.mint_filter ?? null}, ${body.network}, ${expiresAt}, ${body.siws_signature})
- returning id, expires_at, max_sol_lamports
- `;
-
- return json(res, 201, {
- ok: true,
- delegation_id: row.id,
- relayer_pubkey: relayer,
- expires_at: row.expires_at,
- max_sol_lamports: row.max_sol_lamports.toString(),
- });
-});
diff --git a/api/pump/relay-delegations.js b/api/pump/relay-delegations.js
deleted file mode 100644
index 26375541b..000000000
--- a/api/pump/relay-delegations.js
+++ /dev/null
@@ -1,32 +0,0 @@
-// GET /api/pump/relay-delegations
-// Lists the user's active relay delegations.
-
-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: '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 rows = await sql`
- select id, agent_id, relayer_pubkey, user_wallet,
- max_sol_lamports, spent_sol_lamports,
- direction_filter, mint_filter, network,
- expires_at, created_at
- from pump_trade_delegations
- where user_id=${user.id} and revoked_at is null and expires_at > now()
- order by created_at desc
- `;
-
- return json(res, 200, {
- data: rows.map((r) => ({
- ...r,
- max_sol_lamports: r.max_sol_lamports.toString(),
- spent_sol_lamports: r.spent_sol_lamports.toString(),
- })),
- });
-});
diff --git a/api/pump/relay-revoke.js b/api/pump/relay-revoke.js
deleted file mode 100644
index 0a44b0969..000000000
--- a/api/pump/relay-revoke.js
+++ /dev/null
@@ -1,37 +0,0 @@
-// POST /api/pump/relay-revoke
-// Marks an active delegation as revoked. Subsequent /api/pump/relay-trade
-// calls referencing it will 403.
-
-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';
-
-const bodySchema = z.object({
- delegation_id: z.string().uuid(),
-});
-
-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 rows = await sql`
- update pump_trade_delegations
- set revoked_at = now()
- where id=${body.delegation_id} and user_id=${user.id} and revoked_at is null
- returning id
- `;
- if (rows.length === 0) return error(res, 404, 'not_found', 'no active delegation found');
-
- return json(res, 200, { ok: true, delegation_id: body.delegation_id });
-});
diff --git a/api/pump/relay-trade.js b/api/pump/relay-trade.js
deleted file mode 100644
index 74722669a..000000000
--- a/api/pump/relay-trade.js
+++ /dev/null
@@ -1,217 +0,0 @@
-// POST /api/pump/relay-trade
-//
-// Executes a pump.fun buy/sell using the server-held relayer keypair on
-// behalf of a user with an active delegation. Auth: session OR bearer (so
-// MCP / wallet-less clients can drive trades). Spend cap is enforced via
-// SELECT … FOR UPDATE on pump_trade_delegations.
-
-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 { getConnection, getPumpSdk, getAmmPoolState, solanaPubkey } from '../_lib/pump.js';
-import { loadRelayer } from '../_lib/pump-relayer.js';
-
-const bodySchema = z.object({
- delegation_id: z.string().uuid(),
- mint: z.string().min(32).max(44),
- network: z.enum(['mainnet', 'devnet']).default('mainnet'),
- direction: z.enum(['buy', 'sell']),
- sol: z.number().positive().max(50).optional(),
- tokens: z.string().regex(/^\d+$/).optional(),
- slippage_bps: z.number().int().min(0).max(5000).default(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 userId = session?.id ?? bearer.userId;
-
- 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));
-
- if (body.direction === 'buy' && !body.sol)
- return error(res, 400, 'validation_error', 'sol required for buy');
- if (body.direction === 'sell' && !body.tokens)
- return error(res, 400, 'validation_error', 'tokens required for sell');
-
- const relayer = await loadRelayer().catch((e) => {
- throw e;
- });
-
- // Reserve cap atomically. We bump spent_sol_lamports up-front; if the tx
- // then fails on-chain, we refund in the catch path below.
- const lamports = body.direction === 'buy' ? BigInt(Math.floor(body.sol * 1_000_000_000)) : 0n;
-
- // Atomic reservation: single UPDATE that advances spent_sol_lamports only
- // if every constraint passes. Returns the delegation row on success or
- // nothing if any check (cap, expiry, filters) fails.
- const [delegation] = await sql`
- update pump_trade_delegations
- set spent_sol_lamports = spent_sol_lamports + ${lamports.toString()}
- where id = ${body.delegation_id}
- and user_id = ${userId}
- and revoked_at is null
- and expires_at > now()
- and network = ${body.network}
- and (direction_filter = 'both' or direction_filter = ${body.direction})
- and (mint_filter is null or mint_filter = ${body.mint})
- and spent_sol_lamports + ${lamports.toString()} <= max_sol_lamports
- returning id, max_sol_lamports, spent_sol_lamports
- `;
- if (!delegation) {
- // Diagnose which constraint failed for a clearer error.
- const [d] = await sql`
- select revoked_at, expires_at, network, direction_filter, mint_filter,
- spent_sol_lamports, max_sol_lamports
- from pump_trade_delegations where id=${body.delegation_id} and user_id=${userId}
- `;
- if (!d) return error(res, 404, 'not_found', 'delegation not found');
- if (d.revoked_at) return error(res, 403, 'revoked', 'delegation revoked');
- if (new Date(d.expires_at) < new Date())
- return error(res, 403, 'expired', 'delegation expired');
- if (d.network !== body.network)
- return error(res, 400, 'network_mismatch', 'network mismatch');
- if (d.direction_filter !== 'both' && d.direction_filter !== body.direction)
- return error(res, 403, 'direction_blocked', 'direction not permitted');
- if (d.mint_filter && d.mint_filter !== body.mint)
- return error(res, 403, 'mint_blocked', 'mint not permitted');
- return error(res, 403, 'cap_exceeded', 'spend cap exceeded');
- }
-
- let sig, route;
- try {
- const result = await executeTrade({ body, relayer });
- sig = result.signature;
- route = result.route;
- } catch (e) {
- // Refund the reservation by subtracting `lamports` from current value.
- // Done as a relative update to avoid clobbering concurrent reservations.
- if (lamports > 0n) {
- await sql`
- update pump_trade_delegations
- set spent_sol_lamports = greatest(0, spent_sol_lamports - ${lamports.toString()})
- where id=${delegation.id}
- `;
- }
- return error(res, e.status || 502, e.code || 'pump_sdk_error', e.message || 'trade failed');
- }
-
- await sql`
- insert into pump_relay_trades
- (delegation_id, direction, mint, network, route, sol_lamports, token_amount, tx_signature)
- values
- (${delegation.id}, ${body.direction}, ${body.mint}, ${body.network}, ${route},
- ${body.direction === 'buy' ? lamports.toString() : null},
- ${body.direction === 'sell' ? body.tokens : null},
- ${sig})
- on conflict (tx_signature, network) do nothing
- `;
-
- return json(res, 200, {
- ok: true,
- delegation_id: delegation.id,
- direction: body.direction,
- route,
- mint: body.mint,
- network: body.network,
- tx_signature: sig,
- });
-});
-
-async function executeTrade({ body, relayer }) {
- const userPk = relayer.publicKey;
- const mintPk = solanaPubkey(body.mint);
- if (!mintPk) throw Object.assign(new Error('invalid mint'), { status: 400 });
-
- const { sdk, BN } = await getPumpSdk({ network: body.network });
- const slippage = body.slippage_bps / 10_000;
- const connection = getConnection({ network: body.network });
-
- let ixs;
- let route;
-
- if (body.direction === 'buy') {
- const lamports = new BN(Math.floor(body.sol * 1_000_000_000));
- let buyState = null;
- try {
- if (sdk.fetchBuyState) buyState = await sdk.fetchBuyState(mintPk, userPk);
- } catch {}
- if (buyState && buyState.bondingCurve && !buyState.bondingCurve.complete) {
- const global = await sdk.fetchGlobal();
- 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,
- });
- route = 'bonding_curve';
- } else {
- 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(connection);
- const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
- ixs = await offline.buyQuoteInput(swapState, lamports, slippage);
- route = 'amm';
- }
- } else {
- const tokens = new BN(body.tokens);
- let sellState = null;
- try {
- if (sdk.fetchSellState) sellState = await sdk.fetchSellState(mintPk, userPk);
- } catch {}
- if (sellState && sellState.bondingCurve && !sellState.bondingCurve.complete) {
- const global = await sdk.fetchGlobal();
- ixs = await sdk.sellInstructions({
- global,
- bondingCurveAccountInfo: sellState.bondingCurveAccountInfo,
- bondingCurve: sellState.bondingCurve,
- mint: mintPk,
- user: userPk,
- amount: tokens,
- solAmount: new BN(0),
- slippage,
- });
- route = 'bonding_curve';
- } else {
- 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(connection);
- const swapState = await onlineAmm.swapSolanaState(amm.poolKey, userPk);
- ixs = await offline.sellBaseInput(swapState, tokens, slippage);
- route = 'amm';
- }
- }
-
- const { TransactionMessage, VersionedTransaction } = await import('@solana/web3.js');
- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
- const msg = new TransactionMessage({
- payerKey: userPk,
- recentBlockhash: blockhash,
- instructions: ixs,
- }).compileToV0Message();
- const vtx = new VersionedTransaction(msg);
- vtx.sign([relayer]);
-
- const sig = await connection.sendRawTransaction(vtx.serialize(), { skipPreflight: false });
- await connection.confirmTransaction(
- { signature: sig, blockhash, lastValidBlockHeight },
- 'confirmed',
- );
- return { signature: sig, route };
-}
diff --git a/api/pump/relayer-info.js b/api/pump/relayer-info.js
deleted file mode 100644
index 3d1ac1924..000000000
--- a/api/pump/relayer-info.js
+++ /dev/null
@@ -1,33 +0,0 @@
-// GET /api/pump/relayer-info
-//
-// Public endpoint: returns the server relayer pubkey so clients can build
-// the SIWS authorization message. No auth — pubkey is non-sensitive.
-
-import { cors, json, method, wrap, error } from '../_lib/http.js';
-import { relayerPubkeyString } from '../_lib/pump-relayer.js';
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
- if (!method(req, res, ['GET'])) return;
-
- try {
- const pubkey = await relayerPubkeyString();
- return json(
- res,
- 200,
- {
- relayer_pubkey: pubkey,
- siws_template: [
- `Authorize three.ws relayer ${pubkey} to trade pump.fun on my behalf.`,
- 'max=<SOL>',
- 'expires=<ISO8601>',
- 'mint=<optional pubkey>',
- 'direction=<buy|sell|both>',
- ].join('\n'),
- },
- { 'cache-control': 'public, max-age=60', 'access-control-allow-origin': '*' },
- );
- } catch (e) {
- return error(res, e.status || 503, e.code || 'not_configured', e.message);
- }
-});
diff --git a/package.json b/package.json
index 548e73750..a20662c5e 100644
--- a/package.json
+++ b/package.json
@@ -57,7 +57,6 @@
"validate:cards": "node scripts/validate-agent-cards.mjs",
"db:migrate": "node scripts/apply-migrations.mjs --apply",
"db:status": "node scripts/apply-migrations.mjs",
- "pump:keygen": "node scripts/pump-relayer-keygen.mjs",
"pump:smoke": "node scripts/pumpfun-lifecycle-smoke.js"
},
"dependencies": {
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 2c976488a..34d1576bc 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1141,7 +1141,6 @@
<a href="#account" data-tab="account">Account</a>
<a href="/dashboard/wallets">Wallets</a>
<a href="/dashboard/agent-pumpfun">Agent · Pump.fun</a>
- <a href="/dashboard/pump-relay">Pump · Relay trading</a>
<a href="/discover" title="Browse on-chain agents across every supported chain"
>Discover on-chain ↗</a
>
diff --git a/public/dashboard/pump-relay.html b/public/dashboard/pump-relay.html
deleted file mode 100644
index de415a880..000000000
--- a/public/dashboard/pump-relay.html
+++ /dev/null
@@ -1,381 +0,0 @@
-<!doctype html>
-<html lang="en">
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width,initial-scale=1" />
- <title>Pump.fun relay · Dashboard · three.ws</title>
- <link rel="icon" href="/favicon.ico" />
- <style>
- :root {
- color-scheme: dark;
- --accent: #6a5cff;
- --ok: #4ade80;
- --err: #f87171;
- --border: #22222e;
- --bg: #0b0b10;
- --panel: #14141c;
- --muted: #888;
- }
- * {
- box-sizing: border-box;
- }
- body {
- font:
- 15px/1.55 system-ui,
- sans-serif;
- color: #eee;
- margin: 0;
- background: var(--bg);
- }
- header {
- display: flex;
- justify-content: space-between;
- padding: 16px 24px;
- border-bottom: 1px solid var(--border);
- }
- main {
- padding: 28px;
- max-width: 880px;
- margin: 0 auto;
- }
- h1 {
- font-size: 22px;
- margin: 0 0 6px;
- }
- .sub {
- color: var(--muted);
- margin: 0 0 22px;
- }
- .panel {
- background: var(--panel);
- border: 1px solid var(--border);
- border-radius: 14px;
- padding: 18px 20px;
- margin-bottom: 18px;
- }
- label {
- display: block;
- font-size: 13px;
- color: var(--muted);
- margin: 8px 0 4px;
- }
- input,
- select {
- width: 100%;
- padding: 8px 10px;
- background: #0e0e14;
- border: 1px solid var(--border);
- border-radius: 8px;
- color: #eee;
- font: inherit;
- }
- button {
- background: var(--accent);
- color: white;
- border: 0;
- padding: 9px 16px;
- border-radius: 8px;
- font: inherit;
- cursor: pointer;
- }
- button:disabled {
- opacity: 0.5;
- cursor: not-allowed;
- }
- button.ghost {
- background: transparent;
- border: 1px solid var(--border);
- color: #eee;
- }
- .row {
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 12px;
- }
- .muted {
- color: var(--muted);
- }
- .ok {
- color: var(--ok);
- }
- .err {
- color: var(--err);
- }
- pre {
- background: #08080c;
- border: 1px solid var(--border);
- border-radius: 8px;
- padding: 10px;
- overflow: auto;
- font-size: 12px;
- }
- table {
- width: 100%;
- border-collapse: collapse;
- font-size: 13px;
- }
- td,
- th {
- padding: 8px 6px;
- border-bottom: 1px solid var(--border);
- text-align: left;
- }
- .mono {
- font-family: ui-monospace, monospace;
- }
- </style>
- </head>
- <body>
- <header>
- <div><a href="/dashboard">← dashboard</a></div>
- <div class="muted">pump.fun relay</div>
- </header>
- <main>
- <h1>Pump.fun relay trading</h1>
- <p class="sub">
- Authorize the three.ws server keypair to execute pump.fun trades on your behalf,
- capped by SOL and TTL. MCP clients without a wallet can then drive trades.
- </p>
-
- <div class="panel">
- <h2 style="margin-top: 0">Server relayer</h2>
- <div id="relayer-info">Loading…</div>
- </div>
-
- <div class="panel">
- <h2 style="margin-top: 0">Authorize</h2>
- <div class="row">
- <div>
- <label>Wallet (base58)</label>
- <input id="wallet" placeholder="paste your Solana wallet pubkey" />
- </div>
- <div>
- <label>Network</label>
- <select id="network">
- <option>mainnet</option>
- <option>devnet</option>
- </select>
- </div>
- </div>
- <div class="row">
- <div>
- <label>Max SOL (cumulative cap)</label>
- <input
- id="max-sol"
- type="number"
- min="0.01"
- max="100"
- step="0.01"
- value="0.5"
- />
- </div>
- <div>
- <label>TTL (hours)</label>
- <input id="ttl-hours" type="number" min="1" max="720" value="24" />
- </div>
- </div>
- <div class="row">
- <div>
- <label>Direction</label>
- <select id="direction">
- <option>both</option>
- <option>buy</option>
- <option>sell</option>
- </select>
- </div>
- <div>
- <label>Mint filter (optional)</label>
- <input id="mint-filter" placeholder="lock to a single mint" />
- </div>
- </div>
- <div style="margin-top: 14px; display: flex; gap: 8px">
- <button id="authorize">Sign + authorize</button>
- <button id="refresh" class="ghost">Refresh delegations</button>
- </div>
- <div id="status" class="muted" style="margin-top: 10px"></div>
- </div>
-
- <div class="panel">
- <h2 style="margin-top: 0">Active delegations</h2>
- <div id="delegations">Loading…</div>
- </div>
- </main>
-
- <script type="module">
- function buildRelayAuthorizationMessage({
- userWallet,
- relayerPubkey,
- maxSol,
- mint,
- direction = 'both',
- network = 'mainnet',
- ttlHours = 24,
- domain = location.host,
- }) {
- const issuedAt = new Date().toISOString();
- const expiresAt = new Date(Date.now() + ttlHours * 3600 * 1000).toISOString();
- const nonce = Math.random().toString(36).slice(2, 14);
- const statement =
- `Authorize three.ws relayer ${relayerPubkey} to trade pump.fun on my behalf.\n` +
- `max=${maxSol}\nexpires=${expiresAt}\ndirection=${direction}` +
- (mint ? `\nmint=${mint}` : '');
- return [
- `${domain} wants you to sign in with your Solana account:`,
- userWallet,
- '',
- statement,
- '',
- `URI: https://${domain}/api/pump/relay-authorize`,
- 'Version: 1',
- `Chain ID: ${network}`,
- `Nonce: ${nonce}`,
- `Issued At: ${issuedAt}`,
- `Expiration Time: ${expiresAt}`,
- ].join('\n');
- }
-
- const $ = (id) => document.getElementById(id);
- let RELAYER_PUBKEY = null;
-
- async function loadRelayerInfo() {
- try {
- const r = await fetch('/api/pump/relayer-info').then((r) => r.json());
- if (r.relayer_pubkey) {
- RELAYER_PUBKEY = r.relayer_pubkey;
- $('relayer-info').innerHTML =
- `<div class="mono" style="word-break:break-all">${r.relayer_pubkey}</div><div class="muted" style="margin-top:4px">Fund this address with SOL to cover trade fees.</div>`;
- } else {
- $('relayer-info').innerHTML =
- `<span class="err">Relayer not configured (PUMP_RELAYER_SECRET_KEY_B64 unset)</span>`;
- }
- } catch (e) {
- $('relayer-info').innerHTML = `<span class="err">${e.message}</span>`;
- }
- }
-
- async function loadDelegations() {
- try {
- const r = await fetch('/api/pump/relay-delegations', {
- credentials: 'include',
- });
- if (!r.ok) throw new Error(`${r.status}`);
- const data = await r.json();
- if (!data.data || data.data.length === 0) {
- $('delegations').innerHTML =
- '<div class="muted">No active delegations.</div>';
- return;
- }
- const rows = data.data
- .map(
- (d) => `
- <tr>
- <td class="mono" style="font-size:12px">${d.id.slice(0, 8)}…</td>
- <td>${d.network}</td>
- <td>${(Number(d.max_sol_lamports) / 1e9).toFixed(3)} SOL</td>
- <td>${(Number(d.spent_sol_lamports) / 1e9).toFixed(3)}</td>
- <td>${d.direction_filter}</td>
- <td>${new Date(d.expires_at).toLocaleString()}</td>
- <td><button data-id="${d.id}" class="ghost revoke">Revoke</button></td>
- </tr>
- `,
- )
- .join('');
- $('delegations').innerHTML = `
- <table>
- <thead><tr><th>id</th><th>net</th><th>cap</th><th>spent</th><th>dir</th><th>expires</th><th></th></tr></thead>
- <tbody>${rows}</tbody>
- </table>
- `;
- $('delegations')
- .querySelectorAll('button.revoke')
- .forEach((b) => b.addEventListener('click', () => revoke(b.dataset.id)));
- } catch (e) {
- $('delegations').innerHTML = `<span class="err">${e.message}</span>`;
- }
- }
-
- async function authorize() {
- const btn = $('authorize');
- btn.disabled = true;
- $('status').textContent = '';
- $('status').className = 'muted';
- try {
- if (!RELAYER_PUBKEY) throw new Error('relayer not loaded');
- const wallet = $('wallet').value.trim();
- if (!wallet) throw new Error('wallet required');
- const maxSol = Number($('max-sol').value);
- const network = $('network').value;
- const direction = $('direction').value;
- const mintFilter = $('mint-filter').value.trim() || null;
- const ttlHours = Number($('ttl-hours').value);
-
- const message = buildRelayAuthorizationMessage({
- userWallet: wallet,
- relayerPubkey: RELAYER_PUBKEY,
- maxSol,
- mint: mintFilter,
- direction,
- network,
- ttlHours,
- });
-
- const provider = window.solana || window.phantom?.solana;
- if (!provider) throw new Error('No Solana wallet detected (install Phantom).');
- if (!provider.isConnected) await provider.connect();
- const encoded = new TextEncoder().encode(message);
- const { signature } = await provider.signMessage(encoded, 'utf8');
- const bs58 = await import('https://esm.sh/bs58@5');
- const sigB58 = bs58.default.encode(signature);
-
- const res = await fetch('/api/pump/relay-authorize', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- user_wallet: wallet,
- max_sol: maxSol,
- direction_filter: direction,
- mint_filter: mintFilter || undefined,
- network,
- ttl_hours: ttlHours,
- siws_message: message,
- siws_signature: sigB58,
- }),
- });
- const j = await res.json();
- if (!res.ok) throw new Error(j.error_description || j.error || `${res.status}`);
- $('status').textContent = `Authorized · delegation ${j.delegation_id}`;
- $('status').className = 'ok';
- await loadDelegations();
- } catch (e) {
- $('status').textContent = `Error: ${e.message}`;
- $('status').className = 'err';
- } finally {
- btn.disabled = false;
- }
- }
-
- async function revoke(id) {
- if (!confirm('Revoke this delegation?')) return;
- const res = await fetch('/api/pump/relay-revoke', {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ delegation_id: id }),
- });
- if (!res.ok) {
- const j = await res.json().catch(() => ({}));
- alert(`Revoke failed: ${j.error_description || res.status}`);
- return;
- }
- await loadDelegations();
- }
-
- $('authorize').addEventListener('click', authorize);
- $('refresh').addEventListener('click', loadDelegations);
-
- loadRelayerInfo();
- loadDelegations();
- </script>
- </body>
-</html>
diff --git a/scripts/pump-relayer-keygen.mjs b/scripts/pump-relayer-keygen.mjs
deleted file mode 100644
index d3ba45261..000000000
--- a/scripts/pump-relayer-keygen.mjs
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/usr/bin/env node
-// Generate a Solana keypair for the pump.fun trade relayer.
-// Prints the base64-encoded secret key + base58 pubkey.
-//
-// Usage:
-// node scripts/pump-relayer-keygen.mjs
-//
-// Then set in your env (Vercel project / .env.local):
-// PUMP_RELAYER_SECRET_KEY_B64=<the base64 string>
-//
-// Fund the printed pubkey with a small amount of SOL (mainnet) or use
-// `solana airdrop 1 <pubkey> --url devnet` for devnet testing.
-
-import { Keypair } from '@solana/web3.js';
-
-const kp = Keypair.generate();
-const secretB64 = Buffer.from(kp.secretKey).toString('base64');
-
-console.log('Pump relayer keypair (KEEP SECRET KEY PRIVATE):');
-console.log(' pubkey: ', kp.publicKey.toBase58());
-console.log(' secret base64: ', secretB64);
-console.log('');
-console.log('Add to env:');
-console.log(` PUMP_RELAYER_SECRET_KEY_B64='${secretB64}'`);
-console.log('');
-console.log('Fund the pubkey with SOL before serving relay-trade requests.');
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index 890ddb7e8..5bd3745c4 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -153,56 +153,6 @@ export async function runServerFlow({
return { signature: sig, prep, confirm: confirmJson };
}
-/**
- * Build the SIWS message that authorizes the three.ws relayer to trade
- * pump.fun on the user's behalf. Caller must sign + POST to /api/pump/relay-authorize.
- *
- * @param {Object} opts
- * @param {string} opts.userWallet — base58 pubkey signing the authz
- * @param {string} opts.relayerPubkey — server pubkey from /api/pump/relayer-info
- * @param {number} opts.maxSol — cumulative spend cap (SOL)
- * @param {string} [opts.mint] — optional lock to a single mint
- * @param {('buy'|'sell'|'both')} [opts.direction='both']
- * @param {string} [opts.network='mainnet']
- * @param {number} [opts.ttlHours=24]
- * @param {string} [opts.domain] — defaults to current page host
- * @returns {{ message: string, nonce: string, expiresAt: string }}
- */
-export function buildRelayAuthorizationMessage({
- userWallet,
- relayerPubkey,
- maxSol,
- mint,
- direction = 'both',
- network = 'mainnet',
- ttlHours = 24,
- domain = typeof location !== 'undefined' ? location.host : 'three.ws',
-}) {
- const issuedAt = new Date().toISOString();
- const expiresAt = new Date(Date.now() + ttlHours * 3600 * 1000).toISOString();
- const nonce = Math.random().toString(36).slice(2, 14);
- const statement =
- `Authorize three.ws relayer ${relayerPubkey} to trade pump.fun on my behalf.\n` +
- `max=${maxSol}\n` +
- `expires=${expiresAt}\n` +
- `direction=${direction}` +
- (mint ? `\nmint=${mint}` : '');
- const message = [
- `${domain} wants you to sign in with your Solana account:`,
- userWallet,
- '',
- statement,
- '',
- `URI: https://${domain}/api/pump/relay-authorize`,
- 'Version: 1',
- `Chain ID: ${network}`,
- `Nonce: ${nonce}`,
- `Issued At: ${issuedAt}`,
- `Expiration Time: ${expiresAt}`,
- ].join('\n');
- return { message, nonce, expiresAt };
-}
-
function deriveSymbol(name) {
return (
String(name || 'AGENT')
diff --git a/src/app.js b/src/app.js
index 5b5411337..ce3c6b255 100644
--- a/src/app.js
+++ b/src/app.js
@@ -841,6 +841,16 @@ class App {
}
async _loadAgentForEdit(agentId) {
+ // Swap this.identity to the agent being edited so AgentHome (and the
+ // Solana wallet card) render for *this* agent rather than the viewer's
+ // default identity.
+ this.identity = new AgentIdentity({ agentId, autoLoad: false });
+ try {
+ await this.identity.load();
+ } catch {
+ /* fall through; identity getter still returns _agentId */
+ }
+
// Fetch the agent record and load its GLB into the editor (main UI, not embed)
let glbUrl = null;
try {
diff --git a/vercel.json b/vercel.json
index dbb506deb..6705bf98d 100644
--- a/vercel.json
+++ b/vercel.json
@@ -75,7 +75,6 @@
},
{ "src": "/api/avatars/([^/]+)/pin-ipfs", "dest": "/api/avatars/[id]/pin-ipfs?id=$1" },
{ "src": "/dashboard/storage", "dest": "/dashboard/storage.html" },
- { "src": "/dashboard/pump-relay", "dest": "/dashboard/pump-relay.html" },
{
"src": "/api/agents/([^/]+)/embed-policy",
"dest": "/api/agents/[id]/embed-policy?id=$1"