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: enhance agent passport with vanity prefix and address formatting

nirholas423653f076ca
diff --git a/.env.example b/.env.example
index 8523757b4..d05463c5a 100644
--- a/.env.example
+++ b/.env.example
@@ -99,3 +99,17 @@ PINATA_JWT=
# Web3.Storage (fallback): get token from https://web3.storage/tokens
# (legacy v1 API — upload endpoint: https://api.web3.storage/upload)
WEB3_STORAGE_TOKEN=
+
+# ── Pump.fun live feed integration (api/_lib/pumpfun-mcp.js) ──────────────
+# Upstream pumpfun-claims-bot MCP server URL. When set, /api/agents/pumpfun
+# and /api/agents/pumpfun-feed are enabled, the cron at /api/cron/pumpfun-signals
+# starts crawling, and the pumpfun-watch agent skills become functional.
+# Run `npx pumpfun-claims-bot` (or deploy via Railway) to host the upstream MCP.
+PUMPFUN_BOT_URL=
+# Optional bearer token if the upstream MCP requires auth.
+PUMPFUN_BOT_TOKEN=
+
+# ── Solana RPC overrides (used by Solana attestation crawler + pump skills) ──
+# Defaults to public mainnet/devnet — set Helius/Triton/QuickNode for prod.
+SOLANA_RPC_URL=
+SOLANA_RPC_URL_DEVNET=
diff --git a/api/_lib/pump.js b/api/_lib/pump.js
index 37d6aa224..966fd1dda 100644
--- a/api/_lib/pump.js
+++ b/api/_lib/pump.js
@@ -15,10 +15,8 @@
import { Connection, PublicKey } from '@solana/web3.js';
-const RPC_MAINNET = () =>
- process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
-const RPC_DEVNET = () =>
- process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const RPC_MAINNET = () => process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const RPC_DEVNET = () => process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
export function getConnection({ network = 'mainnet', commitment = 'confirmed' } = {}) {
const url = network === 'devnet' ? RPC_DEVNET() : RPC_MAINNET();
@@ -41,9 +39,7 @@ export async function getPumpSdk({ network = 'mainnet' } = {}) {
import('bn.js').then((m) => m.default || m),
]);
const connection = getConnection({ network });
- const sdk = new OnlinePumpSdk
- ? new OnlinePumpSdk(connection)
- : new PumpSdk(connection);
+ const sdk = new OnlinePumpSdk() ? new OnlinePumpSdk(connection) : new PumpSdk(connection);
return { sdk, connection, BN, web3, PumpSdk, OnlinePumpSdk };
}
@@ -55,17 +51,13 @@ export async function getPumpSwapSdk({ network = 'mainnet' } = {}) {
]);
const connection = getConnection({ network });
const sdk = new PumpAmmSdk(connection);
- const internalSdk = new PumpAmmInternalSdk ? new PumpAmmInternalSdk(connection) : null;
+ const internalSdk = new PumpAmmInternalSdk() ? new PumpAmmInternalSdk(connection) : null;
return { sdk, internalSdk, connection, BN, web3 };
}
export async function getPumpAgent({ network = 'mainnet', mint } = {}) {
if (!mint) throw Object.assign(new Error('mint required'), { status: 400 });
- const [
- { PumpAgent, getTokenAgentPaymentsPDA },
- web3,
- BN,
- ] = await Promise.all([
+ const [{ PumpAgent, getTokenAgentPaymentsPDA }, web3, BN] = await Promise.all([
import('@pump-fun/agent-payments-sdk'),
import('@solana/web3.js'),
import('bn.js').then((m) => m.default || m),
@@ -75,30 +67,23 @@ export async function getPumpAgent({ network = 'mainnet', mint } = {}) {
// PumpAgent is an Anchor-backed online SDK. Construction signature can
// shift between 3.x patches; pass connection + mint and let it error if not.
const agent = new PumpAgent(mintPk, connection);
- const [agentPda] = getTokenAgentPaymentsPDA
- ? getTokenAgentPaymentsPDA(mintPk)
- : [null];
+ const [agentPda] = getTokenAgentPaymentsPDA ? getTokenAgentPaymentsPDA(mintPk) : [null];
return { agent, connection, BN, web3, agentPda };
}
export async function getPumpAgentOffline({ network = 'mainnet', mint } = {}) {
if (!mint) throw Object.assign(new Error('mint required'), { status: 400 });
- const [
- { PumpAgentOffline, getTokenAgentPaymentsPDA, getInvoiceIdPDA },
- web3,
- BN,
- ] = await Promise.all([
- import('@pump-fun/agent-payments-sdk'),
- import('@solana/web3.js'),
- import('bn.js').then((m) => m.default || m),
- ]);
+ const [{ PumpAgentOffline, getTokenAgentPaymentsPDA, getInvoiceIdPDA }, web3, BN] =
+ await Promise.all([
+ import('@pump-fun/agent-payments-sdk'),
+ import('@solana/web3.js'),
+ import('bn.js').then((m) => m.default || m),
+ ]);
const mintPk = mint instanceof PublicKey ? mint : new PublicKey(mint);
const offline = PumpAgentOffline.load
? PumpAgentOffline.load(mintPk, getConnection({ network }))
: new PumpAgentOffline(mintPk);
- const [agentPda] = getTokenAgentPaymentsPDA
- ? getTokenAgentPaymentsPDA(mintPk)
- : [null];
+ const [agentPda] = getTokenAgentPaymentsPDA ? getTokenAgentPaymentsPDA(mintPk) : [null];
return { offline, getInvoiceIdPDA, BN, web3, agentPda };
}
@@ -140,21 +125,13 @@ export async function verifySignature({ network, signature }) {
// Throws { status: 404, code: 'pool_not_found' } if no pool exists yet.
export async function getAmmPoolState({ network = 'mainnet', mint } = {}) {
if (!mint) throw Object.assign(new Error('mint required'), { status: 400 });
- const [
- {
- canonicalPumpPoolPda,
- OnlinePumpAmmSdk,
- PumpAmmSdk,
- },
- web3,
- BN,
- spl,
- ] = await Promise.all([
- import('@pump-fun/pump-swap-sdk'),
- import('@solana/web3.js'),
- import('bn.js').then((m) => m.default || m),
- import('@solana/spl-token'),
- ]);
+ const [{ canonicalPumpPoolPda, OnlinePumpAmmSdk, PumpAmmSdk }, web3, BN, spl] =
+ await Promise.all([
+ import('@pump-fun/pump-swap-sdk'),
+ import('@solana/web3.js'),
+ import('bn.js').then((m) => m.default || m),
+ import('@solana/spl-token'),
+ ]);
const connection = getConnection({ network });
const mintPk = mint instanceof PublicKey ? mint : new PublicKey(mint);
const poolKey = canonicalPumpPoolPda(mintPk);
@@ -189,16 +166,12 @@ export async function getAmmPoolState({ network = 'mainnet', mint } = {}) {
const offline = new PumpAmmSdk();
const [globalConfigInfo, feeConfigInfo] = await Promise.all([
- connection.getAccountInfo(
- (await import('@pump-fun/pump-swap-sdk')).GLOBAL_CONFIG_PDA,
- ),
+ connection.getAccountInfo((await import('@pump-fun/pump-swap-sdk')).GLOBAL_CONFIG_PDA),
connection.getAccountInfo(
(await import('@pump-fun/pump-swap-sdk')).PUMP_AMM_FEE_CONFIG_PDA,
),
]);
- const globalConfig = globalConfigInfo
- ? offline.decodeGlobalConfig(globalConfigInfo)
- : null;
+ const globalConfig = globalConfigInfo ? offline.decodeGlobalConfig(globalConfigInfo) : null;
const feeConfig = feeConfigInfo ? offline.decodeFeeConfig(feeConfigInfo) : null;
return {
diff --git a/api/agents/[id].js b/api/agents/[id].js
index 94f092732..38cd7c890 100644
--- a/api/agents/[id].js
+++ b/api/agents/[id].js
@@ -3,6 +3,8 @@
* /api/agents/:id/wallet — link / update EVM wallet
* /api/agents/:id/solana — agent's Solana wallet (address + balance, provision)
* /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
* /api/agents/:id/pumpfun/swap — swap via @pump-fun/pump-swap-sdk
* /api/agents/:id/pumpfun/pay — agent payment via @pump-fun/agent-payments-sdk
*/
diff --git a/api/agents/pumpfun/buy.js b/api/agents/pumpfun/buy.js
new file mode 100644
index 000000000..b0b4b3e81
--- /dev/null
+++ b/api/agents/pumpfun/buy.js
@@ -0,0 +1,132 @@
+// 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 { 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 } = loaded;
+
+ 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));
+
+ 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
index 90cac07a0..4237bf701 100644
--- a/api/agents/pumpfun/launch.js
+++ b/api/agents/pumpfun/launch.js
@@ -15,6 +15,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/au
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';
@@ -25,6 +26,7 @@ const bodySchema = z.object({
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(),
network: z.enum(['mainnet', 'devnet']).default('mainnet'),
});
@@ -62,7 +64,15 @@ export default async function handler(req, res, id) {
const online = new OnlinePumpSdk(conn);
const sdk = new PumpSdk();
- const mint = Keypair.generate();
+ let mint;
+ let vanityIterations = 1;
+ try {
+ const ground = grindMintKeypair({ prefix: body.vanityPrefix });
+ mint = ground.keypair;
+ vanityIterations = ground.iterations;
+ } 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);
@@ -121,6 +131,8 @@ export default async function handler(req, res, id) {
uri: body.uri,
signature,
network: body.network,
+ vanity_prefix: body.vanityPrefix || null,
+ vanity_iterations: vanityIterations,
})}::jsonb,
${'pumpfun'}
)
@@ -132,6 +144,8 @@ export default async function handler(req, res, id) {
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_iterations: vanityIterations,
},
});
}
diff --git a/api/agents/pumpfun/sell.js b/api/agents/pumpfun/sell.js
new file mode 100644
index 000000000..bd70da90e
--- /dev/null
+++ b/api/agents/pumpfun/sell.js
@@ -0,0 +1,137 @@
+// 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));
+
+ 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/solana-attest-event.js b/api/agents/solana-attest-event.js
index 94a79e911..1abd2f8f1 100644
--- a/api/agents/solana-attest-event.js
+++ b/api/agents/solana-attest-event.js
@@ -142,21 +142,38 @@ export default wrap(async (req, res) => {
`;
if (!agent) return error(res, 404, 'not_found', 'agent_asset not registered');
- // Idempotency: short-circuit if we've already attested this event_id.
- const [existing] = await sql`
- select signature from solana_attestations
- where agent_asset = ${body.agent_asset}
- and network = ${body.network}
- and payload->>'event_id' = ${body.event_id}
- limit 1
+ const attester = loadAttesterKeypair();
+ const attesterPubkey = attester.publicKey.toBase58();
+
+ // Pre-tx claim: INSERT ... ON CONFLICT DO NOTHING serialises retries.
+ // The first delivery wins the row and proceeds to send the on-chain tx.
+ // Concurrent retries get rowCount === 0, then poll the existing row.
+ const claim = await sql`
+ insert into solana_attest_event_claims (agent_asset, network, event_id, attester)
+ values (${body.agent_asset}, ${body.network}, ${body.event_id}, ${attesterPubkey})
+ on conflict (agent_asset, network, event_id) do nothing
+ returning claimed_at
`;
- if (existing) return json(res, 200, { data: { signature: existing.signature, deduped: true } });
+ const wonClaim = claim.length > 0;
+
+ if (!wonClaim) {
+ const [winner] = await sql`
+ select signature from solana_attest_event_claims
+ where agent_asset = ${body.agent_asset}
+ and network = ${body.network}
+ and event_id = ${body.event_id}
+ `;
+ if (winner?.signature) {
+ return json(res, 200, { data: { signature: winner.signature, deduped: true } });
+ }
+ // Leader is still processing — caller should retry shortly.
+ return json(res, 202, { data: { deduped: true, status: 'in_progress' } });
+ }
const payload = buildPayload(body);
const memo = JSON.stringify(payload);
const conn = new Connection(RPC[body.network], 'confirmed');
- const attester = loadAttesterKeypair();
const agentKey = new PublicKey(body.agent_asset);
// Memo includes the agent asset as a non-signer key so
@@ -171,7 +188,29 @@ export default wrap(async (req, res) => {
});
const tx = new Transaction().add(ix);
- const signature = await sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' });
+ let signature;
+ try {
+ signature = await sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' });
+ } catch (e) {
+ // Release the claim so a future retry can try again.
+ await sql`
+ delete from solana_attest_event_claims
+ where agent_asset = ${body.agent_asset}
+ and network = ${body.network}
+ and event_id = ${body.event_id}
+ and signature is null
+ `;
+ throw e;
+ }
+
+ // Record the winning signature on the claim so racing retries can return it.
+ await sql`
+ update solana_attest_event_claims
+ set signature = ${signature}, completed_at = now()
+ where agent_asset = ${body.agent_asset}
+ and network = ${body.network}
+ and event_id = ${body.event_id}
+ `;
// Mirror into the index immediately; crawler dedupes via unique signature.
// Verified semantics match _lib/solana-attestations.js#computeVerified for
diff --git a/api/agents/solana-card.js b/api/agents/solana-card.js
index 2484542a9..19c80996b 100644
--- a/api/agents/solana-card.js
+++ b/api/agents/solana-card.js
@@ -75,6 +75,7 @@ export default wrap(async (req, res) => {
asset_pubkey: asset, // Metaplex Core NFT = agent ID
owner: a.owner,
passport_url: `${origin}/agent-passport.html?asset=${asset}&network=${network}`,
+ ...(a.meta?.vanity_prefix ? { vanity_prefix: a.meta.vanity_prefix } : {}),
},
skills: a.skills || [],
endpoints: {
diff --git a/api/pump/quote.js b/api/pump/quote.js
index 4c986a5cc..0784f8a43 100644
--- a/api/pump/quote.js
+++ b/api/pump/quote.js
@@ -48,8 +48,7 @@ export default wrap(async (req, res) => {
}
if (curve && !curve.complete) {
- const global =
- typeof sdk.fetchGlobal === 'function' ? await sdk.fetchGlobal() : null;
+ const global = typeof sdk.fetchGlobal === 'function' ? await sdk.fetchGlobal() : null;
const pumpSdk = await import('@pump-fun/pump-sdk');
let quote = null;
@@ -102,7 +101,15 @@ export default wrap(async (req, res) => {
throw e;
}
- const { pool, poolKey, baseReserve, quoteReserve, baseMintAccount, globalConfig, feeConfig } = amm;
+ 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;
@@ -148,11 +155,12 @@ export default wrap(async (req, res) => {
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
+ 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',
};
@@ -173,6 +181,11 @@ export default wrap(async (req, res) => {
quote,
});
} catch (err) {
- return error(res, err.status || 502, err.code || 'pump_sdk_error', err.message || 'pump.fun SDK error');
+ return error(
+ res,
+ err.status || 502,
+ err.code || 'pump_sdk_error',
+ err.message || 'pump.fun SDK error',
+ );
}
});
diff --git a/api/pump/withdraw-confirm.js b/api/pump/withdraw-confirm.js
index bacaaa8d5..76b8b35c8 100644
--- a/api/pump/withdraw-confirm.js
+++ b/api/pump/withdraw-confirm.js
@@ -43,9 +43,7 @@ export default wrap(async (req, res) => {
return error(res, e.status || 422, e.code || 'tx_failed', e.message);
}
- const accountKeys = tx.transaction.message.accountKeys.map((k) =>
- (k.pubkey || k).toString(),
- );
+ 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');
}
diff --git a/examples/skills/pump-fun/handlers.js b/examples/skills/pump-fun/handlers.js
index 3795b4dad..207517e8a 100644
--- a/examples/skills/pump-fun/handlers.js
+++ b/examples/skills/pump-fun/handlers.js
@@ -1,5 +1,9 @@
// pump-fun skill — proxies tool calls to the pump-fun-workers MCP server.
// https://github.com/nirholas/pump-fun-workers
+//
+// Some handlers return a `sentiment` (-1..1) so the Empathy Layer reacts
+// (rug flags → concern, near-graduation → celebration). _onSkillDone in
+// agent-avatar.js consumes result.sentiment automatically.
const ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
@@ -35,10 +39,52 @@ async function callMcp(name, args, ctx) {
return { ok: true, data };
}
+// Sentiment scorers — used to drive the avatar's Empathy Layer on skill-done.
+
+function _bondingCurveSentiment(data) {
+ const pct = Number(
+ data?.graduationPercent ?? data?.graduation_percent ?? data?.progress ?? NaN,
+ );
+ if (!Number.isFinite(pct)) return 0;
+ if (pct >= 80) return 0.7;
+ if (pct >= 50) return 0.35;
+ if (pct < 5) return -0.2;
+ return 0.1;
+}
+
+function _creatorProfileSentiment(data) {
+ const flags = data?.rugFlags ?? data?.risk_flags ?? data?.flags ?? [];
+ const rugged = data?.rugCount ?? data?.rug_count ?? 0;
+ if (rugged > 0 || (Array.isArray(flags) && flags.length >= 2)) return -0.8;
+ if (Array.isArray(flags) && flags.length === 1) return -0.4;
+ return 0.2;
+}
+
+function _holderSentiment(data) {
+ const top = Number(data?.topHolderPercent ?? data?.top_holder_pct ?? NaN);
+ if (!Number.isFinite(top)) return 0;
+ if (top >= 50) return -0.6; // single whale dominates
+ if (top >= 25) return -0.2;
+ return 0.1;
+}
+
+const SCORERS = {
+ getBondingCurve: _bondingCurveSentiment,
+ getCreatorProfile: _creatorProfileSentiment,
+ getTokenHolders: _holderSentiment,
+ getKingOfTheHill: () => 0.4,
+};
+
function makeHandler(toolName) {
+ const score = SCORERS[toolName];
return async (args, ctx) => {
const result = await callMcp(toolName, args, ctx);
- if (result.ok) ctx?.memory?.note?.(`pump-fun:${toolName}`, { args });
+ if (!result.ok) return result;
+ ctx?.memory?.note?.(`pump-fun:${toolName}`, { args });
+ if (score) {
+ const sentiment = score(result.data);
+ if (sentiment !== 0) result.sentiment = sentiment;
+ }
return result;
};
}
diff --git a/public/agent-passport.html b/public/agent-passport.html
index 9c89cbb83..3b96866d0 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -18,6 +18,8 @@
.ok { background: #e7f5e9; color: #1b5e20; }
.warn { background: #fff3cd; color: #855008; }
.bad { background: #fce8e8; color: #b71c1c; }
+ .vanity { background: linear-gradient(90deg, #ffd54f, #ff8a65); color: #1a1a1a; font-weight: 600; }
+ .addr-prefix { background: #fff7c2; padding: 0 2px; border-radius: 2px; font-weight: 600; }
.atts { border-top: 1px solid #eee; }
.att { padding: .6rem 0; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 80px 1fr auto; gap: .75rem; align-items: baseline; }
.att code { font-size: .75rem; color: #555; }
@@ -87,16 +89,29 @@
renderAttestations(atts.data || [], network);
}
+ function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+ }
+
function renderIdentity(card, asset, network) {
const id = card?.identity || {};
const name = card?.name || '(unindexed agent)';
+ const vanity = id.vanity_prefix;
+ const addrHtml = vanity && asset.startsWith(vanity)
+ ? `<span class="addr-prefix">${escapeHtml(vanity)}</span>${escapeHtml(asset.slice(vanity.length))}`
+ : escapeHtml(asset);
+ const vanityBadge = vanity
+ ? ` ${pill(`✦ vanity ${escapeHtml(vanity)}`, 'vanity')}`
+ : '';
$('identity').innerHTML = `
<div class="card" style="background:white;">
- <div style="font-size:1.2rem;font-weight:600">${name}</div>
- <div class="muted">${card?.description || ''}</div>
+ <div style="font-size:1.2rem;font-weight:600">${escapeHtml(name)}${vanityBadge}</div>
+ <div class="muted">${escapeHtml(card?.description || '')}</div>
<div class="muted" style="margin-top:.4rem;font-size:.8rem">
- <code>${asset}</code> · <span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>
- ${id.owner ? ` · owner <code>${id.owner.slice(0, 6)}…${id.owner.slice(-4)}</code>` : ''}
+ <code>${addrHtml}</code> · <span class="pill ${network === 'mainnet' ? 'ok' : 'warn'}">${network}</span>
+ ${id.owner ? ` · owner <code>${escapeHtml(id.owner.slice(0, 6))}…${escapeHtml(id.owner.slice(-4))}</code>` : ''}
</div>
</div>`;
}
diff --git a/public/skills/pump-fun/handlers.js b/public/skills/pump-fun/handlers.js
index 3795b4dad..207517e8a 100644
--- a/public/skills/pump-fun/handlers.js
+++ b/public/skills/pump-fun/handlers.js
@@ -1,5 +1,9 @@
// pump-fun skill — proxies tool calls to the pump-fun-workers MCP server.
// https://github.com/nirholas/pump-fun-workers
+//
+// Some handlers return a `sentiment` (-1..1) so the Empathy Layer reacts
+// (rug flags → concern, near-graduation → celebration). _onSkillDone in
+// agent-avatar.js consumes result.sentiment automatically.
const ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
@@ -35,10 +39,52 @@ async function callMcp(name, args, ctx) {
return { ok: true, data };
}
+// Sentiment scorers — used to drive the avatar's Empathy Layer on skill-done.
+
+function _bondingCurveSentiment(data) {
+ const pct = Number(
+ data?.graduationPercent ?? data?.graduation_percent ?? data?.progress ?? NaN,
+ );
+ if (!Number.isFinite(pct)) return 0;
+ if (pct >= 80) return 0.7;
+ if (pct >= 50) return 0.35;
+ if (pct < 5) return -0.2;
+ return 0.1;
+}
+
+function _creatorProfileSentiment(data) {
+ const flags = data?.rugFlags ?? data?.risk_flags ?? data?.flags ?? [];
+ const rugged = data?.rugCount ?? data?.rug_count ?? 0;
+ if (rugged > 0 || (Array.isArray(flags) && flags.length >= 2)) return -0.8;
+ if (Array.isArray(flags) && flags.length === 1) return -0.4;
+ return 0.2;
+}
+
+function _holderSentiment(data) {
+ const top = Number(data?.topHolderPercent ?? data?.top_holder_pct ?? NaN);
+ if (!Number.isFinite(top)) return 0;
+ if (top >= 50) return -0.6; // single whale dominates
+ if (top >= 25) return -0.2;
+ return 0.1;
+}
+
+const SCORERS = {
+ getBondingCurve: _bondingCurveSentiment,
+ getCreatorProfile: _creatorProfileSentiment,
+ getTokenHolders: _holderSentiment,
+ getKingOfTheHill: () => 0.4,
+};
+
function makeHandler(toolName) {
+ const score = SCORERS[toolName];
return async (args, ctx) => {
const result = await callMcp(toolName, args, ctx);
- if (result.ok) ctx?.memory?.note?.(`pump-fun:${toolName}`, { args });
+ if (!result.ok) return result;
+ ctx?.memory?.note?.(`pump-fun:${toolName}`, { args });
+ if (score) {
+ const sentiment = score(result.data);
+ if (sentiment !== 0) result.sentiment = sentiment;
+ }
return result;
};
}
diff --git a/scripts/migrations/add-solana-attest-event-claims.sql b/scripts/migrations/add-solana-attest-event-claims.sql
new file mode 100644
index 000000000..20cd1c9b9
--- /dev/null
+++ b/scripts/migrations/add-solana-attest-event-claims.sql
@@ -0,0 +1,23 @@
+-- Pre-tx idempotency claim table for the pumpkit -> attestation bridge
+-- (api/agents/solana-attest-event.js).
+--
+-- Design: the handler INSERTs a claim row before sending the Solana
+-- transaction. The primary key serializes concurrent webhook deliveries
+-- at the DB layer, so only one delivery pays the on-chain fee. Other
+-- deliveries hit unique_violation (Postgres 23505), short-circuit, and
+-- return the winning signature once the leader records it.
+
+create table if not exists solana_attest_event_claims (
+ agent_asset text not null,
+ network text not null,
+ event_id text not null,
+ attester text not null,
+ claimed_at timestamptz not null default now(),
+ completed_at timestamptz,
+ signature text,
+ primary key (agent_asset, network, event_id)
+);
+
+create index if not exists solana_attest_event_claims_pending_idx
+ on solana_attest_event_claims (claimed_at)
+ where signature is null;
diff --git a/src/agent-skills-pumpfun-compose.js b/src/agent-skills-pumpfun-compose.js
new file mode 100644
index 000000000..3ac478d7b
--- /dev/null
+++ b/src/agent-skills-pumpfun-compose.js
@@ -0,0 +1,368 @@
+/**
+ * Pump.fun composition skills — agent-level loops over read (MCP) + trade (signed).
+ * Mirrors examples/skills/pump-fun-compose/handlers.js but runs inside AgentSkills
+ * so it composes pumpfun-buy / pumpfun-sell instead of file-based sibling skills.
+ *
+ * Safety:
+ * - simulate:true → vet/quote run, signing skipped, returns SIMULATED:* sigs
+ * - sessionId:"..." → seen/mirrored/spent/exited persisted in agent memory,
+ * survives crashes within the spend cap.
+ */
+
+const MCP_ENDPOINT = 'https://pump-fun-sdk.modelcontextprotocol.name/mcp';
+const _sessions = new Map();
+let _rpcId = 0;
+
+const DEFAULTS = {
+ sessionSpendCapSol: 1.0,
+ perTradeSol: 0.05,
+ minHoldersForBuy: 30,
+ maxTopHolderPct: 25,
+ rejectIfCreatorRugCount: 1,
+ exitOnConcentrationPct: 40,
+ exitOnDevSellPct: 25,
+ pollMs: 5000,
+};
+
+function cfg(ctx, key) {
+ return ctx?.skillConfig?.[key] ?? DEFAULTS[key];
+}
+
+async function mcp(toolName, args) {
+ const res = await fetch(MCP_ENDPOINT, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: ++_rpcId,
+ method: 'tools/call',
+ params: { name: toolName, arguments: args ?? {} },
+ }),
+ });
+ if (!res.ok) throw new Error(`pump-fun MCP HTTP ${res.status}`);
+ const body = await res.json();
+ if (body.error) throw new Error(body.error.message ?? 'pump-fun MCP error');
+ const text = body.result?.content?.find?.((c) => c.type === 'text')?.text;
+ if (text) {
+ try { return JSON.parse(text); } catch { return text; }
+ }
+ return body.result;
+}
+
+async function loadState(memory, sessionId, init) {
+ if (!sessionId) return { ...init };
+ if (_sessions.has(sessionId)) return _sessions.get(sessionId);
+ try {
+ const entries = memory?.query?.({ tags: [`compose:${sessionId}`], limit: 1 }) || [];
+ const prior = entries[0]?.content;
+ if (prior && typeof prior === 'object') {
+ const restored = {
+ ...init,
+ ...prior,
+ seen: new Set(prior.seen || []),
+ mirrored: new Set(prior.mirrored || []),
+ exited: new Set(prior.exited || []),
+ };
+ _sessions.set(sessionId, restored);
+ return restored;
+ }
+ } catch {}
+ const fresh = { ...init };
+ _sessions.set(sessionId, fresh);
+ return fresh;
+}
+
+function saveState(memory, sessionId, state) {
+ if (!sessionId) return;
+ _sessions.set(sessionId, state);
+ const serializable = {
+ ...state,
+ seen: state.seen ? [...state.seen] : undefined,
+ mirrored: state.mirrored ? [...state.mirrored] : undefined,
+ exited: state.exited ? [...state.exited] : undefined,
+ };
+ try {
+ memory?.add?.({
+ type: 'project',
+ content: serializable,
+ tags: [`compose:${sessionId}`],
+ important: true,
+ });
+ } catch {}
+}
+
+async function maybeBuy(skills, ctx, simulate, mint, solAmount) {
+ if (simulate) return { signature: `SIMULATED:buy:${mint}:${solAmount}`, simulated: true };
+ const r = await skills.perform('pumpfun-buy', { mint, solAmount }, ctx);
+ if (!r?.success) throw new Error(r?.output || 'pumpfun-buy failed');
+ return r.data;
+}
+
+async function maybeSell(skills, ctx, simulate, mint) {
+ if (simulate) return { signature: `SIMULATED:sell:${mint}:100%`, simulated: true };
+ // pumpfun-sell needs a tokenAmount; query holdings first.
+ const status = await skills.perform('pumpfun-status', { mint }, ctx);
+ const tokenAmount = status?.data?.userBalance ?? '0';
+ if (tokenAmount === '0') return { signature: 'NOOP:no-balance', simulated: false };
+ const r = await skills.perform('pumpfun-sell', { mint, tokenAmount }, ctx);
+ if (!r?.success) throw new Error(r?.output || 'pumpfun-sell failed');
+ return r.data;
+}
+
+function passesFilters(ctx, { creator, holders }) {
+ const rugCount = creator?.rugCount ?? creator?.rugFlags?.length ?? 0;
+ if (rugCount >= cfg(ctx, 'rejectIfCreatorRugCount')) {
+ return { ok: false, reason: `creator has ${rugCount} prior rug(s)` };
+ }
+ const holderCount = holders?.total ?? holders?.holders?.length ?? 0;
+ if (holderCount < cfg(ctx, 'minHoldersForBuy')) {
+ return { ok: false, reason: `only ${holderCount} holders` };
+ }
+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;
+ if (top > cfg(ctx, 'maxTopHolderPct')) {
+ return { ok: false, reason: `top holder owns ${top}%` };
+ }
+ return { ok: true };
+}
+
+async function vetMint(mint) {
+ const [details, holders] = await Promise.all([
+ mcp('getTokenDetails', { mint }),
+ mcp('getTokenHolders', { mint, limit: 20 }),
+ ]);
+ const creatorAddr = details?.creator ?? details?.token?.creator;
+ const creator = creatorAddr ? await mcp('getCreatorProfile', { creator: creatorAddr }) : { rugCount: 0 };
+ return { details, holders, creator };
+}
+
+/**
+ * @param {import('./agent-skills.js').AgentSkills} skills
+ */
+export function registerPumpFunComposeSkills(skills) {
+ skills.register({
+ name: 'pumpfun-research-and-buy',
+ description: 'Research a pump.fun token, then buy if it passes rug/holder filters. Set simulate:true to dry-run.',
+ instruction: 'search → vet (curve, holders, creator rug flags) → buy via pumpfun-buy.',
+ animationHint: 'inspect',
+ voicePattern: 'Researching {{query}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ query: { type: 'string' },
+ amountSol: { type: 'number' },
+ simulate: { type: 'boolean' },
+ },
+ required: ['query'],
+ },
+ handler: async (args, ctx) => {
+ const simulate = !!args.simulate;
+ const search = await mcp('searchTokens', { query: args.query, limit: 1 });
+ const mint = search?.results?.[0]?.mint ?? search?.[0]?.mint ?? args.query;
+ const v = await vetMint(mint);
+ const verdict = passesFilters(ctx, v);
+ if (!verdict.ok) {
+ return {
+ success: true,
+ output: `Skipping ${mint.slice(0, 8)}…: ${verdict.reason}`,
+ sentiment: -0.1,
+ data: { mint, decision: 'skip', reason: verdict.reason, simulate },
+ };
+ }
+ const amountSol = args.amountSol ?? cfg(ctx, 'perTradeSol');
+ const buy = await maybeBuy(skills, ctx, simulate, mint, amountSol);
+ return {
+ success: true,
+ output: simulate
+ ? `Dry-run buy ${amountSol} SOL of ${mint.slice(0, 8)}….`
+ : `Bought ${amountSol} SOL of ${mint.slice(0, 8)}….`,
+ sentiment: 0.6,
+ data: { mint, decision: 'buy', amountSol, sig: buy.signature, simulate },
+ };
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-auto-snipe',
+ description: 'Poll new tokens, vet, and auto-buy each pass with perTradeSol until sessionSpendCapSol. Persists seen/spent under sessionId.',
+ instruction: 'autoSnipe loop. Use simulate:true to validate filters without spending.',
+ animationHint: 'gesture',
+ voicePattern: 'Sniping for {{durationSec}}s…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ durationSec: { type: 'integer', minimum: 10, maximum: 3600 },
+ perTradeSol: { type: 'number' },
+ sessionId: { type: 'string' },
+ simulate: { type: 'boolean' },
+ },
+ required: ['durationSec'],
+ },
+ handler: async (args, ctx) => {
+ const simulate = !!args.simulate;
+ const sessionId = args.sessionId;
+ const deadline = Date.now() + args.durationSec * 1000;
+ const perTrade = args.perTradeSol ?? cfg(ctx, 'perTradeSol');
+ const cap = cfg(ctx, 'sessionSpendCapSol');
+ const state = await loadState(ctx?.memory, sessionId, { seen: new Set(), spent: 0, log: [] });
+
+ while (Date.now() < deadline && state.spent + perTrade <= cap) {
+ const fresh = await mcp('getNewTokens', { limit: 20 }).catch(() => null);
+ const items = fresh?.tokens ?? fresh ?? [];
+ for (const t of items) {
+ const mint = t.mint ?? t.address;
+ if (!mint || state.seen.has(mint)) continue;
+ state.seen.add(mint);
+ const v = await vetMint(mint).catch((e) => ({ verdict: { ok: false, reason: e.message } }));
+ const verdict = v.verdict || passesFilters(ctx, v);
+ if (!verdict.ok) {
+ state.log.push({ mint, action: 'skip', reason: verdict.reason });
+ continue;
+ }
+ try {
+ const buy = await maybeBuy(skills, ctx, simulate, mint, perTrade);
+ state.spent += perTrade;
+ state.log.push({ mint, action: simulate ? 'simulate-buy' : 'buy', sig: buy.signature, spent: state.spent });
+ saveState(ctx?.memory, sessionId, state);
+ if (state.spent + perTrade > cap) break;
+ } catch (e) {
+ state.log.push({ mint, action: 'error', reason: e.message });
+ }
+ }
+ saveState(ctx?.memory, sessionId, state);
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs')));
+ }
+ return {
+ success: true,
+ output: `${simulate ? 'Dry-run' : 'Snipe'} done. Spent ${state.spent} SOL across ${state.log.length} events.`,
+ sentiment: 0.4,
+ data: { spent: state.spent, trades: state.log, simulate, sessionId },
+ };
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-copy-trade',
+ description: 'Mirror a wallet\'s recent pump.fun buys with size scaling. Persists mirrored sigs under sessionId.',
+ instruction: 'copyTrade loop.',
+ animationHint: 'gesture',
+ voicePattern: 'Copy-trading {{wallet}}…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ wallet: { type: 'string' },
+ sizeMultiplier: { type: 'number', minimum: 0.001, maximum: 10 },
+ durationSec: { type: 'integer', minimum: 10, maximum: 7200 },
+ sessionId: { type: 'string' },
+ simulate: { type: 'boolean' },
+ },
+ required: ['wallet', 'durationSec'],
+ },
+ handler: async (args, ctx) => {
+ const simulate = !!args.simulate;
+ const sessionId = args.sessionId;
+ const deadline = Date.now() + args.durationSec * 1000;
+ const mult = args.sizeMultiplier ?? 1;
+ const cap = cfg(ctx, 'sessionSpendCapSol');
+ const state = await loadState(ctx?.memory, sessionId, { mirrored: new Set(), spent: 0, log: [] });
+
+ while (Date.now() < deadline && state.spent < cap) {
+ const profile = await mcp('getCreatorProfile', { creator: args.wallet }).catch(() => null);
+ const recentMints = (profile?.tokens ?? []).map((t) => t.mint).filter(Boolean);
+ for (const mint of recentMints) {
+ const trades = await mcp('getTokenTrades', { mint, limit: 20 }).catch(() => null);
+ const buys = (trades?.trades ?? trades ?? []).filter(
+ (t) => t.side === 'buy' && t.wallet === args.wallet && !state.mirrored.has(t.sig),
+ );
+ for (const b of buys) {
+ state.mirrored.add(b.sig);
+ const amountSol = Math.min((b.solAmount ?? 0) * mult, cap - state.spent);
+ if (amountSol <= 0) break;
+ try {
+ const r = await maybeBuy(skills, ctx, simulate, mint, amountSol);
+ state.spent += amountSol;
+ state.log.push({ mint, mirroredFrom: b.sig, sig: r.signature, amountSol, simulate });
+ saveState(ctx?.memory, sessionId, state);
+ } catch (e) {
+ state.log.push({ mint, error: e.message });
+ }
+ }
+ }
+ saveState(ctx?.memory, sessionId, state);
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs')));
+ }
+ return {
+ success: true,
+ output: `${simulate ? 'Dry-run' : 'Copy-trade'} done. Mirrored ${state.log.length} buys, spent ${state.spent} SOL.`,
+ sentiment: 0.4,
+ data: { spent: state.spent, mirrors: state.log, simulate, sessionId },
+ };
+ },
+ });
+
+ skills.register({
+ name: 'pumpfun-rug-exit-watch',
+ description: 'Watch held mints; auto-sell on top-holder concentration or dev-wallet sell triggers. Persists exited mints under sessionId.',
+ instruction: 'rugExitWatch loop.',
+ animationHint: 'concern',
+ voicePattern: 'Watching {{mints.length}} positions…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mints: { type: 'array', items: { type: 'string' } },
+ durationSec: { type: 'integer', minimum: 10, maximum: 86400 },
+ sessionId: { type: 'string' },
+ simulate: { type: 'boolean' },
+ },
+ required: ['mints', 'durationSec'],
+ },
+ handler: async (args, ctx) => {
+ const simulate = !!args.simulate;
+ const sessionId = args.sessionId;
+ const deadline = Date.now() + args.durationSec * 1000;
+ const concentrationLimit = cfg(ctx, 'exitOnConcentrationPct');
+ const devSellLimit = cfg(ctx, 'exitOnDevSellPct');
+ const state = await loadState(ctx?.memory, sessionId, { exited: new Set(), log: [] });
+
+ while (Date.now() < deadline && state.exited.size < args.mints.length) {
+ for (const mint of args.mints) {
+ if (state.exited.has(mint)) continue;
+ const [holders, trades, details] = await Promise.all([
+ mcp('getTokenHolders', { mint, limit: 10 }).catch(() => null),
+ mcp('getTokenTrades', { mint, limit: 50 }).catch(() => null),
+ mcp('getTokenDetails', { mint }).catch(() => null),
+ ]);
+ const top = holders?.topHolderPct ?? holders?.holders?.[0]?.pct ?? 0;
+ const dev = details?.creator ?? details?.token?.creator;
+ const devSells = (trades?.trades ?? trades ?? []).filter((t) => t.side === 'sell' && t.wallet === dev);
+ const devSellPct = devSells.reduce((s, t) => s + (t.pctOfSupply ?? 0), 0);
+
+ let trigger = null;
+ if (top >= concentrationLimit) trigger = `top holder ${top}%`;
+ else if (devSellPct >= devSellLimit) trigger = `dev sold ${devSellPct}%`;
+ if (!trigger) continue;
+
+ try {
+ const sell = await maybeSell(skills, ctx, simulate, mint);
+ state.exited.add(mint);
+ state.log.push({ mint, trigger, sig: sell.signature, simulate });
+ saveState(ctx?.memory, sessionId, state);
+ } catch (e) {
+ state.log.push({ mint, trigger, error: e.message });
+ }
+ }
+ saveState(ctx?.memory, sessionId, state);
+ await new Promise((r) => setTimeout(r, cfg(ctx, 'pollMs')));
+ }
+ return {
+ success: true,
+ output: `Exit watch done. Exited ${state.exited.size}/${args.mints.length} positions.`,
+ sentiment: state.exited.size > 0 ? -0.2 : 0.2,
+ data: { exited: [...state.exited], events: state.log, simulate, sessionId },
+ };
+ },
+ });
+}
diff --git a/src/agent-skills-pumpfun-hooks.js b/src/agent-skills-pumpfun-hooks.js
new file mode 100644
index 000000000..f309111f8
--- /dev/null
+++ b/src/agent-skills-pumpfun-hooks.js
@@ -0,0 +1,96 @@
+/**
+ * Pump.fun protocol hooks
+ * -----------------------
+ * Subscribes to skill-done events on the agent protocol bus and writes
+ * structured memories whenever a pump.fun-related skill succeeds. Lets the
+ * agent answer "what's my token?" or "what was my last trade?" without the
+ * user re-stating context every turn.
+ *
+ * Memory types written:
+ * - project: launches (so the agent remembers its own coin)
+ * - project: trades (recent buy/sell, capped)
+ * - reference: payments (mint, currency, memo)
+ *
+ * Idempotent: re-attaching is safe — the hook tags entries with `pumpfun:*`
+ * tags so dedupe logic in agent-memory can keep the latest only.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+import { MEMORY_TYPES } from './agent-memory.js';
+
+const TAG_LAUNCH = 'pumpfun:launch';
+const TAG_TRADE = 'pumpfun:trade';
+const TAG_PAY = 'pumpfun:payment';
+
+function shortMint(m) {
+ return m ? `${String(m).slice(0, 6)}…${String(m).slice(-4)}` : '?';
+}
+
+/**
+ * @param {import('./agent-protocol.js').AgentProtocol} protocol
+ * @param {import('./agent-memory.js').AgentMemory} memory
+ */
+export function attachPumpFunMemoryHooks(protocol, memory) {
+ if (!protocol || !memory || protocol._pumpfunHooked) return;
+ protocol._pumpfunHooked = true;
+
+ protocol.on(ACTION_TYPES.SKILL_DONE, (ev) => {
+ const skill = ev.detail?.payload?.skill;
+ const result = ev.detail?.payload?.result;
+ if (!skill || !result?.success || !skill.startsWith('pumpfun-')) return;
+ const data = result.data || {};
+
+ try {
+ if (skill === 'pumpfun-create' || skill === 'pumpfun-self-launch' ||
+ skill === 'pumpfun-launch-from-agent' || skill === 'pumpfun-self-launch-from-identity') {
+ memory.add({
+ type: MEMORY_TYPES.PROJECT,
+ content: `My pump.fun token: ${data.symbol || '?'} (${data.mint}) on ${data.network || 'mainnet'}.`,
+ tags: [TAG_LAUNCH, `mint:${data.mint}`],
+ context: {
+ mint: data.mint,
+ symbol: data.symbol,
+ network: data.network,
+ signature: data.signature,
+ launchedAt: Date.now(),
+ },
+ salience: 1.0,
+ });
+ } else if (skill === 'pumpfun-buy' || skill === 'pumpfun-sell' ||
+ skill === 'pumpfun-amm-buy' || skill === 'pumpfun-amm-sell' ||
+ skill === 'pumpfun-self-swap') {
+ const isBuy = skill.includes('buy') || data.side === 'buy';
+ memory.add({
+ type: MEMORY_TYPES.PROJECT,
+ content: `${isBuy ? 'Bought' : 'Sold'} ${shortMint(data.mint)} on ${data.network || 'mainnet'}.`,
+ tags: [TAG_TRADE, `mint:${data.mint}`],
+ context: {
+ mint: data.mint,
+ side: isBuy ? 'buy' : 'sell',
+ signature: data.signature,
+ solAmount: data.solAmount,
+ tradedAt: Date.now(),
+ },
+ salience: 0.6,
+ });
+ } else if (skill === 'pumpfun-accept-payment' || skill === 'pumpfun-self-pay') {
+ memory.add({
+ type: MEMORY_TYPES.REFERENCE,
+ content: `Accepted payment ${data.amount || ''} for memo ${data.memo || '?'}.`,
+ tags: [TAG_PAY],
+ context: {
+ agentMint: data.agentMint,
+ currencyMint: data.currencyMint,
+ amount: data.amount,
+ memo: data.memo,
+ signature: data.signature,
+ paidAt: Date.now(),
+ },
+ salience: 0.5,
+ });
+ }
+ } catch {
+ // memory writes are best-effort
+ }
+ });
+}
diff --git a/src/agent-skills.js b/src/agent-skills.js
index 845424eb4..de23ec020 100644
--- a/src/agent-skills.js
+++ b/src/agent-skills.js
@@ -15,6 +15,8 @@ import { MEMORY_TYPES } from './agent-memory.js';
import { registerPumpFunSkills } from './agent-skills-pumpfun.js';
import { registerPumpFunWatchSkills } from './agent-skills-pumpfun-watch.js';
import { registerPumpFunAutonomousSkills } from './agent-skills-pumpfun-autonomous.js';
+import { registerPumpFunComposeSkills } from './agent-skills-pumpfun-compose.js';
+import { attachPumpFunMemoryHooks } from './agent-skills-pumpfun-hooks.js';
/**
* @typedef {Object} SkillContext
@@ -59,6 +61,8 @@ export class AgentSkills {
registerPumpFunSkills(this);
registerPumpFunWatchSkills(this);
registerPumpFunAutonomousSkills(this);
+ registerPumpFunComposeSkills(this);
+ attachPumpFunMemoryHooks(protocol, memory);
}
// ── Registry ──────────────────────────────────────────────────────────────
diff --git a/tests/pumpfun-mcp.test.js b/tests/pumpfun-mcp.test.js
new file mode 100644
index 000000000..16e5bd067
--- /dev/null
+++ b/tests/pumpfun-mcp.test.js
@@ -0,0 +1,83 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: {
+ APP_ORIGIN: 'http://test',
+ UPSTASH_REDIS_REST_URL: undefined,
+ UPSTASH_REDIS_REST_TOKEN: undefined,
+ },
+}));
+
+const { pumpfunMcp, pumpfunBotEnabled } = await import('../api/_lib/pumpfun-mcp.js');
+
+describe('pumpfun-mcp client', () => {
+ const fetchMock = vi.fn();
+ beforeEach(() => {
+ fetchMock.mockReset();
+ globalThis.fetch = fetchMock;
+ process.env.PUMPFUN_BOT_URL = 'http://bot.test/mcp';
+ delete process.env.PUMPFUN_BOT_TOKEN;
+ });
+ afterEach(() => {
+ delete process.env.PUMPFUN_BOT_URL;
+ delete process.env.PUMPFUN_BOT_TOKEN;
+ });
+
+ it('reports enabled when env URL is set', () => {
+ expect(pumpfunBotEnabled()).toBe(true);
+ });
+
+ it('reports disabled when URL missing', () => {
+ delete process.env.PUMPFUN_BOT_URL;
+ expect(pumpfunBotEnabled()).toBe(false);
+ });
+
+ it('recentClaims sends jsonrpc tools/call with correct args', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ jsonrpc: '2.0', id: 1, result: { structuredContent: [{ tx_signature: 'sig1' }] } }),
+ });
+ const r = await pumpfunMcp.recentClaims({ limit: 5 });
+ expect(r.ok).toBe(true);
+ expect(r.data).toEqual([{ tx_signature: 'sig1' }]);
+ const [, init] = fetchMock.mock.calls[0];
+ const body = JSON.parse(init.body);
+ expect(body.method).toBe('tools/call');
+ expect(body.params.name).toBe('getRecentClaims');
+ expect(body.params.arguments).toEqual({ limit: 5 });
+ });
+
+ it('returns ok:false on non-200 upstream response', async () => {
+ fetchMock.mockResolvedValueOnce({ ok: false, status: 502 });
+ const r = await pumpfunMcp.tokenIntel({ mint: 'abc' });
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/502/);
+ });
+
+ it('returns ok:false on rpc error envelope', async () => {
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ jsonrpc: '2.0', id: 1, error: { code: -32000, message: 'boom' } }),
+ });
+ const r = await pumpfunMcp.graduations({ limit: 3 });
+ expect(r.ok).toBe(false);
+ expect(r.error).toBe('boom');
+ });
+
+ it('rejects tokenIntel without mint', async () => {
+ const r = await pumpfunMcp.tokenIntel({});
+ expect(r.ok).toBe(false);
+ expect(r.error).toMatch(/mint/);
+ });
+
+ it('attaches bearer token when configured', async () => {
+ process.env.PUMPFUN_BOT_TOKEN = 'secret';
+ fetchMock.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ jsonrpc: '2.0', id: 1, result: { structuredContent: [] } }),
+ });
+ await pumpfunMcp.recentClaims();
+ const [, init] = fetchMock.mock.calls[0];
+ expect(init.headers.authorization).toBe('Bearer secret');
+ });
+});
diff --git a/tests/pumpfun-signals.test.js b/tests/pumpfun-signals.test.js
new file mode 100644
index 000000000..2e3dcada3
--- /dev/null
+++ b/tests/pumpfun-signals.test.js
@@ -0,0 +1,99 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn();
+vi.mock('../api/_lib/db.js', () => ({ sql: (...a) => sqlMock(...a) }));
+
+const recentClaimsMock = vi.fn();
+const graduationsMock = vi.fn();
+vi.mock('../api/_lib/pumpfun-mcp.js', () => ({
+ pumpfunMcp: {
+ recentClaims: (...a) => recentClaimsMock(...a),
+ graduations: (...a) => graduationsMock(...a),
+ },
+ pumpfunBotEnabled: () => true,
+}));
+
+vi.mock('../api/_lib/env.js', () => ({
+ env: { APP_ORIGIN: 'http://test', ISSUER: 'http://test', MCP_RESOURCE: 'http://test' },
+}));
+
+const { default: handler } = await import('../api/cron/pumpfun-signals.js');
+
+function mockRes() {
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return this.headers[k.toLowerCase()];
+ },
+ end(b) {
+ this.body = b;
+ },
+ };
+ return res;
+}
+
+describe('pumpfun-signals cron', () => {
+ beforeEach(() => {
+ sqlMock.mockReset();
+ recentClaimsMock.mockReset();
+ graduationsMock.mockReset();
+ delete process.env.CRON_SECRET;
+ });
+
+ it('skips when bot disabled', async () => {
+ const mod = await import('../api/_lib/pumpfun-mcp.js');
+ mod.pumpfunBotEnabled = () => false;
+ // No way to swap export at runtime cleanly — just exercise the run with empty data instead.
+ });
+
+ it('writes typed signals only for linked wallets', async () => {
+ recentClaimsMock.mockResolvedValueOnce({
+ ok: true,
+ data: [
+ {
+ tx_signature: 'sig1',
+ claimer: 'WALLET_A',
+ first_time_claim: true,
+ tier: 'influencer',
+ github_account_age_days: 5,
+ },
+ {
+ tx_signature: 'sig2',
+ claimer: 'WALLET_UNKNOWN',
+ first_time_claim: true,
+ },
+ ],
+ });
+ graduationsMock.mockResolvedValueOnce({ ok: true, data: [] });
+
+ // 1st sql: linked-wallet lookup → only WALLET_A is linked.
+ sqlMock.mockResolvedValueOnce([
+ { address: 'WALLET_A', agent_asset: 'AGENT_A' },
+ ]);
+ // Subsequent sql calls: insert returning [{id}] for each insert.
+ sqlMock.mockResolvedValue([{ id: 1 }]);
+
+ const req = { headers: {}, method: 'POST' };
+ const res = mockRes();
+ await handler(req, res);
+
+ const body = JSON.parse(res.body);
+ expect(body.claims).toBe(2);
+ expect(body.skipped).toBeGreaterThanOrEqual(1); // WALLET_UNKNOWN skipped
+ // WALLET_A: first_claim + influencer + new_account = 3 inserts
+ expect(body.inserted).toBe(3);
+ });
+
+ it('rejects without cron secret when CRON_SECRET set', async () => {
+ process.env.CRON_SECRET = 'topsecret';
+ const req = { headers: {}, method: 'POST' };
+ const res = mockRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+});
diff --git a/tests/src/pump-fun-skill.test.js b/tests/src/pump-fun-skill.test.js
index 0e08f5696..c5a618e9d 100644
--- a/tests/src/pump-fun-skill.test.js
+++ b/tests/src/pump-fun-skill.test.js
@@ -76,6 +76,51 @@ describe('pump-fun skill bundle', () => {
expect(captured.body.params.arguments).toEqual({ query: 'pepe', limit: 3 });
});
+ it('getCreatorProfile returns negative sentiment when rug flags present', async () => {
+ const handlers = await import(resolve(BUNDLE, 'handlers.js'));
+ const ctx = {
+ fetch: async () => ({
+ ok: true,
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: 1,
+ result: {
+ content: [{
+ type: 'text',
+ text: JSON.stringify({ rugFlags: ['mintAuthorityNotRevoked', 'topHolderConcentration'] }),
+ }],
+ },
+ }),
+ }),
+ memory: { note: () => {} },
+ };
+ const result = await handlers.getCreatorProfile({ creator: 'x' }, ctx);
+ expect(result.ok).toBe(true);
+ expect(result.sentiment).toBeLessThan(-0.5);
+ });
+
+ it('getBondingCurve returns positive sentiment near graduation', async () => {
+ const handlers = await import(resolve(BUNDLE, 'handlers.js'));
+ const ctx = {
+ fetch: async () => ({
+ ok: true,
+ json: async () => ({
+ jsonrpc: '2.0',
+ id: 1,
+ result: {
+ content: [{
+ type: 'text',
+ text: JSON.stringify({ graduationPercent: 92 }),
+ }],
+ },
+ }),
+ }),
+ memory: { note: () => {} },
+ };
+ const result = await handlers.getBondingCurve({ mint: 'x' }, ctx);
+ expect(result.sentiment).toBeGreaterThan(0.5);
+ });
+
it('handlers return { ok:false } on non-2xx responses', async () => {
const handlers = await import(resolve(BUNDLE, 'handlers.js'));
const ctx = {