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(alerts): alert rules can watch a prediction market outcome crossing a probability threshold
nirholasebf0e6d10dd8
diff --git a/api/_lib/alert-delivery.js b/api/_lib/alert-delivery.jsindex c1bbba32d..29f7b9f90 100644--- a/api/_lib/alert-delivery.js+++ b/api/_lib/alert-delivery.js@@ -46,7 +46,7 @@ async function deliverInApp(rule, payload) {try {await sql`insert into user_notifications (user_id, type, payload)- values (${rule.user_id}, 'pump_alert', ${JSON.stringify(payload)}::jsonb)+ values (${rule.user_id}, 'pump_alert', ${JSON.stringify({ ...payload, summary: formatAlertSummary(payload) })}::jsonb)`;return { attempted: true, ok: true, detail: null };} catch (e) {diff --git a/api/_lib/pump-alert-eval.js b/api/_lib/pump-alert-eval.jsindex cfbecac5d..5fd231b30 100644--- a/api/_lib/pump-alert-eval.js+++ b/api/_lib/pump-alert-eval.js@@ -10,9 +10,12 @@* @typedef {Object} AlertRule* @property {string} id* @property {string} user_id- * @property {'graduation'|'price_above'|'price_below'|'whale_buy'|'new_mint'} kind+ * @property {'graduation'|'price_above'|'price_below'|'whale_buy'|'new_mint'|'market_price'} kind* @property {string|null} [target_mint]* @property {string|null} [target_agent]+ * @property {string|null} [target_market] prediction market id (market_price)+ * @property {'yes'|'no'|null} [target_side] outcome side watched (market_price)+ * @property {'above'|'below'|null} [direction] crossing direction (market_price)* @property {number|null} [threshold]* @property {boolean} [deliver_in_app]* @property {string|null} [webhook_url]@@ -27,8 +30,10 @@export const MINT_TARGETED_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy']);/** Kinds that require an agent target. */export const AGENT_TARGETED_KINDS = Object.freeze(['new_mint']);+/** Kinds that watch one outcome of a prediction market. */+export const MARKET_TARGETED_KINDS = Object.freeze(['market_price']);/** Kinds whose threshold is meaningful and must be > 0. */-export const THRESHOLD_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy']);+export const THRESHOLD_KINDS = Object.freeze(['price_above', 'price_below', 'whale_buy', 'market_price']);/*** True when enough wall-clock has passed since the rule last fired.@@ -115,6 +120,34 @@ export function evaluatePriceRule(rule, currentMcapUsd, lastState = {}) {return { fire: false, nextState: { side: 'under' }, reason: 'not_price_rule' };}+/**+ * Edge-triggered evaluation of a prediction-market watch: fires once when the+ * watched side's implied probability crosses `threshold` in `direction`, then+ * re-arms only after it crosses back. Same shape as evaluatePriceRule.+ *+ * @param {AlertRule} rule+ * @param {number|null|undefined} probability current implied probability, 0..1+ * @param {{ side?: 'over'|'under'|null }} [lastState]+ */+export function evaluateMarketPriceRule(rule, probability, lastState = {}) {+ const p = probability == null ? NaN : Number(probability);+ const threshold = Number(rule.threshold);+ if (!Number.isFinite(p) || !Number.isFinite(threshold) || threshold <= 0 || threshold >= 1) {+ return { fire: false, nextState: { side: lastState.side === 'over' ? 'over' : 'under' }, reason: 'no_price' };+ }+ const over = p >= threshold;+ const nextState = { side: /** @type {'over'|'under'} */ (over ? 'over' : 'under') };+ if (rule.direction === 'below') {+ const under = p <= threshold;+ // Seed state from the first reading so a market already below the line+ // when the watch is created does not fire instantly.+ const fire = under && lastState.side === 'over';+ return { fire, nextState: { side: under ? 'under' : 'over' }, reason: under ? 'below_threshold' : 'above_threshold' };+ }+ const fire = over && lastState.side === 'under';+ return { fire, nextState, reason: over ? 'above_threshold' : 'below_threshold' };+}+// ── Payload builders ─────────────────────────────────────────────────────────// Every alert is stored as a `user_notifications` row of type 'pump_alert' with// a payload shaped consistently across kinds so the dashboard renders them@@ -190,6 +223,28 @@ export function buildPricePayload(rule, token) {};}+/**+ * @param {AlertRule} rule+ * @param {{ id: string, title?: string, event_id?: string|null, side_label?: string|null, probability: number }} m+ */+export function buildMarketPricePayload(rule, m) {+ return {+ kind: 'market_price',+ rule_id: rule.id,+ event_id: `market_price:${rule.id}:${Math.floor(Date.now() / 60_000)}`,+ market_id: m.id,+ market_title: m.title || null,+ prediction_event_id: m.event_id || null,+ side: rule.target_side || 'yes',+ side_label: m.side_label || null,+ direction: rule.direction || 'above',+ threshold: Number(rule.threshold),+ probability: Number(m.probability),+ link: m.event_id ? `/predictions?event=${encodeURIComponent(m.event_id)}&market=${encodeURIComponent(m.id)}` : '/predictions',+ at: iso(Date.now()),+ };+}+/*** Human-readable one-line summary used for the Telegram message and as the* in-app feed title.@@ -214,6 +269,11 @@ export function formatAlertSummary(p) {return `📈 ${tok} mcap rose above ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;case 'price_below':return `📉 ${tok} mcap fell below ${usd(p.threshold_usd)} (now ${usd(p.market_cap_usd)})`;+ case 'market_price': {+ const pct = (n) => `${(Number(n) * 100).toFixed(1).replace(/\.0$/, '')}%`;+ const side = p.side_label || (p.side === 'no' ? 'No' : 'Yes');+ return `${p.direction === 'below' ? '📉' : '📈'} ${p.market_title || 'Market'}: ${side} ${p.direction === 'below' ? 'fell below' : 'rose above'} ${pct(p.threshold)} (now ${pct(p.probability)})`;+ }default:return `🔔 ${tok} alert`;}@@ -237,6 +297,8 @@ export function deriveRuleLabel(rule) {return `Mcap above $${rule.threshold} · ${target}`;case 'price_below':return `Mcap below $${rule.threshold} · ${target}`;+ case 'market_price':+ return `${rule.target_side === 'no' ? 'No' : 'Yes'} ${rule.direction === 'below' ? 'below' : 'above'} ${Math.round(Number(rule.threshold) * 100)}% · ${rule.target_market || 'market'}`;default:return 'Alert';}diff --git a/api/_lib/pump-alert-runner.js b/api/_lib/pump-alert-runner.jsindex 5d2b1ef2a..8b6a069b5 100644--- a/api/_lib/pump-alert-runner.js+++ b/api/_lib/pump-alert-runner.js@@ -12,6 +12,7 @@// new_mint → pump_agent_mints (a tracked agent's new coins)// price_* → pump.fun coins API (authoritative USD market cap)// whale_buy → pump.fun trades API (recent buys on the target mint)+// market_price → the prediction venue's live market price (api/_lib/predictions/)import { sql } from './db.js';import {@@ -20,6 +21,8 @@ import {newMintMatchesRule,isWhaleBuy,evaluatePriceRule,+ evaluateMarketPriceRule,+ buildMarketPricePayload,buildGraduationPayload,buildNewMintPayload,buildWhalePayload,@@ -27,6 +30,7 @@ import {} from './pump-alert-eval.js';import { deliverAlert } from './alert-delivery.js';import { solPriceUsd as sharedSolPriceUsd } from './sol-price.js';+import { getVenue, sideProbability } from './predictions/index.js';const GRAD_WINDOW = '15 minutes';const NEW_MINT_WINDOW = '60 minutes';@@ -34,6 +38,7 @@ const GRADS_PER_RUN = 100;const DELIVER_CAP = 5; // max events delivered per rule per run (storm guard)const MAX_PRICE_MINTS = 60; // distinct mints priced per runconst MAX_WHALE_MINTS = 60; // distinct mints polled for trades per run+const MAX_MARKETS = 120; // distinct prediction markets priced per runconst TRADES_LIMIT = 50;const FETCH_TIMEOUT_MS = 2_500;@@ -51,7 +56,7 @@ export async function runPumpAlertRules(now = Date.now()) {fired: 0,deliveries: { in_app: 0, webhook: 0, telegram: 0 },failures: { in_app: 0, webhook: 0, telegram: 0 },- capped: { price_mints: false, whale_mints: false },+ capped: { price_mints: false, whale_mints: false, markets: false },errors: 0,};@@ -59,7 +64,7 @@ export async function runPumpAlertRules(now = Date.now()) {let rules;try {rules = await sql`- SELECT id, user_id, kind, target_mint, target_agent, threshold,+ SELECT id, user_id, kind, target_mint, target_agent, target_market, target_side, direction, threshold,deliver_in_app, webhook_url, webhook_secret, telegram_chat,cooldown_seconds, enabled, labelFROM pump_alert_rules@@ -84,12 +89,13 @@ export async function runPumpAlertRules(now = Date.now()) {const fireState = new Map(fireRows.map((f) => [f.rule_id, f]));// Partition rules by kind.- const byKind = { graduation: [], new_mint: [], price: [], whale_buy: [] };+ const byKind = { graduation: [], new_mint: [], price: [], whale_buy: [], market_price: [] };for (const r of rules) {if (r.kind === 'graduation') byKind.graduation.push(r);else if (r.kind === 'new_mint') byKind.new_mint.push(r);else if (r.kind === 'price_above' || r.kind === 'price_below') byKind.price.push(r);else if (r.kind === 'whale_buy') byKind.whale_buy.push(r);+ else if (r.kind === 'market_price') byKind.market_price.push(r);}const ctx = { now, solPrice: 0 };@@ -99,6 +105,7 @@ export async function runPumpAlertRules(now = Date.now()) {runNewMintRules(byKind.new_mint, fireState, report, ctx).catch((e) => bumpErr(report, e)),runPriceRules(byKind.price, fireState, report, ctx).catch((e) => bumpErr(report, e)),runWhaleRules(byKind.whale_buy, fireState, report, ctx).catch((e) => bumpErr(report, e)),+ runMarketPriceRules(byKind.market_price, fireState, report, ctx).catch((e) => bumpErr(report, e)),]);await pruneDeliveries();@@ -237,6 +244,41 @@ async function runWhaleRules(rules, fireState, report, ctx) {}}+// ── prediction-market watches (implied probability crossing) ─────────────────++async function runMarketPriceRules(rules, fireState, report, ctx) {+ if (!rules.length) return;+ let ids = [...new Set(rules.map((r) => r.target_market).filter(Boolean))];+ if (ids.length > MAX_MARKETS) {+ report.capped.markets = ids.length;+ console.warn(`[pump-alerts] market rules: ${ids.length} markets exceeds cap ${MAX_MARKETS}; pricing first ${MAX_MARKETS}`);+ ids = ids.slice(0, MAX_MARKETS);+ }+ const venue = getVenue();+ const markets = new Map();+ await Promise.all(ids.map(async (id) => {+ markets.set(id, await venue.getMarket(id).catch(() => null));+ }));++ for (const rule of rules) {+ report.evaluated++;+ const market = markets.get(rule.target_market);+ if (!market) continue;+ const probability = sideProbability(market, rule.target_side || 'yes');+ const fs = fireState.get(rule.id);+ const { fire, nextState } = evaluateMarketPriceRule(rule, probability, fs?.last_state || {});+ if (!fire || !cooldownElapsed(fs?.last_fired_at, rule.cooldown_seconds, ctx.now)) {+ await upsertFire(rule.id, { last_state: nextState });+ continue;+ }+ const outcome = market.outcomes.find((o) => o.side === (rule.target_side || 'yes'));+ const payload = buildMarketPricePayload(rule, { id: market.id, title: market.title, event_id: market.event_id, side_label: outcome?.label || null, probability });+ await deliverOne(rule, payload, report);+ await upsertFire(rule.id, { last_fired_at: new Date(ctx.now), last_event_id: payload.event_id, last_state: nextState });+ report.fired++;+ }+}+// ── generic event delivery (graduation / new_mint / whale) ─────────────────────/**@@ -355,7 +397,7 @@ async function fetchCoin(mint) {* Recent trades for a mint, newest-first, normalized to* { signature, is_buy, sol_amount (SOL), sol_value_usd, buyer, ts }.*/-async function fetchRecentTrades(mint, solPrice = 0) {+export async function fetchRecentTrades(mint, solPrice = 0) {const d = await fetchJsonWithTimeout(`${PUMPFUN_TRADES_API}/${encodeURIComponent(mint)}?limit=${TRADES_LIMIT}&offset=0`);if (!Array.isArray(d)) return [];return d.map((t) => {diff --git a/api/alerts/_rules.js b/api/alerts/_rules.jsindex bd8bc92c6..b42545dab 100644--- a/api/alerts/_rules.js+++ b/api/alerts/_rules.js@@ -4,9 +4,9 @@import { z } from 'zod';import { isValidSolanaAddress, isUuid } from '../_lib/validate.js';-import { MINT_TARGETED_KINDS, AGENT_TARGETED_KINDS, THRESHOLD_KINDS, deriveRuleLabel } from '../_lib/pump-alert-eval.js';+import { MINT_TARGETED_KINDS, AGENT_TARGETED_KINDS, MARKET_TARGETED_KINDS, THRESHOLD_KINDS, deriveRuleLabel } from '../_lib/pump-alert-eval.js';-export const RULE_KINDS = ['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint'];+export const RULE_KINDS = ['graduation', 'price_above', 'price_below', 'whale_buy', 'new_mint', 'market_price'];const telegramChat = z.string()@@ -43,6 +43,16 @@ const baseShape = {.refine((v) => isUuid(v), 'target_agent must be a UUID').nullable().optional(),+ // market_price: one outcome of one prediction market (api/_lib/predictions/).+ target_market: z+ .string()+ .trim()+ .max(128)+ .regex(/^[A-Za-z0-9._:-]+$/, 'target_market is not a valid market id')+ .nullable()+ .optional(),+ target_side: z.enum(['yes', 'no']).nullable().optional(),+ direction: z.enum(['above', 'below']).nullable().optional(),threshold: z.coerce.number().positive().max(1e15).nullable().optional(),deliver_in_app: z.boolean().optional(),webhook_url: nullableUrl.optional(),@@ -56,6 +66,22 @@ const baseShape = {function refineRule(v, ctx) {const mintTargeted = MINT_TARGETED_KINDS.includes(v.kind);const agentTargeted = AGENT_TARGETED_KINDS.includes(v.kind);+ const marketTargeted = MARKET_TARGETED_KINDS.includes(v.kind);++ if (marketTargeted) {+ if (!v.target_market) {+ ctx.addIssue({ code: 'custom', path: ['target_market'], message: `${v.kind} requires a target_market` });+ }+ if (!v.target_side) {+ ctx.addIssue({ code: 'custom', path: ['target_side'], message: `${v.kind} requires a target_side of yes or no` });+ }+ if (!v.direction) {+ ctx.addIssue({ code: 'custom', path: ['direction'], message: `${v.kind} requires a direction of above or below` });+ }+ if (Number(v.threshold) >= 1) {+ ctx.addIssue({ code: 'custom', path: ['threshold'], message: `${v.kind} threshold is a probability below 1 (0.65 means 65%)` });+ }+ }if (mintTargeted) {if (!v.target_mint) {@@ -117,6 +143,9 @@ export function validateUpdate(current, patch) {kind: patch.kind ?? current.kind,target_mint: 'target_mint' in patch ? patch.target_mint : current.target_mint,target_agent: 'target_agent' in patch ? patch.target_agent : current.target_agent,+ target_market: 'target_market' in patch ? patch.target_market : current.target_market,+ target_side: 'target_side' in patch ? patch.target_side : current.target_side,+ direction: 'direction' in patch ? patch.direction : current.direction,threshold: 'threshold' in patch ? patch.threshold : current.threshold,deliver_in_app: 'deliver_in_app' in patch ? patch.deliver_in_app : current.deliver_in_app,webhook_url: 'webhook_url' in patch ? patch.webhook_url : current.webhook_url,@@ -154,6 +183,11 @@ export function normalizeForKind(v) {if (!THRESHOLD_KINDS.includes(out.kind)) out.threshold = null;if (!MINT_TARGETED_KINDS.includes(out.kind) && out.kind !== 'graduation') out.target_mint = null;if (!AGENT_TARGETED_KINDS.includes(out.kind) && out.kind !== 'graduation') out.target_agent = null;+ if (!MARKET_TARGETED_KINDS.includes(out.kind)) {+ out.target_market = null;+ out.target_side = null;+ out.direction = null;+ }if (out.deliver_in_app === undefined) out.deliver_in_app = true;if (out.cooldown_seconds === undefined) out.cooldown_seconds = 300;if (out.enabled === undefined) out.enabled = true;@@ -167,6 +201,9 @@ export function serializeRule(row) {kind: row.kind,target_mint: row.target_mint || null,target_agent: row.target_agent || null,+ target_market: row.target_market || null,+ target_side: row.target_side || null,+ direction: row.direction || null,threshold: row.threshold != null ? Number(row.threshold) : null,deliver_in_app: row.deliver_in_app,webhook_url: row.webhook_url || null,diff --git a/api/alerts/rules.js b/api/alerts/rules.jsindex d7cb8dc3e..b2866335d 100644--- a/api/alerts/rules.js+++ b/api/alerts/rules.js@@ -55,14 +55,17 @@ export default wrap(async (req, res) => {const [row] = await sql`INSERT INTO pump_alert_rules- (user_id, kind, target_mint, target_agent, threshold, deliver_in_app,+ (user_id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, deliver_in_app,webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, label)VALUES(${user.id}, ${body.kind}, ${body.target_mint || null}, ${body.target_agent || null},+ ${body.target_market || null}, ${body.target_side || null}, ${body.direction || null},${body.threshold ?? null}, ${body.deliver_in_app}, ${body.webhook_url || null},${webhookSecret}, ${body.telegram_chat || null}, ${body.cooldown_seconds},${body.enabled}, ${body.label || null})- RETURNING id, kind, target_mint, target_agent, threshold, deliver_in_app,+ RETURNING id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, deliver_in_app,webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled,label, created_at, updated_at`;@@ -95,7 +98,8 @@ async function healWebhookSecrets(rows) {async function listRules(userId) {return sql`- SELECT r.id, r.kind, r.target_mint, r.target_agent, r.threshold,+ SELECT r.id, r.kind, r.target_mint, r.target_agent, r.target_market, r.target_side,+ r.direction, r.threshold,r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,f.last_fired_at,diff --git a/api/alerts/rules/[id].js b/api/alerts/rules/[id].jsindex a30a6f960..dae9c0c36 100644--- a/api/alerts/rules/[id].js+++ b/api/alerts/rules/[id].js@@ -37,7 +37,8 @@ export default wrap(async (req, res) => {// PATCHconst [current] = await sql`- SELECT id, kind, target_mint, target_agent, threshold, deliver_in_app,+ SELECT id, kind, target_mint, target_agent, target_market, target_side, direction,+ threshold, deliver_in_app,webhook_url, webhook_secret, telegram_chat, cooldown_seconds, enabled, labelFROM pump_alert_rulesWHERE id = ${id} AND user_id = ${user.id}@@ -67,6 +68,9 @@ export default wrap(async (req, res) => {kind = ${next.kind},target_mint = ${next.target_mint || null},target_agent = ${next.target_agent || null},+ target_market = ${next.target_market || null},+ target_side = ${next.target_side || null},+ direction = ${next.direction || null},threshold = ${next.threshold ?? null},deliver_in_app = ${next.deliver_in_app},webhook_url = ${next.webhook_url || null},@@ -80,7 +84,8 @@ export default wrap(async (req, res) => {`;const [row] = await sql`- SELECT r.id, r.kind, r.target_mint, r.target_agent, r.threshold,+ SELECT r.id, r.kind, r.target_mint, r.target_agent, r.target_market, r.target_side,+ r.direction, r.threshold,r.deliver_in_app, r.webhook_url, r.webhook_secret, r.telegram_chat,r.cooldown_seconds, r.enabled, r.label, r.created_at, r.updated_at,f.last_fired_at,diff --git a/src/notifications.js b/src/notifications.jsindex 2d58fcfc5..df167a956 100644--- a/src/notifications.js+++ b/src/notifications.js@@ -173,6 +173,8 @@ export function notifLabel(n) {// The store already wrote the line for this status, so the bell reads// exactly what the order timeline says rather than a second wording of it.return p.message || `Your print order was updated${p.status ? `: ${String(p.status).replace(/_/g, ' ')}` : ''}`;+ case 'pump_alert':+ return p.summary || 'An alert rule fired';case 'royalty_paid':return p.usd? `${p.actor || 'A fork of your avatar'} paid you $${Number(p.usd).toFixed(3)} in royalties`