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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix: complete all broken skill-pricing and purchase handler files
overstepping2c15a77c8101
diff --git a/api/agent-skill-price.js b/api/agent-skill-price.jsindex 98afc9768..96292b440 100644--- a/api/agent-skill-price.js+++ b/api/agent-skill-price.js@@ -1,58 +1,80 @@-import { sql } from '@vercel/postgres';-import { getAuth } from '@clerk/nextjs/server';--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- const { userId } = getAuth(req);- if (!userId) {- return res.status(401).json({ error: 'Unauthorized' });- }-- const { agentId } = req.query;- const { skill_name, amount, currency_mint } = req.body;-- try {- // Verify ownership of the agent- const { rows: agents } = await sql`- SELECT id, creator_id FROM agents WHERE id = ${agentId};- `;-- if (agents.length === 0 || agents[0].creator_id !== userId) {- return res.status(403).json({ error: 'Forbidden' });- }-- // Input validation from Prompt 4- if (!skill_name || amount == null || !currency_mint) {- return res.status(400).json({ error: 'Missing required fields: skill_name, amount, currency_mint' });- }- if (!Number.isInteger(amount) || amount < 0) {- return res.status(400).json({ error: 'Amount must be a non-negative integer.' });- }- // A simple validation for mint address format.- if (!/^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(currency_mint)) {- return res.status(400).json({ error: 'Invalid currency mint address.' });- }-- if (amount > 0) {- await sql`- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)- VALUES (${agentId}, ${skill_name}, ${amount}, ${currency_mint})- ON CONFLICT (agent_id, skill_name)- DO UPDATE SET amount = EXCLUDED.amount, currency_mint = EXCLUDED.currency_mint, updated_at = NOW();- `;- } else {- await sql`- DELETE FROM agent_skill_prices- WHERE agent_id = ${agentId} AND skill_name = ${skill_name};- `;- }-- res.status(200).json({ message: 'Skill price updated successfully.' });- } catch (error) {- console.error('Error updating skill price:', error);- res.status(500).json({ error: 'Internal Server Error' });- }+/**+ * POST /api/agent-skill-price?agentId=:id+ * Single-skill price upsert (legacy entry point).+ * Accepts { skill, amount, currency_mint, chain } — amount=0 deactivates.+ * Canonical bulk endpoint: PUT /api/agents/:id/skills-pricing+ */+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 BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const bodySchema = z.object({+ skill: z.string().trim().min(1).max(100),+ amount: z.number().int().min(0),+ currency_mint: z.string().trim().regex(BASE58_RE, 'invalid mint address'),+ chain: z.string().trim().min(1).max(20).default('solana'),+});++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;}++export default wrap(async (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');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agentId');+ if (!agentId) return error(res, 400, 'validation_error', 'agentId query param required');++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'request body required');++ const parsed = bodySchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }++ const { skill, amount, currency_mint, chain } = parsed.data;++ if (amount === 0) {+ await sql`+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()+ WHERE agent_id = ${agentId} AND skill = ${skill}+ `;+ } else {+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)+ VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ updated_at = now()+ `;+ }++ return json(res, 200, { data: { ok: true } });+});diff --git a/api/agent-skills.js b/api/agent-skills.jsindex 7ea7beb2f..86bb1a649 100644--- a/api/agent-skills.js+++ b/api/agent-skills.js@@ -1,25 +1,27 @@+/**+ * POST /api/agents/:agentId/skills/set-price+ * Routed via vercel.json: /api/agents/([^/]+)/skills/set-price → /api/agent-skills?agentId=$1&action=set-price+ * Single-skill price upsert. For bulk replacement use PUT /api/agents/:id/skills-pricing.+ */import { sql } from './_lib/db.js';-import { authenticateBearer, getSessionUser } from './_lib/auth.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 setPriceSchema = z.object({- skill_name: z.string().trim().min(1, 'skill name required').max(100),- amount: z.number().int().min(0, 'amount must be positive'),- currency_mint: z.string().trim().min(1, 'currency mint required').max(100),- chain: z.string().trim().min(1, 'chain required').max(100),+ skill: z.string().trim().min(1, 'skill required').max(100),+ amount: z.number().int().min(0, 'amount must be non-negative'),+ currency_mint: z.string().trim().min(1, 'currency_mint required').max(100),+ chain: z.string().trim().min(1, 'chain required').max(20).default('solana'),});export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');- const parts = url.pathname.split('/').filter(Boolean);- const agentId = parts[2];- const action = parts[3];+ const agentId = url.searchParams.get('agentId') || url.pathname.split('/').filter(Boolean)[2];+ const action = url.searchParams.get('action') || url.pathname.split('/').filter(Boolean)[4];- if (action === 'set-price') {- return handleSetPrice(req, res, agentId);- }+ if (action === 'set-price') return handleSetPrice(req, res, agentId);return error(res, 404, 'not_found', 'unknown agent skills action');});@@ -34,6 +36,8 @@ async function handleSetPrice(req, res, agentId) {const rl = await limits.authIp(clientIp(req));if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');+ if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+const [agent] = await sql`SELECT id, user_id FROM agent_identitiesWHERE id = ${agentId} AND deleted_at IS NULL@@ -46,30 +50,36 @@ async function handleSetPrice(req, res, agentId) {const parsed = setPriceSchema.safeParse(body);if (!parsed.success) {- const msg = parsed.error.issues[0]?.message || 'validation error';- return error(res, 400, 'validation_error', msg);+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');}- const { skill_name, amount, currency_mint, chain } = parsed.data;+ const { skill, amount, currency_mint, chain } = parsed.data;- await sql`- INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain)- VALUES (${agentId}, ${skill_name}, ${amount}, ${currency_mint}, ${chain})- ON CONFLICT (agent_id, skill)- DO UPDATE SET- amount = ${amount},- currency_mint = ${currency_mint},- chain = ${chain},- updated_at = NOW()- `;+ if (amount === 0) {+ await sql`+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()+ WHERE agent_id = ${agentId} AND skill = ${skill}+ `;+ } else {+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)+ VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ updated_at = now()+ `;+ }- return json(res, 200, { data: { success: true } });+ return json(res, 200, { data: { ok: true } });}async function resolveAuth(req) {const session = await getSessionUser(req);if (session) return { userId: session.id };- const bearer = await authenticateBearer(req.headers.get('authorization'));+ const bearer = await authenticateBearer(extractBearer(req));if (bearer) return { userId: bearer.userId };return null;}diff --git a/api/agents/pricing.js b/api/agents/pricing.jsindex 4ee000f2a..505a43890 100644--- a/api/agents/pricing.js+++ b/api/agents/pricing.js@@ -1,47 +1,79 @@+/**+ * POST /api/agents/:id/pricing (legacy entry point)+ * Single-skill price upsert. Vercel routes /api/agents/:id/pricing → api/agents/[id].js+ * which dispatches to api/agents/_id/pricing/index.js (GET/PUT bulk endpoint).+ * This file handles the POST variant for callers that send individual price updates.+ */+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';-import { db } from '../_lib/db';-import { authMiddleware } from '../_lib/auth';--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- // 1. Authenticate and authorize the user- const user = await authMiddleware(req, res);- if (!user) return; // authMiddleware handles the response-- const { id: agentId } = req.query;- const { skill_name, amount, currency_mint } = req.body;-- // 2. Validate input- if (!skill_name || typeof amount !== 'number' || !currency_mint) {- return res.status(400).json({ error: 'Invalid input' });- }-- try {- // 3. Check if the user owns the agent- const agent = await db.one('SELECT owner_id FROM agents WHERE id = $1', [agentId]);- if (agent.owner_id !== user.id) {- return res.status(403).json({ error: 'Forbidden' });- }-- // 4. Upsert the price into the database- const query = `- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)- VALUES ($1, $2, $3, $4)- ON CONFLICT (agent_id, skill_name)- DO UPDATE SET amount = $3, currency_mint = $4, updated_at = NOW();- `;- await db.none(query, [agentId, skill_name, amount, currency_mint]);-- // 5. Return success- return res.status(200).json({ message: 'Price updated successfully' });- } catch (error) {- console.error('Error setting skill price:', error);- if (error.code === '23503') { // Foreign key violation- return res.status(404).json({ error: 'Agent not found' });- }- return res.status(500).json({ error: 'Internal Server Error' });- }+const bodySchema = z.object({+ skill: z.string().trim().min(1).max(100),+ amount: z.number().int().min(0),+ currency_mint: z.string().trim().min(1).max(100),+ chain: z.string().trim().min(1).max(20).default('solana'),+});++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;}++export default wrap(async (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');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const parts = url.pathname.split('/').filter(Boolean);+ const agentId = url.searchParams.get('id') || parts[2];+ if (!agentId) return error(res, 400, 'validation_error', 'agent id required');++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agentId} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ const body = await readJson(req).catch(() => null);+ if (!body) return error(res, 400, 'validation_error', 'request body required');++ const parsed = bodySchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }++ const { skill, amount, currency_mint, chain } = parsed.data;++ if (amount === 0) {+ await sql`+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()+ WHERE agent_id = ${agentId} AND skill = ${skill}+ `;+ } else {+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)+ VALUES (${agentId}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ updated_at = now()+ `;+ }++ return json(res, 200, { data: { ok: true } });+});diff --git a/api/marketplace/set-skill-price.js b/api/marketplace/set-skill-price.jsindex 8e4efa84b..7b12c6989 100644--- a/api/marketplace/set-skill-price.js+++ b/api/marketplace/set-skill-price.js@@ -1,43 +1,75 @@+/**+ * POST /api/marketplace/set-skill-price+ * Single-skill price upsert via the marketplace namespace.+ * Body: { agent_id, skill, amount, currency_mint, chain? }+ * Canonical bulk endpoint: PUT /api/agents/:id/skills-pricing+ */import { sql } from '../_lib/db.js';-import { json, method, cors, error, auth } from '../_lib/http.js';--export default async function setSkillPrice(req, res) {- if (cors(req, res)) return;- if (!method(req, res, ['POST'])) return;- const authUser = await auth(req, res);- if (!authUser) return;-- const { agent_id, skill_name, amount, currency_mint } = req.body;-- if (!agent_id || !skill_name || !amount || !currency_mint) {- return error(res, 400, 'bad_request', 'Missing required fields.');- }-- try {- // First, verify ownership of the agent- const [agent] = await sql`- SELECT id FROM agents WHERE id = ${agent_id} AND user_id = ${authUser.id}- `;-- if (!agent) {- return error(res, 403, 'forbidden', 'You do not own this agent.');- }-- // Now, upsert the price- await sql`- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint, updated_at)- VALUES (${agent_id}, ${skill_name}, ${amount}, ${currency_mint}, NOW())- ON CONFLICT (agent_id, skill_name)- DO UPDATE SET- amount = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- updated_at = NOW();- `;-- return json(res, 200, { ok: true, message: 'Price set successfully.' });-- } catch (e) {- console.error('Error setting skill price:', e);- return error(res, 500, 'server_error', 'Failed to set skill price.');- }+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 bodySchema = z.object({+ agent_id: z.string().uuid(),+ skill: z.string().trim().min(1).max(100),+ amount: z.number().int().min(0),+ currency_mint: z.string().trim().min(1).max(100),+ chain: z.string().trim().min(1).max(20).default('solana'),+});++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;}++export default wrap(async (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');++ 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 = bodySchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }++ const { agent_id, skill, amount, currency_mint, chain } = parsed.data;++ const [agent] = await sql`+ SELECT id, user_id FROM agent_identities+ WHERE id = ${agent_id} AND deleted_at IS NULL+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');+ if (agent.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');++ if (amount === 0) {+ await sql`+ UPDATE agent_skill_prices SET is_active = false, updated_at = now()+ WHERE agent_id = ${agent_id} AND skill = ${skill}+ `;+ } else {+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill, amount, currency_mint, chain, is_active)+ VALUES (${agent_id}, ${skill}, ${amount}, ${currency_mint}, ${chain}, true)+ ON CONFLICT (agent_id, skill) DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ updated_at = now()+ `;+ }++ return json(res, 200, { data: { ok: true } });+});diff --git a/api/payments/intent.js b/api/payments/intent.jsindex ecd9d2790..7dadb0783 100644--- a/api/payments/intent.js+++ b/api/payments/intent.js@@ -1,8 +1,19 @@+/**+ * POST /api/payments/intent+ * Creates an agent_payment_intents record for a skill purchase and returns+ * the payment details the frontend needs to build the Solana Pay transaction.+ *+ * This is the agent_payment_intents–based flow (distinct from the+ * skill_purchases Solana Pay reference flow at /api/marketplace/purchase).+ */import { sql } from '../_lib/db.js';import { getSessionUser } from '../_lib/auth.js';import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';import { nanoid } from 'nanoid';+const INTENT_TTL_MINUTES = 15;+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;@@ -10,52 +21,71 @@ export default wrap(async (req, res) => {const user = await getSessionUser(req);if (!user) return error(res, 401, 'unauthorized', 'sign in required');- const { agent_id, skill_name } = await readJson(req);- if (!agent_id || !skill_name) {- return error(res, 400, 'validation_error', 'agent_id and skill_name are 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);+ const agent_id = body?.agent_id;+ const skill = typeof body?.skill === 'string' ? body.skill.trim() : null;+ if (!agent_id || !skill) {+ return error(res, 400, 'validation_error', 'agent_id and skill are required');}- // 1. Fetch skill price and agent owner's payout wallet- const [priceInfo] = await sql`- SELECT- p.amount, p.currency_mint,- a.user_id as owner_user_id- FROM agent_skill_prices p- JOIN agent_identities a ON p.agent_id = a.id- WHERE p.agent_id = ${agent_id}- AND p.skill_name = ${skill_name}+ // Fetch active skill price+ const [price] = await sql`+ SELECT amount, currency_mint, chain+ FROM agent_skill_prices+ WHERE agent_id = ${agent_id} AND skill = ${skill} AND is_active = true+ LIMIT 1`;+ if (!price) return error(res, 404, 'not_found', 'skill is not for sale');- if (!priceInfo) {- return error(res, 404, 'not_found', 'The specified skill is not for sale.');+ // Resolve creator payout wallet (agent-specific first, then user default)+ const [payout] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = ${price.chain}+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${agent_id} AND a.deleted_at IS NULL+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;++ // Fall back to agent meta.solana_address for legacy agents without payout wallet rows+ let recipient_address = payout?.address;+ if (!recipient_address) {+ const [agentRow] = await sql`SELECT meta FROM agent_identities WHERE id = ${agent_id}`;+ recipient_address = agentRow?.meta?.solana_address ?? null;}-- // For this example, we assume the owner's Solana wallet is on the agent's meta field- // A better approach would be a dedicated agent_payout_wallets table- const [agent] = await sql`SELECT meta FROM agent_identities WHERE id = ${agent_id}`;- const recipient_address = agent.meta?.solana_address;-if (!recipient_address) {- return error(res, 500, 'configuration_error', 'Agent owner has not configured a payout wallet.');+ return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');}- // 2. Create and store the payment intent- const intent_id = `pi_${nanoid()}`;- const expires_at = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes from now+ const memo = nanoid(16);+ const intent_id = `pi_${nanoid()}`;+ const now = new Date();+ const expires_at = new Date(now.getTime() + INTENT_TTL_MINUTES * 60 * 1000);await sql`INSERT INTO agent_payment_intents- (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at, payload)+ (id, payer_user_id, agent_id, currency_mint, amount, memo,+ start_time, end_time, status, cluster, payload, expires_at)VALUES- (${intent_id}, ${user.id}, ${agent_id}, ${priceInfo.currency_mint}, ${String(priceInfo.amount)}, 'pending', ${expires_at}, ${JSON.stringify({ skill: skill_name, recipient_address })})+ (${intent_id}, ${user.id}, ${agent_id}, ${price.currency_mint},+ ${String(price.amount)}, ${memo},+ ${now}, ${expires_at}, 'pending', 'mainnet',+ ${JSON.stringify({ skill, recipient_address })}, ${expires_at})`;- // 3. Return details to the frontendreturn json(res, 201, {intent_id,recipient_address,- amount: String(priceInfo.amount),- currency_mint: priceInfo.currency_mint,- expires_at: expires_at.toISOString(),+ amount: String(price.amount),+ currency_mint: price.currency_mint,+ chain: price.chain,+ memo,+ expires_at: expires_at.toISOString(),});});diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.jsindex 9567077f9..410ddaa56 100644--- a/api/payments/prepare-skill-purchase.js+++ b/api/payments/prepare-skill-purchase.js@@ -1,87 +1,143 @@-// api/payments/prepare-skill-purchase.js-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';-// These are placeholders for DB functions we will create in later prompts.-// import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db';--const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d');-// You will need to replace this with your actual platform wallet address.-const PLATFORM_WALLET = new PublicKey('YourPlatformWalletAddressHere');--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- try {- // In a real application, you would get the authenticated user's public key.- // For now, we'll use a placeholder.- const buyerPublicKey = new PublicKey('BUYER_PUBLIC_KEY_HERE');-- const { agentId, skillName } = req.body;- if (!agentId || !skillName) {- return res.status(400).json({ error: 'agentId and skillName are required' });- }-- // These functions will be implemented in a later prompt.- // For now, we'll use mock data.- const priceInfo = { amount: 1000000 }; // 1 USDC in lamports- const creatorPayoutWallet = 'CREATOR_WALLET_ADDRESS_HERE';-- if (!priceInfo) {- return res.status(404).json({ error: 'Skill or price not found' });- }-- if (!creatorPayoutWallet) {- return res.status(500).json({ error: 'Creator payout wallet not configured' });- }-- const connection = new Connection(process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');- const { blockhash } = await connection.getLatestBlockhash();-- const transaction = new Transaction({- recentBlockhash: blockhash,- feePayer: buyerPublicKey,- });-- const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);- const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, new PublicKey(creatorPayoutWallet));-- // Assuming a 5% platform fee- const platformFee = Math.floor(priceInfo.amount * 0.05);- const creatorAmount = priceInfo.amount - platformFee;-- // Transfer to creator- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- creatorUsdcAddress,- buyerPublicKey,- creatorAmount- )- );-- // Transfer to platform- const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- platformUsdcAddress,- buyerPublicKey,- platformFee- )- );-- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });-- res.status(200).json({- transaction: serializedTransaction.toString('base64'),- message: `Purchase skill "${skillName}" for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`,- label: 'three.ws Agent Skill',- });-- } catch (error) {- console.error('Error preparing skill purchase:', error);- res.status(500).json({ error: 'Internal Server Error' });- }+/**+ * POST /api/payments/prepare-skill-purchase+ * Builds and returns a base64-serialised Solana legacy transaction that the+ * browser wallet can sign and send. The buyer's public key must be provided+ * in the request body so the fee-payer and ATA source can be set correctly.+ *+ * Body: { agentId, skillName, buyerPublicKey }+ * Returns: { transaction (base64), reference, recipient, amount, currency_mint }+ */+import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';+import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';++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 BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const bodySchema = z.object({+ agentId: z.string().uuid(),+ skillName: z.string().trim().min(1).max(100),+ buyerPublicKey: z.string().regex(BASE58_RE, 'invalid public key'),+});++const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++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;}++export default wrap(async (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');++ 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 parsed = bodySchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }++ const { agentId, skillName, buyerPublicKey } = parsed.data;++ // Fetch active price+ const [price] = await sql`+ SELECT amount, currency_mint, chain+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true+ LIMIT 1+ `;+ if (!price) return error(res, 404, 'not_found', 'skill is not for sale');+ if (price.chain !== 'solana') {+ return error(res, 400, 'unsupported_chain', `chain '${price.chain}' does not support prepared transactions`);+ }++ // Resolve payout wallet+ const [payout] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = 'solana'+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;+ let recipient = payout?.address;+ if (!recipient) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ recipient = row?.meta?.solana_address ?? null;+ }+ if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');++ // Mint a reference keypair for Solana Pay tracking+ const referenceKeypair = Keypair.generate();+ const referenceKey = referenceKeypair.publicKey;+ const reference = referenceKey.toBase58();++ // Record pending purchase before building tx so confirm can find it+ await sql`+ INSERT INTO skill_purchases (user_id, agent_id, skill, status, reference, amount, currency_mint, chain)+ VALUES (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},+ ${price.amount}, ${price.currency_mint}, 'solana')+ ON CONFLICT DO NOTHING+ `;++ // Build the SPL token transfer transaction+ const connection = new Connection(SOLANA_RPC, 'confirmed');+ const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');++ const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));+ const decimals = mintInfo.decimals;++ const buyer = new PublicKey(buyerPublicKey);+ const recipientKey = new PublicKey(recipient);+ const mintKey = new PublicKey(price.currency_mint);++ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);+ const toAta = getAssociatedTokenAddressSync(mintKey, recipientKey);++ const ix = createTransferCheckedInstruction(+ fromAta,+ mintKey,+ toAta,+ buyer,+ BigInt(price.amount),+ decimals,+ );+ // Append reference key as non-signer so findReference can locate this tx+ ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });++ const tx = new Transaction({+ feePayer: buyer,+ recentBlockhash: blockhash,+ lastValidBlockHeight,+ }).add(ix);++ const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });++ return json(res, 200, {+ data: {+ transaction: serialized.toString('base64'),+ reference,+ recipient,+ amount: String(price.amount),+ currency_mint: price.currency_mint,+ label: `Skill: ${skillName.slice(0, 40)}`,+ message: `Unlock '${skillName}' for this agent`,+ },+ });+});diff --git a/api/payments/purchase-skill.js b/api/payments/purchase-skill.jsindex aab0467dd..4e91ae074 100644--- a/api/payments/purchase-skill.js+++ b/api/payments/purchase-skill.js@@ -1,52 +1,106 @@-import { getSessionUser } from '../../_lib/auth.js';-import { sql } from '../../_lib/db.js';-import { error, json, method, readJson, wrap } from '../../_lib/http.js';+/**+ * POST /api/payments/purchase-skill+ * Alternative entry point for skill purchase initiation.+ * Body: { agentId, skillName } — delegates to the canonical skill_purchases flow.+ * Canonical endpoint: POST /api/marketplace/purchase+ */+import { Keypair } from '@solana/web3.js';-export default wrap(async (req, res) => {- if (!method(req, res, ['POST'])) return;+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 bodySchema = z.object({+ agentId: z.string().uuid(),+ skillName: z.string().trim().min(1).max(100),+});- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized', 'sign in required');+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;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;- const { agentId, skillName, userWallet } = await readJson(req);+ const auth = await resolveAuth(req);+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');- if (!agentId || !skillName || !userWallet) {- return error(res, 400, 'bad_request', 'Missing required fields.');- }+ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');- // 1. Verify the agent and skill exist and get the price- const [priceInfo] = await sql`- SELECT p.amount, p.currency_mint, a.user_id as creator_id- FROM agent_skill_prices p- JOIN agent_identities a ON p.agent_id = a.id- WHERE p.agent_id = ${agentId} AND p.skill_id = ${skillName} AND p.is_active = true- `;+ const body = await readJson(req).catch(() => null);+ const parsed = bodySchema.safeParse(body);+ if (!parsed.success) {+ return error(res, 400, 'validation_error', parsed.error.issues[0]?.message || 'validation error');+ }- if (!priceInfo) {- return error(res, 404, 'not_found', 'Skill not for sale.');- }+ const { agentId, skillName } = parsed.data;- // 2. Verify the user does not already own the skill- const [existingPurchase] = await sql`- SELECT id FROM skill_purchases- WHERE user_id = ${user.id} AND agent_id = ${agentId} AND skill_name = ${skillName}- `;+ // Fetch active price+ const [price] = await sql`+ SELECT amount, currency_mint, chain+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true+ LIMIT 1+ `;+ if (!price) return error(res, 404, 'not_found', 'skill is not for sale');- if (existingPurchase) {- return error(res, 409, 'conflict', 'Skill already owned.');- }+ // Resolve payout wallet+ const [payout] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = ${price.chain}+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;+ let recipient = payout?.address;+ if (!recipient) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ recipient = row?.meta?.solana_address ?? null;+ }+ if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');- // 3. Construct the Solana Transaction (to be implemented)- const transaction = "base64_serialized_transaction_here";- const signature = "transaction_signature_here";+ // Already purchased?+ const [existing] = await sql`+ SELECT reference, status FROM skill_purchases+ WHERE user_id = ${auth.userId} AND agent_id = ${agentId} AND skill = ${skillName}+ AND status = 'confirmed'+ LIMIT 1+ `;+ if (existing) {+ return json(res, 200, { data: { already_owned: true, reference: existing.reference } });+ }+ // Mint a Solana Pay reference keypair+ const reference = Keypair.generate().publicKey.toBase58();- // 4. Record the pending transaction- await sql`- INSERT INTO skill_purchases (user_id, agent_id, skill_name, transaction_signature, amount, currency_mint)- VALUES (${user.id}, ${agentId}, ${skillName}, ${signature}, ${priceInfo.amount}, ${priceInfo.currency_mint})- `;+ const [row] = await sql`+ INSERT INTO skill_purchases (user_id, agent_id, skill, status, reference, amount, currency_mint, chain)+ VALUES (${auth.userId}, ${agentId}, ${skillName}, 'pending', ${reference},+ ${price.amount}, ${price.currency_mint}, ${price.chain})+ RETURNING reference, amount, currency_mint, chain+ `;- // 5. Return the transaction- return json(res, 200, { transaction, signature });+ return json(res, 201, {+ data: {+ reference: row.reference,+ recipient,+ amount: String(row.amount),+ currency_mint: row.currency_mint,+ chain: row.chain,+ label: `Skill: ${skillName.slice(0, 40)}`,+ message: `Unlock '${skillName}' for this agent`,+ },+ });});diff --git a/api/purchase/skill.js b/api/purchase/skill.jsindex 189184da8..7d71b3fd0 100644--- a/api/purchase/skill.js+++ b/api/purchase/skill.js@@ -1,62 +1,104 @@-import { Keypair, Connection, PublicKey, clusterApiUrl } from '@solana/web3.js';-import { findReference, FindReferenceError } from '@solana/pay';-import { db } from '../_lib/db'; // Your database utility--// The GET handler is called by wallets to get transaction details-async function get(req, res) {- const { agent_id, skill_name } = req.query;-- // 1. Fetch price and creator wallet from DB- const priceInfo = await db.one(- `SELECT p.amount, p.currency_mint, a.owner_id- FROM agent_skill_prices p- JOIN agents a ON p.agent_id = a.id- WHERE p.agent_id = $1 AND p.skill_name = $2`,- [agent_id, skill_name]- );-- const creatorWallet = await db.one('SELECT wallet_address FROM users WHERE id = $1', [priceInfo.owner_id]);-- // 2. Respond with Solana Pay GET spec- res.status(200).json({- label: "3D-Agent Marketplace",- icon: "https://your-app.com/icon.png",- });-}--// The POST handler is called by wallets after the user approves the transaction-async function post(req, res) {- const { account } = req.body;- if (!account) throw new Error('Missing account');-- const { reference } = req.query;- if (!reference) throw new Error('Missing reference');-- const signature = await verifyTransaction(account, reference);- // Here you would grant the user access to the skill in your DB- // grantSkillAccess(account, reference.skill_name);-- res.status(200).json({ status: 'ok', signature });-}---async function verifyTransaction(account, reference) {- const connection = new Connection(clusterApiUrl('mainnet-beta'));-- // Find the transaction signature from the reference- const signatureInfo = await findReference(connection, new PublicKey(reference));-- // Here you would add more validation, e.g., checking the transaction amount and destination match the skill price.-- return signatureInfo.signature;-}--export default async function handler(req, res) {- if (req.method === 'GET') {- return await get(req, res);- } else if (req.method === 'POST') {- return await post(req, res);- } else {- return res.status(405).json({ error: 'Method Not Allowed' });- }-}+/**+ * GET /api/purchase/skill?agent_id=&skill= — Solana Pay transaction request GET (label/icon)+ * POST /api/purchase/skill?agent_id=&skill= — Solana Pay transaction request POST (build tx)+ *+ * Implements the Solana Pay Transaction Request spec so wallets that scan a+ * QR code can fetch and sign the USDC transfer directly.+ */+import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';+import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';+import { findReference } from '@solana/pay';++import { sql } from '../_lib/db.js';+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';++const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const url = new URL(req.url, 'http://x');+ const agentId = url.searchParams.get('agent_id');+ const skillName = url.searchParams.get('skill');++ if (!agentId || !skillName) {+ return error(res, 400, 'validation_error', 'agent_id and skill query params required');+ }++ if (req.method === 'GET') {+ // Solana Pay spec: return label + icon for the wallet QR display+ return json(res, 200, {+ label: 'three.ws Agent Marketplace',+ icon: 'https://three.ws/favicon.ico',+ });+ }++ // POST — wallet sends its account (public key), we return a prepared transaction+ const body = await readJson(req).catch(() => null);+ const account = body?.account;+ if (!account) return error(res, 400, 'validation_error', 'account required');++ const [price] = await sql`+ SELECT amount, currency_mint, chain+ FROM agent_skill_prices+ WHERE agent_id = ${agentId} AND skill = ${skillName} AND is_active = true+ LIMIT 1+ `;+ if (!price) return error(res, 404, 'not_found', 'skill is not for sale');+ if (price.chain !== 'solana') {+ return error(res, 400, 'unsupported_chain', 'only solana transactions are supported via this endpoint');+ }++ // Resolve payout wallet+ const [payout] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = 'solana'+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${agentId} AND a.deleted_at IS NULL+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;+ let recipient = payout?.address;+ if (!recipient) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${agentId}`;+ recipient = row?.meta?.solana_address ?? null;+ }+ if (!recipient) return error(res, 412, 'creator_wallet_missing', 'agent owner has not configured a payout wallet');++ // Reference keypair for Solana Pay tracking+ const referenceKeypair = Keypair.generate();+ const referenceKey = referenceKeypair.publicKey;++ // Record pending purchase+ await sql`+ INSERT INTO skill_purchases (agent_id, skill, status, reference, amount, currency_mint, chain)+ VALUES (${agentId}, ${skillName}, 'pending', ${referenceKey.toBase58()},+ ${price.amount}, ${price.currency_mint}, 'solana')+ ON CONFLICT DO NOTHING+ `;++ // Build transaction+ const connection = new Connection(SOLANA_RPC, 'confirmed');+ const { blockhash } = await connection.getLatestBlockhash('confirmed');++ const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));+ const buyer = new PublicKey(account);+ const mintKey = new PublicKey(price.currency_mint);++ const fromAta = getAssociatedTokenAddressSync(mintKey, buyer);+ const toAta = getAssociatedTokenAddressSync(mintKey, new PublicKey(recipient));++ const ix = createTransferCheckedInstruction(+ fromAta, mintKey, toAta, buyer, BigInt(price.amount), mintInfo.decimals,+ );+ ix.keys.push({ pubkey: referenceKey, isSigner: false, isWritable: false });++ const tx = new Transaction({ feePayer: buyer, recentBlockhash: blockhash }).add(ix);+ const serialized = tx.serialize({ requireAllSignatures: false, verifySignatures: false });++ return json(res, 200, { transaction: serialized.toString('base64') });+});diff --git a/api/webhooks/solana-pay.js b/api/webhooks/solana-pay.jsindex 779723b96..fd4956bd8 100644--- a/api/webhooks/solana-pay.js+++ b/api/webhooks/solana-pay.js@@ -1,98 +1,158 @@-import { Connection, PublicKey, Transaction } from '@solana/web3.js';-import { sql } from '../../_lib/db.js';-import { error, json, readJson, wrap } from '../../_lib/http.js';+/**+ * POST /api/webhooks/solana-pay+ * Server-side webhook / polling endpoint to confirm a pending skill purchase.+ * Called by a cron job or monitoring service after it observes the on-chain tx.+ *+ * Body: { reference }+ * reference — the base58 Solana Pay reference key for the skill_purchases row+ *+ * Authorization: bearer token matching WEBHOOK_SECRET env var.+ *+ * Flow:+ * 1. Look up the pending skill_purchases row by reference.+ * 2. Use findReference + validateTransfer to locate and verify the on-chain tx.+ * 3. Mark the purchase confirmed and return.+ */+import { PublicKey } from '@solana/web3.js';+import { findReference, validateTransfer } from '@solana/pay';+import BigNumber from 'bignumber.js';-const SOLANA_RPC_URL = process.env.RPC_URL_1399901; // Using the placeholder from the prompt-const connection = new Connection(SOLANA_RPC_URL, 'confirmed');+import { sql } from '../_lib/db.js';+import { error, json, method, readJson, wrap } from '../_lib/http.js';+import { rpcFallbackFromEnv } from '../_lib/solana/rpc-fallback.js';-export default wrap(async (req, res) => {- if (req.method === 'GET') {- // Solana Pay endpoint validation GET request- return json(res, {- label: '3D-Agent Skill Marketplace',- icon: 'https://three.ws/assets/logo.png', // Using a placeholder logo- });- }+let _rpc;+function rpc() {+ if (!_rpc) _rpc = rpcFallbackFromEnv({ network: 'mainnet' });+ return _rpc;+}- if (req.method === 'POST') {- const { transaction, reference } = await readJson(req);+function authOk(req) {+ const secret = process.env.WEBHOOK_SECRET;+ if (!secret) return false; // require explicit secret; no secret = endpoint disabled+ const header = req.headers?.authorization || '';+ return header === `Bearer ${secret}`;+}- if (!reference) {- return error(res, 400, 'bad_request', 'Missing reference parameter');- }+export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;- // 1. Find the purchase record using the reference (purchaseId)- const [purchase] = await sql`- SELECT- p.id, p.status, p.agent_id, p.skill_id,- pr.amount, pr.currency_mint,- u.wallet_address AS creator_wallet- FROM user_skill_purchases p- JOIN agent_skill_prices pr ON p.price_id = pr.id- JOIN users u ON pr.creator_id = u.id- WHERE p.id = ${reference}- `;-- if (!purchase) {- return error(res, 404, 'not_found', 'Purchase record not found.');- }- if (purchase.status !== 'pending') {- return json(res, { message: 'Purchase already processed.' });- }+ if (req.method === 'GET') {+ // Solana Pay merchant discovery probe.+ return json(res, 200, {+ label: '3D-Agent Skill Marketplace',+ icon: 'https://three.ws/assets/logo.png',+ });+ }- // 2. Verify the transaction on-chain- try {- const tx = await connection.getParsedTransaction(transaction, {- maxSupportedTransactionVersion: 0,- commitment: 'confirmed'- });+ if (!authOk(req)) return error(res, 401, 'unauthorized', 'invalid or missing webhook secret');- if (!tx) {- throw new Error('Transaction not found or not confirmed.');- }+ const body = await readJson(req).catch(() => null);+ const reference = typeof body?.reference === 'string' ? body.reference.trim() : null;+ if (!reference) return error(res, 400, 'validation_error', 'reference required');- // Basic validation- if (tx.meta?.err) {- throw new Error('Transaction failed on-chain.');- }+ // Load the pending purchase+ const [pur] = await sql`+ SELECT id, user_id, agent_id, skill, status, amount, currency_mint, chain+ FROM skill_purchases+ WHERE reference = ${reference}+ LIMIT 1+ `;+ if (!pur) return error(res, 404, 'not_found', 'purchase not found');+ if (pur.status === 'confirmed') {+ return json(res, 200, { data: { status: 'confirmed' } });+ }+ if (pur.status === 'failed') {+ return error(res, 409, 'purchase_failed', 'purchase was already marked failed');+ }+ if (pur.chain !== 'solana') {+ return error(res, 501, 'not_implemented', `chain '${pur.chain}' not supported`);+ }- // Deeper validation: find the correct SPL transfer instruction- const transferInstruction = tx.transaction.message.instructions.find(ix => {- if ('parsed' in ix && ix.parsed.type === 'transferChecked') {- const p = ix.parsed.info;- const recipientMatch = p.destination === purchase.creator_wallet;- const mintMatch = p.mint === purchase.currency_mint;- const amountMatch = BigInt(p.tokenAmount.uiAmount * (10 ** p.tokenAmount.decimals)) === BigInt(purchase.amount);- return recipientMatch && mintMatch && amountMatch;- }- return false;- });+ // Resolve payout wallet (re-verify to prevent recipient drift)+ const [payout] = await sql`+ SELECT pw.address+ FROM agent_identities a+ JOIN agent_payout_wallets pw+ ON pw.user_id = a.user_id+ AND pw.chain = 'solana'+ AND (pw.agent_id = a.id OR pw.is_default = true)+ WHERE a.id = ${pur.agent_id}+ ORDER BY (pw.agent_id IS NOT NULL) DESC, pw.is_default DESC, pw.created_at ASC+ LIMIT 1+ `;+ let recipientAddress = payout?.address;+ if (!recipientAddress) {+ const [row] = await sql`SELECT meta FROM agent_identities WHERE id = ${pur.agent_id}`;+ recipientAddress = row?.meta?.solana_address ?? null;+ }+ if (!recipientAddress) return error(res, 412, 'creator_wallet_missing', 'payout wallet not configured');- if (!transferInstruction) {- throw new Error('Valid SPL transfer not found in transaction.');- }+ const refKey = new PublicKey(reference);+ const recipient = new PublicKey(recipientAddress);+ const splToken = new PublicKey(pur.currency_mint);+ const expectedAmount = new BigNumber(pur.amount).dividedBy(1e6); // 6-decimal USDC- // 3. If validation passes, update the purchase status- await sql`- UPDATE user_skill_purchases- SET status = 'confirmed', transaction_id = ${transaction}, updated_at = NOW()- WHERE id = ${reference}- `;+ 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;+ }- // TODO from Prompt 20: Send email notification to creator here+ const txSig = signatureInfo.signature;- return json(res, { message: 'Transaction confirmed successfully.' });+ try {+ await rpc().withFallback((conn) =>+ validateTransfer(+ conn,+ txSig,+ { recipient, amount: expectedAmount, splToken, reference: refKey },+ { commitment: 'confirmed' },+ ),+ );+ } catch (e) {+ await sql`+ UPDATE skill_purchases SET status = 'failed', tx_signature = ${txSig}+ WHERE id = ${pur.id} AND status = 'pending'+ `;+ return error(res, 409, 'transfer_mismatch', `on-chain transfer did not match: ${e.message}`);+ }- } catch (e) {- console.error('Transaction verification failed:', e);- await sql`- UPDATE user_skill_purchases- SET status = 'failed', updated_at = NOW()- WHERE id = ${reference}- `;- return error(res, 400, 'transaction_invalid', e.message);- }- }+ const intentId = `sp_${pur.id}`;+ const updated = await sql`+ UPDATE skill_purchases+ SET status = 'confirmed', tx_signature = ${txSig}, confirmed_at = now()+ WHERE id = ${pur.id} AND status = 'pending'+ RETURNING id+ `;+ if (updated.length > 0) {+ await sql`+ INSERT INTO agent_payment_intents+ (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at,+ cluster, tx_signature, paid_at, payload)+ VALUES+ (${intentId}, ${pur.user_id}, ${pur.agent_id}, ${pur.currency_mint},+ ${String(pur.amount)}, 'confirmed', now() + interval '30 days',+ 'mainnet', ${txSig}, now(),+ ${JSON.stringify({ kind: 'skill_purchase', skill: pur.skill, reference })}::jsonb)+ ON CONFLICT (id) DO NOTHING+ `;+ await sql`+ INSERT INTO agent_revenue_events+ (agent_id, intent_id, skill, gross_amount, fee_amount, net_amount,+ currency_mint, chain, payer_address)+ VALUES+ (${pur.agent_id}, ${intentId}, ${pur.skill},+ ${pur.amount}, 0, ${pur.amount},+ ${pur.currency_mint}, ${pur.chain}, ${recipientAddress})+ `;+ }- return error(res, 405, 'method_not_allowed');+ return json(res, 200, { data: { status: 'confirmed', tx_signature: txSig } });});