Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: Add database migrations and API endpoints for skill purchases and monetization features
nirholas5a65533dc475
diff --git a/api/_lib/migrations/002_create_agent_skill_prices.sql b/api/_lib/migrations/002_create_agent_skill_prices.sqlnew file mode 100644index 000000000..a847710cb--- /dev/null+++ b/api/_lib/migrations/002_create_agent_skill_prices.sql@@ -0,0 +1,10 @@+create table agent_skill_prices (+ id serial primary key,+ agent_id integer not null references agents(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(),+ unique (agent_id, skill_name)+);diff --git a/api/agents/[id]/skill-prices.js b/api/agents/[id]/skill-prices.jsnew file mode 100644index 000000000..ef563d470--- /dev/null+++ b/api/agents/[id]/skill-prices.js@@ -0,0 +1,71 @@+import { sql } from '../../_lib/db.js';+import { getSessionUser } from '../../_lib/auth.js';+import { error, json, wrap } from '../../_lib/http.js';+import { z } from 'zod';++const priceSchema = z.object({+ skill_id: z.string().min(1),+ amount: z.number().int().positive(),+ currency_mint: z.string().min(32), // Solana mint address length+});++const updatePriceSchema = z.object({+ skill_id: z.string().min(1),+ amount: z.number().int().positive(),+});++const deletePriceSchema = z.object({+ skill_id: z.string().min(1),+});++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ const agentId = req.query.id;+ const [agent] = await sql`+ SELECT user_id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL+ `;++ if (!agent || agent.user_id !== user.id) {+ return error(res, 403, 'forbidden', 'You do not own this agent.');+ }++ if (req.method === 'POST') {+ const body = priceSchema.parse(await readJson(req));+ await sql`+ INSERT INTO agent_skill_prices (agent_id, skill_id, creator_id, amount, currency_mint)+ VALUES (${agentId}, ${body.skill_id}, ${user.id}, ${body.amount}, ${body.currency_mint})+ ON CONFLICT (agent_id, skill_id) WHERE deleted_at IS NULL+ DO UPDATE SET+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ creator_id = EXCLUDED.creator_id,+ updated_at = NOW(),+ deleted_at = NULL+ `;+ return json(res, { success: true });+ }++ if (req.method === 'PUT') {+ const body = updatePriceSchema.parse(await readJson(req));+ await sql`+ UPDATE agent_skill_prices+ SET amount = ${body.amount}, updated_at = NOW()+ WHERE agent_id = ${agentId} AND skill_id = ${body.skill_id} AND deleted_at IS NULL+ `;+ return json(res, { success: true });+ }++ if (req.method === 'DELETE') {+ const body = deletePriceSchema.parse(await readJson(req));+ await sql`+ UPDATE agent_skill_prices+ SET deleted_at = NOW()+ WHERE agent_id = ${agentId} AND skill_id = ${body.skill_id}+ `;+ return json(res, { success: true });+ }++ return error(res, 405, 'method_not_allowed');+});diff --git a/api/marketplace.js b/api/marketplace.jsindex 206153664..4f1a48142 100644--- a/api/marketplace.js+++ b/api/marketplace.js@@ -13,7 +13,11 @@ export default (req, res) => {"avatar": "✍️","prompt": "You are an AI assistant specialized in creative writing. Help users brainstorm ideas, write stories, and craft compelling content.","greeting": "Hello! I'm here to help you write something amazing. What's on your mind?",- "versions": [{ "version": "1.0", "date": "2024-05-15", "notes": "Initial release." }]+ "versions": [{ "version": "1.0", "date": "2024-05-15", "notes": "Initial release." }],+ "skills": ["generate-poem", "summarize-text"],+ "skill_prices": {+ "generate-poem": { "amount": 1000000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u" }+ }},{"id": "2",@@ -28,7 +32,12 @@ export default (req, res) => {"avatar": "💻","prompt": "You are a friendly and helpful AI pair programmer. Assist users with their coding tasks, from simple scripts to complex applications.","greeting": "Hey there! I'm ready to code. What are we working on today?",- "versions": [{ "version": "1.0", "date": "2024-05-14", "notes": "Initial release." }]+ "versions": [{ "version": "1.0", "date": "2024-05-14", "notes": "Initial release." }],+ "skills": ["explain-code", "refactor-code", "generate-tests"],+ "skill_prices": {+ "refactor-code": { "amount": 2500000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u" },+ "generate-tests": { "amount": 5000000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u" }+ }},{"id": "3",@@ -43,7 +52,9 @@ export default (req, res) => {"avatar": "🔗","prompt": "You are an expert on the Solana blockchain. Provide accurate and up-to-date information about Solana, its ecosystem, and its technology.","greeting": "Welcome! I'm here to answer all your questions about the Solana blockchain.",- "versions": [{ "version": "1.0", "date": "2024-05-12", "notes": "Initial release." }]+ "versions": [{ "version": "1.0", "date": "2024-05-12", "notes": "Initial release." }],+ "skills": ["get-token-price", "check-transaction-status"],+ "skill_prices": {}}];diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex c9a032260..1ced5f547 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -340,28 +340,7 @@ async function handleDetail(req, res, id) {return json(res,200,- { data: { agent: { ...toDetail(row, skill_prices), bookmarked } } },- { 'cache-control': 'public, max-age=15' },- );- const [auth] = await Promise.all([- resolveAuth(req).catch(() => null),- ]);-- let bookmarked = false;- if (auth) {- const [b] =- await sql`SELECT 1 AS x FROM agent_bookmarks WHERE user_id = ${auth.userId} AND agent_id = ${id}`;- bookmarked = !!b;- }-- const skill_prices = Object.fromEntries(- priceRows.map((p) => [p.skill, { amount: p.amount, currency_mint: p.currency_mint, chain: p.chain }]),- );-- return json(- res,- 200,- { data: { agent: { ...toDetail(row), skill_prices }, bookmarked } },+ { data: { agent: { ...toDetail(row), skill_prices, bookmarked } } },{ 'cache-control': 'public, max-age=15' },);}diff --git a/docs/monetization/02-ui-skill-pricing.md b/docs/monetization/02-ui-skill-pricing.mdnew file mode 100644index 000000000..3b7bbd1c3--- /dev/null+++ b/docs/monetization/02-ui-skill-pricing.md@@ -0,0 +1,68 @@+---+status: not-started+---++# Prompt 2: UI for Setting Skill Prices++## Objective+Create a UI in the agent edit page (`agent-edit.html`) for creators to set prices for their skills.++## Explanation+To sell skills, creators need an intuitive interface to manage pricing. This will involve adding a new section to the agent editor where they can input a price and select a currency for each skill associated with their agent. This prompt focuses only on creating the frontend UI components.++## Instructions+1. **Identify the Agent Editor:** Locate the files responsible for the agent creation/editing page (e.g., `agent-edit.html` and its corresponding JavaScript).+2. **Add a New UI Section:** In the HTML, add a new section titled "Skill Pricing". This section should contain a list or form where skills will be dynamically rendered.+3. **Dynamically Render Skills:** In the page's JavaScript, fetch the agent's currently defined skills. For each skill, render a row in the "Skill Pricing" section.+4. **Add Input Fields:** Each skill row should include:+ * The skill name (as static text).+ * A number input field for the price.+ * A dropdown (`<select>`) to choose the currency. Initially, this can be hardcoded to just "USDC".+5. **Add a Save Button:** Include a "Save Prices" button at the bottom of the section. Its functionality will be implemented in a subsequent step.+6. **Load Existing Prices:** The script should also fetch and display any previously saved prices for the skills in the input fields.++## Code Example (HTML in `agent-edit.html`)++```html+<!-- Inside the main form of the agent editor -->+<div class="form-section">+ <h2>Skill Pricing</h2>+ <p class="description">Set prices for individual skills. Leave blank for free skills.</p>+ <div id="skill-pricing-list">+ <!-- Skills will be rendered here by JavaScript -->+ </div>+ <button type="button" id="save-prices-btn" class="cta-button">Save Prices</button>+</div>+```++## Code Example (JavaScript logic)++```javascript+// Function to render the pricing UI+function renderSkillPricer(agent) {+ const skills = agent.skills || [];+ const prices = agent.skill_prices || {};+ const container = document.getElementById('skill-pricing-list');++ if (skills.length === 0) {+ container.innerHTML = '<p>Add skills to this agent to set prices.</p>';+ return;+ }++ container.innerHTML = skills.map(skill => {+ const skillName = skill.name || skill;+ const price = prices[skillName];+ const amount = price ? (price.amount / 1e6).toFixed(2) : '';+ // Note: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3' is the mint for USDC on Solana Mainnet+ return `+ <div class="skill-price-row">+ <span class="skill-name">${escapeHtml(skillName)}</span>+ <input type="number" class="price-input" data-skill="${escapeHtml(skillName)}" value="${amount}" placeholder="0.00">+ <select class="currency-select" data-skill-currency="${escapeHtml(skillName)}">+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7uP3">USDC</option>+ </select>+ </div>+ `;+ }).join('');+}+```diff --git a/docs/monetization/03-save-skill-prices.md b/docs/monetization/03-save-skill-prices.mdnew file mode 100644index 000000000..71a9fd414--- /dev/null+++ b/docs/monetization/03-save-skill-prices.md@@ -0,0 +1,106 @@+---+status: not-started+---++# Prompt 3: Save Skill Prices++## Objective+Implement the backend API and frontend logic to save the skill prices set by a creator in the agent edit page.++## Explanation+Following the creation of the UI for skill pricing, this step involves creating the necessary API endpoint to receive and store the pricing data in the database. The frontend will be updated to send the data from the form to this endpoint.++## Instructions+1. **Database Schema:**+ * Ensure you have a table to store prices, e.g., `agent_skill_prices`.+ * It should contain columns like `agent_id`, `skill_name`, `amount` (as an integer or bigint for precision), and `currency_mint`.++2. **Create a Backend API Endpoint:**+ * Create a new endpoint, for example, `POST /api/agents/:id/prices`. This could be in `api/agents/prices.js` or handled within the main agent update logic.+ * This endpoint will receive an agent ID and a payload of skill prices (e.g., `{ "skill_name": { "amount": 1500000, "currency_mint": "..." } }`).+ * The endpoint should be protected, ensuring only the agent's owner can update prices.+ * The backend logic should perform an "upsert" operation: for each skill in the payload, it should `UPDATE` the price if it exists or `INSERT` a new row if it doesn't. Skills not in the payload or with an empty price can be deleted.++3. **Update Frontend JavaScript:**+ * In the script for `agent-edit.html`, add an event listener to the "Save Prices" button.+ * When clicked, the script should gather all the data from the skill price input fields.+ * It should construct a payload object mapping skill names to their price and currency. Remember to convert the human-readable amount (e.g., 1.50 USDC) back to the base unit (e.g., 1,500,000 lamports).+ * Send this payload to the new API endpoint using a `fetch` POST request.+ * Provide user feedback (e.g., a toast notification) on success or failure.++## Code Example (Backend API - Express.js style)++```javascript+// POST /api/agents/:id/prices+app.post('/api/agents/:id/prices', async (req, res) => {+ const { id } = req.params;+ const prices = req.body.prices; // Expects an object like { skillName: { amount, currency_mint } }+ const userId = await getUserIdFromRequest(req); // Your auth logic++ // 1. Verify user owns the agent+ const agent = await db.query('SELECT owner_id FROM agents WHERE id = $1', [id]);+ if (!agent || agent.owner_id !== userId) {+ return res.status(403).json({ error: 'Forbidden' });+ }++ // 2. Use a transaction to update prices+ const client = await db.getClient();+ try {+ await client.query('BEGIN');+ // First, clear existing prices for this agent+ await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [id]);+ // Then, insert the new ones+ for (const skillName in prices) {+ const { amount, currency_mint } = prices[skillName];+ if (amount > 0) {+ await client.query(+ 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',+ [id, skillName, amount, currency_mint]+ );+ }+ }+ await client.query('COMMIT');+ res.status(200).json({ message: 'Prices updated successfully' });+ } catch (e) {+ await client.query('ROLLBACK');+ res.status(500).json({ error: 'Database error' });+ } finally {+ client.release();+ }+});+```++## Code Example (Frontend JavaScript)++```javascript+document.getElementById('save-prices-btn').addEventListener('click', async () => {+ const prices = {};+ const agentId = /* get agent ID from page */;++ document.querySelectorAll('.skill-price-row').forEach(row => {+ const priceInput = row.querySelector('.price-input');+ const currencySelect = row.querySelector('.currency-select');+ const skillName = priceInput.dataset.skill;+ const amountFloat = parseFloat(priceInput.value);++ if (skillName && !isNaN(amountFloat) && amountFloat > 0) {+ prices[skillName] = {+ amount: Math.round(amountFloat * 1e6), // Convert to lamports+ currency_mint: currencySelect.value+ };+ }+ });++ try {+ const response = await fetch(`/api/agents/${agentId}/prices`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', /* Auth headers */ },+ body: JSON.stringify({ prices })+ });+ if (!response.ok) throw new Error('Failed to save prices');+ showToast('Prices saved!', 'success');+ } catch (error) {+ showToast(error.message, 'error');+ }+});+```diff --git a/migrations/001_create_agent_skill_prices.sql b/migrations/001_create_agent_skill_prices.sqlnew file mode 100644index 000000000..5ee6cef92--- /dev/null+++ b/migrations/001_create_agent_skill_prices.sql@@ -0,0 +1,34 @@+-- Migration to create the agent_skill_prices table++CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,+ skill_name VARCHAR(255) NOT NULL,+ amount BIGINT NOT NULL, -- Storing price in the smallest currency unit (e.g., lamports for SOL)+ currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),++ UNIQUE (agent_id, skill_name)+);++-- Create an index for faster lookups by agent_id+CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);++-- A function 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;++-- A trigger to call the function before any update+CREATE TRIGGER set_timestamp+BEFORE UPDATE ON agent_skill_prices+FOR EACH ROW+EXECUTE PROCEDURE trigger_set_timestamp();++COMMENT ON TABLE agent_skill_prices IS 'Stores the prices for skills associated with an agent.';+COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest unit of the currency (e.g., lamports).';diff --git a/migrations/001_create_skill_prices.sql b/migrations/001_create_skill_prices.sqlnew file mode 100644index 000000000..5d50f4dea--- /dev/null+++ b/migrations/001_create_skill_prices.sql@@ -0,0 +1,19 @@++-- Migration to create the agent_skill_prices table++CREATE TABLE IF NOT EXISTS agent_skill_prices (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ skill_id UUID NOT NULL,+ creator_id UUID NOT NULL,+ 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 IF NOT EXISTS idx_agent_skill_prices_on_skill_id ON agent_skill_prices(skill_id);+\ No newline at end of filediff --git a/public/marketplace.css b/public/marketplace.cssindex b5c3d4e6b..cd54ef002 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -498,10 +498,42 @@ body.market-page {line-height: 1.7;background: var(--mk-panel);border: 1px solid var(--mk-border);- border-radius: var(--mk-radius);- padding: 18px;- margin: 0 0 18px;- font-size: 14px;+}++.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);+}++.purchase-btn {+ margin-left: 8px;+ padding: 4px 10px;+ background-color: #4f46e5;+ color: white;+ border: none;+ border-radius: 4px;+ cursor: pointer;+ font-size: 12px;+ font-weight: 600;+ transition: background-color 0.2s;+}+.purchase-btn:hover {+ background-color: #4338ca;}.market-skills,diff --git a/scripts/run-migrations.js b/scripts/run-migrations.jsnew file mode 100644index 000000000..dc89332d1--- /dev/null+++ b/scripts/run-migrations.js@@ -0,0 +1,27 @@++const { db } = require('../api/_lib/db');+const fs = require('fs');+const path = require('path');++async function runMigrations() {+ const migrationsDir = path.join(__dirname, '../migrations');+ const files = fs.readdirSync(migrationsDir).sort();++ for (const file of files) {+ if (file.endsWith('.sql')) {+ console.log(`Running migration: ${file}`);+ const sql = fs.readFileSync(path.join(migrationsDir, file), 'utf-8');+ await db.query(sql);+ console.log(`Finished migration: ${file}`);+ }+ }++ await db.end();+ console.log('All migrations completed.');+}++runMigrations().catch(err => {+ console.error('Migration failed:', err);+ process.exit(1);+});+\ No newline at end of filediff --git a/src/marketplace.js b/src/marketplace.jsindex 74a9f39fb..883a21861 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -175,7 +175,7 @@ function renderCard(a) {<div class="avatar">${a.avatar}</div><div style="min-width:0;flex:1"><div class="title">${escapeHtml(a.name || 'Untitled')}</div>- <div class="author">${escapeHtml(a.author || 'Anonymous')}</div>+ <div class="author">${escapeHtml(a.author_name || 'Anonymous')}</div></div></div><div class="desc">${escapeHtml(a.description || '')}</div>@@ -254,10 +254,16 @@ function renderDetail(a, bookmarked) {? skillsArr.map((s) => {const name = typeof s === 'string' ? s : (s.name || '');const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;+ 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>';$('d-library').innerHTML = libraryArr.lengthdiff --git a/tasks/monetization-feature/04-backend-create-purchases-table.md b/tasks/monetization-feature/04-backend-create-purchases-table.mdnew file mode 100644index 000000000..09b5ec7af--- /dev/null+++ b/tasks/monetization-feature/04-backend-create-purchases-table.md@@ -0,0 +1,49 @@+---+status: not-started+---++# Prompt 4: Create Purchases Database Table++**Status:** Not Started++## Objective+Create a database table (`skill_purchases`) to record which users have purchased which skills.++## Explanation+To grant users access to paid skills, we need to track their purchases. This table will create an association between a user, an agent's skill, and the transaction details of the purchase.++## Instructions+- [ ] **Update the Migration Script:**+ - [ ] Add a new `CREATE TABLE` statement to your `scripts/migrate-db.mjs` script.+- [ ] **Define the Table Schema:**+ - [ ] The `skill_purchases` table should include:+ - `user_id`: Foreign key to the `users` table.+ - `agent_id`: Foreign key to the `agent_identities` table.+ - `skill_name`: The name of the skill purchased.+ - `transaction_signature`: The Solana transaction signature of the purchase.+ - `purchase_amount`: The amount paid.+ - `purchase_currency_mint`: The currency used.+ - `created_at`: A timestamp for the purchase date.+ - [ ] Create a primary key or unique constraint on `(user_id, agent_id, skill_name)`.+- [ ] **Execute and Verify:**+ - [ ] Run the migration script.+ - [ ] Verify the table is created correctly in your database.++## Code Example (SQL)++```sql+CREATE TABLE IF NOT EXISTS skill_purchases (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ agent_id UUID NOT NULL,+ skill_name VARCHAR(255) NOT NULL,+ transaction_signature VARCHAR(255) UNIQUE NOT NULL,+ purchase_amount BIGINT NOT NULL,+ purchase_currency_mint VARCHAR(255) NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ -- Foreign key to the prices table at the time of purchase+ FOREIGN KEY (agent_id, skill_name) REFERENCES agent_skill_prices(agent_id, skill_name) ON DELETE SET NULL,+ -- Prevent user from buying the same skill twice+ UNIQUE (user_id, agent_id, skill_name)+);+```diff --git a/tasks/monetization-feature/05-backend-solana-pay-endpoint.md b/tasks/monetization-feature/05-backend-solana-pay-endpoint.mdnew file mode 100644index 000000000..395066201--- /dev/null+++ b/tasks/monetization-feature/05-backend-solana-pay-endpoint.md@@ -0,0 +1,59 @@+---+status: not-started+---++# Prompt 5: Backend Solana Pay Endpoint++**Status:** Not Started++## Objective+Create a backend endpoint that generates a Solana Pay transaction request for purchasing a skill.++## Explanation+When a user clicks "Buy," the frontend will need to request a transaction from the backend. This endpoint will generate a Solana Pay-compliant response, specifying the recipient wallet (the agent creator's), the amount, the SPL token mint, and a unique reference key for tracking the transaction.++## Instructions+- [ ] **Create a new API endpoint file** (e.g., `/api/payments/solana-pay.js`).+- [ ] **Endpoint Logic:**+ - [ ] It should accept a `POST` request with `agentId` and `skillName`.+ - [ ] Authenticate the user.+ - [ ] Fetch the skill price from the `agent_skill_prices` table.+ - [ ] Fetch the agent creator's wallet address from the `agent_identities` or a related table. This may require adding a `solana_wallet` column to `agent_identities` if it doesn't exist.+ - [ ] Generate a unique reference public key (`Keypair.generate()`). This will be used to find the transaction later.+ - [ ] Construct the Solana Pay response object, which includes a `label`, `icon`, `transaction` (URL for the next step), and `message`.+- [ ] **Return the Solana Pay JSON response.**++## Code Example (Conceptual Node.js)++```javascript+// In /api/payments/solana-pay.js+import { Keypair } from '@solana/web3.js';+// ... other imports++export default wrap(async (req, res) => {+ // ... authentication and validation+ const { agentId, skillName } = await readJson(req);++ // 1. Fetch skill price and creator's wallet+ const [priceInfo] = await sql`...`;+ const [agentInfo] = await sql`...`;+ const recipientWallet = agentInfo.solana_wallet;++ // 2. Generate a reference keypair+ const reference = new Keypair();++ // 3. Construct the Solana Pay response+ const response = {+ label: `3D-Agent Skill Purchase`,+ icon: 'https://3d-agent.com/icon.png',+ // The transaction URL points to another endpoint that builds the actual transaction+ transaction: `${process.env.NEXT_PUBLIC_URL}/api/payments/create-skill-tx?agentId=${agentId}&skillName=${skillName}&reference=${reference.publicKey.toBase58()}`,+ message: `Purchase '${skillName}' for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`+ };++ // You might need to store the reference key in cache/DB to validate the next step+ // await cache.set(`tx-ref:${reference.publicKey.toBase58()}`, { ...details });++ return json(res, 200, response);+});+```diff --git a/tasks/monetization-feature/06-backend-solana-webhook.md b/tasks/monetization-feature/06-backend-solana-webhook.mdnew file mode 100644index 000000000..8bc71d49e--- /dev/null+++ b/tasks/monetization-feature/06-backend-solana-webhook.md@@ -0,0 +1,71 @@+---+status: not-started+---++# Prompt 6: Backend Solana Transaction Confirmation++**Status:** Not Started++## Objective+Create a backend endpoint that verifies a Solana transaction signature, and if valid, records the skill purchase in the database.++## Explanation+After a user approves a transaction with their wallet, the wallet will submit it to the network. The frontend will get the transaction signature and send it to our backend. This endpoint will confirm the transaction on-chain, check that the details (amount, recipient) are correct, and then insert a record into the `skill_purchases` table.++## Instructions+- [ ] **Create a new API endpoint file** (e.g., `/api/payments/confirm-tx.js`).+- [ ] **Endpoint Logic:**+ - [ ] Accept a `POST` request with a `transactionSignature`.+ - [ ] Authenticate the user.+ - [ ] Use the Solana RPC API (`@solana/web3.js`) to fetch the confirmed transaction details.+ - [ ] **Crucially, verify:**+ - The transaction was successful.+ - The transfer destination matches the agent creator's wallet.+ - The transfer amount and mint match the skill's price.+ - The transaction includes the unique `reference` key from the Solana Pay request.+ - [ ] If all checks pass, `INSERT` a new row into the `skill_purchases` table.+- [ ] **Return a success or failure response** to the frontend.++## Code Example (Conceptual Node.js)++```javascript+import { Connection } from '@solana/web3.js';+// ...++const connection = new Connection(process.env.SOLANA_RPC_URL);++export default wrap(async (req, res) => {+ const user = await getSessionUser(req);+ // ...+ const { signature, agentId, skillName } = await readJson(req);++ // 1. Fetch transaction+ const tx = await connection.getParsedTransaction(signature, 'confirmed');+ if (!tx || tx.meta.err) {+ return error(res, 400, 'Transaction not confirmed or failed.');+ }++ // 2. Fetch expected price and recipient+ const [priceInfo] = await sql`...`;+ const [agentInfo] = await sql`...`;++ // 3. Verify transaction details (this part is complex and requires parsing instructions)+ // You need to find the correct spl-token transfer instruction and check its `info`.+ const transferInstruction = tx.transaction.message.instructions.find(...)+ const sentAmount = transferInstruction.info.amount;+ const recipient = transferInstruction.info.destination;+ const mint = transferInstruction.info.mint;++ if (recipient !== agentInfo.solana_wallet || sentAmount < priceInfo.amount || mint !== priceInfo.currency_mint) {+ return error(res, 400, 'Transaction details do not match.');+ }++ // 4. Record purchase+ await sql`+ INSERT INTO skill_purchases (user_id, agent_id, skill_name, ...)+ VALUES (${user.id}, ${agentId}, ${skillName}, ...);+ `;++ return json(res, 200, { message: 'Purchase successful!' });+});+```diff --git a/tasks/monetization-feature/07-backend-list-purchased-skills-api.md b/tasks/monetization-feature/07-backend-list-purchased-skills-api.mdnew file mode 100644index 000000000..40a6c4596--- /dev/null+++ b/tasks/monetization-feature/07-backend-list-purchased-skills-api.md@@ -0,0 +1,53 @@+---+status: not-started+---++# Prompt 7: API to List Purchased Skills++**Status:** Not Started++## Objective+Create an API endpoint that allows a logged-in user to see a list of all the skills they have purchased.++## Explanation+The frontend needs a way to know which skills the current user owns. This is useful for updating the UI on agent detail pages (e.g., showing "Owned" instead of "Buy") and for displaying a list of all purchased skills on the user's profile page.++## Instructions+- [ ] **Create a new API endpoint file** (e.g., `/api/users/my-skills.js`).+- [ ] **Endpoint Logic:**+ - [ ] Handle a `GET` request.+ - [ ] Authenticate the user to get their `user_id`.+ - [ ] Query the `skill_purchases` table for all records matching the `user_id`.+ - [ ] The query should return the `agent_id` and `skill_name` for each purchase.+- [ ] **Return the list of purchased skills as a JSON array.** For efficiency, you might return an object structure that's easy for the frontend to look up, e.g., `{ "agent_id:skill_name": true }`.++## Code Example (Node.js + @vercel/postgres)++```javascript+// In /api/users/my-skills.js++import { sql } from '../_lib/db.js';+import { getSessionUser } from '../_lib/auth.js';+// ...++export default wrap(async (req, res) => {+ if (req.method !== 'GET') return error(res, 405, 'method not allowed');++ const user = await getSessionUser(req);+ if (!user) return error(res, 401, 'unauthorized');++ const { rows } = await sql`+ SELECT agent_id, skill_name+ FROM skill_purchases+ WHERE user_id = ${user.id};+ `;++ // Create a lookup map for easy access on the frontend+ const purchasedSkillsLookup = {};+ for (const row of rows) {+ purchasedSkillsLookup[`${row.agent_id}:${row.skill_name}`] = true;+ }++ return json(res, 200, { purchased: purchasedSkillsLookup });+});+```diff --git a/tasks/monetization-feature/08-backend-gate-skill-usage.md b/tasks/monetization-feature/08-backend-gate-skill-usage.mdnew file mode 100644index 000000000..afbff174e--- /dev/null+++ b/tasks/monetization-feature/08-backend-gate-skill-usage.md@@ -0,0 +1,54 @@+---+status: not-started+---++# Prompt 8: Gate Skill Usage on Backend++**Status:** Not Started++## Objective+Modify the agent action/chat endpoint to verify that a user owns a paid skill before allowing its execution.++## Explanation+This is the core enforcement mechanism. When a user tries to use a skill (e.g., via a chat command), the backend must check two things: 1) if the skill is a paid skill, and 2) if the user has purchased it. If it's a paid skill and the user hasn't bought it, the request should be denied with an appropriate message.++## Instructions+- [ ] **Locate the main agent action endpoint** (e.g., `/api/chat.js` or `/api/agent-actions.js`).+- [ ] **Modify the Logic:**+ - [ ] When a request to execute a skill comes in, get the `agentId`, `skillName`, and the authenticated `userId`.+ - [ ] First, query `agent_skill_prices` to see if the requested `(agentId, skillName)` has a price.+ - [ ] If it does not have a price, it's a free skill, so proceed with execution as normal.+ - [ ] If it *does* have a price, you must then query the `skill_purchases` table to see if a record exists for `(userId, agentId, skillName)`.+ - [ ] If a purchase record exists, proceed with execution.+ - [ ] If no purchase record exists, return an error response (e.g., HTTP 402 Payment Required).+- [ ] **Optimize the query:** You can combine these checks into a single, more efficient SQL query.++## Code Example (Conceptual Node.js in `/api/chat.js`)++```javascript+// ... inside the chat handler, before executing the skill ...++const { agentId, skillName, ... } = req.body;+const user = await getSessionUser(req);++// Check if the skill is priced+const [priceInfo] = await sql`SELECT amount FROM agent_skill_prices WHERE agent_id = ${agentId} AND skill_name = ${skillName}`;++if (priceInfo) {+ // It's a paid skill, now check for ownership+ if (!user) {+ return res.status(402).json({ error: 'This is a premium skill. Please sign in to purchase.' });+ }++ const [purchase] = await sql`+ SELECT id FROM skill_purchases+ WHERE user_id = ${user.id} AND agent_id = ${agentId} AND skill_name = ${skillName}`;++ if (!purchase) {+ return res.status(402).json({ error: `You must purchase the '${skillName}' skill to use it.` });+ }+}++// If we reach here, the user is authorized to use the skill.+// ... proceed to execute the skill ...+```diff --git a/tasks/monetization-feature/09-backend-creator-payouts-table.md b/tasks/monetization-feature/09-backend-creator-payouts-table.mdnew file mode 100644index 000000000..6840d5d80--- /dev/null+++ b/tasks/monetization-feature/09-backend-creator-payouts-table.md@@ -0,0 +1,52 @@+---+status: not-started+---++# Prompt 9: Create Creator Payouts Table++**Status:** Not Started++## Objective+Create the necessary database tables to manage payouts for agent creators.++## Explanation+To complete the monetization loop, we need to track how much each agent creator has earned and when they get paid. This involves two tables: one to store creator wallet/payout information (`creator_payout_settings`) and another to log each payout transaction (`payouts`).++## Instructions+- [ ] **Update the Migration Script:** Add `CREATE TABLE` statements for two new tables in `scripts/migrate-db.mjs`.+- [ ] **`creator_payout_settings` Schema:**+ - `user_id`: Foreign key to `users`. This is the agent creator.+ - `payout_wallet_address`: The Solana address where they want to receive funds.+ - `payout_currency_mint`: The currency they prefer for payouts.+- [ ] **`payouts` Schema:**+ - `id`: Primary key.+ - `user_id`: The user (creator) who was paid.+ - `amount`: The total amount paid out.+ - `currency_mint`: The currency of the payout.+ - `transaction_signature`: The on-chain signature of the payout transaction.+ - `created_at`: Timestamp of the payout.+ - It should also include details on the earnings period this payout covers.+- [ ] **Execute and Verify** the migration.++## Code Example (SQL)++```sql+CREATE TABLE IF NOT EXISTS creator_payout_settings (+ user_id UUID PRIMARY KEY NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ payout_wallet_address VARCHAR(255) NOT NULL,+ payout_currency_mint VARCHAR(255) NOT NULL,+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE TABLE IF NOT EXISTS payouts (+ id UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ user_id UUID NOT NULL REFERENCES users(id),+ amount BIGINT NOT NULL,+ currency_mint VARCHAR(255) NOT NULL,+ -- Could be a Solana tx sig or a Stripe transfer ID, etc.+ transaction_signature VARCHAR(255) UNIQUE,+ earnings_start_date DATE NOT NULL,+ earnings_end_date DATE NOT NULL,+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+);+```diff --git a/tasks/monetization-feature/10-backend-payout-cron.md b/tasks/monetization-feature/10-backend-payout-cron.mdnew file mode 100644index 000000000..5071dc794--- /dev/null+++ b/tasks/monetization-feature/10-backend-payout-cron.md@@ -0,0 +1,67 @@+---+status: not-started+---++# Prompt 10: Backend Payout Cron Job++**Status:** Not Started++## Objective+Create a scheduled job (cron job) that calculates creator earnings and initiates payouts.++## Explanation+This is a backend-only task. On a regular schedule (e.g., weekly or monthly), a script needs to run that:+1. Calculates the total revenue for each agent creator from `skill_purchases`.+2. Subtracts any platform fees.+3. Initiates a transfer to the creator's wallet stored in `creator_payout_settings`.+4. Records the transaction in the `payouts` table.++## Instructions+- [ ] **Create a new cron job file** within the Vercel infrastructure (e.g., `/api/cron/process-payouts.js`).+- [ ] **Configuration:**+ - [ ] Configure `vercel.json` to schedule this job to run periodically (e.g., once a month).+- [ ] **Script Logic:**+ - [ ] Find the date of the last payout for each user to determine the new earnings period.+ - [ ] `SELECT` and `SUM` the `purchase_amount` from `skill_purchases`, grouped by the agent's `user_id`.+ - [ ] For each user with earnings, calculate the final payout amount after fees.+ - [ ] Fetch their payout wallet from `creator_payout_settings`.+ - [ ] Use the Solana SDK to create and send a transaction for the payout amount.+ - [ ] After the transaction is confirmed, `INSERT` a record into the `payouts` table.+- [ ] **Security:** This endpoint must be protected and only executable by Vercel's cron service, typically via a secret key.++## Code Example (Conceptual Vercel Cron Job)++```javascript+// In /api/cron/process-payouts.js+import { sql } from '../_lib/db.js';++export default async function handler(req, res) {+ // 1. Authenticate the cron job request+ // ...++ // 2. Determine earnings period (e.g., the last month)+ const endDate = new Date();+ const startDate = new Date();+ startDate.setMonth(startDate.getMonth() - 1);++ // 3. Calculate earnings for all creators in this period+ const { rows: earnings } = await sql`+ SELECT i.user_id, SUM(p.purchase_amount) as total_earnings+ FROM skill_purchases p+ JOIN agent_identities i ON p.agent_id = i.id+ WHERE p.created_at >= ${startDate} AND p.created_at < ${endDate}+ GROUP BY i.user_id;+ `;++ // 4. Process each payout+ for (const userEarning of earnings) {+ const platformFee = 0.10; // 10% fee+ const payoutAmount = userEarning.total_earnings * (1 - platformFee);++ // Fetch wallet, create & send Solana tx, then record in payouts table+ // ... (complex logic here) ...+ }++ res.status(200).send('Payouts processed');+}+```diff --git a/tasks/monetization-feature/11-frontend-monetization-tab.md b/tasks/monetization-feature/11-frontend-monetization-tab.mdnew file mode 100644index 000000000..872024f70--- /dev/null+++ b/tasks/monetization-feature/11-frontend-monetization-tab.md@@ -0,0 +1,58 @@+---+status: not-started+---++# Prompt 11: Frontend Monetization Tab++**Status:** Not Started++## Objective+Add a new "Monetization" tab or section to the agent creation/editing page.++## Explanation+Agent creators need a dedicated area to manage the pricing of their skills. The first step is to create the UI container for these settings. This involves adding a new tab to the navigation on the agent editor page.++## Instructions+- [ ] **Identify the agent editor file:**+ - [ ] Locate the main HTML file for editing an agent (e.g., `agent-edit.html`).+- [ ] **Add a new navigation tab:**+ - [ ] In the HTML, find the tab navigation structure.+ - [ ] Add a new tab link labeled "Monetization".+- [ ] **Create the content pane:**+ - [ ] Add a corresponding content `div` for the monetization tab. This `div` will initially be hidden and shown only when the "Monetization" tab is active.+ - [ ] This pane will house the skill pricing UI, which will be built in the next prompt.+- [ ] **Implement the tab switching logic:**+ - [ ] In the corresponding JavaScript file, add or update the event listeners to handle showing and hiding the new monetization pane when its tab is clicked.++## Code Example (HTML in `agent-edit.html`)++```html+<!-- ... inside agent-edit.html ... -->++<div class="tabs">+ <a href="#" class="tab-link active" data-tab="profile">Profile</a>+ <a href="#" class="tab-link" data-tab="avatar">Avatar</a>+ <a href="#" class="tab-link" data-tab="skills">Skills</a>+ <!-- New Tab -->+ <a href="#" class="tab-link" data-tab="monetization">Monetization</a>+</div>++<div class="tab-content">+ <div id="tab-profile" class="tab-pane active">+ <!-- ... profile content ... -->+ </div>+ <div id="tab-avatar" class="tab-pane">+ <!-- ... avatar content ... -->+ </div>+ <div id="tab-skills" class="tab-pane">+ <!-- ... skills content ... -->+ </div>+ <!-- New Pane -->+ <div id="tab-monetization" class="tab-pane">+ <h2>Skill Pricing</h2>+ <p>Set prices for your premium skills here.</p>+ <!-- UI for pricing will go here in the next step -->+ <div id="skill-pricing-list"></div>+ </div>+</div>+```diff --git a/tasks/monetization-feature/12-frontend-price-management-ui.md b/tasks/monetization-feature/12-frontend-price-management-ui.mdnew file mode 100644index 000000000..a4691e128--- /dev/null+++ b/tasks/monetization-feature/12-frontend-price-management-ui.md@@ -0,0 +1,59 @@+---+status: not-started+---++# Prompt 12: Frontend Price Management UI++**Status:** Not Started++## Objective+Build the user interface within the "Monetization" tab for agent creators to view their skills and set prices for them.++## Explanation+This task involves dynamically generating a list of the agent's skills in the monetization tab. Each skill will have input fields for a price and currency, allowing the creator to manage their premium offerings.++## Instructions+- [ ] **Locate the agent editor's JavaScript file.**+- [ ] **Fetch and Display Skills:**+ - [ ] When the monetization tab is loaded, use the agent's data (which should already be loaded on the page) to get the list of skills.+ - [ ] Also, get the existing `skill_prices` for the agent.+ - [ ] Dynamically generate HTML to list each skill.+ - [ ] For each skill, create:+ - The skill name (as a label).+ - An `input` field for the `amount`.+ - A `select` dropdown for the `currency_mint` (e.g., with an option for USDC).+- [ ] **Populate Existing Prices:**+ - [ ] If a skill already has a price set, populate the input fields with the existing data.+- [ ] **Add a "Save" button** for each skill or a single "Save All Prices" button for the page.++## Code Example (JavaScript)++```javascript+// In the agent editor's JS file, in a function that renders the monetization tab++function renderMonetizationTab(agent) {+ const container = document.getElementById('skill-pricing-list');+ const skills = agent.skills || [];+ const prices = agent.skill_prices || {};++ if (skills.length === 0) {+ container.innerHTML = '<p>Add skills in the "Skills" tab first.</p>';+ return;+ }++ container.innerHTML = skills.map(skillName => {+ const price = prices[skillName] || { amount: 0, currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T' };+ const priceInUsdc = price.amount / 1e6;++ return `+ <div class="skill-price-entry" data-skill-name="${skillName}">+ <label>${skillName}</label>+ <input type="number" class="price-input" value="${priceInUsdc}" min="0" step="0.01">+ <select class="currency-input">+ <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>+ </select>+ </div>+ `;+ }).join('') + '<button id="save-prices-btn">Save Prices</button>';+}+```diff --git a/tasks/monetization-feature/13-frontend-js-sign-transaction.md b/tasks/monetization-feature/13-frontend-js-sign-transaction.mdnew file mode 100644index 000000000..ad6e93fee--- /dev/null+++ b/tasks/monetization-feature/13-frontend-js-sign-transaction.md@@ -0,0 +1,59 @@+---+status: not-started+---+# Prompt 13: Sign and Send Transaction from Frontend++**Status:** Not Started++## Objective+Implement the logic to have the user's wallet sign the transaction received from the backend and broadcast it to the Solana network.++## Explanation+This is the core of the on-chain interaction. The frontend acts as a bridge between the backend (which creates the transaction) and the user's wallet (which holds the keys and signs). A successful broadcast returns a transaction signature.++## Instructions+- **This task builds on the previous one, using the `transaction` string.**+- **Create a `signAndSendTransaction` function.**+- **Inside this function:**+ 1. **Deserialize the Transaction:** The backend sent a base64-encoded string. You need to decode it and reconstruct the `Transaction` object.+ 2. **Sign the Transaction:** Use the `signTransaction` method from the wallet adapter. This will prompt the user in their wallet UI.+ 3. **Send the Transaction:** Use `connection.sendRawTransaction` to broadcast the signed transaction to the network.+ 4. **Confirm the Transaction:** Use `connection.confirmTransaction` to wait for the transaction to be finalized on the blockchain. This returns the signature.+ 5. **Fulfill the Purchase:** Call the backend fulfillment endpoint (`/api/skills/fulfill_purchase`) with the transaction signature.++## Code Example (Frontend - using `@solana/wallet-adapter` hooks)+```javascript+import { Connection, Transaction } from '@solana/web3.js';+// const { publicKey, signTransaction } = useWallet();+// const connection = new Connection(...);++async function signAndSendTransaction(base64Transaction) {+ if (!publicKey || !signTransaction) return;++ try {+ // 1. Deserialize+ const transactionBuffer = Buffer.from(base64Transaction, 'base64');+ const transaction = Transaction.from(transactionBuffer);++ // 2. Sign+ const signedTransaction = await signTransaction(transaction);++ // 3. Send+ const signature = await connection.sendRawTransaction(+ signedTransaction.serialize()+ );++ // 4. Confirm+ await connection.confirmTransaction(signature);++ console.log('Transaction successful with signature:', signature);++ // 5. Fulfill (call backend)+ await fulfillPurchaseOnBackend(signature);++ } catch (error) {+ console.error('Signing failed:', error);+ alert('Transaction was not approved or failed to send.');+ }+}+```diff --git a/tasks/monetization-feature/13-frontend-save-skill-prices.md b/tasks/monetization-feature/13-frontend-save-skill-prices.mdnew file mode 100644index 000000000..3616fa8bb--- /dev/null+++ b/tasks/monetization-feature/13-frontend-save-skill-prices.md@@ -0,0 +1,76 @@+---+status: not-started+---++# Prompt 13: Frontend Logic to Save Skill Prices++**Status:** Not Started++## Objective+Implement the client-side JavaScript to handle saving the skill prices set by the agent creator.++## Explanation+When the user clicks the "Save Prices" button in the monetization tab, the frontend needs to collect the data from all the input fields and send it to the backend API endpoint created in Prompt 3.++## Instructions+- [ ] **Add an Event Listener:**+ - [ ] In the agent editor's JavaScript, add a `click` event listener to the "Save Prices" button (`#save-prices-btn`).+- [ ] **Data Collection:**+ - [ ] Inside the event listener, iterate through each `.skill-price-entry` element.+ - [ ] For each skill, read the `skill-name` from the `data-` attribute, the price from the `.price-input`, and the currency from the `.currency-input`.+ - [ ] Remember to convert the human-readable price (e.g., 1.50 USDC) back into the smallest unit (lamports, e.g., 1,500,000).+- [ ] **API Call:**+ - [ ] For each skill that has a price set, call the `POST /api/agents/prices` endpoint. You can do this in a loop or batch the requests.+ - [ ] The body of the request should be `{ agentId, skillName, amount, currencyMint }`.+- [ ] **Provide User Feedback:**+ - [ ] Show a success message (e.g., a toast notification) when the prices are saved successfully.+ - [ ] Display an error message if the API call fails.++## Code Example (JavaScript)++```javascript+// In the agent editor's JS file++document.addEventListener('click', async (e) => {+ if (e.target.id === 'save-prices-btn') {+ e.target.disabled = true;+ e.target.textContent = 'Saving...';++ const entries = document.querySelectorAll('.skill-price-entry');+ for (const entry of entries) {+ const skillName = entry.dataset.skillName;+ const amountUSD = parseFloat(entry.querySelector('.price-input').value);+ const currencyMint = entry.querySelector('.currency-input').value;+ const amountLamports = Math.round(amountUSD * 1e6); // Convert to lamports++ try {+ const response = await fetch('/api/agents/prices', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ agentId: currentAgent.id, // Assumes currentAgent is available in scope+ skillName,+ amount: amountLamports,+ currencyMint,+ }),+ });++ if (!response.ok) {+ throw new Error('Failed to save price for ' + skillName);+ }+ } catch (err) {+ console.error(err);+ alert('Error saving prices. Check the console.');+ // Re-enable button and break+ e.target.disabled = false;+ e.target.textContent = 'Save Prices';+ return;+ }+ }++ e.target.disabled = false;+ e.target.textContent = 'Save Prices';+ alert('Prices saved successfully!');+ }+});+```diff --git a/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.md b/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.mdnew file mode 100644index 000000000..313d1fbac--- /dev/null+++ b/tasks/monetization-feature/14-frontend-creator-earnings-dashboard.md@@ -0,0 +1,60 @@+---+status: not-started+---++# Prompt 14: Creator Earnings Dashboard++**Status:** Not Started++## Objective+Create a simple dashboard for agent creators to see their total earnings and a history of their payouts.++## Explanation+To provide transparency and build trust, creators need to see how much they've earned from their paid skills. This task involves creating a new UI component, possibly in the "Monetization" tab or on a separate page, that fetches and displays earnings and payout data from the backend.++## Instructions+- [ ] **Create Backend Endpoints:**+ - [ ] You will need two new API endpoints:+ - `GET /api/earnings/summary`: Should return the user's total all-time earnings and their current balance pending payout.+ - `GET /api/earnings/payouts`: Should return a paginated list of the user's past payouts from the `payouts` table.+- [ ] **Build the Frontend UI:**+ - [ ] In the agent editor's "Monetization" tab (or a new page), add a new section for "Earnings".+ - [ ] Add display cards for "Total Revenue" and "Pending Payout".+ - [ ] Add a table to display the payout history.+- [ ] **Fetch and Render Data:**+ - [ ] On page load, call the new endpoints to get the data.+ - [ ] Populate the UI with the fetched data. Format dates and amounts nicely.++## Code Example (Conceptual UI)++```html+<!-- In the Monetization tab -->+<div id="earnings-dashboard">+ <h3>Your Earnings</h3>+ <div class="stats-grid">+ <div class="stat-card">+ <h4>Total Revenue</h4>+ <p id="total-revenue">$0.00</p>+ </div>+ <div class="stat-card">+ <h4>Pending Payout</h4>+ <p id="pending-payout">$0.00</p>+ </div>+ </div>++ <h4>Payout History</h4>+ <table id="payouts-table">+ <thead>+ <tr>+ <th>Date</th>+ <th>Amount</th>+ <th>Status</th>+ <th>Transaction</th>+ </tr>+ </thead>+ <tbody>+ <!-- Rows will be populated by JavaScript -->+ </tbody>+ </table>+</div>+```diff --git a/tasks/monetization-feature/14-frontend-ui-purchase-flow.md b/tasks/monetization-feature/14-frontend-ui-purchase-flow.mdnew file mode 100644index 000000000..012418f67--- /dev/null+++ b/tasks/monetization-feature/14-frontend-ui-purchase-flow.md@@ -0,0 +1,58 @@+---+status: not-started+---+# Prompt 14: Frontend UI for Purchase Flow++**Status:** Not Started++## Objective+Provide clear, real-time feedback to the user throughout the entire purchase process.++## Explanation+A user should never be left wondering what's happening, especially when money is involved. This task is about updating the UI to reflect the state of the purchase: preparing, waiting for signature, sending, confirming, and success or failure.++## Instructions+1. **Refactor the purchase logic from the previous tasks.**+2. **When the "Purchase" button is clicked:**+ - Immediately disable the button and show a loading spinner or "Preparing..." text.+3. **When waiting for the user to sign in their wallet:**+ - Update the status message to "Please approve the transaction in your wallet...".+4. **After the transaction is signed and being sent:**+ - Change the message to "Sending transaction...".+5. **While confirming the transaction on the blockchain:**+ - Update to "Confirming transaction on the blockchain...".+6. **Upon success:**+ - Show a success message (e.g., "Purchase Complete!").+ - Replace the "Purchase" button with an "Owned" badge.+7. **On any failure (user rejects, network error, etc.):**+ - Show a descriptive error message.+ - Re-enable the "Purchase" button so the user can try again.++## Code Example (UI state management)+```javascript+// In the purchase button click handler+const purchaseButton = event.target;++function setButtonState(btn, text, disabled) {+ btn.textContent = text;+ btn.disabled = disabled;+}++try {+ setButtonState(purchaseButton, 'Preparing...', true);+ const { transaction } = await fetchFromApi(...);++ setButtonState(purchaseButton, 'Approve in wallet...', true);+ const signature = await signAndSend(transaction); // This function internally would update state too++ setButtonState(purchaseButton, 'Confirming...', true);+ await fulfillOnBackend(signature);++ // Replace button with "Owned" badge+ purchaseButton.outerHTML = `<span class="price-badge price-owned">Owned</span>`;++} catch (error) {+ alert(`Failed: ${error.message}`);+ setButtonState(purchaseButton, 'Purchase', false); // Reset on failure+}+```diff --git a/tasks/monetization-feature/15-backend-logic-skill-unlock.md b/tasks/monetization-feature/15-backend-logic-skill-unlock.mdnew file mode 100644index 000000000..7eb1f08cd--- /dev/null+++ b/tasks/monetization-feature/15-backend-logic-skill-unlock.md@@ -0,0 +1,50 @@+---+status: not-started+---+# Prompt 15: Backend Logic for Skill Unlocking++**Status:** Not Started++## Objective+Modify the backend logic to ensure that an agent can only use/execute skills that are either free or have been purchased for it.++## Explanation+This is the enforcement part of the monetization feature. When an agent is about to perform an action using a skill, the backend must first verify access rights. This prevents users from using paid skills without paying for them.++## Instructions+1. **Locate the core agent logic where a skill is executed.** This might be in a chat processing loop or an action handler.+2. **Before executing a skill, perform an access check:**+ - **Get the skill's pricing information.** You'll need to query the `agent_skill_prices` table.+ - **If the skill is not in the pricing table, it's free.** Allow execution.+ - **If the skill has a price, it's a paid skill.** You must check if a valid purchase record exists.+ - **Query the `skill_purchases` table** for a row matching the current `agent_id` and the `skill_id`.+ - **If a purchase record exists, allow execution.**+ - **If no purchase record exists, block execution** and return an error message to the user (e.g., "This agent has not purchased the '[skill name]' skill.").++## Code Example (Conceptual backend logic)+```javascript+async function executeSkill(agent, skillName, user) {+ const skill = await getSkillByName(skillName);++ // Check if the skill is priced+ const priceInfo = await db.query('SELECT id FROM agent_skill_prices WHERE skill_id = $1', [skill.id]);++ if (!priceInfo) {+ // Skill is free, proceed+ return skill.execute(agent);+ }++ // Skill is paid, check for purchase+ const purchase = await db.query(`+ SELECT id FROM skill_purchases+ WHERE agent_id = $1 AND skill_id = $2+ `, [agent.id, skill.id]);++ if (!purchase) {+ throw new Error(`Access denied. The skill '${skillName}' must be purchased for this agent.`);+ }++ // Access granted, proceed+ return skill.execute(agent);+}+```diff --git a/tasks/monetization-feature/15-frontend-add-buy-button.md b/tasks/monetization-feature/15-frontend-add-buy-button.mdnew file mode 100644index 000000000..ace72a6ea--- /dev/null+++ b/tasks/monetization-feature/15-frontend-add-buy-button.md@@ -0,0 +1,53 @@+---+status: not-started+---++# Prompt 15: Add "Buy" Button to Marketplace++**Status:** Not Started++## Objective+Modify the agent detail page in the marketplace to show a "Buy" button next to paid skills that the user has not yet purchased.++## Explanation+This is the call-to-action for users. Instead of just showing a price, we need to provide an interactive button that initiates the purchase flow. The button's state should depend on whether the user is logged in and whether they already own the skill.++## Instructions+- [ ] **Update Frontend Data Fetching:**+ - [ ] When the marketplace page loads, in addition to fetching agent details, also make a call to the `/api/users/my-skills` endpoint (from Prompt 7) to get a list of the user's purchased skills. Store this in a local variable. This should only be done if the user is logged in.+- [ ] **Modify the `renderDetail` function in `src/marketplace.js`:**+ - [ ] Inside the loop that renders skills, you now have access to both the `skillPrices` and the `userPurchases`.+ - [ ] Add a new function or logic to determine the button's state for each skill:+ - If the skill is free: show a "Free" badge.+ - If the skill is paid and the user owns it: show an "Owned" badge or a disabled button.+ - If the skill is paid and the user does *not* own it: show an active "Buy for X USDC" button.+ - If the user is not logged in: the "Buy" button should prompt them to sign in.+- [ ] **Add `data-` attributes to the button** to store the `agentId` and `skillName`, which will be needed to start the purchase flow.++## Code Example (JavaScript in `src/marketplace.js`)++```javascript+// Assumes `userPurchases` is a lookup map like { "agent_id:skill_name": true }+const skillPrices = a.skill_prices || {};+const userPurchases = state.mySkills || {}; // state.mySkills is fetched on load++$('d-skills').innerHTML = skillsArr.map(s => {+ const name = s.name || s;+ const price = skillPrices[name];+ const purchaseKey = `${a.id}:${name}`;+ const isOwned = userPurchases[purchaseKey];++ let badgeOrButton;+ if (isOwned) {+ badgeOrButton = `<span class="price-badge price-owned">Owned</span>`;+ } else if (price) {+ badgeOrButton = `<button class="btn-buy" data-agent-id="${a.id}" data-skill-name="${name}">+ Buy for ${(price.amount / 1e6).toFixed(2)} USDC+ </button>`;+ } else {+ badgeOrButton = `<span class="price-badge price-free">Free</span>`;+ }++ return `<span class="skill-entry">${escapeHtml(name)}${badgeOrButton}</span>`;+}).join(' ');+```diff --git a/tasks/monetization-feature/16-frontend-purchase-modal.md b/tasks/monetization-feature/16-frontend-purchase-modal.mdnew file mode 100644index 000000000..92f2be0de--- /dev/null+++ b/tasks/monetization-feature/16-frontend-purchase-modal.md@@ -0,0 +1,61 @@+---+status: not-started+---++# Prompt 16: Frontend Purchase Modal++**Status:** Not Started++## Objective+Create a modal dialog on the frontend that appears when a user clicks the "Buy" button, displaying a Solana Pay QR code for the transaction.++## Explanation+The purchase modal is the heart of the user-facing payment flow. It needs to be clean, clear, and easy to use. It will fetch the Solana Pay transaction request from our backend and display it as a QR code that mobile wallets can scan, or provide a link for desktop wallets.++## Instructions+- [ ] **Add a hidden modal to `marketplace.html`:**+ - [ ] Create the HTML structure for the modal, including a space for the QR code, a title, price details, and a close button. Initially, it should be hidden with CSS.+- [ ] **Add a click listener for the `.btn-buy` buttons.**+- [ ] **When a "Buy" button is clicked:**+ - [ ] Get the `agentId` and `skillName` from the button's `data-` attributes.+ - [ ] Show the modal and display a loading spinner.+ - [ ] Make a `POST` request to your `/api/payments/solana-pay` endpoint.+ - [ ] The backend will respond with a Solana Pay URL (the `transaction` field from Prompt 5).+- [ ] **Generate and Display QR Code:**+ - [ ] Use a client-side QR code generation library (like `qr-code-styling`) to turn the Solana Pay URL into a QR code and display it in the modal.+ - [ ] Also provide a clickable link for desktop users.++## Code Example (JavaScript using a QR library)++```javascript+import QRCodeStyling from 'qr-code-styling';++// ... listener for .btn-buy clicks ...+async function onBuyClick(agentId, skillName) {+ showModal(); // Show modal with a loading state+ const modalBody = document.getElementById('purchase-modal-body');++ try {+ const res = await fetch('/api/payments/solana-pay', {+ method: 'POST',+ body: JSON.stringify({ agentId, skillName }),+ });+ const solanaPayRequest = await res.json();+ const solanaPayUrl = solanaPayRequest.transaction; // This is the URL to encode++ const qrCode = new QRCodeStyling({+ width: 300,+ height: 300,+ data: solanaPayUrl,+ // ... styling options+ });++ modalBody.innerHTML = ''; // Clear loader+ qrCode.append(modalBody);+ modalBody.innerHTML += `<a href="${solanaPayUrl}">Open in Wallet</a>`;++ } catch (err) {+ modalBody.innerHTML = 'Error creating transaction. Please try again.';+ }+}+```diff --git a/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.md b/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.mdnew file mode 100644index 000000000..16d6d7376--- /dev/null+++ b/tasks/monetization-feature/16-frontend-ui-my-agents-purchased-skills.md@@ -0,0 +1,42 @@+---+status: not-started+---+# Prompt 16: Display Purchased Skills in "My Agents"++**Status:** Not Started++## Objective+Update the "My Agents" page to display the list of skills, including purchased premium skills, for each agent owned by the user.++## Explanation+Users need to see what skills their agents possess. This task involves enhancing the "My Agents" page to not only list the agents but also their associated skills, visually distinguishing between default/free skills and purchased ones.++## Instructions+1. **Modify the API endpoint that serves data for the "My Agents" page** (e.g., `/api/users/me/agents`).+2. **In the backend query, `JOIN` with the `skill_purchases` and `skills` tables** to retrieve the names of all skills purchased for each agent.+3. **Also include the agent's base/free skills.** The final agent object in the API response should have an array like `skills: [{ name: 'wave', purchased: false }, { name: 'translator', purchased: true }]`.+4. **In the frontend JavaScript for the "My Agents" page, update the rendering logic.**+5. Iterate through the new `skills` array for each agent and display them, perhaps with a special icon or style for `purchased: true` skills.++## Code Example (Frontend rendering)+```javascript+// Inside the function that renders a single agent card+function renderAgent(agent) {+ const skillsHtml = agent.skills.map(skill => `+ <span class="agent-skill ${skill.purchased ? 'skill-purchased' : 'skill-free'}">+ ${skill.name}+ ${skill.purchased ? '<i class="premium-icon"></i>' : ''}+ </span>+ `).join(' ');++ return `+ <div class="agent-card">+ <h3>${agent.name}</h3>+ <div class="agent-skills-list">+ ${skillsHtml}+ </div>+ </div>+ `;+}+```+This provides a clear visual inventory for the user.diff --git a/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.md b/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.mdnew file mode 100644index 000000000..a64cfbfd3--- /dev/null+++ b/tasks/monetization-feature/17-frontend-ui-marketplace-purchased-indicator.md@@ -0,0 +1,39 @@+---+status: not-started+---+# Prompt 17: "Owned" Indicator in Marketplace++**Status:** Not Started++## Objective+Refine the marketplace UI to clearly show when a paid skill has already been purchased for the currently viewed agent.++## Explanation+This is a follow-up to Prompt #10. The goal is to prevent users from re-purchasing skills they already own. The "Purchase" button should be replaced with a non-interactive "Owned" badge or similar indicator.++## Instructions+1. **Ensure the agent detail API endpoint (`/api/marketplace/agents/:id`) includes information about which skills are owned.**+ - This endpoint should return an array of skill names or IDs that have been purchased for this specific agent, for example, `owned_skills: ["translator", "weather_forecast"]`.+2. **In `src/marketplace.js`, within the `renderDetail` function, use this `owned_skills` array.**+3. **When rendering the list of skills, check if the current skill's name exists in the `owned_skills` array.**+4. **Use conditional logic:**+ - If `owned_skills.includes(skill.name)`, render the "Owned" badge.+ - Otherwise, render the "Purchase" button for the priced skill.++## Code Example (Revisiting `src/marketplace.js`)+```javascript+// Inside renderDetail, assuming 'a' is the agent object from the API+const ownedSkills = a.owned_skills || [];++// ... inside the skill mapping logic ...+const isOwned = ownedSkills.includes(name);++if (price && isOwned) {+ badgeHtml = `<span class="price-badge price-owned">Owned</span>`;+} else if (price && !isOwned) {+ badgeHtml = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;+} else {+ badgeHtml = `<span class="price-badge price-free">Free</span>`;+}+```+This provides an intuitive user experience and prevents accidental duplicate purchases.diff --git a/tasks/monetization-feature/18-backend-revenue-sharing.md b/tasks/monetization-feature/18-backend-revenue-sharing.mdnew file mode 100644index 000000000..5da616aac--- /dev/null+++ b/tasks/monetization-feature/18-backend-revenue-sharing.md@@ -0,0 +1,54 @@+---+status: not-started+---+# Prompt 18: Backend Revenue Sharing++**Status:** Not Started++## Objective+Implement a simple revenue sharing model in the backend where the platform takes a small percentage fee from each skill sale.++## Explanation+To create a sustainable business model, the platform needs to generate revenue. A common approach is to take a small commission on transactions occurring in the marketplace. This task modifies the transaction creation logic to include a platform fee.++## Instructions+1. **Establish a platform wallet address.** Store this securely in your backend environment variables (e.g., `PLATFORM_WALLET_ADDRESS`).+2. **Define the platform fee percentage.** Store this as a constant or environment variable (e.g., `PLATFORM_FEE_PERCENT = 0.05` for 5%).+3. **Locate the API endpoint that initiates the purchase transaction (`/api/skills/:skill_id/purchase` from Prompt 5).**+4. **Modify the transaction construction logic:**+ - Calculate the payment amount for the creator (`price * (1 - PLATFORM_FEE_PERCENT)`).+ - Calculate the platform fee amount (`price * PLATFORM_FEE_PERCENT`).+ - Instead of one `SystemProgram.transfer` instruction, the transaction will now have two:+ - One transfer from the user to the skill creator's wallet.+ - A second transfer from the user to the platform's wallet.+5. **Return the new two-instruction transaction to the client for signing.**++## Code Example (Backend - `initiatePurchase` logic)+```javascript+// ... inside the initiatePurchase function+const priceInfo = ...+const creatorWallet = new PublicKey(creator.wallet_address);+const platformWallet = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);+const feePercentage = 0.05; // 5%++const creatorAmount = Math.floor(priceInfo.amount * (1 - feePercentage));+const feeAmount = priceInfo.amount - creatorAmount; // Avoid floating point issues++const transaction = new Transaction(...);++// Transfer to creator+transaction.add(SystemProgram.transfer({+ fromPubkey: user_wallet,+ toPubkey: creatorWallet,+ lamports: creatorAmount,+}));++// Transfer to platform+transaction.add(SystemProgram.transfer({+ fromPubkey: user_wallet,+ toPubkey: platformWallet,+ lamports: feeAmount,+}));++// Serialize and return transaction...+```diff --git a/tasks/monetization-feature/19-creator-analytics.md b/tasks/monetization-feature/19-creator-analytics.mdnew file mode 100644index 000000000..7edcc0314--- /dev/null+++ b/tasks/monetization-feature/19-creator-analytics.md@@ -0,0 +1,37 @@+---+status: not-started+---+# Prompt 19: Creator Analytics Page++**Status:** Not Started++## Objective+Create a basic analytics page for creators to view their sales and total revenue.++## Explanation+Providing creators with data on their skill performance is crucial for a healthy ecosystem. This task involves creating a new page and API endpoint to display simple metrics like total sales, revenue, and a list of recent transactions.++## Instructions+1. **Backend: Create a new API endpoint `GET /api/creator/analytics`.**+ - This endpoint should be authenticated.+ - It should query the `skill_purchases` table, filtering for skills created by the logged-in user.+ - Calculate aggregate data: `total_sales`, `total_revenue`.+ - Retrieve the last 10-20 purchase records (`skill_name`, `purchase_at`, `purchase_amount`).+ - Return this data as a JSON object.+2. **Frontend: Create a new page `public/creator-analytics.html`.**+3. **Add a new script `src/creator-analytics.js`.**+4. **On page load, fetch data from the new analytics endpoint.**+5. **Render the data in a user-friendly way:**+ - Display "Total Revenue" and "Total Skills Sold" in prominent stat boxes.+ - Show a table of "Recent Sales" with details for each transaction.++## Code Example (Backend - SQL Query for Analytics)+```sql+SELECT+ COUNT(*) AS total_sales,+ SUM(p.purchase_amount) AS total_revenue+FROM skill_purchases p+JOIN skills s ON p.skill_id = s.id+WHERE s.creator_id = $1; -- $1 is the authenticated user's ID+```+This gives creators valuable insight and encourages them to build more high-quality skills.diff --git a/tasks/monetization-feature/20-ui-transaction-history.md b/tasks/monetization-feature/20-ui-transaction-history.mdnew file mode 100644index 000000000..57b7df759--- /dev/null+++ b/tasks/monetization-feature/20-ui-transaction-history.md@@ -0,0 +1,43 @@+---+status: not-started+---+# Prompt 20: User Transaction History UI++**Status:** Not Started++## Objective+Create a "Transaction History" page for users to see a list of their past skill purchases.++## Explanation+Users need a way to track their spending and see a record of the skills they've acquired. This adds transparency and helps with user account management.++## Instructions+1. **Backend: Create a new endpoint `GET /api/users/me/purchases`.**+ - The endpoint must be authenticated.+ - Query the `skill_purchases` table for all records matching the logged-in `user_id`.+ - For each record, join with the `skills` and `agents` tables to get their names.+ - Return an array of purchase objects.+2. **Frontend: Create a new page `public/purchase-history.html`.**+3. **Create a script `src/purchase-history.js`.**+4. **Fetch data from the new endpoint on page load.**+5. **Render the data as a table or a list.**+ - Each row should display: Skill Name, Agent Name it was purchased for, Price, and Purchase Date.+ - Include a link to the transaction signature on a block explorer like Solscan or Solana Explorer.++## Code Example (Frontend - Rendering a history row)+```javascript+// purchases is the array from the API+const historyHtml = purchases.map(p => `+ <tr>+ <td>${p.skill_name}</td>+ <td>${p.agent_name}</td>+ <td>${(p.purchase_amount / 1e6).toFixed(2)} USDC</td>+ <td>${new Date(p.purchased_at).toLocaleDateString()}</td>+ <td>+ <a href="https://solscan.io/tx/${p.transaction_signature}" target="_blank">View on Solscan</a>+ </td>+ </tr>+`).join('');++document.getElementById('history-table-body').innerHTML = historyHtml;+```diff --git a/tasks/monetization-feature/21-search-filter-by-price.md b/tasks/monetization-feature/21-search-filter-by-price.mdnew file mode 100644index 000000000..e2b099de3--- /dev/null+++ b/tasks/monetization-feature/21-search-filter-by-price.md@@ -0,0 +1,45 @@+---+status: not-started+---+# Prompt 21: Search & Filter by Price++**Status:** Not Started++## Objective+Add controls to the marketplace page that allow users to filter agents based on whether they have free or paid skills.++## Explanation+As the marketplace grows, users will need tools to find what they're looking for. Filtering by price is a fundamental discovery feature.++## Instructions+1. **Backend: Modify the marketplace agent search/list endpoint (`/api/marketplace/agents`).**+ - The endpoint should accept a new query parameter, e.g., `price_filter=paid` or `price_filter=free`.+ - If `price_filter=paid`, the database query should only return agents that have at least one priced skill. This can be done with a `WHERE EXISTS` subquery checking `agent_skill_prices`.+ - If `price_filter=free`, return agents that have no priced skills.+2. **Frontend: Add filter UI to `marketplace.html`.**+ - This could be a set of radio buttons or a dropdown: (All, Free, Paid).+3. **Frontend: In `src/marketplace.js`, add an event listener to the filter controls.**+ - When a filter is changed, re-fetch the agent list from the API, appending the new query parameter.+ - Re-render the agent grid with the filtered results.++## Code Example (Frontend - Fetching with filter)+```javascript+// In marketplace.js+let currentPriceFilter = 'all'; // Default++document.getElementById('price-filters').addEventListener('change', (event) => {+ currentPriceFilter = event.target.value;+ fetchAgents();+});++async function fetchAgents() {+ let url = '/api/marketplace/agents';+ if (currentPriceFilter !== 'all') {+ url += `?price_filter=${currentPriceFilter}`;+ }++ const response = await fetch(url);+ const agents = await response.json();+ renderAgentGrid(agents);+}+```diff --git a/tasks/monetization-feature/22-skill-gating-preview.md b/tasks/monetization-feature/22-skill-gating-preview.mdnew file mode 100644index 000000000..46d36611c--- /dev/null+++ b/tasks/monetization-feature/22-skill-gating-preview.md@@ -0,0 +1,26 @@+---+status: not-started+---+# Prompt 22: Skill Gating and Previews++**Status:** Not Started++## Objective+Allow creators to offer a limited "preview" or trial of a paid skill to encourage purchases.++## Explanation+Letting users try before they buy can significantly increase conversion rates. This feature involves defining what a "preview" means (e.g., 3 free uses) and implementing the logic to track and enforce this limit.++## Instructions+1. **Backend: Modify the `agent_skill_prices` table.**+ - Add new columns: `is_trial_allowed BOOLEAN DEFAULT FALSE` and `trial_uses INTEGER DEFAULT 3`.+2. **Backend: Create a new table `skill_trial_usage`.**+ - Columns: `id`, `agent_id`, `skill_id`, `uses_left`.+3. **Backend: Update the skill execution logic (from Prompt 15).**+ - If a skill is paid and not purchased, check if a trial is allowed and if the agent has remaining trial uses.+ - If so, allow execution and decrement the `uses_left` in `skill_trial_usage`.+ - If uses are 0, block execution and message "Your trial for this skill has ended. Please purchase to continue."+4. **Frontend: Update the Creator Dashboard** to allow creators to enable/disable trials for their skills.+5. **Frontend: Update the Marketplace UI.**+ - Display a "Trial available" badge on skills that offer a preview.+ - When a user tries a skill, show how many uses are left.diff --git a/tasks/monetization-feature/23-localization-currency.md b/tasks/monetization-feature/23-localization-currency.mdnew file mode 100644index 000000000..f19ccae9e--- /dev/null+++ b/tasks/monetization-feature/23-localization-currency.md@@ -0,0 +1,36 @@+---+status: not-started+---+# Prompt 23: Price Localization++**Status:** Not Started++## Objective+Display skill prices in the user's local currency (e.g., USD) in addition to the cryptocurrency (e.g., USDC).++## Explanation+Showing prices in a familiar fiat currency makes them easier for users to understand and can increase the likelihood of a purchase. This requires integrating a third-party API to fetch real-time conversion rates.++## Instructions+1. **Choose a currency conversion API** (e.g., CoinGecko, an exchange API).+2. **Backend: Create a new microservice or a cached API endpoint (`/api/prices/conversion-rates`)** that fetches the current price of SOL, USDC, etc., in USD.+ - Cache the results for 5-10 minutes to avoid hitting API rate limits.+3. **Frontend: In the marketplace, fetch the conversion rates from this new endpoint.**+4. **When rendering a price, calculate and display the USD equivalent.**+ - Store the conversion rates globally so you don't have to re-fetch on every render.+5. **Update the UI to show both prices, or allow the user to toggle.**++## Code Example (Frontend - displaying converted price)+```javascript+// Assume 'rates' is { "USDC": 1.00, "SOL": 150.25 }+// Assume 'price' is { amount: 1500000, currency_mint: "EPj..." (USDC) }++const cryptoAmount = price.amount / 1e6; // 1.5+const rate = rates['USDC']; // 1.00+const usdAmount = cryptoAmount * rate;++const priceDisplay = `${cryptoAmount.toFixed(2)} USDC (~$${usdAmount.toFixed(2)} USD)`;++// Render priceDisplay in the UI+```+This small change can significantly improve the user experience for a global audience.diff --git a/tasks/monetization-feature/24-notifications-on-purchase.md b/tasks/monetization-feature/24-notifications-on-purchase.mdnew file mode 100644index 000000000..8d9fb4d1c--- /dev/null+++ b/tasks/monetization-feature/24-notifications-on-purchase.md@@ -0,0 +1,44 @@+---+status: not-started+---+# Prompt 24: Purchase Notifications for Creators++**Status:** Not Started++## Objective+Implement a system to notify creators in real-time or via email when one of their skills is sold.++## Explanation+Instant feedback is highly motivating for creators. A notification system can encourage them to engage more with the platform and build more skills.++## Instructions+1. **Choose a notification delivery method.** Options include:+ - WebSockets for real-time in-app notifications.+ - An email service (e.g., SendGrid, Mailgun) for email notifications.+2. **Integrate the chosen service into your backend.**+3. **Modify the purchase fulfillment endpoint (`/api/skills/fulfill_purchase` from Prompt 6).**+4. **After successfully recording a purchase in the database, trigger the notification.**+ - Get the creator's user details (e.g., email address, or user ID for WebSocket targeting).+ - Send a notification with details like "Your skill '[Skill Name]' was just purchased!"++## Code Example (Backend - Conceptual Email Notification)+```javascript+// In fulfillPurchase, after the purchase is saved to DB+import { sendEmail } from './email-service';++// ...+await db.none('INSERT INTO skill_purchases ...');++// Get creator info+const skill = await db.one('SELECT name, creator_id FROM skills WHERE id = $1', skill_id);+const creator = await db.one('SELECT email FROM users WHERE id = $1', skill.creator_id);++// Send notification+await sendEmail({+ to: creator.email,+ subject: 'You made a sale!',+ body: `Congratulations! Your skill "${skill.name}" was just purchased on three.ws.`+});+// ...+```+This creates a positive feedback loop for creators.diff --git a/tasks/monetization-feature/25-refactor-skill-display-component.md b/tasks/monetization-feature/25-refactor-skill-display-component.mdnew file mode 100644index 000000000..b50badd2a--- /dev/null+++ b/tasks/monetization-feature/25-refactor-skill-display-component.md@@ -0,0 +1,45 @@+---+status: not-started+---+# Prompt 25: Refactor Skill Display Component++**Status:** Not Started++## Objective+Refactor the UI code that displays skills into a reusable component to be used across the Marketplace, Creator Dashboard, and My Agents pages.++## Explanation+You currently have similar but slightly different logic for displaying skills in multiple places. This leads to code duplication and makes future changes difficult. Creating a single, reusable function or component will improve code quality and maintainability.++## Instructions+1. **Create a new JavaScript file, e.g., `src/components/SkillBadge.js`.**+2. **Define a function, e.g., `createSkillBadge(skill, context)`, that generates the HTML for a single skill.**+ - `skill`: An object containing skill name, price info, ownership status, etc.+ - `context`: A string like `'marketplace'`, `'my-agents'`, or `'creator-dashboard'` to determine which buttons/info to show (e.g., show "Set Price" button in creator context).+3. **Move all the conditional rendering logic** (free/paid, owned, purchase button, price) into this function.+4. **Import and use this function in `marketplace.js`, `creator-dashboard.js`, and your "My Agents" script.**+5. This simplifies the rendering loops in those files to something like:+ `container.innerHTML = skills.map(s => createSkillBadge(s, 'marketplace')).join('')`++## Code Example (`src/components/SkillBadge.js`)+```javascript+export function createSkillBadge(skill, context = 'marketplace') {+ const { name, price, isOwned, isCreator } = skill;+ let actionsHtml = '';++ if (context === 'creator-dashboard' && isCreator) {+ actionsHtml = `<button class="set-price-btn" data-skill-name="${name}">Set Price</button>`;+ } else if (price) {+ if (isOwned) {+ actionsHtml = `<span class="price-badge price-owned">Owned</span>`;+ } else {+ actionsHtml = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;+ }+ } else {+ actionsHtml = `<span class="price-badge price-free">Free</span>`;+ }++ return `<span class="skill-entry">${escapeHtml(name)}${actionsHtml}</span>`;+}+```+This refactoring makes the frontend codebase much cleaner and easier to manage.