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(wallet-transactions): Implement wallet provider store and transaction approval modal

nirholas58378cac26ed
diff --git a/api/_lib/fee.js b/api/_lib/fee.js
new file mode 100644
index 000000000..43ed8d5c7
--- /dev/null
+++ b/api/_lib/fee.js
@@ -0,0 +1,10 @@
+const FEE_BPS = parseInt(process.env.PLATFORM_FEE_BPS ?? '250', 10);
+
+export function getFeeBps() {
+ return FEE_BPS;
+}
+
+export function calculateFee(grossAmount) {
+ const fee = Math.floor((grossAmount * FEE_BPS) / 10_000);
+ return { fee, net: grossAmount - fee };
+}
diff --git a/api/_lib/migrations/2026-04-30-agent-monetization.sql b/api/_lib/migrations/2026-04-30-agent-monetization.sql
new file mode 100644
index 000000000..3b8efe825
--- /dev/null
+++ b/api/_lib/migrations/2026-04-30-agent-monetization.sql
@@ -0,0 +1,78 @@
+-- Migration: agent monetization tables.
+--
+-- Adds:
+-- • agent_skill_prices — per-skill pricing set by agent owner
+-- • agent_revenue_events — immutable earnings record per consumed payment
+-- • agent_payout_wallets — owner wallet addresses for receiving revenue
+-- • agent_withdrawals — payout requests from agent owners
+
+begin;
+
+create table if not exists agent_skill_prices (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id) on delete cascade,
+ skill text not null,
+ currency_mint text not null,
+ chain text not null default 'solana',
+ amount bigint not null,
+ is_active boolean not null default true,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ unique (agent_id, skill)
+);
+
+create index if not exists agent_skill_prices_agent_id
+ on agent_skill_prices (agent_id);
+
+create table if not exists agent_revenue_events (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id),
+ intent_id text not null references agent_payment_intents(id),
+ skill text not null,
+ gross_amount bigint not null,
+ fee_amount bigint not null,
+ net_amount bigint not null,
+ currency_mint text not null,
+ chain text not null,
+ payer_address text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists agent_revenue_events_agent_created
+ on agent_revenue_events (agent_id, created_at desc);
+
+create index if not exists agent_revenue_events_intent_id
+ on agent_revenue_events (intent_id);
+
+create table if not exists agent_payout_wallets (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ agent_id uuid references agent_identities(id) on delete set null,
+ address text not null,
+ chain text not null default 'solana',
+ is_default boolean not null default false,
+ created_at timestamptz not null default now(),
+ unique (user_id, agent_id, chain)
+);
+
+create index if not exists agent_payout_wallets_user_id
+ on agent_payout_wallets (user_id);
+
+create table if not exists agent_withdrawals (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id),
+ agent_id uuid references agent_identities(id),
+ amount bigint not null,
+ currency_mint text not null,
+ chain text not null,
+ to_address text not null,
+ status text not null default 'pending',
+ tx_signature text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists agent_withdrawals_user_status
+ on agent_withdrawals (user_id, status);
+
+commit;
diff --git a/api/_lib/migrations/2026-04-30-notifications.sql b/api/_lib/migrations/2026-04-30-notifications.sql
new file mode 100644
index 000000000..5da6e06fd
--- /dev/null
+++ b/api/_lib/migrations/2026-04-30-notifications.sql
@@ -0,0 +1,20 @@
+-- Migration: user notifications table.
+--
+-- Stores in-app notifications for agent owners (payment received, withdrawal
+-- completed/failed). Fire-and-forget inserts; failures are logged not thrown.
+
+begin;
+
+create table if not exists user_notifications (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid not null references users(id) on delete cascade,
+ type text not null,
+ payload jsonb not null default '{}',
+ read_at timestamptz,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists user_notifications_user_unread
+ on user_notifications (user_id, read_at, created_at desc);
+
+commit;
diff --git a/api/_lib/migrations/2026-04-30-skills-marketplace.sql b/api/_lib/migrations/2026-04-30-skills-marketplace.sql
new file mode 100644
index 000000000..a8d67926f
--- /dev/null
+++ b/api/_lib/migrations/2026-04-30-skills-marketplace.sql
@@ -0,0 +1,303 @@
+-- Migration: skills marketplace tables.
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-04-30-skills-marketplace.sql
+
+-- ── marketplace_skills ───────────────────────────────────────────────────────
+create table marketplace_skills (
+ id uuid primary key default gen_random_uuid(),
+ author_id uuid references users(id) on delete set null,
+ name text not null,
+ slug text not null unique,
+ description text not null,
+ category text not null default 'general',
+ schema_json jsonb not null,
+ tags text[] not null default '{}',
+ is_public boolean not null default true,
+ install_count integer not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index marketplace_skills_category_idx on marketplace_skills(category);
+create index marketplace_skills_author_idx on marketplace_skills(author_id);
+create index marketplace_skills_popular_idx on marketplace_skills(install_count desc);
+create index marketplace_skills_new_idx on marketplace_skills(created_at desc);
+
+-- ── skill_installs ───────────────────────────────────────────────────────────
+create table skill_installs (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid references users(id) on delete cascade,
+ skill_id uuid references marketplace_skills(id) on delete cascade,
+ installed_at timestamptz not null default now(),
+ unique (user_id, skill_id)
+);
+
+create index skill_installs_user_idx on skill_installs(user_id);
+
+-- ── skill_ratings ────────────────────────────────────────────────────────────
+create table skill_ratings (
+ id uuid primary key default gen_random_uuid(),
+ user_id uuid references users(id) on delete cascade,
+ skill_id uuid references marketplace_skills(id) on delete cascade,
+ rating smallint not null check (rating between 1 and 5),
+ created_at timestamptz not null default now(),
+ unique (user_id, skill_id)
+);
+
+-- ── updated_at trigger ───────────────────────────────────────────────────────
+do $$ begin
+ create trigger marketplace_skills_set_updated_at before update on marketplace_skills
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- ── seed data — system skills translated from chat/src/tools.js curatedToolPacks ──
+insert into marketplace_skills (author_id, name, slug, description, category, schema_json, tags, is_public) values
+
+(
+ null,
+ 'TradingView Charts',
+ 'tradingview-charts',
+ 'Display interactive TradingView price charts for any symbol.',
+ 'finance',
+ $json$[
+ {
+ "clientDefinition": {
+ "id": "tradingview-chart-001",
+ "name": "TradingViewChart",
+ "description": "Displays an interactive TradingView chart for a given symbol.",
+ "arguments": [
+ {"name": "symbol", "type": "string", "description": "Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL"},
+ {"name": "interval", "type": "string", "description": "Chart interval: 1, 5, 15, 30, 60, D, W, M"},
+ {"name": "theme", "type": "string", "description": "light or dark"}
+ ],
+ "body": "const symbol = args.symbol || 'BINANCE:BTCUSDT';\nconst interval = args.interval || 'D';\nconst theme = args.theme || 'light';\nconst html = `<!DOCTYPE html><html><head><style>html,body{margin:0;padding:0;height:100%;overflow:hidden}</style></head><body><div id=\"tv_chart\" style=\"width:100%;height:100vh\"></div><script src=\"https://s3.tradingview.com/tv.js\"><\\/script><script>new TradingView.widget({container_id:\"tv_chart\",symbol:${JSON.stringify(symbol)},interval:${JSON.stringify(interval)},theme:${JSON.stringify(theme)},style:\"1\",width:\"100%\",height:\"100%\",toolbar_bg:\"#f1f3f6\",hide_side_toolbar:false,allow_symbol_change:true});<\\/script></body></html>`;\nreturn { contentType: 'text/html', content: html };"
+ },
+ "type": "function",
+ "function": {
+ "name": "TradingViewChart",
+ "description": "Display an interactive TradingView chart. Use for any request to show a price chart, candlestick chart, or market data visualization.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "symbol": {"type": "string", "description": "Trading symbol e.g. BINANCE:BTCUSDT, NASDAQ:AAPL, FX:EURUSD"},
+ "interval": {"type": "string", "enum": ["1","5","15","30","60","D","W","M"], "description": "Chart interval"},
+ "theme": {"type": "string", "enum": ["light","dark"], "description": "Chart theme"}
+ },
+ "required": ["symbol"]
+ }
+ }
+ }
+ ]$json$::jsonb,
+ '{charts,finance,tradingview}',
+ true
+),
+
+(
+ null,
+ 'Web Search',
+ 'web-search',
+ 'Search the web via DuckDuckGo and return a summary and top results.',
+ 'utilities',
+ $json$[
+ {
+ "clientDefinition": {
+ "id": "pack-websearch-001",
+ "name": "WebSearch",
+ "description": "Search the web via DuckDuckGo.",
+ "arguments": [
+ {"name": "query", "type": "string", "description": "Search query"}
+ ],
+ "body": "const res = await fetch('https://api.duckduckgo.com/?q=' + encodeURIComponent(args.query) + '&format=json&no_html=1');\nconst d = await res.json();\nconst topics = (d.RelatedTopics || []).slice(0, 3).map(t => t.Text).filter(Boolean);\nreturn JSON.stringify({ abstract: d.AbstractText || '', topics });"
+ },
+ "type": "function",
+ "function": {
+ "name": "WebSearch",
+ "description": "Search the web via DuckDuckGo and return an abstract and top related topics.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "query": {"type": "string", "description": "Search query"}
+ },
+ "required": ["query"]
+ }
+ }
+ }
+ ]$json$::jsonb,
+ '{search,web,utilities}',
+ true
+),
+
+(
+ null,
+ 'Date & Time',
+ 'date-time',
+ 'Get the current time and timezone.',
+ 'utilities',
+ $json$[
+ {
+ "clientDefinition": {
+ "id": "pack-datetime-001",
+ "name": "GetCurrentTime",
+ "description": "Returns the current date and time as an ISO string.",
+ "arguments": [],
+ "body": "return new Date().toISOString();"
+ },
+ "type": "function",
+ "function": {
+ "name": "GetCurrentTime",
+ "description": "Returns the current date and time as an ISO 8601 string.",
+ "parameters": {"type": "object", "properties": {}}
+ }
+ },
+ {
+ "clientDefinition": {
+ "id": "pack-datetime-002",
+ "name": "GetTimezone",
+ "description": "Returns the user's current timezone.",
+ "arguments": [],
+ "body": "return Intl.DateTimeFormat().resolvedOptions().timeZone;"
+ },
+ "type": "function",
+ "function": {
+ "name": "GetTimezone",
+ "description": "Returns the user's current IANA timezone string.",
+ "parameters": {"type": "object", "properties": {}}
+ }
+ }
+ ]$json$::jsonb,
+ '{time,date,utilities}',
+ true
+),
+
+(
+ null,
+ 'Wallet Transactions',
+ 'wallet-transactions',
+ 'Send and swap tokens on Solana and EVM chains directly from chat. Supports SOL, SPL tokens, ETH, ERC20, and DEX swaps via Jupiter and 1inch.',
+ 'crypto',
+ $json$[
+ {
+ "clientDefinition": {
+ "id": "solana-transfer-013",
+ "name": "solana_transfer",
+ "description": "Send SOL or a Solana SPL token (e.g. USDC) to a recipient address. Requires a connected Solana wallet.",
+ "arguments": [
+ {"name": "recipient", "type": "string", "description": "Base58 recipient wallet address"},
+ {"name": "amount", "type": "number", "description": "Amount to send in human-readable units (e.g. 1.5 for 1.5 SOL)"},
+ {"name": "token", "type": "string", "description": "Token to send: SOL or an SPL mint address. Default: SOL"},
+ {"name": "memo", "type": "string", "description": "Optional memo string to attach"},
+ {"name": "network", "type": "string", "description": "mainnet or devnet. Default: mainnet"}
+ ],
+ "body": "// see chat/src/tools.js → walletToolSchema solana_transfer"
+ },
+ "type": "function",
+ "function": {
+ "name": "solana_transfer",
+ "description": "Send SOL or SPL tokens on Solana. Requires a connected Solana wallet.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "recipient": {"type": "string", "description": "Base58 recipient wallet address"},
+ "amount": {"type": "number", "description": "Amount in human-readable units"},
+ "token": {"type": "string", "description": "SOL or SPL mint address. Default: SOL"},
+ "memo": {"type": "string", "description": "Optional memo"},
+ "network": {"type": "string", "enum": ["mainnet","devnet"], "description": "Default: mainnet"}
+ },
+ "required": ["recipient", "amount"]
+ }
+ }
+ },
+ {
+ "clientDefinition": {
+ "id": "solana-swap-014",
+ "name": "solana_swap",
+ "description": "Swap tokens on Solana via Jupiter aggregator. Finds the best route automatically. Requires a connected Solana wallet.",
+ "arguments": [
+ {"name": "inputMint", "type": "string", "description": "Mint address of the token to sell"},
+ {"name": "outputMint", "type": "string", "description": "Mint address of the token to buy"},
+ {"name": "amount", "type": "number", "description": "Amount of input token in human-readable units"},
+ {"name": "slippageBps", "type": "number", "description": "Max slippage in basis points (100 = 1%). Default: 50"}
+ ],
+ "body": "// see chat/src/tools.js → walletToolSchema solana_swap"
+ },
+ "type": "function",
+ "function": {
+ "name": "solana_swap",
+ "description": "Swap tokens on Solana via Jupiter. Best-route aggregation.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "inputMint": {"type": "string", "description": "Mint address of token to sell"},
+ "outputMint": {"type": "string", "description": "Mint address of token to buy"},
+ "amount": {"type": "number", "description": "Amount of input token in human-readable units"},
+ "slippageBps": {"type": "number", "description": "Max slippage in bps. Default: 50"}
+ },
+ "required": ["inputMint", "outputMint", "amount"]
+ }
+ }
+ },
+ {
+ "clientDefinition": {
+ "id": "evm-transfer-015",
+ "name": "evm_transfer",
+ "description": "Send ETH or an ERC20 token to a recipient address on any EVM chain. Requires a connected EVM wallet.",
+ "arguments": [
+ {"name": "recipient", "type": "string", "description": "0x recipient address"},
+ {"name": "amount", "type": "string", "description": "Amount in human-readable units (e.g. 0.01 for 0.01 ETH)"},
+ {"name": "token", "type": "string", "description": "ETH for native token, or an ERC20 contract address. Default: ETH"},
+ {"name": "decimals", "type": "number", "description": "Token decimals (required for ERC20, ignored for ETH). Default: 18"}
+ ],
+ "body": "// see chat/src/tools.js → walletToolSchema evm_transfer"
+ },
+ "type": "function",
+ "function": {
+ "name": "evm_transfer",
+ "description": "Send ETH or ERC20 tokens on any EVM chain (Ethereum, Base, Optimism, Arbitrum, Polygon).",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "recipient": {"type": "string", "description": "0x recipient address"},
+ "amount": {"type": "string", "description": "Amount in human-readable units"},
+ "token": {"type": "string", "description": "ETH or ERC20 contract address. Default: ETH"},
+ "decimals": {"type": "number", "description": "ERC20 decimals. Default: 18"}
+ },
+ "required": ["recipient", "amount"]
+ }
+ }
+ },
+ {
+ "clientDefinition": {
+ "id": "evm-swap-016",
+ "name": "evm_swap",
+ "description": "Swap tokens on EVM chains using 1inch aggregator. Finds best DEX route. Requires a connected EVM wallet.",
+ "arguments": [
+ {"name": "fromToken", "type": "string", "description": "Token contract address to sell (use 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE for native ETH)"},
+ {"name": "toToken", "type": "string", "description": "Token contract address to buy"},
+ {"name": "amount", "type": "string", "description": "Amount of fromToken in human-readable units"},
+ {"name": "decimals", "type": "number", "description": "Decimals of fromToken. Default: 18"},
+ {"name": "slippage", "type": "number", "description": "Max slippage percentage (e.g. 1 for 1%). Default: 1"}
+ ],
+ "body": "// see chat/src/tools.js → walletToolSchema evm_swap"
+ },
+ "type": "function",
+ "function": {
+ "name": "evm_swap",
+ "description": "Swap ERC20 tokens or ETH on EVM chains via 1inch DEX aggregator.",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "fromToken": {"type": "string", "description": "Token to sell (address or 0xEeee... for ETH)"},
+ "toToken": {"type": "string", "description": "Token to buy (address)"},
+ "amount": {"type": "string", "description": "Amount of fromToken in human-readable units"},
+ "decimals": {"type": "number", "description": "fromToken decimals. Default: 18"},
+ "slippage": {"type": "number", "description": "Max slippage %. Default: 1"}
+ },
+ "required": ["fromToken", "toToken", "amount"]
+ }
+ }
+ }
+ ]$json$::jsonb,
+ '{crypto,solana,evm,defi,wallet}',
+ true
+)
+
+on conflict (slug) do nothing;
diff --git a/api/_lib/notify.js b/api/_lib/notify.js
new file mode 100644
index 000000000..10d489fd1
--- /dev/null
+++ b/api/_lib/notify.js
@@ -0,0 +1,16 @@
+/**
+ * Fire-and-forget in-app notification insert.
+ * Failures are logged, never thrown — callers must not await this for correctness.
+ *
+ * @param {string} userId
+ * @param {'payment_received'|'withdrawal_completed'|'withdrawal_failed'} type
+ * @param {object} payload
+ */
+import { sql } from './db.js';
+
+export function insertNotification(userId, type, payload) {
+ sql`
+ insert into user_notifications (user_id, type, payload)
+ values (${userId}, ${type}, ${JSON.stringify(payload)}::jsonb)
+ `.catch((err) => console.error('[notify] insert failed:', err.message));
+}
diff --git a/api/_lib/payout.js b/api/_lib/payout.js
new file mode 100644
index 000000000..b438e5b97
--- /dev/null
+++ b/api/_lib/payout.js
@@ -0,0 +1,16 @@
+import { sql } from './db.js';
+
+export async function resolvePayoutAddress(agentId, chain) {
+ const [wallet] = await sql`
+ select address from agent_payout_wallets
+ where agent_id = ${agentId} and chain = ${chain}
+ order by is_default desc, created_at desc
+ limit 1
+ `;
+ if (wallet) return wallet.address;
+
+ const [agent] = await sql`
+ select wallet_address from agent_identities where id = ${agentId}
+ `;
+ return agent?.wallet_address ?? null;
+}
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
new file mode 100644
index 000000000..290e534cf
--- /dev/null
+++ b/api/_lib/solana-transfer.js
@@ -0,0 +1,47 @@
+import { Connection, PublicKey, Transaction, Keypair } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddress,
+ createAssociatedTokenAccountInstruction,
+ createTransferInstruction,
+} from '@solana/spl-token';
+import bs58 from 'bs58';
+
+const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+
+/**
+ * Transfer SPL tokens from the platform treasury to a recipient address.
+ * @param {object} opts
+ * @param {string} opts.fromWallet base58-encoded treasury keypair (64 bytes)
+ * @param {string} opts.toAddress recipient Solana address
+ * @param {bigint|number} opts.amount token amount in smallest units (e.g. 6-decimal USDC)
+ * @param {string} opts.mint SPL mint address
+ * @returns {Promise<string>} transaction signature
+ */
+export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }) {
+ const kp = Keypair.fromSecretKey(bs58.decode(fromWallet));
+ const mintPubkey = new PublicKey(mint);
+ const recipientPubkey = new PublicKey(toAddress);
+
+ const connection = new Connection(SOLANA_RPC, 'confirmed');
+
+ const senderATA = await getAssociatedTokenAddress(mintPubkey, kp.publicKey);
+ const recipientATA = await getAssociatedTokenAddress(mintPubkey, recipientPubkey);
+
+ const tx = new Transaction();
+
+ const recipientAccount = await connection.getAccountInfo(recipientATA);
+ if (!recipientAccount) {
+ tx.add(createAssociatedTokenAccountInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey));
+ }
+
+ tx.add(createTransferInstruction(senderATA, recipientATA, kp.publicKey, BigInt(amount)));
+
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash();
+ tx.feePayer = kp.publicKey;
+ tx.recentBlockhash = blockhash;
+
+ tx.sign(kp);
+ const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false });
+ await connection.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');
+ return sig;
+}
diff --git a/api/_lib/x402.js b/api/_lib/x402.js
index ce738ba49..6aaf6b934 100644
--- a/api/_lib/x402.js
+++ b/api/_lib/x402.js
@@ -124,6 +124,7 @@ export async function verifyPaid(req, { agentId, skill, expectedAmount, expected
amount: row.amount,
currency: row.currency_mint,
paidAt: row.paid_at,
+ payerAddress: row.payload?.wallet_address ?? null,
};
}
diff --git a/api/admin/revenue.js b/api/admin/revenue.js
new file mode 100644
index 000000000..d0fdbbe8f
--- /dev/null
+++ b/api/admin/revenue.js
@@ -0,0 +1,60 @@
+// GET /api/admin/revenue — platform fee income aggregated across all agents.
+// Admin-only. Query params: from, to (ISO-8601 dates).
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { requireAdmin } from '../_lib/admin.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+ if (!(await requireAdmin(req, res))) return;
+
+ const q = req.query ?? {};
+ const now = new Date();
+ const defaultFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
+
+ const fromDate = q.from ? new Date(q.from) : defaultFrom;
+ const toDate = q.to ? new Date(q.to) : now;
+
+ if (isNaN(fromDate.getTime()))
+ return error(res, 400, 'validation_error', 'from must be a valid ISO-8601 date');
+ if (isNaN(toDate.getTime()))
+ return error(res, 400, 'validation_error', 'to must be a valid ISO-8601 date');
+
+ const [{ total_fee_collected }] = await sql`
+ SELECT COALESCE(SUM(fee_amount), 0)::bigint AS total_fee_collected
+ FROM agent_revenue_events
+ WHERE created_at BETWEEN ${fromDate} AND ${toDate}
+ `;
+
+ const byCurrency = await sql`
+ SELECT currency_mint, chain, SUM(fee_amount)::bigint AS total
+ FROM agent_revenue_events
+ WHERE created_at BETWEEN ${fromDate} AND ${toDate}
+ GROUP BY currency_mint, chain
+ ORDER BY total DESC
+ `;
+
+ const byDay = await sql`
+ SELECT date_trunc('day', created_at)::date AS date,
+ SUM(fee_amount)::bigint AS fee_total
+ FROM agent_revenue_events
+ WHERE created_at BETWEEN ${fromDate} AND ${toDate}
+ GROUP BY 1
+ ORDER BY 1
+ `;
+
+ return json(res, 200, {
+ total_fee_collected: Number(total_fee_collected),
+ by_currency: byCurrency.map((r) => ({
+ currency_mint: r.currency_mint,
+ chain: r.chain,
+ total: Number(r.total),
+ })),
+ by_day: byDay.map((r) => ({
+ date: r.date instanceof Date ? r.date.toISOString().slice(0, 10) : String(r.date),
+ fee_total: Number(r.fee_total),
+ })),
+ });
+});
diff --git a/api/admin/withdrawals/[id].js b/api/admin/withdrawals/[id].js
new file mode 100644
index 000000000..4db99dd9c
--- /dev/null
+++ b/api/admin/withdrawals/[id].js
@@ -0,0 +1,74 @@
+// PATCH /api/admin/withdrawals/:id — advance withdrawal status (admin only)
+// Allowed transitions: pending → processing, processing → completed | failed
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { requireAdmin } from '../../_lib/admin.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { insertNotification } from '../../_lib/notify.js';
+
+const TRANSITIONS = {
+ pending: ['processing'],
+ processing: ['completed', 'failed'],
+};
+
+const patchBody = z.object({
+ status: z.enum(['processing', 'completed', 'failed']),
+ tx_signature: z.string().trim().min(1).max(200).optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'PATCH,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PATCH'])) return;
+ if (!(await requireAdmin(req, res))) return;
+
+ const id = req.query?.id;
+ const body = parse(patchBody, await readJson(req));
+ const { status, tx_signature } = body;
+
+ const [current] = await sql`
+ select id, status from agent_withdrawals where id = ${id}
+ `;
+
+ if (!current) return error(res, 404, 'not_found', 'withdrawal not found');
+
+ const allowed = TRANSITIONS[current.status] ?? [];
+ if (!allowed.includes(status)) {
+ return error(
+ res,
+ 422,
+ 'invalid_transition',
+ `cannot transition from '${current.status}' to '${status}'`,
+ );
+ }
+
+ if (status === 'processing' && !tx_signature) {
+ return error(res, 400, 'validation_error', 'tx_signature required when advancing to processing');
+ }
+
+ const [withdrawal] = await sql`
+ update agent_withdrawals
+ set
+ status = ${status},
+ tx_signature = coalesce(${tx_signature ?? null}, tx_signature),
+ updated_at = now()
+ where id = ${id}
+ returning id, user_id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, created_at, updated_at
+ `;
+
+ if (status === 'completed' || status === 'failed') {
+ const notifType = status === 'completed' ? 'withdrawal_completed' : 'withdrawal_failed';
+ insertNotification(withdrawal.user_id, notifType, {
+ withdrawal_id: withdrawal.id,
+ amount: Number(withdrawal.amount),
+ currency_mint: withdrawal.currency_mint,
+ chain: withdrawal.chain,
+ to_address: withdrawal.to_address,
+ tx_signature: withdrawal.tx_signature ?? null,
+ });
+ }
+
+ return json(res, 200, { withdrawal });
+});
diff --git a/api/agents/[id]/pricing/[skill].js b/api/agents/[id]/pricing/[skill].js
new file mode 100644
index 000000000..265065e5d
--- /dev/null
+++ b/api/agents/[id]/pricing/[skill].js
@@ -0,0 +1,90 @@
+import { z } from 'zod';
+import { sql } from '../../../_lib/db.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error } from '../../../_lib/http.js';
+import { parse } from '../../../_lib/validate.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+
+// First char must be alphanumeric; rest may include hyphens; total 1–64 chars.
+const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,63}$/;
+
+const pricingBody = z.object({
+ currency_mint: z.string().trim().min(1),
+ chain: z.enum(['solana', 'base', 'evm']),
+ amount: z.number().int().gt(0),
+ is_active: z.boolean().default(true),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+// PUT /api/agents/:id/pricing/:skill — create or update a skill price (owner only)
+// DELETE /api/agents/:id/pricing/:skill — soft-delete; ?hard=true for permanent removal
+export default wrap(async (req, res, id, skill) => {
+ if (cors(req, res, { methods: 'PUT,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['PUT', 'DELETE'])) return;
+
+ if (!skill || !SKILL_RE.test(skill)) {
+ return error(res, 400, 'validation_error', 'skill must be alphanumeric + hyphens, max 64 chars');
+ }
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [agent] = await sql`
+ SELECT id, user_id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ if (agent.user_id !== userId) return error(res, 403, 'forbidden', 'not your agent');
+
+ if (req.method === 'PUT') {
+ const body = parse(pricingBody, await readJson(req));
+
+ const [existing] = await sql`
+ SELECT id FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+
+ await sql`
+ INSERT INTO agent_skill_prices
+ (agent_id, skill, currency_mint, chain, amount, is_active, updated_at)
+ VALUES
+ (${id}, ${skill}, ${body.currency_mint}, ${body.chain}, ${body.amount}, ${body.is_active}, now())
+ ON CONFLICT (agent_id, skill) DO UPDATE SET
+ currency_mint = EXCLUDED.currency_mint,
+ chain = EXCLUDED.chain,
+ amount = EXCLUDED.amount,
+ is_active = EXCLUDED.is_active,
+ updated_at = now()
+ `;
+
+ const [row] = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active
+ FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+
+ return json(res, existing ? 200 : 201, row);
+ }
+
+ // DELETE
+ const url = new URL(req.url, 'http://x');
+ const hard = url.searchParams.get('hard') === 'true';
+
+ if (hard) {
+ await sql`DELETE FROM agent_skill_prices WHERE agent_id = ${id} AND skill = ${skill}`;
+ } else {
+ await sql`
+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()
+ WHERE agent_id = ${id} AND skill = ${skill}
+ `;
+ }
+
+ return json(res, 200, { deleted: true });
+});
diff --git a/api/agents/[id]/pricing/index.js b/api/agents/[id]/pricing/index.js
new file mode 100644
index 000000000..d2b24b72e
--- /dev/null
+++ b/api/agents/[id]/pricing/index.js
@@ -0,0 +1,26 @@
+import { sql } from '../../../_lib/db.js';
+import { cors, json, method, wrap, error } from '../../../_lib/http.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+
+// GET /api/agents/:id/pricing — public for all agents (x402 manifest reads this)
+export default wrap(async (req, res, id) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.pricingPerIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [agent] = await sql`
+ SELECT id FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+
+ const prices = await sql`
+ SELECT id, skill, currency_mint, chain, amount, is_active
+ FROM agent_skill_prices
+ WHERE agent_id = ${id} AND is_active = true
+ ORDER BY skill
+ `;
+
+ return json(res, 200, { prices });
+});
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index 3f7e082d5..621a9b3ea 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -7,6 +7,8 @@ import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';
+import { calculateFee } from '../../_lib/fee.js';
+import { insertNotification } from '../../_lib/notify.js';
const HANDLERS = { echo: async (args) => ({ ok: true, echoed: args }) };
@@ -43,7 +45,7 @@ async function handleInvoke(req, res) {
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const body = parse(invokeSchema, await readJson(req));
- const [agent] = await sql`select id, name, meta from agent_identities where id = ${body.agent_id} and deleted_at is null limit 1`;
+ const [agent] = await sql`select id, user_id, name, meta from agent_identities where id = ${body.agent_id} and deleted_at is null limit 1`;
if (!agent) return error(res, 404, 'not_found', 'agent not found');
if (!agent.meta?.payments?.configured) return error(res, 409, 'precondition_failed', 'agent has not enabled payments');
if (!HANDLERS[body.skill]) return error(res, 404, 'unknown_skill', `skill "${body.skill}" is not registered`);
@@ -53,6 +55,21 @@ async function handleInvoke(req, res) {
if (!paid) return emit402(res, { agent, skill: body.skill, amount: price.amount, currency: price.currency });
await consumeIntent(paid.intentId);
+ const gross = parseInt(paid.amount, 10);
+ const { fee, net } = calculateFee(gross);
+ await sql`
+ insert into agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address)
+ values
+ (${agent.id}, ${paid.intentId}, ${body.skill}, ${gross}, ${fee}, ${net}, ${paid.currency}, ${'solana'}, ${paid.payerAddress})
+ `;
+ insertNotification(agent.user_id, 'payment_received', {
+ agent_id: agent.id,
+ agent_name: agent.name,
+ skill: body.skill,
+ net_amount: net,
+ currency_mint: paid.currency,
+ });
const result = await HANDLERS[body.skill](body.args, { agent, caller: auth });
return json(res, 200, { ok: true, intent_id: paid.intentId, amount: paid.amount, currency: paid.currency, result });
}
diff --git a/api/billing/fee-info.js b/api/billing/fee-info.js
new file mode 100644
index 000000000..97d546dfa
--- /dev/null
+++ b/api/billing/fee-info.js
@@ -0,0 +1,16 @@
+// GET /api/billing/fee-info — public endpoint returning the current platform fee rate.
+// Used by pricing UIs so agent owners see how much the platform takes.
+
+import { cors, json, method, wrap } from '../_lib/http.js';
+import { getFeeBps } from '../_lib/fee.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const fee_bps = getFeeBps();
+ return json(res, 200, {
+ fee_bps,
+ fee_percent: (fee_bps / 100).toFixed(1),
+ });
+});
diff --git a/api/billing/payout-wallets/[id].js b/api/billing/payout-wallets/[id].js
new file mode 100644
index 000000000..ac7e7cccf
--- /dev/null
+++ b/api/billing/payout-wallets/[id].js
@@ -0,0 +1,26 @@
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['DELETE'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const { id } = req.query;
+ const [deleted] = await sql`
+ delete from agent_payout_wallets
+ where id = ${id} and user_id = ${user.id}
+ returning id
+ `;
+
+ if (!deleted) return error(res, 404, 'not_found', 'wallet not found');
+
+ return json(res, 200, { id: deleted.id });
+});
diff --git a/api/billing/payout-wallets/index.js b/api/billing/payout-wallets/index.js
new file mode 100644
index 000000000..714aa5de8
--- /dev/null
+++ b/api/billing/payout-wallets/index.js
@@ -0,0 +1,78 @@
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse, isValidSolanaAddress, isValidEvmAddress } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { z } from 'zod';
+
+const postBody = z.object({
+ address: z.string().trim().min(1).max(100),
+ chain: z.enum(['solana', 'base', 'evm']),
+ agent_id: z.string().uuid().nullable().optional(),
+ is_default: z.boolean().optional().default(false),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const wallets = await sql`
+ select id, agent_id, address, chain, is_default, created_at
+ from agent_payout_wallets
+ where user_id = ${user.id}
+ order by created_at desc
+ `;
+ return json(res, 200, { wallets });
+ }
+
+ // POST
+ const body = parse(postBody, await readJson(req));
+ const { address, chain, agent_id = null, is_default } = body;
+
+ if (chain === 'solana' && !isValidSolanaAddress(address)) {
+ return error(res, 400, 'validation_error', 'invalid Solana address');
+ }
+ if ((chain === 'base' || chain === 'evm') && !isValidEvmAddress(address)) {
+ return error(res, 400, 'validation_error', 'invalid EVM address');
+ }
+
+ // Verify agent_id belongs to this user if provided
+ if (agent_id) {
+ const [agent] = await sql`
+ select id from agent_identities
+ where id = ${agent_id} and user_id = ${user.id} and deleted_at is null
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ }
+
+ let wallet;
+ if (is_default) {
+ // Clear existing defaults for (user, chain) in a transaction, then insert
+ const clearDefault =
+ agent_id !== null
+ ? sql`update agent_payout_wallets set is_default = false where user_id = ${user.id} and chain = ${chain} and agent_id = ${agent_id}`
+ : sql`update agent_payout_wallets set is_default = false where user_id = ${user.id} and chain = ${chain} and agent_id is null`;
+ const insert = sql`
+ insert into agent_payout_wallets (user_id, agent_id, address, chain, is_default)
+ values (${user.id}, ${agent_id}, ${address}, ${chain}, true)
+ returning id, agent_id, address, chain, is_default, created_at
+ `;
+ const results = await sql.transaction([clearDefault, insert]);
+ [wallet] = results[1];
+ } else {
+ [wallet] = await sql`
+ insert into agent_payout_wallets (user_id, agent_id, address, chain, is_default)
+ values (${user.id}, ${agent_id}, ${address}, ${chain}, false)
+ returning id, agent_id, address, chain, is_default, created_at
+ `;
+ }
+
+ return json(res, 201, { wallet });
+});
diff --git a/api/billing/revenue.js b/api/billing/revenue.js
new file mode 100644
index 000000000..c6bf46563
--- /dev/null
+++ b/api/billing/revenue.js
@@ -0,0 +1,105 @@
+// GET /api/billing/revenue — aggregated earnings for the authenticated user's agents.
+// Powers the agent owner revenue dashboard (Task 12).
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const VALID_GRANULARITY = new Set(['day', 'week', 'month']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const q = req.query ?? {};
+
+ // Parse and validate query params
+ const agentId = q.agent_id ?? null;
+ if (agentId !== null && !UUID_RE.test(agentId))
+ return error(res, 400, 'validation_error', 'agent_id must be a UUID');
+
+ const granularity = q.granularity ?? 'day';
+ if (!VALID_GRANULARITY.has(granularity))
+ return error(res, 400, 'validation_error', 'granularity must be day, week, or month');
+
+ const now = new Date();
+ const defaultFrom = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
+
+ const fromDate = q.from ? new Date(q.from) : defaultFrom;
+ const toDate = q.to ? new Date(q.to) : now;
+
+ if (isNaN(fromDate.getTime()))
+ return error(res, 400, 'validation_error', 'from must be a valid ISO-8601 date');
+ if (isNaN(toDate.getTime()))
+ return error(res, 400, 'validation_error', 'to must be a valid ISO-8601 date');
+
+ const agentFilter = agentId ? sql`AND re.agent_id = ${agentId}::uuid` : sql``;
+
+ const [summaryRow] = await sql`
+ SELECT
+ COALESCE(SUM(re.gross_amount), 0)::bigint AS gross_total,
+ COALESCE(SUM(re.fee_amount), 0)::bigint AS fee_total,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS payment_count,
+ MAX(re.currency_mint) AS currency_mint,
+ MAX(re.chain) AS chain
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${user.id}
+ AND re.created_at BETWEEN ${fromDate} AND ${toDate}
+ ${agentFilter}
+ `;
+
+ const bySkill = await sql`
+ SELECT
+ re.skill,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS count
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${user.id}
+ AND re.created_at BETWEEN ${fromDate} AND ${toDate}
+ ${agentFilter}
+ GROUP BY re.skill
+ ORDER BY net_total DESC
+ `;
+
+ const timeseries = await sql`
+ SELECT
+ date_trunc(${granularity}, re.created_at) AS period,
+ COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
+ COUNT(*)::int AS count
+ FROM agent_revenue_events re
+ JOIN agent_identities ai ON ai.id = re.agent_id
+ WHERE ai.user_id = ${user.id}
+ AND re.created_at BETWEEN ${fromDate} AND ${toDate}
+ ${agentFilter}
+ GROUP BY period
+ ORDER BY period
+ `;
+
+ return json(res, 200, {
+ summary: {
+ gross_total: Number(summaryRow.gross_total),
+ fee_total: Number(summaryRow.fee_total),
+ net_total: Number(summaryRow.net_total),
+ currency_mint: summaryRow.currency_mint ?? null,
+ chain: summaryRow.chain ?? null,
+ payment_count: summaryRow.payment_count,
+ },
+ by_skill: bySkill.map((r) => ({
+ skill: r.skill,
+ net_total: Number(r.net_total),
+ count: r.count,
+ })),
+ timeseries: timeseries.map((r) => ({
+ period: r.period instanceof Date ? r.period.toISOString().slice(0, 10) : String(r.period),
+ net_total: Number(r.net_total),
+ count: r.count,
+ })),
+ });
+});
diff --git a/api/billing/withdrawals/[id].js b/api/billing/withdrawals/[id].js
new file mode 100644
index 000000000..1e3c5d1f9
--- /dev/null
+++ b/api/billing/withdrawals/[id].js
@@ -0,0 +1,30 @@
+// GET /api/billing/withdrawals/:id — single withdrawal details
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const id = req.query?.id;
+
+ const [withdrawal] = await sql`
+ select id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, created_at, updated_at
+ from agent_withdrawals
+ where id = ${id} and user_id = ${user.id}
+ `;
+
+ if (!withdrawal) return error(res, 404, 'not_found', 'withdrawal not found');
+
+ return json(res, 200, { withdrawal });
+});
diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.js
new file mode 100644
index 000000000..9b8a0fcc4
--- /dev/null
+++ b/api/billing/withdrawals/index.js
@@ -0,0 +1,107 @@
+// GET /api/billing/withdrawals — list user's withdrawal history
+// POST /api/billing/withdrawals — initiate a withdrawal request
+
+import { z } from 'zod';
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
+import { parse } from '../../_lib/validate.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+
+const postBody = z.object({
+ amount: z.number().int().positive(),
+ currency_mint: z.string().trim().min(1).max(100),
+ chain: z.enum(['solana', 'base', 'evm']),
+ to_address: z.string().trim().min(1).max(200),
+ agent_id: z.string().uuid().nullable().optional(),
+});
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ if (req.method === 'GET') {
+ const params = new URL(req.url, 'http://x').searchParams;
+ const status = params.get('status') || null;
+ const limit = Math.min(100, Math.max(1, parseInt(params.get('limit') || '20', 10)));
+ const offset = Math.max(0, parseInt(params.get('offset') || '0', 10));
+
+ const withdrawals = await sql`
+ select id, agent_id, amount, currency_mint, chain, to_address,
+ status, tx_signature, created_at, updated_at
+ from agent_withdrawals
+ where user_id = ${user.id}
+ and (${status} is null or status = ${status})
+ order by created_at desc
+ limit ${limit} offset ${offset}
+ `;
+
+ const [{ total }] = await sql`
+ select count(*)::int as total
+ from agent_withdrawals
+ where user_id = ${user.id}
+ and (${status} is null or status = ${status})
+ `;
+
+ return json(res, 200, { withdrawals, total, limit, offset });
+ }
+
+ // POST
+ const rlUser = await limits.withdrawalPerUser(user.id);
+ if (!rlUser.success) return error(res, 429, 'rate_limited', 'too many withdrawal requests');
+
+ const body = parse(postBody, await readJson(req));
+ const { amount, currency_mint, chain, to_address, agent_id = null } = body;
+
+ const MIN_WITHDRAWAL = 1_000_000;
+ if (amount < MIN_WITHDRAWAL) {
+ return error(res, 422, 'below_minimum', 'Minimum withdrawal is 1 USDC');
+ }
+
+ // Verify agent_id belongs to this user if provided
+ if (agent_id) {
+ const [agent] = await sql`
+ select id from agent_identities
+ where id = ${agent_id} and user_id = ${user.id} and deleted_at is null
+ `;
+ if (!agent) return error(res, 404, 'not_found', 'agent not found');
+ }
+
+ // Check available balance (earned minus in-flight withdrawals)
+ const [balance] = await sql`
+ select
+ coalesce(sum(re.net_amount), 0)::bigint as earned,
+ (
+ select coalesce(sum(w2.amount), 0)::bigint
+ from agent_withdrawals w2
+ where w2.user_id = ${user.id}
+ and w2.status in ('pending', 'processing')
+ and w2.currency_mint = ${currency_mint}
+ ) as pending_amount
+ from agent_revenue_events re
+ join agent_identities ai on ai.id = re.agent_id
+ where ai.user_id = ${user.id}
+ and re.currency_mint = ${currency_mint}
+ `;
+
+ const available = Number(balance.earned) - Number(balance.pending_amount);
+ if (amount > available) {
+ return error(res, 422, 'insufficient_balance', 'requested amount exceeds available balance');
+ }
+
+ const [withdrawal] = await sql`
+ insert into agent_withdrawals
+ (user_id, agent_id, amount, currency_mint, chain, to_address, status)
+ values
+ (${user.id}, ${agent_id}, ${amount}, ${currency_mint}, ${chain}, ${to_address}, 'pending')
+ returning id, agent_id, amount, currency_mint, chain, to_address, status, tx_signature, created_at, updated_at
+ `;
+
+ return json(res, 201, { withdrawal });
+});
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index e4231672b..2c71692d5 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -138,7 +138,11 @@ async function handleList(req, res, url) {
const rows = await sql`
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
- av.thumbnail_key
+ av.thumbnail_key,
+ EXISTS (
+ SELECT 1 FROM agent_skill_prices asp
+ WHERE asp.agent_id = ai.id AND asp.is_active = true
+ ) AS has_paid_skills
FROM agent_identities ai
LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
WHERE ai.is_published = true
@@ -435,6 +439,7 @@ function toCard(row) {
views_count: row.views_count || 0,
published_at: row.published_at,
created_at: row.created_at,
+ has_paid_skills: row.has_paid_skills || false,
};
}
diff --git a/api/notifications/[id]/read.js b/api/notifications/[id]/read.js
new file mode 100644
index 000000000..42da1d90b
--- /dev/null
+++ b/api/notifications/[id]/read.js
@@ -0,0 +1,27 @@
+// POST /api/notifications/:id/read — mark a single notification as read.
+
+import { sql } from '../../_lib/db.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const id = req.query?.id;
+ if (!id) return error(res, 400, 'validation_error', 'id required');
+
+ const [row] = await sql`
+ update user_notifications
+ set read_at = coalesce(read_at, now())
+ where id = ${id} and user_id = ${user.id}
+ returning id, read_at
+ `;
+
+ if (!row) return error(res, 404, 'not_found', 'notification not found');
+
+ return json(res, 200, { id: row.id, read_at: row.read_at });
+});
diff --git a/api/notifications/index.js b/api/notifications/index.js
new file mode 100644
index 000000000..c689b0b64
--- /dev/null
+++ b/api/notifications/index.js
@@ -0,0 +1,45 @@
+// GET /api/notifications — list recent notifications for the authenticated user.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const limit = Math.min(50, Math.max(1, parseInt(params.get('limit') || '20', 10)));
+
+ const notifications = await sql`
+ select id, type, payload, read_at, created_at
+ from user_notifications
+ where user_id = ${user.id}
+ order by created_at desc
+ limit ${limit}
+ `;
+
+ const [{ unread_count }] = await sql`
+ select count(*)::int as unread_count
+ from user_notifications
+ where user_id = ${user.id} and read_at is null
+ `;
+
+ return json(res, 200, {
+ notifications: notifications.map((n) => ({
+ id: n.id,
+ type: n.type,
+ payload: n.payload,
+ read_at: n.read_at ?? null,
+ created_at: n.created_at,
+ })),
+ unread_count,
+ });
+});
diff --git a/api/notifications/read-all.js b/api/notifications/read-all.js
new file mode 100644
index 000000000..106274a28
--- /dev/null
+++ b/api/notifications/read-all.js
@@ -0,0 +1,22 @@
+// POST /api/notifications/read-all — mark all unread notifications as read.
+
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { cors, json, method, wrap, error } from '../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const [{ count }] = await sql`
+ update user_notifications
+ set read_at = now()
+ where user_id = ${user.id} and read_at is null
+ returning count(*) over ()::int as count
+ `;
+
+ return json(res, 200, { marked_read: count ?? 0 });
+});
diff --git a/api/tx/solana/[action].js b/api/tx/solana/[action].js
new file mode 100644
index 000000000..5babb8640
--- /dev/null
+++ b/api/tx/solana/[action].js
@@ -0,0 +1,151 @@
+import { z } from 'zod';
+import {
+ Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,
+ TransactionInstruction,
+} from '@solana/web3.js';
+import {
+ createTransferInstruction, getMint, getAssociatedTokenAddress,
+ createAssociatedTokenAccountInstruction,
+} from '@solana/spl-token';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+
+const SOLANA_RPC_MAINNET = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
+const SOLANA_RPC_DEVNET = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');
+
+// ── build-transfer ────────────────────────────────────────────────────────────
+
+const transferSchema = z.object({
+ sender: z.string(),
+ recipient: z.string(),
+ amount: z.number().positive(),
+ token: z.string().default('SOL'),
+ memo: z.string().optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+
+async function handleBuildTransfer(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const { sender, recipient, amount, token, memo, network } = parse(transferSchema, await readJson(req));
+
+ const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;
+ const connection = new Connection(rpcUrl, 'confirmed');
+ const senderPubkey = new PublicKey(sender);
+ const recipientPubkey = new PublicKey(recipient);
+
+ const tx = new Transaction();
+
+ if (token === 'SOL') {
+ tx.add(SystemProgram.transfer({
+ fromPubkey: senderPubkey,
+ toPubkey: recipientPubkey,
+ lamports: Math.round(amount * LAMPORTS_PER_SOL),
+ }));
+ } else {
+ const mint = new PublicKey(token);
+ const mintInfo = await getMint(connection, mint);
+ const senderATA = await getAssociatedTokenAddress(mint, senderPubkey);
+ const recipientATA = await getAssociatedTokenAddress(mint, recipientPubkey);
+
+ const recipientAccount = await connection.getAccountInfo(recipientATA);
+ if (!recipientAccount) {
+ tx.add(createAssociatedTokenAccountInstruction(senderPubkey, recipientATA, recipientPubkey, mint));
+ }
+
+ const amountInSmallestUnit = BigInt(Math.round(amount * 10 ** mintInfo.decimals));
+ tx.add(createTransferInstruction(senderATA, recipientATA, senderPubkey, amountInSmallestUnit));
+ }
+
+ if (memo) {
+ tx.add(new TransactionInstruction({
+ keys: [],
+ programId: MEMO_PROGRAM_ID,
+ data: Buffer.from(memo, 'utf-8'),
+ }));
+ }
+
+ const latestBlockhash = await connection.getLatestBlockhash();
+ tx.feePayer = senderPubkey;
+ tx.recentBlockhash = latestBlockhash.blockhash;
+
+ const serialized = tx.serialize({ requireAllSignatures: false });
+ return json(res, 200, {
+ transaction: serialized.toString('base64'),
+ network,
+ blockhash: latestBlockhash.blockhash,
+ lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
+ });
+}
+
+// ── build-swap ────────────────────────────────────────────────────────────────
+
+const swapSchema = z.object({
+ sender: z.string(),
+ inputMint: z.string(),
+ outputMint: z.string(),
+ amount: z.number().positive(),
+ slippageBps: z.number().int().min(1).max(5000).default(50),
+ network: z.enum(['mainnet']).default('mainnet'),
+});
+
+async function handleBuildSwap(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const { sender, inputMint, outputMint, amount, slippageBps } = parse(swapSchema, await readJson(req));
+
+ const connection = new Connection(SOLANA_RPC_MAINNET, 'confirmed');
+ const inputMintPk = new PublicKey(inputMint);
+ const mintInfo = await getMint(connection, inputMintPk);
+ const amountInSmallestUnit = Math.round(amount * 10 ** mintInfo.decimals);
+
+ const quoteUrl = `https://quote-api.jup.ag/v6/quote?inputMint=${inputMint}&outputMint=${outputMint}&amount=${amountInSmallestUnit}&slippageBps=${slippageBps}`;
+ const quoteRes = await fetch(quoteUrl);
+ if (!quoteRes.ok) return error(res, 422, 'no_route', 'No swap route found');
+ const quoteResponse = await quoteRes.json();
+ if (!quoteResponse || quoteResponse.error) return error(res, 422, 'no_route', 'No swap route found');
+
+ const swapRes = await fetch('https://quote-api.jup.ag/v6/swap', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ quoteResponse, userPublicKey: sender, wrapAndUnwrapSol: true }),
+ });
+ if (!swapRes.ok) return error(res, 422, 'swap_failed', 'Jupiter swap transaction fetch failed');
+ const swapResponse = await swapRes.json();
+
+ const outputMintInfo = await getMint(connection, new PublicKey(outputMint));
+ const outputDecimals = outputMintInfo.decimals;
+
+ return json(res, 200, {
+ transaction: swapResponse.swapTransaction,
+ network: 'mainnet',
+ inputAmount: amount,
+ outputAmount: Number(quoteResponse.outAmount) / 10 ** outputDecimals,
+ outputMint,
+ priceImpactPct: quoteResponse.priceImpactPct,
+ });
+}
+
+// ── router ────────────────────────────────────────────────────────────────────
+
+const DISPATCH = { 'build-transfer': handleBuildTransfer, 'build-swap': handleBuildSwap };
+
+export default wrap(async (req, res) => {
+ const action = req.query?.action ?? new URL(req.url, 'http://x').pathname.split('/').pop();
+ const fn = DISPATCH[action];
+ if (!fn) return error(res, 404, 'not_found', `unknown action: ${action}`);
+ return fn(req, res);
+});
diff --git a/chat/src/App.svelte b/chat/src/App.svelte
index aa043a05e..f87b79451 100644
--- a/chat/src/App.svelte
+++ b/chat/src/App.svelte
@@ -46,6 +46,7 @@
feCpu,
feDownload,
feEdit2,
+ feGrid,
feMenu,
feTerminal,
feMoreHorizontal,
@@ -74,6 +75,7 @@
import TopNav from './manus/TopNav.svelte';
import WebsiteFlow from './manus/flows/WebsiteFlow.svelte';
import DesktopFlow from './manus/flows/DesktopFlow.svelte';
+ import RevenueDashboard from './manus/pages/RevenueDashboard.svelte';
marked.use(
markedKatex({
@@ -1442,6 +1444,12 @@
// Non-critical, fail silently
}
}
+
+ let showSkillsMarketplace = false;
+
+ function removeSkill(name) {
+ toolSchema.update(groups => groups.filter(g => g.name !== name));
+ }
</script>
<svelte:window
@@ -1498,6 +1506,11 @@
<div class="sticky top-0 z-[110]"><TopNav /></div>
<ResourcePage slug={$route.slice('resources/'.length)} />
</div>
+{:else if $route === 'dashboard/revenue'}
+ <div class="min-h-dvh bg-[#F5F4EF]">
+ <div class="sticky top-0 z-[110]"><TopNav /></div>
+ <RevenueDashboard />
+ </div>
{:else if $route.startsWith('features/')}
<div class="min-h-dvh bg-paper overflow-y-auto">
<div class="sticky top-0 z-[110]"><TopNav /></div>
@@ -1931,6 +1944,28 @@
</div>
<div class="pointer-events-none absolute bottom-[72px] inset-x-0 h-8 z-[98] bg-gradient-to-t from-paper to-transparent" />
+ {#if $toolSchema.length > 0}
+ <div class="flex flex-wrap gap-1.5 px-4 pt-2 pb-0">
+ {#each $toolSchema as group}
+ <span class="inline-flex items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[11px] font-medium text-indigo-700">
+ {group.name}
+ <button
+ class="ml-0.5 rounded-full p-0.5 text-indigo-400 hover:bg-indigo-100 hover:text-indigo-600"
+ on:click={() => removeSkill(group.name)}
+ aria-label="Remove {group.name}"
+ >
+ <Icon icon={feX} class="h-2.5 w-2.5" />
+ </button>
+ </span>
+ {/each}
+ <button
+ class="text-[11px] text-slate-400 hover:text-slate-600"
+ on:click={() => (showSkillsMarketplace = true)}
+ >
+ + Add skill
+ </button>
+ </div>
+ {/if}
<Composer
bind:generating
bind:convo
diff --git a/chat/src/SkillsMarketplaceModal.svelte b/chat/src/SkillsMarketplaceModal.svelte
new file mode 100644
index 000000000..c673ba151
--- /dev/null
+++ b/chat/src/SkillsMarketplaceModal.svelte
@@ -0,0 +1,561 @@
+<script>
+ import Modal from './Modal.svelte';
+ import { toolSchema, currentUser, notify } from './stores.js';
+
+ export let open = false;
+
+ let view = 'browse';
+
+ // Browse state
+ let skills = [];
+ let loading = false;
+ let searchQuery = '';
+ let debouncedSearch = '';
+ let selectedCategory = null;
+ let page = null;
+ let hasMore = false;
+ let sort = 'popular';
+ let expandedSkillId = null;
+ let installPending = {};
+ let ratingPending = {};
+
+ // Publish state
+ let publishForm = {
+ name: '',
+ slug: '',
+ description: '',
+ category: '',
+ tags: '',
+ schemaText: JSON.stringify(
+ [
+ {
+ name: 'my_tool',
+ description: 'What this tool does',
+ parameters: {
+ type: 'object',
+ properties: {
+ query: { type: 'string', description: 'Input query' }
+ },
+ required: ['query']
+ }
+ }
+ ],
+ null,
+ 2
+ ),
+ isPublic: true
+ };
+ let publishError = null;
+ let publishLoading = false;
+ let schemaValid = null;
+ let schemaErrorMsg = '';
+
+ $: categories = [...new Set(skills.map((s) => s.category).filter(Boolean))];
+
+ function isInstalled(skill) {
+ return $toolSchema.some((g) => g.name === skill.name);
+ }
+
+ async function loadSkills(reset = false) {
+ loading = true;
+ try {
+ const p = new URLSearchParams();
+ if (debouncedSearch) p.set('search', debouncedSearch);
+ if (selectedCategory) p.set('category', selectedCategory);
+ if (sort) p.set('sort', sort);
+ if (!reset && page) p.set('cursor', page);
+ const res = await fetch(`/api/skills?${p}`);
+ if (!res.ok) throw new Error('Failed to load skills');
+ const data = await res.json();
+ skills = reset ? (data.skills || []) : [...skills, ...(data.skills || [])];
+ page = data.nextCursor || null;
+ hasMore = !!data.hasMore;
+ } catch (e) {
+ notify(e.message, 'error');
+ } finally {
+ loading = false;
+ }
+ }
+
+ let searchTimer;
+ function handleSearchInput(e) {
+ clearTimeout(searchTimer);
+ searchTimer = setTimeout(() => {
+ debouncedSearch = e.target.value;
+ page = null;
+ loadSkills(true);
+ }, 300);
+ }
+
+ function selectCategory(cat) {
+ selectedCategory = cat;
+ page = null;
+ loadSkills(true);
+ }
+
+ function handleSortChange(e) {
+ sort = e.target.value;
+ page = null;
+ loadSkills(true);
+ }
+
+ async function toggleInstall(skill) {
+ if (!$currentUser) return;
+ installPending = { ...installPending, [skill.id]: true };
+ const wasInstalled = isInstalled(skill);
+ // Optimistic update
+ if (!wasInstalled) {
+ $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json }];
+ } else {
+ $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);
+ }
+ try {
+ const method = wasInstalled ? 'DELETE' : 'POST';
+ const res = await fetch(`/api/skills/${skill.id}/install`, {
+ method,
+ credentials: 'include'
+ });
+ if (!res.ok) throw new Error('Request failed');
+ skills = skills.map((s) =>
+ s.id === skill.id
+ ? { ...s, install_count: (s.install_count || 0) + (wasInstalled ? -1 : 1) }
+ : s
+ );
+ } catch (e) {
+ // Rollback
+ if (!wasInstalled) {
+ $toolSchema = $toolSchema.filter((g) => g.name !== skill.name);
+ } else {
+ $toolSchema = [...$toolSchema, { name: skill.name, schema: skill.schema_json }];
+ }
+ notify(e.message, 'error');
+ } finally {
+ const next = { ...installPending };
+ delete next[skill.id];
+ installPending = next;
+ }
+ }
+
+ async function rateSkill(skill, stars) {
+ if (!$currentUser) return;
+ ratingPending = { ...ratingPending, [skill.id]: true };
+ try {
+ const res = await fetch(`/api/skills/${skill.id}/rate`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ rating: stars })
+ });
+ if (!res.ok) throw new Error('Rating failed');
+ const data = await res.json();
+ skills = skills.map((s) =>
+ s.id === skill.id
+ ? { ...s, avg_rating: data.avg_rating, rating_count: data.rating_count }
+ : s
+ );
+ } catch (e) {
+ notify(e.message, 'error');
+ } finally {
+ const next = { ...ratingPending };
+ delete next[skill.id];
+ ratingPending = next;
+ }
+ }
+
+ function nameToSlug(name) {
+ return name
+ .toLowerCase()
+ .replace(/\s+/g, '-')
+ .replace(/[^a-z0-9-]/g, '');
+ }
+
+ function handleNameInput(e) {
+ publishForm.name = e.target.value;
+ publishForm.slug = nameToSlug(publishForm.name);
+ }
+
+ function validateSchema() {
+ try {
+ JSON.parse(publishForm.schemaText);
+ schemaValid = true;
+ schemaErrorMsg = '';
+ } catch (e) {
+ schemaValid = false;
+ schemaErrorMsg = e.message;
+ }
+ }
+
+ async function publishSkill() {
+ publishError = null;
+ validateSchema();
+ if (!schemaValid) {
+ publishError = 'Fix JSON errors before publishing';
+ return;
+ }
+ publishLoading = true;
+ try {
+ const tags = publishForm.tags
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean);
+ const res = await fetch('/api/skills', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ name: publishForm.name,
+ slug: publishForm.slug,
+ description: publishForm.description,
+ category: publishForm.category,
+ tags,
+ schema_json: JSON.parse(publishForm.schemaText),
+ is_public: publishForm.isPublic
+ })
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.error || 'Publish failed');
+ }
+ notify('Skill published!', 'success');
+ view = 'browse';
+ await loadSkills(true);
+ } catch (e) {
+ publishError = e.message;
+ } finally {
+ publishLoading = false;
+ }
+ }
+
+ $: if (open && skills.length === 0) loadSkills(true);
+
+ function formatRating(avg, count) {
+ if (!count) return 'No ratings yet';
+ return `⭐ ${Number(avg).toFixed(1)} (${count})`;
+ }
+
+ $: tagPills = publishForm.tags
+ .split(',')
+ .map((t) => t.trim())
+ .filter(Boolean);
+</script>
+
+<Modal bind:open class="md:w-[820px] max-w-[820px]">
+ <!-- Tab bar -->
+ <div class="-mx-5 mb-4 flex border-b border-slate-200 px-5">
+ <button
+ class="mr-4 border-b-2 pb-2 text-[13px] font-medium transition-colors {view === 'browse'
+ ? 'border-indigo-500 text-indigo-600'
+ : 'border-transparent text-slate-500 hover:text-slate-700'}"
+ on:click={() => (view = 'browse')}
+ >
+ Browse
+ </button>
+ <button
+ class="border-b-2 pb-2 text-[13px] font-medium transition-colors {view === 'publish'
+ ? 'border-indigo-500 text-indigo-600'
+ : 'border-transparent text-slate-500 hover:text-slate-700'}"
+ on:click={() => (view = 'publish')}
+ >
+ Publish
+ </button>
+ </div>
+
+ {#if view === 'browse'}
+ <div class="flex min-h-[420px] gap-x-4">
+ <!-- Sidebar -->
+ <aside class="hidden w-40 shrink-0 flex-col gap-y-0.5 md:flex">
+ <button
+ class="rounded-md px-3 py-1.5 text-left text-[12px] font-medium transition-colors {selectedCategory === null
+ ? 'bg-indigo-50 text-indigo-700'
+ : 'text-slate-600 hover:bg-slate-100'}"
+ on:click={() => selectCategory(null)}
+ >
+ All skills
+ </button>
+ {#each categories as cat}
+ <button
+ class="rounded-md px-3 py-1.5 text-left text-[12px] transition-colors {selectedCategory === cat
+ ? 'bg-indigo-50 font-medium text-indigo-700'
+ : 'text-slate-600 hover:bg-slate-100'}"
+ on:click={() => selectCategory(cat)}
+ >
+ {cat}
+ </button>
+ {/each}
+ </aside>
+
+ <!-- Main panel -->
+ <div class="min-w-0 flex-1">
+ <!-- Search + sort -->
+ <div class="mb-4 flex gap-x-2">
+ <input
+ type="text"
+ placeholder="Search skills…"
+ bind:value={searchQuery}
+ on:input={handleSearchInput}
+ class="min-w-0 flex-1 rounded-lg border border-slate-200 bg-white px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ <select
+ on:change={handleSortChange}
+ class="rounded-lg border border-slate-200 bg-white px-2 py-1.5 text-[12px] text-slate-600 outline-none focus:border-indigo-400"
+ >
+ <option value="popular">Popular</option>
+ <option value="newest">Newest</option>
+ <option value="az">A–Z</option>
+ </select>
+ </div>
+
+ <!-- Category filter on mobile -->
+ <div class="mb-3 flex flex-wrap gap-1.5 md:hidden">
+ <button
+ class="rounded-full border px-2.5 py-0.5 text-[11px] {selectedCategory === null
+ ? 'border-indigo-400 bg-indigo-50 text-indigo-700'
+ : 'border-slate-200 text-slate-500'}"
+ on:click={() => selectCategory(null)}>All</button
+ >
+ {#each categories as cat}
+ <button
+ class="rounded-full border px-2.5 py-0.5 text-[11px] {selectedCategory === cat
+ ? 'border-indigo-400 bg-indigo-50 text-indigo-700'
+ : 'border-slate-200 text-slate-500'}"
+ on:click={() => selectCategory(cat)}>{cat}</button
+ >
+ {/each}
+ </div>
+
+ {#if loading && skills.length === 0}
+ <p class="mt-8 text-center text-[13px] text-slate-400">Loading skills…</p>
+ {:else if skills.length === 0}
+ <p class="mt-8 text-center text-[13px] text-slate-400">No skills found</p>
+ {:else}
+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
+ {#each skills as skill (skill.id)}
+ <div class="flex flex-col rounded-lg border border-slate-200 {expandedSkillId === skill.id ? 'border-indigo-300 ring-1 ring-indigo-200' : ''}">
+ <!-- Card main row -->
+ <!-- svelte-ignore a11y-click-events-have-key-events -->
+ <!-- svelte-ignore a11y-no-static-element-interactions -->
+ <div
+ class="flex cursor-pointer items-start justify-between gap-x-3 px-3 py-3"
+ on:click={(e) => {
+ if (e.target.closest('button')) return;
+ expandedSkillId = expandedSkillId === skill.id ? null : skill.id;
+ }}
+ >
+ <div class="min-w-0 flex-1">
+ <div class="flex flex-wrap items-center gap-x-1.5 gap-y-1">
+ <span class="text-[13px] font-medium text-slate-800">{skill.name}</span>
+ {#if skill.category}
+ <span class="rounded-full bg-slate-100 px-2 py-0.5 text-[10px] text-slate-500"
+ >{skill.category}</span
+ >
+ {/if}
+ </div>
+ <p class="mt-0.5 line-clamp-2 text-[11px] leading-relaxed text-slate-500">
+ {skill.description || ''}
+ </p>
+ <div class="mt-1.5 flex items-center gap-x-3 text-[11px] text-slate-400">
+ <span>{skill.install_count || 0} installs</span>
+ <span>{formatRating(skill.avg_rating, skill.rating_count)}</span>
+ <span>by {skill.author_name || 'System'}</span>
+ </div>
+ </div>
+
+ {#if !$currentUser}
+ <span class="shrink-0 text-[11px] text-slate-400">Sign in to install</span>
+ {:else if installPending[skill.id]}
+ <span class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-400"
+ >…</span
+ >
+ {:else if isInstalled(skill)}
+ <button
+ class="shrink-0 rounded-lg border border-slate-200 px-3 py-1.5 text-[11px] text-slate-500 transition-colors hover:border-red-200 hover:bg-red-50 hover:text-red-600"
+ on:click|stopPropagation={() => toggleInstall(skill)}
+ >
+ Remove
+ </button>
+ {:else}
+ <button
+ class="shrink-0 rounded-lg border border-slate-200 bg-slate-50 px-3 py-1.5 text-[11px] font-medium text-slate-700 transition-colors hover:bg-slate-100"
+ on:click|stopPropagation={() => toggleInstall(skill)}
+ >
+ Install
+ </button>
+ {/if}
+ </div>
+
+ <!-- Expanded view -->
+ {#if expandedSkillId === skill.id}
+ <div class="border-t border-slate-100 px-3 pb-3 pt-2.5">
+ <p class="text-[12px] leading-relaxed text-slate-600">
+ {skill.description || 'No description'}
+ </p>
+ {#if skill.tags && skill.tags.length}
+ <div class="mt-2 flex flex-wrap gap-1">
+ {#each skill.tags as tag}
+ <span class="rounded-full bg-indigo-50 px-2 py-0.5 text-[10px] text-indigo-600"
+ >{tag}</span
+ >
+ {/each}
+ </div>
+ {/if}
+ <!-- Star rating -->
+ <div class="mt-3">
+ <p class="mb-1 text-[11px] text-slate-400">Rate this skill</p>
+ <div class="flex gap-x-0.5">
+ {#each [1, 2, 3, 4, 5] as star}
+ <button
+ disabled={!$currentUser || ratingPending[skill.id]}
+ class="text-lg leading-none transition-transform hover:scale-110 disabled:opacity-40"
+ on:click={() => rateSkill(skill, star)}
+ >
+ {(skill.avg_rating || 0) >= star ? '⭐' : '☆'}
+ </button>
+ {/each}
+ </div>
+ </div>
+ </div>
+ {/if}
+ </div>
+ {/each}
+ </div>
+
+ {#if hasMore}
+ <button
+ class="mt-4 w-full rounded-lg border border-slate-200 py-2 text-[12px] text-slate-500 transition-colors hover:bg-slate-50 disabled:opacity-50"
+ disabled={loading}
+ on:click={() => loadSkills(false)}
+ >
+ {loading ? 'Loading…' : 'Load more'}
+ </button>
+ {/if}
+ {/if}
+ </div>
+ </div>
+ {:else}
+ <!-- Publish form -->
+ <div class="flex max-w-lg flex-col gap-y-4">
+ <h2 class="text-[14px] font-semibold text-slate-800">Publish a skill</h2>
+
+ <div class="flex flex-col gap-y-1">
+ <label for="pf-name" class="text-[12px] font-medium text-slate-600">Name</label>
+ <input
+ id="pf-name"
+ type="text"
+ bind:value={publishForm.name}
+ on:input={handleNameInput}
+ placeholder="My Skill"
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ </div>
+
+ <div class="flex flex-col gap-y-1">
+ <label for="pf-slug" class="text-[12px] font-medium text-slate-600">Slug</label>
+ <input
+ id="pf-slug"
+ type="text"
+ bind:value={publishForm.slug}
+ placeholder="my-skill"
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ {#if publishForm.slug}
+ <p class="text-[11px] text-slate-400">Preview: /skills/{publishForm.slug}</p>
+ {/if}
+ </div>
+
+ <div class="flex flex-col gap-y-1">
+ <label class="text-[12px] font-medium text-slate-600">Description</label>
+ <textarea
+ bind:value={publishForm.description}
+ placeholder="Describe what this skill does…"
+ rows="3"
+ class="resize-none rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ </div>
+
+ <div class="flex gap-x-3">
+ <div class="flex flex-1 flex-col gap-y-1">
+ <label class="text-[12px] font-medium text-slate-600">Category</label>
+ <input
+ type="text"
+ list="skill-categories"
+ bind:value={publishForm.category}
+ placeholder="e.g. Search"
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ <datalist id="skill-categories">
+ {#each categories as cat}
+ <option value={cat} />
+ {/each}
+ </datalist>
+ </div>
+
+ <div class="flex flex-1 flex-col gap-y-1">
+ <label class="text-[12px] font-medium text-slate-600">Tags (comma-separated)</label>
+ <input
+ type="text"
+ bind:value={publishForm.tags}
+ placeholder="search, web, api"
+ class="rounded-lg border border-slate-200 px-3 py-1.5 text-[13px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ </div>
+ </div>
+
+ {#if tagPills.length}
+ <div class="flex flex-wrap gap-1">
+ {#each tagPills as tag}
+ <span class="rounded-full bg-indigo-50 px-2.5 py-0.5 text-[11px] text-indigo-600"
+ >{tag}</span
+ >
+ {/each}
+ </div>
+ {/if}
+
+ <div class="flex flex-col gap-y-1">
+ <label class="text-[12px] font-medium text-slate-600">Schema (JSON)</label>
+ <textarea
+ bind:value={publishForm.schemaText}
+ rows="10"
+ spellcheck="false"
+ class="resize-y rounded-lg border border-slate-200 px-3 py-1.5 font-mono text-[12px] text-slate-700 outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200"
+ />
+ <div class="flex items-center gap-x-2">
+ <button
+ type="button"
+ class="rounded-lg border border-slate-200 px-3 py-1 text-[11px] text-slate-600 transition-colors hover:bg-slate-50"
+ on:click={validateSchema}
+ >
+ Validate JSON
+ </button>
+ {#if schemaValid === true}
+ <span class="text-[11px] text-green-600">✓ Valid</span>
+ {:else if schemaValid === false}
+ <span class="text-[11px] text-red-500">{schemaErrorMsg}</span>
+ {/if}
+ </div>
+ </div>
+
+ <div class="flex items-center gap-x-2">
+ <input
+ id="skill-public"
+ type="checkbox"
+ bind:checked={publishForm.isPublic}
+ class="h-3.5 w-3.5 accent-indigo-500"
+ />
+ <label for="skill-public" class="text-[12px] text-slate-600">Make public</label>
+ </div>
+
+ {#if publishError}
+ <p class="text-[12px] text-red-500">{publishError}</p>
+ {/if}
+
+ <button
+ type="button"
+ disabled={publishLoading || !publishForm.name || !publishForm.slug}
+ class="self-start rounded-lg bg-indigo-600 px-4 py-2 text-[13px] font-medium text-white transition-colors hover:bg-indigo-700 disabled:opacity-50"
+ on:click={publishSkill}
+ >
+ {publishLoading ? 'Publishing…' : 'Publish skill'}
+ </button>
+ </div>
+ {/if}
+</Modal>
diff --git a/chat/src/TxApprovalModal.svelte b/chat/src/TxApprovalModal.svelte
new file mode 100644
index 000000000..5ecea1ea7
--- /dev/null
+++ b/chat/src/TxApprovalModal.svelte
@@ -0,0 +1,84 @@
+<script>
+ import { fade, scale } from 'svelte/transition';
+ import { cubicIn } from 'svelte/easing';
+ import Button from './Button.svelte';
+
+ export let details; // { network, from, to, amount, token, memo?, estimatedFee? }
+ export let onApprove; // () => void
+ export let onReject; // () => void
+
+ let pending = false;
+
+ function truncate(addr) {
+ if (!addr || addr.length <= 12) return addr;
+ return addr.slice(0, 6) + '…' + addr.slice(-4);
+ }
+
+ function approve() {
+ pending = true;
+ onApprove();
+ }
+
+ function reject() {
+ pending = true;
+ onReject();
+ }
+
+ $: rows = [
+ { label: 'Network', value: details.network },
+ { label: 'From', value: truncate(details.from) },
+ { label: 'To', value: truncate(details.to) },
+ { label: 'Amount', value: `${details.amount} ${details.token}` },
+ ...(details.memo ? [{ label: 'Memo', value: details.memo }] : []),
+ ...(details.estimatedFee ? [{ label: 'Estimated Fee', value: details.estimatedFee }] : []),
+ ];
+</script>
+
+<div
+ transition:fade={{ duration: 200, easing: cubicIn }}
+ aria-hidden="true"
+ class="fixed inset-0 z-[200] bg-black/60"
+/>
+
+<div
+ role="dialog"
+ aria-modal="true"
+ aria-label="Approve Transaction"
+ transition:scale={{ opacity: 0, start: 0.97, duration: 150, easing: cubicIn }}
+ class="fixed left-1/2 top-1/2 z-[201] w-[95%] max-w-md -translate-x-1/2 -translate-y-1/2 rounded-xl border border-slate-700 bg-slate-900 p-6 shadow-2xl"
+>
+ <h2 class="mb-1 text-lg font-semibold text-white">Approve Transaction</h2>
+ <span class="mb-5 inline-block rounded-full bg-slate-700 px-2.5 py-0.5 text-xs font-medium text-slate-300">
+ {details.network}
+ </span>
+
+ <table class="mb-6 w-full text-sm">
+ <tbody>
+ {#each rows as row}
+ <tr class="border-b border-slate-800 last:border-0">
+ <td class="py-2.5 pr-4 font-medium text-slate-400">{row.label}</td>
+ <td class="py-2.5 text-right font-mono text-slate-200 break-all">{row.value}</td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+
+ <div class="flex gap-3">
+ <Button
+ variant="outline"
+ class="flex-1 !justify-center !border-slate-600 !bg-transparent !text-slate-300 hover:!border-slate-400 disabled:opacity-50"
+ disabled={pending}
+ on:click={reject}
+ >
+ Reject
+ </Button>
+ <Button
+ variant="dark"
+ class="flex-1 !justify-center !bg-indigo-600 hover:!bg-indigo-500 disabled:opacity-50"
+ disabled={pending}
+ on:click={approve}
+ >
+ Approve
+ </Button>
+ </div>
+</div>
diff --git a/chat/src/manus/pages/RevenueDashboard.svelte b/chat/src/manus/pages/RevenueDashboard.svelte
new file mode 100644
index 000000000..890347fa4
--- /dev/null
+++ b/chat/src/manus/pages/RevenueDashboard.svelte
@@ -0,0 +1,399 @@
+<script>
+ import { onMount } from 'svelte';
+ import { route } from '../../stores.js';
+
+ // --- state ---
+ let revenueData = null;
+ let wallets = [];
+ let withdrawals = [];
+ let withdrawalsTotal = 0;
+ let loading = true;
+ let loadError = '';
+
+ // Available balance = net earned minus pending/processing withdrawals
+ let availableBalance = 0;
+ let currencyMint = null;
+ let chain = null;
+
+ // Form
+ let amountDisplay = ''; // what user types (in USDC)
+ let selectedWalletId = '';
+ let submitting = false;
+ let submitError = '';
+ let submitSuccess = '';
+
+ // History pagination
+ let histOffset = 0;
+ const HIST_LIMIT = 20;
+
+ function formatUSDC(lamports) {
+ return (lamports / 1_000_000).toLocaleString('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }) + ' USDC';
+ }
+
+ function truncateAddr(addr) {
+ if (!addr || addr.length <= 12) return addr;
+ return addr.slice(0, 6) + '…' + addr.slice(-4);
+ }
+
+ function explorerUrl(w) {
+ if (!w.tx_signature) return null;
+ if (w.chain === 'solana') return `https://solscan.io/tx/${w.tx_signature}`;
+ return `https://basescan.org/tx/${w.tx_signature}`;
+ }
+
+ const STATUS_LABEL = { pending: 'Queued', processing: 'Processing', completed: 'Sent', failed: 'Failed' };
+ const STATUS_CLASS = {
+ pending: 'bg-yellow-100 text-yellow-800',
+ processing: 'bg-blue-100 text-blue-800',
+ completed: 'bg-green-100 text-green-800',
+ failed: 'bg-red-100 text-red-800',
+ };
+
+ async function loadAll() {
+ loading = true;
+ loadError = '';
+ try {
+ const [revRes, walletsRes, histRes] = await Promise.all([
+ fetch('/api/billing/revenue', { credentials: 'include' }),
+ fetch('/api/billing/payout-wallets', { credentials: 'include' }),
+ fetch(`/api/billing/withdrawals?limit=${HIST_LIMIT}&offset=${histOffset}`, { credentials: 'include' }),
+ ]);
+
+ if (!revRes.ok) throw new Error('Failed to load revenue');
+ if (!walletsRes.ok) throw new Error('Failed to load payout wallets');
+ if (!histRes.ok) throw new Error('Failed to load withdrawal history');
+
+ revenueData = await revRes.json();
+ const walletsJson = await walletsRes.json();
+ const histJson = await histRes.json();
+
+ wallets = walletsJson.wallets ?? [];
+ withdrawals = histJson.withdrawals ?? [];
+ withdrawalsTotal = histJson.total ?? 0;
+
+ // Compute available balance
+ const netEarned = revenueData.summary?.net_total ?? 0;
+ currencyMint = revenueData.summary?.currency_mint ?? null;
+ chain = revenueData.summary?.chain ?? null;
+
+ // Sum pending/processing withdrawals
+ const inFlight = withdrawals
+ .filter(w => w.status === 'pending' || w.status === 'processing')
+ .reduce((s, w) => s + Number(w.amount), 0);
+
+ availableBalance = Math.max(0, netEarned - inFlight);
+
+ // Default wallet selection
+ if (!selectedWalletId && wallets.length > 0) {
+ const def = wallets.find(w => w.is_default) ?? wallets[0];
+ selectedWalletId = def.id;
+ }
+ } catch (e) {
+ loadError = e.message;
+ } finally {
+ loading = false;
+ }
+ }
+
+ async function loadHistory() {
+ try {
+ const res = await fetch(`/api/billing/withdrawals?limit=${HIST_LIMIT}&offset=${histOffset}`, { credentials: 'include' });
+ if (!res.ok) throw new Error('Failed to load history');
+ const json = await res.json();
+ withdrawals = json.withdrawals ?? [];
+ withdrawalsTotal = json.total ?? 0;
+ } catch (e) {
+ loadError = e.message;
+ }
+ }
+
+ function setMax() {
+ amountDisplay = (availableBalance / 1_000_000).toFixed(6).replace(/\.?0+$/, '');
+ }
+
+ function validateAmount() {
+ const v = parseFloat(amountDisplay);
+ if (isNaN(v) || v <= 0) return 'Enter a valid amount';
+ const lamports = Math.round(v * 1_000_000);
+ if (lamports > availableBalance) return 'Insufficient balance';
+ return null;
+ }
+
+ async function submit() {
+ submitError = '';
+ submitSuccess = '';
+
+ const err = validateAmount();
+ if (err) { submitError = err; return; }
+ if (!selectedWalletId) { submitError = 'Select a payout wallet'; return; }
+
+ const wallet = wallets.find(w => w.id === selectedWalletId);
+ if (!wallet) { submitError = 'Wallet not found'; return; }
+
+ const lamports = Math.round(parseFloat(amountDisplay) * 1_000_000);
+
+ submitting = true;
+ try {
+ const res = await fetch('/api/billing/withdrawals', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ amount: lamports,
+ currency_mint: currencyMint ?? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ chain: wallet.chain,
+ to_address: wallet.address,
+ }),
+ });
+
+ const json = await res.json();
+ if (!res.ok) {
+ if (res.status === 422) {
+ submitError = 'Insufficient balance';
+ } else {
+ submitError = json.error_description ?? json.error ?? 'Request failed';
+ }
+ return;
+ }
+
+ submitSuccess = 'Withdrawal requested. Processing typically takes 1–2 business days.';
+ amountDisplay = '';
+ await loadAll();
+ } catch (e) {
+ submitError = e.message;
+ } finally {
+ submitting = false;
+ }
+ }
+
+ async function prevPage() {
+ if (histOffset === 0) return;
+ histOffset = Math.max(0, histOffset - HIST_LIMIT);
+ await loadHistory();
+ }
+
+ async function nextPage() {
+ if (histOffset + HIST_LIMIT >= withdrawalsTotal) return;
+ histOffset += HIST_LIMIT;
+ await loadHistory();
+ }
+
+ $: noWallets = wallets.length === 0;
+ $: amountErr = amountDisplay ? validateAmount() : null;
+
+ onMount(loadAll);
+</script>
+
+<section class="pt-10 pb-20 px-4 max-w-2xl mx-auto">
+ <div class="flex items-center gap-3 mb-8">
+ <button
+ class="text-[#6B6B6B] hover:text-[#1A1A1A] text-sm"
+ on:click={() => route.set('chat')}
+ >← Back</button>
+ <h1 class="font-serif text-2xl font-semibold text-[#1A1A1A]">Revenue &amp; Withdrawals</h1>
+ </div>
+
+ {#if loading}
+ <p class="text-[#6B6B6B] text-sm">Loading…</p>
+ {:else if loadError}
+ <div class="rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700">{loadError}</div>
+ {:else}
+
+ <!-- Summary cards -->
+ {#if revenueData}
+ <div class="grid grid-cols-2 gap-3 mb-8 sm:grid-cols-4">
+ {#each [
+ { label: 'Gross Earnings', value: revenueData.summary.gross_total },
+ { label: 'Platform Fees', value: revenueData.summary.fee_total, neg: true },
+ { label: 'Net Earnings', value: revenueData.summary.net_total },
+ { label: 'Payments', count: revenueData.summary.payment_count },
+ ] as card}
+ <div class="rounded-xl border border-[#E5E3DC] bg-white p-4">
+ <p class="text-xs text-[#6B6B6B] mb-1">{card.label}</p>
+ {#if card.count !== undefined}
+ <p class="text-lg font-semibold text-[#1A1A1A]">{card.count}</p>
+ {:else}
+ <p class="text-lg font-semibold {card.neg ? 'text-red-600' : 'text-[#1A1A1A]'}">
+ {card.neg ? '−' : ''}{formatUSDC(card.value)}
+ </p>
+ {/if}
+ </div>
+ {/each}
+ </div>
+ {/if}
+
+ <!-- Withdraw Earnings -->
+ <div class="rounded-2xl border border-[#E5E3DC] bg-white p-6 mb-6">
+ <h2 class="font-semibold text-[#1A1A1A] mb-4">Withdraw Earnings</h2>
+
+ <!-- Available balance -->
+ <div class="flex items-baseline gap-2 mb-5">
+ <span class="text-sm text-[#6B6B6B]">Available balance</span>
+ <span class="text-xl font-semibold text-[#1A1A1A]">{formatUSDC(availableBalance)}</span>
+ </div>
+
+ {#if noWallets}
+ <div class="rounded-xl bg-[#F5F4EF] border border-[#E5E3DC] p-4 text-sm text-[#6B6B6B] mb-4">
+ No payout wallet configured.
+ <button class="text-[#1A1A1A] underline ml-1" on:click={() => route.set('settings/payout-wallets')}>
+ Add a wallet
+ </button>
+ to enable withdrawals.
+ </div>
+ {/if}
+
+ <!-- Amount -->
+ <label class="block mb-4">
+ <span class="text-xs font-medium text-[#6B6B6B] mb-1.5 block">Amount (USDC)</span>
+ <div class="flex gap-2">
+ <input
+ type="number"
+ min="0"
+ step="0.000001"
+ bind:value={amountDisplay}
+ disabled={noWallets}
+ placeholder="0.00"
+ class="flex-1 h-11 px-4 rounded-xl border border-[#E5E3DC] bg-white focus:outline-none focus:border-[#1A1A1A] disabled:bg-[#F5F4EF] disabled:text-[#9C9A93] text-sm"
+ />
+ <button
+ type="button"
+ disabled={noWallets || availableBalance === 0}
+ on:click={setMax}
+ class="h-11 px-4 rounded-xl border border-[#E5E3DC] bg-white text-sm font-medium text-[#1A1A1A] hover:bg-[#F5F4EF] disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
+ >Max</button>
+ </div>
+ {#if amountErr}
+ <p class="text-xs text-red-500 mt-1">{amountErr}</p>
+ {/if}
+ </label>
+
+ <!-- Wallet selector -->
+ <label class="block mb-5">
+ <span class="text-xs font-medium text-[#6B6B6B] mb-1.5 block">To wallet</span>
+ <div class="flex gap-2 items-center">
+ {#if wallets.length > 0}
+ <select
+ bind:value={selectedWalletId}
+ class="flex-1 h-11 px-4 rounded-xl border border-[#E5E3DC] bg-white focus:outline-none focus:border-[#1A1A1A] text-sm"
+ >
+ {#each wallets as w}
+ <option value={w.id}>
+ {w.chain.toUpperCase()} · {truncateAddr(w.address)}{w.is_default ? ' (default)' : ''}
+ </option>
+ {/each}
+ </select>
+ {:else}
+ <div class="flex-1 h-11 px-4 rounded-xl border border-[#E5E3DC] bg-[#F5F4EF] flex items-center text-sm text-[#9C9A93]">
+ No wallets
+ </div>
+ {/if}
+ <button
+ class="text-sm text-[#1A1A1A] underline whitespace-nowrap"
+ on:click={() => route.set('settings/payout-wallets')}
+ >+ Add wallet</button>
+ </div>
+ </label>
+
+ <!-- Feedback messages -->
+ {#if submitSuccess}
+ <div class="rounded-xl border border-green-200 bg-green-50 p-3 text-sm text-green-800 mb-4">
+ {submitSuccess}
+ </div>
+ {/if}
+ {#if submitError}
+ <div class="rounded-xl border border-red-200 bg-red-50 p-3 text-sm text-red-700 mb-4">
+ {submitError}
+ </div>
+ {/if}
+
+ <!-- Submit -->
+ <div title={noWallets ? 'Add a payout wallet first' : ''}>
+ <button
+ type="button"
+ disabled={noWallets || submitting || availableBalance === 0}
+ on:click={submit}
+ class="w-full h-11 rounded-full bg-black text-white text-sm font-medium hover:bg-[#1A1A1A] disabled:opacity-40 disabled:cursor-not-allowed transition-colors"
+ >
+ {submitting ? 'Requesting…' : 'Request Withdrawal'}
+ </button>
+ </div>
+ </div>
+
+ <!-- Withdrawal History -->
+ <div class="rounded-2xl border border-[#E5E3DC] bg-white p-6">
+ <h2 class="font-semibold text-[#1A1A1A] mb-4">Withdrawal History</h2>
+
+ {#if withdrawals.length === 0}
+ <p class="text-sm text-[#9C9A93]">No withdrawals yet.</p>
+ {:else}
+ <div class="overflow-x-auto">
+ <table class="w-full text-sm">
+ <thead>
+ <tr class="border-b border-[#E5E3DC]">
+ <th class="py-2 pr-4 text-left text-xs font-medium text-[#6B6B6B]">Date</th>
+ <th class="py-2 pr-4 text-left text-xs font-medium text-[#6B6B6B]">Amount</th>
+ <th class="py-2 pr-4 text-left text-xs font-medium text-[#6B6B6B]">Wallet</th>
+ <th class="py-2 pr-4 text-left text-xs font-medium text-[#6B6B6B]">Status</th>
+ <th class="py-2 text-left text-xs font-medium text-[#6B6B6B]">Tx</th>
+ </tr>
+ </thead>
+ <tbody>
+ {#each withdrawals as w}
+ {@const txUrl = explorerUrl(w)}
+ <tr class="border-b border-[#E5E3DC] last:border-0">
+ <td class="py-3 pr-4 text-[#6B6B6B] whitespace-nowrap">
+ {new Date(w.created_at).toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
+ </td>
+ <td class="py-3 pr-4 font-mono text-[#1A1A1A] whitespace-nowrap">
+ {formatUSDC(w.amount)}
+ </td>
+ <td class="py-3 pr-4 font-mono text-[#6B6B6B] whitespace-nowrap">
+ {truncateAddr(w.to_address)}
+ </td>
+ <td class="py-3 pr-4">
+ <span class="inline-block rounded-full px-2 py-0.5 text-xs font-medium {STATUS_CLASS[w.status] ?? 'bg-gray-100 text-gray-700'}">
+ {STATUS_LABEL[w.status] ?? w.status}
+ </span>
+ </td>
+ <td class="py-3">
+ {#if txUrl}
+ <a href={txUrl} target="_blank" rel="noopener noreferrer"
+ class="text-xs text-indigo-600 hover:underline font-mono">
+ {w.tx_signature.slice(0, 8)}…
+ </a>
+ {:else}
+ <span class="text-xs text-[#9C9A93]">—</span>
+ {/if}
+ </td>
+ </tr>
+ {/each}
+ </tbody>
+ </table>
+ </div>
+
+ <!-- Pagination -->
+ {#if withdrawalsTotal > HIST_LIMIT}
+ <div class="flex items-center justify-between mt-4 text-sm text-[#6B6B6B]">
+ <span>{histOffset + 1}–{Math.min(histOffset + HIST_LIMIT, withdrawalsTotal)} of {withdrawalsTotal}</span>
+ <div class="flex gap-2">
+ <button
+ disabled={histOffset === 0}
+ on:click={prevPage}
+ class="px-3 py-1 rounded-lg border border-[#E5E3DC] hover:bg-[#F5F4EF] disabled:opacity-40 disabled:cursor-not-allowed"
+ >← Prev</button>
+ <button
+ disabled={histOffset + HIST_LIMIT >= withdrawalsTotal}
+ on:click={nextPage}
+ class="px-3 py-1 rounded-lg border border-[#E5E3DC] hover:bg-[#F5F4EF] disabled:opacity-40 disabled:cursor-not-allowed"
+ >Next →</button>
+ </div>
+ </div>
+ {/if}
+ {/if}
+ </div>
+
+ {/if}
+</section>
diff --git a/sdk/src/agent-client.js b/sdk/src/agent-client.js
new file mode 100644
index 000000000..e0fa2f8ba
--- /dev/null
+++ b/sdk/src/agent-client.js
@@ -0,0 +1,88 @@
+/**
+ * AgentClient — programmatic x402 payment support for skill invocation.
+ */
+
+export class PaymentRequiredError extends Error {
+ /**
+ * @param {import('./index.d.ts').X402Manifest} manifest
+ */
+ constructor(manifest) {
+ super(`Skill requires payment: ${manifest.amount} ${manifest.currencySymbol}`);
+ this.name = 'PaymentRequiredError';
+ this.manifest = manifest;
+ }
+}
+
+export class AgentClient {
+ /**
+ * @param {object} opts
+ * @param {string} opts.baseUrl Base URL of the 3D agent API (e.g. https://3d.irish)
+ */
+ constructor({ baseUrl = '' } = {}) {
+ this.baseUrl = baseUrl.replace(/\/$/, '');
+ }
+
+ /**
+ * Returns pricing info for all skills of an agent.
+ *
+ * @param {string} agentId
+ * @returns {Promise<import('./index.d.ts').SkillPrice[]>}
+ */
+ async getSkillPrices(agentId) {
+ const res = await fetch(`${this.baseUrl}/api/agents/${agentId}/pricing`);
+ if (!res.ok) throw new Error(`getSkillPrices failed: ${res.status} ${res.statusText}`);
+ return res.json();
+ }
+
+ /**
+ * Invoke a skill, handling x402 payment automatically when required.
+ *
+ * @param {string} agentId
+ * @param {string} skill
+ * @param {Record<string, unknown>} args
+ * @param {{ signer?: import('./index.d.ts').WalletSigner }} [options]
+ * @returns {Promise<import('./index.d.ts').SkillResult>}
+ */
+ async invokeSkill(agentId, skill, args, options = {}) {
+ const manifestRes = await fetch(`${this.baseUrl}/api/agents/${agentId}/x402/${skill}/manifest`);
+
+ if (manifestRes.status === 404) {
+ // Free skill — invoke directly
+ return this._callSkill(agentId, skill, args, null);
+ }
+
+ if (!manifestRes.ok) {
+ throw new Error(`Manifest fetch failed: ${manifestRes.status} ${manifestRes.statusText}`);
+ }
+
+ const manifest = await manifestRes.json();
+
+ if (!options.signer) {
+ throw new PaymentRequiredError(manifest);
+ }
+
+ const paymentProof = await options.signer.signPayment(manifest);
+ return this._callSkill(agentId, skill, args, paymentProof);
+ }
+
+ /**
+ * @param {string} agentId
+ * @param {string} skill
+ * @param {Record<string, unknown>} args
+ * @param {string | null} paymentProof
+ * @returns {Promise<import('./index.d.ts').SkillResult>}
+ */
+ async _callSkill(agentId, skill, args, paymentProof) {
+ const headers = { 'Content-Type': 'application/json' };
+ if (paymentProof) headers['X-Payment-Proof'] = paymentProof;
+
+ const res = await fetch(`${this.baseUrl}/api/agents/${agentId}/skills/${skill}`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify(args),
+ });
+
+ if (!res.ok) throw new Error(`Skill invocation failed: ${res.status} ${res.statusText}`);
+ return res.json();
+ }
+}
diff --git a/tasks/agent-monetization/00-overview.md b/tasks/agent-monetization/00-overview.md
new file mode 100644
index 000000000..39d7c92d9
--- /dev/null
+++ b/tasks/agent-monetization/00-overview.md
@@ -0,0 +1,58 @@
+# Agent Monetization — Feature Overview & Task Index
+
+## What This Feature Does
+Allows agent owners on Three.ws to charge callers for skill invocations. Revenue flows to the owner's configured payout wallet (Solana USDC or Base USDC), minus a configurable platform fee (default 2.5%). Owners can track earnings and request withdrawals from the dashboard.
+
+## User Stories
+- **As an agent owner**, I can set a price (in USDC) for each skill my agent offers
+- **As an agent owner**, I can see how much I've earned, broken down by skill and over time
+- **As an agent owner**, I can withdraw my earnings to my Solana or Base wallet
+- **As a caller**, I see the price before invoking a paid skill and can approve or cancel
+- **As a caller browsing the marketplace**, I can see which agents have paid skills at a glance
+
+## Architecture Summary
+- Pricing stored in `agent_skill_prices` table (per agent, per skill)
+- x402 manifest endpoint reads live pricing from DB
+- Payment intents (existing `agent_payment_intents`) are consumed; revenue recorded in `agent_revenue_events`
+- Platform fee calculated at event time (`fee_bps` from `PLATFORM_FEE_BPS` env var)
+- Withdrawals queued in `agent_withdrawals`, processed by a Vercel cron every 15 minutes
+- All revenue scoped by `agent_identities.user_id` for authorization
+
+## Task Index
+
+| # | Task | Description | Depends On |
+|---|------|-------------|------------|
+| 01 | [DB Schema](01-db-schema.md) | 4 new tables: prices, revenue, payout wallets, withdrawals | — |
+| 02 | [Pricing API](02-pricing-api.md) | CRUD for per-skill prices | 01 |
+| 03 | [x402 Manifest Update](03-x402-manifest-update.md) | Dynamic pricing in payment manifests | 01, 02 |
+| 04 | [Revenue Attribution](04-revenue-attribution.md) | Write revenue events on intent consumption | 01, 03 |
+| 05 | [Payout Wallet API](05-payout-wallet-api.md) | CRUD for payout wallet addresses | 01 |
+| 06 | [Revenue Dashboard API](06-revenue-dashboard-api.md) | Aggregated earnings data endpoint | 01, 04 |
+| 07 | [Withdrawal API](07-withdrawal-api.md) | Request and track payouts | 01, 05, 06 |
+| 08 | [Monetization Settings UI](08-monetization-settings-ui.md) | Agent editor Monetization tab | 02, 05 |
+| 09 | [Caller Payment Gate](09-caller-payment-gate.md) | Frontend intercept for paid skill invocations | 03 |
+| 10 | [Revenue Dashboard UI](10-revenue-dashboard-ui.md) | Earnings charts and summary cards | 06 |
+| 11 | [Withdrawal UI](11-withdrawal-ui.md) | Request payout from the dashboard | 07, 10 |
+| 12 | [Platform Fee Config](12-platform-fee-config.md) | Fee rate exposure and admin revenue view | 04 |
+| 13 | [Marketplace Pricing Display](13-agent-marketplace-pricing-display.md) | Show prices on agent cards and detail pages | 02 |
+| 14 | [SDK Payment Support](14-sdk-payment-support.md) | Programmatic payment for SDK callers | 03 |
+| 15 | [Cron: Withdrawal Processor](15-cron-withdrawal-processor.md) | On-chain USDC transfers for pending withdrawals | 07 |
+| 16 | [Rate Limiting & Abuse](16-rate-limiting-and-abuse.md) | Rate limits on payment and withdrawal endpoints | 02, 07 |
+| 17 | [Notifications](17-notifications.md) | Earnings and withdrawal alerts for owners | 04, 15 |
+| 18 | [E2E Tests](18-e2e-tests.md) | Integration tests for the full flow | All above |
+| 19 | [Security Review](19-security-review.md) | Pre-ship security checklist | All above |
+
+## Recommended Implementation Order
+1. Tasks 01–05 (backend foundation — no UI needed yet)
+2. Tasks 06–07 (revenue and withdrawal APIs)
+3. Tasks 08–11 (frontend — parallel with 12–14)
+4. Tasks 12–14 (parallel work: fee config, marketplace, SDK)
+5. Tasks 15–17 (cron, rate limits, notifications)
+6. Task 18 (tests — add as you go, finalize last)
+7. Task 19 (security review — gate on all above complete)
+
+## Key Env Vars to Add
+```
+PLATFORM_FEE_BPS=250
+PLATFORM_TREASURY_KEYPAIR=<base58-private-key>
+```
diff --git a/tasks/agent-monetization/01-db-schema.md b/tasks/agent-monetization/01-db-schema.md
new file mode 100644
index 000000000..16a9667df
--- /dev/null
+++ b/tasks/agent-monetization/01-db-schema.md
@@ -0,0 +1,104 @@
+# Task 01 — Database Schema: Agent Monetization Tables
+
+## Goal
+Add the database tables needed to store per-skill pricing, payment revenue records, and owner payout wallet config. All migrations must be additive (no destructive changes).
+
+## Success Criteria
+- `npm run db:migrate` runs without error
+- All new tables exist with correct columns and constraints
+- Foreign keys reference existing `agent_identities` and `users` tables correctly
+
+## Tables to Create
+
+### `agent_skill_prices`
+Stores the price an agent owner sets for each monetized skill.
+
+```sql
+CREATE TABLE agent_skill_prices (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ skill TEXT NOT NULL, -- skill name, e.g. "answer-question"
+ currency_mint TEXT NOT NULL, -- SPL mint or EVM token address
+ chain TEXT NOT NULL DEFAULT 'solana', -- "solana" | "base" | "evm"
+ amount BIGINT NOT NULL, -- smallest unit (lamports or wei)
+ is_active BOOLEAN NOT NULL DEFAULT true,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (agent_id, skill)
+);
+```
+
+### `agent_revenue_events`
+Immutable record written each time a payment intent is consumed. This is the source of truth for earnings.
+
+```sql
+CREATE TABLE agent_revenue_events (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agent_identities(id),
+ intent_id UUID NOT NULL REFERENCES agent_payment_intents(id),
+ skill TEXT NOT NULL,
+ gross_amount BIGINT NOT NULL, -- full amount paid by caller (smallest unit)
+ fee_amount BIGINT NOT NULL, -- platform fee deducted
+ net_amount BIGINT NOT NULL, -- gross_amount - fee_amount
+ currency_mint TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ payer_address TEXT, -- caller wallet (nullable if anonymous)
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+```
+
+### `agent_payout_wallets`
+The wallet address where an agent owner wants to receive revenue.
+
+```sql
+CREATE TABLE agent_payout_wallets (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ agent_id UUID REFERENCES agent_identities(id) ON DELETE SET NULL, -- NULL = default for all agents
+ address TEXT NOT NULL,
+ chain TEXT NOT NULL DEFAULT 'solana',
+ is_default BOOLEAN NOT NULL DEFAULT false,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ UNIQUE (user_id, agent_id, chain)
+);
+```
+
+### `agent_withdrawals`
+Tracks payout requests from agent owners.
+
+```sql
+CREATE TABLE agent_withdrawals (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id),
+ agent_id UUID REFERENCES agent_identities(id),
+ amount BIGINT NOT NULL,
+ currency_mint TEXT NOT NULL,
+ chain TEXT NOT NULL,
+ to_address TEXT NOT NULL,
+ status TEXT NOT NULL DEFAULT 'pending', -- pending | processing | completed | failed
+ tx_signature TEXT, -- on-chain tx hash when completed
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+```
+
+## Migration File
+Create `/api/_lib/migrations/013_agent_monetization.sql` with all four `CREATE TABLE` statements above plus index creation:
+
+```sql
+CREATE INDEX ON agent_skill_prices (agent_id);
+CREATE INDEX ON agent_revenue_events (agent_id, created_at DESC);
+CREATE INDEX ON agent_revenue_events (intent_id);
+CREATE INDEX ON agent_payout_wallets (user_id);
+CREATE INDEX ON agent_withdrawals (user_id, status);
+```
+
+## Files to Touch
+- `/api/_lib/migrations/013_agent_monetization.sql` — new file
+- `/api/_lib/db.js` — verify migration runner picks up new file (check glob pattern)
+
+## Verify
+```bash
+npm run db:migrate
+psql $DATABASE_URL -c "\dt agent_skill_prices agent_revenue_events agent_payout_wallets agent_withdrawals"
+```
diff --git a/tasks/agent-monetization/02-pricing-api.md b/tasks/agent-monetization/02-pricing-api.md
new file mode 100644
index 000000000..dabaa7a90
--- /dev/null
+++ b/tasks/agent-monetization/02-pricing-api.md
@@ -0,0 +1,86 @@
+# Task 02 — API: Skill Pricing CRUD
+
+## Goal
+REST endpoints so agent owners can read, set, and remove per-skill prices for their agents.
+
+## Success Criteria
+- Owner can GET, PUT, and DELETE skill prices
+- Non-owner gets 403
+- Unauthenticated gets 401
+- PUT validates amount > 0, known chain, non-empty skill name
+- Changes are immediately reflected in x402 manifest (Task 03 depends on this)
+
+## Endpoints
+
+### `GET /api/agents/:id/pricing`
+Returns all active skill prices for the agent.
+
+```json
+{
+ "prices": [
+ {
+ "id": "uuid",
+ "skill": "answer-question",
+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "chain": "solana",
+ "amount": 1000000,
+ "is_active": true
+ }
+ ]
+}
+```
+
+Auth: session or Bearer token. Public agents: prices are readable by anyone. Private agents: owner only.
+
+### `PUT /api/agents/:id/pricing/:skill`
+Create or update the price for a specific skill.
+
+Request body:
+```json
+{
+ "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "chain": "solana",
+ "amount": 1000000,
+ "is_active": true
+}
+```
+
+Requires: authenticated, `user_id` must match agent owner.
+
+Validation:
+- `amount` must be integer > 0
+- `chain` must be one of: `solana`, `base`, `evm`
+- `currency_mint` must be non-empty string
+- `skill` must be a valid identifier (alphanumeric + hyphens, max 64 chars)
+
+Uses `INSERT ... ON CONFLICT (agent_id, skill) DO UPDATE`.
+
+Response: `201` on create, `200` on update.
+
+### `DELETE /api/agents/:id/pricing/:skill`
+Soft-delete (sets `is_active = false`). Hard-delete on explicit `?hard=true` for owners who want to fully remove.
+
+## File to Create
+`/api/agents/[id]/pricing/index.js` — handles GET
+`/api/agents/[id]/pricing/[skill].js` — handles PUT, DELETE
+
+## Shared Helpers to Use
+- `requireAuth(req)` from `/api/_lib/auth.js`
+- `db` from `/api/_lib/db.js`
+- `json(res, status, body)` and `error(res, status, code, msg)` from `/api/_lib/http.js`
+- `validate(schema, data)` from `/api/_lib/validate.js`
+
+## Verify
+```bash
+# Set price
+curl -X PUT /api/agents/:id/pricing/answer-question \
+ -H "Cookie: __Host-sid=..." \
+ -d '{"currency_mint":"EPjF...","chain":"solana","amount":1000000}'
+
+# Read back
+curl /api/agents/:id/pricing
+
+# Non-owner should 403
+curl -X PUT /api/agents/:id/pricing/answer-question \
+ -H "Cookie: __Host-sid=<other-user-session>" ...
+```
diff --git a/tasks/agent-monetization/03-x402-manifest-update.md b/tasks/agent-monetization/03-x402-manifest-update.md
new file mode 100644
index 000000000..a5b140682
--- /dev/null
+++ b/tasks/agent-monetization/03-x402-manifest-update.md
@@ -0,0 +1,62 @@
+# Task 03 — Update x402 Manifest to Use Dynamic Pricing
+
+## Goal
+The existing endpoint `GET /api/agents/:id/x402/:skill/manifest` returns a hardcoded payment manifest. Update it to pull live pricing from the `agent_skill_prices` table created in Task 01.
+
+## Current Behavior (file: `/api/agents/x402/[...slug].js` or similar)
+The manifest likely returns a static amount from env vars or agent meta. Find the exact file and understand its shape before editing.
+
+## Success Criteria
+- Manifest amount matches the price set via the pricing API (Task 02)
+- If no price is configured for the skill, return `404` with `{ error: "skill_not_priced" }`
+- If `is_active = false`, return `404` with `{ error: "skill_not_available" }`
+- Existing x402 intent creation flow continues to work unchanged
+
+## Changes Required
+
+### In the manifest handler:
+1. Parse `agent_id` and `skill` from the route
+2. Query `agent_skill_prices` for a row where `agent_id = ? AND skill = ? AND is_active = true`
+3. If no row → 404
+4. Build the manifest using `row.amount`, `row.currency_mint`, `row.chain`
+5. Keep payout address from `agent_payout_wallets` (join on `agent_id`, fallback to agent's `wallet_address` in `agent_identities`)
+
+### Payout address resolution (new helper `resolvePayoutAddress(agentId, chain)`)
+```js
+// api/_lib/payout.js
+export async function resolvePayoutAddress(agentId, chain) {
+ const row = await db.query(
+ `SELECT address FROM agent_payout_wallets
+ WHERE agent_id = $1 AND chain = $2
+ ORDER BY is_default DESC, created_at DESC LIMIT 1`,
+ [agentId, chain]
+ );
+ if (row) return row.address;
+ // Fallback: agent's own wallet_address
+ const agent = await db.query(
+ `SELECT wallet_address FROM agent_identities WHERE id = $1`,
+ [agentId]
+ );
+ return agent?.wallet_address ?? null;
+}
+```
+
+## Files to Touch
+- Find and edit the existing x402 manifest endpoint (search for `x402` in `/api/agents/`)
+- Add `/api/_lib/payout.js` (new helper)
+
+## Do NOT Change
+- Intent creation (`agent_payment_intents` insert) — that's unchanged
+- Payment verification logic
+- x402 spec envelope structure
+
+## Verify
+```bash
+# After setting price via Task 02 API:
+curl /api/agents/:id/x402/answer-question/manifest
+# Should return manifest with amount=1000000 and correct payTo address
+
+# Unpriced skill:
+curl /api/agents/:id/x402/unpriced-skill/manifest
+# Should return 404 { error: "skill_not_priced" }
+```
diff --git a/tasks/agent-monetization/04-revenue-attribution.md b/tasks/agent-monetization/04-revenue-attribution.md
new file mode 100644
index 000000000..f6096cee1
--- /dev/null
+++ b/tasks/agent-monetization/04-revenue-attribution.md
@@ -0,0 +1,69 @@
+# Task 04 — Revenue Attribution: Write Revenue Events on Intent Consumption
+
+## Goal
+When a caller pays for a skill and the intent is consumed, write an immutable `agent_revenue_events` row. This is the financial record that powers the revenue dashboard and withdrawal system.
+
+## Success Criteria
+- Every consumed intent creates exactly one `agent_revenue_events` row
+- Platform fee (configurable, default 2.5%) is calculated and stored
+- `net_amount = gross_amount - fee_amount` is always correct
+- Double-consumption is prevented (the existing intent status check still holds)
+
+## Where to Hook In
+
+Find where intents transition from `paid` → `consumed`. This is likely in:
+- `/api/agents/x402/[...slug].js` (the skill access verification endpoint)
+- Or wherever `UPDATE agent_payment_intents SET status = 'consumed'` happens
+
+After the intent is marked consumed (inside the same transaction if possible), insert into `agent_revenue_events`.
+
+## Platform Fee
+
+Add env var: `PLATFORM_FEE_BPS` (basis points, default `250` = 2.5%).
+
+```js
+// api/_lib/fee.js
+const FEE_BPS = parseInt(process.env.PLATFORM_FEE_BPS ?? '250', 10);
+
+export function calculateFee(grossAmount) {
+ const fee = Math.floor((grossAmount * FEE_BPS) / 10_000);
+ return { fee, net: grossAmount - fee };
+}
+```
+
+## Revenue Event Insert
+
+```js
+import { calculateFee } from '../_lib/fee.js';
+
+// Inside intent consumption handler, after status update:
+const { fee, net } = calculateFee(intent.amount);
+await db.query(
+ `INSERT INTO agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,
+ currency_mint, chain, payer_address)
+ VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`,
+ [intent.agent_id, intent.id, intent.skill, intent.amount,
+ fee, net, intent.currency_mint, intent.chain, payerAddress]
+);
+```
+
+`payerAddress` should come from the payment proof in the x402 request headers (the `X-Payment` header contains the signed payment with sender address).
+
+## Files to Touch
+- Find and edit the intent consumption endpoint in `/api/agents/`
+- Add `/api/_lib/fee.js` (new helper)
+
+## Do NOT Change
+- Intent status machine logic
+- x402 header parsing
+- Skill response format
+
+## Verify
+```bash
+# Complete a full payment flow for a priced skill.
+# Then query:
+psql $DATABASE_URL -c "SELECT * FROM agent_revenue_events ORDER BY created_at DESC LIMIT 5;"
+# Verify fee_amount = floor(gross_amount * 0.025)
+# Verify net_amount = gross_amount - fee_amount
+```
diff --git a/tasks/agent-monetization/05-payout-wallet-api.md b/tasks/agent-monetization/05-payout-wallet-api.md
new file mode 100644
index 000000000..9fee20f7d
--- /dev/null
+++ b/tasks/agent-monetization/05-payout-wallet-api.md
@@ -0,0 +1,83 @@
+# Task 05 — API: Payout Wallet Configuration
+
+## Goal
+Endpoints for agent owners to register the wallet address that receives their revenue. Supports per-agent and per-user-default wallets, multiple chains.
+
+## Success Criteria
+- Owner can add, list, and remove payout wallets
+- Can mark one wallet as default per chain
+- Wallet address format is validated per chain type
+- `resolvePayoutAddress()` from Task 03 returns correct address
+
+## Endpoints
+
+### `GET /api/billing/payout-wallets`
+Returns all payout wallets for the authenticated user.
+
+```json
+{
+ "wallets": [
+ {
+ "id": "uuid",
+ "agent_id": null,
+ "address": "7xK...",
+ "chain": "solana",
+ "is_default": true
+ }
+ ]
+}
+```
+
+### `POST /api/billing/payout-wallets`
+Register a new payout wallet.
+
+```json
+{
+ "address": "7xK...",
+ "chain": "solana",
+ "agent_id": null,
+ "is_default": true
+}
+```
+
+If `is_default: true`, set all other wallets for the same `(user_id, chain)` to `is_default = false` first (in a transaction).
+
+Validation:
+- Solana: base58, 32–44 chars
+- EVM/Base: starts with `0x`, 42 chars, valid checksum preferred
+
+### `DELETE /api/billing/payout-wallets/:id`
+Remove a payout wallet. If it was default, clear the default (caller must set a new one).
+
+## Files to Create
+- `/api/billing/payout-wallets/index.js` — GET, POST
+- `/api/billing/payout-wallets/[id].js` — DELETE
+
+## Address Validation Helper
+
+Add to `/api/_lib/validate.js`:
+
+```js
+export function isValidSolanaAddress(addr) {
+ return /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(addr);
+}
+
+export function isValidEvmAddress(addr) {
+ return /^0x[0-9a-fA-F]{40}$/.test(addr);
+}
+```
+
+## Verify
+```bash
+# Add a Solana payout wallet
+curl -X POST /api/billing/payout-wallets \
+ -H "Cookie: __Host-sid=..." \
+ -d '{"address":"7xK...","chain":"solana","is_default":true}'
+
+# List wallets
+curl /api/billing/payout-wallets -H "Cookie: __Host-sid=..."
+
+# Invalid address should 400
+curl -X POST /api/billing/payout-wallets \
+ -d '{"address":"not-valid","chain":"solana"}'
+```
diff --git a/tasks/agent-monetization/06-revenue-dashboard-api.md b/tasks/agent-monetization/06-revenue-dashboard-api.md
new file mode 100644
index 000000000..5d878c620
--- /dev/null
+++ b/tasks/agent-monetization/06-revenue-dashboard-api.md
@@ -0,0 +1,88 @@
+# Task 06 — API: Revenue Dashboard Data
+
+## Goal
+An endpoint that gives agent owners aggregated earnings data to display in the dashboard UI (Task 12).
+
+## Success Criteria
+- Returns total earnings, per-skill breakdown, and time-series data
+- Scoped to the authenticated user's agents only
+- Optional filter by `agent_id` query param
+- Optional filter by date range (`from` / `to` ISO-8601 params)
+- Returns zero-values gracefully (no earnings yet = valid response, not 404)
+
+## Endpoint
+
+### `GET /api/billing/revenue`
+
+Query params:
+- `agent_id` (optional UUID) — filter to a single agent
+- `from` (optional ISO date) — defaults to 30 days ago
+- `to` (optional ISO date) — defaults to now
+- `granularity` — `day` | `week` | `month` (default: `day`)
+
+Response:
+```json
+{
+ "summary": {
+ "gross_total": 15000000,
+ "fee_total": 375000,
+ "net_total": 14625000,
+ "currency_mint": "EPjF...",
+ "chain": "solana",
+ "payment_count": 42
+ },
+ "by_skill": [
+ { "skill": "answer-question", "net_total": 10000000, "count": 30 },
+ { "skill": "generate-image", "net_total": 4625000, "count": 12 }
+ ],
+ "timeseries": [
+ { "period": "2026-04-01", "net_total": 500000, "count": 3 },
+ { "period": "2026-04-02", "net_total": 1000000, "count": 7 }
+ ]
+}
+```
+
+## SQL Queries
+
+### Summary
+```sql
+SELECT
+ SUM(gross_amount) AS gross_total,
+ SUM(fee_amount) AS fee_total,
+ SUM(net_amount) AS net_total,
+ COUNT(*) AS payment_count,
+ currency_mint, chain
+FROM agent_revenue_events re
+JOIN agent_identities ai ON ai.id = re.agent_id
+WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ AND ($4::uuid IS NULL OR re.agent_id = $4)
+GROUP BY currency_mint, chain
+```
+
+### Time-series (daily example)
+```sql
+SELECT
+ date_trunc('day', created_at) AS period,
+ SUM(net_amount) AS net_total,
+ COUNT(*) AS count
+FROM agent_revenue_events re
+JOIN agent_identities ai ON ai.id = re.agent_id
+WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+GROUP BY period
+ORDER BY period
+```
+
+## File to Create
+`/api/billing/revenue.js`
+
+## Verify
+```bash
+curl "/api/billing/revenue?from=2026-01-01&to=2026-04-30" \
+ -H "Cookie: __Host-sid=..."
+# Returns { summary, by_skill, timeseries }
+
+# Without any revenue yet:
+# Returns { summary: { gross_total: 0, ... }, by_skill: [], timeseries: [] }
+```
diff --git a/tasks/agent-monetization/07-withdrawal-api.md b/tasks/agent-monetization/07-withdrawal-api.md
new file mode 100644
index 000000000..1c023b15f
--- /dev/null
+++ b/tasks/agent-monetization/07-withdrawal-api.md
@@ -0,0 +1,89 @@
+# Task 07 — API: Withdrawal (Payout) Flow
+
+## Goal
+Allow agent owners to request a payout of their earned revenue. The flow is: owner requests withdrawal → backend validates sufficient balance → creates `agent_withdrawals` row in `pending` state → (cron or webhook) processes the on-chain transfer → marks `completed`.
+
+## Success Criteria
+- Owner can request a withdrawal for a specific amount and currency
+- System validates available (unconsumed) net balance before creating the request
+- Double-withdrawal is prevented (pending + processing withdrawals reduce available balance)
+- Status transitions: `pending` → `processing` → `completed` | `failed`
+- Only the owner can initiate; only an admin or cron can advance status to `processing`/`completed`
+
+## Endpoints
+
+### `POST /api/billing/withdrawals`
+Initiate a withdrawal request.
+
+```json
+{
+ "amount": 10000000,
+ "currency_mint": "EPjF...",
+ "chain": "solana",
+ "to_address": "7xK...",
+ "agent_id": "uuid-or-null"
+}
+```
+
+**Available balance check:**
+```sql
+SELECT
+ COALESCE(SUM(net_amount), 0) AS earned,
+ (
+ SELECT COALESCE(SUM(amount), 0)
+ FROM agent_withdrawals w2
+ WHERE w2.user_id = $1
+ AND w2.status IN ('pending','processing')
+ AND w2.currency_mint = $2
+ ) AS pending_amount
+FROM agent_revenue_events re
+JOIN agent_identities ai ON ai.id = re.agent_id
+WHERE ai.user_id = $1
+ AND re.currency_mint = $2
+```
+
+`available = earned - pending_amount`. If `requested_amount > available` → 422 `{ error: "insufficient_balance" }`.
+
+On success: insert into `agent_withdrawals` with `status = 'pending'`, return `{ id, status, amount, ... }`.
+
+### `GET /api/billing/withdrawals`
+List the authenticated user's withdrawal history.
+
+Query params: `status` (optional filter), `limit` (default 20), `offset` (default 0).
+
+### `GET /api/billing/withdrawals/:id`
+Single withdrawal details.
+
+## Admin Endpoint (separate from user-facing)
+
+### `PATCH /api/admin/withdrawals/:id`
+Advance withdrawal status. Admin-only.
+
+```json
+{ "status": "processing", "tx_signature": "5J..." }
+```
+
+Only transitions:
+- `pending` → `processing` (set `tx_signature`)
+- `processing` → `completed` | `failed`
+
+## Files to Create
+- `/api/billing/withdrawals/index.js` — GET (list), POST
+- `/api/billing/withdrawals/[id].js` — GET single
+- `/api/admin/withdrawals/[id].js` — PATCH (admin only, use existing `requireAdmin()`)
+
+## Verify
+```bash
+# Initiate withdrawal
+curl -X POST /api/billing/withdrawals \
+ -H "Cookie: __Host-sid=..." \
+ -d '{"amount":1000000,"currency_mint":"EPjF...","chain":"solana","to_address":"7xK..."}'
+
+# Over-withdrawal should 422
+curl -X POST /api/billing/withdrawals \
+ -d '{"amount":9999999999,...}'
+# → { error: "insufficient_balance" }
+
+# List
+curl /api/billing/withdrawals -H "Cookie: __Host-sid=..."
+```
diff --git a/tasks/agent-monetization/08-monetization-settings-ui.md b/tasks/agent-monetization/08-monetization-settings-ui.md
new file mode 100644
index 000000000..611b1b297
--- /dev/null
+++ b/tasks/agent-monetization/08-monetization-settings-ui.md
@@ -0,0 +1,70 @@
+# Task 08 — Frontend: Monetization Settings Tab in Agent Editor
+
+## Goal
+Add a "Monetization" tab to the existing agent settings/editor UI so owners can configure skill prices and payout wallet without leaving the agent management flow.
+
+## Success Criteria
+- Tab appears in the agent editor only for the agent's owner
+- Loads existing prices on open
+- Owner can add/edit/remove prices per skill
+- Skill list is populated from the agent's registered skills
+- Changes call the pricing API (Task 02) and show success/error feedback
+- Payout wallet section lets owner add or change their Solana/Base payout address
+
+## Approach
+
+### Where to add the tab
+Search for the agent editor/settings component. Likely in:
+- `src/components/agent-editor.jsx` or similar
+- Or a settings panel in the main agent detail page
+
+Add a new tab entry: `Monetization` alongside existing tabs (Identity, Skills, Memory, etc.).
+
+### Tab Content Structure
+
+```
+Monetization
+├── Skill Prices
+│ ├── [skill name] [amount input] [currency dropdown] [active toggle] [Save]
+│ ├── [skill name] ...
+│ └── [+ Add skill price] button
+└── Payout Wallet
+ ├── Solana: [address input or connected wallet selector] [Set as payout]
+ └── Base/EVM: [address input] [Set as payout]
+```
+
+### Skill List Source
+Fetch from `GET /api/agents/:id` — the agent's `skills[]` array lists registered skills. Use these as the options in the skill name dropdown/selector.
+
+### Component: `SkillPriceRow`
+```jsx
+// Props: skill, price (may be null), agentId, onSave, onDelete
+// Renders: skill name label, amount input (number), currency select, is_active toggle, Save/Delete buttons
+```
+
+### API Calls
+- On mount: `GET /api/agents/:id/pricing` to load existing prices
+- On save row: `PUT /api/agents/:id/pricing/:skill`
+- On delete row: `DELETE /api/agents/:id/pricing/:skill`
+- Payout wallet: `GET /api/billing/payout-wallets` on mount, `POST` to add
+
+### Currency Options
+Display human-readable labels:
+- Solana USDC: mint `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`
+- Base USDC: address `0x833589fcd6edb6e08f4c7c32d4f71b54bda02913`
+
+Amount inputs should be in human units (USDC with 6 decimal places), converted to `bigint` (×10^6) before sending to API.
+
+## Files to Touch
+- Find and edit the agent editor component (search `agent-editor` or `settings` in `src/components/`)
+- Add new component file `src/components/monetization-settings.jsx`
+
+## Do NOT Change
+- Other tabs in the editor
+- Agent identity or skill registration flows
+
+## Verify
+1. Open agent editor as owner → "Monetization" tab is visible
+2. Open agent editor as non-owner (or logged out) → tab is hidden
+3. Set a price for a skill → price persists after page reload
+4. Remove a price → skill returns to free
diff --git a/tasks/agent-monetization/09-caller-payment-gate.md b/tasks/agent-monetization/09-caller-payment-gate.md
new file mode 100644
index 000000000..cf6d34161
--- /dev/null
+++ b/tasks/agent-monetization/09-caller-payment-gate.md
@@ -0,0 +1,71 @@
+# Task 09 — Frontend: Caller Payment Gate (Skill Invocation Intercept)
+
+## Goal
+When a caller tries to invoke a priced skill, intercept the request client-side, show them the price, and require payment before the skill executes. After successful payment, resume the skill call with a payment proof token.
+
+## Success Criteria
+- Free skills invoke without any payment prompt
+- Priced skills show a modal with the price before executing
+- Caller can approve (pay) or cancel
+- After payment, skill executes exactly once
+- Payment proof is passed to the skill context so the backend can verify it
+- Works in both the embedded widget and the full agent viewer
+
+## Where to Hook In
+
+The skill invocation path flows through `/src/skills/index.js` (the skill registry runner). Find the `invoke(skill, args, ctx)` or equivalent method.
+
+Before executing, check if the skill has a price:
+1. `GET /api/agents/:agentId/x402/:skill/manifest`
+2. If 404 (not priced) → proceed normally
+3. If 200 (has price) → pause, show payment modal, wait for user confirmation
+4. On confirmation → initiate x402 payment flow → get payment proof
+5. Resume skill with `ctx.paymentProof = proof`
+
+## Payment Modal Component
+
+Create `src/components/payment-gate-modal.jsx`:
+
+```jsx
+// Props: skill, amount, currencySymbol, chain, onPay, onCancel
+// Shows:
+// Title: "This skill requires payment"
+// Body: "[skill] costs [amount] [currency]"
+// Buttons: [Pay] [Cancel]
+// [Pay] triggers the x402 client payment flow
+```
+
+The `[Pay]` button calls the existing x402 client helpers (look in `src/` for x402-related code or `agent-payments-sdk`).
+
+## x402 Client Flow
+
+The client-side x402 flow should:
+1. Call `GET /api/agents/:id/x402/:skill/manifest` → get payment details
+2. Construct and sign the payment on the user's connected wallet
+3. Call `POST /api/agents/:id/x402/:skill/pay` (or the prep/confirm endpoints) with the signed payment
+4. Receive back a `payment_proof` or `intent_id`
+5. Pass this as a header/arg when invoking the skill
+
+Reference the existing `agent-payments-sdk/` and `/api/agents/payments/` for the flow pattern.
+
+## Files to Touch
+- `/src/skills/index.js` — add intercept in invoke path
+- Add `src/components/payment-gate-modal.jsx` — new file
+- `/src/runtime/index.js` — may need to thread `paymentProof` into tool context
+
+## Do NOT Change
+- The skill handler signatures or return format
+- The x402 backend verification logic
+
+## Edge Cases
+- Wallet not connected → show "Connect wallet" before price modal
+- Payment timeout → show error, allow retry
+- Skill returns error after payment → log to console, do NOT re-charge (intent is consumed)
+- Duplicate calls racing → debounce or disable [Pay] button after first click
+
+## Verify
+1. Add a price to a skill via Task 08 UI
+2. Click that skill in the viewer → payment modal appears with correct price
+3. Approve payment → skill runs, output appears
+4. Cancel → skill does not run, no payment
+5. Free skill → no modal, runs immediately
diff --git a/tasks/agent-monetization/10-revenue-dashboard-ui.md b/tasks/agent-monetization/10-revenue-dashboard-ui.md
new file mode 100644
index 000000000..1d962b04f
--- /dev/null
+++ b/tasks/agent-monetization/10-revenue-dashboard-ui.md
@@ -0,0 +1,70 @@
+# Task 10 — Frontend: Revenue Dashboard UI
+
+## Goal
+A dashboard page (or panel within the agent management UI) where agent owners can see their earnings: total revenue, per-skill breakdown, and a time-series chart.
+
+## Success Criteria
+- Shows gross/net revenue and payment count for selected time range
+- Per-skill breakdown table with amounts
+- Simple bar or line chart for daily/weekly earnings
+- Date range picker (Last 7d / 30d / 90d / custom)
+- Agent selector dropdown if user has multiple agents (or "All agents" default)
+- Amounts rendered in human-readable USDC (divide lamports by 10^6, show "USDC")
+- Empty state for users with no revenue yet
+
+## Route/Location
+
+Add a route `/dashboard/revenue` (or `/agents/:id/revenue` for per-agent view).
+
+If there's an existing dashboard or billing page, add a "Revenue" section/tab there. Search for `billing`, `dashboard`, or `settings` pages in `src/`.
+
+## Component: `RevenueDashboard`
+
+```
+RevenueDashboard
+├── Header: "Revenue" + date range picker + agent selector
+├── Summary Cards
+│ ├── Gross Earnings: $X.XX USDC
+│ ├── Platform Fees: -$X.XX USDC
+│ ├── Net Earnings: $X.XX USDC
+│ └── Payments: N transactions
+├── Earnings Chart (bar chart, one bar per day/week)
+└── Skill Breakdown Table
+ ├── Skill | Net Earnings | Transactions
+ └── ...rows...
+```
+
+## Data Source
+`GET /api/billing/revenue` (Task 06).
+
+Use `fetch` with the session cookie. On load, call with default `from=30 days ago`.
+
+Re-fetch when date range or agent filter changes.
+
+## Chart
+Use a minimal vanilla SVG bar chart (no external charting lib) or a simple `<canvas>` bar chart. Match existing project style (no React, use vhtml JSX or plain DOM). Keep it under 100 lines.
+
+## Amount Formatting Helper
+```js
+function formatUSDC(lamports) {
+ return (lamports / 1_000_000).toLocaleString('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2
+ }) + ' USDC';
+}
+```
+
+## Files to Create/Touch
+- `src/components/revenue-dashboard.jsx` — new component
+- Wire into the existing routing/navigation (find where other dashboard routes are registered)
+
+## Do NOT Build
+- Real-time WebSocket updates (polling on page focus is fine)
+- CSV export (future task)
+- Multi-currency support in the chart (show primary currency only)
+
+## Verify
+1. Navigate to revenue dashboard → summary cards show (zeros if no revenue)
+2. Change date range → numbers update
+3. Complete a test payment → earnings appear within one page reload
+4. With multiple agents → agent selector filters correctly
diff --git a/tasks/agent-monetization/11-withdrawal-ui.md b/tasks/agent-monetization/11-withdrawal-ui.md
new file mode 100644
index 000000000..6198000fb
--- /dev/null
+++ b/tasks/agent-monetization/11-withdrawal-ui.md
@@ -0,0 +1,69 @@
+# Task 11 — Frontend: Withdrawal UI
+
+## Goal
+UI inside the revenue dashboard for agent owners to request a payout of their earnings to their configured payout wallet.
+
+## Success Criteria
+- Shows available balance (net earnings minus pending withdrawals)
+- Amount input with max = available balance
+- Payout wallet selector (from Task 05 API) with "Add wallet" link
+- Submit creates a withdrawal request and shows confirmation
+- Withdrawal history table below the form
+- Pending/processing withdrawals are clearly indicated
+
+## Component Structure
+
+Add a "Withdraw" section at the bottom of `RevenueDashboard` (Task 10) or as a sibling route `/dashboard/revenue/withdraw`.
+
+```
+Withdraw Earnings
+├── Available balance: $X.XX USDC
+├── Amount: [input, max = available] [Max] button
+├── To wallet: [dropdown of payout wallets] [+ Add wallet]
+├── [Request Withdrawal] button
+│
+└── Withdrawal History
+ ├── Date | Amount | Wallet | Status | Tx
+ └── ...
+```
+
+## Interactions
+
+**On load:**
+- `GET /api/billing/revenue` → derive available balance (net_total)
+- `GET /api/billing/withdrawals?status=pending,processing` → subtract pending from available
+- `GET /api/billing/payout-wallets` → populate wallet dropdown
+
+**On submit:**
+- Validate: amount > 0, amount ≤ available, wallet selected
+- `POST /api/billing/withdrawals` with `{ amount, currency_mint, chain, to_address }`
+- On success: show "Withdrawal requested. Processing typically takes 1–2 business days."
+- Refresh available balance and history
+
+**"+ Add wallet" link:**
+- Opens the payout wallet form (inline or links to payout-wallets settings)
+
+## Amount Conversion
+- Display in USDC (÷ 10^6), store as lamports (× 10^6) when sending to API
+- [Max] button fills input with full available balance
+
+## Status Display
+| Status | Display |
+|--------|---------|
+| `pending` | "Queued" (yellow badge) |
+| `processing` | "Processing" (blue badge) |
+| `completed` | "Sent" (green badge) + tx hash link |
+| `failed` | "Failed" (red badge) |
+
+For `completed`, show a link to the transaction on Solscan or Basescan depending on chain.
+
+## Files to Touch
+- `src/components/revenue-dashboard.jsx` — add withdrawal section
+- Or add `src/components/withdrawal-panel.jsx` and import it
+
+## Verify
+1. Available balance shows correctly
+2. [Max] fills the amount
+3. Submit with valid amount → success message, history row appears with "Queued"
+4. Submit exceeding balance → inline error "Insufficient balance"
+5. No payout wallet configured → [Request Withdrawal] is disabled with tooltip "Add a payout wallet first"
diff --git a/tasks/agent-monetization/12-platform-fee-config.md b/tasks/agent-monetization/12-platform-fee-config.md
new file mode 100644
index 000000000..8e5560f69
--- /dev/null
+++ b/tasks/agent-monetization/12-platform-fee-config.md
@@ -0,0 +1,82 @@
+# Task 12 — Platform Fee Configuration & Admin Controls
+
+## Goal
+Make the platform fee configurable per-plan (or globally) and add an admin endpoint to see fee revenue. This is needed so the business can adjust fee rates without a code deploy.
+
+## Success Criteria
+- Fee BPS is readable from the database (with env var as fallback)
+- Admin can view total platform fee revenue
+- Fee rate is visible to agent owners when they set prices ("Platform takes X%")
+- Fee rate changes take effect for new payments only (old intents are unaffected)
+
+## DB Change
+Add to the existing `plan_quotas` table (or a new `platform_config` table):
+
+Option A — Simplest: add a `platform_config` table:
+```sql
+CREATE TABLE platform_config (
+ key TEXT PRIMARY KEY,
+ value TEXT NOT NULL,
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+INSERT INTO platform_config (key, value) VALUES ('fee_bps', '250');
+```
+
+Option B — Use env var only (`PLATFORM_FEE_BPS`). Simpler, no DB change needed.
+
+**Recommendation:** Use Option B for now. The `fee.js` helper from Task 04 already reads `PLATFORM_FEE_BPS`. Add a public endpoint to expose the rate to the frontend.
+
+## New Endpoint
+
+### `GET /api/billing/fee-info`
+Public (no auth required). Returns the current platform fee rate so the UI can display it.
+
+```json
+{ "fee_bps": 250, "fee_percent": "2.5" }
+```
+
+## Admin Revenue Endpoint
+
+### `GET /api/admin/revenue`
+Admin-only. Aggregate platform fee income.
+
+```json
+{
+ "total_fee_collected": 375000,
+ "by_currency": [
+ { "currency_mint": "EPjF...", "chain": "solana", "total": 375000 }
+ ],
+ "by_day": [
+ { "date": "2026-04-01", "fee_total": 12500 }
+ ]
+}
+```
+
+SQL:
+```sql
+SELECT currency_mint, chain, SUM(fee_amount) AS total
+FROM agent_revenue_events
+WHERE created_at BETWEEN $1 AND $2
+GROUP BY currency_mint, chain
+```
+
+## Frontend: Show Fee Rate in Pricing UI
+In `monetization-settings.jsx` (Task 08), below each price input, show:
+> "Platform fee: 2.5% — You receive $X.XX per payment"
+
+Fetch the fee rate from `GET /api/billing/fee-info` on component mount.
+
+## Files to Touch
+- `/api/_lib/fee.js` — already created in Task 04, no change needed
+- Add `/api/billing/fee-info.js` — new public endpoint
+- Add `/api/admin/revenue.js` — new admin endpoint
+- `src/components/monetization-settings.jsx` — add fee rate display
+
+## Verify
+```bash
+curl /api/billing/fee-info
+# → { fee_bps: 250, fee_percent: "2.5" }
+
+# Change fee in env: PLATFORM_FEE_BPS=500
+# → { fee_bps: 500, fee_percent: "5.0" }
+```
diff --git a/tasks/agent-monetization/13-agent-marketplace-pricing-display.md b/tasks/agent-monetization/13-agent-marketplace-pricing-display.md
new file mode 100644
index 000000000..d596b2b3a
--- /dev/null
+++ b/tasks/agent-monetization/13-agent-marketplace-pricing-display.md
@@ -0,0 +1,70 @@
+# Task 13 — Marketplace: Show Pricing on Agent Cards & Detail Pages
+
+## Goal
+When browsing the agent marketplace or an agent's public profile, show callers which skills are priced (and how much) so they know before they invoke anything.
+
+## Success Criteria
+- Agent cards in `/api/marketplace` response include `has_paid_skills: boolean`
+- Agent detail page shows a "Skills" section with price badges
+- Free skills show "Free", priced skills show the amount (e.g., "0.01 USDC")
+- Pricing data is served from the existing `/api/agents/:id/pricing` endpoint (read-only, public)
+
+## API Changes
+
+### Update `GET /api/agents` (marketplace list)
+Add `has_paid_skills` boolean to each agent in the list response.
+
+```sql
+-- In the agents list query, add:
+EXISTS (
+ SELECT 1 FROM agent_skill_prices asp
+ WHERE asp.agent_id = ai.id AND asp.is_active = true
+) AS has_paid_skills
+```
+
+### Update `GET /api/agents/:id` (agent detail)
+Include skill prices in the response:
+
+```json
+{
+ "id": "...",
+ "name": "...",
+ "skills": ["answer-question", "generate-image"],
+ "skill_prices": {
+ "answer-question": { "amount": 1000000, "currency_mint": "EPjF...", "chain": "solana" },
+ "generate-image": null
+ }
+}
+```
+
+`null` = free. Only return `is_active = true` prices.
+
+## Frontend Changes
+
+### Agent Card (marketplace grid)
+If `has_paid_skills = true`, add a small "Paid" badge (e.g., 💰 or "$" icon) to the agent card. Keep the badge minimal — don't crowd the card.
+
+### Agent Detail Page
+In the skills list section, for each skill:
+- If `skill_prices[skill]` is non-null: show `0.01 USDC` badge (green)
+- If null: show `Free` badge (gray)
+
+Format amounts the same way as the revenue dashboard: `lamports / 10^6` + " USDC".
+
+## Files to Touch
+- `/api/agents/index.js` (or wherever the marketplace list handler lives) — add `has_paid_skills`
+- `/api/agents/[id].js` — add `skill_prices` to response
+- `src/components/agent-card.jsx` (or equivalent) — add paid badge
+- `src/components/agent-detail.jsx` (or equivalent) — add price badges to skill list
+
+## Do NOT Change
+- Marketplace search/filter logic
+- Agent card layout beyond adding the badge
+- Agent detail sections unrelated to skills
+
+## Verify
+1. Create an agent with a priced skill
+2. Browse marketplace → agent card shows "Paid" indicator
+3. Open agent detail → skills list shows correct price next to each skill
+4. Free skill shows "Free"
+5. Unauthenticated user can see prices (public data)
diff --git a/tasks/agent-monetization/14-sdk-payment-support.md b/tasks/agent-monetization/14-sdk-payment-support.md
new file mode 100644
index 000000000..8930d785b
--- /dev/null
+++ b/tasks/agent-monetization/14-sdk-payment-support.md
@@ -0,0 +1,88 @@
+# Task 14 — SDK: Payment Support for Programmatic Callers
+
+## Goal
+Update the TypeScript SDK (`/sdk/`) so that programmatic callers (MCP clients, third-party apps) can discover skill prices, initiate x402 payments, and invoke paid skills — all without a browser UI.
+
+## Success Criteria
+- `agent.getSkillPrices()` returns pricing info for all skills
+- `agent.invokeSkill(skill, args, { paymentOptions })` handles payment automatically when a price is required
+- Payment is skipped if the skill is free
+- Caller can pass a wallet signer to the SDK for signing payments
+- All new methods are documented with JSDoc
+
+## New SDK Methods
+
+### `AgentClient.getSkillPrices(agentId)`
+```ts
+async getSkillPrices(agentId: string): Promise<SkillPrice[]>
+// Calls GET /api/agents/:id/pricing
+// Returns: [{ skill, amount, currencyMint, chain, isActive }]
+```
+
+### `AgentClient.invokeSkill(agentId, skill, args, options?)`
+```ts
+async invokeSkill(
+ agentId: string,
+ skill: string,
+ args: Record<string, unknown>,
+ options?: { signer?: WalletSigner }
+): Promise<SkillResult>
+```
+
+Internally:
+1. `GET /api/agents/:id/x402/:skill/manifest`
+2. If 404 (free) → call skill directly
+3. If 200 (priced) → if no `signer` provided → throw `PaymentRequiredError`
+4. If signer provided → build and sign payment → call skill with payment proof
+
+### `PaymentRequiredError`
+```ts
+class PaymentRequiredError extends Error {
+ constructor(public readonly manifest: X402Manifest) {
+ super(`Skill requires payment: ${manifest.amount} ${manifest.currencySymbol}`);
+ }
+}
+```
+
+### `WalletSigner` Interface
+```ts
+interface WalletSigner {
+ address: string;
+ chain: 'solana' | 'base';
+ signPayment(manifest: X402Manifest): Promise<string>; // returns signed payment proof
+}
+```
+
+Callers provide their own signer implementation (Solana: use `@solana/web3.js` Keypair; Base: use `viem` or `ethers`). The SDK doesn't bundle wallet libraries.
+
+## Files to Touch
+- `/sdk/src/agent-client.ts` (or equivalent main client file)
+- `/sdk/src/types.ts` — add `SkillPrice`, `X402Manifest`, `WalletSigner`, `PaymentRequiredError`
+- `/sdk/src/index.ts` — export new types
+
+## Do NOT Change
+- Existing SDK methods
+- SDK build config
+
+## Verify
+```ts
+import { AgentClient } from '@threews/sdk';
+
+const client = new AgentClient({ baseUrl: 'https://3d.irish' });
+
+// Discover prices
+const prices = await client.getSkillPrices('agent-uuid');
+// [{ skill: 'answer-question', amount: 1000000, ... }]
+
+// Free skill — no payment needed
+const result = await client.invokeSkill('agent-uuid', 'greet', {});
+
+// Paid skill — no signer → throws PaymentRequiredError
+try {
+ await client.invokeSkill('agent-uuid', 'answer-question', { query: 'hello' });
+} catch (e) {
+ if (e instanceof PaymentRequiredError) {
+ console.log('Need to pay:', e.manifest.amount);
+ }
+}
+```
diff --git a/tasks/agent-monetization/15-cron-withdrawal-processor.md b/tasks/agent-monetization/15-cron-withdrawal-processor.md
new file mode 100644
index 000000000..64690150c
--- /dev/null
+++ b/tasks/agent-monetization/15-cron-withdrawal-processor.md
@@ -0,0 +1,111 @@
+# Task 15 — Cron: Withdrawal Processor
+
+## Goal
+A cron job that picks up `pending` withdrawal requests and executes the on-chain transfer, then marks them `completed` or `failed`. This is the backend job that actually moves funds.
+
+## Success Criteria
+- Cron runs at a configurable interval (default: every 15 minutes)
+- Picks up rows with `status = 'pending'` in `agent_withdrawals`
+- For Solana USDC: transfers SPL token from the platform escrow/treasury wallet to `to_address`
+- Marks `processing` before sending, `completed` with tx hash after confirmation, `failed` on error
+- A single failed transfer doesn't block other pending withdrawals
+- Re-entrancy is safe: each row is locked with `SELECT ... FOR UPDATE SKIP LOCKED`
+
+## Implementation
+
+### File: `/api/cron/process-withdrawals.js`
+
+```js
+export default async function handler(req, res) {
+ // Verify Vercel cron secret
+ if (req.headers['authorization'] !== `Bearer ${process.env.CRON_SECRET}`) {
+ return res.status(401).end();
+ }
+
+ // Lock and fetch pending withdrawals (process up to 10 at a time)
+ const rows = await db.query(`
+ SELECT * FROM agent_withdrawals
+ WHERE status = 'pending'
+ ORDER BY created_at ASC
+ LIMIT 10
+ FOR UPDATE SKIP LOCKED
+ `);
+
+ for (const row of rows) {
+ try {
+ // Mark processing
+ await db.query(
+ `UPDATE agent_withdrawals SET status='processing', updated_at=now() WHERE id=$1`,
+ [row.id]
+ );
+
+ // Execute transfer (Solana USDC example)
+ const txSig = await transferSolanaUSDC({
+ fromWallet: process.env.PLATFORM_TREASURY_KEYPAIR, // base58 keypair
+ toAddress: row.to_address,
+ amount: row.amount, // lamports
+ mint: row.currency_mint,
+ });
+
+ // Mark completed
+ await db.query(
+ `UPDATE agent_withdrawals SET status='completed', tx_signature=$1, updated_at=now() WHERE id=$2`,
+ [txSig, row.id]
+ );
+ } catch (err) {
+ console.error(`Withdrawal ${row.id} failed:`, err.message);
+ await db.query(
+ `UPDATE agent_withdrawals SET status='failed', updated_at=now() WHERE id=$1`,
+ [row.id]
+ );
+ }
+ }
+
+ res.json({ processed: rows.length });
+}
+```
+
+### Solana Transfer Helper
+Create `/api/_lib/solana-transfer.js`:
+```js
+export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }) {
+ // Use @solana/web3.js + @solana/spl-token
+ // createTransferInstruction → send transaction → return signature
+}
+```
+
+Reference existing Solana code in `/api/agents/` or `/src/wallet/` for patterns.
+
+## Vercel Cron Config
+Add to `vercel.json`:
+```json
+{
+ "crons": [
+ { "path": "/api/cron/process-withdrawals", "schedule": "*/15 * * * *" }
+ ]
+}
+```
+
+## Required Env Vars
+- `PLATFORM_TREASURY_KEYPAIR` — base58 private key of the platform's treasury wallet (holds float for payouts)
+- `CRON_SECRET` — shared secret for cron authorization (already used by other crons)
+
+## Files to Create/Touch
+- `/api/cron/process-withdrawals.js` — new cron handler
+- `/api/_lib/solana-transfer.js` — new Solana transfer helper
+- `vercel.json` — add cron entry
+
+## Security Notes
+- `PLATFORM_TREASURY_KEYPAIR` must never be logged or returned in responses
+- All DB mutations should be inside a transaction where possible
+- `SKIP LOCKED` prevents two cron instances from double-processing the same row
+
+## Verify
+```bash
+# Simulate cron call
+curl -X GET /api/cron/process-withdrawals \
+ -H "Authorization: Bearer $CRON_SECRET"
+
+# Check withdrawal status changed
+psql $DATABASE_URL -c "SELECT id, status, tx_signature FROM agent_withdrawals ORDER BY created_at DESC LIMIT 5;"
+```
diff --git a/tasks/agent-monetization/16-rate-limiting-and-abuse.md b/tasks/agent-monetization/16-rate-limiting-and-abuse.md
new file mode 100644
index 000000000..e0d8617d7
--- /dev/null
+++ b/tasks/agent-monetization/16-rate-limiting-and-abuse.md
@@ -0,0 +1,87 @@
+# Task 16 — Rate Limiting & Abuse Prevention for Paid Skills
+
+## Goal
+Prevent abuse of the payment and pricing APIs: rate-limit payment intent creation, prevent fake intent replays, and ensure callers can't enumerate skill prices to scrape agent configurations at scale.
+
+## Success Criteria
+- Payment intent creation is rate-limited per caller address
+- Replayed payment proofs are rejected (idempotency enforcement)
+- Pricing endpoint has a reasonable public rate limit
+- Withdrawal endpoint is rate-limited per user
+
+## Changes
+
+### 1. Payment Intent Rate Limit
+In the x402 intent creation handler, add a per-payer rate limit using the existing Upstash Redis rate limiter.
+
+Add a new rate limit bucket to `/api/_lib/rate-limit.js`:
+```js
+export const paymentIntentPerPayer = rateLimit({
+ prefix: 'payment_intent_payer',
+ limit: 20,
+ window: 60, // 20 intents per minute per payer address
+});
+```
+
+Apply in the intent creation endpoint:
+```js
+const limited = await paymentIntentPerPayer.check(payerAddress);
+if (limited) return error(res, 429, 'rate_limited', 'Too many payment attempts');
+```
+
+### 2. Intent Replay Prevention
+Payment intents already have a unique `id` and status machine. Ensure the skill access handler checks:
+```sql
+SELECT status FROM agent_payment_intents
+WHERE id = $1 AND status = 'paid'
+FOR UPDATE
+```
+If `status != 'paid'` → reject with 409. The existing `status = 'consumed'` update inside a transaction handles this, but verify it's in a transaction (`BEGIN/COMMIT`).
+
+### 3. Pricing Endpoint Public Rate Limit
+Add to the GET `/api/agents/:id/pricing` handler:
+```js
+export const pricingPerIp = rateLimit({
+ prefix: 'pricing_ip',
+ limit: 100,
+ window: 60, // 100 reads/minute per IP
+});
+```
+
+### 4. Withdrawal Rate Limit
+In `POST /api/billing/withdrawals`, add:
+```js
+export const withdrawalPerUser = rateLimit({
+ prefix: 'withdrawal_user',
+ limit: 3,
+ window: 3600, // 3 withdrawal requests per hour per user
+});
+```
+
+### 5. Minimum Withdrawal Amount
+In the withdrawal API (Task 07), enforce a minimum amount (e.g., 1 USDC = 1,000,000 lamports):
+```js
+const MIN_WITHDRAWAL = 1_000_000;
+if (amount < MIN_WITHDRAWAL) {
+ return error(res, 422, 'below_minimum', 'Minimum withdrawal is 1 USDC');
+}
+```
+
+## Files to Touch
+- `/api/_lib/rate-limit.js` — add 3 new rate limit configs
+- The x402 intent creation handler — add payer rate limit
+- `/api/agents/:id/pricing` GET handler — add IP rate limit
+- `/api/billing/withdrawals/index.js` — add user rate limit and minimum
+
+## Verify
+```bash
+# Hammer intent creation from same address — should 429 after 20 req/min
+for i in {1..25}; do curl -X POST /api/agents/:id/x402/:skill/prep ...; done
+
+# Replay intent ID — should 409
+curl POST .../x402/:skill/consume with same intent_id twice
+
+# Withdrawal below minimum
+curl POST /api/billing/withdrawals -d '{"amount":100,...}'
+# → 422 below_minimum
+```
diff --git a/tasks/agent-monetization/17-notifications.md b/tasks/agent-monetization/17-notifications.md
new file mode 100644
index 000000000..d856c8af8
--- /dev/null
+++ b/tasks/agent-monetization/17-notifications.md
@@ -0,0 +1,94 @@
+# Task 17 — Notifications: Earnings Alerts for Agent Owners
+
+## Goal
+Notify agent owners when they receive a payment (and when a withdrawal completes). This closes the feedback loop so owners know their monetized agents are generating revenue without having to check the dashboard.
+
+## Success Criteria
+- Owner receives a notification when an `agent_revenue_events` row is inserted
+- Owner receives a notification when a withdrawal transitions to `completed` or `failed`
+- Notifications are non-blocking (fire-and-forget, failure silently logged not thrown)
+- Owners can opt out per notification type
+
+## Notification Types to Implement
+
+### In-app notifications (simplest, do this first)
+Add a `notifications` table:
+```sql
+CREATE TABLE user_notifications (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ type TEXT NOT NULL, -- "payment_received" | "withdrawal_completed" | "withdrawal_failed"
+ payload JSONB NOT NULL,
+ read_at TIMESTAMPTZ,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
+CREATE INDEX ON user_notifications (user_id, read_at, created_at DESC);
+```
+
+### Endpoints
+
+`GET /api/notifications` — list unread notifications for the current user
+```json
+{
+ "notifications": [
+ {
+ "id": "uuid",
+ "type": "payment_received",
+ "payload": { "agent_name": "Atlas", "skill": "answer-question", "net_amount": 950000 },
+ "created_at": "2026-04-30T12:00:00Z"
+ }
+ ],
+ "unread_count": 3
+}
+```
+
+`POST /api/notifications/:id/read` — mark a notification read
+
+`POST /api/notifications/read-all` — mark all read
+
+### When to Write Notifications
+
+**Payment received** — in the revenue attribution code (Task 04), after inserting the `agent_revenue_events` row:
+```js
+await db.query(
+ `INSERT INTO user_notifications (user_id, type, payload)
+ SELECT ai.user_id, 'payment_received',
+ jsonb_build_object(
+ 'agent_id', $2,
+ 'skill', $3,
+ 'net_amount', $4,
+ 'currency_mint', $5
+ )
+ FROM agent_identities ai WHERE ai.id = $2`,
+ [/* ... */]
+);
+```
+
+**Withdrawal completed/failed** — in the cron processor (Task 15), after updating withdrawal status.
+
+### UI: Notification Bell
+In the main nav/header, add a bell icon with an unread count badge.
+- Fetches `GET /api/notifications` on load (and on focus)
+- Clicking opens a dropdown list of recent notifications
+- "Mark all read" button
+
+Keep the component small — a simple dropdown, not a full page.
+
+## Email Notifications (optional, lower priority)
+If `SENDGRID_API_KEY` or an SMTP env var is configured, also send an email. Make this opt-in via user preferences. Implement only if the in-app version is working.
+
+## Files to Create/Touch
+- `/api/_lib/migrations/014_notifications.sql` — new table
+- `/api/notifications/index.js` — GET
+- `/api/notifications/[id]/read.js` — POST
+- `/api/notifications/read-all.js` — POST
+- Revenue attribution handler (Task 04) — add notification insert
+- Cron withdrawal processor (Task 15) — add notification insert
+- `src/components/notification-bell.jsx` — new component
+- Main layout/nav component — wire in notification bell
+
+## Verify
+1. Complete a payment for a priced skill → notification appears in bell within one page reload
+2. Click bell → dropdown shows "Atlas received payment: 0.95 USDC for answer-question"
+3. Click "Mark all read" → badge clears
+4. Withdrawal completes → "Withdrawal of 1.00 USDC sent" notification appears
diff --git a/tasks/agent-monetization/18-e2e-tests.md b/tasks/agent-monetization/18-e2e-tests.md
new file mode 100644
index 000000000..91ca96e27
--- /dev/null
+++ b/tasks/agent-monetization/18-e2e-tests.md
@@ -0,0 +1,126 @@
+# Task 18 — End-to-End Tests: Agent Monetization Flow
+
+## Goal
+Automated tests that cover the complete monetization flow: set price → caller pays → revenue recorded → owner withdraws. These are integration tests that hit real DB (test schema) and real API handlers.
+
+## Success Criteria
+- All happy-path scenarios pass
+- Key error paths are covered (insufficient balance, wrong owner, replay)
+- Tests are isolated (each test creates its own users/agents, cleans up after)
+- Tests run with `npm test` without side effects on production data
+
+## Test File
+`/tests/agent-monetization.test.js`
+
+Use the existing test framework (Vitest based on the project setup). Reference `/tests/` for existing patterns.
+
+## Test Cases
+
+### 1. Pricing CRUD
+```js
+test('owner can set and read skill price', async () => {
+ const { agent, session } = await createTestAgent();
+ await setPricing(session, agent.id, 'answer-question', { amount: 1000000, chain: 'solana', ... });
+ const prices = await getPricing(agent.id);
+ expect(prices[0].amount).toBe(1000000);
+});
+
+test('non-owner gets 403', async () => {
+ const { agent } = await createTestAgent();
+ const { session: otherSession } = await createTestUser();
+ const res = await setPricing(otherSession, agent.id, 'answer-question', { ... });
+ expect(res.status).toBe(403);
+});
+```
+
+### 2. x402 Manifest
+```js
+test('manifest returns price when skill is priced', async () => {
+ // set price, then fetch manifest
+ const manifest = await getManifest(agent.id, 'answer-question');
+ expect(manifest.amount).toBe(1000000);
+});
+
+test('manifest returns 404 when skill is not priced', async () => {
+ const res = await fetch(`/api/agents/${agent.id}/x402/free-skill/manifest`);
+ expect(res.status).toBe(404);
+});
+```
+
+### 3. Revenue Attribution
+```js
+test('consuming an intent creates revenue event', async () => {
+ // Create intent, mark paid, consume
+ await consumeIntent(intentId, payerAddress);
+ const events = await db.query(
+ 'SELECT * FROM agent_revenue_events WHERE intent_id = $1', [intentId]
+ );
+ expect(events.length).toBe(1);
+ expect(events[0].fee_amount).toBe(Math.floor(1000000 * 0.025));
+ expect(events[0].net_amount).toBe(1000000 - events[0].fee_amount);
+});
+
+test('double-consumption is rejected', async () => {
+ await consumeIntent(intentId, payerAddress);
+ const res2 = await consumeIntent(intentId, payerAddress);
+ expect(res2.status).toBe(409);
+});
+```
+
+### 4. Revenue Dashboard
+```js
+test('revenue endpoint returns correct totals', async () => {
+ // Insert test revenue events
+ const data = await getRevenue(session);
+ expect(data.summary.gross_total).toBeGreaterThan(0);
+ expect(data.by_skill.length).toBeGreaterThan(0);
+});
+```
+
+### 5. Withdrawals
+```js
+test('owner can withdraw available balance', async () => {
+ // Seed revenue events, then request withdrawal
+ const w = await requestWithdrawal(session, { amount: 950000, ... });
+ expect(w.status).toBe('pending');
+});
+
+test('over-withdrawal is rejected', async () => {
+ const res = await requestWithdrawal(session, { amount: 9999999999, ... });
+ expect(res.status).toBe(422);
+ expect(res.error).toBe('insufficient_balance');
+});
+```
+
+### 6. Rate Limiting
+```js
+test('payment intent creation is rate-limited', async () => {
+ // Send 25 intent requests from the same payer address
+ // At least some should return 429
+ const results = await Promise.all(Array(25).fill(null).map(() => createIntent(...)));
+ expect(results.some(r => r.status === 429)).toBe(true);
+});
+```
+
+## Test Helpers to Create
+
+```js
+// tests/_helpers/monetization.js
+export async function createTestAgent(overrides = {}) { ... }
+export async function setPricing(session, agentId, skill, price) { ... }
+export async function getPricing(agentId) { ... }
+export async function getManifest(agentId, skill) { ... }
+export async function consumeIntent(intentId, payerAddress) { ... }
+export async function getRevenue(session, params = {}) { ... }
+export async function requestWithdrawal(session, body) { ... }
+```
+
+## Files to Create
+- `/tests/agent-monetization.test.js`
+- `/tests/_helpers/monetization.js`
+
+## Verify
+```bash
+npm test -- tests/agent-monetization.test.js
+# All tests pass, no leftover test data in DB
+```
diff --git a/tasks/agent-monetization/19-security-review.md b/tasks/agent-monetization/19-security-review.md
new file mode 100644
index 000000000..dcc3df54c
--- /dev/null
+++ b/tasks/agent-monetization/19-security-review.md
@@ -0,0 +1,67 @@
+# Task 19 — Security Review: Agent Monetization Feature
+
+## Goal
+Before shipping, conduct a targeted security review of all new code added in Tasks 01–18. Focus on the highest-risk areas: payment flows, authorization boundaries, and financial data integrity.
+
+## Method
+Run `/security-review` on the branch containing all monetization changes, then manually verify each item in the checklist below.
+
+## Checklist
+
+### Authorization
+- [ ] Every pricing write endpoint (`PUT`, `DELETE`) verifies `agent.user_id === session.user_id`
+- [ ] Revenue data endpoints (`/billing/revenue`, `/billing/withdrawals`) are scoped to the authenticated user only — no other user's data leaks
+- [ ] Admin endpoints (`/admin/revenue`, `PATCH /admin/withdrawals/:id`) require `is_admin = true` on the user row
+- [ ] Public endpoints (`GET /api/agents/:id/pricing`, `GET /api/billing/fee-info`) return no sensitive data (wallet private keys, user emails, session tokens)
+
+### Payment Integrity
+- [ ] Intent status transitions are atomic (inside a DB transaction)
+- [ ] `status = 'consumed'` is only set once per intent (idempotency)
+- [ ] `agent_revenue_events.intent_id` has a unique constraint or the insert is inside the same transaction as the status update
+- [ ] `gross_amount = fee_amount + net_amount` is enforced in the insert, not just the application layer
+- [ ] Payment proof signature is verified on the backend before marking intent as `paid` (check existing x402 verification is still called)
+
+### Financial Data
+- [ ] `agent_revenue_events` is append-only (no UPDATE or DELETE allowed from application code)
+- [ ] Withdrawal amount cannot exceed available balance (checked with `SELECT FOR UPDATE` to prevent race conditions)
+- [ ] `PLATFORM_TREASURY_KEYPAIR` is never logged, returned in responses, or stored in the DB
+
+### Input Validation
+- [ ] Skill name in pricing API is validated against `^[a-z0-9-]{1,64}$` (prevent injection via skill name)
+- [ ] Amount fields are integers — no floating-point arithmetic in financial calculations
+- [ ] Payout wallet addresses are validated for correct format per chain before storage
+
+### Rate Limiting
+- [ ] Payment intent creation: rate-limited per payer address
+- [ ] Withdrawal creation: rate-limited per user (max 3/hour)
+- [ ] Pricing read: rate-limited per IP
+
+### CSRF
+- [ ] All state-mutating endpoints (POST, PUT, DELETE, PATCH) that accept session cookie auth require CSRF token verification (check existing `verifyCsrfToken()` is applied)
+
+### Data Leakage
+- [ ] Error messages in payment endpoints do not reveal internal state (intent IDs, stack traces) to callers
+- [ ] Withdrawal `to_address` is not returned to non-owners (the admin endpoint is OK, but the user-facing GET should only return their own)
+
+## Files to Review
+All files created/modified in Tasks 01–18:
+- `/api/_lib/migrations/013_agent_monetization.sql`
+- `/api/_lib/fee.js`
+- `/api/_lib/payout.js`
+- `/api/_lib/solana-transfer.js`
+- `/api/agents/[id]/pricing/*.js`
+- `/api/billing/revenue.js`
+- `/api/billing/withdrawals/*.js`
+- `/api/billing/payout-wallets/*.js`
+- `/api/billing/fee-info.js`
+- `/api/cron/process-withdrawals.js`
+- `/api/notifications/*.js`
+- The modified x402 manifest endpoint
+
+## Output
+Create a brief report listing:
+1. Any HIGH severity findings with the file + line number
+2. Any MEDIUM findings
+3. Confirmation that all checklist items passed
+
+Fix all HIGH and MEDIUM findings before merging.
diff --git a/tasks/skills-marketplace/00-overview.md b/tasks/skills-marketplace/00-overview.md
new file mode 100644
index 000000000..eda1ffa8e
--- /dev/null
+++ b/tasks/skills-marketplace/00-overview.md
@@ -0,0 +1,51 @@
+# Skills Marketplace — Implementation Overview
+
+A community skills marketplace embedded in the chat UI, allowing users to browse, install,
+publish, and rate skill packs that extend the LLM's tool capabilities.
+
+## Task execution order
+
+Run each task in a **new chat** in the order listed. Each task is self-contained with full
+context, but later tasks depend on earlier ones being merged.
+
+| # | File | What it builds | Depends on |
+|---|------|----------------|------------|
+| 01 | `01-db-schema.md` | Postgres tables: `marketplace_skills`, `skill_installs`, `skill_ratings` + basic seed data | nothing |
+| 02 | `02-skills-api.md` | REST API: `/api/skills/` (list, create, install, rate) | 01 |
+| 03 | `03-marketplace-modal.md` | `SkillsMarketplaceModal.svelte` — full browse + publish UI | 01, 02 |
+| 04 | `04-chat-integration.md` | Wire modal into `App.svelte` toolbar | 03 |
+| 05 | `05-seed-and-categories.md` | 15 seed skills + `/api/skills/categories` endpoint + modal update | 02, 03 |
+| 06 | `06-skill-detail-and-ratings.md` | Expanded detail panel + star rating widget | 03, 04, 05 |
+| 07 | `07-installed-skills-toolbar.md` | Active skill chip strip above chat input | 04 |
+
+## Feature summary
+
+### For users
+- **Browse** community skills by category (Finance, Developer, Utility, etc.) with search + sort
+- **Install** a skill with one click — it immediately appears as an active LLM tool
+- **See** installed skills as chips above the input bar, removable with ×
+- **Rate** skills 1–5 stars
+- **Publish** your own skill: name, description, category, and a JSON tool definition
+
+### Architecture
+- Skills are stored in `marketplace_skills` (Postgres). The `schema_json` column holds a JSON
+ array in the exact shape of the existing `curatedToolPacks` in `tools.js`.
+- When installed, a skill is written to the `toolSchema` Svelte store (persisted in localStorage).
+ The existing LLM tool pipeline reads from this store — no changes to `convo.js` or `providers.js`
+ are needed.
+- The community marketplace API lives at `/api/skills/`. System skills have `author_id = null`.
+
+### Files created/modified
+New files:
+- `/api/_lib/migrations/2026-04-30-skills-marketplace.sql`
+- `/api/_lib/migrations/2026-04-30-skills-seed.sql`
+- `/api/skills/index.js`
+- `/api/skills/[id].js`
+- `/api/skills/[id]/install.js`
+- `/api/skills/[id]/rate.js`
+- `/api/skills/categories.js`
+- `/chat/src/SkillsMarketplaceModal.svelte`
+
+Modified files:
+- `/api/_lib/schema.sql` (append new tables)
+- `/chat/src/App.svelte` (import + button + modal instance + chip strip + removeSkill)
diff --git a/tasks/skills-marketplace/01-db-schema.md b/tasks/skills-marketplace/01-db-schema.md
new file mode 100644
index 000000000..c95070b0c
--- /dev/null
+++ b/tasks/skills-marketplace/01-db-schema.md
@@ -0,0 +1,85 @@
+# Task 01 — DB Schema: Skills Marketplace Tables
+
+## Goal
+Add the database tables required to back a community skills marketplace. When done, the schema
+should support: publishing skills, browsing/searching them, installing them per-user, and basic
+ratings. This is a migration-only task — no API or UI changes.
+
+## Context
+- Project: `/workspaces/3D-Agent`
+- DB: Neon serverless PostgreSQL
+- Migration files live in `/api/_lib/migrations/` as dated SQL files (e.g. `2026-04-30-chat-admin-key.sql`)
+- The existing schema is at `/api/_lib/schema.sql` (~900 lines). Read it first to understand conventions
+ (id format, timestamps, foreign keys, naming style).
+- Auth/user table is `users(id uuid pk, email, display_name, ...)`.
+- Today's date: 2026-04-30.
+
+## What to build
+
+### 1. Migration file
+Create `/api/_lib/migrations/2026-04-30-skills-marketplace.sql` with the following tables:
+
+**`marketplace_skills`**
+```
+id uuid primary key default gen_random_uuid()
+author_id uuid references users(id) on delete set null
+name text not null
+slug text not null unique -- url-safe, e.g. "tradingview-charts"
+description text not null
+category text not null default 'general'
+-- JSON array matching the existing ToolPack schema used in /chat/src/tools.js:
+-- each element: { clientDefinition: {...}, type, function: { name, description, parameters } }
+schema_json jsonb not null
+tags text[] not null default '{}'
+is_public boolean not null default true
+install_count integer not null default 0
+created_at timestamptz not null default now()
+updated_at timestamptz not null default now()
+```
+
+**`skill_installs`** — tracks which users have installed which skills
+```
+id uuid primary key default gen_random_uuid()
+user_id uuid references users(id) on delete cascade
+skill_id uuid references marketplace_skills(id) on delete cascade
+installed_at timestamptz not null default now()
+unique(user_id, skill_id)
+```
+
+**`skill_ratings`**
+```
+id uuid primary key default gen_random_uuid()
+user_id uuid references users(id) on delete cascade
+skill_id uuid references marketplace_skills(id) on delete cascade
+rating smallint not null check (rating between 1 and 5)
+created_at timestamptz not null default now()
+unique(user_id, skill_id)
+```
+
+### 2. Indexes
+Add indexes for the common query patterns:
+- `marketplace_skills(category)`
+- `marketplace_skills(author_id)`
+- `marketplace_skills(install_count desc)` (for "popular" sort)
+- `marketplace_skills(created_at desc)` (for "new" sort)
+- `skill_installs(user_id)`
+
+### 3. Update /api/_lib/schema.sql
+Append the same table definitions (without `IF NOT EXISTS` guards — the schema.sql is the
+canonical reference, not a runnable migration) to the bottom of `/api/_lib/schema.sql`.
+Keep the same formatting style as the rest of the file.
+
+### 4. Seed data
+Add 5 seed rows to `marketplace_skills` in the migration file so there's something to browse.
+Re-use the skill schemas from `/chat/src/tools.js` `curatedToolPacks` — translate each pack's
+`schema` array directly into the `schema_json` column value. The 5 packs in tools.js are:
+`tradingview`, `web-search`, `calculator`, `qr-code`, and any others present in that file.
+Set `author_id = null` (system skills), `is_public = true`.
+
+Use `ON CONFLICT (slug) DO NOTHING` so the seeds are idempotent.
+
+## Verification
+After writing the files:
+1. Read both files back and confirm the SQL is syntactically correct.
+2. Confirm foreign key references match actual table/column names in schema.sql.
+3. Confirm the jsonb seed data is valid JSON (no JS template literals or unquoted strings).
diff --git a/tasks/skills-marketplace/02-skills-api.md b/tasks/skills-marketplace/02-skills-api.md
new file mode 100644
index 000000000..5e85ca78c
--- /dev/null
+++ b/tasks/skills-marketplace/02-skills-api.md
@@ -0,0 +1,118 @@
+# Task 02 — API: Skills Marketplace Endpoints
+
+## Goal
+Build the REST API for the skills marketplace. When done, the chat frontend can list skills,
+search/filter them, install/uninstall them, publish new ones, and fetch install state.
+
+## Prerequisites
+Task 01 (DB schema) must be merged first. The `marketplace_skills`, `skill_installs`, and
+`skill_ratings` tables must exist.
+
+## Context
+- Project: `/workspaces/3D-Agent`
+- API layer: Vercel serverless functions in `/api/` (ESM, Node 24)
+- Shared libs in `/api/_lib/`:
+ - `db.js` — Neon client, tagged-template `sql`. Read it to see exact export shape.
+ - `auth.js` — `requireAuth(req)` throws on failure, returns `{ userId }`. Also `optionalAuth(req)`.
+ Read it — the actual export names may differ slightly.
+ - `http.js` — `json(res, data, status?)`, `error(res, msg, status?)`, CORS headers. Read it.
+ - `rate-limit.js` — pre-built limiters. Read it for available exports.
+ - `validate.js` — Zod helpers. Read it.
+- Existing similar endpoint to study: `/api/marketplace/[action].js` — read it for patterns.
+- Auth cookies: `credentials: 'include'` from the browser.
+
+## Endpoints to build
+
+Create `/api/skills/index.js` (handles `/api/skills` GET + POST) and
+`/api/skills/[id].js` (handles `/api/skills/:id` GET/PUT/DELETE) and
+`/api/skills/[id]/install.js` (POST to install, DELETE to uninstall) and
+`/api/skills/[id]/rate.js` (POST to rate).
+
+### GET /api/skills
+Query params: `?q=`, `?category=`, `?sort=popular|new|az`, `?cursor=` (uuid for keyset pagination),
+`?limit=` (default 20, max 50), `?installed=true` (filter to skills installed by authed user).
+
+Response:
+```json
+{
+ "skills": [
+ {
+ "id": "uuid",
+ "name": "TradingView Charts",
+ "slug": "tradingview-charts",
+ "description": "...",
+ "category": "finance",
+ "tags": ["charts", "trading"],
+ "install_count": 42,
+ "avg_rating": 4.5,
+ "rating_count": 12,
+ "author": { "id": "uuid", "display_name": "Alice" },
+ "installed": true,
+ "created_at": "iso8601"
+ }
+ ],
+ "next_cursor": "uuid-or-null"
+}
+```
+
+`installed` field: true/false if user is authenticated, omitted if not.
+`author` is null for system skills (author_id IS NULL).
+
+### POST /api/skills
+Requires auth. Publish a new skill.
+
+Request body:
+```json
+{
+ "name": "My Tool",
+ "slug": "my-tool",
+ "description": "Does X",
+ "category": "utility",
+ "tags": ["tag1"],
+ "schema_json": [...],
+ "is_public": true
+}
+```
+
+Validate: name 2–80 chars, slug matches `/^[a-z0-9-]+$/` max 60 chars, unique slug,
+description max 500 chars, schema_json is an array with at least 1 item, each item has
+`function.name` (string) and `function.parameters` (object).
+
+Response: `{ skill: { ...full row, author: {...} } }` with 201.
+
+### GET /api/skills/:id
+Returns full skill including `schema_json`. `installed` field present if authed.
+
+### PUT /api/skills/:id
+Requires auth. Only the author (or admin) can edit. Updates name/description/tags/is_public/schema_json.
+Slug is immutable after publish.
+
+### DELETE /api/skills/:id
+Requires auth. Only the author can delete. Also deletes all installs for that skill.
+Returns 204.
+
+### POST /api/skills/:id/install
+Requires auth. Installs skill for the current user. Increments `install_count` atomically.
+Idempotent (409 → treat as success, or just upsert). Returns `{ installed: true }`.
+
+### DELETE /api/skills/:id/install
+Requires auth. Uninstalls. Decrements `install_count` (floor at 0). Returns `{ installed: false }`.
+
+### POST /api/skills/:id/rate
+Requires auth. Upserts a rating (1–5). Returns `{ avg_rating, rating_count }`.
+
+## Implementation notes
+- All endpoints must set CORS headers via the shared `http.js` helper — look at how other
+ endpoints do it.
+- Use keyset pagination (cursor = last seen id) not offset.
+- The `avg_rating` field is computed via a JOIN or subquery against `skill_ratings`, not stored.
+- Apply `rate-limit.js` to POST endpoints (use the lightest available limiter for authenticated
+ users — read the file to pick the right one).
+- Do not write any UI code.
+- Do not modify existing files other than adding the new `/api/skills/` files.
+
+## Verification
+1. Read each file back and confirm there are no syntax errors.
+2. Confirm all SQL uses the tagged-template `sql` from `db.js` (no raw string concatenation).
+3. Confirm auth is checked on every mutating endpoint.
+4. Confirm pagination is correct (cursor-based, not offset).
diff --git a/tasks/skills-marketplace/03-marketplace-modal.md b/tasks/skills-marketplace/03-marketplace-modal.md
new file mode 100644
index 000000000..69bb6316c
--- /dev/null
+++ b/tasks/skills-marketplace/03-marketplace-modal.md
@@ -0,0 +1,108 @@
+# Task 03 — UI: SkillsMarketplaceModal.svelte
+
+## Goal
+Build a Svelte modal component for the skills marketplace. It lives at
+`/chat/src/SkillsMarketplaceModal.svelte`. When done, users can browse community skills,
+search/filter by category, install/uninstall, rate, and publish their own skills — all from
+within the chat UI.
+
+## Prerequisites
+Tasks 01 and 02 must be complete (DB + API exist and are functional).
+
+## Context
+- Framework: Svelte 4 (not SvelteKit — plain Svelte components)
+- Styling: Tailwind CSS utility classes (same as the rest of the chat UI)
+- Existing components to study and reuse:
+ - `/chat/src/Modal.svelte` — base modal wrapper, `export let open = false`
+ - `/chat/src/ToolPackModal.svelte` — current (simple) tool pack modal — read it fully; the
+ new component replaces the behaviour but not the file
+ - `/chat/src/Button.svelte` — read it
+ - `/chat/src/stores.js` — `toolSchema` (persisted writable of tool group array), `currentUser`,
+ `notify()` — read the full file
+- The `toolSchema` store shape: an array of `{ name: string, schema: ToolDef[] }`.
+ Each `ToolDef` matches the shape in `/chat/src/tools.js`.
+- API base: `/api/skills/` (built in Task 02).
+- This component does NOT import from `tools.js` — it fetches from the API instead.
+
+## Component spec
+
+### Props
+```svelte
+export let open = false; // bind:open from parent
+```
+
+### State (internal)
+- `view`: `'browse' | 'publish'` — tabs at the top
+- `skills`: array of skill objects from the API
+- `loading`: boolean
+- `searchQuery`: string (debounced, 300ms)
+- `selectedCategory`: string | null
+- `categories`: string[] derived from loaded skills
+- `page`: cursor string for pagination
+- `hasMore`: boolean
+- `publishForm`: `{ name, slug, description, category, tags, schemaText, isPublic }`
+- `publishError`: string | null
+- `publishLoading`: boolean
+
+### Layout
+
+#### Header
+- Tab bar: "Browse" | "Publish" — switching sets `view`
+- Close button (calls `open = false`)
+
+#### Browse view
+Left sidebar (~180px wide on desktop, collapsible to icons on narrow):
+- "All" category + dynamic list of categories from loaded skills
+- Show install count next to each category
+
+Main panel:
+- Search input at top (debounced)
+- Sort dropdown: Popular | Newest | A–Z
+- Skill card grid (2 cols desktop, 1 col mobile). Each card:
+ - Name + category badge
+ - Description (truncated at 2 lines)
+ - Install count + avg rating (⭐ n.n, or "No ratings yet")
+ - Author name (or "System" if null)
+ - **Install / Remove button** — calls `/api/skills/:id/install` (POST) or DELETE
+ - Optimistically toggles, rolls back on error
+ - On install: appends the skill's `schema_json` to `toolSchema` store as `{ name, schema }`
+ - On uninstall: removes from `toolSchema` by name match
+ - Clicking anywhere else on the card opens an inline expanded view (below the card row)
+ showing full description, tags, and a 1–5 star rating widget.
+
+Load more: "Load more" button at bottom (fetches next page using cursor).
+
+#### Publish view
+A form to publish a new skill:
+- Name input
+- Slug input (auto-derived from name, editable, shows live preview: `/skills/{slug}`)
+- Description textarea
+- Category input (text, with datalist suggestions from existing categories)
+- Tags input (comma-separated, shown as pills)
+- Schema editor: a `<textarea>` pre-filled with a JSON starter template
+ (one tool entry matching the ToolDef shape). Monospace font.
+ Below it, a "Validate JSON" button that parses and shows a green checkmark or red error.
+- Public/Private toggle
+- Submit button — POST to `/api/skills`
+
+On success: switch to Browse view, show a success notification via `notify()`, scroll to
+the new skill.
+
+### Error handling
+- API errors: show inline error message (not modal) next to the failing action
+- Auth required: if `$currentUser` is null, show "Sign in to install skills" inline — no redirect
+
+### No external dependencies
+Do not import any library not already in `/chat/package.json`. Use native `fetch`.
+
+## File to create
+`/chat/src/SkillsMarketplaceModal.svelte`
+
+## Verification
+1. Read back the file and confirm it is valid Svelte 4 syntax.
+2. Confirm `toolSchema` is correctly imported from `./stores.js` and updated on install/uninstall.
+3. Confirm the Publish form auto-derives slug from name (lowercase, replace spaces with `-`,
+ strip non-alphanumeric except `-`).
+4. Confirm no hardcoded skills — all data comes from the `/api/skills` fetch.
+5. Confirm the component compiles (run `cd /workspaces/3D-Agent/chat && npm run build` and fix
+ any errors before declaring done).
diff --git a/tasks/skills-marketplace/04-chat-integration.md b/tasks/skills-marketplace/04-chat-integration.md
new file mode 100644
index 000000000..d57672d70
--- /dev/null
+++ b/tasks/skills-marketplace/04-chat-integration.md
@@ -0,0 +1,98 @@
+# Task 04 — Chat Integration: Wire Marketplace into Chat UI
+
+## Goal
+Replace the existing "Tool Packs" button/modal in the chat toolbar with the new Skills
+Marketplace modal. Installed skills from the marketplace must surface as active tools in the
+LLM conversation exactly like the current hardcoded tool packs.
+
+## Prerequisites
+Tasks 01, 02, and 03 must be complete.
+
+## Context — what exists today
+
+### ToolPackModal (current)
+- `/chat/src/ToolPackModal.svelte` — simple modal that installs hardcoded packs from `tools.js`
+ into the `toolSchema` store. It stays in the codebase (don't delete it) but is no longer
+ the primary entry point.
+
+### App.svelte (main chat component, ~63KB)
+- Located at `/chat/src/App.svelte`
+- Read the **entire file** before making any changes — it is large and dense.
+- Find where `ToolPackModal` is imported and rendered.
+- Find where the toolbar button that opens it is rendered.
+- Find where `toolSchema` is consumed to build the tool list sent to the LLM.
+
+### stores.js
+- `toolSchema` — persisted writable, shape: `Array<{ name: string, schema: ToolDef[] }>`
+- The new `SkillsMarketplaceModal` (Task 03) already writes to this store on install/uninstall.
+
+## Changes to make
+
+### 1. App.svelte — swap modal and button
+
+Find the import of `ToolPackModal` and add an import for `SkillsMarketplaceModal`:
+```js
+import SkillsMarketplaceModal from './SkillsMarketplaceModal.svelte';
+```
+
+Find the state variable that controls the ToolPackModal's `open` prop (it will be something
+like `let showToolPacks = false`). Add a parallel variable:
+```js
+let showSkillsMarketplace = false;
+```
+
+Find the toolbar button that opens ToolPackModal. Add a second button immediately after it:
+```svelte
+<button
+ class="..." <!-- match the style of the existing tool-packs button exactly -->
+ on:click={() => (showSkillsMarketplace = true)}
+ title="Skills Marketplace"
+>
+ <!-- Use an appropriate icon from feather.js — "grid" or "package" works -->
+ <svelte:component this={Icon} name="grid" size={16} />
+ <span class="hidden sm:inline">Skills</span>
+</button>
+```
+
+Add the modal instance near the ToolPackModal instance:
+```svelte
+<SkillsMarketplaceModal bind:open={showSkillsMarketplace} />
+```
+
+### 2. Sync on open — pre-populate installed state
+When `showSkillsMarketplace` becomes true, the modal should show which skills are already
+installed (i.e. present in `toolSchema`). The `SkillsMarketplaceModal` already handles this by
+comparing API results against `$toolSchema` on the Browse fetch — no extra wiring needed.
+
+### 3. Verify toolSchema → LLM tools pipeline
+Search `App.svelte` for where `toolSchema` is read to build the tool array sent to the LLM
+provider (it likely maps over `$toolSchema` and flattens `.schema` arrays). Confirm it still
+works correctly — the marketplace installs skills in the same format as the existing ToolPackModal
+(`{ name, schema: ToolDef[] }`), so no change should be needed. If the pipeline looks different,
+document exactly what you found and adjust accordingly.
+
+### 4. Active skills indicator
+Find where the toolbar shows the count of active tools (if any). Update it to include
+marketplace-installed skills in the count. If no such indicator exists, add a simple badge
+on the Skills button showing `$toolSchema.length` when > 0:
+```svelte
+{#if $toolSchema.length > 0}
+ <span class="ml-1 rounded-full bg-indigo-500 px-1.5 py-0.5 text-[10px] text-white">
+ {$toolSchema.length}
+ </span>
+{/if}
+```
+
+## Constraints
+- **Surgical changes only.** Touch only the lines needed. Do not reformat, refactor, or clean up
+ unrelated code in App.svelte.
+- Do not remove or break the existing ToolPackModal — it should still work.
+- Do not change `stores.js`, `tools.js`, `convo.js`, or `providers.js`.
+- Match the exact class/style convention of the surrounding toolbar buttons.
+
+## Verification
+1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must complete with no errors.
+2. Read back the changed section of App.svelte and confirm the new button and modal binding are
+ present and syntactically correct.
+3. Confirm `ToolPackModal` is still imported and rendered (not removed).
+4. Confirm `showSkillsMarketplace` is initialised to `false`.
diff --git a/tasks/skills-marketplace/05-seed-and-categories.md b/tasks/skills-marketplace/05-seed-and-categories.md
new file mode 100644
index 000000000..5cf88ba87
--- /dev/null
+++ b/tasks/skills-marketplace/05-seed-and-categories.md
@@ -0,0 +1,105 @@
+# Task 05 — Seed Skills & Category Taxonomy
+
+## Goal
+Populate the skills marketplace with a rich set of seed skills so it is immediately useful when
+users open it. Also standardise the category list and add a categories endpoint. This task is
+primarily data + a small API addition.
+
+## Prerequisites
+Tasks 01 and 02 must be complete.
+
+## Part A — Expanded seed data migration
+
+Create `/api/_lib/migrations/2026-04-30-skills-seed.sql`.
+
+This migration inserts ready-to-use skills into `marketplace_skills`. All rows: `author_id = null`,
+`is_public = true`. Use `ON CONFLICT (slug) DO NOTHING` for idempotency.
+
+### Canonical categories (use exactly these strings)
+`finance`, `productivity`, `developer`, `data`, `media`, `utility`, `ai`
+
+### Skills to seed (build full valid `schema_json` for each)
+
+The `schema_json` must be a valid JSON array of tool definitions. Each element shape:
+```json
+{
+ "clientDefinition": {
+ "id": "unique-string",
+ "name": "ToolName",
+ "description": "...",
+ "arguments": [{ "name": "arg", "type": "string", "description": "..." }],
+ "body": "// JavaScript that returns { contentType, content } or a JSON-serialisable value"
+ },
+ "type": "function",
+ "function": {
+ "name": "ToolName",
+ "description": "When to use this tool — written for the LLM",
+ "parameters": {
+ "type": "object",
+ "properties": { "arg": { "type": "string", "description": "..." } },
+ "required": ["arg"]
+ }
+ }
+}
+```
+
+**Skills to create:**
+
+1. **tradingview-charts** (finance) — interactive TradingView price chart iframe
+2. **web-search** (utility) — DuckDuckGo search returning abstract + top topics
+3. **qr-code** (utility) — renders a QR code image via `api.qrserver.com`
+4. **calculator** (utility) — safe `eval`-less expression evaluator (use Function constructor)
+5. **markdown-preview** (productivity) — renders user-supplied markdown as styled HTML in an iframe
+6. **color-palette** (media) — given a theme description, generates a 5-colour palette as swatches
+7. **json-formatter** (developer) — pretty-prints and validates JSON input
+8. **regex-tester** (developer) — tests a regex against input, highlights matches
+9. **unit-converter** (utility) — converts between common units (length, weight, temperature, etc.)
+10. **mermaid-diagram** (developer) — renders a Mermaid.js diagram in an iframe using the CDN build
+11. **csv-table** (data) — renders CSV input as an HTML table with sorting
+12. **world-clock** (utility) — shows current time in N timezones side-by-side
+13. **image-from-url** (media) — renders an image URL in a resizable preview iframe
+14. **base64-codec** (developer) — encodes/decodes base64
+15. **word-counter** (productivity) — counts words, chars, sentences, reading time
+
+For each skill's `body`: write actual working JavaScript (not pseudocode). The body runs in the
+browser sandbox and returns a value. For HTML-rendering tools, return `{ contentType: 'text/html', content: htmlString }`.
+
+## Part B — Categories API endpoint
+
+Create `/api/skills/categories.js` handling `GET /api/skills/categories`.
+
+No auth required.
+
+Response:
+```json
+{
+ "categories": [
+ { "slug": "finance", "label": "Finance", "count": 4 },
+ { "slug": "productivity", "label": "Productivity", "count": 3 },
+ ...
+ ]
+}
+```
+
+Query: count of `is_public = true` skills per category, ordered by count desc.
+Include only categories with at least 1 public skill.
+
+Derive `label` from `slug` by title-casing.
+
+Cache-Control: `public, max-age=60` (categories change rarely).
+
+## Part C — Update SkillsMarketplaceModal to use categories API
+
+In `/chat/src/SkillsMarketplaceModal.svelte` (created in Task 03):
+
+Replace the client-side category derivation with a fetch to `/api/skills/categories` when the
+modal opens. This gives accurate counts even before skills are loaded.
+
+Change the existing `onMount` (or `$: if (open)` reactive block) to also fetch categories in
+parallel with the skills list fetch.
+
+## Verification
+1. Confirm the migration file is valid SQL (no JS syntax, proper JSON escaping in string literals).
+2. Confirm all 15 seed skills have valid `schema_json` — parse each manually.
+3. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass.
+4. Confirm categories endpoint returns correct structure.
diff --git a/tasks/skills-marketplace/06-skill-detail-and-ratings.md b/tasks/skills-marketplace/06-skill-detail-and-ratings.md
new file mode 100644
index 000000000..522bc285a
--- /dev/null
+++ b/tasks/skills-marketplace/06-skill-detail-and-ratings.md
@@ -0,0 +1,99 @@
+# Task 06 — UI: Skill Detail Panel & Ratings
+
+## Goal
+Add an expanded detail view inside the marketplace modal and a working star-rating widget.
+When a user clicks a skill card, a side panel (or inline expansion) shows full details,
+all tags, schema preview, author info, and lets the user leave a 1–5 star rating.
+
+## Prerequisites
+Tasks 01, 02, 03, 04, and 05 must be complete and building cleanly.
+
+## Context
+- File to edit: `/chat/src/SkillsMarketplaceModal.svelte`
+- Read the entire current file before changing anything.
+- API endpoints available (from Task 02):
+ - `GET /api/skills/:id` — full skill including `schema_json`
+ - `POST /api/skills/:id/rate` body `{ rating: 1-5 }` → `{ avg_rating, rating_count }`
+- `currentUser` store from `./stores.js` — null if not signed in
+- `notify` function from `./stores.js`
+
+## Changes
+
+### 1. SkillDetailPanel — inline expansion
+
+When the user clicks anywhere on a skill card (not the Install/Remove button), toggle an
+inline expansion directly below that card row. Only one card can be expanded at a time.
+
+The expanded panel contains:
+
+**Left column (60%)**
+- Full description (no truncation)
+- Tags as pills (styled with `bg-slate-100 text-slate-600 text-[11px] px-2 py-0.5 rounded-full`)
+- Author section: "By {author.display_name}" or "By the 3D-Agent team" if system skill
+- Install count + created date ("Published {relative date}")
+
+**Right column (40%)**
+- **Rating widget**: 5 stars, filled/empty based on `avg_rating`. If user is logged in and
+ hasn't rated yet, the stars are interactive (hover highlights, click submits). Show current
+ user's rating in a different colour if they've already rated.
+ - On click: POST to `/api/skills/:id/rate`, update displayed avg/count on success.
+ - If not logged in: stars are display-only with tooltip "Sign in to rate"
+- Schema preview: a `<pre>` block showing the first tool's `function.name` and
+ `function.description`, and a list of its parameter names. **Do not show the full schema JSON**
+ (it can be large). Just a human-readable summary.
+- If there are multiple tools in the schema, show "and N more tools" after the first.
+
+**Action row** (below both columns)
+- Same Install/Remove button as the card (redundant but more prominent)
+- A "Copy slug" button that writes the skill slug to clipboard and shows a brief "Copied!" toast
+
+### 2. Star rating component — extract as inline sub-component
+
+Write the star rating logic as a `<StarRating>` component defined inline in the file using
+Svelte's component syntax (not a separate file). Props:
+```svelte
+<!-- internal component -->
+let { value, interactive, onRate } = ...
+```
+
+If Svelte 4 doesn't support `$props()`, use `export let` props.
+
+Stars should animate on hover (scale 1.1 with CSS transition).
+
+### 3. Relative date helper
+
+Add a small helper function `relativeDate(isoString)` at the top of the `<script>` block:
+```js
+function relativeDate(iso) {
+ const diff = Date.now() - new Date(iso).getTime();
+ const days = Math.floor(diff / 86400000);
+ if (days === 0) return 'today';
+ if (days === 1) return 'yesterday';
+ if (days < 30) return `${days} days ago`;
+ if (days < 365) return `${Math.floor(days / 30)} months ago`;
+ return `${Math.floor(days / 365)} years ago`;
+}
+```
+
+### 4. Loading state for detail fetch
+
+When a card is clicked, immediately show a skeleton loader in the expanded area while
+`GET /api/skills/:id` loads. The skeleton should be a simple grey animated pulse div
+(use `animate-pulse bg-slate-200 rounded` Tailwind classes).
+
+### 5. Keyboard accessibility
+- Pressing Escape while the detail panel is open should close it (not the whole modal).
+- The expanded card should have `role="region"` and `aria-label="{skill.name} details"`.
+
+## Constraints
+- All changes go in `SkillsMarketplaceModal.svelte` only. No new files.
+- Do not change any API files.
+- Do not change `App.svelte`.
+
+## Verification
+1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass with no errors.
+2. Read back the changed file and confirm:
+ - Only one card can be expanded at a time (clicking another card collapses the previous).
+ - The rating POST is only triggered when the user is authenticated.
+ - The "Copy slug" uses `navigator.clipboard.writeText` with a fallback.
+ - The skeleton loader disappears once the detail fetch resolves.
diff --git a/tasks/skills-marketplace/07-installed-skills-toolbar.md b/tasks/skills-marketplace/07-installed-skills-toolbar.md
new file mode 100644
index 000000000..ee95bd4b7
--- /dev/null
+++ b/tasks/skills-marketplace/07-installed-skills-toolbar.md
@@ -0,0 +1,69 @@
+# Task 07 — UI: Installed Skills Toolbar Chip Strip
+
+## Goal
+When one or more skills are installed (i.e. `$toolSchema.length > 0`), show a horizontal strip
+of chips just above the chat input bar listing each installed skill by name, with an × to remove
+it. This makes the active skill set visible at a glance without opening the modal.
+
+## Prerequisites
+Tasks 01–04 must be complete and building cleanly.
+
+## Context
+- File to edit: `/chat/src/App.svelte` (read the entire file first)
+- `toolSchema` store: `Array<{ name: string, schema: ToolDef[] }>` from `./stores.js`
+- Find where the chat input component (`<Input ...>` or equivalent) is rendered. The chip strip
+ goes immediately above it, inside the same container.
+- The input area likely has classes like `border-t`, `px-4 py-2`, or similar — match the spacing.
+
+## What to build
+
+### Chip strip
+Add this block immediately above the chat input render point in App.svelte:
+
+```svelte
+{#if $toolSchema.length > 0}
+ <div class="flex flex-wrap gap-1.5 px-4 pt-2 pb-0">
+ {#each $toolSchema as group}
+ <span class="inline-flex items-center gap-1 rounded-full border border-indigo-200 bg-indigo-50 px-2.5 py-0.5 text-[11px] font-medium text-indigo-700">
+ {group.name}
+ <button
+ class="ml-0.5 rounded-full p-0.5 text-indigo-400 hover:bg-indigo-100 hover:text-indigo-600"
+ on:click={() => removeSkill(group.name)}
+ aria-label="Remove {group.name}"
+ >
+ <!-- feather x icon, 10px -->
+ </button>
+ </span>
+ {/each}
+ <button
+ class="text-[11px] text-slate-400 hover:text-slate-600"
+ on:click={() => (showSkillsMarketplace = true)}
+ >
+ + Add skill
+ </button>
+ </div>
+{/if}
+```
+
+### removeSkill helper
+Add this function in the App.svelte `<script>` block (near the other tool-related logic):
+```js
+function removeSkill(name) {
+ toolSchema.update(groups => groups.filter(g => g.name !== name));
+}
+```
+
+### Icon
+Use the existing `feather.js` / `Icon` component pattern already used in App.svelte for the
+× icon (look at how other small × close buttons are done in the file and match exactly).
+
+## Constraints
+- Surgical: only add the chip strip block and the `removeSkill` function. Nothing else.
+- Do not change the layout of the input area itself.
+- `showSkillsMarketplace` is already declared in App.svelte from Task 04 — do not re-declare it.
+
+## Verification
+1. Run `cd /workspaces/3D-Agent/chat && npm run build` — must pass.
+2. Confirm the chip strip only renders when `$toolSchema.length > 0`.
+3. Confirm clicking × removes only that group from `toolSchema`.
+4. Confirm "+ Add skill" opens the marketplace modal.
diff --git a/tasks/wallet-transactions/01-wallet-provider-store.md b/tasks/wallet-transactions/01-wallet-provider-store.md
new file mode 100644
index 000000000..684f64c29
--- /dev/null
+++ b/tasks/wallet-transactions/01-wallet-provider-store.md
@@ -0,0 +1,50 @@
+# Task 01 — Wallet Provider Store
+
+## Goal
+Expose a reactive Svelte store that tracks which wallet is currently connected (type, address, chainId). Tool bodies and other components can read this store instead of parsing `currentUser` or polling `window.solana`/`window.ethereum` directly.
+
+## Context
+- `chat/src/stores.js` holds all app-wide Svelte stores. `currentUser` already exists but only holds the server-side user record — it does not carry which wallet type is connected or the live provider reference.
+- `chat/src/walletAuth.js` exports `signInWithEVM()` and `signInWithSolana()`. Both return `{ user, wallet }` where `wallet = { type: 'evm'|'solana', address, chainId? }`.
+- `chat/src/WalletConnect.svelte` calls those functions and then calls `loadCurrentUser()` but does not persist the wallet object anywhere.
+- Tool bodies (eval'd JavaScript strings in `tools.js`) run in the browser and can call `import { get } from 'svelte/store'` or read a plain `window.__wallet` global.
+
+## Changes Required
+
+### 1. `chat/src/stores.js`
+Add after the `currentUser` store definition:
+
+```js
+export const walletProvider = writable(null);
+// Shape: { type: 'solana'|'evm', address: string, chainId?: number|string } | null
+```
+
+Add a helper used by tool bodies:
+```js
+export function getConnectedWallet() {
+ return get(walletProvider);
+}
+```
+
+Also expose it as a browser global so eval'd tool bodies can access it without imports:
+At the bottom of the file add:
+```js
+if (typeof window !== 'undefined') {
+ walletProvider.subscribe(w => { window.__wallet = w; });
+}
+```
+
+### 2. `chat/src/WalletConnect.svelte`
+- Import `walletProvider` from `./stores.js`
+- After successful `signInWithEVM()`: call `walletProvider.set(wallet)`
+- After successful `signInWithSolana()`: call `walletProvider.set(wallet)`
+- On sign-out (when `signOut()` is called): call `walletProvider.set(null)`
+
+### 3. `chat/src/walletAuth.js`
+No changes needed — `signInWithEVM` and `signInWithSolana` already return the `wallet` object with the right shape. The WalletConnect component is responsible for storing it.
+
+## Verification
+- After connecting a Solana wallet, `window.__wallet` in the browser console should be `{ type: 'solana', address: '...' }`.
+- After connecting an EVM wallet, `window.__wallet.type === 'evm'` and `window.__wallet.chainId` is present.
+- After sign-out, `window.__wallet === null`.
+- No other stores or components should be changed.
diff --git a/tasks/wallet-transactions/02-tx-approval-modal.md b/tasks/wallet-transactions/02-tx-approval-modal.md
new file mode 100644
index 000000000..adcc39c8a
--- /dev/null
+++ b/tasks/wallet-transactions/02-tx-approval-modal.md
@@ -0,0 +1,68 @@
+# Task 02 — Transaction Approval Modal
+
+## Goal
+Create a `TxApprovalModal.svelte` component that shows transaction details and Ask/Reject buttons before any wallet transaction executes. Wire it into `App.svelte` via a global `window.requestWalletApproval(details)` function that returns a Promise — tool bodies call this function to pause execution until the user approves or rejects.
+
+## Context
+- Tool bodies in `tools.js` are eval'd JavaScript strings that run in the browser. They can call `window.*` globals freely.
+- `chat/src/Choice.svelte` shows a similar "pause and wait for user input" pattern — study its props and how `Toolcall.svelte` renders it for reference style.
+- `chat/src/Modal.svelte` is an existing modal shell — use it as the outer wrapper.
+- `chat/src/Button.svelte` is the standard button component.
+- `chat/src/App.svelte` is where global UI overlays are mounted (search for where `<Notifications />` is rendered — add the modal nearby).
+
+## `TxApprovalModal.svelte` — New File at `chat/src/TxApprovalModal.svelte`
+
+Props:
+```js
+export let details; // { network, from, to, amount, token, memo?, estimatedFee? }
+export let onApprove; // () => void
+export let onReject; // () => void
+```
+
+UI layout (use existing Tailwind classes that match the app's dark slate aesthetic):
+- Title: "Approve Transaction"
+- Network badge: e.g. "Solana" or "Ethereum / Base / etc."
+- Table of rows: From, To, Amount, Token, Memo (if present), Estimated Fee (if present)
+- Long addresses: truncate to first 6 + `…` + last 4 chars
+- Two full-width buttons at bottom: "Reject" (secondary/outline) and "Approve" (primary/accent)
+- Disabled state on both buttons while a `pending` flag is true (set true on Approve click, to prevent double-submit)
+
+## `App.svelte` Changes
+
+1. Import `TxApprovalModal`.
+2. Add reactive vars:
+ ```js
+ let txApprovalDetails = null;
+ let txApprovalResolve = null;
+ let txApprovalReject = null;
+ ```
+3. In `onMount` (or a top-level `if (typeof window !== 'undefined')` block), assign:
+ ```js
+ window.requestWalletApproval = (details) => new Promise((resolve, reject) => {
+ txApprovalDetails = details;
+ txApprovalResolve = resolve;
+ txApprovalReject = reject;
+ });
+ ```
+4. Mount the modal conditionally in the template:
+ ```svelte
+ {#if txApprovalDetails}
+ <TxApprovalModal
+ details={txApprovalDetails}
+ onApprove={() => { txApprovalResolve(); txApprovalDetails = null; }}
+ onReject={() => { txApprovalReject(new Error('User rejected transaction')); txApprovalDetails = null; }}
+ />
+ {/if}
+ ```
+ Render this at the very end of the `<body>` content so it overlays everything.
+
+## Verification
+- Open the browser console and run:
+ ```js
+ window.requestWalletApproval({ network: 'Solana', from: 'ABC123', to: 'XYZ789', amount: 1.5, token: 'SOL' })
+ .then(() => console.log('approved'))
+ .catch(e => console.log('rejected:', e.message));
+ ```
+ The modal should appear. Clicking Approve logs "approved". Clicking Reject logs "rejected: User rejected transaction".
+- The modal must be centered/overlaid on the full viewport with a dark backdrop.
+- No existing functionality in App.svelte should change.
diff --git a/tasks/wallet-transactions/03-tx-result-display.md b/tasks/wallet-transactions/03-tx-result-display.md
new file mode 100644
index 000000000..59e6178fd
--- /dev/null
+++ b/tasks/wallet-transactions/03-tx-result-display.md
@@ -0,0 +1,94 @@
+# Task 03 — Transaction Result Display in Toolcall
+
+## Goal
+Add a `tx_result` display type to `Toolcall.svelte` so wallet transaction tool results render as a clean status card (hash, explorer link, amount, status badge) instead of raw JSON.
+
+## Context
+- `chat/src/Toolcall.svelte` already handles `image`, `webpage`, `markdown`, and `choice` display types by checking `toolresponse.content.contentType`.
+- Tool bodies return `{ contentType: 'application/tx-result', content: { ... } }` to trigger this display type.
+- Explorer base URLs by network:
+ - `solana` mainnet: `https://solscan.io/tx/`
+ - `solana` devnet: `https://solscan.io/tx/?cluster=devnet`
+ - EVM chain 1 (Ethereum): `https://etherscan.io/tx/`
+ - EVM chain 8453 (Base): `https://basescan.org/tx/`
+ - EVM chain 10 (Optimism): `https://optimistic.etherscan.io/tx/`
+ - EVM chain 42161 (Arbitrum): `https://arbiscan.io/tx/`
+ - EVM chain 137 (Polygon): `https://polygonscan.com/tx/`
+
+## Expected `content` Shape
+```js
+{
+ status: 'success' | 'failed' | 'pending',
+ txHash: string, // Solana signature or EVM 0x... hash
+ network: string, // 'solana' | 'ethereum' | 'base' | etc.
+ chainId?: number, // EVM only
+ from: string,
+ to: string,
+ amount: string, // human-readable, e.g. "1.5"
+ token: string, // e.g. "SOL", "USDC", "ETH"
+ explorerUrl: string, // full URL to block explorer
+}
+```
+
+## Changes to `chat/src/Toolcall.svelte`
+
+### 1. Detection logic
+In the reactive block that sets `displayType`, add:
+```js
+} else if (contentType === 'application/tx-result') {
+ displayType = 'tx_result';
+}
+```
+
+### 2. Template block
+In the `{#if !collapsable || toolcall.expanded}` section, add a new branch after the `'choice'` block:
+
+```svelte
+{:else if toolresponse && displayType === 'tx_result'}
+ <div class="flex flex-col rounded-b-lg border border-t-0 border-slate-200 px-5 py-4 gap-3">
+ <!-- Status badge -->
+ <div class="flex items-center gap-2">
+ {#if displayedContent.status === 'success'}
+ <span class="rounded-full bg-emerald-100 px-2.5 py-0.5 text-xs font-medium text-emerald-700">Confirmed</span>
+ {:else if displayedContent.status === 'pending'}
+ <span class="rounded-full bg-yellow-100 px-2.5 py-0.5 text-xs font-medium text-yellow-700">Pending</span>
+ {:else}
+ <span class="rounded-full bg-red-100 px-2.5 py-0.5 text-xs font-medium text-red-700">Failed</span>
+ {/if}
+ <span class="text-sm font-medium text-slate-700">{displayedContent.amount} {displayedContent.token}</span>
+ <span class="text-xs text-slate-400">on {displayedContent.network}</span>
+ </div>
+
+ <!-- Addresses -->
+ <div class="grid grid-cols-[auto_1fr] gap-x-3 gap-y-1 text-xs text-slate-600 font-mono">
+ <span class="text-slate-400 font-sans">From</span>
+ <span>{displayedContent.from?.slice(0,6)}…{displayedContent.from?.slice(-4)}</span>
+ <span class="text-slate-400 font-sans">To</span>
+ <span>{displayedContent.to?.slice(0,6)}…{displayedContent.to?.slice(-4)}</span>
+ </div>
+
+ <!-- Tx hash + explorer link -->
+ <div class="flex items-center gap-2 text-xs font-mono text-slate-500">
+ <span>{displayedContent.txHash?.slice(0,12)}…{displayedContent.txHash?.slice(-6)}</span>
+ <a
+ href={displayedContent.explorerUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ class="ml-auto whitespace-nowrap rounded border border-slate-200 px-2 py-0.5 text-[10px] font-sans text-slate-600 hover:bg-slate-50 transition-colors"
+ >
+ View on Explorer ↗
+ </a>
+ </div>
+ </div>
+{/if}
+```
+
+### 3. `displayedContent` assignment
+The existing reactive block already sets `displayedContent = toolresponse.content.content`. For `tx_result`, the full object IS the content — make sure the assignment in the block uses `displayedContent = toolresponse.content.content` which should already be the parsed object if the tool returns it correctly.
+
+If `toolresponse.content` is the raw object (i.e., `{ contentType: 'application/tx-result', content: { status, txHash, ... } }`), then `displayedContent = toolresponse.content.content` is already correct.
+
+## Verification
+- No existing display types (image, webpage, markdown, choice) should be affected.
+- A tool response with `contentType: 'application/tx-result'` renders the card, not raw JSON.
+- The "View code / View component" toggle button still works for this display type.
diff --git a/tasks/wallet-transactions/04-solana-tx-api.md b/tasks/wallet-transactions/04-solana-tx-api.md
new file mode 100644
index 000000000..b34b63f99
--- /dev/null
+++ b/tasks/wallet-transactions/04-solana-tx-api.md
@@ -0,0 +1,130 @@
+# Task 04 — Backend: Solana Transaction Builder API
+
+## Goal
+Create a single API file `api/tx/solana/[action].js` with two endpoints:
+- `POST /api/tx/solana/build-transfer` — builds a serialized Solana transaction for SOL or SPL token transfer
+- `POST /api/tx/solana/build-swap` — fetches a swap transaction from Jupiter v6 for any token pair
+
+The frontend tool body will call these endpoints, receive a base64-encoded serialized transaction, have the user sign it via `window.solana`, then broadcast it.
+
+## Context
+- Existing API files (e.g., `api/payments/solana/[action].js`) use helpers from `api/_lib/`:
+ - `cors`, `json`, `method`, `readJson`, `wrap`, `error` from `api/_lib/http.js`
+ - `getSessionUser` from `api/_lib/auth.js`
+ - `parse` + `z` (zod) from `api/_lib/validate.js`
+ - `limits`, `clientIp` from `api/_lib/rate-limit.js`
+- Solana RPC env vars: `SOLANA_RPC_URL` (mainnet), `SOLANA_RPC_URL_DEVNET`
+- Available npm packages (already in package.json or resolvable): `@solana/web3.js`, `@solana/spl-token`
+
+## `api/tx/solana/[action].js`
+
+### Imports
+```js
+import { z } from 'zod';
+import {
+ Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,
+ sendAndConfirmTransaction
+} from '@solana/web3.js';
+import {
+ getOrCreateAssociatedTokenAccount, createTransferInstruction,
+ getMint, getAssociatedTokenAddress
+} from '@solana/spl-token';
+import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
+import { getSessionUser } from '../../_lib/auth.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { parse } from '../../_lib/validate.js';
+```
+
+### `handleBuildTransfer`
+
+Schema:
+```js
+const transferSchema = z.object({
+ sender: z.string(), // base58 sender public key
+ recipient: z.string(), // base58 recipient public key
+ amount: z.number().positive(), // human-readable (e.g. 1.5 SOL or 10 USDC)
+ token: z.string().default('SOL'), // 'SOL' or SPL mint address
+ memo: z.string().optional(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+});
+```
+
+Logic:
+1. Validate auth: require `getSessionUser` (return 401 if not signed in).
+2. Build `Connection` from RPC URL based on network.
+3. If `token === 'SOL'`:
+ - `SystemProgram.transfer({ fromPubkey, toPubkey, lamports: amount * LAMPORTS_PER_SOL })`
+4. If token is an SPL mint address:
+ - Get sender ATA: `getAssociatedTokenAddress(mint, senderPubkey)`
+ - Get recipient ATA: `getAssociatedTokenAddress(mint, recipientPubkey)`
+ - Get mint decimals via `getMint(connection, mint)`
+ - Build `createTransferInstruction(senderATA, recipientATA, senderPubkey, amountInSmallestUnit)`
+ - Note: the transaction includes creating the recipient ATA if it doesn't exist (add `createAssociatedTokenAccountInstruction` if needed, checking `connection.getAccountInfo(recipientATA)`)
+5. Fetch recent blockhash: `connection.getLatestBlockhash()`
+6. Assemble `Transaction`, set `feePayer = senderPubkey`, set `recentBlockhash`
+7. If memo is provided, add a memo instruction using the SPL Memo program: `new TransactionInstruction({ keys: [], programId: new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr'), data: Buffer.from(memo, 'utf-8') })`
+8. Serialize: `tx.serialize({ requireAllSignatures: false })` → base64
+9. Return:
+```js
+json(res, 200, {
+ transaction: base64EncodedTx,
+ network,
+ blockhash: latestBlockhash.blockhash,
+ lastValidBlockHeight: latestBlockhash.lastValidBlockHeight,
+});
+```
+
+### `handleBuildSwap`
+
+Schema:
+```js
+const swapSchema = z.object({
+ sender: z.string(), // base58 wallet pubkey
+ inputMint: z.string(), // token mint to sell
+ outputMint: z.string(), // token mint to buy
+ amount: z.number().positive(), // human-readable input amount
+ slippageBps: z.number().int().min(1).max(5000).default(50),
+ network: z.enum(['mainnet']).default('mainnet'), // Jupiter only supports mainnet
+});
+```
+
+Logic:
+1. Require auth.
+2. Get mint decimals for `inputMint` via RPC to compute `amountInSmallestUnit`.
+3. Fetch Jupiter v6 quote:
+ ```
+ GET https://quote-api.jup.ag/v6/quote?inputMint={inputMint}&outputMint={outputMint}&amount={amountInSmallestUnit}&slippageBps={slippageBps}
+ ```
+4. If quote fails or no routes, return 422 with `{ error: 'no_route', message: 'No swap route found' }`.
+5. Fetch swap transaction from Jupiter:
+ ```
+ POST https://quote-api.jup.ag/v6/swap
+ Body: { quoteResponse: <quote>, userPublicKey: sender, wrapAndUnwrapSol: true }
+ ```
+6. Return:
+```js
+json(res, 200, {
+ transaction: swapResponse.swapTransaction, // already base64
+ network: 'mainnet',
+ inputAmount: amount,
+ outputAmount: quoteResponse.outAmount / 10**outputDecimals,
+ outputMint,
+ priceImpactPct: quoteResponse.priceImpactPct,
+});
+```
+
+### Router
+```js
+export default wrap(async (req, res) => {
+ const action = req.url.split('/').pop().split('?')[0];
+ if (action === 'build-transfer') return handleBuildTransfer(req, res);
+ if (action === 'build-swap') return handleBuildSwap(req, res);
+ return error(res, 404, 'not_found', 'unknown action');
+});
+```
+
+## Verification
+- `POST /api/tx/solana/build-transfer` with `{ sender, recipient, amount: 0.001, token: 'SOL', network: 'devnet' }` returns `{ transaction: '<base64>', blockhash, lastValidBlockHeight }`.
+- `POST /api/tx/solana/build-swap` with a valid Jupiter mainnet pair returns `{ transaction, outputAmount, priceImpactPct }`.
+- Unauthenticated requests return 401.
+- Invalid body returns 400/422.
diff --git a/tasks/wallet-transactions/05-solana-wallet-tools.md b/tasks/wallet-transactions/05-solana-wallet-tools.md
new file mode 100644
index 000000000..52c73552d
--- /dev/null
+++ b/tasks/wallet-transactions/05-solana-wallet-tools.md
@@ -0,0 +1,214 @@
+# Task 05 — Frontend: Solana Wallet Tools
+
+## Goal
+Add two new tools to `chat/src/tools.js` — `solana_transfer` and `solana_swap` — that the LLM can invoke to execute Solana transactions from within chat. Each tool:
+1. Calls the backend API (built in Task 04) to get a serialized transaction.
+2. Calls `window.requestWalletApproval(details)` (set up in Task 02) to pause for user confirmation.
+3. Signs the transaction with `window.solana`.
+4. Broadcasts via the Solana RPC.
+5. Returns a `tx_result` content object (rendered by Task 03).
+
+## Context
+- Tool bodies are JavaScript strings stored in `clientDefinition.body`. They are eval'd in the browser context. They can use `fetch`, `window.*`, and `async/await`.
+- `window.__wallet` holds `{ type, address }` (set up in Task 01).
+- `window.requestWalletApproval(details)` returns a Promise that resolves on user approval, rejects on cancel (Task 02).
+- `window.solana` is the Phantom/Solana wallet adapter.
+- Tool body receives its arguments as local variables matching the `arguments` array names.
+- Add these tools to the existing `pumpToolSchema` array at the bottom of that array (or create a new `walletToolSchema` — see Task 07).
+
+## Common Explorer URL helper (inline in each body)
+
+```js
+const solscanBase = network === 'devnet'
+ ? 'https://solscan.io/tx/'
+ : 'https://solscan.io/tx/';
+```
+Both mainnet and devnet use solscan; devnet links append `?cluster=devnet`.
+
+---
+
+## Tool 1: `solana_transfer`
+
+### `clientDefinition`
+```js
+{
+ name: 'solana_transfer',
+ description: 'Send SOL or a Solana SPL token (e.g. USDC) to a recipient address. Requires a connected Solana wallet.',
+ arguments: [
+ { name: 'recipient', type: 'string', description: 'Base58 recipient wallet address' },
+ { name: 'amount', type: 'number', description: 'Amount to send in human-readable units (e.g. 1.5 for 1.5 SOL)' },
+ { name: 'token', type: 'string', description: 'Token to send: "SOL" or an SPL mint address (e.g. USDC mint). Default: "SOL"' },
+ { name: 'memo', type: 'string', description: 'Optional memo string to attach' },
+ { name: 'network', type: 'string', description: '"mainnet" or "devnet". Default: "mainnet"' },
+ ],
+ async body({ recipient, amount, token = 'SOL', memo, network = 'mainnet' }) {
+ const wallet = window.__wallet;
+ if (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected. Please connect a Solana wallet first.');
+
+ // 1. Build transaction on backend
+ const buildRes = await fetch('/api/tx/solana/build-transfer', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ sender: wallet.address, recipient, amount, token, memo, network }),
+ });
+ if (!buildRes.ok) {
+ const err = await buildRes.json().catch(() => ({}));
+ throw new Error(err.message || 'Failed to build transaction');
+ }
+ const { transaction: txBase64 } = await buildRes.json();
+
+ // 2. Request user approval
+ await window.requestWalletApproval({
+ network: network === 'devnet' ? 'Solana Devnet' : 'Solana',
+ from: wallet.address,
+ to: recipient,
+ amount: String(amount),
+ token,
+ memo,
+ });
+
+ // 3. Deserialize, sign, and send
+ const txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));
+ // Use wallet.signAndSendTransaction if available (Phantom), else signTransaction + manual broadcast
+ let signature;
+ if (window.solana.signAndSendTransaction) {
+ const { Transaction } = await import('https://esm.sh/@solana/web3.js@1');
+ const tx = Transaction.from(txBytes);
+ const result = await window.solana.signAndSendTransaction(tx);
+ signature = result.signature;
+ } else {
+ throw new Error('Wallet does not support signAndSendTransaction');
+ }
+
+ const explorerUrl = `https://solscan.io/tx/${signature}${network === 'devnet' ? '?cluster=devnet' : ''}`;
+
+ return {
+ contentType: 'application/tx-result',
+ content: {
+ status: 'success',
+ txHash: signature,
+ network: network === 'devnet' ? 'Solana Devnet' : 'Solana',
+ from: wallet.address,
+ to: recipient,
+ amount: String(amount),
+ token,
+ explorerUrl,
+ },
+ };
+ }
+}
+```
+
+### `function` schema (OpenAI-compatible)
+```js
+{
+ name: 'solana_transfer',
+ description: 'Send SOL or SPL tokens on Solana. Requires a connected Solana wallet.',
+ parameters: {
+ type: 'object',
+ properties: {
+ recipient: { type: 'string', description: 'Base58 recipient wallet address' },
+ amount: { type: 'number', description: 'Amount in human-readable units' },
+ token: { type: 'string', description: '"SOL" or SPL mint address. Default: "SOL"' },
+ memo: { type: 'string', description: 'Optional memo' },
+ network: { type: 'string', enum: ['mainnet', 'devnet'], description: 'Default: mainnet' },
+ },
+ required: ['recipient', 'amount'],
+ },
+}
+```
+
+---
+
+## Tool 2: `solana_swap`
+
+### `clientDefinition`
+```js
+{
+ name: 'solana_swap',
+ description: 'Swap tokens on Solana via Jupiter aggregator. Finds the best route automatically. Requires a connected Solana wallet.',
+ arguments: [
+ { name: 'inputMint', type: 'string', description: 'Mint address of the token to sell (e.g. USDC: EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v)' },
+ { name: 'outputMint', type: 'string', description: 'Mint address of the token to buy (e.g. SOL: So11111111111111111111111111111111111111112)' },
+ { name: 'amount', type: 'number', description: 'Amount of input token to sell in human-readable units' },
+ { name: 'slippageBps', type: 'number', description: 'Max slippage in basis points (100 = 1%). Default: 50' },
+ ],
+ async body({ inputMint, outputMint, amount, slippageBps = 50 }) {
+ const wallet = window.__wallet;
+ if (!wallet || wallet.type !== 'solana') throw new Error('No Solana wallet connected.');
+
+ // 1. Build swap transaction
+ const buildRes = await fetch('/api/tx/solana/build-swap', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ sender: wallet.address, inputMint, outputMint, amount, slippageBps }),
+ });
+ if (!buildRes.ok) {
+ const err = await buildRes.json().catch(() => ({}));
+ throw new Error(err.message || 'Failed to get swap route');
+ }
+ const { transaction: txBase64, outputAmount, priceImpactPct } = await buildRes.json();
+
+ // 2. Request approval
+ await window.requestWalletApproval({
+ network: 'Solana',
+ from: wallet.address,
+ to: 'Jupiter (DEX aggregator)',
+ amount: String(amount),
+ token: `${inputMint.slice(0,6)}… → ${outputMint.slice(0,6)}…`,
+ memo: `~${outputAmount} out, ${priceImpactPct}% price impact`,
+ });
+
+ // 3. Sign and send
+ const txBytes = Uint8Array.from(atob(txBase64), c => c.charCodeAt(0));
+ const { Transaction } = await import('https://esm.sh/@solana/web3.js@1');
+ const tx = Transaction.from(txBytes);
+ const result = await window.solana.signAndSendTransaction(tx);
+ const signature = result.signature;
+
+ return {
+ contentType: 'application/tx-result',
+ content: {
+ status: 'success',
+ txHash: signature,
+ network: 'Solana',
+ from: wallet.address,
+ to: outputMint,
+ amount: String(outputAmount),
+ token: outputMint.slice(0, 8) + '…',
+ explorerUrl: `https://solscan.io/tx/${signature}`,
+ },
+ };
+ }
+}
+```
+
+### `function` schema
+```js
+{
+ name: 'solana_swap',
+ description: 'Swap tokens on Solana via Jupiter. Best-route aggregation.',
+ parameters: {
+ type: 'object',
+ properties: {
+ inputMint: { type: 'string', description: 'Mint address of token to sell' },
+ outputMint: { type: 'string', description: 'Mint address of token to buy' },
+ amount: { type: 'number', description: 'Amount of input token in human-readable units' },
+ slippageBps: { type: 'number', description: 'Max slippage in bps. Default: 50' },
+ },
+ required: ['inputMint', 'outputMint', 'amount'],
+ },
+}
+```
+
+---
+
+## Where to Add in `tools.js`
+Add both tools to the `pumpToolSchema` array. Each entry needs both `clientDefinition` and `function` keys, matching the pattern of existing tools in that array.
+
+## Verification
+- The LLM can see both tools when `pumpToolSchema` tools are active.
+- Calling `solana_transfer` from chat (with a connected Phantom wallet on devnet) shows the approval modal, then on approve attempts to sign and submit the transaction.
+- If no wallet is connected, the tool throws a clear error message that the LLM relays to the user.
diff --git a/tasks/wallet-transactions/06-evm-wallet-tools.md b/tasks/wallet-transactions/06-evm-wallet-tools.md
new file mode 100644
index 000000000..a759220fa
--- /dev/null
+++ b/tasks/wallet-transactions/06-evm-wallet-tools.md
@@ -0,0 +1,234 @@
+# Task 06 — Frontend: EVM Wallet Tools
+
+## Goal
+Add two tools — `evm_transfer` and `evm_swap` — to `chat/src/tools.js` that execute EVM transactions from chat. Unlike Solana, EVM wallets (MetaMask) handle transaction building, signing, and broadcasting natively via `window.ethereum`, so no backend endpoint is needed for transfer. Swap uses the 1inch Fusion+ API for calldata.
+
+## Context
+- `window.__wallet` holds `{ type: 'evm', address, chainId }` after EVM sign-in (Task 01).
+- `window.ethereum` is the MetaMask provider. Use `eth_sendTransaction` RPC call to send.
+- `window.requestWalletApproval(details)` pauses for user confirmation (Task 02).
+- ERC20 ABI for transfer: `transfer(address to, uint256 amount)` → selector `0xa9059cbb`
+- MetaMask will show its own native confirmation after our approval modal — that's expected and fine.
+- For swaps, use the 1inch v5 API (no auth key needed for public quotes): `https://api.1inch.dev/swap/v5.2/{chainId}/swap`
+
+## Tool 1: `evm_transfer`
+
+### `clientDefinition`
+```js
+{
+ name: 'evm_transfer',
+ description: 'Send ETH or an ERC20 token to a recipient address on any EVM chain. Requires a connected EVM wallet (MetaMask or compatible).',
+ arguments: [
+ { name: 'recipient', type: 'string', description: '0x recipient address' },
+ { name: 'amount', type: 'string', description: 'Amount in human-readable units (e.g. "0.01" for 0.01 ETH)' },
+ { name: 'token', type: 'string', description: '"ETH" for native token, or an ERC20 contract address (0x...). Default: "ETH"' },
+ { name: 'decimals', type: 'number', description: 'Token decimals (required for ERC20, ignored for ETH). Default: 18' },
+ ],
+ async body({ recipient, amount, token = 'ETH', decimals = 18 }) {
+ const wallet = window.__wallet;
+ if (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected. Please connect MetaMask or a compatible wallet.');
+
+ // Chain name lookup
+ const chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };
+ const networkName = chainNames[wallet.chainId] || `Chain ${wallet.chainId}`;
+
+ // 1. Request approval
+ await window.requestWalletApproval({
+ network: networkName,
+ from: wallet.address,
+ to: recipient,
+ amount,
+ token: token === 'ETH' ? 'ETH' : `${token.slice(0, 8)}…`,
+ });
+
+ // 2. Build and send transaction
+ let txHash;
+ if (token === 'ETH') {
+ // Native ETH transfer
+ const valueHex = '0x' + BigInt(Math.round(parseFloat(amount) * 1e18)).toString(16);
+ txHash = await window.ethereum.request({
+ method: 'eth_sendTransaction',
+ params: [{ from: wallet.address, to: recipient, value: valueHex }],
+ });
+ } else {
+ // ERC20 transfer
+ const amountBigInt = BigInt(Math.round(parseFloat(amount) * 10 ** decimals));
+ // Encode transfer(address, uint256) calldata
+ const selector = '0xa9059cbb';
+ const paddedTo = recipient.slice(2).padStart(64, '0');
+ const paddedAmount = amountBigInt.toString(16).padStart(64, '0');
+ const data = selector + paddedTo + paddedAmount;
+ txHash = await window.ethereum.request({
+ method: 'eth_sendTransaction',
+ params: [{ from: wallet.address, to: token, data }],
+ });
+ }
+
+ // 3. Explorer URL
+ const explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };
+ const explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;
+
+ return {
+ contentType: 'application/tx-result',
+ content: {
+ status: 'pending', // EVM tx is pending until mined; wallet confirmation happens outside this tool
+ txHash,
+ network: networkName,
+ chainId: wallet.chainId,
+ from: wallet.address,
+ to: recipient,
+ amount,
+ token: token === 'ETH' ? 'ETH' : token.slice(0, 10) + '…',
+ explorerUrl,
+ },
+ };
+ }
+}
+```
+
+### `function` schema
+```js
+{
+ name: 'evm_transfer',
+ description: 'Send ETH or ERC20 tokens on any EVM chain (Ethereum, Base, Optimism, Arbitrum, Polygon).',
+ parameters: {
+ type: 'object',
+ properties: {
+ recipient: { type: 'string', description: '0x recipient address' },
+ amount: { type: 'string', description: 'Amount in human-readable units' },
+ token: { type: 'string', description: '"ETH" or ERC20 contract address. Default: "ETH"' },
+ decimals: { type: 'number', description: 'ERC20 decimals. Default: 18' },
+ },
+ required: ['recipient', 'amount'],
+ },
+}
+```
+
+---
+
+## Tool 2: `evm_swap`
+
+### `clientDefinition`
+```js
+{
+ name: 'evm_swap',
+ description: 'Swap tokens on EVM chains using 1inch aggregator. Finds best DEX route. Requires a connected EVM wallet.',
+ arguments: [
+ { name: 'fromToken', type: 'string', description: 'Token contract address to sell (use "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE" for native ETH)' },
+ { name: 'toToken', type: 'string', description: 'Token contract address to buy' },
+ { name: 'amount', type: 'string', description: 'Amount of fromToken in human-readable units' },
+ { name: 'decimals', type: 'number', description: 'Decimals of fromToken. Default: 18' },
+ { name: 'slippage', type: 'number', description: 'Max slippage percentage (e.g. 1 for 1%). Default: 1' },
+ ],
+ async body({ fromToken, toToken, amount, decimals = 18, slippage = 1 }) {
+ const wallet = window.__wallet;
+ if (!wallet || wallet.type !== 'evm') throw new Error('No EVM wallet connected.');
+
+ const chainNames = { 1: 'Ethereum', 8453: 'Base', 10: 'Optimism', 42161: 'Arbitrum', 137: 'Polygon' };
+ const networkName = chainNames[wallet.chainId] || `Chain ${wallet.chainId}`;
+ const amountWei = BigInt(Math.round(parseFloat(amount) * 10 ** decimals)).toString();
+
+ // 1. Get swap calldata from 1inch
+ const quoteUrl = `https://api.1inch.dev/swap/v5.2/${wallet.chainId}/swap?src=${fromToken}&dst=${toToken}&amount=${amountWei}&from=${wallet.address}&slippage=${slippage}&disableEstimate=true`;
+ const quoteRes = await fetch(quoteUrl, {
+ headers: { 'Accept': 'application/json' },
+ });
+ if (!quoteRes.ok) {
+ const err = await quoteRes.json().catch(() => ({}));
+ throw new Error(err.description || 'Failed to get swap quote from 1inch');
+ }
+ const quote = await quoteRes.json();
+
+ const toAmountHuman = (Number(quote.toAmount) / 10 ** 18).toFixed(6); // approximate; real decimals of toToken unknown here
+
+ // 2. Request approval
+ await window.requestWalletApproval({
+ network: networkName,
+ from: wallet.address,
+ to: `1inch Router`,
+ amount,
+ token: `${fromToken.slice(0,8)}… → ${toToken.slice(0,8)}…`,
+ memo: `~${toAmountHuman} out`,
+ });
+
+ // 3. Check allowance and approve if needed (ERC20 only)
+ const ETH_ADDRESS = '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE';
+ if (fromToken.toLowerCase() !== ETH_ADDRESS.toLowerCase()) {
+ // Check current allowance
+ const allowanceSelector = '0xdd62ed3e';
+ const paddedOwner = wallet.address.slice(2).padStart(64, '0');
+ const paddedSpender = quote.tx.to.slice(2).padStart(64, '0');
+ const allowanceData = allowanceSelector + paddedOwner + paddedSpender;
+ const allowanceHex = await window.ethereum.request({
+ method: 'eth_call',
+ params: [{ to: fromToken, data: allowanceData }, 'latest'],
+ });
+ const allowance = BigInt(allowanceHex || '0x0');
+ const needed = BigInt(amountWei);
+ if (allowance < needed) {
+ // Approve max
+ const approveSelector = '0x095ea7b3';
+ const maxUint256 = 'f'.repeat(64);
+ const approveData = approveSelector + paddedSpender + maxUint256;
+ await window.ethereum.request({
+ method: 'eth_sendTransaction',
+ params: [{ from: wallet.address, to: fromToken, data: approveData }],
+ });
+ }
+ }
+
+ // 4. Send swap transaction
+ const txHash = await window.ethereum.request({
+ method: 'eth_sendTransaction',
+ params: [{ from: wallet.address, to: quote.tx.to, data: quote.tx.data, value: quote.tx.value || '0x0' }],
+ });
+
+ const explorerBases = { 1: 'https://etherscan.io/tx/', 8453: 'https://basescan.org/tx/', 10: 'https://optimistic.etherscan.io/tx/', 42161: 'https://arbiscan.io/tx/', 137: 'https://polygonscan.com/tx/' };
+ const explorerUrl = (explorerBases[wallet.chainId] || 'https://etherscan.io/tx/') + txHash;
+
+ return {
+ contentType: 'application/tx-result',
+ content: {
+ status: 'pending',
+ txHash,
+ network: networkName,
+ chainId: wallet.chainId,
+ from: wallet.address,
+ to: toToken,
+ amount: `~${toAmountHuman}`,
+ token: toToken.slice(0, 10) + '…',
+ explorerUrl,
+ },
+ };
+ }
+}
+```
+
+### `function` schema
+```js
+{
+ name: 'evm_swap',
+ description: 'Swap ERC20 tokens or ETH on EVM chains via 1inch DEX aggregator.',
+ parameters: {
+ type: 'object',
+ properties: {
+ fromToken: { type: 'string', description: 'Token to sell (address or 0xEeee... for ETH)' },
+ toToken: { type: 'string', description: 'Token to buy (address)' },
+ amount: { type: 'string', description: 'Amount of fromToken in human-readable units' },
+ decimals: { type: 'number', description: 'fromToken decimals. Default: 18' },
+ slippage: { type: 'number', description: 'Max slippage %. Default: 1' },
+ },
+ required: ['fromToken', 'toToken', 'amount'],
+ },
+}
+```
+
+---
+
+## Where to Add
+Add both tools to `pumpToolSchema` in `tools.js` (or to a new `walletToolSchema` if Task 07 creates one).
+
+## Verification
+- With MetaMask connected on a testnet, calling `evm_transfer` from chat opens the approval modal, then MetaMask's own confirmation dialog.
+- The tool returns a `tx_result` content object with `status: 'pending'` and a correct explorer link.
+- If no EVM wallet is connected, the tool returns a clear error.
diff --git a/tasks/wallet-transactions/07-wallet-tools-pack.md b/tasks/wallet-transactions/07-wallet-tools-pack.md
new file mode 100644
index 000000000..ae8ce6af9
--- /dev/null
+++ b/tasks/wallet-transactions/07-wallet-tools-pack.md
@@ -0,0 +1,65 @@
+# Task 07 — Wallet Tools Pack Registration
+
+## Goal
+Bundle the four wallet transaction tools (from Tasks 05 and 06) into a named `walletToolSchema` export and register it as a curated tool pack so users can enable it from the tool dropdown like any other pack.
+
+## Context
+- `chat/src/tools.js` exports: `curatedToolPacks`, `defaultToolSchema`, `agentToolSchema`, `pumpToolSchema`
+- `curatedToolPacks` is an array of `{ name, description, tools }` objects used to populate the tool-pack picker UI
+- `chat/src/App.svelte` imports `{ defaultToolSchema, agentToolSchema, pumpToolSchema, curatedToolPacks }` from `./tools.js`
+- After this task, `walletToolSchema` should be importable from `tools.js` and appear in the curated tool packs list
+
+## Changes to `chat/src/tools.js`
+
+### 1. Extract `walletToolSchema`
+Move the four wallet tools added in Tasks 05 and 06 out of `pumpToolSchema` (or from wherever they were added) into their own named export:
+
+```js
+export const walletToolSchema = [
+ {
+ clientDefinition: { /* solana_transfer clientDefinition */ },
+ function: { /* solana_transfer function schema */ },
+ },
+ {
+ clientDefinition: { /* solana_swap clientDefinition */ },
+ function: { /* solana_swap function schema */ },
+ },
+ {
+ clientDefinition: { /* evm_transfer clientDefinition */ },
+ function: { /* evm_transfer function schema */ },
+ },
+ {
+ clientDefinition: { /* evm_swap clientDefinition */ },
+ function: { /* evm_swap function schema */ },
+ },
+];
+```
+
+### 2. Add to `curatedToolPacks`
+Append a new entry to the `curatedToolPacks` array:
+
+```js
+{
+ name: 'Wallet Transactions',
+ description: 'Send and swap tokens on Solana and EVM chains directly from chat. Supports SOL, SPL tokens, ETH, ERC20, and DEX swaps via Jupiter and 1inch.',
+ tools: walletToolSchema,
+},
+```
+
+Place it after the existing packs (after the pump.fun / crypto pack if one exists).
+
+### 3. Update `App.svelte` import
+In `chat/src/App.svelte`, update the import line:
+
+```js
+import { defaultToolSchema, agentToolSchema, pumpToolSchema, walletToolSchema, curatedToolPacks } from './tools.js';
+```
+
+No other changes to App.svelte are needed — the curated tool packs are already consumed by the ToolPackModal component via `curatedToolPacks`.
+
+## Verification
+- Open the tool dropdown / tool pack modal in the chat UI.
+- A "Wallet Transactions" pack appears in the list with the correct description.
+- Enabling the pack adds all four tools (`solana_transfer`, `solana_swap`, `evm_transfer`, `evm_swap`) to the active tool set.
+- The LLM can see all four tool definitions when the pack is enabled.
+- No other tool packs or existing functionality is affected.