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(marketplace): agent-to-agent marketplace with escrowed settlement and a sweep cron

nirholas76dc1e6cd7c2
diff --git a/api/_lib/agent-market/chain.js b/api/_lib/agent-market/chain.js
new file mode 100644
index 000000000..cbbc04052
--- /dev/null
+++ b/api/_lib/agent-market/chain.js
@@ -0,0 +1,312 @@
+// On-chain primitives for the whole-agent marketplace: per-listing escrow
+// accounts, currency mints, and the exactly-once "leg" sender every escrow
+// payout, refund and custody sweep goes through.
+//
+// Escrow. Each listing gets its own Solana account whose keypair is derived, not
+// stored: seed = HMAC-SHA256(AGENT_MARKET_ESCROW_SECRET, domain + listingId). The
+// secret falls back to WALLET_ENCRYPTION_KEY (the custody root, which is already
+// never rotated because rotating it bricks every custodial wallet) and never to
+// JWT_SECRET. The derived address is stored on the listing at creation and
+// re-derived before every signature: a mismatch means the secret changed, and
+// signing then fails closed instead of moving money from the wrong account.
+// Escrow accounts hold no SOL; the platform marketplace payer (the monitored
+// `marketplace-payer` signer in api/_lib/solana-signers.js) pays every fee and
+// every token-account rent, and gets the rent back when an escrow empties.
+//
+// Legs. A payout that crashes between broadcast and bookkeeping must not be paid
+// twice on resume, and a resend while the first attempt might still land would
+// do exactly that. So a leg is signed locally, its signature and the blockhash's
+// last valid height are persisted through `onPrepared` BEFORE broadcast, and a
+// resume reconciles against that record: landed means done, reverted or expired
+// means resend, still-valid-and-unknown means wait. Every leg also carries a
+// deterministic reference key, so even a lost record is recoverable by looking
+// the reference up on chain.
+
+import { createHash, createHmac } from 'node:crypto';
+import {
+ ComputeBudgetProgram,
+ Keypair,
+ PublicKey,
+ TransactionMessage,
+ VersionedTransaction,
+} from '@solana/web3.js';
+import {
+ createAssociatedTokenAccountIdempotentInstruction,
+ createCloseAccountInstruction,
+ createTransferCheckedInstruction,
+ getAssociatedTokenAddressSync,
+ TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import bs58 from 'bs58';
+
+import { env } from '../env.js';
+import { solanaConnection } from '../agent-pumpfun.js';
+import { pollConfirmation } from '../solana/confirm.js';
+import { resolveMarketplacePayer } from '../solana/gasless-tx.js';
+import { tokenProgramIdForMint } from '../token/token-program.js';
+import { TOKEN_MINT, TOKEN_DECIMALS } from '../token/config.js';
+
+const ESCROW_DOMAIN = 'three.ws:agent-market-escrow:v1:';
+const REFERENCE_DOMAIN = 'three.ws:agent-market-leg:v1:';
+
+export const USDC_DECIMALS = 6;
+const USDC_MINT_BY_NETWORK = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+
+// A marketplace transfer is a handful of instructions; 200k CU is a ceiling, not
+// an estimate, and the price is a modest fixed bid: settlement is not a race.
+const LEG_CU_LIMIT = 300_000;
+const LEG_CU_PRICE_MICROLAMPORTS = 50_000;
+
+export function marketNetwork() {
+ return env.AGENT_MARKET_NETWORK === 'devnet' ? 'devnet' : 'mainnet';
+}
+
+export function marketConnection() {
+ return solanaConnection(marketNetwork());
+}
+
+function typed(status, code, message) {
+ return Object.assign(new Error(message), { status, code, expose: true });
+}
+
+// ── Currencies ───────────────────────────────────────────────────────────────
+
+/** Mint, decimals and display symbol for a marketplace currency. */
+export function currencyInfo(currency, network = marketNetwork()) {
+ if (currency === 'THREE') {
+ return { currency: 'THREE', symbol: '$THREE', mint: TOKEN_MINT, decimals: Number(TOKEN_DECIMALS) };
+ }
+ return { currency: 'USDC', symbol: 'USDC', mint: USDC_MINT_BY_NETWORK[network], decimals: USDC_DECIMALS };
+}
+
+/** Decimal string for display, never float-rounded. */
+export function formatAtomics(atomics, decimals) {
+ const v = BigInt(String(atomics));
+ const neg = v < 0n;
+ const abs = neg ? -v : v;
+ const base = 10n ** BigInt(decimals);
+ const whole = abs / base;
+ const frac = (abs % base).toString().padStart(decimals, '0').replace(/0+$/, '');
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
+}
+
+/** Parse a decimal amount into atomics without float error. Throws 400 on junk. */
+export function parseAmount(value, decimals) {
+ const s = String(value ?? '').trim();
+ if (!/^\d+(\.\d+)?$/.test(s)) throw typed(400, 'bad_amount', `"${value}" is not a positive amount`);
+ const [whole, frac = ''] = s.split('.');
+ if (frac.length > decimals) throw typed(400, 'bad_amount', `at most ${decimals} decimal places`);
+ const atomics = BigInt(whole) * 10n ** BigInt(decimals) + BigInt(frac.padEnd(decimals, '0') || '0');
+ if (atomics <= 0n) throw typed(400, 'bad_amount', 'amount must be greater than zero');
+ return atomics;
+}
+
+export async function tokenProgramFor(connection, mint) {
+ return tokenProgramIdForMint(connection, mint);
+}
+
+// ── Escrow derivation ────────────────────────────────────────────────────────
+
+function escrowSecret() {
+ const secret = env.AGENT_MARKET_ESCROW_SECRET;
+ if (!secret) {
+ throw typed(503, 'escrow_unavailable', 'marketplace escrow is not configured on this server');
+ }
+ return secret;
+}
+
+function deriveEscrowKeypair(listingId) {
+ const seed = createHmac('sha256', escrowSecret()).update(ESCROW_DOMAIN + listingId).digest();
+ return Keypair.fromSeed(seed);
+}
+
+/** The escrow address for a listing. Public; safe to log and return. */
+export function escrowAddressFor(listingId) {
+ return deriveEscrowKeypair(listingId).publicKey.toBase58();
+}
+
+/**
+ * Hand the listing's escrow keypair to `fn` after proving it still derives to
+ * the address recorded at listing time. `fn` must not let the keypair escape.
+ */
+export async function withEscrowKeypair(listing, fn) {
+ const kp = deriveEscrowKeypair(listing.id);
+ if (kp.publicKey.toBase58() !== listing.escrow_address) {
+ throw typed(
+ 503,
+ 'escrow_key_mismatch',
+ 'the escrow secret no longer derives this listing\'s escrow account; refusing to sign',
+ );
+ }
+ return fn(kp);
+}
+
+/** Deterministic reference key for one leg, e.g. `refund:<bidId>`. */
+export function legReference(legId) {
+ return new PublicKey(createHash('sha256').update(REFERENCE_DOMAIN + legId).digest());
+}
+
+async function requirePayer() {
+ const payer = await resolveMarketplacePayer();
+ if (!payer) {
+ throw typed(503, 'fee_payer_unavailable', 'the marketplace fee payer is not configured on this server');
+ }
+ return payer;
+}
+
+// ── Token movement instructions ──────────────────────────────────────────────
+
+/**
+ * Instructions that move `atomics` of `mint` from `owner`'s ATA to
+ * `recipient`'s ATA, creating the recipient's account if needed (rent from
+ * `rentPayer`). The reference key rides the transfer.
+ */
+export function transferIxs({ owner, recipient, mint, programId, decimals, atomics, rentPayer, reference }) {
+ const mintPk = new PublicKey(mint);
+ const ownerPk = new PublicKey(owner);
+ const recipientPk = new PublicKey(recipient);
+ const fromAta = getAssociatedTokenAddressSync(mintPk, ownerPk, true, programId);
+ const toAta = getAssociatedTokenAddressSync(mintPk, recipientPk, true, programId);
+ const transfer = createTransferCheckedInstruction(
+ fromAta, mintPk, toAta, ownerPk, BigInt(atomics), decimals, [], programId,
+ );
+ if (reference) transfer.keys.push({ pubkey: reference, isSigner: false, isWritable: false });
+ return [
+ createAssociatedTokenAccountIdempotentInstruction(
+ new PublicKey(rentPayer), toAta, recipientPk, mintPk, programId,
+ ),
+ transfer,
+ ];
+}
+
+/** Close `owner`'s token account for `mint`, returning its rent to `rentTo`. */
+export function closeIx({ owner, mint, programId, rentTo }) {
+ const ata = getAssociatedTokenAddressSync(new PublicKey(mint), new PublicKey(owner), true, programId);
+ return createCloseAccountInstruction(ata, new PublicKey(rentTo), new PublicKey(owner), [], programId);
+}
+
+/** Current token balance of `owner`'s ATA for `mint` (atomics), 0n when absent. */
+export async function tokenBalance(connection, owner, mint, programId) {
+ const ata = getAssociatedTokenAddressSync(new PublicKey(mint), new PublicKey(owner), true, programId);
+ try {
+ const bal = await connection.getTokenAccountBalance(ata, 'confirmed');
+ return BigInt(bal?.value?.amount ?? '0');
+ } catch (err) {
+ if (/could not find account|Invalid param: could not find/i.test(err?.message || '')) return 0n;
+ throw err;
+ }
+}
+
+// ── Exactly-once legs ────────────────────────────────────────────────────────
+
+/**
+ * Where a previously prepared leg stands on chain.
+ * @returns {Promise<'landed'|'failed'|'in_flight'|'expired'>}
+ */
+export async function reconcileLeg(connection, prior) {
+ if (!prior?.signature) return 'expired';
+ let status = null;
+ try {
+ const res = await connection.getSignatureStatuses([prior.signature], { searchTransactionHistory: true });
+ status = res?.value?.[0] ?? null;
+ } catch {
+ // An unreadable chain is not an answer: treat it as in flight so the
+ // caller waits instead of resending into a possible double pay.
+ return 'in_flight';
+ }
+ if (status) {
+ if (status.err) return 'failed';
+ if (status.confirmationStatus === 'confirmed' || status.confirmationStatus === 'finalized') return 'landed';
+ return 'in_flight';
+ }
+ let height;
+ try {
+ height = await connection.getBlockHeight('confirmed');
+ } catch {
+ return 'in_flight';
+ }
+ return height > Number(prior.lastValidBlockHeight) ? 'expired' : 'in_flight';
+}
+
+/** A successful transaction that already carries this leg's reference, if any. */
+export async function findLandedByReference(connection, reference) {
+ const sigs = await connection.getSignaturesForAddress(reference, { limit: 10 }, 'confirmed');
+ const ok = (sigs || []).find((s) => !s.err);
+ return ok ? ok.signature : null;
+}
+
+/**
+ * Send one leg exactly once.
+ *
+ * @param {object} a
+ * @param {string} a.legId stable id, e.g. `payout:<transferId>`
+ * @param {(ref: PublicKey) => import('@solana/web3.js').TransactionInstruction[]} a.build
+ * instructions for the leg; attach `ref` to a transfer so it is findable
+ * @param {import('@solana/web3.js').Keypair[]} a.signers authorities beside the fee payer
+ * @param {{signature:string,lastValidBlockHeight:number}|null} a.prior record from an earlier attempt
+ * @param {(rec: {signature:string,lastValidBlockHeight:number}) => Promise<void>} a.onPrepared
+ * persist the record; called before broadcast, and the leg aborts if it throws
+ * @returns {Promise<{ signature: string, replayed: boolean }>}
+ */
+export async function sendLeg({ legId, build, signers, prior = null, onPrepared, connection = marketConnection() }) {
+ const reference = legReference(legId);
+
+ if (prior?.signature) {
+ const state = await reconcileLeg(connection, prior);
+ if (state === 'landed') return { signature: prior.signature, replayed: true };
+ if (state === 'in_flight') {
+ throw typed(409, 'leg_in_flight', `a previous attempt of ${legId} may still land; retry after its blockhash expires`);
+ }
+ }
+ const landed = await findLandedByReference(connection, reference).catch(() => null);
+ if (landed) return { signature: landed, replayed: true };
+
+ const payer = await requirePayer();
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({
+ payerKey: payer.publicKey,
+ recentBlockhash: blockhash,
+ instructions: [
+ ComputeBudgetProgram.setComputeUnitLimit({ units: LEG_CU_LIMIT }),
+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: LEG_CU_PRICE_MICROLAMPORTS }),
+ ...build(reference, payer.publicKey),
+ ],
+ }).compileToV0Message();
+ const tx = new VersionedTransaction(message);
+ tx.sign([payer, ...signers]);
+ const signature = bs58.encode(tx.signatures[0]);
+
+ // Simulate before recording: a leg that cannot succeed (empty escrow, frozen
+ // account) should fail loudly now, not after a record that implies it flew.
+ const sim = await connection.simulateTransaction(tx, { sigVerify: false, commitment: 'confirmed' });
+ if (sim?.value?.err) {
+ const logs = (sim.value.logs || []).slice(-4).join(' | ');
+ throw typed(502, 'leg_simulation_failed', `${legId} would fail on chain: ${JSON.stringify(sim.value.err)} ${logs}`.slice(0, 480));
+ }
+
+ await onPrepared({ signature, lastValidBlockHeight });
+
+ const raw = tx.serialize();
+ await connection.sendRawTransaction(raw, { skipPreflight: true, maxRetries: 3 });
+ // Rebroadcast until it lands or the blockhash dies: a single send is dropped
+ // often enough under load that settlement would stall on it.
+ const rebroadcast = setInterval(() => {
+ connection.sendRawTransaction(raw, { skipPreflight: true, maxRetries: 0 }).catch(() => {});
+ }, 2_000);
+ try {
+ const result = await pollConfirmation(connection, { signature, blockhash, lastValidBlockHeight }, 'confirmed', {
+ timeoutMs: 90_000,
+ });
+ if (result?.value?.err) {
+ throw typed(502, 'leg_reverted', `${legId} reverted on chain: ${JSON.stringify(result.value.err)}`);
+ }
+ } finally {
+ clearInterval(rebroadcast);
+ }
+ return { signature, replayed: false };
+}
+
+export { TOKEN_PROGRAM_ID };
diff --git a/api/_lib/agent-market/custody.js b/api/_lib/agent-market/custody.js
new file mode 100644
index 000000000..3d5a64c22
--- /dev/null
+++ b/api/_lib/agent-market/custody.js
@@ -0,0 +1,552 @@
+// Custody rotation for a sold agent: the steps that make the buyer the only
+// party who can control it.
+//
+// The seller may know the agent's current private key (an imported vanity key,
+// an export), so ownership alone is not enough: the agent gets a brand-new
+// server-generated keypair, everything on the old wallet is swept off it, the
+// new key replaces the old one in a single conditional write, and the old
+// ciphertext is purged. Every grant, automation and payout path the seller set
+// up is revoked or reset to conservative defaults, and every owner copy follows
+// the buyer.
+//
+// Each exported step is idempotent on its own: it inspects what is already
+// done and finishes only the rest, so settlement.js can re-run any of them
+// after a crash. Nothing here decides ORDER; the state machine does.
+
+import { PublicKey, SystemProgram } from '@solana/web3.js';
+import { TOKEN_2022_PROGRAM_ID, TOKEN_PROGRAM_ID } from '@solana/spl-token';
+
+import { sql } from '../db.js';
+import {
+ decryptSecret,
+ generateAgentWallet,
+ generateSolanaAgentWallet,
+ recoverSolanaAgentKeypair,
+} from '../agent-wallet.js';
+import { recordCustodyEvent, SPEND_LIMIT_DEFAULTS, TRADE_LIMIT_DEFAULTS } from '../agent-trade-guards.js';
+import { closeIx, marketConnection, sendLeg, transferIxs } from './chain.js';
+
+// What a freshly transferred agent is allowed to do until its new owner says
+// otherwise: nothing autonomous. The wallet starts frozen, trading starts
+// killed, and the caps are small, so the buyer opts back in deliberately.
+export const CONSERVATIVE_SPEND_LIMITS = Object.freeze({
+ ...SPEND_LIMIT_DEFAULTS,
+ daily_usd: 25,
+ per_tx_usd: 10,
+ per_counterparty_daily_usd: 10,
+ withdraw_allowlist: [],
+ frozen: true,
+});
+export const CONSERVATIVE_TRADE_LIMITS = Object.freeze({
+ ...TRADE_LIMIT_DEFAULTS,
+ per_trade_sol: 0.05,
+ daily_budget_sol: 0.25,
+ kill_switch: true,
+});
+
+// Meta keys that describe the SELLER's setup, not the agent: payout routing,
+// recovery beneficiaries, bot bindings, autopilot destinations.
+const SELLER_META_KEYS = ['autopilot', 'recovery', 'telegram', 'policy_rules', 'withdraw_allowlist'];
+
+function typed(status, code, message) {
+ return Object.assign(new Error(message), { status, code, expose: true });
+}
+
+async function custody(agentId, userId, eventType, reason, meta = {}, extra = {}) {
+ await recordCustodyEvent({ agentId, userId, eventType, reason, meta, ...extra }).catch((e) =>
+ console.warn('[agent-market] custody event failed', eventType, e?.message),
+ );
+}
+
+export async function loadAgent(agentId) {
+ const [row] = await sql`
+ SELECT id, user_id, name, meta, wallet_address, chain_id, avatar_id, voice_key_source, deleted_at
+ FROM agent_identities WHERE id = ${agentId} LIMIT 1
+ `;
+ if (!row) throw typed(404, 'agent_not_found', 'agent not found');
+ return row;
+}
+
+// ── 1. New keys ──────────────────────────────────────────────────────────────
+
+/**
+ * Generate the agent's replacement keys once and park them, encrypted, on the
+ * transfer row BEFORE anything is swept to them. A crash after this point can
+ * never strand funds on a key nobody stored.
+ */
+export async function prepareNewKeys(transfer, agent) {
+ if (transfer.rotation?.pending?.solana_address) return transfer.rotation.pending;
+ const sol = await generateSolanaAgentWallet();
+ const pending = {
+ solana_address: sol.address,
+ encrypted_solana_secret: sol.encrypted_secret,
+ old_solana_address: agent.meta?.solana_address || null,
+ generated_at: new Date().toISOString(),
+ };
+ if (agent.meta?.encrypted_wallet_key) {
+ const evm = await generateAgentWallet();
+ pending.evm_address = evm.address;
+ pending.encrypted_evm_key = evm.encrypted_key;
+ pending.old_evm_address = agent.wallet_address || null;
+ }
+ const [row] = await sql`
+ UPDATE agent_transfers
+ SET rotation = rotation || jsonb_build_object('pending', ${JSON.stringify(pending)}::jsonb),
+ old_wallet_address = ${pending.old_solana_address},
+ new_wallet_address = ${pending.solana_address},
+ updated_at = now()
+ WHERE id = ${transfer.id} AND NOT (rotation ? 'pending')
+ RETURNING rotation
+ `;
+ if (row) {
+ await custody(agent.id, transfer.seller_user_id, 'key_rotation', 'marketplace_new_key', {
+ transfer_id: transfer.id, new_address: pending.solana_address, evm: Boolean(pending.evm_address),
+ });
+ return pending;
+ }
+ const [fresh] = await sql`SELECT rotation FROM agent_transfers WHERE id = ${transfer.id}`;
+ return fresh.rotation.pending;
+}
+
+// ── 2. Sweep the old Solana wallet ───────────────────────────────────────────
+
+async function tokenAccounts(connection, owner) {
+ const out = [];
+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {
+ const resp = await connection.getParsedTokenAccountsByOwner(new PublicKey(owner), { programId }, 'confirmed');
+ for (const { pubkey, account } of resp.value || []) {
+ const info = account.data?.parsed?.info;
+ if (!info?.tokenAmount) continue;
+ out.push({
+ ata: pubkey.toBase58(),
+ mint: info.mint,
+ programId,
+ decimals: info.tokenAmount.decimals,
+ amount: BigInt(info.tokenAmount.amount || '0'),
+ frozen: info.state === 'frozen',
+ });
+ }
+ }
+ return out;
+}
+
+function legStore(transferId) {
+ return async (legId, rec) => {
+ await sql`
+ UPDATE agent_transfers
+ SET legs = legs || jsonb_build_object(${legId}::text, ${JSON.stringify(rec)}::jsonb), updated_at = now()
+ WHERE id = ${transferId}
+ `;
+ };
+}
+
+/**
+ * Move every token and all SOL off the old wallet to `destination`: the new
+ * wallet when the balance was included, the seller's payout address when not.
+ * The platform payer pays fees, so the old wallet can be drained to exactly
+ * zero. Frozen token accounts cannot move by anyone; they are recorded as
+ * stranded in the rotation record rather than blocking the transfer forever.
+ */
+export async function sweepOldWallet({ transfer, agent, destination, connection = marketConnection() }) {
+ const oldAddress = transfer.rotation?.pending?.old_solana_address || agent.meta?.solana_address;
+ if (!oldAddress) return { swept: [], stranded: [], sol_lamports: '0' };
+ if (agent.meta?.solana_address !== oldAddress) {
+ // Keys already swapped on an earlier run; the sweep finished before that.
+ return transfer.rotation?.sweep || { swept: [], stranded: [], sol_lamports: '0' };
+ }
+ const oldKp = await recoverSolanaAgentKeypair(agent.meta.encrypted_solana_secret, {
+ agentId: agent.id, userId: transfer.seller_user_id, reason: 'marketplace_sweep', meta: { transfer_id: transfer.id },
+ });
+ if (oldKp.publicKey.toBase58() !== oldAddress) {
+ throw typed(500, 'wallet_key_mismatch', 'the stored key does not match the agent wallet address');
+ }
+ const save = legStore(transfer.id);
+ const legs = transfer.legs || {};
+ const swept = [];
+ const stranded = [];
+
+ for (const acct of await tokenAccounts(connection, oldAddress)) {
+ if (acct.frozen) {
+ if (acct.amount > 0n) stranded.push({ mint: acct.mint, amount: acct.amount.toString(), reason: 'frozen' });
+ continue;
+ }
+ const legId = `sweep:${transfer.id}:${acct.ata}`;
+ const build = (withClose) => (reference, payer) => [
+ ...(acct.amount > 0n
+ ? transferIxs({
+ owner: oldAddress, recipient: destination, mint: acct.mint, programId: acct.programId,
+ decimals: acct.decimals, atomics: acct.amount, rentPayer: payer.toBase58(), reference,
+ })
+ : []),
+ ...(withClose ? [closeIx({ owner: oldAddress, mint: acct.mint, programId: acct.programId, rentTo: destination })] : []),
+ ];
+ try {
+ const r = await sendLeg({
+ connection, legId, prior: legs[legId] || null, signers: [oldKp], build: build(true),
+ onPrepared: (rec) => save(legId, rec),
+ });
+ swept.push({ mint: acct.mint, amount: acct.amount.toString(), signature: r.signature, closed: true });
+ } catch (err) {
+ if (err.code !== 'leg_simulation_failed') throw err;
+ // A Token-2022 account holding withheld transfer fees cannot close.
+ // An empty one is left behind as is; a funded one moves its balance
+ // and leaves the empty account.
+ if (acct.amount === 0n) continue;
+ const r = await sendLeg({
+ connection, legId: `${legId}:noclose`, prior: legs[`${legId}:noclose`] || null, signers: [oldKp],
+ build: build(false), onPrepared: (rec) => save(`${legId}:noclose`, rec),
+ });
+ swept.push({ mint: acct.mint, amount: acct.amount.toString(), signature: r.signature, closed: false });
+ }
+ }
+
+ const lamports = BigInt(await connection.getBalance(new PublicKey(oldAddress), 'confirmed'));
+ let solSig = null;
+ if (lamports > 0n) {
+ const legId = `sweep-sol:${transfer.id}`;
+ const r = await sendLeg({
+ connection, legId, prior: legs[legId] || null, signers: [oldKp],
+ build: (reference) => {
+ const ix = SystemProgram.transfer({ fromPubkey: oldKp.publicKey, toPubkey: new PublicKey(destination), lamports });
+ ix.keys.push({ pubkey: reference, isSigner: false, isWritable: false });
+ return [ix];
+ },
+ onPrepared: (rec) => save(legId, rec),
+ });
+ solSig = r.signature;
+ }
+
+ const leftover = (await tokenAccounts(connection, oldAddress)).filter((a) => a.amount > 0n && !a.frozen);
+ if (leftover.length) {
+ throw typed(409, 'sweep_incomplete', `the old wallet still holds ${leftover.length} token balance(s); resume to sweep them`);
+ }
+ const record = { destination, swept, stranded, sol_lamports: lamports.toString(), sol_signature: solSig, at: new Date().toISOString() };
+ await sql`
+ UPDATE agent_transfers SET rotation = rotation || jsonb_build_object('sweep', ${JSON.stringify(record)}::jsonb), updated_at = now()
+ WHERE id = ${transfer.id}
+ `;
+ await custody(agent.id, transfer.seller_user_id, 'spend', 'marketplace_sweep', record, {
+ category: 'marketplace_transfer', asset: 'ALL', destination, status: 'confirmed', signature: solSig || swept.at(-1)?.signature || null,
+ });
+ return record;
+}
+
+// ── 3. Sweep the old EVM wallet (Base) when the agent had a custodial one ─────
+
+const ERC20_ABI = [
+ { type: 'function', name: 'balanceOf', stateMutability: 'view', inputs: [{ name: 'a', type: 'address' }], outputs: [{ type: 'uint256' }] },
+ { type: 'function', name: 'transfer', stateMutability: 'nonpayable', inputs: [{ name: 'to', type: 'address' }, { name: 'amount', type: 'uint256' }], outputs: [{ type: 'bool' }] },
+];
+
+/**
+ * Empty the agent's old custodial EVM wallet into `destination`. Every send
+ * moves the FULL current balance, so a resumed run after an unrecorded send
+ * can only revert for lack of funds, never pay twice.
+ */
+export async function sweepOldEvmWallet({ transfer, agent, destination }) {
+ const pending = transfer.rotation?.pending;
+ if (!pending?.old_evm_address || !agent.meta?.encrypted_wallet_key) return null;
+ if (agent.wallet_address?.toLowerCase() !== pending.old_evm_address.toLowerCase()) {
+ return transfer.rotation?.evm_sweep || null;
+ }
+ const chainId = Number(agent.chain_id) || 8453;
+ const [{ createPublicClient, createWalletClient }, { privateKeyToAccount }, chains, { evmTransport }, { EVM_USDC }] = await Promise.all([
+ import('viem'), import('viem/accounts'), import('viem/chains'), import('../evm/rpc.js'), import('../../payments/_config.js'),
+ ]);
+ const chain = Object.values(chains).find((c) => c?.id === chainId);
+ if (!chain) throw typed(500, 'evm_chain_unsupported', `unsupported EVM chain ${chainId}`);
+ const transport = evmTransport(chainId);
+ const pub = createPublicClient({ chain, transport });
+ const pk = await decryptSecret(agent.meta.encrypted_wallet_key);
+ const account = privateKeyToAccount(pk);
+ if (account.address.toLowerCase() !== pending.old_evm_address.toLowerCase()) {
+ throw typed(500, 'evm_key_mismatch', 'the stored EVM key does not match the agent wallet address');
+ }
+ const wallet = createWalletClient({ account, chain, transport });
+ const hashes = [];
+ const usdc = EVM_USDC[chainId];
+ if (usdc) {
+ const bal = await pub.readContract({ address: usdc, abi: ERC20_ABI, functionName: 'balanceOf', args: [account.address] });
+ if (bal > 0n) {
+ const native = await pub.getBalance({ address: account.address });
+ if (native === 0n) {
+ throw typed(409, 'evm_needs_gas', `the agent's EVM wallet ${account.address} holds USDC but no native gas; send a little ETH to it, then resume`);
+ }
+ const hash = await wallet.writeContract({ address: usdc, abi: ERC20_ABI, functionName: 'transfer', args: [destination, bal] });
+ await pub.waitForTransactionReceipt({ hash, timeout: 90_000 });
+ hashes.push({ asset: 'USDC', amount: bal.toString(), hash });
+ }
+ }
+ const native = await pub.getBalance({ address: account.address });
+ if (native > 0n) {
+ const gasPrice = await pub.getGasPrice();
+ const fee = gasPrice * 21_000n * 2n;
+ if (native > fee) {
+ const hash = await wallet.sendTransaction({ to: destination, value: native - fee, gas: 21_000n, gasPrice });
+ await pub.waitForTransactionReceipt({ hash, timeout: 90_000 });
+ hashes.push({ asset: 'native', amount: (native - fee).toString(), hash });
+ }
+ }
+ const record = { destination, chain_id: chainId, legs: hashes, at: new Date().toISOString() };
+ await sql`
+ UPDATE agent_transfers SET rotation = rotation || jsonb_build_object('evm_sweep', ${JSON.stringify(record)}::jsonb), updated_at = now()
+ WHERE id = ${transfer.id}
+ `;
+ if (hashes.length) {
+ await custody(agent.id, transfer.seller_user_id, 'spend', 'marketplace_evm_sweep', record, {
+ category: 'marketplace_transfer', asset: 'ALL', destination, network: `eip155:${chainId}`, status: 'confirmed', signature: hashes.at(-1).hash,
+ });
+ }
+ return record;
+}
+
+// ── 4. Swap keys ─────────────────────────────────────────────────────────────
+
+/**
+ * Replace the agent's keys with the pending ones in one conditional write. The
+ * old ciphertexts are dropped from meta in the same statement; only public
+ * addresses survive, in the wallet history.
+ */
+export async function swapKeys({ transfer, agent }) {
+ const pending = transfer.rotation?.pending;
+ if (!pending?.solana_address) throw typed(500, 'rotation_missing_keys', 'no pending keys to install');
+ if (agent.meta?.solana_address === pending.solana_address) return { swapped: false, already: true };
+
+ const meta = { ...(agent.meta || {}) };
+ const history = Array.isArray(meta.solana_wallet_history) ? meta.solana_wallet_history : [];
+ if (pending.old_solana_address) {
+ meta.solana_wallet_history = [
+ ...history,
+ { address: pending.old_solana_address, replaced_at: new Date().toISOString(), reason: 'marketplace_transfer', swept: true },
+ ].slice(-10);
+ }
+ meta.solana_address = pending.solana_address;
+ meta.encrypted_solana_secret = pending.encrypted_solana_secret;
+ meta.solana_wallet_source = 'marketplace_rotation';
+ delete meta.solana_vanity_prefix;
+ delete meta.solana_vanity_suffix;
+
+ let walletAddress = agent.wallet_address;
+ if (pending.evm_address) {
+ meta.encrypted_wallet_key = pending.encrypted_evm_key;
+ walletAddress = pending.evm_address;
+ } else if (agent.wallet_address && !agent.meta?.encrypted_wallet_key) {
+ // An EVM address with no custodial key is the SELLER's own wallet.
+ walletAddress = null;
+ }
+
+ const [row] = await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify(meta)}::jsonb, wallet_address = ${walletAddress}, updated_at = now()
+ WHERE id = ${agent.id} AND meta->>'solana_address' IS NOT DISTINCT FROM ${pending.old_solana_address}
+ RETURNING id
+ `;
+ if (!row) throw typed(409, 'wallet_changed', 'the agent wallet changed during settlement; resume to re-sweep');
+ await custody(agent.id, transfer.seller_user_id, 'key_rotation', 'marketplace_keys_installed', {
+ transfer_id: transfer.id, from: pending.old_solana_address, to: pending.solana_address,
+ evm_from: pending.old_evm_address || null, evm_to: pending.evm_address || null,
+ });
+ return { swapped: true };
+}
+
+// ── 5. Revoke the seller's grants and reset policy ───────────────────────────
+
+// Each revocation is its own statement so one table's absence on an older
+// database cannot block the rest. Every column here is verified against the
+// migrations; a missing TABLE (42P01) is the only error tolerated.
+function revocations(agentId, sellerId) {
+ return [
+ ['wallet_capabilities', () => sql`UPDATE agent_wallet_capabilities SET revoked_at = now(), revoked_reason = 'marketplace_transfer', updated_at = now() WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['recovery_guardians', () => sql`UPDATE agent_recovery_guardians SET status = 'removed', updated_at = now() WHERE agent_id = ${agentId} AND status = 'active' RETURNING id`],
+ ['recovery_requests', () => sql`UPDATE agent_recovery_requests SET status = 'cancelled', updated_at = now() WHERE agent_id = ${agentId} AND status IN ('pending_approvals', 'time_locked', 'ready') RETURNING id`],
+ ['wallet_intents', () => sql`UPDATE agent_wallet_intents SET enabled = false, updated_at = now() WHERE agent_id = ${agentId} AND enabled RETURNING id`],
+ ['payout_wallets', () => sql`DELETE FROM agent_payout_wallets WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['paid_services', () => sql`UPDATE agent_paid_services SET archived_at = now(), updated_at = now() WHERE agent_id = ${agentId} AND archived_at IS NULL RETURNING id`],
+ ['signal_feeds', () => sql`UPDATE signal_feeds SET status = 'paused', updated_at = now() WHERE publisher_agent_id = ${agentId} AND status = 'active' RETURNING id`],
+ ['trade_delegations', () => sql`UPDATE pump_trade_delegations SET revoked_at = now() WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['payment_sessions', () => sql`UPDATE payment_sessions SET status = 'cancelled', updated_at = now() WHERE agent_id = ${agentId} AND status = 'active' RETURNING id`],
+ ['home_satellites', () => sql`UPDATE home_satellites SET revoked_at = now() WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['home_satellite_codes', () => sql`UPDATE home_satellite_codes SET expires_at = now() WHERE agent_id = ${agentId} AND claimed_at IS NULL AND expires_at > now() RETURNING id`],
+ ['glance_widget_tokens', () => sql`UPDATE glance_widget_tokens SET revoked_at = now() WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['x_triggers', () => sql`UPDATE x_triggers SET enabled = false, updated_at = now() WHERE agent_id = ${agentId} AND enabled RETURNING id`],
+ ['x_scheduled_posts', () => sql`DELETE FROM x_scheduled_posts WHERE agent_id = ${agentId} AND posted_at IS NULL AND published_at IS NULL RETURNING id`],
+ ['x_pending_reviews', () => sql`UPDATE x_pending_reviews SET status = 'rejected', resolved_at = now() WHERE agent_id = ${agentId} AND status = 'pending' RETURNING id`],
+ ['x_memory_consents', () => sql`UPDATE x_memory_consents SET revoked_at = now(), revoked_reason = 'marketplace_transfer' WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['farcaster_memory_consents', () => sql`UPDATE farcaster_memory_consents SET revoked_at = now() WHERE agent_id = ${agentId} AND revoked_at IS NULL RETURNING id`],
+ ['sniper_strategies', () => sql`UPDATE agent_sniper_strategies SET enabled = false, kill_switch = true, auto_fund_enabled = false, telegram_chat_id = NULL, updated_at = now() WHERE agent_id = ${agentId} RETURNING id`],
+ ['launcher_configs', () => sql`UPDATE agent_launcher_configs SET enabled = false, auto_claim_enabled = false, updated_at = now() WHERE agent_id = ${agentId} RETURNING id`],
+ ['market_maker_configs', () => sql`UPDATE agent_market_maker_configs SET enabled = false, updated_at = now() WHERE agent_id = ${agentId} RETURNING id`],
+ ['market_maker_policies', () => sql`UPDATE market_maker_policies SET enabled = false, kill_switch = true, status = CASE WHEN status IN ('active', 'idle') THEN 'paused' ELSE status END, updated_at = now() WHERE agent_id = ${agentId} RETURNING id`],
+ ['orders', () => sql`UPDATE orders SET status = 'cancelled', cancelled_at = now(), updated_at = now() WHERE agent_id = ${agentId} AND status IN ('active', 'partial', 'paused') RETURNING id`],
+ ['oracle_watch', () => sql`UPDATE oracle_agent_watch SET armed = false, telegram_chat_id = NULL, updated_at = now() WHERE agent_id = ${agentId} RETURNING agent_id`],
+ ['labor_policies', () => sql`UPDATE agent_labor_policies SET poster_enabled = false, worker_enabled = false, updated_at = now() WHERE agent_id = ${agentId} RETURNING agent_id`],
+ ['strategy_equips', () => sql`UPDATE agent_strategy_equips SET active = false, updated_at = now() WHERE agent_id = ${agentId} AND active RETURNING id`],
+ ['mirror_follows', () => sql`UPDATE agent_mirror_follows SET enabled = false, paused_reason = 'marketplace_transfer', updated_at = now() WHERE follower_agent_id = ${agentId} AND enabled RETURNING id`],
+ ['launcher_queue', () => sql`UPDATE launcher_queue SET enabled = false WHERE agent_id = ${agentId} AND enabled RETURNING agent_id`],
+ ['autopilot_proposals', () => sql`UPDATE agent_autopilot_proposals SET status = 'dismissed', decided_at = now() WHERE agent_id = ${agentId} AND status = 'pending' RETURNING id`],
+ ];
+}
+
+// Owner copies that must follow the agent to its new owner.
+function ownerMoves(agentId, sellerId, buyerId) {
+ return [
+ ['sniper_strategies', () => sql`UPDATE agent_sniper_strategies SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['sniper_positions', () => sql`UPDATE agent_sniper_positions SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['launcher_configs', () => sql`UPDATE agent_launcher_configs SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['market_maker_configs', () => sql`UPDATE agent_market_maker_configs SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['launched_coins', () => sql`UPDATE agent_launched_coins SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['market_maker_policies', () => sql`UPDATE market_maker_policies SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['orders', () => sql`UPDATE orders SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['oracle_watch', () => sql`UPDATE oracle_agent_watch SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING agent_id`],
+ ['oracle_actions', () => sql`UPDATE oracle_watch_actions SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['labor_policies', () => sql`UPDATE agent_labor_policies SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING agent_id`],
+ ['strategy_equips', () => sql`UPDATE agent_strategy_equips SET owner_id = ${buyerId} WHERE agent_id = ${agentId} AND owner_id = ${sellerId} RETURNING id`],
+ ['strategy_positions', () => sql`UPDATE agent_strategy_positions SET owner_id = ${buyerId} WHERE agent_id = ${agentId} AND owner_id = ${sellerId} RETURNING id`],
+ ['mirror_follows', () => sql`UPDATE agent_mirror_follows SET owner_user_id = ${buyerId} WHERE follower_agent_id = ${agentId} AND owner_user_id = ${sellerId} RETURNING id`],
+ ['paid_services', () => sql`UPDATE agent_paid_services SET owner_user_id = ${buyerId} WHERE agent_id = ${agentId} AND owner_user_id = ${sellerId} RETURNING id`],
+ ['signal_feeds', () => sql`UPDATE signal_feeds SET owner_user_id = ${buyerId} WHERE publisher_agent_id = ${agentId} AND owner_user_id = ${sellerId} RETURNING id`],
+ ['token_plans', () => sql`UPDATE agent_token_plans SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['launcher_queue', () => sql`UPDATE launcher_queue SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING agent_id`],
+ ['native_launches', () => sql`UPDATE native_launches SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['pump_agent_mints', () => sql`UPDATE pump_agent_mints SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['wallet_intents', () => sql`UPDATE agent_wallet_intents SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ['autopilot_proposals', () => sql`UPDATE agent_autopilot_proposals SET user_id = ${buyerId} WHERE agent_id = ${agentId} AND user_id = ${sellerId} RETURNING id`],
+ ];
+}
+
+async function runEach(list) {
+ const out = {};
+ for (const [name, run] of list) {
+ try {
+ const rows = await run();
+ out[name] = rows.length;
+ } catch (err) {
+ if (err?.code === '42P01') {
+ out[name] = 'absent';
+ continue;
+ }
+ throw Object.assign(err, { step_detail: name });
+ }
+ }
+ return out;
+}
+
+/** Revoke every seller grant and automation, and reset policy to conservative. */
+export async function revokeSellerAccess({ transfer, agent }) {
+ const revoked = await runEach(revocations(agent.id, transfer.seller_user_id));
+
+ const meta = { ...(agent.meta || {}) };
+ for (const k of SELLER_META_KEYS) delete meta[k];
+ meta.spend_limits = { ...CONSERVATIVE_SPEND_LIMITS };
+ meta.trade_limits = { ...CONSERVATIVE_TRADE_LIMITS };
+ if (meta.payments && typeof meta.payments === 'object') {
+ meta.payments = { ...meta.payments, configured: false };
+ delete meta.payments.receiver;
+ }
+ await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify(meta)}::jsonb,
+ x_username = NULL, x_seeded_at = NULL,
+ farcaster_fid = NULL, farcaster_fname = NULL, farcaster_seeded_at = NULL,
+ voice_provider = CASE WHEN voice_key_source = 'owner' THEN 'browser' ELSE voice_provider END,
+ voice_id = CASE WHEN voice_key_source = 'owner' THEN NULL ELSE voice_id END,
+ voice_cloned_at = CASE WHEN voice_key_source = 'owner' THEN NULL ELSE voice_cloned_at END,
+ voice_key_source = CASE WHEN voice_key_source = 'owner' THEN NULL ELSE voice_key_source END,
+ updated_at = now()
+ WHERE id = ${agent.id}
+ `;
+ await custody(agent.id, transfer.seller_user_id, 'limit_change', 'marketplace_reset', {
+ transfer_id: transfer.id, revoked, spend_limits: CONSERVATIVE_SPEND_LIMITS, trade_limits: CONSERVATIVE_TRADE_LIMITS,
+ });
+ return revoked;
+}
+
+// ── 6. History (when the listing excluded it) ───────────────────────────────
+
+export async function detachHistory({ agent }) {
+ return runEach([
+ ['memories', () => sql`DELETE FROM agent_memories WHERE agent_id = ${agent.id} RETURNING id`],
+ ['memory_entities', () => sql`DELETE FROM agent_memory_entities WHERE agent_id = ${agent.id} RETURNING id`],
+ ['memory_pins', () => sql`DELETE FROM agent_memory_pins WHERE agent_id = ${agent.id} RETURNING agent_id`],
+ ['mood_history', () => sql`DELETE FROM agent_mood_history WHERE agent_id = ${agent.id} RETURNING agent_id`],
+ ['actions', () => sql`DELETE FROM agent_actions WHERE agent_id = ${agent.id} RETURNING id`],
+ ]);
+}
+
+// ── 7. Reassign ownership ────────────────────────────────────────────────────
+
+/**
+ * Make the buyer the owner: the guarded flip, the owner copies, the avatar,
+ * and the revenue cutover so the seller keeps what the agent earned for them.
+ */
+export async function reassignOwner({ transfer, agent }) {
+ const { seller_user_id: sellerId, buyer_user_id: buyerId } = transfer;
+ // Stamp pre-sale revenue with the seller BEFORE the flip: earnings balances
+ // follow the current owner, so this is what keeps them with the seller.
+ await sql`UPDATE agent_revenue_events SET owner_user_id = ${sellerId} WHERE agent_id = ${agent.id} AND owner_user_id IS NULL`;
+ if (agent.user_id !== buyerId) {
+ const [row] = await sql`
+ UPDATE agent_identities SET user_id = ${buyerId}, updated_at = now()
+ WHERE id = ${agent.id} AND user_id = ${sellerId}
+ RETURNING id
+ `;
+ if (!row) throw typed(409, 'owner_changed', 'the agent changed owner outside this sale');
+ }
+ if (agent.avatar_id) {
+ await sql`UPDATE avatars SET owner_id = ${buyerId} WHERE id = ${agent.avatar_id} AND owner_id = ${sellerId}`;
+ }
+ const moved = await runEach(ownerMoves(agent.id, sellerId, buyerId));
+ await custody(agent.id, buyerId, 'ownership_transfer', 'marketplace_sale', {
+ transfer_id: transfer.id, from: sellerId, to: buyerId, moved,
+ });
+ return moved;
+}
+
+// ── 8. Destroy the old key ───────────────────────────────────────────────────
+
+/**
+ * Purge the pending-key ciphertext from the transfer row (the agent row holds
+ * the only copy now) and prove the installed key is the one that signs.
+ */
+export async function destroyOldKey({ transfer, agent }) {
+ const pending = transfer.rotation?.pending;
+ const installed = await recoverSolanaAgentKeypair(agent.meta.encrypted_solana_secret);
+ if (installed.publicKey.toBase58() !== pending?.solana_address && installed.publicKey.toBase58() !== transfer.new_wallet_address) {
+ throw typed(500, 'rotation_verify_failed', 'the installed key does not derive the new wallet address');
+ }
+ const record = {
+ new_address: installed.publicKey.toBase58(),
+ old_address: transfer.old_wallet_address,
+ evm_new_address: pending?.evm_address || null,
+ evm_old_address: pending?.old_evm_address || null,
+ verified_at: new Date().toISOString(),
+ };
+ await sql`
+ UPDATE agent_transfers
+ SET rotation = (rotation - 'pending') || jsonb_build_object('keys', ${JSON.stringify(record)}::jsonb), updated_at = now()
+ WHERE id = ${transfer.id}
+ `;
+ await custody(agent.id, transfer.buyer_user_id, 'key_rotation', 'marketplace_old_key_destroyed', { transfer_id: transfer.id, ...record });
+ return record;
+}
+
+// ── Open positions follow the tokens ─────────────────────────────────────────
+
+/**
+ * Open trading positions track tokens in the old wallet. When the balance went
+ * to the buyer they now live in the new wallet; when it went to the seller they
+ * are gone from the agent, so the positions close.
+ */
+export async function repointPositions({ transfer, agent, includeBalance }) {
+ const oldAddress = transfer.rotation?.pending?.old_solana_address || transfer.old_wallet_address;
+ const newAddress = transfer.rotation?.pending?.solana_address || transfer.new_wallet_address;
+ if (includeBalance) {
+ return runEach([
+ ['sniper_positions', () => sql`UPDATE agent_sniper_positions SET wallet = ${newAddress} WHERE agent_id = ${agent.id} AND wallet = ${oldAddress} AND status IN ('opening', 'open', 'closing') RETURNING id`],
+ ]);
+ }
+ return runEach([
+ ['sniper_positions', () => sql`UPDATE agent_sniper_positions SET status = 'closed', exit_reason = 'manual', error = 'balance swept to the seller at marketplace transfer', closed_at = now() WHERE agent_id = ${agent.id} AND status IN ('opening', 'open', 'closing') RETURNING id`],
+ ['strategy_positions', () => sql`UPDATE agent_strategy_positions SET status = 'closed', error = 'balance swept to the seller at marketplace transfer', closed_at = now() WHERE agent_id = ${agent.id} AND status IN ('open', 'closing') RETURNING id`],
+ ]);
+}
diff --git a/api/_lib/agent-market/escrow.js b/api/_lib/agent-market/escrow.js
new file mode 100644
index 000000000..e98c56d90
--- /dev/null
+++ b/api/_lib/agent-market/escrow.js
@@ -0,0 +1,259 @@
+// Escrow custody for whole-agent marketplace bids.
+//
+// A bid is money in the listing's escrow account, never a promise. Two ways in:
+//
+// agent_wallet the platform signs a guarded USDC transfer from one of the
+// bidder's own agents to escrow, under that agent's spend
+// limits and kill switch, with a custody-event receipt
+// (api/_lib/agent-usdc-transfer.js).
+// connected_wallet the server prepares a transfer the bidder signs in their
+// wallet; the platform marketplace payer is the fee payer
+// and creates the escrow token account, so the bidder needs
+// no SOL. A reference key rides the transfer; confirmation
+// reads the landed transaction and checks the exact amount
+// moved from the bidder's address into escrow.
+//
+// Two ways out: a refund to wherever the bid was funded from (rejected,
+// withdrawn, expired, outbid on a closed listing), or the settlement legs in
+// settlement.js. Both go through chain.js sendLeg, so neither can pay twice.
+
+import { randomUUID } from 'node:crypto';
+import { Keypair, PublicKey, TransactionMessage, VersionedTransaction } from '@solana/web3.js';
+import { getAssociatedTokenAddressSync } from '@solana/spl-token';
+
+import { sql } from '../db.js';
+import { transferUsdcGuarded } from '../agent-usdc-transfer.js';
+import { resolveMarketplacePayer } from '../solana/gasless-tx.js';
+import {
+ closeIx,
+ currencyInfo,
+ formatAtomics,
+ marketConnection,
+ marketNetwork,
+ sendLeg,
+ tokenBalance,
+ tokenProgramFor,
+ transferIxs,
+ withEscrowKeypair,
+} from './chain.js';
+
+// Long enough to connect a wallet and approve; a prepared transaction's
+// blockhash dies within ~90 seconds, so nothing signed can land after this.
+export const FUND_WINDOW_MS = 10 * 60 * 1000;
+
+function typed(status, code, message, extra = {}) {
+ return Object.assign(new Error(message), { status, code, expose: true, ...extra });
+}
+
+// ── Funding: agent wallet ────────────────────────────────────────────────────
+
+/**
+ * Escrow a USDC bid from one of the bidder's agents. Synchronous: returns once
+ * the transfer confirmed (or refused under the agent's spend policy).
+ */
+export async function fundFromAgentWallet({ bid, listing, fundingAgent }) {
+ const usdc = Number(formatAtomics(bid.amount_atomics, 6));
+ const result = await transferUsdcGuarded({
+ fromAgentId: fundingAgent.id,
+ fromUserId: fundingAgent.user_id,
+ fromMeta: fundingAgent.meta,
+ toAddress: listing.escrow_address,
+ usdc,
+ network: marketNetwork(),
+ category: 'marketplace_bid',
+ idempotencyKey: `agent-market-bid:${bid.id}`,
+ rowMeta: { listing_id: listing.id, bid_id: bid.id, escrow: listing.escrow_address },
+ });
+ if (result.status === 'paid' || result.status === 'replayed') return { signature: result.signature };
+ const messages = {
+ wallet_frozen: 'That agent\'s wallet is frozen, so it cannot fund a bid. Unfreeze it under Limits & Safety or pay from a connected wallet.',
+ daily_limit: 'This bid would exceed that agent\'s daily spend limit. Raise the limit or pay from a connected wallet.',
+ per_tx_limit: 'This bid is above that agent\'s per-transaction limit. Raise the limit or pay from a connected wallet.',
+ wallet_preparing: 'That agent has no Solana wallet yet.',
+ send_failed: 'The escrow transfer could not be sent. Nothing left the wallet; check its USDC and SOL balance and try again.',
+ unconfirmed: 'The escrow transfer was sent but has not confirmed yet. It will be picked up automatically once it lands.',
+ };
+ throw typed(
+ result.status === 'blocked' ? 403 : 502,
+ result.code || 'funding_failed',
+ messages[result.code] || result.message || 'The escrow transfer failed.',
+ { signature: result.signature || null },
+ );
+}
+
+/** Where an agent-wallet bid stands if the process died mid-transfer. */
+export async function agentWalletFundingStatus(bid) {
+ const [row] = await sql`
+ SELECT status, signature FROM agent_custody_events
+ WHERE agent_id = ${bid.funding_agent_id} AND idempotency_key = ${`agent-market-bid:${bid.id}`}
+ LIMIT 1
+ `;
+ if (!row) return { state: 'none' };
+ if (row.status === 'confirmed' && row.signature) return { state: 'landed', signature: row.signature };
+ if (row.status === 'pending') return { state: 'pending', signature: row.signature || null };
+ return { state: 'failed' };
+}
+
+// ── Funding: connected wallet ────────────────────────────────────────────────
+
+export function newReference() {
+ return Keypair.generate().publicKey.toBase58();
+}
+
+/**
+ * Build the escrow transfer for the bidder to sign. With a marketplace payer
+ * configured it is partially signed (the platform pays the fee and the escrow
+ * account rent); without one the bidder is the fee payer.
+ */
+export async function buildFundingTransaction({ bid, listing }) {
+ const connection = marketConnection();
+ const info = currencyInfo(bid.currency);
+ const programId = await tokenProgramFor(connection, info.mint);
+ const payer = await resolveMarketplacePayer();
+ const bidder = new PublicKey(bid.funding_address);
+ const feePayer = payer ? payer.publicKey : bidder;
+ const ixs = transferIxs({
+ owner: bidder.toBase58(),
+ recipient: listing.escrow_address,
+ mint: info.mint,
+ programId,
+ decimals: info.decimals,
+ atomics: BigInt(String(bid.amount_atomics)),
+ rentPayer: feePayer.toBase58(),
+ reference: new PublicKey(bid.escrow_reference),
+ });
+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
+ const message = new TransactionMessage({ payerKey: feePayer, recentBlockhash: blockhash, instructions: ixs }).compileToV0Message();
+ const tx = new VersionedTransaction(message);
+ if (payer) tx.sign([payer]);
+ return {
+ transaction: Buffer.from(tx.serialize()).toString('base64'),
+ fee_payer: feePayer.toBase58(),
+ gasless: Boolean(payer),
+ last_valid_block_height: lastValidBlockHeight,
+ reference: bid.escrow_reference,
+ escrow_address: listing.escrow_address,
+ network: marketNetwork(),
+ mint: info.mint,
+ amount: formatAtomics(bid.amount_atomics, info.decimals),
+ currency: info.currency,
+ };
+}
+
+/**
+ * Find and verify the bidder's escrow transfer. Returns the signature when the
+ * exact amount moved from the bidder's address into escrow in a landed,
+ * successful transaction carrying the bid's reference key; null when nothing
+ * has landed yet. Throws on a transaction that landed but does not match.
+ */
+export async function verifyConnectedFunding({ bid, listing, signature = null }) {
+ const connection = marketConnection();
+ const reference = new PublicKey(bid.escrow_reference);
+ let sig = signature;
+ if (!sig) {
+ const found = await connection.getSignaturesForAddress(reference, { limit: 5 }, 'confirmed');
+ sig = (found || []).find((s) => !s.err)?.signature || null;
+ if (!sig) return null;
+ }
+ const tx = await connection.getParsedTransaction(sig, { commitment: 'confirmed', maxSupportedTransactionVersion: 0 });
+ if (!tx) return null;
+ if (tx.meta?.err) throw typed(422, 'funding_reverted', 'That transaction failed on chain; no funds reached escrow.');
+
+ const keys = tx.transaction.message.accountKeys.map((k) => (k.pubkey ? k.pubkey.toBase58() : String(k)));
+ if (!keys.includes(reference.toBase58())) {
+ throw typed(422, 'funding_mismatch', 'That transaction is not the escrow transfer for this bid.');
+ }
+ const info = currencyInfo(bid.currency);
+ const delta = (owner) => {
+ const pick = (list) => (list || []).find((b) => b.owner === owner && b.mint === info.mint);
+ const pre = BigInt(pick(tx.meta.preTokenBalances)?.uiTokenAmount?.amount ?? '0');
+ const post = BigInt(pick(tx.meta.postTokenBalances)?.uiTokenAmount?.amount ?? '0');
+ return post - pre;
+ };
+ const want = BigInt(String(bid.amount_atomics));
+ if (delta(listing.escrow_address) !== want || delta(bid.funding_address) !== -want) {
+ throw typed(422, 'funding_mismatch', 'The escrow transfer amount or sender does not match this bid.');
+ }
+ return sig;
+}
+
+// ── Refunds and closure ──────────────────────────────────────────────────────
+
+/**
+ * Where a bid's refund goes: the connected wallet it came from, or the funding
+ * agent's CURRENT wallet (an agent can rotate its key, e.g. a vanity swap, and
+ * the old address may no longer be spendable).
+ */
+export async function refundDestination(bid) {
+ if (bid.funding_source !== 'agent_wallet' || !bid.funding_agent_id) return bid.funding_address;
+ const [agent] = await sql`
+ SELECT user_id, meta->>'solana_address' AS address FROM agent_identities WHERE id = ${bid.funding_agent_id}
+ `;
+ if (agent?.address && agent.user_id === bid.bidder_user_id) return agent.address;
+ return bid.funding_address;
+}
+
+/** Pay a bid's escrowed funds back. Exactly once; resumable. */
+export async function refundBid({ bid, listing }) {
+ const connection = marketConnection();
+ const info = currencyInfo(bid.currency);
+ const programId = await tokenProgramFor(connection, info.mint);
+ const destination = await refundDestination(bid);
+ return withEscrowKeypair(listing, (escrow) =>
+ sendLeg({
+ connection,
+ legId: `refund:${bid.id}`,
+ prior: bid.refund_leg,
+ signers: [escrow],
+ build: (reference, payer) =>
+ transferIxs({
+ owner: escrow.publicKey.toBase58(),
+ recipient: destination,
+ mint: info.mint,
+ programId,
+ decimals: info.decimals,
+ atomics: BigInt(String(bid.amount_atomics)),
+ rentPayer: payer.toBase58(),
+ reference,
+ }),
+ onPrepared: async (rec) => {
+ await sql`UPDATE agent_listing_bids SET refund_leg = ${JSON.stringify(rec)}::jsonb, updated_at = now() WHERE id = ${bid.id}`;
+ },
+ }).then((r) => ({ ...r, destination })),
+ );
+}
+
+/**
+ * Close a finished listing's escrow token accounts so their rent returns to
+ * the marketplace payer. Only when every token account is empty: anything left
+ * belongs to someone and stays until it is refunded.
+ */
+export async function closeEscrow(listing) {
+ const connection = marketConnection();
+ const payer = await resolveMarketplacePayer();
+ if (!payer) return { closed: false, reason: 'fee_payer_unavailable' };
+ const currencies = ['USDC', 'THREE'];
+ const open = [];
+ for (const currency of currencies) {
+ const info = currencyInfo(currency);
+ const programId = await tokenProgramFor(connection, info.mint);
+ const ata = getAssociatedTokenAddressSync(new PublicKey(info.mint), new PublicKey(listing.escrow_address), true, programId);
+ const acct = await connection.getAccountInfo(ata, 'confirmed');
+ if (!acct) continue;
+ const balance = await tokenBalance(connection, listing.escrow_address, info.mint, programId);
+ if (balance > 0n) return { closed: false, reason: 'escrow_not_empty', currency, balance: balance.toString() };
+ open.push({ info, programId });
+ }
+ if (!open.length) return { closed: true, signature: null };
+ const { signature } = await withEscrowKeypair(listing, (escrow) =>
+ sendLeg({
+ connection,
+ legId: `close:${listing.id}:${randomUUID()}`,
+ signers: [escrow],
+ build: () => open.map(({ info, programId }) =>
+ closeIx({ owner: escrow.publicKey.toBase58(), mint: info.mint, programId, rentTo: payer.publicKey.toBase58() })),
+ onPrepared: async () => {},
+ }),
+ );
+ return { closed: true, signature };
+}
diff --git a/api/_lib/agent-market/service.js b/api/_lib/agent-market/service.js
new file mode 100644
index 000000000..c26ac5f87
--- /dev/null
+++ b/api/_lib/agent-market/service.js
@@ -0,0 +1,831 @@
+// Whole-agent marketplace: every business rule in one place. The REST routes
+// (api/v1/marketplace/agents/) and the MCP tools (api/_mcpagent/marketplace-tools.js)
+// are thin adapters over these functions, so a rule changed here changes both.
+//
+// Money-moving calls take `confirm: true` and refuse without it. The MCP layer
+// additionally requires a preview id from previewAction for the same action and
+// arguments, so a model always shows the user the confirmation table first.
+
+import { createHash, randomUUID } from 'node:crypto';
+import { PublicKey } from '@solana/web3.js';
+
+import { sql } from '../db.js';
+import { cacheGet, cacheSet } from '../cache.js';
+import { logAudit } from '../audit.js';
+import { insertNotification } from '../notify.js';
+import { currentSignatureFor, agreementRequirement } from '../real-funds-agreement.js';
+import { getSolanaAddressBalances } from '../agent-wallet.js';
+import { getSpendLimits } from '../agent-trade-guards.js';
+import { resolveMarketplacePayer } from '../solana/gasless-tx.js';
+import { getAgentReputation, scoreAgentsLite } from '../trust/wallet-reputation.js';
+import {
+ currencyInfo, escrowAddressFor, formatAtomics, marketNetwork, parseAmount,
+} from './chain.js';
+import {
+ agentWalletFundingStatus, buildFundingTransaction, FUND_WINDOW_MS, fundFromAgentWallet, newReference,
+ refundBid, verifyConnectedFunding,
+} from './escrow.js';
+import * as store from './store.js';
+import { effectiveFeeBps, feeRecipient, runTransfer, saleFeeBps, transferView } from './settlement.js';
+
+export const PREVIEW_TTL_MS = 10 * 60 * 1000;
+const MIN_DURATION_HOURS = 1;
+const MAX_DURATION_HOURS = 30 * 24;
+const DEFAULT_DURATION_HOURS = 7 * 24;
+// How long an HTTP request drives settlement before handing it to the cron.
+const INLINE_SETTLE_MS = 45_000;
+
+function fail(status, code, message, extra = {}) {
+ throw Object.assign(new Error(message), { status, code, expose: true, ...extra });
+}
+
+function isUuid(v) {
+ return typeof v === 'string' && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(v);
+}
+
+function solanaAddressOrFail(value, field) {
+ try {
+ const pk = new PublicKey(String(value || '').trim());
+ return pk.toBase58();
+ } catch {
+ return fail(400, 'bad_address', `${field} is not a valid Solana address`);
+ }
+}
+
+function requireUser(user) {
+ if (!user?.id) fail(401, 'unauthorized', 'sign in to use the agent marketplace');
+}
+
+function requireConfirm(confirm, what) {
+ if (confirm !== true) fail(400, 'confirmation_required', `${what} moves real funds; pass confirm: true after showing the preview`);
+}
+
+async function requireAgreement(userId) {
+ let signed;
+ try {
+ signed = await currentSignatureFor(userId);
+ } catch {
+ fail(503, 'agreement_check_unavailable', 'could not verify your signed real-funds agreements; nothing moved');
+ }
+ if (!signed) {
+ const req = agreementRequirement();
+ fail(403, 'risk_ack_required', `sign the real-funds agreements first at ${req.sign_url}`, { requirement: req });
+ }
+}
+
+async function requireFeePayer() {
+ if (!(await resolveMarketplacePayer())) {
+ fail(503, 'fee_payer_unavailable', 'the marketplace fee payer is not configured, so escrow cannot settle');
+ }
+}
+
+function money(atomics, currency) {
+ const info = currencyInfo(currency);
+ return `${formatAtomics(atomics, info.decimals)} ${info.symbol}`;
+}
+
+// ── Reads ────────────────────────────────────────────────────────────────────
+
+async function liveBalances(address) {
+ if (!address) return null;
+ const key = `agent-market:bal:${address}`;
+ const hit = await cacheGet(key).catch(() => null);
+ if (hit) return hit;
+ const bal = await getSolanaAddressBalances(address, marketNetwork());
+ if (bal.sol != null) await cacheSet(key, bal, 60).catch(() => {});
+ return bal;
+}
+
+async function tradeSummary(agentId) {
+ const [row] = await sql`
+ SELECT count(*) FILTER (WHERE event = 'sold')::int AS sales,
+ max(amount_atomics) FILTER (WHERE event = 'sold' AND currency = 'USDC') AS best_sale_atomics,
+ max(created_at) FILTER (WHERE event = 'sold') AS last_sale_at
+ FROM agent_marketplace_history WHERE agent_id = ${agentId}
+ `;
+ return {
+ sales: row?.sales || 0,
+ best_sale: row?.best_sale_atomics != null ? money(row.best_sale_atomics, 'USDC') : null,
+ last_sale_at: row?.last_sale_at ? new Date(row.last_sale_at).toISOString() : null,
+ };
+}
+
+/** Browse live listings with reputation and (when included) live balances. */
+export async function browseListings({ q = '', sort = 'ending', limit = 24, cursor = 0, viewerId = null } = {}) {
+ const lim = Math.min(48, Math.max(1, Number(limit) || 24));
+ const offset = Math.max(0, Number(cursor) || 0);
+ const { rows, hasMore } = await store.listListings({ q: String(q || '').trim(), sort: store.normalizeSort(sort), limit: lim, offset });
+ const reps = await scoreAgentsLite(rows.map((r) => r.agent_id)).catch(() => new Map());
+ const items = await Promise.all(rows.map(async (r) => {
+ const v = store.listingView(r, { viewerId });
+ const rep = reps.get(r.agent_id);
+ v.reputation = rep ? { score: rep.score, tier: rep.tier, label: rep.tierLabel } : null;
+ v.wallet_balance = r.include_balance ? await liveBalances(r.agent_solana_address).catch(() => null) : null;
+ return v;
+ }));
+ return { items, next_cursor: hasMore ? String(offset + lim) : null };
+}
+
+/** Public, published agents that could be bought or bid on, with sale state. */
+export async function browsePublicAgents({ q = '', limit = 24, cursor = 0 } = {}) {
+ const lim = Math.min(48, Math.max(1, Number(limit) || 24));
+ const offset = Math.max(0, Number(cursor) || 0);
+ const qLike = q ? `%${String(q).trim().slice(0, 80)}%` : null;
+ const rows = await sql`
+ SELECT ai.id, ai.name, ai.description, ai.skills, ai.category, ai.user_id,
+ l.id AS listing_id, l.ask_usdc_atomics, l.min_bid_usdc_atomics, l.expires_at
+ FROM agent_identities ai
+ LEFT JOIN agent_listings l ON l.agent_id = ai.id AND l.status = 'active' AND l.expires_at > now()
+ WHERE ai.deleted_at IS NULL AND ai.is_published = true
+ AND (${qLike}::text IS NULL OR ai.name ILIKE ${qLike} OR ai.description ILIKE ${qLike})
+ ORDER BY (l.id IS NOT NULL) DESC, ai.views_count DESC NULLS LAST, ai.id
+ LIMIT ${lim + 1} OFFSET ${offset}
+ `;
+ return {
+ items: rows.slice(0, lim).map((r) => ({
+ id: r.id,
+ name: r.name,
+ description: r.description,
+ skills: r.skills || [],
+ category: r.category,
+ url: `/agents/${r.id}`,
+ for_sale: r.listing_id
+ ? {
+ listing_id: r.listing_id,
+ ask: r.ask_usdc_atomics != null ? money(r.ask_usdc_atomics, 'USDC') : null,
+ min_bid: money(r.min_bid_usdc_atomics, 'USDC'),
+ expires_at: new Date(r.expires_at).toISOString(),
+ url: `/marketplace/agents/listing/${r.listing_id}`,
+ }
+ : null,
+ })),
+ next_cursor: rows.length > lim ? String(offset + lim) : null,
+ };
+}
+
+/** Full listing detail: listing, bids, reputation, balance, history, transfer. */
+export async function getListingDetail(listingId, viewerId = null) {
+ if (!isUuid(listingId)) fail(404, 'not_found', 'listing not found');
+ const row = await store.getListing(listingId);
+ if (!row) fail(404, 'not_found', 'listing not found');
+ const [bids, history, rep, balances, trades, transfer] = await Promise.all([
+ store.listBidsForListing(listingId),
+ store.listHistory({ listingId, limit: 50 }),
+ getAgentReputation(row.agent_id, { lite: true }).catch(() => null),
+ liveBalances(row.agent_solana_address).catch(() => null),
+ tradeSummary(row.agent_id),
+ store.getTransferForListing(listingId),
+ ]);
+ const listing = store.listingView(row, { viewerId });
+ listing.reputation = rep ? { score: rep.score, tier: rep.tier, label: rep.tierLabel } : null;
+ listing.wallet_balance = balances;
+ listing.trade_history = trades;
+ listing.fee_bps = saleFeeBps();
+ listing.what_transfers = whatTransfers(row);
+ return {
+ listing,
+ bids: bids.map((b) => store.bidView(b, { viewerId })),
+ history: history.map(store.historyView),
+ transfer: transfer ? transferView(transfer, { viewerId }) : null,
+ };
+}
+
+export async function getLiveListingForAgent(agentId, viewerId = null) {
+ if (!isUuid(agentId)) fail(404, 'not_found', 'agent not found');
+ const row = await store.getLiveListingForAgent(agentId);
+ return row ? store.listingView(row, { viewerId }) : null;
+}
+
+export async function marketplaceHistory({ agentId = null, limit = 50 } = {}) {
+ if (agentId && !isUuid(agentId)) fail(400, 'bad_request', 'agent_id must be a uuid');
+ const rows = await store.listHistory({ agentId, limit: Math.min(200, Math.max(1, Number(limit) || 50)) });
+ return rows.map(store.historyView);
+}
+
+export async function sellerDashboard(user) {
+ requireUser(user);
+ const [{ rows }, received] = await Promise.all([
+ store.listListings({ sellerId: user.id, sort: 'newest', limit: 100 }),
+ store.listBidsReceived(user.id),
+ ]);
+ const transfers = await sql`
+ SELECT * FROM agent_transfers WHERE seller_user_id = ${user.id} OR buyer_user_id = ${user.id}
+ ORDER BY created_at DESC LIMIT 50
+ `;
+ return {
+ listings: rows.map((r) => store.listingView(r, { viewerId: user.id })),
+ received_bids: received.map((b) => store.bidView(b, { viewerId: user.id })),
+ transfers: transfers.map((t) => transferView(t, { viewerId: user.id })),
+ };
+}
+
+export async function myBids(user) {
+ requireUser(user);
+ const rows = await store.listBidsByBidder(user.id);
+ return rows.map((b) => store.bidView(b, { viewerId: user.id }));
+}
+
+export async function receivedBids(user) {
+ requireUser(user);
+ const rows = await store.listBidsReceived(user.id);
+ return rows.map((b) => store.bidView(b, { viewerId: user.id }));
+}
+
+export async function getTransferForViewer(transferId, user) {
+ requireUser(user);
+ if (!isUuid(transferId)) fail(404, 'not_found', 'transfer not found');
+ const row = await store.getTransfer(transferId);
+ if (!row || (row.buyer_user_id !== user.id && row.seller_user_id !== user.id)) fail(404, 'not_found', 'transfer not found');
+ return transferView(row, { viewerId: user.id });
+}
+
+// ── What transfers ───────────────────────────────────────────────────────────
+
+export function whatTransfers(listing) {
+ return [
+ { item: 'Identity, name and public profile', transfers: true },
+ { item: 'Persona, system prompt and greeting', transfers: true },
+ { item: 'Installed skills and skill prices', transfers: true },
+ { item: '3D body (avatar)', transfers: true },
+ {
+ item: 'Wallet balance (SOL and every token)',
+ transfers: Boolean(listing.include_balance),
+ note: listing.include_balance
+ ? 'moves to the agent\'s new wallet'
+ : 'swept to the seller before the handover',
+ },
+ {
+ item: 'Memories, activity and mood history',
+ transfers: Boolean(listing.include_history),
+ note: listing.include_history ? undefined : 'deleted before the handover',
+ },
+ { item: 'Custodial wallet key', transfers: false, note: 'replaced by a new key only the buyer controls; the old key is destroyed' },
+ { item: "Seller's allowlists, payout wallets, delegations, automations and social links", transfers: false, note: 'revoked; spend limits reset to conservative defaults and the wallet starts frozen' },
+ { item: 'Earnings the agent made before the sale', transfers: false, note: 'stay with the seller' },
+ ];
+}
+
+// ── Previews ─────────────────────────────────────────────────────────────────
+
+function paramsHash(action, params) {
+ const canon = JSON.stringify(Object.keys(params).sort().reduce((o, k) => {
+ if (params[k] !== undefined && params[k] !== null && k !== 'preview_id' && !k.startsWith('confirm')) o[k] = params[k];
+ return o;
+ }, {}));
+ return createHash('sha256').update(`${action}:${canon}`).digest('hex');
+}
+
+function tableText(rows) {
+ return ['| Field | Value |', '|---|---|', ...rows.map((r) => `| ${r.label} | ${String(r.value).replace(/\|/g, '/')} |`)].join('\n');
+}
+
+/**
+ * Build the confirmation table for a money-moving action without doing it,
+ * and record it so the commit call can cite it. Throws the same precondition
+ * errors the commit would, so a preview that succeeds describes a commit that
+ * can succeed.
+ */
+export async function previewAction(user, action, params = {}) {
+ requireUser(user);
+ let preview;
+ switch (action) {
+ case 'create_listing': preview = await previewCreateListing(user, params); break;
+ case 'delist': preview = await previewDelist(user, params); break;
+ case 'place_bid': preview = await previewBid(user, params, 'bid'); break;
+ case 'buy_now': preview = await previewBid(user, params, 'buy_now'); break;
+ case 'accept_bid': preview = await previewAccept(user, params); break;
+ case 'withdraw_bid': preview = await previewWithdraw(user, params); break;
+ default: fail(400, 'bad_action', `unknown marketplace action "${action}"`);
+ }
+ const id = `amp_${randomUUID().replace(/-/g, '')}`;
+ await sql`
+ INSERT INTO agent_market_previews (id, user_id, action, params_hash, payload)
+ VALUES (${id}, ${user.id}, ${action}, ${paramsHash(action, params)}, ${JSON.stringify(preview)}::jsonb)
+ `;
+ return { preview_id: id, action, expires_at: new Date(Date.now() + PREVIEW_TTL_MS).toISOString(), ...preview, text: tableText(preview.table) };
+}
+
+/** Validate and consume a preview for a commit. Throws a designed error. */
+export async function consumePreview(user, action, params, previewId, previewTool) {
+ if (!previewId) fail(400, 'preview_required', `call ${previewTool} with action "${action}" first, show the user its table, then pass its preview_id`);
+ const [row] = await sql`
+ UPDATE agent_market_previews SET consumed_at = now()
+ WHERE id = ${previewId} AND user_id = ${user.id} AND action = ${action}
+ AND consumed_at IS NULL AND created_at > now() - make_interval(secs => ${PREVIEW_TTL_MS / 1000})
+ AND params_hash = ${paramsHash(action, params)}
+ RETURNING id
+ `;
+ if (!row) {
+ fail(409, 'preview_stale', `that preview is missing, used, older than ten minutes, or was for different arguments; call ${previewTool} again`);
+ }
+}
+
+// ── Listing ──────────────────────────────────────────────────────────────────
+
+async function loadOwnedAgent(agentId, userId) {
+ if (!isUuid(agentId)) fail(400, 'bad_request', 'agent_id must be a uuid');
+ const [row] = await sql`
+ SELECT id, user_id, name, description, persona_prompt, skills, meta, wallet_address, chain_id, deleted_at
+ FROM agent_identities WHERE id = ${agentId} LIMIT 1
+ `;
+ if (!row || row.deleted_at) fail(404, 'agent_not_found', 'agent not found');
+ if (row.user_id !== userId) fail(403, 'forbidden', "that agent isn't on your account");
+ return row;
+}
+
+async function listingBlockers(agent) {
+ const [row] = await sql`
+ SELECT
+ (SELECT count(*)::int FROM agent_vaults WHERE agent_id = ${agent.id} AND status IN ('open', 'paused', 'closing')) AS vaults,
+ (SELECT count(*)::int FROM agent_recovery_requests WHERE agent_id = ${agent.id} AND status IN ('pending_approvals', 'time_locked', 'ready')) AS recoveries,
+ (SELECT count(*)::int FROM agent_listing_bids WHERE funding_agent_id = ${agent.id} AND status IN ('awaiting_funds', 'open')) AS funding_bids,
+ (SELECT count(*)::int FROM agent_listings WHERE agent_id = ${agent.id} AND status IN ('active', 'settling')) AS live
+ `;
+ if (row.live) fail(409, 'already_listed', 'this agent already has a live listing');
+ if (row.vaults) fail(409, 'vault_open', 'this agent manages a vault holding backers\' funds; close the vault before selling the agent');
+ if (row.recoveries) fail(409, 'recovery_pending', 'this agent has a pending recovery request; resolve it before listing');
+ if (row.funding_bids) fail(409, 'agent_funding_bids', 'this agent is funding open marketplace bids; withdraw them before listing it');
+}
+
+async function listingWarnings(agent) {
+ const warnings = [];
+ const [coins] = await sql`
+ SELECT (SELECT count(*)::int FROM pump_agent_mints WHERE agent_id = ${agent.id})
+ + (SELECT count(*)::int FROM agent_launched_coins WHERE agent_id = ${agent.id}) AS n
+ `.catch(() => [{ n: 0 }]);
+ if (coins?.n) {
+ warnings.push(`This agent launched ${coins.n} coin(s). Creator fees accrue to its current wallet, whose key is destroyed at transfer: claim them before the sale settles.`);
+ }
+ if (agent.meta?.encrypted_wallet_key && agent.wallet_address) {
+ warnings.push(`This agent also has a custodial EVM wallet (${agent.wallet_address}). Its balance follows the balance setting when you name an EVM payout address, and otherwise transfers with the agent.`);
+ }
+ const lim = getSpendLimits(agent.meta || {});
+ if (lim.frozen) warnings.push('The agent wallet is frozen now; it stays frozen for the buyer until they unfreeze it.');
+ return warnings;
+}
+
+async function defaultPayoutAddress(userId) {
+ const [row] = await sql`
+ SELECT address FROM user_wallets WHERE user_id = ${userId} AND chain_type = 'solana'
+ ORDER BY is_primary DESC, last_used_at DESC NULLS LAST, created_at DESC LIMIT 1
+ `;
+ return row?.address || null;
+}
+
+async function normalizeListingParams(user, p) {
+ const agent = await loadOwnedAgent(p.agent_id, user.id);
+ const minBid = parseAmount(p.min_bid_usdc, 6);
+ const askUsdc = p.ask_usdc != null && p.ask_usdc !== '' ? parseAmount(p.ask_usdc, 6) : null;
+ const askThree = p.ask_three != null && p.ask_three !== '' ? parseAmount(p.ask_three, currencyInfo('THREE').decimals) : null;
+ if (askUsdc != null && askUsdc < minBid) fail(400, 'bad_price', 'the buy-now price cannot be lower than the minimum bid');
+ const hours = p.duration_hours == null ? DEFAULT_DURATION_HOURS : Number(p.duration_hours);
+ if (!Number.isFinite(hours) || hours < MIN_DURATION_HOURS || hours > MAX_DURATION_HOURS) {
+ fail(400, 'bad_duration', `duration_hours must be between ${MIN_DURATION_HOURS} and ${MAX_DURATION_HOURS}`);
+ }
+ const payoutRaw = p.payout_address || (await defaultPayoutAddress(user.id));
+ if (!payoutRaw) fail(400, 'payout_address_required', 'name a Solana payout_address for the sale proceeds (no linked Solana wallet was found)');
+ const payout = solanaAddressOrFail(payoutRaw, 'payout_address');
+ if (payout === agent.meta?.solana_address) fail(400, 'bad_address', 'the payout address cannot be the agent\'s own wallet: that wallet is handed to the buyer');
+ let payoutEvm = null;
+ if (p.payout_evm_address) {
+ if (!/^0x[0-9a-fA-F]{40}$/.test(String(p.payout_evm_address))) fail(400, 'bad_address', 'payout_evm_address is not a valid EVM address');
+ payoutEvm = String(p.payout_evm_address);
+ }
+ const note = p.note ? String(p.note).trim().slice(0, 1000) : null;
+ return {
+ agent, minBid, askUsdc, askThree, hours, payout, payoutEvm, note,
+ includeBalance: p.include_balance === true,
+ includeHistory: p.include_history !== false,
+ };
+}
+
+async function previewCreateListing(user, p) {
+ const n = await normalizeListingParams(user, p);
+ await listingBlockers(n.agent);
+ const bal = await liveBalances(n.agent.meta?.solana_address).catch(() => null);
+ const bps = await effectiveFeeBps('USDC');
+ const refPrice = n.askUsdc ?? n.minBid;
+ const fee = (refPrice * BigInt(bps)) / 10_000n;
+ const table = [
+ { label: 'Agent', value: `${n.agent.name} (${n.agent.id})` },
+ { label: 'Buy-now price', value: n.askUsdc != null ? money(n.askUsdc, 'USDC') : 'none (auction only)' },
+ ...(n.askThree != null ? [{ label: 'Buy-now price in $THREE', value: money(n.askThree, 'THREE') }] : []),
+ { label: 'Minimum bid', value: money(n.minBid, 'USDC') },
+ { label: 'Ends', value: new Date(Date.now() + n.hours * 3_600_000).toISOString() },
+ { label: 'Wallet balance', value: n.includeBalance ? `transfers to the buyer (now ${bal?.sol ?? '?'} SOL, ${bal?.usdc ?? '?'} USDC)` : `swept to ${n.payout} before the handover` },
+ { label: 'History', value: n.includeHistory ? 'transfers' : 'deleted before the handover' },
+ { label: 'Proceeds to', value: n.payout },
+ { label: 'Platform fee', value: `${bps / 100}% (${money(fee, 'USDC')} at ${money(refPrice, 'USDC')})` },
+ { label: 'Chain', value: `Solana ${marketNetwork()}` },
+ ];
+ return { table, warnings: await listingWarnings(n.agent), what_transfers: whatTransfers({ include_balance: n.includeBalance, include_history: n.includeHistory }) };
+}
+
+/** List an agent for sale. Committing: the agent can be sold once this runs. */
+export async function createListing(user, p, { confirm = false } = {}) {
+ requireUser(user);
+ requireConfirm(confirm, 'Listing an agent');
+ await requireAgreement(user.id);
+ await requireFeePayer();
+ const n = await normalizeListingParams(user, p);
+ await listingBlockers(n.agent);
+ const id = randomUUID();
+ const escrowAddress = escrowAddressFor(id);
+ const [rep, bal, warnings] = await Promise.all([
+ getAgentReputation(n.agent.id, { lite: true }).catch(() => null),
+ liveBalances(n.agent.meta?.solana_address).catch(() => null),
+ listingWarnings(n.agent),
+ ]);
+ const snapshot = {
+ persona_summary: String(n.agent.description || n.agent.persona_prompt || '').slice(0, 280),
+ skills: n.agent.skills || [],
+ wallet_address: n.agent.meta?.solana_address || null,
+ wallet_balance: bal,
+ reputation: rep ? { score: rep.score, tier: rep.tier } : null,
+ warnings,
+ payout_evm_address: n.payoutEvm,
+ fee_bps_at_listing: saleFeeBps(),
+ };
+ try {
+ await store.insertListing({
+ id, agentId: n.agent.id, sellerUserId: user.id, askUsdc: n.askUsdc != null ? String(n.askUsdc) : null,
+ askThree: n.askThree != null ? String(n.askThree) : null, minBid: String(n.minBid),
+ expiresAt: new Date(Date.now() + n.hours * 3_600_000), includeBalance: n.includeBalance,
+ includeHistory: n.includeHistory, payoutAddress: n.payout, escrowAddress, note: n.note, snapshot,
+ });
+ } catch (err) {
+ if (err?.code === '23505') fail(409, 'already_listed', 'this agent already has a live listing');
+ throw err;
+ }
+ await store.addHistory({
+ agentId: n.agent.id, listingId: id, actorUserId: user.id, event: 'listed',
+ currency: 'USDC', amount: n.askUsdc ?? n.minBid, meta: { min_bid: String(n.minBid), ask: n.askUsdc != null ? String(n.askUsdc) : null },
+ });
+ logAudit({ userId: user.id, action: 'agent_market.listed', resourceId: n.agent.id, meta: { listing_id: id } });
+ return getListingDetail(id, user.id);
+}
+
+async function loadSellerListing(user, listingId) {
+ if (!isUuid(listingId)) fail(404, 'not_found', 'listing not found');
+ const row = await store.getListing(listingId);
+ if (!row) fail(404, 'not_found', 'listing not found');
+ if (row.seller_user_id !== user.id) fail(403, 'forbidden', 'only the seller can do that');
+ return row;
+}
+
+async function previewDelist(user, p) {
+ const row = await loadSellerListing(user, p.listing_id);
+ if (row.status !== 'active') fail(409, 'not_active', `this listing is ${row.status}`);
+ const bids = (await store.listBidsForListing(row.id)).filter((b) => b.status === 'open');
+ const table = [
+ { label: 'Listing', value: `${row.agent_name} (${row.id})` },
+ { label: 'Open bids refunded', value: String(bids.length) },
+ ...bids.map((b) => ({ label: `Refund ${b.id.slice(0, 8)}`, value: `${money(b.amount_atomics, b.currency)} to ${b.funding_address}` })),
+ { label: 'Chain', value: `Solana ${marketNetwork()}` },
+ ];
+ return { table, warnings: [] };
+}
+
+/** Take a listing down and refund every open bid. */
+export async function delistListing(user, listingId, { confirm = false } = {}) {
+ requireUser(user);
+ requireConfirm(confirm, 'Delisting refunds every open bid and');
+ const row = await loadSellerListing(user, listingId);
+ const closed = await store.closeListing({ listingId: row.id, sellerId: user.id, to: 'delisted', bidStatus: 'rejected' });
+ if (!closed) fail(409, 'not_active', 'this listing is no longer active (it may already be settling a sale)');
+ await store.addHistory({ agentId: row.agent_id, listingId: row.id, actorUserId: user.id, event: 'delisted', meta: { refunds: closed.refunds } });
+ await refundPendingForListing(row.id);
+ return getListingDetail(row.id, user.id);
+}
+
+// ── Bids ─────────────────────────────────────────────────────────────────────
+
+async function loadActiveListingForBid(user, listingId) {
+ if (!isUuid(listingId)) fail(404, 'not_found', 'listing not found');
+ const row = await store.getListing(listingId);
+ if (!row) fail(404, 'not_found', 'listing not found');
+ if (row.status !== 'active' || new Date(row.expires_at).getTime() <= Date.now()) fail(409, 'not_active', 'this listing is no longer taking bids');
+ if (row.seller_user_id === user.id || row.agent_owner_id === user.id) fail(403, 'own_listing', 'you cannot bid on your own agent');
+ return row;
+}
+
+async function resolveFunding(user, p, currency) {
+ const source = p.funding_source === 'agent_wallet' ? 'agent_wallet' : 'connected_wallet';
+ if (source === 'agent_wallet') {
+ if (currency !== 'USDC') fail(400, 'bad_funding', '$THREE buy-now payments come from a connected wallet');
+ if (!isUuid(p.funding_agent_id)) fail(400, 'bad_funding', 'funding_agent_id is required to pay from an agent wallet');
+ const [agent] = await sql`
+ SELECT id, user_id, name, meta, deleted_at FROM agent_identities WHERE id = ${p.funding_agent_id} LIMIT 1
+ `;
+ if (!agent || agent.deleted_at || agent.user_id !== user.id) fail(403, 'forbidden', "that funding agent isn't on your account");
+ if (!agent.meta?.solana_address || !agent.meta?.encrypted_solana_secret) fail(409, 'no_wallet', 'that agent has no Solana wallet yet');
+ const [live] = await sql`SELECT 1 FROM agent_listings WHERE agent_id = ${agent.id} AND status IN ('active', 'settling') LIMIT 1`;
+ if (live) fail(409, 'funding_agent_listed', 'that agent is listed for sale, so it cannot fund bids');
+ return { source, agent, address: agent.meta.solana_address };
+ }
+ return { source, agent: null, address: solanaAddressOrFail(p.wallet_address, 'wallet_address') };
+}
+
+async function bidTerms(user, p, kind) {
+ const listing = await loadActiveListingForBid(user, p.listing_id);
+ const currency = kind === 'buy_now' && p.currency === 'THREE' ? 'THREE' : 'USDC';
+ let amount;
+ if (kind === 'buy_now') {
+ const ask = currency === 'THREE' ? listing.ask_three_atomics : listing.ask_usdc_atomics;
+ if (ask == null) fail(409, 'no_buy_now', currency === 'THREE' ? 'this listing has no $THREE price' : 'this listing has no buy-now price; place a bid instead');
+ amount = BigInt(String(ask));
+ } else {
+ amount = parseAmount(p.amount_usdc, 6);
+ if (amount < BigInt(String(listing.min_bid_usdc_atomics))) fail(400, 'below_minimum', `the minimum bid is ${money(listing.min_bid_usdc_atomics, 'USDC')}`);
+ if (listing.top_bid_atomics != null && amount <= BigInt(String(listing.top_bid_atomics))) {
+ fail(400, 'not_highest', `bids must beat the current top bid of ${money(listing.top_bid_atomics, 'USDC')}`);
+ }
+ if (listing.ask_usdc_atomics != null && amount >= BigInt(String(listing.ask_usdc_atomics))) {
+ fail(400, 'use_buy_now', `that meets the buy-now price of ${money(listing.ask_usdc_atomics, 'USDC')}; use buy now instead`);
+ }
+ }
+ const funding = await resolveFunding(user, p, currency);
+ return { listing, currency, amount, funding };
+}
+
+async function previewBid(user, p, kind) {
+ const t = await bidTerms(user, p, kind);
+ const info = currencyInfo(t.currency);
+ const table = [
+ { label: 'Action', value: kind === 'buy_now' ? 'Buy now (settles immediately)' : 'Place bid' },
+ { label: 'Agent', value: `${t.listing.agent_name} (${t.listing.agent_id})` },
+ { label: 'Amount', value: money(t.amount, t.currency) },
+ { label: 'Token', value: `${info.symbol} (${info.mint})` },
+ { label: 'Chain', value: `Solana ${marketNetwork()}` },
+ { label: 'Recipient (escrow)', value: t.listing.escrow_address },
+ { label: 'Paid from', value: t.funding.source === 'agent_wallet' ? `agent ${t.funding.agent.name} wallet ${t.funding.address}` : `connected wallet ${t.funding.address}` },
+ { label: 'Refunded to', value: t.funding.address + ' if the bid is rejected, withdrawn, outbid at close, or expires' },
+ ];
+ const warnings = kind === 'buy_now'
+ ? ['Buy now accepts the seller\'s price: once the escrow transfer lands, the sale settles and custody rotates to you.']
+ : [];
+ return { table, warnings, what_transfers: whatTransfers(t.listing) };
+}
+
+/**
+ * Place a bid (or buy now). From an agent wallet the escrow transfer happens
+ * here and the bid comes back open; from a connected wallet the bid comes back
+ * awaiting funds with the transaction to sign.
+ */
+export async function placeBid(user, p, { confirm = false, kind = 'bid' } = {}) {
+ requireUser(user);
+ requireConfirm(confirm, kind === 'buy_now' ? 'Buying an agent' : 'A bid');
+ await requireAgreement(user.id);
+ await requireFeePayer();
+ const t = await bidTerms(user, p, kind);
+ const bid = await store.insertBid({
+ id: randomUUID(), listingId: t.listing.id, bidderUserId: user.id, kind, currency: t.currency, amount: t.amount,
+ fundingSource: t.funding.source, fundingAgentId: t.funding.agent?.id || null, fundingAddress: t.funding.address,
+ reference: t.funding.source === 'connected_wallet' ? newReference() : null,
+ fundBy: new Date(Date.now() + FUND_WINDOW_MS),
+ });
+ await store.addHistory({
+ agentId: t.listing.agent_id, listingId: t.listing.id, bidId: bid.id, actorUserId: user.id,
+ event: kind === 'buy_now' ? 'buy_now_started' : 'bid_placed', currency: t.currency, amount: t.amount,
+ meta: { funding_source: t.funding.source },
+ });
+
+ if (t.funding.source === 'connected_wallet') {
+ const tx = await buildFundingTransaction({ bid, listing: t.listing });
+ return { bid: store.bidView(bid, { viewerId: user.id }), funding: { status: 'awaiting_signature', ...tx } };
+ }
+
+ let signature;
+ try {
+ ({ signature } = await fundFromAgentWallet({ bid, listing: t.listing, fundingAgent: t.funding.agent }));
+ } catch (err) {
+ if (err.code !== 'unconfirmed') await store.expireUnfundedBid(bid.id, err.code || 'funding_failed');
+ throw err;
+ }
+ return onFunded(user, bid.id, signature);
+}
+
+/** Confirm a connected-wallet bid once its escrow transfer has landed. */
+export async function confirmBidFunding(user, bidId, { signature = null } = {}) {
+ requireUser(user);
+ if (!isUuid(bidId)) fail(404, 'not_found', 'bid not found');
+ const bid = await store.getBid(bidId);
+ if (!bid || bid.bidder_user_id !== user.id) fail(404, 'not_found', 'bid not found');
+ if (bid.status !== 'awaiting_funds') return { bid: store.bidView(bid, { viewerId: user.id }), funding: { status: 'already_recorded' } };
+ if (bid.funding_source !== 'connected_wallet') fail(409, 'not_wallet_bid', 'this bid is funded from an agent wallet');
+ const listing = await store.getListing(bid.listing_id);
+ const sig = await verifyConnectedFunding({ bid, listing, signature });
+ if (!sig) return { bid: store.bidView(bid, { viewerId: user.id }), funding: { status: 'not_landed' } };
+ return onFunded(user, bid.id, sig);
+}
+
+/** Rebuild the transaction for an unfunded connected-wallet bid (blockhash expired). */
+export async function rebuildFundingTransaction(user, bidId) {
+ requireUser(user);
+ const bid = isUuid(bidId) ? await store.getBid(bidId) : null;
+ if (!bid || bid.bidder_user_id !== user.id) fail(404, 'not_found', 'bid not found');
+ if (bid.status !== 'awaiting_funds' || bid.funding_source !== 'connected_wallet') fail(409, 'not_awaiting', 'this bid is not waiting for a wallet signature');
+ if (new Date(bid.fund_by).getTime() - Date.now() < 3 * 60 * 1000) fail(409, 'fund_window_closing', 'this bid\'s funding window is closing; place a new bid');
+ const listing = await store.getListing(bid.listing_id);
+ return { bid: store.bidView(bid, { viewerId: user.id }), funding: { status: 'awaiting_signature', ...(await buildFundingTransaction({ bid, listing })) } };
+}
+
+async function onFunded(user, bidId, signature) {
+ let funded;
+ try {
+ funded = await store.markBidFunded(bidId, signature);
+ } catch (err) {
+ if (err?.code === '23505') fail(409, 'signature_reused', 'that transaction already funded another bid');
+ throw err;
+ }
+ const bid = funded || (await store.getBid(bidId));
+ const listing = await store.getListing(bid.listing_id);
+ await store.addHistory({
+ agentId: listing.agent_id, listingId: listing.id, bidId: bid.id, actorUserId: bid.bidder_user_id,
+ event: 'bid_funded', currency: bid.currency, amount: bid.amount_atomics, signature,
+ });
+
+ if (bid.status === 'expired') {
+ await processRefund(bid.id);
+ fail(409, 'listing_closed', 'the listing closed before your escrow transfer landed; it is being refunded', { bid_id: bid.id });
+ }
+
+ // A higher bid from the same bidder replaces their earlier open ones.
+ const older = await sql`
+ UPDATE agent_listing_bids SET status = 'withdrawn', refund_status = 'pending', decided_at = now(), updated_at = now()
+ WHERE listing_id = ${bid.listing_id} AND bidder_user_id = ${bid.bidder_user_id} AND status = 'open' AND id <> ${bid.id}
+ RETURNING id
+ `;
+ for (const o of older) await processRefund(o.id).catch(() => {});
+
+ if (bid.kind === 'buy_now') {
+ return { bid: store.bidView(bid, { viewerId: user.id }), ...(await settleAccepted({ listing, bid, actorId: bid.bidder_user_id, bySystem: true })) };
+ }
+ insertNotification(listing.seller_user_id, 'agent_bid_received', {
+ agent_id: listing.agent_id, listing_id: listing.id, bid_id: bid.id, amount: money(bid.amount_atomics, bid.currency),
+ });
+ return { bid: store.bidView(bid, { viewerId: user.id }), funding: { status: 'escrowed', signature } };
+}
+
+async function loadBidAndListing(bidId) {
+ if (!isUuid(bidId)) fail(404, 'not_found', 'bid not found');
+ const bid = await store.getBid(bidId);
+ if (!bid) fail(404, 'not_found', 'bid not found');
+ const listing = await store.getListing(bid.listing_id);
+ return { bid, listing };
+}
+
+async function previewAccept(user, p) {
+ const { bid, listing } = await loadBidAndListing(p.bid_id);
+ if (listing.seller_user_id !== user.id) fail(403, 'forbidden', 'only the seller can accept a bid');
+ if (bid.status !== 'open') fail(409, 'bid_not_open', `this bid is ${bid.status}`);
+ const bps = await effectiveFeeBps(bid.currency);
+ const gross = BigInt(String(bid.amount_atomics));
+ const fee = (gross * BigInt(bps)) / 10_000n;
+ const table = [
+ { label: 'Agent', value: `${listing.agent_name} (${listing.agent_id})` },
+ { label: 'Winning bid', value: money(gross, bid.currency) },
+ { label: 'Platform fee', value: `${money(fee, bid.currency)} (${bps / 100}%) to ${(await feeRecipient(bid.currency)) || 'none'}` },
+ { label: 'You receive', value: `${money(gross - fee, bid.currency)} at ${listing.payout_address}` },
+ { label: 'Paid from (escrow)', value: listing.escrow_address },
+ { label: 'Chain', value: `Solana ${marketNetwork()}` },
+ { label: 'Other open bids', value: 'rejected and refunded' },
+ { label: 'New owner', value: bid.bidder_user_id },
+ ];
+ return {
+ table,
+ warnings: ['Accepting is final: the agent, its identity and (per the listing) its balance move to the buyer, and its wallet key is replaced.'],
+ what_transfers: whatTransfers(listing),
+ };
+}
+
+async function settleAccepted({ listing, bid, actorId, bySystem }) {
+ const feeBps = await effectiveFeeBps(bid.currency);
+ const accepted = await store.acceptBidAtomically({ listingId: listing.id, bidId: bid.id, sellerId: bySystem ? null : actorId, feeBps });
+ if (!accepted) {
+ if (bySystem) {
+ const refundable = await store.decideBid({ bidId: bid.id, to: 'expired' });
+ if (refundable) await processRefund(bid.id).catch(() => {});
+ }
+ fail(409, 'accept_lost', 'the listing or bid changed before it could be accepted (another bid may have won)');
+ }
+ await store.addHistory({
+ agentId: listing.agent_id, listingId: listing.id, bidId: bid.id, transferId: accepted.transfer_id, actorUserId: actorId,
+ event: 'accepted', currency: bid.currency, amount: bid.amount_atomics, meta: { rejected_others: accepted.rejected },
+ });
+ logAudit({ userId: actorId, action: 'agent_market.accepted', resourceId: listing.agent_id, meta: { listing_id: listing.id, bid_id: bid.id } });
+ await refundPendingForListing(listing.id);
+ const run = await runTransfer(accepted.transfer_id, { deadlineMs: INLINE_SETTLE_MS });
+ return { transfer: transferView(run.transfer, { viewerId: actorId }), settlement_error: run.error || null };
+}
+
+/** Seller accepts an open bid: settlement and custody rotation start at once. */
+export async function acceptBid(user, bidId, { confirm = false } = {}) {
+ requireUser(user);
+ requireConfirm(confirm, 'Accepting a bid sells the agent and');
+ await requireAgreement(user.id);
+ const { bid, listing } = await loadBidAndListing(bidId);
+ if (listing.seller_user_id !== user.id) fail(403, 'forbidden', 'only the seller can accept a bid');
+ if (bid.status !== 'open') fail(409, 'bid_not_open', `this bid is ${bid.status}`);
+ return settleAccepted({ listing, bid, actorId: user.id, bySystem: false });
+}
+
+export async function rejectBid(user, bidId) {
+ requireUser(user);
+ const { bid, listing } = await loadBidAndListing(bidId);
+ if (listing.seller_user_id !== user.id) fail(403, 'forbidden', 'only the seller can reject a bid');
+ const row = await store.decideBid({ bidId: bid.id, to: 'rejected', sellerId: user.id });
+ if (!row) fail(409, 'bid_not_open', `this bid is ${bid.status}`);
+ await store.addHistory({ agentId: listing.agent_id, listingId: listing.id, bidId: bid.id, actorUserId: user.id, event: 'bid_rejected', currency: bid.currency, amount: bid.amount_atomics });
+ insertNotification(bid.bidder_user_id, 'agent_bid_rejected', { agent_id: listing.agent_id, listing_id: listing.id, bid_id: bid.id, amount: money(bid.amount_atomics, bid.currency) });
+ const refund = await processRefund(bid.id);
+ return { bid: store.bidView(await store.getBid(bid.id), { viewerId: user.id }), refund };
+}
+
+async function previewWithdraw(user, p) {
+ const { bid, listing } = await loadBidAndListing(p.bid_id);
+ if (bid.bidder_user_id !== user.id) fail(403, 'forbidden', 'only the bidder can withdraw a bid');
+ if (bid.status !== 'open') fail(409, 'bid_not_open', `this bid is ${bid.status}`);
+ const table = [
+ { label: 'Agent', value: listing.agent_name },
+ { label: 'Refund', value: money(bid.amount_atomics, bid.currency) },
+ { label: 'From (escrow)', value: listing.escrow_address },
+ { label: 'To', value: bid.funding_address },
+ { label: 'Chain', value: `Solana ${marketNetwork()}` },
+ ];
+ return { table, warnings: [] };
+}
+
+export async function withdrawBid(user, bidId, { confirm = false } = {}) {
+ requireUser(user);
+ requireConfirm(confirm, 'Withdrawing a bid');
+ const { bid, listing } = await loadBidAndListing(bidId);
+ if (bid.bidder_user_id !== user.id) fail(403, 'forbidden', 'only the bidder can withdraw a bid');
+ const row = await store.decideBid({ bidId: bid.id, to: 'withdrawn', bidderId: user.id });
+ if (!row) fail(409, 'bid_not_open', `this bid is ${bid.status}`);
+ await store.addHistory({ agentId: listing.agent_id, listingId: listing.id, bidId: bid.id, actorUserId: user.id, event: 'bid_withdrawn', currency: bid.currency, amount: bid.amount_atomics });
+ const refund = await processRefund(bid.id);
+ return { bid: store.bidView(await store.getBid(bid.id), { viewerId: user.id }), refund };
+}
+
+// ── Refunds ──────────────────────────────────────────────────────────────────
+
+/**
+ * Send one pending refund under a lease. Errors are recorded on the bid for
+ * the sweep cron to retry; the return value says what happened.
+ */
+export async function processRefund(bidId) {
+ const [bid] = await sql`
+ UPDATE agent_listing_bids
+ SET refund_locked_until = now() + interval '3 minutes', refund_attempts = refund_attempts + 1, updated_at = now()
+ WHERE id = ${bidId} AND refund_status IN ('pending', 'failed')
+ AND (refund_locked_until IS NULL OR refund_locked_until < now())
+ RETURNING *
+ `;
+ if (!bid) return { status: 'not_due' };
+ const [listing] = await sql`SELECT * FROM agent_listings WHERE id = ${bid.listing_id}`;
+ try {
+ const { signature, destination } = await refundBid({ bid, listing });
+ await sql`
+ UPDATE agent_listing_bids
+ SET refund_status = 'sent', refund_signature = ${signature}, refund_error = NULL, refund_locked_until = NULL, updated_at = now()
+ WHERE id = ${bid.id}
+ `;
+ await store.addHistory({
+ agentId: listing.agent_id, listingId: listing.id, bidId: bid.id, event: 'bid_refunded',
+ currency: bid.currency, amount: bid.amount_atomics, signature, meta: { to: destination },
+ });
+ insertNotification(bid.bidder_user_id, 'agent_bid_refunded', {
+ listing_id: listing.id, bid_id: bid.id, amount: money(bid.amount_atomics, bid.currency), signature,
+ });
+ return { status: 'sent', signature, destination };
+ } catch (err) {
+ await sql`
+ UPDATE agent_listing_bids
+ SET refund_status = 'failed', refund_error = ${String(err?.message || err).slice(0, 400)}, refund_locked_until = NULL, updated_at = now()
+ WHERE id = ${bid.id}
+ `;
+ return { status: 'retrying', code: err?.code || 'refund_failed', message: err?.message };
+ }
+}
+
+async function refundPendingForListing(listingId) {
+ const due = await sql`SELECT id FROM agent_listing_bids WHERE listing_id = ${listingId} AND refund_status IN ('pending', 'failed')`;
+ for (const b of due) await processRefund(b.id).catch(() => {});
+}
+
+// ── Resume ───────────────────────────────────────────────────────────────────
+
+/** The failure state's resume action: either party may drive it forward. */
+export async function resumeTransfer(user, transferId) {
+ requireUser(user);
+ if (!isUuid(transferId)) fail(404, 'not_found', 'transfer not found');
+ const row = await store.getTransfer(transferId);
+ if (!row || (row.buyer_user_id !== user.id && row.seller_user_id !== user.id)) fail(404, 'not_found', 'transfer not found');
+ if (row.status === 'completed') return { transfer: transferView(row, { viewerId: user.id }) };
+ const run = await runTransfer(transferId, { deadlineMs: INLINE_SETTLE_MS });
+ if (run.busy) fail(409, 'transfer_busy', 'settlement is already running for this transfer; refresh in a moment');
+ return { transfer: transferView(run.transfer, { viewerId: user.id }), settlement_error: run.error || null };
+}
+
+export { agentWalletFundingStatus, isUuid };
diff --git a/api/_lib/agent-market/settlement.js b/api/_lib/agent-market/settlement.js
new file mode 100644
index 000000000..7b78bdebf
--- /dev/null
+++ b/api/_lib/agent-market/settlement.js
@@ -0,0 +1,397 @@
+// Settlement: the one idempotent state machine that turns an accepted bid into
+// a paid seller and an agent the buyer alone controls.
+//
+// pay_seller -> pay_fee -> prepare_keys -> sweep_wallet -> swap_keys
+// -> revoke_access -> detach_history -> reassign_owner -> destroy_old_key
+// -> finalize -> done
+//
+// `agent_transfers.step` is the resume point. A step runs, then the row
+// advances with a compare-and-set on the step it ran, so a crash at any point
+// re-runs at most the step in progress, and every step is written to be safe to
+// re-run (on-chain legs through chain.js sendLeg, database writes conditional
+// on the state they expect). A lease (`locked_until`) keeps two workers from
+// driving one transfer at once; an expired lease is how a dead worker's
+// transfer gets picked back up by the marketplace-escrow-sweep cron.
+
+import { sql } from '../db.js';
+import { insertNotification } from '../notify.js';
+import { logAudit } from '../audit.js';
+import { getFeeBps } from '../fee.js';
+import { loadBuybackSigner } from '../token/buyback.js';
+import { treasuryWalletOrNull } from '../token/config.js';
+import { marketplaceFeeRecipient } from '../marketplace-platform-fee.js';
+import { SOLANA_USDC_MINT } from '../../payments/_config.js';
+import {
+ currencyInfo, formatAtomics, marketConnection, marketNetwork, sendLeg, tokenProgramFor, transferIxs, withEscrowKeypair,
+} from './chain.js';
+import {
+ destroyOldKey, detachHistory, loadAgent, prepareNewKeys, reassignOwner, repointPositions,
+ revokeSellerAccess, swapKeys, sweepOldEvmWallet, sweepOldWallet,
+} from './custody.js';
+import { addHistory } from './store.js';
+
+export const STEPS = [
+ 'pay_seller',
+ 'pay_fee',
+ 'prepare_keys',
+ 'sweep_wallet',
+ 'swap_keys',
+ 'revoke_access',
+ 'detach_history',
+ 'reassign_owner',
+ 'destroy_old_key',
+ 'finalize',
+];
+
+export const STEP_LABELS = {
+ pay_seller: 'Pay the seller from escrow',
+ pay_fee: 'Route the platform fee',
+ prepare_keys: 'Generate the new wallet keys',
+ sweep_wallet: 'Sweep the old wallet',
+ swap_keys: 'Install the new keys',
+ revoke_access: "Revoke the seller's access",
+ detach_history: 'Apply the history setting',
+ reassign_owner: 'Transfer ownership',
+ destroy_old_key: 'Destroy the old key',
+ finalize: 'Close the sale',
+};
+
+// Long enough for the slowest step (a sweep of many token accounts, each leg
+// confirming for up to 90 seconds); renewed on every step advance.
+const LEASE_SECONDS = 600;
+const MAX_FEE_BPS = 1000;
+
+export function nextStep(step) {
+ const i = STEPS.indexOf(step);
+ if (i < 0) throw new Error(`unknown settlement step ${step}`);
+ return i === STEPS.length - 1 ? 'done' : STEPS[i + 1];
+}
+
+// ── Fees ─────────────────────────────────────────────────────────────────────
+
+/** The sale fee rate: AGENT_MARKET_FEE_BPS, else the platform rate, capped. */
+export function saleFeeBps() {
+ const raw = process.env.AGENT_MARKET_FEE_BPS;
+ const n = raw == null || String(raw).trim() === '' ? getFeeBps() : parseInt(raw, 10);
+ if (!Number.isFinite(n) || n < 0) return 0;
+ return Math.min(n, MAX_FEE_BPS);
+}
+
+/**
+ * Where the sale fee goes: USDC to the $THREE buyback wallet, whose balance the
+ * run-three-buyback cron turns into market buys routed to the treasury; $THREE
+ * straight to the treasury. Falls back to the marketplace fee wallet. Null means
+ * no fee can be routed, and the sale then charges none.
+ */
+export async function feeRecipient(currency) {
+ if (currency === 'THREE') {
+ const treasury = treasuryWalletOrNull();
+ if (treasury) return treasury;
+ } else {
+ const signer = await loadBuybackSigner().catch(() => null);
+ if (signer) return signer.publicKey.toBase58();
+ }
+ const fallback = await marketplaceFeeRecipient();
+ return fallback ? fallback.toBase58() : null;
+}
+
+/** Fee rate to lock in at accept time: zero when nothing could receive it. */
+export async function effectiveFeeBps(currency) {
+ const bps = saleFeeBps();
+ if (bps === 0) return 0;
+ return (await feeRecipient(currency)) ? bps : 0;
+}
+
+// ── Store (swappable for tests) ──────────────────────────────────────────────
+
+export const dbStore = {
+ async lease(transferId) {
+ const [row] = await sql`
+ UPDATE agent_transfers
+ SET locked_until = now() + make_interval(secs => ${LEASE_SECONDS}), attempts = attempts + 1,
+ status = 'in_progress', updated_at = now()
+ WHERE id = ${transferId} AND status <> 'completed'
+ AND (locked_until IS NULL OR locked_until < now())
+ RETURNING *
+ `;
+ return row || null;
+ },
+ async load(transferId) {
+ const [row] = await sql`SELECT * FROM agent_transfers WHERE id = ${transferId}`;
+ return row || null;
+ },
+ async advance(transferId, from, to) {
+ const [row] = await sql`
+ UPDATE agent_transfers
+ SET step = ${to}, last_error = NULL, updated_at = now(),
+ locked_until = now() + make_interval(secs => ${LEASE_SECONDS}),
+ status = CASE WHEN ${to} = 'done' THEN 'completed' ELSE status END,
+ completed_at = CASE WHEN ${to} = 'done' THEN now() ELSE completed_at END
+ WHERE id = ${transferId} AND step = ${from}
+ RETURNING *
+ `;
+ if (!row) throw new Error(`transfer ${transferId} left step ${from} under another worker`);
+ return row;
+ },
+ async fail(transferId, step, message) {
+ await sql`
+ UPDATE agent_transfers
+ SET status = 'failed', last_error = ${`${step}: ${message}`.slice(0, 600)}, locked_until = NULL, updated_at = now()
+ WHERE id = ${transferId}
+ `;
+ },
+ async release(transferId) {
+ await sql`UPDATE agent_transfers SET locked_until = NULL WHERE id = ${transferId}`;
+ },
+};
+
+// ── Steps ────────────────────────────────────────────────────────────────────
+
+async function loadListing(listingId) {
+ const [row] = await sql`SELECT * FROM agent_listings WHERE id = ${listingId}`;
+ return row;
+}
+
+function legRecorder(transferId, column) {
+ return async (legId, rec) => {
+ await sql`
+ UPDATE agent_transfers
+ SET legs = legs || jsonb_build_object(${legId}::text, ${JSON.stringify(rec)}::jsonb),
+ payout_signature = CASE WHEN ${column} = 'payout' THEN ${rec.signature} ELSE payout_signature END,
+ fee_signature = CASE WHEN ${column} = 'fee' THEN ${rec.signature} ELSE fee_signature END,
+ updated_at = now()
+ WHERE id = ${transferId}
+ `;
+ };
+}
+
+async function escrowPay({ transfer, listing, legId, column, to, atomics }) {
+ const connection = marketConnection();
+ const info = currencyInfo(transfer.currency);
+ const programId = await tokenProgramFor(connection, info.mint);
+ const record = legRecorder(transfer.id, column);
+ return withEscrowKeypair(listing, (escrow) =>
+ sendLeg({
+ connection,
+ legId,
+ prior: transfer.legs?.[legId] || null,
+ signers: [escrow],
+ build: (reference, payer) =>
+ transferIxs({
+ owner: escrow.publicKey.toBase58(), recipient: to, mint: info.mint, programId,
+ decimals: info.decimals, atomics: BigInt(String(atomics)), rentPayer: payer.toBase58(), reference,
+ }),
+ onPrepared: (rec) => record(legId, rec),
+ }),
+ );
+}
+
+async function recordFeeRevenue(transfer, signature) {
+ if (transfer.currency !== 'USDC') return;
+ const intentId = `agent-market:${transfer.id}`;
+ const fee = String(transfer.fee_atomics);
+ await sql`
+ INSERT INTO agent_payment_intents
+ (id, payer_user_id, agent_id, currency_mint, amount, memo, start_time, end_time, status, cluster, tx_signature, paid_at, payload, expires_at)
+ VALUES (
+ ${intentId}, ${transfer.buyer_user_id}, ${transfer.agent_id}, ${SOLANA_USDC_MINT}, ${String(transfer.amount_atomics)},
+ ${`agent sale ${transfer.listing_id}`}, now(), now(), 'paid', ${marketNetwork()}, ${signature}, now(),
+ ${JSON.stringify({ kind: 'agent_sale', transfer_id: transfer.id, listing_id: transfer.listing_id })}::jsonb, now()
+ )
+ ON CONFLICT (id) DO NOTHING
+ `;
+ // gross = net = the platform's share only: the sale proceeds are the
+ // seller's, not the agent's earnings, so the agent is credited nothing.
+ await sql`
+ INSERT INTO agent_revenue_events
+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount, currency_mint, chain, payer_address, owner_user_id)
+ VALUES (${transfer.agent_id}, ${intentId}, 'marketplace:agent_sale', ${fee}, ${fee}, 0, ${SOLANA_USDC_MINT}, 'solana', NULL, ${transfer.seller_user_id})
+ ON CONFLICT (intent_id) DO NOTHING
+ `;
+}
+
+export const defaultSteps = {
+ async pay_seller({ transfer, listing }) {
+ const legId = `payout:${transfer.id}`;
+ const { signature } = await escrowPay({
+ transfer, listing, legId, column: 'payout', to: listing.payout_address, atomics: transfer.seller_net_atomics,
+ });
+ await addHistory({
+ agentId: transfer.agent_id, listingId: listing.id, bidId: transfer.bid_id, transferId: transfer.id,
+ actorUserId: transfer.seller_user_id, event: 'seller_paid', currency: transfer.currency,
+ amount: transfer.seller_net_atomics, signature, meta: { to: listing.payout_address },
+ });
+ },
+
+ async pay_fee({ transfer, listing }) {
+ if (BigInt(String(transfer.fee_atomics)) <= 0n) return;
+ const to = await feeRecipient(transfer.currency);
+ if (!to) throw Object.assign(new Error('no fee wallet is configured'), { code: 'fee_wallet_unavailable' });
+ const legId = `fee:${transfer.id}`;
+ const { signature } = await escrowPay({ transfer, listing, legId, column: 'fee', to, atomics: transfer.fee_atomics });
+ await recordFeeRevenue(transfer, signature);
+ await addHistory({
+ agentId: transfer.agent_id, listingId: listing.id, transferId: transfer.id, event: 'fee_routed',
+ currency: transfer.currency, amount: transfer.fee_atomics, signature, meta: { to },
+ });
+ },
+
+ async prepare_keys({ transfer, agent }) {
+ await prepareNewKeys(transfer, agent);
+ },
+
+ async sweep_wallet({ transfer, listing, agent }) {
+ const pending = transfer.rotation?.pending;
+ const destination = listing.include_balance ? pending.solana_address : listing.payout_address;
+ await sweepOldWallet({ transfer, agent, destination });
+ if (pending?.old_evm_address) {
+ // Base funds follow the balance setting when the seller named an EVM
+ // payout address; otherwise they transfer with the agent.
+ const evmDest = listing.include_balance || !listing.snapshot?.payout_evm_address
+ ? pending.evm_address
+ : listing.snapshot.payout_evm_address;
+ await sweepOldEvmWallet({ transfer: await dbStore.load(transfer.id), agent, destination: evmDest });
+ }
+ await repointPositions({ transfer, agent, includeBalance: listing.include_balance });
+ },
+
+ async swap_keys({ transfer, agent }) {
+ await swapKeys({ transfer, agent });
+ },
+
+ async revoke_access({ transfer, agent }) {
+ await revokeSellerAccess({ transfer, agent });
+ },
+
+ async detach_history({ transfer, listing, agent }) {
+ if (listing.include_history) return;
+ await detachHistory({ transfer, agent });
+ },
+
+ async reassign_owner({ transfer, agent }) {
+ await reassignOwner({ transfer, agent });
+ },
+
+ async destroy_old_key({ transfer, agent }) {
+ await destroyOldKey({ transfer, agent });
+ },
+
+ async finalize({ transfer, listing }) {
+ await sql`
+ UPDATE agent_listings SET status = 'sold', closed_at = coalesce(closed_at, now()), updated_at = now()
+ WHERE id = ${listing.id} AND status = 'settling'
+ `;
+ const [existing] = await sql`
+ SELECT 1 FROM agent_marketplace_history WHERE transfer_id = ${transfer.id} AND event = 'sold' LIMIT 1
+ `;
+ if (!existing) {
+ await addHistory({
+ agentId: transfer.agent_id, listingId: listing.id, bidId: transfer.bid_id, transferId: transfer.id,
+ actorUserId: transfer.buyer_user_id, event: 'sold', currency: transfer.currency, amount: transfer.amount_atomics,
+ signature: transfer.payout_signature,
+ meta: { buyer: transfer.buyer_user_id, seller: transfer.seller_user_id, new_wallet: transfer.new_wallet_address },
+ });
+ const info = currencyInfo(transfer.currency);
+ const amount = `${formatAtomics(transfer.amount_atomics, info.decimals)} ${info.symbol}`;
+ insertNotification(transfer.buyer_user_id, 'agent_purchased', {
+ agent_id: transfer.agent_id, transfer_id: transfer.id, amount,
+ message: 'The agent is yours. Its wallet starts frozen with conservative limits; unfreeze it under Limits & Safety.',
+ });
+ insertNotification(transfer.seller_user_id, 'agent_sold', {
+ agent_id: transfer.agent_id, transfer_id: transfer.id, amount,
+ net: `${formatAtomics(transfer.seller_net_atomics, info.decimals)} ${info.symbol}`,
+ signature: transfer.payout_signature,
+ });
+ logAudit({
+ userId: transfer.buyer_user_id, action: 'agent_market.transfer_completed', resourceId: transfer.agent_id,
+ meta: { transfer_id: transfer.id, seller: transfer.seller_user_id, amount_atomics: String(transfer.amount_atomics), currency: transfer.currency },
+ });
+ }
+ },
+};
+
+// ── Runner ───────────────────────────────────────────────────────────────────
+
+async function defaultContext(transfer) {
+ const [listing, agent] = await Promise.all([loadListing(transfer.listing_id), loadAgent(transfer.agent_id)]);
+ return { transfer, listing, agent };
+}
+
+/**
+ * Drive a transfer from its current step to done, or until a step fails.
+ * Returns the final row and, on failure, the error. Never throws for a step
+ * failure: the failure is recorded on the row and the next run resumes it.
+ *
+ * @param {string} transferId
+ * @param {{ store?: typeof dbStore, steps?: typeof defaultSteps, context?: (t: object) => Promise<object>,
+ * deadlineMs?: number }} [deps]
+ */
+export async function runTransfer(transferId, deps = {}) {
+ const store = deps.store || dbStore;
+ const steps = deps.steps || defaultSteps;
+ const context = deps.context || defaultContext;
+ const deadline = Date.now() + (deps.deadlineMs ?? 240_000);
+
+ let transfer = await store.lease(transferId);
+ if (!transfer) {
+ const current = await store.load(transferId);
+ return { transfer: current, busy: current ? current.status !== 'completed' : false };
+ }
+ while (transfer.step !== 'done') {
+ if (Date.now() > deadline) {
+ await store.release(transferId);
+ return { transfer, paused: true };
+ }
+ const step = transfer.step;
+ try {
+ const ctx = await context(transfer);
+ await steps[step](ctx);
+ } catch (err) {
+ const message = err?.message || String(err);
+ await store.fail(transferId, step, message);
+ if (deps.log !== false) console.warn('[agent-market] settlement step failed', transferId, step, message);
+ return { transfer: await store.load(transferId), error: { step, code: err?.code || 'step_failed', message } };
+ }
+ transfer = await store.advance(transferId, step, nextStep(step));
+ if (store === dbStore) {
+ await addHistory({
+ agentId: transfer.agent_id, listingId: transfer.listing_id, transferId, event: 'transfer_step',
+ meta: { step, label: STEP_LABELS[step] },
+ }).catch(() => {});
+ }
+ }
+ return { transfer };
+}
+
+/** Public shape of a transfer for the UI and tools: step-by-step progress. */
+export function transferView(row, { viewerId = null } = {}) {
+ const info = currencyInfo(row.currency);
+ const doneIndex = row.step === 'done' ? STEPS.length : STEPS.indexOf(row.step);
+ const party = viewerId === row.buyer_user_id ? 'buyer' : viewerId === row.seller_user_id ? 'seller' : null;
+ return {
+ id: row.id,
+ listing_id: row.listing_id,
+ agent_id: row.agent_id,
+ status: row.status,
+ step: row.step,
+ viewer_role: party,
+ amount: { atomics: String(row.amount_atomics), amount: formatAtomics(row.amount_atomics, info.decimals), symbol: info.symbol },
+ fee: { atomics: String(row.fee_atomics), amount: formatAtomics(row.fee_atomics, info.decimals), symbol: info.symbol },
+ seller_net: { atomics: String(row.seller_net_atomics), amount: formatAtomics(row.seller_net_atomics, info.decimals), symbol: info.symbol },
+ steps: STEPS.map((s, i) => ({
+ id: s,
+ label: STEP_LABELS[s],
+ state: i < doneIndex ? 'done' : i === doneIndex ? (row.status === 'failed' ? 'failed' : 'running') : 'pending',
+ })),
+ payout_signature: row.payout_signature || null,
+ fee_signature: row.fee_signature || null,
+ old_wallet_address: row.old_wallet_address || null,
+ new_wallet_address: row.new_wallet_address || null,
+ stranded: row.rotation?.sweep?.stranded || [],
+ last_error: party ? row.last_error || null : undefined,
+ attempts: row.attempts,
+ can_resume: row.status === 'failed' && Boolean(party),
+ completed_at: row.completed_at ? new Date(row.completed_at).toISOString() : null,
+ updated_at: new Date(row.updated_at).toISOString(),
+ };
+}
diff --git a/api/_lib/agent-market/store.js b/api/_lib/agent-market/store.js
new file mode 100644
index 000000000..dc989752a
--- /dev/null
+++ b/api/_lib/agent-market/store.js
@@ -0,0 +1,422 @@
+// Data layer for the whole-agent marketplace: listing and bid queries, the
+// atomic state transitions, the history log, and the public view shapes.
+//
+// Every transition that races (accept vs withdraw, two accepts, buy-now vs
+// delist) is ONE conditional statement: the database driver has no interactive
+// transactions, and a single statement is what makes "only one caller wins"
+// true under concurrency. Callers read the RETURNING rows to learn if they won.
+
+import { sql } from '../db.js';
+import { thumbnailUrl, publicUrlOrNull } from '../r2.js';
+import { currencyInfo, formatAtomics } from './chain.js';
+
+export const LISTING_STATUSES = ['active', 'settling', 'sold', 'delisted', 'expired'];
+
+// ── Listings ─────────────────────────────────────────────────────────────────
+
+const LISTING_COLUMNS = sql`
+ l.*,
+ ai.name AS agent_name,
+ ai.description AS agent_description,
+ ai.persona_prompt AS agent_persona,
+ ai.skills AS agent_skills,
+ ai.category AS agent_category,
+ ai.user_id AS agent_owner_id,
+ ai.meta->>'solana_address' AS agent_solana_address,
+ av.thumbnail_key AS avatar_thumbnail_key,
+ av.storage_key AS avatar_storage_key,
+ av.visibility AS avatar_visibility,
+ su.display_name AS seller_name,
+ (SELECT max(b.amount_atomics) FROM agent_listing_bids b
+ WHERE b.listing_id = l.id AND b.status = 'open' AND b.currency = 'USDC') AS top_bid_atomics,
+ (SELECT count(*)::int FROM agent_listing_bids b
+ WHERE b.listing_id = l.id AND b.status IN ('open', 'accepted')) AS bid_count,
+ (SELECT count(*)::int FROM agent_marketplace_history h
+ WHERE h.agent_id = l.agent_id AND h.event = 'sold') AS prior_sales
+`;
+
+const LISTING_FROM = sql`
+ FROM agent_listings l
+ JOIN agent_identities ai ON ai.id = l.agent_id
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ LEFT JOIN users su ON su.id = l.seller_user_id
+`;
+
+export async function getListing(id) {
+ const [row] = await sql`SELECT ${LISTING_COLUMNS} ${LISTING_FROM} WHERE l.id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+/** The live (active or settling) listing for an agent, if any. */
+export async function getLiveListingForAgent(agentId) {
+ const [row] = await sql`
+ SELECT ${LISTING_COLUMNS} ${LISTING_FROM}
+ WHERE l.agent_id = ${agentId} AND l.status IN ('active', 'settling')
+ LIMIT 1
+ `;
+ return row || null;
+}
+
+const SORTS = {
+ ending: sql`l.expires_at ASC`,
+ newest: sql`l.created_at DESC`,
+ price_asc: sql`coalesce(l.ask_usdc_atomics, l.min_bid_usdc_atomics) ASC`,
+ price_desc: sql`coalesce(l.ask_usdc_atomics, l.min_bid_usdc_atomics) DESC`,
+ most_bids: sql`bid_count DESC, l.expires_at ASC`,
+};
+
+export function normalizeSort(sort) {
+ return Object.prototype.hasOwnProperty.call(SORTS, sort) ? sort : 'ending';
+}
+
+/**
+ * Browse listings. `status` defaults to active (and unexpired). `sellerId`
+ * narrows to one seller and lifts the status default so a dashboard sees all.
+ */
+export async function listListings({ q = '', sort = 'ending', limit = 24, offset = 0, sellerId = null, status = null } = {}) {
+ const qLike = q ? `%${q.slice(0, 80)}%` : null;
+ const orderBy = SORTS[normalizeSort(sort)];
+ const statusFilter = status
+ ? sql`l.status = ${status}`
+ : sellerId
+ ? sql`true`
+ : sql`l.status = 'active' AND l.expires_at > now()`;
+ const rows = await sql`
+ SELECT ${LISTING_COLUMNS} ${LISTING_FROM}
+ WHERE ${statusFilter}
+ AND ai.deleted_at IS NULL
+ AND (${sellerId}::uuid IS NULL OR l.seller_user_id = ${sellerId})
+ AND (${qLike}::text IS NULL OR ai.name ILIKE ${qLike} OR ai.description ILIKE ${qLike}
+ OR EXISTS (SELECT 1 FROM unnest(ai.skills) s WHERE s ILIKE ${qLike}))
+ ORDER BY ${orderBy}, l.id
+ LIMIT ${limit + 1} OFFSET ${offset}
+ `;
+ return { rows: rows.slice(0, limit), hasMore: rows.length > limit };
+}
+
+export async function insertListing(l) {
+ const [row] = await sql`
+ INSERT INTO agent_listings (
+ id, agent_id, seller_user_id, ask_usdc_atomics, ask_three_atomics, min_bid_usdc_atomics,
+ expires_at, include_balance, include_history, payout_address, escrow_address, note, snapshot
+ ) VALUES (
+ ${l.id}, ${l.agentId}, ${l.sellerUserId}, ${l.askUsdc}, ${l.askThree}, ${l.minBid},
+ ${l.expiresAt}, ${l.includeBalance}, ${l.includeHistory}, ${l.payoutAddress},
+ ${l.escrowAddress}, ${l.note}, ${JSON.stringify(l.snapshot)}::jsonb
+ )
+ RETURNING id
+ `;
+ return row.id;
+}
+
+/**
+ * Close an active listing (delist or expire) and move every open bid to a
+ * refund. One statement, so a racing accept either wins first (and this
+ * returns null) or finds the listing already closed.
+ */
+export async function closeListing({ listingId, sellerId = null, to, bidStatus }) {
+ const [row] = await sql`
+ WITH l AS (
+ UPDATE agent_listings
+ SET status = ${to}, closed_at = now(), updated_at = now()
+ WHERE id = ${listingId} AND status = 'active'
+ AND (${sellerId}::uuid IS NULL OR seller_user_id = ${sellerId})
+ RETURNING id, agent_id
+ ), b AS (
+ UPDATE agent_listing_bids
+ SET status = ${bidStatus}, refund_status = 'pending', decided_at = now(), updated_at = now()
+ WHERE listing_id = ${listingId} AND status = 'open' AND EXISTS (SELECT 1 FROM l)
+ RETURNING id
+ )
+ SELECT (SELECT id FROM l) AS listing_id, (SELECT agent_id FROM l) AS agent_id,
+ (SELECT count(*)::int FROM b) AS refunds
+ `;
+ return row?.listing_id ? row : null;
+}
+
+// ── Bids ─────────────────────────────────────────────────────────────────────
+
+export async function getBid(id) {
+ const [row] = await sql`SELECT * FROM agent_listing_bids WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+export async function listBidsForListing(listingId) {
+ return sql`
+ SELECT b.*, u.display_name AS bidder_name
+ FROM agent_listing_bids b
+ LEFT JOIN users u ON u.id = b.bidder_user_id
+ WHERE b.listing_id = ${listingId} AND b.status <> 'awaiting_funds'
+ ORDER BY b.amount_atomics DESC, b.created_at ASC
+ LIMIT 200
+ `;
+}
+
+export async function listBidsByBidder(userId, { limit = 50 } = {}) {
+ return sql`
+ SELECT b.*, ai.name AS agent_name, l.agent_id, l.status AS listing_status, l.expires_at AS listing_expires_at
+ FROM agent_listing_bids b
+ JOIN agent_listings l ON l.id = b.listing_id
+ JOIN agent_identities ai ON ai.id = l.agent_id
+ WHERE b.bidder_user_id = ${userId}
+ ORDER BY b.created_at DESC
+ LIMIT ${limit}
+ `;
+}
+
+export async function listBidsReceived(sellerId, { limit = 100 } = {}) {
+ return sql`
+ SELECT b.*, ai.name AS agent_name, l.agent_id, l.status AS listing_status,
+ l.expires_at AS listing_expires_at, u.display_name AS bidder_name
+ FROM agent_listing_bids b
+ JOIN agent_listings l ON l.id = b.listing_id
+ JOIN agent_identities ai ON ai.id = l.agent_id
+ LEFT JOIN users u ON u.id = b.bidder_user_id
+ WHERE l.seller_user_id = ${sellerId} AND b.status <> 'awaiting_funds'
+ ORDER BY (b.status = 'open') DESC, b.created_at DESC
+ LIMIT ${limit}
+ `;
+}
+
+export async function insertBid(b) {
+ const [row] = await sql`
+ INSERT INTO agent_listing_bids (
+ id, listing_id, bidder_user_id, kind, currency, amount_atomics, funding_source,
+ funding_agent_id, funding_address, escrow_reference, fund_by
+ ) VALUES (
+ ${b.id}, ${b.listingId}, ${b.bidderUserId}, ${b.kind}, ${b.currency}, ${String(b.amount)},
+ ${b.fundingSource}, ${b.fundingAgentId}, ${b.fundingAddress}, ${b.reference}, ${b.fundBy}
+ )
+ RETURNING *
+ `;
+ return row;
+}
+
+/**
+ * Record that a bid's escrow transfer landed. It opens only while its listing
+ * is still active; otherwise the funds are already in escrow and must go back,
+ * so it lands as expired with a pending refund.
+ */
+export async function markBidFunded(bidId, signature) {
+ const [row] = await sql`
+ UPDATE agent_listing_bids b
+ SET escrow_signature = ${signature}, funded_at = now(), updated_at = now(),
+ status = CASE WHEN l.status = 'active' AND l.expires_at > now() THEN 'open' ELSE 'expired' END,
+ refund_status = CASE WHEN l.status = 'active' AND l.expires_at > now() THEN NULL ELSE 'pending' END,
+ decided_at = CASE WHEN l.status = 'active' AND l.expires_at > now() THEN NULL ELSE now() END
+ FROM agent_listings l
+ WHERE b.id = ${bidId} AND l.id = b.listing_id AND b.status = 'awaiting_funds'
+ RETURNING b.*
+ `;
+ return row || null;
+}
+
+export async function expireUnfundedBid(bidId, reason) {
+ const [row] = await sql`
+ UPDATE agent_listing_bids
+ SET status = 'expired', decided_at = now(), updated_at = now(), refund_error = ${reason}
+ WHERE id = ${bidId} AND status = 'awaiting_funds'
+ RETURNING *
+ `;
+ return row || null;
+}
+
+/** Move one open bid to rejected or withdrawn with a pending refund. */
+export async function decideBid({ bidId, to, sellerId = null, bidderId = null }) {
+ const [row] = await sql`
+ UPDATE agent_listing_bids b
+ SET status = ${to}, refund_status = 'pending', decided_at = now(), updated_at = now()
+ FROM agent_listings l
+ WHERE b.id = ${bidId} AND l.id = b.listing_id AND b.status = 'open'
+ AND (${sellerId}::uuid IS NULL OR l.seller_user_id = ${sellerId})
+ AND (${bidderId}::uuid IS NULL OR b.bidder_user_id = ${bidderId})
+ RETURNING b.*
+ `;
+ return row || null;
+}
+
+/**
+ * Accept a bid: listing -> settling, bid -> accepted, every other open bid ->
+ * rejected with a pending refund, and the transfer row created. The listing is
+ * locked FIRST so two concurrent accepts serialize on it, and the bid update is
+ * conditional on the listing update having won.
+ */
+export async function acceptBidAtomically({ listingId, bidId, sellerId, feeBps }) {
+ const [row] = await sql`
+ WITH l AS (
+ UPDATE agent_listings
+ SET status = 'settling', sold_bid_id = ${bidId}, updated_at = now()
+ WHERE id = ${listingId} AND status = 'active' AND expires_at > now()
+ AND (${sellerId}::uuid IS NULL OR seller_user_id = ${sellerId})
+ AND EXISTS (SELECT 1 FROM agent_listing_bids WHERE id = ${bidId} AND listing_id = ${listingId} AND status = 'open')
+ RETURNING id, agent_id, seller_user_id
+ ), b AS (
+ UPDATE agent_listing_bids
+ SET status = 'accepted', decided_at = now(), updated_at = now()
+ WHERE id = ${bidId} AND listing_id = ${listingId} AND status = 'open' AND EXISTS (SELECT 1 FROM l)
+ RETURNING id, bidder_user_id, currency, amount_atomics
+ ), others AS (
+ UPDATE agent_listing_bids
+ SET status = 'rejected', refund_status = 'pending', decided_at = now(), updated_at = now()
+ WHERE listing_id = ${listingId} AND status = 'open' AND id <> ${bidId} AND EXISTS (SELECT 1 FROM b)
+ RETURNING id
+ ), t AS (
+ INSERT INTO agent_transfers (
+ listing_id, bid_id, agent_id, buyer_user_id, seller_user_id, currency,
+ amount_atomics, fee_atomics, seller_net_atomics
+ )
+ SELECT l.id, b.id, l.agent_id, b.bidder_user_id, l.seller_user_id, b.currency,
+ b.amount_atomics,
+ floor(b.amount_atomics * ${feeBps} / 10000),
+ b.amount_atomics - floor(b.amount_atomics * ${feeBps} / 10000)
+ FROM l, b
+ RETURNING id
+ )
+ SELECT (SELECT id FROM l) AS listing_id, (SELECT id FROM b) AS bid_id,
+ (SELECT id FROM t) AS transfer_id, (SELECT count(*)::int FROM others) AS rejected
+ `;
+ if (row?.transfer_id) return row;
+ // The listing moved but the bid did not (it was withdrawn in between):
+ // put the listing back so it can take another bid.
+ if (row?.listing_id) {
+ await sql`
+ UPDATE agent_listings SET status = 'active', sold_bid_id = NULL, updated_at = now()
+ WHERE id = ${listingId} AND status = 'settling' AND sold_bid_id = ${bidId}
+ AND NOT EXISTS (SELECT 1 FROM agent_transfers WHERE listing_id = ${listingId})
+ `;
+ }
+ return null;
+}
+
+// ── Transfers ────────────────────────────────────────────────────────────────
+
+export async function getTransfer(id) {
+ const [row] = await sql`SELECT * FROM agent_transfers WHERE id = ${id} LIMIT 1`;
+ return row || null;
+}
+
+export async function getTransferForListing(listingId) {
+ const [row] = await sql`SELECT * FROM agent_transfers WHERE listing_id = ${listingId} LIMIT 1`;
+ return row || null;
+}
+
+// ── History ──────────────────────────────────────────────────────────────────
+
+export async function addHistory(e) {
+ await sql`
+ INSERT INTO agent_marketplace_history
+ (agent_id, listing_id, bid_id, transfer_id, actor_user_id, event, currency, amount_atomics, signature, meta)
+ VALUES (
+ ${e.agentId}, ${e.listingId ?? null}, ${e.bidId ?? null}, ${e.transferId ?? null},
+ ${e.actorUserId ?? null}, ${e.event}, ${e.currency ?? null},
+ ${e.amount != null ? String(e.amount) : null}, ${e.signature ?? null},
+ ${JSON.stringify(e.meta || {})}::jsonb
+ )
+ `;
+}
+
+export async function listHistory({ agentId = null, listingId = null, limit = 50 } = {}) {
+ return sql`
+ SELECT h.*, ai.name AS agent_name
+ FROM agent_marketplace_history h
+ LEFT JOIN agent_identities ai ON ai.id = h.agent_id
+ WHERE (${agentId}::uuid IS NULL OR h.agent_id = ${agentId})
+ AND (${listingId}::uuid IS NULL OR h.listing_id = ${listingId})
+ ORDER BY h.created_at DESC, h.id DESC
+ LIMIT ${limit}
+ `;
+}
+
+// ── Views ────────────────────────────────────────────────────────────────────
+
+function money(atomics, currency) {
+ if (atomics == null) return null;
+ const info = currencyInfo(currency);
+ return { atomics: String(atomics), amount: formatAtomics(atomics, info.decimals), currency: info.currency, symbol: info.symbol };
+}
+
+function personaSummary(row) {
+ const text = String(row.agent_description || row.agent_persona || '').replace(/\s+/g, ' ').trim();
+ return text.length > 280 ? `${text.slice(0, 277)}...` : text;
+}
+
+export function listingView(row, { viewerId = null } = {}) {
+ const avatarPublic = !row.avatar_visibility || row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';
+ const snapshot = row.snapshot || {};
+ const expiresAt = row.expires_at instanceof Date ? row.expires_at : new Date(row.expires_at);
+ const live = row.status === 'active' && expiresAt.getTime() > Date.now();
+ return {
+ id: row.id,
+ status: live || row.status !== 'active' ? row.status : 'expired',
+ agent: {
+ id: row.agent_id,
+ name: row.agent_name,
+ persona_summary: personaSummary(row),
+ category: row.agent_category || null,
+ skills: row.agent_skills || [],
+ thumbnail_url: thumbnailUrl(row.avatar_thumbnail_key),
+ avatar_glb_url: row.avatar_storage_key && avatarPublic ? publicUrlOrNull(row.avatar_storage_key) : null,
+ wallet_address: row.agent_solana_address || null,
+ url: `/agents/${row.agent_id}`,
+ },
+ seller: { id: row.seller_user_id, name: row.seller_name || null, is_viewer: Boolean(viewerId && viewerId === row.seller_user_id) },
+ ask: money(row.ask_usdc_atomics, 'USDC'),
+ ask_three: money(row.ask_three_atomics, 'THREE'),
+ min_bid: money(row.min_bid_usdc_atomics, 'USDC'),
+ top_bid: money(row.top_bid_atomics, 'USDC'),
+ bid_count: row.bid_count || 0,
+ prior_sales: row.prior_sales || 0,
+ include_balance: row.include_balance,
+ include_history: row.include_history,
+ payout_address: viewerId && viewerId === row.seller_user_id ? row.payout_address : undefined,
+ escrow_address: row.escrow_address,
+ note: row.note || null,
+ snapshot,
+ expires_at: expiresAt.toISOString(),
+ created_at: new Date(row.created_at).toISOString(),
+ closed_at: row.closed_at ? new Date(row.closed_at).toISOString() : null,
+ url: `/marketplace/agents/listing/${row.id}`,
+ };
+}
+
+export function bidView(row, { viewerId = null } = {}) {
+ const mine = Boolean(viewerId && viewerId === row.bidder_user_id);
+ return {
+ id: row.id,
+ listing_id: row.listing_id,
+ agent_id: row.agent_id ?? undefined,
+ agent_name: row.agent_name ?? undefined,
+ listing_status: row.listing_status ?? undefined,
+ kind: row.kind,
+ status: row.status,
+ amount: money(row.amount_atomics, row.currency),
+ bidder: { id: row.bidder_user_id, name: row.bidder_name || null, is_viewer: mine },
+ funding_source: row.funding_source,
+ funding_address: row.funding_address,
+ escrow_signature: row.escrow_signature || null,
+ refund: row.refund_status
+ ? { status: row.refund_status, signature: row.refund_signature || null, error: mine ? row.refund_error || null : undefined }
+ : null,
+ fund_by: row.status === 'awaiting_funds' && row.fund_by ? new Date(row.fund_by).toISOString() : null,
+ created_at: new Date(row.created_at).toISOString(),
+ decided_at: row.decided_at ? new Date(row.decided_at).toISOString() : null,
+ };
+}
+
+export function historyView(row) {
+ return {
+ id: String(row.id),
+ agent_id: row.agent_id,
+ agent_name: row.agent_name || null,
+ listing_id: row.listing_id,
+ bid_id: row.bid_id,
+ transfer_id: row.transfer_id,
+ event: row.event,
+ amount: row.amount_atomics != null && row.currency ? money(row.amount_atomics, row.currency) : null,
+ signature: row.signature || null,
+ meta: row.meta || {},
+ at: new Date(row.created_at).toISOString(),
+ };
+}
+
+export { money };
diff --git a/api/_lib/agent-market/sweep.js b/api/_lib/agent-market/sweep.js
new file mode 100644
index 000000000..1dd81f026
--- /dev/null
+++ b/api/_lib/agent-market/sweep.js
@@ -0,0 +1,138 @@
+// The marketplace-escrow-sweep tick: everything in the whole-agent marketplace
+// that must happen whether or not anyone is watching.
+//
+// 1. Unfunded bids past their funding window: a connected-wallet transfer
+// that landed late is recorded (and refunded if the listing moved on); an
+// agent-wallet transfer that crashed mid-flight is reconciled from its
+// custody receipt; anything that never landed expires.
+// 2. Listings past their end time expire, and every open bid on them moves
+// to a refund.
+// 3. Pending and failed refunds are sent (each under its own lease).
+// 4. Transfers that stalled (a dead worker's lease expired, or a failed step)
+// are resumed through the state machine.
+// 5. Finished listings with empty escrow close their token accounts so the
+// rent returns to the marketplace payer.
+//
+// Every stage is bounded per tick and idempotent; the next tick finishes the rest.
+
+import { sql } from '../db.js';
+import { agentWalletFundingStatus, closeEscrow, verifyConnectedFunding } from './escrow.js';
+import { processRefund } from './service.js';
+import { runTransfer } from './settlement.js';
+import * as store from './store.js';
+
+const BATCH = 25;
+// A failed transfer is retried at most this often, so a persistent failure
+// (e.g. an EVM wallet waiting on gas) does not hammer the chain every tick.
+const FAILED_RETRY_MINUTES = 10;
+
+async function reconcileUnfunded(summary) {
+ const due = await sql`
+ SELECT * FROM agent_listing_bids
+ WHERE status = 'awaiting_funds' AND fund_by < now()
+ ORDER BY fund_by ASC LIMIT ${BATCH}
+ `;
+ for (const bid of due) {
+ try {
+ let signature = null;
+ if (bid.funding_source === 'connected_wallet') {
+ const listing = await store.getListing(bid.listing_id);
+ signature = await verifyConnectedFunding({ bid, listing });
+ } else {
+ const st = await agentWalletFundingStatus(bid);
+ if (st.state === 'pending') continue;
+ if (st.state === 'landed') signature = st.signature;
+ }
+ if (!signature) {
+ await store.expireUnfundedBid(bid.id, 'funding_window_elapsed');
+ summary.unfunded_expired++;
+ continue;
+ }
+ const funded = await store.markBidFunded(bid.id, signature);
+ if (funded?.status === 'expired') await processRefund(bid.id);
+ summary.late_funded++;
+ } catch (err) {
+ summary.errors.push({ stage: 'unfunded', bid: bid.id, message: err?.message });
+ }
+ }
+}
+
+async function expireListings(summary) {
+ const due = await sql`
+ SELECT id FROM agent_listings WHERE status = 'active' AND expires_at < now()
+ ORDER BY expires_at ASC LIMIT ${BATCH}
+ `;
+ for (const { id } of due) {
+ const closed = await store.closeListing({ listingId: id, to: 'expired', bidStatus: 'expired' });
+ if (!closed) continue;
+ await store.addHistory({ agentId: closed.agent_id, listingId: id, event: 'listing_expired', meta: { refunds: closed.refunds } });
+ summary.listings_expired++;
+ }
+}
+
+async function sendRefunds(summary) {
+ const due = await sql`
+ SELECT id FROM agent_listing_bids
+ WHERE refund_status IN ('pending', 'failed')
+ AND (refund_locked_until IS NULL OR refund_locked_until < now())
+ ORDER BY updated_at ASC LIMIT ${BATCH}
+ `;
+ for (const { id } of due) {
+ const r = await processRefund(id);
+ if (r.status === 'sent') summary.refunds_sent++;
+ else if (r.status === 'retrying') summary.errors.push({ stage: 'refund', bid: id, message: r.message });
+ }
+}
+
+async function resumeTransfers(summary) {
+ const due = await sql`
+ SELECT id FROM agent_transfers
+ WHERE status <> 'completed'
+ AND (locked_until IS NULL OR locked_until < now())
+ AND (status <> 'failed' OR updated_at < now() - make_interval(mins => ${FAILED_RETRY_MINUTES}))
+ ORDER BY updated_at ASC LIMIT 5
+ `;
+ for (const { id } of due) {
+ const run = await runTransfer(id, { deadlineMs: 50_000 });
+ if (run.transfer?.status === 'completed') summary.transfers_completed++;
+ else if (run.error) summary.errors.push({ stage: 'transfer', transfer: id, message: `${run.error.step}: ${run.error.message}` });
+ }
+}
+
+async function closeEscrows(summary) {
+ const due = await sql`
+ SELECT l.* FROM agent_listings l
+ WHERE l.status IN ('sold', 'delisted', 'expired') AND l.escrow_closed_at IS NULL
+ AND NOT EXISTS (
+ SELECT 1 FROM agent_listing_bids b
+ WHERE b.listing_id = l.id AND (b.status = 'awaiting_funds' OR b.refund_status IN ('pending', 'failed')))
+ AND NOT EXISTS (SELECT 1 FROM agent_transfers t WHERE t.listing_id = l.id AND t.status <> 'completed')
+ ORDER BY l.closed_at ASC NULLS FIRST LIMIT ${BATCH}
+ `;
+ for (const listing of due) {
+ try {
+ const r = await closeEscrow(listing);
+ if (r.closed) {
+ await sql`UPDATE agent_listings SET escrow_closed_at = now(), updated_at = now() WHERE id = ${listing.id}`;
+ summary.escrows_closed++;
+ } else if (r.reason === 'escrow_not_empty') {
+ summary.errors.push({ stage: 'close', listing: listing.id, message: `escrow still holds ${r.balance} ${r.currency}` });
+ }
+ } catch (err) {
+ summary.errors.push({ stage: 'close', listing: listing.id, message: err?.message });
+ }
+ }
+}
+
+export async function runMarketplaceSweep() {
+ const summary = {
+ unfunded_expired: 0, late_funded: 0, listings_expired: 0, refunds_sent: 0,
+ transfers_completed: 0, escrows_closed: 0, errors: [],
+ };
+ await reconcileUnfunded(summary);
+ await expireListings(summary);
+ await sendRefunds(summary);
+ await resumeTransfers(summary);
+ await closeEscrows(summary);
+ return summary;
+}
diff --git a/api/_lib/migrations/20260922140000_agent_marketplace.sql b/api/_lib/migrations/20260922140000_agent_marketplace.sql
new file mode 100644
index 000000000..4a7493429
--- /dev/null
+++ b/api/_lib/migrations/20260922140000_agent_marketplace.sql
@@ -0,0 +1,235 @@
+-- Whole-agent marketplace: listings, escrowed bids, settlement, custody rotation.
+-- Apply: npm run db:status, then npm run db:migrate. Idempotent.
+--
+-- The skills marketplace sells capabilities; this sells the agent itself:
+-- identity, persona, skills, history and the custodial wallet move to the buyer.
+--
+-- Money never moves on a database flag. A bid is only `open` once its USDC has
+-- landed in the listing's escrow account, a Solana keypair derived per listing
+-- from AGENT_MARKET_ESCROW_SECRET (api/_lib/agent-market/chain.js). The stored
+-- escrow_address is re-derived and compared before every escrow signature, so a
+-- changed secret fails closed instead of signing from the wrong account.
+--
+-- Bids live in agent_listing_bids: agent_bids already belongs to the labor
+-- market (bounty bids, 20260623180000_agent_labor_market.sql).
+--
+-- Lifecycles:
+-- listing active -> settling -> sold
+-- \-> delisted | expired
+-- bid awaiting_funds -> open -> accepted
+-- \-> expired \-> rejected | withdrawn | expired
+-- every non-accepted funded bid carries refund_status
+-- pending -> sent, driven by the marketplace-escrow-sweep cron.
+-- transfer one idempotent state machine (api/_lib/agent-market/settlement.js)
+-- whose `step` column is the resume point after any failure.
+
+begin;
+
+create table if not exists agent_listings (
+ id uuid primary key default gen_random_uuid(),
+ agent_id uuid not null references agent_identities(id),
+ seller_user_id uuid not null references users(id),
+ status text not null default 'active',
+ -- Buy-now price in USDC atomics (6dp). Null means auction only.
+ ask_usdc_atomics bigint,
+ -- Optional buy-now price in $THREE atomics.
+ ask_three_atomics numeric,
+ -- Floor for bids, USDC atomics.
+ min_bid_usdc_atomics bigint not null,
+ expires_at timestamptz not null,
+ -- true: the agent wallet's balance goes to the buyer with the agent.
+ -- false: the balance is swept to the seller's payout address first.
+ include_balance boolean not null default false,
+ -- true: memories, chat and activity history transfer. false: they are
+ -- detached from the agent before the buyer takes ownership.
+ include_history boolean not null default true,
+ -- Seller's Solana address for sale proceeds and (when excluded) the balance.
+ payout_address text not null,
+ escrow_address text not null,
+ note text,
+ -- What the listing advertised at creation: skills, persona summary, wallet
+ -- balance, so a buyer can compare it with what actually transferred.
+ snapshot jsonb not null default '{}'::jsonb,
+ sold_bid_id uuid,
+ -- Set once the escrow token accounts are closed and their rent returned.
+ escrow_closed_at timestamptz,
+ closed_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+do $$
+begin
+ if not exists (select 1 from pg_constraint where conname = 'agent_listings_status_chk') then
+ alter table agent_listings add constraint agent_listings_status_chk
+ check (status in ('active', 'settling', 'sold', 'delisted', 'expired'));
+ end if;
+ if not exists (select 1 from pg_constraint where conname = 'agent_listings_price_chk') then
+ alter table agent_listings add constraint agent_listings_price_chk
+ check (min_bid_usdc_atomics > 0
+ and (ask_usdc_atomics is null or ask_usdc_atomics >= min_bid_usdc_atomics)
+ and (ask_three_atomics is null or ask_three_atomics > 0));
+ end if;
+end $$;
+
+-- One live listing per agent: a second would let two buyers win the same agent.
+create unique index if not exists agent_listings_one_live
+ on agent_listings (agent_id)
+ where status in ('active', 'settling');
+create index if not exists agent_listings_browse
+ on agent_listings (status, created_at desc);
+create index if not exists agent_listings_seller
+ on agent_listings (seller_user_id, created_at desc);
+create index if not exists agent_listings_expiry
+ on agent_listings (expires_at)
+ where status = 'active';
+
+create table if not exists agent_listing_bids (
+ id uuid primary key default gen_random_uuid(),
+ listing_id uuid not null references agent_listings(id),
+ bidder_user_id uuid not null references users(id),
+ kind text not null default 'bid', -- bid | buy_now
+ currency text not null default 'USDC', -- USDC | THREE
+ amount_atomics numeric not null,
+ status text not null default 'awaiting_funds',
+ -- agent_wallet: escrowed by the platform from one of the bidder's agents.
+ -- connected_wallet: the bidder signed the escrow transfer in their wallet.
+ funding_source text not null,
+ funding_agent_id uuid references agent_identities(id),
+ -- Where the escrowed funds came from, and so where a refund goes.
+ funding_address text not null,
+ -- Solana Pay reference key riding the escrow transfer (connected wallet).
+ escrow_reference text,
+ escrow_signature text,
+ funded_at timestamptz,
+ -- Unfunded bids lapse; a signed-but-unsent wallet transaction expires with
+ -- its blockhash long before this.
+ fund_by timestamptz,
+ decided_at timestamptz,
+ refund_status text,
+ refund_signature text,
+ refund_error text,
+ refund_attempts integer not null default 0,
+ -- Exactly-once record of the refund transaction ({signature,
+ -- lastValidBlockHeight}), written before broadcast (chain.js sendLeg).
+ refund_leg jsonb,
+ -- Lease: an inline refund and the sweep cron never send the same refund.
+ refund_locked_until timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+do $$
+begin
+ if not exists (select 1 from pg_constraint where conname = 'agent_listing_bids_status_chk') then
+ alter table agent_listing_bids add constraint agent_listing_bids_status_chk
+ check (status in ('awaiting_funds', 'open', 'accepted', 'rejected', 'withdrawn', 'expired'));
+ end if;
+ if not exists (select 1 from pg_constraint where conname = 'agent_listing_bids_refund_chk') then
+ alter table agent_listing_bids add constraint agent_listing_bids_refund_chk
+ check (refund_status is null or refund_status in ('pending', 'sent', 'failed'));
+ end if;
+ if not exists (select 1 from pg_constraint where conname = 'agent_listing_bids_shape_chk') then
+ alter table agent_listing_bids add constraint agent_listing_bids_shape_chk
+ check (amount_atomics > 0
+ and kind in ('bid', 'buy_now')
+ and currency in ('USDC', 'THREE')
+ and funding_source in ('agent_wallet', 'connected_wallet'));
+ end if;
+end $$;
+
+-- An escrow transfer funds exactly one bid.
+create unique index if not exists agent_listing_bids_escrow_signature_key
+ on agent_listing_bids (escrow_signature) where escrow_signature is not null;
+create unique index if not exists agent_listing_bids_escrow_reference_key
+ on agent_listing_bids (escrow_reference) where escrow_reference is not null;
+create index if not exists agent_listing_bids_listing
+ on agent_listing_bids (listing_id, status, amount_atomics desc);
+create index if not exists agent_listing_bids_bidder
+ on agent_listing_bids (bidder_user_id, created_at desc);
+create index if not exists agent_listing_bids_refund_due
+ on agent_listing_bids (updated_at) where refund_status in ('pending', 'failed');
+
+create table if not exists agent_transfers (
+ id uuid primary key default gen_random_uuid(),
+ listing_id uuid not null unique references agent_listings(id),
+ bid_id uuid not null unique references agent_listing_bids(id),
+ agent_id uuid not null references agent_identities(id),
+ buyer_user_id uuid not null references users(id),
+ seller_user_id uuid not null references users(id),
+ currency text not null,
+ amount_atomics numeric not null,
+ fee_atomics numeric not null,
+ seller_net_atomics numeric not null,
+ -- The state machine's resume point (see settlement.js STEPS).
+ step text not null default 'pay_seller',
+ status text not null default 'in_progress', -- in_progress | completed | failed
+ payout_signature text,
+ fee_signature text,
+ old_wallet_address text,
+ new_wallet_address text,
+ -- The custody rotation record: every step, its time, and its signatures.
+ -- The pending new key sits here encrypted (secret-box) only between key
+ -- generation and the ownership swap, then is cleared.
+ rotation jsonb not null default '{}'::jsonb,
+ -- Exactly-once records of every on-chain leg, keyed by leg id.
+ legs jsonb not null default '{}'::jsonb,
+ attempts integer not null default 0,
+ last_error text,
+ -- Lease so two workers never drive the same transfer at once.
+ locked_until timestamptz,
+ completed_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists agent_transfers_open
+ on agent_transfers (updated_at) where status <> 'completed';
+create index if not exists agent_transfers_buyer
+ on agent_transfers (buyer_user_id, created_at desc);
+create index if not exists agent_transfers_seller
+ on agent_transfers (seller_user_id, created_at desc);
+
+create table if not exists agent_marketplace_history (
+ id bigserial primary key,
+ agent_id uuid not null,
+ listing_id uuid,
+ bid_id uuid,
+ transfer_id uuid,
+ actor_user_id uuid,
+ event text not null,
+ currency text,
+ amount_atomics numeric,
+ signature text,
+ meta jsonb not null default '{}'::jsonb,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists agent_marketplace_history_agent
+ on agent_marketplace_history (agent_id, created_at desc);
+create index if not exists agent_marketplace_history_listing
+ on agent_marketplace_history (listing_id, created_at desc);
+
+-- Preview records for the financial MCP tools: each commit must cite a preview
+-- the same user produced for the same action and arguments in the last ten
+-- minutes, so a model can never skip showing the user what it is about to do.
+create table if not exists agent_market_previews (
+ id text primary key,
+ user_id uuid not null,
+ action text not null,
+ params_hash text not null,
+ payload jsonb not null,
+ consumed_at timestamptz,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists agent_market_previews_user
+ on agent_market_previews (user_id, created_at desc);
+
+-- Revenue follows the owner who earned it. Earnings balances join revenue to
+-- the agent's CURRENT owner, so without this a sale would hand the seller's
+-- unwithdrawn earnings to the buyer. Settlement stamps every pre-sale row with
+-- the seller; rows written after the sale stay null and follow the new owner.
+alter table agent_revenue_events add column if not exists owner_user_id uuid;
+
+commit;
diff --git a/api/_mcpagent/marketplace-tools.js b/api/_mcpagent/marketplace-tools.js
new file mode 100644
index 000000000..c25cab8df
--- /dev/null
+++ b/api/_mcpagent/marketplace-tools.js
@@ -0,0 +1,496 @@
+// threews-agent MCP: the whole-agent marketplace tools.
+//
+// Buy, sell and bid on entire agents (identity, persona, skills, history and
+// the custodial wallet) with USDC held in per-listing escrow on Solana. Every
+// tool is a thin adapter over api/_lib/agent-market/service.js, the same layer
+// the REST API and the /marketplace/agents pages use.
+//
+// Tool policy (docs/prompts/03): each definition carries `group`, `tier`, and
+// for the financial ones `confirmFlag` and `previewTool`. A financial tool
+// refuses unless its confirm flag is exactly true AND it cites a preview_id
+// that preview_marketplace_action issued to the same user, for the same action
+// and arguments, within the last ten minutes. The preview is the confirmation
+// table the model must show the user before asking for a yes.
+
+import { hasScope } from '../_lib/auth.js';
+import { limits } from '../_lib/rate-limit.js';
+import * as svc from '../_lib/agent-market/service.js';
+
+const PREVIEW_TOOL = 'preview_marketplace_action';
+
+// The argument keys each action's preview and commit agree on. Both sides hash
+// exactly these, so a commit with different terms than the preview is refused.
+const ACTION_KEYS = {
+ create_listing: ['agent_id', 'ask_usdc', 'ask_three', 'min_bid_usdc', 'duration_hours', 'include_balance', 'include_history', 'payout_address', 'payout_evm_address', 'note'],
+ delist: ['listing_id'],
+ place_bid: ['listing_id', 'amount_usdc', 'funding_source', 'funding_agent_id', 'wallet_address'],
+ buy_now: ['listing_id', 'currency', 'funding_source', 'funding_agent_id', 'wallet_address'],
+ accept_bid: ['bid_id'],
+ withdraw_bid: ['bid_id'],
+};
+
+function pick(args, action) {
+ const out = {};
+ for (const k of ACTION_KEYS[action]) {
+ const v = args[k];
+ if (v === undefined || v === null || v === '') continue;
+ out[k] = typeof v === 'number' ? String(v) : v;
+ }
+ return out;
+}
+
+function refusal(text, reason, extra = {}) {
+ return { content: [{ type: 'text', text }], structuredContent: { ok: false, reason, ...extra }, isError: true };
+}
+
+function ok(text, data) {
+ return { content: [{ type: 'text', text }], structuredContent: { ok: true, ...data } };
+}
+
+async function enforce(limiter, auth) {
+ const rl = await limiter(auth.userId || auth.rateKey || 'anon');
+ if (!rl.success) {
+ throw Object.assign(new Error('rate_limited'), { code: -32000, data: { retry_after: Math.ceil((rl.reset - Date.now()) / 1000) } });
+ }
+}
+
+/**
+ * Run a service call with the shared sign-in, scope, rate and error handling.
+ * Designed service errors become designed tool results; anything else is left
+ * to the dispatcher's sanitizer.
+ */
+async function run(auth, { scope = null, signIn = true, pay = false }, fn) {
+ await enforce(pay ? limits.mcpAgentPay : limits.mcpAgent, auth);
+ if (signIn && !auth.userId) return refusal('Sign in to three.ws to use the agent marketplace.', 'auth_required', { signed_in: false });
+ if (scope && !hasScope(auth.scope, scope)) {
+ return refusal(`This action needs the ${scope} scope. Re-authorize with it granted.`, 'insufficient_scope', { required: scope });
+ }
+ try {
+ return await fn(auth.userId ? { id: auth.userId } : null);
+ } catch (err) {
+ if (err?.expose && err.code && (err.status ?? 500) < 500) {
+ return refusal(err.message, err.code, err.requirement ? { requirement: err.requirement } : {});
+ }
+ if (err?.expose && err.code) return refusal(err.message, err.code);
+ throw err;
+ }
+}
+
+/**
+ * The financial gate: exact confirm flag, then a fresh matching preview.
+ * Returns a refusal result, or null when the call may proceed.
+ */
+async function gate(user, args, action, confirmFlag) {
+ if (args[confirmFlag] !== true) {
+ return refusal(
+ `This moves real funds or commits your agent. Call ${PREVIEW_TOOL} with action "${action}" first, show the user the table it returns, and only after a clear yes call again with ${confirmFlag}: true and its preview_id.`,
+ 'confirmation_required',
+ { confirm_flag: confirmFlag, preview_tool: PREVIEW_TOOL },
+ );
+ }
+ await svc.consumePreview(user, action, pick(args, action), args.preview_id, PREVIEW_TOOL);
+ return null;
+}
+
+function listingLine(l) {
+ const price = l.ask ? `buy now ${l.ask.amount} USDC` : 'auction';
+ const top = l.top_bid ? `top bid ${l.top_bid.amount} USDC` : `min bid ${l.min_bid.amount} USDC`;
+ return `${l.agent.name}: ${price}, ${top}, ${l.bid_count} bid(s), ends ${l.expires_at}\n listing ${l.id} https://three.ws${l.url}`;
+}
+
+const ann = (readOnly, destructive, idempotent) => ({
+ readOnlyHint: readOnly, destructiveHint: destructive, idempotentHint: idempotent, openWorldHint: true,
+});
+
+const uuid = { type: 'string', format: 'uuid' };
+const amount = { type: ['string', 'number'], description: 'Decimal amount, e.g. "25" or "25.5".' };
+const confirmArg = (desc) => ({ type: 'boolean', description: desc });
+const previewArg = { type: 'string', description: `The preview_id ${PREVIEW_TOOL} returned for these exact arguments (valid ten minutes).` };
+const funding = {
+ funding_source: { type: 'string', enum: ['agent_wallet', 'connected_wallet'], description: 'Pay from one of your agents (settles here) or a browser wallet (returns a transaction to sign).' },
+ funding_agent_id: { ...uuid, description: 'Your agent whose USDC funds the bid (funding_source agent_wallet).' },
+ wallet_address: { type: 'string', description: 'Your Solana wallet address (funding_source connected_wallet).' },
+};
+
+export const marketplaceToolDefs = [
+ {
+ name: 'browse_marketplace',
+ title: 'Browse agents for sale',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'List whole agents currently for sale on three.ws: each with its persona summary, skills, reputation, buy-now price, top bid, bid count, whether its wallet balance is included, and time left. Read-only.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ q: { type: 'string', maxLength: 80, description: 'Match name, description or skill.' },
+ sort: { type: 'string', enum: ['ending', 'newest', 'price_asc', 'price_desc', 'most_bids'] },
+ limit: { type: 'integer', minimum: 1, maximum: 48 },
+ cursor: { type: 'string' },
+ },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { signIn: false }, async (user) => {
+ const r = await svc.browseListings({ ...args, viewerId: user?.id || null });
+ const text = r.items.length
+ ? r.items.map((l, i) => `${i + 1}. ${listingLine(l)}`).join('\n')
+ : 'No agents are listed for sale right now. List one with create_marketplace_listing.';
+ return ok(text, r);
+ });
+ },
+ },
+ {
+ name: 'browse_public_agents',
+ title: 'Browse public agents',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Search published three.ws agents, listed-for-sale ones first, with each one\'s sale state (price, minimum bid, listing link) when it has a live listing. Read-only.',
+ inputSchema: {
+ type: 'object',
+ properties: { q: { type: 'string', maxLength: 80 }, limit: { type: 'integer', minimum: 1, maximum: 48 }, cursor: { type: 'string' } },
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { signIn: false }, async () => {
+ const r = await svc.browsePublicAgents(args);
+ const text = r.items.length
+ ? r.items.map((a, i) => `${i + 1}. ${a.name} (${a.id})${a.for_sale ? ` FOR SALE: min bid ${a.for_sale.min_bid}${a.for_sale.ask ? `, buy now ${a.for_sale.ask}` : ''}` : ''}`).join('\n')
+ : 'No published agents matched.';
+ return ok(text, r);
+ });
+ },
+ },
+ {
+ name: 'get_listing',
+ title: 'Get an agent listing',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Full detail for one agent listing: what transfers, live wallet balance, reputation, trade history, every bid, the event history, and settlement progress if it sold. Read-only.',
+ inputSchema: { type: 'object', properties: { listing_id: uuid }, required: ['listing_id'], additionalProperties: false },
+ async handler(args, auth) {
+ return run(auth, { signIn: false }, async (user) => {
+ const d = await svc.getListingDetail(args.listing_id, user?.id || null);
+ const l = d.listing;
+ const lines = [
+ listingLine(l),
+ `Status: ${l.status}. Escrow: ${l.escrow_address}. Platform fee ${l.fee_bps / 100}%.`,
+ ...l.what_transfers.map((w) => ` ${w.transfers ? 'transfers' : 'stays'}: ${w.item}${w.note ? ` (${w.note})` : ''}`),
+ `Bids: ${d.bids.length ? d.bids.map((b) => `${b.amount.amount} ${b.amount.symbol} ${b.status}`).join(', ') : 'none'}`,
+ ];
+ if (d.transfer) lines.push(`Settlement: ${d.transfer.status} at step ${d.transfer.step}`);
+ return ok(lines.join('\n'), d);
+ });
+ },
+ },
+ {
+ name: 'get_marketplace_history',
+ title: 'Get marketplace history',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'The whole-agent marketplace event log (listed, bids, refunds, sales, settlement steps) for one agent or across the marketplace, newest first, with on-chain signatures. Read-only.',
+ inputSchema: { type: 'object', properties: { agent_id: uuid, limit: { type: 'integer', minimum: 1, maximum: 200 } }, additionalProperties: false },
+ async handler(args, auth) {
+ return run(auth, { signIn: false }, async () => {
+ const events = await svc.marketplaceHistory({ agentId: args.agent_id || null, limit: args.limit });
+ const text = events.length
+ ? events.map((e) => `${e.at} ${e.agent_name || e.agent_id}: ${e.event}${e.amount ? ` ${e.amount.amount} ${e.amount.symbol}` : ''}${e.signature ? ` (${e.signature})` : ''}`).join('\n')
+ : 'No marketplace history yet.';
+ return ok(text, { events });
+ });
+ },
+ },
+ {
+ name: PREVIEW_TOOL,
+ title: 'Preview a marketplace action',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Build the confirmation table for a money-moving marketplace action WITHOUT doing it: recipient, amount, token, chain, fees, what transfers and any warnings. Show the table to the user, wait for a clear yes, then call the action tool with its confirm flag and this preview_id (valid ten minutes, one use). Actions: create_listing, delist, place_bid, buy_now, accept_bid, withdraw_bid; pass the same arguments the action tool will get.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ action: { type: 'string', enum: Object.keys(ACTION_KEYS) },
+ agent_id: uuid, listing_id: uuid, bid_id: uuid,
+ ask_usdc: amount, ask_three: amount, min_bid_usdc: amount, amount_usdc: amount,
+ duration_hours: { type: 'number', minimum: 1, maximum: 720 },
+ include_balance: { type: 'boolean' }, include_history: { type: 'boolean' },
+ payout_address: { type: 'string' }, payout_evm_address: { type: 'string' }, note: { type: 'string', maxLength: 1000 },
+ currency: { type: 'string', enum: ['USDC', 'THREE'] },
+ ...funding,
+ },
+ required: ['action'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:read' }, async (user) => {
+ const p = await svc.previewAction(user, args.action, pick(args, args.action));
+ const text = [
+ `Preview (${p.action}), preview_id ${p.preview_id}, valid until ${p.expires_at}:`,
+ p.text,
+ ...(p.warnings || []).map((w) => `Warning: ${w}`),
+ 'Show this to the user and get a clear yes before committing.',
+ ].join('\n');
+ return ok(text, p);
+ });
+ },
+ },
+ {
+ name: 'create_marketplace_listing',
+ title: 'List an agent for sale',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_listing',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'List one of your agents for sale: a minimum bid in USDC, an optional buy-now price (USDC and optionally $THREE), a duration, and whether its wallet balance and history transfer. Commits the agent: a buy-now or an accepted bid sells it. Requires a preview_id from preview_marketplace_action (action create_listing) and confirm_listing: true.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ agent_id: uuid,
+ min_bid_usdc: amount,
+ ask_usdc: { ...amount, description: 'Optional buy-now price in USDC.' },
+ ask_three: { ...amount, description: 'Optional buy-now price in $THREE.' },
+ duration_hours: { type: 'number', minimum: 1, maximum: 720, description: 'Default 168 (7 days).' },
+ include_balance: { type: 'boolean', description: 'true: the wallet balance goes to the buyer. Default false: swept to you first.' },
+ include_history: { type: 'boolean', description: 'Default true. false deletes memories and activity before the handover.' },
+ payout_address: { type: 'string', description: 'Your Solana address for the proceeds. Defaults to your linked Solana wallet.' },
+ payout_evm_address: { type: 'string', description: 'Optional: where a custodial EVM wallet balance goes when the balance is not included.' },
+ note: { type: 'string', maxLength: 1000 },
+ preview_id: previewArg,
+ confirm_listing: confirmArg('Must be true, after the user approved the preview.'),
+ },
+ required: ['agent_id', 'min_bid_usdc'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'create_listing', 'confirm_listing');
+ if (blocked) return blocked;
+ const d = await svc.createListing(user, pick(args, 'create_listing'), { confirm: true });
+ return ok(`Listed ${d.listing.agent.name}. ${listingLine(d.listing)}`, d);
+ });
+ },
+ },
+ {
+ name: 'delist_marketplace_listing',
+ title: 'Delist an agent',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_delist',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'Take your listing down and refund every open bid from escrow. Requires a preview_id from preview_marketplace_action (action delist) and confirm_delist: true.',
+ inputSchema: {
+ type: 'object',
+ properties: { listing_id: uuid, preview_id: previewArg, confirm_delist: confirmArg('Must be true, after the user approved the preview.') },
+ required: ['listing_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'delist', 'confirm_delist');
+ if (blocked) return blocked;
+ const d = await svc.delistListing(user, args.listing_id, { confirm: true });
+ const refunds = d.bids.filter((b) => b.refund).map((b) => `${b.amount.amount} ${b.amount.symbol}: ${b.refund.status}${b.refund.signature ? ` (${b.refund.signature})` : ''}`);
+ return ok(`Delisted. ${refunds.length ? `Refunds: ${refunds.join('; ')}` : 'There were no open bids.'}`, d);
+ });
+ },
+ },
+ {
+ name: 'place_bid',
+ title: 'Bid on an agent',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_bid',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'Bid USDC on a listed agent. The bid is locked in the listing\'s escrow on Solana and refunded if it is rejected, withdrawn, or the listing ends without accepting it. From an agent wallet the escrow transfer happens now; from a connected wallet you get a transaction to sign. Requires a preview_id from preview_marketplace_action (action place_bid) and confirm_bid: true.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ listing_id: uuid, amount_usdc: amount, ...funding,
+ preview_id: previewArg, confirm_bid: confirmArg('Must be true, after the user approved the preview.'),
+ },
+ required: ['listing_id', 'amount_usdc', 'funding_source'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'wallet:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'place_bid', 'confirm_bid');
+ if (blocked) return blocked;
+ const r = await svc.placeBid(user, pick(args, 'place_bid'), { confirm: true, kind: 'bid' });
+ const text = r.funding?.status === 'awaiting_signature'
+ ? `Bid created. Sign the escrow transfer in your wallet within 10 minutes: open https://three.ws/marketplace/agents/listing/${r.bid.listing_id} (the transaction is also in structuredContent.funding.transaction).`
+ : `Bid of ${r.bid.amount.amount} USDC is escrowed (${r.funding?.signature}).`;
+ return ok(text, r);
+ });
+ },
+ },
+ {
+ name: 'buy_now',
+ title: 'Buy an agent now',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_payment',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'Pay a listing\'s buy-now price (USDC, or $THREE when the seller set one) into escrow; once it lands the sale settles and custody rotates to you: new wallet key, the seller\'s access revoked, ownership transferred. Requires a preview_id from preview_marketplace_action (action buy_now) and confirm_payment: true.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ listing_id: uuid, currency: { type: 'string', enum: ['USDC', 'THREE'] }, ...funding,
+ preview_id: previewArg, confirm_payment: confirmArg('Must be true, after the user approved the preview.'),
+ },
+ required: ['listing_id', 'funding_source'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'wallet:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'buy_now', 'confirm_payment');
+ if (blocked) return blocked;
+ const r = await svc.placeBid(user, pick(args, 'buy_now'), { confirm: true, kind: 'buy_now' });
+ const text = r.funding?.status === 'awaiting_signature'
+ ? `Purchase started. Sign the escrow transfer in your wallet: https://three.ws/marketplace/agents/listing/${r.bid.listing_id}`
+ : `Paid. Settlement is ${r.transfer?.status} at step ${r.transfer?.step}.${r.settlement_error ? ` It paused on ${r.settlement_error.step}: ${r.settlement_error.message}; it resumes automatically.` : ''}`;
+ return ok(text, r);
+ });
+ },
+ },
+ {
+ name: 'get_my_bids',
+ title: 'My bids',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Every bid you placed on agent listings, with status, escrow and refund signatures. Read-only.',
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+ async handler(_args, auth) {
+ return run(auth, { scope: 'agents:read' }, async (user) => {
+ const bids = await svc.myBids(user);
+ const text = bids.length
+ ? bids.map((b) => `${b.agent_name}: ${b.amount.amount} ${b.amount.symbol} ${b.status}${b.refund ? `, refund ${b.refund.status}` : ''} (bid ${b.id})`).join('\n')
+ : 'You have not bid on any agent yet. browse_marketplace shows what is for sale.';
+ return ok(text, { bids });
+ });
+ },
+ },
+ {
+ name: 'get_received_bids',
+ title: 'Bids on my listings',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Every bid on your agent listings, open ones first. Read-only.',
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
+ async handler(_args, auth) {
+ return run(auth, { scope: 'agents:read' }, async (user) => {
+ const bids = await svc.receivedBids(user);
+ const text = bids.length
+ ? bids.map((b) => `${b.agent_name}: ${b.amount.amount} ${b.amount.symbol} ${b.status} (bid ${b.id})`).join('\n')
+ : 'No bids on your listings yet.';
+ return ok(text, { bids });
+ });
+ },
+ },
+ {
+ name: 'accept_marketplace_bid',
+ title: 'Accept a bid',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_accept',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'Accept an open bid on your listing. Final: escrow pays you (minus the platform fee), every other bid is refunded, and custody rotates to the buyer. Requires a preview_id from preview_marketplace_action (action accept_bid) and confirm_accept: true.',
+ inputSchema: {
+ type: 'object',
+ properties: { bid_id: uuid, preview_id: previewArg, confirm_accept: confirmArg('Must be true, after the user approved the preview.') },
+ required: ['bid_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'accept_bid', 'confirm_accept');
+ if (blocked) return blocked;
+ const r = await svc.acceptBid(user, args.bid_id, { confirm: true });
+ const t = r.transfer;
+ const text = t.status === 'completed'
+ ? `Sold. You received ${t.seller_net.amount} ${t.seller_net.symbol} (${t.payout_signature}). The buyer now controls the agent through its new wallet ${t.new_wallet_address}.`
+ : `Accepted. Settlement is at step ${t.step}${r.settlement_error ? ` and paused: ${r.settlement_error.message}. It resumes automatically, or call resume_agent_transfer.` : '.'}`;
+ return ok(text, r);
+ });
+ },
+ },
+ {
+ name: 'reject_marketplace_bid',
+ title: 'Reject a bid',
+ group: 'marketplace',
+ tier: 'write',
+ annotations: ann(false, false, true),
+ description: 'Reject an open bid on your listing; its escrowed funds go back to the bidder. Your listing stays up.',
+ inputSchema: { type: 'object', properties: { bid_id: uuid }, required: ['bid_id'], additionalProperties: false },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:write' }, async (user) => {
+ const r = await svc.rejectBid(user, args.bid_id);
+ return ok(`Rejected. Refund ${r.refund.status}${r.refund.signature ? ` (${r.refund.signature})` : ''}.`, r);
+ });
+ },
+ },
+ {
+ name: 'withdraw_marketplace_bid',
+ title: 'Withdraw my bid',
+ group: 'marketplace',
+ tier: 'financial',
+ confirmFlag: 'confirm_withdraw',
+ previewTool: PREVIEW_TOOL,
+ annotations: ann(false, true, false),
+ description: 'Withdraw one of your open bids; escrow refunds it to where it came from. Requires a preview_id from preview_marketplace_action (action withdraw_bid) and confirm_withdraw: true.',
+ inputSchema: {
+ type: 'object',
+ properties: { bid_id: uuid, preview_id: previewArg, confirm_withdraw: confirmArg('Must be true, after the user approved the preview.') },
+ required: ['bid_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ return run(auth, { scope: 'wallet:write', pay: true }, async (user) => {
+ const blocked = await gate(user, args, 'withdraw_bid', 'confirm_withdraw');
+ if (blocked) return blocked;
+ const r = await svc.withdrawBid(user, args.bid_id, { confirm: true });
+ return ok(`Withdrawn. Refund ${r.refund.status}${r.refund.signature ? ` (${r.refund.signature})` : ''}.`, r);
+ });
+ },
+ },
+ {
+ name: 'get_agent_transfer',
+ title: 'Settlement progress',
+ group: 'marketplace',
+ tier: 'read',
+ annotations: ann(true, false, false),
+ description: 'Step-by-step progress of an agent sale you are party to: seller payout, fee, key rotation, sweep, revocation, ownership, with signatures and any error. Read-only.',
+ inputSchema: { type: 'object', properties: { transfer_id: uuid }, required: ['transfer_id'], additionalProperties: false },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:read' }, async (user) => {
+ const t = await svc.getTransferForViewer(args.transfer_id, user);
+ return ok(t.steps.map((s) => `${s.state.padEnd(7)} ${s.label}`).join('\n') + (t.last_error ? `\nError: ${t.last_error}` : ''), t);
+ });
+ },
+ },
+ {
+ name: 'resume_agent_transfer',
+ title: 'Resume a stalled sale',
+ group: 'marketplace',
+ tier: 'write',
+ annotations: ann(false, false, true),
+ description: 'Resume an agent sale whose settlement stopped on an error. Safe to repeat: every step is idempotent and no leg can pay twice. The sweep cron also retries on its own.',
+ inputSchema: { type: 'object', properties: { transfer_id: uuid }, required: ['transfer_id'], additionalProperties: false },
+ async handler(args, auth) {
+ return run(auth, { scope: 'agents:write' }, async (user) => {
+ const r = await svc.resumeTransfer(user, args.transfer_id);
+ return ok(`Settlement ${r.transfer.status} at step ${r.transfer.step}.${r.settlement_error ? ` Still blocked: ${r.settlement_error.message}` : ''}`, r);
+ });
+ },
+ },
+];
diff --git a/api/cron/marketplace-escrow-sweep.js b/api/cron/marketplace-escrow-sweep.js
new file mode 100644
index 000000000..ebaab6212
--- /dev/null
+++ b/api/cron/marketplace-escrow-sweep.js
@@ -0,0 +1,27 @@
+// GET/POST /api/cron/marketplace-escrow-sweep: the whole-agent marketplace's
+// background tick (Cloud Scheduler, every 2 minutes).
+//
+// Refunds rejected, withdrawn and expired bids from escrow, expires listings
+// past their end time, records connected-wallet escrow transfers that landed
+// after the bidder closed the tab, resumes any settlement a crashed worker left
+// mid-way, and closes empty escrow token accounts. Every stage is bounded and
+// idempotent (api/_lib/agent-market/sweep.js), so an overlapping tick is safe.
+//
+// Auth: the shared, fail-closed cron gate (api/_lib/cron-auth.js).
+
+import { cors, json, method, wrapCron } from '../_lib/http.js';
+import { requireCron } from '../_lib/cron-auth.js';
+import { runMarketplaceSweep } from '../_lib/agent-market/sweep.js';
+
+export const maxDuration = 300;
+
+export default wrapCron(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (!requireCron(req, res)) return;
+
+ const t0 = Date.now();
+ const summary = await runMarketplaceSweep();
+ if (summary.errors.length) console.warn('[marketplace-escrow-sweep] errors', JSON.stringify(summary.errors).slice(0, 2000));
+ return json(res, 200, { ok: true, ms: Date.now() - t0, ...summary });
+});
diff --git a/api/v1/marketplace/agents/[...route].js b/api/v1/marketplace/agents/[...route].js
new file mode 100644
index 000000000..c44aa0821
--- /dev/null
+++ b/api/v1/marketplace/agents/[...route].js
@@ -0,0 +1,150 @@
+// Whole-agent marketplace REST API: /api/v1/marketplace/agents/*
+//
+// GET /api/v1/marketplace/agents browse live listings (index.js)
+// GET /api/v1/marketplace/agents/public published agents, with sale state
+// GET /api/v1/marketplace/agents/history?agent_id= marketplace event history
+// GET /api/v1/marketplace/agents/by-agent/:agentId an agent's live listing (or null)
+// GET /api/v1/marketplace/agents/dashboard seller dashboard (auth)
+// GET /api/v1/marketplace/agents/bids/mine bids I placed (auth)
+// GET /api/v1/marketplace/agents/bids/received bids on my listings (auth)
+// POST /api/v1/marketplace/agents/preview confirmation table for any money action (auth)
+// POST /api/v1/marketplace/agents/listings create a listing (auth, confirm)
+// GET /api/v1/marketplace/agents/listings/:id listing detail, bids, history, transfer
+// POST /api/v1/marketplace/agents/listings/:id/delist delist and refund open bids (auth, confirm)
+// POST /api/v1/marketplace/agents/listings/:id/bids place a bid (auth, confirm)
+// POST /api/v1/marketplace/agents/listings/:id/buy buy now (auth, confirm)
+// POST /api/v1/marketplace/agents/bids/:id/confirm record a wallet-signed escrow transfer (auth)
+// POST /api/v1/marketplace/agents/bids/:id/transaction rebuild the escrow transaction (auth)
+// POST /api/v1/marketplace/agents/bids/:id/accept accept a bid (auth, confirm)
+// POST /api/v1/marketplace/agents/bids/:id/reject reject a bid (auth)
+// POST /api/v1/marketplace/agents/bids/:id/withdraw withdraw a bid (auth, confirm)
+// GET /api/v1/marketplace/agents/transfers/:id settlement progress (auth, buyer or seller)
+// POST /api/v1/marketplace/agents/transfers/:id/resume resume a failed settlement (auth)
+//
+// Auth: a browser session (state-changing calls need the X-CSRF-Token header),
+// a three.ws API key, or an OAuth token. Keys and tokens need agents:read for
+// the private reads, agents:write for listing and accepting, and wallet:write
+// for anything that moves the caller's own funds. Envelope: { data } on success,
+// { error, error_description } on failure, like every /api/v1 route.
+
+import { cors, error, json, readJson, wrap, rateLimited, setRateLimitHeaders } from '../../../_lib/http.js';
+import { authenticateBearer, extractBearer, getSessionUser, hasScope } from '../../../_lib/auth.js';
+import { requireCsrf } from '../../../_lib/csrf.js';
+import { limits, clientIp } from '../../../_lib/rate-limit.js';
+import * as svc from '../../../_lib/agent-market/service.js';
+
+async function principal(req) {
+ const session = await getSessionUser(req);
+ if (session) return { id: session.id, source: 'session', scope: 'all' };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { id: bearer.userId, source: bearer.source, scope: bearer.scope || '' };
+ return null;
+}
+
+function denied(res, status, code, message) {
+ error(res, status, code, message);
+ return null;
+}
+
+// Resolve and authorize the caller for a route. Returns the user or null after
+// answering the request.
+async function authorize(req, res, { scope, write }) {
+ const user = await principal(req);
+ if (!user) return denied(res, 401, 'unauthorized', 'sign in, or send a three.ws API key as `Authorization: Bearer sk_live_…`');
+ if (user.source !== 'session' && scope && !hasScope(user.scope, scope)) {
+ return denied(res, 403, 'insufficient_scope', `this endpoint requires the "${scope}" scope`);
+ }
+ if (write && user.source === 'session' && !(await requireCsrf(req, res, user.id))) return null;
+ return user;
+}
+
+function parts(req) {
+ const { pathname } = new URL(req.url, 'http://internal');
+ return pathname.replace(/^\/api\/v1\/marketplace\/agents\/?/, '').split('/').filter(Boolean);
+}
+
+function query(req) {
+ return Object.fromEntries(new URL(req.url, 'http://internal').searchParams);
+}
+
+// Route table: [method, pattern, auth, handler]. `:x` segments bind params.
+const ROUTES = [
+ ['GET', 'public', null, (ctx) => svc.browsePublicAgents(ctx.query)],
+ ['GET', 'history', null, (ctx) => svc.marketplaceHistory({ agentId: ctx.query.agent_id || null, limit: ctx.query.limit })],
+ ['GET', 'by-agent/:agentId', { optional: true }, (ctx) => svc.getLiveListingForAgent(ctx.params.agentId, ctx.user?.id)],
+ ['GET', 'dashboard', { scope: 'agents:read' }, (ctx) => svc.sellerDashboard(ctx.user)],
+ ['GET', 'bids/mine', { scope: 'agents:read' }, (ctx) => svc.myBids(ctx.user)],
+ ['GET', 'bids/received', { scope: 'agents:read' }, (ctx) => svc.receivedBids(ctx.user)],
+ ['POST', 'preview', { scope: 'agents:read', write: true }, (ctx) => {
+ const { action, ...params } = ctx.body || {};
+ return svc.previewAction(ctx.user, action, params);
+ }],
+ ['POST', 'listings', { scope: 'agents:write', write: true }, (ctx) => svc.createListing(ctx.user, ctx.body, { confirm: ctx.body.confirm === true })],
+ ['GET', 'listings/:id', { optional: true }, (ctx) => svc.getListingDetail(ctx.params.id, ctx.user?.id)],
+ ['POST', 'listings/:id/delist', { scope: 'agents:write', write: true }, (ctx) => svc.delistListing(ctx.user, ctx.params.id, { confirm: ctx.body.confirm === true })],
+ ['POST', 'listings/:id/bids', { scope: 'wallet:write', write: true }, (ctx) =>
+ svc.placeBid(ctx.user, { ...ctx.body, listing_id: ctx.params.id }, { confirm: ctx.body.confirm === true, kind: 'bid' })],
+ ['POST', 'listings/:id/buy', { scope: 'wallet:write', write: true }, (ctx) =>
+ svc.placeBid(ctx.user, { ...ctx.body, listing_id: ctx.params.id }, { confirm: ctx.body.confirm === true, kind: 'buy_now' })],
+ ['POST', 'bids/:id/confirm', { scope: 'wallet:write', write: true }, (ctx) => svc.confirmBidFunding(ctx.user, ctx.params.id, { signature: ctx.body.signature || null })],
+ ['POST', 'bids/:id/transaction', { scope: 'wallet:write', write: true }, (ctx) => svc.rebuildFundingTransaction(ctx.user, ctx.params.id)],
+ ['POST', 'bids/:id/accept', { scope: 'agents:write', write: true }, (ctx) => svc.acceptBid(ctx.user, ctx.params.id, { confirm: ctx.body.confirm === true })],
+ ['POST', 'bids/:id/reject', { scope: 'agents:write', write: true }, (ctx) => svc.rejectBid(ctx.user, ctx.params.id)],
+ ['POST', 'bids/:id/withdraw', { scope: 'wallet:write', write: true }, (ctx) => svc.withdrawBid(ctx.user, ctx.params.id, { confirm: ctx.body.confirm === true })],
+ ['GET', 'transfers/:id', { scope: 'agents:read' }, (ctx) => svc.getTransferForViewer(ctx.params.id, ctx.user)],
+ ['POST', 'transfers/:id/resume', { scope: 'agents:write', write: true }, (ctx) => svc.resumeTransfer(ctx.user, ctx.params.id)],
+];
+
+function match(segs) {
+ for (const [m, pattern, auth, handler] of ROUTES) {
+ const p = pattern.split('/');
+ if (p.length !== segs.length) continue;
+ const params = {};
+ let ok = true;
+ for (let i = 0; i < p.length; i++) {
+ if (p[i].startsWith(':')) params[p[i].slice(1)] = segs[i];
+ else if (p[i] !== segs[i]) { ok = false; break; }
+ }
+ if (ok) return { method: m, auth, handler, params };
+ }
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ const segs = parts(req);
+ const route = match(segs);
+ if (!route) return error(res, 404, 'not_found', 'no such marketplace route; see GET /api/v1');
+ if (route.method !== req.method) {
+ res.setHeader('allow', `${route.method}, OPTIONS`);
+ return error(res, 405, 'method_not_allowed', `use ${route.method}`);
+ }
+
+ const rl = await limits.apiV1(`ip:${clientIp(req)}`);
+ setRateLimitHeaders(res, rl);
+ if (!rl.success) return rateLimited(res, rl);
+
+ let user = null;
+ if (route.auth?.optional) {
+ user = await principal(req);
+ } else if (route.auth) {
+ user = await authorize(req, res, route.auth);
+ if (!user) return;
+ }
+
+ const body = req.method === 'POST' ? (await readJson(req).catch(() => ({}))) || {} : {};
+ try {
+ const data = await route.handler({ req, user, params: route.params, query: query(req), body });
+ res.setHeader('cache-control', req.method === 'GET' && !user ? 'public, max-age=15' : 'no-store');
+ return json(res, 200, { data: data ?? null });
+ } catch (err) {
+ if (err?.expose && err.code && err.status && err.status < 500) {
+ const extra = {};
+ if (err.requirement) extra.requirement = err.requirement;
+ if (err.bid_id) extra.bid_id = err.bid_id;
+ if (err.signature) extra.signature = err.signature;
+ return error(res, err.status, err.code, err.message, extra);
+ }
+ throw err;
+ }
+});
diff --git a/api/v1/marketplace/agents/index.js b/api/v1/marketplace/agents/index.js
new file mode 100644
index 000000000..3084d8d06
--- /dev/null
+++ b/api/v1/marketplace/agents/index.js
@@ -0,0 +1,24 @@
+// GET /api/v1/marketplace/agents: browse agents listed for sale.
+//
+// Query: q (name, description or skill), sort (ending | newest | price_asc |
+// price_desc | most_bids), limit (1-48), cursor (from next_cursor). Public; a
+// signed-in viewer additionally sees which listings are their own. Every other
+// marketplace route lives in [...route].js beside this file.
+
+import { defineEndpoint } from '../../../_lib/gateway.js';
+import { browseListings } from '../../../_lib/agent-market/service.js';
+
+export default defineEndpoint({
+ name: 'v1.marketplace.agents.browse',
+ method: 'GET',
+ auth: 'optional',
+ scope: 'agents:read',
+ handler: ({ query, principal }) =>
+ browseListings({
+ q: query.q || '',
+ sort: query.sort || 'ending',
+ limit: query.limit,
+ cursor: query.cursor,
+ viewerId: principal?.userId || null,
+ }),
+});