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.

marketplace: asset pricing + buy flow, dashboard + explore polish

nirholas13c1d354db2d
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index 764e4ed4a..e1bc34534 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -95,6 +95,20 @@ export default wrap(async (req, res) => {
const avatar = await getAvatar({ id, requesterId: auth?.userId });
if (!avatar) return error(res, 404, 'not_found', 'avatar not found');
const urlInfo = await resolveAvatarUrl(avatar);
+ const [priceRow] = await sql`
+ SELECT amount, currency_mint, chain, mint_decimals
+ FROM asset_prices
+ WHERE item_type = 'avatar' AND item_id = ${id} AND is_active = true
+ LIMIT 1
+ `;
+ const price = priceRow
+ ? {
+ amount: String(priceRow.amount),
+ currency_mint: priceRow.currency_mint,
+ chain: priceRow.chain,
+ mint_decimals: priceRow.mint_decimals ?? 6,
+ }
+ : null;
recordEvent({
userId: auth?.userId,
clientId: auth?.clientId,
@@ -102,7 +116,7 @@ export default wrap(async (req, res) => {
avatarId: id,
kind: 'avatar_fetch',
});
- return json(res, 200, { avatar: stripOwnerFor({ ...avatar, ...urlInfo }, auth?.userId) });
+ return json(res, 200, { avatar: stripOwnerFor({ ...avatar, ...urlInfo, price }, auth?.userId) });
}
if (!auth?.userId) return error(res, 401, 'unauthorized', 'authentication required');
diff --git a/api/explore.js b/api/explore.js
index c36f70e65..3355b1605 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -86,9 +86,15 @@ export default wrap(async (req, res) => {
coalesce(a.view_count, 0) AS view_count,
u.username AS owner_username,
u.display_name AS owner_display_name,
- u.wallet_address AS owner_wallet
+ u.wallet_address AS owner_wallet,
+ ap.amount AS price_amount,
+ ap.currency_mint AS price_currency_mint,
+ ap.chain AS price_chain,
+ ap.mint_decimals AS price_mint_decimals
FROM avatars a
LEFT JOIN users u ON u.id = a.owner_id AND u.deleted_at IS NULL
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'avatar' AND ap.item_id = a.id AND ap.is_active = true
WHERE a.deleted_at IS NULL
AND a.visibility = 'public'
AND (${q || null}::text IS NULL OR (
@@ -137,6 +143,14 @@ export default wrap(async (req, res) => {
: r.owner_wallet
? shortAddr(r.owner_wallet)
: null;
+ const price = r.price_amount != null
+ ? {
+ amount: String(r.price_amount),
+ currency_mint: r.price_currency_mint,
+ chain: r.price_chain,
+ mint_decimals: r.price_mint_decimals ?? 6,
+ }
+ : null;
return {
kind: 'avatar',
sortDate: r.created_at,
@@ -153,6 +167,7 @@ export default wrap(async (req, res) => {
viewCount: Number(r.view_count) || 0,
createdAt: r.created_at,
viewerUrl: `/app#model=${encodeURIComponent(glb)}`,
+ price,
author: handle
? {
handle,
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 79a90b715..533f22a4c 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -253,9 +253,15 @@ async function handleMine(req, res) {
const rows = await sql`
SELECT ai.id, ai.name, ai.description, ai.category, ai.tags, ai.avatar_id, ai.user_id,
ai.forks_count, ai.views_count, ai.published_at, ai.created_at, ai.skills,
- ai.is_published, av.thumbnail_key
+ ai.is_published, av.thumbnail_key,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
FROM agent_identities ai
LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'agent' AND ap.item_id = ai.id AND ap.is_active = true
WHERE ai.user_id = ${auth.userId} AND ai.deleted_at IS NULL
ORDER BY ai.created_at DESC
LIMIT 100
@@ -309,10 +315,16 @@ async function handleList(req, res, url) {
WHERE sp.agent_id = ai.id AND sp.status = 'confirmed'
AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h,
COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = ai.id), 0) AS rating_avg,
- COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = ai.id), 0) AS rating_count
+ COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = ai.id), 0) AS rating_count,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
FROM agent_identities ai
LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
LEFT JOIN users u ON u.id = ai.user_id
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'agent' AND ap.item_id = ai.id AND ap.is_active = true
WHERE ai.is_published = true
AND ai.deleted_at IS NULL
AND ai.name !~* ${AGENT_AUTONAMED_RE_SQL}
@@ -363,10 +375,16 @@ async function handleDetail(req, res, id) {
WHERE sp.agent_id = a.id AND sp.status = 'confirmed'
AND sp.confirmed_at > now() - interval '24 hours') AS buyers_24h,
COALESCE((SELECT AVG(rating)::numeric(3,2) FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_avg,
- COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_count
+ COALESCE((SELECT count(*)::int FROM agent_reviews r WHERE r.agent_id = a.id), 0) AS rating_count,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
FROM agent_identities a
LEFT JOIN users u ON u.id = a.user_id
LEFT JOIN avatars av ON av.id = a.avatar_id AND av.deleted_at IS NULL
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'agent' AND ap.item_id = a.id AND ap.is_active = true
WHERE a.id = ${id} AND a.deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
@@ -895,6 +913,14 @@ async function handleView(req, res, id) {
function toCard(row) {
const avatarPublic = !row.avatar_visibility || row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';
+ const price = row.asset_price_amount != null
+ ? {
+ amount: String(row.asset_price_amount),
+ currency_mint: row.asset_price_currency_mint,
+ chain: row.asset_price_chain,
+ mint_decimals: row.asset_price_mint_decimals ?? 6,
+ }
+ : null;
return {
id: row.id,
name: row.name,
@@ -915,6 +941,7 @@ function toCard(row) {
has_paid_skills: row.has_paid_skills || false,
rating_avg: Number(row.rating_avg || 0),
rating_count: row.rating_count || 0,
+ price,
};
}
diff --git a/api/marketplace/asset-price.js b/api/marketplace/asset-price.js
new file mode 100644
index 000000000..f2d39cbcb
--- /dev/null
+++ b/api/marketplace/asset-price.js
@@ -0,0 +1,153 @@
+/**
+ * /api/marketplace/asset-price
+ *
+ * Owner-driven price configuration for whole assets in the marketplace
+ * (avatars, agents, plugins). Skills have their own table — this one is for
+ * "buy the avatar / agent / plugin itself" listings.
+ *
+ * GET ?item_type=avatar&item_id=<uuid> → public read, returns active price or null
+ * POST { item_type, item_id, amount, currency_mint?, chain? }
+ * amount=0 deactivates the listing (back to free). Only the owner of the
+ * underlying entity may write.
+ *
+ * Currency defaults: USDC on Solana mainnet, 6 decimals.
+ */
+
+import { sql } from '../_lib/db.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { z } from 'zod';
+
+const DEFAULT_USDC_MAINNET = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+const ITEM_TYPES = ['avatar', 'agent', 'plugin'];
+
+const postBody = z.object({
+ item_type: z.enum(ITEM_TYPES),
+ item_id: z.string().uuid(),
+ amount: z.number().int().min(0).max(2_000_000_000_000), // 2M USDC ceiling, sanity bound
+ currency_mint: z.string().trim().min(1).max(100).default(DEFAULT_USDC_MAINNET),
+ chain: z.enum(['solana']).default('solana'), // start Solana-only; matches skill flow
+ mint_decimals: z.number().int().min(0).max(18).default(6),
+});
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+// Confirms the caller owns the asset they're trying to price.
+async function getOwnerUserId(itemType, itemId) {
+ if (itemType === 'avatar') {
+ const [row] = await sql`SELECT owner_id AS user_id FROM avatars WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row?.user_id ?? null;
+ }
+ if (itemType === 'agent') {
+ const [row] = await sql`SELECT user_id FROM agent_identities WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row?.user_id ?? null;
+ }
+ if (itemType === 'plugin') {
+ const [row] = await sql`SELECT author_id AS user_id FROM plugins WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row?.user_id ?? null;
+ }
+ return null;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+ if (req.method === 'GET') return handleGet(req, res);
+ return handleSet(req, res);
+});
+
+async function handleGet(req, res) {
+ const url = new URL(req.url, 'http://x');
+ const itemType = url.searchParams.get('item_type');
+ const itemId = url.searchParams.get('item_id');
+ if (!ITEM_TYPES.includes(itemType) || !itemId) {
+ return error(res, 400, 'validation_error', 'item_type and item_id required');
+ }
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [row] = await sql`
+ SELECT ap.amount, ap.currency_mint, ap.chain, ap.mint_decimals, ap.owner_user_id, ap.updated_at,
+ pw.address AS payout_address
+ FROM asset_prices ap
+ LEFT JOIN agent_payout_wallets pw
+ ON pw.user_id = ap.owner_user_id
+ AND pw.chain = ap.chain
+ AND pw.is_default = true
+ WHERE ap.item_type = ${itemType} AND ap.item_id = ${itemId} AND ap.is_active = true
+ ORDER BY pw.created_at ASC
+ LIMIT 1
+ `;
+ if (!row) return json(res, 200, { data: { price: null, sellable: false } });
+ return json(res, 200, {
+ data: {
+ price: {
+ amount: String(row.amount),
+ currency_mint: row.currency_mint,
+ chain: row.chain,
+ mint_decimals: row.mint_decimals,
+ updated_at: row.updated_at,
+ },
+ sellable: !!row.payout_address,
+ },
+ });
+}
+
+async function handleSet(req, res) {
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req).catch(() => null);
+ if (!body) return error(res, 400, 'validation_error', 'request body required');
+ const parsed = postBody.safeParse(body);
+ if (!parsed.success) {
+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');
+ }
+ const { item_type, item_id, amount, currency_mint, chain, mint_decimals } = parsed.data;
+
+ const ownerId = await getOwnerUserId(item_type, item_id);
+ if (!ownerId) return error(res, 404, 'not_found', 'asset not found');
+ if (ownerId !== auth.userId) return error(res, 403, 'forbidden', 'not your asset');
+
+ if (amount === 0) {
+ await sql`
+ UPDATE asset_prices
+ SET is_active = false, updated_at = now()
+ WHERE item_type = ${item_type} AND item_id = ${item_id} AND is_active = true
+ `;
+ return json(res, 200, { data: { ok: true, price: null } });
+ }
+
+ await sql`
+ INSERT INTO asset_prices (item_type, item_id, owner_user_id, amount, currency_mint, chain, mint_decimals, is_active)
+ VALUES (${item_type}, ${item_id}, ${auth.userId}, ${amount}, ${currency_mint}, ${chain}, ${mint_decimals}, true)
+ ON CONFLICT (item_type, item_id)
+ DO UPDATE SET
+ amount = EXCLUDED.amount,
+ currency_mint = EXCLUDED.currency_mint,
+ chain = EXCLUDED.chain,
+ mint_decimals = EXCLUDED.mint_decimals,
+ owner_user_id = EXCLUDED.owner_user_id,
+ is_active = true,
+ updated_at = now()
+ `;
+
+ return json(res, 200, {
+ data: {
+ ok: true,
+ price: { amount: String(amount), currency_mint, chain, mint_decimals },
+ },
+ });
+}
diff --git a/api/marketplace/buy-asset.js b/api/marketplace/buy-asset.js
new file mode 100644
index 000000000..fcb0bdc05
--- /dev/null
+++ b/api/marketplace/buy-asset.js
@@ -0,0 +1,369 @@
+/**
+ * Whole-asset purchase flow (Solana Pay) — avatars, agents, plugins.
+ * Sibling of /api/marketplace/purchase which sells individual skills.
+ *
+ * POST /api/marketplace/buy-asset
+ * Body: { item_type, item_id }
+ * Creates a pending asset_purchases row, returns Solana Pay params.
+ *
+ * GET /api/marketplace/buy-asset/:reference
+ * Returns { status, tx_signature, confirmed_at } for the caller.
+ *
+ * POST /api/marketplace/buy-asset/:reference/confirm
+ * Validates the on-chain tx, marks confirmed, emits receipt + notifications.
+ *
+ * Routed via vercel.json rewrites (see project root).
+ */
+
+import { Keypair, PublicKey } from '@solana/web3.js';
+import { findReference, validateTransfer } from '@solana/pay';
+import BigNumber from 'bignumber.js';
+import crypto from 'node:crypto';
+
+import { sql } from '../_lib/db.js';
+import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';
+import { clientIp, limits } from '../_lib/rate-limit.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';
+import { insertNotification } from '../_lib/notify.js';
+
+const REFERENCE_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const ITEM_TYPES = ['avatar', 'agent', 'plugin'];
+
+let _rpc;
+function rpc() {
+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });
+ return _rpc;
+}
+
+function receiptKey() {
+ return (
+ process.env.PURCHASE_RECEIPT_KEY ||
+ crypto.createHash('sha256').update((process.env.SESSION_SECRET || 'dev') + ':receipts').digest('hex')
+ );
+}
+
+export default wrap(async (req, res) => {
+ const url = new URL(req.url, 'http://x');
+ const parts = url.pathname.split('/').filter(Boolean);
+ const reference = url.searchParams.get('reference') || parts[3] || null;
+ const op = url.searchParams.get('op') || parts[4] || null;
+
+ if (!reference) {
+ if (req.method === 'POST') return handleCreate(req, res);
+ return error(res, 405, 'method_not_allowed', 'POST required');
+ }
+ if (!REFERENCE_RE.test(reference)) {
+ return error(res, 400, 'validation_error', 'invalid reference');
+ }
+ if (!op) return handleStatus(req, res, reference);
+ if (op === 'confirm') return handleConfirm(req, res, reference);
+ return error(res, 404, 'not_found', 'unknown action');
+});
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function getSellerForItem(itemType, itemId) {
+ if (itemType === 'avatar') {
+ const [row] = await sql`SELECT owner_id AS user_id, name FROM avatars WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row ? { userId: row.user_id, label: row.name || 'Avatar' } : null;
+ }
+ if (itemType === 'agent') {
+ const [row] = await sql`SELECT user_id, name FROM agent_identities WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row ? { userId: row.user_id, label: row.name || 'Agent' } : null;
+ }
+ if (itemType === 'plugin') {
+ const [row] = await sql`SELECT author_id AS user_id, name FROM plugins WHERE id = ${itemId} AND deleted_at IS NULL`;
+ return row ? { userId: row.user_id, label: row.name || 'Plugin' } : null;
+ }
+ return null;
+}
+
+async function resolveSellerPayout(sellerUserId, chain) {
+ const [row] = await sql`
+ SELECT address FROM agent_payout_wallets
+ WHERE user_id = ${sellerUserId} AND chain = ${chain} AND is_default = true
+ ORDER BY created_at ASC
+ LIMIT 1
+ `;
+ return row?.address ?? null;
+}
+
+// ── Create ─────────────────────────────────────────────────────────────────
+
+async function handleCreate(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const body = await readJson(req).catch(() => null);
+ const itemType = String(body?.item_type || '').trim();
+ const itemId = String(body?.item_id || '').trim();
+ if (!ITEM_TYPES.includes(itemType) || !itemId) {
+ return error(res, 400, 'validation_error', 'item_type and item_id required');
+ }
+
+ const [price] = await sql`
+ SELECT amount, currency_mint, chain, mint_decimals, owner_user_id
+ FROM asset_prices
+ WHERE item_type = ${itemType} AND item_id = ${itemId} AND is_active = true
+ `;
+ if (!price) return error(res, 404, 'not_found', 'this asset is not for sale');
+ if (price.owner_user_id === auth.userId) {
+ return error(res, 400, 'self_purchase', 'you already own this asset');
+ }
+
+ const seller = await getSellerForItem(itemType, itemId);
+ if (!seller) return error(res, 404, 'not_found', 'asset not found');
+
+ const payoutAddress = await resolveSellerPayout(seller.userId, price.chain);
+ if (!payoutAddress) {
+ return error(res, 412, 'creator_wallet_missing', 'seller has not configured a payout wallet');
+ }
+
+ // Already-owned: any confirmed asset purchase returns the existing row.
+ const [existing] = await sql`
+ SELECT reference, status, tx_signature, confirmed_at
+ FROM asset_purchases
+ WHERE buyer_user_id = ${auth.userId}
+ AND item_type = ${itemType} AND item_id = ${itemId}
+ AND status = 'confirmed'
+ ORDER BY confirmed_at DESC NULLS LAST
+ LIMIT 1
+ `;
+ if (existing) {
+ return json(res, 200, {
+ data: { already_owned: true, ...existing },
+ });
+ }
+
+ // Reuse a fresh pending row if one exists (idempotent retries).
+ const [pending] = await sql`
+ SELECT reference, amount, currency_mint, chain, expires_at
+ FROM asset_purchases
+ WHERE buyer_user_id = ${auth.userId}
+ AND item_type = ${itemType} AND item_id = ${itemId}
+ AND status = 'pending' AND expires_at > now()
+ ORDER BY created_at DESC
+ LIMIT 1
+ `;
+
+ const referrerUserId = await resolveReferrer(req, auth.userId);
+ const reference = pending?.reference ?? Keypair.generate().publicKey.toBase58();
+ const label = `${seller.label.slice(0, 40)}`;
+ const message = `Purchase ${itemType}: '${seller.label.slice(0, 50)}'`;
+
+ let row = pending;
+ if (!pending) {
+ const [inserted] = await sql`
+ INSERT INTO asset_purchases (
+ buyer_user_id, item_type, item_id, seller_user_id, status, reference,
+ amount, currency_mint, chain, payout_address, expires_at, referrer_user_id
+ ) VALUES (
+ ${auth.userId}, ${itemType}, ${itemId}, ${seller.userId}, 'pending', ${reference},
+ ${price.amount}, ${price.currency_mint}, ${price.chain}, ${payoutAddress},
+ now() + interval '30 minutes', ${referrerUserId}
+ )
+ RETURNING reference, amount, currency_mint, chain, expires_at
+ `;
+ row = inserted;
+ }
+
+ return json(res, 201, {
+ data: {
+ reference: row.reference,
+ recipient: payoutAddress,
+ amount: String(row.amount),
+ currency_mint: row.currency_mint,
+ chain: row.chain,
+ mint_decimals: price.mint_decimals,
+ expires_at: row.expires_at,
+ label,
+ message,
+ item_type: itemType,
+ item_id: itemId,
+ },
+ });
+}
+
+// ── Status ─────────────────────────────────────────────────────────────────
+
+async function handleStatus(req, res, reference) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+
+ const rl = await limits.widgetRead(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [row] = await sql`
+ SELECT reference, item_type, item_id, status, tx_signature, confirmed_at,
+ amount, currency_mint, chain
+ FROM asset_purchases
+ WHERE reference = ${reference} AND buyer_user_id = ${auth.userId}
+ `;
+ if (!row) return error(res, 404, 'not_found', 'purchase not found');
+ return json(res, 200, { data: row }, { 'cache-control': 'no-store' });
+}
+
+// ── Confirm ────────────────────────────────────────────────────────────────
+
+async function handleConfirm(req, res, reference) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const [pur] = await sql`
+ SELECT id, buyer_user_id, item_type, item_id, seller_user_id, status,
+ amount, currency_mint, chain, tx_signature, expires_at, reference,
+ payout_address, referrer_user_id
+ FROM asset_purchases
+ WHERE reference = ${reference} AND buyer_user_id = ${auth.userId}
+ `;
+ if (!pur) return error(res, 404, 'not_found', 'purchase not found');
+ if (pur.status === 'confirmed') {
+ return json(res, 200, { data: { status: 'confirmed', tx_signature: pur.tx_signature } });
+ }
+ if (pur.status === 'expired' || (pur.expires_at && new Date(pur.expires_at) < new Date())) {
+ await sql`UPDATE asset_purchases SET status = 'expired', updated_at = now() WHERE id = ${pur.id} AND status = 'pending'`;
+ return error(res, 410, 'purchase_expired', 'this pending purchase expired; please start a new one');
+ }
+ if (pur.chain !== 'solana') {
+ return error(res, 501, 'not_implemented', `chain '${pur.chain}' confirmation not yet supported`);
+ }
+
+ const refKey = new PublicKey(pur.reference);
+ const recipient = new PublicKey(pur.payout_address);
+ const splToken = new PublicKey(pur.currency_mint);
+ const decimals = 6;
+ const expectedAmount = new BigNumber(pur.amount).dividedBy(new BigNumber(10).pow(decimals));
+
+ let signatureInfo;
+ try {
+ signatureInfo = await rpc().withFallback((conn) =>
+ findReference(conn, refKey, { finality: 'confirmed' }),
+ );
+ } catch (e) {
+ if (/FindReferenceError|not found/i.test(e?.message || '')) {
+ return json(res, 200, { data: { status: 'pending' } });
+ }
+ throw e;
+ }
+ const txSignature = signatureInfo.signature;
+
+ try {
+ await rpc().withFallback((conn) =>
+ validateTransfer(
+ conn,
+ txSignature,
+ { recipient, amount: expectedAmount, splToken, reference: refKey },
+ { commitment: 'confirmed' },
+ ),
+ );
+ } catch (e) {
+ await sql`
+ UPDATE asset_purchases
+ SET status = 'tipped', tx_signature = ${txSignature}, confirmed_at = now(), updated_at = now()
+ WHERE id = ${pur.id} AND status = 'pending'
+ `;
+ await insertNotification(pur.seller_user_id, 'asset_payment_mismatch', {
+ item_type: pur.item_type,
+ item_id: pur.item_id,
+ expected_amount: String(pur.amount),
+ tx_signature: txSignature,
+ purchase_id: pur.id,
+ reason: e?.message,
+ });
+ return error(res, 409, 'transfer_mismatch', e?.message || 'on-chain transfer did not match expected', {
+ status: 'tipped',
+ tx_signature: txSignature,
+ });
+ }
+
+ const updated = await sql`
+ UPDATE asset_purchases
+ SET status = 'confirmed', tx_signature = ${txSignature}, confirmed_at = now(), updated_at = now()
+ WHERE id = ${pur.id} AND status = 'pending'
+ RETURNING id
+ `;
+
+ if (updated.length > 0) {
+ // Receipt: signed JSON payload, stored once.
+ const body = {
+ v: 1,
+ kind: 'asset_purchase',
+ purchase_id: pur.id,
+ reference: pur.reference,
+ buyer_user_id: pur.buyer_user_id,
+ seller_user_id: pur.seller_user_id,
+ item_type: pur.item_type,
+ item_id: pur.item_id,
+ amount: String(pur.amount),
+ currency_mint: pur.currency_mint,
+ chain: pur.chain,
+ recipient: pur.payout_address,
+ tx_signature: txSignature,
+ issued_at: new Date().toISOString(),
+ };
+ const canonical = JSON.stringify(body, Object.keys(body).sort());
+ const sig = crypto.createHmac('sha256', receiptKey()).update(canonical).digest('hex');
+ await sql`
+ INSERT INTO asset_purchase_receipts (purchase_id, receipt_json, signature)
+ VALUES (${pur.id}, ${JSON.stringify(body)}::jsonb, ${sig})
+ ON CONFLICT (purchase_id) DO NOTHING
+ `.catch(() => {/* table may not exist; non-fatal */});
+
+ await insertNotification(pur.seller_user_id, 'asset_purchased', {
+ item_type: pur.item_type,
+ item_id: pur.item_id,
+ amount: String(pur.amount),
+ currency_mint: pur.currency_mint,
+ tx_signature: txSignature,
+ purchase_id: pur.id,
+ });
+ await insertNotification(pur.buyer_user_id, 'asset_purchase_confirmed', {
+ item_type: pur.item_type,
+ item_id: pur.item_id,
+ amount: String(pur.amount),
+ currency_mint: pur.currency_mint,
+ tx_signature: txSignature,
+ purchase_id: pur.id,
+ });
+ }
+
+ return json(res, 200, { data: { status: 'confirmed', tx_signature: txSignature } });
+}
+
+// Resolve the inviting user from a ?ref=<code> query or users.referred_by_id.
+async function resolveReferrer(req, buyerUserId) {
+ const url = new URL(req.url, 'http://x');
+ const code = url.searchParams.get('ref');
+ if (code) {
+ const [u] = await sql`SELECT id FROM users WHERE referral_code = ${code} LIMIT 1`;
+ if (u && u.id !== buyerUserId) return u.id;
+ }
+ const [me] = await sql`SELECT referred_by_id FROM users WHERE id = ${buyerUserId}`;
+ if (me?.referred_by_id && me.referred_by_id !== buyerUserId) return me.referred_by_id;
+ return null;
+}
diff --git a/api/plugins/[action].js b/api/plugins/[action].js
index e7d3f6ae2..d62e2ade1 100644
--- a/api/plugins/[action].js
+++ b/api/plugins/[action].js
@@ -53,6 +53,14 @@ async function resolveAuth(req) {
// ── Row → API shape ───────────────────────────────────────────────────────────
function toPlugin(row) {
+ const price = row.asset_price_amount != null
+ ? {
+ amount: String(row.asset_price_amount),
+ currency_mint: row.asset_price_currency_mint,
+ chain: row.asset_price_chain,
+ mint_decimals: row.asset_price_mint_decimals ?? 6,
+ }
+ : null;
return {
id: row.id,
identifier: row.identifier,
@@ -68,6 +76,7 @@ function toPlugin(row) {
? { id: row.author_id, display_name: row.author_display_name }
: null,
created_at: row.created_at,
+ price,
};
}
@@ -139,9 +148,15 @@ async function handleList(req, res, url) {
const fetchLimit = limit + 1;
const rows = await sql`
- SELECT p.*, u.display_name AS author_display_name
+ SELECT p.*, u.display_name AS author_display_name,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
FROM plugins p
LEFT JOIN users u ON u.id = p.author_id
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'plugin' AND ap.item_id = p.id AND ap.is_active = true
WHERE p.is_public = true
AND p.deleted_at IS NULL
AND (${category}::text IS NULL OR p.category = ${category})
@@ -173,9 +188,15 @@ async function handleDetail(req, res, id) {
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
const [row] = await sql`
- SELECT p.*, u.display_name AS author_display_name
+ SELECT p.*, u.display_name AS author_display_name,
+ ap.amount AS asset_price_amount,
+ ap.currency_mint AS asset_price_currency_mint,
+ ap.chain AS asset_price_chain,
+ ap.mint_decimals AS asset_price_mint_decimals
FROM plugins p
LEFT JOIN users u ON u.id = p.author_id
+ LEFT JOIN asset_prices ap
+ ON ap.item_type = 'plugin' AND ap.item_id = p.id AND ap.is_active = true
WHERE p.id = ${id} AND p.deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'plugin not found');
diff --git a/api/users/earnings.js b/api/users/earnings.js
index 0087a5afe..46f5bdb89 100644
--- a/api/users/earnings.js
+++ b/api/users/earnings.js
@@ -31,6 +31,36 @@ export default wrap(async (req, res) => {
LIMIT 100
`;
+ // Asset sales (avatars / agents / plugins). asset_purchases stores amount
+ // in atomic USDC units (6 decimals on Solana mainnet) — divide to get
+ // price_usd for consistent reporting alongside the royalty ledger.
+ let assetRows = [];
+ try {
+ assetRows = await sql`
+ SELECT
+ ap.id,
+ ap.item_type,
+ ap.item_id,
+ ap.amount,
+ ap.currency_mint,
+ ap.confirmed_at,
+ ap.created_at,
+ ap.status,
+ CASE ap.item_type
+ WHEN 'avatar' THEN (SELECT name FROM avatars WHERE id = ap.item_id)
+ WHEN 'agent' THEN (SELECT name FROM agent_identities WHERE id = ap.item_id)
+ ELSE NULL
+ END AS item_name
+ FROM asset_purchases ap
+ WHERE ap.seller_user_id = ${userId}
+ AND ap.status = 'confirmed'
+ ORDER BY ap.confirmed_at DESC NULLS LAST
+ LIMIT 100
+ `;
+ } catch {
+ // asset_purchases migration hasn't run yet — leave list empty.
+ }
+
const pending_usd = rows
.filter((r) => r.status === 'pending')
.reduce((s, r) => s + Number(r.price_usd), 0);
@@ -39,13 +69,35 @@ export default wrap(async (req, res) => {
.filter((r) => r.status === 'settled')
.reduce((s, r) => s + Number(r.price_usd), 0);
+ const asset_settled_usd = assetRows.reduce(
+ (s, r) => s + Number(r.amount) / 1_000_000,
+ 0,
+ );
+
const entries = rows.map((r) => ({
skill_name: r.skill_name,
agent_name: r.agent_name,
price_usd: Number(r.price_usd),
status: r.status,
created_at: r.created_at,
+ kind: 'skill',
}));
+ for (const r of assetRows) {
+ entries.push({
+ skill_name: `${r.item_type[0].toUpperCase()}${r.item_type.slice(1)} sale`,
+ agent_name: r.item_name || '(deleted)',
+ price_usd: Number(r.amount) / 1_000_000,
+ status: 'settled',
+ created_at: r.confirmed_at || r.created_at,
+ kind: r.item_type,
+ });
+ }
+ // Newest first, regardless of source.
+ entries.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
- return json(res, 200, { pending_usd, settled_usd, entries });
+ return json(res, 200, {
+ pending_usd,
+ settled_usd: settled_usd + asset_settled_usd,
+ entries,
+ });
});
diff --git a/migrations/20260523140000_create_asset_prices_and_purchases.sql b/migrations/20260523140000_create_asset_prices_and_purchases.sql
new file mode 100644
index 000000000..188d74162
--- /dev/null
+++ b/migrations/20260523140000_create_asset_prices_and_purchases.sql
@@ -0,0 +1,87 @@
+-- Marketplace: paid avatars / agents / plugins (and any future asset kind).
+--
+-- Skills already have their own price + purchase tables (agent_skill_prices,
+-- skill_purchases) and a confirmed Solana Pay flow. This migration generalises
+-- the same pattern to *whole assets* — let any owner attach a price to an
+-- avatar, agent identity, or plugin and let buyers pay USDC for access.
+--
+-- Pre-existing rows in avatars / agent_identities / plugins are NOT mirrored
+-- here, which is exactly what we want: absent listing == free. New paid
+-- listings are explicit, owner-driven inserts.
+
+-- ── asset_prices ────────────────────────────────────────────────────────────
+-- One row per (item_type, item_id). Soft-deactivate via is_active=false
+-- rather than DELETE so we keep history for analytics / receipts.
+CREATE TABLE IF NOT EXISTS asset_prices (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ item_type text NOT NULL CHECK (item_type IN ('avatar', 'agent', 'plugin')),
+ item_id uuid NOT NULL,
+ owner_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ amount bigint NOT NULL CHECK (amount >= 0), -- in smallest unit (e.g. USDC = 6 decimals)
+ currency_mint text NOT NULL, -- SPL mint address or 'native' for ETH/SOL
+ chain text NOT NULL DEFAULT 'solana',
+ mint_decimals int NOT NULL DEFAULT 6,
+ is_active boolean NOT NULL DEFAULT true,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+-- One row per (item_type, item_id). Deactivation flips is_active rather than
+-- deleting, so the same row gets re-used when a seller re-lists.
+CREATE UNIQUE INDEX IF NOT EXISTS asset_prices_item_unique
+ ON asset_prices(item_type, item_id);
+
+CREATE INDEX IF NOT EXISTS asset_prices_owner
+ ON asset_prices(owner_user_id) WHERE is_active = true;
+
+CREATE INDEX IF NOT EXISTS asset_prices_kind_active
+ ON asset_prices(item_type, is_active);
+
+-- ── asset_purchases ─────────────────────────────────────────────────────────
+-- One row per (buyer, item) purchase attempt. Lives separately from
+-- skill_purchases so the skill flow stays untouched.
+CREATE TABLE IF NOT EXISTS asset_purchases (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ buyer_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ item_type text NOT NULL CHECK (item_type IN ('avatar', 'agent', 'plugin')),
+ item_id uuid NOT NULL,
+ seller_user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ status text NOT NULL DEFAULT 'pending'
+ CHECK (status IN ('pending', 'confirmed', 'expired', 'tipped', 'refunded')),
+ reference text NOT NULL UNIQUE,
+ amount bigint NOT NULL CHECK (amount >= 0),
+ currency_mint text NOT NULL,
+ chain text NOT NULL DEFAULT 'solana',
+ tx_signature text UNIQUE,
+ payout_address text NOT NULL,
+ expires_at timestamptz NOT NULL,
+ confirmed_at timestamptz,
+ referrer_user_id uuid REFERENCES users(id) ON DELETE SET NULL,
+ metadata jsonb NOT NULL DEFAULT '{}'::jsonb,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+
+CREATE INDEX IF NOT EXISTS asset_purchases_buyer
+ ON asset_purchases(buyer_user_id, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS asset_purchases_seller
+ ON asset_purchases(seller_user_id, status, created_at DESC);
+
+CREATE INDEX IF NOT EXISTS asset_purchases_item
+ ON asset_purchases(item_type, item_id, status);
+
+CREATE INDEX IF NOT EXISTS asset_purchases_pending_expiry
+ ON asset_purchases(expires_at) WHERE status = 'pending';
+
+-- ── asset_purchase_receipts ─────────────────────────────────────────────────
+-- HMAC-signed receipt per confirmed purchase, mirroring purchase_receipts for
+-- skill sales. Stored once at confirm time so buyers can verify the trade
+-- happened without re-querying the chain.
+CREATE TABLE IF NOT EXISTS asset_purchase_receipts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ purchase_id uuid NOT NULL UNIQUE REFERENCES asset_purchases(id) ON DELETE CASCADE,
+ receipt_json jsonb NOT NULL,
+ signature text NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
diff --git a/pages/marketplace.html b/pages/marketplace.html
index b0241a11b..a8b709240 100644
--- a/pages/marketplace.html
+++ b/pages/marketplace.html
@@ -646,6 +646,42 @@
color: #fafafa;
}
+ /* ── Asset price pill (Free / N USDC) ────────────────────────── */
+ .market-price-pill {
+ position: absolute;
+ top: 8px;
+ right: 8px;
+ z-index: 2;
+ display: inline-flex;
+ align-items: center;
+ padding: 3px 9px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.03em;
+ font-family: 'Space Grotesk', sans-serif;
+ backdrop-filter: blur(6px);
+ border: 1px solid transparent;
+ line-height: 1.4;
+ pointer-events: none;
+ white-space: nowrap;
+ }
+ .market-price-pill.free {
+ background: rgba(52, 211, 153, 0.16);
+ color: #34d399;
+ border-color: rgba(52, 211, 153, 0.28);
+ }
+ .market-price-pill.paid {
+ background: rgba(253, 224, 71, 0.18);
+ color: #fde047;
+ border-color: rgba(253, 224, 71, 0.32);
+ }
+ /* Agent cards aren't position:relative by default — make them so the
+ pill anchors to the card edge instead of the page. */
+ .market-card-agent {
+ position: relative;
+ }
+
/* Featured-curated badge over the avatar thumbnail (gold star, top-left) */
.market-card-avatar.featured {
border-color: rgba(253, 224, 71, 0.25);
@@ -860,6 +896,119 @@
margin-top: auto;
padding-top: 16px;
}
+
+ /* Sell-or-buy panel inside the avatar / agent detail modal. Owners
+ see a price + payout-wallet editor; non-owners see Pay-with-USDC. */
+ .avatar-modal-sale {
+ margin-top: 6px;
+ padding: 14px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid #1f1f1f;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ font-size: 13px;
+ }
+ .avatar-modal-sale .sale-eyebrow {
+ font-family: 'Space Grotesk', sans-serif;
+ font-size: 10px;
+ letter-spacing: 0.18em;
+ text-transform: uppercase;
+ color: #a1a1aa;
+ font-weight: 600;
+ }
+ .avatar-modal-sale .sale-price {
+ font-size: 22px;
+ font-weight: 700;
+ color: #fde047;
+ font-family: 'Space Grotesk', sans-serif;
+ }
+ .avatar-modal-sale .sale-price.free {
+ color: #34d399;
+ }
+ .avatar-modal-sale label {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ font-size: 11px;
+ color: #a1a1aa;
+ }
+ .avatar-modal-sale input[type="number"],
+ .avatar-modal-sale input[type="text"] {
+ background: #0a0a0a;
+ border: 1px solid #2a2a2a;
+ border-radius: 8px;
+ color: #fafafa;
+ padding: 8px 10px;
+ font-size: 13px;
+ font-family: inherit;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ .avatar-modal-sale input[type="number"]:focus,
+ .avatar-modal-sale input[type="text"]:focus {
+ border-color: #7dd3fc;
+ }
+ .avatar-modal-sale .sale-row {
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ }
+ .avatar-modal-sale .sale-row label { flex: 1; }
+ .avatar-modal-sale .sale-row .sale-currency {
+ background: #1a1a1a;
+ border: 1px solid #2a2a2a;
+ color: #d4d4d8;
+ padding: 8px 10px;
+ border-radius: 8px;
+ font-family: 'Space Grotesk', sans-serif;
+ font-weight: 600;
+ font-size: 12px;
+ }
+ .avatar-modal-sale button.sale-save,
+ .avatar-modal-sale button.sale-buy,
+ .avatar-modal-sale button.sale-clear {
+ border: 0;
+ padding: 10px 14px;
+ border-radius: 10px;
+ font-weight: 600;
+ font-size: 13px;
+ cursor: pointer;
+ font-family: inherit;
+ transition: transform 0.15s;
+ }
+ .avatar-modal-sale button.sale-save {
+ background: #fafafa;
+ color: #0a0a0a;
+ }
+ .avatar-modal-sale button.sale-buy {
+ background: linear-gradient(180deg, #fde047, #facc15);
+ color: #18181b;
+ }
+ .avatar-modal-sale button.sale-buy:hover,
+ .avatar-modal-sale button.sale-save:hover {
+ transform: translateY(-1px);
+ }
+ .avatar-modal-sale button.sale-clear {
+ background: transparent;
+ color: #a1a1aa;
+ border: 1px solid #2a2a2a;
+ }
+ .avatar-modal-sale .sale-status {
+ font-size: 11px;
+ color: #a1a1aa;
+ min-height: 14px;
+ }
+ .avatar-modal-sale .sale-status.ok { color: #34d399; }
+ .avatar-modal-sale .sale-status.err { color: #f43f5e; }
+ .avatar-modal-sale .sale-hint {
+ font-size: 11px;
+ color: #71717a;
+ line-height: 1.5;
+ }
+ .avatar-modal-sale .sale-hint a { color: #7dd3fc; text-decoration: none; }
+ .avatar-modal-sale .sale-hint a:hover { text-decoration: underline; }
.avatar-modal-actions button,
.avatar-modal-actions a {
width: 100%;
@@ -1432,6 +1581,11 @@
<button class="market-chip" data-filter="avatars" role="tab" aria-selected="false">Avatars</button>
<button class="market-chip" data-filter="onchain" role="tab" aria-selected="false" title="ERC-8004 agents indexed onchain across Base, Polygon, and Solana" aria-label="Onchain — ERC-8004 agents indexed across all supported chains">Onchain <span class="chip-count" id="chip-count-onchain"></span></button>
</div>
+ <div class="market-filter-chips" id="market-price-filter-chips" role="group" aria-label="Filter by price">
+ <button class="market-chip active" data-price-filter="all">Any</button>
+ <button class="market-chip" data-price-filter="free" title="Show only free listings">Free</button>
+ <button class="market-chip" data-price-filter="paid" title="Show only paid listings">Paid</button>
+ </div>
<label class="market-visually-hidden" for="market-sort">Sort marketplace results</label>
<select id="market-sort" class="market-sort" aria-label="Sort marketplace results">
<option value="recommended">Recommended</option>
@@ -1481,6 +1635,9 @@
<button class="market-bookmark" id="d-bookmark" aria-label="Bookmark">☆</button>
</div>
+ <!-- Sell / Buy panel for the agent itself (separate from per-skill prices). -->
+ <div class="avatar-modal-sale" id="agent-sale-panel" hidden></div>
+
<nav class="market-tabs" role="tablist">
<button data-tab="overview" class="active" role="tab">Overview</button>
<button data-tab="profile" role="tab">Agent Profile</button>
@@ -1990,6 +2147,7 @@
<h2 class="avatar-modal-title" id="avatar-modal-title">—</h2>
<p class="avatar-modal-desc" id="avatar-modal-desc"></p>
<div class="avatar-modal-meta" id="avatar-modal-meta"></div>
+ <div class="avatar-modal-sale" id="avatar-modal-sale" hidden></div>
<div class="avatar-modal-actions">
<button class="btn-primary" id="avatar-modal-use">Start an agent with this avatar</button>
<a class="btn-secondary" id="avatar-modal-view" href="#" target="_blank" rel="noopener">Open in 3D viewer</a>
diff --git a/public/dashboard/index.html b/public/dashboard/index.html
index 9e059f3d4..fd6a9bbb3 100644
--- a/public/dashboard/index.html
+++ b/public/dashboard/index.html
@@ -1257,6 +1257,7 @@
<a href="/dashboard/subscriptions" data-tab="subscriptions">Subscriptions</a>
<a href="/dashboard/billing" data-tab="billing">Plan &amp; usage</a>
<a href="/dashboard/revenue" data-tab="revenue">Revenue</a>
+ <a href="/dashboard/withdrawals" data-tab="withdrawals">Withdrawals</a>
<a href="/dashboard/earnings" data-tab="earnings">Earnings</a>
<a href="/dashboard/account" data-tab="account">Account</a>
<a href="/dashboard/wallets">Wallets</a>
diff --git a/public/demos/3d-home.html b/public/demos/3d-home.html
index eb911962c..67e0544ed 100644
--- a/public/demos/3d-home.html
+++ b/public/demos/3d-home.html
@@ -131,6 +131,20 @@
.brand-dot { width:8px; height:8px; border-radius:50%; background:linear-gradient(135deg,#3dc1ff,#aacc00); box-shadow:0 0 10px rgba(61, 193, 255,0.6); }
.nav a.link { color:#555870; text-decoration:none; font-size:13px; margin-left:auto; }
.nav a.link:hover { color:#3dc1ff; }
+
+ /* Mobile: tighter padding, top-aligned so chips stay onscreen, smaller buttons */
+ @media (max-width: 640px) {
+ .page {
+ padding: 84px 22px 40px;
+ justify-content: flex-start;
+ max-width: 100%;
+ }
+ .hero-sub { margin-bottom: 28px; }
+ .btn { padding: 14px 22px; font-size: 14px; }
+ .cta-row { gap: 10px; }
+ .anim-controls { margin-top: 22px; }
+ .chip { padding: 8px 12px; font-size: 11.5px; }
+ }
</style>
</head>
<body>
@@ -148,7 +162,7 @@
<span class="eyebrow-dot"></span>
<span>The 3D layer for onchain AI agents</span>
</div>
- <h1 class="hero-title"><span id="sit-line">Give your AI</span><br />a <em>body.</em></h1>
+ <h1 class="hero-title"><span id="sit-line">Give</span> your AI<br />a <em>body.</em></h1>
<p class="hero-sub">
Born in 3D. Raised on-chain. Yours forever.
Your AI has been a chatbox long enough — give it a body,
@@ -159,9 +173,9 @@
<span>Build your agent — free</span>
<span>→</span>
</a>
- <a href="#" class="btn btn-ghost">
+ <a href="/app" class="btn btn-ghost" target="_blank" rel="noopener">
<span>Watch it live</span>
- <span style="opacity:.4">↓</span>
+ <span style="opacity:.4">↗</span>
</a>
</div>
<div class="anim-controls" id="anim-controls" role="group" aria-label="Avatar animations">
@@ -214,12 +228,18 @@
// ── OrthographicCamera: 1 world unit = PX_PER_UNIT pixels ────────
// This makes screen→world mapping trivially exact: no perspective math.
- const PX_PER_UNIT = 120; // avatar (1.8u tall) = 216px on screen
+ // Avatar (1.8u tall) = 216px on desktop, scales down on narrow viewports
+ // so the figure doesn't dominate a phone screen.
+ let PX_PER_UNIT = 120;
+ function computePxPerUnit() {
+ return window.innerWidth < 640 ? 92 : 120;
+ }
const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
camera.position.z = 10;
function updateFrustum() {
+ PX_PER_UNIT = computePxPerUnit();
const hw = window.innerWidth / PX_PER_UNIT / 2;
const hh = window.innerHeight / PX_PER_UNIT / 2;
camera.left = -hw; camera.right = hw;
@@ -314,7 +334,12 @@
let seqT = 0, landed = false, jumpTarget = { x: 0, y: 0 };
const STAND_S = 2.566; // standup clip duration
- const JUMP_S = 2.667; // jumpdown clip duration
+ // Jumpdown clip runs at 1.7x via fallAction.timeScale so the drop
+ // feels decisive rather than floaty; JUMP_S mirrors the played-back
+ // duration (2.667 / 1.7) so the position math finishes with the clip.
+ const JUMP_CLIP_S = 2.667;
+ const JUMP_RATE = 1.7;
+ const JUMP_S = JUMP_CLIP_S / JUMP_RATE;
const SIT_DWELL_S = 2.4; // how long he sits before standing
// Earliest-possible fraction at which the impact effects MAY fire.
// The actual trigger is gated on screen-space proximity below — this
@@ -323,26 +348,36 @@
// Feet must be within this many SCREEN px of the button top before the
// squish/splash fire. The parabolic arc only returns to 0 at p≈1.0, so
// gating on real px (not the fraction p) keeps the impact synced.
- const LAND_PX = 10;
- const PEAK_U = 0.55; // arc peak in world units
- const JUMP_YAW = 0.22; // ~12° peak yaw mid-flight (face-forward at both ends)
+ const LAND_PX = 14;
+ // Straight drop: no arc, no yaw. Reads as a deliberate fall rather
+ // than a hesitating leap. She lands on whatever sits directly below
+ // her perch (the CTA button extends past "Give" to the right, so a
+ // vertical drop lands her on the button's left portion).
+ const PEAK_U = 0;
+ const JUMP_YAW = 0;
// cz.glb origin is at the feet (verified in /demos/button-jump.html).
// FEET_OFFSET stays 0 so the visible feet land on the button top.
// SIT_OFFSET pushes the origin DOWN by the seated feet→butt distance,
// so the butt — not the feet — rests on the text line. Tuned to the
- // sitidle pose where legs dangle below the hips.
+ // sitidle pose where legs dangle below the hips; scales with the
+ // avatar's on-screen size so a mobile-sized figure perches correctly.
+ // Lowered from 120 so her butt clears the line-box top and visibly
+ // perches ON TOP of "Give" rather than sinking onto the baseline.
const FEET_OFFSET_PX = 0;
- const SIT_OFFSET_PX = 120;
+ const SIT_OFFSET_PX_BASE = 90;
+ function sitOffsetPx() {
+ return SIT_OFFSET_PX_BASE * (PX_PER_UNIT / 120);
+ }
function smoothstep(t) { return t * t * (3 - 2 * t); }
- // Sit anchor: perched on the right edge of "Give your AI".
+ // Sit anchor: perched centered on top of "Give".
// SIT_OFFSET_PX shifts the GLB origin DOWN in screen px so the visible
// butt rests on the text rather than the origin landing on the text.
function getSitWorld() {
const rect = sitLine.getBoundingClientRect();
- const sx = rect.right - rect.height * 0.4;
- const sy = rect.top + SIT_OFFSET_PX;
+ const sx = rect.left + rect.width / 2;
+ const sy = rect.top + sitOffsetPx();
return domToWorld(sx, sy);
}
// Jump target: visible feet land on the top edge of the button.
@@ -406,10 +441,12 @@
// bounce. DOM nodes so the splash composites with the button itself.
const SPLASH_GRAVITY = 1800; // px/s² — heavier so drops fall faster
const SPLASH_COUNT = 36; // more spray for the harder landing
- function fireSplash() {
- const rect = ctaBtn.getBoundingClientRect();
- const ox = rect.left + rect.width / 2;
- const oy = rect.top + 2;
+ function fireSplash(ox, oy) {
+ if (ox == null || oy == null) {
+ const rect = ctaBtn.getBoundingClientRect();
+ ox = rect.left + rect.width / 2;
+ oy = rect.top + 2;
+ }
const drops = [];
for (let i = 0; i < SPLASH_COUNT; i++) {
const size = 6 + Math.random() * 10;
@@ -487,9 +524,11 @@
function triggerJump() {
if (!avatar || !fallAction || phase === 'jumping') return;
- // Re-read both endpoints fresh so the trajectory is always layout-correct
- startW = getSitWorld(); // where we ACTUALLY jump from (avatar's current rest)
- jumpTarget = getButtonWorld(); // where the feet need to land
+ // Re-read endpoints fresh so the trajectory is always layout-correct.
+ // Straight drop: X stays at the sit anchor; only Y falls to the button.
+ startW = getSitWorld();
+ const btn = getButtonWorld();
+ jumpTarget = { x: startW.x, y: btn.y };
phase = 'jumping'; seqT = 0; landed = false;
fallAction.reset();
@@ -499,38 +538,39 @@
function updateSeq(dt) {
if (phase !== 'jumping' || !avatar) return;
seqT += dt;
- const p = Math.min(seqT / JUMP_S, 1);
- const ease = smoothstep(p);
-
- // Animate BOTH axes between startW (sit anchor) and jumpTarget (button)
- const x = startW.x + (jumpTarget.x - startW.x) * ease;
- const arc = PEAK_U * 4 * p * (1 - p);
- const y = startW.y + (jumpTarget.y - startW.y) * ease + arc;
-
+ const p = Math.min(seqT / JUMP_S, 1);
+
+ // Straight drop: X is locked (jumpTarget.x === startW.x) and Y
+ // follows a gravity-like p² curve — barely moves at the top,
+ // accelerates into the landing. No upward arc and no yaw, so
+ // the motion reads as "fell off the perch" instead of "leapt".
+ const x = startW.x;
+ const y = startW.y + (jumpTarget.y - startW.y) * (p * p);
avatar.position.set(x, y, 0);
- // Subtle in-flight yaw — peaks mid-arc, returns to 0 by landing.
- // Sign follows horizontal travel direction so he looks where he's going.
- const dir = Math.sign(jumpTarget.x - startW.x);
- avatar.rotation.y = JUMP_YAW * dir * Math.sin(Math.PI * p);
-
- // Squish + splash fire only on real screen-space contact. The arc
- // only returns to 0 at p≈1.0, so we gate on actual feet-to-button
- // distance (LAND_PX) rather than the time fraction — otherwise the
- // bounce telegraphs ~35px before the visual landing.
+ // Squish + splash gate on real screen-space contact so the
+ // effects fire on the actual landing frame.
if (!landed && p >= LAND_P) {
- const dxPx = Math.abs(avatar.position.x - jumpTarget.x) * PX_PER_UNIT;
const dyPx = Math.abs(avatar.position.y - jumpTarget.y) * PX_PER_UNIT;
- if (dxPx < LAND_PX && dyPx < LAND_PX) {
+ if (dyPx < LAND_PX) {
landed = true;
fireSquish();
- fireSplash();
+ const btnRect = ctaBtn.getBoundingClientRect();
+ const sitRect = sitLine.getBoundingClientRect();
+ const landX = sitRect.left + sitRect.width / 2;
+ fireSplash(landX, btnRect.top + 2);
}
}
if (p >= 1) {
phase = 'resting';
later(() => {
+ // 60% of landings, surprise the user with a perform clip on
+ // the button instead of an immediate slide back — breaks the
+ // sit→jump→sit monotony and showcases the chip animations
+ // without requiring a click. The perform's own resume path
+ // handles the slide back to sit, so we just bail here.
+ if (maybeAutoPerform()) return;
const fromX = avatar.position.x;
const fromY = avatar.position.y;
const back = getSitWorld();
@@ -636,6 +676,22 @@
chip.addEventListener('click', () => performAction(chip.dataset.clip));
}
+ // Auto-perform: occasionally play a one-shot clip after landing so the
+ // loop reads as "alive" instead of mechanical. Skips rumba (long, looping)
+ // and only fires once every couple of cycles so it stays surprising.
+ const AUTO_PERFORM_CLIPS = ['wave', 'celebrate', 'taunt'];
+ let landingsSinceAutoPerform = 0;
+ function maybeAutoPerform() {
+ landingsSinceAutoPerform++;
+ if (landingsSinceAutoPerform < 2) return false;
+ if (!performActions.wave) return false; // clips not loaded yet
+ if (Math.random() >= 0.6) return false;
+ landingsSinceAutoPerform = 0;
+ const pick = AUTO_PERFORM_CLIPS[Math.floor(Math.random() * AUTO_PERFORM_CLIPS.length)];
+ performAction(pick);
+ return true;
+ }
+
// ── Load avatar + animations ──────────────────────────────────────
// Realistic Avaturn-rigged humanoid; clips in /public/animations/clips
// are retargeted to this rig (see public/animations/registry.json).
@@ -674,6 +730,7 @@
fallAction = mixer.clipAction(THREE.AnimationClip.parse(jumpJson));
fallAction.setLoop(THREE.LoopOnce, 1);
fallAction.clampWhenFinished = true;
+ fallAction.timeScale = JUMP_RATE;
PERFORM_CLIPS.forEach((def, i) => {
const a = mixer.clipAction(THREE.AnimationClip.parse(performJsons[i]));
diff --git a/scripts/run-asset-marketplace-migration.mjs b/scripts/run-asset-marketplace-migration.mjs
new file mode 100644
index 000000000..342053e79
--- /dev/null
+++ b/scripts/run-asset-marketplace-migration.mjs
@@ -0,0 +1,46 @@
+// One-shot migration runner for the asset marketplace tables. The repo's
+// older scripts/run-migrations.js targets a pg-style client that this project
+// no longer exports, so this script speaks the Neon HTTP driver directly.
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { neon } from '@neondatabase/serverless';
+import 'dotenv/config';
+
+const MIGRATION = resolve('migrations/20260523140000_create_asset_prices_and_purchases.sql');
+
+const connStr = process.env.DATABASE_URL;
+if (!connStr) {
+ console.error('DATABASE_URL not set — load .env.local first or pass it inline.');
+ process.exit(1);
+}
+
+const sql = neon(connStr);
+const raw = readFileSync(MIGRATION, 'utf-8');
+
+// Strip /* */ comments first, then split on `;` followed by newline. Statements
+// in this migration don't embed semicolons inside string literals.
+const cleaned = raw.replace(/--[^\n]*/g, '');
+const statements = cleaned
+ .split(/;\s*\n/)
+ .map((s) => s.trim())
+ .filter((s) => s.length);
+
+console.log(`Found ${statements.length} statements.`);
+for (const stmt of statements) {
+ const preview = stmt.split('\n')[0].slice(0, 80);
+ try {
+ await sql(stmt);
+ console.log(`✓ ${preview}…`);
+ } catch (err) {
+ // IF NOT EXISTS makes most of these idempotent; if it still fails, surface why.
+ console.error(`✗ ${preview}…`);
+ console.error(' ', err.message);
+ process.exit(1);
+ }
+}
+
+const [p] = await sql`SELECT to_regclass('public.asset_prices') AS t`;
+const [u] = await sql`SELECT to_regclass('public.asset_purchases') AS t`;
+const [r] = await sql`SELECT to_regclass('public.asset_purchase_receipts') AS t`;
+console.log('asset_prices:', p.t, '| asset_purchases:', u.t, '| asset_purchase_receipts:', r.t);
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index cc8337b25..9cccf4fbf 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -56,6 +56,16 @@ export const api = {
if (params.granularity) q.set('granularity', params.granularity);
return j('GET', `/api/billing/revenue?${q.toString()}`);
},
+ listWithdrawals: ({ status, limit, offset } = {}) => {
+ const q = new URLSearchParams();
+ if (status) q.set('status', status);
+ if (limit) q.set('limit', String(limit));
+ if (offset) q.set('offset', String(offset));
+ const qs = q.toString();
+ return j('GET', `/api/billing/withdrawals${qs ? '?' + qs : ''}`);
+ },
+ requestWithdrawal: (body) => j('POST', '/api/billing/withdrawals', body),
+ listPayoutWallets: () => j('GET', '/api/billing/payout-wallets'),
};
// Single-use CSRF token: fetched lazily, invalidated on consumption. Re-issued
@@ -122,6 +132,7 @@ const KNOWN_TABS = [
'subscriptions',
'billing',
'revenue',
+ 'withdrawals',
'earnings',
'account',
];
@@ -227,6 +238,7 @@ const tabs = {
subscriptions: renderSubscriptions,
billing: renderBilling,
revenue: renderRevenue,
+ withdrawals: renderWithdrawals,
earnings: renderEarnings,
account: renderAccount,
};
@@ -3428,6 +3440,259 @@ async function renderRevenue(root) {
window.addEventListener('focus', onFocus, { once: true });
}
+// ── Withdrawals ─────────────────────────────────────────────────────────────
+// Owner-facing UI for pulling earned USDC out to a wallet they control.
+// Backend: GET/POST /api/billing/withdrawals (CSRF-gated POST).
+// Cron processor (api/cron/[name].js → handleProcessWithdrawals) moves rows
+// from pending → processing → completed/failed on-chain.
+
+const USDC_MINTS = {
+ solana: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ base: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913',
+};
+const MIN_WITHDRAWAL_LAMPORTS = 1_000_000; // 1 USDC
+
+const SOLANA_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const EVM_ADDR_RE = /^0x[a-fA-F0-9]{40}$/;
+
+function isValidAddrFor(chain, addr) {
+ if (chain === 'solana') return SOLANA_ADDR_RE.test(addr);
+ if (chain === 'base' || chain === 'evm') return EVM_ADDR_RE.test(addr);
+ return false;
+}
+
+function shortAddr(a) {
+ if (!a) return '—';
+ if (a.length <= 14) return a;
+ return a.slice(0, 6) + '…' + a.slice(-4);
+}
+
+function withdrawalStatusBadge(status) {
+ const colors = {
+ pending: '#f59e0b',
+ processing: '#5cc8ff',
+ completed: '#22c55e',
+ failed: '#ef4444',
+ };
+ const c = colors[status] || '#888';
+ return `<span style="font-size:11px;padding:2px 7px;border-radius:10px;background:${c}22;color:${c}">${esc(status)}</span>`;
+}
+
+function withdrawalTxLink(w) {
+ if (!w.tx_signature) return '<span class="muted">—</span>';
+ const sig = encodeURIComponent(w.tx_signature);
+ const url =
+ w.chain === 'solana'
+ ? `https://solscan.io/tx/${sig}`
+ : w.chain === 'base'
+ ? `https://basescan.org/tx/${sig}`
+ : `https://etherscan.io/tx/${sig}`;
+ return `<a href="${url}" target="_blank" rel="noopener">view ↗</a>`;
+}
+
+async function renderWithdrawals(root) {
+ root.innerHTML = `
+ <h1>Withdrawals</h1>
+ <p class="sub">Pull your earned USDC to a wallet you control.</p>
+ <div id="wd-body"><div class="muted">Loading…</div></div>
+ `;
+ const body = root.querySelector('#wd-body');
+
+ let revenue, withdrawalsResp, walletsResp;
+ try {
+ [revenue, withdrawalsResp, walletsResp] = await Promise.all([
+ api.getRevenue({ from: '1970-01-01T00:00:00Z', granularity: 'month' }),
+ api.listWithdrawals({ limit: 50 }),
+ api.listPayoutWallets(),
+ ]);
+ } catch (e) {
+ body.innerHTML = `<div class="err">${esc(e.message || 'Failed to load withdrawal data')}</div>`;
+ return;
+ }
+
+ const withdrawals = withdrawalsResp.withdrawals || [];
+ const wallets = walletsResp.wallets || [];
+ const earned = Number(revenue.summary?.net_total || 0);
+ const inflight = withdrawals
+ .filter((w) => w.status === 'pending' || w.status === 'processing')
+ .reduce((s, w) => s + Number(w.amount), 0);
+ const available = Math.max(0, earned - inflight);
+ const canWithdraw = available >= MIN_WITHDRAWAL_LAMPORTS;
+
+ const solWallet = wallets.find((w) => w.chain === 'solana');
+ const baseWallet = wallets.find((w) => w.chain === 'base' || w.chain === 'evm');
+
+ body.innerHTML = `
+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:20px">
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Net earned (all time)</div>
+ <div style="font-size:20px;font-weight:700">${esc(formatUSDC(earned))}</div>
+ </div>
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">In flight</div>
+ <div style="font-size:20px;font-weight:700;color:#f59e0b">${esc(formatUSDC(inflight))}</div>
+ </div>
+ <div class="card">
+ <div class="muted" style="font-size:12px;margin-bottom:4px">Available</div>
+ <div style="font-size:20px;font-weight:700;color:#00e5a0">${esc(formatUSDC(available))}</div>
+ </div>
+ </div>
+
+ <div class="card" style="margin-bottom:20px;max-width:560px">
+ <h3 style="margin:0 0 12px">Request a withdrawal</h3>
+ ${
+ canWithdraw
+ ? ''
+ : `<div class="muted" style="margin-bottom:12px">Minimum withdrawal is 1 USDC. Available balance is too low.</div>`
+ }
+ <div style="display:flex;flex-direction:column;gap:12px">
+ <label style="display:flex;flex-direction:column;gap:4px">
+ <span class="muted" style="font-size:12px">Amount (USDC)</span>
+ <div class="row" style="gap:8px">
+ <input id="wd-amount" type="number" min="1" step="0.000001" placeholder="0.00" style="flex:1;font-size:14px" ${canWithdraw ? '' : 'disabled'}>
+ <button class="btn sec" id="wd-max" type="button" ${canWithdraw ? '' : 'disabled'}>Max</button>
+ </div>
+ </label>
+ <label style="display:flex;flex-direction:column;gap:4px">
+ <span class="muted" style="font-size:12px">Chain</span>
+ <select id="wd-chain" style="font-size:14px" ${canWithdraw ? '' : 'disabled'}>
+ <option value="solana">Solana (USDC)</option>
+ <option value="base">Base (USDC)</option>
+ </select>
+ </label>
+ <label style="display:flex;flex-direction:column;gap:4px">
+ <span class="muted" style="font-size:12px">Destination address</span>
+ <input id="wd-address" type="text" placeholder="destination address" style="font-size:14px;font-family:ui-monospace,monospace" ${canWithdraw ? '' : 'disabled'}>
+ <span id="wd-addr-hint" class="muted" style="font-size:12px"></span>
+ </label>
+ <div class="row" style="gap:8px">
+ <button class="btn" id="wd-submit" ${canWithdraw ? '' : 'disabled'}>Request withdrawal</button>
+ <span id="wd-msg" class="muted" style="font-size:13px"></span>
+ </div>
+ </div>
+ </div>
+
+ <div class="card">
+ <h3 style="margin:0 0 12px">History</h3>
+ ${
+ withdrawals.length === 0
+ ? '<div class="muted">No withdrawals yet.</div>'
+ : `<table style="width:100%;border-collapse:collapse;font-size:13px">
+ <thead>
+ <tr style="text-align:left;color:#888;border-bottom:1px solid var(--border)">
+ <th style="padding:8px 10px">Amount</th>
+ <th style="padding:8px 10px">Chain</th>
+ <th style="padding:8px 10px">Destination</th>
+ <th style="padding:8px 10px">Status</th>
+ <th style="padding:8px 10px">Tx</th>
+ <th style="padding:8px 10px">Requested</th>
+ </tr>
+ </thead>
+ <tbody>
+ ${withdrawals
+ .map(
+ (w) => `<tr style="border-bottom:1px solid var(--border)">
+ <td style="padding:8px 10px;font-variant-numeric:tabular-nums">${esc(formatUSDC(Number(w.amount)))}</td>
+ <td style="padding:8px 10px">${esc(w.chain)}</td>
+ <td style="padding:8px 10px;font-family:ui-monospace,monospace;font-size:11px" title="${attr(w.to_address)}">${esc(shortAddr(w.to_address))}</td>
+ <td style="padding:8px 10px">${withdrawalStatusBadge(w.status)}</td>
+ <td style="padding:8px 10px">${withdrawalTxLink(w)}</td>
+ <td style="padding:8px 10px;color:#888">${new Date(w.created_at).toLocaleString()}</td>
+ </tr>`,
+ )
+ .join('')}
+ </tbody>
+ </table>`
+ }
+ </div>
+ `;
+
+ if (!canWithdraw) return;
+
+ const amountEl = body.querySelector('#wd-amount');
+ const chainEl = body.querySelector('#wd-chain');
+ const addrEl = body.querySelector('#wd-address');
+ const hintEl = body.querySelector('#wd-addr-hint');
+ const maxBtn = body.querySelector('#wd-max');
+ const submitBtn = body.querySelector('#wd-submit');
+ const msgEl = body.querySelector('#wd-msg');
+
+ function syncDefaultAddress() {
+ const chain = chainEl.value;
+ const fallback = chain === 'solana' ? solWallet : baseWallet;
+ if (fallback) {
+ addrEl.value = fallback.address;
+ hintEl.textContent = `Pre-filled from your ${chain === 'solana' ? 'Solana' : 'Base'} payout wallet.`;
+ } else {
+ addrEl.value = '';
+ hintEl.innerHTML =
+ 'No default set. Configure one on the <a href="/dashboard/monetization">Monetization tab</a> to pre-fill.';
+ }
+ }
+ syncDefaultAddress();
+ chainEl.addEventListener('change', syncDefaultAddress);
+
+ maxBtn.addEventListener('click', () => {
+ amountEl.value = (available / 1_000_000).toString();
+ });
+
+ submitBtn.addEventListener('click', async () => {
+ msgEl.style.color = '';
+ const human = parseFloat(amountEl.value);
+ if (!Number.isFinite(human) || human <= 0) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = 'Enter a valid amount.';
+ return;
+ }
+ const amount = Math.round(human * 1_000_000);
+ if (amount < MIN_WITHDRAWAL_LAMPORTS) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = 'Minimum withdrawal is 1 USDC.';
+ return;
+ }
+ if (amount > available) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = `Exceeds available (${formatUSDC(available)}).`;
+ return;
+ }
+ const chain = chainEl.value;
+ const to_address = addrEl.value.trim();
+ if (!to_address) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = 'Destination address required.';
+ return;
+ }
+ if (!isValidAddrFor(chain, to_address)) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent =
+ chain === 'solana'
+ ? 'Invalid Solana address (expected base58, 32–44 chars).'
+ : 'Invalid Base address (expected 0x + 40 hex chars).';
+ return;
+ }
+
+ submitBtn.disabled = true;
+ msgEl.style.color = '#888';
+ msgEl.textContent = 'Submitting…';
+ try {
+ const resp = await api.requestWithdrawal({
+ amount,
+ chain,
+ currency_mint: USDC_MINTS[chain] || USDC_MINTS.solana,
+ to_address,
+ });
+ msgEl.style.color = '#00e5a0';
+ msgEl.textContent = 'Withdrawal requested.';
+ if (resp?.withdrawal) withdrawals.unshift(resp.withdrawal);
+ renderWithdrawals(root);
+ } catch (e) {
+ msgEl.style.color = '#ffb3b3';
+ msgEl.textContent = e?.data?.error_description || e.message || 'Request failed';
+ submitBtn.disabled = false;
+ }
+ });
+}
+
// ── Widgets ─────────────────────────────────────────────────────────────────
// Saved 3D experiences the user has generated in the Studio. Each gets its own
// card with a live, lazy-loaded preview iframe. Editing happens in /studio —
diff --git a/src/marketplace.js b/src/marketplace.js
index 5a11fcbb5..1b0521d30 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -112,6 +112,7 @@ const state = {
tag: null, // ?tag=humanoid → filter all cards to entries containing this tag
sort: 'recommended',
filter: 'all', // all | agents | avatars | onchain
+ priceFilter: 'all', // all | free | paid
cursor: null,
items: [],
loading: false,
@@ -896,6 +897,18 @@ function bindFilterChips() {
renderGrid();
});
});
+
+ // Price-filter chips (Any / Free / Paid) act orthogonally to the kind
+ // filter — toggling them just re-filters the in-memory grid without
+ // triggering a refetch.
+ const priceChips = document.querySelectorAll('#market-price-filter-chips .market-chip');
+ priceChips.forEach((chip) => {
+ chip.addEventListener('click', () => {
+ priceChips.forEach((c) => c.classList.toggle('active', c === chip));
+ state.priceFilter = chip.dataset.priceFilter || 'all';
+ renderGrid();
+ });
+ });
}
function renderTagBanner() {
@@ -936,6 +949,17 @@ function renderGrid() {
onchain = onchain.filter((a) => matches(a.tags));
}
+ // Price filter (Free / Paid). Onchain agents aren't sold through this
+ // marketplace surface, so the filter only applies to agents + avatars.
+ if (state.priceFilter === 'free') {
+ agentItems = agentItems.filter((a) => !hasActivePrice(a.price));
+ avatars = avatars.filter((a) => !hasActivePrice(a.price));
+ } else if (state.priceFilter === 'paid') {
+ agentItems = agentItems.filter((a) => hasActivePrice(a.price));
+ avatars = avatars.filter((a) => hasActivePrice(a.price));
+ onchain = [];
+ }
+
renderTagBanner();
const totalCards = agentItems.length + avatars.length + onchain.length;
@@ -1172,6 +1196,9 @@ function openAvatarModal(avatar) {
overlay.hidden = false;
requestAnimationFrame(() => overlay.classList.add('show'));
+ // Render the sell-or-buy panel — empty for demo/onchain avatars.
+ renderAvatarSalePanel(avatar);
+
// Fire-and-forget view tracking — server rate-limits per IP/avatar so safe to call on every open.
if (avatar.avatarId && !String(avatar.avatarId).startsWith('avatar_demo_')) {
fetch(`${API}/avatars/view`, {
@@ -1183,6 +1210,343 @@ function openAvatarModal(avatar) {
}
}
+// ── Sell-or-buy panel for the avatar detail modal ─────────────────────────
+//
+// Asks the server who owns the avatar + its active price, then renders one
+// of two inline panels:
+// 1. Owner → editor: set/clear a USDC price + payout wallet.
+// 2. Non-owner → "Pay X USDC" button (only when there's an active price).
+//
+// Demo / onchain avatars skip the panel since they're not stored as our rows.
+async function renderAvatarSalePanel(avatar) {
+ const sale = $('avatar-modal-sale');
+ if (!sale) return;
+ sale.hidden = true;
+ sale.innerHTML = '';
+
+ const id = avatar.avatarId || '';
+ if (!id || id.startsWith('avatar_demo_')) return;
+
+ // Fetch the canonical avatar row to determine ownership + payout state.
+ // `owner_id` is present in the response only when the caller IS the owner —
+ // see api/_lib/avatars.js#stripOwnerFor. We use that as our cheap auth check.
+ let detail;
+ try {
+ const r = await fetch(`${API}/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });
+ if (!r.ok) return;
+ const j = await r.json();
+ detail = j?.avatar;
+ } catch (err) {
+ console.warn('[marketplace] sale-panel fetch failed', err);
+ return;
+ }
+ if (!detail) return;
+
+ const isOwner = !!detail.owner_id;
+ const price = detail.price || avatar.price || null;
+
+ if (isOwner) {
+ sale.hidden = false;
+ const decimals = Number(price?.mint_decimals ?? 6);
+ const currentUsd = price ? (Number(price.amount) / Math.pow(10, decimals)).toString() : '';
+ sale.innerHTML = `
+ <div class="sale-eyebrow">Sell this avatar</div>
+ ${price
+ ? `<div class="sale-price">${escapeHtml(formatAssetPrice(price) || 'Free')}</div>`
+ : `<div class="sale-price free">Free</div>`}
+ <div class="sale-row">
+ <label>
+ Price
+ <input type="number" id="avatar-sale-price" min="0" step="0.01" placeholder="0.00" value="${escapeHtml(currentUsd)}" />
+ </label>
+ <span class="sale-currency">USDC</span>
+ </div>
+ <label>
+ Solana payout wallet
+ <input type="text" id="avatar-sale-payout" placeholder="Your Solana address" />
+ </label>
+ <div class="sale-row" style="gap:8px">
+ <button class="sale-save" type="button" id="avatar-sale-save">${price ? 'Update price' : 'List for sale'}</button>
+ ${price ? '<button class="sale-clear" type="button" id="avatar-sale-clear">Make free</button>' : ''}
+ </div>
+ <p class="sale-status" id="avatar-sale-status"></p>
+ <p class="sale-hint">Buyers pay USDC on Solana. We don't take a cut — funds land in your payout wallet (minus referral commission if applicable).</p>
+ `;
+
+ // Prefill payout wallet field from /api/billing/payout-wallets if the
+ // seller already saved one. Falls back to empty otherwise.
+ fetch(`${API}/billing/payout-wallets`, { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => {
+ const ws = j?.wallets || [];
+ const solana = ws.find((w) => w.chain === 'solana' && w.is_default) || ws.find((w) => w.chain === 'solana');
+ if (solana?.address) {
+ const inp = $('avatar-sale-payout');
+ if (inp && !inp.value) inp.value = solana.address;
+ }
+ })
+ .catch(() => {});
+
+ $('avatar-sale-save')?.addEventListener('click', () => saveAvatarPrice(id));
+ $('avatar-sale-clear')?.addEventListener('click', () => clearAvatarPrice(id));
+ return;
+ }
+
+ if (price) {
+ sale.hidden = false;
+ sale.innerHTML = `
+ <div class="sale-eyebrow">For sale</div>
+ <div class="sale-price">${escapeHtml(formatAssetPrice(price))}</div>
+ <button class="sale-buy" type="button" id="avatar-sale-buy">Buy now with USDC</button>
+ <p class="sale-status" id="avatar-sale-status"></p>
+ <p class="sale-hint">Pay directly to the creator on Solana. You'll need a connected wallet with USDC.</p>
+ `;
+ $('avatar-sale-buy')?.addEventListener('click', () => openAssetPurchaseFlow({
+ item_type: 'avatar',
+ item_id: id,
+ label: avatar.name || 'Avatar',
+ price,
+ }));
+ }
+}
+
+async function saveAvatarPrice(avatarId) {
+ const priceInput = $('avatar-sale-price');
+ const payoutInput = $('avatar-sale-payout');
+ const status = $('avatar-sale-status');
+ if (!priceInput || !payoutInput) return;
+ const usd = Number(priceInput.value || 0);
+ const payout = (payoutInput.value || '').trim();
+ if (!Number.isFinite(usd) || usd < 0) { setSaleStatus(status, 'Enter a valid price.', 'err'); return; }
+ if (usd > 0 && !payout) { setSaleStatus(status, 'A payout wallet is required to charge.', 'err'); return; }
+
+ setSaleStatus(status, 'Saving…');
+ try {
+ // 1. Save the payout wallet first (if provided) so the price is sellable
+ // the moment it's set. Server is idempotent on (user, chain, address).
+ if (payout) {
+ const r = await fetch(`${API}/billing/payout-wallets`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ address: payout, chain: 'solana', is_default: true }),
+ });
+ if (!r.ok && r.status !== 409) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || 'Failed to save payout wallet');
+ }
+ }
+
+ // 2. Write the price. amount is in atomic USDC units (6 decimals).
+ const amount = Math.round(usd * 1_000_000);
+ const r = await apiPostWithCsrf('/api/marketplace/asset-price', {
+ item_type: 'avatar',
+ item_id: avatarId,
+ amount,
+ currency_mint: USDC_MAINNET_MINT,
+ chain: 'solana',
+ mint_decimals: 6,
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to save price');
+
+ setSaleStatus(status, amount === 0 ? '✓ Avatar is now free.' : `✓ Listed for ${usd} USDC.`, 'ok');
+ // Refresh the in-memory item so the card reflects the new price next time.
+ if (activeAvatar?.avatarId === avatarId) activeAvatar.price = j.data.price;
+ updateAvatarCardPriceInGrid(avatarId, j.data.price);
+ } catch (err) {
+ setSaleStatus(status, err.message || 'Save failed', 'err');
+ }
+}
+
+async function clearAvatarPrice(avatarId) {
+ const status = $('avatar-sale-status');
+ setSaleStatus(status, 'Clearing…');
+ try {
+ const r = await apiPostWithCsrf('/api/marketplace/asset-price', {
+ item_type: 'avatar',
+ item_id: avatarId,
+ amount: 0,
+ currency_mint: USDC_MAINNET_MINT,
+ chain: 'solana',
+ mint_decimals: 6,
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || 'Failed to clear price');
+ }
+ setSaleStatus(status, '✓ Avatar is now free.', 'ok');
+ if (activeAvatar?.avatarId === avatarId) activeAvatar.price = null;
+ updateAvatarCardPriceInGrid(avatarId, null);
+ // Re-render the panel so the editor shows the new free state.
+ if (activeAvatar?.avatarId === avatarId) renderAvatarSalePanel(activeAvatar);
+ } catch (err) {
+ setSaleStatus(status, err.message || 'Failed', 'err');
+ }
+}
+
+function setSaleStatus(el, text, kind) {
+ if (!el) return;
+ el.textContent = text || '';
+ el.className = 'sale-status' + (kind ? ' ' + kind : '');
+}
+
+// Live-update the in-grid card pill so the seller sees the change without a reload.
+function updateAvatarCardPriceInGrid(avatarId, price) {
+ const card = document.querySelector(`.market-card-avatar[data-avatar-id="${avatarId}"]`);
+ if (!card) return;
+ const thumb = card.querySelector('.thumb');
+ if (!thumb) return;
+ const old = thumb.querySelector('.market-price-pill');
+ if (old) old.remove();
+ thumb.insertAdjacentHTML('afterbegin', priceBadgeHtml(price));
+}
+
+// ── Sell-or-buy panel for the agent detail view ──────────────────────────
+//
+// Renders inside the existing #agent-sale-panel container right under the
+// agent's name. Mirrors the avatar modal panel: owner sees price/payout
+// editor, non-owner with active price sees a Buy button. Free agents for
+// non-owners get nothing.
+function renderAgentSalePanel(agent) {
+ const panel = $('agent-sale-panel');
+ if (!panel || !agent) return;
+ panel.hidden = true;
+ panel.innerHTML = '';
+
+ const isOwner = !!(currentUserId && agent.author_id && currentUserId === agent.author_id);
+ const price = agent.price || null;
+
+ if (isOwner) {
+ panel.hidden = false;
+ const decimals = Number(price?.mint_decimals ?? 6);
+ const currentUsd = price ? (Number(price.amount) / Math.pow(10, decimals)).toString() : '';
+ panel.innerHTML = `
+ <div class="sale-eyebrow">Sell this agent</div>
+ ${price
+ ? `<div class="sale-price">${escapeHtml(formatAssetPrice(price) || 'Free')}</div>`
+ : `<div class="sale-price free">Free</div>`}
+ <div class="sale-row">
+ <label>
+ Price
+ <input type="number" id="agent-sale-price" min="0" step="0.01" placeholder="0.00" value="${escapeHtml(currentUsd)}" />
+ </label>
+ <span class="sale-currency">USDC</span>
+ </div>
+ <label>
+ Solana payout wallet
+ <input type="text" id="agent-sale-payout" placeholder="Your Solana address" />
+ </label>
+ <div class="sale-row" style="gap:8px">
+ <button class="sale-save" type="button" id="agent-sale-save">${price ? 'Update price' : 'List for sale'}</button>
+ ${price ? '<button class="sale-clear" type="button" id="agent-sale-clear">Make free</button>' : ''}
+ </div>
+ <p class="sale-status" id="agent-sale-status"></p>
+ <p class="sale-hint">Per-skill prices are still available below — this sets a single one-time price to fork the whole agent.</p>
+ `;
+ fetch(`${API}/billing/payout-wallets`, { credentials: 'include' })
+ .then((r) => (r.ok ? r.json() : null))
+ .then((j) => {
+ const ws = j?.wallets || [];
+ const solana = ws.find((w) => w.chain === 'solana' && w.is_default) || ws.find((w) => w.chain === 'solana');
+ if (solana?.address) {
+ const inp = $('agent-sale-payout');
+ if (inp && !inp.value) inp.value = solana.address;
+ }
+ })
+ .catch(() => {});
+
+ $('agent-sale-save')?.addEventListener('click', () => saveAgentPrice(agent.id));
+ $('agent-sale-clear')?.addEventListener('click', () => clearAgentPrice(agent.id));
+ return;
+ }
+
+ if (price) {
+ panel.hidden = false;
+ panel.innerHTML = `
+ <div class="sale-eyebrow">For sale</div>
+ <div class="sale-price">${escapeHtml(formatAssetPrice(price))}</div>
+ <button class="sale-buy" type="button" id="agent-sale-buy">Buy agent with USDC</button>
+ <p class="sale-status" id="agent-sale-status"></p>
+ <p class="sale-hint">One-time purchase grants ownership to fork the whole agent. Per-skill prices below are separate.</p>
+ `;
+ $('agent-sale-buy')?.addEventListener('click', () => openAssetPurchaseFlow({
+ item_type: 'agent',
+ item_id: agent.id,
+ label: agent.name || 'Agent',
+ price,
+ }));
+ }
+}
+
+async function saveAgentPrice(agentId) {
+ const priceInput = $('agent-sale-price');
+ const payoutInput = $('agent-sale-payout');
+ const status = $('agent-sale-status');
+ if (!priceInput || !payoutInput) return;
+ const usd = Number(priceInput.value || 0);
+ const payout = (payoutInput.value || '').trim();
+ if (!Number.isFinite(usd) || usd < 0) { setSaleStatus(status, 'Enter a valid price.', 'err'); return; }
+ if (usd > 0 && !payout) { setSaleStatus(status, 'A payout wallet is required to charge.', 'err'); return; }
+
+ setSaleStatus(status, 'Saving…');
+ try {
+ if (payout) {
+ const r = await fetch(`${API}/billing/payout-wallets`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ address: payout, chain: 'solana', is_default: true }),
+ });
+ if (!r.ok && r.status !== 409) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || 'Failed to save payout wallet');
+ }
+ }
+ const amount = Math.round(usd * 1_000_000);
+ const r = await apiPostWithCsrf('/api/marketplace/asset-price', {
+ item_type: 'agent',
+ item_id: agentId,
+ amount,
+ currency_mint: USDC_MAINNET_MINT,
+ chain: 'solana',
+ mint_decimals: 6,
+ });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to save price');
+
+ setSaleStatus(status, amount === 0 ? '✓ Agent is now free.' : `✓ Listed for ${usd} USDC.`, 'ok');
+ if (detailState?.agent?.id === agentId) detailState.agent.price = j.data.price;
+ if (detailState?.agent?.id === agentId) renderAgentSalePanel(detailState.agent);
+ } catch (err) {
+ setSaleStatus(status, err.message || 'Save failed', 'err');
+ }
+}
+
+async function clearAgentPrice(agentId) {
+ const status = $('agent-sale-status');
+ setSaleStatus(status, 'Clearing…');
+ try {
+ const r = await apiPostWithCsrf('/api/marketplace/asset-price', {
+ item_type: 'agent',
+ item_id: agentId,
+ amount: 0,
+ currency_mint: USDC_MAINNET_MINT,
+ chain: 'solana',
+ mint_decimals: 6,
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || 'Failed to clear price');
+ }
+ setSaleStatus(status, '✓ Agent is now free.', 'ok');
+ if (detailState?.agent?.id === agentId) detailState.agent.price = null;
+ if (detailState?.agent?.id === agentId) renderAgentSalePanel(detailState.agent);
+ } catch (err) {
+ setSaleStatus(status, err.message || 'Failed', 'err');
+ }
+}
+
function closeAvatarModal() {
const overlay = $('avatar-modal-overlay');
if (!overlay) return;
@@ -2314,9 +2678,10 @@ function renderAvatarCard(a, spotlight = false) {
const spotlightBadge = isSpotlight ? '<span class="card-featured-badge" title="Featured">⭐</span>' : '';
const bmActive = getAvatarBookmarks().has(a.avatarId || '');
const views = Number(a.viewCount) > 0 ? `<span class="stat-pill views" title="${a.viewCount} views">⊙ ${fmtNumber(a.viewCount)}</span>` : '';
+ const priceBadge = priceBadgeHtml(a.price);
const cardClasses = ['market-card-avatar', isSpotlight && 'market-card-avatar--featured'].filter(Boolean).join(' ');
return `<div class="${cardClasses}" data-avatar-id="${escapeHtml(a.avatarId || '')}">
- <div class="thumb">${spotlightBadge}${preview}</div>
+ <div class="thumb">${spotlightBadge}${priceBadge}${preview}</div>
<div class="body">
<div class="title-row">
<div class="title">${name}</div>
@@ -2343,6 +2708,7 @@ function renderCard(a) {
const buyers = a.buyers_total ?? 0;
const buyers24h = a.buyers_24h ?? 0;
const paid = a.has_paid_skills || Object.keys(a.skill_prices || {}).length > 0;
+ const priceBadge = priceBadgeHtml(a.price);
const ratingAvg = Number(a.rating_avg || 0);
const ratingCount = Number(a.rating_count || 0);
const avatarBlock = a.thumbnail_url
@@ -2358,6 +2724,7 @@ function renderCard(a) {
const starBtn = `<button type="button" class="card-star${bmOn ? ' on' : ''}" data-agent-bm="${escapeHtml(a.id)}" aria-label="Bookmark agent" aria-pressed="${bmOn}" title="${bmOn ? 'Remove bookmark' : 'Bookmark agent'}">${bmOn ? '★' : '☆'}</button>`;
return `<div class="market-card-agent" data-id="${a.id}">
${previewStrip}
+ ${priceBadge}
${starBtn}
<div class="head">
${avatarBlock}
@@ -2769,6 +3136,8 @@ function renderDetail(a, bookmarked) {
$('d-category').textContent = CATEGORY_LABELS[a.category] || a.category || 'General';
$('d-views').textContent = `⊙ ${fmtNumber(views)}`;
$('d-overview').textContent = a.description || '';
+
+ renderAgentSalePanel(a);
$('d-profile').textContent = a.system_prompt || a.prompt || '(No profile yet.)';
startPreviewSession(a);
$('d-bookmark').classList.toggle('on', bookmarked);
@@ -3303,6 +3672,36 @@ function fmtNumber(n) {
return String(num);
}
+// USDC mainnet mint. Anything else gets shown as a generic token symbol.
+const USDC_MAINNET_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// Render a price object (from /api/explore or /api/marketplace/agents) as a
+// human-readable string. Pass `null` / undefined to get "Free".
+function formatAssetPrice(price) {
+ if (!price || price.amount == null) return null;
+ const decimals = Number(price.mint_decimals ?? 6);
+ const amount = Number(price.amount);
+ if (!Number.isFinite(amount) || amount <= 0) return null;
+ const value = amount / Math.pow(10, decimals);
+ const symbol = price.currency_mint === USDC_MAINNET_MINT ? 'USDC' : (price.currency_mint || '').slice(0, 4) + '…';
+ const formatted = value >= 100 ? value.toFixed(0) : value >= 1 ? value.toFixed(2) : value.toFixed(3);
+ return `${formatted.replace(/\.?0+$/, '')} ${symbol}`;
+}
+
+// Reusable badge HTML for a Free/Paid listing. Returns empty string when there
+// is nothing to show.
+function priceBadgeHtml(price) {
+ const label = formatAssetPrice(price);
+ if (label) {
+ return `<span class="market-price-pill paid" title="${escapeHtml(label)}">${escapeHtml(label)}</span>`;
+ }
+ return `<span class="market-price-pill free">Free</span>`;
+}
+
+function hasActivePrice(price) {
+ return !!(price && Number(price.amount) > 0);
+}
+
// ── Purchase Flow ─────────────────────────────────────────────────────────
//
// One-shot Solana Pay purchase: server mints a unique reference Pubkey, the
@@ -3429,7 +3828,11 @@ function closePaymentModal() {
$('payment-modal-overlay').hidden = true;
const qr = $('payment-qr'); if (qr) qr.innerHTML = '';
const confirmBtn = $('payment-confirm-btn');
- if (confirmBtn) delete confirmBtn.dataset.durationHours;
+ if (confirmBtn) {
+ delete confirmBtn.dataset.durationHours;
+ delete confirmBtn.dataset.mode;
+ }
+ pendingAssetPurchase = null;
}
function shortMintLabel(mint) {
@@ -3559,8 +3962,129 @@ async function createPendingPurchase(agentId, skill, durationHours = null) {
return j.data;
}
+// ── Asset purchase (avatar / agent / plugin) ──────────────────────────────
+//
+// Shares the payment modal UI with the skill purchase flow but routes to the
+// generic /api/marketplace/buy-asset endpoint. The Confirm button reads
+// `dataset.mode` to decide which handler runs, so the same modal can be
+// re-used by both flows without duplicating wallet/UI plumbing.
+
+let pendingAssetPurchase = null; // { item_type, item_id, label, price }
+
+function openAssetPurchaseFlow(asset) {
+ const confirmBtn = $('payment-confirm-btn');
+ const skillName = $('payment-skill-name');
+ const agentName = $('payment-agent-name');
+ const priceDisplay = $('payment-price-display');
+ if (!confirmBtn || !skillName || !priceDisplay) {
+ alert('Payment UI not available on this page.');
+ return;
+ }
+
+ pendingAssetPurchase = asset;
+ confirmBtn.dataset.mode = 'asset';
+ confirmBtn.disabled = false;
+ delete confirmBtn.dataset.durationHours;
+
+ skillName.textContent = asset.label || 'Asset';
+ if (agentName) agentName.textContent = asset.item_type.charAt(0).toUpperCase() + asset.item_type.slice(1);
+
+ const decimals = Number(asset.price?.mint_decimals ?? 6);
+ const human = (Number(asset.price?.amount || 0) / Math.pow(10, decimals)).toFixed(decimals === 6 ? 2 : 4);
+ priceDisplay.textContent = `${human} ${shortMintLabel(asset.price?.currency_mint || '')}`;
+
+ const qr = $('payment-qr'); if (qr) qr.innerHTML = '';
+ setStatus('');
+ $('payment-modal-overlay').hidden = false;
+ updateWalletUI();
+}
+
+async function createPendingAssetPurchase(itemType, itemId) {
+ const r = await apiPostWithCsrf('/api/marketplace/buy-asset', { item_type: itemType, item_id: itemId });
+ const j = await r.json();
+ if (!r.ok) throw new Error(j.error_description || j.error || 'Failed to create purchase');
+ return j.data;
+}
+
+async function pollAssetConfirm(reference, windowMs = 60_000) {
+ const deadline = Date.now() + windowMs;
+ while (Date.now() < deadline) {
+ const r = await apiPostWithCsrf(`/api/marketplace/buy-asset/${reference}/confirm`, null);
+ const j = await r.json().catch(() => ({}));
+ if (r.ok && j.data?.status === 'confirmed') return true;
+ if (r.status === 410) throw new Error('Pending purchase expired. Please try again.');
+ if (r.status === 409) throw new Error(j.error_description || 'Transfer did not match expected amount.');
+ await new Promise((res) => setTimeout(res, 2500));
+ }
+ return false;
+}
+
+async function handleAssetPurchase() {
+ const confirmBtn = $('payment-confirm-btn');
+ const asset = pendingAssetPurchase;
+ if (!asset) { setStatus('No asset selected.', 'err'); return; }
+ if (!connectedWallet) { setStatus('Connect a wallet first.', 'err'); return; }
+
+ confirmBtn.disabled = true;
+ setStatus('Creating purchase…');
+
+ let purchase;
+ try {
+ purchase = await createPendingAssetPurchase(asset.item_type, asset.item_id);
+ if (purchase.already_owned) {
+ setStatus('Already purchased.', 'ok');
+ setTimeout(closePaymentModal, 1200);
+ return;
+ }
+ } catch (e) {
+ setStatus(e.message, 'err');
+ confirmBtn.disabled = false;
+ return;
+ }
+
+ try {
+ setStatus('Building transfer…');
+ const tx = await buildSplTransferWithReference({
+ payer: connectedWallet.publicKey,
+ recipient: purchase.recipient,
+ mint: purchase.currency_mint,
+ amount: BigInt(purchase.amount),
+ reference: purchase.reference,
+ });
+
+ setStatus('Approve in wallet…');
+ let txid;
+ if (typeof connectedWallet.provider.signAndSendTransaction === 'function') {
+ const result = await connectedWallet.provider.signAndSendTransaction(tx);
+ txid = result?.signature ?? result;
+ } else {
+ txid = await connectedWallet.provider.sendTransaction(tx, await getSolanaConnection());
+ }
+
+ setStatus('Waiting for on-chain confirmation…');
+ await (await getSolanaConnection()).confirmTransaction(txid, 'confirmed');
+
+ setStatus('Verifying with server…');
+ const ok = await pollAssetConfirm(purchase.reference, 60_000);
+ if (!ok) throw new Error('Server could not verify the transaction within 60 seconds.');
+
+ setStatus(`✓ ${asset.label} purchased.`, 'ok');
+ setTimeout(closePaymentModal, 1500);
+ } catch (e) {
+ console.error('[marketplace] asset purchase failed', e);
+ setStatus(e.message || 'Purchase failed', 'err');
+ confirmBtn.disabled = false;
+ }
+}
+
async function handlePurchase() {
const confirmBtn = $('payment-confirm-btn');
+ // Asset purchases (avatar / agent / plugin) come through the same Confirm
+ // button as skill purchases — the mode marker on the button decides which
+ // backend flow to run.
+ if (confirmBtn?.dataset.mode === 'asset') {
+ return handleAssetPurchase();
+ }
if (!connectedWallet) { setStatus('Connect a wallet first.', 'err'); return; }
if (!detailState?.agent) return;
@@ -3856,10 +4380,27 @@ function init() {
loadTheme();
initPlugins();
fetchUserPurchases();
+ loadCurrentUser();
bindDetailExtras({ navTo, openAvatarModal });
render();
}
+// Cached current user id. Used by the sell/buy panels to decide whether the
+// viewer is the owner of the asset (and therefore should see the editor) or
+// a potential buyer (and therefore should see the Buy button). Anonymous
+// visitors get `null` and only see the buyer side.
+let currentUserId = null;
+async function loadCurrentUser() {
+ try {
+ const r = await fetch('/api/auth/me', { credentials: 'include' });
+ if (!r.ok) return;
+ const j = await r.json();
+ currentUserId = j?.user?.id || j?.data?.id || j?.id || null;
+ } catch {
+ // non-fatal — page works fully for anonymous viewers
+ }
+}
+
// ── Plugin Marketplace ────────────────────────────────────────────────────────
const PLUGIN_API = '/api/plugins';
@@ -3998,8 +4539,23 @@ function renderPluginGrid() {
grid.querySelectorAll('[data-plugin-id]').forEach((btn) => {
btn.addEventListener('click', () => {
const id = btn.dataset.pluginId;
- const manifest = pluginState.items.find((p) => p.identifier === id);
- if (manifest) togglePluginInstall(manifest.manifest_json ?? manifest);
+ const pluginUuid = btn.dataset.pluginUuid || null;
+ const isPaid = btn.dataset.pluginPaid === '1';
+ const plugin = pluginState.items.find((p) => p.identifier === id);
+ if (!plugin) return;
+
+ // Paid plugins go through the asset purchase flow first; only
+ // installed (already-purchased) ones can be added to the agent.
+ if (isPaid && pluginUuid && !installed.has(id)) {
+ openAssetPurchaseFlow({
+ item_type: 'plugin',
+ item_id: pluginUuid,
+ label: plugin.name || id,
+ price: plugin.price,
+ });
+ return;
+ }
+ togglePluginInstall(plugin.manifest_json ?? plugin);
});
});
if (more) more.hidden = !pluginState.cursor;
@@ -4014,7 +4570,9 @@ function renderPluginCard(p, installed) {
const isInstalled = installed.has(p.identifier);
const cat = escapeHtml(p.category || manifest?.meta?.category || 'general');
const icon = (p.name || p.identifier || '?')[0].toUpperCase();
- return `<div class="plugin-card">
+ const priceBadge = priceBadgeHtml(p.price);
+ return `<div class="plugin-card" style="position:relative">
+ ${priceBadge}
<div class="head">
<div class="avatar">${icon}</div>
<div style="min-width:0;flex:1">
@@ -4029,8 +4587,10 @@ function renderPluginCard(p, installed) {
<div class="plugin-card-footer">
<span class="stat-pill">↓ ${p.install_count || 0}</span>
<button class="plugin-install-btn${isInstalled ? ' installed' : ''}"
- data-plugin-id="${escapeHtml(p.identifier)}">
- ${isInstalled ? 'Installed ✓' : 'Add to Agent'}
+ data-plugin-id="${escapeHtml(p.identifier)}"
+ data-plugin-uuid="${escapeHtml(p.id || '')}"
+ data-plugin-paid="${hasActivePrice(p.price) ? '1' : '0'}">
+ ${isInstalled ? 'Installed ✓' : hasActivePrice(p.price) ? `Buy ${escapeHtml(formatAssetPrice(p.price))}` : 'Add to Agent'}
</button>
</div>
</div>`;
diff --git a/vercel.json b/vercel.json
index 0b8347a55..fd138c411 100644
--- a/vercel.json
+++ b/vercel.json
@@ -386,7 +386,7 @@
"dest": "/dashboard/x402.html"
},
{
- "src": "/dashboard/(agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|earnings|account)/?",
+ "src": "/dashboard/(agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|withdrawals|earnings|account)/?",
"dest": "/dashboard/index.html"
},
{
@@ -493,6 +493,14 @@
"src": "/api/marketplace/purchase/([^/]+)",
"dest": "/api/marketplace/purchase?reference=$1"
},
+ {
+ "src": "/api/marketplace/buy-asset/([^/]+)/confirm",
+ "dest": "/api/marketplace/buy-asset?reference=$1&op=confirm"
+ },
+ {
+ "src": "/api/marketplace/buy-asset/([^/]+)",
+ "dest": "/api/marketplace/buy-asset?reference=$1"
+ },
{
"src": "/marketplace",
"dest": "/marketplace.html"
diff --git a/vite.config.js b/vite.config.js
index 527cb6d49..1caa48872 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -451,7 +451,7 @@ const appConfig = {
// /dashboard/<tab> and /dashboard/edit/<id> → SPA index
else if (
!filePath &&
- /^\/dashboard\/(?:agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|earnings|account)\/?$/.test(
+ /^\/dashboard\/(?:agents|avatars|create|upload|animations|widgets|embed|keys|mcp|monetization|payments|subscriptions|billing|revenue|withdrawals|earnings|account)\/?$/.test(
path,
)
)