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: MEV execution engine, sniper executor and trade-client upgrades
nirholas6635b922f0e5
diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsnew file mode 100644index 000000000..2196b9705--- /dev/null+++ b/api/_lib/execution-engine.js@@ -0,0 +1,550 @@+// MEV-aware execution engine — the single protected broadcast path for every+// agent-signed trade on three.ws (the sniper worker + both discretionary trade+// endpoints).+//+// submitProtected({ network, connection, payer, instructions, opts })+// → { signature, slot, route, tipLamports, priorityFeeMicroLamports, attempts, landedMs }+//+// What it does, all with REAL on-chain / Jito calls (never a simulated landing+// or a fabricated fee):+//+// 1. Dynamic compute budget. Prepends ComputeBudgetProgram.setComputeUnitLimit+// from a REAL simulateTransaction unit estimate (not a guess) and+// setComputeUnitPrice from a REAL priority-fee estimate — Helius+// getPriorityFeeEstimate when HELIUS_API_KEY is set, falling back to the+// getRecentPrioritizationFees 75th-percentile. Both estimates are cached+// briefly so the hot snipe path doesn't re-pay for them every tick.+//+// 2. Jito bundle route. When tipMode is 'economy'|'turbo' AND a Jito Block+// Engine is reachable on mainnet, it fetches the live tip-floor, appends a+// REAL SOL tip transfer to a Jito tip account as the last instruction, and+// submits the signed tx as a single-tx bundle via sendBundle. It then polls+// getBundleStatuses for a real landing. Tip sizing is adaptive: it scales+// with the mode and the live tip-floor and escalates on retry.+//+// 3. Transparent fallback. Devnet, tipMode 'off', no Jito, or a Jito error all+// fall back to the protected single-tx route (sendRawTransaction + confirm)+// and SAY SO in the returned `route`/`fallbackReason`. A bundle that doesn't+// land within the poll window is reported as not-landed and retried on the+// protected route — never claimed as landed.+//+// 4. Adaptive retry. Simulate first (skippable for a pre-simulated caller); on+// blockhash expiry or a not-landed bundle, refresh the blockhash, escalate+// the priority fee + tip, and re-submit up to a bounded count. Honest+// landing telemetry (route, attempts, tip, fee, landedMs) is returned.+//+// Idempotency / double-spend safety is the CALLER's responsibility (the sniper's+// per-(agent,mint) lock + DB claim, the endpoints' idempotency key). Re-sending+// the same signed tx to a second RPC or a bundle is safe — Solana dedupes by+// signature, and a landed tx confirms regardless of which lane carried it.++import {+ ComputeBudgetProgram,+ PublicKey,+ SystemProgram,+ TransactionMessage,+ VersionedTransaction,+} from '@solana/web3.js';++// Jito's published mainnet tip accounts. A bundle's tip must transfer SOL to one+// of these — Jito only accepts a bundle that pays a tip to a known tip account.+// (https://docs.jito.wtf/lowlatencytxnsend/#tip-amount). We rotate per-attempt to+// spread load and avoid a hot account.+const JITO_TIP_ACCOUNTS = [+ '96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5',+ 'HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe',+ 'Cw8CFyM9FkoMi7K7Crf6HNQqf4uEMzpKw6QNghp5dF6',+ 'ADaUMid9yfUytqMBgopwjb2DTLSokTSzL1zt6iGPaS49',+ 'DfXygSm4jCyNCybVYYK6DwvWqjKee8pbDmJGcLWNDXjh',+ 'ADuUkR4vqLUMWXxW9gh6D6L8pMSawimctcNZ5pGwDcEt',+ 'DttWaMuVvTiduZRnguLF7jNxTgiMBZ1hyAumKUiL2KRL',+ '3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT',+];++const DEFAULT_JITO_URL = 'https://mainnet.block-engine.jito.wtf';+const LAMPORTS_PER_SOL = 1_000_000_000;++// ── adaptive tip sizing (lamports) ────────────────────────────────────────────+// A tip is real SOL leaving the wallet, so the floors are deliberately modest and+// the ceiling hard-caps any single tip. 'economy' rides near the live tip-floor;+// 'turbo' pays a multiple for first-block inclusion under contention. Each retry+// escalates the chosen tip toward the ceiling.+const TIP_PROFILE = {+ economy: { floor: 10_000n, multiplier: 1.5, ceiling: 1_000_000n },+ turbo: { floor: 100_000n, multiplier: 4, ceiling: 5_000_000n },+};++// Compute-unit price floors per mode (microLamports/CU) — a lower bound so the tx+// is never priced below what the network currently demands even if the estimate+// reads abnormally low. Turbo bids the network fee up alongside the bundle tip.+const CU_PRICE_FLOOR = { off: 1_000, economy: 5_000, turbo: 25_000 };+const CU_PRICE_CEILING = 5_000_000; // hard cap on microLamports/CU++const MAX_ATTEMPTS = 3;+const BUNDLE_POLL_MS = 700; // between getBundleStatuses polls+const BUNDLE_POLL_TIMEOUT_MS = 12_000; // give a bundle this long to land before falling back++// ── brief estimate caches (per lambda instance) ──────────────────────────────+// Keyed by network. The hot snipe path calls submitProtected on every fill; these+// keep the priority-fee + tip-floor reads off the critical path for a few seconds+// without ever serving a stale-enough value to misprice a tx.+const PRIORITY_FEE_TTL_MS = 4_000;+const TIP_FLOOR_TTL_MS = 4_000;+const _priorityFeeCache = new Map(); // network → { at, microLamports }+const _tipFloorCache = new Map(); // jitoUrl → { at, lamports }++function jitoBlockEngineUrl() {+ const u = (process.env.JITO_BLOCK_ENGINE_URL || DEFAULT_JITO_URL).trim();+ return u.replace(/\/+$/, '');+}++/** A Jito bundle route is only attempted on mainnet with a non-'off' tip mode. */+function jitoEligible(network, tipMode) {+ return network !== 'devnet' && (tipMode === 'economy' || tipMode === 'turbo');+}++function pickTipAccount(attempt) {+ return JITO_TIP_ACCOUNTS[attempt % JITO_TIP_ACCOUNTS.length];+}++function clampBig(v, min, max) {+ if (v < min) return min;+ if (v > max) return max;+ return v;+}++// ── priority fee estimate (microLamports per CU) ──────────────────────────────+// Helius getPriorityFeeEstimate first (it reads the global fee market, not just+// this node's recent blocks); falls back to the connection's+// getRecentPrioritizationFees 75th percentile. Cached briefly per network.+async function estimatePriorityFeeMicroLamports(connection, network) {+ const cached = _priorityFeeCache.get(network);+ if (cached && Date.now() - cached.at < PRIORITY_FEE_TTL_MS) return cached.microLamports;++ let micro = null;+ const heliusKey = process.env.HELIUS_API_KEY;+ if (heliusKey) {+ micro = await heliusPriorityFee(heliusKey, network).catch(() => null);+ }+ if (micro == null) {+ micro = await recentPrioritizationFee(connection).catch(() => null);+ }+ if (micro == null) micro = 5_000; // last-resort floor; never zero-priced++ const value = Math.max(0, Math.round(micro));+ _priorityFeeCache.set(network, { at: Date.now(), microLamports: value });+ return value;+}++async function heliusPriorityFee(heliusKey, network) {+ const host = network === 'devnet' ? 'devnet.helius-rpc.com' : 'mainnet.helius-rpc.com';+ const url = `https://${host}/?api-key=${heliusKey}`;+ const resp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({+ jsonrpc: '2.0',+ id: 'three-ws-mev',+ method: 'getPriorityFeeEstimate',+ // account-less, options-only form: Helius returns the global recommended+ // microLamports/CU. We escalate from this in turbo, so 'Medium'/recommended+ // is the right anchor.+ params: [{ options: { recommended: true } }],+ }),+ });+ if (!resp.ok) throw new Error(`helius pf ${resp.status}`);+ const body = await resp.json();+ const est = body?.result?.priorityFeeEstimate;+ if (typeof est !== 'number' || !Number.isFinite(est)) throw new Error('helius pf shape');+ return est;+}++async function recentPrioritizationFee(connection) {+ const fees = await connection.getRecentPrioritizationFees();+ if (!Array.isArray(fees) || fees.length === 0) return 1_000;+ const sorted = fees.map((f) => f.prioritizationFee).filter((n) => Number.isFinite(n)).sort((a, b) => a - b);+ if (!sorted.length) return 1_000;+ return sorted[Math.floor(sorted.length * 0.75)] ?? sorted[sorted.length - 1];+}++// ── compute-unit estimate ─────────────────────────────────────────────────────+// A REAL simulateTransaction of the trade instructions to read unitsConsumed,+// padded 15% for the runtime drift between sim and land. Not cached (it depends on+// the exact instruction set), but it's a single RPC call on the hot path.+async function estimateComputeUnits(connection, payer, instructions) {+ const { blockhash } = await connection.getLatestBlockhash('confirmed');+ const msg = new TransactionMessage({+ payerKey: payer.publicKey,+ recentBlockhash: blockhash,+ instructions,+ }).compileToV0Message();+ const sim = await connection.simulateTransaction(new VersionedTransaction(msg), {+ sigVerify: false,+ replaceRecentBlockhash: true,+ commitment: 'confirmed',+ });+ if (sim.value?.err) {+ const err = new Error(`pre-broadcast simulation failed: ${JSON.stringify(sim.value.err)}`);+ err.code = 'SIM_FAILED';+ err.simLogs = sim.value.logs || [];+ throw err;+ }+ const units = sim.value?.unitsConsumed;+ if (!units || units <= 0) {+ // No unit count returned — fall back to a conservative bound by instruction+ // count rather than the chain default 200k (which under-budgets a multi-CPI+ // pump.fun buy that opens an ATA).+ return Math.min(1_400_000, 60_000 + instructions.length * 40_000);+ }+ // +15% headroom, clamped to the per-tx max (1.4M CU).+ return Math.min(1_400_000, Math.ceil(units * 1.15));+}++// ── Jito Block Engine REST ────────────────────────────────────────────────────+async function jitoRpc(method, params) {+ const url = `${jitoBlockEngineUrl()}/api/v1/bundles`;+ const resp = await fetch(url, {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),+ });+ if (!resp.ok) {+ const text = await resp.text().catch(() => '');+ const err = new Error(`jito ${method} ${resp.status}: ${text.slice(0, 160)}`);+ err.code = 'JITO_HTTP';+ throw err;+ }+ const body = await resp.json();+ if (body.error) {+ const err = new Error(`jito ${method}: ${body.error.message || JSON.stringify(body.error)}`);+ err.code = 'JITO_RPC';+ throw err;+ }+ return body.result;+}++// Live Jito tip-floor (lamports). Reads the tip-floor endpoint and uses the 50th+// percentile of recent landed-tips as the baseline. Cached briefly. Returns null+// when the endpoint is unreachable — the caller then uses the mode floor.+async function fetchJitoTipFloorLamports() {+ const url = jitoBlockEngineUrl();+ const cached = _tipFloorCache.get(url);+ if (cached && Date.now() - cached.at < TIP_FLOOR_TTL_MS) return cached.lamports;+ try {+ const resp = await fetch(`${url}/api/v1/bundles/tip_floor`, { method: 'GET' });+ if (!resp.ok) return null;+ const body = await resp.json();+ const row = Array.isArray(body) ? body[0] : body;+ // The endpoint reports tips in SOL; prefer the 50th percentile, fall back to+ // the EMA of landed tips.+ const sol = row?.landed_tips_50th_percentile ?? row?.ema_landed_tips_50th_percentile ?? null;+ if (sol == null || !Number.isFinite(Number(sol))) return null;+ const lamports = BigInt(Math.max(0, Math.round(Number(sol) * LAMPORTS_PER_SOL)));+ _tipFloorCache.set(url, { at: Date.now(), lamports });+ return lamports;+ } catch {+ return null;+ }+}++// Resolve the tip for this attempt: max(mode floor, live tip-floor) scaled by the+// mode multiplier and the attempt index, hard-capped by the mode ceiling.+function resolveTipLamports(tipMode, tipFloorLamports, attempt) {+ const profile = TIP_PROFILE[tipMode];+ if (!profile) return 0n;+ const base = tipFloorLamports != null && tipFloorLamports > profile.floor ? tipFloorLamports : profile.floor;+ // Escalate with both the mode multiplier and the retry index (attempt 0 = base).+ const scaled = BigInt(Math.ceil(Number(base) * profile.multiplier * (1 + attempt * 0.5)));+ return clampBig(scaled, profile.floor, profile.ceiling);+}++// Submit a signed v0 tx as a single-tx Jito bundle and poll for a real landing.+// Returns { landed, slot, bundleId } — landed:false means the poll window lapsed+// without an on-chain landing (the caller falls back to the protected route).+async function sendJitoBundle(signedTx, signature, connection) {+ const b64 = Buffer.from(signedTx.serialize()).toString('base64');+ const bundleId = await jitoRpc('sendBundle', [[b64], { encoding: 'base64' }]);++ const deadline = Date.now() + BUNDLE_POLL_TIMEOUT_MS;+ while (Date.now() < deadline) {+ await sleep(BUNDLE_POLL_MS);+ // Prefer the chain's own view of the signature — it's authoritative and avoids+ // trusting Jito's status alone for a landing claim.+ const status = await connection+ .getSignatureStatus(signature, { searchTransactionHistory: true })+ .catch(() => null);+ const conf = status?.value?.confirmationStatus;+ if (status?.value?.err) {+ return { landed: false, slot: null, bundleId, error: status.value.err };+ }+ if (conf === 'confirmed' || conf === 'finalized') {+ return { landed: true, slot: status.value.slot ?? null, bundleId };+ }+ // Cross-check Jito's bundle status: a 'Failed'/'Dropped' verdict ends the wait+ // early so we fall back without burning the full timeout.+ const jitoStatus = await jitoRpc('getBundleStatuses', [[bundleId]]).catch(() => null);+ const st = jitoStatus?.value?.[0]?.confirmation_status || jitoStatus?.value?.[0]?.status;+ if (st === 'failed' || st === 'Failed' || st === 'dropped' || st === 'Dropped') {+ return { landed: false, slot: null, bundleId };+ }+ }+ return { landed: false, slot: null, bundleId };+}++function sleep(ms) {+ return new Promise((r) => setTimeout(r, ms));+}++// ── protected single-tx route ─────────────────────────────────────────────────+// sendRawTransaction with preflight, then a bounded confirm with an ambiguous-+// timeout re-check (a landed tx is never reported as failed). Returns the slot on+// landing.+async function sendProtected(signedTx, signature, connection, blockhashCtx, confirmTimeoutMs) {+ await connection.sendRawTransaction(signedTx.serialize(), { skipPreflight: false, maxRetries: 3 });++ const confirmPromise = connection.confirmTransaction(+ { signature, blockhash: blockhashCtx.blockhash, lastValidBlockHeight: blockhashCtx.lastValidBlockHeight },+ 'confirmed',+ );+ const timeout = new Promise((_, rej) =>+ setTimeout(() => rej(Object.assign(new Error('confirm timeout'), { code: 'CONFIRM_TIMEOUT' })), confirmTimeoutMs),+ );++ let landed = false;+ let slot = null;+ try {+ const result = await Promise.race([confirmPromise, timeout]);+ if (result?.value?.err) {+ throw Object.assign(new Error(`tx failed on-chain: ${JSON.stringify(result.value.err)}`), { code: 'TX_ERR' });+ }+ landed = true;+ slot = result?.context?.slot ?? null;+ } catch (err) {+ if (err?.code === 'TX_ERR') throw err;+ // Ambiguous confirm (timeout / RPC blip): re-check the chain before giving up+ // so a tx that actually landed isn't retried or reported as not-landed.+ const status = await connection.getSignatureStatus(signature, { searchTransactionHistory: true }).catch(() => null);+ if (status?.value?.err) {+ throw Object.assign(new Error(`tx failed on-chain: ${JSON.stringify(status.value.err)}`), { code: 'TX_ERR' });+ }+ const conf = status?.value?.confirmationStatus;+ landed = conf === 'confirmed' || conf === 'finalized';+ slot = status?.value?.slot ?? null;+ if (!landed) {+ const e = new Error('not landed within confirm window');+ e.code = 'NOT_LANDED';+ throw e;+ }+ }+ return { landed, slot };+}++/**+ * Submit a protected, MEV-aware transaction.+ *+ * @param {object} o+ * @param {'mainnet'|'devnet'} o.network+ * @param {import('@solana/web3.js').Connection} o.connection failover-wrapped Connection+ * @param {import('@solana/web3.js').Keypair} o.payer the agent keypair (signs)+ * @param {import('@solana/web3.js').TransactionInstruction[]} o.instructions the trade ixs+ * @param {object} [o.opts]+ * @param {'off'|'economy'|'turbo'} [o.opts.tipMode='off'] per-strategy Jito tip policy+ * @param {number} [o.opts.confirmTimeoutMs=45000] protected-route confirm bound+ * @param {boolean} [o.opts.preSimulated=false] caller already simulated (firewall) — still estimates CU+ * @param {(tipLamports: bigint, route: string) => Promise<void>} [o.opts.onTip]+ * Spend-guard hook invoked BEFORE a tip is appended. Throw to veto the+ * tip (engine then falls back to the protected route, no tip paid).+ * @returns {Promise<{ signature: string, slot: number|null, route: string,+ * tipLamports: number, priorityFeeMicroLamports: number, attempts: number,+ * landedMs: number, fallbackReason: string|null }>}+ */+export async function submitProtected({ network, connection, payer, instructions, opts = {} }) {+ const tipMode = ['economy', 'turbo'].includes(opts.tipMode) ? opts.tipMode : 'off';+ const confirmTimeoutMs = Number.isFinite(opts.confirmTimeoutMs) ? opts.confirmTimeoutMs : 45_000;+ const t0 = Date.now();++ // 1. Data-driven compute budget. Estimate the priority fee and the CU limit in+ // parallel — both are real RPC reads (fee cached, CU is a fresh simulate).+ const [priorityFeeBase, cuLimit] = await Promise.all([+ estimatePriorityFeeMicroLamports(connection, network),+ estimateComputeUnits(connection, payer, instructions),+ ]);++ const canJito = jitoEligible(network, tipMode);+ const tipFloor = canJito ? await fetchJitoTipFloorLamports() : null;++ let attempts = 0;+ let lastErr = null;+ let fallbackReason = canJito ? null : (network === 'devnet' ? 'devnet_no_jito' : (tipMode === 'off' ? 'tip_mode_off' : null));++ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {+ attempts = attempt + 1;++ // Escalate the priority fee on each retry; floor + ceiling clamp it.+ const feeFloor = CU_PRICE_FLOOR[tipMode] || CU_PRICE_FLOOR.off;+ const priorityFeeMicroLamports = Math.min(+ CU_PRICE_CEILING,+ Math.max(feeFloor, Math.round(priorityFeeBase * (1 + attempt * 0.6))),+ );++ // Decide whether THIS attempt rides the Jito bundle. The first attempt(s) try+ // Jito; a bundle that doesn't land falls the NEXT attempt back to protected.+ const tryJito = canJito && fallbackReason == null;+ let tipLamports = 0n;+ const budgetIxs = [+ ComputeBudgetProgram.setComputeUnitLimit({ units: cuLimit }),+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: priorityFeeMicroLamports }),+ ];+ const txIxs = [...budgetIxs, ...instructions];++ if (tryJito) {+ tipLamports = resolveTipLamports(tipMode, tipFloor, attempt);+ // Spend-guard the tip BEFORE it's appended. The hook counts it against the+ // daily budget + kill switch; a veto drops us to the protected route with no+ // tip ever leaving the wallet.+ let tipVetoed = false;+ if (typeof opts.onTip === 'function') {+ try {+ await opts.onTip(tipLamports, tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy');+ } catch (e) {+ tipVetoed = true;+ fallbackReason = e?.code === 'spend_guard' ? 'tip_spend_guarded' : 'tip_vetoed';+ }+ }+ if (tipVetoed) {+ // Re-loop on the same attempt index via protected route (don't consume a+ // retry just to drop the tip).+ attempt--;+ continue;+ }+ txIxs.push(+ SystemProgram.transfer({+ fromPubkey: payer.publicKey,+ toPubkey: new PublicKey(pickTipAccount(attempt)),+ lamports: tipLamports,+ }),+ );+ }++ // Build, sign.+ let blockhashCtx;+ try {+ blockhashCtx = await connection.getLatestBlockhash('confirmed');+ } catch (e) {+ lastErr = e;+ continue;+ }+ const msg = new TransactionMessage({+ payerKey: payer.publicKey,+ recentBlockhash: blockhashCtx.blockhash,+ instructions: txIxs,+ }).compileToV0Message();+ const tx = new VersionedTransaction(msg);+ tx.sign([payer]);+ const signature = bs58Sig(tx);++ try {+ if (tryJito) {+ const res = await sendJitoBundle(tx, signature, connection).catch((e) => {+ // Jito unreachable / rejected: record honestly and fall back. We do NOT+ // claim a landing — control falls through to the protected re-send of the+ // SAME signed tx (Solana dedupes), so the tip tx still has a chance to land.+ fallbackReason = `jito_unavailable:${e?.code || 'error'}`;+ return null;+ });+ if (res?.landed) {+ return {+ signature,+ slot: res.slot,+ route: tipMode === 'turbo' ? 'jito_turbo' : 'jito_economy',+ tipLamports: Number(tipLamports),+ priorityFeeMicroLamports,+ attempts,+ landedMs: Date.now() - t0,+ fallbackReason: null,+ };+ }+ // Bundle didn't land (or Jito errored). The SAME signed tx (tip included)+ // may still land via a normal RPC broadcast — re-send it protected before+ // giving up this attempt.+ if (res && fallbackReason == null) fallbackReason = 'jito_not_landed';+ const prot = await sendProtected(tx, signature, connection, blockhashCtx, confirmTimeoutMs).catch((e) => {+ lastErr = e;+ return null;+ });+ if (prot?.landed) {+ return {+ signature,+ slot: prot.slot,+ // The tip tx landed via the public lane — honest route label.+ route: 'protected',+ tipLamports: Number(tipLamports),+ priorityFeeMicroLamports,+ attempts,+ landedMs: Date.now() - t0,+ fallbackReason: fallbackReason || 'jito_not_landed',+ };+ }+ // Neither lane landed this attempt — retry with a fresh blockhash + higher+ // fee/tip. Stop attempting Jito if it's the one that's down.+ continue;+ }++ // Protected single-tx route (devnet, tip 'off', or post-fallback).+ const prot = await sendProtected(tx, signature, connection, blockhashCtx, confirmTimeoutMs);+ if (prot.landed) {+ return {+ signature,+ slot: prot.slot,+ route: 'protected',+ tipLamports: 0,+ priorityFeeMicroLamports,+ attempts,+ landedMs: Date.now() - t0,+ fallbackReason,+ };+ }+ } catch (e) {+ lastErr = e;+ // A hard on-chain failure (TX_ERR) is terminal — the instructions reverted,+ // retrying the same trade would just revert again.+ if (e?.code === 'TX_ERR' || e?.code === 'SIM_FAILED') throw e;+ // Blockhash expiry / not-landed: refresh and retry.+ }+ }++ const err = lastErr || new Error('execution engine exhausted retries without landing');+ if (!err.code) err.code = 'EXEC_EXHAUSTED';+ throw err;+}++// Recover the base58 signature string from a signed VersionedTransaction without+// re-importing bs58 (web3.js bundles it; the signature is the first signature).+function bs58Sig(tx) {+ const sig = tx.signatures?.[0];+ if (!sig) throw new Error('transaction is not signed');+ // @solana/web3.js exposes bs58 via its own export; encode the 64-byte sig.+ return encodeBase58(sig);+}++// Minimal, dependency-free base58 encode (Bitcoin alphabet) for a 64-byte sig.+const B58_ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';+function encodeBase58(bytes) {+ const digits = [0];+ for (let i = 0; i < bytes.length; i++) {+ let carry = bytes[i];+ for (let j = 0; j < digits.length; j++) {+ carry += digits[j] << 8;+ digits[j] = carry % 58;+ carry = (carry / 58) | 0;+ }+ while (carry > 0) {+ digits.push(carry % 58);+ carry = (carry / 58) | 0;+ }+ }+ let out = '';+ for (let k = 0; k < bytes.length && bytes[k] === 0; k++) out += '1';+ for (let q = digits.length - 1; q >= 0; q--) out += B58_ALPHABET[digits[q]];+ return out;+}diff --git a/api/_lib/migrations/20260620062600_mev_execution.sql b/api/_lib/migrations/20260620062600_mev_execution.sqlnew file mode 100644index 000000000..58cd5826d--- /dev/null+++ b/api/_lib/migrations/20260620062600_mev_execution.sql@@ -0,0 +1,45 @@+-- Migration: MEV-Aware Execution Engine — Jito bundle telemetry + per-strategy tip mode.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260620062600_mev_execution.sql+-- Idempotent.+--+-- The execution engine (api/_lib/execution-engine.js) replaces the sniper's and+-- the discretionary endpoints' raw single-tx broadcast with a protected path:+-- a data-driven compute budget (real simulate + real priority-fee estimate), an+-- optional real Jito Block Engine bundle with an adaptive SOL tip, simulate-then-+-- send with bounded adaptive retry, and honest landing telemetry. This migration:+--+-- 1. agent_sniper_strategies.mev_tip_mode — per-strategy Jito tip policy.+-- 'off' (default): never pay a Jito tip; submit the protected single tx.+-- 'economy': pay a small tip near the tip-floor when a bundle route is viable.+-- 'turbo': pay an aggressive tip for first-block inclusion under contention.+--+-- 2. agent_sniper_positions execution telemetry (all nullable — a position+-- opened before this migration, or in simulate mode, simply has nulls):+-- exec_route — 'jito_turbo' | 'jito_economy' | 'protected' | 'simulated'+-- tip_lamports — real SOL tip paid to the Jito tip account (0 when none)+-- priority_fee_microlamports — the compute-unit price actually set on the tx+-- landed_ms — wall-clock ms from first submit to confirmed landing++begin;++-- ── per-strategy Jito tip policy ─────────────────────────────────────────────+alter table agent_sniper_strategies+ add column if not exists mev_tip_mode text not null default 'off'+ check (mev_tip_mode in ('off', 'economy', 'turbo'));++-- ── execution telemetry on each position ─────────────────────────────────────+alter table agent_sniper_positions+ add column if not exists exec_route text+ check (exec_route is null or exec_route in+ ('jito_turbo', 'jito_economy', 'protected', 'simulated'));++alter table agent_sniper_positions+ add column if not exists tip_lamports numeric(20, 0);++alter table agent_sniper_positions+ add column if not exists priority_fee_microlamports numeric(20, 0);++alter table agent_sniper_positions+ add column if not exists landed_ms integer;++commit;diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.jsindex 96dd01c13..665b78863 100644--- a/api/agents/agent-trade.js+++ b/api/agents/agent-trade.js@@ -44,6 +44,7 @@ import {SOL_FEE_HEADROOM_LAMPORTS, TRADE_LIMIT_DEFAULTS,} from '../_lib/agent-trade-guards.js';import { assessTradeSafety, recordFirewallDecision, firewallGuardResponse } from '../_lib/trade-firewall.js';+import { submitProtected } from '../_lib/execution-engine.js';const WSOL_MINT = 'So11111111111111111111111111111111111111112';const CONFIRM_TIMEOUT_MS = 45_000;@@ -528,10 +529,10 @@ async function handleExecute(req, res, id) {return error(res, 500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');}- // Submit + confirm, re-checking the chain on an ambiguous timeout.+ // Submit + confirm through the protected execution engine.let result;try {- result = await signSendConfirm(conn, keypair, built.instructions);+ result = await signSendConfirm(conn, keypair, built.instructions, network);} catch (e) {await updateCustodyEvent(claimId, { status: 'failed', meta: { error: e?.code || 'send_failed', message: e?.message?.slice(0, 200) } }).catch(() => {});logAudit({ userId: auth.userId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint: input.mint, reason: e?.code || 'send_failed', network }, req });@@ -544,8 +545,8 @@ async function handleExecute(req, res, id) {return error(res, 202, 'trade_unconfirmed', 'the trade was submitted but not yet confirmed — check the explorer link before retrying', { signature: result.signature, explorer: explorerTxUrl(result.signature, network) });}- await updateCustodyEvent(claimId, { status: 'confirmed', signature: result.signature }).catch(() => {});- logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: input.mint, venue: prep.venue, network, signature: result.signature, usd: prep.usdValue }, req });+ await updateCustodyEvent(claimId, { status: 'confirmed', signature: result.signature, meta: result.exec ? { exec: result.exec } : undefined }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: input.mint, venue: prep.venue, network, signature: result.signature, usd: prep.usdValue, exec_route: result.exec?.route }, req });// Re-read the SOL balance for the response.let newSol = null;@@ -564,6 +565,7 @@ async function handleExecute(req, res, id) {: { tokens_sold: prep.baseAmount.toString(), sol_received: lamportsToSol(prep.expectedOutRaw) }),min_out: prep.minOutRaw.toString(),new_balance_sol: newSol,+ execution: result.exec || null,},});}@@ -572,40 +574,32 @@ async function safeBlockhash(conn) {try { return await conn.getLatestBlockhash('confirmed'); } catch { return null; }}-// Assemble a v0 tx, sign with the agent key, broadcast, and confirm — with a-// status re-check on an ambiguous confirm so a landed tx is never marked failed.-// Mirrors the proven flow in solana-wallet.js handleWithdraw.-async function signSendConfirm(conn, payer, instructions) {- const bh = await conn.getLatestBlockhash('confirmed');- const message = new TransactionMessage({- payerKey: payer.publicKey,- recentBlockhash: bh.blockhash,- instructions,- }).compileToV0Message();- const vtx = new VersionedTransaction(message);- vtx.sign([payer]);-- let signature;+// Broadcast + confirm through the MEV-aware execution engine: dynamic compute+// budget (real simulate + real priority-fee estimate) and bounded adaptive retry+// with an ambiguous-confirm re-check so a landed tx is never marked failed. The+// discretionary path has no per-strategy tip policy, so it uses the protected+// single-tx route (tipMode 'off' — no Jito tip) while still getting the data-driven+// fee + retry. Returns the execution telemetry for the response.+async function signSendConfirm(conn, payer, instructions, network) {+ let result;try {- signature = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });+ result = await submitProtected({+ network, connection: conn, payer, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: CONFIRM_TIMEOUT_MS },+ });} catch (e) {- throw Object.assign(new Error(e?.message || 'send failed'), { code: 'send_failed' });- }-- let confirmed = true;- try {- const r = await conn.confirmTransaction({ signature, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight }, 'confirmed');- if (r?.value?.err) confirmed = false;- } catch {- try {- const st = await conn.getSignatureStatus(signature, { searchTransactionHistory: true });- const s = st?.value?.confirmationStatus;- confirmed = !st?.value?.err && (s === 'confirmed' || s === 'finalized');- } catch {- confirmed = false;+ if (e?.code === 'TX_ERR') {+ // Landed but reverted on-chain — surfaced as confirmed:false so the caller+ // records the (failed) signature rather than retrying.+ return { signature: e.signature || null, confirmed: false, exec: null };}+ throw Object.assign(new Error(e?.message || 'send failed'), { code: 'send_failed' });}- return { signature, confirmed };+ return {+ signature: result.signature,+ confirmed: true,+ exec: { route: result.route, priority_fee_microlamports: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts },+ };}// ── preview / quote ───────────────────────────────────────────────────────────diff --git a/api/agents/solana-trade.js b/api/agents/solana-trade.jsindex 876c439a6..2fa272f15 100644--- a/api/agents/solana-trade.js+++ b/api/agents/solana-trade.js@@ -25,7 +25,7 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';import { solanaConnection, solanaPublicConnection } from '../_lib/agent-pumpfun.js';-import { PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';+import { PublicKey } from '@solana/web3.js';import { cacheSet } from '../_lib/cache.js';import { logAudit } from '../_lib/audit.js';import { explorerTxUrl } from '../_lib/avatar-wallet.js';@@ -42,6 +42,7 @@ import {import { getBuyQuote, getSellQuote } from '../_lib/solana/sdk-bridge.js';import { getAmmPoolState } from '../_lib/pump.js';import { assessTradeSafety, recordFirewallDecision } from '../_lib/trade-firewall.js';+import { submitProtected } from '../_lib/execution-engine.js';const LAMPORTS_PER_SOL = 1_000_000_000;const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -526,39 +527,32 @@ export async function handleTrade(req, res, id) {return error(res, 422, 'build_failed', 'could not build this trade — the market may have moved; try again');}- // Sign v0 + send + confirm (with the same unconfirmed re-check the withdraw- // path uses — never mark failed on an ambiguous confirm that may have landed).+ // Broadcast + confirm through the MEV-aware execution engine: dynamic compute+ // budget (real simulate + real priority-fee estimate) + bounded adaptive retry,+ // with the same ambiguous-confirm re-check the withdraw path uses (never mark a+ // landed tx failed). The discretionary path has no per-strategy tip policy, so it+ // uses the protected single-tx route (tipMode 'off' — no Jito tip).const signConn = solanaConnection(network);- let blockhashCtx;- try {- blockhashCtx = await signConn.getLatestBlockhash('confirmed');- } catch {- await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'blockhash_failed' } }).catch(() => {});- return error(res, 502, 'rpc_error', 'the Solana network was unreachable — no funds were moved; try again');- }- const msg = new TransactionMessage({ payerKey: keypair.publicKey, recentBlockhash: blockhashCtx.blockhash, instructions }).compileToV0Message();- const vtx = new VersionedTransaction(msg);- vtx.sign([keypair]);-let signature;- try {- signature = await signConn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });- } catch (e) {- await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});- logAudit({ userId: auth.userId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint: mintStr, reason: 'send_failed' }, req });- return error(res, 502, 'send_failed', 'the trade could not be submitted and no funds were moved — try again');- }-let confirmed = true;+ let execTelemetry = null;try {- const r = await signConn.confirmTransaction({ signature, blockhash: blockhashCtx.blockhash, lastValidBlockHeight: blockhashCtx.lastValidBlockHeight }, 'confirmed');- if (r?.value?.err) confirmed = false;- } catch {- try {- const st = await signConn.getSignatureStatus(signature, { searchTransactionHistory: true });- const s = st?.value?.confirmationStatus;- confirmed = !st?.value?.err && (s === 'confirmed' || s === 'finalized');- } catch { confirmed = false; }+ const result = await submitProtected({+ network, connection: signConn, payer: keypair, instructions,+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },+ });+ signature = result.signature;+ execTelemetry = { route: result.route, priority_fee_microlamports: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts };+ } catch (e) {+ if (e?.code === 'TX_ERR') {+ // Landed but reverted on-chain — record the failed signature, don't re-send.+ signature = e.signature || null;+ confirmed = false;+ } else {+ await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'send_failed', message: (e?.message || '').slice(0, 200) } }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade_failed', resourceId: id, meta: { side, mint: mintStr, reason: 'send_failed' }, req });+ return error(res, 502, 'send_failed', 'the trade could not be submitted and no funds were moved — try again');+ }}if (!confirmed) {@@ -567,8 +561,8 @@ export async function handleTrade(req, res, id) {return error(res, 202, 'trade_unconfirmed', 'the trade was submitted but not yet confirmed — check the explorer link before retrying', { signature, explorer: explorerTxUrl(signature, network) });}- await updateCustodyEvent(claimId, { status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null }).catch(() => {});- logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: mintStr, venue: quote.venue, usd: usdValue, signature, network }, req });+ await updateCustodyEvent(claimId, { status: 'confirmed', signature, usd: side === 'buy' ? usdValue ?? null : null, meta: execTelemetry ? { exec: execTelemetry } : undefined }).catch(() => {});+ logAudit({ userId: auth.userId, action: 'custody.trade', resourceId: id, meta: { side, mint: mintStr, venue: quote.venue, usd: usdValue, signature, network, exec_route: execTelemetry?.route }, req });// Mirror into pump_agent_trades for cross-feature analytics when the mint is a// three.ws-launched coin (FK requires a pump_agent_mints row). Best-effort.@@ -587,6 +581,7 @@ export async function handleTrade(req, res, id) {...quotePayload,filled: { in: quotePayload.in, expected_out: quotePayload.out, min_received: quotePayload.min_received },new_balance_sol: newSol,+ execution: execTelemetry,},});}diff --git a/api/sniper/history.js b/api/sniper/history.jsindex a264998dc..d281664b8 100644--- a/api/sniper/history.js+++ b/api/sniper/history.js@@ -54,6 +54,7 @@ export default wrap(async (req, res) => {select p.id, p.agent_id, p.network, p.mint, p.symbol, p.name,p.status, p.exit_reason, p.entry_quote_lamports, p.exit_quote_lamports,p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,+ p.exec_route, p.tip_lamports, p.priority_fee_microlamports, p.landed_ms,p.opened_at, p.closed_at,a.name as agent_name, a.profile_image_url as agent_image, a.avatar_url as agent_avatarfrom agent_sniper_positions p@@ -69,6 +70,7 @@ export default wrap(async (req, res) => {select p.id, p.agent_id, p.network, p.mint, p.symbol, p.name,p.status, p.exit_reason, p.entry_quote_lamports, p.exit_quote_lamports,p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,+ p.exec_route, p.tip_lamports, p.priority_fee_microlamports, p.landed_ms,p.opened_at, p.closed_at,a.name as agent_name, a.profile_image_url as agent_image, a.avatar_url as agent_avatarfrom agent_sniper_positions p@@ -94,6 +96,10 @@ export default wrap(async (req, res) => {pnl_pct: r.realized_pnl_pct != null ? Number(r.realized_pnl_pct) : null,buy_url: solscan(r.buy_sig, network),sell_url: solscan(r.sell_sig, network),+ exec_route: r.exec_route || null,+ tip_lamports: r.tip_lamports != null ? Number(r.tip_lamports) : null,+ priority_fee_microlamports: r.priority_fee_microlamports != null ? Number(r.priority_fee_microlamports) : null,+ landed_ms: r.landed_ms != null ? Number(r.landed_ms) : null,opened_at: r.opened_at,closed_at: r.closed_at,}));diff --git a/api/sniper/strategy.js b/api/sniper/strategy.jsindex 3b21d5bcd..b57744736 100644--- a/api/sniper/strategy.js+++ b/api/sniper/strategy.js@@ -69,6 +69,9 @@ const STRATEGY_SCHEMA = z.object({max_concurrent_positions: z.union([z.string(), z.number()]).optional(),slippage_bps: z.union([z.string(), z.number()]).optional(),max_price_impact_pct: z.union([z.string(), z.number()]).optional(),+ // MEV-aware execution: per-strategy Jito tip policy + rug/honeypot firewall mode.+ mev_tip_mode: z.enum(['off', 'economy', 'turbo']).optional(),+ firewall_level: z.enum(['block', 'warn', 'off']).optional(),// entry filters (null clears)min_market_cap_usd: optPct,max_market_cap_usd: optPct,@@ -256,6 +259,7 @@ async function upsertStrategy(req, res, userId) {min_claim_lamports: null, max_claim_lamports: null, first_claim_max_age_seconds: null,daily_budget_lamports: '0', per_trade_lamports: '0',max_concurrent_positions: 1, slippage_bps: 500, max_price_impact_pct: 10,+ mev_tip_mode: 'off', firewall_level: 'block',min_market_cap_usd: null, max_market_cap_usd: null,min_creator_graduated: null, max_creator_launches: null,require_socials: false, require_sol_quote: true,@@ -280,6 +284,8 @@ async function upsertStrategy(req, res, userId) {max_concurrent_positions: p.max_concurrent_positions != null ? clampInt(p.max_concurrent_positions, 1, 50, 1) : cur.max_concurrent_positions,slippage_bps: p.slippage_bps != null ? clampInt(p.slippage_bps, 0, 5000, 500) : cur.slippage_bps,max_price_impact_pct: p.max_price_impact_pct != null ? Math.min(100, Math.max(0, Number(p.max_price_impact_pct))) : Number(cur.max_price_impact_pct),+ mev_tip_mode: p.mev_tip_mode != null ? p.mev_tip_mode : (cur.mev_tip_mode || 'off'),+ firewall_level: p.firewall_level != null ? p.firewall_level : (cur.firewall_level || 'block'),min_market_cap_usd: 'min_market_cap_usd' in p ? numOrNull(p.min_market_cap_usd) : (cur.min_market_cap_usd != null ? Number(cur.min_market_cap_usd) : null),max_market_cap_usd: 'max_market_cap_usd' in p ? numOrNull(p.max_market_cap_usd) : (cur.max_market_cap_usd != null ? Number(cur.max_market_cap_usd) : null),min_creator_graduated: 'min_creator_graduated' in p ? intOrNull(p.min_creator_graduated) : cur.min_creator_graduated,@@ -320,7 +326,7 @@ async function upsertStrategy(req, res, userId) {(agent_id, user_id, network, enabled, kill_switch,trigger, buy_delay_ms, min_claim_lamports, max_claim_lamports, first_claim_max_age_seconds,daily_budget_lamports, per_trade_lamports, max_concurrent_positions,- slippage_bps, max_price_impact_pct,+ slippage_bps, max_price_impact_pct, mev_tip_mode, firewall_level,min_market_cap_usd, max_market_cap_usd, min_creator_graduated, max_creator_launches,require_socials, require_sol_quote,take_profit_pct, stop_loss_pct, trailing_stop_pct, max_hold_seconds,@@ -331,7 +337,7 @@ async function upsertStrategy(req, res, userId) {(${p.agent_id}, ${userId}, ${p.network}, ${next.enabled}, ${next.kill_switch},${next.trigger}, ${next.buy_delay_ms}, ${next.min_claim_lamports}, ${next.max_claim_lamports}, ${next.first_claim_max_age_seconds},${next.daily_budget_lamports}, ${next.per_trade_lamports}, ${next.max_concurrent_positions},- ${next.slippage_bps}, ${next.max_price_impact_pct},+ ${next.slippage_bps}, ${next.max_price_impact_pct}, ${next.mev_tip_mode}, ${next.firewall_level},${next.min_market_cap_usd}, ${next.max_market_cap_usd}, ${next.min_creator_graduated}, ${next.max_creator_launches},${next.require_socials}, ${next.require_sol_quote},${next.take_profit_pct}, ${next.stop_loss_pct}, ${next.trailing_stop_pct}, ${next.max_hold_seconds},@@ -351,6 +357,8 @@ async function upsertStrategy(req, res, userId) {max_concurrent_positions = excluded.max_concurrent_positions,slippage_bps = excluded.slippage_bps,max_price_impact_pct = excluded.max_price_impact_pct,+ mev_tip_mode = excluded.mev_tip_mode,+ firewall_level = excluded.firewall_level,min_market_cap_usd = excluded.min_market_cap_usd,max_market_cap_usd = excluded.max_market_cap_usd,min_creator_graduated = excluded.min_creator_graduated,diff --git a/api/sniper/stream.js b/api/sniper/stream.jsindex bb82181c2..a592e5e45 100644--- a/api/sniper/stream.js+++ b/api/sniper/stream.js@@ -45,6 +45,10 @@ function shape(r, network) {pnl_pct: r.realized_pnl_pct != null ? Number(r.realized_pnl_pct) : (entry > 0 ? ((last - entry) / entry) * 100 : null),buy_url: solscan(r.buy_sig, network),sell_url: solscan(r.sell_sig, network),+ exec_route: r.exec_route || null,+ tip_lamports: r.tip_lamports != null ? Number(r.tip_lamports) : null,+ priority_fee_microlamports: r.priority_fee_microlamports != null ? Number(r.priority_fee_microlamports) : null,+ landed_ms: r.landed_ms != null ? Number(r.landed_ms) : null,at: r.changed_at,};}@@ -84,7 +88,9 @@ export default async function handleSniperStream(req, res) {select p.id, p.agent_id, a.name as agent_name, p.mint, p.symbol, p.name,p.status, p.exit_reason, p.entry_quote_lamports, p.last_value_lamports,p.exit_quote_lamports, p.realized_pnl_lamports, p.realized_pnl_pct,- p.buy_sig, p.sell_sig, p.opened_at, p.closed_at,+ p.buy_sig, p.sell_sig,+ p.exec_route, p.tip_lamports, p.priority_fee_microlamports, p.landed_ms,+ p.opened_at, p.closed_at,greatest(p.opened_at, coalesce(p.closed_at, p.opened_at),coalesce(p.last_quoted_at, p.opened_at)) as changed_atfrom agent_sniper_positions pdiff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.jsindex c88b6f6a0..1af355435 100644--- a/src/dashboard-next/pages/sniper.js+++ b/src/dashboard-next/pages/sniper.js@@ -134,6 +134,14 @@ const STYLE = `<style>.sn-ob-score { font: 700 11px/1 var(--nxt-mono, monospace); font-variant-numeric: tabular-nums; }.sn-ob-tier { font: 600 8px/1 var(--nxt-mono, monospace); text-transform: uppercase; letter-spacing: .06em; opacity: .8; }.sn-empty { color: var(--nxt-ink-faint); font-size: 13px; padding: 24px 16px; text-align: center; }+/* execution readout — MEV route, tip, time-to-land */+.sn-exec { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-top: 5px; }+.sn-exec-badge { font: 600 9.5px/1 var(--nxt-mono, monospace); text-transform: uppercase; letter-spacing: .05em; padding: 3px 6px; border-radius: 5px; border: 1px solid var(--nxt-stroke); color: var(--nxt-ink-faint); }+.sn-exec-turbo { color: #c084fc; border-color: color-mix(in srgb, #c084fc 45%, transparent); background: color-mix(in srgb, #c084fc 10%, transparent); }+.sn-exec-jito { color: #34d399; border-color: color-mix(in srgb, #34d399 45%, transparent); background: color-mix(in srgb, #34d399 10%, transparent); }+.sn-exec-prot { color: #60a5fa; border-color: color-mix(in srgb, #60a5fa 40%, transparent); }+.sn-exec-sim { color: var(--nxt-ink-faint); }+.sn-exec-meta { font: 500 10px/1 var(--nxt-mono, monospace); color: var(--nxt-ink-faint); font-variant-numeric: tabular-nums; }/* trade history */.sn-hist { background: var(--nxt-panel); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); overflow: hidden; }@@ -392,6 +400,26 @@ function stratForm(s) {<span class="sn-hint">100 bps = 1%.</span></div>+ <div class="sn-section-head">Execution & Safety</div>+ <div class="sn-field">+ <label>MEV tip mode</label>+ <select name="mev_tip_mode" aria-label="MEV tip mode">+ <option value="off" ${(!s.mev_tip_mode || s.mev_tip_mode === 'off') ? 'selected' : ''}>Off — protected single tx, no tip</option>+ <option value="economy" ${s.mev_tip_mode === 'economy' ? 'selected' : ''}>Economy — Jito bundle, small tip near the floor</option>+ <option value="turbo" ${s.mev_tip_mode === 'turbo' ? 'selected' : ''}>Turbo — Jito bundle, aggressive tip for first-block</option>+ </select>+ <span class="sn-hint">A Jito tip is real SOL leaving the wallet — it counts against your daily budget and is recorded in the custody ledger. Off uses the protected route with a dynamic priority fee. Falls back to protected automatically on devnet or when Jito is unreachable.</span>+ </div>+ <div class="sn-field">+ <label>Firewall level</label>+ <select name="firewall_level" aria-label="Rug/honeypot firewall level">+ <option value="block" ${(!s.firewall_level || s.firewall_level === 'block') ? 'selected' : ''}>Block — abort the snipe on a block verdict (recommended)</option>+ <option value="warn" ${s.firewall_level === 'warn' ? 'selected' : ''}>Warn — record the verdict but proceed (raw speed)</option>+ <option value="off" ${s.firewall_level === 'off' ? 'selected' : ''}>Off — skip the safety simulation</option>+ </select>+ <span class="sn-hint">A real on-chain simulated buy→sell round-trip + authority audit before every buy. Block is the safe default.</span>+ </div>+<div class="sn-section-head">Exit Rules</div><div class="sn-field"><label>Take profit (%)</label>@@ -569,6 +597,7 @@ function posRow(p) {<div class="sn-pos-info"><div class="sn-pos-sym">${esc(p.symbol || p.mint?.slice(0, 8) || '—')}</div><div class="sn-pos-sub">${esc(p.agent_name || '')}${p.opened_at ? ` · opened ${relTime(p.opened_at)}` : ''}</div>+ ${execReadout(p)}</div><div class="sn-pos-pnl">${pnlStr}</div><span class="sn-pos-oracle"></span>@@ -903,6 +932,8 @@ async function saveForm(form, root) {per_trade_lamports: solToLamports(fd.per_trade_sol || '0'),max_concurrent_positions: Number(fd.max_concurrent_positions) || 1,slippage_bps: Number(fd.slippage_bps) || 500,+ mev_tip_mode: ['off', 'economy', 'turbo'].includes(fd.mev_tip_mode) ? fd.mev_tip_mode : 'off',+ firewall_level: ['block', 'warn', 'off'].includes(fd.firewall_level) ? fd.firewall_level : 'block',take_profit_pct: fd.take_profit_pct !== '' ? Number(fd.take_profit_pct) : null,stop_loss_pct: Number(fd.stop_loss_pct) || 30,trailing_stop_pct: fd.trailing_stop_pct !== '' ? Number(fd.trailing_stop_pct) : null,@@ -1066,9 +1097,38 @@ function normPos(p) {unrealized_pct: pnlPct,buy_url: p.buy_url || null,opened_at: p.at || p.opened_at || null,+ exec_route: p.exec_route || null,+ tip_lamports: p.tip_lamports != null ? Number(p.tip_lamports) : null,+ priority_fee_microlamports: p.priority_fee_microlamports != null ? Number(p.priority_fee_microlamports) : null,+ landed_ms: p.landed_ms != null ? Number(p.landed_ms) : null,};}+// Render the MEV execution readout for a position/trade: the route badge, the+// Jito tip paid (if any), and the time-to-land. Returns '' when no telemetry+// exists (a pre-engine position or a paper fill with no broadcast).+const EXEC_ROUTE = {+ jito_turbo: { label: 'Jito turbo', cls: 'sn-exec-turbo', title: 'Landed via a Jito bundle with an aggressive tip' },+ jito_economy: { label: 'Jito', cls: 'sn-exec-jito', title: 'Landed via a Jito bundle with an economy tip' },+ protected: { label: 'Protected', cls: 'sn-exec-prot', title: 'Landed via the protected single-tx route (dynamic fee + retry)' },+ simulated: { label: 'Paper', cls: 'sn-exec-sim', title: 'Simulated fill — no broadcast' },+};++function execReadout(p) {+ const route = p.exec_route;+ if (!route) return '';+ const meta = EXEC_ROUTE[route] || { label: route, cls: 'sn-exec-prot', title: 'Execution route' };+ const parts = [`<span class="sn-exec-badge ${meta.cls}" title="${esc(meta.title)}">${esc(meta.label)}</span>`];+ if (p.tip_lamports != null && p.tip_lamports > 0) {+ parts.push(`<span class="sn-exec-meta" title="Jito tip paid">tip ◎${(p.tip_lamports / 1e9).toFixed(5)}</span>`);+ }+ if (p.landed_ms != null && p.landed_ms >= 0) {+ const s = p.landed_ms >= 1000 ? `${(p.landed_ms / 1000).toFixed(1)}s` : `${p.landed_ms}ms`;+ parts.push(`<span class="sn-exec-meta" title="Time to land">${s}</span>`);+ }+ return `<div class="sn-exec">${parts.join('')}</div>`;+}+function renderOwnedPositions() {const owned = ownedAgentIds();const list = [..._positionsMap.values()]diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.jsindex 564b5f66f..e0722ca1b 100644--- a/workers/agent-sniper/executor.js+++ b/workers/agent-sniper/executor.js@@ -8,12 +8,13 @@import { sql } from '../../api/_lib/db.js';import { log } from './log.js';import { loadAgentKeypair } from './keys.js';-import { getTradeCtx, signAndSend } from './trade-client.js';+import { getTradeCtx, signAndSend, submitProtectedTrade } from './trade-client.js';import { countOpenPositions, getDailySpend } from './strategy-store.js';import { notifyBuy, notifySell } from '../../api/_lib/sniper/notify.js';import {getSpendLimits, enforceSpendLimit, SpendLimitError, recordSpend, lamportsToUsd,checkConcurrency, checkDailyBudgetLamports, checkSolHeadroom, checkPriceImpact,+ recordCustodyEvent,SOL_FEE_HEADROOM_LAMPORTS,} from '../../api/_lib/agent-trade-guards.js';import { buildAmmSellInstructions } from './amm-exit.js';@@ -92,6 +93,65 @@ async function recordSnipeSpend({ agentId, userId, network, lamports, signature,}}+// Build the spend-guard hook the execution engine calls BEFORE appending a Jito+// tip. A tip is real SOL leaving the agent wallet, so it must obey the SAME+// ceilings as the trade itself: the kill switch (frozen wallet), the rolling+// daily SOL budget (tip + already-committed spend must fit the strategy's+// daily_budget_lamports), and the cross-path USD ceiling. On a breach the hook+// THROWS with code 'spend_guard' — the engine vetoes the tip and falls back to+// the protected route, so a tip can never bypass a limit. On allow it records the+// real tip outflow into agent_custody_events (category 'mev_tip') so it counts+// toward the daily ceiling and shows in the owner's audit trail.+function makeTipGuard({ strat, network, alreadyCommittedLamports, dailySpentLamports }) {+ return async function onTip(tipLamports, route) {+ const tip = BigInt(tipLamports);+ if (tip <= 0n) return;++ // Kill switch / wallet freeze — the same gate every autonomous spend honors.+ if (strat.kill_switch === true) {+ throw Object.assign(new Error('strategy kill switch is on'), { code: 'spend_guard' });+ }+ let limits;+ try {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${strat.agent_id} AND deleted_at IS NULL`;+ limits = getSpendLimits(row?.meta);+ } catch {+ limits = null;+ }+ if (limits?.frozen) {+ throw Object.assign(new Error('agent wallet is frozen'), { code: 'spend_guard' });+ }++ // Daily SOL budget — the tip stacks on the buy already committed this attempt+ // plus the day's prior spend. Keep the wallet inside the strategy budget.+ const budget = BigInt(strat.daily_budget_lamports);+ if (dailySpentLamports + alreadyCommittedLamports + tip > budget) {+ throw Object.assign(new Error('tip would exceed daily budget'), { code: 'spend_guard' });+ }++ // Cross-path USD ceiling (best-effort price; a pricing outage records lamports+ // without a USD value rather than blocking — the lamports budget above holds).+ let usd = null;+ try {+ usd = await lamportsToUsd(tip);+ await enforceSpendLimit({ agentId: strat.agent_id, limits, category: 'snipe', usdValue: usd, network });+ } catch (err) {+ if (err instanceof SpendLimitError) {+ throw Object.assign(new Error(err.message), { code: 'spend_guard' });+ }+ // pricing/RPC hiccup — fall through and record lamports only.+ }++ // Record the real tip outflow into the shared custody ledger.+ await recordCustodyEvent({+ agentId: strat.agent_id, userId: strat.user_id, eventType: 'spend',+ category: 'mev_tip', network, asset: 'SOL', amountLamports: tip, usd,+ status: 'confirmed', reason: 'jito_tip',+ meta: { mint: strat._tip_mint || null, route, mode: strat.mev_tip_mode || 'off' },+ }).catch((err) => log.warn?.('mev_tip_record_failed', { agent: strat.agent_id, message: err?.message }));+ };+}+/*** Attempt to snipe `mint` for `strat`. All checks short-circuit before any tx.* @returns {Promise<{ status: string, reason?: string, sig?: string }>}@@ -212,8 +272,29 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {if (baseAmount <= 0n) return await fail(posId, tag, 'zero_tokens');let sig = 'SIMULATED';+ // Execution telemetry — only set on a live broadcast; simulate keeps nulls+ // (except a 'simulated' route marker so the UI can label paper fills).+ let exec = { route: 'simulated', tipLamports: 0, priorityFeeMicroLamports: null, landedMs: null };if (cfg.mode === 'live') {- sig = await signAndSend(ctx, keypair, built.instructions, cfg.confirmTimeoutMs);+ const tipMode = ['economy', 'turbo'].includes(strat.mev_tip_mode) ? strat.mev_tip_mode : 'off';+ // The tip guard needs to know what's already committed today + this trade.+ strat._tip_mint = mint.mint;+ const onTip = makeTipGuard({+ strat, network: cfg.network,+ alreadyCommittedLamports: perTrade,+ dailySpentLamports: spent,+ });+ const result = await submitProtectedTrade(ctx, keypair, built.instructions, cfg.confirmTimeoutMs, {+ tipMode, onTip, preSimulated: firewallLevel !== 'off',+ });+ sig = result.signature;+ exec = {+ route: result.route,+ tipLamports: result.tipLamports,+ priorityFeeMicroLamports: result.priorityFeeMicroLamports,+ landedMs: result.landedMs,+ };+ log.trade('exec', { ...tag, route: result.route, tip: result.tipLamports, fee: result.priorityFeeMicroLamports, landed_ms: result.landedMs, attempts: result.attempts, fallback: result.fallbackReason || null });}const pricePerToken = Number(perTrade) / Number(baseAmount);@@ -226,6 +307,10 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {entry_price_impact_pct = ${Number(quote.priceImpactPct)},peak_value_lamports = ${perTrade.toString()},last_value_lamports = ${perTrade.toString()},+ exec_route = ${exec.route},+ tip_lamports = ${exec.tipLamports != null ? String(exec.tipLamports) : null},+ priority_fee_microlamports = ${exec.priorityFeeMicroLamports != null ? String(exec.priorityFeeMicroLamports) : null},+ landed_ms = ${exec.landedMs},last_quoted_at = now()WHERE id = ${posId}`;diff --git a/workers/agent-sniper/trade-client.js b/workers/agent-sniper/trade-client.jsindex 3cdc7d148..264916211 100644--- a/workers/agent-sniper/trade-client.js+++ b/workers/agent-sniper/trade-client.js@@ -2,10 +2,13 @@//// Thin wrapper over the platform's PumpTradeClient (api/_lib/pump.js, which// resolves the right RPC and the @three-ws/agent-payments build) plus a single-// place that assembles, signs with the AGENT's keypair, and broadcasts a v0 tx.-// Mirrors the sign+send flow used by handleRunBuyback in api/cron/[name].js.+// place that assembles, signs with the AGENT's keypair, and broadcasts — now+// through the MEV-aware execution engine (api/_lib/execution-engine.js): dynamic+// compute budget, optional Jito bundle with an adaptive tip, simulate-then-send+// with bounded adaptive retry, and honest landing telemetry.import { getPumpTradeClient } from '../../api/_lib/pump.js';+import { submitProtected } from '../../api/_lib/execution-engine.js';let _ctx = null;@@ -18,43 +21,43 @@ export async function getTradeCtx(network) {}/**- * Assemble a v0 transaction from instructions, sign with `payer`, broadcast,- * and wait for confirmation. Returns the signature.+ * Assemble, sign, and broadcast a trade through the MEV-aware execution engine,+ * returning the FULL execution telemetry. Use this when the caller wants to+ * persist route/tip/fee/landed_ms (executeBuy does); `signAndSend` wraps this and+ * returns only the signature for callers that don't (executeSell).** @param {object} ctx result of getTradeCtx* @param {import('@solana/web3.js').Keypair} payer* @param {import('@solana/web3.js').TransactionInstruction[]} instructions* @param {number} confirmTimeoutMs+ * @param {object} [opts] forwarded to submitProtected (tipMode, onTip, preSimulated)+ * @returns {Promise<{ signature, slot, route, tipLamports, priorityFeeMicroLamports, attempts, landedMs, fallbackReason }>}*/-export async function signAndSend(ctx, payer, instructions, confirmTimeoutMs) {- const { connection, web3 } = ctx;- const { TransactionMessage, VersionedTransaction } = web3;-- const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');- const msg = new TransactionMessage({- payerKey: payer.publicKey,- recentBlockhash: blockhash,+export async function submitProtectedTrade(ctx, payer, instructions, confirmTimeoutMs, opts = {}) {+ return submitProtected({+ network: ctx.network,+ connection: ctx.connection,+ payer,instructions,- }).compileToV0Message();- const tx = new VersionedTransaction(msg);- tx.sign([payer]);-- const sig = await connection.sendRawTransaction(tx.serialize(), {- skipPreflight: false,- maxRetries: 3,+ opts: { confirmTimeoutMs, ...opts },});+}- // Bound the confirmation wait so a stuck tx can't pin the loop forever.- const confirmPromise = connection.confirmTransaction(- { signature: sig, blockhash, lastValidBlockHeight },- 'confirmed',- );- const timeout = new Promise((_, rej) =>- setTimeout(() => rej(Object.assign(new Error('confirm timeout'), { code: 'CONFIRM_TIMEOUT', sig })), confirmTimeoutMs),- );- const result = await Promise.race([confirmPromise, timeout]);- if (result?.value?.err) {- throw Object.assign(new Error(`tx failed on-chain: ${JSON.stringify(result.value.err)}`), { code: 'TX_ERR', sig });- }- return sig;+/**+ * Broadcast a trade and wait for confirmation. Returns the signature only — the+ * stable contract every caller (notably executeSell) relies on. Internally this+ * routes through the same protected execution engine as the buy path, so sells+ * also get the dynamic compute budget and adaptive retry; sells just don't pay a+ * Jito tip (tipMode defaults to 'off') and don't persist the telemetry.+ *+ * @param {object} ctx result of getTradeCtx+ * @param {import('@solana/web3.js').Keypair} payer+ * @param {import('@solana/web3.js').TransactionInstruction[]} instructions+ * @param {number} confirmTimeoutMs+ * @param {object} [opts] optional execution opts (tipMode, onTip)+ * @returns {Promise<string>} the transaction signature+ */+export async function signAndSend(ctx, payer, instructions, confirmTimeoutMs, opts = {}) {+ const result = await submitProtectedTrade(ctx, payer, instructions, confirmTimeoutMs, opts);+ return result.signature;}