Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

sniper(executor): wire the risk officer and the SOL-quote requirement into the buy path

nirholasf2edc6df180f
diff --git a/api/sniper/strategy.js b/api/sniper/strategy.js
index d19e5584f..91374c95d 100644
--- a/api/sniper/strategy.js
+++ b/api/sniper/strategy.js
@@ -83,6 +83,11 @@ export const STRATEGY_SCHEMA = z.object({
// 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(),
+ // Adversarial pre-trade Risk Officer. 'shadow' (default) reviews and records
+ // without changing the trade; 'enforce' lets a veto abort the buy and a smaller
+ // suggested size shrink it; 'off' skips the review entirely.
+ risk_officer_level: z.enum(['off', 'shadow', 'enforce']).optional(),
+ risk_officer_model: z.string().max(120).nullable().optional(),
// entry filters (null clears)
min_market_cap_usd: optPct,
max_market_cap_usd: optPct,
@@ -251,6 +256,8 @@ async function listStrategies(req, res, userId) {
max_price_impact_pct: Number(s.max_price_impact_pct),
mev_tip_mode: s.mev_tip_mode || 'off',
firewall_level: s.firewall_level || 'block',
+ risk_officer_level: s.risk_officer_level || 'shadow',
+ risk_officer_model: s.risk_officer_model || null,
min_market_cap_usd: s.min_market_cap_usd != null ? Number(s.min_market_cap_usd) : null,
max_market_cap_usd: s.max_market_cap_usd != null ? Number(s.max_market_cap_usd) : null,
min_creator_graduated: s.min_creator_graduated,
@@ -344,6 +351,7 @@ async function upsertStrategy(req, res, userId) {
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',
+ risk_officer_level: 'shadow', risk_officer_model: null,
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,
@@ -377,6 +385,8 @@ async function upsertStrategy(req, res, userId) {
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'),
+ risk_officer_level: p.risk_officer_level != null ? p.risk_officer_level : (cur.risk_officer_level || 'shadow'),
+ risk_officer_model: 'risk_officer_model' in p ? (p.risk_officer_model || null) : (cur.risk_officer_model || null),
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,
@@ -453,6 +463,7 @@ async function upsertStrategy(req, res, userId) {
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, mev_tip_mode, firewall_level,
+ risk_officer_level, risk_officer_model,
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,
@@ -469,6 +480,7 @@ async function upsertStrategy(req, res, userId) {
${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.mev_tip_mode}, ${next.firewall_level},
+ ${next.risk_officer_level}, ${next.risk_officer_model},
${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},
@@ -495,6 +507,8 @@ async function upsertStrategy(req, res, userId) {
max_price_impact_pct = excluded.max_price_impact_pct,
mev_tip_mode = excluded.mev_tip_mode,
firewall_level = excluded.firewall_level,
+ risk_officer_level = excluded.risk_officer_level,
+ risk_officer_model = excluded.risk_officer_model,
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,
@@ -554,6 +568,8 @@ async function upsertStrategy(req, res, userId) {
max_price_impact_pct: Number(row.max_price_impact_pct),
mev_tip_mode: row.mev_tip_mode || 'off',
firewall_level: row.firewall_level || 'block',
+ risk_officer_level: row.risk_officer_level || 'shadow',
+ risk_officer_model: row.risk_officer_model || null,
min_market_cap_usd: row.min_market_cap_usd != null ? Number(row.min_market_cap_usd) : null,
max_market_cap_usd: row.max_market_cap_usd != null ? Number(row.max_market_cap_usd) : null,
min_creator_graduated: row.min_creator_graduated,
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index 9d19dabe9..b053fd43d 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -111,6 +111,16 @@ export function loadConfig() {
// Global emergency stop — set SNIPER_GLOBAL_KILL=1 to halt all new buys
// while still letting the position loop manage/exit open positions.
globalKill: bool('SNIPER_GLOBAL_KILL', false),
+ // ── adversarial Risk Officer ─────────────────────────────────────────────
+ // Fleet-wide DEFAULT enforcement level for the independent pre-trade review
+ // (workers/agent-sniper/risk-officer.js); a strategy's own
+ // `risk_officer_level` column overrides it. 'shadow' (the default) records
+ // the veto it would have cast and changes nothing; 'enforce' lets a veto
+ // abort the buy and a smaller suggested size shrink it; 'off' skips it.
+ // Deliberately NOT 'enforce' out of the box: enforcement changes what the
+ // live fleet buys with real SOL, so arming it is an owner decision made
+ // against the evidence in sniper_risk_reviews.
+ riskOfficer: (process.env.SNIPER_RISK_OFFICER || 'shadow').trim().toLowerCase(),
// Position re-quote / exit-evaluation cadence.
pollMs: Math.max(1_000, num('SNIPER_POLL_MS', 5_000)),
// Liquidity-decay exit: an underwater position whose quoted value has not
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index 0b07129a7..3b68cee6b 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -9,6 +9,7 @@ import { sql } from '../../api/_lib/db.js';
import { log } from './log.js';
import { loadAgentKeypair } from './keys.js';
import { mayhemGate } from './mayhem-gate.js';
+import { reviewBuy, resolveRiskOfficerLevel } from './risk-officer.js';
import { marketCapBandReason } from './scorer.js';
import { recordJournal, journalEntry } from './journal.js';
import { getTradeCtx, signAndSend, submitProtectedTrade } from './trade-client.js';
@@ -42,7 +43,7 @@ function snipeConfidence({ priceImpactPct, maxImpactPct, firewallVerdict }) {
// ledger. Best-effort: the on-chain buy has already settled, so a ledger-write
// failure must never throw the trade away. Reconciled later against the closed
// position's realized P&L by api/cron/reconcile-decisions.js.
-async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, priceImpactPct, firewall, perTradeLamports }) {
+async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, priceImpactPct, firewall, perTradeLamports, riskOfficer }) {
try {
const perTradeSol = Number(BigInt(perTradeLamports)) / 1e9;
const confidence = snipeConfidence({
@@ -74,6 +75,10 @@ async function recordSnipeDecision({ strat, network, mint, posId, sig, mode, pri
mode,
symbol: mint.symbol || null,
llm: mint.llm ? { model: mint.llm.model, confidence: mint.llm.confidence, thesis: mint.llm.thesis } : null,
+ // The adversarial second opinion, when one was ENFORCED on this trade.
+ // A shadow-mode review is a counterfactual, not part of the decision,
+ // so it lives in sniper_risk_reviews and never in the ledger's inputs.
+ risk_officer: riskOfficer || null,
},
prediction: { direction: 'up', basis: 'snipe entry expects a profitable exit', metric: 'realized_pnl' },
rationale,
@@ -374,19 +379,25 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
// require_sol_quote check below only guards the curve branch.
const ammEntry = mint.venue === 'amm';
- // 6. quote + price-impact circuit breaker
- let quote;
- if (ammEntry) {
- const ammQuote = await quoteAmmBuy({
- network: cfg.network, mint: mint.mint, quoteAmount: bn(ctx, perTrade), slippagePct,
- });
- quote = { priceImpactPct: ammQuote.priceImpactPct };
- } else {
- quote = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: bn(ctx, perTrade), slippagePct });
- if (strat.require_sol_quote && !quote.quoteMint.equals(ctx.web3.PublicKey.default) && quote.quoteMint.toBase58() !== 'So11111111111111111111111111111111111111112') {
- return await fail(posId, tag, 'quote_not_sol');
+ // 6. quote + price-impact circuit breaker. Priced through a helper so the
+ // trade can be re-quoted at a smaller size if the risk officer (6c)
+ // cuts it — the impact we RECORD must describe the trade we actually
+ // send, not the larger one that was refused.
+ const quoteFor = async (size) => {
+ if (ammEntry) {
+ const ammQuote = await quoteAmmBuy({
+ network: cfg.network, mint: mint.mint, quoteAmount: bn(ctx, size), slippagePct,
+ });
+ return { priceImpactPct: ammQuote.priceImpactPct };
}
- }
+ const curveQuote = await ctx.client.quoteForBuy({ mint: mintPk, quoteAmount: bn(ctx, size), slippagePct });
+ if (strat.require_sol_quote && !curveQuote.quoteMint.equals(ctx.web3.PublicKey.default) && curveQuote.quoteMint.toBase58() !== 'So11111111111111111111111111111111111111112') {
+ return { rejected: 'quote_not_sol' };
+ }
+ return curveQuote;
+ };
+ let quote = await quoteFor(perTrade);
+ if (quote.rejected) return await fail(posId, tag, quote.rejected);
const impact = checkPriceImpact(Number(quote.priceImpactPct), Number(strat.max_price_impact_pct));
if (impact) return await fail(posId, tag, impact.reason);
@@ -461,6 +472,56 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
}
}
+ // 6c. adversarial Risk Officer — the independent second opinion. Every
+ // gate above answers a question with a number; this one is handed the
+ // proposed trade plus the agent's own thesis and told to find what the
+ // agent missed. Runs LAST so it sees the real price impact and the real
+ // firewall verdict. Default level is 'shadow': it records the veto it
+ // WOULD have cast and changes nothing, because enforcement decides what
+ // the live fleet buys with real SOL and arming that is an owner call.
+ // Fails OPEN, unlike the firewall: it sits behind a safety proof that
+ // already passed, so a reviewer outage must never halt the fleet.
+ const officer = await reviewBuy({
+ cfg, strat, mint, posId,
+ perTradeLamports: perTrade,
+ minTradeLamports: cfg.minTradeLamports,
+ budgetLeftLamports: dailyBudget > BigInt(spent) ? dailyBudget - BigInt(spent) : 0n,
+ slotsLeft: Math.max(0, Number(strat.max_concurrent_positions) - open),
+ priceImpactPct: Number(quote.priceImpactPct),
+ firewall: firewallSnapshot,
+ agentReason: mint.llm?.thesis || null,
+ });
+ if (officer.blocked) {
+ await sql`
+ UPDATE agent_sniper_positions
+ SET status = 'failed', error = ${`risk_officer_veto: ${officer.reason}`.slice(0, 280)}, closed_at = now()
+ WHERE id = ${posId}
+ `;
+ log.warn('buy vetoed by the risk officer', { ...tag, reasons: officer.review?.reasons });
+ screenPush(`$${(mint.symbol || mint.mint.slice(0, 6)).toUpperCase()} vetoed by risk review: ${officer.reason}`, 'analysis');
+ return { status: 'failed', reason: 'risk_officer_veto' };
+ }
+ if (officer.resized) {
+ log.info('trade size cut by the risk officer', {
+ ...tag, from: perTrade.toString(), to: officer.sizeLamports.toString(),
+ reasons: officer.review?.reasons,
+ });
+ perTrade = officer.sizeLamports;
+ // A smaller buy can only move the curve less, so the breaker above
+ // cannot newly trip; re-quote purely so the recorded entry impact is
+ // the one this trade actually pays.
+ const reQuote = await quoteFor(perTrade).catch(() => null);
+ if (reQuote && !reQuote.rejected) quote = reQuote;
+ }
+ const officerSnapshot = officer.review
+ ? {
+ level: resolveRiskOfficerLevel(strat, cfg.riskOfficer),
+ severity: officer.review.severity,
+ reasons: officer.review.reasons,
+ resized: officer.resized,
+ }
+ : null;
+
// 7. build + (live) broadcast
let built;
if (ammEntry) {
@@ -538,6 +599,7 @@ export async function executeBuy({ cfg, strat, mint, throttle }) {
await recordSnipeDecision({
strat, network: cfg.network, mint, posId, sig, mode: cfg.mode,
priceImpactPct: Number(quote.priceImpactPct), firewall: firewallSnapshot, perTradeLamports: perTrade,
+ riskOfficer: officerSnapshot,
});
return { status: 'open', sig };
} catch (err) {