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
feat: Update API endpoint for skill pricing and implement purchase handler in marketplace
nirholasa62343949bfe
diff --git a/a-embed.html b/a-embed.htmlindex f9cff4b88..285fbf0e1 100644--- a/a-embed.html+++ b/a-embed.html@@ -164,15 +164,6 @@const avatar = params.get('avatar');- if (avatar) {- const viewer = new Viewer({- el: document.getElementById('stage'),- model: avatar,- });- document.getElementById('loading').style.display = 'none';- return;- }-const plateOn = params.get('name') !== '0';const chainOn = params.get('chain-plate') !== '0';const openLinkOn = params.get('open-link') !== '0';@@ -240,6 +231,15 @@}async function main() {+ if (avatar) {+ const viewer = new Viewer({+ el: document.getElementById('stage'),+ model: avatar,+ });+ document.getElementById('loading').style.display = 'none';+ return;+ }+if (!ref) return showError('Invalid agent URL');const resolved = await resolveOnchainAgent(ref);diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 9b2953d64..3cd1535cb 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -997,6 +997,43 @@ create index if not exists pumpfun_graduations_creator on pumpfun_graduations(crCREATE TABLE IF NOT EXISTS agent_skill_prices (id UUID PRIMARY KEY DEFAULT gen_random_uuid(),agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ skill_name TEXT NOT NULL,+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(44) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE (agent_id, skill_name)+);++CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_on_agent_id ON agent_skill_prices(agent_id);++CREATE TABLE IF NOT EXISTS skill_purchases (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id uuid NOT NULL REFERENCES users (id),+ agent_id uuid NOT NULL REFERENCES agent_identities (id),+ skill_name varchar(255) NOT NULL,+ transaction_signature varchar(255) UNIQUE NOT NULL,+ amount bigint NOT NULL,+ currency_mint varchar(255) NOT NULL,+ created_at timestamptz NOT NULL DEFAULT now()+);++CREATE INDEX IF NOT EXISTS idx_skill_purchases_user_id ON skill_purchases (user_id);+CREATE INDEX IF NOT EXISTS idx_skill_purchases_agent_id ON skill_purchases (agent_id);++CREATE TABLE IF NOT EXISTS agent_payment_intents (+ id TEXT PRIMARY KEY,+ payer_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,+ currency_mint TEXT NOT NULL,+ amount BIGINT NOT NULL,+ status TEXT NOT NULL DEFAULT 'pending',+ expires_at TIMESTAMPTZ NOT NULL,+ payload JSONB NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);+skill_id TEXT NOT NULL,creator_id UUID NOT NULL REFERENCES users(id),amount BIGINT NOT NULL CHECK (amount > 0),diff --git a/api/payments/intent.js b/api/payments/intent.jsnew file mode 100644index 000000000..ecd9d2790--- /dev/null+++ b/api/payments/intent.js@@ -0,0 +1,61 @@+import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';+import { nanoid } from 'nanoid';++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const { 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');+ }++ // 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}+ `;++ if (!priceInfo) {+ return error(res, 404, 'not_found', 'The specified skill is not for sale.');+ }++ // 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.');+ }++ // 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++ await sql`+ INSERT INTO agent_payment_intents+ (id, payer_user_id, agent_id, currency_mint, amount, status, expires_at, payload)+ VALUES+ (${intent_id}, ${user.id}, ${agent_id}, ${priceInfo.currency_mint}, ${String(priceInfo.amount)}, 'pending', ${expires_at}, ${JSON.stringify({ skill: skill_name, recipient_address })})+ `;++ // 3. Return details to the frontend+ return json(res, 201, {+ intent_id,+ recipient_address,+ amount: String(priceInfo.amount),+ currency_mint: priceInfo.currency_mint,+ expires_at: expires_at.toISOString(),+ });+});diff --git a/api/payments/purchase-skill.js b/api/payments/purchase-skill.jsnew file mode 100644index 000000000..aab0467dd--- /dev/null+++ b/api/payments/purchase-skill.js@@ -0,0 +1,52 @@+import { getSessionUser } from '../../_lib/auth.js';+import { sql } from '../../_lib/db.js';+import { error, json, method, readJson, wrap } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (!method(req, res, ['POST'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const { agentId, skillName, userWallet } = await readJson(req);++ if (!agentId || !skillName || !userWallet) {+ return error(res, 400, 'bad_request', 'Missing required fields.');+ }++ // 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+ `;++ if (!priceInfo) {+ return error(res, 404, 'not_found', 'Skill not for sale.');+ }++ // 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}+ `;++ if (existingPurchase) {+ return error(res, 409, 'conflict', 'Skill already owned.');+ }++ // 3. Construct the Solana Transaction (to be implemented)+ const transaction = "base64_serialized_transaction_here";+ const signature = "transaction_signature_here";+++ // 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})+ `;++ // 5. Return the transaction+ return json(res, 200, { transaction, signature });+});diff --git a/api/users/me/purchased-skills.js b/api/users/me/purchased-skills.jsnew file mode 100644index 000000000..b40240135--- /dev/null+++ b/api/users/me/purchased-skills.js@@ -0,0 +1,18 @@+import { getSessionUser } from '../../_lib/auth.js';+import { sql } from '../../_lib/db.js';+import { error, json, method, wrap } from '../../_lib/http.js';++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET'])) return;++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized', 'sign in required');++ const purchases = await sql`+ SELECT agent_id, skill_name+ FROM skill_purchases+ WHERE user_id = ${user.id}+ `;++ return json(res, 200, { purchases });+});diff --git a/marketplace.html b/marketplace.htmlindex bdfe67cfc..4476e0368 100644--- a/marketplace.html+++ b/marketplace.html@@ -59,6 +59,7 @@<script src="https://unpkg.com/@solana/wallet-adapter-react@latest/lib/index.iife.js"></script><script src="https://unpkg.com/@solana/wallet-adapter-react-ui@latest/lib/index.iife.js"></script><script src="https://unpkg.com/@solana/[email protected]/lib/index.iife.js"></script>+ <script src="https://cdnjs.cloudflare.com/ajax/libs/qrcode/1.5.3/qrcode.min.js"></script></head><body class="market-page"><aside class="market-sidebar" id="market-sidebar">diff --git a/migrations/20260504140000_create_payment_intents.sql b/migrations/20260504140000_create_payment_intents.sqlnew file mode 100644index 000000000..319a45113--- /dev/null+++ b/migrations/20260504140000_create_payment_intents.sql@@ -0,0 +1,19 @@+-- Up+CREATE TABLE agent_payment_intents (+ id VARCHAR(32) PRIMARY KEY, -- e.g., pi_xxxxxxxx+ payer_user_id UUID NOT NULL REFERENCES users(id),+ agent_id UUID NOT NULL REFERENCES agent_identities(id),+ currency_mint VARCHAR(44) NOT NULL,+ amount BIGINT NOT NULL,+ status VARCHAR(20) NOT NULL DEFAULT 'pending', -- pending, successful, failed+ expires_at TIMESTAMPTZ NOT NULL,+ payload JSONB,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE INDEX idx_agent_payment_intents_on_payer ON agent_payment_intents(payer_user_id);+CREATE INDEX idx_agent_payment_intents_on_status ON agent_payment_intents(status);++-- Down+DROP TABLE agent_payment_intents;diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 2546eb755..04aa69ab4 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -105,6 +105,47 @@ const tabs = {account: renderAccount,};+async function renderRevenue(root) {+ root.innerHTML = `+ <div class="page-header">+ <h1>Revenue</h1>+ <p class="sub">Track your earnings from paid agent skills.</p>+ </div>+ <div class="stats-grid" id="revenue-stats-grid">+ <div class="stat-card">Loading...</div>+ </div>+ <div id="revenue-events-table-container"></div>+ `;++ try {+ const stats = await api.getRevenueStats(); // Assumes an api helper exists+ renderRevenueStats(stats);+ } catch (e) {+ document.getElementById('revenue-stats-grid').innerHTML = `<div class="err">Failed to load stats: ${e.message}</div>`;+ }+}++function renderRevenueStats(stats) {+ const grid = document.getElementById('revenue-stats-grid');++ const formatUSDC = (amount) => `$${(Number(amount) / 1e6).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;++ grid.innerHTML = `+ <div class="stat-card">+ <div class="label">Current Balance</div>+ <div class="value green">${formatUSDC(stats.current_balance)}</div>+ </div>+ <div class="stat-card">+ <div class="label">Net Earnings (30 Days)</div>+ <div class="value">${formatUSDC(stats.earnings_last_30_days)}</div>+ </div>+ <div class="stat-card">+ <div class="label">Lifetime Net Revenue</div>+ <div class="value">${formatUSDC(stats.total_revenue_net)}</div>+ </div>+ `;+}+// ── Avatars ─────────────────────────────────────────────────────────────────async function renderAvatars(root) {root.innerHTML = `<h1>Your avatars</h1><p class="sub">Each avatar gets a stable URL and can be rendered in Claude or any app via MCP.</p><div id="list" class="cards"></div>`;diff --git a/public/marketplace.css b/public/marketplace.cssindex 7971ba970..e6807d76e 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -998,6 +998,40 @@ body.market-page {.plugin-card .head {display: flex;align-items: center;+.skill-row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 8px 0;+ border-bottom: 1px solid rgba(255, 255, 255, 0.05);+}++.skill-row:last-child {+ border-bottom: none;+}++.skill-name {+ font-size: 14px;+ color: rgba(255, 255, 255, 0.9);+}++.skill-btn {+ background-color: #374151;+ color: #d1d5db;+ border: none;+ border-radius: 6px;+ padding: 4px 12px;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background-color 0.2s;+}++.skill-btn:disabled {+ background-color: #1f2937;+ color: #6b7280;+ cursor: not-allowed;+}gap: 12px;}diff --git a/pump-dashboard.html b/pump-dashboard.htmlindex e62973111..779500d26 100644--- a/pump-dashboard.html+++ b/pump-dashboard.html@@ -420,6 +420,7 @@to { opacity: 1; transform: translateY(0); }}</style>+<div id="toast-container"></div></head><body><div class="app">@@ -455,6 +456,7 @@<div class="section-label">System</div><a href="#" data-page="config"><span class="icon">⚙️</span> Configuration</a><a href="#" data-page="api"><span class="icon">🔌</span> API Keys</a>+ <a href="#" data-page="revenue"><span class="icon">💰</span> Revenue</a></nav><div class="sidebar-footer"><div id="bot-uptime">Uptime: --</div>@@ -540,6 +542,10 @@</div></div>+ <div class="content page" id="page-revenue" style="display:none">+ <!-- Content will be rendered here by dashboard.js -->+ </div>+<!-- ═══════ Live Feed Page ═══════ --><div class="content page" id="page-feed" style="display:none"><div style="display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap;">diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 186b5353f..1ee7b86f9 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -206,10 +206,10 @@ function render(agent) {else $('ad-trade').style.display = 'none';document.querySelector('.ad-main').classList.remove('loading');+ bindWalletActions();}-function renderNotFound(id, reason) {- document.title = 'Agent not found — three.ws';+function bindWalletActions() {const receiveBtn = document.getElementById('receive-btn');const withdrawBtn = document.getElementById('withdraw-btn');const swapBtn = document.getElementById('swap-btn');diff --git a/src/agent-edit.js b/src/agent-edit.jsindex f9e0a21fa..ad3f95869 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -125,7 +125,7 @@ $('monetization-save').addEventListener('click', async () => {});try {- const r = await fetch(`${API_BASE}/agents/${agentId}/skill-prices`, {+ const r = await fetch(`${API_BASE}/agents/${agentId}/skills-pricing`, {method: 'POST',headers: { 'Content-Type': 'application/json' },body: JSON.stringify({ prices })diff --git a/src/marketplace.js b/src/marketplace.jsindex f2ba01722..317e21591 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -1,6 +1,3 @@-import QRCode from 'qrcode';-import { createQR } from '@solana/pay';-import { escapeHtml } from './utils'; // Assuming you have this/*** Agent Marketplace — discovery + detail page controller.@@ -12,6 +9,20 @@ import { escapeHtml } from './utils'; // Assuming you have thisconst API = '/api';+let purchasedSkills = new Set();++async function fetchUserPurchases() {+ try {+ const r = await fetch(`${API}/users/me/purchased-skills`);+ if (!r.ok) return;+ const j = await r.json();+ purchasedSkills = new Set(j.purchases.map(p => `${p.agent_id}:${p.skill_name}`));+ } catch (err) {+ console.error('[marketplace] purchases', err);+ }+}++const CATEGORY_LABELS = {academic: 'Academic',career: 'Career',@@ -200,6 +211,39 @@ function renderCard(a) {// ── Detail view ───────────────────────────────────────────────────────────let detailState = null;+let unlockedSkills = new Set(); // In a real app, this would be populated from an API call on load++// --- New function, refactored from renderDetail ---+function renderSkillList(agent) {+ const skillsContainer = $('d-skills');+ if (!skillsContainer) return;++ const skillsArr = Array.isArray(agent.capabilities.skills) ? agent.capabilities.skills : agent.skills || [];+ const skillPrices = agent.skill_prices || {};++ skillsContainer.innerHTML = skillsArr.length+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];++ let actionButton;+ if (unlockedSkills.has(name)) {+ actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;+ } else if (price) {+ actionButton = `<button class="skill-btn purchase" data-skill-name="${escapeHtml(name)}">Purchase</button>`;+ } else {+ actionButton = `<button class="skill-btn" disabled>Free</button>`;+ }++ const priceDisplay = price ? `<span class="price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>` : ``;++ return `<div class="skill-row">+ <span class="skill-name">${escapeHtml(name)} ${priceDisplay}</span>+ ${actionButton}+ </div>`;+ }).join('')+ : '<div>This Agent has no skills defined.</div>';+}async function loadDetail(id) {els.discovery.hidden = true;@@ -266,19 +310,29 @@ function renderDetail(a, bookmarked) {$('d-library-count').textContent = libraryArr.length;const skillPrices = a.skill_prices || {};+$('d-skills').innerHTML = skillsArr.length- ? skillsArr- .map((s) => {- const name = typeof s === 'string' ? s : s.name || '';- const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(- 2,- )} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;- })- .join(' ')+ ? skillsArr.map((s) => {+ const name = typeof s === 'string' ? s : (s.name || '');+ const price = skillPrices[name];+ const purchaseKey = `${a.id}:${name}`;++ let badge;+ if (purchasedSkills.has(purchaseKey)) {+ badge = `<span class="price-badge price-owned">✓ Owned</span>`;+ } else if (price) {+ const priceInUSDC = (price.amount / 1e6).toFixed(2);+ badge = `<span class="price-badge price-paid">${priceInUSDC} USDC</span>` ++ `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}" data-agent-id="${a.id}">Purchase</button>`;+ } else {+ badge = `<span class="price-badge price-free">Free</span>`;+ }++ return `<div class="skill-row">+ <span class="skill-name">${escapeHtml(name)}</span>+ ${badge}+ </div>`;+ }).join(''): '<div>This Agent has no skills defined.</div>';$('d-library').innerHTML = libraryArr.length@@ -426,22 +480,13 @@ function bindEvents() {bindTabs();bindSubmit();- document.body.addEventListener('click', async (e) => {- if (e.target.matches('.btn-buy')) {- const agentId = e.target.dataset.agentId;- const skillId = e.target.dataset.skillId;- await onBuySkill(agentId, skillId);- }- });-}-}--// ── Submit Modal ──────────────────────────────────────────────────────────-bindTabs();- bindSubmit();+ document.body.addEventListener('click', async (e) => {+ if (e.target.matches('.btn-buy')) {+ const agentId = e.target.dataset.agentId;+ const skillId = e.target.dataset.skillId;+ await onBuySkill(agentId, skillId);+ }- // Delegated listener for purchase and close buttons- document.body.addEventListener('click', e => {if (e.target.matches('.purchase-btn')) {const skillName = e.target.dataset.skillName;const agent = detailState?.agent;@@ -460,15 +505,19 @@ bindTabs();}});- // Listener for backdrop clickconst purchaseModal = $('purchase-modal');if (purchaseModal) {- purchaseModal.addEventListener('click', e => {+ purchaseModal.addEventListener('click', (e) => {if (e.target.id === 'purchase-modal') {purchaseModal.classList.add('modal-hidden');}});- }ubmitModal() {+ }+}++// ── Submit Modal ──────────────────────────────────────────────────────────++function openSubmitModal() {$('market-submit-overlay').hidden = false;$('sf-name').focus();}@@ -575,7 +624,7 @@ function showPurchaseModal(txDetails) {detailsEl.textContent = `${txDetails.amount} USDC for "${txDetails.label}"`;- QRCode.toCanvas(canvas, url.toString(), { width: 256 }, (error) => {+ window.QRCode.toCanvas(canvas, url.toString(), { width: 256 }, (error) => {if (error) console.error(error);});@@ -625,6 +674,12 @@ function updateWalletUI() {`;$('payment-disconnect-btn').addEventListener('click', () => wallet.disconnect());confirmBtn.disabled = false;++ // Make sure to remove old listeners if this function can be called multiple times+ const newConfirmBtn = confirmBtn.cloneNode(true);+ confirmBtn.parentNode.replaceChild(newConfirmBtn, confirmBtn);++ newConfirmBtn.addEventListener('click', handlePurchase);} else {walletArea.innerHTML = `<button class="btn-primary" id="payment-connect-wallet-btn">Connect Phantom Wallet</button>@@ -645,6 +700,85 @@ function updateWalletUI() {}}+// Create the main purchase handler function+async function handlePurchase() {+ const statusEl = $('payment-status');+ const confirmBtn = $('payment-confirm-btn');+ confirmBtn.disabled = true;+ statusEl.textContent = 'Building transaction...';+ statusEl.className = 'payment-status';++ const intentId = document.getElementById('payment-modal-overlay').dataset.intentId;+ if (!intentId) {+ statusEl.textContent = 'Error: Missing payment intent ID.';+ statusEl.classList.add('err');+ return;+ }++ try {+ const intent = await getCurrentIntentDetails(intentId); // Placeholder+ if (!wallet.publicKey) throw new Error('Wallet is not connected.');++ statusEl.textContent = 'Please approve the transaction in your wallet...';+ const transaction = await buildUsdcTransferTransaction(intent, wallet.publicKey);+ const txid = await wallet.sendTransaction(transaction, solanaConnection);++ statusEl.textContent = `Waiting for on-chain confirmation...`;+ const confirmation = await solanaConnection.confirmTransaction(txid, 'confirmed');+ if (confirmation.value.err) throw new Error('On-chain transaction failed.');++ statusEl.textContent = 'Verifying purchase with server...';++ const verifyRes = await fetch('/api/payments/confirm', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({+ intent_id: intentId,+ transaction_signature: txid,+ }),+ });++ const verifyBody = await verifyRes.json();+ if (!verifyRes.ok) {+ throw new Error(verifyBody.error_description || 'Failed to verify purchase.');+ }++ statusEl.textContent = 'Success! Skill unlocked.';+ statusEl.classList.add('ok');++ // In the next prompt, we will add logic to update the UI permanently+ // fireEvent('skill:purchased', { skillName: intent.payload.skill });++ setTimeout(closePaymentModal, 2000);++ } catch (error) {+ statusEl.textContent = `Error: ${error.message}`;+ statusEl.classList.add('err');+ console.error("Purchase failed", error);+ confirmBtn.disabled = false; // Re-enable on failure+ }+}++// A placeholder function - you'd need to implement this+// or pass the intent object around properly.+async function getCurrentIntentDetails(intentId) {+ // In a real app, you might re-fetch this from your server or have it stored+ // For now, we'll reconstruct it from the UI for this example+ const priceText = $('payment-price-display').textContent;+ const amount = Math.round(parseFloat(priceText.replace(' USDC', '')) * 1e6);+ // You would also need to get the recipient address and mint from the intent.+ // This highlights the need for better state management than just the DOM.++ // For now, let's return a dummy object. The real implementation would be more robust.+ return {+ recipient_address: '...', // You would need to fetch this+ amount: String(amount),+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC+ }+}++function openPaymentModal(intent, skillName) {// Store intent for later usedocument.getElementById('payment-modal-overlay').dataset.intentId = intent.intent_id;diff --git a/src/wallet.js b/src/wallet.jsindex 381e9255a..8c200762d 100644--- a/src/wallet.js+++ b/src/wallet.js@@ -1,61 +1,66 @@-import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';-import { Connection, PublicKey } from '@solana/web3.js';-let connectedWalletAddress = null;+let listenersBound = false;-// Initialize the wallet adapter-const wallet = new PhantomWalletAdapter();--// Listen for connection events-wallet.on('connect', (publicKey) => {- connectedWalletAddress = publicKey.toBase58();- console.log(`Wallet connected: ${connectedWalletAddress}`);- updateWalletState(connectedWalletAddress);-});+function getPhantom() {+ const provider = typeof window !== 'undefined' ? window.solana : null;+ return provider && provider.isPhantom ? provider : null;+}-wallet.on('disconnect', () => {- console.log('Wallet disconnected');- connectedWalletAddress = null;- updateWalletState(null);-});+function bindPhantomListeners(provider) {+ if (listenersBound || !provider) return;+ listenersBound = true;+ provider.on('connect', (publicKey) => {+ connectedWalletAddress = publicKey?.toString?.() || null;+ updateWalletState(connectedWalletAddress);+ });+ provider.on('disconnect', () => {+ connectedWalletAddress = null;+ updateWalletState(null);+ });+}async function onConnectWallet() {- if (!wallet.connected) {- try {- await wallet.connect();- } catch (error) {- console.error('Wallet connection failed:', error);- }- }+ const provider = getPhantom();+ if (!provider) {+ window.open('https://phantom.app/', '_blank', 'noopener');+ return;+ }+ bindPhantomListeners(provider);+ try {+ const res = await provider.connect();+ connectedWalletAddress = res?.publicKey?.toString?.() || null;+ updateWalletState(connectedWalletAddress);+ } catch (err) {+ console.error('Wallet connection failed:', err);+ }}export function updateWalletState(address) {- const btn = document.getElementById('connect-wallet-btn');- if (btn) {- if (address) {- // Display shortened address- btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;- } else {- btn.textContent = 'Connect Wallet';- }- }+ const btn = document.getElementById('connect-wallet-btn');+ if (!btn) return;+ btn.textContent = address ? `${address.slice(0, 4)}...${address.slice(-4)}` : 'Connect Wallet';}export function initWalletButton() {- const btn = document.getElementById('connect-wallet-btn');- if (btn) {- btn.addEventListener('click', onConnectWallet);- }- // Auto-connect if wallet is already connected- if (wallet.autoConnect) {- wallet.autoConnect();- }+ const btn = document.getElementById('connect-wallet-btn');+ if (btn) btn.addEventListener('click', onConnectWallet);++ const provider = getPhantom();+ if (!provider) return;+ bindPhantomListeners(provider);+ provider.connect({ onlyIfTrusted: true })+ .then((res) => {+ connectedWalletAddress = res?.publicKey?.toString?.() || null;+ updateWalletState(connectedWalletAddress);+ })+ .catch(() => {});}export function getConnectedWallet() {- return wallet.connected ? wallet : null;+ const provider = getPhantom();+ return provider && provider.isConnected ? provider : null;}export function getConnectedWalletAddress() {- return connectedWalletAddress;+ return connectedWalletAddress;}diff --git a/style.css b/style.cssindex f855323a6..49f48637f 100644--- a/style.css+++ b/style.css@@ -997,6 +997,9 @@ footer .separator {.phi-grid-h::after {content: '';position: absolute;+ left: 0;+ right: 0;+ height: 1px;}.price-badge {@@ -1039,10 +1042,6 @@ footer .separator {color: #fde047;background-color: rgba(253, 224, 71, 0.1);}- left: 0;- right: 0;- height: 1px;-}.phi-grid-h::before {top: 38.2%;diff --git a/tasks/monetization-feature/02-ui-add-purchase-skill-button.md b/tasks/monetization-feature/02-ui-add-purchase-skill-button.mdindex d110f2545..8c3b193b4 100644--- a/tasks/monetization-feature/02-ui-add-purchase-skill-button.md+++ b/tasks/monetization-feature/02-ui-add-purchase-skill-button.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 2: Add "Purchase Skill" Button to UIdiff --git a/tasks/monetization-feature/03-backend-api-for-skill-pricing.md b/tasks/monetization-feature/03-backend-api-for-skill-pricing.mdindex 6427eb7a0..16cefdd56 100644--- a/tasks/monetization-feature/03-backend-api-for-skill-pricing.md+++ b/tasks/monetization-feature/03-backend-api-for-skill-pricing.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Create API for Skill Pricingdiff --git a/tasks/monetization-feature/03-backend-api-set-skill-price.md b/tasks/monetization-feature/03-backend-api-set-skill-price.mdindex dac89a7ee..08d052f0c 100644--- a/tasks/monetization-feature/03-backend-api-set-skill-price.md+++ b/tasks/monetization-feature/03-backend-api-set-skill-price.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend API - Set/Update Skill Pricediff --git a/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md b/tasks/monetization-feature/03-backend-api-to-set-skill-prices.mdindex 6c881651f..300f713dd 100644--- a/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md+++ b/tasks/monetization-feature/03-backend-api-to-set-skill-prices.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend - API to Set Skill Pricesdiff --git a/tasks/monetization-feature/03-backend-create-skill-purchase-table.md b/tasks/monetization-feature/03-backend-create-skill-purchase-table.mdindex 210c5492c..036437de3 100644--- a/tasks/monetization-feature/03-backend-create-skill-purchase-table.md+++ b/tasks/monetization-feature/03-backend-create-skill-purchase-table.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Create Skill Purchases Database Tablediff --git a/tasks/monetization-feature/03-backend-purchase-skill-api.md b/tasks/monetization-feature/03-backend-purchase-skill-api.mdindex 815fa98d9..0713b9815 100644--- a/tasks/monetization-feature/03-backend-purchase-skill-api.md+++ b/tasks/monetization-feature/03-backend-purchase-skill-api.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend for Skill Purchasediff --git a/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md b/tasks/monetization-feature/03-backend-seed-skill-pricing-data.mdindex 0f1bf3c29..80c0d8e82 100644--- a/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md+++ b/tasks/monetization-feature/03-backend-seed-skill-pricing-data.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend - Seed Skill Pricing Datadiff --git a/tasks/monetization-feature/03-backend-set-skill-price-api.md b/tasks/monetization-feature/03-backend-set-skill-price-api.mdindex a88b63b6f..cf487048d 100644--- a/tasks/monetization-feature/03-backend-set-skill-price-api.md+++ b/tasks/monetization-feature/03-backend-set-skill-price-api.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 3: Backend - Create API for Setting Skill Pricesdiff --git a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.mdindex 1a526b862..d365228c4 100644--- a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md+++ b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md@@ -1,11 +1,6 @@---title: "Prompt 3: Creator UI for Skill Pricing"-status: "completed"------# Prompt 3: Creator UI for Skill Pricing--**Status:** Completed+status: completed## ObjectiveCreate a user interface in the agent editor that allows creators to view their agent's skills and set a price for each one.diff --git a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.mdindex b0141948a..d5b1df646 100644--- a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md+++ b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md@@ -1,5 +1,5 @@----status: in-progress+status: completed---# Prompt 3: UI - Creator Dashboard for Pricingdiff --git a/tasks/monetization-feature/04-backend-api-set-skill-price.md b/tasks/monetization-feature/04-backend-api-set-skill-price.mdindex 7ddf02ee6..044da811c 100644--- a/tasks/monetization-feature/04-backend-api-set-skill-price.md+++ b/tasks/monetization-feature/04-backend-api-set-skill-price.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: API to Set Skill Pricesdiff --git a/tasks/monetization-feature/04-backend-create-purchase-table.md b/tasks/monetization-feature/04-backend-create-purchase-table.mdindex 344b3eda1..e06005ed5 100644--- a/tasks/monetization-feature/04-backend-create-purchase-table.md+++ b/tasks/monetization-feature/04-backend-create-purchase-table.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: Backend - Create Purchase History Tablediff --git a/tasks/monetization-feature/04-backend-skill-purchase-api.md b/tasks/monetization-feature/04-backend-skill-purchase-api.mdindex 2596f59be..ecea431de 100644--- a/tasks/monetization-feature/04-backend-skill-purchase-api.md+++ b/tasks/monetization-feature/04-backend-skill-purchase-api.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: Backend - Skill Purchase APIdiff --git a/tasks/monetization-feature/04-frontend-create-pricebadge-component.md b/tasks/monetization-feature/04-frontend-create-pricebadge-component.mdindex 22e4d2045..a1849de77 100644--- a/tasks/monetization-feature/04-frontend-create-pricebadge-component.md+++ b/tasks/monetization-feature/04-frontend-create-pricebadge-component.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: Frontend - Create Reusable PriceBadge Componentdiff --git a/tasks/monetization-feature/04-frontend-skill-pricing-ui.md b/tasks/monetization-feature/04-frontend-skill-pricing-ui.mdindex 70f82f09a..ddc07c729 100644--- a/tasks/monetization-feature/04-frontend-skill-pricing-ui.md+++ b/tasks/monetization-feature/04-frontend-skill-pricing-ui.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: Frontend - UI for Skill Price Managementdiff --git a/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.mdindex 04df0136c..9d8f4078a 100644--- a/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md+++ b/tasks/monetization-feature/04-frontend-ui-for-setting-skill-prices.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: Frontend - UI for Setting Skill Pricesdiff --git a/tasks/monetization-feature/04-ui-show-purchased-skills.md b/tasks/monetization-feature/04-ui-show-purchased-skills.mdindex 0f6f6478f..5e7a941d2 100644--- a/tasks/monetization-feature/04-ui-show-purchased-skills.md+++ b/tasks/monetization-feature/04-ui-show-purchased-skills.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 4: UI to Show Purchased Skillsdiff --git a/tasks/monetization-feature/05-backend-api-check-skill-access.md b/tasks/monetization-feature/05-backend-api-check-skill-access.mdindex 168011ca1..503f6b237 100644--- a/tasks/monetization-feature/05-backend-api-check-skill-access.md+++ b/tasks/monetization-feature/05-backend-api-check-skill-access.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 5: Backend API - Check Skill Accessdiff --git a/tasks/monetization-feature/05-backend-api-initiate-purchase.md b/tasks/monetization-feature/05-backend-api-initiate-purchase.mdindex d623dad6e..205b09361 100644--- a/tasks/monetization-feature/05-backend-api-initiate-purchase.md+++ b/tasks/monetization-feature/05-backend-api-initiate-purchase.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 5: API to Initiate Skill Purchasediff --git a/tasks/monetization-feature/05-backend-api-purchase-skill.md b/tasks/monetization-feature/05-backend-api-purchase-skill.mdindex adf2f9c7d..dc12148b4 100644--- a/tasks/monetization-feature/05-backend-api-purchase-skill.md+++ b/tasks/monetization-feature/05-backend-api-purchase-skill.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 5: API to Purchase a Skilldiff --git a/tasks/monetization-feature/05-backend-create-purchases-table.md b/tasks/monetization-feature/05-backend-create-purchases-table.mdindex c4680c061..70846a195 100644--- a/tasks/monetization-feature/05-backend-create-purchases-table.md+++ b/tasks/monetization-feature/05-backend-create-purchases-table.md@@ -1,5 +1,5 @@----status: not-started+status: completed---# Prompt 5: Create Purchase-Tracking Tablediff --git a/vercel.json b/vercel.jsonindex 634ed58e3..00bce93c2 100644--- a/vercel.json+++ b/vercel.json@@ -88,6 +88,18 @@"src": "/api/agents/([^/]+)/skills/price","dest": "/api/agent-skill-price.js?agentId=$1"},+ {+ "src": "/api/agents/([^/]+)/unlocked-skills",+ "dest": "/api/agents/[id]/unlocked-skills?id=$1"+ },+ {+ "src": "/api/billing/payout-wallet",+ "dest": "/api/billing/payout-wallet"+ },+ {+ "src": "/api/billing/withdraw",+ "dest": "/api/billing/withdraw"+ },{"src": "/api/newsletter/subscribe","dest": "/api/newsletter-subscribe"@@ -98,6 +110,10 @@},{"src": "/oauth/consent",+ {+ "src": "/api/payments/intent",+ "dest": "/api/payments/intent"+ },"dest": "/api/oauth/[action]?action=authorize"},{