Skip to content

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

feat(db): add schemas for destination whitelists, mail controls, EVM launch records, agent self-signup, portfolio snapshots, launch-matched pump alerts and duel challenges

nirholas4ab22e4bff73
diff --git a/api/_lib/migrations/20261010160000_destination_whitelist.sql b/api/_lib/migrations/20261010160000_destination_whitelist.sql
new file mode 100644
index 000000000..3765086c6
--- /dev/null
+++ b/api/_lib/migrations/20261010160000_destination_whitelist.sql
@@ -0,0 +1,145 @@
+-- Migration: the destination whitelist. Every address an agent wallet may send
+-- funds to, with a label, per-destination caps, and a cooldown before a new
+-- address becomes usable, so a stolen session or a prompt-injected agent cannot
+-- add an attacker address and drain the wallet in one minute.
+-- Apply: node scripts/apply-migrations.mjs --apply --file 20261010160000_destination_whitelist.sql
+-- Idempotent.
+--
+-- destination_whitelist_entries
+-- status proposed an agent or API credential asked for the address; it
+-- is inert until the owner approves it with step-up.
+-- pending approved, serving its cooldown. activates_at says
+-- when it becomes usable. The owner can cancel it.
+-- active usable as a destination.
+-- cancelled a pending or proposed entry the owner cancelled.
+-- removed a previously active entry the owner removed.
+-- address_key the comparison key: the canonical form of the address (base58
+-- for Solana, EIP-55 checksummed for EVM) lower-cased for EVM.
+-- Every lookup goes through this column, never the display value.
+-- per_tx_cap_usd / daily_cap_usd
+-- optional ceilings that apply to this destination only, on top
+-- of the agent's global limits.
+-- proposed_by owner (session with step-up) | agent | api_key | oauth |
+-- legacy (grandfathered from meta.spend_limits.withdraw_allowlist).
+--
+-- destination_whitelist_settings
+-- One row per agent. cooldown_seconds is owner-configurable and never below an
+-- hour. enforced says whether outbound sends are restricted to active entries.
+-- A change that LOOSENS protection (a shorter cooldown, turning enforcement
+-- off) is not applied at once: it is parked in pending_change with the time it
+-- takes effect, one full current cooldown away, so an attacker cannot shorten
+-- the cooldown and add an address in the same minute. Tightening is instant.
+--
+-- destination_stepup_grants
+-- A one-time permission to run ONE whitelist operation, minted after the owner
+-- re-authenticates (password, wallet signature or emailed code). Bound to the
+-- session, the user, the agent and a hash of the exact operation, so a grant
+-- for "add address A" can never authorise "add address B". Used once.
+
+create table if not exists destination_whitelist_entries (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ user_id uuid not null,
+ chain text not null check (chain in ('solana', 'evm')),
+ address text not null,
+ address_key text not null,
+ label text,
+ per_tx_cap_usd numeric,
+ daily_cap_usd numeric,
+ status text not null check (status in ('proposed', 'pending', 'active', 'cancelled', 'removed')),
+ proposed_by text not null default 'owner',
+ note text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ approved_at timestamptz,
+ activates_at timestamptz,
+ activated_at timestamptz,
+ cancelled_at timestamptz,
+ removed_at timestamptz
+);
+
+create unique index if not exists destination_whitelist_live_uq
+ on destination_whitelist_entries (agent_id, chain, address_key)
+ where status in ('proposed', 'pending', 'active');
+
+create index if not exists destination_whitelist_agent_idx
+ on destination_whitelist_entries (agent_id, status, created_at desc);
+
+create index if not exists destination_whitelist_due_idx
+ on destination_whitelist_entries (activates_at)
+ where status = 'pending';
+
+create table if not exists destination_whitelist_settings (
+ agent_id uuid primary key references agent_identities(id) on delete cascade,
+ user_id uuid not null,
+ cooldown_seconds integer not null default 86400 check (cooldown_seconds >= 3600),
+ enforced boolean not null default false,
+ pending_change jsonb,
+ updated_at timestamptz not null default now()
+);
+
+create table if not exists destination_stepup_grants (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null,
+ session_id uuid not null,
+ agent_id uuid not null,
+ op_hash text not null,
+ method text not null check (method in ('password', 'wallet', 'email_code')),
+ expires_at timestamptz not null,
+ used_at timestamptz,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists destination_stepup_lookup_idx
+ on destination_stepup_grants (user_id, session_id, op_hash)
+ where used_at is null;
+
+-- One-time email codes for the email_code step-up method. Only the hash is stored.
+create table if not exists destination_stepup_codes (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null,
+ session_id uuid not null,
+ op_hash text not null,
+ code_hash text not null,
+ attempts integer not null default 0,
+ expires_at timestamptz not null,
+ used_at timestamptz,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists destination_stepup_codes_lookup_idx
+ on destination_stepup_codes (user_id, session_id, op_hash)
+ where used_at is null;
+
+-- Grandfather every existing Solana withdraw allowlist: each address becomes an
+-- active entry (no cooldown, the owner already trusted it) and enforcement stays
+-- on, so nothing that was protected becomes less protected.
+insert into destination_whitelist_entries
+ (agent_id, user_id, chain, address, address_key, label, status, proposed_by, approved_at, activates_at, activated_at)
+select a.id, a.user_id, 'solana', e.addr, e.addr, null, 'active', 'legacy', now(), now(), now()
+from agent_identities a
+cross join lateral jsonb_array_elements_text(
+ case when jsonb_typeof(a.meta #> '{spend_limits,withdraw_allowlist}') = 'array'
+ then a.meta #> '{spend_limits,withdraw_allowlist}' else '[]'::jsonb end
+) as e(addr)
+where a.deleted_at is null
+ and length(e.addr) between 32 and 44
+on conflict do nothing;
+
+insert into destination_whitelist_entries
+ (agent_id, user_id, chain, address, address_key, label, status, proposed_by, approved_at, activates_at, activated_at)
+select a.id, a.user_id, 'evm', e.addr, lower(e.addr), null, 'active', 'legacy', now(), now(), now()
+from agent_identities a
+cross join lateral jsonb_array_elements_text(
+ case when jsonb_typeof(a.meta #> '{evm_spend_limits,withdraw_allowlist}') = 'array'
+ then a.meta #> '{evm_spend_limits,withdraw_allowlist}' else '[]'::jsonb end
+) as e(addr)
+where a.deleted_at is null
+ and e.addr ~* '^0x[0-9a-f]{40}$'
+on conflict do nothing;
+
+insert into destination_whitelist_settings (agent_id, user_id, enforced)
+select distinct on (agent_id) agent_id, user_id, true
+from destination_whitelist_entries
+where proposed_by = 'legacy'
+on conflict (agent_id) do nothing;
diff --git a/api/_lib/migrations/20261010184500_agent_mail_controls.sql b/api/_lib/migrations/20261010184500_agent_mail_controls.sql
new file mode 100644
index 000000000..64ff7980f
--- /dev/null
+++ b/api/_lib/migrations/20261010184500_agent_mail_controls.sql
@@ -0,0 +1,67 @@
+-- Agent mail controls: the owner's guardrails and routing rules for an agent's
+-- mailbox (api/_lib/mail/controls.js, api/_lib/mail/rules.js, docs/agent-mail.md).
+--
+-- agent_mail_policies one row per agent. allowlist_enabled restricts
+-- every outbound send to the addresses and @domains in
+-- `allowlist`; daily_send_cap is the owner's own ceiling
+-- on sends per rolling 24 hours, applied on top of the
+-- platform's warm-up limits (null means the warm-up
+-- limit alone). No row means no allowlist and no cap.
+-- agent_mail_rules "when mail arrives from X, do Y". A rule matches on
+-- the sender (an address or an @domain) and optionally
+-- a subject substring. mode 'approve' parks every match
+-- for the owner to approve before anything runs;
+-- mode 'auto' starts an agent run at once. The run uses
+-- the read-only tool registry and receives the message
+-- only as delimited, untrusted data.
+-- agent_mail_rule_events one row per (rule, message) match, so a message never
+-- fires the same rule twice. status tracks the match
+-- from pending through approval or dismissal to the run
+-- it started.
+
+create table if not exists agent_mail_policies (
+ agent_id uuid primary key references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ allowlist_enabled boolean not null default false,
+ allowlist text[] not null default '{}',
+ daily_send_cap integer check (daily_send_cap is null or (daily_send_cap >= 0 and daily_send_cap <= 10000)),
+ updated_at timestamptz not null default now()
+);
+
+create table if not exists agent_mail_rules (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ name text not null,
+ enabled boolean not null default true,
+ match_from text not null,
+ match_subject text,
+ mode text not null default 'approve' check (mode in ('approve', 'auto')),
+ prompt text not null,
+ fire_count integer not null default 0,
+ last_fired_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists agent_mail_rules_agent_idx on agent_mail_rules (agent_id) where enabled;
+
+create table if not exists agent_mail_rule_events (
+ id uuid primary key default gen_random_uuid(),
+ rule_id uuid not null references agent_mail_rules(id) on delete cascade,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ message_id uuid not null references agent_mail_messages(id) on delete cascade,
+ status text not null default 'pending'
+ check (status in ('pending', 'approved', 'dismissed', 'run_started', 'failed')),
+ run_id uuid,
+ error text,
+ created_at timestamptz not null default now(),
+ decided_at timestamptz,
+ unique (rule_id, message_id)
+);
+
+create index if not exists agent_mail_rule_events_agent_idx
+ on agent_mail_rule_events (agent_id, created_at desc);
+create index if not exists agent_mail_rule_events_pending_idx
+ on agent_mail_rule_events (user_id) where status = 'pending';
diff --git a/api/_lib/migrations/20261010190000_evm_launch_records.sql b/api/_lib/migrations/20261010190000_evm_launch_records.sql
new file mode 100644
index 000000000..54bc8ba43
--- /dev/null
+++ b/api/_lib/migrations/20261010190000_evm_launch_records.sql
@@ -0,0 +1,45 @@
+-- Durable record of every EVM launch (paired and Uniswap lanes).
+--
+-- A launch signs several things and takes seconds to minutes, so a client that
+-- times out used to have no way to learn whether the coin exists. Each launch
+-- now writes one row before anything is signed. The row carries the stages the
+-- launch has passed, the transaction hash once sent, and the finished result.
+-- GET /api/launches/:id reads it and settles a launch whose transaction landed
+-- after the request that sent it went away.
+--
+-- `idempotency_key` is the client's Idempotency-Key header. Together with the
+-- caller it is unique, and `fingerprint` (sha256 of the lane and request body)
+-- lets a retry with the same key return the same row while the same key with a
+-- different body is refused. Rows without a key are still recorded.
+--
+-- Service layer: api/_lib/evm-launch-records.js.
+
+CREATE TABLE IF NOT EXISTS evm_launch_records (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id uuid NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ lane text NOT NULL,
+ chain text NOT NULL,
+ idempotency_key text,
+ fingerprint text NOT NULL,
+ status text NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'submitted', 'confirmed', 'finalized', 'failed')),
+ stages jsonb NOT NULL DEFAULT '[]'::jsonb,
+ tx_hash text,
+ token text,
+ result jsonb,
+ error jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS evm_launch_records_user_key
+ ON evm_launch_records (user_id, idempotency_key)
+ WHERE idempotency_key IS NOT NULL;
+
+CREATE INDEX IF NOT EXISTS evm_launch_records_user_created
+ ON evm_launch_records (user_id, created_at DESC, id DESC);
+
+CREATE INDEX IF NOT EXISTS evm_launch_records_open
+ ON evm_launch_records (updated_at)
+ WHERE status IN ('pending', 'submitted', 'confirmed');
diff --git a/api/_lib/migrations/20261010200000_agent_portfolio_snapshots.sql b/api/_lib/migrations/20261010200000_agent_portfolio_snapshots.sql
new file mode 100644
index 000000000..4506f6219
--- /dev/null
+++ b/api/_lib/migrations/20261010200000_agent_portfolio_snapshots.sql
@@ -0,0 +1,30 @@
+-- Agent portfolio snapshots: the time series behind get_balance_history.
+--
+-- getPortfolio (api/_lib/portfolio.js) values an agent wallet live, but nothing
+-- kept the answer, so "how has this agent's net worth moved" had no source.
+-- api/_lib/portfolio-history.js writes one row per agent per network whenever a
+-- valuation is taken (the MCP portfolio tools, the /api/v1/agents/:id/portfolio
+-- route, and the hourly /api/cron/agent-portfolio-snapshots sweep over recently
+-- active agents), throttled to one row per 15 minutes so a polling client cannot
+-- grow the table faster than the cron does.
+--
+-- Values are the real valuation at captured_at: native SOL plus every priceable
+-- SPL holding, realized P&L from the trade ledger, unrealized P&L on open FIFO
+-- lots. Idempotent.
+
+create table if not exists agent_portfolio_snapshots (
+ id bigserial primary key,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ captured_at timestamptz not null default now(),
+ net_worth_sol double precision not null,
+ net_worth_usd double precision,
+ sol_usd double precision,
+ realized_pnl_sol double precision,
+ unrealized_pnl_sol double precision,
+ holdings_count integer not null default 0,
+ source text not null default 'read' check (source in ('read','cron'))
+);
+
+create index if not exists agent_portfolio_snapshots_agent_time
+ on agent_portfolio_snapshots (agent_id, network, captured_at desc);
diff --git a/api/_lib/migrations/20261010200000_agent_self_signup.sql b/api/_lib/migrations/20261010200000_agent_self_signup.sql
new file mode 100644
index 000000000..376d24d54
--- /dev/null
+++ b/api/_lib/migrations/20261010200000_agent_self_signup.sql
@@ -0,0 +1,44 @@
+-- Migration: agent self-signup. An autonomous agent proves it holds an Ed25519
+-- key by signing a payload; the platform creates the agent, its custodial
+-- wallets and a paper-mode account. A human later claims it with a one-time
+-- code. Idempotent.
+--
+-- agent_self_signups
+-- public_key base58 Ed25519 key that signed the signup. One signup per key.
+-- agent_id / user_id the created agent and its placeholder owner row.
+-- api_key_id the key returned once at signup; retired when a human claims.
+-- claim_code_hash sha256 of the one-time claim code (never the code itself).
+-- claimed_at set when a human takes ownership; null while in paper mode.
+--
+-- agent_self_signup_nonces
+-- One row per accepted (public_key, nonce). The primary key is the replay
+-- guard: a second insert of the same pair fails, on every instance, which an
+-- in-memory or per-instance cache cannot promise. Rows are pruned past the
+-- timestamp window.
+
+create table if not exists agent_self_signups (
+ id uuid primary key default gen_random_uuid(),
+ public_key text not null unique,
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ api_key_id uuid,
+ requested_name text not null,
+ signup_ip text,
+ claim_code_hash text not null,
+ claim_expires_at timestamptz not null,
+ claimed_at timestamptz,
+ claimed_by uuid references users(id) on delete set null,
+ created_at timestamptz not null default now()
+);
+
+create unique index if not exists agent_self_signups_agent_uniq on agent_self_signups(agent_id);
+create unique index if not exists agent_self_signups_claim_uniq on agent_self_signups(claim_code_hash);
+
+create table if not exists agent_self_signup_nonces (
+ public_key text not null,
+ nonce text not null,
+ seen_at timestamptz not null default now(),
+ primary key (public_key, nonce)
+);
+
+create index if not exists agent_self_signup_nonces_seen on agent_self_signup_nonces(seen_at);
diff --git a/api/_lib/migrations/20261010200100_pump_alert_launch_match.sql b/api/_lib/migrations/20261010200100_pump_alert_launch_match.sql
new file mode 100644
index 000000000..0cce62f42
--- /dev/null
+++ b/api/_lib/migrations/20261010200100_pump_alert_launch_match.sql
@@ -0,0 +1,26 @@
+-- launch_match alert rules: "tell me when a new launch matches these filters".
+--
+-- pump_alert_rules gains a `filters` jsonb column and a `launch_match` kind.
+-- The pumpfun-monitor runner evaluates launch_match rules against
+-- pump_coin_intel, which scores every new pump.fun launch once its first
+-- observation window closes. Supported filter keys (validated in
+-- api/alerts/_rules.js, matched in api/_lib/pump-alert-eval.js):
+--
+-- name_pattern "|"-separated alternatives, "*" wildcards, matched
+-- case-insensitively against the name or symbol
+-- min_market_cap_usd market cap at first sight, USD
+-- max_market_cap_usd
+-- min_safety_score pump_coin_intel.quality_score, 0 to 100
+-- min_creator_graduated creator's earlier launches that graduated
+-- max_creator_launches creator's earlier launches in total (serial deployers)
+-- exclude_risk_flags drop launches carrying any of these risk flags
+-- require_socials at least one of twitter, telegram, website
+--
+-- Idempotent.
+
+alter table pump_alert_rules add column if not exists filters jsonb;
+
+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', 'launch_match'));
diff --git a/api/_lib/migrations/20261010200200_agent_duel_challenges.sql b/api/_lib/migrations/20261010200200_agent_duel_challenges.sql
new file mode 100644
index 000000000..0c67612d4
--- /dev/null
+++ b/api/_lib/migrations/20261010200200_agent_duel_challenges.sql
@@ -0,0 +1,42 @@
+-- Agent duel challenges: one agent calls out another to a head-to-head.
+--
+-- Trader duels (20260930150000_trader_duels.sql) were generated only by the
+-- rivalry engine. A challenge lets an agent owner pick the opponent: the
+-- challenged agent's owner accepts or declines, and an accepted challenge opens
+-- a regular duel_markets row for the next day or week window, tagged
+-- context.source = 'challenge' so the rivalry generator leaves that window to
+-- it. Resolution, calls and points are the existing free-play duel engine;
+-- no funds move anywhere. Pending challenges expire after 48 hours
+-- (/api/cron/duels-tick). api/_lib/duel-challenges.js owns every read and write.
+-- Idempotent.
+
+create table if not exists agent_duel_challenges (
+ id uuid primary key default gen_random_uuid(),
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ window_kind text not null default 'day' check (window_kind in ('day','week')),
+ challenger_agent uuid not null references agent_identities(id) on delete cascade,
+ challenger_user uuid not null references users(id) on delete cascade,
+ challenged_agent uuid not null references agent_identities(id) on delete cascade,
+ challenged_user uuid not null references users(id) on delete cascade,
+ message text check (message is null or char_length(message) <= 280),
+ status text not null default 'pending'
+ check (status in ('pending','accepted','declined','expired','cancelled')),
+ market_id uuid references duel_markets(id) on delete set null,
+ expires_at timestamptz not null default (now() + interval '48 hours'),
+ created_at timestamptz not null default now(),
+ responded_at timestamptz,
+ check (challenger_agent <> challenged_agent)
+);
+
+-- One live challenge per ordered pair, network and window kind.
+create unique index if not exists agent_duel_challenges_one_pending
+ on agent_duel_challenges (network, window_kind, challenger_agent, challenged_agent)
+ where status = 'pending';
+create index if not exists agent_duel_challenges_challenged
+ on agent_duel_challenges (challenged_user, status, created_at desc);
+create index if not exists agent_duel_challenges_challenger
+ on agent_duel_challenges (challenger_user, status, created_at desc);
+create index if not exists agent_duel_challenges_market
+ on agent_duel_challenges (market_id) where market_id is not null;
+create index if not exists agent_duel_challenges_expiry
+ on agent_duel_challenges (expires_at) where status = 'pending';