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.

12.7 KB
Raw Blame
-- Migration: reputation-gated signal marketplace (x402 paid alpha feeds).
--
-- The first trust-gated copy-trading economy: a trader whose ON-CHAIN track
-- record is verified (api/_lib/trader-stats.js `verified` badge — 12+ closed
-- trades, 5+ coins, ≤40% churn, positive realized SOL, all proven by tx) may
-- publish their real entry/exit fills as an x402-metered signal feed. A
-- follower's agent pays USDC per signal (or per epoch) from its OWN custodial
-- wallet, and auto-mirrors the trade through the SAME firewall + MEV engine +
-- spend guards every other outbound path uses (api/_lib/agent-mirror.js
-- runFollowerTrade). Every emission binds to a real fill and accrues a realized
-- outcome, so the marketplace ranks sellers by PROVEN edge, not follower count.
--
-- Four tables:
--   signal_feeds         — a verified publisher's feed config + pricing.
--   signal_emissions     — one row per published entry/exit, generated from the
--                          publisher's real agent_sniper_positions; realized
--                          outcome backfilled when the source position closes.
--   signal_subscriptions — a follower agent's subscription (mode, sizing, kill).
--   signal_deliveries    — per (subscription, emission): the x402 payment row +
--                          the mirror fill + emit→fill latency = accountability.
--
-- apply-migrations.mjs only runs api/_lib/migrations/*.sql, so the schema lives
-- here. Everything is `if not exists`, safe to re-apply.
begin;

-- ── signal_feeds — a verified trader's published feed ─────────────────────────
-- One row = "publisher_agent_id sells its live signals under owner_user_id's
-- account." Creation is gated in api/signals/feeds.js on the publisher's REAL
-- trader-stats `verified` badge — a feed can never be published by an unproven
-- wallet. payout_address snapshots the publisher agent's Solana USDC receiving
-- address at publish time. The two cursors track how far emission generation has
-- consumed the publisher's position lifecycle (entry = open, exit = close), so a
-- sync pass never re-emits an old fill.
create table if not exists signal_feeds (
    id                     bigserial   primary key,
    publisher_agent_id     uuid        not null references agent_identities(id) on delete cascade,
    owner_user_id          uuid        not null references users(id) on delete cascade,
    network                text        not null default 'mainnet' check (network in ('mainnet','devnet')),
    slug                   text        not null unique,
    title                  text        not null,
    description            text,

    -- Pricing. At least one of the two must be > 0 (enforced in the endpoint).
    -- price_per_signal_usdc bills the subscriber once per delivered emission;
    -- price_per_epoch_usdc bills once per epoch_seconds window (a subscription).
    price_per_signal_usdc  numeric     not null default 0 check (price_per_signal_usdc >= 0),
    price_per_epoch_usdc   numeric     not null default 0 check (price_per_epoch_usdc >= 0),
    epoch_seconds          integer     not null default 86400 check (epoch_seconds >= 3600),

    -- What the feed emits.
    emit_entries           boolean     not null default true,
    emit_exits             boolean     not null default true,
    reveal_sizing          boolean     not null default true,   -- expose size_multiple / entry_sol
    min_conviction         numeric     not null default 0 check (min_conviction >= 0 and min_conviction <= 1),

    visibility             text        not null default 'public' check (visibility in ('public','unlisted')),
    status                 text        not null default 'active' check (status in ('active','paused')),
    payout_address         text        not null,

    -- Emission-generation cursors over the publisher's positions.
    entry_cursor           timestamptz not null default 'epoch',  -- max opened_at emitted as an entry
    exit_cursor            timestamptz not null default 'epoch',  -- max closed_at processed for exits/outcomes

    created_at             timestamptz not null default now(),
    updated_at             timestamptz not null default now(),

    -- A publisher runs at most one feed per agent per network (the product is the
    -- agent's track record; multiple feeds would just fragment it).
    unique (publisher_agent_id, network)
);

create index if not exists signal_feeds_status
    on signal_feeds (network, status) where status = 'active';

-- ── signal_emissions — one published entry/exit, bound to a real fill ─────────
-- Generated by api/_lib/signal-engine.js from agent_sniper_positions: an `entry`
-- the moment a position opens, an `exit` when it closes. The entry row's
-- realized outcome is BACKFILLED when its source position closes, so every entry
-- signal eventually carries a proven realized_pnl_pct + win/loss — this is what
-- the marketplace ranks on. source_buy_sig / source_sell_sig are the on-chain
-- proof that the signal was a real trade, not hand-authored alpha.
create table if not exists signal_emissions (
    id                  bigserial   primary key,
    feed_id             bigint      not null references signal_feeds(id) on delete cascade,
    publisher_agent_id  uuid        not null references agent_identities(id) on delete cascade,
    network             text        not null default 'mainnet',
    source_position_id  uuid        not null,             -- agent_sniper_positions.id

    mint                text        not null,
    symbol              text,
    name                text,
    side                text        not null check (side in ('entry','exit')),

    size_multiple       numeric,                          -- entry size ÷ publisher's typical entry
    conviction          numeric     not null default 0,   -- 0..1, derived from relative bet size
    entry_sol           numeric,                          -- publisher's entry size (SOL), for transparency
    ref_price_lpt       numeric,                          -- entry price (lamports per token)

    status              text        not null default 'open' check (status in ('open','closed')),
    realized_pnl_pct    numeric,                          -- backfilled on close
    realized_pnl_sol    numeric,
    outcome             text        check (outcome in ('win','loss','flat')),

    source_buy_sig      text,
    source_sell_sig     text,
    emitted_at          timestamptz not null default now(),
    closed_at           timestamptz,

    -- One emission per (feed, position, side) — the sync idempotency key.
    unique (feed_id, source_position_id, side)
);

create index if not exists signal_emissions_feed_time
    on signal_emissions (feed_id, id desc);
create index if not exists signal_emissions_outcome
    on signal_emissions (feed_id, side, status) where side = 'entry';

-- ── signal_subscriptions — a follower agent following a feed ──────────────────
-- subscriber_agent_id auto-mirrors feed_id's paid emissions under owner_user_id's
-- spend policy. `mode` simulate mirrors WITHOUT paying or trading (trust-building,
-- clearly labelled); live pays real USDC + mirrors a real trade. `killed` is the
-- instant halt — set true and no further payment or trade ever fires. base_sol ×
-- size_multiple × size_scaling = the mirrored order, hard-capped at
-- max_per_trade_sol and then re-gated by the agent's own trade limits. The cursor
-- last_emission_id ensures a fanout never double-delivers.
create table if not exists signal_subscriptions (
    id                   bigserial   primary key,
    subscriber_agent_id  uuid        not null references agent_identities(id) on delete cascade,
    owner_user_id        uuid        not null references users(id) on delete cascade,
    feed_id              bigint      not null references signal_feeds(id) on delete cascade,
    network              text        not null default 'mainnet' check (network in ('mainnet','devnet')),

    mode                 text        not null default 'simulate' check (mode in ('simulate','live')),
    billing              text        not null default 'per_signal' check (billing in ('per_signal','per_epoch')),

    base_sol             numeric     not null default 0.05 check (base_sol > 0),
    size_scaling         numeric     not null default 1   check (size_scaling > 0),
    max_per_trade_sol    numeric     not null default 0.25 check (max_per_trade_sol > 0),
    slippage_bps         integer     not null default 300 check (slippage_bps >= 0 and slippage_bps <= 5000),
    firewall_level       text        not null default 'block' check (firewall_level in ('warn','block')),
    copy_exits           boolean     not null default true,

    status               text        not null default 'active' check (status in ('active','paused','stopped')),
    killed               boolean     not null default false,
    epoch_paid_until     timestamptz,                     -- per_epoch: paid through this instant
    last_emission_id     bigint      not null default 0,  -- cursor into signal_emissions.id

    created_at           timestamptz not null default now(),
    updated_at           timestamptz not null default now(),

    -- One subscription per (subscriber agent, feed). The subscribe upsert keys here.
    unique (subscriber_agent_id, feed_id),
    -- A subscriber can never follow its own feed (the mirror would be a no-op loop).
    check (subscriber_agent_id <> '00000000-0000-0000-0000-000000000000')
);

create index if not exists signal_subscriptions_feed
    on signal_subscriptions (feed_id, status) where status = 'active';
create index if not exists signal_subscriptions_owner
    on signal_subscriptions (owner_user_id, created_at desc);

-- ── signal_deliveries — per-signal accountability (payment + mirror + latency) ─
-- One row per (subscription, emission): the x402 USDC payment (custody event id +
-- signature, category 'signal'), the mirror fill (the 'trade' custody event from
-- runFollowerTrade), the realized order, and emit→fill latency. signal_realized_pct
-- is copied from the emission's realized outcome when its source position closes,
-- so a feed's avg-follower-ROI rollup is grounded in proven outcomes. Idempotent
-- on (subscription, emission) so a fanout retry never double-pays or double-trades.
create table if not exists signal_deliveries (
    id                     bigserial   primary key,
    subscription_id        bigint      not null references signal_subscriptions(id) on delete cascade,
    emission_id            bigint      not null references signal_emissions(id) on delete cascade,
    feed_id                bigint      not null references signal_feeds(id) on delete cascade,
    subscriber_agent_id    uuid        not null,
    publisher_agent_id     uuid        not null,
    network                text        not null default 'mainnet',
    mode                   text        not null check (mode in ('simulate','live')),
    side                   text        not null check (side in ('entry','exit')),

    -- x402 payment leg.
    payment_status         text        not null default 'none'
                              check (payment_status in ('none','paid','failed','skipped')),
    payment_custody_event_id bigint,
    payment_signature      text,
    payment_usdc           numeric,

    -- Mirror trade leg.
    mirror_status          text        not null default 'pending'
                              check (mirror_status in ('pending','executed','simulated','skipped','failed','unconfirmed')),
    mirror_skip_reason     text,
    mirror_custody_event_id bigint,
    mirror_signature       text,
    order_sol              numeric,
    price_impact_pct       numeric,

    emit_to_fill_ms        bigint,                        -- emission.emitted_at → delivery fill
    signal_realized_pct    numeric,                       -- backfilled from emission outcome on close

    created_at             timestamptz not null default now(),
    updated_at             timestamptz not null default now(),

    unique (subscription_id, emission_id)
);

create index if not exists signal_deliveries_feed_time
    on signal_deliveries (feed_id, created_at desc);
create index if not exists signal_deliveries_sub_time
    on signal_deliveries (subscription_id, created_at desc);
create index if not exists signal_deliveries_emission
    on signal_deliveries (emission_id);

comment on table signal_feeds is
    'Reputation-gated x402 signal feeds. Publish gated on api/_lib/trader-stats.js '
    'verified badge. See api/_lib/signal-engine.js + api/signals/*.';
comment on table signal_emissions is
    'Published entry/exit signals, generated from real agent_sniper_positions; '
    'realized outcome backfilled on close. Ranking source for the marketplace.';

commit;