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(predictions): prediction markets for agents with a Solana venue, order book and price history
nirholas3b8b8b454e4c
diff --git a/api/_lib/migrations/20260922160000_prediction_markets.sql b/api/_lib/migrations/20260922160000_prediction_markets.sqlnew file mode 100644index 000000000..cb94a34d7--- /dev/null+++ b/api/_lib/migrations/20260922160000_prediction_markets.sql@@ -0,0 +1,51 @@+-- Prediction markets from the agent wallet (api/_lib/predictions/).+--+-- 1. prediction_previews: every fund-moving prediction action (open, close,+-- redeem) is priced first by a preview, and the execution call must present+-- that preview's id. A preview is bound to one agent and one action, lives+-- ten minutes, and is consumed by the execution it authorizes, so a stale or+-- replayed preview can never move money.+--+-- kind open | close | redeem+-- params what the owner asked for (market, side, stake, limit price)+-- quote what the preview showed (fill estimate, fees, guards)+-- consumed_at set atomically by the execution that uses the preview+--+-- 2. market_price alert rules: pump_alert_rules gains a `market_price` kind that+-- watches one outcome of one prediction market and fires when its implied+-- probability crosses `threshold` (0 to 1) in `direction`. The same monitor+-- cron that evaluates the pump rules evaluates these, and they deliver over+-- the same in-app, webhook and Telegram channels. `target_agent_scope`+-- records the agent whose predictions page set the watch, so that page can+-- list its own watches; it is separate from `target_agent`, which already+-- means "the agent whose launches a new_mint rule follows".++create table if not exists prediction_previews (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid references users(id) on delete cascade,+ venue text not null,+ kind text not null check (kind in ('open', 'close', 'redeem')),+ params jsonb not null default '{}'::jsonb,+ quote jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now(),+ expires_at timestamptz not null,+ consumed_at timestamptz+);++create index if not exists prediction_previews_agent_created+ on prediction_previews (agent_id, created_at desc);++alter table pump_alert_rules+ add column if not exists target_market text,+ add column if not exists target_side text check (target_side in ('yes', 'no')),+ add column if not exists direction text check (direction in ('above', 'below')),+ add column if not exists target_agent_scope uuid references agent_identities(id) on delete set null;++alter table pump_alert_rules drop constraint if exists pump_alert_rules_kind_check;+alter table pump_alert_rules+ add constraint pump_alert_rules_kind_check+ check (kind in ('graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint', 'market_price'));++create index if not exists pump_alert_rules_market+ on pump_alert_rules (target_market) where kind = 'market_price';diff --git a/api/_lib/predictions/book.js b/api/_lib/predictions/book.jsnew file mode 100644index 000000000..c0aad1849--- /dev/null+++ b/api/_lib/predictions/book.js@@ -0,0 +1,149 @@+// @ts-check+// Pure order-book math for binary event contracts. No I/O: every function is+// deterministic in its inputs so fills, slippage and depth are unit-tested+// against books recorded from the live venue (tests/predictions-book.test.js).+//+// A book is { yes_bids, no_bids }, each a list of [price, contracts] with price+// a probability in (0, 1), best (highest) first. A contract pays $1 if its side+// wins, so buying YES at p is the same trade as selling NO at 1 - p: the asks+// for one side are the other side's bids, mirrored.++/** @typedef {[number, number]} Level */+/** @typedef {{ yes_bids: Level[], no_bids: Level[] }} Book */+/** @typedef {'yes'|'no'} Side */++const EPS = 1e-9;+const round = (n, dp = 6) => Math.round(n * 10 ** dp) / 10 ** dp;++/** Asks for `side`, cheapest first. */+export function asksFor(/** @type {Book} */ book, /** @type {Side} */ side) {+ const opposite = side === 'yes' ? book.no_bids : book.yes_bids;+ return (opposite || [])+ .map(([p, q]) => /** @type {Level} */ ([round(1 - p, 4), q]))+ .sort((a, b) => a[0] - b[0]);+}++/** Bids for `side`, richest first. */+export function bidsFor(/** @type {Book} */ book, /** @type {Side} */ side) {+ return [...((side === 'yes' ? book.yes_bids : book.no_bids) || [])].sort((a, b) => b[0] - a[0]);+}++/**+ * Walk the asks with a USD budget, never paying above `maxPrice`.+ * @param {Level[]} asks cheapest first+ * @param {number} stakeUsd+ * @param {number} maxPrice+ */+export function estimateBuy(asks, stakeUsd, maxPrice) {+ let remaining = stakeUsd;+ let contracts = 0;+ let spent = 0;+ let worst = null;+ for (const [price, qty] of asks) {+ if (remaining <= EPS) break;+ if (price > maxPrice + EPS) break;+ const levelCost = price * qty;+ if (levelCost >= remaining - EPS) {+ contracts += remaining / price;+ spent += remaining;+ remaining = 0;+ worst = price;+ break;+ }+ contracts += qty;+ spent += levelCost;+ remaining -= levelCost;+ worst = price;+ }+ const best = asks.length ? asks[0][0] : null;+ const avg = contracts > 0 ? spent / contracts : null;+ return {+ contracts: round(contracts, 4),+ spent_usd: round(spent, 4),+ unfilled_usd: round(Math.max(0, remaining), 4),+ filled_fully: remaining <= 1e-6,+ best_price: best,+ avg_price: avg != null ? round(avg, 4) : null,+ worst_price: worst,+ slippage_bps: avg != null && best ? Math.max(0, Math.round(((avg - best) / best) * 10_000)) : null,+ payout_usd: round(contracts, 4),+ max_profit_usd: round(contracts - spent, 4),+ };+}++/**+ * Walk the bids selling `contracts`, never accepting below `minPrice`.+ * @param {Level[]} bids richest first+ * @param {number} contracts+ * @param {number} minPrice+ */+export function estimateSell(bids, contracts, minPrice) {+ let remaining = contracts;+ let proceeds = 0;+ let sold = 0;+ let worst = null;+ for (const [price, qty] of bids) {+ if (remaining <= EPS) break;+ if (price < minPrice - EPS) break;+ const take = Math.min(qty, remaining);+ proceeds += take * price;+ sold += take;+ remaining -= take;+ worst = price;+ }+ const best = bids.length ? bids[0][0] : null;+ const avg = sold > 0 ? proceeds / sold : null;+ return {+ contracts_sold: round(sold, 4),+ unfilled_contracts: round(Math.max(0, remaining), 4),+ filled_fully: remaining <= 1e-6,+ proceeds_usd: round(proceeds, 4),+ best_price: best,+ avg_price: avg != null ? round(avg, 4) : null,+ worst_price: worst,+ slippage_bps: avg != null && best ? Math.max(0, Math.round(((best - avg) / best) * 10_000)) : null,+ };+}++/**+ * USD resting within `band` (probability points) of the best level. For bids+ * that is dollars a seller can hit; for asks, dollars a buyer can lift.+ * @param {Level[]} levels best first+ * @param {number} [band]+ */+export function depthUsd(levels, band = 0.05) {+ if (!levels.length) return 0;+ const best = levels[0][0];+ let total = 0;+ for (const [p, q] of levels) {+ if (Math.abs(p - best) > band + EPS) break;+ total += p * q;+ }+ return round(total, 2);+}++/** A compact summary of both sides for display: best prices, spread, depth. */+export function summarizeBook(/** @type {Book} */ book) {+ const out = {};+ for (const side of /** @type {Side[]} */ (['yes', 'no'])) {+ const asks = asksFor(book, side);+ const bids = bidsFor(book, side);+ out[side] = {+ best_ask: asks[0]?.[0] ?? null,+ best_bid: bids[0]?.[0] ?? null,+ ask_depth_usd: depthUsd(asks),+ bid_depth_usd: depthUsd(bids),+ levels: {+ asks: asks.slice(0, 8),+ bids: bids.slice(0, 8),+ },+ };+ }+ const yesAsk = out.yes.best_ask;+ const yesBid = out.yes.best_bid;+ return {+ ...out,+ spread: yesAsk != null && yesBid != null ? round(Math.max(0, yesAsk - yesBid), 4) : null,+ liquidity_usd: round(out.yes.ask_depth_usd + out.yes.bid_depth_usd, 2),+ };+}diff --git a/api/_lib/predictions/engine.js b/api/_lib/predictions/engine.jsnew file mode 100644index 000000000..2e9c9dc68--- /dev/null+++ b/api/_lib/predictions/engine.js@@ -0,0 +1,557 @@+// Prediction orders from the agent's custodial Solana wallet.+//+// One engine behind the REST routes (api/v1/agents/[id]/predictions/) and the+// MCP tools (api/_mcpagent/predictions-tools.js), so both are held to the same+// guards, ledger and confirmation rules:+//+// preview price the action against the live venue, run every guard, store+// the result, return a preview_id (ten-minute life)+// execute requires confirm_trade === true and a fresh preview_id for the+// same agent and action; re-runs the guards; builds the venue+// transaction; SIMULATES it and refuses unless the wallet's USDC and+// SOL move no more than the preview allowed; signs with the agent key;+// submits; records the outcome in agent_custody_events+//+// The simulation bound is what makes signing a venue-built transaction safe:+// whatever the instructions are, the agent wallet cannot lose more USDC than+// the stake the owner confirmed, nor more SOL than network fees.++import { PublicKey, VersionedTransaction } from '@solana/web3.js';+import { getAssociatedTokenAddressSync } from '@solana/spl-token';+import { sql } from '../db.js';+import { logAudit } from '../audit.js';+import { ensureAgentWallet, recoverSolanaAgentKeypair, getSolanaAddressBalances } from '../agent-wallet.js';+import { solanaConnection } from '../agent-pumpfun.js';+import {+ getPredictionLimits, checkPredictionStake, getPredictionStakeUsd, tradeGuardResponse,+ reserveSpendUsd, releaseSpendReservation, updateCustodyEvent, recordCustodyEvent,+ SpendLimitError, getSpendLimits,+} from '../agent-trade-guards.js';+import { getVenue, DEFAULT_VENUE, VenueError } from './index.js';+import { asksFor, bidsFor, estimateBuy, estimateSell } from './book.js';+import { createPreview, loadPreview, consumePreview, releasePreview, PreviewError } from './previews.js';++export const MIN_STAKE_USD = 1;+export const MAX_STAKE_USD = 100_000;+// SOL the wallet may spend on a prediction transaction: base fee, priority fee+// and at most one token-account rent. Anything past this is refused.+const MAX_LAMPORTS_OUT = 5_000_000;+const MIN_SOL_FOR_FEES = 0.002;+const USDC_DECIMALS = 6;+// A buy can cost at most its stake; the venue's own fee rides inside it. Allow+// one cent of rounding and nothing else.+const USDC_ROUNDING_ATOMIC = 10_000n;++export class PredictionError extends Error {+ constructor(code, message, status = 400, detail = null) {+ super(message);+ this.name = 'PredictionError';+ this.code = code;+ this.status = status;+ this.detail = detail;+ }+}++/** Map any engine failure to { status, code, message, detail } for a boundary. */+export function describeError(err) {+ if (err instanceof PredictionError || err instanceof PreviewError || err instanceof VenueError) {+ return { status: err.status, code: err.code, message: err.message, detail: err.detail || null };+ }+ if (err instanceof SpendLimitError) {+ return { status: err.status || 403, code: err.code, message: err.message, detail: err.detail || null };+ }+ return null;+}++// ── Agent + wallet ───────────────────────────────────────────────────────────++/** Load an agent the user owns. Throws PredictionError 404/403. */+export async function loadOwnedAgent(agentId, userId) {+ const [row] = await sql`+ SELECT id, user_id, name, meta FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!row) throw new PredictionError('not_found', 'No agent with that id.', 404);+ if (row.user_id !== userId) throw new PredictionError('forbidden', "That agent isn't on your account.", 403);+ return row;+}++async function walletFor(agent, userId, reason) {+ const { address } = await ensureAgentWallet(agent.id, userId, { reason });+ return address;+}++function usdcAtaFor(owner, venue) {+ return getAssociatedTokenAddressSync(new PublicKey(venue.settlement.mint), new PublicKey(owner), true);+}++// ── Validation ───────────────────────────────────────────────────────────────++function parseSide(v) {+ const s = String(v || '').toLowerCase();+ if (s !== 'yes' && s !== 'no') throw new PredictionError('invalid_side', 'side must be "yes" or "no".');+ return s;+}++function parseStake(v) {+ const n = Number(v);+ if (!Number.isFinite(n) || n < MIN_STAKE_USD || n > MAX_STAKE_USD) {+ throw new PredictionError('invalid_stake', `stake_usd must be between $${MIN_STAKE_USD} and $${MAX_STAKE_USD.toLocaleString('en-US')}.`);+ }+ return Math.round(n * 100) / 100;+}++function parsePrice(v, name) {+ const n = Number(v);+ if (!Number.isFinite(n) || n <= 0 || n >= 1) throw new PredictionError(`invalid_${name}`, `${name} must be a probability strictly between 0 and 1 (0.62 means 62 cents a contract).`);+ return Math.round(n * 100) / 100;+}++function sideOutcome(market, side) {+ return market.outcomes.find((o) => o.side === side) || null;+}++// ── Guards ───────────────────────────────────────────────────────────────────++async function marketExposureUsd(venue, owner, agentId, marketId) {+ let positions;+ try {+ positions = await venue.listPositions(owner);+ } catch {+ // Venue positions unreadable: fall back to every stake this platform+ // placed in the market over the last 30 days, which can only overcount.+ return getPredictionStakeUsd(agentId, { marketId, windowHours: 24 * 30 });+ }+ const filled = positions+ .filter((p) => p.market_id === marketId && p.status === 'open')+ .reduce((sum, p) => sum + (p.cost_usd || 0), 0);+ // A stake submitted in the last 30 minutes may not have filled into a+ // position yet; count it so two quick orders cannot pass the cap together.+ // A fast fill is briefly counted twice, which errs toward refusing.+ const inflight = await getPredictionStakeUsd(agentId, { marketId, windowHours: 0.5 });+ return filled + inflight;+}++/** Run the stake guards. Returns { ok, checks[] } or throws PredictionError with the guard message. */+async function stakeGuards({ agent, venue, owner, marketId, stakeUsd, throwOnBlock }) {+ const limits = getPredictionLimits(agent.meta);+ const spend = getSpendLimits(agent.meta);+ const [exposure, daily] = await Promise.all([+ marketExposureUsd(venue, owner, agent.id, marketId),+ getPredictionStakeUsd(agent.id, { windowHours: 24 }),+ ]);+ const blocked = checkPredictionStake({ limits, stakeUsd, marketExposureUsd: exposure, dailyStakedUsd: daily });+ const checks = [+ { id: 'enabled', ok: limits.enabled, label: limits.enabled ? 'Prediction orders are on for this agent' : 'Prediction orders are off for this agent' },+ { id: 'market_cap', ok: exposure + stakeUsd <= limits.max_stake_per_market_usd + 1e-9, label: `At risk in this market after the order: $${(exposure + stakeUsd).toFixed(2)} of $${limits.max_stake_per_market_usd.toFixed(2)}` },+ { id: 'daily_cap', ok: daily + stakeUsd <= limits.max_daily_stake_usd + 1e-9, label: `Staked in the last 24h after the order: $${(daily + stakeUsd).toFixed(2)} of $${limits.max_daily_stake_usd.toFixed(2)}` },+ { id: 'wallet_frozen', ok: !spend.frozen, label: spend.frozen ? 'The wallet is frozen' : 'The wallet is not frozen' },+ ];+ if (spend.per_tx_usd != null) {+ checks.push({ id: 'per_tx', ok: stakeUsd <= spend.per_tx_usd + 1e-9, label: `Wallet per-transaction limit: $${spend.per_tx_usd.toFixed(2)}` });+ }+ if (blocked && throwOnBlock) {+ const r = tradeGuardResponse(blocked);+ throw new PredictionError(r.code, r.message, r.status, r.detail);+ }+ return { limits, exposure_usd: exposure, staked_today_usd: daily, blocked: blocked ? tradeGuardResponse(blocked) : null, checks };+}++// ── Simulation bound ─────────────────────────────────────────────────────────++function decodeTokenAmount(account) {+ if (!account) return 0n;+ const data = Array.isArray(account.data) ? Buffer.from(account.data[0], 'base64') : null;+ if (!data || data.length < 72) return 0n;+ return data.readBigUInt64LE(64);+}++/**+ * Simulate the venue transaction against current chain state and verify the+ * owner's USDC and SOL move within bounds. Throws PredictionError otherwise.+ */+export async function simulateWithinBounds({ conn, vtx, owner, usdcAta, maxUsdcOutAtomic }) {+ const ownerKey = owner.toBase58();+ const ataKey = usdcAta.toBase58();+ const [preLamports, preUsdc] = await Promise.all([+ conn.getBalance(owner, 'confirmed'),+ conn.getTokenAccountBalance(usdcAta, 'confirmed').then((b) => BigInt(b?.value?.amount || '0')).catch(() => 0n),+ ]);+ let sim;+ try {+ sim = await conn.simulateTransaction(vtx, {+ sigVerify: false,+ replaceRecentBlockhash: true,+ commitment: 'confirmed',+ accounts: { encoding: 'base64', addresses: [ownerKey, ataKey] },+ });+ } catch (err) {+ throw new PredictionError('simulation_unavailable', 'Could not simulate the order before signing, so nothing was sent. Try again.', 503, { message: err?.message?.slice(0, 200) || null });+ }+ const v = sim?.value;+ if (v?.err) {+ throw new PredictionError('simulation_failed', 'The order failed simulation, so it was not sent and no funds moved.', 422, { err: v.err, logs: (v.logs || []).slice(-8) });+ }+ const postLamports = v?.accounts?.[0]?.lamports ?? preLamports;+ const postUsdc = v?.accounts?.[1] ? decodeTokenAmount(v.accounts[1]) : preUsdc;+ const usdcOut = preUsdc - postUsdc;+ const lamportsOut = preLamports - postLamports;+ if (usdcOut > maxUsdcOutAtomic + USDC_ROUNDING_ATOMIC) {+ throw new PredictionError('simulation_out_of_bounds', 'The venue transaction would move more USDC than you confirmed, so it was not signed.', 422, {+ usdc_out: Number(usdcOut) / 10 ** USDC_DECIMALS,+ allowed_usdc_out: Number(maxUsdcOutAtomic) / 10 ** USDC_DECIMALS,+ });+ }+ if (lamportsOut > MAX_LAMPORTS_OUT) {+ throw new PredictionError('simulation_out_of_bounds', 'The venue transaction would spend more SOL than network fees, so it was not signed.', 422, {+ sol_out: lamportsOut / 1e9,+ allowed_sol_out: MAX_LAMPORTS_OUT / 1e9,+ });+ }+ return { usdc_out: Number(usdcOut) / 10 ** USDC_DECIMALS, sol_out: lamportsOut / 1e9, units: v?.unitsConsumed ?? null };+}++async function signAndSubmit({ agent, userId, venue, built, maxUsdcOutAtomic, owner, reason, custodyId }) {+ if (!built?.transaction) {+ throw new PredictionError('no_transaction', 'The venue returned no transaction to sign.', 502);+ }+ const vtx = VersionedTransaction.deserialize(Buffer.from(built.transaction, 'base64'));+ const ownerKey = new PublicKey(owner);+ const signerKeys = vtx.message.staticAccountKeys.slice(0, vtx.message.header.numRequiredSignatures).map((k) => k.toBase58());+ if (!signerKeys.includes(owner)) {+ throw new PredictionError('unexpected_transaction', 'The venue transaction does not name the agent wallet as a signer, so it was not signed.', 502);+ }+ const conn = solanaConnection('mainnet');+ const sim = await simulateWithinBounds({ conn, vtx, owner: ownerKey, usdcAta: usdcAtaFor(owner, venue), maxUsdcOutAtomic });++ const keypair = await recoverSolanaAgentKeypair(agent.meta.encrypted_solana_secret, {+ agentId: agent.id,+ userId,+ reason,+ meta: { venue: venue.id, custody_event_id: custodyId },+ });+ vtx.sign([keypair]);+ const signedTransaction = Buffer.from(vtx.serialize()).toString('base64');+ const { signature } = await venue.submit({ signedTransaction, context: built.context });+ return { signature, simulation: sim };+}++// ── Open ─────────────────────────────────────────────────────────────────────++async function priceOpen({ venue, owner, market, side, stakeUsd, maxPrice }) {+ const book = await venue.getOrderbook(market.id);+ const est = estimateBuy(asksFor(book, side), stakeUsd, maxPrice);+ let venueQuote = null;+ let venueQuoteError = null;+ try {+ const built = await venue.buildOpenOrder({ owner, marketId: market.id, side, usd: stakeUsd, maxPrice, quoteOnly: true });+ venueQuote = built.quote;+ } catch (err) {+ if (!(err instanceof VenueError)) throw err;+ venueQuoteError = { code: err.code, message: err.message };+ }+ return { book, est, venueQuote, venueQuoteError };+}++/** Preview an open. Never moves funds. */+export async function previewOpen({ agentId, userId, venueId = DEFAULT_VENUE, marketId, side: rawSide, stakeUsd: rawStake, maxPrice: rawMax }) {+ const venue = getVenue(venueId);+ const agent = await loadOwnedAgent(agentId, userId);+ const side = parseSide(rawSide);+ const stakeUsd = parseStake(rawStake);+ const market = await venue.getMarket(String(marketId || ''));+ if (!market.tradable) throw new PredictionError('market_closed', `This market is ${market.status || 'not open'}; it takes no new orders.`, 409);+ const outcome = sideOutcome(market, side);+ const ask = outcome?.buy_price ?? null;+ if (ask == null) throw new PredictionError('no_liquidity', 'Nobody is selling this side right now, so there is no price to buy at.', 409);+ // Default limit: two cents over the best ask, capped at 99 cents.+ const maxPrice = rawMax != null ? parsePrice(rawMax, 'max_price') : Math.min(0.99, Math.round((ask + 0.02) * 100) / 100);+ if (maxPrice < ask - 1e-9) {+ throw new PredictionError('max_price_below_market', `Your max price of ${(maxPrice * 100).toFixed(0)}¢ is under the best ask of ${(ask * 100).toFixed(1)}¢, so the order would not fill. Raise max_price or wait for the price to come down.`, 409, { best_ask: ask });+ }+ const owner = await walletFor(agent, userId, 'prediction_preview');+ const [{ est, venueQuote, venueQuoteError }, balances, status, guards] = await Promise.all([+ priceOpen({ venue, owner, market, side, stakeUsd, maxPrice }),+ getSolanaAddressBalances(owner, 'mainnet'),+ venue.tradingStatus().catch(() => ({ trading_active: null })),+ stakeGuards({ agent, venue, owner, marketId: market.id, stakeUsd, throwOnBlock: false }),+ ]);++ const contracts = venueQuote?.contracts || est.contracts;+ const avgPrice = venueQuote?.avg_price || est.avg_price;+ const walletOk = balances.usdc != null && balances.usdc + 1e-9 >= stakeUsd;+ const solOk = balances.sol != null && balances.sol >= MIN_SOL_FOR_FEES;+ const checks = [+ ...guards.checks,+ { id: 'wallet_usdc', ok: walletOk, label: balances.usdc == null ? 'Could not read the wallet USDC balance' : `Wallet holds $${balances.usdc.toFixed(2)} USDC for a $${stakeUsd.toFixed(2)} stake` },+ { id: 'wallet_sol', ok: solOk, label: balances.sol == null ? 'Could not read the wallet SOL balance' : `Wallet holds ${balances.sol.toFixed(4)} SOL for network fees` },+ { id: 'fill', ok: est.filled_fully, label: est.filled_fully ? 'The book holds enough at or under your max price to fill the whole stake' : `Only $${est.spent_usd.toFixed(2)} of the stake fills at or under your max price` },+ { id: 'venue_trading', ok: status.trading_active !== false, label: status.trading_active === false ? 'The venue has paused trading' : 'The venue is taking orders' },+ ];+ if (venueQuoteError) checks.push({ id: 'venue_quote', ok: false, label: venueQuoteError.message, code: venueQuoteError.code });++ const quote = {+ market: { id: market.id, event_id: market.event_id, title: market.title, provider: market.provider, close_time: market.close_time },+ side,+ side_label: outcome.label,+ stake_usd: stakeUsd,+ max_price: maxPrice,+ best_ask: ask,+ expected_contracts: contracts,+ expected_avg_price: avgPrice,+ max_payout_usd: contracts,+ max_profit_usd: contracts != null ? Math.round((contracts - stakeUsd) * 100) / 100 : null,+ slippage_bps: venueQuote?.slippage_bps ?? est.slippage_bps,+ fees_usd: venueQuote?.fees_usd ?? null,+ quote_source: venueQuote ? 'venue' : 'order_book',+ book_fill: est,+ wallet: { address: owner, usdc: balances.usdc, sol: balances.sol },+ limits: { max_stake_per_market_usd: guards.limits.max_stake_per_market_usd, max_daily_stake_usd: guards.limits.max_daily_stake_usd, exposure_usd: guards.exposure_usd, staked_today_usd: guards.staked_today_usd },+ checks,+ blocked_by: checks.filter((c) => !c.ok).map((c) => c.id),+ executable: checks.every((c) => c.ok),+ };+ const { preview_id, expires_at } = await createPreview({+ agentId: agent.id,+ userId,+ venue: venue.id,+ kind: 'open',+ params: { market_id: market.id, side, stake_usd: stakeUsd, max_price: maxPrice },+ quote,+ });+ return { preview_id, expires_at, venue: venue.id, chain: 'solana', ...quote, confirm_with: { confirm_trade: true, preview_id } };+}++function requireConfirm(confirm, kind) {+ if (confirm !== true) {+ throw new PredictionError('confirmation_required', `This ${kind} moves real funds. Show the preview to the owner and pass confirm_trade: true only after a clear yes.`, 400);+ }+}++/** Execute a previewed open. Moves the stake. */+export async function executeOpen({ agentId, userId, previewId, confirm, req = null, source = 'owner' }) {+ requireConfirm(confirm, 'order');+ const preview = await loadPreview(previewId, { agentId, kind: 'open' });+ const venue = getVenue(preview.venue);+ const agent = await loadOwnedAgent(agentId, userId);+ const { market_id: marketId, side, stake_usd: stakeUsd, max_price: maxPrice } = preview.params;+ const owner = await walletFor(agent, userId, 'prediction_open');+ await stakeGuards({ agent, venue, owner, marketId, stakeUsd, throwOnBlock: true });+ await consumePreview(preview.id, 'open');++ let reservation;+ try {+ reservation = await reserveSpendUsd({+ agentId: agent.id,+ userId,+ meta: agent.meta,+ category: 'prediction',+ usdValue: stakeUsd,+ destination: `prediction-venue:${venue.id}`,+ asset: 'USDC',+ rowMeta: { prediction_action: 'open', market_id: marketId, side, max_price: maxPrice, venue: venue.id, preview_id: preview.id, source },+ });+ } catch (err) {+ await releasePreview(preview.id).catch(() => {});+ throw err;+ }+ const custodyId = reservation.reservationId;++ let built;+ try {+ built = await venue.buildOpenOrder({ owner, marketId, side, usd: stakeUsd, maxPrice });+ } catch (err) {+ await releaseSpendReservation(custodyId, 'prediction_build_failed').catch(() => {});+ await releasePreview(preview.id).catch(() => {});+ throw err;+ }++ let landed;+ try {+ landed = await signAndSubmit({+ agent, userId, venue, built, owner, custodyId,+ maxUsdcOutAtomic: BigInt(Math.round(stakeUsd * 10 ** USDC_DECIMALS)),+ reason: 'prediction_open',+ });+ } catch (err) {+ await releaseSpendReservation(custodyId, err?.code || 'prediction_submit_failed').catch(() => {});+ logAudit({ userId, action: 'custody.prediction_open_failed', resourceId: agent.id, meta: { market_id: marketId, side, stake_usd: stakeUsd, code: err?.code || null, source }, req });+ throw err;+ }++ await updateCustodyEvent(custodyId, {+ status: 'confirmed',+ signature: landed.signature,+ meta: { order_id: built.order_id, position_id: built.position_id, quote: built.quote, simulation: landed.simulation },+ }).catch(() => {});+ logAudit({ userId, action: 'custody.prediction_open', resourceId: agent.id, meta: { market_id: marketId, side, stake_usd: stakeUsd, signature: landed.signature, source }, req });++ return {+ ok: true,+ action: 'open',+ signature: landed.signature,+ explorer: `https://solscan.io/tx/${landed.signature}`,+ order_id: built.order_id,+ position_id: built.position_id,+ market_id: marketId,+ side,+ stake_usd: stakeUsd,+ max_price: maxPrice,+ expected_contracts: built.quote?.contracts ?? null,+ note: 'The order is on chain. The venue fills it against the book within moments; the position appears under positions once filled.',+ };+}++// ── Close ────────────────────────────────────────────────────────────────────++async function findPosition(venue, owner, positionId) {+ const positions = await venue.listPositions(owner);+ const pos = positions.find((p) => p.id === positionId);+ if (!pos) throw new PredictionError('position_not_found', 'This agent holds no position with that id.', 404);+ return pos;+}++export async function previewClose({ agentId, userId, positionId, contracts: rawContracts, minPrice: rawMin }) {+ const venue = getVenue(DEFAULT_VENUE);+ const agent = await loadOwnedAgent(agentId, userId);+ const owner = await walletFor(agent, userId, 'prediction_preview');+ const pos = await findPosition(venue, owner, String(positionId || ''));+ if (pos.status !== 'open') throw new PredictionError('position_settled', 'This market has resolved. Redeem the position instead of closing it.', 409);+ const contracts = rawContracts == null ? pos.contracts : Math.min(pos.contracts, Number(rawContracts));+ if (!Number.isFinite(contracts) || contracts <= 0) throw new PredictionError('invalid_contracts', `contracts must be between 0 and ${pos.contracts}.`);+ const book = await venue.getOrderbook(pos.market_id);+ const bids = bidsFor(book, pos.side);+ const bestBid = pos.exit_price ?? bids[0]?.[0] ?? null;+ if (bestBid == null) throw new PredictionError('no_liquidity', 'Nobody is bidding on this side right now, so there is no price to sell at.', 409);+ const minPrice = rawMin != null ? parsePrice(rawMin, 'min_price') : Math.max(0.01, Math.floor((bestBid - 0.02) * 100) / 100);+ const est = estimateSell(bids, contracts, minPrice);+ const quote = {+ position: { id: pos.id, market_id: pos.market_id, market_title: pos.market_title, event_title: pos.event_title, side: pos.side, side_label: pos.side_label, contracts_held: pos.contracts, cost_usd: pos.cost_usd },+ contracts,+ min_price: minPrice,+ best_bid: bestBid,+ expected_proceeds_usd: est.proceeds_usd,+ expected_avg_price: est.avg_price,+ expected_realized_pnl_usd: pos.cost_usd != null && pos.contracts > 0 ? Math.round((est.proceeds_usd - (pos.cost_usd * contracts) / pos.contracts) * 100) / 100 : null,+ slippage_bps: est.slippage_bps,+ book_fill: est,+ checks: [+ { id: 'fill', ok: est.filled_fully, label: est.filled_fully ? 'The book holds enough bids at or above your min price' : `Only ${est.contracts_sold} of ${contracts} contracts sell at or above your min price` },+ ],+ };+ quote.executable = quote.checks.every((c) => c.ok);+ quote.blocked_by = quote.checks.filter((c) => !c.ok).map((c) => c.id);+ const { preview_id, expires_at } = await createPreview({ agentId: agent.id, userId, venue: venue.id, kind: 'close', params: { position_id: pos.id, market_id: pos.market_id, side: pos.side, contracts, min_price: minPrice }, quote });+ return { preview_id, expires_at, venue: venue.id, chain: 'solana', ...quote, confirm_with: { confirm_trade: true, preview_id } };+}++export async function executeClose({ agentId, userId, previewId, confirm, req = null, source = 'owner' }) {+ requireConfirm(confirm, 'close');+ const preview = await loadPreview(previewId, { agentId, kind: 'close' });+ const venue = getVenue(preview.venue);+ const agent = await loadOwnedAgent(agentId, userId);+ const owner = await walletFor(agent, userId, 'prediction_close');+ const { position_id: positionId, market_id: marketId, side, contracts, min_price: minPrice } = preview.params;+ await consumePreview(preview.id, 'close');+ const custodyId = await recordCustodyEvent({+ agentId: agent.id, userId, eventType: 'spend', category: 'prediction', asset: 'USDC', status: 'pending',+ reason: 'prediction_close', destination: `prediction-venue:${venue.id}`,+ meta: { prediction_action: 'close', position_id: positionId, market_id: marketId, side, contracts, min_price: minPrice, preview_id: preview.id, source },+ });+ try {+ const built = await venue.buildCloseOrder({ owner, positionId, marketId, side, contracts, minPrice });+ const landed = await signAndSubmit({ agent, userId, venue, built, owner, custodyId, maxUsdcOutAtomic: 0n, reason: 'prediction_close' });+ await updateCustodyEvent(custodyId, { status: 'confirmed', signature: landed.signature, meta: { order_id: built.order_id, simulation: landed.simulation } }).catch(() => {});+ logAudit({ userId, action: 'custody.prediction_close', resourceId: agent.id, meta: { position_id: positionId, contracts, signature: landed.signature, source }, req });+ return { ok: true, action: 'close', signature: landed.signature, explorer: `https://solscan.io/tx/${landed.signature}`, order_id: built.order_id, position_id: positionId, contracts, min_price: minPrice, note: 'The sell order is on chain; proceeds reach the wallet as it fills.' };+ } catch (err) {+ await updateCustodyEvent(custodyId, { status: 'failed', meta: { error: err?.code || 'close_failed' } }).catch(() => {});+ await releasePreview(preview.id).catch(() => {});+ throw err;+ }+}++// ── Redeem ───────────────────────────────────────────────────────────────────++export async function previewRedeem({ agentId, userId, positionId }) {+ const venue = getVenue(DEFAULT_VENUE);+ const agent = await loadOwnedAgent(agentId, userId);+ const owner = await walletFor(agent, userId, 'prediction_preview');+ const pos = await findPosition(venue, owner, String(positionId || ''));+ const checks = [+ { id: 'resolved', ok: pos.status !== 'open', label: pos.status === 'open' ? 'The market has not resolved yet' : 'The market has resolved' },+ { id: 'winning', ok: pos.won !== false, label: pos.won === false ? 'This side lost; there is nothing to redeem' : 'This side is owed a payout' },+ { id: 'claimable', ok: pos.claimable, label: pos.claimed ? 'Already redeemed' : pos.claimable ? 'The payout is claimable now' : 'The payout is not claimable yet' },+ ];+ const quote = {+ position: { id: pos.id, market_id: pos.market_id, market_title: pos.market_title, event_title: pos.event_title, side: pos.side, side_label: pos.side_label, contracts_held: pos.contracts, cost_usd: pos.cost_usd, result: pos.result },+ expected_payout_usd: pos.payout_usd,+ checks,+ executable: checks.every((c) => c.ok),+ blocked_by: checks.filter((c) => !c.ok).map((c) => c.id),+ };+ const { preview_id, expires_at } = await createPreview({ agentId: agent.id, userId, venue: venue.id, kind: 'redeem', params: { position_id: pos.id, market_id: pos.market_id }, quote });+ return { preview_id, expires_at, venue: venue.id, chain: 'solana', ...quote, confirm_with: { confirm_trade: true, preview_id } };+}++export async function executeRedeem({ agentId, userId, previewId, confirm, req = null, source = 'owner' }) {+ requireConfirm(confirm, 'redemption');+ const preview = await loadPreview(previewId, { agentId, kind: 'redeem' });+ const venue = getVenue(preview.venue);+ const agent = await loadOwnedAgent(agentId, userId);+ const owner = await walletFor(agent, userId, 'prediction_redeem');+ const { position_id: positionId, market_id: marketId } = preview.params;+ await consumePreview(preview.id, 'redeem');+ const custodyId = await recordCustodyEvent({+ agentId: agent.id, userId, eventType: 'spend', category: 'prediction', asset: 'USDC', status: 'pending',+ reason: 'prediction_redeem', destination: `prediction-venue:${venue.id}`,+ meta: { prediction_action: 'redeem', position_id: positionId, market_id: marketId, preview_id: preview.id, source },+ });+ try {+ const built = await venue.buildRedeem({ owner, positionId });+ const landed = await signAndSubmit({ agent, userId, venue, built, owner, custodyId, maxUsdcOutAtomic: 0n, reason: 'prediction_redeem' });+ await updateCustodyEvent(custodyId, { status: 'confirmed', signature: landed.signature, meta: { payout_usd: built.payout_usd, simulation: landed.simulation } }).catch(() => {});+ logAudit({ userId, action: 'custody.prediction_redeem', resourceId: agent.id, meta: { position_id: positionId, payout_usd: built.payout_usd, signature: landed.signature, source }, req });+ return { ok: true, action: 'redeem', signature: landed.signature, explorer: `https://solscan.io/tx/${landed.signature}`, position_id: positionId, payout_usd: built.payout_usd };+ } catch (err) {+ await updateCustodyEvent(custodyId, { status: 'failed', meta: { error: err?.code || 'redeem_failed' } }).catch(() => {});+ await releasePreview(preview.id).catch(() => {});+ throw err;+ }+}++// ── Positions ────────────────────────────────────────────────────────────────++/** The agent's positions and recent fills with a PnL summary. Owner-only. */+export async function agentPositions({ agentId, userId }) {+ const venue = getVenue(DEFAULT_VENUE);+ const agent = await loadOwnedAgent(agentId, userId);+ const owner = await walletFor(agent, userId, 'prediction_positions');+ const [positions, fills, balances] = await Promise.all([+ venue.listPositions(owner),+ venue.listFills(owner, { limit: 50 }).catch(() => []),+ getSolanaAddressBalances(owner, 'mainnet'),+ ]);+ const open = positions.filter((p) => p.status === 'open');+ const settled = positions.filter((p) => p.status !== 'open');+ const sum = (arr, k) => Math.round(arr.reduce((s, p) => s + (Number(p[k]) || 0), 0) * 100) / 100;+ return {+ venue: venue.id,+ chain: 'solana',+ agent: { id: agent.id, name: agent.name },+ wallet: { address: owner, usdc: balances.usdc, sol: balances.sol },+ limits: getPredictionLimits(agent.meta),+ summary: {+ open_count: open.length,+ settled_count: settled.length,+ open_cost_usd: sum(open, 'cost_usd'),+ open_value_usd: sum(open, 'value_usd'),+ unrealized_pnl_usd: sum(open, 'pnl_usd'),+ realized_pnl_usd: sum(positions, 'realized_pnl_usd'),+ claimable_usd: sum(positions.filter((p) => p.claimable), 'payout_usd'),+ },+ open,+ settled,+ fills,+ };+}diff --git a/api/_lib/predictions/index.js b/api/_lib/predictions/index.jsnew file mode 100644index 000000000..bd681686c--- /dev/null+++ b/api/_lib/predictions/index.js@@ -0,0 +1,133 @@+// Venue-agnostic prediction-market interface.+//+// Routes (api/v1/agents/[id]/predictions/, api/predictions/), the MCP tools+// (api/_mcpagent/predictions-tools.js) and the market_price alert runner talk to+// this module only. Each venue is one file exporting an object that satisfies+// VENUE_METHODS; adding a venue is adding that file and one line to VENUES.+//+// Solana is the default and the only venue today: event contracts settled in+// USDC on Solana (api/_lib/predictions/solana-venue.js).++import { venue as solanaVenue } from './solana-venue.js';++/**+ * @typedef {Object} PredictionOutcome+ * @property {'yes'|'no'} side+ * @property {string} label what the side means for this market ("Yes", a team name)+ * @property {number|null} buy_price price to buy one contract, as a probability 0..1+ * @property {number|null} sell_price price one contract sells for right now+ *+ * @typedef {Object} PredictionMarket+ * @property {string} id+ * @property {string|null} event_id+ * @property {string} venue+ * @property {string|null} provider the book that fills and resolves the market+ * @property {string} title+ * @property {string|null} status+ * @property {string|null} result 'yes' | 'no' | 'draw' | 'refund' once resolved+ * @property {boolean} tradable+ * @property {string|null} open_time+ * @property {string|null} close_time+ * @property {string|null} resolve_at+ * @property {number|null} probability implied probability of YES (mid price)+ * @property {number|null} spread+ * @property {number|null} volume_contracts+ * @property {PredictionOutcome[]} outcomes+ * @property {string|null} rules+ * @property {string|null} rules_secondary+ * @property {string|null} image_url+ * @property {object|null} history_ref+ *+ * @typedef {Object} PredictionEvent+ * @property {string} id+ * @property {string} venue+ * @property {string|null} provider+ * @property {string} title+ * @property {string|null} subtitle+ * @property {string|null} category+ * @property {string|null} subcategory+ * @property {string[]} tags+ * @property {string|null} image_url+ * @property {boolean} is_active+ * @property {boolean} is_live+ * @property {string|null} begin_at+ * @property {string|null} close_time+ * @property {number|null} volume_usd+ * @property {number|null} volume_24h_usd+ * @property {{ condition: string|null, rules_pdf: string|null, source: string|null }} resolution+ * @property {number} market_count+ * @property {PredictionMarket[]} markets+ *+ * @typedef {Object} PredictionPosition+ * @property {string} id+ * @property {string} market_id+ * @property {'yes'|'no'} side+ * @property {number} contracts+ * @property {number|null} cost_usd+ * @property {number|null} value_usd+ * @property {number|null} pnl_usd+ * @property {'open'|'settled'|'lost'|'redeemed'} status+ * @property {boolean} claimable+ */++/** Every venue implements these. tests/predictions-venue.test.js enforces it. */+export const VENUE_METHODS = Object.freeze([+ 'listEvents',+ 'listCategories',+ 'getEvent',+ 'getMarket',+ 'getOrderbook',+ 'getPriceHistory',+ 'tradingStatus',+ 'listPositions',+ 'listFills',+ 'getOrderStatus',+ 'buildOpenOrder',+ 'buildCloseOrder',+ 'buildRedeem',+ 'submit',+]);++export const VENUES = Object.freeze({ [solanaVenue.id]: solanaVenue });+export const DEFAULT_VENUE = solanaVenue.id;++/** Methods a venue object is missing. Empty when it satisfies the contract. */+export function missingVenueMethods(v) {+ return VENUE_METHODS.filter((m) => typeof v?.[m] !== 'function');+}++export function getVenue(id = DEFAULT_VENUE) {+ const v = VENUES[id || DEFAULT_VENUE];+ if (!v) {+ const err = new Error(`Unknown prediction venue "${id}". Known: ${Object.keys(VENUES).join(', ')}.`);+ err.status = 400;+ err.code = 'unknown_venue';+ throw err;+ }+ return v;+}++export function listVenues() {+ return Object.values(VENUES).map((v) => ({ id: v.id, label: v.label, chain: v.chain, settlement: v.settlement, default: v.id === DEFAULT_VENUE }));+}++/**+ * Implied probability of one side of a market: the mid of its buy and sell+ * price when both exist, else whichever exists, else the complement of the+ * other side's mid. Null when the market has no price at all.+ * @param {PredictionMarket} market+ * @param {'yes'|'no'} side+ */+export function sideProbability(market, side) {+ const mid = (o) => {+ if (!o) return null;+ if (o.buy_price != null && o.sell_price != null) return (o.buy_price + o.sell_price) / 2;+ return o.buy_price ?? o.sell_price ?? null;+ };+ const own = mid(market?.outcomes?.find((o) => o.side === side));+ if (own != null) return Math.round(own * 10_000) / 10_000;+ const other = mid(market?.outcomes?.find((o) => o.side !== side));+ return other != null ? Math.round((1 - other) * 10_000) / 10_000 : null;+}++export { VenueError } from './solana-venue.js';diff --git a/api/_lib/predictions/previews.js b/api/_lib/predictions/previews.jsnew file mode 100644index 000000000..f801e0e03--- /dev/null+++ b/api/_lib/predictions/previews.js@@ -0,0 +1,94 @@+// Preview-then-execute for prediction orders.+//+// Every fund-moving prediction action (open, close, redeem) runs in two calls.+// The preview prices it against the live venue and stores what it showed; the+// execution must present that preview's id. A preview is bound to one agent+// and one action, expires after PREVIEW_TTL_MS, and is consumed atomically by+// the execution that uses it, so a stale or replayed preview never moves money+// and the order that lands is the one the owner saw.++import { sql } from '../db.js';++export const PREVIEW_TTL_MS = 10 * 60_000;++export class PreviewError extends Error {+ constructor(code, message, status = 409) {+ super(message);+ this.name = 'PreviewError';+ this.code = code;+ this.status = status;+ }+}++const PREVIEW_TOOL = { open: 'predictions_open_preview', close: 'predictions_close_preview', redeem: 'predictions_redeem_preview' };+const PREVIEW_ROUTE = { open: 'open/preview', close: 'close/preview', redeem: 'redeem/preview' };++/** Where to get a fresh preview for `kind`, for error messages. */+export function previewHint(kind) {+ return `Call ${PREVIEW_TOOL[kind]} (POST .../predictions/${PREVIEW_ROUTE[kind]}) first and pass its preview_id.`;+}++/**+ * Decide whether a stored preview may authorize an execution. Pure.+ * @param {{ agent_id: string, kind: string, expires_at: string|Date, consumed_at: string|Date|null } | null} row+ * @param {{ agentId: string, kind: string, now?: number }} want+ * @returns {null | PreviewError}+ */+export function previewProblem(row, { agentId, kind, now = Date.now() }) {+ if (!row) return new PreviewError('preview_not_found', `No preview with that id. ${previewHint(kind)}`, 404);+ if (row.agent_id !== agentId) return new PreviewError('preview_mismatch', `That preview belongs to a different agent. ${previewHint(kind)}`, 409);+ if (row.kind !== kind) return new PreviewError('preview_mismatch', `That preview is for a ${row.kind}, not a ${kind}. ${previewHint(kind)}`, 409);+ if (row.consumed_at) return new PreviewError('preview_consumed', `That preview was already used. ${previewHint(kind)}`, 409);+ if (new Date(row.expires_at).getTime() <= now) {+ return new PreviewError('preview_expired', `That preview is more than ${PREVIEW_TTL_MS / 60_000} minutes old and prices have moved. ${previewHint(kind)}`, 409);+ }+ return null;+}++export async function createPreview({ agentId, userId, venue, kind, params, quote }) {+ const expires = new Date(Date.now() + PREVIEW_TTL_MS);+ const [row] = await sql`+ INSERT INTO prediction_previews (agent_id, user_id, venue, kind, params, quote, expires_at)+ VALUES (${agentId}, ${userId ?? null}, ${venue}, ${kind}, ${JSON.stringify(params)}::jsonb, ${JSON.stringify(quote)}::jsonb, ${expires.toISOString()})+ RETURNING id, expires_at+ `;+ return { preview_id: row.id, expires_at: new Date(row.expires_at).toISOString() };+}++const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;++/** Load a preview and verify it may authorize `kind` for `agentId`. Throws PreviewError. */+export async function loadPreview(previewId, { agentId, kind }) {+ if (!previewId || !UUID_RE.test(String(previewId))) {+ throw new PreviewError('preview_required', `A preview_id is required. ${previewHint(kind)}`, 400);+ }+ const [row] = await sql`+ SELECT id, agent_id, user_id, venue, kind, params, quote, created_at, expires_at, consumed_at+ FROM prediction_previews WHERE id = ${previewId}+ `;+ const problem = previewProblem(row || null, { agentId, kind });+ if (problem) throw problem;+ return row;+}++/**+ * Mark a preview used. Atomic: of two concurrent executions presenting the same+ * preview, exactly one wins; the other gets preview_consumed.+ */+export async function consumePreview(previewId, kind) {+ const rows = await sql`+ UPDATE prediction_previews SET consumed_at = now()+ WHERE id = ${previewId} AND consumed_at IS NULL AND expires_at > now()+ RETURNING id+ `;+ if (!rows.length) throw new PreviewError('preview_consumed', `That preview was already used or just expired. ${previewHint(kind)}`, 409);+}++/** Return a consumed preview to service when the execution moved nothing. */+export async function releasePreview(previewId) {+ await sql`UPDATE prediction_previews SET consumed_at = NULL WHERE id = ${previewId} AND expires_at > now()`;+}++export async function prunePreviews() {+ await sql`DELETE FROM prediction_previews WHERE created_at < now() - interval '2 days'`;+}diff --git a/api/_lib/predictions/routes.js b/api/_lib/predictions/routes.jsnew file mode 100644index 000000000..541fc4ef6--- /dev/null+++ b/api/_lib/predictions/routes.js@@ -0,0 +1,198 @@+// Route table for prediction markets, in the v1 API contract+// (api/_lib/agents-v1/http.js: one envelope, per-route auth and scopes, CSRF on+// cookie writes, Idempotency-Key replay).+//+// Two mounts share it:+// /api/v1/agents/:id/predictions/* api/v1/agents/[id]/predictions/[...path].js+// /api/predictions/* api/predictions/[...path].js (public reads only)+//+// Reads (events, categories, event, market) are public. Everything touching+// the agent (positions, previews, orders, limits, watches) is owner-only, and+// the three fund-moving routes also require the signed real-funds agreement,+// confirm_trade: true, and a fresh preview_id.++import { apiError, created, requireUuid, strParam, intParam } from '../agents-v1/http.js';+import { currentSignatureFor, agreementRequirement } from '../real-funds-agreement.js';+import { getPredictionLimits, setPredictionLimits } from '../agent-trade-guards.js';+import { getVenue, DEFAULT_VENUE, listVenues } from './index.js';+import { summarizeBook } from './book.js';+import {+ previewOpen, executeOpen, previewClose, executeClose, previewRedeem, executeRedeem,+ agentPositions, loadOwnedAgent, describeError,+} from './engine.js';+import { createWatch, listWatches, deleteWatch } from './watch.js';++const SORTS = new Set(['volume', 'volume_24h', 'close', 'new']);+const RANGES = new Set(['1d', '1w', '1m', 'max']);+const ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;++/** Re-throw engine errors as v1 ApiErrors so the envelope carries their code. */+async function run(fn) {+ try {+ return await fn();+ } catch (err) {+ const d = describeError(err);+ if (d) throw apiError(d.status, d.code, d.message, d.detail);+ throw err;+ }+}++function venueId(q) {+ return q?.venue ? String(q.venue) : DEFAULT_VENUE;+}++function venueRef(id) {+ if (typeof id !== 'string' || !ID_RE.test(id)) throw apiError(404, 'not_found', 'No market or event with that id.');+ return id;+}++// ── public reads ─────────────────────────────────────────────────────────────++async function listEventsRoute({ query }) {+ const sort = SORTS.has(query.sort) ? query.sort : 'volume';+ const out = await run(() => getVenue(venueId(query)).listEvents({+ q: strParam(query.q, { name: 'q', max: 120 }) || '',+ category: strParam(query.category, { name: 'category', max: 40 }),+ subcategory: strParam(query.subcategory, { name: 'subcategory', max: 40 }),+ sort,+ start: intParam(query.start, { name: 'start', min: 0, max: 10_000, fallback: 0 }),+ limit: intParam(query.limit, { name: 'limit', min: 1, max: 50, fallback: 24 }),+ includeClosed: query.include_closed === 'true',+ }));+ return { ...out, venue: venueId(query), sort };+}++async function categoriesRoute({ query }) {+ return { categories: await run(() => getVenue(venueId(query)).listCategories()), venues: listVenues() };+}++async function marketDetail(venue, market, range) {+ const [bookRaw, history] = await Promise.all([+ market.tradable ? venue.getOrderbook(market.id).catch(() => null) : null,+ venue.getPriceHistory(market, range).catch(() => ({ source: null, range, points: [], unavailable: true })),+ ]);+ return { ...market, book: bookRaw ? summarizeBook(bookRaw) : null, history };+}++async function eventRoute({ params, query }) {+ const venue = getVenue(venueId(query));+ const range = RANGES.has(query.range) ? query.range : '1w';+ const event = await run(() => venue.getEvent(venueRef(params.eventId)));+ const lead = event.markets.find((m) => m.id === query.market) || event.markets[0] || null;+ const leadDetail = lead ? await run(() => marketDetail(venue, lead, range)) : null;+ return { ...event, selected_market: leadDetail };+}++async function marketRoute({ params, query }) {+ const venue = getVenue(venueId(query));+ const range = RANGES.has(query.range) ? query.range : '1w';+ const market = await run(() => venue.getMarket(venueRef(params.marketId)));+ return run(() => marketDetail(venue, market, range));+}++export function publicRoutes(prefix) {+ return [+ { method: 'GET', path: `${prefix}/events`, name: 'predictions.events', auth: 'public', handler: listEventsRoute },+ { method: 'GET', path: `${prefix}/categories`, name: 'predictions.categories', auth: 'public', handler: categoriesRoute },+ { method: 'GET', path: `${prefix}/event/:eventId`, name: 'predictions.event', auth: 'public', handler: eventRoute },+ { method: 'GET', path: `${prefix}/market/:marketId`, name: 'predictions.market', auth: 'public', handler: marketRoute },+ ];+}++// ── owner routes ─────────────────────────────────────────────────────────────++async function requireAgreement(userId) {+ let signed;+ try {+ signed = await currentSignatureFor(userId);+ } catch {+ throw apiError(503, 'agreement_check_unavailable', 'Could not verify your signed real-funds agreements, so nothing was sent. Try again in a moment.');+ }+ if (!signed) {+ const r = agreementRequirement();+ throw apiError(403, 'risk_ack_required', 'Sign the real-funds agreements (Terms of Service, Risk Disclosure, and Agent Wallet Agreement) before moving funds. Nothing was sent.', r);+ }+}++const agentOf = (params) => requireUuid(params.id, 'agent');+const sourceOf = (principal) => (principal.source === 'session' ? 'owner' : `api:${principal.source}`);++export const agentRoutes = [+ ...publicRoutes('/agents/:id/predictions'),+ {+ method: 'GET', path: '/agents/:id/predictions/positions', name: 'predictions.positions', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal }) => run(() => agentPositions({ agentId: agentOf(params), userId: principal.userId })),+ },+ {+ method: 'GET', path: '/agents/:id/predictions/limits', name: 'predictions.limits.get', auth: 'required', scope: 'wallet:read',+ handler: async ({ params, principal }) => {+ const agent = await run(() => loadOwnedAgent(agentOf(params), principal.userId));+ return getPredictionLimits(agent.meta);+ },+ },+ {+ method: 'PUT', path: '/agents/:id/predictions/limits', name: 'predictions.limits.set', auth: 'required', scope: 'wallet:write',+ handler: ({ params, principal, body, req }) => run(() => setPredictionLimits(agentOf(params), principal.userId, body, { req })),+ },+ {+ method: 'POST', path: '/agents/:id/predictions/open/preview', name: 'predictions.open.preview', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal, body }) => run(() => previewOpen({+ agentId: agentOf(params), userId: principal.userId, venueId: body.venue,+ marketId: body.market_id, side: body.side, stakeUsd: body.stake_usd, maxPrice: body.max_price,+ })),+ },+ {+ method: 'POST', path: '/agents/:id/predictions/open', name: 'predictions.open', auth: 'required', scope: 'wallet:write',+ handler: async ({ params, principal, body, req }) => {+ await requireAgreement(principal.userId);+ return run(() => executeOpen({ agentId: agentOf(params), userId: principal.userId, previewId: body.preview_id, confirm: body.confirm_trade, req, source: sourceOf(principal) }));+ },+ },+ {+ method: 'POST', path: '/agents/:id/predictions/close/preview', name: 'predictions.close.preview', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal, body }) => run(() => previewClose({+ agentId: agentOf(params), userId: principal.userId, positionId: body.position_id, contracts: body.contracts, minPrice: body.min_price,+ })),+ },+ {+ method: 'POST', path: '/agents/:id/predictions/close', name: 'predictions.close', auth: 'required', scope: 'wallet:write',+ handler: async ({ params, principal, body, req }) => {+ await requireAgreement(principal.userId);+ return run(() => executeClose({ agentId: agentOf(params), userId: principal.userId, previewId: body.preview_id, confirm: body.confirm_trade, req, source: sourceOf(principal) }));+ },+ },+ {+ method: 'POST', path: '/agents/:id/predictions/redeem/preview', name: 'predictions.redeem.preview', auth: 'required', scope: 'wallet:read',+ handler: ({ params, principal, body }) => run(() => previewRedeem({ agentId: agentOf(params), userId: principal.userId, positionId: body.position_id })),+ },+ {+ method: 'POST', path: '/agents/:id/predictions/redeem', name: 'predictions.redeem', auth: 'required', scope: 'wallet:write',+ handler: async ({ params, principal, body, req }) => {+ await requireAgreement(principal.userId);+ return run(() => executeRedeem({ agentId: agentOf(params), userId: principal.userId, previewId: body.preview_id, confirm: body.confirm_trade, req, source: sourceOf(principal) }));+ },+ },+ {+ method: 'GET', path: '/agents/:id/predictions/watch', name: 'predictions.watch.list', auth: 'required', scope: 'wallet:read',+ handler: async ({ params, principal }) => {+ const agentId = agentOf(params);+ await run(() => loadOwnedAgent(agentId, principal.userId));+ return { watches: await run(() => listWatches({ agentId, userId: principal.userId })) };+ },+ },+ {+ method: 'POST', path: '/agents/:id/predictions/watch', name: 'predictions.watch.create', auth: 'required', scope: 'wallet:write',+ handler: async ({ params, principal, body }) => {+ const agentId = agentOf(params);+ await run(() => loadOwnedAgent(agentId, principal.userId));+ return created(await run(() => createWatch({ agentId, userId: principal.userId, body })));+ },+ },+ {+ method: 'DELETE', path: '/agents/:id/predictions/watch/:watchId', name: 'predictions.watch.delete', auth: 'required', scope: 'wallet:write',+ handler: async ({ params, principal }) => {+ await run(() => loadOwnedAgent(agentOf(params), principal.userId));+ return run(() => deleteWatch({ userId: principal.userId, watchId: requireUuid(params.watchId, 'watch') }));+ },+ },+];diff --git a/api/_lib/predictions/solana-venue.js b/api/_lib/predictions/solana-venue.jsnew file mode 100644index 000000000..8139bab3f--- /dev/null+++ b/api/_lib/predictions/solana-venue.js@@ -0,0 +1,561 @@+// Solana prediction venue: event contracts settled in USDC on Solana.+//+// The venue runs an on-chain program that holds each trader's positions as+// program accounts on Solana, escrows USDC for open orders, and pays winning+// contracts $1 each at resolution. Liquidity comes from two external event+// order books that the venue's keepers fill against, which is why a market's+// `provider` field names one of them: that is the book the order is filled on+// and the source that resolves it.+//+// This module is the only file that knows the venue's wire format. Everything+// it returns is normalized into the venue-agnostic shapes documented in+// api/_lib/predictions/index.js, so a second venue is one added file.+//+// Reads (events, markets, order books, positions, history) are public and need+// no key. Order building answers `unsupported_region` for requests from+// jurisdictions the venue does not serve; that answer is surfaced verbatim as+// a designed state (VenueError code `venue_region_unavailable`), never retried+// from somewhere else.++import { fetchAnyJson, fetchUpstreamJson, UpstreamError } from '../upstream-fetch.js';+import { createCache, cached } from '../mem-cache.js';++export const VENUE_ID = 'solana';+export const VENUE_LABEL = 'Solana event contracts';+export const SETTLEMENT_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';++// Three hosts serve the same API; the chain fails over in order. An operator+// can replace the list with PREDICTIONS_API_BASES (comma separated).+const DEFAULT_BASES = [+ 'https://prediction-market-api.jup.ag/api/v1',+ 'https://api.jup.ag/prediction/v1',+ 'https://lite-api.jup.ag/prediction/v1',+];++const POLY_HISTORY = 'https://clob.polymarket.com/prices-history';+const KALSHI_API = 'https://api.elections.kalshi.com/trade-api/v2';++const MICRO = 1_000_000;+const READ_TIMEOUT_MS = 8_000;+const WRITE_TIMEOUT_MS = 15_000;++const cache = createCache({ max: 800, ttlMs: 20_000 });+const slowCache = createCache({ max: 400, ttlMs: 5 * 60_000 });++export class VenueError extends Error {+ constructor(code, message, { status = 502, detail = null } = {}) {+ super(message);+ this.name = 'VenueError';+ this.code = code;+ this.status = status;+ this.detail = detail;+ }+}++function bases() {+ const raw = process.env.PREDICTIONS_API_BASES;+ if (raw && raw.trim()) return raw.split(',').map((s) => s.trim().replace(/\/+$/, '')).filter(Boolean);+ return DEFAULT_BASES;+}++function qs(params) {+ const u = new URLSearchParams();+ for (const [k, v] of Object.entries(params)) {+ if (v === undefined || v === null || v === '') continue;+ u.set(k, String(v));+ }+ const s = u.toString();+ return s ? `?${s}` : '';+}++async function read(path, params = {}) {+ const urls = bases().map((b) => `${b}${path}${qs(params)}`);+ try {+ const { value } = await fetchAnyJson(urls, {}, { name: 'predictions-venue', timeoutMs: READ_TIMEOUT_MS, label: 'predictions venue' });+ return value;+ } catch (err) {+ const status = err?.cause?.status ?? err?.status;+ if (status === 404) throw new VenueError('not_found', 'The venue has no record of that id.', { status: 404 });+ throw new VenueError('venue_unavailable', 'The prediction venue did not answer. Try again in a moment.', { status: 503 });+ }+}++// Writes go to one host at a time: a transaction built by one host is submitted+// through the same family, and a 4xx is an answer, not an outage, so it is+// never retried on the next host.+async function write(path, { method = 'POST', body } = {}) {+ let lastErr;+ for (const base of bases()) {+ try {+ const res = await fetch(`${base}${path}`, {+ method,+ headers: { 'content-type': 'application/json', accept: 'application/json' },+ body: body == null ? undefined : JSON.stringify(body),+ signal: AbortSignal.timeout(WRITE_TIMEOUT_MS),+ });+ const text = await res.text();+ let data = null;+ try { data = text ? JSON.parse(text) : null; } catch { data = null; }+ if (res.ok && data) return data;+ if (res.status >= 400 && res.status < 500) throw venueRefusal(res.status, data, text);+ lastErr = new VenueError('venue_unavailable', `The venue answered ${res.status}.`, { status: 503 });+ } catch (err) {+ if (err instanceof VenueError && err.code !== 'venue_unavailable') throw err;+ lastErr = err instanceof VenueError ? err : new VenueError('venue_unavailable', 'The prediction venue did not answer. Try again in a moment.', { status: 503 });+ }+ }+ throw lastErr;+}++function venueRefusal(status, data, text) {+ const code = data?.code || data?.error?.code || null;+ const message = data?.message || data?.error?.message || (typeof data?.error === 'string' ? data.error : null) || text?.slice(0, 200) || `HTTP ${status}`;+ if (code === 'unsupported_region') {+ return new VenueError(+ 'venue_region_unavailable',+ 'The venue does not accept orders from the region this server runs in. Browsing, research and watches keep working; orders cannot be placed from here.',+ { status: 451, detail: { venue_code: code } },+ );+ }+ if (code === 'INSUFFICIENT_FUNDS' || /insufficient/i.test(message)) {+ return new VenueError('insufficient_funds', 'The agent wallet does not hold enough USDC for this order.', { status: 409, detail: { venue_code: code } });+ }+ return new VenueError('venue_rejected', `The venue rejected the request: ${message}`, { status: 422, detail: { venue_code: code } });+}++// ── Normalizers ──────────────────────────────────────────────────────────────++const usd = (micro) => {+ const n = Number(micro);+ return Number.isFinite(n) ? n / MICRO : null;+};+const prob = (micro) => {+ const n = Number(micro);+ return Number.isFinite(n) && n > 0 ? Math.round((n / MICRO) * 10_000) / 10_000 : null;+};+const iso = (v) => {+ if (v == null || v === '') return null;+ const n = Number(v);+ const d = Number.isFinite(n) ? new Date(n < 1e12 ? n * 1000 : n) : new Date(v);+ return Number.isFinite(d.getTime()) ? d.toISOString() : null;+};++function sideLabels(m) {+ const opts = Array.isArray(m.marketOptions) ? m.marketOptions : [];+ const yes = opts.find((o) => o.buyYes === true)?.label;+ const no = opts.find((o) => o.buyYes === false)?.label;+ const outcomes = Array.isArray(m.outcomes) ? m.outcomes : [];+ return { yes: yes || outcomes[0] || 'Yes', no: no || outcomes[1] || 'No' };+}++/** @returns {import('./index.js').PredictionMarket} */+export function normalizeMarket(m, event = null) {+ const p = m.pricing || {};+ const buyYes = prob(p.buyYesPriceUsd);+ const sellYes = prob(p.sellYesPriceUsd);+ const buyNo = prob(p.buyNoPriceUsd);+ const sellNo = prob(p.sellNoPriceUsd);+ const labels = sideLabels(m);+ const mid = buyYes != null && sellYes != null ? (buyYes + sellYes) / 2 : buyYes ?? sellYes ?? (buyNo != null ? 1 - buyNo : null);+ const spread = buyYes != null && sellYes != null ? Math.round(Math.max(0, buyYes - sellYes) * 10_000) / 10_000 : null;+ const series = event?.metadata?.series || null;+ return {+ id: m.marketId,+ event_id: m.eventId || event?.eventId || null,+ venue: VENUE_ID,+ provider: m.provider || null,+ title: m.title || '',+ status: m.status || null,+ result: m.result || null,+ tradable: m.status === 'open',+ open_time: iso(m.openTime),+ close_time: iso(m.closeTime),+ resolve_at: iso(m.resolveAt),+ probability: mid != null ? Math.round(mid * 10_000) / 10_000 : null,+ spread,+ volume_contracts: Number.isFinite(Number(p.volume)) ? Number(p.volume) : null,+ outcomes: [+ { side: 'yes', label: labels.yes, buy_price: buyYes, sell_price: sellYes },+ { side: 'no', label: labels.no, buy_price: buyNo, sell_price: sellNo },+ ],+ rules: m.rulesPrimary || null,+ rules_secondary: m.rulesSecondary || null,+ image_url: m.imageUrl || m.team?.imageUrl || null,+ history_ref: historyRef(m, series),+ };+}++function historyRef(m, series) {+ if (m.provider === 'polymarket' && Array.isArray(m.clobTokenIds) && m.clobTokenIds[0]) {+ return { source: 'polymarket', token: String(m.clobTokenIds[0]) };+ }+ if (m.provider === 'kalshi' && series && m.marketId) {+ return { source: 'kalshi', series: String(series), ticker: String(m.marketId) };+ }+ return null;+}++/** @returns {import('./index.js').PredictionEvent} */+export function normalizeEvent(e) {+ const md = e.metadata || {};+ const markets = Array.isArray(e.markets) ? e.markets.map((m) => normalizeMarket(m, e)) : [];+ // Lead with the most likely open outcome, the way a reader scans a board.+ markets.sort((a, b) => (b.tradable - a.tradable) || ((b.probability ?? -1) - (a.probability ?? -1)));+ const provider = markets[0]?.provider || (md.series === 'polymarket' ? 'polymarket' : md.series ? 'kalshi' : null);+ return {+ id: e.eventId,+ venue: VENUE_ID,+ provider,+ title: md.title || e.eventId,+ subtitle: md.subtitle || null,+ category: e.category || null,+ subcategory: e.subcategory || null,+ tags: Array.isArray(e.tags) ? e.tags.filter((t) => !/^earn-\d+$/.test(t)).slice(0, 8) : [],+ image_url: md.imageUrl || null,+ is_active: e.isActive !== false,+ is_live: !!(e.isLive || md.isLive),+ begin_at: iso(e.beginAt),+ close_time: iso(md.closeTime),+ volume_usd: usd(e.volumeUsd),+ volume_24h_usd: usd(e.volume24hr),+ resolution: {+ condition: e.closeCondition || md.earlyCloseCondition || null,+ rules_pdf: e.rulesPdf || md.rulesPdf || null,+ source: provider,+ },+ market_count: markets.length,+ markets,+ };+}++/** @returns {import('./index.js').PredictionPosition} */+export function normalizePosition(p) {+ const mm = p.marketMetadata || {};+ const em = p.eventMetadata || {};+ const labels = sideLabels({ marketOptions: mm.marketOptions, outcomes: null });+ const side = p.isYes ? 'yes' : 'no';+ const settled = mm.status === 'closed' || mm.status === 'settled' || mm.lifecycleStatus === 'settled' || !!mm.result;+ const won = settled && mm.result ? (mm.result === 'yes') === !!p.isYes : null;+ return {+ id: p.pubkey,+ venue: VENUE_ID,+ market_id: p.marketId,+ event_id: p.eventId || em.eventId || null,+ event_title: em.title || null,+ market_title: mm.title || null,+ side,+ side_label: side === 'yes' ? labels.yes : labels.no === 'No' && labels.yes !== 'Yes' ? `Not ${labels.yes}` : labels.no,+ contracts: Number(p.contractsDecimal ?? p.contracts ?? 0),+ cost_usd: usd(p.totalCostUsd ?? p.sizeUsd),+ avg_price: prob(p.avgPriceUsd),+ mark_price: prob(p.markPriceUsd),+ exit_price: prob(p.sellPriceUsd),+ value_usd: usd(p.valueUsd),+ pnl_usd: usd(p.pnlUsd),+ pnl_pct: Number.isFinite(Number(p.pnlUsdPercent)) ? Number(p.pnlUsdPercent) : null,+ pnl_after_fees_usd: usd(p.pnlUsdAfterFees),+ realized_pnl_usd: usd(p.realizedPnlUsd),+ fees_paid_usd: usd(p.feesPaidUsd),+ open_orders: Number(p.openOrders || 0),+ status: settled ? (p.claimed ? 'redeemed' : won === false ? 'lost' : 'settled') : 'open',+ result: mm.result || null,+ won,+ claimable: !!p.claimable && !p.claimed,+ claimed: !!p.claimed,+ claimed_usd: usd(p.claimedUsd),+ payout_usd: usd(p.payoutUsd),+ max_slippage_bps: p.maxSlippageBps ?? null,+ opened_at: iso(p.openedAt),+ updated_at: iso(p.updatedAt),+ close_time: iso(mm.closeTime ?? em.closeTime),+ image_url: em.imageUrl || mm.team?.imageUrl || null,+ provider: mm.provider || null,+ };+}++/**+ * The venue's order book lists resting bids per side as [cents, contracts].+ * Return both sides aggregated per price level as probabilities, best first.+ */+export function normalizeOrderbook(raw) {+ const agg = (levels) => {+ const m = new Map();+ for (const lvl of Array.isArray(levels) ? levels : []) {+ const cents = Number(lvl?.[0]);+ const qty = Number(lvl?.[1]);+ if (!Number.isFinite(cents) || !Number.isFinite(qty) || cents <= 0 || cents >= 100 || qty <= 0) continue;+ m.set(cents, (m.get(cents) || 0) + qty);+ }+ return [...m.entries()].sort((a, b) => b[0] - a[0]).map(([c, q]) => [c / 100, Math.round(q * 100) / 100]);+ };+ return { yes_bids: agg(raw?.yes), no_bids: agg(raw?.no) };+}++// ── Reads ────────────────────────────────────────────────────────────────────++const SORTS = { volume: 'volume', volume_24h: 'volume24hr', close: 'closeTime', new: 'beginAt' };++export async function listEvents({ q = '', category = null, subcategory = null, sort = 'volume', start = 0, limit = 24, includeClosed = false } = {}) {+ const lim = Math.min(50, Math.max(1, Number(limit) || 24));+ const st = Math.max(0, Number(start) || 0);+ if (q && q.trim()) {+ const key = `search:${q}:${st}:${lim}`;+ const raw = await cached(cache, key, () => read('/events/search', { query: q.trim().slice(0, 120), includeMarkets: true, start: st, end: st + lim }));+ const events = (raw?.data || []).map(normalizeEvent);+ return { events, total: raw?.pagination?.total ?? events.length, start: st, has_more: !!raw?.pagination?.hasNext };+ }+ const sortBy = SORTS[sort] || 'volume';+ const key = `events:${category}:${subcategory}:${sortBy}:${st}:${lim}:${includeClosed}`;+ const raw = await cached(cache, key, () => read('/events', {+ includeMarkets: true,+ includeCount: true,+ start: st,+ end: st + lim,+ category: category || undefined,+ subcategory: subcategory || undefined,+ sortBy,+ sortDirection: sort === 'close' ? 'asc' : 'desc',+ includeClosed: includeClosed ? true : undefined,+ }));+ const events = (raw?.data || []).map(normalizeEvent);+ return { events, total: raw?.pagination?.total ?? events.length, start: st, has_more: !!raw?.pagination?.hasNext };+}++export async function listCategories() {+ const raw = await cached(slowCache, 'categories', () => read('/events/categories'));+ return (raw?.data || []).map((c) => ({+ id: c.category,+ label: c.category ? c.category.charAt(0).toUpperCase() + c.category.slice(1) : '',+ event_count: Number(c.eventCount || 0),+ subcategories: (c.subcategories || []).map((s) => ({ id: s.subcategory, label: s.label || s.subcategory, event_count: Number(s.eventCount || 0) })),+ })).filter((c) => c.id && c.event_count > 0);+}++export async function getEvent(eventId) {+ const raw = await cached(cache, `event:${eventId}`, () => read(`/events/${encodeURIComponent(eventId)}`, { includeMarkets: true }));+ if (!raw?.eventId) throw new VenueError('not_found', 'No event with that id.', { status: 404 });+ return normalizeEvent(raw);+}++export async function getMarket(marketId) {+ const raw = await cached(cache, `market:${marketId}`, () => read(`/markets/${encodeURIComponent(marketId)}`));+ if (!raw?.marketId) throw new VenueError('not_found', 'No market with that id.', { status: 404 });+ let event = null;+ if (raw.eventId && raw.provider === 'kalshi') {+ event = await getRawEvent(raw.eventId).catch(() => null);+ }+ return normalizeMarket(raw, event);+}++async function getRawEvent(eventId) {+ return cached(cache, `event-raw:${eventId}`, () => read(`/events/${encodeURIComponent(eventId)}`, { includeMarkets: false }));+}++export async function getOrderbook(marketId) {+ const raw = await cached(cache, `book:${marketId}`, () => read(`/orderbook/${encodeURIComponent(marketId)}`));+ return normalizeOrderbook(raw);+}++export async function tradingStatus() {+ const raw = await cached(cache, 'trading-status', () => read('/trading-status'));+ return { trading_active: raw?.trading_active === true };+}++export async function listPositions(owner) {+ const raw = await read('/positions', { ownerPubkey: owner, includePrices: true, start: 0, end: 200 });+ return (raw?.data || []).map(normalizePosition);+}++export async function listFills(owner, { limit = 50 } = {}) {+ const raw = await read('/history', { ownerPubkey: owner, start: 0, end: Math.min(200, limit) });+ return (raw?.data || []).map((h) => ({+ id: h.id,+ type: h.eventType,+ signature: h.signature || null,+ at: iso(h.timestamp),+ market_id: h.marketId,+ event_id: h.eventId || null,+ position_id: h.positionPubkey || null,+ order_id: h.orderPubkey || null,+ side: h.isYes ? 'yes' : 'no',+ is_buy: !!h.isBuy,+ contracts: Number(h.filledContractsDecimal && Number(h.filledContractsDecimal) > 0 ? h.filledContractsDecimal : h.contractsDecimal || 0),+ avg_price: prob(h.avgFillPriceUsd),+ cost_usd: usd(h.totalCostUsd),+ proceeds_usd: usd(h.netProceedsUsd),+ payout_usd: usd(h.payoutAmountUsd),+ fee_usd: usd(h.feeUsd),+ realized_pnl_usd: usd(h.realizedPnl),+ market_title: h.marketMetadata?.title || null,+ event_title: h.eventMetadata?.title || null,+ }));+}++export async function getOrderStatus(orderPubkey) {+ return read(`/orders/status/${encodeURIComponent(orderPubkey)}`);+}++// ── Price history ────────────────────────────────────────────────────────────+// The venue publishes live prices but not their history, so history comes+// from the book that fills the market, which is also its resolution source.++const RANGES = {+ '1d': { seconds: 86_400, polyInterval: '1d', polyFidelity: 15, kalshiPeriod: 60 },+ '1w': { seconds: 7 * 86_400, polyInterval: '1w', polyFidelity: 60, kalshiPeriod: 60 },+ '1m': { seconds: 30 * 86_400, polyInterval: '1m', polyFidelity: 360, kalshiPeriod: 1440 },+ max: { seconds: 365 * 86_400, polyInterval: 'max', polyFidelity: 1440, kalshiPeriod: 1440 },+};++export function parsePolyHistory(raw) {+ return (raw?.history || [])+ .map((h) => ({ t: Number(h.t) * 1000, p: Number(h.p) }))+ .filter((pt) => Number.isFinite(pt.t) && Number.isFinite(pt.p) && pt.p >= 0 && pt.p <= 1);+}++export function parseKalshiCandles(raw) {+ const num = (v) => (v == null || v === '' ? NaN : Number(v));+ return (raw?.candlesticks || [])+ .map((c) => {+ let p = num(c.price?.close_dollars);+ if (!Number.isFinite(p)) {+ const bid = num(c.yes_bid?.close_dollars);+ const ask = num(c.yes_ask?.close_dollars);+ p = Number.isFinite(bid) && Number.isFinite(ask) ? (bid + ask) / 2 : NaN;+ }+ return { t: Number(c.end_period_ts) * 1000, p };+ })+ .filter((pt) => Number.isFinite(pt.t) && Number.isFinite(pt.p) && pt.p >= 0 && pt.p <= 1);+}++export async function getPriceHistory(market, range = '1w') {+ const r = RANGES[range] || RANGES['1w'];+ const ref = market?.history_ref;+ if (!ref) return { source: null, range, points: [] };+ const key = `hist:${ref.source}:${ref.token || ref.ticker}:${range}`;+ const points = await cached(slowCache, key, async () => {+ if (ref.source === 'polymarket') {+ const raw = await fetchUpstreamJson(`${POLY_HISTORY}${qs({ market: ref.token, interval: r.polyInterval, fidelity: r.polyFidelity })}`, {}, { name: 'predictions-history-poly', timeoutMs: READ_TIMEOUT_MS });+ return parsePolyHistory(raw);+ }+ const now = Math.floor(Date.now() / 1000);+ const raw = await fetchUpstreamJson(+ `${KALSHI_API}/series/${encodeURIComponent(ref.series)}/markets/${encodeURIComponent(ref.ticker)}/candlesticks${qs({ start_ts: now - r.seconds, end_ts: now, period_interval: r.kalshiPeriod })}`,+ {},+ { name: 'predictions-history-kalshi', timeoutMs: READ_TIMEOUT_MS },+ );+ return parseKalshiCandles(raw);+ }).catch((err) => {+ if (err instanceof UpstreamError) return null;+ throw err;+ });+ if (points == null) return { source: ref.source, range, points: [], unavailable: true };+ return { source: ref.source, range, points };+}++// ── Transaction building + submission ───────────────────────────────────────++function priceMicro(p) {+ // Whole cents are on every market's tick, so a limit is floored (buy) or+ // ceiled (sell) to the cent, which only ever tightens it.+ return Math.round(p * 100) * 10_000;+}++/**+ * Build an order that buys `usd` of one side, never above `maxPrice`.+ * `quoteOnly` asks the venue for its quote without a transaction when the+ * wallet cannot cover it yet (used for previews of an unfunded wallet).+ */+export async function buildOpenOrder({ owner, marketId, side, usd: stakeUsd, maxPrice, quoteOnly = false }) {+ const body = {+ ownerPubkey: owner,+ marketId,+ isYes: side === 'yes',+ isBuy: true,+ depositAmount: String(Math.round(stakeUsd * MICRO)),+ depositMint: SETTLEMENT_MINT,+ maxBuyPriceUsd: String(Math.floor(maxPrice * 100) * 10_000),+ returnQuoteOnInsufficientFunds: quoteOnly,+ };+ return normalizeBuild(await write('/orders', { body }));+}++/** Sell `contracts` of an existing position, never below `minPrice`. */+export async function buildCloseOrder({ owner, positionId, marketId, side, contracts, minPrice }) {+ const body = {+ ownerPubkey: owner,+ positionPubkey: positionId,+ marketId,+ isYes: side === 'yes',+ isBuy: false,+ contractsDecimal: String(contracts),+ minSellPriceUsd: String(Math.max(10_000, priceMicro(Math.ceil(minPrice * 100) / 100))),+ };+ return normalizeBuild(await write('/orders', { body }));+}++/** Claim the payout of a resolved, winning position. */+export async function buildRedeem({ owner, positionId }) {+ const raw = await write(`/positions/${encodeURIComponent(positionId)}/claim`, { body: { ownerPubkey: owner } });+ return {+ transaction: raw.transaction || null,+ required_signers: raw.requiredSigners || [],+ context: raw.execution?.context || { type: 'claim_payout' },+ payout_usd: usd(raw.position?.payoutAmountUsd),+ contracts: Number(raw.position?.contractsDecimal ?? 0),+ quote: null,+ };+}++function normalizeBuild(raw) {+ const o = raw?.order || {};+ return {+ transaction: raw?.transaction || null,+ required_signers: raw?.requiredSigners || [],+ context: raw?.execution?.context || { type: 'create_order' },+ is_gasless: !!raw?.isGasless,+ order_id: o.orderPubkey || null,+ position_id: o.positionPubkey || null,+ quote: {+ contracts: Number(o.contractsDecimal ?? 0),+ cost_usd: usd(o.orderCostUsd),+ avg_price: prob(o.newAvgPriceUsd),+ max_price: prob(o.maxBuyPriceUsd),+ min_price: prob(o.minSellPriceUsd),+ payout_usd: usd(o.payoutUsd),+ fees_usd: usd(o.estimatedTotalFeeUsd),+ slippage_bps: o.slippageBps ?? null,+ max_slippage_bps: o.maxSlippageBps ?? null,+ },+ };+}++/** Submit an owner-signed transaction through the venue executor. */+export async function submit({ signedTransaction, context }) {+ const raw = await write('/execute', { body: { signedTransaction, context } });+ if (raw?.status === 'Success' && raw.signature) return { signature: raw.signature };+ throw new VenueError('execution_failed', raw?.error ? `The venue could not land the transaction: ${raw.error}` : 'The venue could not land the transaction.', {+ status: 502,+ detail: { signature: raw?.signature || null },+ });+}++export const venue = {+ id: VENUE_ID,+ label: VENUE_LABEL,+ chain: 'solana',+ settlement: { asset: 'USDC', mint: SETTLEMENT_MINT, decimals: 6 },+ listEvents,+ listCategories,+ getEvent,+ getMarket,+ getOrderbook,+ getPriceHistory,+ tradingStatus,+ listPositions,+ listFills,+ getOrderStatus,+ buildOpenOrder,+ buildCloseOrder,+ buildRedeem,+ submit,+};diff --git a/api/_lib/predictions/watch.js b/api/_lib/predictions/watch.jsnew file mode 100644index 000000000..db37ada38--- /dev/null+++ b/api/_lib/predictions/watch.js@@ -0,0 +1,124 @@+// Market watches: `market_price` alert rules on one outcome of one market.+//+// A watch is a row in pump_alert_rules (kind 'market_price') so it rides the+// alert system that already exists: the monitor cron evaluates it+// (api/_lib/pump-alert-runner.js), delivery goes to in-app, webhook and+// Telegram (api/_lib/alert-delivery.js), and the rules are listed and edited on+// the notifications settings like every other alert. The rule fires once when+// the side's implied probability crosses the threshold, then re-arms only after+// it crosses back.++import { sql } from '../db.js';+import { randomToken } from '../crypto.js';+import { getVenue, DEFAULT_VENUE, sideProbability } from './index.js';+import { PredictionError } from './engine.js';++const MAX_WATCHES_PER_USER = 50;+const DEFAULT_COOLDOWN_S = 900;+const TELEGRAM_RE = /^(-?\d{1,32}|@[a-zA-Z0-9_]{4,64})$/;++/** Validate a watch request. Pure. Returns the normalized fields or throws PredictionError. */+export function parseWatch(body) {+ const b = body && typeof body === 'object' ? body : {};+ const marketId = typeof b.market_id === 'string' ? b.market_id.trim() : '';+ if (!marketId || marketId.length > 128) throw new PredictionError('invalid_market', 'market_id is required.');+ const side = String(b.side || 'yes').toLowerCase();+ if (side !== 'yes' && side !== 'no') throw new PredictionError('invalid_side', 'side must be "yes" or "no".');+ const direction = String(b.direction || '').toLowerCase();+ if (direction !== 'above' && direction !== 'below') throw new PredictionError('invalid_direction', 'direction must be "above" or "below".');+ const threshold = Number(b.threshold);+ if (!Number.isFinite(threshold) || threshold <= 0 || threshold >= 1) {+ throw new PredictionError('invalid_threshold', 'threshold is an implied probability strictly between 0 and 1 (0.65 means 65%).');+ }+ const cooldown = b.cooldown_seconds == null ? DEFAULT_COOLDOWN_S : Math.round(Number(b.cooldown_seconds));+ if (!Number.isFinite(cooldown) || cooldown < 60 || cooldown > 86_400) throw new PredictionError('invalid_cooldown', 'cooldown_seconds must be between 60 and 86400.');+ const telegram = b.telegram_chat ? String(b.telegram_chat).trim() : null;+ if (telegram && !TELEGRAM_RE.test(telegram)) throw new PredictionError('invalid_telegram', 'telegram_chat must be a numeric chat id or @username.');+ const webhook = b.webhook_url ? String(b.webhook_url).trim() : null;+ if (webhook && (!/^https:\/\//i.test(webhook) || webhook.length > 2048)) throw new PredictionError('invalid_webhook', 'webhook_url must be an https URL.');+ const label = typeof b.label === 'string' && b.label.trim() ? b.label.trim().slice(0, 80) : null;+ return { marketId, side, direction, threshold: Math.round(threshold * 10_000) / 10_000, cooldown, telegram, webhook, label };+}++function serializeWatch(row, market = null) {+ const outcome = market?.outcomes?.find((o) => o.side === row.target_side) || null;+ const current = market ? sideProbability(market, row.target_side) : null;+ return {+ id: row.id,+ market_id: row.target_market,+ side: row.target_side,+ direction: row.direction,+ threshold: Number(row.threshold),+ label: row.label || null,+ enabled: row.enabled,+ cooldown_seconds: row.cooldown_seconds,+ delivery: { in_app: row.deliver_in_app, telegram_chat: row.telegram_chat || null, webhook_url: row.webhook_url || null },+ last_fired_at: row.last_fired_at || null,+ created_at: row.created_at,+ market: market ? { id: market.id, title: market.title, event_id: market.event_id, status: market.status, side_label: outcome?.label || null } : null,+ current_probability: current,+ };+}++export async function createWatch({ agentId, userId, body }) {+ const w = parseWatch(body);+ const venue = getVenue(DEFAULT_VENUE);+ const market = await venue.getMarket(w.marketId);+ const [{ count }] = await sql`SELECT count(*)::int AS count FROM pump_alert_rules WHERE user_id = ${userId}`;+ if (count >= MAX_WATCHES_PER_USER) throw new PredictionError('limit_reached', `You can have at most ${MAX_WATCHES_PER_USER} alert rules. Remove one first.`, 409);+ const outcome = market.outcomes.find((o) => o.side === w.side);+ const label = w.label || `${market.title}: ${outcome?.label || w.side} ${w.direction} ${Math.round(w.threshold * 100)}%`.slice(0, 80);+ const [row] = await sql`+ INSERT INTO pump_alert_rules+ (user_id, kind, target_market, target_side, direction, threshold, target_agent_scope,+ deliver_in_app, webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label)+ VALUES+ (${userId}, 'market_price', ${market.id}, ${w.side}, ${w.direction}, ${w.threshold}, ${agentId},+ true, ${w.webhook}, ${w.webhook ? `whsec_${randomToken(24)}` : null}, ${w.telegram}, ${w.cooldown}, true, ${label})+ RETURNING id, target_market, target_side, direction, threshold, label, enabled, cooldown_seconds,+ deliver_in_app, telegram_chat, webhook_url, created_at+ `;+ // Seed the crossing state from the price right now, so the monitor's next+ // tick fires on a genuine crossing instead of spending a tick learning which+ // side of the line the market started on.+ const now = sideProbability(market, w.side);+ if (now != null) {+ const side = now >= w.threshold ? 'over' : 'under';+ await sql`+ INSERT INTO pump_alert_rule_fires (rule_id, last_state, updated_at)+ VALUES (${row.id}, ${JSON.stringify({ side })}::jsonb, now())+ ON CONFLICT (rule_id) DO NOTHING+ `;+ }+ return serializeWatch({ ...row, last_fired_at: null }, market);+}++export async function listWatches({ agentId, userId }) {+ const rows = await sql`+ SELECT r.id, r.target_market, r.target_side, r.direction, r.threshold, r.label, r.enabled,+ r.cooldown_seconds, r.deliver_in_app, r.telegram_chat, r.webhook_url, r.created_at,+ f.last_fired_at+ FROM pump_alert_rules r+ LEFT JOIN pump_alert_rule_fires f ON f.rule_id = r.id+ WHERE r.user_id = ${userId} AND r.kind = 'market_price'+ AND (${agentId}::uuid IS NULL OR r.target_agent_scope = ${agentId})+ ORDER BY r.created_at DESC+ LIMIT 100+ `;+ const venue = getVenue(DEFAULT_VENUE);+ const markets = new Map();+ await Promise.all([...new Set(rows.map((r) => r.target_market))].map(async (id) => {+ markets.set(id, await venue.getMarket(id).catch(() => null));+ }));+ return rows.map((r) => serializeWatch(r, markets.get(r.target_market)));+}++export async function deleteWatch({ userId, watchId }) {+ const rows = await sql`+ DELETE FROM pump_alert_rules+ WHERE id = ${watchId} AND user_id = ${userId} AND kind = 'market_price'+ RETURNING id+ `;+ if (!rows.length) throw new PredictionError('not_found', 'No watch with that id on your account.', 404);+ return { deleted: true, id: watchId };+}diff --git a/api/predictions/[...path].js b/api/predictions/[...path].jsnew file mode 100644index 000000000..fb7bfd1ff--- /dev/null+++ b/api/predictions/[...path].js@@ -0,0 +1,8 @@+// /api/predictions/* — public prediction-market reads for the /predictions page:+// events, categories, event detail with price history, market detail with the+// order book. Route table: api/_lib/predictions/routes.js. Guide: docs/predictions.md.++import { defineRouter } from '../_lib/agents-v1/http.js';+import { publicRoutes } from '../_lib/predictions/routes.js';++export default defineRouter({ base: '/api', routes: publicRoutes('/predictions') });diff --git a/api/v1/agents/[id]/predictions/[...path].js b/api/v1/agents/[id]/predictions/[...path].jsnew file mode 100644index 000000000..baa90e323--- /dev/null+++ b/api/v1/agents/[id]/predictions/[...path].js@@ -0,0 +1,7 @@+// /api/v1/agents/:id/predictions/* — prediction markets from the agent wallet.+// Route table and behavior: api/_lib/predictions/routes.js. Guide: docs/predictions.md.++import { defineRouter } from '../../../../_lib/agents-v1/http.js';+import { agentRoutes } from '../../../../_lib/predictions/routes.js';++export default defineRouter({ base: '/api/v1', routes: agentRoutes });