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: implement token stats rendering and agent wallet assignment

nirholas9b72f28dcb73
diff --git a/api/_lib/migrations/2026-04-29-pump-relay-delegations.sql b/api/_lib/migrations/2026-04-29-pump-relay-delegations.sql
new file mode 100644
index 000000000..543bdebc6
--- /dev/null
+++ b/api/_lib/migrations/2026-04-29-pump-relay-delegations.sql
@@ -0,0 +1,52 @@
+-- Migration: hot-wallet relayer delegation table.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-29-pump-relay-delegations.sql
+-- Idempotent.
+--
+-- A row authorizes the server-held PUMP_RELAYER pubkey to execute pump.fun
+-- buys/sells on behalf of a user up to (max_sol_lamports cumulative spend)
+-- and (expires_at). The user signs an off-chain SIWS message granting this;
+-- /api/pump/relay-authorize records the row.
+--
+-- Writers: api/pump/relay-authorize.js, api/pump/relay-revoke.js
+-- Readers: api/pump/relay-trade.js
+
+begin;
+
+create table if not exists pump_trade_delegations (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid references agent_identities(id) on delete cascade,
+ relayer_pubkey text not null,
+ user_wallet text not null, -- the wallet that signed the SIWS authz
+ max_sol_lamports numeric(40, 0) not null default 0, -- cumulative cap across all trades
+ spent_sol_lamports numeric(40, 0) not null default 0,
+ direction_filter text check (direction_filter in ('buy','sell','both')) default 'both',
+ mint_filter text, -- optional: lock to a single mint
+ network text not null check (network in ('mainnet','devnet')),
+ expires_at timestamptz not null,
+ revoked_at timestamptz,
+ created_at timestamptz not null default now(),
+ siws_signature text -- proof of authz (base58)
+);
+create index if not exists pump_trade_delegations_user on pump_trade_delegations(user_id);
+create index if not exists pump_trade_delegations_active
+ on pump_trade_delegations(user_id, agent_id)
+ where revoked_at is null;
+
+create table if not exists pump_relay_trades (
+ id uuid primary key default gen_random_uuid(),
+ delegation_id uuid not null references pump_trade_delegations(id) on delete cascade,
+ direction text not null check (direction in ('buy','sell')),
+ mint text not null,
+ network text not null check (network in ('mainnet','devnet')),
+ route text not null check (route in ('bonding_curve','amm')),
+ sol_lamports numeric(40, 0),
+ token_amount numeric(40, 0),
+ tx_signature text not null,
+ created_at timestamptz not null default now(),
+ unique (tx_signature, network)
+);
+create index if not exists pump_relay_trades_delegation
+ on pump_relay_trades(delegation_id, created_at desc);
+
+commit;
diff --git a/api/_lib/pump-relayer.js b/api/_lib/pump-relayer.js
new file mode 100644
index 000000000..6815352bd
--- /dev/null
+++ b/api/_lib/pump-relayer.js
@@ -0,0 +1,37 @@
+// 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/_lib/siws.js b/api/_lib/siws.js
index 1efddf31b..91a3d9aee 100644
--- a/api/_lib/siws.js
+++ b/api/_lib/siws.js
@@ -1,7 +1,7 @@
// Sign-In with Solana (CAIP-122 / SIP-0) message parser and signature verifier.
// Message format mirrors SIWE but uses a base58 Solana address and string Chain ID.
-import { ed25519 } from '@noble/curves/ed25519';
+import { ed25519 } from '@noble/curves/ed25519.js';
import bs58 from 'bs58';
// ─── Parser ─────────────────────────────────────────────────────────────────
@@ -26,14 +26,30 @@ export function parseSiwsMessage(msg) {
const key = kv[1].trim();
const val = kv[2].trim();
switch (key) {
- case 'URI': out.uri = val; break;
- case 'Version': out.version = val; break;
- case 'Chain ID': out.chainId = val; break; // string: 'mainnet'|'devnet'|'testnet'
- case 'Nonce': out.nonce = val; break;
- case 'Issued At': out.issuedAt = val; break;
- case 'Expiration Time': out.expirationTime = val; break;
- case 'Not Before': out.notBefore = val; break;
- case 'Request ID': out.requestId = val; break;
+ case 'URI':
+ out.uri = val;
+ break;
+ case 'Version':
+ out.version = val;
+ break;
+ case 'Chain ID':
+ out.chainId = val;
+ break; // string: 'mainnet'|'devnet'|'testnet'
+ case 'Nonce':
+ out.nonce = val;
+ break;
+ case 'Issued At':
+ out.issuedAt = val;
+ break;
+ case 'Expiration Time':
+ out.expirationTime = val;
+ break;
+ case 'Not Before':
+ out.notBefore = val;
+ break;
+ case 'Request ID':
+ out.requestId = val;
+ break;
}
}
if (!out.uri || !out.nonce || !out.version) return null;
diff --git a/api/agents/solana-reputation.js b/api/agents/solana-reputation.js
index 388855646..1cdd290b6 100644
--- a/api/agents/solana-reputation.js
+++ b/api/agents/solana-reputation.js
@@ -24,13 +24,16 @@ export default wrap(async (req, res) => {
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const url = new URL(req.url, `http://${req.headers.host}`);
- const asset = url.searchParams.get('asset');
+ const url = new URL(req.url, `http://${req.headers.host}`);
+ const asset = url.searchParams.get('asset');
const network = url.searchParams.get('network') === 'mainnet' ? 'mainnet' : 'devnet';
if (!asset) return error(res, 400, 'validation_error', 'asset query param required');
- try { new PublicKey(asset); }
- catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }
+ try {
+ new PublicKey(asset);
+ } catch {
+ return error(res, 400, 'validation_error', 'invalid asset pubkey');
+ }
// One pass: feedback aggregates split by verified-task-acceptance, by
// SAS credentialing, and by event-attested provenance. Trust layers:
@@ -210,36 +213,36 @@ export default wrap(async (req, res) => {
pumpfun_signals: pumpfunSignals,
token_activity: tokenActivity,
feedback: {
- total: fb.total,
- verified: fb.verified,
- credentialed: fb.credentialed,
- event_attested: fb.event_attested,
- disputed: fb.disputed,
- unique_attesters: fb.unique_attesters,
- unique_verified_attesters: fb.unique_verified_attesters,
- unique_credentialed_attesters: fb.unique_credentialed_attesters,
- score_avg: Number(fb.score_avg.toFixed(3)),
- score_avg_verified: Number(fb.score_avg_verified.toFixed(3)),
- score_avg_credentialed: Number(fb.score_avg_credentialed.toFixed(3)),
- score_avg_event_attested: Number(fb.score_avg_event_attested.toFixed(3)),
- score_avg_weighted: Number(fb.score_avg_weighted.toFixed(3)),
- score_avg_weighted_verified: Number(fb.score_avg_weighted_verified.toFixed(3)),
- score_avg_weighted_credentialed: Number(fb.score_avg_weighted_credentialed.toFixed(3)),
+ total: fb.total,
+ verified: fb.verified,
+ credentialed: fb.credentialed,
+ event_attested: fb.event_attested,
+ disputed: fb.disputed,
+ unique_attesters: fb.unique_attesters,
+ unique_verified_attesters: fb.unique_verified_attesters,
+ unique_credentialed_attesters: fb.unique_credentialed_attesters,
+ score_avg: Number(fb.score_avg.toFixed(3)),
+ score_avg_verified: Number(fb.score_avg_verified.toFixed(3)),
+ score_avg_credentialed: Number(fb.score_avg_credentialed.toFixed(3)),
+ score_avg_event_attested: Number(fb.score_avg_event_attested.toFixed(3)),
+ score_avg_weighted: Number(fb.score_avg_weighted.toFixed(3)),
+ score_avg_weighted_verified: Number(fb.score_avg_weighted_verified.toFixed(3)),
+ score_avg_weighted_credentialed: Number(fb.score_avg_weighted_credentialed.toFixed(3)),
},
validation: {
- self_passed: val.passed,
- self_failed: val.failed,
- event_passed: val.event_passed,
- event_failed: val.event_failed,
+ self_passed: val.passed,
+ self_failed: val.failed,
+ event_passed: val.event_passed,
+ event_failed: val.event_failed,
audited_passed: auditedVal.passed,
audited_failed: auditedVal.failed,
},
tasks: {
- offered: counts.tasks_offered,
+ offered: counts.tasks_offered,
accepted: counts.tasks_accepted,
},
disputes_filed: counts.disputes_filed,
- revoked_count: counts.revoked_count,
+ revoked_count: counts.revoked_count,
last_indexed_at: cursor?.last_indexed_at || null,
});
});
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 95da9485b..f5dbe199b 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -1,18 +1,55 @@
// /api/agents/:id/solana
+//
// GET — return the agent's Solana address + SOL balance (owner only).
-// POST — provision a Solana wallet for this agent if it doesn't have one.
-// Idempotent: returns the existing address if already provisioned.
+// POST — provision a Solana wallet for this agent.
+// • No body: server generates a fresh random keypair.
+// • Body { secret_key, vanity_prefix? }: imports a user-grinded
+// keypair (e.g. from /vanity-wallet.html). Server verifies the
+// secret derives the claimed pubkey and the prefix matches.
+// Idempotent for "no body" + existing wallet (returns existing).
+// 409 if importing onto an agent that already has a wallet
+// (call DELETE first to replace).
+// DELETE — remove the agent's Solana wallet (clears address + secret).
//
// The encrypted secret never leaves the server. Signing is done by the
// pump.fun action endpoints in api/agents/pumpfun/*.
import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
-import { cors, json, method, error } from '../_lib/http.js';
+import { cors, json, method, error, readJson } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';
import { solanaConnection } from '../_lib/agent-pumpfun.js';
-import { PublicKey } from '@solana/web3.js';
+import { Keypair, PublicKey } from '@solana/web3.js';
+import { webcrypto } from 'node:crypto';
+import { env } from '../_lib/env.js';
+
+const subtle = globalThis.crypto?.subtle || webcrypto.subtle;
+
+// Mirror agent-wallet.js encryption — keep in sync.
+async function _deriveKey() {
+ const raw = new TextEncoder().encode(env.JWT_SECRET);
+ const base = await subtle.importKey('raw', raw, 'HKDF', false, ['deriveKey']);
+ return subtle.deriveKey(
+ { name: 'HKDF', hash: 'SHA-256', salt: new TextEncoder().encode('agent-wallet-v1'), info: new Uint8Array(0) },
+ base,
+ { name: 'AES-GCM', length: 256 },
+ false,
+ ['encrypt', 'decrypt'],
+ );
+}
+async function _encryptSecret(plaintext) {
+ const key = await _deriveKey();
+ const iv = new Uint8Array(12);
+ (globalThis.crypto || webcrypto).getRandomValues(iv);
+ const ct = await subtle.encrypt({ name: 'AES-GCM', iv }, key, new TextEncoder().encode(plaintext));
+ const buf = new Uint8Array(iv.length + ct.byteLength);
+ buf.set(iv, 0);
+ buf.set(new Uint8Array(ct), iv.length);
+ return Buffer.from(buf).toString('base64');
+}
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]+$/;
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -23,8 +60,8 @@ async function resolveAuth(req) {
}
export default async function handler(req, res, id) {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'POST'])) return;
+ 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');
@@ -41,12 +78,70 @@ export default async function handler(req, res, id) {
let meta = { ...(row.meta || {}) };
- if (req.method === 'POST' && !meta.solana_address) {
- const sol = await generateSolanaAgentWallet();
- meta = { ...meta, solana_address: sol.address, encrypted_solana_secret: sol.encrypted_secret };
- await sql`
- UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}
- `;
+ // ── DELETE ─────────────────────────────────────────────────────────────
+ if (req.method === 'DELETE') {
+ delete meta.solana_address;
+ delete meta.encrypted_solana_secret;
+ delete meta.solana_vanity_prefix;
+ delete meta.solana_wallet_source;
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ return json(res, 200, { data: { ok: true } });
+ }
+
+ // ── POST ───────────────────────────────────────────────────────────────
+ if (req.method === 'POST') {
+ const body = await readJson(req).catch(() => ({}));
+ const importing = body && (body.secret_key || body.vanity_prefix);
+
+ if (importing) {
+ // Validate secret_key shape: 64 numbers (Solana CLI / web3.js format).
+ const sk = body.secret_key;
+ if (!Array.isArray(sk) || sk.length !== 64 || !sk.every((n) => Number.isInteger(n) && n >= 0 && n <= 255)) {
+ return error(res, 400, 'validation_error', 'secret_key must be a 64-byte number array');
+ }
+
+ let kp;
+ try {
+ kp = Keypair.fromSecretKey(Uint8Array.from(sk));
+ } catch (e) {
+ return error(res, 400, 'validation_error', 'secret_key did not parse as a valid Solana keypair');
+ }
+ const address = kp.publicKey.toBase58();
+
+ if (body.vanity_prefix) {
+ if (!BASE58_RE.test(body.vanity_prefix) || body.vanity_prefix.length > 6) {
+ return error(res, 400, 'validation_error', 'vanity_prefix is not valid base58 (max 6 chars)');
+ }
+ if (!address.startsWith(body.vanity_prefix)) {
+ return error(res, 400, 'validation_error', 'vanity_prefix does not match the keypair address');
+ }
+ }
+
+ if (meta.solana_address) {
+ return error(res, 409, 'conflict',
+ 'agent already has a Solana wallet — DELETE /api/agents/:id/solana first to replace');
+ }
+
+ const encrypted_secret = await _encryptSecret(Buffer.from(kp.secretKey).toString('base64'));
+ meta = {
+ ...meta,
+ solana_address: address,
+ encrypted_solana_secret: encrypted_secret,
+ solana_wallet_source: 'imported_vanity',
+ ...(body.vanity_prefix ? { solana_vanity_prefix: body.vanity_prefix } : {}),
+ };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ } else if (!meta.solana_address) {
+ // No body, no existing wallet → server generates.
+ const sol = await generateSolanaAgentWallet();
+ meta = {
+ ...meta,
+ solana_address: sol.address,
+ encrypted_solana_secret: sol.encrypted_secret,
+ solana_wallet_source: 'generated',
+ };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ }
}
if (!meta.solana_address) {
@@ -62,12 +157,14 @@ export default async function handler(req, res, id) {
console.error('[agents/solana] balance fetch failed', err);
}
- return json(res, 200, {
+ return json(res, req.method === 'POST' ? 201 : 200, {
data: {
address: meta.solana_address,
network,
lamports,
sol: lamports == null ? null : lamports / 1e9,
+ vanity_prefix: meta.solana_vanity_prefix || null,
+ source: meta.solana_wallet_source || (meta.encrypted_solana_secret ? 'generated' : null),
},
});
}
diff --git a/api/cron/pump-agent-stats.js b/api/cron/pump-agent-stats.js
index 4d8da9924..ba0d85299 100644
--- a/api/cron/pump-agent-stats.js
+++ b/api/cron/pump-agent-stats.js
@@ -199,7 +199,8 @@ function derivePrice(stats) {
const totalTok =
BigInt(stats.bonding_curve.virtual_token || 0) +
BigInt(stats.bonding_curve.real_token || 0);
- const market_cap_lamports = totalTok > 0n ? BigInt(Math.floor(sol_per_token * Number(totalTok))) : null;
+ const market_cap_lamports =
+ totalTok > 0n ? BigInt(Math.floor(sol_per_token * Number(totalTok))) : null;
return { sol_per_token, market_cap_lamports, source: 'bonding_curve' };
}
}
diff --git a/api/pump/relay-authorize.js b/api/pump/relay-authorize.js
new file mode 100644
index 000000000..e34d853f7
--- /dev/null
+++ b/api/pump/relay-authorize.js
@@ -0,0 +1,87 @@
+// 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-revoke.js b/api/pump/relay-revoke.js
new file mode 100644
index 000000000..0a44b0969
--- /dev/null
+++ b/api/pump/relay-revoke.js
@@ -0,0 +1,37 @@
+// 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
new file mode 100644
index 000000000..74722669a
--- /dev/null
+++ b/api/pump/relay-trade.js
@@ -0,0 +1,217 @@
+// 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/public/agent-passport.html b/public/agent-passport.html
index 92176eb2a..c4b97facf 100644
--- a/public/agent-passport.html
+++ b/public/agent-passport.html
@@ -1,304 +1,694 @@
<!doctype html>
<html lang="en">
-<head>
- <meta charset="utf-8">
- <title>Agent passport · three.ws</title>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- <style>
- * { box-sizing: border-box; }
- :root {
- --fg: #111; --muted: #555; --border: #e5e5e5; --bg: #fafafa;
- --ok-bg: #e7f5e9; --ok-fg: #1b5e20;
- --warn-bg: #fff3cd; --warn-fg: #855008;
- --bad-bg: #fce8e8; --bad-fg: #b71c1c;
- --info-bg: #e3f2fd; --info-fg: #0d47a1;
- }
- body { font: 14px/1.5 system-ui, -apple-system, sans-serif; max-width: 880px; margin: 1.5rem auto; padding: 0 1rem; color: var(--fg); }
- h1 { font-size: 1.4rem; margin: 0 0 .25rem; }
- h2 { font-size: 1rem; margin: 1.5rem 0 .5rem; display: flex; align-items: baseline; gap: .5rem; }
- h2 .hint { font-weight: 400; font-size: .8rem; color: var(--muted); }
- .muted { color: var(--muted); }
- .row { display: flex; gap: .5rem; align-items: center; flex-wrap: wrap; margin: .5rem 0 1rem; }
- .row input { font: inherit; padding: .4rem .55rem; border: 1px solid var(--border); border-radius: 6px; flex: 1 1 320px; min-width: 0; }
- .row input.invalid { border-color: var(--bad-fg); background: #fff8f8; }
- .row select, .row button { font: inherit; padding: .4rem .65rem; border: 1px solid #ccc; background: #fff; border-radius: 6px; cursor: pointer; }
- .row button.primary { background: #111; color: #fff; border-color: #111; }
- .row button:disabled { opacity: .5; cursor: wait; }
-
- .identity-card { border: 1px solid var(--border); border-radius: 10px; padding: 1rem 1.1rem; background: #fff; }
- .identity-row { display: flex; align-items: center; gap: .75rem; flex-wrap: wrap; }
- .identity-name { font-size: 1.2rem; font-weight: 600; }
- .identity-meta { display: flex; gap: .5rem; flex-wrap: wrap; align-items: center; font-size: .8rem; color: var(--muted); margin-top: .35rem; }
- .identity-meta code { background: #f3f3f3; padding: .1rem .35rem; border-radius: 4px; font-size: .75rem; }
- .copy-btn { padding: .1rem .35rem; font-size: .7rem; line-height: 1.4; cursor: pointer; border: 1px solid var(--border); background: #fff; border-radius: 4px; }
- .copy-btn:hover { background: #f3f3f3; }
-
- .trust-bar { display: flex; align-items: center; gap: .75rem; margin-top: .75rem; padding: .65rem .85rem; border-radius: 8px; background: var(--bg); border: 1px solid var(--border); }
- .trust-bar .spark { margin-left: auto; flex: 0 0 120px; }
- .trust-bar .spark svg { width: 120px; height: 32px; display: block; }
- .trust-bar .spark-empty { font-size: .7rem; color: var(--muted); }
- .trust-grade { font-size: 1.6rem; font-weight: 700; min-width: 2rem; text-align: center; }
- .trust-A { color: var(--ok-fg); }
- .trust-B { color: #2e7d32; }
- .trust-C { color: var(--warn-fg); }
- .trust-D { color: #c62828; }
- .trust-NA { color: var(--muted); }
- .trust-summary { font-size: .85rem; color: var(--muted); }
-
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: .65rem; margin: .75rem 0; }
- .card { border: 1px solid var(--border); border-radius: 8px; padding: .65rem .85rem; background: var(--bg); position: relative; }
- .card .v { font-size: 1.55rem; font-weight: 600; line-height: 1.1; }
- .card .v small { font-size: 1rem; color: var(--muted); font-weight: 400; }
- .card .l { font-size: .75rem; color: var(--muted); margin-top: .15rem; display: flex; align-items: center; gap: .25rem; }
- .card.tier-credentialed { border-color: #b8d8e8; background: #f4faff; }
- .card.tier-event { border-color: #d4c5f0; background: #f8f4ff; }
- .card.tier-pump { border-color: #ffd8b8; background: #fff8f0; }
- .card.danger { border-color: #f5c6c6; background: #fff5f5; }
-
- .tip { display: inline-block; cursor: help; color: var(--muted); border: 1px solid var(--border); border-radius: 50%; width: 13px; height: 13px; font-size: 9px; line-height: 11px; text-align: center; }
-
- .pill { display: inline-block; padding: .1rem .55rem; border-radius: 999px; font-size: .7rem; line-height: 1.5; }
- .ok { background: var(--ok-bg); color: var(--ok-fg); }
- .warn { background: var(--warn-bg); color: var(--warn-fg); }
- .bad { background: var(--bad-bg); color: var(--bad-fg); }
- .info { background: var(--info-bg); color: var(--info-fg); }
- .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; }
-
- .filters { display: flex; gap: .35rem; flex-wrap: wrap; margin: .5rem 0 .75rem; }
- .chip { padding: .2rem .65rem; border: 1px solid var(--border); border-radius: 999px; cursor: pointer; font-size: .75rem; background: #fff; user-select: none; }
- .chip[aria-pressed="true"] { background: #111; color: #fff; border-color: #111; }
-
- .atts { border-top: 1px solid #eee; }
- .att { padding: .55rem .25rem; border-bottom: 1px solid #eee; display: grid; grid-template-columns: 92px 1fr; gap: .5rem .75rem; align-items: baseline; transition: background .8s ease; }
- .att.fresh { background: #fffbe5; animation: fadeFresh 4s ease forwards; }
- @keyframes fadeFresh { 0% { background: #fff3a3; } 100% { background: transparent; } }
- .att code { font-size: .72rem; color: #555; }
- .live-dot { display: inline-flex; align-items: center; gap: .3rem; font-size: .72rem; color: var(--muted); }
- .live-dot::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: #c8c8c8; }
- .live-dot.on::before { background: #43a047; box-shadow: 0 0 0 0 rgba(67,160,71,.5); animation: pulse 1.6s infinite; }
- .live-dot.off::before { background: #aaa; }
- @keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(67,160,71,.5); } 50% { box-shadow: 0 0 0 5px rgba(67,160,71,0); } }
- .kind-feedback { color: var(--ok-fg); }
- .kind-validation { color: var(--info-fg); }
- .kind-task { color: #6a1b9a; }
- .kind-accept { color: #4527a0; }
- .kind-revoke { color: var(--bad-fg); }
- .kind-dispute { color: #ef6c00; }
-
- .skeleton { background: linear-gradient(90deg, #eee 0%, #f6f6f6 50%, #eee 100%); background-size: 200% 100%; animation: shimmer 1.2s infinite; border-radius: 6px; }
- @keyframes shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
- .sk-row { height: 76px; margin: .65rem 0; }
-
- .error-box { padding: .65rem .85rem; border: 1px solid #f5c6c6; background: #fff5f5; color: var(--bad-fg); border-radius: 6px; }
-
- details { margin-top: .25rem; }
- details pre { font-size: .72rem; background: #f4f4f4; padding: .4rem; border-radius: 4px; overflow: auto; max-height: 240px; }
- a { color: var(--info-fg); }
-
- @media (max-width: 520px) {
- .att { grid-template-columns: 1fr; }
- .identity-name { font-size: 1.05rem; }
- }
- </style>
-</head>
-<body>
- <h1>Solana agent passport</h1>
- <p class="muted">ERC-8004-style identity, reputation, and validation. <a href="/.well-known/agent-attestation-schemas" target="_blank">View schemas</a></p>
-
- <div class="row">
- <input id="asset" placeholder="Metaplex Core asset pubkey…" autocomplete="off" spellcheck="false">
- <select id="network">
- <option value="devnet">devnet</option>
- <option value="mainnet">mainnet</option>
- </select>
- <button id="load" class="primary">Load</button>
- <button id="share" title="Copy shareable link">Share</button>
- <button id="embed" title="Copy iframe embed snippet">Embed</button>
- </div>
-
- <div id="identity"></div>
-
- <h2>Reputation <span class="hint" id="rep-hint"></span></h2>
- <div id="reputation"></div>
-
- <h2>Recent attestations <span class="hint" id="atts-count"></span> <span id="live" class="live-dot off" title="Live updates">off</span></h2>
- <div class="filters" id="filters" hidden>
- <button class="chip" data-filter="all" aria-pressed="true">all</button>
- <button class="chip" data-filter="feedback" aria-pressed="false">feedback</button>
- <button class="chip" data-filter="validation" aria-pressed="false">validation</button>
- <button class="chip" data-filter="task" aria-pressed="false">task</button>
- <button class="chip" data-filter="event" aria-pressed="false">event-attested</button>
- <button class="chip" data-filter="disputed" aria-pressed="false">disputed</button>
- </div>
- <div id="atts" class="atts"></div>
-
- <script type="module">
- const $ = (id) => document.getElementById(id);
- const params = new URLSearchParams(location.search);
- $('asset').value = params.get('asset') || '';
- $('network').value = params.get('network') || 'devnet';
-
- let cache = { rows: [], net: 'devnet', knownSigs: new Set(), freshSigs: new Set() };
- let activeFilter = 'all';
- let pollTimer = null;
- const POLL_MS = 8000;
-
- const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
-
- function pill(text, cls = '') { return `<span class="pill ${cls}">${escapeHtml(text)}</span>`; }
- function tip(text) { return `<span class="tip" title="${escapeHtml(text)}">?</span>`; }
- function explorer(sig, net) {
- return `https://explorer.solana.com/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`;
- }
- function shortKey(k) { return k ? `${k.slice(0,4)}…${k.slice(-4)}` : ''; }
- function fmtScore(n) { return (typeof n === 'number' && n > 0) ? n.toFixed(2) : '—'; }
-
- // Trust grade. Order: credentialed > verified > event-attested > raw.
- function computeTrust(rep) {
- const f = rep?.feedback || {};
- const v = rep?.validation || {};
- const tiers = [
- { score: f.score_avg_weighted_credentialed, n: f.unique_credentialed_attesters, tier: 'credentialed' },
- { score: f.score_avg_weighted_verified, n: f.unique_verified_attesters, tier: 'verified' },
- { score: f.score_avg_event_attested, n: f.event_attested, tier: 'event-attested' },
- { score: f.score_avg_weighted, n: f.unique_attesters, tier: 'community' },
- ];
- const best = tiers.find((t) => t.score > 0 && (t.n || 0) > 0);
- if (!best) return { grade: '—', cls: 'NA', summary: 'no attestations yet' };
-
- const passed = v.audited_passed || v.self_passed || 0;
- const failed = v.audited_failed || v.self_failed || 0;
- const passRate = (passed + failed) ? passed / (passed + failed) : 1;
-
- const adjust = best.score
- - (f.disputed > 0 ? 0.5 : 0)
- - (passRate < 0.5 ? 1 : 0);
-
- const grade =
- adjust >= 4.5 ? 'A' :
- adjust >= 3.8 ? 'B' :
- adjust >= 3.0 ? 'C' : 'D';
- return {
- grade,
- cls: grade,
- summary: `${best.tier} ${best.score.toFixed(2)} from ${best.n} attester${best.n === 1 ? '' : 's'}`
- + (f.disputed ? ` · ${f.disputed} disputed` : '')
- + (failed ? ` · ${failed} failed validation${failed === 1 ? '' : 's'}` : ''),
- };
- }
-
- function showError(target, message) { $(target).innerHTML = `<div class="error-box">${escapeHtml(message)}</div>`; }
- function showSkeletons(target, count = 1) {
- $(target).innerHTML = Array.from({ length: count }, () => `<div class="skeleton sk-row"></div>`).join('');
- }
-
- async function load() {
- const asset = $('asset').value.trim();
- const network = $('network').value;
- $('asset').classList.toggle('invalid', !!asset && !PUBKEY_RE.test(asset));
- if (!asset) { showError('identity', 'Enter an asset pubkey above.'); return; }
- if (!PUBKEY_RE.test(asset)) { showError('identity', 'That doesn’t look like a Solana pubkey.'); return; }
-
- stopPolling();
- history.replaceState({}, '', `?asset=${asset}&network=${network}`);
- $('load').disabled = true;
- showSkeletons('identity', 1);
- showSkeletons('reputation', 1);
- $('atts').innerHTML = '';
- $('atts-count').textContent = '';
- $('filters').hidden = true;
-
- try {
- const [card, rep, atts, hist] = await Promise.all([
- fetch(`/api/agents/solana-card?asset=${asset}`).then((r) => r.ok ? r.json() : null).catch(() => null),
- fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
- fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
- fetch(`/api/agents/solana-reputation-history?asset=${asset}&network=${network}&days=30`).then((r) => r.json()).catch(() => ({ series: [] })),
- ]);
-
- const initialRows = atts.data || [];
- renderIdentity(card, rep, asset, network, hist?.series || []);
- renderReputation(rep);
- cache = {
- rows: initialRows,
- net: network,
- knownSigs: new Set(initialRows.map((r) => r.signature)),
- freshSigs: new Set(),
+ <head>
+ <meta charset="utf-8" />
+ <title>Agent passport · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+ :root {
+ --fg: #111;
+ --muted: #555;
+ --border: #e5e5e5;
+ --bg: #fafafa;
+ --ok-bg: #e7f5e9;
+ --ok-fg: #1b5e20;
+ --warn-bg: #fff3cd;
+ --warn-fg: #855008;
+ --bad-bg: #fce8e8;
+ --bad-fg: #b71c1c;
+ --info-bg: #e3f2fd;
+ --info-fg: #0d47a1;
+ }
+ body {
+ font:
+ 14px/1.5 system-ui,
+ -apple-system,
+ sans-serif;
+ max-width: 880px;
+ margin: 1.5rem auto;
+ padding: 0 1rem;
+ color: var(--fg);
+ }
+ h1 {
+ font-size: 1.4rem;
+ margin: 0 0 0.25rem;
+ }
+ h2 {
+ font-size: 1rem;
+ margin: 1.5rem 0 0.5rem;
+ display: flex;
+ align-items: baseline;
+ gap: 0.5rem;
+ }
+ h2 .hint {
+ font-weight: 400;
+ font-size: 0.8rem;
+ color: var(--muted);
+ }
+ .muted {
+ color: var(--muted);
+ }
+ .row {
+ display: flex;
+ gap: 0.5rem;
+ align-items: center;
+ flex-wrap: wrap;
+ margin: 0.5rem 0 1rem;
+ }
+ .row input {
+ font: inherit;
+ padding: 0.4rem 0.55rem;
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ flex: 1 1 320px;
+ min-width: 0;
+ }
+ .row input.invalid {
+ border-color: var(--bad-fg);
+ background: #fff8f8;
+ }
+ .row select,
+ .row button {
+ font: inherit;
+ padding: 0.4rem 0.65rem;
+ border: 1px solid #ccc;
+ background: #fff;
+ border-radius: 6px;
+ cursor: pointer;
+ }
+ .row button.primary {
+ background: #111;
+ color: #fff;
+ border-color: #111;
+ }
+ .row button:disabled {
+ opacity: 0.5;
+ cursor: wait;
+ }
+
+ .identity-card {
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 1rem 1.1rem;
+ background: #fff;
+ }
+ .identity-row {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ flex-wrap: wrap;
+ }
+ .identity-name {
+ font-size: 1.2rem;
+ font-weight: 600;
+ }
+ .identity-meta {
+ display: flex;
+ gap: 0.5rem;
+ flex-wrap: wrap;
+ align-items: center;
+ font-size: 0.8rem;
+ color: var(--muted);
+ margin-top: 0.35rem;
+ }
+ .identity-meta code {
+ background: #f3f3f3;
+ padding: 0.1rem 0.35rem;
+ border-radius: 4px;
+ font-size: 0.75rem;
+ }
+ .copy-btn {
+ padding: 0.1rem 0.35rem;
+ font-size: 0.7rem;
+ line-height: 1.4;
+ cursor: pointer;
+ border: 1px solid var(--border);
+ background: #fff;
+ border-radius: 4px;
+ }
+ .copy-btn:hover {
+ background: #f3f3f3;
+ }
+
+ .trust-bar {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ margin-top: 0.75rem;
+ padding: 0.65rem 0.85rem;
+ border-radius: 8px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ }
+ .trust-bar .spark {
+ margin-left: auto;
+ flex: 0 0 120px;
+ }
+ .trust-bar .spark svg {
+ width: 120px;
+ height: 32px;
+ display: block;
+ }
+ .trust-bar .spark-empty {
+ font-size: 0.7rem;
+ color: var(--muted);
+ }
+ .trust-grade {
+ font-size: 1.6rem;
+ font-weight: 700;
+ min-width: 2rem;
+ text-align: center;
+ }
+ .trust-A {
+ color: var(--ok-fg);
+ }
+ .trust-B {
+ color: #2e7d32;
+ }
+ .trust-C {
+ color: var(--warn-fg);
+ }
+ .trust-D {
+ color: #c62828;
+ }
+ .trust-NA {
+ color: var(--muted);
+ }
+ .trust-summary {
+ font-size: 0.85rem;
+ color: var(--muted);
+ }
+
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
+ gap: 0.65rem;
+ margin: 0.75rem 0;
+ }
+ .card {
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 0.65rem 0.85rem;
+ background: var(--bg);
+ position: relative;
+ }
+ .card .v {
+ font-size: 1.55rem;
+ font-weight: 600;
+ line-height: 1.1;
+ }
+ .card .v small {
+ font-size: 1rem;
+ color: var(--muted);
+ font-weight: 400;
+ }
+ .card .l {
+ font-size: 0.75rem;
+ color: var(--muted);
+ margin-top: 0.15rem;
+ display: flex;
+ align-items: center;
+ gap: 0.25rem;
+ }
+ .card.tier-credentialed {
+ border-color: #b8d8e8;
+ background: #f4faff;
+ }
+ .card.tier-event {
+ border-color: #d4c5f0;
+ background: #f8f4ff;
+ }
+ .card.tier-pump {
+ border-color: #ffd8b8;
+ background: #fff8f0;
+ }
+ .card.danger {
+ border-color: #f5c6c6;
+ background: #fff5f5;
+ }
+
+ .tip {
+ display: inline-block;
+ cursor: help;
+ color: var(--muted);
+ border: 1px solid var(--border);
+ border-radius: 50%;
+ width: 13px;
+ height: 13px;
+ font-size: 9px;
+ line-height: 11px;
+ text-align: center;
+ }
+
+ .pill {
+ display: inline-block;
+ padding: 0.1rem 0.55rem;
+ border-radius: 999px;
+ font-size: 0.7rem;
+ line-height: 1.5;
+ }
+ .ok {
+ background: var(--ok-bg);
+ color: var(--ok-fg);
+ }
+ .warn {
+ background: var(--warn-bg);
+ color: var(--warn-fg);
+ }
+ .bad {
+ background: var(--bad-bg);
+ color: var(--bad-fg);
+ }
+ .info {
+ background: var(--info-bg);
+ color: var(--info-fg);
+ }
+ .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;
+ }
+
+ .filters {
+ display: flex;
+ gap: 0.35rem;
+ flex-wrap: wrap;
+ margin: 0.5rem 0 0.75rem;
+ }
+ .chip {
+ padding: 0.2rem 0.65rem;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ cursor: pointer;
+ font-size: 0.75rem;
+ background: #fff;
+ user-select: none;
+ }
+ .chip[aria-pressed='true'] {
+ background: #111;
+ color: #fff;
+ border-color: #111;
+ }
+
+ .atts {
+ border-top: 1px solid #eee;
+ }
+ .att {
+ padding: 0.55rem 0.25rem;
+ border-bottom: 1px solid #eee;
+ display: grid;
+ grid-template-columns: 92px 1fr;
+ gap: 0.5rem 0.75rem;
+ align-items: baseline;
+ transition: background 0.8s ease;
+ }
+ .att.fresh {
+ background: #fffbe5;
+ animation: fadeFresh 4s ease forwards;
+ }
+ @keyframes fadeFresh {
+ 0% {
+ background: #fff3a3;
+ }
+ 100% {
+ background: transparent;
+ }
+ }
+ .att code {
+ font-size: 0.72rem;
+ color: #555;
+ }
+ .live-dot {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.3rem;
+ font-size: 0.72rem;
+ color: var(--muted);
+ }
+ .live-dot::before {
+ content: '';
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #c8c8c8;
+ }
+ .live-dot.on::before {
+ background: #43a047;
+ box-shadow: 0 0 0 0 rgba(67, 160, 71, 0.5);
+ animation: pulse 1.6s infinite;
+ }
+ .live-dot.off::before {
+ background: #aaa;
+ }
+ @keyframes pulse {
+ 0%,
+ 100% {
+ box-shadow: 0 0 0 0 rgba(67, 160, 71, 0.5);
+ }
+ 50% {
+ box-shadow: 0 0 0 5px rgba(67, 160, 71, 0);
+ }
+ }
+ .kind-feedback {
+ color: var(--ok-fg);
+ }
+ .kind-validation {
+ color: var(--info-fg);
+ }
+ .kind-task {
+ color: #6a1b9a;
+ }
+ .kind-accept {
+ color: #4527a0;
+ }
+ .kind-revoke {
+ color: var(--bad-fg);
+ }
+ .kind-dispute {
+ color: #ef6c00;
+ }
+
+ .skeleton {
+ background: linear-gradient(90deg, #eee 0%, #f6f6f6 50%, #eee 100%);
+ background-size: 200% 100%;
+ animation: shimmer 1.2s infinite;
+ border-radius: 6px;
+ }
+ @keyframes shimmer {
+ 0% {
+ background-position: 200% 0;
+ }
+ 100% {
+ background-position: -200% 0;
+ }
+ }
+ .sk-row {
+ height: 76px;
+ margin: 0.65rem 0;
+ }
+
+ .error-box {
+ padding: 0.65rem 0.85rem;
+ border: 1px solid #f5c6c6;
+ background: #fff5f5;
+ color: var(--bad-fg);
+ border-radius: 6px;
+ }
+
+ details {
+ margin-top: 0.25rem;
+ }
+ details pre {
+ font-size: 0.72rem;
+ background: #f4f4f4;
+ padding: 0.4rem;
+ border-radius: 4px;
+ overflow: auto;
+ max-height: 240px;
+ }
+ a {
+ color: var(--info-fg);
+ }
+
+ @media (max-width: 520px) {
+ .att {
+ grid-template-columns: 1fr;
+ }
+ .identity-name {
+ font-size: 1.05rem;
+ }
+ }
+ </style>
+ </head>
+ <body>
+ <h1>Solana agent passport</h1>
+ <p class="muted">
+ ERC-8004-style identity, reputation, and validation.
+ <a href="/.well-known/agent-attestation-schemas" target="_blank">View schemas</a>
+ </p>
+
+ <div class="row">
+ <input
+ id="asset"
+ placeholder="Metaplex Core asset pubkey…"
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <select id="network">
+ <option value="devnet">devnet</option>
+ <option value="mainnet">mainnet</option>
+ </select>
+ <button id="load" class="primary">Load</button>
+ <button id="share" title="Copy shareable link">Share</button>
+ <button id="embed" title="Copy iframe embed snippet">Embed</button>
+ </div>
+
+ <div id="identity"></div>
+
+ <div id="token-stats" hidden></div>
+
+ <h2>Reputation <span class="hint" id="rep-hint"></span></h2>
+ <div id="reputation"></div>
+
+ <h2>
+ Recent attestations <span class="hint" id="atts-count"></span>
+ <span id="live" class="live-dot off" title="Live updates">off</span>
+ </h2>
+ <div class="filters" id="filters" hidden>
+ <button class="chip" data-filter="all" aria-pressed="true">all</button>
+ <button class="chip" data-filter="feedback" aria-pressed="false">feedback</button>
+ <button class="chip" data-filter="validation" aria-pressed="false">validation</button>
+ <button class="chip" data-filter="task" aria-pressed="false">task</button>
+ <button class="chip" data-filter="event" aria-pressed="false">event-attested</button>
+ <button class="chip" data-filter="disputed" aria-pressed="false">disputed</button>
+ </div>
+ <div id="atts" class="atts"></div>
+
+ <script type="module">
+ const $ = (id) => document.getElementById(id);
+ const params = new URLSearchParams(location.search);
+ $('asset').value = params.get('asset') || '';
+ $('network').value = params.get('network') || 'devnet';
+
+ let cache = { rows: [], net: 'devnet', knownSigs: new Set(), freshSigs: new Set() };
+ let activeFilter = 'all';
+ let pollTimer = null;
+ const POLL_MS = 8000;
+
+ const PUBKEY_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+ function pill(text, cls = '') {
+ return `<span class="pill ${cls}">${escapeHtml(text)}</span>`;
+ }
+ function tip(text) {
+ return `<span class="tip" title="${escapeHtml(text)}">?</span>`;
+ }
+ function explorer(sig, net) {
+ return `https://explorer.solana.com/tx/${sig}${net === 'devnet' ? '?cluster=devnet' : ''}`;
+ }
+ function shortKey(k) {
+ return k ? `${k.slice(0, 4)}…${k.slice(-4)}` : '';
+ }
+ function fmtScore(n) {
+ return typeof n === 'number' && n > 0 ? n.toFixed(2) : '—';
+ }
+
+ // Trust grade. Order: credentialed > verified > event-attested > raw.
+ function computeTrust(rep) {
+ const f = rep?.feedback || {};
+ const v = rep?.validation || {};
+ const tiers = [
+ {
+ score: f.score_avg_weighted_credentialed,
+ n: f.unique_credentialed_attesters,
+ tier: 'credentialed',
+ },
+ {
+ score: f.score_avg_weighted_verified,
+ n: f.unique_verified_attesters,
+ tier: 'verified',
+ },
+ {
+ score: f.score_avg_event_attested,
+ n: f.event_attested,
+ tier: 'event-attested',
+ },
+ { score: f.score_avg_weighted, n: f.unique_attesters, tier: 'community' },
+ ];
+ const best = tiers.find((t) => t.score > 0 && (t.n || 0) > 0);
+ if (!best) return { grade: '—', cls: 'NA', summary: 'no attestations yet' };
+
+ const passed = v.audited_passed || v.self_passed || 0;
+ const failed = v.audited_failed || v.self_failed || 0;
+ const passRate = passed + failed ? passed / (passed + failed) : 1;
+
+ const adjust = best.score - (f.disputed > 0 ? 0.5 : 0) - (passRate < 0.5 ? 1 : 0);
+
+ const grade = adjust >= 4.5 ? 'A' : adjust >= 3.8 ? 'B' : adjust >= 3.0 ? 'C' : 'D';
+ return {
+ grade,
+ cls: grade,
+ summary:
+ `${best.tier} ${best.score.toFixed(2)} from ${best.n} attester${best.n === 1 ? '' : 's'}` +
+ (f.disputed ? ` · ${f.disputed} disputed` : '') +
+ (failed ? ` · ${failed} failed validation${failed === 1 ? '' : 's'}` : ''),
};
- $('filters').hidden = false;
- renderAttestations();
- startPolling(asset, network);
- } catch (e) {
- showError('identity', `Failed to load: ${e.message || e}`);
- } finally {
- $('load').disabled = false;
}
- }
- // -- Live polling --------------------------------------------------
+ function showError(target, message) {
+ $(target).innerHTML = `<div class="error-box">${escapeHtml(message)}</div>`;
+ }
+ function showSkeletons(target, count = 1) {
+ $(target).innerHTML = Array.from(
+ { length: count },
+ () => `<div class="skeleton sk-row"></div>`,
+ ).join('');
+ }
+
+ async function load() {
+ const asset = $('asset').value.trim();
+ const network = $('network').value;
+ $('asset').classList.toggle('invalid', !!asset && !PUBKEY_RE.test(asset));
+ if (!asset) {
+ showError('identity', 'Enter an asset pubkey above.');
+ return;
+ }
+ if (!PUBKEY_RE.test(asset)) {
+ showError('identity', 'That doesn’t look like a Solana pubkey.');
+ return;
+ }
+
+ stopPolling();
+ history.replaceState({}, '', `?asset=${asset}&network=${network}`);
+ $('load').disabled = true;
+ showSkeletons('identity', 1);
+ showSkeletons('reputation', 1);
+ $('atts').innerHTML = '';
+ $('atts-count').textContent = '';
+ $('filters').hidden = true;
- function startPolling(asset, network) {
- stopPolling();
- setLive(true);
- const tick = async () => {
- if (document.hidden) return;
try {
- const [atts, rep] = await Promise.all([
- fetch(`/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`).then((r) => r.json()),
- fetch(`/api/agents/solana-reputation?asset=${asset}&network=${network}`).then((r) => r.json()),
+ const [card, rep, atts, hist] = await Promise.all([
+ fetch(`/api/agents/solana-card?asset=${asset}`)
+ .then((r) => (r.ok ? r.json() : null))
+ .catch(() => null),
+ fetch(
+ `/api/agents/solana-reputation?asset=${asset}&network=${network}`,
+ ).then((r) => r.json()),
+ fetch(
+ `/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`,
+ ).then((r) => r.json()),
+ fetch(
+ `/api/agents/solana-reputation-history?asset=${asset}&network=${network}&days=30`,
+ )
+ .then((r) => r.json())
+ .catch(() => ({ series: [] })),
]);
- const rows = atts.data || [];
- const freshSigs = new Set();
- for (const r of rows) {
- if (!cache.knownSigs.has(r.signature)) freshSigs.add(r.signature);
- }
- if (freshSigs.size > 0) {
- cache.rows = rows;
- cache.knownSigs = new Set(rows.map((r) => r.signature));
- cache.freshSigs = freshSigs;
- renderAttestations();
- renderReputation(rep);
- // clear the highlight class after the animation
- setTimeout(() => { cache.freshSigs = new Set(); }, 4500);
+
+ const initialRows = atts.data || [];
+ renderIdentity(card, rep, asset, network, hist?.series || []);
+ renderTokenStats(card?.token_stats);
+ renderReputation(rep);
+ cache = {
+ rows: initialRows,
+ net: network,
+ knownSigs: new Set(initialRows.map((r) => r.signature)),
+ freshSigs: new Set(),
+ };
+ $('filters').hidden = false;
+ renderAttestations();
+ startPolling(asset, network);
+ } catch (e) {
+ showError('identity', `Failed to load: ${e.message || e}`);
+ } finally {
+ $('load').disabled = false;
+ }
+ }
+
+ // -- Live polling --------------------------------------------------
+
+ function startPolling(asset, network) {
+ stopPolling();
+ setLive(true);
+ const tick = async () => {
+ if (document.hidden) return;
+ try {
+ const [atts, rep] = await Promise.all([
+ fetch(
+ `/api/agents/solana-attestations?asset=${asset}&network=${network}&limit=25`,
+ ).then((r) => r.json()),
+ fetch(
+ `/api/agents/solana-reputation?asset=${asset}&network=${network}`,
+ ).then((r) => r.json()),
+ ]);
+ const rows = atts.data || [];
+ const freshSigs = new Set();
+ for (const r of rows) {
+ if (!cache.knownSigs.has(r.signature)) freshSigs.add(r.signature);
+ }
+ if (freshSigs.size > 0) {
+ cache.rows = rows;
+ cache.knownSigs = new Set(rows.map((r) => r.signature));
+ cache.freshSigs = freshSigs;
+ renderAttestations();
+ renderReputation(rep);
+ // clear the highlight class after the animation
+ setTimeout(() => {
+ cache.freshSigs = new Set();
+ }, 4500);
+ }
+ } catch {
+ // transient — stay live, try again next tick
}
- } catch {
- // transient — stay live, try again next tick
+ };
+ pollTimer = setInterval(tick, POLL_MS);
+ }
+
+ function stopPolling() {
+ if (pollTimer) {
+ clearInterval(pollTimer);
+ pollTimer = null;
}
- };
- pollTimer = setInterval(tick, POLL_MS);
- }
-
- function stopPolling() {
- if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
- setLive(false);
- }
-
- function setLive(on) {
- const el = $('live');
- el.classList.toggle('on', on);
- el.classList.toggle('off', !on);
- el.textContent = on ? 'live' : 'off';
- }
-
- document.addEventListener('visibilitychange', () => {
- if (!pollTimer) return;
- setLive(!document.hidden);
- });
-
- function renderIdentity(card, rep, asset, network, history = []) {
- const id = card?.identity || {};
- const name = card?.name || '(unindexed agent)';
- const trust = computeTrust(rep);
- const lastIndexed = rep?.last_indexed_at
- ? `indexed ${new Date(rep.last_indexed_at).toLocaleString()}`
- : 'never indexed';
- const sparkSvg = renderSparkline(history);
- const vanity = id.vanity_prefix && asset.startsWith(id.vanity_prefix) ? id.vanity_prefix : null;
- const shortAddrHtml = vanity
- ? `<span class="addr-prefix">${escapeHtml(vanity)}</span>${escapeHtml(asset.slice(vanity.length, 4))}…${escapeHtml(asset.slice(-4))}`
- : escapeHtml(shortKey(asset));
- $('identity').innerHTML = `
+ setLive(false);
+ }
+
+ function setLive(on) {
+ const el = $('live');
+ el.classList.toggle('on', on);
+ el.classList.toggle('off', !on);
+ el.textContent = on ? 'live' : 'off';
+ }
+
+ document.addEventListener('visibilitychange', () => {
+ if (!pollTimer) return;
+ setLive(!document.hidden);
+ });
+
+ function renderIdentity(card, rep, asset, network, history = []) {
+ const id = card?.identity || {};
+ const name = card?.name || '(unindexed agent)';
+ const trust = computeTrust(rep);
+ const lastIndexed = rep?.last_indexed_at
+ ? `indexed ${new Date(rep.last_indexed_at).toLocaleString()}`
+ : 'never indexed';
+ const sparkSvg = renderSparkline(history);
+ const vanity =
+ id.vanity_prefix && asset.startsWith(id.vanity_prefix)
+ ? id.vanity_prefix
+ : null;
+ const shortAddrHtml = vanity
+ ? `<span class="addr-prefix">${escapeHtml(vanity)}</span>${escapeHtml(asset.slice(vanity.length, 4))}…${escapeHtml(asset.slice(-4))}`
+ : escapeHtml(shortKey(asset));
+ $('identity').innerHTML = `
<div class="identity-card">
<div class="identity-row">
<div class="identity-name">${escapeHtml(name)}</div>
@@ -321,112 +711,235 @@
<div class="spark" title="30-day score history">${sparkSvg}</div>
</div>
</div>`;
- $('identity').querySelectorAll('[data-copy]').forEach((b) => {
- b.addEventListener('click', () => copyText(b.dataset.copy, b));
- });
- if (id.owner) loadOwnerBalance(id.owner, network);
- }
-
- async function loadOwnerBalance(owner, network) {
- const el = document.getElementById('owner-balance');
- if (!el) return;
- try {
- const rpc = network === 'devnet'
- ? 'https://api.devnet.solana.com'
- : 'https://api.mainnet-beta.solana.com';
- const r = await fetch(rpc, {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'getBalance', params: [owner] }),
- }).then((x) => x.json());
- const lamports = r?.result?.value;
- if (typeof lamports === 'number') {
- el.textContent = `${(lamports / 1e9).toFixed(3)} SOL`;
- el.classList.add(lamports > 0 ? 'ok' : 'warn');
- } else {
+ $('identity')
+ .querySelectorAll('[data-copy]')
+ .forEach((b) => {
+ b.addEventListener('click', () => copyText(b.dataset.copy, b));
+ });
+ if (id.owner) loadOwnerBalance(id.owner, network);
+ }
+
+ async function loadOwnerBalance(owner, network) {
+ const el = document.getElementById('owner-balance');
+ if (!el) return;
+ try {
+ const rpc =
+ network === 'devnet'
+ ? 'https://api.devnet.solana.com'
+ : 'https://api.mainnet-beta.solana.com';
+ const r = await fetch(rpc, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'getBalance',
+ params: [owner],
+ }),
+ }).then((x) => x.json());
+ const lamports = r?.result?.value;
+ if (typeof lamports === 'number') {
+ el.textContent = `${(lamports / 1e9).toFixed(3)} SOL`;
+ el.classList.add(lamports > 0 ? 'ok' : 'warn');
+ } else {
+ el.textContent = '— SOL';
+ }
+ } catch {
el.textContent = '— SOL';
}
- } catch {
- el.textContent = '— SOL';
- }
- }
-
- function renderReputation(r) {
- if (!r || r.error) { $('reputation').innerHTML = `<p class="muted">no data</p>`; return; }
- const f = r.feedback || {}, v = r.validation || {}, p = r.pump_payments || {};
- const pf = r.pumpfun_signals || { count: 0, weight: 0, by_kind: {} };
- $('rep-hint').textContent = 'higher tiers are more Sybil-resistant';
-
- const cards = [
- { cls: 'tier-credentialed', value: fmtScore(f.score_avg_weighted_credentialed),
- label: 'credentialed score',
- tooltip: 'Average from attesters holding a threews.verified-client.v1 SAS credential. Strongest Sybil resistance.' },
- { cls: 'tier-credentialed', value: `${f.unique_credentialed_attesters || 0}<small>/${f.unique_attesters || 0}</small>`,
- label: 'credentialed / unique attesters' },
- { cls: '', value: fmtScore(f.score_avg_weighted_verified),
- label: 'verified score',
- tooltip: 'Feedback whose task_id has a matching threews.accept.v1 from the agent owner.' },
- { cls: 'tier-event', value: fmtScore(f.score_avg_event_attested),
- label: 'event-attested score',
- tooltip: 'Feedback sourced from on-chain event monitors (e.g. pumpkit). Sybil-resistant via the event.' },
- { cls: 'tier-event', value: `${f.event_attested || 0}`,
- label: 'event-attested feedback' },
- { cls: '', value: fmtScore(f.score_avg_weighted),
- label: 'all-feedback score',
- tooltip: 'Per-attester average then averaged. Raw signal.' },
- { cls: '', value: `${f.verified || 0}<small>/${f.total || 0}</small>`,
- label: 'verified / total feedback' },
- { cls: '', value: `${v.audited_passed || 0}<small>/${(v.audited_passed||0)+(v.audited_failed||0)}</small>`,
- label: 'audited validation passed',
- tooltip: 'From SAS-credentialed validators.' },
- { cls: '', value: `${v.event_passed || 0}<small>/${(v.event_passed||0)+(v.event_failed||0)}</small>`,
- label: 'event validation passed',
- tooltip: 'From on-chain event monitors (graduations vs CTOs).' },
- { cls: '', value: `${r.tasks?.accepted || 0}<small>/${r.tasks?.offered || 0}</small>`,
- label: 'tasks accepted / offered' },
- ...(Number(p.confirmed_count) ? [
- { cls: 'tier-pump', value: `${p.confirmed_count}<small>/${p.unique_payers || 0}</small>`,
- label: 'pump payments / unique payers',
- tooltip: 'Confirmed acceptPayment receipts. Volume-weighted reputation lane.' },
- ] : []),
- ...(Number(pf.count) ? [
- { cls: 'tier-pump', value: `${pf.count}<small> ${pf.weight >= 0 ? '+' : ''}${pf.weight.toFixed(2)}</small>`,
- label: 'pump.fun signals (weight)',
- tooltip: 'Off-chain pump.fun activity tied to this agent\'s wallet — first claims, graduations, fake claims, and influencer tier. Weighted positive/negative.' },
- ...Object.entries(pf.by_kind || {}).map(([kind, info]) => ({
- cls: info.weight < 0 ? 'danger' : 'tier-pump',
- value: info.count,
- label: `pf · ${kind.replace('_', ' ')}`,
- tooltip: `Aggregate weight ${info.weight >= 0 ? '+' : ''}${info.weight}`,
- })),
- ] : []),
- ...(f.disputed ? [{ cls: 'danger', value: f.disputed, label: 'disputed' }] : []),
- ...(r.revoked_count ? [{ cls: 'danger', value: r.revoked_count, label: 'revoked' }] : []),
- ];
-
- $('reputation').innerHTML = `<div class="grid">${cards.map((c) => `
+ }
+
+ function renderTokenStats(ts) {
+ const host = $('token-stats');
+ if (!ts) {
+ host.hidden = true;
+ host.innerHTML = '';
+ return;
+ }
+ host.hidden = false;
+ const fmtSol = (lamports) =>
+ lamports == null ? '—' : (Number(lamports) / 1e9).toFixed(3) + ' SOL';
+ const lastSig = ts.last_signature
+ ? `<a href="https://solscan.io/tx/${ts.last_signature}${ts.network === 'devnet' ? '?cluster=devnet' : ''}" target="_blank" rel="noopener">${ts.last_signature.slice(0, 12)}…</a>`
+ : '—';
+ const refreshedAgo = ts.refreshed_at
+ ? `${Math.max(0, Math.round((Date.now() - new Date(ts.refreshed_at)) / 60000))}m ago`
+ : '—';
+
+ let body;
+ if (ts.graduated) {
+ const a = ts.amm || {};
+ body = `
+ <span class="badge tier-pump" title="Token has graduated to the pump.fun AMM pool">graduated · AMM</span>
+ <div class="grid">
+ <div class="card"><div class="v">${fmtSol(a.quote_reserve)}</div><div class="l">pool quote (SOL)</div></div>
+ <div class="card"><div class="v">${a.base_reserve ? Number(a.base_reserve).toExponential(2) : '—'}</div><div class="l">pool base (tokens)</div></div>
+ <div class="card"><div class="v">${ts.recent_tx_count || 0}</div><div class="l">recent tx (50-tail)</div></div>
+ <div class="card"><div class="v" style="font-size:.85em">${lastSig}</div><div class="l">last tx</div></div>
+ </div>
+ `;
+ } else if (ts.bonding_curve) {
+ const c = ts.bonding_curve;
+ const pct = Number(c.progress_pct || 0);
+ body = `
+ <span class="badge" title="Pre-graduation: trades go through the pump.fun bonding curve">bonding curve · ${pct.toFixed(1)}% to graduation</span>
+ <div style="background:#222; border-radius:6px; height:10px; overflow:hidden; margin:.4em 0 .8em">
+ <div style="background:linear-gradient(90deg,#5c8fff,#00d4ff); width:${Math.min(100, pct)}%; height:100%"></div>
+ </div>
+ <div class="grid">
+ <div class="card"><div class="v">${fmtSol(c.real_sol)}</div><div class="l">real SOL reserves</div></div>
+ <div class="card"><div class="v">${c.real_token ? Number(c.real_token).toExponential(2) : '—'}</div><div class="l">real token reserves</div></div>
+ <div class="card"><div class="v">${ts.recent_tx_count || 0}</div><div class="l">recent tx (50-tail)</div></div>
+ <div class="card"><div class="v" style="font-size:.85em">${lastSig}</div><div class="l">last tx</div></div>
+ </div>
+ `;
+ } else {
+ body = `<p class="muted">No bonding curve or AMM pool detected. Refreshed ${refreshedAgo}.</p>`;
+ }
+
+ host.innerHTML = `
+ <h2>Token <span class="hint">${ts.network} · refreshed ${refreshedAgo}</span></h2>
+ ${body}
+ `;
+ }
+
+ function renderReputation(r) {
+ if (!r || r.error) {
+ $('reputation').innerHTML = `<p class="muted">no data</p>`;
+ return;
+ }
+ const f = r.feedback || {},
+ v = r.validation || {},
+ p = r.pump_payments || {};
+ const pf = r.pumpfun_signals || { count: 0, weight: 0, by_kind: {} };
+ $('rep-hint').textContent = 'higher tiers are more Sybil-resistant';
+
+ const cards = [
+ {
+ cls: 'tier-credentialed',
+ value: fmtScore(f.score_avg_weighted_credentialed),
+ label: 'credentialed score',
+ tooltip:
+ 'Average from attesters holding a threews.verified-client.v1 SAS credential. Strongest Sybil resistance.',
+ },
+ {
+ cls: 'tier-credentialed',
+ value: `${f.unique_credentialed_attesters || 0}<small>/${f.unique_attesters || 0}</small>`,
+ label: 'credentialed / unique attesters',
+ },
+ {
+ cls: '',
+ value: fmtScore(f.score_avg_weighted_verified),
+ label: 'verified score',
+ tooltip:
+ 'Feedback whose task_id has a matching threews.accept.v1 from the agent owner.',
+ },
+ {
+ cls: 'tier-event',
+ value: fmtScore(f.score_avg_event_attested),
+ label: 'event-attested score',
+ tooltip:
+ 'Feedback sourced from on-chain event monitors (e.g. pumpkit). Sybil-resistant via the event.',
+ },
+ {
+ cls: 'tier-event',
+ value: `${f.event_attested || 0}`,
+ label: 'event-attested feedback',
+ },
+ {
+ cls: '',
+ value: fmtScore(f.score_avg_weighted),
+ label: 'all-feedback score',
+ tooltip: 'Per-attester average then averaged. Raw signal.',
+ },
+ {
+ cls: '',
+ value: `${f.verified || 0}<small>/${f.total || 0}</small>`,
+ label: 'verified / total feedback',
+ },
+ {
+ cls: '',
+ value: `${v.audited_passed || 0}<small>/${(v.audited_passed || 0) + (v.audited_failed || 0)}</small>`,
+ label: 'audited validation passed',
+ tooltip: 'From SAS-credentialed validators.',
+ },
+ {
+ cls: '',
+ value: `${v.event_passed || 0}<small>/${(v.event_passed || 0) + (v.event_failed || 0)}</small>`,
+ label: 'event validation passed',
+ tooltip: 'From on-chain event monitors (graduations vs CTOs).',
+ },
+ {
+ cls: '',
+ value: `${r.tasks?.accepted || 0}<small>/${r.tasks?.offered || 0}</small>`,
+ label: 'tasks accepted / offered',
+ },
+ ...(Number(p.confirmed_count)
+ ? [
+ {
+ cls: 'tier-pump',
+ value: `${p.confirmed_count}<small>/${p.unique_payers || 0}</small>`,
+ label: 'pump payments / unique payers',
+ tooltip:
+ 'Confirmed acceptPayment receipts. Volume-weighted reputation lane.',
+ },
+ ]
+ : []),
+ ...(Number(pf.count)
+ ? [
+ {
+ cls: 'tier-pump',
+ value: `${pf.count}<small> ${pf.weight >= 0 ? '+' : ''}${pf.weight.toFixed(2)}</small>`,
+ label: 'pump.fun signals (weight)',
+ tooltip:
+ "Off-chain pump.fun activity tied to this agent's wallet — first claims, graduations, fake claims, and influencer tier. Weighted positive/negative.",
+ },
+ ...Object.entries(pf.by_kind || {}).map(([kind, info]) => ({
+ cls: info.weight < 0 ? 'danger' : 'tier-pump',
+ value: info.count,
+ label: `pf · ${kind.replace('_', ' ')}`,
+ tooltip: `Aggregate weight ${info.weight >= 0 ? '+' : ''}${info.weight}`,
+ })),
+ ]
+ : []),
+ ...(f.disputed
+ ? [{ cls: 'danger', value: f.disputed, label: 'disputed' }]
+ : []),
+ ...(r.revoked_count
+ ? [{ cls: 'danger', value: r.revoked_count, label: 'revoked' }]
+ : []),
+ ];
+
+ $('reputation').innerHTML = `<div class="grid">${cards
+ .map(
+ (c) => `
<div class="card ${c.cls}">
<div class="v">${c.value}</div>
<div class="l">${escapeHtml(c.label)}${c.tooltip ? ' ' + tip(c.tooltip) : ''}</div>
- </div>`).join('')}</div>`;
- }
-
- function renderAttestations() {
- const rows = filterRows(cache.rows, activeFilter);
- $('atts-count').textContent = `${rows.length} of ${cache.rows.length}`;
- if (!rows.length) {
- $('atts').innerHTML = `<p class="muted" style="padding:.75rem 0">no matching attestations</p>`;
- return;
- }
- $('atts').innerHTML = rows.map((row) => {
- const k = row.kind?.split('.')[1] || 'unknown';
- const flags = [];
- if (row.verified) flags.push(pill('verified', 'ok'));
- if (row.disputed) flags.push(pill('disputed', 'warn'));
- if (row.revoked) flags.push(pill('revoked', 'bad'));
- if (row.payload?.source?.startsWith?.('pumpkit.')) flags.push(pill(row.payload.source, 'info'));
- const fresh = cache.freshSigs.has(row.signature) ? ' fresh' : '';
- return `
+ </div>`,
+ )
+ .join('')}</div>`;
+ }
+
+ function renderAttestations() {
+ const rows = filterRows(cache.rows, activeFilter);
+ $('atts-count').textContent = `${rows.length} of ${cache.rows.length}`;
+ if (!rows.length) {
+ $('atts').innerHTML =
+ `<p class="muted" style="padding:.75rem 0">no matching attestations</p>`;
+ return;
+ }
+ $('atts').innerHTML = rows
+ .map((row) => {
+ const k = row.kind?.split('.')[1] || 'unknown';
+ const flags = [];
+ if (row.verified) flags.push(pill('verified', 'ok'));
+ if (row.disputed) flags.push(pill('disputed', 'warn'));
+ if (row.revoked) flags.push(pill('revoked', 'bad'));
+ if (row.payload?.source?.startsWith?.('pumpkit.'))
+ flags.push(pill(row.payload.source, 'info'));
+ const fresh = cache.freshSigs.has(row.signature) ? ' fresh' : '';
+ return `
<div class="att${fresh}">
<div class="kind-${k}"><strong>${escapeHtml(k)}</strong></div>
<div>
@@ -440,85 +953,112 @@
<details><summary class="muted" style="font-size:.72rem">payload</summary><pre>${escapeHtml(JSON.stringify(row.payload, null, 2))}</pre></details>
</div>
</div>`;
- }).join('');
- }
-
- function filterRows(rows, filter) {
- if (filter === 'all') return rows;
- if (filter === 'disputed') return rows.filter((r) => r.disputed || r.revoked);
- if (filter === 'event') return rows.filter((r) => r.payload?.source?.startsWith?.('pumpkit.'));
- return rows.filter((r) => r.kind?.includes(`.${filter}.`));
- }
-
- function describe(row) {
- const p = row.payload || {};
- switch (row.kind) {
- case 'threews.feedback.v1': return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}${p.source ? ` (${p.source})` : ''}`;
- case 'threews.validation.v1': return `validation ${p.passed ? '✓ passed' : '✗ failed'}${p.task_hash ? ` (task hash ${String(p.task_hash).slice(0,12)}…)` : ''}`;
- case 'threews.task.v1': return `task offered: ${p.task_id}`;
- case 'threews.accept.v1': return `task accepted: ${p.task_id}`;
- case 'threews.revoke.v1': return `revoked ${String(p.target_signature || '').slice(0,12)}…`;
- case 'threews.dispute.v1': return `disputed ${String(p.target_signature || '').slice(0,12)}…${p.reason ? ` — ${p.reason}` : ''}`;
- default: return row.kind;
- }
- }
-
- function escapeHtml(s) {
- return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' })[c]);
- }
-
- // SVG sparkline of historical scores (1..5 fixed y-axis).
- function renderSparkline(series) {
- if (!series || series.length < 2) {
- return `<div class="spark-empty">${series?.length ? '1 day' : 'no history'}</div>`;
- }
- const W = 120, H = 32, P = 2;
- const xs = series.map((_, i) => P + (i * (W - 2 * P)) / (series.length - 1));
- const ys = series.map((d) => {
- const score = Math.max(1, Math.min(5, d.score || 0));
- return P + (1 - (score - 1) / 4) * (H - 2 * P);
- });
- const path = xs.map((x, i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(' ');
- const lastScore = series[series.length - 1].score;
- const stroke = lastScore >= 4 ? '#1b5e20' : lastScore >= 3 ? '#855008' : '#c62828';
- const fillPath = `${path} L${xs[xs.length-1].toFixed(1)},${H - P} L${xs[0].toFixed(1)},${H - P} Z`;
- return `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-label="score history">
+ })
+ .join('');
+ }
+
+ function filterRows(rows, filter) {
+ if (filter === 'all') return rows;
+ if (filter === 'disputed') return rows.filter((r) => r.disputed || r.revoked);
+ if (filter === 'event')
+ return rows.filter((r) => r.payload?.source?.startsWith?.('pumpkit.'));
+ return rows.filter((r) => r.kind?.includes(`.${filter}.`));
+ }
+
+ function describe(row) {
+ const p = row.payload || {};
+ switch (row.kind) {
+ case 'threews.feedback.v1':
+ return `score ${p.score}/5${p.task_id ? ` for task ${p.task_id}` : ''}${p.source ? ` (${p.source})` : ''}`;
+ case 'threews.validation.v1':
+ return `validation ${p.passed ? '✓ passed' : '✗ failed'}${p.task_hash ? ` (task hash ${String(p.task_hash).slice(0, 12)}…)` : ''}`;
+ case 'threews.task.v1':
+ return `task offered: ${p.task_id}`;
+ case 'threews.accept.v1':
+ return `task accepted: ${p.task_id}`;
+ case 'threews.revoke.v1':
+ return `revoked ${String(p.target_signature || '').slice(0, 12)}…`;
+ case 'threews.dispute.v1':
+ return `disputed ${String(p.target_signature || '').slice(0, 12)}…${p.reason ? ` — ${p.reason}` : ''}`;
+ default:
+ return row.kind;
+ }
+ }
+
+ function escapeHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[
+ c
+ ],
+ );
+ }
+
+ // SVG sparkline of historical scores (1..5 fixed y-axis).
+ function renderSparkline(series) {
+ if (!series || series.length < 2) {
+ return `<div class="spark-empty">${series?.length ? '1 day' : 'no history'}</div>`;
+ }
+ const W = 120,
+ H = 32,
+ P = 2;
+ const xs = series.map((_, i) => P + (i * (W - 2 * P)) / (series.length - 1));
+ const ys = series.map((d) => {
+ const score = Math.max(1, Math.min(5, d.score || 0));
+ return P + (1 - (score - 1) / 4) * (H - 2 * P);
+ });
+ const path = xs
+ .map((x, i) => `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${ys[i].toFixed(1)}`)
+ .join(' ');
+ const lastScore = series[series.length - 1].score;
+ const stroke = lastScore >= 4 ? '#1b5e20' : lastScore >= 3 ? '#855008' : '#c62828';
+ const fillPath = `${path} L${xs[xs.length - 1].toFixed(1)},${H - P} L${xs[0].toFixed(1)},${H - P} Z`;
+ return `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" aria-label="score history">
<path d="${fillPath}" fill="${stroke}" opacity=".12" />
<path d="${path}" fill="none" stroke="${stroke}" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" />
- <circle cx="${xs[xs.length-1].toFixed(1)}" cy="${ys[ys.length-1].toFixed(1)}" r="2" fill="${stroke}" />
+ <circle cx="${xs[xs.length - 1].toFixed(1)}" cy="${ys[ys.length - 1].toFixed(1)}" r="2" fill="${stroke}" />
</svg>`;
- }
-
- async function copyText(text, btn) {
- try {
- await navigator.clipboard.writeText(text);
- const prev = btn.textContent;
- btn.textContent = 'copied';
- setTimeout(() => { btn.textContent = prev; }, 1200);
- } catch {}
- }
-
- $('load').onclick = load;
- $('asset').addEventListener('keydown', (e) => { if (e.key === 'Enter') load(); });
- $('network').addEventListener('change', () => { if ($('asset').value.trim()) load(); });
- $('share').onclick = () => copyText(location.href, $('share'));
- $('embed').onclick = () => {
- const asset = $('asset').value.trim();
- const network = $('network').value;
- if (!asset || !PUBKEY_RE.test(asset)) return;
- const src = `${location.origin}/agent-badge.html?asset=${asset}&network=${network}`;
- const snippet = `<iframe src="${src}" width="320" height="80" style="border:0" loading="lazy"></iframe>`;
- copyText(snippet, $('embed'));
- };
- $('filters').addEventListener('click', (e) => {
- const btn = e.target.closest('.chip');
- if (!btn) return;
- activeFilter = btn.dataset.filter;
- $('filters').querySelectorAll('.chip').forEach((c) => c.setAttribute('aria-pressed', c === btn ? 'true' : 'false'));
- renderAttestations();
- });
-
- if ($('asset').value) load();
- </script>
-</body>
+ }
+
+ async function copyText(text, btn) {
+ try {
+ await navigator.clipboard.writeText(text);
+ const prev = btn.textContent;
+ btn.textContent = 'copied';
+ setTimeout(() => {
+ btn.textContent = prev;
+ }, 1200);
+ } catch {}
+ }
+
+ $('load').onclick = load;
+ $('asset').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') load();
+ });
+ $('network').addEventListener('change', () => {
+ if ($('asset').value.trim()) load();
+ });
+ $('share').onclick = () => copyText(location.href, $('share'));
+ $('embed').onclick = () => {
+ const asset = $('asset').value.trim();
+ const network = $('network').value;
+ if (!asset || !PUBKEY_RE.test(asset)) return;
+ const src = `${location.origin}/agent-badge.html?asset=${asset}&network=${network}`;
+ const snippet = `<iframe src="${src}" width="320" height="80" style="border:0" loading="lazy"></iframe>`;
+ copyText(snippet, $('embed'));
+ };
+ $('filters').addEventListener('click', (e) => {
+ const btn = e.target.closest('.chip');
+ if (!btn) return;
+ activeFilter = btn.dataset.filter;
+ $('filters')
+ .querySelectorAll('.chip')
+ .forEach((c) => c.setAttribute('aria-pressed', c === btn ? 'true' : 'false'));
+ renderAttestations();
+ });
+
+ if ($('asset').value) load();
+ </script>
+ </body>
</html>
diff --git a/public/vanity-wallet.html b/public/vanity-wallet.html
index ef47adcd1..e7ec9d096 100644
--- a/public/vanity-wallet.html
+++ b/public/vanity-wallet.html
@@ -60,6 +60,14 @@
.warn { background: var(--warn-bg); color: var(--warn-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .8rem; }
.warn strong { color: var(--bad-fg); }
+ .assign { margin-top: 1rem; padding: .9rem 1rem; background: #fff; border: 1px solid var(--border); border-radius: 8px; }
+ .assign h4 { margin: 0 0 .4rem; font-size: .9rem; }
+ .assign select { font: inherit; padding: .4rem .55rem; border: 1px solid #ccc; border-radius: 6px; width: 100%; }
+ .assign .custody { font-size: .72rem; color: var(--muted); margin-top: .5rem; }
+ .assign .custody label { display: flex; align-items: flex-start; gap: .4rem; cursor: pointer; }
+ .assign .custody input { margin-top: 3px; }
+ .assigned-ok { background: var(--ok-bg); color: var(--ok-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .85rem; }
+
.error { background: #fff5f5; color: var(--bad-fg); padding: .6rem .85rem; border-radius: 6px; margin-top: 1rem; font-size: .85rem; border: 1px solid #f5c6c6; }
footer { margin-top: 2.5rem; padding-top: 1rem; border-top: 1px solid var(--border); font-size: .78rem; color: var(--muted); }
@@ -307,15 +315,15 @@
</div>
<div class="warn">
<strong>Save this file somewhere safe before navigating away.</strong>
- Once you close this tab the secret key is gone — we don't store it.
+ Once you close this tab the secret key is gone unless you assign it to an agent below.
Anyone with the file can spend funds at this address.
</div>
</div>
+ <div id="assign-host"></div>
`;
const filename = `${addr.slice(0, 8)}.json`;
$('download').addEventListener('click', () => {
- // Solana CLI keypair format: JSON array of 64 bytes.
const json = JSON.stringify(Array.from(result.secretKey));
const blob = new Blob([json], { type: 'application/json' });
const url = URL.createObjectURL(blob);
@@ -335,6 +343,111 @@
setTimeout(() => { $('copy-pubkey').textContent = 'Copy public key'; }, 1500);
} catch {}
});
+
+ renderAssignBlock(result, prefix);
+ }
+
+ // ── Assign to agent ────────────────────────────────────────────────
+ async function renderAssignBlock(result, prefix) {
+ const host = document.getElementById('assign-host');
+ let agents = [];
+ try {
+ const r = await fetch('/api/agents', { credentials: 'include' });
+ if (r.status === 401) {
+ host.innerHTML = `
+ <div class="assign">
+ <h4>Use this wallet with an agent</h4>
+ <p style="font-size:.8rem;color:#555;margin:0">
+ <a href="/login.html?next=${encodeURIComponent(location.pathname)}">Sign in</a>
+ to assign this wallet to one of your agents — they'll be able to sign transactions with it (e.g. for pump.fun trades).
+ </p>
+ </div>`;
+ return;
+ }
+ if (!r.ok) throw new Error(`agents fetch ${r.status}`);
+ const data = await r.json();
+ agents = data.agents || [];
+ } catch (e) {
+ host.innerHTML = `<div class="assign"><h4>Use this wallet with an agent</h4><p style="font-size:.8rem;color:#b71c1c;margin:0">Could not load your agents: ${esc(e.message)}</p></div>`;
+ return;
+ }
+ if (!agents.length) {
+ host.innerHTML = `
+ <div class="assign">
+ <h4>Use this wallet with an agent</h4>
+ <p style="font-size:.8rem;color:#555;margin:0">No agents yet. <a href="/create.html">Create one</a> and come back to assign this wallet.</p>
+ </div>`;
+ return;
+ }
+
+ host.innerHTML = `
+ <div class="assign">
+ <h4>Assign this wallet to an agent</h4>
+ <p style="font-size:.78rem;color:#555;margin:0 0 .5rem">
+ The agent will be able to sign Solana transactions with this address — pumpfun trades, attestations, payments. The secret key will be encrypted at rest on our server.
+ </p>
+ <select id="assign-agent">
+ <option value="">— select an agent —</option>
+ ${agents.map((a) => `<option value="${esc(a.id)}">${esc(a.name)} ${a.meta?.solana_address ? '(already has wallet)' : ''}</option>`).join('')}
+ </select>
+ <div class="custody">
+ <label>
+ <input type="checkbox" id="assign-ack" />
+ <span>I understand this transfers custody — three.ws will be able to sign transactions on the agent's behalf, and the secret key will be encrypted server-side. <strong>Download the file above first as a backup.</strong></span>
+ </label>
+ </div>
+ <div class="actions">
+ <button id="assign-btn" class="btn primary" type="button" disabled>Assign to agent</button>
+ </div>
+ <div id="assign-status" style="margin-top:.5rem;font-size:.8rem"></div>
+ </div>
+ `;
+
+ const sel = document.getElementById('assign-agent');
+ const ack = document.getElementById('assign-ack');
+ const btn = document.getElementById('assign-btn');
+ const status = document.getElementById('assign-status');
+
+ function refresh() { btn.disabled = !sel.value || !ack.checked; }
+ sel.addEventListener('change', refresh);
+ ack.addEventListener('change', refresh);
+
+ btn.addEventListener('click', async () => {
+ btn.disabled = true;
+ status.textContent = 'assigning…';
+ status.style.color = '#555';
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(sel.value)}/solana`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ secret_key: Array.from(result.secretKey),
+ vanity_prefix: prefix,
+ }),
+ });
+ const data = await r.json();
+ if (!r.ok) {
+ if (r.status === 409) {
+ status.innerHTML = `<span style="color:#b71c1c">${esc(data.error_description)} — pick another agent or remove the existing wallet first.</span>`;
+ } else {
+ status.innerHTML = `<span style="color:#b71c1c">Failed: ${esc(data.error_description || r.status)}</span>`;
+ }
+ btn.disabled = false;
+ return;
+ }
+ const agentName = sel.options[sel.selectedIndex].text.replace(/\s*\(already.*\)$/, '');
+ host.innerHTML = `
+ <div class="assigned-ok">
+ ✦ Assigned to <strong>${esc(agentName)}</strong>.
+ The agent can now sign Solana transactions with <code style="font-family:ui-monospace,monospace">${esc(prefix)}…${esc(addr.slice(-4))}</code>.
+ <a href="/agent/${esc(sel.value)}" style="color:inherit;text-decoration:underline">Open agent →</a>
+ </div>`;
+ } catch (e) {
+ status.innerHTML = `<span style="color:#b71c1c">Network error: ${esc(e.message)}</span>`;
+ btn.disabled = false;
+ }
+ });
}
</script>
</body>
diff --git a/src/agent-skills-pumpfun.js b/src/agent-skills-pumpfun.js
index e4b7596a4..5bd3745c4 100644
--- a/src/agent-skills-pumpfun.js
+++ b/src/agent-skills-pumpfun.js
@@ -184,8 +184,14 @@ export function registerPumpFunSkills(skills) {
uri: { type: 'string', description: 'Metaplex metadata URI' },
network: { type: 'string', enum: ['mainnet', 'devnet'] },
initialBuySol: { type: 'number', description: 'Optional dev-buy in same tx (SOL)' },
- mintPublicKey: { type: 'string', description: 'Optional pre-ground vanity mint pubkey' },
- mintSecretKeyB64: { type: 'string', description: 'Base64 64-byte secret key paired with mintPublicKey' },
+ mintPublicKey: {
+ type: 'string',
+ description: 'Optional pre-ground vanity mint pubkey',
+ },
+ mintSecretKeyB64: {
+ type: 'string',
+ description: 'Base64 64-byte secret key paired with mintPublicKey',
+ },
},
required: ['symbol', 'uri'],
},
diff --git a/tests/api/solana-wallet-import.test.js b/tests/api/solana-wallet-import.test.js
new file mode 100644
index 000000000..80947243e
--- /dev/null
+++ b/tests/api/solana-wallet-import.test.js
@@ -0,0 +1,150 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+import { Keypair } from '@solana/web3.js';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+const authState = { session: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+const sqlState = { queue: [], calls: [] };
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: true })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/env.js', () => ({
+ env: { JWT_SECRET: 'test-secret-please-do-not-use-in-production-ever' },
+}));
+
+vi.mock('../../api/_lib/agent-pumpfun.js', () => ({
+ solanaConnection: vi.fn(() => ({
+ getBalance: vi.fn(async () => 0),
+ })),
+}));
+
+vi.mock('../../api/_lib/agent-wallet.js', () => ({
+ generateSolanaAgentWallet: vi.fn(async () => ({
+ address: 'GeneratedAddr1111111111111111111111111111111',
+ encrypted_secret: 'mocked-cipher',
+ })),
+}));
+
+const { default: handler } = await import('../../api/agents/solana-wallet.js');
+
+// ── Helpers ──────────────────────────────────────────────────────────────
+function makeReq({ method = 'POST', body = null } = {}) {
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ base.method = method;
+ base.url = '/api/agents/agent-1/solana';
+ base.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost' };
+ return base;
+}
+function makeRes() {
+ return {
+ statusCode: 200, headers: {}, body: '', writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(c) { if (c !== undefined) this.body += c; this.writableEnded = true; },
+ };
+}
+async function invoke(opts) {
+ const req = makeReq(opts);
+ const res = makeRes();
+ await handler(req, res, 'agent-1');
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+beforeEach(() => {
+ authState.session = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+});
+
+describe('POST /api/agents/:id/solana — import vanity wallet', () => {
+ it('rejects when unauthenticated', async () => {
+ const { status, body } = await invoke({ body: { secret_key: [] } });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('rejects when agent not owned by user', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'someone-else', meta: {} }]);
+ const { status, body } = await invoke({ body: { secret_key: Array(64).fill(0), vanity_prefix: 'AGNT' } });
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+
+ it('rejects malformed secret_key', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'u1', meta: {} }]);
+ const { status, body } = await invoke({ body: { secret_key: [1, 2, 3] } });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/64-byte/);
+ });
+
+ it('rejects vanity_prefix that does not match keypair', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'u1', meta: {} }]);
+ const kp = Keypair.generate();
+ // pick a prefix that almost certainly isn't a real prefix of the address
+ const claimedPrefix = kp.publicKey.toBase58().startsWith('Z') ? 'AAAA' : 'ZZZZ';
+ const { status, body } = await invoke({
+ body: { secret_key: Array.from(kp.secretKey), vanity_prefix: claimedPrefix },
+ });
+ expect(status).toBe(400);
+ expect(body.error_description).toMatch(/does not match/);
+ });
+
+ it('imports a valid keypair successfully', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'u1', meta: {} }]);
+ sqlState.queue.push([]); // UPDATE result (empty)
+ const kp = Keypair.generate();
+ const realPrefix = kp.publicKey.toBase58().slice(0, 1); // first char is always valid
+ const { status, body } = await invoke({
+ body: { secret_key: Array.from(kp.secretKey), vanity_prefix: realPrefix },
+ });
+ expect(status).toBe(201);
+ expect(body.data.address).toBe(kp.publicKey.toBase58());
+ expect(body.data.vanity_prefix).toBe(realPrefix);
+ expect(body.data.source).toBe('imported_vanity');
+ });
+
+ it('rejects import when agent already has a wallet', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{ id: 'agent-1', user_id: 'u1', meta: { solana_address: 'ExistingAddr111' } }]);
+ const kp = Keypair.generate();
+ const { status, body } = await invoke({
+ body: { secret_key: Array.from(kp.secretKey) },
+ });
+ expect(status).toBe(409);
+ expect(body.error).toBe('conflict');
+ });
+});
+
+describe('DELETE /api/agents/:id/solana', () => {
+ it('clears the wallet for the owner', async () => {
+ authState.session = { id: 'u1' };
+ sqlState.queue.push([{
+ id: 'agent-1', user_id: 'u1',
+ meta: { solana_address: 'X', encrypted_solana_secret: 'enc', solana_vanity_prefix: 'AGNT' },
+ }]);
+ sqlState.queue.push([]); // UPDATE
+ const { status, body } = await invoke({ method: 'DELETE' });
+ expect(status).toBe(200);
+ expect(body.data.ok).toBe(true);
+ });
+});