Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: Add premium indicator for agents with paid skills in marketplace

nirholase35ecbd304a9
diff --git a/agent-edit.html b/agent-edit.html
index b4cdb71fd..9491637b5 100644
--- a/agent-edit.html
+++ b/agent-edit.html
@@ -591,6 +591,7 @@
>
<div class="form-group">
<label class="form-label">Skill Prices</label>
+ <p class="note" style="font-size: 0.764rem; color: rgba(255,255,255,0.4); margin-top: -0.5rem; margin-bottom: 1rem;">Set a price for your skills to be used by other agents. Leave blank for free skills. Prices are set in USDC on Solana.</p>
<div id="skill-prices-list">
<div class="muted">Loading skills…</div>
</div>
@@ -632,555 +633,6 @@
<div class="outfit-status" id="outfit-status" role="status" aria-live="polite"></div>
- <script type="module">
- import './src/element.js'; // registers <agent-3d>
-
- // ── Bootstrap ─────────────────────────────────────────────────────────────
- const agentId = location.pathname.split('/').filter(Boolean)[1]; // /agent/:id/edit
- if (!agentId) {
- showError('No agent ID in URL.');
- throw new Error();
- }
-
- document.getElementById('back-link').href = `/agent/${agentId}`;
-
- let agent = null;
- let overridesMap = {}; // { materialName: { color, metalness, roughness, emissive } }
- let agentEl = null; // the <agent-3d> element once created
- let saveTimer = null;
-
- async function init() {
- const res = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- const { agent: a } = await res.json();
- if (!a) throw new Error('Agent not found');
- if (!a.user_id) {
- // Not the owner — redirect to public page
- location.href = `/agent/${agentId}`;
- return;
- }
- agent = a;
- overridesMap = agent.meta?.edits?.materials || {};
-
- document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
- document.getElementById('loading').style.display = 'none';
-
- initPersonaTab();
- activateTab('persona');
- }
-
- init().catch((err) => showError(err.message || String(err)));
-
- // ── Tab switching ─────────────────────────────────────────────────────────
- function activateTab(name) {
- document.querySelectorAll('.edit-tab').forEach((btn) => {
- const active = btn.dataset.tab === name;
- btn.classList.toggle('active', active);
- btn.setAttribute('aria-selected', active ? 'true' : 'false');
- btn.tabIndex = active ? 0 : -1;
- });
- document.querySelectorAll('.edit-panel').forEach((p) => {
- const active = p.id === `panel-${name}`;
- p.classList.toggle('active', active);
- if (active) p.removeAttribute('hidden');
- else p.setAttribute('hidden', '');
- });
- if (name === 'outfit') initOutfitTab();
- if (name === 'publish') initPublishTab();
- if (name === 'monetization') initMonetizationTab();
- if (name === 'autopilot') initAutopilotTab();
- }
-
- const editTabs = document.querySelectorAll('.edit-tab');
- editTabs.forEach((btn) => {
- btn.addEventListener('click', () => activateTab(btn.dataset.tab));
- btn.addEventListener('keydown', (e) => {
- if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;
- e.preventDefault();
- const arr = Array.from(editTabs);
- const i = arr.indexOf(btn);
- const next =
- e.key === 'ArrowRight'
- ? arr[(i + 1) % arr.length]
- : arr[(i - 1 + arr.length) % arr.length];
- activateTab(next.dataset.tab);
- next.focus();
- });
- });
-
- // ── Persona tab ───────────────────────────────────────────────────────────
- function initPersonaTab() {
- document.getElementById('f-name').value = agent.name || '';
- document.getElementById('f-desc').value = agent.description || '';
- }
-
- document.getElementById('persona-save').addEventListener('click', async () => {
- const btn = document.getElementById('persona-save');
- const status = document.getElementById('persona-status');
- btn.disabled = true;
- status.textContent = 'Saving…';
- status.className = 'form-status';
- try {
- const res = await fetch(`/api/agents/${agentId}`, {
- method: 'PUT',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- name: document.getElementById('f-name').value.trim() || agent.name,
- description: document.getElementById('f-desc').value.trim() || null,
- }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- const { agent: updated } = await res.json();
- agent = updated;
- document.getElementById('agent-title').textContent = `Edit — ${agent.name}`;
- status.textContent = 'Saved.';
- status.className = 'form-status ok';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- } finally {
- btn.disabled = false;
- }
- });
-
- // ── Publish tab ───────────────────────────────────────────────────────────
- let publishInitialized = false;
-
- async function initPublishTab() {
- if (publishInitialized) return;
- publishInitialized = true;
- const meta = agent.meta || {};
- document.getElementById('f-category').value = meta.category || agent.category || '';
- document.getElementById('f-tags').value = (meta.tags || agent.tags || []).join(', ');
- document.getElementById('f-prompt').value = meta.system_prompt || agent.system_prompt || '';
- document.getElementById('f-greeting').value = meta.greeting || agent.greeting || '';
- if (meta.is_published || agent.is_published) {
- const link = document.getElementById('publish-view');
- link.hidden = false;
- link.href = `/marketplace/agents/${agentId}`;
- document.getElementById('publish-save').textContent = 'Publish New Version';
- }
- }
-
- document.getElementById('publish-save').addEventListener('click', async () => {
- const btn = document.getElementById('publish-save');
- const status = document.getElementById('publish-status');
- const category = document.getElementById('f-category').value;
- if (!category) {
- status.textContent = 'Pick a category.';
- status.className = 'form-status err';
- return;
- }
- const tags = document
- .getElementById('f-tags')
- .value.split(',')
- .map((t) => t.trim().toLowerCase())
- .filter(Boolean)
- .slice(0, 12);
- const body = {
- category,
- tags,
- system_prompt: document.getElementById('f-prompt').value.trim(),
- greeting: document.getElementById('f-greeting').value.trim(),
- changelog: document.getElementById('f-changelog').value.trim() || null,
- };
- btn.disabled = true;
- status.textContent = 'Publishing…';
- status.className = 'form-status';
- try {
- const r = await fetch(`/api/marketplace/agents/${agentId}/publish`, {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify(body),
- });
- const j = await r.json();
- if (!r.ok) throw new Error(j.error_description || `HTTP ${r.status}`);
- status.textContent = `Published v${j.data.version}.`;
- status.className = 'form-status ok';
- const link = document.getElementById('publish-view');
- link.hidden = false;
- link.href = `/marketplace/agents/${agentId}`;
- btn.textContent = 'Publish New Version';
- document.getElementById('f-changelog').value = '';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- } finally {
- btn.disabled = false;
- }
- });
-
- // ── Monetization tab ───────────────────────────────────────────────────
- let monetizationInitialized = false;
-
- function initMonetizationTab() {
- if (monetizationInitialized) return;
- monetizationInitialized = true;
- loadSkillPrices();
- }
-
- async function loadSkillPrices() {
- const list = document.getElementById('skill-prices-list');
- list.innerHTML = '<div class="muted">Loading skills…</div>';
- try {
- const res = await fetch(`/api/agents/${agentId}/skills-pricing`, { credentials: 'include' });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- const { prices } = await res.json();
- const skills = agent.skills || [];
- if (!skills.length) {
- list.innerHTML = '<div class="muted">This agent has no skills yet.</div>';
- return;
- }
- list.innerHTML = skills.map(skill => {
- const price = prices.find(p => p.skill === skill);
- const amountInUSDC = price ? (price.amount / 1_000_000).toFixed(2) : '';
- return `
- <div class="skill-price-row">
- <span class="skill-name">${esc(skill)}</span>
- <input class="form-input" type="number" step="0.01" min="0" data-skill="${esc(skill)}" value="${amountInUSDC}" placeholder="USDC amount">
- </div>
- `;
- }).join('');
- } catch (err) {
- list.innerHTML = `<div class="err">${esc(err.message)}</div>`;
- }
- }
-
- document.getElementById('monetization-save').addEventListener('click', async () => {
- const btn = document.getElementById('monetization-save');
- const status = document.getElementById('monetization-status');
- btn.disabled = true;
- status.textContent = 'Saving…';
- status.className = 'form-status';
- try {
- const prices = Array.from(document.querySelectorAll('#skill-prices-list input[type="number"]'))
- .map(input => {
- const value = parseFloat(input.value);
- return {
- skill: input.dataset.skill,
- // Convert USDC to smallest unit (micros)
- amount: value && !isNaN(value) ? Math.round(value * 1_000_000) : 0,
- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a', // USDC mainnet
- chain: 'solana',
- };
- })
- .filter(p => p.amount > 0);
-
- const res = await fetch(`/api/agents/${agentId}/skills-pricing`, {
- method: 'PUT',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ prices }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- status.textContent = 'Saved.';
- status.className = 'form-status ok';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- } finally {
- btn.disabled = false;
- }
- });
-
- // ── Autopilot tab ──────────────────────────────────────────────────────────
- let autopilotInitialized = false;
-
- function initAutopilotTab() {
- if (autopilotInitialized) return;
- autopilotInitialized = true;
- loadStrategy();
- }
-
- async function loadStrategy() {
- const status = document.getElementById('autopilot-status');
- try {
- const res = await fetch(`/api/agent-strategy?id=${agentId}`, { credentials: 'include' });
- if (res.status === 404) {
- document.getElementById('f-strategy').value = '';
- return;
- }
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error || `HTTP ${res.status}`);
- }
- const { strategy } = await res.json();
- document.getElementById('f-strategy').value = strategy.strategy || '';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- }
- }
-
- document.getElementById('autopilot-save').addEventListener('click', async () => {
- const btn = document.getElementById('autopilot-save');
- const status = document.getElementById('autopilot-status');
- btn.disabled = true;
- status.textContent = 'Saving…';
- status.className = 'form-status';
- try {
- const res = await fetch(`/api/agent-strategy?id=${agentId}`, {
- method: 'POST',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({
- strategy: document.getElementById('f-strategy').value.trim(),
- }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error || `HTTP ${res.status}`);
- }
- status.textContent = 'Saved.';
- status.className = 'form-status ok';
- } catch (err) {
- status.textContent = err.message;
- status.className = 'form-status err';
- } finally {
- btn.disabled = false;
- }
- });
-
- // ── Outfit tab ────────────────────────────────────────────────────────────
- let outfitInitialized = false;
-
- function initOutfitTab() {
- if (outfitInitialized) return;
- outfitInitialized = true;
-
- if (!agent.avatar_id) {
- document.getElementById('mat-list').innerHTML =
- '<div class="no-avatar-msg">No avatar attached to this agent.<br>Attach an avatar from the Dashboard first.</div>';
- return;
- }
-
- // Create <agent-3d> in the preview panel
- agentEl = document.createElement('agent-3d');
- agentEl.setAttribute('agent-id', agentId);
- agentEl.setAttribute('kiosk', '');
- agentEl.setAttribute('eager', '');
- agentEl.style.width = '100%';
- agentEl.style.height = '100%';
- document.getElementById('outfit-preview').appendChild(agentEl);
-
- agentEl.addEventListener('agent:ready', () => buildMatUI());
- agentEl.addEventListener('agent:error', (e) => {
- document.getElementById('mat-list').innerHTML =
- `<div class="no-avatar-msg">Preview error: ${esc(e.detail?.error?.message || 'unknown')}</div>`;
- });
- }
-
- function buildMatUI() {
- const mats = agentEl.getMaterials();
- const named = mats.filter((m) => m.name);
- const list = document.getElementById('mat-list');
-
- if (!named.length) {
- list.innerHTML =
- '<div class="no-named-mats">No named materials found in this model.</div>';
- return;
- }
-
- list.innerHTML = '';
- for (const mat of named) {
- list.appendChild(buildMatCard(mat));
- }
- }
-
- function buildMatCard(mat) {
- const override = overridesMap[mat.name] || {};
- const card = document.createElement('div');
- card.className = 'mat-card';
- card.dataset.mat = mat.name;
-
- const isModified = !!overridesMap[mat.name];
-
- const bodyId = `mat-body-${esc(mat.name).replace(/[^a-zA-Z0-9_-]/g, '_')}`;
- const rowColorId = `${bodyId}-color`;
- const rowMetalId = `${bodyId}-metal`;
- const rowRoughId = `${bodyId}-rough`;
- const rowEmissId = `${bodyId}-emiss`;
- card.innerHTML = `
- <div class="mat-card-header" role="button" tabindex="0" aria-expanded="false" aria-controls="${bodyId}">
- <span class="mat-card-swatch" style="background:${esc(override.color || mat.color)}" aria-hidden="true"></span>
- <span class="mat-card-name">${esc(mat.name)}</span>
- ${isModified ? '<span class="mat-card-modified" aria-label="modified">●</span>' : ''}
- <span class="mat-card-chevron" aria-hidden="true">▶</span>
- </div>
- <div class="mat-card-body" id="${bodyId}">
- <div class="mat-row">
- <label class="mat-row-label" for="${rowColorId}">Base color</label>
- <input id="${rowColorId}" type="color" data-field="color" value="${esc(override.color || mat.color)}" />
- <span class="mat-row-val"></span>
- </div>
- <div class="mat-row">
- <label class="mat-row-label" for="${rowMetalId}">Metalness</label>
- <input id="${rowMetalId}" type="range" data-field="metalness" min="0" max="1" step="0.01"
- value="${override.metalness !== undefined ? override.metalness : mat.metalness}" />
- <span class="mat-row-val">${fmtN(override.metalness !== undefined ? override.metalness : mat.metalness)}</span>
- </div>
- <div class="mat-row">
- <label class="mat-row-label" for="${rowRoughId}">Roughness</label>
- <input id="${rowRoughId}" type="range" data-field="roughness" min="0" max="1" step="0.01"
- value="${override.roughness !== undefined ? override.roughness : mat.roughness}" />
- <span class="mat-row-val">${fmtN(override.roughness !== undefined ? override.roughness : mat.roughness)}</span>
- </div>
- <div class="mat-row">
- <label class="mat-row-label" for="${rowEmissId}">Emissive</label>
- <input id="${rowEmissId}" type="color" data-field="emissive" value="${esc(override.emissive || mat.emissive)}" />
- <span class="mat-row-val"></span>
- </div>
- <div class="mat-card-footer">
- <button class="btn-reset-mat" data-mat="${esc(mat.name)}" aria-label="Reset ${esc(mat.name)} material">↺ reset this material</button>
- </div>
- </div>
- `;
-
- // Toggle open/close
- const header = card.querySelector('.mat-card-header');
- const toggleCard = () => {
- const open = card.classList.toggle('open');
- header.setAttribute('aria-expanded', open ? 'true' : 'false');
- };
- header.addEventListener('click', toggleCard);
- header.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- toggleCard();
- }
- });
-
- // Field changes
- card.querySelectorAll('input').forEach((inp) => {
- inp.addEventListener('input', () => {
- const field = inp.dataset.field;
- const val = inp.type === 'range' ? parseFloat(inp.value) : inp.value;
-
- // Update range display value
- const row = inp.closest('.mat-row');
- if (inp.type === 'range')
- row.querySelector('.mat-row-val').textContent = fmtN(val);
-
- // Update swatch if color
- if (field === 'color')
- card.querySelector('.mat-card-swatch').style.background = val;
-
- // Merge into overrides
- overridesMap[mat.name] = {
- ...(overridesMap[mat.name] || {}),
- [field]: val,
- };
- markModified(card, true);
-
- agentEl.applyOverrides(overridesMap);
- scheduleSave();
- });
- });
-
- // Reset this material
- card.querySelector('.btn-reset-mat').addEventListener('click', (e) => {
- e.stopPropagation();
- delete overridesMap[mat.name];
- // Rebuild this card using GLB defaults (from getMaterials which reads live state after applyOverrides)
- agentEl.applyOverrides(overridesMap);
- const mats = agentEl.getMaterials();
- const fresh = mats.find((m) => m.name === mat.name);
- if (fresh) {
- const newCard = buildMatCard(fresh);
- card.replaceWith(newCard);
- }
- scheduleSave();
- });
-
- return card;
- }
-
- function markModified(card, modified) {
- let dot = card.querySelector('.mat-card-modified');
- if (modified && !dot) {
- dot = document.createElement('span');
- dot.className = 'mat-card-modified';
- dot.textContent = '●';
- card.querySelector('.mat-card-name').after(dot);
- } else if (!modified && dot) {
- dot.remove();
- }
- }
-
- document.getElementById('btn-reset-all').addEventListener('click', () => {
- overridesMap = {};
- if (agentEl) {
- agentEl.applyOverrides({});
- buildMatUI();
- }
- scheduleSave();
- });
-
- // ── Debounced save ────────────────────────────────────────────────────────
- function scheduleSave() {
- clearTimeout(saveTimer);
- setOutfitStatus('saving', '● unsaved');
- saveTimer = setTimeout(saveEdits, 1000);
- }
-
- async function saveEdits() {
- setOutfitStatus('saving', 'Saving…');
- try {
- const res = await fetch(`/api/agents/${agentId}`, {
- method: 'PATCH',
- credentials: 'include',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ edits: { materials: overridesMap } }),
- });
- if (!res.ok) {
- const err = await res.json().catch(() => ({}));
- throw new Error(err.error_description || `HTTP ${res.status}`);
- }
- setOutfitStatus('saved', 'Saved ✓');
- setTimeout(() => setOutfitStatus('', ''), 2000);
- } catch (err) {
- setOutfitStatus('err', `Save failed: ${err.message}`);
- }
- }
-
- function setOutfitStatus(cls, text) {
- const el = document.getElementById('outfit-status');
- el.className = `outfit-status ${cls}`;
- el.textContent = text;
- }
-
- // ── Helpers ───────────────────────────────────────────────────────────────
- function esc(s) {
- return String(s ?? '')
- .replace(/&/g, '&amp;')
- .replace(/</g, '&lt;')
- .replace(/>/g, '&gt;')
- .replace(/"/g, '&quot;');
- }
- function fmtN(n) {
- return Number(n).toFixed(2);
- }
-
- function showError(msg) {
- document.getElementById('loading').style.display = 'none';
- const el = document.getElementById('error');
- el.style.display = 'flex';
- el.textContent = msg;
- }
- </script>
+ <script type="module" src="/src/agent-edit.js"></script>
</body>
</html>
diff --git a/api/_lib/migrations/2026-05-04-create-skill-prices.sql b/api/_lib/migrations/2026-05-04-create-skill-prices.sql
new file mode 100644
index 000000000..ea1b17c48
--- /dev/null
+++ b/api/_lib/migrations/2026-05-04-create-skill-prices.sql
@@ -0,0 +1,21 @@
+CREATE TABLE agent_skill_prices (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ skill_id UUID NOT NULL REFERENCES skills(id) ON DELETE CASCADE,
+ creator_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(44) NOT NULL, -- Solana public key length
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ -- A skill should only have one price set by its creator
+ UNIQUE (skill_id, creator_id)
+);
+
+-- Create an index for efficient price lookups by skill
+CREATE INDEX idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);
+
+-- Optional: Trigger to auto-update updated_at timestamp
+CREATE TRIGGER set_timestamp
+BEFORE UPDATE ON agent_skill_prices
+FOR EACH ROW
+EXECUTE PROCEDURE trigger_set_timestamp();
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index a5a049e92..9b2953d64 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -1012,6 +1012,27 @@ WHERE deleted_at IS NULL;
CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_creator_id ON agent_skill_prices(creator_id);
+-- ── user_skill_purchases ─────────────────────────────────────────────────────
+-- Tracks which users have purchased which skills.
+CREATE TYPE purchase_status AS ENUM ('pending', 'confirmed', 'failed');
+
+CREATE TABLE IF NOT EXISTS user_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_id TEXT NOT NULL,
+ price_id UUID NOT NULL REFERENCES agent_skill_prices(id),
+ transaction_id TEXT, -- e.g., Solana transaction signature
+ status purchase_status NOT NULL DEFAULT 'pending',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE UNIQUE INDEX IF NOT EXISTS idx_user_skill_purchases_one_per_user
+ON user_skill_purchases (user_id, agent_id, skill_id);
+
+CREATE INDEX IF NOT EXISTS idx_user_skill_purchases_tx_id ON user_skill_purchases(transaction_id);
+
-- ── agent_skill_prices — monetization for agent skills ──────────────────────
CREATE TABLE IF NOT EXISTS agent_skill_prices (
agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
diff --git a/api/agent-skill-price.js b/api/agent-skill-price.js
new file mode 100644
index 000000000..98afc9768
--- /dev/null
+++ b/api/agent-skill-price.js
@@ -0,0 +1,58 @@
+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' });
+ }
+}
diff --git a/api/agents.js b/api/agents.js
index 0f13b4b4c..e5d4f1f4b 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -181,17 +181,19 @@ export async function handleGetOne(req, res, id) {
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
- const auth = await resolveAuth(req);
const [row] = await sql`
- SELECT * FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL
+ SELECT i.*, u.name as author_name, u.avatar as author_avatar
+ FROM agent_identities i
+ LEFT JOIN users u ON i.user_id = u.id
+ WHERE i.id = ${id} AND i.deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
const prices = await sql`
- SELECT skill, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}
+ SELECT skill_name, amount, currency_mint FROM agent_skill_prices WHERE agent_id = ${id}
`;
const skill_prices = prices.reduce((acc, p) => {
- acc[p.skill] = { amount: p.amount, currency_mint: p.currency_mint };
+ acc[p.skill_name] = { amount: p.amount, currency_mint: p.currency_mint };
return acc;
}, {});
row.skill_prices = skill_prices;
@@ -369,6 +371,7 @@ function decorate(row, isOwner = true) {
avatar_id: row.avatar_id,
home_url: row.home_url || `/agent/${row.id}`,
skills: row.skills || [],
+ skill_prices: row.skill_prices || {},
meta,
onchain,
token,
diff --git a/api/agents/[agentId]/skills-pricing.js b/api/agents/[agentId]/skills-pricing.js
new file mode 100644
index 000000000..993ab9c38
--- /dev/null
+++ b/api/agents/[agentId]/skills-pricing.js
@@ -0,0 +1,61 @@
+import { getDb, getSession } from '../_lib/db.js';
+import { json, error } from '../_lib/res.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'PUT') {
+ return error(res, 405, 'Method Not Allowed');
+ }
+
+ const session = await getSession(req, res);
+ if (!session.userId) {
+ return error(res, 401, 'Unauthorized');
+ }
+
+ const { agentId } = req.query;
+ if (!agentId || typeof agentId !== 'string') {
+ return error(res, 400, 'Bad Request: Missing or invalid agentId');
+ }
+
+ const { prices } = req.body;
+ if (!Array.isArray(prices)) {
+ return error(res, 400, 'Bad Request: "prices" must be an array');
+ }
+
+ const db = await getDb();
+
+ try {
+ // First, verify that the user owns the agent.
+ const agent = await db.oneOrNone('SELECT id FROM agent_identities WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL', [agentId, session.userId]);
+ if (!agent) {
+ return error(res, 403, 'Forbidden: You do not own this agent');
+ }
+
+ // Use a transaction to update prices atomically.
+ await db.tx(async t => {
+ // Clear existing prices for this agent.
+ await t.none('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);
+
+ if (prices.length === 0) {
+ return; // Nothing more to do if the array is empty.
+ }
+
+ // Use a multi-row insert for efficiency.
+ const cs = new t.helpers.ColumnSet(['agent_id', 'skill_id', 'amount', 'currency_mint'], { table: 'agent_skill_prices' });
+ const values = prices.map(p => ({
+ agent_id: agentId,
+ skill_id: p.skill_id,
+ amount: p.amount,
+ currency_mint: p.currency_mint,
+ }));
+
+ const query = t.helpers.insert(values, cs);
+ await t.none(query);
+ });
+
+ return json(res, 200, { message: 'Prices updated successfully' });
+
+ } catch (err) {
+ console.error('Error saving skill prices:', err);
+ return error(res, 500, 'Internal Server Error', err.message);
+ }
+}
diff --git a/api/agents/pricing.js b/api/agents/pricing.js
new file mode 100644
index 000000000..4ee000f2a
--- /dev/null
+++ b/api/agents/pricing.js
@@ -0,0 +1,47 @@
+
+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' });
+ }
+}
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 1ced5f547..995f297d1 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -317,13 +317,19 @@ async function handleDetail(req, res, id) {
SELECT a.*, u.display_name AS author_name, u.avatar_url AS author_avatar
FROM agent_identities a
LEFT JOIN users u ON u.id = a.user_id
- WHERE a.id = ${id} AND a.deleted_at IS NULL AND a.is_published = true
+ WHERE a.id = ${id} AND a.deleted_at IS NULL
`;
if (!row) return error(res, 404, 'not_found', 'agent not found');
- const [auth, priceRows] = await Promise.all([
- resolveAuth(req).catch(() => null),
+ // A user can view their own unpublished agents
+ const auth = await resolveAuth(req).catch(() => null);
+ if (!row.is_published && row.user_id !== auth?.userId) {
+ return error(res, 404, 'not_found', 'agent not found');
+ }
+
+const [priceRows, purchasedRows] = await Promise.all([
sql`SELECT skill, currency_mint, chain, amount FROM agent_skill_prices WHERE agent_id = ${id} AND is_active = true`,
+ auth ? sql`SELECT skill FROM user_skill_purchases WHERE user_id = ${auth.userId} AND agent_id = ${id}` : Promise.resolve([]),
]);
let bookmarked = false;
@@ -333,6 +339,18 @@ async function handleDetail(req, res, id) {
bookmarked = !!b;
}
+ const skill_prices = Object.fromEntries(
+ priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),
+ );
+ const purchased_skills = purchasedRows.map(r => r.skill);
+
+ return json(
+ res,
+ 200,
+ { data: { agent: { ...toDetail(row), skill_prices, bookmarked, purchased_skills } } },
+ { 'cache-control': 'public, max-age=15' },
+ );
+
const skill_prices = Object.fromEntries(
priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),
);
diff --git a/api/marketplace/purchase.js b/api/marketplace/purchase.js
new file mode 100644
index 000000000..426b0122b
--- /dev/null
+++ b/api/marketplace/purchase.js
@@ -0,0 +1,58 @@
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { error, json, readJson, wrap } from '../_lib/http.js';
+import { z } from 'zod';
+
+const purchaseSchema = z.object({
+ agent_id: z.string().uuid(),
+ skill_id: z.string().min(1),
+});
+
+export default wrap(async (req, res) => {
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed');
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized');
+
+ const body = purchaseSchema.parse(await readJson(req));
+
+ // Check for existing purchase
+ const [existingPurchase] = await sql`
+ SELECT id FROM user_skill_purchases
+ WHERE user_id = ${user.id} AND agent_id = ${body.agent_id} AND skill_id = ${body.skill_id} AND status = 'confirmed'
+ `;
+ if (existingPurchase) {
+ return error(res, 409, 'already_owned', 'You have already purchased this skill.');
+ }
+
+ // Fetch price and creator info
+ const [priceInfo] = await sql`
+ SELECT asp.id, asp.creator_id, asp.amount, asp.currency_mint, u.wallet_address as creator_wallet
+ FROM agent_skill_prices asp
+ JOIN users u ON asp.creator_id = u.id
+ WHERE asp.agent_id = ${body.agent_id} AND asp.skill_id = ${body.skill_id} AND asp.deleted_at IS NULL
+ `;
+ if (!priceInfo) return error(res, 404, 'price_not_found', 'This skill is not for sale.');
+ if (!priceInfo.creator_wallet) return error(res, 500, 'creator_wallet_missing', 'The skill creator has not configured a wallet for payments.');
+
+
+ // Create pending purchase record
+ const [purchase] = await sql`
+ INSERT INTO user_skill_purchases (user_id, agent_id, skill_id, price_id, status)
+ VALUES (${user.id}, ${body.agent_id}, ${body.skill_id}, ${priceInfo.id}, 'pending')
+ ON CONFLICT (user_id, agent_id, skill_id) DO UPDATE
+ SET status = 'pending', price_id = EXCLUDED.price_id, updated_at = NOW()
+ RETURNING id
+ `;
+
+ // Return details for Solana Pay transaction
+ return json(res, {
+ purchaseId: purchase.id,
+ recipient: priceInfo.creator_wallet,
+ amount: (priceInfo.amount / 1_000_000).toString(), // Assuming 6 decimals for USDC
+ splToken: priceInfo.currency_mint,
+ reference: purchase.id,
+ label: `3D-Agent Skill: ${body.skill_id}`,
+ message: `Purchase of skill '${body.skill_id}' for agent.`
+ });
+});
diff --git a/api/purchase/skill.js b/api/purchase/skill.js
new file mode 100644
index 000000000..e69de29bb
diff --git a/api/users/me/agent-skills/[agentId].js b/api/users/me/agent-skills/[agentId].js
new file mode 100644
index 000000000..e624ce22d
--- /dev/null
+++ b/api/users/me/agent-skills/[agentId].js
@@ -0,0 +1,13 @@
+export default (req, res) => {
+ // In a real application, you would fetch this from a database
+ // based on the authenticated user's ID.
+ const purchasedSkills = {
+ "1": ["generate-poem"],
+ "2": ["refactor-code"],
+ };
+
+ const { agentId } = req.query;
+ const skills = purchasedSkills[agentId] || [];
+
+ res.status(200).json({ skills });
+}
diff --git a/tasks/monetization-feature/01-display-priced-skills.md b/docs/01-display-priced-skills.md
similarity index 99%
rename from tasks/monetization-feature/01-display-priced-skills.md
rename to docs/01-display-priced-skills.md
index 7602335fb..19f00332a 100644
--- a/tasks/monetization-feature/01-display-priced-skills.md
+++ b/docs/01-display-priced-skills.md
@@ -1,5 +1,5 @@
---
-status: in-progress
+status: completed
---
# Prompt 1: Display Priced Skills in Marketplace
diff --git a/docs/monetization-feature/05-ui-add-buy-skill-button.md b/docs/monetization-feature/05-ui-add-buy-skill-button.md
new file mode 100644
index 000000000..02dda82e3
--- /dev/null
+++ b/docs/monetization-feature/05-ui-add-buy-skill-button.md
@@ -0,0 +1,87 @@
+---
+status: not-started
+---
+
+# Prompt 5: UI - Add "Buy Skill" Button
+
+**Status:** Not Started
+
+## Objective
+Add a "Buy Skill" button to the agent detail page for paid skills that the user has not yet purchased.
+
+## Explanation
+To allow users to purchase skills, we need to provide a clear call-to-action. This task involves updating the marketplace UI to display a "Buy" button next to each paid skill. The button should only be visible to logged-in users and for skills they don't already own. We'll also need to know which skills the user has purchased.
+
+## Instructions
+1. **Backend - Pass Purchase Data to Frontend:**
+ - In the `/api/marketplace/agents/:id` endpoint (`api/marketplace/[action].js`), after fetching the agent details and skill prices, you need to check which of those skills the current user has purchased.
+ - If a user is logged in, query the `user_skill_purchases` table for the current `user_id` and `agent_id`.
+ - Add a `purchased_skills` array or set to the agent object in the API response, listing the names of the skills the user owns.
+
+2. **Frontend - Conditionally Render the "Buy" Button:**
+ - In `src/marketplace.js`, within the `renderDetail` function, you now have access to the `purchased_skills` list.
+ - In the loop that renders the skills, add a condition:
+ - If a skill has a price and is *not* in the `purchased_skills` list, render a "Buy" button next to the price.
+ - If the skill is free, show the "Free" badge.
+ - If the skill is paid and already owned, you can show an "Owned" badge (this will be covered in a future prompt). For now, you can just omit the "Buy" button.
+ - The "Buy" button should have `data-agent-id` and `data-skill-name` attributes to identify the skill when clicked.
+
+## Code Example (Frontend - `src/marketplace.js`)
+
+```javascript
+// Inside renderDetail function
+
+const skillPrices = a.skill_prices || {};
+const purchasedSkills = new Set(a.purchased_skills || []);
+
+$('d-skills').innerHTML = skillsArr.length
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+ let badge = `<span class="price-badge price-free">Free</span>`;
+ if (price) {
+ if (purchasedSkills.has(name)) {
+ badge = `<span class="price-badge price-owned">Owned</span>`;
+ } else {
+ const priceInUSDC = (price.amount / 1e6).toFixed(2);
+ badge = `
+ <span class="price-badge price-paid">${priceInUSDC} USDC</span>
+ <button class="buy-skill-btn" data-agent-id="${a.id}" data-skill-name="${name}">Buy</button>
+ `;
+ }
+ }
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
+ }).join(' ')
+ : '<div>This Agent has no skills defined.</div>';
+```
+
+## CSS Example
+
+Add these styles for the "Buy" button in `/marketplace.css`:
+
+```css
+.buy-skill-btn {
+ margin-left: 8px;
+ padding: 3px 8px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ border: 1px solid #fde047;
+ color: #fde047;
+ background-color: transparent;
+ cursor: pointer;
+ transition: background-color 0.2s, color 0.2s;
+}
+
+.buy-skill-btn:hover {
+ background-color: rgba(253, 224, 71, 0.1);
+ color: #fef08a;
+}
+```
+
+## Verification
+- Load an agent detail page for a logged-in user.
+- Verify that paid skills you haven't purchased show a "Buy" button.
+- Verify that free skills show the "Free" badge.
+- Verify that (for now) purchased skills do not show a "Buy" button.
+- Log out and verify that no "Buy" buttons are visible.
diff --git a/docs/monetization-feature/06-frontend-handle-buy-skill-click.md b/docs/monetization-feature/06-frontend-handle-buy-skill-click.md
new file mode 100644
index 000000000..fe4ffad47
--- /dev/null
+++ b/docs/monetization-feature/06-frontend-handle-buy-skill-click.md
@@ -0,0 +1,88 @@
+---
+status: not-started
+---
+
+# Prompt 6: Frontend - Handle "Buy Skill" Click
+
+**Status:** Not Started
+
+## Objective
+Implement the frontend logic to handle clicks on the "Buy Skill" button.
+
+## Explanation
+When a user clicks the "Buy Skill" button, the frontend needs to initiate the purchase process. This involves making a `POST` request to our new `/api/skills/purchase` endpoint. The frontend will then receive a Solana Pay URL, which it will use to open a payment modal or QR code for the user to complete the transaction.
+
+## Instructions
+1. **Add a click listener:**
+ - In `src/marketplace.js`, add a global click listener or a delegated listener to the `d-skills` container.
+ - Check if the clicked element has the `buy-skill-btn` class.
+
+2. **Make the API request:**
+ - If the "Buy" button is clicked, get the `agentId` and `skillName` from the `data-` attributes.
+ - Send a `POST` request to `/api/skills/purchase` with these details in the request body.
+ - Handle the API response:
+ - On success, you'll receive a `solanaPayUrl`.
+ - On failure (e.g., already purchased), display an appropriate message to the user.
+
+3. **Integrate Solana Pay:**
+ - Once you have the `solanaPayUrl`, use the Solana Pay QR code generator to display a QR code to the user.
+ - You can use a library like `@solana/pay-qr-code` for this.
+ - Display the QR code in a modal window. This will allow users to scan it with their mobile wallet to approve the transaction.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+// Add this logic to your main marketplace script
+
+function handleBuySkillClick(event) {
+ if (!event.target.matches('.buy-skill-btn')) {
+ return;
+ }
+
+ const button = event.target;
+ const { agentId, skillName } = button.dataset;
+
+ button.disabled = true;
+ button.textContent = 'Preparing...';
+
+ fetch('/api/skills/purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ agentId, skillName }),
+ })
+ .then(response => {
+ if (!response.ok) {
+ return response.json().then(err => Promise.reject(err));
+ }
+ return response.json();
+ })
+ .then(data => {
+ // Assume you have a function to show a Solana Pay modal
+ showSolanaPayModal(data.solanaPayUrl);
+ button.textContent = 'Pay...';
+ })
+ .catch(err => {
+ console.error('Purchase failed:', err);
+ alert(err.error || 'Could not initiate purchase.');
+ button.disabled = false;
+ button.textContent = 'Buy';
+ });
+}
+
+// Attach the listener
+document.addEventListener('click', handleBuySkillClick);
+
+// You will need to implement this modal function
+function showSolanaPayModal(url) {
+ // 1. Create a modal element
+ // 2. Use a QR code library to generate a QR code from the URL
+ // 3. Append the QR code to the modal and display it
+}
+```
+
+## Verification
+- Click a "Buy" button on the agent detail page.
+- Verify in your browser's developer tools that the `POST` request is sent to the backend.
+- Check that the backend responds with a Solana Pay URL.
+- Ensure that a modal with a QR code appears.
+- Try clicking "Buy" for a skill you've already purchased (if you have seeded data) and verify the error handling.
diff --git a/docs/monetization-feature/07-backend-verify-and-record-purchase.md b/docs/monetization-feature/07-backend-verify-and-record-purchase.md
new file mode 100644
index 000000000..80da0cd63
--- /dev/null
+++ b/docs/monetization-feature/07-backend-verify-and-record-purchase.md
@@ -0,0 +1,76 @@
+---
+status: not-started
+---
+
+# Prompt 7: Backend - Verify and Record Purchase
+
+**Status:** Not Started
+
+## Objective
+Create a backend endpoint to verify a completed Solana transaction and record the skill purchase in the database.
+
+## Explanation
+After a user approves a transaction through the Solana Pay QR code, we need a way to confirm that the payment was successful. Solana Pay includes a mechanism for this. The transaction can be found on-chain and, once verified, the purchase can be recorded in our `user_skill_purchases` table. This endpoint will be responsible for this verification and recording process.
+
+## Instructions
+1. **Create a verification endpoint:**
+ - Create a new API route, e.g., `/api/skills/verify-purchase`.
+ - It should accept a `POST` request with the `transaction_signature`.
+
+2. **Verify the transaction:**
+ - In the endpoint, use the Solana Web3 library (`@solana/web3.js`) to fetch the transaction details using the provided signature.
+ - **Crucially, verify all aspects of the transaction:**
+ - That the transaction was successful.
+ - That the correct amount of the correct SPL token was transferred.
+ - That the token was transferred to the correct recipient (the agent creator).
+ - That the `reference` public key in the transaction matches the one you generated in the purchase initiation step.
+
+3. **Record the purchase:**
+ - If the transaction is valid, insert a new record into the `user_skill_purchases` table.
+ - The record should include the `user_id`, `agent_id`, `skill_name`, price, currency, and the transaction signature.
+
+4. **Polling from the frontend:**
+ - The frontend, after displaying the Solana Pay QR code, will need to poll this verification endpoint to know when the purchase is complete.
+ - The frontend will send the transaction signature (which it can get from the Solana Pay `findTransactionSignature` method) to the backend.
+ - When the backend confirms the purchase, the frontend can close the modal and update the UI to show the skill as "Owned."
+
+## Code Example (`api/skills/verify-purchase.js`)
+
+```javascript
+// api/skills/verify-purchase.js
+import { Connection, PublicKey } from '@solana/web3.js';
+
+export default async function handler(req, res) {
+ // ... authentication and request validation ...
+
+ const { transactionSignature, agentId, skillName } = req.body;
+ const userId = await getUserIdFromSession(req);
+
+ // 1. Fetch transaction from Solana blockchain
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+ const transaction = await connection.getTransaction(transactionSignature);
+
+ // 2. Verify transaction details (this is a simplified example)
+ // In a real app, you would need to parse the transaction instructions
+ // to confirm the amount, mint, and recipient are correct.
+ if (transaction && !transaction.meta.err) {
+ // 3. Record the purchase
+ const price = await getSkillPrice(agentId, skillName); // You need this function
+ await db.query(
+ `INSERT INTO user_skill_purchases (user_id, agent_id, skill_name, purchase_price, purchase_currency, transaction_signature)
+ VALUES ($1, $2, $3, $4, $5, $6)`,
+ [userId, agentId, skillName, price.amount, price.currency_mint, transactionSignature]
+ );
+
+ return res.status(200).json({ success: true, message: 'Purchase successful' });
+ } else {
+ return res.status(400).json({ error: 'Transaction verification failed' });
+ }
+}
+```
+
+## Verification
+- Use a test wallet to complete a purchase generated by your "Buy" button.
+- After the transaction is confirmed, manually call the `/api/skills/verify-purchase` endpoint with the transaction signature.
+- Check your `user_skill_purchases` table to ensure the purchase was recorded correctly.
+- Test with an invalid or failed transaction signature to ensure the endpoint handles errors properly.
diff --git a/docs/monetization-feature/08-ui-polling-for-purchase-completion.md b/docs/monetization-feature/08-ui-polling-for-purchase-completion.md
new file mode 100644
index 000000000..86f200ec1
--- /dev/null
+++ b/docs/monetization-feature/08-ui-polling-for-purchase-completion.md
@@ -0,0 +1,82 @@
+---
+status: not-started
+---
+
+# Prompt 8: UI - Polling for Purchase Completion
+
+**Status:** Not Started
+
+## Objective
+Implement frontend logic to poll the backend for purchase verification and update the UI upon successful purchase.
+
+## Explanation
+After the user is shown the Solana Pay QR code, the frontend needs to know when the transaction is complete. The standard way to do this with Solana Pay is to poll an endpoint on our backend. This task involves writing the JavaScript to repeatedly check for purchase completion and then update the UI in real-time without requiring the user to refresh the page.
+
+## Instructions
+1. **Start polling after QR code is shown:**
+ - In `src/marketplace.js`, in the function that shows the Solana Pay modal (`showSolanaPayModal`), you will need the `reference` public key that you generated on the backend. This should be returned from the `/api/skills/purchase` endpoint.
+ - Use the Solana Pay `findTransactionSignature` method to listen for the transaction on-chain. This will give you the transaction signature once it's found.
+
+2. **Poll the verification endpoint:**
+ - Once `findTransactionSignature` returns a signature, start polling your `/api/skills/verify-purchase` endpoint.
+ - Use a `setInterval` or a recursive `setTimeout` function to make a `POST` request every few seconds (e.g., every 2-3 seconds).
+ - Send the transaction signature to the endpoint.
+
+3. **Handle the polling response:**
+ - If the backend responds with success:
+ - Stop the polling.
+ - Close the payment modal.
+ - Update the UI to reflect that the skill is now owned. You can do this by re-rendering the skills section or by directly manipulating the DOM to change the "Buy" button to an "Owned" badge.
+ - If the backend responds with an error (e.g., transaction not found yet), continue polling.
+ - Implement a timeout for the polling (e.g., 5 minutes) to avoid indefinite requests. If it times out, inform the user that the transaction is taking longer than expected.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+// In your showSolanaPayModal function or similar
+
+async function pollForPurchaseCompletion(reference, agentId, skillName) {
+ const connection = new Connection(SOLANA_RPC_URL);
+ let signature;
+
+ try {
+ signature = await findTransactionSignature(connection, reference, { finality: 'confirmed' });
+ } catch (error) {
+ // Handle timeout or other errors from findTransactionSignature
+ console.error(error);
+ alert('Transaction not found. Please check your wallet.');
+ return;
+ }
+
+ const pollInterval = setInterval(async () => {
+ try {
+ const response = await fetch('/api/skills/verify-purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ transactionSignature: signature, agentId, skillName }),
+ });
+
+ if (response.ok) {
+ clearInterval(pollInterval);
+ closeSolanaPayModal(); // Assume this function exists
+ // Re-render agent details or update the specific skill entry
+ updateSkillAsOwned(skillName);
+ }
+ } catch (error) {
+ console.error('Polling error:', error);
+ }
+ }, 3000);
+
+ // Add a timeout to stop polling after, e.g., 5 minutes
+ setTimeout(() => {
+ clearInterval(pollInterval);
+ }, 300000);
+}
+```
+
+## Verification
+- Go through the full purchase flow in your browser.
+- After scanning the QR code and approving the transaction, watch the browser's network tab to see the polling requests.
+- Verify that once the transaction is confirmed on-chain, the polling stops.
+- Confirm that the UI updates automatically to show the skill as "Owned," and the "Buy" button is removed.
+- Test the timeout logic by generating a QR code but not completing the transaction.
diff --git a/docs/monetization-feature/09-ui-creator-set-prices-interface.md b/docs/monetization-feature/09-ui-creator-set-prices-interface.md
new file mode 100644
index 000000000..85b9d6a9d
--- /dev/null
+++ b/docs/monetization-feature/09-ui-creator-set-prices-interface.md
@@ -0,0 +1,78 @@
+---
+status: not-started
+---
+
+# Prompt 9: UI - Creator-Facing "Set Prices" Interface
+
+**Status:** Not Started
+
+## Objective
+Create a user interface for agent creators to set and manage prices for their skills.
+
+## Explanation
+To enable skill monetization, creators need a way to specify which of their skills are for sale and at what price. This task involves creating a new section in the agent editing interface where a creator can view their agent's skills and set a price for each one. This will be a new page or a new tab in the existing `agent-edit.html`.
+
+## Instructions
+1. **Create the UI component:**
+ - In `agent-edit.html`, add a new tab for "Monetization" or "Skill Pricing."
+ - This panel should fetch and display a list of the agent's skills (from the `capabilities.skills` object in the agent's data).
+ - For each skill, display its name and an input field for the price.
+
+2. **Design the pricing input:**
+ - The price input should be a number field.
+ - Add a currency selector (for now, you can default to USDC, but a dropdown would be better for the future).
+ - Include a "Save Prices" button.
+
+3. **Handle data fetching:**
+ - When the panel loads, it should fetch the current skill prices for the agent from a new backend endpoint (which you'll create in the next step). This ensures that existing prices are displayed for editing.
+
+4. **Handle saving:**
+ - When the "Save Prices" button is clicked, collect the pricing data from all the input fields.
+ - Send this data to a new backend endpoint (`/api/agents/:id/skill-prices`) that will save the prices to the `agent_skill_prices` table.
+
+## Code Example (HTML in `agent-edit.html`)
+
+```html
+<!-- Inside the new "Monetization" tab panel -->
+<div class="edit-panel" id="monetization-panel">
+ <h3>Skill Pricing</h3>
+ <p>Set prices for your skills in USDC. Leave the price as 0 for free skills.</p>
+ <div id="skill-pricing-list">
+ <!-- Skills will be dynamically rendered here -->
+ </div>
+ <button id="save-prices-btn">Save Prices</button>
+</div>
+```
+
+## Code Example (JavaScript to render the pricing list)
+
+```javascript
+// In your agent editing script
+
+async function renderSkillPricing(agentId) {
+ const agent = await fetchAgentData(agentId); // Assumes you have this
+ const skills = agent.capabilities.skills || [];
+ const prices = await fetchSkillPrices(agentId); // You'll build this endpoint
+
+ const listEl = document.getElementById('skill-pricing-list');
+ listEl.innerHTML = skills.map(skill => {
+ const price = prices[skill.name] || { amount: 0, currency_mint: 'USDC' };
+ const priceInUSDC = price.amount / 1e6;
+
+ return `
+ <div class="skill-price-entry">
+ <span class="skill-name">${skill.name}</span>
+ <input type="number" class="price-input" data-skill-name="${skill.name}" value="${priceInUSDC}" min="0" step="0.01">
+ <span class="currency-label">USDC</span>
+ </div>
+ `;
+ }).join('');
+}
+```
+
+## Verification
+- Navigate to the agent edit page.
+- Verify that the new "Monetization" tab is present.
+- Check that it correctly lists the agent's skills.
+- Ensure that price input fields and a "Save" button are visible.
+- The save functionality will be verified after the next prompt's task (creating the backend endpoint) is complete.
diff --git a/docs/monetization-feature/10-backend-save-skill-prices.md b/docs/monetization-feature/10-backend-save-skill-prices.md
new file mode 100644
index 000000000..15e11cffb
--- /dev/null
+++ b/docs/monetization-feature/10-backend-save-skill-prices.md
@@ -0,0 +1,97 @@
+---
+status: not-started
+---
+
+# Prompt 10: Backend - Save Skill Prices Endpoint
+
+**Status:** Not Started
+
+## Objective
+Create a backend endpoint for saving or updating skill prices for an agent.
+
+## Explanation
+The creator-facing UI for setting prices needs a backend endpoint to persist the data. This endpoint will receive a list of skills and their prices and will perform an "upsert" operation (insert or update) into the `agent_skill_prices` table. This is a critical step in allowing creators to manage their skill offerings.
+
+## Instructions
+1. **Create the API route:**
+ - Create a new API route to handle this, e.g., `/api/agents/:id/skill-prices`.
+ - It should accept `POST` or `PUT` requests.
+ - This endpoint must be authenticated, and you must verify that the logged-in user is the owner of the agent they are trying to price skills for.
+
+2. **Handle the request:**
+ - The request body should contain an object or array of skill prices, e.g., `[{ skill_name: 'text-to-speech', price: 1.50, currency: 'USDC' }, ...]`.
+ - Loop through the submitted prices.
+ - For each skill price, perform an `UPSERT` operation on the `agent_skill_prices` table.
+ - If a price for that `agent_id` and `skill_name` already exists, `UPDATE` it.
+ - If it doesn't exist, `INSERT` a new row.
+ - Remember to convert the price from the human-readable format (e.g., 1.50 USDC) to the smallest unit (e.g., 1,500,000 lamports) before saving.
+
+3. **Handle price removal:**
+ - If a creator sets a price to 0 or removes it, you can either delete the corresponding row from `agent_skill_prices` or mark it as inactive (e.g., with an `is_active` flag). Deleting is simpler for now.
+
+## Code Example (SQL for `UPSERT`)
+
+This example uses PostgreSQL syntax for an `UPSERT` operation.
+
+```sql
+-- For each skill price provided in the API request body...
+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 = EXCLUDED.amount,
+ currency_mint = EXCLUDED.currency_mint,
+ updated_at = NOW();
+```
+
+## Code Example (Node.js/Express-like handler)
+
+```javascript
+// api/agents/[id]/skill-prices.js
+
+export default async function handler(req, res) {
+ // ... authentication and ownership verification ...
+ const agentId = req.query.id;
+ const pricesToSet = req.body.prices; // e.g., [{ skill_name, price, currency }]
+
+ // Use a transaction to update all prices atomically
+ const client = await db.getClient();
+ try {
+ await client.query('BEGIN');
+
+ for (const p of pricesToSet) {
+ const amountInSmallestUnit = p.price * 1e6; // Convert to lamports
+ if (amountInSmallestUnit > 0) {
+ await client.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, updated_at = NOW()`,
+ [agentId, p.skill_name, amountInSmallestUnit, 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7Gz3'] // USDC mint
+ );
+ } else {
+ // If price is 0, delete the record
+ await client.query(
+ 'DELETE FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2',
+ [agentId, p.skill_name]
+ );
+ }
+ }
+
+ await client.query('COMMIT');
+ res.status(200).json({ success: true, message: 'Prices updated' });
+ } catch (error) {
+ await client.query('ROLLBACK');
+ res.status(500).json({ error: 'Failed to update prices' });
+ } finally {
+ client.release();
+ }
+}
+```
+
+## Verification
+- On the "Monetization" tab of the agent edit page, set some prices for skills.
+- Click "Save Prices."
+- Check the network tab in your browser's developer tools to ensure the request is sent correctly.
+- Verify that the data in your `agent_skill_prices` table is updated as expected.
+- Reload the page and confirm that the prices you set are correctly displayed in the input fields.
+- Try setting a price to 0 and verify that the corresponding row is deleted from the database.
diff --git a/docs/monetization/01-display-priced-skills.md b/docs/monetization/01-display-priced-skills.md
index 4f41e44f2..898c69a71 100644
--- a/docs/monetization/01-display-priced-skills.md
+++ b/docs/monetization/01-display-priced-skills.md
@@ -1,5 +1,5 @@
---
-status: not-started
+status: completed
---
# Prompt 1: Display Priced Skills in Marketplace
diff --git a/docs/monetization/02-add-wallet-connect-button.md b/docs/monetization/02-add-wallet-connect-button.md
index ab2363062..511b7478a 100644
--- a/docs/monetization/02-add-wallet-connect-button.md
+++ b/docs/monetization/02-add-wallet-connect-button.md
@@ -1,7 +1,7 @@
# Prompt 2: Add "Connect Wallet" Button
## Status
-- [ ] Not Started
+- [x] Completed
## Objective
Integrate a "Connect Wallet" button into the main application header, which will serve as the entry point for users to connect their Solana wallets.
diff --git a/docs/monetization/02-display-priced-skills-api.md b/docs/monetization/02-display-priced-skills-api.md
index 4c308a13c..5c8fdf5fe 100644
--- a/docs/monetization/02-display-priced-skills-api.md
+++ b/docs/monetization/02-display-priced-skills-api.md
@@ -1,6 +1,6 @@
---
-status: not-started
-completed_at: null
+status: completed
+completed_at: 2026-05-04T12:05:00Z
---
# Prompt 2: Modify Agent Detail API to Include Skill Prices
diff --git a/docs/monetization/04-premium-indicator-marketplace.md b/docs/monetization/04-premium-indicator-marketplace.md
new file mode 100644
index 000000000..b437c2359
--- /dev/null
+++ b/docs/monetization/04-premium-indicator-marketplace.md
@@ -0,0 +1,86 @@
+---
+status: not-started
+---
+
+# Prompt 4: Premium Indicator in Marketplace
+
+## Objective
+Add a "Premium" indicator or tag to agents that have at least one paid skill in the main marketplace list view.
+
+## Explanation
+To help users quickly identify monetized agents, we need a visual cue on the main marketplace page (`marketplace.html`). This makes premium agents stand out and signals that they offer advanced, paid functionality.
+
+## Instructions
+1. **Modify the Backend API:**
+ * Locate the API endpoint that serves the list of agents for the marketplace (e.g., `/api/marketplace/agents`).
+ * The query should be modified to check if each agent has any associated entries in the `agent_skill_prices` table.
+ * A simple way is to use a `LEFT JOIN` and a `COUNT` or an `EXISTS` subquery.
+ * The API response for each agent object should now include a boolean flag, e.g., `has_paid_skills: true`.
+
+2. **Update the Frontend UI:**
+ * In the JavaScript file for the marketplace, locate the function that renders the list or grid of agent cards.
+ * When iterating through the agents, check for the `has_paid_skills` flag.
+ * If `true`, add a "Premium" badge or icon to the agent's card template.
+
+## Code Example (Backend - SQL Query)
+
+A possible SQL modification to get the flag:
+
+```sql
+SELECT
+ agents.*,
+ EXISTS (
+ SELECT 1
+ FROM agent_skill_prices
+ WHERE agent_skill_prices.agent_id = agents.id
+ ) AS has_paid_skills
+FROM
+ agents
+-- ... add your WHERE clauses, LIMIT, OFFSET etc.
+```
+
+## Code Example (Frontend - Agent Card Rendering)
+
+```javascript
+// Inside the function that renders multiple agent cards
+function renderAgentCard(agent) {
+ const premiumBadge = agent.has_paid_skills
+ ? `<span class="premium-badge">💎 Premium</span>`
+ : '';
+
+ return `
+ <div class="agent-card">
+ <div class="card-header">
+ <span class="agent-name">${escapeHtml(agent.name)}</span>
+ ${premiumBadge}
+ </div>
+ <div class="agent-description">${escapeHtml(agent.description)}</div>
+ // ... rest of the card
+ </div>
+ `;
+}
+```
+
+## CSS Example
+
+Add these styles to the marketplace CSS file.
+
+```css
+.premium-badge {
+ display: inline-block;
+ margin-left: auto; /* Pushes it to the right in a flex container */
+ padding: 3px 8px;
+ font-size: 10px;
+ font-weight: 700;
+ border-radius: 99px;
+ color: #facc15; /* A gold/yellow color */
+ background-color: rgba(250, 204, 21, 0.1);
+ border: 1px solid rgba(250, 204, 21, 0.2);
+}
+
+.card-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+```
diff --git a/docs/monetization/05-filter-marketplace-price.md b/docs/monetization/05-filter-marketplace-price.md
new file mode 100644
index 000000000..6a6ffcfe0
--- /dev/null
+++ b/docs/monetization/05-filter-marketplace-price.md
@@ -0,0 +1,84 @@
+---
+status: not-started
+---
+
+# Prompt 5: Filter Marketplace by Price
+
+## Objective
+Implement a filter control in the marketplace UI to allow users to view "All", "Free", or "Paid" agents.
+
+## Explanation
+Adding a filter enhances user experience by allowing them to narrow down the agent list based on their interest in free or premium offerings. This requires a small UI addition and logic to re-fetch the agent list with the selected filter.
+
+## Instructions
+1. **Update the Frontend UI (`marketplace.html`):**
+ * Add a set of filter buttons or a dropdown menu to the marketplace page, typically above the agent list.
+ * The options should be "All", "Free", and "Paid".
+
+2. **Update the Backend API:**
+ * Modify the marketplace agent list endpoint (e.g., `/api/marketplace/agents`) to accept a query parameter, such as `pricing`.
+ * The backend should interpret `pricing=free`, `pricing=paid`, or no parameter (for "all").
+ * If `pricing=free`, the query should be adjusted to only return agents that do NOT have any entries in `agent_skill_prices`.
+ * If `pricing=paid`, the query should only return agents that HAVE at least one entry in `agent_skill_prices`.
+
+3. **Update Frontend JavaScript:**
+ * Add event listeners to the new filter controls.
+ * When a filter is selected, store the chosen value (e.g., 'free', 'paid').
+ * Trigger a function to re-fetch the agent list from the API, appending the new query parameter (e.g., `?pricing=paid`).
+ * The existing rendering logic should then automatically display the filtered list.
+ * Remember to handle pagination correctly if it's implemented.
+
+## Code Example (HTML)
+
+```html
+<div class="marketplace-filters">
+ <button class="filter-btn active" data-filter="all">All</button>
+ <button class="filter-btn" data-filter="free">Free</button>
+ <button class="filter-btn" data-filter="paid">Paid</button>
+</div>
+```
+
+## Code Example (Frontend JavaScript)
+
+```javascript
+let currentPriceFilter = 'all';
+
+document.querySelector('.marketplace-filters').addEventListener('click', (e) => {
+ if (e.target.classList.contains('filter-btn')) {
+ document.querySelectorAll('.filter-btn').forEach(btn => btn.classList.remove('active'));
+ e.target.classList.add('active');
+ currentPriceFilter = e.target.dataset.filter;
+ fetchAndRenderAgents(); // Your main function to get and display agents
+ }
+});
+
+async function fetchAndRenderAgents(page = 1) {
+ let apiUrl = `/api/marketplace/agents?page=${page}`;
+ if (currentPriceFilter !== 'all') {
+ apiUrl += `&pricing=${currentPriceFilter}`;
+ }
+ // ... rest of the fetch and render logic
+}
+```
+
+## Code Example (Backend - SQL Query Modification)
+
+This demonstrates how to adjust the SQL query based on the filter.
+
+```sql
+-- Base Query
+let query = `
+ SELECT agents.*, EXISTS (...) AS has_paid_skills
+ FROM agents
+`;
+
+// Filtering logic
+if (req.query.pricing === 'paid') {
+ query += ` WHERE EXISTS (SELECT 1 FROM agent_skill_prices p WHERE p.agent_id = agents.id)`;
+} else if (req.query.pricing === 'free') {
+ query += ` WHERE NOT EXISTS (SELECT 1 FROM agent_skill_prices p WHERE p.agent_id = agents.id)`;
+}
+
+// Add ordering, limit, offset, etc.
+// ...
+```
diff --git a/docs/monetization/06-solana-pay-integration.md b/docs/monetization/06-solana-pay-integration.md
new file mode 100644
index 000000000..446e3c319
--- /dev/null
+++ b/docs/monetization/06-solana-pay-integration.md
@@ -0,0 +1,91 @@
+---
+status: not-started
+---
+
+# Prompt 6: Solana Pay Integration
+
+## Objective
+Integrate the Solana Pay SDK and set up the basic client-side structure for handling skill purchases.
+
+## Explanation
+To facilitate payments, we will use Solana Pay, a standard for decentralized payments on the Solana blockchain. This prompt covers the initial setup of the Solana Pay JavaScript library and creating placeholder functions for the purchase flow.
+
+## Instructions
+1. **Add Solana Pay SDK:**
+ * Include the Solana Pay SDK in your frontend. You can add it via a script tag from a CDN or install it as an npm package if you have a build process.
+ * For example: `<script src="https://unpkg.com/@solana/[email protected]/dist/index.iife.js"></script>`
+
+2. **Add Solana Web3.js SDK:**
+ * Solana Pay often works in conjunction with the core Solana Web3 library. Include this as well.
+ * For example: `<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>`
+
+3. **Create a Purchase Module:**
+ * In your frontend JavaScript for the agent detail page, create a new section or object to handle the purchase logic.
+ * This module will contain functions to initiate a purchase, create a transaction request, display a QR code, and monitor the transaction status.
+
+4. **Implement Placeholder Functions:**
+ * Create empty or `console.log` stub functions for the main steps:
+ * `initiatePurchase(skillName)`: Called when a user clicks a "Buy" button.
+ * `fetchTransactionRequest(skillName)`: Will call our backend to get transaction details.
+ * `displayPaymentQR(transactionUrl)`: Will use the Solana Pay SDK to generate and show a QR code.
+ * `monitorTransaction(transactionSignature)`: Will poll the blockchain to confirm the payment.
+
+## Code Example (HTML - adding scripts in `marketplace.html`)
+
+```html
+<!-- At the end of your body tag -->
+<script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>
+<script src="https://unpkg.com/@solana/[email protected]/dist/index.iife.js"></script>
+<script src="/src/marketplace.js"></script> <!-- Your app's script -->
+```
+
+## Code Example (JavaScript - Purchase Module Stub)
+
+```javascript
+// In your marketplace JavaScript file
+
+const PurchaseFlow = {
+ async initiatePurchase(agent, skillName) {
+ console.log(`Initiating purchase for skill: ${skillName} from agent: ${agent.name}`);
+
+ // 1. Fetch transaction details from our backend
+ const transactionUrl = await this.fetchTransactionRequest(agent.id, skillName);
+ if (!transactionUrl) return;
+
+ // 2. Display QR code for payment
+ this.displayPaymentQR(transactionUrl);
+
+ // 3. Monitor for payment completion (to be fully implemented later)
+ // This part requires getting a signature, which is part of the Solana Pay flow.
+ // For now, we can just log.
+ console.log('Purchase flow started. Waiting for payment...');
+ },
+
+ async fetchTransactionRequest(agentId, skillName) {
+ console.log('Fetching transaction request from backend...');
+ // In the next step, this will make a real API call.
+ // For now, it's a placeholder.
+ // The backend will return a Solana Pay URL like:
+ // "solana:https://your-api.com/api/purchase/transaction?agent=...&skill=..."
+ // We'll stub this out later.
+ showToast('Backend for transactions not implemented yet.', 'error');
+ return null;
+ },
+
+ displayPaymentQR(url) {
+ console.log(`Displaying QR code for URL: ${url}`);
+ // This will be implemented using SolanaPay.createQR()
+ // and rendered into a modal.
+ showToast('QR code display not implemented yet.', 'error');
+ },
+
+ async monitorTransaction(signature) {
+ console.log(`Monitoring signature: ${signature}`);
+ // This will use solanaWeb3.Connection to check transaction status.
+ showToast('Transaction monitoring not implemented yet.', 'error');
+ }
+};
+
+// Example of how it would be called from the skill rendering logic:
+// <button onclick="PurchaseFlow.initiatePurchase(...)">Buy</button>
+```
diff --git a/docs/monetization/07-purchase-skill-ui.md b/docs/monetization/07-purchase-skill-ui.md
new file mode 100644
index 000000000..a4cf1b907
--- /dev/null
+++ b/docs/monetization/07-purchase-skill-ui.md
@@ -0,0 +1,109 @@
+---
+status: not-started
+---
+
+# Prompt 7: Purchase Skill UI
+
+## Objective
+Create the user interface elements for purchasing a skill, including a "Buy" button and a modal to display the payment QR code.
+
+## Explanation
+With the basic Solana Pay integration in place, we now need the UI that users will interact with. This involves replacing the price badge for unowned, paid skills with a "Buy" button and designing a modal window that will contain the payment instructions and QR code.
+
+## Instructions
+1. **Update Skill Rendering Logic:**
+ * In the agent detail page's JavaScript, modify the skill rendering function.
+ * For a paid skill that the user has *not* yet purchased, instead of just a price badge, render a "Buy" button alongside the price.
+ * The button should have an event listener (e.g., `onclick`) that calls the `PurchaseFlow.initiatePurchase(agent, skillName)` function.
+ * You will need a (currently mock) function `userHasSkill(skillName)` to check ownership.
+
+2. **Create the Payment Modal HTML:**
+ * In `marketplace.html`, add the HTML structure for a modal dialog.
+ * It should be hidden by default (e.g., with `display: none`).
+ * The modal should include:
+ * A title, e.g., "Complete Your Purchase".
+ * A container element where the QR code will be rendered.
+ * An area to display information like the skill name and price.
+ * A "Cancel" or close button.
+
+3. **Style the Modal:**
+ * Add CSS to style the modal as an overlay with a centered content box, similar to other modals in the application.
+
+4. **Implement Modal Show/Hide Logic:**
+ * Create simple JavaScript functions `showPaymentModal()` and `hidePaymentModal()`.
+ * The `PurchaseFlow.displayPaymentQR` function will call `showPaymentModal()` once it's ready to display the QR code.
+ * The close button and overlay background should call `hidePaymentModal()`.
+
+## Code Example (Updated Skill Rendering)
+
+```javascript
+// (Assuming a mock function `userHasSkill` for now)
+const userUnlockedSkills = []; // Mock: will be populated with user data
+function userHasSkill(skillName) {
+ return userUnlockedSkills.includes(skillName);
+}
+
+// Inside agent detail rendering
+const skillPrices = agent.skill_prices || {};
+skillsElement.innerHTML = agent.skills.map(skill => {
+ const name = skill.name || skill;
+ const price = skillPrices[name];
+
+ let badgeOrButton;
+ if (price) {
+ if (userHasSkill(name)) {
+ badgeOrButton = `<span class="price-badge price-unlocked">✅ Purchased</span>`;
+ } else {
+ const priceStr = `${(price.amount / 1e6).toFixed(2)} USDC`;
+ badgeOrButton = `<span class="price-badge price-paid">${priceStr}</span>
+ <button class="buy-button" onclick='PurchaseFlow.initiatePurchase(${JSON.stringify(agent)}, "${escapeJs(name)}")'>Buy</button>`;
+ }
+ } else {
+ badgeOrButton = `<span class="price-badge price-free">Free</span>`;
+ }
+ return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;
+}).join('');
+```
+
+## Code Example (HTML for Payment Modal)
+
+```html
+<!-- Add this somewhere in your marketplace.html body -->
+<div id="payment-modal-backdrop" class="modal-backdrop">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h3>Complete Your Purchase</h3>
+ <button id="payment-modal-close" class="close-button">&times;</button>
+ </div>
+ <div class="modal-body">
+ <p>Scan the code with a Solana Pay compatible wallet to purchase:</p>
+ <strong id="payment-skill-name"></strong> for <strong id="payment-skill-price"></strong>
+ <div id="payment-qr-container">
+ <!-- QR Code will be rendered here -->
+ </div>
+ <div class="spinner" id="payment-spinner"></div>
+ <p class="status-text" id="payment-status-text">Waiting for payment...</p>
+ </div>
+ </div>
+</div>
+```
+
+## CSS for Buy Button
+
+```css
+.buy-button {
+ background-color: var(--accent);
+ color: #000;
+ border: none;
+ border-radius: 4px;
+ padding: 3px 8px;
+ font-size: 10px;
+ font-weight: 600;
+ cursor: pointer;
+ margin-left: 8px;
+ vertical-align: middle;
+}
+.buy-button:hover {
+ background-color: #00ff55;
+}
+```
diff --git a/docs/monetization/08-backend-solana-pay-transaction.md b/docs/monetization/08-backend-solana-pay-transaction.md
new file mode 100644
index 000000000..d89c1afce
--- /dev/null
+++ b/docs/monetization/08-backend-solana-pay-transaction.md
@@ -0,0 +1,105 @@
+---
+status: not-started
+---
+
+# Prompt 8: Backend Solana Pay Transaction Request
+
+## Objective
+Create a backend API endpoint that generates a Solana Pay transaction request for a specific skill purchase.
+
+## Explanation
+When a user clicks "Buy", the frontend needs to ask the backend to prepare a transaction. The backend will define the transaction parameters (recipient, amount, etc.) and encode them into a special URL format that Solana Pay wallets understand. This ensures that the payment details are secure and controlled by the platform.
+
+## Instructions
+1. **Create the API Endpoint:**
+ * Create a new GET endpoint, for example, `/api/purchase/transaction`.
+ * This endpoint should accept query parameters for `agentId` and `skillName`.
+
+2. **Logic to Fetch Price:**
+ * Inside the endpoint, use the `agentId` and `skillName` to look up the price from the `agent_skill_prices` table in your database.
+ * If no price is found, return an error.
+
+3. **Define Transaction Parameters:**
+ * **Recipient:** This should be the agent owner's public key, which you should have stored alongside the agent's data. For now, you can use a placeholder wallet address.
+ * **Amount:** The price of the skill, fetched from the database.
+ * **SPL Token:** The currency mint address (e.g., USDC).
+ * **Reference:** A unique public key generated on the fly for this specific transaction. This is crucial for tracking the payment later. Use `Keypair.generate().publicKey`.
+ * **Label:** The name of your platform or store.
+ * **Message:** A descriptive message, e.g., "Purchase of 'SkillName' for 'AgentName'".
+ * **Memo:** A short, unique identifier for the purchase, which will be attached to the on-chain transaction. This helps with auditing. E.g., `agent-123:skill-abc`.
+
+4. **Construct Solana Pay URL:**
+ * The endpoint needs to return a URL that starts with `solana:`. The rest of the URL is the *URL of the endpoint itself*, which the wallet will then call to get the transaction details.
+ * Example: `solana:https://your-api.com/api/purchase/details?agentId=...&skillName=...`
+
+5. **Create the Transaction Details Endpoint:**
+ * Create a second endpoint (e.g., `POST /api/purchase/details`) that the wallet will call. This is part of the Solana Pay spec.
+ * This endpoint receives the user's public key in the request body (`{ account: "USER_WALLET_ADDRESS" }`).
+ * It should return a JSON object containing the full transaction details, including a base64-encoded, serialized transaction.
+ * Use the `@solana/web3.js` library to build a `SystemProgram.transfer` or `splToken.createTransferInstruction` transaction.
+ * Add the `memo` to the transaction.
+ * Serialize the transaction, but **do not sign it**. The user's wallet will sign.
+
+## Code Example (Backend - Express.js style)
+
+```javascript
+// This is the first endpoint the frontend calls
+// GET /api/purchase/transaction?agentId=...&skillName=...
+app.get('/api/purchase/transaction', (req, res) => {
+ const { agentId, skillName } = req.query;
+ // IMPORTANT: The URL returned here is the *next* endpoint the wallet will call.
+ const url = new URL(`${req.protocol}://${req.get('host')}/api/purchase/details`);
+ url.searchParams.set('agentId', agentId);
+ url.searchParams.set('skillName', skillName);
+
+ // This is the URL the QR code will encode
+ const solanaPayUrl = `solana:${encodeURIComponent(url.toString())}`;
+ res.json({ url: solanaPayUrl });
+});
+
+
+// This is the second endpoint the WALLET calls
+// POST /api/purchase/details
+app.post('/api/purchase/details', async (req, res) => {
+ const { account } = req.body; // User's wallet address
+ const { agentId, skillName } = req.query;
+
+ // 1. Fetch skill price and agent owner's wallet from DB
+ const priceInfo = await db.getSkillPrice(agentId, skillName); // { amount, currency_mint, owner_wallet }
+ if (!priceInfo) {
+ return res.status(404).json({ error: "Skill or price not found" });
+ }
+
+ // 2. Create a reference keypair for tracking
+ const reference = new solanaWeb3.Keypair().publicKey;
+
+ // 3. Build the transaction
+ const transaction = new solanaWeb3.Transaction();
+ // ... logic to get recent blockhash ...
+
+ // Add a transfer instruction
+ transaction.add(
+ splToken.createTransferInstruction(...) // From: `account`, To: `priceInfo.owner_wallet`, Amount: `priceInfo.amount`
+ );
+
+ // Add the memo
+ transaction.add(new solanaWeb3.TransactionInstruction({
+ keys: [],
+ programId: new solanaWeb3.PublicKey('MemoSq4gqABAXKb96qnH8TysNcVnuizgaCgWvunP'),
+ data: Buffer.from(`Purchase: ${skillName} from Agent ${agentId}`),
+ }));
+
+ transaction.feePayer = new solanaWeb3.PublicKey(account);
+ transaction.recentBlockhash = ...;
+
+ // 4. Serialize and encode
+ const serializedTx = transaction.serialize({ requireAllSignatures: false });
+ const base64Tx = serializedTx.toString('base64');
+
+ // 5. Return the response in Solana Pay format
+ res.json({
+ transaction: base64Tx,
+ message: `Purchase ${skillName}`,
+ });
+});
+```
diff --git a/docs/monetization/09-frontend-solana-pay-qr.md b/docs/monetization/09-frontend-solana-pay-qr.md
new file mode 100644
index 000000000..9ed47b6fc
--- /dev/null
+++ b/docs/monetization/09-frontend-solana-pay-qr.md
@@ -0,0 +1,113 @@
+---
+status: not-started
+---
+
+# Prompt 9: Frontend Solana Pay QR Code
+
+## Objective
+Implement the frontend logic to display the Solana Pay QR code in the payment modal and handle user interaction.
+
+## Explanation
+Once the frontend receives the Solana Pay URL from the backend, it needs to use the Solana Pay SDK to render it as a scannable QR code. This prompt covers the client-side rendering and the beginning of the payment monitoring loop.
+
+## Instructions
+1. **Update `fetchTransactionRequest`:**
+ * In the `PurchaseFlow` module, modify the `fetchTransactionRequest` function.
+ * It should now make a real `fetch` call to your new backend endpoint (`/api/purchase/transaction`).
+ * It should expect a JSON response like `{ url: "solana:..." }` and return the URL.
+
+2. **Implement `displayPaymentQR`:**
+ * This function will take the Solana Pay URL as an argument.
+ * Get the QR code container element from the payment modal.
+ * Use the `SolanaPay.createQR()` function from the SDK to generate the QR code. This function takes a URL and optional parameters for size and background color.
+ * Append the generated QR code (which is an `HTMLDivElement`) to your container.
+ * Populate the modal with skill name and price information.
+ * Finally, call `showPaymentModal()` to reveal the modal to the user.
+
+3. **Start the Monitoring Loop:**
+ * The Solana Pay QR code flow includes a reference keypair that allows you to find the transaction once it's been confirmed.
+ * The `createQR` function can help with this. The Solana Pay spec involves the wallet calling your API, and your API finding the transaction.
+ * A simple way to start is to begin polling a "check status" endpoint on your backend after displaying the QR code.
+ * Modify `initiatePurchase` to start a `setInterval` loop that calls a new function, e.g., `checkPaymentStatus()`.
+
+## Code Example (JavaScript - `PurchaseFlow` module)
+
+```javascript
+const PurchaseFlow = {
+ // ... other functions
+ currentPurchase: null, // To store state between steps
+
+ async initiatePurchase(agent, skillName) {
+ // Store context for use in other functions
+ this.currentPurchase = { agent, skillName, reference: null };
+
+ // Get the Solana Pay URL from our server
+ const response = await fetch(`/api/purchase/transaction?agentId=${agent.id}&skillName=${encodeURIComponent(skillName)}`);
+ if (!response.ok) {
+ showToast('Error creating transaction.', 'error');
+ return;
+ }
+ const { url, reference } = await response.json(); // Assume backend also returns the reference public key
+ this.currentPurchase.reference = new solanaWeb3.PublicKey(reference);
+
+ this.displayPaymentQR(url, agent, skillName);
+
+ // Start checking for the transaction confirmation
+ this.startMonitoring();
+ },
+
+ displayPaymentQR(url, agent, skillName) {
+ const qrContainer = document.getElementById('payment-qr-container');
+ qrContainer.innerHTML = ''; // Clear previous QR code
+
+ // Use the Solana Pay SDK to create the QR code element
+ const qr = SolanaPay.createQR(url, 300, 'white', 'black');
+ qrContainer.appendChild(qr.canvas);
+
+ // Update modal text
+ const price = agent.skill_prices[skillName];
+ document.getElementById('payment-skill-name').textContent = skillName;
+ document.getElementById('payment-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
+
+ // Show the modal
+ showPaymentModal();
+ },
+
+ startMonitoring() {
+ this.stopMonitoring(); // Clear any existing interval
+ this.monitoringInterval = setInterval(async () => {
+ try {
+ // This will be a new backend endpoint
+ const response = await fetch(`/api/purchase/status?reference=${this.currentPurchase.reference.toBase58()}`);
+ const data = await response.json();
+
+ if (data.status === 'confirmed') {
+ this.stopMonitoring();
+ showToast('Payment confirmed!', 'success');
+ hidePaymentModal();
+ // TODO: Refresh UI to show the skill as "Purchased"
+ } else if (data.status === 'expired') {
+ this.stopMonitoring();
+ showToast('Transaction expired.', 'error');
+ hidePaymentModal();
+ }
+ } catch (e) {
+ console.error('Error checking payment status:', e);
+ }
+ }, 2000); // Poll every 2 seconds
+ },
+
+ stopMonitoring() {
+ if (this.monitoringInterval) {
+ clearInterval(this.monitoringInterval);
+ this.monitoringInterval = null;
+ }
+ }
+};
+
+// Ensure monitoring stops when the modal is closed manually
+document.getElementById('payment-modal-close').addEventListener('click', () => {
+ PurchaseFlow.stopMonitoring();
+ hidePaymentModal();
+});
+```
diff --git a/docs/monetization/11-reflect-unlocked-skills.md b/docs/monetization/11-reflect-unlocked-skills.md
new file mode 100644
index 000000000..4abbd17f2
--- /dev/null
+++ b/docs/monetization/11-reflect-unlocked-skills.md
@@ -0,0 +1,97 @@
+---
+status: not-started
+---
+
+# Prompt 11: Reflect Unlocked Skills in UI
+
+## Objective
+Update the user interface to visually indicate which skills a user has purchased and remove the "Buy" button for those skills.
+
+## Explanation
+After a user successfully purchases a skill, the UI should immediately update to reflect their new ownership status. This provides instant gratification and prevents them from trying to buy the same skill again. This requires fetching the user's unlocked skills and using that data in the rendering logic.
+
+## Instructions
+1. **Create a Backend Endpoint for User Skills:**
+ * Create a new API endpoint, e.g., `GET /api/users/me/unlocked-skills`.
+ * This endpoint should be authenticated and return a list of all skills the currently logged-in user has purchased.
+ * The response could be an array of objects, e.g., `[{ agent_id: '...', skill_name: '...' }]`, or structured as a map for easier lookup on the frontend.
+
+2. **Fetch Unlocked Skills on Page Load:**
+ * In the marketplace JavaScript, when the agent detail page loads, make a call to this new endpoint.
+ * Store the list of unlocked skills in a client-side variable (e.g., a `Set` for fast lookups).
+
+3. **Update the `userHasSkill` Function:**
+ * Modify the mock `userHasSkill` function created in a previous step.
+ * It should now check against the list of skills fetched from the API. The check might need to be specific to the agent, e.g., `userHasSkill(agentId, skillName)`.
+
+4. **Trigger UI Re-render After Purchase:**
+ * In the `PurchaseFlow` module, after a transaction is successfully confirmed, the UI needs to be updated.
+ * The simplest way is to add the newly purchased skill to the client-side list of unlocked skills and then call the main `renderDetail` function again to completely re-render the agent's skill list.
+
+## Code Example (Backend API - User Skills)
+
+```javascript
+// GET /api/users/me/unlocked-skills
+app.get('/api/users/me/unlocked-skills', async (req, res) => {
+ const userId = await getUserIdFromRequest(req);
+ if (!userId) {
+ return res.status(401).json({ error: 'Unauthorized' });
+ }
+ const { rows } = await db.query(
+ 'SELECT agent_id, skill_name FROM user_unlocked_skills WHERE user_id = $1',
+ [userId]
+ );
+ // Return a map for easy frontend lookup: { "agentId:skillName": true }
+ const unlockedSkillsMap = rows.reduce((acc, row) => {
+ acc[`${row.agent_id}:${row.skill_name}`] = true;
+ return acc;
+ }, {});
+ res.json(unlockedSkillsMap);
+});
+```
+
+## Code Example (Frontend JavaScript)
+
+```javascript
+// --- State management ---
+let unlockedSkills = {}; // Will hold the map from the API
+
+// --- On page load ---
+async function initializeAgentDetailPage(agentId) {
+ // Fetch agent details...
+ // Then fetch user's skills
+ try {
+ const response = await fetch('/api/users/me/unlocked-skills');
+ if (response.ok) {
+ unlockedSkills = await response.json();
+ }
+ } catch (e) {
+ console.error("Couldn't fetch user skills. Assuming none are unlocked.", e);
+ }
+ // Now render the agent details
+ renderDetail(agent);
+}
+
+// --- Update the check function ---
+function userHasSkill(agentId, skillName) {
+ return !!unlockedSkills[`${agentId}:${skillName}`];
+}
+
+// --- Update rendering logic to use the new check ---
+// (No changes needed if it already calls userHasSkill(agent.id, name))
+
+// --- Update PurchaseFlow on success ---
+// Inside startMonitoring(), in the 'confirmed' block:
+if (data.status === 'confirmed') {
+ this.stopMonitoring();
+ showToast('Payment confirmed!', 'success');
+ hidePaymentModal();
+
+ // Add the skill to our local state
+ const { agent, skillName } = this.currentPurchase;
+ unlockedSkills[`${agent.id}:${skillName}`] = true;
+
+ // Re-render the agent details to update the UI
+ renderDetail(agent);
+}
+```
diff --git a/docs/monetization/12-user-purchase-history.md b/docs/monetization/12-user-purchase-history.md
new file mode 100644
index 000000000..9c6c51365
--- /dev/null
+++ b/docs/monetization/12-user-purchase-history.md
@@ -0,0 +1,115 @@
+---
+status: not-started
+---
+
+# Prompt 12: User Purchase History
+
+## Objective
+Create a new section in the user's profile or dashboard page to display a history of their skill purchases.
+
+## Explanation
+Users should have a record of their transactions and purchased items. A purchase history page provides transparency and allows users to see the value they've received from the platform.
+
+## Instructions
+1. **Create a Backend Endpoint for Purchase History:**
+ * Create a new authenticated API endpoint, e.g., `GET /api/users/me/purchase-history`.
+ * This endpoint should query the `user_unlocked_skills` table for the current user.
+ * It should join with the `agents` and `agent_skill_prices` tables to retrieve richer data for each entry, such as the agent's name, the skill name, the price paid, the currency, the transaction signature, and the purchase date.
+ * The endpoint should support pagination (e.g., using `LIMIT` and `OFFSET`).
+
+2. **Create a New Frontend Page/Section:**
+ * In the user's main dashboard or profile area, add a new tab or link for "Purchase History".
+ * Create the HTML structure for this section, which will primarily be a table to display the history.
+ * The table should have columns for: Agent, Skill, Date, Price, and a link to the transaction on a block explorer.
+
+3. **Implement Frontend Logic:**
+ * When the user navigates to the purchase history section, a JavaScript function should be called to fetch the data from the new API endpoint.
+ * The script should then dynamically render the rows of the table using the fetched data.
+ * Format the data for display (e.g., format dates, format prices, create the block explorer link).
+ * If you implemented pagination, add "Next" and "Previous" buttons.
+
+## Code Example (Backend - SQL Query)
+
+```sql
+SELECT
+ u.skill_name,
+ u.transaction_signature,
+ u.created_at AS purchase_date,
+ a.name AS agent_name,
+ p.amount,
+ p.currency_mint
+FROM
+ user_unlocked_skills u
+JOIN
+ agents a ON u.agent_id = a.id
+LEFT JOIN
+ agent_skill_prices p ON u.agent_id = p.agent_id AND u.skill_name = p.skill_name
+WHERE
+ u.user_id = $1
+ORDER BY
+ u.created_at DESC
+LIMIT 20 OFFSET $2;
+```
+
+## Code Example (HTML Structure)
+
+```html
+<!-- In user-dashboard.html or similar -->
+<div id="purchase-history-section">
+ <h2>Purchase History</h2>
+ <div class="table-container">
+ <table>
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Agent</th>
+ <th>Skill</th>
+ <th>Price</th>
+ <th>Transaction</th>
+ </tr>
+ </thead>
+ <tbody id="purchase-history-table-body">
+ <!-- Rows will be rendered here -->
+ </tbody>
+ </table>
+ </div>
+ <div class="pagination-controls">
+ <button id="history-prev-btn">Previous</button>
+ <button id="history-next-btn">Next</button>
+ </div>
+</div>
+```
+
+## Code Example (Frontend JavaScript)
+
+```javascript
+async function renderPurchaseHistory(page = 1) {
+ const tbody = document.getElementById('purchase-history-table-body');
+ try {
+ const response = await fetch(`/api/users/me/purchase-history?page=${page}`);
+ const history = await response.json();
+
+ if (history.length === 0 && page === 1) {
+ tbody.innerHTML = '<tr><td colspan="5">No purchases yet.</td></tr>';
+ return;
+ }
+
+ tbody.innerHTML = history.map(item => {
+ const price = item.amount ? `${(item.amount / 1e6).toFixed(2)} USDC` : 'N/A';
+ const explorerUrl = `https://solscan.io/tx/${item.transaction_signature}`;
+ return `
+ <tr>
+ <td>${new Date(item.purchase_date).toLocaleDateString()}</td>
+ <td>${escapeHtml(item.agent_name)}</td>
+ <td>${escapeHtml(item.skill_name)}</td>
+ <td>${price}</td>
+ <td><a href="${explorerUrl}" target="_blank" rel="noopener">View on Solscan</a></td>
+ </tr>
+ `;
+ }).join('');
+ } catch (error) {
+ tbody.innerHTML = '<tr><td colspan="5">Failed to load purchase history.</td></tr>';
+ console.error(error);
+ }
+}
+```
diff --git a/docs/monetization/13-subscription-tiers-db-schema.md b/docs/monetization/13-subscription-tiers-db-schema.md
new file mode 100644
index 000000000..70395d835
--- /dev/null
+++ b/docs/monetization/13-subscription-tiers-db-schema.md
@@ -0,0 +1,83 @@
+---
+status: not-started
+---
+
+# Prompt 13: Subscription Tiers Database Schema
+
+## Objective
+Design and create the necessary database tables to support agent-specific subscription tiers.
+
+## Explanation
+To move beyond one-time purchases, we need a system for recurring subscriptions. This starts with a robust database schema that allows creators to define different subscription tiers for their agents, and for the system to track user subscriptions.
+
+## Instructions
+1. **Create `agent_subscription_tiers` Table:**
+ * This table will store the different subscription plans offered by a creator for a specific agent.
+ * **Columns:**
+ * `id`: Primary key (e.g., UUID or SERIAL).
+ * `agent_id`: Foreign key to the `agents` table.
+ * `name`: The name of the tier (e.g., "Supporter", "Pro").
+ * `description`: A short description of the tier's benefits.
+ * `price_amount`: The recurring price in the smallest unit (e.g., lamports).
+ * `price_currency_mint`: The currency of the price.
+ * `interval`: The billing cycle (e.g., 'day', 'week', 'month', 'year').
+ * `interval_count`: The number of intervals per cycle (e.g., 1 for monthly, 3 for quarterly).
+ * `active`: A boolean to allow creators to enable/disable tiers.
+ * `created_at`, `updated_at`: Timestamps.
+
+2. **Create `user_subscriptions` Table:**
+ * This table will track which users are subscribed to which tiers.
+ * **Columns:**
+ * `id`: Primary key.
+ * `user_id`: Foreign key to the `users` table.
+ * `tier_id`: Foreign key to the `agent_subscription_tiers` table.
+ * `status`: The status of the subscription (e.g., 'active', 'past_due', 'canceled', 'expired').
+ * `current_period_start`: Timestamp for the beginning of the current billing cycle.
+ * `current_period_end`: Timestamp for the end of the current billing cycle.
+ * `canceled_at`: Timestamp if the user has canceled but the subscription is still active until the period end.
+ * `ended_at`: Timestamp when the subscription fully ended.
+ * `latest_transaction_signature`: The signature of the most recent payment transaction.
+ * `created_at`, `updated_at`: Timestamps.
+
+## SQL Schema Example (PostgreSQL)
+
+```sql
+-- Table for creators to define their subscription tiers
+CREATE TABLE agent_subscription_tiers (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ price_amount BIGINT NOT NULL CHECK (price_amount >= 0),
+ price_currency_mint VARCHAR(44) NOT NULL,
+ interval VARCHAR(20) NOT NULL, -- e.g., 'day', 'week', 'month'
+ interval_count INT NOT NULL DEFAULT 1,
+ active BOOLEAN NOT NULL DEFAULT TRUE,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (agent_id, name) -- An agent can't have two tiers with the same name
+);
+
+-- Table to track active user subscriptions
+CREATE TYPE subscription_status AS ENUM ('active', 'past_due', 'canceled', 'expired', 'incomplete');
+
+CREATE TABLE user_subscriptions (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ tier_id UUID NOT NULL REFERENCES agent_subscription_tiers(id),
+ status subscription_status NOT NULL DEFAULT 'incomplete',
+ current_period_start TIMESTAMPTZ,
+ current_period_end TIMESTAMPTZ,
+ canceled_at TIMESTAMPTZ,
+ ended_at TIMESTAMPTZ,
+ latest_transaction_signature VARCHAR(88),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE(user_id, tier_id) -- A user can only have one subscription to a specific tier at a time.
+);
+
+-- Indexes for performance
+CREATE INDEX idx_user_subscriptions_user_id ON user_subscriptions(user_id);
+CREATE INDEX idx_agent_subscription_tiers_agent_id ON agent_subscription_tiers(agent_id);
+```
+**Note:** This is a foundational schema. A real-world implementation might be more complex, potentially involving a separate `subscription_periods` table for a more detailed history, but this is a strong starting point.
diff --git a/docs/monetization/14-subscription-tiers-ui-creator.md b/docs/monetization/14-subscription-tiers-ui-creator.md
new file mode 100644
index 000000000..689a952cb
--- /dev/null
+++ b/docs/monetization/14-subscription-tiers-ui-creator.md
@@ -0,0 +1,127 @@
+---
+status: not-started
+---
+
+# Prompt 14: Subscription Tiers UI for Creators
+
+## Objective
+Create a user interface in the agent edit page for creators to define and manage their subscription tiers.
+
+## Explanation
+Creators need a way to create, view, edit, and delete subscription tiers for their agents. This UI will allow them to set up their monetization strategy directly from the agent management dashboard.
+
+## Instructions
+1. **Add a New UI Section in `agent-edit.html`:**
+ * Create a new section titled "Subscription Tiers".
+ * This section should have a button to "Create New Tier".
+ * It should also contain a list or table to display existing tiers for the agent.
+
+2. **Create a Tier Editor Modal:**
+ * Clicking "Create New Tier" (or "Edit" on an existing tier) should open a modal dialog.
+ * The modal form should contain input fields for all the properties of a subscription tier:
+ * Tier Name (text input)
+ * Description (textarea)
+ * Price (number input)
+ * Currency (select, e.g., USDC)
+ * Billing Interval (e.g., a select dropdown with "Monthly", "Yearly").
+ * Active (a checkbox/toggle)
+
+3. **Implement Frontend Logic:**
+ * Write JavaScript to fetch the agent's existing tiers and render them in the list.
+ * Each rendered tier should have "Edit" and "Delete" buttons.
+ * Implement the logic to show the modal and populate it with data when editing an existing tier, or show it empty for a new tier.
+ * The "Save" button in the modal will be wired up to the backend API in the next step.
+ * The "Delete" button should trigger a confirmation prompt before proceeding.
+
+## Code Example (HTML in `agent-edit.html`)
+
+```html
+<div class="form-section">
+ <h2>Subscription Tiers</h2>
+ <div id="existing-tiers-list">
+ <!-- Existing tiers will be rendered here -->
+ </div>
+ <button type="button" id="create-tier-btn" class="cta-button">+ Create New Tier</button>
+</div>
+
+<!-- Tier Editor Modal (hidden by default) -->
+<div id="tier-editor-modal" class="modal-backdrop">
+ <div class="modal-content">
+ <div class="modal-header">
+ <h3 id="tier-modal-title">Create Tier</h3>
+ </div>
+ <div class="modal-body">
+ <input type="hidden" id="tier-id-input">
+ <div class="form-group">
+ <label for="tier-name">Tier Name</label>
+ <input type="text" id="tier-name" placeholder="e.g., Supporter">
+ </div>
+ <div class="form-group">
+ <label for="tier-description">Description</label>
+ <textarea id="tier-description" placeholder="e.g., Access to exclusive content..."></textarea>
+ </div>
+ <div class="form-row">
+ <div class="form-group">
+ <label for="tier-price">Price</label>
+ <input type="number" id="tier-price" placeholder="0.00">
+ </div>
+ <div class="form-group">
+ <label for="tier-currency">Currency</label>
+ <select id="tier-currency">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3">USDC</option>
+ </select>
+ </div>
+ <div class="form-group">
+ <label for="tier-interval">Interval</label>
+ <select id="tier-interval">
+ <option value="month">Monthly</option>
+ <option value="year">Yearly</option>
+ </select>
+ </div>
+ </div>
+ </div>
+ <div class="modal-actions">
+ <button id="cancel-tier-btn" type="button">Cancel</button>
+ <button id="save-tier-btn" type="button" class="cta-button">Save Tier</button>
+ </div>
+ </div>
+</div>
+```
+
+## Code Example (JavaScript Logic)
+
+```javascript
+// Renders the list of existing tiers
+async function renderTiersList(agentId) {
+ const response = await fetch(`/api/agents/${agentId}/tiers`);
+ const tiers = await response.json();
+ const container = document.getElementById('existing-tiers-list');
+
+ container.innerHTML = tiers.map(tier => `
+ <div class="tier-summary-row">
+ <span>${escapeHtml(tier.name)} - ${(tier.price_amount / 1e6).toFixed(2)} USDC / ${tier.interval}</span>
+ <div>
+ <button onclick="openTierModal(${JSON.stringify(tier)})">Edit</button>
+ <button onclick="deleteTier('${tier.id}')">Delete</button>
+ </div>
+ </div>
+ `).join('');
+}
+
+// Opens the modal for creating or editing a tier
+function openTierModal(tier = null) {
+ const modal = document.getElementById('tier-editor-modal');
+ if (tier) {
+ // Populate form with existing tier data for editing
+ document.getElementById('tier-modal-title').textContent = 'Edit Tier';
+ document.getElementById('tier-id-input').value = tier.id;
+ // ... set other input values
+ } else {
+ // Clear form for creating a new tier
+ document.getElementById('tier-modal-title').textContent = 'Create Tier';
+ document.getElementById('tier-id-input').value = '';
+ // ... clear other input values
+ }
+ modal.style.display = 'flex';
+}
+```
diff --git a/docs/monetization/15-save-subscription-tiers-api.md b/docs/monetization/15-save-subscription-tiers-api.md
new file mode 100644
index 000000000..b97dfa138
--- /dev/null
+++ b/docs/monetization/15-save-subscription-tiers-api.md
@@ -0,0 +1,94 @@
+---
+status: not-started
+---
+
+# Prompt 15: Save and Manage Subscription Tiers API
+
+## Objective
+Implement the backend API endpoints for creating, updating, and deleting subscription tiers.
+
+## Explanation
+This prompt provides the backend support for the creator-facing UI built in the previous step. It involves creating a set of CRUD (Create, Read, Update, Delete) APIs to manage the `agent_subscription_tiers` table.
+
+## Instructions
+1. **Create API Routes:**
+ * Set up the following authenticated routes, ensuring that only the agent owner can perform these actions.
+ * `POST /api/agents/:id/tiers`: Create a new subscription tier.
+ * `GET /api/agents/:id/tiers`: Get all tiers for a specific agent.
+ * `PUT /api/agents/:id/tiers/:tierId`: Update an existing tier.
+ * `DELETE /api/agents/:id/tiers/:tierId`: Delete a tier.
+
+2. **Implement Create Logic (`POST`):**
+ * The endpoint receives tier details in the request body.
+ * Validate the input (e.g., price must be a non-negative number).
+ * Insert a new record into the `agent_subscription_tiers` table.
+ * Return the newly created tier object.
+
+3. **Implement Read Logic (`GET`):**
+ * This endpoint can be public or owner-only, depending on whether you want users to see tiers before the UI is ready.
+ * Query the database for all tiers associated with the `agent_id`.
+ * Return the list of tiers.
+
+4. **Implement Update Logic (`PUT`):**
+ * Receive updated tier details in the request body.
+ * Validate the input.
+ * Update the corresponding record in the `agent_subscription_tiers` table where the `id` and `agent_id` match.
+ * Return the updated tier object.
+
+5. **Implement Delete Logic (`DELETE`):**
+ * This is a critical action. Before deleting, check if there are any active subscribers to this tier in the `user_subscriptions` table.
+ * Decide on a policy: either prevent deletion of tiers with active subscribers, or mark the tier as inactive (`active = false`) instead of a hard delete. Marking as inactive is generally safer.
+ * Perform the delete or update operation.
+ * Return a success status.
+
+## Code Example (Backend - Express.js style routes)
+
+```javascript
+// Middleware to verify agent ownership for all tier routes
+const verifyAgentOwner = async (req, res, next) => {
+ const agentId = req.params.id;
+ const userId = await getUserIdFromRequest(req);
+ const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [agentId]);
+ if (!agent || agent.owner_id !== userId) {
+ return res.status(403).json({ error: 'Forbidden' });
+ }
+ next();
+};
+
+const tierRoutes = express.Router({ mergeParams: true });
+tierRoutes.use(verifyAgentOwner);
+
+// GET /api/agents/:id/tiers
+tierRoutes.get('/', async (req, res) => {
+ const tiers = await db.query('SELECT * FROM agent_subscription_tiers WHERE agent_id = $1 ORDER BY price_amount', [req.params.id]);
+ res.json(tiers.rows);
+});
+
+// POST /api/agents/:id/tiers
+tierRoutes.post('/', async (req, res) => {
+ const { name, description, price, currency, interval } = req.body;
+ // Convert price to integer lamports, validate inputs...
+ const amount = Math.round(price * 1e6);
+ const result = await db.query(
+ 'INSERT INTO agent_subscription_tiers (agent_id, name, description, price_amount, price_currency_mint, interval) VALUES ($1, $2, $3, $4, $5, $6) RETURNING *',
+ [req.params.id, name, description, amount, currency, interval]
+ );
+ res.status(201).json(result.rows[0]);
+});
+
+// PUT /api/agents/:id/tiers/:tierId
+tierRoutes.put('/:tierId', async (req, res) => {
+ // ... similar logic to POST for updating ...
+});
+
+// DELETE /api/agents/:id/tiers/:tierId
+tierRoutes.delete('/:tierId', async (req, res) => {
+ const { tierId } = req.params;
+ // SAFER: Mark as inactive instead of deleting
+ await db.query('UPDATE agent_subscription_tiers SET active = false WHERE id = $1', [tierId]);
+ res.status(204).send();
+});
+
+// Mount the routes in your main app file
+// app.use('/api/agents/:id/tiers', tierRoutes);
+```
diff --git a/docs/monetization/16-user-facing-subscription-ui.md b/docs/monetization/16-user-facing-subscription-ui.md
new file mode 100644
index 000000000..b8a583fb8
--- /dev/null
+++ b/docs/monetization/16-user-facing-subscription-ui.md
@@ -0,0 +1,128 @@
+---
+status: not-started
+---
+
+# Prompt 16: User-Facing Subscription UI
+
+## Objective
+Display available subscription tiers on the agent detail page and provide a UI for users to initiate a subscription.
+
+## Explanation
+Now that creators can define tiers, we need to show them to potential subscribers. This involves fetching the tiers for an agent and displaying them in a clear, compelling way, with a "Subscribe" button for each.
+
+## Instructions
+1. **Update Agent Detail API:**
+ * Modify the main agent detail API endpoint (`/api/marketplace/agents/:id`).
+ * In addition to the agent's details, also fetch its *active* subscription tiers from the `agent_subscription_tiers` table.
+ * Include these tiers in the response, e.g., in an `agent.subscription_tiers` array.
+
+2. **Create Subscription Tiers Section in UI:**
+ * On the `marketplace.html` page (or its detail view template), add a new section for "Subscriptions".
+ * This section will contain a grid or list to display the tier cards.
+
+3. **Implement Frontend Rendering Logic:**
+ * In the `renderDetail` function, check if `agent.subscription_tiers` exists and is not empty.
+ * If it is, iterate over the tiers and render a card for each one.
+ * Each card should display:
+ * Tier Name
+ * Price (e.g., "5.00 USDC / month")
+ * Description / list of perks
+ * A "Subscribe" button.
+
+4. **Handle User Subscription Status:**
+ * You will need to know if the user is already subscribed to the agent (at any tier).
+ * You can fetch this information along with the user's other data (like unlocked skills).
+ * If the user is already subscribed to a tier, the UI should reflect this. For example, highlight the current tier and change the button to "Manage Subscription", while disabling the buttons for other tiers.
+
+## Code Example (HTML Structure for Tiers)
+
+```html
+<!-- In agent detail view -->
+<div id="subscription-tiers-section" style="display: none;">
+ <h3>Subscribe for Exclusive Perks</h3>
+ <div id="tiers-grid" class="tiers-grid">
+ <!-- Tier cards will be rendered here -->
+ </div>
+</div>
+```
+
+## CSS Example for Tier Cards
+
+```css
+.tiers-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
+ gap: 16px;
+ margin-top: 16px;
+}
+.tier-card {
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
+ padding: 20px;
+ text-align: center;
+}
+.tier-card.subscribed {
+ border-color: var(--accent);
+ box-shadow: 0 0 10px rgba(0, 255, 65, 0.2);
+}
+.tier-card .name {
+ font-size: 18px;
+ font-weight: bold;
+ color: var(--text-bright);
+}
+.tier-card .price {
+ font-size: 22px;
+ color: var(--accent);
+ margin: 8px 0;
+}
+.tier-card .price .interval {
+ font-size: 12px;
+ color: #888;
+}
+.tier-card .description {
+ font-size: 12px;
+ color: #888;
+ min-height: 50px;
+}
+.tier-card .subscribe-btn {
+ margin-top: 16px;
+ width: 100%;
+}
+```
+
+## Code Example (Frontend Rendering Logic)
+
+```javascript
+function renderSubscriptionTiers(agent, userSubscription) {
+ const container = document.getElementById('subscription-tiers-section');
+ const grid = document.getElementById('tiers-grid');
+ const tiers = agent.subscription_tiers || [];
+
+ if (tiers.length === 0) {
+ container.style.display = 'none';
+ return;
+ }
+ container.style.display = 'block';
+
+ grid.innerHTML = tiers.map(tier => {
+ const isSubscribed = userSubscription && userSubscription.tier_id === tier.id;
+ const buttonText = isSubscribed ? 'Current Plan' : 'Subscribe';
+ const isDisabled = userSubscription && !isSubscribed; // Disable other tiers if already subbed
+
+ return `
+ <div class="tier-card ${isSubscribed ? 'subscribed' : ''}">
+ <div class="name">${escapeHtml(tier.name)}</div>
+ <div class="price">
+ ${(tier.price_amount / 1e6).toFixed(2)} USDC
+ <span class="interval">/ ${tier.interval}</span>
+ </div>
+ <div class="description">${escapeHtml(tier.description)}</div>
+ <button class="subscribe-btn" ${isDisabled || isSubscribed ? 'disabled' : ''}
+ onclick="initiateSubscription('${tier.id}')">
+ ${buttonText}
+ </button>
+ </div>
+ `;
+ }).join('');
+}
+```
diff --git a/docs/monetization/17-subscription-payment-activation.md b/docs/monetization/17-subscription-payment-activation.md
new file mode 100644
index 000000000..e2eacec99
--- /dev/null
+++ b/docs/monetization/17-subscription-payment-activation.md
@@ -0,0 +1,67 @@
+---
+status: not-started
+---
+
+# Prompt 17: Subscription Payment and Activation
+
+## Objective
+Implement the backend and frontend logic to handle a new subscription payment using Solana Pay and activate the subscription in the database.
+
+## Explanation
+This process is similar to a one-time skill purchase but involves creating a `user_subscriptions` record instead. For simplicity in this initial implementation, we will treat the first subscription payment as a one-time charge. True recurring payments on Solana are more complex and can be implemented later.
+
+## Instructions
+1. **Create a Subscription Transaction Endpoint:**
+ * Create a new backend endpoint, e.g., `GET /api/subscribe/transaction?tierId=...`.
+ * This endpoint will be called when a user clicks a "Subscribe" button.
+ * It should look up the tier details (price, currency) from the `agent_subscription_tiers` table.
+ * Generate a `reference` keypair for tracking this specific subscription activation.
+ * Before returning the transaction URL, it should create a new record in the `user_subscriptions` table with a status of `'incomplete'` and store the `reference` key. This "locks in" the intent to subscribe.
+
+2. **Create the Solana Pay Details Endpoint:**
+ * Similar to the one-time purchase, create the `POST /api/subscribe/details` endpoint that the wallet will call.
+ * This endpoint should build and serialize a transaction to transfer the correct subscription price from the user's wallet to the agent owner's wallet.
+
+3. **Create a Subscription Verification Endpoint:**
+ * Create an endpoint like `GET /api/subscribe/status?reference=...`.
+ * This endpoint will be polled by the frontend after the user is shown the QR code.
+ * Its logic should:
+ * Find the transaction using the `reference` public key.
+ * Thoroughly validate the transaction details (amount, recipient, etc.).
+ * If valid, find the `'incomplete'` record in `user_subscriptions` associated with this `reference`.
+ * Update the record's status to `'active'`.
+ * Set the `current_period_start` to `NOW()` and `current_period_end` to the appropriate future date (e.g., 1 month from now).
+ * Store the transaction signature.
+ * Return `{ status: 'confirmed' }` to the frontend.
+
+4. **Update Frontend Logic:**
+ * The `initiateSubscription('tierId')` function should call the `/api/subscribe/transaction` endpoint.
+ * It should then display the QR code and start polling the `/api/subscribe/status` endpoint.
+ * Upon confirmation, it should refresh the UI to show the user's new "Current Plan".
+
+## Key Difference from One-Time Purchase
+The main difference is the database interaction. Instead of inserting into `user_unlocked_skills`, we are creating and then updating a record in `user_subscriptions`. This sets the foundation for managing the subscription lifecycle (renewals, cancellations, etc.) in the future.
+
+## Code Example (Backend - Creating 'incomplete' subscription)
+
+```javascript
+// Inside GET /api/subscribe/transaction
+// ... after fetching tier details
+const reference = new solanaWeb3.Keypair();
+const userId = await getUserIdFromRequest(req);
+
+// Create an initial record to track this attempt
+const subResult = await db.query(
+ `INSERT INTO user_subscriptions (user_id, tier_id, status, payment_reference)
+ VALUES ($1, $2, 'incomplete', $3) RETURNING id`,
+ [userId, tierId, reference.publicKey.toBase58()]
+);
+const subscriptionId = subResult.rows[0].id;
+
+// Now construct the Solana Pay URL, perhaps including the subscriptionId for context
+const url = new URL(`${req.protocol}://${req.get('host')}/api/subscribe/details`);
+url.searchParams.set('subId', subscriptionId); // Pass the new ID to the details endpoint
+
+const solanaPayUrl = `solana:${encodeURIComponent(url.toString())}`;
+res.json({ url: solanaPayUrl, reference: reference.publicKey.toBase58() });
+```
diff --git a/docs/monetization/18-tip-jar-feature.md b/docs/monetization/18-tip-jar-feature.md
new file mode 100644
index 000000000..e375ccbfd
--- /dev/null
+++ b/docs/monetization/18-tip-jar-feature.md
@@ -0,0 +1,96 @@
+---
+status: not-started
+---
+
+# Prompt 18: Tip Jar Feature
+
+## Objective
+Add a simple "Tip" button and flow to the agent detail page, allowing users to send a custom amount of SOL or USDC to the agent's creator.
+
+## Explanation
+A tip jar is a straightforward way to let appreciative users support creators without the commitment of a subscription. This feature leverages the existing Solana Pay infrastructure for a simple, one-off payment.
+
+## Instructions
+1. **Add UI Elements:**
+ * On the agent detail page (`marketplace.html`), add a "Send a Tip" button, perhaps near the agent's name or creator details.
+ * Clicking this button should open a small modal.
+ * The modal should contain:
+ * An input field for the amount.
+ * A dropdown to select the currency (e.g., SOL, USDC).
+ * A "Generate Payment QR" button.
+
+2. **Create a Backend Endpoint for Tip Transactions:**
+ * Create a new endpoint, e.g., `GET /api/tip/transaction`.
+ * This endpoint will take `agentId`, `amount`, and `currency` as query parameters.
+ * The logic will be very similar to the skill purchase endpoint:
+ * Fetch the agent owner's wallet address.
+ * Generate a `reference` keypair for tracking.
+ * Construct the Solana Pay details URL.
+ * Return the `solana:...` URL and the `reference` public key.
+
+3. **Create the Solana Pay Details Endpoint:**
+ * Create the corresponding `POST /api/tip/details` endpoint.
+ * This will receive the user's wallet and build the appropriate transaction (either a `SystemProgram.transfer` for SOL or an `splToken.createTransferInstruction` for USDC).
+ * The amount will be read from the query parameters passed along in the details URL.
+ * Return the serialized transaction in the Solana Pay format.
+
+4. **Implement Frontend Logic:**
+ * Wire up the "Send a Tip" button to open the modal.
+ * When the user clicks "Generate Payment QR" inside the modal:
+ * Read the amount and currency from the form.
+ * Call the `/api/tip/transaction` endpoint with these parameters.
+ * Receive the Solana Pay URL and display it as a QR code in the modal.
+ * You can optionally add a polling mechanism to confirm the tip was received and show a "Thank you" message.
+
+## Code Example (Tip Modal HTML)
+
+```html
+<div id="tip-modal" class="modal-backdrop">
+ <div class="modal-content">
+ <div class="modal-header"><h3>Send a Tip</h3></div>
+ <div class="modal-body">
+ <div class="form-group">
+ <label>Amount</label>
+ <input type="number" id="tip-amount" placeholder="1.0">
+ </div>
+ <div class="form-group">
+ <label>Currency</label>
+ <select id="tip-currency">
+ <option value="SOL">SOL</option>
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3">USDC</option>
+ </select>
+ </div>
+ <button id="generate-tip-qr-btn" class="cta-button">Generate Payment Code</button>
+ <div id="tip-qr-container" style="margin-top: 16px;"></div>
+ </div>
+ </div>
+</div>
+```
+
+## Code Example (Frontend JavaScript)
+
+```javascript
+document.getElementById('generate-tip-qr-btn').addEventListener('click', async () => {
+ const amount = document.getElementById('tip-amount').value;
+ const currency = document.getElementById('tip-currency').value;
+ const agentId = /* get current agent ID */;
+
+ if (!amount || parseFloat(amount) <= 0) {
+ showToast('Please enter a valid amount.', 'error');
+ return;
+ }
+
+ try {
+ const response = await fetch(`/api/tip/transaction?agentId=${agentId}&amount=${amount}&currency=${currency}`);
+ const { url } = await response.json();
+
+ const qrContainer = document.getElementById('tip-qr-container');
+ qrContainer.innerHTML = '';
+ const qr = SolanaPay.createQR(url, 250);
+ qrContainer.appendChild(qr.canvas);
+
+ } catch (e) {
+ showToast('Could not generate payment code.', 'error');
+ }
+});
+```
diff --git a/docs/monetization/19-creator-revenue-dashboard.md b/docs/monetization/19-creator-revenue-dashboard.md
new file mode 100644
index 000000000..0665f8529
--- /dev/null
+++ b/docs/monetization/19-creator-revenue-dashboard.md
@@ -0,0 +1,93 @@
+---
+status: not-started
+---
+
+# Prompt 19: Creator Revenue Dashboard
+
+## Objective
+Create a new, dedicated "Creator Dashboard" page where agent owners can view their earnings from skill sales and subscriptions.
+
+## Explanation
+To empower creators, they need a clear and transparent view of their revenue. This dashboard is the central hub for creators to track their monetization success on the platform. This prompt focuses on the initial structure and UI of the dashboard.
+
+## Instructions
+1. **Create a New HTML File:**
+ * Create a new file, `creator-dashboard.html`.
+ * This page should be protected and only accessible to logged-in users.
+
+2. **Design the Dashboard Layout:**
+ * The layout should include several key components:
+ * **Summary Stats:** A section at the top for key metrics like "Total Revenue," "30-Day Earnings," "Total Subscribers," and "Total Sales."
+ * **Revenue Chart:** A placeholder for a chart that will visualize earnings over time (e.g., daily or monthly).
+ * **Breakdown Section:** A section to show revenue broken down by source (e.g., "Skill Sales" vs. "Subscriptions").
+ * **Recent Transactions:** A table or list showing the most recent sales and subscription payments.
+ * **Top Performing Agents/Skills:** A list of the creator's agents or skills that are generating the most revenue.
+
+3. **Add Placeholders:**
+ * For this initial step, populate the dashboard with static HTML and placeholder values. The goal is to build the structure first.
+ * Use clear IDs for all elements that will be populated with dynamic data later.
+
+## Code Example (HTML Structure for `creator-dashboard.html`)
+
+```html
+<!DOCTYPE html>
+<html lang="en">
+<head>
+ <title>Creator Dashboard</title>
+ <!-- Link to your standard CSS files -->
+</head>
+<body>
+ <header>
+ <!-- Your standard site header -->
+ </header>
+ <main class="container">
+ <h1>Creator Dashboard</h1>
+
+ <!-- Summary Stats -->
+ <div class="stats-grid">
+ <div class="stat-card">
+ <div class="label">Total Revenue (USDC)</div>
+ <div class="value" id="total-revenue">$0.00</div>
+ </div>
+ <div class="stat-card">
+ <div class="label">Last 30 Days</div>
+ <div class="value" id="revenue-30-days">$0.00</div>
+ </div>
+ <div class="stat-card">
+ <div class="label">Total Subscribers</div>
+ <div class="value" id="total-subscribers">0</div>
+ </div>
+ <div class="stat-card">
+ <div class="label">Total Sales</div>
+ <div class="value" id="total-sales">0</div>
+ </div>
+ </div>
+
+ <!-- Revenue Chart -->
+ <div class="panel">
+ <div class="panel-header"><h2>Revenue Over Time</h2></div>
+ <div class="panel-body">
+ <div id="revenue-chart-container" class="empty">Chart loading...</div>
+ </div>
+ </div>
+
+ <!-- Recent Transactions -->
+ <div class="panel">
+ <div class="panel-header"><h2>Recent Transactions</h2></div>
+ <div class="panel-body no-pad">
+ <table id="transactions-table">
+ <thead>
+ <tr><th>Date</th><th>Type</th><th>Agent/Skill</th><th>Amount</th><th>Status</th></tr>
+ </thead>
+ <tbody>
+ <tr><td colspan="5" class="empty">No transactions yet.</td></tr>
+ </tbody>
+ </table>
+ </div>
+ </div>
+ </main>
+</body>
+</html>
+```
+
+**Next Steps:** The following prompts will focus on creating the backend APIs to populate this dashboard with real data.
diff --git a/docs/monetization/20-creator-revenue-api.md b/docs/monetization/20-creator-revenue-api.md
new file mode 100644
index 000000000..94ff5da63
--- /dev/null
+++ b/docs/monetization/20-creator-revenue-api.md
@@ -0,0 +1,76 @@
+---
+status: not-started
+---
+
+# Prompt 20: Creator Revenue API
+
+## Objective
+Implement the backend API endpoints required to populate the Creator Dashboard with revenue and transaction data.
+
+## Explanation
+The Creator Dashboard UI needs data to be useful. This task involves creating authenticated endpoints that aggregate and return a creator's financial data from the database.
+
+## Instructions
+1. **Create a Summary Stats Endpoint:**
+ * Create an endpoint like `GET /api/creators/me/stats`.
+ * This endpoint should calculate several key metrics for the logged-in user (creator):
+ * **Total Revenue:** Sum the `amount` from all successful purchases (`user_unlocked_skills` joined with prices) and subscription payments (`user_subscriptions` joined with tier prices). This is complex and may require querying transaction logs. A simpler start is to sum from your own records.
+ * **30-Day Revenue:** The same calculation, but limited to the last 30 days.
+ * **Total Subscribers:** Count the number of `active` subscriptions for all of the creator's agents.
+ * **Total Sales:** Count the number of records in `user_unlocked_skills` for the creator's agents.
+
+2. **Create a Transactions Endpoint:**
+ * Create an endpoint like `GET /api/creators/me/transactions`.
+ * This should return a paginated list of all revenue-generating events for the creator.
+ * You will need to `UNION` results from two sources:
+ * Skill purchases from `user_unlocked_skills`.
+ * Subscription payments (you may need a new `subscription_payments` table for this, or infer it from `user_subscriptions`).
+ * Each item in the result should have a consistent shape, e.g., `{ date, type: 'sale' | 'subscription', description, amount, currency, status }`.
+
+3. **Create a Chart Data Endpoint:**
+ * Create an endpoint like `GET /api/creators/me/revenue-chart`.
+ * This endpoint should return data formatted for a charting library.
+ * It should accept a time range parameter (e.g., `?range=30d` or `?range=12m`).
+ * The backend should group revenue by day, week, or month and return an array of data points, e.g., `[{ date: 'YYYY-MM-DD', revenue: 15.50 }]`.
+
+4. **Security:**
+ * Ensure all endpoints are authenticated and strictly scoped to the data owned by the logged-in user. A creator should never be able to see another creator's revenue.
+
+## Code Example (Backend - Summary Stats Logic)
+
+```javascript
+// GET /api/creators/me/stats
+app.get('/api/creators/me/stats', async (req, res) => {
+ const userId = await getUserIdFromRequest(req);
+
+ // Query for total sales revenue
+ const salesResult = await db.query(`
+ SELECT SUM(p.amount)
+ FROM user_unlocked_skills u
+ JOIN agents a ON u.agent_id = a.id
+ JOIN agent_skill_prices p ON u.agent_id = p.agent_id AND u.skill_name = p.skill_name
+ WHERE a.owner_id = $1
+ `, [userId]);
+
+ // Query for active subscribers
+ const subsResult = await db.query(`
+ SELECT COUNT(*)
+ FROM user_subscriptions s
+ JOIN agent_subscription_tiers t ON s.tier_id = t.id
+ JOIN agents a ON t.agent_id = a.id
+ WHERE a.owner_id = $1 AND s.status = 'active'
+ `, [userId]);
+
+ // ... and so on for other stats.
+ // These queries can be complex and should be optimized.
+
+ res.json({
+ total_revenue: (salesResult.rows[0].sum || 0) / 1e6, // Example
+ total_subscribers: parseInt(subsResult.rows[0].count, 10),
+ // ... other stats
+ });
+});
+```
+
+## Frontend Integration
+The frontend JavaScript for `creator-dashboard.html` will call these new endpoints upon loading and use the returned data to populate the elements created in the previous step.
diff --git a/docs/monetization/21-platform-fee-mechanism.md b/docs/monetization/21-platform-fee-mechanism.md
new file mode 100644
index 000000000..0b14fc801
--- /dev/null
+++ b/docs/monetization/21-platform-fee-mechanism.md
@@ -0,0 +1,79 @@
+---
+status: not-started
+---
+
+# Prompt 21: Platform Fee Mechanism
+
+## Objective
+Implement a mechanism in the backend to automatically take a platform fee from every successful transaction (skill purchase or subscription payment).
+
+## Explanation
+A platform fee is a primary business model for a marketplace. This requires modifying the transaction-building logic to split the payment between the creator and the platform. On Solana, this is typically done using multiple transfer instructions within the same transaction.
+
+## Instructions
+1. **Configuration:**
+ * Store the platform fee percentage and the platform's treasury wallet address in a secure configuration file or environment variables. Do not hardcode them.
+ * Example: `PLATFORM_FEE_BPS=500` (500 basis points = 5%) and `PLATFORM_TREASURY_WALLET="YOUR_WALLET_ADDRESS"`.
+
+2. **Modify Transaction-Building Logic:**
+ * Locate all the places where you create a Solana Pay transaction (`/api/purchase/details`, `/api/subscribe/details`, `/api/tip/details`).
+ * For each transaction, calculate the fee amount.
+ * `totalAmount` = price of the item.
+ * `feeAmount` = `totalAmount * (PLATFORM_FEE_BPS / 10000)`.
+ * `creatorAmount` = `totalAmount - feeAmount`.
+ * Ensure you are working with integers (lamports) to avoid floating-point errors.
+
+3. **Add a Second Transfer Instruction:**
+ * Instead of a single transfer instruction from the user to the creator, the transaction will now have two:
+ * **Instruction 1:** Transfer `creatorAmount` from the user's wallet to the creator's wallet.
+ * **Instruction 2:** Transfer `feeAmount` from the user's wallet to the platform's treasury wallet (`PLATFORM_TREASURY_WALLET`).
+ * Add both of these instructions to the same `Transaction` object.
+
+4. **Atomic Transactions:**
+ * The beauty of this approach is that the transaction is atomic. If either transfer fails, the entire transaction fails. The user pays once, and the funds are split and distributed in a single, on-chain event.
+
+5. **Update Verification Logic:**
+ * Your transaction verification logic must now be updated to look for and validate *both* transfer instructions. It needs to confirm that the creator received the correct amount and the platform received its fee.
+
+## Code Example (Backend - Modified Details Endpoint)
+
+```javascript
+// Inside a Solana Pay details endpoint (e.g., POST /api/purchase/details)
+app.post('/api/purchase/details', async (req, res) => {
+ // ... fetch priceInfo { amount, currency_mint, owner_wallet } ...
+ const totalAmount = priceInfo.amount;
+
+ // 1. Calculate split
+ const PLATFORM_FEE_BPS = 500; // 5%
+ const PLATFORM_TREASURY_WALLET = new solanaWeb3.PublicKey('...');
+ const feeAmount = Math.floor(totalAmount * (PLATFORM_FEE_BPS / 10000));
+ const creatorAmount = totalAmount - feeAmount;
+
+ // ... build transaction, get blockhash ...
+ const transaction = new solanaWeb3.Transaction();
+
+ // 2. Add two transfer instructions
+ // Transfer to creator
+ transaction.add(
+ splToken.createTransferInstruction(
+ userTokenAccount, // From: user's token account
+ creatorTokenAccount, // To: creator's token account
+ userPublicKey, // User is the owner/signer
+ creatorAmount
+ )
+ );
+ // Transfer to platform treasury
+ transaction.add(
+ splToken.createTransferInstruction(
+ userTokenAccount, // From: user's token account
+ platformTokenAccount, // To: platform's token account
+ userPublicKey, // User is the owner/signer
+ feeAmount
+ )
+ );
+
+ // ... add memo, set fee payer, serialize and return ...
+});
+```
+
+**Note:** This requires you to know the correct SPL Token accounts for the user, creator, and platform. You may need to use `splToken.getAssociatedTokenAddress()` to find or create them as part of the transaction logic. This can get complex, especially if an account doesn't exist yet. An alternative for SOL transfers is to use `SystemProgram.transfer`.
diff --git a/docs/monetization/22-creator-revenue-charts.md b/docs/monetization/22-creator-revenue-charts.md
new file mode 100644
index 000000000..5d5cca52b
--- /dev/null
+++ b/docs/monetization/22-creator-revenue-charts.md
@@ -0,0 +1,118 @@
+---
+status: not-started
+---
+
+# Prompt 22: Creator Revenue Charts
+
+## Objective
+Integrate a charting library into the Creator Dashboard to visually represent revenue data.
+
+## Explanation
+Visual data is much easier to understand than raw numbers. Adding a chart to the Creator Dashboard will provide creators with a clear and immediate understanding of their performance over time.
+
+## Instructions
+1. **Choose a Charting Library:**
+ * Select a suitable JavaScript charting library. Good options include:
+ * **Chart.js:** Simple, popular, and easy to get started with.
+ * **ApexCharts:** Offers more interactive and visually polished charts.
+ * **D3.js:** Extremely powerful and customizable, but with a steeper learning curve.
+ * For this task, Chart.js is a great choice.
+
+2. **Include the Library:**
+ * Add the chosen library to `creator-dashboard.html`, either via a CDN script tag or by installing it as an npm package.
+
+3. **Implement Frontend Charting Logic:**
+ * Create a new JavaScript file for the dashboard, e.g., `src/creator-dashboard.js`.
+ * Write a function, `renderRevenueChart(data)`, that will be responsible for drawing the chart.
+ * On page load, fetch the data from the `/api/creators/me/revenue-chart` endpoint created previously.
+ * Pass the fetched data to your `renderRevenueChart` function.
+ * Inside the function, process the data into the format required by the charting library (e.g., arrays for `labels` and `datasets`).
+ * Create a new chart instance, targeting the canvas element you created in the dashboard's HTML.
+ * Configure the chart's appearance (e.g., line chart, bar chart, colors, tooltips).
+
+## Code Example (HTML in `creator-dashboard.html`)
+
+```html
+<!-- Include Chart.js from a CDN -->
+<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
+
+<!-- ... in your main content ... -->
+<div class="panel">
+ <div class="panel-header">
+ <h2>Revenue Over Time</h2>
+ <select id="chart-range-selector">
+ <option value="7d">Last 7 Days</option>
+ <option value="30d" selected>Last 30 Days</option>
+ <option value="12m">Last 12 Months</option>
+ </select>
+ </div>
+ <div class="panel-body">
+ <canvas id="revenue-chart-canvas"></canvas>
+ </div>
+</div>
+```
+
+## Code Example (JavaScript in `src/creator-dashboard.js`)
+
+```javascript
+let revenueChart = null; // To hold the chart instance
+
+document.addEventListener('DOMContentLoaded', () => {
+ loadChartData('30d');
+ document.getElementById('chart-range-selector').addEventListener('change', (e) => {
+ loadChartData(e.target.value);
+ });
+});
+
+async function loadChartData(range) {
+ try {
+ const response = await fetch(`/api/creators/me/revenue-chart?range=${range}`);
+ const data = await response.json();
+ renderRevenueChart(data);
+ } catch (e) {
+ document.getElementById('revenue-chart-canvas').innerHTML = 'Could not load chart data.';
+ }
+}
+
+function renderRevenueChart(apiData) {
+ const ctx = document.getElementById('revenue-chart-canvas').getContext('2d');
+
+ // Process data for Chart.js
+ const labels = apiData.map(d => new Date(d.date).toLocaleDateString());
+ const revenueData = apiData.map(d => d.revenue);
+
+ // Destroy previous chart instance if it exists
+ if (revenueChart) {
+ revenueChart.destroy();
+ }
+
+ revenueChart = new Chart(ctx, {
+ type: 'line', // Or 'bar'
+ data: {
+ labels: labels,
+ datasets: [{
+ label: 'Revenue (USDC)',
+ data: revenueData,
+ borderColor: '#00ff41',
+ backgroundColor: 'rgba(0, 255, 65, 0.1)',
+ fill: true,
+ tension: 0.3
+ }]
+ },
+ options: {
+ responsive: true,
+ scales: {
+ y: {
+ beginAtZero: true,
+ ticks: { color: '#888' },
+ grid: { color: '#222' }
+ },
+ x: {
+ ticks: { color: '#888' },
+ grid: { color: '#222' }
+ }
+ }
+ }
+ });
+}
+```
diff --git a/docs/monetization/23-skill-gating-api.md b/docs/monetization/23-skill-gating-api.md
new file mode 100644
index 000000000..c95fa9de6
--- /dev/null
+++ b/docs/monetization/23-skill-gating-api.md
@@ -0,0 +1,87 @@
+---
+status: not-started
+---
+
+# Prompt 23: Skill Gating (API Access Control)
+
+## Objective
+Implement a backend mechanism to "gate" the execution of paid skills, ensuring that only users who have purchased a skill can use it via the API.
+
+## Explanation
+Selling skills is only effective if their usage can be restricted to paying customers. This requires adding a check in the core agent interaction/chat API to verify ownership before executing a premium skill.
+
+## Instructions
+1. **Identify the Skill Execution Endpoint:**
+ * Locate the primary backend API endpoint responsible for handling user chats or skill executions with an agent (e.g., `POST /api/chat`).
+
+2. **Modify the Endpoint Logic:**
+ * When a request comes in to execute a specific skill, the logic must first determine if the skill is free or paid.
+ * Perform a lookup in the `agent_skill_prices` table for the requested agent and skill.
+
+3. **Implement the Ownership Check:**
+ * **If the skill has a price**, the endpoint must then verify that the requesting user owns the skill.
+ * Perform a lookup in the `user_unlocked_skills` table for a record matching the `user_id`, `agent_id`, and `skill_name`.
+ * Alternatively, check if the user has an active subscription to the agent, as a subscription might grant access to all skills. This requires checking the `user_subscriptions` table.
+
+4. **Enforce Gating:**
+ * **If the skill is paid AND the user does NOT have a valid unlock record or active subscription**, the API must refuse to execute the skill.
+ * It should return a specific error response, e.g., a `402 Payment Required` status code, with a message like "You must purchase this skill to use it."
+ * **If the skill is free OR the user has purchased it**, the API should proceed with the normal skill execution logic.
+
+## Code Example (Backend - Chat API Middleware/Check)
+
+```javascript
+// This function would be called inside your main chat/interaction endpoint
+async function canUserExecuteSkill(userId, agentId, skillName) {
+ // 1. Check if the skill is priced
+ const price = await db.getSkillPrice(agentId, skillName);
+ if (!price) {
+ // It's a free skill
+ return true;
+ }
+
+ // 2. If it's priced, check for direct ownership
+ const hasUnlocked = await db.query(
+ 'SELECT 1 FROM user_unlocked_skills WHERE user_id = $1 AND agent_id = $2 AND skill_name = $3',
+ [userId, agentId, skillName]
+ );
+ if (hasUnlocked.rowCount > 0) {
+ return true;
+ }
+
+ // 3. Check for an active subscription that grants access (more advanced)
+ const hasActiveSub = await db.query(
+ `SELECT 1 FROM user_subscriptions s
+ JOIN agent_subscription_tiers t ON s.tier_id = t.id
+ WHERE s.user_id = $1 AND t.agent_id = $2 AND s.status = 'active'`,
+ [userId, agentId]
+ );
+ if (hasActiveSub.rowCount > 0) {
+ // Here you might have more granular logic, e.g., does this sub tier include this skill?
+ // For now, we'll assume any active sub grants access.
+ return true;
+ }
+
+ // 4. If all checks fail, user does not have access
+ return false;
+}
+
+// --- Usage within the chat endpoint ---
+// POST /api/chat
+app.post('/api/chat', async (req, res) => {
+ const { agentId, skillToExecute } = req.body;
+ const userId = await getUserIdFromRequest(req);
+
+ const hasAccess = await canUserExecuteSkill(userId, agentId, skillToExecute);
+
+ if (!hasAccess) {
+ return res.status(402).json({
+ error: 'Payment Required',
+ message: `You must purchase the skill "${skillToExecute}" to use it.`
+ });
+ }
+
+ // ... proceed with normal skill execution logic ...
+});
+```
+This logic ensures the economic loop is closed: creators define prices, users purchase access, and the system enforces that access, giving real value to the digital assets.
diff --git a/docs/monetization/24-skill-bundles.md b/docs/monetization/24-skill-bundles.md
new file mode 100644
index 000000000..79a86465e
--- /dev/null
+++ b/docs/monetization/24-skill-bundles.md
@@ -0,0 +1,94 @@
+---
+status: not-started
+---
+
+# Prompt 24: Skill Bundles
+
+## Objective
+Implement a "Skill Bundle" feature, allowing creators to sell a group of skills together, often at a discounted price.
+
+## Explanation
+Bundles are a powerful sales tool. They increase the average transaction value and provide a convenient way for users to acquire a suite of related skills. This requires a new database structure to define bundles and updates to both the backend and frontend.
+
+## Instructions
+1. **Database Schema:**
+ * Create a new table: `agent_skill_bundles`.
+ * Columns: `id`, `agent_id`, `name`, `description`, `price_amount`, `price_currency_mint`.
+ * Create a linking table: `bundle_skills`.
+ * Columns: `bundle_id` (foreign key to `agent_skill_bundles`), `skill_name`.
+
+2. **Creator UI for Bundles:**
+ * In the `agent-edit.html` page, add a new section for "Skill Bundles".
+ * Provide a UI for creators to:
+ * Create a new bundle (giving it a name, description, and price).
+ * Select which of the agent's existing skills to include in the bundle (e.g., using a multi-select list or checkboxes).
+ * View, edit, and delete existing bundles.
+
+3. **Backend API for Bundles:**
+ * Create CRUD API endpoints for managing bundles (e.g., `POST /api/agents/:id/bundles`, `PUT /.../:bundleId`, etc.), similar to the subscription tier APIs.
+ * These endpoints will manage the `agent_skill_bundles` and `bundle_skills` tables.
+
+4. **Frontend Display:**
+ * On the agent detail page, display a new section for "Bundles".
+ * Render a card for each available bundle, showing its name, price, and the list of skills included.
+ * Add a "Buy Bundle" button.
+
+5. **Purchase Flow:**
+ * The purchase flow for a bundle will be nearly identical to a single skill purchase.
+ * The backend transaction endpoint will receive a `bundleId` instead of a `skillName`.
+ * Upon successful payment verification, the backend must add a separate entry in the `user_unlocked_skills` table for *each skill* included in the purchased bundle. This ensures the skill-gating mechanism works without modification.
+
+## Code Example (Frontend Bundle Card)
+
+```html
+<!-- Inside the new "Bundles" section on the agent detail page -->
+<div class="bundle-card">
+ <div class="bundle-name">Master Collection</div>
+ <div class="bundle-price">10.00 USDC</div>
+ <ul class="bundle-skills-list">
+ <li>Advanced Analysis</li>
+ <li>Market Prediction</li>
+ <li>Auto-Trading</li>
+ </ul>
+ <p class="bundle-description">Get all the essential trading skills in one package!</p>
+ <button class="buy-button">Buy Bundle</button>
+</div>
+```
+
+## Code Example (Backend - Purchase Verification Logic)
+
+```javascript
+// Inside your purchase verification endpoint, when a bundleId is detected
+async function unlockSkillsForBundle(userId, bundleId, transactionSignature) {
+ // 1. Get all skill names associated with this bundle
+ const skillsResult = await db.query(
+ 'SELECT skill_name FROM bundle_skills WHERE bundle_id = $1',
+ [bundleId]
+ );
+ const skillsToUnlock = skillsResult.rows.map(r => r.skill_name);
+
+ // Get the agent_id from the bundle
+ const bundleResult = await db.query('SELECT agent_id FROM agent_skill_bundles WHERE id = $1', [bundleId]);
+ const agentId = bundleResult.rows[0].agent_id;
+
+ // 2. Insert a record for each skill into the user's unlocked skills
+ // Use a transaction for atomicity
+ const client = await db.getClient();
+ try {
+ await client.query('BEGIN');
+ for (const skillName of skillsToUnlock) {
+ await client.query(
+ `INSERT INTO user_unlocked_skills (user_id, agent_id, skill_name, transaction_signature)
+ VALUES ($1, $2, $3, $4) ON CONFLICT DO NOTHING`,
+ [userId, agentId, skillName, transactionSignature]
+ );
+ }
+ await client.query('COMMIT');
+ } catch (e) {
+ await client.query('ROLLBACK');
+ throw e; // Propagate error
+ } finally {
+ client.release();
+ }
+}
+```
diff --git a/docs/monetization/25-affiliate-referral-system.md b/docs/monetization/25-affiliate-referral-system.md
new file mode 100644
index 000000000..b4af2cdbf
--- /dev/null
+++ b/docs/monetization/25-affiliate-referral-system.md
@@ -0,0 +1,52 @@
+---
+status: not-started
+---
+
+# Prompt 25: Affiliate and Referral System
+
+## Objective
+Implement a basic affiliate system where users can generate a unique referral link for an agent, and earn a commission on sales made through that link.
+
+## Explanation
+Referral systems are a powerful growth marketing tool. By rewarding users for promoting agents, we can incentivize word-of-mouth marketing and create a viral loop. This is an advanced feature that builds on the entire monetization stack.
+
+## Instructions
+1. **Database Schema:**
+ * **`user_referral_codes`:**
+ * Columns: `id`, `user_id`, `code` (a unique, short string), `created_at`.
+ * **`referral_sales`:**
+ * Columns: `id`, `referral_code_id` (FK to `user_referral_codes`), `new_user_id` (the user who made the purchase), `transaction_signature`, `purchase_amount`, `commission_amount`, `payout_status` ('pending', 'paid'), `created_at`.
+
+2. **Referral Link Generation:**
+ * In the user's profile, provide a section to generate their unique referral code/link (e.g., `.../marketplace/agent/AGENT_ID?ref=USER_CODE`).
+ * Create a backend endpoint to generate and store a unique code for a user if they don't have one.
+
+3. **Tracking Referrals:**
+ * When a user lands on an agent page with a `?ref=` parameter in the URL, store the referral code in a client-side cookie that lasts for a reasonable time (e.g., 30 days).
+ * When a purchase is initiated, the frontend must pass the referral code from the cookie to the backend's transaction generation endpoint.
+
+4. **Modify Purchase Flow for Commission:**
+ * The backend transaction generation logic needs to be updated again.
+ * If a valid referral code is present for a purchase:
+ * Calculate the commission based on the sale amount (e.g., 10% of the platform fee, or a percentage of the total price).
+ * The main payment transaction should now be a three-way split: a portion to the creator, a portion to the platform treasury, and a portion to the referrer's wallet.
+ * **Important:** Adding a third transfer can complicate things. An alternative, simpler model is to have the platform collect the full fee and handle paying out commissions separately. For this prompt, let's assume the latter.
+
+5. **Recording Referral Sales:**
+ * After a referred purchase is verified, create a record in the `referral_sales` table.
+ * This logs the sale, the referrer, and the commission amount earned.
+
+6. **Referral Dashboard:**
+ * Create a simple dashboard for users to see:
+ * Their referral link.
+ * The number of clicks/sign-ups from their link.
+ * A list of sales they've generated.
+ * Their total pending commission and total paid-out commission.
+
+## Simplified Payout Model
+Instead of complex on-chain three-way splits, the backend will:
+1. Take the standard platform fee during the purchase.
+2. Log the commission owed to the referrer in `referral_sales`.
+3. Have a separate, offline or batch process to periodically pay out the "pending" commissions to the referrers. This is much easier to manage than multi-recipient on-chain transactions for every purchase.
+
+This approach provides a robust foundation for a powerful growth engine, turning your users into a distributed sales force.
diff --git a/marketplace.css b/marketplace.css
new file mode 100644
index 000000000..66e674235
--- /dev/null
+++ b/marketplace.css
@@ -0,0 +1,70 @@
+
+/* Agent Marketplace Styles
+ ------------------------------------------------------------------------ */
+
+.price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+
+.price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+}
+
+body.market-page {
+ display: flex;
+ background-color: #000;
+ color: #fff;
+ font-family: 'Inter', sans-serif;
+ height: 100vh;
+ overflow: hidden;
+}
+
+.skill-entry {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ padding: 8px 0;
+ border-bottom: 1px solid var(--border);
+}
+
+.purchase-btn {
+ background-color: var(--accent);
+ color: white;
+ border: none;
+ padding: 6px 12px;
+ font-size: 12px;
+ font-weight: 600;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background-color 0.2s;
+}
+
+.purchase-btn:hover {
+ background-color: #5a4ccc; /* A slightly darker shade of accent */
+}
+
+.skill-status-badge {
+ display: inline-block;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.skill-owned {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
diff --git a/marketplace.html b/marketplace.html
index 9878e5e42..0d2392430 100644
--- a/marketplace.html
+++ b/marketplace.html
@@ -16,11 +16,32 @@
<link rel="stylesheet" href="style.css" />
<link rel="stylesheet" href="footer.css" />
<link rel="stylesheet" href="marketplace.css" />
+ <link rel="stylesheet" href="marketplace-skills.css" />
<link
href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Space+Grotesk:wght@500;600;700&display=swap"
rel="stylesheet"
/>
+ <style>
+ .price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+ }
+ .price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+ }
+
+ .price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+ }
+ </style>
<meta property="og:type" content="website" />
<meta property="og:title" content="Agent Marketplace · three.ws" />
<meta
@@ -289,6 +310,31 @@
</div>
</div>
- <script type="module" src="/src/marketplace.js"></script>
+ <!-- Purchase Modal -->
+ <div id="purchase-modal" class="modal-hidden">
+ <div class="modal-content">
+ <span class="close-button">&times;</span>
+ <h2>Unlock Skill</h2>
+ <p>You are about to purchase:</p>
+ <p><strong>Skill:</strong> <span id="modal-skill-name"></span></p>
+ <p><strong>Price:</strong> <span id="modal-skill-price"></span></p>
+ <button id="modal-confirm-purchase">Confirm Purchase</button>
+ </div>
+ </div>
+
+ <script src="/src/marketplace.js" type="module"></script>
+
+ <div id="purchase-modal" class="modal" hidden>
+ <div class="modal-content">
+ <button class="modal-close" onclick="$('purchase-modal').hidden = true;">&times;</button>
+ <h3>Complete Your Purchase</h3>
+ <p>Scan the QR code with a Solana Pay-compatible wallet to purchase the skill.</p>
+ <canvas id="qr-canvas"></canvas>
+ <p id="purchase-details"></p>
+ </div>
+ </div>
+ </body>
+</html>
+
</body>
</html>
diff --git a/migrations/002_create_agent_skill_prices.sql b/migrations/002_create_agent_skill_prices.sql
new file mode 100644
index 000000000..bed08b48e
--- /dev/null
+++ b/migrations/002_create_agent_skill_prices.sql
@@ -0,0 +1,19 @@
+-- migrations/002_create_agent_skill_prices.sql
+
+CREATE TABLE agent_skill_prices (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ agent_id UUID NOT NULL REFERENCES agents(id),
+ skill_name VARCHAR(128) NOT NULL,
+ amount NUMERIC(20, 0) NOT NULL CHECK (amount >= 0),
+ currency_mint VARCHAR(64) NOT NULL,
+ creator_user_id UUID NOT NULL REFERENCES users(id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ UNIQUE (agent_id, skill_name)
+);
+
+CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);
+CREATE INDEX idx_agent_skill_prices_skill_name ON agent_skill_prices(skill_name);
+
+COMMENT ON TABLE agent_skill_prices IS 'Stores prices for agent skills set by creators.';
+COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest unit of the currency (e.g., lamports).';
diff --git a/migrations/20260504120000_create_agent_skill_prices_table.sql b/migrations/20260504120000_create_agent_skill_prices_table.sql
new file mode 100644
index 000000000..11c5b10f3
--- /dev/null
+++ b/migrations/20260504120000_create_agent_skill_prices_table.sql
@@ -0,0 +1,30 @@
+-- Up
+CREATE TABLE agent_skill_prices (
+ id SERIAL PRIMARY KEY,
+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL, -- Price in the smallest denomination (e.g., lamports)
+ currency_mint VARCHAR(255) NOT NULL, -- SPL Token mint address
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+
+ CONSTRAINT unique_agent_skill UNIQUE (agent_id, skill_name)
+);
+
+-- Optional: Create a trigger to automatically update the updated_at timestamp
+CREATE OR REPLACE FUNCTION trigger_set_timestamp()
+RETURNS TRIGGER AS $$
+BEGIN
+ NEW.updated_at = NOW();
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER set_timestamp
+BEFORE UPDATE ON agent_skill_prices
+FOR EACH ROW
+EXECUTE PROCEDURE trigger_set_timestamp();
+
+-- Down
+DROP TABLE agent_skill_prices;
+DROP FUNCTION trigger_set_timestamp();
diff --git a/public/agent-edit.css b/public/agent-edit.css
new file mode 100644
index 000000000..35d1fc2dc
--- /dev/null
+++ b/public/agent-edit.css
@@ -0,0 +1,27 @@
+.skills-editor-container {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+}
+
+.skill-price-editor {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px;
+ background-color: #f9f9f9;
+ border-radius: 4px;
+}
+
+.skill-name {
+ flex: 1;
+ font-weight: 500;
+}
+
+.price-amount {
+ width: 80px;
+}
+
+.price-currency {
+ width: 80px;
+}
diff --git a/public/marketplace-skills.css b/public/marketplace-skills.css
new file mode 100644
index 000000000..85a215055
--- /dev/null
+++ b/public/marketplace-skills.css
@@ -0,0 +1,43 @@
+.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;
+}
+
+.skill-btn.purchase {
+ background-color: #3b82f6;
+ color: white;
+}
+
+.skill-btn.purchase:hover {
+ background-color: #2563eb;
+}
diff --git a/public/marketplace.css b/public/marketplace.css
index cd54ef002..660a7b54d 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -536,6 +536,68 @@ body.market-page {
background-color: #4338ca;
}
+/* Purchase Modal */
+#purchase-modal {
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background: rgba(0, 0, 0, 0.7);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ z-index: 1000;
+}
+#purchase-modal.modal-hidden {
+ display: none;
+}
+.modal-content {
+ background: var(--mk-panel);
+ padding: 24px;
+ border-radius: var(--mk-radius);
+ border: 1px solid var(--mk-border);
+ width: 90%;
+ max-width: 420px;
+ position: relative;
+}
+.modal-content h2 {
+ margin: 0 0 16px;
+ font-size: 20px;
+}
+.modal-content p {
+ margin: 8px 0;
+ color: var(--mk-text-2);
+}
+.modal-content strong {
+ color: var(--mk-text);
+}
+.close-button {
+ position: absolute;
+ top: 12px;
+ right: 12px;
+ background: none;
+ border: none;
+ font-size: 24px;
+ color: var(--mk-text-3);
+ cursor: pointer;
+}
+#modal-confirm-purchase {
+ width: 100%;
+ padding: 12px;
+ margin-top: 16px;
+ background-color: #4f46e5;
+ color: white;
+ border: none;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 16px;
+ font-weight: 600;
+}
+#modal-confirm-purchase:hover {
+ background-color: #4338ca;
+}
+
.market-skills,
.market-library {
background: var(--mk-panel);
@@ -861,16 +923,6 @@ body.market-page {
padding: 1px 5px;
}
-.price-paid {
- background: #d1fae5;
- color: #065f46;
-}
-
-.price-free {
- background: var(--mk-panel-3, #e5e7eb);
- color: var(--mk-text-3);
-}
-
/* ── Plugin marketplace ───────────────────────────────────────────────────── */
.plugins-topbar {
@@ -997,6 +1049,27 @@ body.market-page {
.tag-pill {
background: var(--mk-panel-2);
border-radius: 5px;
+
+.price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+
+.price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+}
+
padding: 2px 7px;
font-size: 11px;
color: var(--mk-text-3);
@@ -1181,3 +1254,24 @@ body.market-page {
opacity: 0.5;
cursor: not-allowed;
}
+
+.price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+
+.price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+}
+
diff --git a/scripts/migrations/003-create-skill-prices.sql b/scripts/migrations/003-create-skill-prices.sql
new file mode 100644
index 000000000..a3bc97b82
--- /dev/null
+++ b/scripts/migrations/003-create-skill-prices.sql
@@ -0,0 +1,15 @@
+-- Up
+CREATE TABLE agent_skill_prices (
+ agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,
+ skill_name VARCHAR(255) NOT NULL,
+ amount BIGINT NOT NULL,
+ currency_mint VARCHAR(255) NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ PRIMARY KEY (agent_id, skill_name)
+);
+
+CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);
+
+-- Down
+DROP TABLE IF EXISTS agent_skill_prices;
diff --git a/src/agent-edit.js b/src/agent-edit.js
new file mode 100644
index 000000000..6cd17b357
--- /dev/null
+++ b/src/agent-edit.js
@@ -0,0 +1,47 @@
+function renderAgentForEditing(agent) {
+ // ... existing code to render agent name, description, etc.
+
+ const skillsContainer = document.getElementById('skills-editor');
+ const skillPrices = agent.skill_prices || {};
+
+ skillsContainer.innerHTML = agent.skills.map(skill => {
+ const price = skillPrices[skill.name] || {};
+ const amountInUnits = price.amount ? price.amount / 1e6 : ''; // Example for USDC (6 decimals)
+ const currency = price.currency_mint || 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T'; // Default to USDC
+
+ return `
+ <div class="skill-price-editor" data-skill-name="${skill.name}">
+ <span class="skill-name">${skill.name}</span>
+ <input type="number" class="price-amount" placeholder="e.g., 2.50" value="${amountInUnits}">
+ <select class="price-currency">
+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" ${currency === 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' ? 'selected' : ''}>USDC</option>
+ <option value="So11111111111111111111111111111111111111112" ${currency === 'So11111111111111111111111111111111111111112' ? 'selected' : ''}>SOL</option>
+ </select>
+ </div>
+ `;
+ }).join('');
+}
+
+// Add event listener for the "Save Prices" button
+document.getElementById('save-prices-btn').addEventListener('click', async () => {
+ const agentId = /* get agent id from somewhere */;
+ const editors = document.querySelectorAll('.skill-price-editor');
+
+ for (const editor of editors) {
+ const skill_name = editor.dataset.skillName;
+ const amountInUnits = parseFloat(editor.querySelector('.price-amount').value);
+ const currency_mint = editor.querySelector('.price-currency').value;
+
+ if (!isNaN(amountInUnits) && amountInUnits > 0) {
+ const amount = Math.round(amountInUnits * 1e6); // Convert back to smallest unit
+
+ await fetch(`/api/agents/${agentId}/skills/pricing`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', /* + auth headers */ },
+ body: JSON.stringify({ skill_name, amount, currency_mint }),
+ });
+ }
+ }
+ // Show feedback to user
+ alert('Prices saved!');
+});
diff --git a/src/app.js b/src/app.js
index ffc28f968..667fc4d09 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1,5 +1,6 @@
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';
+import { initWalletButton } from './wallet.js';
import { Viewer } from './viewer.js';
import { Editor } from './editor/index.js';
import { SimpleDropzone } from 'simple-dropzone';
@@ -1292,6 +1293,8 @@ class App {
if (this.viewer) this.viewer.dispose();
this.viewerEl = this.viewerContainerEl;
this.viewer = new Viewer(this.viewerEl, this.options);
+ initWalletButton();
+
if (!this.options.kiosk) {
this.editor = new Editor(this.viewer);
this.editor.attach();
diff --git a/src/marketplace.js b/src/marketplace.js
index 883a21861..8db82ed5f 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -1,3 +1,5 @@
+import QRCode from 'qrcode';
+
/**
* Agent Marketplace — discovery + detail page controller.
*
@@ -205,6 +207,17 @@ async function loadDetail(id) {
if (agent) {
detailState = { agent: agent, bookmarked: false };
renderDetail(agent, false);
+
+ // Fetch and render purchased skills
+ try {
+ const res = await fetch(`/api/users/me/agent-skills/${id}`);
+ const { skills: purchasedSkills } = await res.json();
+ renderSkills(agent, purchasedSkills);
+ } catch (error) {
+ console.error('Failed to load purchased skills', error);
+ renderSkills(agent, []);
+ }
+
} else {
renderDetailError('Agent not found');
}
@@ -233,6 +246,35 @@ function renderDetail(a, bookmarked) {
$('d-bookmark').classList.toggle('on', bookmarked);
$('d-bookmark').textContent = bookmarked ? '★' : '☆';
+ const skillPrices = a.skill_prices || {};
+ // For now, assume user owns nothing. We will replace this with a real check later.
+ const ownedSkills = new Set();
+
+ $('d-skills').innerHTML = skillsArr.length
+ ? skillsArr.map((s) => {
+ const name = typeof s === 'string' ? s : (s.name || '');
+ const price = skillPrices[name];
+
+ let actionButton;
+ if (price) {
+ if (ownedSkills.has(name)) {
+ actionButton = `<button class="skill-btn" disabled>Unlocked</button>`;
+ } else {
+ 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>';
+
const forksEl = $('d-forks-pill');
if (a.forks > 0) {
forksEl.textContent = `⑂ ${a.forks} forks`;
@@ -252,20 +294,14 @@ function renderDetail(a, bookmarked) {
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];
- let badge;
- let actionButton = '';
-
- if (price) {
- badge = `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`;
- actionButton = `<button class="purchase-btn" data-skill-name="${escapeHtml(name)}">Unlock</button>`;
- } else {
- badge = `<span class="price-badge price-free">Free</span>`;
- }
- return `<span class="skill-entry">${escapeHtml(name)}${badge}${actionButton}</span>`;
- }).join(' ')
- : '<div>This Agent includes the following Skills to help you complete more tasks.</div>';
+ 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(' ')
+ : '<div>This Agent has no skills defined.</div>';
$('d-library').innerHTML = libraryArr.length
? libraryArr.map((l) => `<span class="stat-pill">${escapeHtml(typeof l === 'string' ? l : l.name || '')}</span>`).join(' ')
: '<div>This Agent includes the following Libraries to help answer more questions.</div>';
@@ -408,11 +444,50 @@ function bindEvents() {
$('d-bookmark').addEventListener('click', toggleBookmark);
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();
+
+ // 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;
+ const price = agent?.skill_prices?.[skillName];
+
+ if (agent && price) {
+ $('modal-skill-name').textContent = skillName;
+ $('modal-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;
+ $('purchase-modal').classList.remove('modal-hidden');
+ }
+ }
+
+ if (e.target.matches('.close-button')) {
+ const modal = e.target.closest('#purchase-modal');
+ if (modal) modal.classList.add('modal-hidden');
+ }
+ });
-function openSubmitModal() {
+ // Listener for backdrop click
+ const purchaseModal = $('purchase-modal');
+ if (purchaseModal) {
+ purchaseModal.addEventListener('click', e => {
+ if (e.target.id === 'purchase-modal') {
+ purchaseModal.classList.add('modal-hidden');
+ }
+ });
+ }ubmitModal() {
$('market-submit-overlay').hidden = false;
$('sf-name').focus();
}
@@ -484,6 +559,55 @@ function formatDate(iso) {
return d.toLocaleDateString(undefined, { year: 'numeric', month: 'short', day: 'numeric' });
}
+// ── Purchase Flow ─────────────────────────────────────────────────────────
+
+async function onBuySkill(agentId, skillId) {
+ try {
+ const res = await fetch('/api/marketplace/purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${getAuthToken()}` },
+ body: JSON.stringify({ agent_id: agentId, skill_id: skillId }),
+ });
+ const txDetails = await res.json();
+ if (!res.ok) {
+ throw new Error(txDetails.error_description || 'Failed to initiate purchase.');
+ }
+
+ showPurchaseModal(txDetails);
+ } catch (err) {
+ console.error('Purchase initiation failed:', err);
+ alert(err.message);
+ }
+}
+
+function showPurchaseModal(txDetails) {
+ const modal = $('purchase-modal');
+ const canvas = $('qr-canvas');
+ const detailsEl = $('purchase-details');
+
+ const url = new URL(`solana:${txDetails.recipient}`);
+ url.searchParams.set('amount', txDetails.amount);
+ url.searchParams.set('spl-token', txDetails.splToken);
+ url.searchParams.set('reference', txDetails.reference);
+ url.searchParams.set('label', txDetails.label);
+ url.searchParams.set('message', txDetails.message);
+
+ detailsEl.textContent = `${txDetails.amount} USDC for "${txDetails.label}"`;
+
+ QRCode.toCanvas(canvas, url.toString(), { width: 256 }, (error) => {
+ if (error) console.error(error);
+ });
+
+ modal.hidden = false;
+ // Start polling for transaction confirmation... (covered in prompt 09)
+}
+
+function getAuthToken() {
+ // Implement logic to get the user's auth token (from cookies, localStorage, etc.)
+ // This is a placeholder.
+ return '';
+}
+
// ── Boot ──────────────────────────────────────────────────────────────────
function render() {
diff --git a/style.css b/style.css
index 06be4f05b..f855323a6 100644
--- a/style.css
+++ b/style.css
@@ -997,6 +997,48 @@ footer .separator {
.phi-grid-h::after {
content: '';
position: absolute;
+}
+
+.price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+
+.price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+}
+
+/* Price Badge Styles from Prompt 1 */
+.price-badge {
+ display: inline-block;
+ margin-left: 8px;
+ padding: 2px 6px;
+ font-size: 10px;
+ font-weight: 600;
+ border-radius: 4px;
+ vertical-align: middle;
+}
+
+.price-free {
+ color: #a7f3d0;
+ background-color: rgba(52, 211, 153, 0.1);
+}
+
+.price-paid {
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+}
left: 0;
right: 0;
height: 1px;
diff --git a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md b/tasks/monetization-feature/02-backend-create-skill-pricing-table.md
index dfa7106ac..679635890 100644
--- a/tasks/monetization-feature/02-backend-create-skill-pricing-table.md
+++ b/tasks/monetization-feature/02-backend-create-skill-pricing-table.md
@@ -1,9 +1,11 @@
---
-status: in-progress
+status: completed
---
# Prompt 2: Backend - Create Skill Pricing Table
+**Status:** Completed
+
## Objective
Create the necessary database table to store the prices of agent skills. This is a foundational step for the monetization feature.
@@ -11,9 +13,9 @@ Create the necessary database table to store the prices of agent skills. This is
To make skills purchasable, we need a dedicated table in our database (`agent_skill_prices`) that links a skill to a price, currency, and the creator who sets the price. This structure will allow us to easily query for a skill's price and manage payments.
## Instructions
-1. **Define the Schema:**
- * Create a new SQL migration file.
- * Define the schema for the `agent_skill_prices` table. It should include the following fields:
+- [x] **Define the Schema:**
+ - [x] Create a new SQL migration file.
+ - [x] Define the schema for the `agent_skill_prices` table. It should include the following fields:
* `id`: Primary key (e.g., UUID).
* `skill_id`: Foreign key referencing the `skills` table.
* `creator_id`: Foreign key referencing the `users` table (the user who created the skill and will receive payment).
@@ -21,8 +23,9 @@ To make skills purchasable, we need a dedicated table in our database (`agent_sk
* `currency_mint`: The public key of the SPL token used for payment (e.g., USDC's mint address). Stored as a string.
* `created_at` / `updated_at`: Timestamps.
-2. **Apply the Migration:**
- * Run the migration to create the table in your development database.
+- [x] **Apply the Migration:**
+ - [x] Run the migration to create the table in your development database.
+
## Code Example (SQL Migration)
diff --git a/tasks/monetization-feature/03-backend-api-set-skill-prices.md b/tasks/monetization-feature/03-backend-api-set-skill-prices.md
index 1f191e2d4..64583b832 100644
--- a/tasks/monetization-feature/03-backend-api-set-skill-prices.md
+++ b/tasks/monetization-feature/03-backend-api-set-skill-prices.md
@@ -1,9 +1,9 @@
---
-status: not-started
+status: completed
---
# Prompt 3: Backend API for Setting Skill Prices
-**Status:** Not Started
+**Status:** Completed
## Objective
Create a secure backend API endpoint for creators to save or update the prices for their agent's skills.
@@ -12,25 +12,25 @@ Create a secure backend API endpoint for creators to save or update the prices f
This endpoint will receive the pricing data from the creator UI (created in Prompt 2) and persist it to the `agent_skill_prices` database table. It's crucial to ensure that only the agent's owner can modify its skill prices.
## Instructions
-1. **Create a New API Route:**
- - In the `api/agents/` directory, create a new file or modify an existing one to handle a `POST` request, for example, `/api/agents/:id/skill-prices`.
+- [x] **Create a New API Route:**
+ - [x] In the `api/agents/` directory, create a new file or modify an existing one to handle a `POST` request, for example, `/api/agents/:id/skill-prices`.
-2. **Implement Authorization:**
- - The endpoint must be protected. Verify the user's session or API token.
- - Check that the authenticated user is the owner of the agent specified by the `:id` parameter. If not, return a `403 Forbidden` error.
+- [x] **Implement Authorization:**
+ - [x] The endpoint must be protected. Verify the user's session or API token.
+ - [x] Check that the authenticated user is the owner of the agent specified by the `:id` parameter. If not, return a `403 Forbidden` error.
-3. **Handle the Request:**
- - The request body will contain an array of skill prices, like `{ prices: [{ skill_name: "...", amount: 500000, currency_mint: "..." }] }`.
- - Validate the input data. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana mint address.
+- [x] **Handle the Request:**
+ - [x] The request body will contain an array of skill prices, like `{ prices: [{ skill_name: "...", amount: 500000, currency_mint: "..." }] }`.
+ - [x] Validate the input data. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana mint address.
-4. **Database Interaction:**
- - For the given `agent_id`, update the `agent_skill_prices` table.
- - A good approach is to use an "upsert" operation: if a price for a skill exists, update it; otherwise, insert a new row. You could also delete all existing prices for the agent and insert the new ones.
- - The table should store `agent_id`, `skill_name`, `amount`, and `currency_mint`.
+- [x] **Database Interaction:**
+ - [x] For the given `agent_id`, update the `agent_skill_prices` table.
+ - [x] A good approach is to use an "upsert" operation: if a price for a skill exists, update it; otherwise, insert a new row. You could also delete all existing prices for the agent and insert the new ones.
+ - [x] The table should store `agent_id`, `skill_name`, `amount`, and `currency_mint`.
-5. **Return a Response:**
- - On success, return a `200 OK` or `204 No Content` response.
- - On failure (validation error, database error), return an appropriate error code (e.g., `400 Bad Request`, `500 Internal Server Error`) with a descriptive message.
+- [x] **Return a Response:**
+ - [x] On success, return a `200 OK` or `204 No Content` response.
+ - [x] On failure (validation error, database error), return an appropriate error code (e.g., `400 Bad Request`, `500 Internal Server Error`) with a descriptive message.
## Code Example (Vercel Serverless Function)
diff --git a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md
index fdbe9e55c..1a526b862 100644
--- a/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md
+++ b/tasks/monetization-feature/03-creator-ui-for-skill-pricing.md
@@ -1,10 +1,12 @@
---
title: "Prompt 3: Creator UI for Skill Pricing"
-status: "not-started"
+status: "completed"
---
# Prompt 3: Creator UI for Skill Pricing
+**Status:** Completed
+
## Objective
Create 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-frontend-skill-purchase-button.md b/tasks/monetization-feature/03-frontend-skill-purchase-button.md
new file mode 100644
index 000000000..62b60354a
--- /dev/null
+++ b/tasks/monetization-feature/03-frontend-skill-purchase-button.md
@@ -0,0 +1,72 @@
+---
+status: not-started
+---
+
+# Prompt 3: Frontend - Add Skill Purchase Button
+
+## Objective
+Add a "Purchase" button for priced skills on the agent detail page to enable users to initiate the buying process.
+
+## Explanation
+With skill prices now displayed, the next step is to provide a clear call-to-action for users to purchase them. This involves replacing the static "Free" or price badge with an interactive "Purchase" button for paid skills. This button will be the entry point for the payment flow.
+
+## Instructions
+1. **Locate the Rendering Logic:**
+ * Open `src/marketplace.js` and find the `renderDetail` function.
+ * Identify the section where skill badges are currently rendered.
+
+2. **Conditionally Render a Button:**
+ * Modify the loop that iterates through the agent's skills.
+ * For each skill, check if a price exists in the `a.skill_prices` object.
+ * If a price exists, instead of just a text badge, render a `<button>` element.
+ * If the skill is free, continue to show the "Free" badge.
+
+3. **Embed Data in the Button:**
+ * The purchase button must contain the necessary information to initiate a transaction.
+ * Add `data-*` attributes to the button to store the `skill_name` and `agent_id`.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+// Inside renderDetail function, modify the skill mapping
+
+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
+ ? `<button class="purchase-btn" data-skill="${escapeHtml(name)}" data-agent="${a.id}">
+ Purchase for ${(price.amount / 1e6).toFixed(2)} USDC
+ </button>`
+ : `<span class="price-badge price-free">Free</span>`;
+
+ return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;
+ }).join(' ')
+ : '<div>This Agent has no skills defined.</div>';
+```
+
+## CSS Example (`/marketplace.css`)
+
+Add styles for the new purchase button.
+
+```css
+.purchase-btn {
+ margin-left: 8px;
+ padding: 4px 10px;
+ font-size: 12px;
+ font-weight: 600;
+ border-radius: 6px;
+ border: 1px solid #fde047;
+ color: #fde047;
+ background-color: rgba(253, 224, 71, 0.1);
+ cursor: pointer;
+ transition: background-color 0.2s, color 0.2s;
+}
+
+.purchase-btn:hover {
+ background-color: #fde047;
+ color: #111827;
+}
+```
diff --git a/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md b/tasks/monetization-feature/03-ui-creator-dashboard-for-pricing.md
index 18e2ba3c1..b0141948a 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: not-started
+status: in-progress
---
# Prompt 3: UI - Creator Dashboard for Pricing
diff --git a/tasks/monetization-feature/04-backend-for-saving-skill-prices.md b/tasks/monetization-feature/04-backend-for-saving-skill-prices.md
new file mode 100644
index 000000000..f5ad3ee28
--- /dev/null
+++ b/tasks/monetization-feature/04-backend-for-saving-skill-prices.md
@@ -0,0 +1,90 @@
+---
+title: "Prompt 4: Backend for Saving Skill Prices"
+status: "completed"
+---
+
+# Prompt 4: Backend for Saving Skill Prices
+
+**Status:** Completed
+
+## Objective
+Create the backend API endpoint to receive and persist the skill pricing data submitted from the creator UI.
+
+## Explanation
+With the creator UI in place, we now need a secure and efficient API endpoint to handle the data. This endpoint will receive a list of skill prices for a specific agent, validate that the request is coming from the agent's owner, and then atomically update the `agent_skill_prices` table.
+
+## Instructions
+1. **Create a new API route:** Create a file at `api/agents/[agentId]/skills-pricing.js`. This will create a dynamic route that handles requests for specific agents.
+2. **Implement the handler:**
+ * The handler should only accept `PUT` requests.
+ * It must authenticate the request and ensure a user is logged in.
+ * It must validate that the logged-in user is the owner of the agent specified in the URL (`agentId`).
+ * It should expect a JSON body with a `prices` array, like `[{ "skill_id": "...", "amount": 1000000, "currency_mint": "..." }]`.
+ * Use a database transaction to first `DELETE` all existing prices for the agent and then `INSERT` the new ones. This ensures data consistency.
+ * Return a success message on completion or a descriptive error on failure.
+
+## Code Example (`api/agents/[agentId]/skills-pricing.js`)
+
+```javascript
+import { getDb, getSession } from '../_lib/db.js';
+import { json, error } from '../_lib/res.js';
+
+export default async function handler(req, res) {
+ if (req.method !== 'PUT') {
+ return error(res, 405, 'Method Not Allowed');
+ }
+
+ const session = await getSession(req, res);
+ if (!session.userId) {
+ return error(res, 401, 'Unauthorized');
+ }
+
+ const { agentId } = req.query;
+ if (!agentId || typeof agentId !== 'string') {
+ return error(res, 400, 'Bad Request: Missing or invalid agentId');
+ }
+
+ const { prices } = req.body;
+ if (!Array.isArray(prices)) {
+ return error(res, 400, 'Bad Request: "prices" must be an array');
+ }
+
+ const db = await getDb();
+
+ try {
+ // First, verify that the user owns the agent.
+ const agent = await db.oneOrNone('SELECT id FROM agent_identities WHERE id = $1 AND user_id = $2 AND deleted_at IS NULL', [agentId, session.userId]);
+ if (!agent) {
+ return error(res, 403, 'Forbidden: You do not own this agent');
+ }
+
+ // Use a transaction to update prices atomically.
+ await db.tx(async t => {
+ // Clear existing prices for this agent.
+ await t.none('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);
+
+ if (prices.length === 0) {
+ return; // Nothing more to do if the array is empty.
+ }
+
+ // Use a multi-row insert for efficiency.
+ const cs = new t.helpers.ColumnSet(['agent_id', 'skill_id', 'amount', 'currency_mint'], { table: 'agent_skill_prices' });
+ const values = prices.map(p => ({
+ agent_id: agentId,
+ skill_id: p.skill_id,
+ amount: p.amount,
+ currency_mint: p.currency_mint,
+ }));
+
+ const query = t.helpers.insert(values, cs);
+ await t.none(query);
+ });
+
+ return json(res, 200, { message: 'Prices updated successfully' });
+
+ } catch (err) {
+ console.error('Error saving skill prices:', err);
+ return error(res, 500, 'Internal Server Error', err.message);
+ }
+}
+```
diff --git a/tasks/monetization-feature/04-backend-solana-pay-endpoint.md b/tasks/monetization-feature/04-backend-solana-pay-endpoint.md
new file mode 100644
index 000000000..930e8df73
--- /dev/null
+++ b/tasks/monetization-feature/04-backend-solana-pay-endpoint.md
@@ -0,0 +1,85 @@
+---
+status: not-started
+---
+
+# Prompt 4: Backend - Create Solana Pay Endpoint
+
+## Objective
+Create a backend endpoint that generates a Solana Pay transaction for a skill purchase, allowing for a seamless on-chain payment experience.
+
+## Explanation
+To enable decentralized payments, we will use Solana Pay. This requires a dedicated backend endpoint that, when requested, constructs and returns a Solana transaction tailored to the specific skill purchase. The frontend will then use this to generate a QR code for mobile wallets or to prompt browser extension wallets.
+
+## Instructions
+1. **Create a New API Route:**
+ * Create a new file at `/api/payments/solana-pay.js`.
+
+2. **Implement the Endpoint Logic:**
+ * The endpoint should handle `POST` requests.
+ * It should expect a JSON body containing the `agent_id` and `skill_name`.
+ * It needs to fetch the skill's price from the `agent_skill_prices` table.
+ * It must identify the recipient's wallet address (the agent creator's address).
+ * Using the Solana SDK (`@solana/web3.js`), construct a system transfer transaction.
+ * The transaction should transfer the correct `amount` of the specified `currency_mint` from the buyer to the creator.
+
+3. **Return Solana Pay Spec Response:**
+ * The endpoint must return a JSON object that conforms to the Solana Pay specification.
+ * This includes a base64-encoded, serialized transaction, a `label`, and a `message`.
+
+## Code Example (`/api/payments/solana-pay.js`)
+
+```javascript
+import { sql } from '../_lib/db.js';
+import { json, error, wrap, readJson } from '../_lib/http.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';
+import { z } from 'zod';
+
+const purchaseSchema = z.object({
+ agent_id: z.string().uuid(),
+ skill_name: z.string().min(1).max(128),
+});
+
+export default wrap(async (req, res) => {
+ if (req.method !== 'POST') return error(res, 405, 'method_not_allowed');
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized');
+
+ const body = await readJson(req);
+ const { agent_id, skill_name } = purchaseSchema.parse(body);
+
+ // 1. Fetch price and creator's wallet
+ const [priceInfo] = await sql`...`; // Get price and creator wallet
+ if (!priceInfo) return error(res, 404, 'price_not_found');
+
+ // 2. Setup Solana connection
+ const connection = new Connection(process.env.SOLANA_RPC_URL);
+ const buyer = new PublicKey(user.wallet_address);
+ const recipient = new PublicKey(priceInfo.creator_wallet_address);
+
+ // 3. Create transaction
+ const { blockhash } = await connection.getLatestBlockhash();
+ const tx = new Transaction({
+ recentBlockhash: blockhash,
+ feePayer: buyer,
+ }).add(
+ SystemProgram.transfer({
+ fromPubkey: buyer,
+ toPubkey: recipient,
+ lamports: priceInfo.amount,
+ })
+ );
+
+ // 4. Serialize and encode
+ const serializedTx = tx.serialize({ requireAllSignatures: false });
+ const base64Tx = serializedTx.toString('base64');
+
+ // 5. Return Solana Pay response
+ return json(res, 200, {
+ transaction: base64Tx,
+ label: '3D-Agent Skill Purchase',
+ message: `Purchase '${skill_name}' for Agent`,
+ });
+});
+```
diff --git a/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md b/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md
index 4dbdb2df4..ec1d4743e 100644
--- a/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md
+++ b/tasks/monetization-feature/04-frontend-ui-set-skill-prices.md
@@ -1,5 +1,5 @@
---
-status: not-started
+status: completed
---
# Prompt 4: Frontend - UI for Creators to Set Skill Prices
diff --git a/tasks/monetization-feature/05-frontend-solana-pay-integration.md b/tasks/monetization-feature/05-frontend-solana-pay-integration.md
new file mode 100644
index 000000000..ba35d6d46
--- /dev/null
+++ b/tasks/monetization-feature/05-frontend-solana-pay-integration.md
@@ -0,0 +1,73 @@
+---
+status: not-started
+---
+
+# Prompt 5: Frontend - Solana Pay Integration
+
+## Objective
+Integrate the frontend "Purchase" button with the backend Solana Pay endpoint to generate and display a payment QR code.
+
+## Explanation
+This task connects the user's purchase action to the on-chain transaction. When a user clicks the "Purchase" button, the frontend will call the new Solana Pay endpoint, retrieve the transaction details, and then use a library to display a QR code. This allows users with mobile wallets to scan and approve the payment seamlessly.
+
+## Instructions
+1. **Add Solana Pay Library:**
+ * Include the Solana Pay QR code generation library in your project. You can use the official `@solana/pay` and a QR code library.
+ * Run `npm install @solana/pay qrcode`.
+
+2. **Create a Modal Component:**
+ * In your main HTML file (e.g., `marketplace.html`), add the structure for a modal dialog that will contain the QR code. It should be hidden by default.
+
+3. **Implement Click Handler:**
+ * In `src/marketplace.js`, add a click event listener to the `d-skills` container (or use event delegation).
+ * The handler should trigger only for clicks on `.purchase-btn`.
+
+4. **Fetch Transaction and Generate QR:**
+ * Inside the click handler, retrieve the `skill_name` and `agent_id` from the button's `data-*` attributes.
+ * Make a `POST` request to `/api/payments/solana-pay` with this data.
+ * The response will contain the Solana Pay URL. Use the `qrcode` library to generate a QR code from this URL.
+ * Inject the QR code into your modal and display it.
+
+## Code Example (`src/marketplace.js`)
+
+```javascript
+import QRCode from 'qrcode';
+
+// ... other code ...
+
+async function handlePurchaseClick(e) {
+ if (!e.target.matches('.purchase-btn')) return;
+
+ const btn = e.target;
+ const { skill, agent } = btn.dataset;
+
+ // Show a loading spinner
+ btn.disabled = true;
+
+ try {
+ const res = await fetch('/api/payments/solana-pay', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ agent_id: agent, skill_name: skill }),
+ });
+
+ if (!res.ok) throw new Error('Failed to create transaction');
+
+ const { transaction, message } = await res.json();
+ const solanaPayUrl = `solana:${transaction}?label=${encodeURIComponent(message)}`;
+
+ // Generate QR and show modal
+ const qrCanvas = document.getElementById('qr-canvas');
+ await QRCode.toCanvas(qrCanvas, solanaPayUrl, { width: 256 });
+ document.getElementById('payment-modal').style.display = 'block';
+
+ } catch (err) {
+ console.error('Purchase failed:', err);
+ // Show an error message
+ } finally {
+ btn.disabled = false;
+ }
+}
+
+$('d-skills').addEventListener('click', handlePurchaseClick);
+```
diff --git a/tasks/monetization-feature/06-backend-payment-verification.md b/tasks/monetization-feature/06-backend-payment-verification.md
new file mode 100644
index 000000000..451abc8e6
--- /dev/null
+++ b/tasks/monetization-feature/06-backend-payment-verification.md
@@ -0,0 +1,75 @@
+---
+status: not-started
+---
+
+# Prompt 6: Backend - Payment Verification and Skill Unlock
+
+## Objective
+Verify completed Solana transactions and record skill purchases to grant users access.
+
+## Explanation
+After a user approves a payment, the backend must confirm the transaction on-chain and then "unlock" the skill for them. This involves creating a record that permanently links the user to their purchased skill, ensuring they have access in the future.
+
+## Instructions
+1. **Create a `user_purchased_skills` Table:**
+ * Create a new migration file.
+ * Define a table to store successful purchases. It should include `user_id`, `agent_id`, `skill_name`, `transaction_signature`, and `created_at`.
+
+2. **Add a Verification Endpoint (or logic):**
+ * The Solana Pay transaction can include a `memo` with a unique reference ID for the purchase.
+ * Create a new endpoint, e.g., `/api/payments/verify`, that the frontend can call after the user signs the transaction.
+ * Alternatively, you can have a backend service that polls or uses a webhook to find transactions addressed to the creator's wallet.
+
+3. **Implement Verification Logic:**
+ * When the verification is triggered, the backend should:
+ * Receive the transaction signature.
+ * Use the Solana SDK (`connection.getTransaction(signature)`) to fetch the transaction details from the blockchain.
+ * Validate that the transaction transferred the correct amount of the correct currency to the correct recipient.
+ * Check that this transaction signature has not already been processed.
+
+4. **Insert Purchase Record:**
+ * If the transaction is valid, insert a new row into the `user_purchased_skills` table.
+
+## SQL Example for Table
+
+```sql
+CREATE TABLE user_purchased_skills (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ user_id UUID NOT NULL REFERENCES users(id),
+ agent_id UUID NOT NULL REFERENCES agents(id),
+ skill_name VARCHAR(128) NOT NULL,
+ transaction_signature VARCHAR(128) NOT NULL UNIQUE,
+ purchase_price NUMERIC(20, 0) NOT NULL,
+ purchase_currency VARCHAR(64) NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX idx_user_purchased_skills_user_id ON user_purchased_skills(user_id);
+```
+
+## Code Snippet (Verification Logic)
+
+```javascript
+// Inside the verification endpoint
+const { signature } = req.body;
+
+const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });
+
+if (!tx) {
+ return error(res, 404, 'transaction_not_found');
+}
+
+// ... deep validation of transaction details ...
+// 1. Check recipient address
+// 2. Check transfer amount
+// 3. Check currency mint (if SPL token)
+
+// If valid, insert into the database
+await sql`
+ INSERT INTO user_purchased_skills (user_id, agent_id, skill_name, transaction_signature, ...)
+ VALUES (...)
+`;
+
+// Return success to the client
+return json(res, 200, { success: true, message: 'Skill unlocked!' });
+```
diff --git a/tasks/monetization-feature/07-backend-api-for-nft-minting.md b/tasks/monetization-feature/07-backend-api-for-nft-minting.md
new file mode 100644
index 000000000..333e10993
--- /dev/null
+++ b/tasks/monetization-feature/07-backend-api-for-nft-minting.md
@@ -0,0 +1,107 @@
+---
+status: not-started
+---
+
+# Prompt 7: Backend - API for Skill NFT Minting
+
+**Status:** Not Started
+
+## Objective
+Create an API endpoint that allows a user to purchase a skill and receive it as an NFT. This endpoint will be responsible for creating and processing the Solana transaction.
+
+## Explanation
+This is the core of the monetization feature. This API will take a user's public key and the desired skill, and in return, provide a transaction that, when signed by the user, will transfer the funds and mint the skill NFT to their wallet. We will use Solana Pay's Transaction Request standard for a seamless user experience.
+
+## Instructions
+1. **Create the API Endpoint:**
+ - Create a new API route, for example, `/api/skills/purchase`.
+ - Implement a `POST` handler that accepts `user_account`, `agent_id`, and `skill_name`.
+
+2. **Implement the Transaction Logic:**
+ - Fetch the skill's price from the `agent_skill_prices` table.
+ - Fetch the agent creator's wallet address from the `users` table.
+ - Fetch the agent's `skill_collection_mint` from the `agents` table.
+ - Upload the skill's NFT metadata (as defined in Prompt 5) to Arweave or IPFS.
+ - Generate a new keypair for the skill NFT's mint account.
+ - Build a Solana transaction using `@solana/web3.js`. This transaction must include:
+ - A `SystemProgram.transfer` instruction to send the purchase amount from the `user_account` to the creator's wallet.
+ - The instructions to create and mint the new NFT, associating it with the agent's collection. Use the Metaplex Umi library for this.
+ - Serialize the transaction, but *do not* sign it.
+
+3. **Return a Solana Pay-Compatible Response:**
+ - The API response should follow the Solana Pay Transaction Request standard.
+ - The `transaction` field should be the base64-encoded serialized transaction.
+ - Include a `message` like "Purchase Skill '[Skill Name]' for [Amount] USDC".
+
+## Code Example (Vercel Serverless Function - `api/skills/purchase.js`)
+
+```javascript
+import { createNft } from '@metaplex-foundation/mpl-token-metadata';
+import { generateSigner, some } from '@metaplex-foundation/umi';
+import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';
+import { initializeUmi } from '@lib/solana/umi';
+import { db } from '@lib/db';
+
+async function handler(req, res) {
+ if (req.method !== 'POST') {
+ return res.status(405).end();
+ }
+ const { user_account, agent_id, skill_name } = req.body;
+
+ try {
+ // 1. Fetch all required data
+ const priceInfo = await db.query('SELECT * FROM agent_skill_prices WHERE agent_id = $1 AND skill_name = $2', [agent_id, skill_name]);
+ const agent = await db.query('SELECT owner_id, skill_collection_mint FROM agents WHERE id = $1', [agent_id]);
+ const creator = await db.query('SELECT wallet_address FROM users WHERE id = $1', [agent.rows[0].owner_id]);
+
+ if (!priceInfo.rows.length || !creator.rows.length || !agent.rows[0].skill_collection_mint) {
+ return res.status(404).json({ error: 'Skill or creator not found' });
+ }
+
+ const umi = initializeUmi();
+ const skillMint = generateSigner(umi);
+
+ // 2. TODO: Upload metadata to Arweave
+ const metadataUri = 'https://...';
+
+ // 3. Build the mint instruction
+ const mintIx = createNft(umi, {
+ mint: skillMint,
+ name: skill_name,
+ uri: metadataUri,
+ sellerFeeBasisPoints: percentAmount(0),
+ collection: some({ key: new PublicKey(agent.rows[0].skill_collection_mint), verified: false }),
+ }).getInstructions();
+
+ // 4. Build the full transaction
+ let transaction = new Transaction();
+ transaction.add(
+ SystemProgram.transfer({
+ fromPubkey: new PublicKey(user_account),
+ toPubkey: new PublicKey(creator.rows[0].wallet_address),
+ lamports: priceInfo.rows[0].amount,
+ })
+ );
+ // This is a simplification; you'd convert the Umi instructions to web3.js format
+ // transaction.add(...convertedMintIx);
+
+ // 5. Return Solana Pay response
+ const serializedTransaction = transaction.serialize({ requireAllSignatures: false });
+
+ return res.status(200).json({
+ transaction: serializedTransaction.toString('base64'),
+ message: `Purchase ${skill_name} for ${priceInfo.rows[0].amount / 1e6} USDC`,
+ });
+
+ } catch (error) {
+ console.error('Failed to create purchase transaction:', error);
+ return res.status(500).json({ error: 'Failed to create transaction' });
+ }
+}
+```
+
+## Definition of Done
+- The `/api/skills/purchase` endpoint is created.
+- The endpoint correctly fetches all necessary data.
+- It generates a transaction with both the payment and minting instructions.
+- The response is compatible with the Solana Pay Transaction Request standard.
diff --git a/tasks/monetization-feature/07-creator-earnings-dashboard.md b/tasks/monetization-feature/07-creator-earnings-dashboard.md
new file mode 100644
index 000000000..789770905
--- /dev/null
+++ b/tasks/monetization-feature/07-creator-earnings-dashboard.md
@@ -0,0 +1,63 @@
+---
+status: not-started
+---
+
+# Prompt 7: Frontend - Creator Earnings Dashboard
+
+## Objective
+Create a dedicated page for creators to view their total earnings, pending payments, and a history of their sales.
+
+## Explanation
+To empower creators, they need a transparent view of their monetization performance. This dashboard will serve as their financial hub, providing key metrics and a detailed breakdown of every sale, which builds trust and encourages them to create more premium content.
+
+## Instructions
+1. **Create New Frontend Files:**
+ * Create a new HTML file: `earnings.html`.
+ * Create a new JavaScript module: `src/earnings.js`.
+ * Link the script in the HTML file: `<script type="module" src="/src/earnings.js"></script>`.
+
+2. **Design the UI in `earnings.html`:**
+ * Add a main title, e.g., "Creator Earnings".
+ * Create summary boxes for "Total Revenue", "Pending Payout", and "Total Sales".
+ * Add a table element with a `<thead>` for the sales history. Columns should include: "Date", "Skill Name", "Agent Name", "Price", and "Status" (e.g., Pending, Paid).
+ * The table should have a `<tbody>` with a unique ID for dynamically inserting rows.
+
+3. **Implement Frontend Logic in `src/earnings.js`:**
+ * On page load, make a GET request to a new `/api/users/earnings` endpoint.
+ * Process the JSON response.
+ * Populate the summary boxes with the aggregate data.
+ * Iterate through the sales history array. For each sale, create a `<tr>` element and insert it into the table body.
+ * Format dates and currency values for readability.
+
+## HTML Structure Example (`earnings.html`)
+
+```html
+<main>
+ <h1>Creator Earnings</h1>
+ <div class="summary-cards">
+ <div class="card">
+ <h2>Total Revenue</h2>
+ <p id="total-revenue">$0.00</p>
+ </div>
+ <div class="card">
+ <h2>Pending Payout</h2>
+ <p id="pending-payout">$0.00</p>
+ </div>
+ </div>
+ <h2>Sales History</h2>
+ <table id="sales-table">
+ <thead>
+ <tr>
+ <th>Date</th>
+ <th>Skill</th>
+ <th>Price</th>
+ <th>Status</th>
+ </tr>
+ </thead>
+ <tbody id="sales-tbody">
+ <!-- Rows will be inserted here by JavaScript -->
+ </tbody>
+ </table>
+</main>
+<script type="module" src="/src/earnings.js"></script>
+```
diff --git a/tasks/monetization-feature/08-backend-creator-earnings-api.md b/tasks/monetization-feature/08-backend-creator-earnings-api.md
new file mode 100644
index 000000000..dda6ff47f
--- /dev/null
+++ b/tasks/monetization-feature/08-backend-creator-earnings-api.md
@@ -0,0 +1,76 @@
+---
+status: not-started
+---
+
+# Prompt 8: Backend - Creator Earnings API Endpoint
+
+## Objective
+Create a secure API endpoint to provide detailed earnings data for the logged-in creator.
+
+## Explanation
+This endpoint is the backbone of the Creator Earnings Dashboard. It needs to securely authenticate the user, query the database for all their sales, calculate summary statistics, and return the data in a clean, organized format for the frontend to consume.
+
+## Instructions
+1. **Create the API Route:**
+ * Create a new file: `/api/users/earnings.js`.
+
+2. **Implement Authentication:**
+ * The endpoint must be protected. Use your existing session management (e.g., `getSessionUser`) to get the `userId` of the requester.
+ * If the user is not authenticated, return a `401 Unauthorized` error.
+
+3. **Query the Database:**
+ * Write a SQL query to fetch sales data for the authenticated `userId`.
+ * You will need to join several tables:
+ * Start with a table that records sales or royalty payments (e.g., `royalty_ledger`).
+ * Join with `agent_skill_prices` or a similar table to get skill details.
+ * Join with `agents` to get agent names.
+ * The query should select all necessary columns: date, skill name, agent name, price, currency, and payment status.
+ * Order the results by date, descending.
+
+4. **Calculate Summary Data:**
+ * After fetching the rows, use code to calculate the total revenue and the amount pending payout.
+ * This is often more efficient than running separate aggregate SQL queries.
+
+5. **Format and Return the Response:**
+ * Structure the response as a JSON object containing the summary figures and an array of the detailed transaction history.
+
+## Code Example (`/api/users/earnings.js`)
+
+```javascript
+import { sql } from '../_lib/db.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { json, error, wrap } from '../_lib/http.js';
+
+export default wrap(async (req, res) => {
+ if (req.method !== 'GET') return error(res, 405);
+
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401, 'unauthorized');
+
+ const sales = await sql`
+ SELECT
+ r.created_at,
+ s.skill_name,
+ a.name AS agent_name,
+ r.price_usd,
+ r.status
+ FROM royalty_ledger r
+ JOIN agent_skill_prices s ON s.id = r.skill_price_id
+ JOIN agents a ON a.id = s.agent_id
+ WHERE r.author_user_id = ${user.id}
+ ORDER BY r.created_at DESC
+ LIMIT 100;
+ `;
+
+ const total_revenue = sales.reduce((sum, r) => sum + Number(r.price_usd), 0);
+ const pending_payout = sales
+ .filter(r => r.status === 'pending')
+ .reduce((sum, r) => sum + Number(r.price_usd), 0);
+
+ return json(res, 200, {
+ total_revenue,
+ pending_payout,
+ history: sales,
+ });
+});
+```
diff --git a/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md b/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md
new file mode 100644
index 000000000..aefa6c7ba
--- /dev/null
+++ b/tasks/monetization-feature/08-frontend-purchase-modal-with-solana.md
@@ -0,0 +1,84 @@
+---
+status: not-started
+---
+
+# Prompt 8: Frontend - Purchase Modal with Solana Pay
+
+**Status:** Not Started
+
+## Objective
+Create a user interface that allows users to purchase a skill NFT using their Solana wallet.
+
+## Explanation
+With the backend ready to generate purchase transactions, we need a frontend to initiate the process. This involves creating a purchase button that, when clicked, opens a modal with a Solana Pay QR code. Users can scan this with their mobile wallet or use a browser extension to approve the transaction.
+
+## Instructions
+1. **Modify the `renderDetail` Function:**
+ - In `src/marketplace.js`, within the skill rendering loop, if a skill has a price, display a "Purchase" button instead of the price badge.
+
+2. **Create the Purchase Modal:**
+ - Design a modal that will display the Solana Pay QR code.
+ - The modal should show the skill name, price, and a spinning loader while waiting for the transaction.
+
+3. **Implement the Purchase Flow:**
+ - When a "Purchase" button is clicked:
+ - Open the purchase modal.
+ - Make a `POST` request to your `/api/skills/purchase` endpoint, sending the user's connected wallet address, the agent ID, and the skill name.
+ - The API will respond with a Solana Pay transaction request.
+ - Use a Solana Pay QR code generation library to render the QR code in the modal.
+ - **Listen for Transaction Confirmation:**
+ - The frontend should poll for the transaction's signature on the Solana blockchain.
+ - Once the transaction is confirmed, update the UI to show a success message and change the skill's button to "Owned".
+
+## Code Example (JavaScript in `src/marketplace.js`)
+
+```javascript
+// ... inside the skill rendering loop in renderDetail ...
+
+if (price) {
+ const purchaseBtn = document.createElement('button');
+ purchaseBtn.className = 'purchase-skill-btn';
+ purchaseBtn.textContent = `Purchase for ${(price.amount / 1e6).toFixed(2)} USDC`;
+ purchaseBtn.onclick = () => openPurchaseModal(a.id, name);
+ skillEntry.appendChild(purchaseBtn);
+}
+
+// ... new function to handle the purchase flow ...
+
+async function openPurchaseModal(agentId, skillName) {
+ const modal = document.getElementById('purchase-modal');
+ const qrCodeContainer = document.getElementById('qr-code');
+ modal.hidden = false;
+
+ const userWallet = /* get connected wallet address */;
+
+ try {
+ const response = await fetch('/api/skills/purchase', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ user_account: userWallet, agent_id: agentId, skill_name: skillName }),
+ });
+ const { transaction, message } = await response.json();
+
+ // Create a Solana Pay URL
+ const solanaPayUrl = `solana:${encodeURIComponent(transaction)}`;
+
+ // Generate and display the QR code
+ const qr = QRCode.create(solanaPayUrl, { size: 256 });
+ qrCodeContainer.innerHTML = '';
+ qr.append(qrCodeContainer);
+
+ // ... add logic to poll for the transaction signature ...
+
+ } catch (error) {
+ console.error('Purchase failed:', error);
+ // show error in modal
+ }
+}
+```
+
+## Definition of Done
+- A "Purchase" button appears next to paid skills in the marketplace.
+- Clicking the button opens a modal displaying a Solana Pay QR code.
+- After the transaction is confirmed, the UI updates to reflect skill ownership.
+- The entire flow is functional on Solana devnet.
diff --git a/tasks/monetization-feature/09-admin-payout-system.md b/tasks/monetization-feature/09-admin-payout-system.md
new file mode 100644
index 000000000..c6186e6ad
--- /dev/null
+++ b/tasks/monetization-feature/09-admin-payout-system.md
@@ -0,0 +1,49 @@
+---
+status: not-started
+---
+
+# Prompt 9: Admin - Creator Payout System
+
+## Objective
+Build a secure internal admin interface to manage and process creator payouts efficiently.
+
+## Explanation
+As creators earn money, the platform needs a robust and trustworthy system for paying them. This internal tool will allow administrators to view pending payouts, mark them as paid, and record transaction details for accounting and dispute resolution. This is a critical operational component for a monetized platform.
+
+## Instructions
+1. **Create a New Admin Page:**
+ * In a dedicated admin section of your application, create a new page: `/admin/payouts.html`.
+ * Secure this page to ensure only authorized administrators can access it.
+
+2. **Backend API for Payouts:**
+ * Create a new admin-only API endpoint: `/api/admin/payouts.js`.
+ * This endpoint will have two functions:
+ * `GET`: Fetches a list of all creators who have a pending payout balance greater than zero. It should include the creator's username, their pending balance, and their preferred payout method/address.
+ * `POST`: Marks a creator's pending payouts as `completed`. It should accept a `creator_id` and a `transaction_reference` (e.g., a bank transfer ID or a blockchain transaction hash).
+
+3. **Frontend UI for Payouts:**
+ * The `/admin/payouts.html` page should:
+ * Fetch and display the list of pending payouts in a table.
+ * Each row should have a "Mark as Paid" button.
+ * Clicking the button should open a form/modal where the admin can enter the transaction reference.
+ * Submitting the form should call the `POST` method on the API endpoint.
+ * The UI should update to reflect the completed payout.
+
+4. **Update Payout Status in the Database:**
+ * The `POST` request to the API should trigger a database update.
+ * It should update the `status` of all `pending` items in the `royalty_ledger` for that creator to `paid`.
+ * It should also record the payout transaction in a new `payouts` table for auditing purposes.
+
+## `payouts` Table SQL Example
+
+```sql
+CREATE TABLE payouts (
+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
+ creator_user_id UUID NOT NULL REFERENCES users(id),
+ amount_usd NUMERIC(12, 2) NOT NULL,
+ payout_method VARCHAR(64),
+ transaction_reference TEXT,
+ processed_by_admin_id UUID NOT NULL REFERENCES users(id),
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+```
diff --git a/tasks/monetization-feature/10-referral-system-frontend.md b/tasks/monetization-feature/10-referral-system-frontend.md
new file mode 100644
index 000000000..8261c4615
--- /dev/null
+++ b/tasks/monetization-feature/10-referral-system-frontend.md
@@ -0,0 +1,71 @@
+---
+status: not-started
+---
+
+# Prompt 10: Frontend - Display Referral System Info
+
+## Objective
+Integrate the user's referral code and performance statistics into their profile page.
+
+## Explanation
+To make the referral program successful, users must be able to easily find their unique referral code and track how many people they've referred. By displaying this information clearly on their profile page, we empower them to become advocates for the platform.
+
+## Instructions
+1. **Update the Profile Page HTML:**
+ * Open the `profile.html` file.
+ * Add a new section titled "Referral Program".
+ * Inside this section, add elements with unique IDs to display:
+ * The user's referral code.
+ * A "copy to clipboard" button next to the code.
+ * The number of users they have successfully referred.
+ * Their total referral earnings to date.
+
+2. **Modify the Profile Page JavaScript:**
+ * Open `src/profile.js`.
+ * In the function that fetches profile data, also make a GET request to the `/api/users/referrals` endpoint you created previously.
+ * When the data is returned, populate the new elements in `profile.html` with the `referral_code`, `referred_users_count`, and `referral_earnings_total`.
+
+3. **Implement the "Copy to Clipboard" Functionality:**
+ * Add a click event listener to the copy button.
+ * When clicked, use the `navigator.clipboard.writeText()` API to copy the referral code to the user's clipboard.
+ * Provide visual feedback to the user, e.g., by changing the button text to "Copied!" for a few seconds.
+
+## HTML Example (`profile.html`)
+
+```html
+<section id="referral-section">
+ <h2>Referral Program</h2>
+ <p>Share your code to earn rewards!</p>
+ <div class="referral-code-wrapper">
+ <strong>Your Code:</strong>
+ <span id="referral-code"></span>
+ <button id="copy-referral-btn">Copy</button>
+ </div>
+ <div class="referral-stats">
+ <div>
+ <p>Users Referred</p>
+ <strong id="referred-users-count">0</strong>
+ </div>
+ <div>
+ <p>Total Earnings</p>
+ <strong id="referral-earnings-total">$0.00</strong>
+ </div>
+ </div>
+</section>
+```
+
+## JavaScript Snippet (`src/profile.js`)
+
+```javascript
+// After fetching data from /api/users/referrals
+const referralData = await response.json();
+
+document.getElementById('referral-code').textContent = referralData.referral_code;
+document.getElementById('referred-users-count').textContent = referralData.referred_users_count;
+document.getElementById('referral-earnings-total').textContent = `$${referralData.referral_earnings_total.toFixed(2)}`;
+
+document.getElementById('copy-referral-btn').addEventListener('click', () => {
+ navigator.clipboard.writeText(referralData.referral_code);
+ // ... provide visual feedback
+});
+```
diff --git a/tasks/monetization-feature/11-referral-system-signup-flow.md b/tasks/monetization-feature/11-referral-system-signup-flow.md
new file mode 100644
index 000000000..a1f38a3d2
--- /dev/null
+++ b/tasks/monetization-feature/11-referral-system-signup-flow.md
@@ -0,0 +1,73 @@
+---
+status: not-started
+---
+
+# Prompt 11: Frontend - Add Referral Code to Signup
+
+## Objective
+Update the user registration form to include an optional field for a referral code.
+
+## Explanation
+To create the link between a referrer and a new user, the referral code must be captured at the moment of signup. This involves adding a new input field to the registration UI and ensuring this data is sent to the backend API.
+
+## Instructions
+1. **Modify the Registration HTML:**
+ * Locate the HTML file that contains your user registration form (e.g., this might be in `app.html`, `index.html`, or handled by a JavaScript template).
+ * Add a new text input field to the form.
+ * Label it clearly, for example, "Referral Code (Optional)".
+ * Give it a `name` and `id`, such as `referral_code`.
+
+2. **Update the Registration JavaScript:**
+ * Find the JavaScript code that handles the registration form submission.
+ * When you gather the form data to send to the `/api/auth/register` endpoint, include the value from the new referral code input.
+ * Since the field is optional, your code should handle cases where it's empty.
+
+3. **Ensure Backend Compatibility:**
+ * This step relies on the backend changes from the earlier referral system task, where the `/api/auth/register` endpoint was updated to accept a `referralCode` field in its request body. No backend changes are needed for this prompt if that was done correctly.
+
+## HTML Form Example
+
+```html
+<!-- Inside your registration form -->
+<form id="register-form">
+ <div>
+ <label for="email">Email</label>
+ <input type="email" id="email" name="email" required>
+ </div>
+ <div>
+ <label for="password">Password</label>
+ <input type="password" id="password" name="password" required>
+ </div>
+ <div>
+ <label for="referral_code">Referral Code (Optional)</label>
+ <input type="text" id="referral_code" name="referral_code">
+ </div>
+ <button type="submit">Sign Up</button>
+</form>
+```
+
+## JavaScript Form Handling Example
+
+```javascript
+document.getElementById('register-form').addEventListener('submit', async (e) => {
+ e.preventDefault();
+ const formData = new FormData(e.target);
+ const data = Object.fromEntries(formData.entries());
+
+ // The backend expects 'referralCode' (camelCase) from the validation schema
+ const payload = {
+ email: data.email,
+ password: data.password,
+ referralCode: data.referral_code, // Ensure key matches backend expectation
+ };
+
+ const response = await fetch('/api/auth/register', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ // Only include referralCode if it has a value
+ body: JSON.stringify(Object.fromEntries(Object.entries(payload).filter(([_, v]) => v))),
+ });
+
+ // ... handle response
+});
+```
diff --git a/tasks/monetization-feature/12-referral-commission-logic.md b/tasks/monetization-feature/12-referral-commission-logic.md
new file mode 100644
index 000000000..53f4f5afd
--- /dev/null
+++ b/tasks/monetization-feature/12-referral-commission-logic.md
@@ -0,0 +1,79 @@
+---
+status: not-started
+---
+
+# Prompt 12: Backend - Implement Referral Commission Logic
+
+## Objective
+Implement the backend logic to award a commission to the referrer when a referred user makes their first purchase.
+
+## Explanation
+This is the core of the referral program's value proposition. When a new user, brought in by a referrer, makes a purchase, the system must automatically calculate and credit a commission to the referrer. This process should be reliable and auditable.
+
+## Instructions
+1. **Locate the Payment Verification Logic:**
+ * Find the part of your backend code that verifies a payment and unlocks a skill for a user (from "Prompt 6: Backend - Payment Verification"). This is likely in a file like `/api/payments/verify.js`.
+
+2. **Identify the Purchaser and Referrer:**
+ * Inside this logic, you have the `user_id` of the person making the purchase.
+ * Query the `users` table to check if this user has a `referred_by_id`.
+ * If `referred_by_id` is `null`, do nothing.
+
+3. **Check if it's the First Purchase:**
+ * To prevent awarding commissions on every purchase, you should typically only award it on the *first* purchase.
+ * Check your `user_purchased_skills` table to see if this user has any prior purchases. If they do, do not award a commission.
+
+4. **Calculate the Commission:**
+ * If there is a `referred_by_id` and this is the user's first purchase:
+ * Define the commission rate (e.g., 5% of the sale price). It's best to store this in a configuration file.
+ * Calculate the commission amount based on the `purchase_price`.
+
+5. **Record the Commission:**
+ * Insert a new entry into your `royalty_ledger` or a similar earnings table.
+ * This entry should be for the `referred_by_id` (the referrer).
+ * Clearly mark this earning as a "referral_commission".
+ * Update the `referral_earnings_total` on the referrer's `users` table row.
+
+## Code Logic Snippet (in payment verification)
+
+```javascript
+// After successfully verifying a transaction and before inserting the purchase record...
+
+const purchasePrice = ...; // price from the transaction
+const purchaserId = ...; // ID of the user who paid
+
+// 1. Get purchaser's referral info
+const [purchaser] = await sql`
+ SELECT referred_by_id FROM users WHERE id = ${purchaserId}
+`;
+
+if (purchaser && purchaser.referred_by_id) {
+ const referrerId = purchaser.referred_by_id;
+
+ // 2. Check if it's the first purchase for this user
+ const [priorPurchases] = await sql`
+ SELECT COUNT(*) as count FROM user_purchased_skills WHERE user_id = ${purchaserId}
+ `;
+
+ if (Number(priorPurchases.count) === 0) {
+ // 3. Calculate and award commission
+ const commissionRate = 0.05; // 5%
+ const commissionAmount = purchasePrice * commissionRate;
+
+ // 4. Record the commission in the ledger for the referrer
+ await sql`
+ INSERT INTO royalty_ledger (author_user_id, amount_usd, type, source_purchase_id, ...)
+ VALUES (${referrerId}, ${commissionAmount}, 'referral_commission', ...);
+ `;
+
+ // 5. Update the total on the user's record
+ await sql`
+ UPDATE users
+ SET referral_earnings_total = referral_earnings_total + ${commissionAmount}
+ WHERE id = ${referrerId};
+ `;
+ }
+}
+
+// Now, proceed to insert the main purchase record for the buyer...
+```
diff --git a/tasks/monetization-feature/13-api-keys-for-developers.md b/tasks/monetization-feature/13-api-keys-for-developers.md
new file mode 100644
index 000000000..c3c6115a3
--- /dev/null
+++ b/tasks/monetization-feature/13-api-keys-for-developers.md
@@ -0,0 +1,62 @@
+---
+status: not-started
+---
+
+# Prompt 13: Backend & Frontend - API Key Generation
+
+## Objective
+Allow users to generate and manage API keys from their profile, enabling programmatic access to the platform.
+
+## Explanation
+To grow into a true platform, third-party developers need a way to interact with your services. Providing API keys is the first step. This involves creating a secure system for generating, storing, and revoking keys, as well as a user-friendly interface for managing them.
+
+## Instructions
+
+### Backend
+1. **Create an `api_keys` Table:**
+ * Create a migration for a table to store API keys.
+ * Columns: `id`, `user_id`, `key_prefix`, `token_hash` (store a hash, not the raw key), `scope`, `created_at`, `revoked_at`, `last_used_at`.
+
+2. **Create API Endpoints (`/api/api-keys.js`):**
+ * `GET /`: Fetches all non-revoked API keys for the logged-in user. (Return only non-sensitive data like `key_prefix`, `scope`, `created_at`).
+ * `POST /`: Generates a new API key.
+ * Create a cryptographically secure key (e.g., `sk_live_` + random bytes).
+ * Hash the key before storing it in the database.
+ * **Important:** Return the full, unhashed key to the user **only once** upon creation. It cannot be retrieved again.
+ * `DELETE /:key_id`: Revokes an API key by setting `revoked_at`.
+
+### Frontend
+1. **Create New UI (`api-keys.html`):**
+ * Create a new page accessible from the user's main navigation.
+ * Add a section to list the user's existing API keys.
+ * Include a button to "Generate New Key".
+ * Each key in the list should have a "Revoke" button.
+
+2. **Implement Frontend Logic (`src/api-keys.js`):**
+ * On page load, `GET` keys from the API and render the list.
+ * When the "Generate" button is clicked, `POST` to the API. The response will contain the new key. Display this key in a modal and make it clear that it must be saved immediately.
+ * When a "Revoke" button is clicked, send a `DELETE` request for that key's ID and remove it from the list on success.
+
+## API Key Generation Snippet (Backend)
+
+```javascript
+import { randomBytes } from 'crypto';
+import { sha256 } from '../_lib/crypto.js';
+import { sql } from '../_lib/db.js';
+
+// Inside POST /api/api-keys
+const user = await getSessionUser(req);
+if (!user) return error(res, 401);
+
+const apiKey = `sk_live_${randomBytes(16).toString('hex')}`;
+const hash = await sha256(apiKey);
+const prefix = apiKey.substring(0, 10); // e.g., "sk_live_..."
+
+await sql`
+ INSERT INTO api_keys (user_id, token_hash, key_prefix, scope)
+ VALUES (${user.id}, ${hash}, ${prefix}, 'default');
+`;
+
+// Return the raw key ONLY this one time.
+return json(res, 201, { new_key: apiKey, message: "Save this key securely. You won't see it again." });
+```
diff --git a/tasks/monetization-feature/14-api-usage-tracking.md b/tasks/monetization-feature/14-api-usage-tracking.md
new file mode 100644
index 000000000..8d20abe37
--- /dev/null
+++ b/tasks/monetization-feature/14-api-usage-tracking.md
@@ -0,0 +1,69 @@
+---
+status: not-started
+---
+
+# Prompt 14: Backend - API Usage Tracking
+
+## Objective
+Implement a middleware to track API usage for each authenticated request, forming the basis for metered billing.
+
+## Explanation
+To bill developers for API consumption, we must first accurately measure it. This task involves creating a middleware that intercepts authenticated API requests, identifies the API key used, and increments a usage counter. This data is essential for enforcing rate limits and calculating monthly bills.
+
+## Instructions
+1. **Choose a Storage Method for Counters:**
+ * For high-throughput APIs, a fast data store like Redis is ideal for usage counters to avoid overwhelming your primary database.
+ * Alternatively, for moderate traffic, you can use a dedicated `api_usage_logs` table in your SQL database.
+
+2. **Create an Authentication/Tracking Middleware:**
+ * This middleware will run before your main API logic on protected routes.
+ * It should extract the bearer token from the `Authorization` header.
+ * Authenticate the token (as implemented in `authenticateBearer`). This function should now be enhanced to check for API keys by looking up their hash in the `api_keys` table.
+ * If the key is valid, attach the `user_id` and `apiKeyId` to the request object (`req.auth`).
+
+3. **Increment the Usage Counter:**
+ * After successful authentication, the middleware should increment the usage counter for the `apiKeyId`.
+ * **If using Redis:** Use the `INCR` command on a key like `api_usage:{apiKeyId}:{yyyy-mm}`.
+ * **If using SQL:** Insert a row into `api_usage_logs` with `api_key_id` and the current timestamp. You would then aggregate these logs for billing.
+
+4. **Apply the Middleware:**
+ * Wrap your API endpoint handlers with this new middleware to protect them and track their usage.
+
+## Middleware Example
+
+```javascript
+// In a file like /api/_lib/auth.js or a new middleware file
+
+import { extractBearer, authenticateBearer } from './auth.js';
+
+export function trackApiUsage(handler) {
+ return async (req, res) => {
+ const token = extractBearer(req);
+ if (!token) {
+ return error(res, 401, 'missing_token');
+ }
+
+ const authContext = await authenticateBearer(token); // This now handles both JWTs and API keys
+ if (!authContext) {
+ return error(res, 401, 'invalid_token');
+ }
+
+ // Attach auth info to the request for the handler to use
+ req.auth = authContext;
+
+ // If the request was via an API key, track usage
+ if (authContext.source === 'apikey') {
+ // Using Redis (example)
+ const redis = getRedisClient();
+ const period = new Date().toISOString().substring(0, 7); // YYYY-MM
+ await redis.incr(`api_usage:${authContext.apiKeyId}:${period}`);
+ }
+
+ // Proceed to the actual API endpoint logic
+ return handler(req, res);
+ };
+}
+
+// In your API route file:
+// export default wrap(trackApiUsage(async (req, res) => { ... your logic ... }));
+```
diff --git a/tasks/monetization-feature/15-api-billing-and-subscriptions.md b/tasks/monetization-feature/15-api-billing-and-subscriptions.md
new file mode 100644
index 000000000..fa23e4dbc
--- /dev/null
+++ b/tasks/monetization-feature/15-api-billing-and-subscriptions.md
@@ -0,0 +1,71 @@
+---
+status: not-started
+---
+
+# Prompt 15: Backend - API Billing and Subscriptions
+
+## Objective
+Integrate a payment provider like Stripe to manage recurring subscriptions for API access.
+
+## Explanation
+This task turns API usage into a revenue stream. It involves setting up subscription plans, creating a secure checkout process for users to subscribe, and using webhooks to keep your application's state in sync with the billing provider.
+
+## Instructions
+1. **Set Up Stripe Account and Products:**
+ * In your Stripe dashboard, create new products for your API plans (e.g., "Developer Plan", "Business Plan").
+ * Define the pricing for each plan (e.g., $49/month) and set usage limits (e.g., 100,000 API calls/month).
+
+2. **Create a `subscriptions` Table:**
+ * In your database, create a table to track user subscriptions.
+ * Columns: `id`, `user_id`, `stripe_subscription_id` (unique), `stripe_customer_id`, `plan_name`, `status` (e.g., `active`, `canceled`, `past_due`), `current_period_end`.
+
+3. **Implement Stripe Checkout Endpoint:**
+ * Create an API endpoint (e.g., `/api/billing/create-checkout-session`).
+ * This endpoint, using the Stripe Node.js library, will create a new Checkout Session for a specific plan.
+ * It should associate the session with a Stripe Customer ID (creating one if the user doesn't have one yet).
+ * Return the `sessionId` to the frontend, which will redirect the user to the Stripe-hosted checkout page.
+
+4. **Implement Stripe Webhook Handler:**
+ * Create a webhook endpoint (e.g., `/api/billing/webhook`) to receive events from Stripe.
+ * **Crucially, verify the webhook signature** to ensure the request is from Stripe.
+ * Handle key events:
+ * `checkout.session.completed`: A user has successfully subscribed. Use the data from this event to create a new record in your `subscriptions` table.
+ * `invoice.payment_succeeded`: A recurring payment was successful. Update the `current_period_end` in your database.
+ * `customer.subscription.deleted`: The user has canceled. Update the subscription `status` in your database.
+
+5. **Link Subscriptions to API Access:**
+ * In your API usage tracking middleware, before allowing an API call, check the user's subscription status in your database. If they have no active subscription or are over their usage limit, return a `403 Forbidden` or `429 Too Many Requests` error.
+
+## Webhook Handler Snippet
+
+```javascript
+// POST /api/billing/webhook
+const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
+
+// ... (inside the handler, after reading the raw body)
+let event;
+try {
+ event = stripe.webhooks.constructEvent(
+ rawBody,
+ req.headers['stripe-signature'],
+ process.env.STRIPE_WEBHOOK_SECRET
+ );
+} catch (err) {
+ return res.status(400).send(`Webhook Error: ${err.message}`);
+}
+
+switch (event.type) {
+ case 'checkout.session.completed':
+ const session = event.data.object;
+ // ... create subscription in your DB
+ break;
+ case 'customer.subscription.updated':
+ case 'customer.subscription.deleted':
+ const subscription = event.data.object;
+ // ... update subscription status in your DB
+ break;
+ // ... other events
+}
+
+res.status(200).json({ received: true });
+```
diff --git a/tasks/monetization-feature/16-ui-ux-monetization-polish.md b/tasks/monetization-feature/16-ui-ux-monetization-polish.md
new file mode 100644
index 000000000..7a65e30e8
--- /dev/null
+++ b/tasks/monetization-feature/16-ui-ux-monetization-polish.md
@@ -0,0 +1,47 @@
+---
+status: not-started
+---
+
+# Prompt 16: UI/UX - Monetization Polish
+
+## Objective
+Review and refine the user interface and experience for all new monetization features to ensure they are intuitive, trustworthy, and visually appealing.
+
+## Explanation
+A polished UI is not just about aesthetics; it builds user trust, which is paramount when dealing with payments and earnings. This task involves a comprehensive review of all monetization-related user flows, from purchasing a skill to checking earnings, to identify and fix any points of friction or confusion.
+
+## Instructions
+1. **Review the Skill Purchase Flow:**
+ * Go through the process of buying a skill, from the marketplace page to the payment modal.
+ * Is the price clear? Is the "Purchase" button prominent?
+ * Is the payment modal easy to understand? Does it provide clear feedback on success or failure?
+ * Add loading indicators to buttons after they are clicked to prevent double-submission.
+
+2. **Enhance the Creator Earnings Dashboard:**
+ * Review the `earnings.html` page.
+ * Are the summary cards easy to read? Use clear, large fonts for the key numbers.
+ * Is the sales history table well-formatted? Ensure dates and currency are localized.
+ * Consider adding simple charts to visualize earnings over time.
+
+3. **Improve the Referrals Section:**
+ * Look at the referral info on the `profile.html` page.
+ * Is the "Copy" button obvious? Does it provide clear feedback?
+ * Add a brief, encouraging explanation of how the referral program works and what the rewards are.
+
+4. **Refine the API Keys Management Page:**
+ * Review the `api-keys.html` page.
+ * When a new key is generated, is the warning to save it immediately prominent and clear?
+ * Is the process of revoking a key straightforward? Add a confirmation step (e.g., "Are you sure you want to revoke this key?") to prevent accidents.
+
+5. **Ensure Consistency:**
+ * Check that all new buttons, badges, modals, and tables use a consistent design language that matches the rest of the application.
+ * Use consistent terminology (e.g., "Purchase" vs. "Buy", "Earnings" vs. "Revenue").
+
+## Example UI Polish Checklist
+
+- [ ] Buttons have clear loading states.
+- [ ] Error messages are user-friendly and displayed in a consistent location.
+- [ ] All monetary values are formatted correctly (e.g., `$1,234.56`).
+- [ ] Forms have proper validation feedback.
+- [ ] The purpose of each page and section is immediately clear to a new user.
+- [ ] The mobile view for all new pages is clean and usable.
diff --git a/tasks/monetization-feature/17-frontend-purchase-confirmation.md b/tasks/monetization-feature/17-frontend-purchase-confirmation.md
new file mode 100644
index 000000000..3e39696bc
--- /dev/null
+++ b/tasks/monetization-feature/17-frontend-purchase-confirmation.md
@@ -0,0 +1,54 @@
+---
+status: not-started
+---
+
+# Prompt 17: Frontend Purchase Confirmation
+
+**Status:** Not Started
+
+## Objective
+Implement client-side logic to detect when a purchase is complete and provide feedback to the user.
+
+## Explanation
+After the user approves the transaction in their wallet, the frontend needs to know when the transaction is confirmed on the blockchain so it can close the purchase modal and update the UI. This is typically done by polling the backend or using a WebSocket.
+
+## Instructions
+- [ ] **Start Polling after Displaying QR Code:**
+ - [ ] Once the purchase modal is shown, start a polling mechanism (e.g., using `setInterval`).
+ - [ ] The polling function will make a request to a new backend endpoint (e.g., `GET /api/payments/check-status?reference=...`), passing the unique `reference` public key that was part of the Solana Pay request.
+- [ ] **Backend Status Check Endpoint:**
+ - [ ] Create the `/api/payments/check-status` endpoint.
+ - [ ] It will take a `reference` public key as a query parameter.
+ - [ ] It should use the Solana `getSignaturesForAddress` RPC method to see if that reference key has been used in a recent transaction.
+ - [ ] If a signature is found, the purchase is likely complete. The endpoint can then do the full confirmation (like in Prompt 6) and record the purchase. It should return `{ status: 'confirmed' }`.
+ - [ ] If no signature is found, it should return `{ status: 'pending' }`.
+- [ ] **Handle Confirmation on Frontend:**
+ - [ ] When the polling function receives a `'confirmed'` status:
+ - Stop the polling (`clearInterval`).
+ - Show a success message in the modal.
+ - Close the modal after a short delay.
+ - Trigger a UI update to change the "Buy" button to "Owned".
+
+## Code Example (Frontend Polling)
+
+```javascript
+// After showing the QR code in the modal...
+
+const reference = new URL(solanaPayUrl).searchParams.get('reference');
+const pollInterval = setInterval(async () => {
+ try {
+ const res = await fetch(`/api/payments/check-status?reference=${reference}`);
+ const { status } = await res.json();
+
+ if (status === 'confirmed') {
+ clearInterval(pollInterval);
+ // Show success animation/message
+ showSuccessAndCloseModal();
+ // Refresh user's skills to update the UI
+ fetchUserSkillsAndUpdateUI();
+ }
+ } catch (err) {
+ // Handle errors, maybe stop polling after too many failures
+ }
+}, 2000); // Poll every 2 seconds
+```
diff --git a/tasks/monetization-feature/17-transactional-emails.md b/tasks/monetization-feature/17-transactional-emails.md
new file mode 100644
index 000000000..12c0bae61
--- /dev/null
+++ b/tasks/monetization-feature/17-transactional-emails.md
@@ -0,0 +1,66 @@
+---
+status: not-started
+---
+
+# Prompt 17: Backend - Transactional Emails
+
+## Objective
+Implement automated transactional emails for key monetization events to keep users informed and engaged.
+
+## Explanation
+Transactional emails are a crucial part of a professional product. They confirm actions, build trust, and can bring users back to the platform. Events like a successful purchase, a new referral, or a monthly earnings summary all warrant a clear and timely email notification.
+
+## Instructions
+1. **Choose and Integrate an Email Service Provider (ESP):**
+ * Select an ESP like SendGrid, Postmark, or AWS SES.
+ * Sign up and get your API keys.
+ * Install their Node.js SDK (e.g., `npm install @sendgrid/mail`).
+ * Create a helper module (e.g., `/api/_lib/email.js`) to centralize your email-sending logic.
+
+2. **Create Email Templates:**
+ * Design simple, clean HTML templates for each email type. You can create these in your ESP's dashboard or as local files.
+ * Required templates:
+ * **Skill Purchase Receipt:** Sent to the buyer. Details the skill purchased, price, and a link back to the agent.
+ * **New Sale Notification:** Sent to the creator. Informs them they've made a sale.
+ * **New Referral Signup:** Sent to the referrer. Lets them know someone signed up with their code.
+ * **Referral Commission Earned:** Sent to the referrer. Informs them they've earned a commission from a sale.
+ * **API Subscription Confirmation:** Sent to a new API subscriber.
+
+3. **Trigger Emails from Backend Logic:**
+ * **Purchase Receipt:** In your payment verification logic, after successfully recording a purchase, call your email helper to send the receipt to the buyer.
+ * **Sale Notification:** At the same time, trigger the notification to the skill's creator.
+ * **Referral Emails:** In the registration and commission logic, call the email helper to notify the referrer.
+ * **Subscription Email:** In your Stripe webhook handler for `checkout.session.completed`, trigger the subscription confirmation email.
+
+## Email Helper Example (`/api/_lib/email.js`)
+
+```javascript
+import sgMail from '@sendgrid/mail';
+
+sgMail.setApiKey(process.env.SENDGRID_API_KEY);
+
+async function sendEmail({ to, subject, html, text }) {
+ const msg = {
+ to,
+ from: '[email protected]', // Use a verified sender
+ subject,
+ text,
+ html,
+ };
+
+ try {
+ await sgMail.send(msg);
+ } catch (error) {
+ console.error('Email sending failed:', error);
+ // Add more robust error handling/logging
+ }
+}
+
+export async function sendPurchaseReceiptEmail({ buyerEmail, skillName, price }) {
+ const subject = 'Your 3D-Agent Skill Purchase';
+ const html = `<p>Thank you for purchasing the skill: <strong>${skillName}</strong> for ${price}.</p>`;
+ await sendEmail({ to: buyerEmail, subject, html });
+}
+
+// ... other email functions
+```
diff --git a/tasks/monetization-feature/18-frontend-update-skill-state.md b/tasks/monetization-feature/18-frontend-update-skill-state.md
new file mode 100644
index 000000000..fa015dc64
--- /dev/null
+++ b/tasks/monetization-feature/18-frontend-update-skill-state.md
@@ -0,0 +1,60 @@
+---
+status: not-started
+---
+
+# Prompt 18: Frontend UI State Update Post-Purchase
+
+**Status:** Not Started
+
+## Objective
+Ensure the UI on the agent detail page correctly updates to reflect a newly purchased skill without requiring a full page reload.
+
+## Explanation
+After a user successfully buys a skill, the "Buy" button for that skill should immediately change to an "Owned" badge. This provides instant feedback and prevents the user from accidentally trying to buy the same skill again.
+
+## Instructions
+- [ ] **Refactor UI Update Logic:**
+ - [ ] Make sure your logic for rendering the skills list and their buttons is in a reusable function (e.g., `updateSkillDisplay(agent, purchases)`).
+- [ ] **Trigger UI Update:**
+ - [ ] After the purchase is confirmed (in the logic from Prompt 17), you need to update the local state that holds the user's purchased skills.
+ - [ ] You can do this in two ways:
+ 1. **Optimistic Update:** Immediately add the new skill's key (`agent_id:skill_name`) to your local `userPurchases` object and re-render. This is fast but could be wrong if there's a server error.
+ 2. **Refetch:** Call the `/api/users/my-skills` endpoint again to get the canonical list of purchases from the server, then re-render. This is more reliable.
+- [ ] **Call the Rendering Function:**
+ - [ ] After updating the local `userPurchases` data, call your reusable rendering function to redraw the skills list. The logic you wrote in Prompt 15 should now automatically show the "Owned" badge for the new skill.
+
+## Code Example (JavaScript)
+
+```javascript
+// state.mySkills is the object holding user's purchases, e.g., { "agentId:skillName": true }
+// state.currentAgent is the agent being viewed
+
+async function handlePurchaseSuccess(agentId, skillName) {
+ // Option 2: Refetch data for reliability
+ try {
+ const response = await fetch('/api/users/my-skills');
+ const data = await response.json();
+ state.mySkills = data.purchased; // Update global state
+ } catch (err) {
+ console.error("Failed to refresh user's skills:", err);
+ // Fallback or show error
+ }
+
+ // Now re-render the skills section
+ renderSkillsForAgent(state.currentAgent, state.mySkills);
+}
+
+function renderSkillsForAgent(agent, purchases) {
+ // This is the rendering logic from Prompt 15, now in its own function
+ const skillsContainer = document.getElementById('d-skills');
+ // ... logic to build the innerHTML for skills based on purchases ...
+ skillsContainer.innerHTML = '...';
+}
+
+// In the purchase confirmation logic (from Prompt 17)...
+if (status === 'confirmed') {
+ clearInterval(pollInterval);
+ showSuccessAndCloseModal();
+ handlePurchaseSuccess(agentIdBeingPurchased, skillNameBeingPurchased);
+}
+```
diff --git a/tasks/monetization-feature/18-terms-of-service-and-privacy-policy.md b/tasks/monetization-feature/18-terms-of-service-and-privacy-policy.md
new file mode 100644
index 000000000..5df9f008f
--- /dev/null
+++ b/tasks/monetization-feature/18-terms-of-service-and-privacy-policy.md
@@ -0,0 +1,40 @@
+---
+status: not-started
+---
+
+# Prompt 18: Legal - Terms of Service & Privacy Policy
+
+## Objective
+Create and integrate the necessary legal documents, such as a Terms of Service and Privacy Policy, to comply with regulations and define the rules of your platform.
+
+## Explanation
+When you handle user data and money, having clear, comprehensive legal documents is non-negotiable. The Terms of Service (ToS) outlines the agreement between the platform and its users, while the Privacy Policy explains how user data is collected, used, and protected. This task is essential for legal compliance and building user trust.
+
+**Disclaimer:** This prompt provides a general guide. You must consult with a qualified legal professional to draft documents appropriate for your specific business and jurisdiction.
+
+## Instructions
+1. **Draft the Legal Documents:**
+ * Work with a lawyer to draft a **Terms of Service**. This should cover:
+ * User responsibilities.
+ * Payment terms, creator payout policies, and fees.
+ * Intellectual property rights for agents and skills.
+ * Rules for API usage and subscriptions.
+ * Disclaimers and limitations of liability.
+ * Draft a **Privacy Policy**. This should cover:
+ * What data you collect (e.g., email, payment info, IP addresses).
+ * How you use the data.
+ * How you share data with third parties (like Stripe).
+ * User rights regarding their data (e.g., GDPR, CCPA compliance).
+
+2. **Create Static Pages for the Documents:**
+ * Create two new HTML files in your project: `terms-of-service.html` and `privacy-policy.html`.
+ * Paste the content of your legal documents into these pages. Format them for readability (e.g., using proper headings and lists).
+
+3. **Link to the Documents:**
+ * **Footer:** Add links to both the ToS and Privacy Policy in the main site footer so they are accessible from every page.
+ * **Registration Form:** Add a checkbox to the signup form that says "I agree to the <a href="/terms-of-service.html">Terms of Service</a> and <a href="/privacy-policy.html">Privacy Policy</a>." This checkbox must be required to complete registration.
+ * **Settings/Profile:** It's also good practice to have links to these documents in the user's account settings area.
+
+4. **Backend Check for Agreement:**
+ * Your registration API endpoint (`/api/auth/register`) should ideally accept a boolean parameter like `agreedToTerms: true`.
+ * The API should reject any registration request where this is not `true`. This creates a server-side record of the user's agreement.
diff --git a/tasks/monetization-feature/19-affiliate-dashboard-improvements.md b/tasks/monetization-feature/19-affiliate-dashboard-improvements.md
new file mode 100644
index 000000000..18e384d2d
--- /dev/null
+++ b/tasks/monetization-feature/19-affiliate-dashboard-improvements.md
@@ -0,0 +1,51 @@
+---
+status: not-started
+---
+
+# Prompt 19: Frontend - Affiliate Dashboard Improvements
+
+## Objective
+Enhance the referral dashboard with more detailed analytics to empower affiliates and motivate them to refer more users.
+
+## Explanation
+A basic referral dashboard shows the number of signups. A great affiliate dashboard provides actionable insights. By showing affiliates a list of the users they've referred and the revenue generated from them, you turn it from a simple counter into a tool they can use to track the effectiveness of their promotional efforts.
+
+## Instructions
+1. **Update the Backend Endpoint:**
+ * Modify the `/api/users/referrals` endpoint.
+ * In addition to the summary counts, the endpoint should also return an array of the users who have signed up with the referrer's code.
+ * The SQL query should join the `users` table with itself (`u1` and `u2`) to find users where `u2.referred_by_id` matches `u1.id`.
+ * For each referred user, return their `username` (or a masked version), their `created_at` (signup date), and the total revenue they have generated (which might require another join or a subquery on your sales table).
+
+2. **Enhance the Frontend HTML:**
+ * Open `profile.html` or your dedicated referral page.
+ * Below the summary stats, add a new section titled "Your Referrals".
+ * Add a table with columns for "Username", "Signup Date", and "Revenue Generated".
+
+3. **Update the Frontend JavaScript:**
+ * In the JavaScript file managing this page, when you fetch data from `/api/users/referrals`, look for the new array of referred users.
+ * Dynamically create and insert table rows (`<tr>`) for each referred user into the new table.
+ * Format the `signup_date` and `revenue_generated` for display.
+ * If there are no referred users, display a message like "You haven't referred any users yet. Share your code to get started!".
+
+## Backend SQL Query Example
+
+```sql
+// In /api/users/referrals, for the detailed list
+const referrals = await sql`
+ SELECT
+ u.username,
+ u.created_at AS signup_date,
+ (
+ SELECT COALESCE(SUM(price_usd), 0)
+ FROM royalty_ledger
+ WHERE author_user_id = ${userId}
+ AND source_user_id = u.id -- Assuming you link sales to the user who paid
+ ) AS revenue_generated
+ FROM users u
+ WHERE u.referred_by_id = ${userId}
+ ORDER BY u.created_at DESC;
+`;
+
+// Return this 'referrals' array along with the summary stats
+```
diff --git a/tasks/monetization-feature/19-frontend-purchased-skills-list.md b/tasks/monetization-feature/19-frontend-purchased-skills-list.md
new file mode 100644
index 000000000..db3f8b2ad
--- /dev/null
+++ b/tasks/monetization-feature/19-frontend-purchased-skills-list.md
@@ -0,0 +1,60 @@
+---
+status: not-started
+---
+
+# Prompt 19: User Profile - Purchased Skills List
+
+**Status:** Not Started
+
+## Objective
+Create a section on the user's profile page that lists all the skills they have purchased across all agents.
+
+## Explanation
+Users need a central place to see all the premium skills they've acquired. This acts as a digital inventory and reinforces the value they've received from the platform.
+
+## Instructions
+- [ ] **Identify the Profile Page:**
+ - [ ] Locate the main HTML and JavaScript files for the user profile page (e.g., `profile.html`).
+- [ ] **Add a New Section:**
+ - [ ] In the HTML, add a new section or tab for "Purchased Skills". It should contain a container element (e.g., `<div id="purchased-skills-list"></div>`).
+- [ ] **Fetch and Render Data:**
+ - [ ] In the profile page's JavaScript, on page load, make a `GET` request to the `/api/users/my-skills` endpoint.
+ - [ ] The endpoint from Prompt 7 returns a list of purchases with `agent_id` and `skill_name`. You will likely need to modify that endpoint or create a new one to also return more details, like the agent's name and an icon, to make the list user-friendly.
+ - [ ] A better endpoint might be `GET /api/users/my-skills-detailed`, which does the necessary `JOIN`s on the backend.
+ - [ ] Once you have the data, dynamically generate HTML to display each purchased skill, showing the skill name and the agent it belongs to. Link back to the agent's detail page.
+
+## Code Example (JavaScript for profile page)
+
+```javascript
+// On profile page load
+async function loadPurchasedSkills() {
+ const container = document.getElementById('purchased-skills-list');
+ container.innerHTML = 'Loading...';
+
+ try {
+ // Assumes a new or modified endpoint that returns detailed info
+ const response = await fetch('/api/users/my-skills-detailed');
+ const { skills } = await response.json(); // skills = [{ skill_name, agent_id, agent_name, agent_avatar_url }, ...]
+
+ if (skills.length === 0) {
+ container.innerHTML = "<p>You haven't purchased any skills yet.</p>";
+ return;
+ }
+
+ container.innerHTML = skills.map(skill => `
+ <div class="purchased-skill-item">
+ <img src="${skill.agent_avatar_url}" alt="${skill.agent_name}">
+ <div>
+ <span class="skill-name">${skill.skill_name}</span>
+ <span class="agent-name">from <a href="/marketplace/agent/${skill.agent_id}">${skill.agent_name}</a></span>
+ </div>
+ </div>
+ `).join('');
+
+ } catch (err) {
+ container.innerHTML = '<p>Could not load purchased skills.</p>';
+ }
+}
+
+loadPurchasedSkills();
+```
diff --git a/tasks/monetization-feature/20-fraud-detection-and-prevention.md b/tasks/monetization-feature/20-fraud-detection-and-prevention.md
new file mode 100644
index 000000000..663f7da9e
--- /dev/null
+++ b/tasks/monetization-feature/20-fraud-detection-and-prevention.md
@@ -0,0 +1,58 @@
+---
+status: not-started
+---
+
+# Prompt 20: Backend - Fraud Detection and Prevention
+
+## Objective
+Implement basic security measures to detect and prevent common forms of abuse in the referral and payment systems.
+
+## Explanation
+Monetization features can attract fraudulent activity. Common schemes include users referring themselves with multiple accounts to farm rewards, or attackers attempting to find vulnerabilities in payment endpoints. Implementing basic preventative measures is crucial for protecting the platform's integrity and finances.
+
+## Instructions
+1. **Rate Limiting on Critical Endpoints:**
+ * Ensure you have strict rate limiting on all monetization-related endpoints.
+ * Apply this to:
+ * `/api/auth/register`: Prevents rapid account creation.
+ * `/api/payments/solana-pay`: Prevents spamming transaction creation.
+ * `/api/payments/verify`: Prevents brute-force attacks.
+ * Use a library like `rate-limiter-flexible` and limit by IP address and/or user ID.
+
+2. **Prevent Self-Referrals:**
+ * In your referral commission logic (`Prompt 12`), add a check to ensure the purchaser's ID is not the same as their `referred_by_id`. While your signup logic should prevent this, a database constraint or an explicit check adds another layer of security.
+
+3. **Detect Multi-Accounting by IP:**
+ * When a user signs up (`/api/auth/register`), log their IP address.
+ * In the referral commission logic, before awarding a commission, check if the purchaser's signup IP address is the same as the referrer's signup IP address.
+ * If the IPs match, you can flag the transaction for manual review or automatically deny the commission. This helps prevent a user from "referring" themselves on the same device.
+
+4. **Database Constraints:**
+ * Add a `CHECK` constraint to your `users` table in the database to prevent a user's `id` from being the same as their `referred_by_id`.
+ * `ALTER TABLE users ADD CONSTRAINT no_self_referral CHECK (id <> referred_by_id);`
+
+## Code Snippet (IP Check in Commission Logic)
+
+```javascript
+// Inside the referral commission logic...
+const [purchaser] = await sql`
+ SELECT referred_by_id, signup_ip FROM users WHERE id = ${purchaserId}
+`;
+
+if (purchaser && purchaser.referred_by_id) {
+ const referrerId = purchaser.referred_by_id;
+
+ const [referrer] = await sql`
+ SELECT signup_ip FROM users WHERE id = ${referrerId}
+ `;
+
+ // Check if signup IPs are the same and not null
+ if (purchaser.signup_ip && referrer.signup_ip && purchaser.signup_ip === referrer.signup_ip) {
+ console.warn(`Potential self-referral detected for user ${purchaserId} and referrer ${referrerId}`);
+ // Optionally, you can decide to not award the commission here
+ return;
+ }
+
+ // ... proceed with awarding the commission
+}
+```
diff --git a/tasks/monetization-feature/20-protocol-add-ownership-context.md b/tasks/monetization-feature/20-protocol-add-ownership-context.md
new file mode 100644
index 000000000..8b43f3850
--- /dev/null
+++ b/tasks/monetization-feature/20-protocol-add-ownership-context.md
@@ -0,0 +1,54 @@
+---
+status: not-started
+---
+
+# Prompt 20: Update Agent Protocol
+
+**Status:** Not Started
+
+## Objective
+Enhance the agent protocol to include information about skill ownership, allowing the agent itself to be aware of monetization.
+
+## Explanation
+While skill usage is gated on the backend API, it can be beneficial for the agent's internal logic to know if a skill is premium and if the current user owns it. This could allow for more nuanced interactions, like the agent saying, "You'll need to purchase my 'Advanced Analysis' skill for that, which you can do from my profile."
+
+## Instructions
+- [ ] **Locate the agent protocol definition** or the place where the agent's context is built (likely in the main chat/action API endpoint).
+- [ ] **Add Ownership Data to Context:**
+ - [ ] When building the context to send to the agent (or the LLM), include a new key, `skill_ownership`.
+ - [ ] This object should map skill names to a boolean indicating if the current user owns them.
+ - [ ] This requires the data from the checks performed in Prompt 8.
+- [ ] **Update Agent's System Prompt:**
+ - [ ] Modify the agent's core system prompt to inform it about this new context.
+ - [ ] Instruct the agent on how to behave. For example: "If the user asks to perform a premium skill they do not own, you should politely inform them that the skill is for purchase and direct them to your agent profile page."
+
+## Code Example (Conceptual - Backend adding to context)
+
+```javascript
+// In the API endpoint that calls the LLM
+
+// ... after performing ownership checks from Prompt 8 ...
+const skillOwnership = {};
+for (const skill of agent.skills) {
+ const price = agent.skill_prices[skill.name];
+ if (price) {
+ const isOwned = await hasUserPurchased(user.id, agent.id, skill.name);
+ skillOwnership[skill.name] = { is_premium: true, is_owned: isOwned };
+ } else {
+ skillOwnership[skill.name] = { is_premium: false, is_owned: true }; // Free skills are "owned"
+ }
+}
+
+// Add this to the context/prompt sent to the LLM
+const llmContext = {
+ // ... other context
+ skill_ownership: skillOwnership,
+};
+
+const systemPrompt = `You are an agent. You have skills. Some may be premium.
+The following JSON shows your skills and if the user owns them:
+${JSON.stringify(llmContext.skill_ownership)}
+If a user tries to use a skill where is_premium is true but is_owned is false, you must decline and tell them it's a paid skill.`
+
+// ... call LLM with the new prompt and context ...
+```
diff --git a/tasks/monetization-feature/21-currency-conversion-support.md b/tasks/monetization-feature/21-currency-conversion-support.md
new file mode 100644
index 000000000..0480c31b0
--- /dev/null
+++ b/tasks/monetization-feature/21-currency-conversion-support.md
@@ -0,0 +1,64 @@
+---
+status: not-started
+---
+
+# Prompt 21: Backend & Frontend - Multi-Currency Support
+
+## Objective
+Enhance the platform to support pricing in multiple fiat currencies and allow users to see prices in their local currency.
+
+## Explanation
+To operate globally, you cannot assume all transactions will be in USD. This task involves integrating a real-time currency conversion service to allow creators to price their skills in their preferred currency and to display an estimated local currency price to potential buyers, improving the user experience for a global audience.
+
+## Instructions
+### Backend
+1. **Integrate a Currency Conversion API:**
+ * Sign up for a service like Open Exchange Rates or ExchangeRate-API.
+ * Create a helper function to fetch and cache the latest exchange rates to avoid hitting the API on every request.
+
+2. **Update Pricing Table:**
+ * Modify the `agent_skill_prices` table. Instead of a single `amount` and `currency_mint` (which is crypto-specific), have `price_amount` and `price_currency` (e.g., 10.00, 'USD'). The `currency_mint` for crypto can remain.
+
+3. **Modify Earnings/Royalty Table:**
+ * Your `royalty_ledger` should store both the original `price_amount` and `price_currency`, as well as a calculated `amount_usd` for standardized reporting.
+
+4. **Update Payment Endpoints:**
+ * When creating a payment (`/api/payments/solana-pay`), you will need to convert the skill's price (e.g., 10 EUR) into the required on-chain currency amount (e.g., USDC lamports) using the latest exchange rate.
+
+### Frontend
+1. **Allow Creators to Set Price Currency:**
+ * In the UI where creators set a skill's price, add a dropdown to select the currency (USD, EUR, JPY, etc.).
+
+2. **Display Localized Prices to Buyers:**
+ * On the marketplace detail page, the API should still send the base price and currency (e.g., 10 EUR).
+ * The frontend can then either:
+ * a) Call a new backend endpoint to get the user's estimated local price.
+ * b) Use a library like `Intl.NumberFormat` in JavaScript, combined with rates fetched from the backend, to display the local price estimate. For example, showing "€10.00 (approx. $10.85)".
+
+## Currency Helper Example
+
+```javascript
+// /api/_lib/currency.js
+let ratesCache = null;
+let cacheTime = 0;
+
+export async function getRates() {
+ // Cache for 1 hour to stay within API limits
+ if (ratesCache && Date.now() - cacheTime < 3600 * 1000) {
+ return ratesCache;
+ }
+
+ const response = await fetch(`https://api.exchangerate-api.com/v4/latest/USD`);
+ ratesCache = await response.json();
+ cacheTime = Date.now();
+ return ratesCache.rates;
+}
+
+export async function convertToUsd(amount, fromCurrency) {
+ if (fromCurrency === 'USD') return amount;
+ const rates = await getRates();
+ const rate = rates[fromCurrency];
+ if (!rate) throw new Error(`Unknown currency: ${fromCurrency}`);
+ return amount / rate;
+}
+```
diff --git a/tasks/monetization-feature/21-fullstack-multi-currency-support.md b/tasks/monetization-feature/21-fullstack-multi-currency-support.md
new file mode 100644
index 000000000..1a1309309
--- /dev/null
+++ b/tasks/monetization-feature/21-fullstack-multi-currency-support.md
@@ -0,0 +1,43 @@
+---
+status: not-started
+---
+
+# Prompt 21: Multi-Currency Support
+
+**Status:** Not Started
+
+## Objective
+Extend the skill pricing and payment system to support multiple SPL tokens (e.g., BONK, RENDER) in addition to USDC.
+
+## Explanation
+To maximize flexibility for users and creators, the platform should not be limited to a single currency. This requires changes on both the backend (to store different currency mints) and the frontend (to display the correct currency symbol and handle different decimals).
+
+## Instructions
+- [ ] **Backend:**
+ - [ ] The `agent_skill_prices` and `skill_purchases` tables already have a `currency_mint` column, which is good.
+ - [ ] When creating a Solana Pay transaction, ensure you are using the correct `splToken` mint address from the skill's price information.
+- [ ] **Frontend - Monetization Tab:**
+ - [ ] Update the currency `<select>` dropdown in the agent editor to include options for other popular SPL tokens (USDC, BONK, etc.). The `value` for each option should be the token's mint address.
+- [ ] **Frontend - Marketplace:**
+ - [ ] When displaying the price and the "Buy" button, fetch the token's metadata (symbol, decimals) from a source like the Solana Token List or a simple hardcoded map.
+ - [ ] Use the correct number of decimals when converting the `amount` from lamports to a human-readable format (e.g., BONK has 5 decimals, USDC has 6).
+ - [ ] Display the correct currency symbol (e.g., "$BONK", "$RNDR").
+
+## Code Example (Frontend Price Display)
+
+```javascript
+// A simple map of known tokens. In a real app, this might come from an API.
+const TOKEN_MAP = {
+ 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T': { symbol: 'USDC', decimals: 6 },
+ 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263': { symbol: 'BONK', decimals: 5 },
+};
+
+// In the marketplace rendering logic...
+const price = skillPrices[name]; // e.g., { amount: 500000, currency_mint: 'Dez...' }
+if (price) {
+ const tokenInfo = TOKEN_MAP[price.currency_mint] || { symbol: 'Unknown', decimals: 0 };
+ const displayAmount = price.amount / Math.pow(10, tokenInfo.decimals);
+ const badge = `<span class="price-badge">${displayAmount.toFixed(2)} ${tokenInfo.symbol}</span>`;
+ // ...
+}
+```
diff --git a/tasks/monetization-feature/22-frontend-payment-error-handling.md b/tasks/monetization-feature/22-frontend-payment-error-handling.md
new file mode 100644
index 000000000..86902fdf6
--- /dev/null
+++ b/tasks/monetization-feature/22-frontend-payment-error-handling.md
@@ -0,0 +1,58 @@
+---
+status: not-started
+---
+
+# Prompt 22: Frontend Payment Error Handling
+
+**Status:** Not Started
+
+## Objective
+Improve the user experience by providing clear feedback in the purchase modal when a payment fails or times out.
+
+## Explanation
+Things can go wrong during the payment process. The user might close the modal, their transaction might fail on-chain, or our backend confirmation might time out. The UI needs to handle these cases gracefully instead of leaving the user in a loading state.
+
+## Instructions
+- [ ] **Implement a Timeout:**
+ - [ ] In the polling logic from Prompt 17, add a timeout mechanism. For example, if the purchase is not confirmed after 2 minutes, stop polling.
+- [ ] **Handle API Errors:**
+ - [ ] Wrap all `fetch` calls in the purchase flow in `try...catch` blocks.
+ - [ ] If an API call fails (e.g., to create the transaction or check the status), display a clear error message in the modal.
+- [ ] **Display Specific Messages:**
+ - [ ] Provide different messages for different states:
+ - "Transaction timed out. Please check your wallet and try again."
+ - "Could not create transaction. Please refresh the page."
+ - "Payment failed. The transaction was not successful on the network."
+- [ ] **Add a "Try Again" Button:**
+ - [ ] When an error occurs, it's helpful to show a "Try Again" button that restarts the purchase process for that skill.
+
+## Code Example (Frontend Polling with Timeout)
+
+```javascript
+const reference = new URL(solanaPayUrl).searchParams.get('reference');
+let pollCount = 0;
+const maxPolls = 60; // 2 minutes if polling every 2 seconds
+
+const pollInterval = setInterval(async () => {
+ pollCount++;
+ if (pollCount > maxPolls) {
+ clearInterval(pollInterval);
+ showErrorInModal("Transaction timed out. Please check your wallet.");
+ return;
+ }
+
+ try {
+ const res = await fetch(`/api/payments/check-status?reference=${reference}`);
+ if (!res.ok) throw new Error('Status check failed');
+ const { status } = await res.json();
+
+ if (status === 'confirmed') {
+ clearInterval(pollInterval);
+ handlePurchaseSuccess(...);
+ }
+ } catch (err) {
+ clearInterval(pollInterval);
+ showErrorInModal("An error occurred. Please try again.");
+ }
+}, 2000);
+```
diff --git a/tasks/monetization-feature/22-tax-compliance-forms.md b/tasks/monetization-feature/22-tax-compliance-forms.md
new file mode 100644
index 000000000..8f4c68110
--- /dev/null
+++ b/tasks/monetization-feature/22-tax-compliance-forms.md
@@ -0,0 +1,45 @@
+---
+status: not-started
+---
+
+# Prompt 22: Backend & Frontend - Tax Compliance
+
+## Objective
+Integrate a system for collecting necessary tax information (e.g., W-9 for US creators) to comply with financial regulations.
+
+## Explanation
+When you pay creators, you may be required by law to report their earnings to tax authorities. This involves collecting tax identification information from them. This process must be secure and user-friendly to ensure compliance without creating excessive friction for your creators.
+
+**Disclaimer:** This is a complex area. Always consult with a tax professional and legal counsel. The following is a technical guide, not legal advice.
+
+## Instructions
+1. **Choose a Compliance Partner (Recommended):**
+ * Services like Stripe Identity or Persona can securely collect and verify tax forms. This is often better than building it yourself.
+ * If using Stripe, you can require Identity verification for connected accounts before enabling payouts.
+
+2. **Database Fields:**
+ * In your `users` table, add fields to track tax status, such as `tax_form_status` (`missing`, `pending`, `verified`) and `tax_form_type` (`w9`, `w8ben`). Do NOT store sensitive information like Social Security Numbers directly in your database unless it is encrypted at the field level.
+
+3. **Create a Tax Center UI:**
+ * In the creator's "Earnings" or "Account" section, add a "Tax Information" page.
+ * This page should clearly explain *why* this information is needed.
+ * Based on the user's country (if collected), prompt them to complete the correct form (e.g., W-9 for the US, W-8BEN for non-US).
+ * Embed the UI of your chosen compliance partner (e.g., the Stripe Identity modal) to handle the secure collection of data.
+
+4. **Gating Payouts:**
+ * In your admin payout system (`Prompt 9`), before processing a payout, your backend must check the creator's `tax_form_status`.
+ * Do not allow payouts to be processed for any creator whose status is not `verified`, especially if their earnings are over the legal reporting threshold (e.g., $600 in the US).
+
+5. **Webhook for Verification Status:**
+ * Your compliance partner will provide webhooks.
+ * Implement a webhook handler to listen for events like `identity.verification_session.verified`.
+ * When you receive this event, update the `tax_form_status` for the corresponding user in your database.
+
+## UI Flow Example
+
+1. User goes to the "Earnings" page.
+2. If their earnings are > $500 and their `tax_form_status` is `missing`, a prominent banner appears: "Action Required: Please submit your tax information to receive payouts."
+3. The banner links to the "Tax Information" page.
+4. User clicks a "Begin Verification" button, which launches the Stripe Identity flow.
+5. User completes the form in the secure modal.
+6. Stripe sends a webhook to your backend, and the user's status is updated to `verified`. The banner on the earnings page disappears.
diff --git a/tasks/monetization-feature/23-creator-analytics-dashboard.md b/tasks/monetization-feature/23-creator-analytics-dashboard.md
new file mode 100644
index 000000000..b3d6e8fe2
--- /dev/null
+++ b/tasks/monetization-feature/23-creator-analytics-dashboard.md
@@ -0,0 +1,59 @@
+---
+status: not-started
+---
+
+# Prompt 23: Frontend - Creator Analytics Dashboard
+
+## Objective
+Provide creators with a dedicated analytics dashboard to help them understand their sales performance and identify trends.
+
+## Explanation
+Beyond a simple list of sales, a true analytics dashboard empowers creators with visual data. Charts and key metrics can help them understand which of their skills are most popular, what times they see the most sales, and their overall growth trajectory. This helps them make better decisions and ultimately leads to more high-quality content on your platform.
+
+## Instructions
+1. **Choose a Charting Library:**
+ * Select a JavaScript charting library to easily create interactive charts. Good options include Chart.js, D3.js, or ECharts.
+ * Install your chosen library: `npm install chart.js`.
+
+2. **Update the Backend Earnings Endpoint:**
+ * Modify `/api/users/earnings`.
+ * In addition to the transaction list, the API should return data pre-aggregated for charts. For example, a time-series of sales per day for the last 30 days.
+ * `SELECT DATE_TRUNC('day', created_at) AS day, SUM(price_usd) AS daily_revenue FROM royalty_ledger WHERE ... GROUP BY day ORDER BY day;`
+ * Also, add an aggregation for sales by skill:
+ * `SELECT skill_name, COUNT(*) as sales_count, SUM(price_usd) as total_revenue FROM ... GROUP BY skill_name;`
+
+3. **Enhance the `earnings.html` UI:**
+ * Add `<canvas>` elements to your earnings page where the charts will be rendered.
+ * Create sections for "Sales Over Time" and "Top Performing Skills".
+
+4. **Implement Frontend Charting Logic:**
+ * In `src/earnings.js`, after fetching the data from the API:
+ * Initialize a new chart using the canvas element for "Sales Over Time". Use the time-series data from the API to populate the chart's labels (dates) and data (revenue).
+ * Create a second chart (e.g., a bar or pie chart) for "Top Performing Skills". Use the skill aggregation data to show which skills are generating the most sales or revenue.
+
+## Chart.js Example (`src/earnings.js`)
+
+```javascript
+import Chart from 'chart.js/auto';
+
+// After fetching the API data which includes a 'sales_over_time' array
+const data = await response.json();
+
+const ctx = document.getElementById('sales-over-time-chart').getContext('2d');
+new Chart(ctx, {
+ type: 'line',
+ data: {
+ labels: data.sales_over_time.map(d => new Date(d.day).toLocaleDateString()),
+ datasets: [{
+ label: 'Daily Revenue (USD)',
+ data: data.sales_over_time.map(d => d.daily_revenue),
+ borderColor: 'rgba(52, 211, 153, 1)',
+ tension: 0.1,
+ fill: true,
+ }]
+ },
+ options: {
+ // ... chart options
+ }
+});
+```
diff --git a/tasks/monetization-feature/23-fullstack-notifications.md b/tasks/monetization-feature/23-fullstack-notifications.md
new file mode 100644
index 000000000..7f9051129
--- /dev/null
+++ b/tasks/monetization-feature/23-fullstack-notifications.md
@@ -0,0 +1,41 @@
+---
+status: not-started
+---
+
+# Prompt 23: User Notifications
+
+**Status:** Not Started
+
+## Objective
+Implement a notification system to inform users about successful purchases and to inform creators about sales.
+
+## Explanation
+Notifications are a key part of a good user experience. A user should get a clear confirmation that their purchase was successful, and a creator should be excited to learn they've made a sale.
+
+## Instructions
+- [ ] **Create a `notifications` Database Table:**
+ - [ ] The table should store `user_id`, a `message`, a `read` status (boolean), a `link`, and a `created_at` timestamp.
+- [ ] **Backend - Generate Notifications:**
+ - [ ] In the payment confirmation endpoint (from Prompt 6), after successfully recording a purchase in `skill_purchases`, insert two new rows into the `notifications` table:
+ 1. One for the **buyer**, with a message like "You successfully purchased the skill 'X' for agent 'Y'." The link should go to the agent's page.
+ 2. One for the **creator** (the agent's `user_id`), with a message like "You made a sale! User 'Z' bought your skill 'X'." The link could go to their earnings dashboard.
+- [ ] **Frontend - Display Notifications:**
+ - [ ] Create a new API endpoint `GET /api/notifications` that fetches the user's unread notifications.
+ - [ ] In the main application layout, add a notification bell icon.
+ - [ ] When the page loads, call the new endpoint. If there are unread notifications, show a badge on the bell icon.
+ - [ ] When the user clicks the icon, display the notifications in a dropdown menu.
+
+## Code Example (Backend Notification Insert)
+
+```sql
+-- After inserting into skill_purchases...
+-- The buyer is `user.id`, the creator is `agent.user_id`
+
+-- Notification for the buyer
+INSERT INTO notifications (user_id, message, link)
+VALUES (${buyerId}, 'You successfully purchased skill ${skillName}.', '/marketplace/agent/${agentId}');
+
+-- Notification for the creator
+INSERT INTO notifications (user_id, message, link)
+VALUES (${creatorId}, 'You sold your skill ${skillName}!', '/agent/edit/${agentId}/monetization');
+```
diff --git a/tasks/monetization-feature/24-backend-analytics.md b/tasks/monetization-feature/24-backend-analytics.md
new file mode 100644
index 000000000..a064dc620
--- /dev/null
+++ b/tasks/monetization-feature/24-backend-analytics.md
@@ -0,0 +1,48 @@
+---
+status: not-started
+---
+
+# Prompt 24: Backend Analytics for Purchases
+
+**Status:** Not Started
+
+## Objective
+Create a basic system for tracking skill purchase analytics to understand which skills and agents are most popular.
+
+## Explanation
+To make informed business decisions, the platform needs data. Tracking sales events allows us to build dashboards showing revenue over time, top-selling skills, and top-earning creators.
+
+## Instructions
+- [ ] **Create an `analytics_events` Table:**
+ - [ ] This table can be very generic to be used for other analytics later.
+ - [ ] Columns: `event_name` (e.g., 'skill_purchased'), `properties` (a JSONB column to store details), `created_at`.
+- [ ] **Log Events on the Backend:**
+ - [ ] In the payment confirmation endpoint (from Prompt 6), after a purchase is fully verified and recorded, insert an event into the new table.
+ - [ ] The `event_name` should be `'skill_purchased'`.
+ - [ ] The `properties` JSON object should contain rich data about the event: `agent_id`, `skill_name`, `user_id`, `amount`, `currency_mint`, `creator_id`, etc.
+- [ ] **Create a Basic Analytics API Endpoint:**
+ - [ ] Create a new admin-only endpoint, e.g., `GET /api/admin/analytics/sales`.
+ - [ ] This endpoint will query the `analytics_events` table.
+ - [ ] It could perform aggregations, for example, to calculate total revenue per day or count the sales for each skill.
+- [ ] **(Optional) Frontend Dashboard:**
+ - [ ] Create a simple, admin-only page to display this data in charts and tables.
+
+## Code Example (Backend Logging)
+
+```javascript
+// In the payment confirmation logic...
+
+const eventProperties = {
+ agentId: agent.id,
+ creatorId: agent.user_id,
+ skillName: skill.name,
+ buyerId: user.id,
+ amount: price.amount,
+ currencyMint: price.currency_mint,
+};
+
+await sql`
+ INSERT INTO analytics_events (event_name, properties)
+ VALUES ('skill_purchased', ${JSON.stringify(eventProperties)});
+`;
+```
diff --git a/tasks/monetization-feature/24-subscription-management-ui.md b/tasks/monetization-feature/24-subscription-management-ui.md
new file mode 100644
index 000000000..916de9016
--- /dev/null
+++ b/tasks/monetization-feature/24-subscription-management-ui.md
@@ -0,0 +1,65 @@
+---
+status: not-started
+---
+
+# Prompt 24: Frontend - Subscription Management UI
+
+## Objective
+Create a user interface that allows developers to manage their API subscriptions, including upgrading, downgrading, and canceling plans.
+
+## Explanation
+A self-service subscription management portal is essential for a smooth developer experience and for reducing customer support load. This UI will typically link out to a secure, pre-built portal hosted by your payment provider (like Stripe), where users can manage their payment methods and subscription status directly.
+
+## Instructions
+1. **Backend - Create Stripe Customer Portal Endpoint:**
+ * Create a new backend API endpoint, e.g., `/api/billing/create-portal-session`.
+ * This endpoint will use the Stripe Node.js SDK.
+ * It should authenticate the user to get their `user_id`.
+ * It will look up the user's `stripe_customer_id` from your `subscriptions` or `users` table.
+ * It then calls `stripe.billingPortal.sessions.create()` to generate a unique, single-use URL for that customer's portal.
+ * The endpoint returns this URL to the frontend.
+
+2. **Frontend - Add a "Manage Subscription" Page/Section:**
+ * On your `api-keys.html` page, or a new `billing.html` page, create a new section called "Subscription Status".
+ * Display the user's current plan name (e.g., "Developer Plan") and the status (e.g., "Active"). You will get this from your own database via an endpoint.
+ * Add a prominent button labeled "Manage Billing & Subscription".
+
+3. **Frontend - Implement the Button Logic:**
+ * In the JavaScript for this page, add a click handler to the "Manage" button.
+ * When clicked, it should make a `POST` request to your new `/api/billing/create-portal-session` endpoint.
+ * The API will respond with a JSON object containing the portal URL.
+ * The frontend should then redirect the user to this URL: `window.location.href = data.url;`.
+
+4. **Configure the Stripe Customer Portal:**
+ * In your Stripe dashboard, go to the Customer Portal settings.
+ * Configure which actions you want to allow users to perform (e.g., update payment methods, view invoice history, change plans, cancel subscriptions).
+ * Set the redirect URL to bring users back to your application after they are done.
+
+## Backend Endpoint Example
+
+```javascript
+// POST /api/billing/create-portal-session
+const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
+
+export default wrap(async (req, res) => {
+ const user = await getSessionUser(req);
+ if (!user) return error(res, 401);
+
+ // 1. Fetch the user's Stripe Customer ID from your database
+ const [sub] = await sql`
+ SELECT stripe_customer_id FROM subscriptions WHERE user_id = ${user.id} AND status = 'active'
+ `;
+ if (!sub || !sub.stripe_customer_id) {
+ return error(res, 404, 'not_found', 'No active subscription found.');
+ }
+
+ // 2. Create the portal session
+ const portalSession = await stripe.billingPortal.sessions.create({
+ customer: sub.stripe_customer_id,
+ return_url: `${process.env.APP_ORIGIN}/api-keys`, // URL to return to
+ });
+
+ // 3. Return the URL for redirect
+ return json(res, 200, { url: portalSession.url });
+});
+```
diff --git a/tasks/monetization-feature/25-backend-api-security.md b/tasks/monetization-feature/25-backend-api-security.md
new file mode 100644
index 000000000..b6a179550
--- /dev/null
+++ b/tasks/monetization-feature/25-backend-api-security.md
@@ -0,0 +1,47 @@
+---
+status: not-started
+---
+
+# Prompt 25: Secure Pricing and Payment APIs
+
+**Status:** Not Started
+
+## Objective
+Perform a security review and add necessary checks to all new monetization-related API endpoints.
+
+## Explanation
+Handling payments requires a high level of security. We must ensure that only authorized users can perform sensitive actions. This prompt is a check to ensure all new endpoints have robust security measures.
+
+## Instructions
+- [ ] **Review `POST /api/agents/prices` (Prompt 3):**
+ - [ ] **Check:** Does it strictly verify that the logged-in user is the owner of the `agent_id` being modified? A user should never be able to set the price for another user's agent.
+- [ ] **Review Solana Pay Endpoints (Prompt 5 & 6):**
+ - [ ] **Check:** When confirming a transaction, does the backend re-fetch the price from the database itself? The price should *not* be trusted from the client request, as it could be manipulated. The backend must be the source of truth for the expected amount.
+ - [ ] **Check:** Is the agent creator's wallet address also fetched securely from the database on the backend, not passed from the client?
+- [ ] **Review Gating Logic (Prompt 8):**
+ - [ ] **Check:** Is the ownership check robust? Does it correctly handle cases where a user is not logged in?
+- [ ] **Review Creator Endpoints (Prompt 14):**
+ - [ ] **Check:** Do the `/api/earnings/*` endpoints correctly scope all queries to the authenticated `user_id`? A user should never be able to see another creator's earnings.
+- [ ] **Add Rate Limiting:**
+ - [ ] Apply rate limiting to sensitive endpoints like transaction creation and confirmation to prevent abuse.
+
+## Code Example (Security Check in Confirmation Endpoint)
+
+```javascript
+// In the confirmation endpoint, DO NOT trust client-side price.
+
+const { signature, agentId, skillName } = await readJson(req);
+
+// ALWAYS re-fetch the price from the DB as the source of truth.
+const [priceInfo] = await sql`
+ SELECT amount, currency_mint
+ FROM agent_skill_prices
+ WHERE agent_id = ${agentId} AND skill_name = ${skillName}`;
+
+if (!priceInfo) {
+ return error(res, 404, 'Skill or price not found.');
+}
+
+// Now, validate the on-chain transaction against THIS `priceInfo`.
+// ...
+```
diff --git a/tasks/monetization-feature/25-documentation-for-monetization-features.md b/tasks/monetization-feature/25-documentation-for-monetization-features.md
new file mode 100644
index 000000000..50a2186bf
--- /dev/null
+++ b/tasks/monetization-feature/25-documentation-for-monetization-features.md
@@ -0,0 +1,43 @@
+---
+status: not-started
+---
+
+# Prompt 25: Content - Documentation for Monetization Features
+
+## Objective
+Create clear, comprehensive documentation for all new monetization features to help users, creators, and developers understand and use them effectively.
+
+## Explanation
+Good documentation is a product feature in itself. For monetization, it's especially critical. Creators need to understand how to price their work and how they get paid. Developers need to understand how your API billing works. Clear documentation reduces confusion, minimizes support tickets, and encourages adoption of your paid features.
+
+## Instructions
+1. **Structure the Documentation:**
+ * In your existing `/docs` directory or on your documentation site, create a new top-level section called "Monetization".
+ * Under this section, plan out the individual articles you will need.
+
+2. **Write Content for Creators:**
+ * **Article: "Selling Your Skills"**
+ * Explain how to set a price for a skill.
+ * Discuss the fee structure (what percentage the platform takes).
+ * Explain the payout process, schedule, and requirements (e.g., tax forms).
+ * **Article: "Referral Program Guide"**
+ * Explain how to find the referral code.
+ * Detail the commission rate and the terms (e.g., commission on first purchase only).
+ * Provide tips on how to effectively share the code.
+
+3. **Write Content for Developers (API Consumers):**
+ * **Article: "API Subscription Plans"**
+ * Detail the different subscription tiers.
+ * Clearly list the usage limits (e.g., API calls per month) and features for each plan.
+ * Explain what happens when a user goes over their limit.
+ * **Article: "Understanding API Billing"**
+ * Explain how API calls are counted.
+ * Describe the monthly billing cycle.
+ * Provide instructions on how to update payment methods via the billing portal.
+ * **Article: "API Authentication"**
+ * Reiterate how to generate and use API keys securely.
+
+4. **Review and Publish:**
+ * Have someone unfamiliar with the features read the documentation to check for clarity.
+ * Ensure all links are correct.
+ * Publish the documentation and link to it from relevant places in your application UI (e.g., a "Read the Docs" link on the API keys page).
diff --git a/tasks/monetization-feature/README.md b/tasks/monetization-feature/README.md
index 4915adfcc..7c32d48db 100644
--- a/tasks/monetization-feature/README.md
+++ b/tasks/monetization-feature/README.md
@@ -10,8 +10,8 @@ The status of each task is tracked in its frontmatter (`status: not-started | in
|----|--------------------------------------------|-------------|
| 01 | Display Priced Skills in Marketplace | `completed` |
| 02 | Create `agent_skill_prices` Table Schema | `completed` |
-| 03 | Creator UI for Skill Pricing | `not-started` |
-| 04 | Backend for Saving Skill Prices | `not-started` |
+| 03 | Creator UI for Skill Pricing | `completed` |
+| 04 | Backend for Saving Skill Prices | `completed` |
| 05 | Add "Purchase" Button to Marketplace UI | `not-started` |
| 06 | Implement User Wallet Connection | `not-started` |
| 07 | Frontend Transaction Logic for Purchases | `not-started` |
diff --git a/vercel.json b/vercel.json
index 6cb05c1bb..f151b7a15 100644
--- a/vercel.json
+++ b/vercel.json
@@ -84,6 +84,10 @@
"src": "/api/agents/([^/]+)/skills-pricing",
"dest": "/api/agents/[id]/skills-pricing?id=$1"
},
+ {
+ "src": "/api/agents/([^/]+)/skills/price",
+ "dest": "/api/agent-skill-price.js?agentId=$1"
+ },
{
"src": "/api/newsletter/subscribe",
"dest": "/api/newsletter-subscribe"