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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(custody): add the signing contract and preview-then-execute records for fund-moving venue actions
nirholasd1f027a9a4d2
diff --git a/api/_lib/action-previews.js b/api/_lib/action-previews.jsnew file mode 100644index 000000000..d02bf9303--- /dev/null+++ b/api/_lib/action-previews.js@@ -0,0 +1,126 @@+// Preview-then-execute records for the venue stacks (perps, lending).+//+// Every fund-moving venue action runs in two calls. The preview prices the+// action against live venue state, runs every guard, and stores exactly what it+// showed the owner; the execution must present that preview's id. A preview is+// bound to one user, one agent and one action, expires after its TTL, and is+// consumed atomically by the execution that uses it, so a stale or replayed+// preview never moves money and the transaction that lands is the one the owner+// confirmed.+//+// Storage is the platform's shared preview ledger, `agent_market_previews`+// (id, user_id, action, params_hash, payload, consumed_at, created_at), the same+// table the agent marketplace's financial MCP tools cite. Venue actions are+// namespaced ("perps.order", "lending.deposit") so they can never satisfy a+// marketplace commit or each other. The agent id, parameters, quote and expiry+// live in `payload`.++import { createHash, randomUUID } from 'node:crypto';+import { sql } from './db.js';++export const DEFAULT_PREVIEW_TTL_MS = 10 * 60_000;++export class ActionPreviewError extends Error {+ constructor(code, message, status = 409) {+ super(message);+ this.name = 'ActionPreviewError';+ this.code = code;+ this.status = status;+ this.detail = null;+ }+}++/** Stable hash of the action and its canonical parameters. */+export function hashParams(action, params = {}) {+ const canon = JSON.stringify(+ Object.keys(params || {})+ .sort()+ .reduce((o, k) => {+ o[k] = params[k];+ return o;+ }, {}),+ );+ return createHash('sha256').update(`${action}:${canon}`).digest('hex');+}++/**+ * Decide whether a stored preview may authorize an execution. Pure, so the+ * expiry and binding rules are unit-tested without a database.+ *+ * @param {{ user_id: string, action: string, payload: object, consumed_at: string|Date|null } | null} row+ * @param {{ userId: string, agentId: string, action: string, hint: string, now?: number }} want+ * @returns {null | ActionPreviewError}+ */+export function actionPreviewProblem(row, { userId, agentId, action, hint, now = Date.now() }) {+ if (!row) return new ActionPreviewError('preview_not_found', `No preview with that id. ${hint}`, 404);+ if (row.user_id !== userId || row.payload?.agent_id !== agentId) {+ return new ActionPreviewError('preview_mismatch', `That preview belongs to a different agent. ${hint}`, 409);+ }+ if (row.action !== action) {+ return new ActionPreviewError('preview_mismatch', `That preview is for ${row.action}, not ${action}. ${hint}`, 409);+ }+ if (row.consumed_at) return new ActionPreviewError('preview_consumed', `That preview was already used. ${hint}`, 409);+ const expires = new Date(row.payload?.expires_at || 0).getTime();+ if (!(expires > now)) {+ const seconds = Math.round((Number(row.payload?.ttl_ms) || DEFAULT_PREVIEW_TTL_MS) / 1000);+ const age = seconds >= 120 ? `${Math.round(seconds / 60)} minutes` : `${seconds} seconds`;+ return new ActionPreviewError('preview_expired', `That preview is more than ${age} old and the market has moved. ${hint}`, 409);+ }+ return null;+}++/**+ * Store a preview and return its id and expiry.+ * @param {{ userId: string, agentId: string, action: string, prefix: string, params: object, quote: object, ttlMs?: number }} o+ */+export async function createActionPreview({ userId, agentId, action, prefix, params, quote, ttlMs = DEFAULT_PREVIEW_TTL_MS }) {+ const id = `${prefix}_${randomUUID().replace(/-/g, '')}`;+ const expiresAt = new Date(Date.now() + ttlMs).toISOString();+ const payload = { agent_id: agentId, params, quote, expires_at: expiresAt, ttl_ms: ttlMs };+ await sql`+ INSERT INTO agent_market_previews (id, user_id, action, params_hash, payload)+ VALUES (${id}, ${userId}, ${action}, ${hashParams(action, params)}, ${JSON.stringify(payload)}::jsonb)+ `;+ return { preview_id: id, expires_at: expiresAt };+}++const ID_RE = /^[a-z]{2,8}_[0-9a-f]{32}$/;++/**+ * Load a preview and verify it may authorize `action` for `agentId`.+ * Returns `{ id, params, quote, expires_at }`. Throws ActionPreviewError.+ */+export async function loadActionPreview(previewId, { userId, agentId, action, hint }) {+ if (!previewId || !ID_RE.test(String(previewId))) {+ throw new ActionPreviewError('preview_required', `A preview_id is required. ${hint}`, 400);+ }+ const [row] = await sql`+ SELECT id, user_id, action, payload, consumed_at, created_at+ FROM agent_market_previews WHERE id = ${previewId}+ `;+ const problem = actionPreviewProblem(row || null, { userId, agentId, action, hint });+ if (problem) throw problem;+ return { id: row.id, params: row.payload.params || {}, quote: row.payload.quote || {}, expires_at: row.payload.expires_at };+}++/**+ * Mark a preview used. Atomic: of two concurrent executions presenting the same+ * preview, exactly one wins; the other gets preview_consumed.+ */+export async function consumeActionPreview(previewId, { hint }) {+ const rows = await sql`+ UPDATE agent_market_previews SET consumed_at = now()+ WHERE id = ${previewId} AND consumed_at IS NULL+ AND (payload->>'expires_at')::timestamptz > now()+ RETURNING id+ `;+ if (!rows.length) throw new ActionPreviewError('preview_consumed', `That preview was already used or just expired. ${hint}`, 409);+}++/** Return a consumed preview to service when the execution moved nothing. */+export async function releaseActionPreview(previewId) {+ await sql`+ UPDATE agent_market_previews SET consumed_at = NULL+ WHERE id = ${previewId} AND (payload->>'expires_at')::timestamptz > now()+ `;+}diff --git a/api/_lib/custody/signing.js b/api/_lib/custody/signing.jsnew file mode 100644index 000000000..7545e10e4--- /dev/null+++ b/api/_lib/custody/signing.js@@ -0,0 +1,307 @@+// The signing contract every fund-moving route and tool calls.+//+// An agent's fund-moving actions are signed one of three ways (agent_signers):+//+// platform the default. The platform decrypts the agent's custodial key and+// signs, behind the confirm flag and the spend policy.+// external the platform never signs. Every fund-moving route returns an+// unsigned, simulated transaction plus a tx_id for the owner's own+// wallet; POST /api/tx/submit broadcasts the signed copy and records+// it in the custody ledger. The signature is the confirmation.+// session the owner granted a delegate key from their own wallet with an+// on-chain SPL approval capped at N units of one mint, valid until+// an expiry. The agent acts unattended within that cap; anything+// the session cannot cover falls back to the external path.+//+// A caller may also ask for `signer: "external"` on any single request, which+// builds for the owner's wallet even when the agent is in platform mode.+//+// Route authors use three functions:+//+// resolveSigningPath() which path this request takes+// prepareForExternalSigner() build + simulate + store an unsigned transaction+// reserveSessionSpend() atomically claim session headroom before signing+//+// and assertPlatformSigningAllowed() is enforced centrally by+// recoverSolanaAgentKeypair, so no custodial signature can happen for an agent+// whose owner opted out of platform custody, even from a route that forgot to+// ask.++import { sql } from '../db.js';+import { prepareExternalTx } from './external-tx.js';+import { clientError } from './builders.js';++export const SIGNER_MODES = Object.freeze(['platform', 'external', 'session']);++// Session limits a grant may ask for. The cap ceiling keeps a typo from+// approving a delegate over the owner's whole balance; the owner can always+// grant again.+export const SESSION_MAX_CAP_UI = 10_000;+export const SESSION_MAX_HOURS = 24 * 30;+export const SESSION_MIN_HOURS = 1;++const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/**+ * Normalize a `signer` request field. Absent means "use the agent's mode".+ * @returns {'platform'|'external'|'session'|null}+ */+export function parseSignerChoice(value) {+ if (value === undefined || value === null || value === '') return null;+ const v = String(value).trim().toLowerCase();+ if (!SIGNER_MODES.includes(v)) {+ throw clientError('invalid_parameter', 'signer must be "platform", "external" or "session"');+ }+ return v;+}++/** The agent's signer row, or the implicit platform default. */+export async function getAgentSigner(agentId) {+ const [row] = await sql`SELECT * FROM agent_signers WHERE agent_id = ${agentId}`;+ return row || { agent_id: agentId, mode: 'platform' };+}++/** A session row's effective status, folding in the expiry clock. */+export function sessionStatus(row, now = Date.now()) {+ if (!row || !row.session_pubkey) return null;+ if (row.session_status === 'active' && row.session_expires_at && new Date(row.session_expires_at).getTime() <= now) {+ return 'expired';+ }+ return row.session_status || null;+}++/** Owner-safe view of a signer row. The session secret never leaves the server. */+export function publicSigner(row, now = Date.now()) {+ const mode = row?.mode || 'platform';+ const status = sessionStatus(row, now);+ const session = row?.session_pubkey+ ? {+ delegate: row.session_pubkey,+ owner: row.external_pubkey || null,+ network: row.session_network || 'mainnet',+ mint: row.session_mint || null,+ decimals: row.session_decimals ?? null,+ cap_raw: row.session_cap_raw != null ? String(row.session_cap_raw) : null,+ cap: row.session_cap_raw != null && row.session_decimals != null+ ? Number(row.session_cap_raw) / 10 ** row.session_decimals+ : null,+ spent_raw: String(row.session_spent_raw ?? 0),+ spent: row.session_decimals != null ? Number(row.session_spent_raw ?? 0) / 10 ** row.session_decimals : null,+ remaining: row.session_cap_raw != null && row.session_decimals != null+ ? Math.max(0, Number(row.session_cap_raw) - Number(row.session_spent_raw ?? 0)) / 10 ** row.session_decimals+ : null,+ expires_at: row.session_expires_at || null,+ status,+ grant_signature: row.session_grant_signature || null,+ }+ : null;+ return {+ agent_id: row?.agent_id ?? null,+ mode,+ external_pubkey: row?.external_pubkey || null,+ custodial: mode === 'platform',+ session,+ updated_at: row?.updated_at || null,+ };+}++/**+ * The user's primary linked Solana wallet (SIWS or wallet link), or null.+ * Used as the external signer when the caller names none.+ */+export async function primaryLinkedSolanaWallet(userId) {+ const [row] = await sql`+ SELECT address FROM user_wallets+ WHERE user_id = ${userId} AND chain_type = 'solana'+ ORDER BY is_primary DESC, last_used_at DESC NULLS LAST, created_at ASC+ LIMIT 1+ `;+ return row?.address || null;+}++function normalizePubkey(value, field) {+ const s = String(value || '').trim();+ if (!BASE58_RE.test(s)) throw clientError('invalid_parameter', `${field} must be a base58 Solana address`);+ return s;+}++/**+ * Decide how one fund-moving request is signed.+ *+ * @param {object} p+ * @param {string|null} p.agentId null for a user-level (no agent) build+ * @param {string} p.userId+ * @param {string|null} [p.requested] parsed `signer` field (parseSignerChoice)+ * @param {string|null} [p.signerPubkey] caller-named wallet for the external path+ * @param {boolean} [p.sessionCapable] true when this action can run under a session key+ * @param {object} [p.signerRow] preloaded agent_signers row (tests, batching)+ * @returns {Promise<{ path: 'custodial' }+ * | { path: 'external', pubkey: string, reason: string }+ * | { path: 'session', signer: object }>}+ */+export async function resolveSigningPath({ agentId, userId, requested = null, signerPubkey = null, sessionCapable = false, signerRow = null }) {+ const named = signerPubkey ? normalizePubkey(signerPubkey, 'signer_pubkey') : null;++ if (!agentId) {+ if (requested === 'platform' || requested === 'session') {+ throw clientError('invalid_parameter', 'a request without an agent can only be signed externally');+ }+ const pubkey = named || (await primaryLinkedSolanaWallet(userId));+ if (!pubkey) throw clientError('signer_pubkey_required', 'Name the wallet that will sign (signer_pubkey), or link a Solana wallet to your account.');+ return { path: 'external', pubkey, reason: 'no_agent' };+ }++ const row = signerRow || (await getAgentSigner(agentId));+ const mode = row.mode || 'platform';++ if (requested === 'platform' && mode !== 'platform') {+ throw clientError('platform_signing_disabled', `This agent is in ${mode} signing mode, so the platform will not sign for it. Use signer "external" or change the mode at PUT /api/agents/${agentId}/signer.`, 409);+ }+ if (requested === 'session' && mode !== 'session') {+ throw clientError('no_session', 'This agent has no active session key. Grant one at PUT /api/agents/' + agentId + '/signer.', 409);+ }++ const externalPubkey = async (reason) => {+ const registered = row.external_pubkey || null;+ if (registered && named && named !== registered) {+ throw clientError('signer_mismatch', `This agent's registered signer is ${registered}; a transaction for another wallet cannot be prepared for it.`, 409);+ }+ const pubkey = registered || named || (await primaryLinkedSolanaWallet(userId));+ if (!pubkey) throw clientError('signer_pubkey_required', 'Name the wallet that will sign (signer_pubkey), or link a Solana wallet to your account.');+ return { path: 'external', pubkey, reason };+ };++ if (requested === 'external') return externalPubkey('requested');+ if (mode === 'external') return externalPubkey('agent_external_mode');+ if (mode === 'session') {+ if (sessionCapable) return { path: 'session', signer: row };+ return externalPubkey('outside_session_scope');+ }+ return { path: 'custodial' };+}++/**+ * Build, simulate and store an unsigned transaction for an external signer.+ *+ * @param {object} p+ * @param {string} p.userId+ * @param {string|null} p.agentId+ * @param {string} p.kind an EXTERNAL_TX_KINDS value (transfer, withdraw, swap, ...)+ * @param {'mainnet'|'devnet'} p.network+ * @param {string} p.pubkey the wallet that signs and pays fees+ * @param {(pubkey: string) => Promise<{ transaction: import('@solana/web3.js').VersionedTransaction,+ * summary: object, lastValidBlockHeight?: number|null }>} p.build+ * @param {object} [p.connection]+ * @param {boolean} [p.simulate=true]+ */+export async function prepareForExternalSigner({ userId, agentId = null, kind, network, pubkey, build, connection = null, simulate = true }) {+ const built = await build(pubkey);+ return prepareExternalTx({+ userId,+ agentId,+ kind,+ network,+ signer: pubkey,+ transaction: built.transaction,+ summary: built.summary,+ lastValidBlockHeight: built.lastValidBlockHeight ?? null,+ simulate,+ connection,+ });+}++/**+ * Pure check: may this session key spend `amountRaw` of `mint` right now?+ * @returns {{ ok: true } | { ok: false, status: number, code: string, message: string }}+ */+export function sessionAllows(row, { mint, amountRaw, network = null, now = Date.now() }) {+ const status = sessionStatus(row, now);+ if (!row || row.mode !== 'session' || !row.session_pubkey) {+ return { ok: false, status: 409, code: 'no_session', message: 'This agent has no session key.' };+ }+ if (status === 'expired') {+ return { ok: false, status: 403, code: 'session_expired', message: `The session key expired at ${new Date(row.session_expires_at).toISOString()}. Grant a new one to keep acting unattended.` };+ }+ if (status !== 'active') {+ return { ok: false, status: 403, code: 'session_inactive', message: `The session key is ${status || 'not active'}; it cannot sign.` };+ }+ if (network && row.session_network && network !== row.session_network) {+ return { ok: false, status: 403, code: 'session_wrong_network', message: `The session key covers ${row.session_network}, not ${network}.` };+ }+ if (!mint || mint !== row.session_mint) {+ return { ok: false, status: 403, code: 'session_wrong_asset', message: 'The session key only covers the token it was granted for.' };+ }+ const amount = BigInt(String(amountRaw));+ if (amount <= 0n) return { ok: false, status: 400, code: 'invalid_amount', message: 'amount must be positive' };+ const cap = BigInt(String(row.session_cap_raw ?? 0));+ const spent = BigInt(String(row.session_spent_raw ?? 0));+ if (spent + amount > cap) {+ const d = Number(row.session_decimals ?? 0);+ const ui = (v) => Number(v) / 10 ** d;+ return {+ ok: false,+ status: 403,+ code: 'session_cap_exceeded',+ message: `This transfer of ${ui(amount)} would exceed the session cap: ${ui(spent)} of ${ui(cap)} already used, ${ui(cap - spent > 0n ? cap - spent : 0n)} left.`,+ };+ }+ return { ok: true };+}++/**+ * Atomically claim `amountRaw` of session headroom. The UPDATE's WHERE clause+ * is the cap check, so two concurrent spends can never together exceed it.+ * Throws a tagged 4xx naming the reason when the claim is refused.+ * @returns {Promise<{ row: object, release: () => Promise<void> }>}+ */+export async function reserveSessionSpend(agentId, { mint, amountRaw, network = null }) {+ const amount = String(BigInt(String(amountRaw)));+ const [row] = await sql`+ UPDATE agent_signers+ SET session_spent_raw = session_spent_raw + ${amount}::numeric, updated_at = now()+ WHERE agent_id = ${agentId}+ AND mode = 'session'+ AND session_status = 'active'+ AND session_expires_at > now()+ AND session_mint = ${mint}+ AND (${network}::text IS NULL OR session_network = ${network})+ AND session_spent_raw + ${amount}::numeric <= session_cap_raw+ RETURNING *+ `;+ if (!row) {+ const current = await getAgentSigner(agentId);+ const verdict = sessionAllows(current, { mint, amountRaw: amount, network });+ const why = verdict.ok+ ? { status: 409, code: 'session_contended', message: 'The session headroom changed while this was being claimed; try again.' }+ : verdict;+ throw clientError(why.code, why.message, why.status);+ }+ let released = false;+ return {+ row,+ release: async () => {+ if (released) return;+ released = true;+ await sql`+ UPDATE agent_signers+ SET session_spent_raw = GREATEST(0, session_spent_raw - ${amount}::numeric), updated_at = now()+ WHERE agent_id = ${agentId}+ `;+ },+ };+}++/**+ * Throw when the platform must not sign for this agent. Called by+ * recoverSolanaAgentKeypair for every audited key recovery.+ */+export async function assertPlatformSigningAllowed(agentId) {+ const [row] = await sql`SELECT mode FROM agent_signers WHERE agent_id = ${agentId}`;+ const mode = row?.mode;+ if (mode === 'external' || mode === 'session') {+ throw Object.assign(+ new Error(`This agent is in ${mode} signing mode, so the platform will not sign for it. Send signer "external" to get a transaction for your own wallet, or switch back to platform custody.`),+ { status: 409, code: 'platform_signing_disabled', expose: true, signerMode: mode },+ );+ }+}diff --git a/api/_lib/trading-tools/agent.js b/api/_lib/trading-tools/agent.jsnew file mode 100644index 000000000..be6bb70f3--- /dev/null+++ b/api/_lib/trading-tools/agent.js@@ -0,0 +1,99 @@+// Shared plumbing for the agent-wallet trading tools: load an agent the caller+// owns, read its wallet balances, and check the real-funds agreement.+//+// Every financial trading tool acts on one agent's custodial Solana wallet and+// only for that agent's owner. These helpers are the one place that check is+// made, so the MCP tools and the v1 REST routes refuse the same way.++import { PublicKey } from '@solana/web3.js';++import { sql } from '../db.js';+import { solanaConnection } from '../agent-pumpfun.js';+import { currentSignatureFor, agreementRequirement } from '../real-funds-agreement.js';+import { ToolInputError, WSOL_MINT } from './market.js';++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/**+ * The agent row, when `userId` owns it. Throws a ToolInputError otherwise.+ * @param {string} agentId+ * @param {string} userId+ */+export async function loadOwnedAgent(agentId, userId) {+ if (!userId) throw new ToolInputError('auth_required', 'Sign in to three.ws to act on your agents.');+ if (typeof agentId !== 'string' || !UUID_RE.test(agentId)) {+ throw new ToolInputError('invalid_agent', 'agent_id must be the uuid of one of your agents.');+ }+ const [row] = await sql`+ SELECT id, user_id, name, status, meta+ FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!row) throw new ToolInputError('agent_not_found', 'No agent with that id exists.');+ if (row.user_id !== userId) throw new ToolInputError('forbidden', 'Only the owner of this agent can use its wallet.');+ const meta = { ...(row.meta || {}) };+ return { ...row, meta, address: meta.solana_address || null, signable: Boolean(meta.encrypted_solana_secret) };+}++/** The agent's wallet address, or a designed refusal when it has none yet. */+export function requireWallet(agent) {+ if (!agent.address) {+ throw new ToolInputError('no_wallet', 'This agent has no Solana wallet yet. Create one with provision_wallet, fund it, then try again.');+ }+ return agent.address;+}++/**+ * Lamports and one token's raw balance for an address, read at 'confirmed'.+ * @param {string} address+ * @param {string|null} mint null or wrapped SOL reads only the SOL balance+ * @returns {Promise<{ lamports: bigint, tokenRaw: bigint|null }>}+ */+export async function readBalances(address, mint = null) {+ const conn = solanaConnection('mainnet');+ const owner = new PublicKey(address);+ const lamports = BigInt(await conn.getBalance(owner, 'confirmed'));+ if (!mint || mint === WSOL_MINT) return { lamports, tokenRaw: null };+ const resp = await conn.getParsedTokenAccountsByOwner(owner, { mint: new PublicKey(mint) });+ let raw = 0n;+ for (const { account } of resp.value || []) {+ const amt = account.data?.parsed?.info?.tokenAmount?.amount;+ if (amt) raw += BigInt(amt);+ }+ return { lamports, tokenRaw: raw };+}++/**+ * Whether the account signed the current real-funds agreements. Throws a+ * designed refusal naming the sign url when it has not.+ * @param {string} userId+ */+export async function requireAgreement(userId) {+ let signed;+ try {+ signed = await currentSignatureFor(userId);+ } catch {+ throw new ToolInputError('agreement_check_unavailable', 'Could not verify your signed real-funds agreements, so nothing moved. Try again in a moment.');+ }+ if (!signed) {+ const r = agreementRequirement();+ throw new ToolInputError('risk_ack_required', `Sign the real-funds agreements before moving funds. Nothing moved. Sign at ${r.sign_url}`, r);+ }+ return signed;+}++/** Same check, as a guard row for a preview (never throws on "not signed"). */+export async function agreementCheck(userId) {+ try {+ const signed = await currentSignatureFor(userId);+ return { id: 'agreement', label: 'Real-funds agreements signed', ok: Boolean(signed), detail: signed ? null : agreementRequirement().sign_url };+ } catch {+ return { id: 'agreement', label: 'Real-funds agreements signed', ok: false, detail: 'could not be verified right now' };+ }+}++/** Shape a list of guard rows into the preview's verdict fields. */+export function verdict(checks) {+ const blocked = checks.filter((c) => !c.ok).map((c) => c.id);+ return { checks, executable: blocked.length === 0, blocked_by: blocked };+}diff --git a/api/_lib/trading-tools/venues.js b/api/_lib/trading-tools/venues.jsnew file mode 100644index 000000000..23acbd419--- /dev/null+++ b/api/_lib/trading-tools/venues.js@@ -0,0 +1,282 @@+// The venue interface: one shape for every place an agent can price or fill a+// swap, so the trading tools, the arbitrage desk and the EVM leg speak the same+// language regardless of which market sits underneath.+//+// A venue is:+//+// {+// id: stable id used in tool arguments ('auto', 'launchpad', a DEX id, 'evm-aggregator')+// chain: 'solana' | 'evm'+// kind: 'aggregate' | 'dex' | 'launchpad' | 'evm-aggregator'+// name: display name+// quote(req): Promise<VenueQuote | null> null means "this venue cannot fill it"+// executor: how an agent wallet fills here (see below), or null when the+// venue is priced for comparison only+// }+//+// VenueQuote (every venue, every chain):+//+// { venue, chain, input, output, in_amount_raw, out_amount_raw, min_out_raw,+// price_impact_pct, slippage_bps, route: string[] }+//+// Solana executors plug into the guarded custodial trade executor in+// api/agents/solana-trade.js (runAgentTrade). That executor owns the whole+// guard chain (kill switch, per-trade cap, daily budget, USD spend ceiling,+// price-impact breaker, rug firewall, SOL headroom), the idempotent custody+// ledger, key recovery and the protected send; a venue only supplies how to+// price and how to build. The launchpad venue is the executor's own default+// (curve, then AMM), so it has no custom executor. Every other Solana venue+// routes through the aggregator, optionally pinned to one DEX, and supplies:+//+// executor.quote(args) the same shape quoteTrade() returns+// executor.build(args) { instructions, addressLookupTables }+//+// Solana custodial swaps keep SOL on one side, because the guard chain meters+// spend in SOL. Any other pair is quoted, never custodially executed.+//+// The EVM venue wraps the EVM leg's aggregator (api/_lib/evm-leg/swap.js),+// which carries its own per-chain guards and custody rows.++import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';++import { jupiterQuote, jupiterSwapTx } from '../token/jupiter.js';+import { ARB_VENUES } from './arbitrage.js';+import { ToolInputError, WSOL_MINT, tokenDecimals } from './market.js';++export const SOLANA = 'solana';+export const EVM = 'evm';++// The launchpad's curve and graduated pool, as the aggregator labels them.+const LAUNCHPAD_ROUTES = ARB_VENUES.filter((v) => v.launchpad);++const LAMPORTS_PER_SOL = 1_000_000_000;++function fail(status, code, message) {+ return Object.assign(new Error(message), { status, code });+}++const pct = (v) => {+ const n = Number(v);+ return Number.isFinite(n) ? Math.max(0, Math.min(100, n * 100)) : 0;+};++// ── Solana aggregator executor ───────────────────────────────────────────────++/**+ * Price one custodial trade on the aggregator, optionally pinned to a single+ * DEX. Returns the exact shape quoteTrade() returns, plus `raw` (the router's+ * quote) so build() fills precisely what was priced.+ */+async function aggregatorQuote(dexLabel, { side, mintStr, network, solAmount, tokenAmountRaw, slippageBps }) {+ if (network !== 'mainnet') throw fail(422, 'venue_mainnet_only', 'this venue routes mainnet liquidity only; use the launchpad venue on devnet');+ const decimals = await tokenDecimals(mintStr).catch(() => null);+ if (decimals == null) throw fail(422, 'unknown_decimals', 'could not read the token decimals for this mint');+ const buy = side === 'buy';+ const amount = buy ? BigInt(Math.floor(Number(solAmount) * LAMPORTS_PER_SOL)) : BigInt(tokenAmountRaw);+ if (amount <= 0n) throw fail(400, 'amount_too_small', 'enter an amount greater than zero');++ let q;+ try {+ q = await jupiterQuote({+ inputMint: buy ? WSOL_MINT : mintStr,+ outputMint: buy ? mintStr : WSOL_MINT,+ amount: amount.toString(),+ slippageBps,+ dexes: dexLabel ? [dexLabel] : null,+ onlyDirectRoutes: Boolean(dexLabel),+ });+ } catch (err) {+ const s = Number(err?.status);+ if (s === 400 || s === 404) throw Object.assign(fail(404, 'pool_not_found', 'this venue has no route for this pair'), { code: 'pool_not_found' });+ throw fail(502, 'quote_failed', 'could not price this trade on this venue right now');+ }+ if (!q?.outAmount) throw Object.assign(fail(404, 'pool_not_found', 'this venue has no route for this pair'), { code: 'pool_not_found' });++ const out = BigInt(q.outAmount);+ const minOut = BigInt(q.otherAmountThreshold ?? q.outAmount);+ const shape = {+ venue: dexLabel ? `dex:${dexLabel}` : 'aggregate',+ graduated: true,+ quoteAsset: 'SOL',+ decimals,+ priceImpactPct: pct(q.priceImpactPct),+ route: (q.routePlan || []).map((r) => r?.swapInfo?.label).filter(Boolean),+ raw: q,+ };+ if (buy) {+ return {+ ...shape,+ inAsset: 'SOL', inAmount: Number(solAmount), inAtomics: amount.toString(),+ outAsset: 'TOKEN', outAtomics: out.toString(), outUi: Number(out) / 10 ** decimals,+ minOutAtomics: minOut.toString(), minOutUi: Number(minOut) / 10 ** decimals,+ };+ }+ return {+ ...shape,+ inAsset: 'TOKEN', inAtomics: amount.toString(), inUi: Number(amount) / 10 ** decimals,+ outAsset: 'SOL', outAtomics: out.toString(), outUi: Number(out) / LAMPORTS_PER_SOL,+ minOutAtomics: minOut.toString(), minOutUi: Number(minOut) / LAMPORTS_PER_SOL,+ };+}++/**+ * Build the priced route as plain instructions plus its address lookup+ * tables, so the protected sender sets its own compute budget and priority+ * fee (it strips the router's) and signs with the agent key.+ */+async function aggregatorBuild({ conn, ownerPk, quote }) {+ if (!quote?.raw) throw fail(422, 'build_failed', 'the quote carries no route to build');+ let b64;+ try {+ b64 = await jupiterSwapTx({ quote: quote.raw, userPublicKey: ownerPk.toBase58(), wrapAndUnwrapSol: true });+ } catch {+ throw fail(502, 'build_failed', 'the router could not build this route right now; try again');+ }+ const tx = VersionedTransaction.deserialize(Buffer.from(b64, 'base64'));+ const lookups = tx.message.addressTableLookups || [];+ const addressLookupTables = [];+ for (const l of lookups) {+ const res = await conn.getAddressLookupTable(new PublicKey(l.accountKey));+ if (!res?.value) throw fail(502, 'build_failed', 'an address lookup table for this route could not be read');+ addressLookupTables.push(res.value);+ }+ const message = TransactionMessage.decompile(tx.message, { addressLookupTableAccounts: addressLookupTables });+ return { instructions: message.instructions, addressLookupTables };+}++function aggregatorExecutor(dexLabel) {+ return {+ id: dexLabel ? `dex:${dexLabel}` : 'aggregate',+ quote: (args) => aggregatorQuote(dexLabel, args),+ build: (args) => aggregatorBuild(args),+ };+}++// ── Solana comparison quote (any pair) ───────────────────────────────────────++async function solanaQuote(dexLabel, { input, output, amountRaw, slippageBps = 50 }) {+ try {+ const q = await jupiterQuote({+ inputMint: input,+ outputMint: output,+ amount: String(amountRaw),+ slippageBps,+ dexes: dexLabel ? [dexLabel] : null,+ onlyDirectRoutes: Boolean(dexLabel),+ });+ if (!q?.outAmount) return null;+ return {+ chain: SOLANA,+ input,+ output,+ in_amount_raw: String(amountRaw),+ out_amount_raw: String(q.outAmount),+ min_out_raw: String(q.otherAmountThreshold ?? q.outAmount),+ price_impact_pct: pct(q.priceImpactPct),+ slippage_bps: slippageBps,+ route: (q.routePlan || []).map((p) => p?.swapInfo?.label).filter(Boolean),+ };+ } catch (err) {+ const s = Number(err?.status);+ if (s === 400 || s === 404) return null;+ throw fail(502, 'venue_unavailable', 'this venue could not be priced right now');+ }+}++// ── registry ─────────────────────────────────────────────────────────────────++const auto = {+ id: 'auto',+ chain: SOLANA,+ kind: 'aggregate',+ name: 'Best route across every Solana venue',+ quote: (req) => solanaQuote(null, req).then((q) => (q ? { venue: 'auto', ...q } : null)),+ executor: aggregatorExecutor(null),+};++const launchpad = {+ id: 'launchpad',+ chain: SOLANA,+ kind: 'launchpad',+ name: 'Launchpad bonding curve and its graduated AMM',+ quote: async (req) => {+ for (const route of LAUNCHPAD_ROUTES) {+ const q = await solanaQuote(route.label, req).catch(() => null);+ if (q) return { venue: 'launchpad', ...q };+ }+ return null;+ },+ // null: runAgentTrade's own quoteTrade/buildTradeInstructions (curve, then AMM).+ executor: null,+};++// Every individually priced venue. The launchpad's own routes fill through the+// executor's default path, so they carry no custom executor.+const dexVenues = ARB_VENUES.map((v) => ({+ id: v.id,+ chain: SOLANA,+ kind: 'dex',+ name: v.name,+ quote: (req) => solanaQuote(v.label, req).then((q) => (q ? { venue: v.id, ...q } : null)),+ executor: v.launchpad ? null : aggregatorExecutor(v.label),+}));++const evmAggregator = {+ id: 'evm-aggregator',+ chain: EVM,+ kind: 'evm-aggregator',+ name: 'EVM aggregator (Base, Robinhood Chain)',+ quote: async ({ chain, input, output, amountRaw, slippageBps = 50, from = null }) => {+ const { quoteEvmSwap } = await import('../evm-leg/swap.js');+ const q = await quoteEvmSwap({ chain, sellToken: input, buyToken: output, amountRaw: String(amountRaw), fromAddress: from, slippageBps });+ return {+ venue: 'evm-aggregator',+ chain: EVM,+ evm_chain: q.chain,+ input,+ output,+ in_amount_raw: q.amount_in_raw,+ out_amount_raw: q.amount_out_raw,+ min_out_raw: q.min_out_raw,+ price_impact_pct: q.price_impact_pct,+ slippage_bps: slippageBps,+ gas_usd: q.gas_usd,+ route: [q.provider].filter(Boolean),+ };+ },+ // EVM fills go through api/_lib/evm-leg/swap.js executeEvmSwap, which owns+ // the per-chain guards and the custody row.+ executor: null,+};++/** Every venue, Solana first. */+export const VENUES = Object.freeze([auto, launchpad, ...dexVenues, evmAggregator]);+const BY_ID = new Map(VENUES.map((v) => [v.id, v]));++/** Venue by id. Throws a ToolInputError naming the valid ids. */+export function getVenue(id = 'auto') {+ const v = BY_ID.get(String(id || 'auto'));+ if (!v) throw new ToolInputError('invalid_venue', `Unknown venue "${id}". Use one of: ${VENUES.map((x) => x.id).join(', ')}.`);+ return v;+}++/** Venues on one chain, as plain descriptors for a tool or page. */+export function listVenues({ chain = null } = {}) {+ return VENUES.filter((v) => !chain || v.chain === chain).map((v) => ({+ id: v.id,+ chain: v.chain,+ kind: v.kind,+ name: v.name,+ custodial_pairs: v.chain === SOLANA ? 'SOL on one side' : 'any ERC-20 or the native coin',+ }));+}++/**+ * The runAgentTrade executor for a Solana venue, or null for the executor's+ * own default path (the launchpad venue). Throws for an EVM venue.+ */+export function solanaExecutorFor(id) {+ const v = getVenue(id);+ if (v.chain !== SOLANA) throw new ToolInputError('wrong_chain', `${v.id} is an EVM venue; pass chain to swap on the EVM leg.`);+ return v.executor;+}