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
chore: remove monetization planning docs
nirholas81ec6ce961ee
diff --git a/docs/monetization/01-db-schema-for-skill-pricing.md b/docs/monetization/01-db-schema-for-skill-pricing.mddeleted file mode 100644index bed30a7e8..000000000--- a/docs/monetization/01-db-schema-for-skill-pricing.md+++ /dev/null@@ -1,84 +0,0 @@-----status: completed-completed_at: 2026-05-04T12:01:00Z-----# Prompt 1: Database Schema for Skill Monetization--## Objective-Design and create the necessary database tables to support pricing skills and tracking user purchases.--## Explanation-To monetize agent skills, we first need a robust database structure. This involves creating two primary tables: one to store the prices set by creators for their agent skills (`agent_skill_prices`) and another to record which users have purchased which skills (`user_skill_purchases`). This foundational schema is critical for all subsequent monetization features.--## Instructions-1. **Design the Schema:**- * **`agent_skill_prices` table:**- * `agent_id`: Foreign key to the `agents` table.- * `skill_name`: The name of the skill being priced (e.g., "translate", "summarize-document").- * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or 10^-6 for USDC). Use a `bigint` for precision.- * `currency_mint`: The mint address of the SPL token for the price (e.g., `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6f` for USDC).- * `created_at`, `updated_at`: Standard timestamps.- * Define a composite primary key on `(agent_id, skill_name)`.- * **`user_skill_purchases` table:**- * `user_id`: Foreign key to the `users` table.- * `agent_id`: Foreign key to the `agents` table.- * `skill_name`: The name of the purchased skill.- * `purchase_tx_signature`: The transaction signature from the on-chain payment.- * `amount_paid`, `currency_mint`: The actual price paid.- * `purchased_at`: Timestamp of the purchase.- * Define a composite primary key on `(user_id, agent_id, skill_name)`.--2. **Write the SQL Migration:**- * Create a new SQL migration file in your migrations directory.- * Write the `CREATE TABLE` statements for both tables designed above.- * Include appropriate indexing for foreign keys to ensure query performance.--## Example SQL Migration--```sql--- migration-YYYYMMDDHHMMSS-create-monetization-tables.sql--CREATE TABLE agent_skill_prices (- agent_id BIGINT NOT NULL,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (agent_id, skill_name),- CONSTRAINT fk_agent- FOREIGN KEY(agent_id)- REFERENCES agents(id)- ON DELETE CASCADE-);--CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);--CREATE TABLE user_skill_purchases (- user_id BIGINT NOT NULL,- agent_id BIGINT NOT NULL,- skill_name VARCHAR(255) NOT NULL,- purchase_tx_signature VARCHAR(255) NOT NULL,- amount_paid BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- purchased_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- PRIMARY KEY (user_id, agent_id, skill_name),- CONSTRAINT fk_user- FOREIGN KEY(user_id)- REFERENCES users(id)- ON DELETE CASCADE,- CONSTRAINT fk_agent- FOREIGN KEY(agent_id)- REFERENCES agents(id)- ON DELETE CASCADE-);--CREATE INDEX idx_user_skill_purchases_user_id ON user_skill_purchases(user_id);-CREATE UNIQUE INDEX idx_user_skill_purchases_tx_signature ON user_skill_purchases(purchase_tx_signature);--```--## Definition of Done-- A new SQL migration file with the `CREATE TABLE` statements for `agent_skill_prices` and `user_skill_purchases` is created.-- The migration has been successfully applied to the development database.-- The schema includes primary keys, foreign keys, and indexes as specified.diff --git a/docs/monetization/01-display-priced-skills.md b/docs/monetization/01-display-priced-skills.mddeleted file mode 100644index 898c69a71..000000000--- a/docs/monetization/01-display-priced-skills.md+++ /dev/null@@ -1,70 +0,0 @@-----status: completed------# Prompt 1: Display Priced Skills in Marketplace--## Objective-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.--## Explanation-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.--## Instructions-1. **Modify the Backend API:**- * Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.- * When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.- * Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.--2. **Update the Frontend UI:**- * In `src/marketplace.js`, find the `renderDetail` function.- * This function receives the agent object, which now includes `skill_prices`.- * Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.- * If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).- * Style the price badge to be visually distinct.--## Code Example (Frontend - `src/marketplace.js`)--Here's how you might modify the skill rendering part within the `renderDetail` function:--```javascript-// Inside renderDetail function--const skillPrices = a.skill_prices || {};-$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;- }).join(' ')- : '<div>This Agent has no skills defined.</div>';-```--## CSS Example--Add these styles to `/marketplace.css` to make the price badges look good.--```css-.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/docs/monetization/01_display_priced_skills.md b/docs/monetization/01_display_priced_skills.mddeleted file mode 100644index 3f2cbd848..000000000--- a/docs/monetization/01_display_priced_skills.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 01: Display Priced Skills in Marketplace--## Objective-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.--## Explanation-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.--## Instructions-1. **Modify the Backend API:**- * Locate the API endpoint that serves the agent detail data (`/api/marketplace/agents/:id`). You can find this in `api/marketplace/[action].js`.- * When fetching agent details, also query the `agent_skill_prices` table to get the prices for the agent's skills.- * Join this pricing data with the agent details response. The agent object should now have a `skill_prices` map or object, like `{ "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.--2. **Update the Frontend UI:**- * In `src/marketplace.js`, find the `renderDetail` function.- * This function receives the agent object, which now includes `skill_prices`.- * Inside the loop that renders the skills (`d-skills` element), check if a price exists for the current skill.- * If a price exists, render a price badge next to the skill name. Convert the amount from lamports (or the smallest unit) to a human-readable format (e.g., 1,000,000 lamports = 1 USDC).- * Style the price badge to be visually distinct.--## Code Example (Frontend - `src/marketplace.js`)--Here's how you might modify the skill rendering part within the `renderDetail` function:--```javascript-// Inside renderDetail function--const skillPrices = a.skill_prices || {};-$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- const badge = price- ? `<span class="price-badge price-paid">${(price.amount / 1e6).toFixed(2)} USDC</span>`- : `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;- }).join(' ')- : '<div>This Agent has no skills defined.</div>';-```--## CSS Example--Add these styles to `/marketplace.css` to make the price badges look good.--```css-.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/docs/monetization/02-add-purchase-button.md b/docs/monetization/02-add-purchase-button.mddeleted file mode 100644index e4786f97e..000000000--- a/docs/monetization/02-add-purchase-button.md+++ /dev/null@@ -1,81 +0,0 @@-----status: not-started------# Prompt 2: Add Purchase Button for Paid Skills--## Objective-On the agent detail page, display a "Purchase" button next to paid skills that the current user has not yet unlocked. This button will initiate the skill purchase flow.--## Explanation-Building on the previous step where we displayed skill prices, we now need to provide a clear call-to-action for users to buy these skills. This involves checking if the user already owns the skill and rendering a button accordingly. For this, we'll need to know which skills the user has unlocked.--## Instructions-- [ ] **Modify the Backend API:**- - [ ] The agent detail endpoint (`/api/marketplace/agents/:id`) needs to also return information about which skills the logged-in user has unlocked for that agent.- - [ ] You will need to query the `user_unlocked_skills` table (you will create this in a later prompt) using the current `user_id` and the `agent_id`.- - [ ] Include an `unlocked_skills` array of skill names in the API response for the currently logged in user.--- [ ] **Update the Frontend UI:**- - [ ] In `src/marketplace.js`, find the `renderDetail` function.- - [ ] When rendering the skills list, for each skill, check if it's priced and if it is NOT in the `unlocked_skills` array from the API response.- - [ ] If a skill is priced and not unlocked, render a "Purchase" button next to the price badge.- - [ ] If a skill is priced and IS unlocked, show an "Owned" badge.- - [ ] The purchase button should have a `data-skill-name` attribute to identify which skill is being purchased when clicked.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail function, an updated version of the skill rendering logic:--const skillPrices = a.skill_prices || {};-const unlockedSkills = new Set(a.unlocked_skills || []);--$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- let badge = '';-- if (price) {- if (unlockedSkills.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="purchase-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>- `;- }- } else {- badge = '<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--Add these styles for the button and owned badge to `/marketplace.css`:--```css-.purchase-btn {- margin-left: 8px;- padding: 2px 8px;- font-size: 10px;- font-weight: 600;- border-radius: 4px;- background-color: var(--accent);- color: white;- border: none;- cursor: pointer;-}--.price-owned {- color: #a7f3d0;- background-color: transparent;- border: 1px solid rgba(52, 211, 153, 0.3);-}-```diff --git a/docs/monetization/02-add-wallet-connect-button.md b/docs/monetization/02-add-wallet-connect-button.mddeleted file mode 100644index 511b7478a..000000000--- a/docs/monetization/02-add-wallet-connect-button.md+++ /dev/null@@ -1,76 +0,0 @@-# Prompt 2: Add "Connect Wallet" Button--## Status-- [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.--## Explanation-Before a user can purchase a skill, they must connect their Solana wallet. This prompt focuses on adding the UI element for wallet connection and setting up the initial event listeners. The actual wallet connection logic will be handled in a subsequent step.--## Instructions-1. **Update the main HTML layout:**- * Locate the primary header or navigation component in `app.html`.- * Add a new button with the ID `connect-wallet-btn`.- * Initially, the button text should be "Connect Wallet". After a successful connection, this text will change to the user's wallet address.--2. **Create a dedicated wallet management module:**- * Create a new file: `src/wallet.js`.- * This module will encapsulate all wallet-related functionality (connecting, disconnecting, getting the current user's address, etc.).- * Create an initialization function, e.g., `initWalletButton`, that adds a click event listener to the new button.--3. **Integrate the wallet module into the main application:**- * In your main application entry point (`src/main.js` or similar), import and call the `initWalletButton` function to activate the button.--## Code Example (app.html)-```html-<!-- Inside the header element -->-<div class="header-actions">- <button id="connect-wallet-btn">Connect Wallet</button>-</div>-```--## Code Example (src/wallet.js)-```javascript-// src/wallet.js--// Placeholder for wallet adapter logic-let wallet;--function onConnectWallet() {- console.log('Attempting to connect wallet...');- // The actual connection logic will be implemented in the next prompt.- // For now, we can simulate a successful connection.- const mockAddress = 'YourWalletAddress...';- updateWalletState(mockAddress);-}--export function updateWalletState(address) {- const btn = document.getElementById('connect-wallet-btn');- if (address) {- // Display shortened address- btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;- } else {- btn.textContent = 'Connect Wallet';- }-}--export function initWalletButton() {- const btn = document.getElementById('connect-wallet-btn');- if (btn) {- btn.addEventListener('click', onConnectWallet);- }-}-```--## Code Example (src/main.js)-```javascript-// src/main.js-import { initWalletButton } from './wallet.js';--document.addEventListener('DOMContentLoaded', () => {- // ... other initializations- initWalletButton();-});-```diff --git a/docs/monetization/02-api-set-skill-price.md b/docs/monetization/02-api-set-skill-price.mddeleted file mode 100644index 75dcc2f98..000000000--- a/docs/monetization/02-api-set-skill-price.md+++ /dev/null@@ -1,84 +0,0 @@-# Prompt 2: API for Creators to Set Skill Prices--## Objective-Create a secure API endpoint for agent creators to set, update, and remove prices for their skills.--## Explanation-To enable monetization, creators need a way to manage the prices of their skills. This endpoint will allow them to programmatically define which skills are paid and how much they cost. It must be secure, ensuring only the agent's owner can modify prices.--## Instructions-1. **Create API Route:**- * Set up a new route: `POST /api/agents/:id/skills/price`.- * This route should handle setting or updating the price for a single skill.--2. **Authentication and Authorization:**- * Protect this endpoint. Ensure that a user is authenticated.- * Verify that the authenticated user is the owner of the agent specified by `:id`. If not, return a `403 Forbidden` error.--3. **Request Body Validation:**- * The request body should be a JSON object with the following structure:- ```json- {- "skill_name": "your-skill-name",- "amount": 1000000,- "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"- }- ```- * Validate the `skill_name`, `amount` (must be a non-negative integer), and `currency_mint`.--4. **Database Interaction:**- * Implement logic to "upsert" this data into 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.- * If `amount` is `0` or `null`, you should delete the corresponding row from `agent_skill_prices` to make the skill free again.--5. **Response:**- * On success, return a `200 OK` status with a confirmation message.- * On failure (validation, auth, etc.), return an appropriate error status and message.--## Code Example (Backend - `api/agents/[id]/skills/price.js`)--```javascript-// Example using an Express-like framework--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- const { id: agentId } = req.query;- const { skill_name, amount, currency_mint } = req.body;-- // 1. Get authenticated user (e.g., from a session or token)- const user = await getAuthenticatedUser(req);- if (!user) {- return res.status(401).json({ error: 'Unauthorized' });- }-- // 2. Verify ownership of the agent- const agent = await db.getAgentById(agentId);- if (!agent || agent.creator_id !== user.id) {- return res.status(403).json({ error: 'Forbidden' });- }-- // 3. Validate input- if (!skill_name || !currency_mint || amount == null || amount < 0) {- return res.status(400).json({ error: 'Invalid input' });- }-- try {- // 4. Upsert or delete price in the database- if (amount > 0) {- await db.upsertSkillPrice({ agent_id: agentId, skill_name, amount, currency_mint });- } else {- await db.deleteSkillPrice({ agent_id: agentId, skill_name });- }-- // 5. Return success- 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/docs/monetization/02-backend-create-skill-pricing-table.md b/docs/monetization/02-backend-create-skill-pricing-table.mddeleted file mode 100644index bc1daa91c..000000000--- a/docs/monetization/02-backend-create-skill-pricing-table.md+++ /dev/null@@ -1,63 +0,0 @@-----status: not-started------# Prompt 2: Backend - Create Skill Pricing Table--## Objective-Design and create the necessary database table to store pricing information for agent skills. This is a foundational step for all monetization features.--## Explanation-To make skills purchasable, we need a dedicated table in our PostgreSQL database (`agent_skill_prices`) that links a skill to an agent, and specifies its price and currency. This table will be the source of truth for all skill pricing on the platform.--## Instructions-1. **Design the Table Schema:**- * The table should be named `agent_skill_prices`.- * It needs columns to link to the agent (`agent_id`) and to identify the skill (`skill_id` or `skill_name`). Using `skill_name` (e.g., a `TEXT` or `VARCHAR` field) can simplify lookups, assuming skill names are unique per agent.- * It must have a column for the price amount (e.g., `amount` as `BIGINT` to store lamports or other smallest currency units).- * It must have a column for the currency (e.g., `currency_mint` as `TEXT` to store the Solana mint address of the currency, like USDC).- * Add a primary key and foreign key constraints to `agent_identities`.- * Create a unique constraint on (`agent_id`, `skill_name`) to prevent duplicate price entries for the same skill on the same agent.--2. **Create a SQL Migration File:**- * Create a new SQL file in a migrations directory (if one exists, otherwise you can place it in `scripts/migrations/`).- * Write the `CREATE TABLE` statement for `agent_skill_prices`.- * Include standard columns like `created_at` and `updated_at`.--## Code Example (SQL)--```sql--- scripts/migrations/002_create_agent_skill_prices.sql--CREATE TABLE IF NOT EXISTS agent_skill_prices (- id SERIAL PRIMARY KEY,- agent_id INTEGER NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- -- Price in the smallest denomination (e.g., lamports for SOL, or 10^-6 for USDC)- amount BIGINT NOT NULL CHECK (amount >= 0),- -- The mint address of the currency token (e.g., USDC, BONK, etc.)- currency_mint VARCHAR(44) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- -- An agent can only have one price per skill.- UNIQUE (agent_id, skill_name)-);---- Optional: Create an index for faster lookups-CREATE INDEX IF NOT EXISTS idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);---- Optional: Add a trigger to automatically update the updated_at timestamp-CREATE OR REPLACE FUNCTION set_updated_at_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 set_updated_at_timestamp();-```diff --git a/docs/monetization/02-creator-ui-set-prices.md b/docs/monetization/02-creator-ui-set-prices.mddeleted file mode 100644index 63e3fb80a..000000000--- a/docs/monetization/02-creator-ui-set-prices.md+++ /dev/null@@ -1,40 +0,0 @@-----status: completed------# Prompt 2: Creator UI to Set Skill Prices--## Objective-Create a user interface within the agent creation/editing page that allows creators to set and update prices for their agent's skills.--## Explanation-To enable skill monetization, creators need a way to manage the prices of their skills. This new UI will allow them to assign a price and currency to each skill, which will then be saved to the database.--## Instructions-1. **Modify the Agent Edit Page:**- * Locate the agent editing page, likely `agent-edit.html` or a similar file.- * Find the section where skills are listed or added.- * For each skill, add input fields for `price` and `currency`. The currency could be a dropdown (e.g., "USDC", "SOL").--2. **Handle Form Submission:**- * In the corresponding JavaScript file (e.g., `src/agent-edit.js`), update the form submission logic.- * When the creator saves the agent, collect the pricing information for each skill.- * Send this data to the backend API.--## Code Example (Frontend - `agent-edit.html`)--This is a conceptual example of what the new skill section might look like.--```html-<div id="skills-section">- <!-- Existing skill list -->- <div class="skill-item">- <span>Skill Name</span>- <input type="number" class="skill-price-input" placeholder="Price">- <select class="skill-currency-select">- <option value="USDC">USDC</option>- <option value="SOL">SOL</option>- </select>- </div>-</div>-```diff --git a/docs/monetization/02-display-priced-skills-api.md b/docs/monetization/02-display-priced-skills-api.mddeleted file mode 100644index 5c8fdf5fe..000000000--- a/docs/monetization/02-display-priced-skills-api.md+++ /dev/null@@ -1,87 +0,0 @@-----status: completed-completed_at: 2026-05-04T12:05:00Z-----# Prompt 2: Modify Agent Detail API to Include Skill Prices--## Objective-Enhance the backend API to include skill pricing information when fetching details for a specific agent.--## Explanation-Building on the new database schema, we need to make pricing data available to the frontend. The API endpoint that serves agent details for the marketplace (`/api/marketplace/agents/:id`) must be updated to join and include the prices for the skills associated with that agent.--## Instructions-1. **Locate the API Endpoint:**- * Find the code responsible for handling the `GET /api/marketplace/agents/:id` request. This is likely in a file such as `api/marketplace/[action].js` or a similar route handler.--2. **Update the Database Query:**- * In the function that fetches the agent's details from the database, add a `LEFT JOIN` to the `agent_skill_prices` table.- * The join condition should be on `agents.id = agent_skill_prices.agent_id`.--3. **Restructure the API Response:**- * The database query will likely return multiple rows for the same agent if it has multiple priced skills. You need to process these rows to build a single agent object.- * The final agent object sent to the frontend should have a new property, `skill_prices`.- * This `skill_prices` property should be an object (or map) where keys are the `skill_name` and values are objects containing the `amount` and `currency_mint`.--## Code Example (Backend API Handler)--Here's a conceptual example of how to modify the data retrieval and shaping logic.--```javascript-// Example using a hypothetical database client like 'db'--async function getAgentWithSkillPrices(agentId) {- const query = `- SELECT- a.*, -- all columns from agents table- sp.skill_name,- sp.amount,- sp.currency_mint- FROM- agents a- LEFT JOIN- agent_skill_prices sp ON a.id = sp.agent_id- WHERE- a.id = $1;- `;-- const { rows } = await db.query(query, [agentId]);-- if (rows.length === 0) {- return null; // or throw 404- }-- // Aggregate the pricing data- const agent = {- // Spread the first row to get agent properties- id: rows[0].id,- name: rows[0].name,- description: rows[0].description,- // ... other agent fields- skills: rows[0].skills, // Assuming skills are stored as a JSONB array- skill_prices: {}- };-- rows.forEach(row => {- if (row.skill_name && row.amount !== null) {- agent.skill_prices[row.skill_name] = {- amount: row.amount,- currency_mint: row.currency_mint- };- }- });-- return agent;-}--// In your API route handler:-// const agent = await getAgentWithSkillPrices(req.params.id);-// res.status(200).json(agent);-```--## Definition of Done-- The API endpoint `GET /api/marketplace/agents/:id` is updated.-- When an agent has priced skills, the JSON response now includes a `skill_prices` object.-- The `skill_prices` object contains an entry for each priced skill with its `amount` and `currency_mint`.-- If an agent has no priced skills, `skill_prices` should be an empty object `{}`.-- The endpoint continues to function correctly for agents with no skills or no priced skills.diff --git a/docs/monetization/02-purchase-skill-button.md b/docs/monetization/02-purchase-skill-button.mddeleted file mode 100644index 3c8d11f88..000000000--- a/docs/monetization/02-purchase-skill-button.md+++ /dev/null@@ -1,78 +0,0 @@-# Prompt 2: "Purchase Skill" Button--## Objective-Add a "Purchase" button to the agent detail page for skills that have a price. This button should be the primary call-to-action for monetizing skills.--## Explanation-Building on the previous prompt where we displayed the skill price, we now need to add an interactive element for users to initiate a purchase. The button should appear next to paid skills and should be disabled or hidden for skills the user already owns (though ownership functionality will be built in a later step).--## Instructions-1. **Update the Frontend UI (`src/marketplace.js`):**- * In the `renderDetail` function, where you iterate over skills, add a conditional button.- * If a skill has a price (`skillPrices[name]`), render a `<button>` element.- * For now, we will not implement the click handler, but we should add placeholder classes and data attributes that we'll use later to wire up the payment flow.- * Give the button a class like `purchase-skill-btn`.- * Store the skill's name in a data attribute, e.g., `data-skill-name="${name}"`.--2. **Style the Button (`marketplace.css`):**- * Add styling for the `purchase-skill-btn` to make it stand out.- * It should be visually appealing and clearly indicate that it's a purchase action. Use an accent color and consider adding an icon (e.g., a shopping cart or a lock icon).--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail function, modifying the skills 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];-- let actionHtml = '';- if (price) {- const priceInUsdc = (price.amount / 1e6).toFixed(2);- const priceBadge = `<span class="price-badge price-paid">${priceInUsdc} USDC</span>`;- // For now, isOwned is a placeholder. We will implement this logic later.- const isOwned = false;- if (isOwned) {- actionHtml = '<span class="skill-owned">✓ Owned</span>';- } else {- actionHtml = `<button class="purchase-skill-btn" data-skill-name="${escapeHtml(name)}">Purchase</button>`;- }- return `<span class="skill-entry">${escapeHtml(name)}${priceBadge}${actionHtml}</span>`;- } else {- const freeBadge = `<span class="price-badge price-free">Free</span>`;- return `<span class="skill-entry">${escapeHtml(name)}${freeBadge}</span>`;- }- }).join(' ')- : '<div>This Agent has no skills defined.</div>';-```--## CSS Example (`marketplace.css`)--```css-.purchase-skill-btn {- margin-left: 8px;- padding: 4px 10px;- font-size: 11px;- font-weight: 600;- border-radius: 5px;- background-color: var(--accent);- color: #fff;- border: 1px solid var(--accent);- cursor: pointer;- transition: background-color 0.2s;-}--.purchase-skill-btn:hover {- filter: brightness(1.1);-}--.skill-owned {- margin-left: 8px;- font-size: 11px;- color: #a7f3d0;- font-weight: 600;-}-```diff --git a/docs/monetization/02-skill-purchase-button.md b/docs/monetization/02-skill-purchase-button.mddeleted file mode 100644index 980daf83a..000000000--- a/docs/monetization/02-skill-purchase-button.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 2: Add Purchase Button for Paid Skills--## Objective-Add an "Unlock" or "Purchase" button next to paid skills on the agent detail page in the marketplace.--## Explanation-With prices now visible, the next logical step is to provide a clear call-to-action for users to initiate a purchase. This button will be the entry point into the skill acquisition flow.--## Instructions-1. **Update Frontend UI (`src/marketplace.js`):**- * In the `renderDetail` function, modify the loop that renders each skill.- * For skills that have a price, render a `<button>` element next to the price badge.- * The button should be labeled "Unlock" or "Purchase."- * Assign a `data-skill-name` attribute to the button, containing the name of the skill, to identify it in event listeners.- * Attach a click event listener to these buttons. For now, this listener can log to the console. It will be wired up to open a purchase modal in a later step.--2. **Add CSS for the Button:**- * In `/marketplace.css`, add styling for the new purchase button to make it visually distinct and interactive.--## Code Example (Frontend - `src/marketplace.js`)-```javascript-// Inside renderDetail's map function for skills...-const skillPrices = a.skill_prices || {};-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>`;-```--## CSS Example (`/marketplace.css`)-```css-.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;-}-```diff --git a/docs/monetization/02-ui-skill-pricing.md b/docs/monetization/02-ui-skill-pricing.mddeleted file mode 100644index 3b7bbd1c3..000000000--- a/docs/monetization/02-ui-skill-pricing.md+++ /dev/null@@ -1,68 +0,0 @@-----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/02-user-wallet-connection.md b/docs/monetization/02-user-wallet-connection.mddeleted file mode 100644index 590d78a92..000000000--- a/docs/monetization/02-user-wallet-connection.md+++ /dev/null@@ -1,111 +0,0 @@-----status: not-started-----# Prompt 2: User Wallet Connection--## Objective-Integrate a "Connect Wallet" feature into the marketplace header, allowing users to connect their Solana wallets to the application. This is a foundational step for enabling on-chain interactions like purchasing skills.--## Explanation-To allow users to purchase premium skills, they first need a way to connect their cryptocurrency wallet. We will use a vanilla JavaScript implementation compatible with the Solana wallet-adapter standards to present a "Connect Wallet" button. This will handle the core logic of connecting to browser-based wallets like Phantom.--## Instructions-- [ ] **Add a Wallet Library:**- - [ ] We will use a CDN version of a suitable library to simplify dependencies. Add this to `marketplace.html` in the `<head>` section:- ```html- <script src="https://unpkg.com/@solana/web3.js@latest/lib/index.iife.js"></script>- ```--- [ ] **Update the Marketplace Header:**- - [ ] In `marketplace.html`, add a "Connect Wallet" button to the header section. We will give it a unique ID to attach our script to it.- - [ ] `<button id="connectWalletBtn" class="connect-wallet-btn">Connect Wallet</button>`--- [ ] **Implement Wallet Connection Logic:**- - [ ] Create a new file `public/wallet-connector.js` to encapsulate the wallet connection logic.- - [ ] This script will check for the presence of a Solana wallet in the browser (like Phantom), handle the connection request, and update the UI to reflect the connection status.--## Code Example (`public/wallet-connector.js`)--```javascript-document.addEventListener('DOMContentLoaded', () => {- const connectWalletBtn = document.getElementById('connectWalletBtn');- let walletPublicKey = null;-- const getProvider = () => {- if ('phantom' in window) {- const provider = window.phantom?.solana;- if (provider?.isPhantom) {- return provider;- }- }- // Add other wallet providers here if needed- return null;- };-- const updateUI = () => {- if (walletPublicKey) {- const key = walletPublicKey.toBase58();- connectWalletBtn.textContent = `Connected: ${key.slice(0, 4)}...${key.slice(-4)}`;- connectWalletBtn.disabled = true;- } else {- connectWalletBtn.textContent = 'Connect Wallet';- connectWalletBtn.disabled = false;- }- };-- connectWalletBtn.addEventListener('click', async () => {- const provider = getProvider();- if (provider) {- try {- const resp = await provider.connect();- walletPublicKey = resp.publicKey;- updateUI();-- provider.on('disconnect', () => {- walletPublicKey = null;- updateUI();- });- } catch (err) {- console.error('Failed to connect to wallet', err);- alert('Could not connect to wallet. Please try again.');- }- } else {- alert('Solana wallet not found! Please install Phantom Wallet.');- window.open('https://phantom.app/', '_blank');- }- });-- // Check for eager connection- const provider = getProvider();- if (provider && provider.isConnected) {- // Will be null if not connected- walletPublicKey = provider.publicKey;- updateUI();- }-});-```--## CSS Example (`/public/marketplace.css`)--```css-.connect-wallet-btn {- background-color: var(--accent, #6a5cff);- color: white;- border: none;- padding: 8px 16px;- border-radius: 6px;- cursor: pointer;- font-weight: 600;- font-size: 13px;- transition: filter 0.15s ease;-}--.connect-wallet-btn:hover {- filter: brightness(1.1);-}--.connect-wallet-btn:disabled {- background-color: #3a3a4a;- cursor: not-allowed;-}-```diff --git a/docs/monetization/02_db_schema_for_pricing.md b/docs/monetization/02_db_schema_for_pricing.mddeleted file mode 100644index b846f4dd3..000000000--- a/docs/monetization/02_db_schema_for_pricing.md+++ /dev/null@@ -1,69 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 02: Database Schema for Skill Pricing--## Objective-Create the necessary database table to store prices for agent skills.--## Explanation-To allow creators to set prices for their skills, we need a dedicated table in our PostgreSQL database. This table will link an agent, a skill, and a price, defined by an amount and a currency. This structure allows for future flexibility, such as supporting multiple currencies.--## Instructions-1. **Design the Table:**- * Create a new table named `agent_skill_prices`.- * The table should have the following columns:- * `id`: Primary key (e.g., UUID or SERIAL).- * `agent_id`: Foreign key referencing the `agent_identities` table.- * `skill_name`: A text field to identify the skill. It should match the name defined in the agent's manifest.- * `amount`: A numeric or bigint type to store the price in the smallest denomination of the currency (e.g., lamports for Solana tokens).- * `currency_mint`: A text field to store the mint address of the currency (e.g., the USDC mint address on Solana).- * `created_at`: Timestamp of creation.- * `updated_at`: Timestamp of the last update.- * Add a unique constraint on (`agent_id`, `skill_name`) to ensure a skill only has one price per agent.--2. **Write the SQL Migration:**- * Create a new SQL migration file.- * Write the `CREATE TABLE` statement according to the design above.- * Include commands to create indexes on `agent_id` for efficient lookups.--## SQL Example--Here is the PostgreSQL `CREATE TABLE` statement.--```sql-CREATE TABLE IF NOT EXISTS agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL CHECK (amount > 0),- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- CONSTRAINT fk_agent- FOREIGN KEY(agent_id)- REFERENCES agent_identities(id)- ON DELETE CASCADE,-- UNIQUE (agent_id, skill_name)-);--CREATE INDEX idx_agent_skill_prices_agent_id ON agent_skill_prices(agent_id);---- Optional: Create a trigger to auto-update 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();--```diff --git a/docs/monetization/03-backend-api-set-prices.md b/docs/monetization/03-backend-api-set-prices.mddeleted file mode 100644index 54bbad60e..000000000--- a/docs/monetization/03-backend-api-set-prices.md+++ /dev/null@@ -1,48 +0,0 @@-----status: not-started------# Prompt 3: Backend API to Set Skill Prices--## Objective-Implement a secure backend API endpoint that allows agent creators to save and update the prices for their skills.--## Explanation-This API will receive the pricing information from the creator UI and persist it in the database. It's crucial that this endpoint is secure and only allows the agent's owner to modify the prices.--## Instructions-1. **Create a New API Endpoint:**- * Create a new API endpoint, for example, `POST /api/agents/:id/skills/prices`.- * This endpoint should be protected and require authentication. Ensure that the authenticated user is the owner of the agent.--2. **Implement the Logic:**- * The endpoint will receive a payload containing the skill prices, like ` { "skill_name": { "amount": 1000000, "currency_mint": "EPjFWdd..." } }`.- * Validate the input data to ensure it's in the correct format.- * In the database, update or insert the new prices in the `agent_skill_prices` table, associating them with the agent and the specific skills.--## Code Example (Backend - Express.js like)--```javascript-// POST /api/agents/:id/skills/prices-router.post('/:id/skills/prices', async (req, res) => {- const { id } = req.params;- const { prices } = req.body;- const userId = req.session.userId;-- // 1. Authenticate and authorize the user- const agent = await db.getAgentById(id);- if (!agent || agent.owner_id !== userId) {- return res.status(403).json({ error: 'Forbidden' });- }-- // 2. Validate the pricing data- if (!prices) {- return res.status(400).json({ error: 'Invalid input' });- }-- // 3. Save the prices to the database- await db.saveSkillPrices(id, prices);-- res.status(200).json({ success: true });-});-```diff --git a/docs/monetization/03-backend-api-set-skill-prices.md b/docs/monetization/03-backend-api-set-skill-prices.mddeleted file mode 100644index b5059d1dc..000000000--- a/docs/monetization/03-backend-api-set-skill-prices.md+++ /dev/null@@ -1,97 +0,0 @@-----status: not-started------# Prompt 3: Backend - API to Set/Update Skill Prices--## Objective-Create a secure backend API endpoint that allows an agent's creator to set or update the price of their skills.--## Explanation-With the database table in place, we now need a way for creators to manage their skill prices programmatically. This requires an authenticated API endpoint that accepts pricing information and updates the `agent_skill_prices` table. The endpoint must verify that the user making the request is the owner of the agent.--## Instructions-1. **Create the API Endpoint File:**- * Create a new file in the API directory, for example, `api/agents/skills.js`. This can be a Vercel serverless function.- * This endpoint should handle `POST` or `PUT` requests to a path like `/api/agents/[agentId]/skills/prices`.--2. **Implement Authentication and Authorization:**- * The endpoint must be authenticated. Use your existing authentication middleware (e.g., checking for a valid JWT or session cookie) to get the `user_id` of the requester.- * Before making any database changes, verify that the `user_id` owns the `agentId` specified in the URL. You'll need to query the `agent_identities` table. If they are not the owner, return a `403 Forbidden` error.--3. **Handle the Request Body:**- * The request body should contain the skill's name, the price amount (in lamports), and the currency mint address.- * Example body: `{ "skill_name": "Jupiter Swapper", "amount": 1000000, "currency_mint": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T" }`- * Validate the input. Ensure `amount` is a non-negative number and `currency_mint` is a valid Solana public key format.--4. **Implement the Database Logic:**- * Use an `INSERT ... ON CONFLICT` (UPSERT) statement to either create a new price entry or update an existing one for the given `agent_id` and `skill_name`.- * The `ON CONFLICT (agent_id, skill_name) DO UPDATE` clause makes the logic simple and atomic.--5. **Return a Response:**- * If successful, return a `200 OK` or `201 Created` status with the newly created/updated pricing information.- * Return appropriate error codes for bad input (`400`), unauthorized access (`403`), or server errors (`500`).--## Code Example (Vercel Serverless Function - `api/agents/skills.js`)--```javascript-import { cors, json, method, wrap } from '../_lib/http.js';-import { getAuth } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';--export default wrap(async (req, res) => {- if (cors(req, res)) return;- if (!method(req, res, ['POST'])) return;-- // 1. Authentication- const auth = await getAuth(req);- if (!auth.userId) {- return json(res, 401, { error: 'Authentication required' });- }-- // 2. Extract agentId and validation- const { agentId } = req.query;- if (!agentId) {- return json(res, 400, { error: 'Agent ID is required' });- }-- const [agent] = await sql`- SELECT user_id FROM agent_identities WHERE id = ${agentId}- `;-- if (!agent) {- return json(res, 404, { error: 'Agent not found' });- }-- // 3. Authorization- if (agent.user_id !== auth.userId) {- return json(res, 403, { error: 'You do not own this agent' });- }-- // 4. Input validation- const { skill_name, amount, currency_mint } = req.body;- if (!skill_name || typeof amount !== 'number' || amount < 0 || !currency_mint) {- return json(res, 400, { error: 'Invalid input: skill_name, amount, and currency_mint are required.' });- }-- // 5. Database UPSERT- try {- const [price] = 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()- RETURNING *- `;- return json(res, 200, { price });- } catch (error) {- console.error('Failed to set skill price:', error);- return json(res, 500, { error: 'Internal Server Error' });- }-});-```diff --git a/docs/monetization/03-creator-api-set-skill-price.md b/docs/monetization/03-creator-api-set-skill-price.mddeleted file mode 100644index 2de31ab21..000000000--- a/docs/monetization/03-creator-api-set-skill-price.md+++ /dev/null@@ -1,95 +0,0 @@-----status: not-started-completed_at: null-----# Prompt 3: Creator API to Set/Update Skill Prices--## Objective-Create a secure backend API endpoint that allows agent creators to set, update, or remove the price for their agent's skills.--## Explanation-To enable a creator-driven economy, we need to provide the tools for creators to manage their offerings. This prompt focuses on building the backend endpoint that will power the UI for pricing skills in the Creator Dashboard. The endpoint must be secure, ensuring only the agent's owner can modify prices.--## Instructions-1. **Define the API Endpoint:**- * Create a new API route: `POST /api/creator/agents/:agentId/skills/price`.- * This endpoint will handle creating, updating, and deleting skill prices.--2. **Implement Authentication and Authorization:**- * The endpoint must be protected. Ensure you have middleware that verifies the user is authenticated (e.g., checks for a valid session cookie or JWT).- * Implement an authorization check. Before processing the request, verify that the authenticated user is the owner of the `agentId` specified in the URL. If not, return a `403 Forbidden` error.--3. **Handle the Request Body:**- * The request body should contain:- * `skill_name`: The name of the skill to price.- * `amount` (optional): The price in the smallest currency unit. If `null` or `0`, it implies the skill is being made free (price is being removed).- * `currency_mint` (optional): The SPL token mint address. Required if `amount` is greater than 0.--4. **Implement Database Logic:**- * **If `amount` is positive:**- * Use an `UPSERT` (or `INSERT ... ON CONFLICT UPDATE`) operation on the `agent_skill_prices` table.- * Match on the composite primary key `(agent_id, skill_name)`.- * If a record exists, `UPDATE` the `amount` and `currency_mint`.- * If no record exists, `INSERT` a new row.- * **If `amount` is `null`, `0`, or not provided:**- * `DELETE` the corresponding row from the `agent_skill_prices` table for that `agent_id` and `skill_name`.--5. **Return a Response:**- * On success, return a `200 OK` or `204 No Content` response.- * On validation failure (e.g., missing `currency_mint` for a paid skill), return a `400 Bad Request`.--## Code Example (Backend API Handler)--```javascript-// Example using Express.js and a hypothetical 'db' client--// Assume 'authMiddleware' and 'agentOwnershipMiddleware' exist and are applied to this route.-app.post('/api/creator/agents/:agentId/skills/price', async (req, res) => {- const { agentId } = req.params;- const { skill_name, amount, currency_mint } = req.body;-- // Basic validation- if (!skill_name) {- return res.status(400).json({ error: 'skill_name is required.' });- }-- const numericAmount = amount ? BigInt(amount) : 0n;-- if (numericAmount > 0n && !currency_mint) {- return res.status(400).json({ error: 'currency_mint is required for paid skills.' });- }-- try {- if (numericAmount > 0n) {- // Upsert logic- 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 = CURRENT_TIMESTAMP;- `;- await db.query(query, [agentId, skill_name, numericAmount, currency_mint]);- } else {- // Delete logic (make skill free)- const query = `- DELETE FROM agent_skill_prices- WHERE agent_id = $1 AND skill_name = $2;- `;- await db.query(query, [agentId, skill_name]);- }-- res.status(204).send();-- } catch (error) {- console.error('Failed to update skill price:', error);- res.status(500).json({ error: 'An internal error occurred.' });- }-});-```--## Definition of Done-- A new `POST` endpoint at `/api/creator/agents/:agentId/skills/price` is created and functional.-- The endpoint correctly requires authentication.-- The endpoint correctly verifies that the user owns the agent before making changes.-- The endpoint can successfully create, update, and delete entries in the `agent_skill_prices` table based on the request body.-- Appropriate error responses (`400`, `403`, `500`) are returned in failure cases.diff --git a/docs/monetization/03-implement-solana-wallet-connection.md b/docs/monetization/03-implement-solana-wallet-connection.mddeleted file mode 100644index 530b0d07d..000000000--- a/docs/monetization/03-implement-solana-wallet-connection.md+++ /dev/null@@ -1,89 +0,0 @@-# Prompt 3: Implement Solana Wallet Connection--## Status-- [ ] Not Started--## Objective-Implement the core logic for connecting to a user's Solana wallet using a standard wallet adapter library like `@solana/wallet-adapter-base` and `@solana/wallet-adapter-wallets`.--## Explanation-This prompt builds on the previous one by implementing the functionality behind the "Connect Wallet" button. We will use the Solana Wallet Adapter libraries to present the user with a list of installed wallets (e.g., Phantom, Solflare) and manage the connection state.--## Instructions-1. **Install Dependencies:**- * Add the necessary Solana wallet adapter libraries to your project's `package.json` and install them.- * You'll typically need `@solana/web3.js`, `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and specific wallet adapters you wish to support.--2. **Update the Wallet Module (`src/wallet.js`):**- * Import the wallet adapter classes.- * Instantiate the wallets you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).- * Implement the `onConnectWallet` function to trigger the wallet adapter's connect flow. This will typically open a modal for the user to select their wallet.- * Listen for changes in the wallet's connection status and update the UI accordingly using the `updateWalletState` function created previously.--## Code Example (Terminal - Installation)-```bash-npm install @solana/web3.js @solana/wallet-adapter-base @solana/wallet-adapter-wallets @solana/wallet-adapter-phantom-```--## Code Example (src/wallet.js)-```javascript-// src/wallet.js-import { PhantomWalletAdapter } from '@solana/wallet-adapter-phantom';-import { Connection, PublicKey } from '@solana/web3.js';--let connectedWalletAddress = null;--// Initialize the wallet adapter-const wallet = new PhantomWalletAdapter();--// Listen for connection events-wallet.on('connect', (publicKey) => {- connectedWalletAddress = publicKey.toBase58();- console.log(`Wallet connected: ${connectedWalletAddress}`);- updateWalletState(connectedWalletAddress);-});--wallet.on('disconnect', () => {- console.log('Wallet disconnected');- connectedWalletAddress = null;- updateWalletState(null);-});--async function onConnectWallet() {- if (!wallet.connected) {- try {- await wallet.connect();- } catch (error) {- console.error('Wallet connection failed:', error);- }- }-}--export function updateWalletState(address) {- const btn = document.getElementById('connect-wallet-btn');- if (address) {- btn.textContent = `${address.slice(0, 4)}...${address.slice(-4)}`;- } else {- btn.textContent = 'Connect Wallet';- }-}--export function initWalletButton() {- const btn = document.getElementById('connect-wallet-btn');- if (btn) {- btn.addEventListener('click', onConnectWallet);- }- // Auto-connect if wallet is already connected- if (wallet.autoConnect) {- wallet.autoConnect();- }-}--export function getConnectedWallet() {- return wallet.connected ? wallet : null;-}--export function getConnectedWalletAddress() {- return connectedWalletAddress;-}-```diff --git a/docs/monetization/03-purchase-flow-ui.md b/docs/monetization/03-purchase-flow-ui.mddeleted file mode 100644index 13d55fe60..000000000--- a/docs/monetization/03-purchase-flow-ui.md+++ /dev/null@@ -1,63 +0,0 @@-# Prompt 3: Implement Purchase Flow UI Modal--## Objective-Create a modal dialog that appears when a user clicks the "Unlock" button for a paid skill, presenting the details of the purchase and asking for confirmation.--## Explanation-A modal is a standard and effective way to handle a confirmation flow without navigating the user away from the current page. This modal will serve as the main interface for the skill purchase process, containing all necessary information for the user to make a decision.--## Instructions-1. **Create Modal HTML:**- * In `marketplace.html`, add the HTML structure for a hidden modal.- * The modal should include a title, a section to display the skill name and price, a "Confirm Purchase" button, and a "Cancel" button or close icon.--2. **Implement Modal Logic (`src/marketplace.js`):**- * Create functions to `showModal()` and `hideModal()`.- * Modify the event listener for the `.purchase-btn` clicks.- * When a purchase button is clicked, extract the skill name and price from the agent data.- * Populate the modal with the specific skill's details.- * Call `showModal()` to display it.- * Add event listeners to the "Cancel" and "Confirm Purchase" buttons within the modal.--## Code Example (HTML - `marketplace.html`)-```html-<!-- Add this inside the <body> tag -->-<div id="purchase-modal" class="modal-hidden">- <div class="modal-content">- <span class="close-button">×</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>-```--## Code Example (JavaScript - `src/marketplace.js`)-```javascript-// Add event listener for purchase buttons (delegated)-document.addEventListener('click', (e) => {- if (e.target.matches('.purchase-btn')) {- const skillName = e.target.dataset.skillName;- const agent = getCurrentAgentData(); // Assume this function gets the current agent's full data- const price = agent.skill_prices[skillName];-- // Populate and show the modal- document.getElementById('modal-skill-name').textContent = skillName;- document.getElementById('modal-skill-price').textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;- document.getElementById('purchase-modal').classList.remove('modal-hidden');- }-});--// Logic to hide modal-document.querySelector('.close-button').addEventListener('click', () => {- document.getElementById('purchase-modal').classList.add('modal-hidden');-});-```--## CSS Example (`/marketplace.css`)-```css-.modal-hidden { display: none; }-/* Add styles for modal backdrop, content, etc. */-```diff --git a/docs/monetization/03-purchase-modal-ui.md b/docs/monetization/03-purchase-modal-ui.mddeleted file mode 100644index bb11a632b..000000000--- a/docs/monetization/03-purchase-modal-ui.md+++ /dev/null@@ -1,80 +0,0 @@-----status: not-started------# Prompt 3: Purchase Modal UI--## Objective-Create a reusable modal component for the skill purchase flow, which will serve as the container for payment steps.--## Explanation-When a user clicks the "Purchase" button, we shouldn't immediately trigger a wallet transaction. Instead, we should present them with a clear, focused modal window that confirms their intent and guides them through the payment process. This modal will initially show the skill details and price, and will later host the wallet connection and payment confirmation steps.--## Instructions-- [ ] **Create the Modal HTML Structure:**- - [ ] Add a generic modal structure to `marketplace.html`. It should be hidden by default (`display: none`).- - [ ] The modal should have a backdrop, a main content area, a title, a close button, and a section for dynamic content.--- [ ] **Create the Modal CSS:**- - [ ] In `marketplace.css`, add styles for the modal, backdrop, and content area.- - [ ] Ensure it's centered, has a reasonable size, and is styled consistently with the rest of the application.--- [ ] **Implement Modal Logic:**- - [ ] In `src/marketplace.js`, add functions to `showModal(title, content)` and `hideModal()`.- - [ ] `showModal` should populate the modal's title and content sections and make it visible.- - [ ] `hideModal` should hide the modal. The close button and backdrop should trigger this function.- - [ ] Add an event listener to the `d-skills` container that listens for clicks on `.purchase-btn` buttons.- - [ ] When a purchase button is clicked, get the skill name from the `data-skill-name` attribute, then call `showModal` with the appropriate details to confirm the purchase.--## HTML Example (`marketplace.html`)--```html-<!-- Add this somewhere in your main container -->-<div id="purchase-modal" class="modal-backdrop" style="display: none;">- <div class="modal-content">- <div class="modal-header">- <h2 id="modal-title"></h2>- <button id="modal-close" class="modal-close-btn">×</button>- </div>- <div id="modal-body"></div>- </div>-</div>-```--## JavaScript Example (`src/marketplace.js`)--```javascript-// Function to show the modal-function showModal(title, content) {- $('modal-title').textContent = title;- $('modal-body').innerHTML = content;- $('purchase-modal').style.display = 'flex';-}--// Function to hide the modal-function hideModal() {- $('purchase-modal').style.display = 'none';-}--// Event listener for closing the modal-$('modal-close').addEventListener('click', hideModal);-$('purchase-modal').addEventListener('click', (e) => {- if (e.target.id === 'purchase-modal') {- hideModal();- }-});--// Event listener for the purchase buttons-$('d-skills').addEventListener('click', (e) => {- if (e.target.classList.contains('purchase-btn')) {- const skillName = e.target.dataset.skillName;- // Find the agent and skill details to show in the modal- // For now, a simple confirmation:- showModal(- `Purchase Skill: ${skillName}`,- `<p>You are about to purchase the skill "${skillName}".</p>- <button id="confirm-purchase-btn">Confirm</button>`- );- }-});-```diff --git a/docs/monetization/03-save-skill-prices.md b/docs/monetization/03-save-skill-prices.mddeleted file mode 100644index 71a9fd414..000000000--- a/docs/monetization/03-save-skill-prices.md+++ /dev/null@@ -1,106 +0,0 @@-----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/docs/monetization/03-skill-purchase-flow-ui.md b/docs/monetization/03-skill-purchase-flow-ui.mddeleted file mode 100644index db82ef516..000000000--- a/docs/monetization/03-skill-purchase-flow-ui.md+++ /dev/null@@ -1,117 +0,0 @@-# Prompt 3: Skill Purchase Flow UI--## Objective-Implement the UI flow for purchasing a skill. When a user clicks on a paid skill on the agent detail page, a confirmation modal should appear displaying the skill name, price, and a "Buy Now" button.--## Explanation-After connecting their wallet, the next step is for users to be able to initiate a purchase. This task focuses on creating the frontend modal that serves as the confirmation step before creating and sending the on-chain transaction. This modal prevents accidental purchases and provides a clear summary of the transaction to the user.--## Instructions-1. **Create the Purchase Modal HTML:**- * In `marketplace.html`, add the HTML structure for a modal dialog. It should be hidden by default.- * The modal should have placeholders for the skill name, price, and action buttons.--2. **Add Event Listeners:**- * In `src/marketplace.js`, modify the `renderDetail` function. When rendering skills, attach a click event listener to the skill entries.- * If a clicked skill is paid, the event listener should populate the purchase modal with the skill's data (name, price) and make the modal visible.--3. **Style the Modal:**- * In `/public/marketplace.css`, add CSS rules to style the modal, its backdrop, and content to match the site's aesthetic.--## HTML Example (`marketplace.html`)--```html-<!-- Add this somewhere inside the <body> tag -->-<div id="purchaseModal" class="modal-backdrop" style="display: none;">- <div class="modal-content">- <div class="modal-header">- <h2>Confirm Purchase</h2>- <button id="closePurchaseModal" class="modal-close-btn">×</button>- </div>- <div class="modal-body">- <p>You are about to purchase the skill:</p>- <h3 id="modalSkillName"></h3>- <p>Price:</p>- <h3 id="modalSkillPrice"></h3>- </div>- <div class="modal-footer">- <button id="confirmPurchaseBtn" class="modal-action-btn">Buy Now</button>- </div>- </div>-</div>-```--## JavaScript Logic (`src/marketplace.js`)--```javascript-// Inside renderDetail or a suitable scope-const purchaseModal = document.getElementById('purchaseModal');-const closePurchaseModalBtn = document.getElementById('closePurchaseModal');-const confirmPurchaseBtn = document.getElementById('confirmPurchaseBtn');-const modalSkillName = document.getElementById('modalSkillName');-const modalSkillPrice = document.getElementById('modalSkillPrice');--function openPurchaseModal(skillName, price) {- modalSkillName.textContent = skillName;- modalSkillPrice.textContent = `${(price.amount / 1e6).toFixed(2)} USDC`;- purchaseModal.style.display = 'flex';- // Store data for the next step- confirmPurchaseBtn.dataset.skillName = skillName;-}--function closePurchaseModal() {- purchaseModal.style.display = 'none';-}--closePurchaseModalBtn.addEventListener('click', closePurchaseModal);-window.addEventListener('click', (event) => {- if (event.target === purchaseModal) {- closePurchaseModal();- }-});--// In your skill rendering loop:-const skillEl = document.createElement('span');-skillEl.className = 'skill-entry';-// ... set content ...-if (price) {- skillEl.addEventListener('click', () => openPurchaseModal(name, price));-}-```--## CSS Example (`/public/marketplace.css`)--```css-.modal-backdrop {- position: fixed;- inset: 0;- background-color: rgba(0, 0, 0, 0.7);- display: flex;- align-items: center;- justify-content: center;- z-index: 1000;-}-.modal-content {- background: var(--panel, #14141c);- padding: 24px;- border-radius: 12px;- border: 1px solid var(--border, #1f1f29);- width: min(400px, 90vw);-}-.modal-header {- display: flex;- justify-content: space-between;- align-items: center;- border-bottom: 1px solid var(--border, #1f1f29);- padding-bottom: 12px;- margin-bottom: 12px;-}-.modal-header h2 { margin: 0; font-size: 18px; }-.modal-close-btn { background: none; border: none; color: #eee; font-size: 24px; cursor: pointer; }-.modal-footer { margin-top: 24px; text-align: right; }-.modal-action-btn {- background-color: var(--accent, #6a5cff);- color: white;- /* ... other button styles */-}-```diff --git a/docs/monetization/03-solana-pay-backend.md b/docs/monetization/03-solana-pay-backend.mddeleted file mode 100644index c5d2a9f35..000000000--- a/docs/monetization/03-solana-pay-backend.md+++ /dev/null@@ -1,110 +0,0 @@-# Prompt 3: Solana Pay Integration (Backend)--## Objective-Create a backend API endpoint that generates a Solana Pay transaction request when a user decides to purchase a skill.--## Explanation-To securely handle payments, we will use Solana Pay. This standard allows us to create a transaction on the backend and present it to the user's mobile wallet for approval. This prompt focuses on creating the API endpoint that prepares this transaction. The endpoint will receive a skill name, look up its price, and construct a transaction to transfer the correct amount of USDC from the buyer to the seller.--## Instructions-1. **Create a New API Endpoint:**- * In the `api/payments/` directory, create a new file named `prepare-skill-purchase.js`.- * This endpoint should handle `POST` requests and expect a `skillName` and `agentId` in the request body.--2. **Implement the Endpoint Logic:**- * The endpoint needs to perform several actions:- * Authenticate the user to identify the buyer.- * From the `agentId`, look up the agent and its creator.- * From the creator's profile, retrieve their payout wallet address.- * From `skillName` and `agentId`, query the `agent_skill_prices` table to get the skill's price (amount and currency). For now, we'll assume USDC.- * Construct a Solana transaction using the `@solana/web3.js` library to transfer the specified amount of USDC from the buyer to the creator.- * Return the transaction details in the format required by the Solana Pay spec. This includes the transaction itself (serialized), a message, and a label.--3. **Dependencies:**- * You will need to add `@solana/pay` and `@solana/spl-token` to your backend dependencies if they are not already present.--## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)--```javascript-// api/payments/prepare-skill-purchase.js-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';-import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db'; // Placeholder for DB functions--const USDC_MINT = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d');-const PLATFORM_WALLET = new PublicKey('YourPlatformWalletAddressHere'); // Your platform's treasury wallet--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- try {- // User must be authenticated (logic not shown)- const buyerPublicKey = new PublicKey(req.user.solana_wallet);-- const { agentId, skillName } = req.body;- if (!agentId || !skillName) {- return res.status(400).json({ error: 'agentId and skillName are required' });- }-- const priceInfo = await findSkillPrice(agentId, skillName);- if (!priceInfo) {- return res.status(404).json({ error: 'Skill or price not found' });- }-- const creatorPayoutWallet = await findCreatorPayoutWallet(agentId);- if (!creatorPayoutWallet) {- return res.status(500).json({ error: 'Creator payout wallet not configured' });- }-- const connection = new Connection(process.env.SOLANA_RPC_URL);- const { blockhash } = await connection.getLatestBlockhash();-- const transaction = new Transaction({- recentBlockhash: blockhash,- feePayer: buyerPublicKey,- });-- const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);- const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, new PublicKey(creatorPayoutWallet));-- // Assuming a 5% platform fee- const platformFee = Math.floor(priceInfo.amount * 0.05);- const creatorAmount = priceInfo.amount - platformFee;-- // Transfer to creator- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- creatorUsdcAddress,- buyerPublicKey,- creatorAmount- )- );-- // Transfer to platform- const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- platformUsdcAddress,- buyerPublicKey,- platformFee- )- );-- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });-- res.status(200).json({- transaction: serializedTransaction.toString('base64'),- message: `Purchase skill "${skillName}" for ${(priceInfo.amount / 1e6).toFixed(2)} USDC`,- label: 'three.ws Agent Skill',- });-- } catch (error) {- console.error('Error preparing skill purchase:', error);- res.status(500).json({ error: 'Internal Server Error' });- }-}-```diff --git a/docs/monetization/03-ui-manage-skill-prices.md b/docs/monetization/03-ui-manage-skill-prices.mddeleted file mode 100644index 3a6d3342e..000000000--- a/docs/monetization/03-ui-manage-skill-prices.md+++ /dev/null@@ -1,98 +0,0 @@-# Prompt 3: UI for Skill Price Management--## Objective-Create a user interface within the agent editing page that allows creators to easily set, update, and remove prices for their skills.--## Explanation-With the backend API in place, creators need a visual tool to manage their skill pricing. This UI will be added to the `agent-edit.html` page, providing an intuitive way to toggle a skill as "paid" and set its price without needing to interact with the API directly.--## Instructions-1. **Locate the Correct File:**- * Open `agent-edit.html`. This page contains the forms for editing an agent's properties.--2. **Add a "Monetization" Section:**- * Find where skills or agent profile prompts are rendered. This is likely in the "Publish" tab (`id="panel-publish"`).- * Add a new section for skill pricing. You could list the agent's available skills (fetched from the agent's metadata) and provide pricing controls for each.--3. **Implement UI Controls for Each Skill:**- * For each skill, display its name.- * Add a checkbox or toggle switch labeled "Paid Skill".- * When the "Paid Skill" toggle is enabled, show two input fields:- * An `input type="number"` for the `amount` (in a user-friendly unit like USDC, not lamports).- * A (potentially hidden or disabled) field for the `currency_mint`, which could default to USDC for now.- * When the toggle is disabled, hide the price inputs.--4. **Handle Form Submission:**- * When the creator saves their changes on the `agent-edit` page, your JavaScript should gather the pricing data for each skill.- * For each skill that is marked as "paid", make a call to the `POST /api/agents/:id/skills/price` endpoint created in the previous prompt.- * Remember to convert the user-friendly amount (e.g., 1.5 USDC) back to the base unit (e.g., 1,500,000 lamports for a 6-decimal currency) before sending it to the API.- * If a skill is marked as free (or was paid and is now free), send a request with `amount: 0` to remove the price.--## Code Example (Frontend - `agent-edit.html` script)--```javascript-// Inside the script tag of agent-edit.html--// Assume 'agent.skills' is an array of skill names and 'currentPrices' is a map from the API-function renderSkillPricingUI(skills, currentPrices) {- const container = document.getElementById('skill-pricing-container'); // You'll need to create this container- container.innerHTML = '<h3>Skill Pricing</h3>';-- skills.forEach(skillName => {- const price = currentPrices[skillName];- const isPaid = !!price;- const amountInUSDC = isPaid ? (price.amount / 1e6).toFixed(2) : '1.00';-- const skillRow = document.createElement('div');- skillRow.className = 'form-group skill-price-row';- skillRow.innerHTML = `- <label class="form-label">${escapeHtml(skillName)}</label>- <div class="skill-price-controls">- <input type="checkbox" class="paid-toggle" data-skill="${escapeHtml(skillName)}" ${isPaid ? 'checked' : ''}>- <span class="toggle-label">Paid</span>- <div class="price-inputs" style="${isPaid ? '' : 'display: none;'}">- <input type="number" class="price-amount" value="${amountInUSDC}" step="0.01" min="0">- <span>USDC</span>- </div>- </div>- `;- container.appendChild(skillRow);- });-- // Add event listeners for toggles- container.querySelectorAll('.paid-toggle').forEach(toggle => {- toggle.addEventListener('change', (e) => {- const inputs = e.target.closest('.skill-price-controls').querySelector('.price-inputs');- inputs.style.display = e.target.checked ? 'flex' : 'none';- });- });-}--// On save, you would iterate through these controls:-async function saveSkillPrices(agentId) {- const rows = document.querySelectorAll('.skill-price-row');- for (const row of rows) {- const toggle = row.querySelector('.paid-toggle');- const skillName = toggle.dataset.skill;- const amountInput = row.querySelector('.price-amount');-- let amountInLamports = 0;- if (toggle.checked) {- const amountInUSDC = parseFloat(amountInput.value);- if (!isNaN(amountInUSDC) && amountInUSDC > 0) {- amountInLamports = Math.round(amountInUSDC * 1e6); // Convert to lamports- }- }-- await fetch(`/api/agents/${agentId}/skills/price`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- skill_name: skillName,- amount: amountInLamports,- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // Assuming USDC- })- });- }-}-```diff --git a/docs/monetization/03_ui_for_setting_prices.md b/docs/monetization/03_ui_for_setting_prices.mddeleted file mode 100644index e7afcbad1..000000000--- a/docs/monetization/03_ui_for_setting_prices.md+++ /dev/null@@ -1,95 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 03: UI for Setting Skill Prices--## Objective-Create a user interface within the agent editor (`agent-edit.html`) that allows agent creators to set and update prices for their skills.--## Explanation-For creators to monetize their work, they need a simple and intuitive way to manage the prices of their skills. This task involves adding a new section to the agent editor page where each skill listed has an input field to set its price.--## Instructions-1. **Locate the Agent Editor:**- * Open `agent-edit.html` and its corresponding JavaScript module, likely `src/agent-edit.js`.--2. **Fetch Existing Prices:**- * When loading the agent for editing, the backend should also fetch and provide any existing prices from the `agent_skill_prices` table. The main agent object should be decorated with this information.--3. **Implement the UI:**- * In the section where the agent's skills are displayed, modify the rendering logic.- * For each skill, display an input field for the price and a dropdown or static text for the currency (initially, we can hardcode to USDC).- * The input should be pre-filled with the existing price if it has been set.- * Add a "Save Prices" button or integrate the price updates into the main "Save Agent" functionality.--## Code Example (HTML Structure in `agent-edit.html`)--This is a conceptual HTML structure. You will need to integrate it into the existing template.--```html-<!-- Inside the agent editor form -->-<div class="panel">- <h2 class="panel-title">Skill Monetization</h2>- <p class="panel-subtitle">Set prices for your agent's skills in USDC.</p>- <div id="skill-pricing-list">- <!-- JavaScript will render individual skill inputs here -->- </div>- <button id="save-skill-prices" class="btn">Save Prices</button>-</div>-```--## Code Example (JavaScript - `src/agent-edit.js`)--This is how you might render the pricing inputs.--```javascript-// Assume `agent` object has `skills` array and `skill_prices` map-const skills = agent.skills || [];-const prices = agent.skill_prices || {};-const container = document.getElementById('skill-pricing-list');--container.innerHTML = skills.map(skill => {- const price = prices[skill.name];- const amount = price ? (price.amount / 1e6).toFixed(2) : ''; // Convert from lamports- return `- <div class="skill-price-entry">- <label for="price-${skill.name}">${skill.name}</label>- <div class="price-input-wrapper">- <input- type="number"- id="price-${skill.name}"- data-skill-name="${skill.name}"- value="${amount}"- placeholder="e.g., 0.99"- min="0"- step="0.01"- />- <span class="currency-label">USDC</span>- </div>- </div>- `;-}).join('');--// Add an event listener to the save button to collect and send data-document.getElementById('save-skill-prices').addEventListener('click', () => {- const updatedPrices = {};- document.querySelectorAll('.price-input-wrapper input').forEach(input => {- const skillName = input.dataset.skillName;- const amount = parseFloat(input.value);- if (skillName && !isNaN(amount) && amount > 0) {- updatedPrices[skillName] = {- amount: Math.round(amount * 1e6), // Convert to lamports- currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a' // USDC mint- };- }- });-- // Send `updatedPrices` to a new API endpoint- fetch(`/api/agents/${agent.id}/skill-prices`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(updatedPrices)- });-});-```diff --git a/docs/monetization/04-backend-price-validation.md b/docs/monetization/04-backend-price-validation.mddeleted file mode 100644index c0038f237..000000000--- a/docs/monetization/04-backend-price-validation.md+++ /dev/null@@ -1,74 +0,0 @@-# Prompt 4: Backend Price Validation Logic--## Objective-Implement robust server-side validation for skill prices to ensure data integrity and prevent invalid pricing information from being stored.--## Explanation-While the frontend can guide users, the backend must be the ultimate authority on data validity. This prompt focuses on strengthening the `POST /api/agents/:id/skills/price` endpoint by adding comprehensive validation logic for the incoming price data.--## Instructions-1. **Locate the API Endpoint:**- * Open the file for the `POST /api/agents/:id/skills/price` endpoint (e.g., `api/agents/[id]/skills/price.js`).--2. **Enhance Validation Logic:**- * Before interacting with the database, ensure the request body contains all required fields (`skill_name`, `amount`, `currency_mint`).- * **Amount Validation:**- * Verify that `amount` is a non-negative integer. Floating-point numbers or negative values should be rejected with a `400 Bad Request` error.- * Consider setting a maximum allowed price to prevent abuse or user error (e.g., max 100,000,000,000 lamports or 100,000 USDC).- * **Currency Mint Validation:**- * Check if `currency_mint` is a valid Solana public key.- * For now, you might enforce that it must be the official USDC mint address on the target network (Mainnet or Devnet). Create a whitelist of accepted mints.- * **Skill Name Validation:**- * Verify that the `skill_name` provided in the request actually corresponds to a real skill defined in the agent's configuration. If not, reject the request.--3. **Return Specific Error Messages:**- * Provide clear and specific error messages in the JSON response when validation fails. This helps the frontend display meaningful error feedback to the user.- * Example error responses:- * `{ "error": "Amount must be a non-negative integer." }`- * `{ "error": "Invalid currency mint address." }`- * `{ "error": "Skill 'invalid-skill' not found for this agent." }`--## Code Example (Backend - API Endpoint)--```javascript-// Inside your /api/agents/:id/skills/price endpoint handler--// Whitelist of accepted currency mints-const ALLOWED_CURRENCIES = {- mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', // USDC Mainnet- devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU', // USDC Devnet-};-const MAX_PRICE_LAMPORTS = 100000 * 1e6; // Max 100,000 USDC--// --- Inside the handler function, after auth -----const { skill_name, amount, currency_mint } = req.body;--// 1. Basic field presence-if (!skill_name || amount == null || !currency_mint) {- return res.status(400).json({ error: 'Missing required fields: skill_name, amount, currency_mint' });-}--// 2. Amount validation-if (!Number.isInteger(amount) || amount < 0) {- return res.status(400).json({ error: 'Amount must be a non-negative integer.' });-}-if (amount > MAX_PRICE_LAMPORTS) {- return res.status(400).json({ error: `Price cannot exceed ${MAX_PRICE_LAMPORTS / 1e6} USDC.` });-}--// 3. Currency mint validation-const network = process.env.SOLANA_NETWORK || 'mainnet'; // Or however you determine the network-if (currency_mint !== ALLOWED_CURRENCIES[network]) {- return res.status(400).json({ error: 'Invalid or unsupported currency.' });-}--// 4. Skill name validation (assuming agent object has a skills array)-const agent = await db.getAgentById(agentId); // You should have this from auth step-const agentSkills = agent.meta?.skills || []; // Adjust based on your agent data structure-if (!agentSkills.some(s => (typeof s === 'string' ? s : s.name) === skill_name)) {- return res.status(400).json({ error: `Skill '${skill_name}' is not defined for this agent.` });-}--// If all checks pass, proceed to database logic...-```diff --git a/docs/monetization/04-backend-purchase-endpoint.md b/docs/monetization/04-backend-purchase-endpoint.mddeleted file mode 100644index 822757acb..000000000--- a/docs/monetization/04-backend-purchase-endpoint.md+++ /dev/null@@ -1,87 +0,0 @@-# Prompt 4: Backend Purchase Endpoint--## Objective-Create a backend API endpoint that generates the necessary Solana transaction for a user to purchase a skill. This endpoint will not execute the transaction but will prepare it for the user to sign on the frontend.--## Explanation-The purchase process must be secure and initiated by the server. This endpoint (`/api/marketplace/skills/purchase`) will be responsible for fetching the skill's price, identifying the creator's treasury wallet, and constructing an unsigned Solana transfer transaction. This transaction is then sent back to the frontend, which will request the user's signature.--## Instructions-1. **Create New API File:**- * Create a new file in `api/marketplace/skills/purchase.js`. This will contain the logic for the new endpoint.--2. **Endpoint Logic:**- * The endpoint should accept a POST request with the `agentId` and `skillName`.- * It must also know the `purchaser`'s public key, which should be sent from the frontend.- * **Security:** The endpoint must verify the agent and skill exist and have a valid price.- * It needs to look up the agent creator's treasury wallet address.- * Using the Solana `@solana/web3.js` library, construct a transaction that transfers the correct amount of the specified currency (e.g., USDC) from the `purchaser` to the creator's treasury wallet.- * The endpoint should serialize the transaction, but *not* sign it, and return it to the frontend as a base64-encoded string.--## Code Example (`api/marketplace/skills/purchase.js`)--```javascript-import { Connection, PublicKey, SystemProgram, Transaction, clusterApiUrl } from '@solana/web3.js';-import { supabase } from '../../_lib/supabase'; // Assuming Supabase for DB-import { json, error } from '../../_lib/http'; // Assuming helper for responses--// Mock get-token-address library for USDC on Solana-const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d';--export default async function handler(req, res) {- if (req.method !== 'POST') {- return error(res, 405, 'Method Not Allowed');- }-- const { agentId, skillName, purchaserPublicKey } = req.body;-- if (!agentId || !skillName || !purchaserPublicKey) {- return error(res, 400, 'Missing required fields.');- }-- // 1. Fetch skill price and agent creator's treasury wallet from DB- const { data: priceData, error: priceError } = await supabase- .from('agent_skill_prices')- .select('amount, currency_mint, agents(creator_treasury_wallet)')- .eq('agent_id', agentId)- .eq('skill_name', skillName)- .single();-- if (priceError || !priceData) {- return error(res, 404, 'Skill price not found.');- }-- const { amount, currency_mint, agents: { creator_treasury_wallet } } = priceData;-- if (!creator_treasury_wallet) {- return error(res, 500, 'Creator has not configured a payout wallet.');- }-- // For this example, we assume native SOL transfer for simplicity- // A real implementation would handle SPL tokens like USDC, which is more complex.- const connection = new Connection(clusterApiUrl('devnet'));- const purchaser = new PublicKey(purchaserPublicKey);- const recipient = new PublicKey(creator_treasury_wallet);-- const transaction = new Transaction().add(- SystemProgram.transfer({- fromPubkey: purchaser,- toPubkey: recipient,- lamports: amount, // Assuming amount is in lamports for SOL transfer- })- );-- // Set the recent blockhash- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;- transaction.feePayer = purchaser;-- // Serialize the transaction and convert to base64- const serializedTransaction = transaction.serialize({- requireAllSignatures: false, // User will sign it- }).toString('base64');-- return json(res, {- transaction: serializedTransaction,- });-}-```diff --git a/docs/monetization/04-connect-wallet-integration.md b/docs/monetization/04-connect-wallet-integration.mddeleted file mode 100644index c07fe9e75..000000000--- a/docs/monetization/04-connect-wallet-integration.md+++ /dev/null@@ -1,48 +0,0 @@-# Prompt 4: Wallet Integration for Payments--## Objective-Integrate a Solana wallet adapter to allow users to connect their crypto wallets to the platform, a prerequisite for making payments.--## Explanation-To interact with the Solana blockchain for payments, users must first connect their own wallet (like Phantom, Solflare, etc.). We will use the official Solana Wallet Adapter libraries to provide a standardized, user-friendly way for users to connect.--## Instructions-1. **Add Dependencies:**- * Install the necessary Solana Wallet Adapter packages (`@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, etc., and their peer dependencies like `@solana/web3.js`).- * This might require refactoring parts of the frontend into a framework like React if not already done, or using the adapter with vanilla JS. For this prompt, assume a vanilla JS setup is possible.--2. **Initialize Wallet Adapter:**- * In a core JavaScript file (e.g., `src/app.js` or `src/wallet.js`), import and initialize the wallet adapter providers.- * Create a "Connect Wallet" button in the main UI (e.g., the header).--3. **Implement Connect/Disconnect Logic:**- * When the "Connect Wallet" button is clicked, present the user with a list of available wallets.- * Once a wallet is selected and approved by the user, the application should store the connection state and public key.- * The UI should update to show the user's connected wallet address and change the button to "Disconnect."--## Code Example (JavaScript - `src/wallet.js`)-```javascript-// This is a simplified example. Refer to official @solana/wallet-adapter docs for a full implementation.-import { Connection, PublicKey } from '@solana/web3.js';-import { WalletAdapter, PhantomWalletAdapter } from '@solana/wallet-adapter-wallets';--// Setup-const connection = new Connection('https://api.mainnet-beta.solana.com');-const wallets = [new PhantomWalletAdapter()];--let wallet;--// UI Connection-document.getElementById('connect-wallet-btn').addEventListener('click', async () => {- const selectedWallet = await showWalletChoice(); // UI function to let user pick from `wallets`- wallet = selectedWallet;- await wallet.connect();- console.log('Wallet connected:', wallet.publicKey.toBase58());- updateUIForConnectedState(wallet.publicKey);-});--wallet.on('connect', (publicKey) => {- console.log('Connected to ' + publicKey.toBase58());-});-```-This is a complex task. The prompt provides the user with the high-level steps and concepts, guiding them through the official documentation.diff --git a/docs/monetization/04-db-schema-skill-prices.md b/docs/monetization/04-db-schema-skill-prices.mddeleted file mode 100644index d2479299e..000000000--- a/docs/monetization/04-db-schema-skill-prices.md+++ /dev/null@@ -1,42 +0,0 @@-----status: not-started------# Prompt 4: Database Schema for Skill Prices--## Objective-Design and implement the necessary database schema to store the prices of agent skills.--## Explanation-A new table, `agent_skill_prices`, is needed to store the monetization information for each skill. This table will link an agent, a skill, and its price.--## Instructions-1. **Design the Table:**- * Create a new table named `agent_skill_prices`.- * The table should have the following columns:- * `id`: Primary key.- * `agent_id`: Foreign key referencing the `agents` table.- * `skill_name`: The name of the skill being priced.- * `amount`: The price of the skill in the smallest currency unit (e.g., lamports).- * `currency_mint`: The mint address of the currency (e.g., the USDC mint on Solana).- * `created_at`, `updated_at`: Timestamps.--2. **Create a Migration:**- * Use your database migration tool to create a new migration file.- * Write the SQL script to create the `agent_skill_prices` table.- * Apply the migration to your database.--## SQL Example--```sql-CREATE TABLE agent_skill_prices (- id SERIAL PRIMARY KEY,- agent_id UUID NOT NULL REFERENCES agents(id),- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- UNIQUE(agent_id, skill_name)-);-```diff --git a/docs/monetization/04-design-database-schema-for-skill-pricing.md b/docs/monetization/04-design-database-schema-for-skill-pricing.mddeleted file mode 100644index cbf9611dc..000000000--- a/docs/monetization/04-design-database-schema-for-skill-pricing.md+++ /dev/null@@ -1,46 +0,0 @@-# Prompt 4: Design Database Schema for Skill Pricing--## Status-- [ ] Not Started--## Objective-Design and create the necessary database table(s) to store pricing information for agent skills.--## Explanation-To make skills purchasable, we need a persistent storage solution for their pricing details. This prompt outlines the creation of an `agent_skill_prices` table that will link skills to their price and currency.--## Instructions-1. **Define the Schema:**- * Create a new table named `agent_skill_prices`.- * The table should include the following columns:- * `id`: Primary key (e.g., UUID or auto-incrementing integer).- * `agent_id`: Foreign key referencing the `agents` table.- * `skill_name`: The name of the skill (e.g., "super-jump"). This should match the skill name defined in the agent's configuration.- * `amount`: The price of the skill in the smallest unit of the currency (e.g., lamports for SOL, or the base unit for USDC). Use a data type that can handle large numbers (e.g., `BIGINT` or `NUMERIC`).- * `currency_mint`: The mint address of the SPL token used for payment (e.g., the USDC mint address).- * `created_at`, `updated_at`: Timestamps for record management.--2. **Write the SQL Migration:**- * Create a new SQL migration file to apply this schema change to the database.- * Include `CREATE TABLE` and `CREATE INDEX` statements. It's recommended to create an index on `(agent_id, skill_name)` for quick lookups.--## SQL Example (PostgreSQL)-```sql--- migration-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) 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()-);--CREATE UNIQUE INDEX idx_agent_skill_prices_on_agent_and_skill-ON agent_skill_prices (agent_id, skill_name);--COMMENT ON COLUMN agent_skill_prices.amount IS 'Price in the smallest currency unit (e.g., lamports)';-COMMENT ON COLUMN agent_skill_prices.currency_mint IS 'Mint address of the SPL token for payment';-```diff --git a/docs/monetization/04-frontend-display-priced-skills.md b/docs/monetization/04-frontend-display-priced-skills.mddeleted file mode 100644index 1306cc926..000000000--- a/docs/monetization/04-frontend-display-priced-skills.md+++ /dev/null@@ -1,84 +0,0 @@-----status: not-started-completed_at: null-----# Prompt 4: Frontend UI for Displaying Priced Skills--## Objective-Modify the agent detail page in the marketplace to visually distinguish between free and paid skills, and display the price for paid skills.--## Explanation-Currently, the agent detail page lists all skills uniformly. To begin building our monetization feature, users need to be able to see which skills are premium and how much they cost. This involves fetching pricing data along with agent details and updating the UI to render prices and a premium indicator.--## Instructions-1. **Locate the Frontend Code:**- * In `src/marketplace.js`, find the `renderDetail` function. This function is responsible for rendering the agent's profile, including its list of skills.--2. **Access Pricing Data:**- * The `renderDetail` function receives the full agent object from the API. With the backend changes from Prompt #2, this object now includes a `skill_prices` map.--3. **Update the Skill Rendering Logic:**- * Inside the loop that renders the skills (likely targeting the `d-skills` element), check if a price exists for the current skill in the `skill_prices` object.- * **If a price exists:** Render a price badge next to the skill name. The amount will be in the smallest unit of the currency (e.g., lamports or 10^-6 for USDC). Convert this to a human-readable format (e.g., `(price.amount / 1e6).toFixed(2)` for a 6-decimal USDC).- * **If a price does not exist:** Render a "Free" badge to make the distinction clear.- * Use different CSS classes for paid vs. free badges for distinct styling.--4. **Add CSS for Badges:**- * Open `/marketplace.css` and add the styles for the new price badges. Make them noticeable but not intrusive.--## Code Example (Frontend - `src/marketplace.js`)--Here's how you might modify the skill rendering part within the `renderDetail` function:--```javascript-// Inside renderDetail function, assuming 'a' is the agent object--const skillPrices = a.skill_prices || {};-const skillsArr = a.skills || []; // Assuming skills is an array of strings or objects--$('d-skills').innerHTML = skillsArr.length- ? skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- if (!name) return ''; // Skip empty skills-- 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>';-```--## CSS Example (`/marketplace.css`)--```css-.price-badge {- display: inline-block;- margin-left: 8px;- padding: 2px 6px;- font-size: 10px;- font-weight: 600;- border-radius: 4px;- vertical-align: middle;- text-transform: uppercase;-}--.price-free {- color: #a7f3d0; /* A light green */- background-color: rgba(52, 211, 153, 0.1);-}--.price-paid {- color: #fde047; /* A light yellow/gold */- background-color: rgba(253, 224, 71, 0.1);-}-```--## Definition of Done-- The agent detail page in the marketplace now displays badges next to each skill.-- Paid skills show the price in a human-readable format (e.g., "1.00 USDC").-- Free skills show a "Free" badge.-- The badges are styled according to the CSS example and look professional.-- The page handles agents with no skills or a mix of free and paid skills without errors.diff --git a/docs/monetization/04-frontend-skill-pricing-ui.md b/docs/monetization/04-frontend-skill-pricing-ui.mddeleted file mode 100644index 279874b3a..000000000--- a/docs/monetization/04-frontend-skill-pricing-ui.md+++ /dev/null@@ -1,120 +0,0 @@-----status: not-started------# Prompt 4: Frontend - Skill Pricing UI in Agent Editor--## Objective-Build a user interface within the agent editor page (`agent-edit.html`) that allows creators to view, add, and update prices for their agent's skills.--## Explanation-To make the new pricing API useful, creators need a friendly UI. This task involves adding a new section to the agent editor page. This section will list all of the agent's available skills and provide input fields for creators to set a price and currency for each one. The UI will then call the API endpoint created in the previous step to save the changes.--## Instructions-1. **Locate the Agent Editor File:**- * Open the `agent-edit.html` file and its corresponding JavaScript file (e.g., `src/agent-edit.js`).--2. **Design the UI:**- * In `agent-edit.html`, add a new section titled "Skill Monetization" or "Skill Pricing".- * This section should dynamically render a list of the agent's skills.- * For each skill, display:- * The skill name (read-only).- * An input field for the price (`amount`).- * A dropdown or input field for the `currency_mint` (for now, you can default this to USDC's mint address).- * A "Save" or "Update" button for each skill, or a single "Save All Prices" button for the section.--3. **Implement the Frontend Logic:**- * In `src/agent-edit.js`, when the agent data is loaded, populate the new UI section. You'll need to fetch the existing skill prices along with the agent details.- * Attach an event listener to the "Save" button(s).- * When a creator clicks "Save", gather the `skill_name`, `amount`, and `currency_mint` from the input fields.- * **Important:** The amount in the UI will be in a human-readable format (e.g., 1.00 USDC), but the API expects lamports. You must convert the UI value to the smallest unit before sending it to the API (e.g., `parseFloat(amountInput.value) * 1e6`).- * Make a `POST` request to the `/api/agents/[agentId]/skills/prices` endpoint with the data in the request body.- * Provide user feedback, such as a toast notification ("Price updated successfully!") or by changing the state of the save button (e.g., showing a checkmark).- * Handle any errors returned from the API and display a helpful message to the user.--## Code Example (HTML in `agent-edit.html`)--```html-<!-- Inside the agent editor form -->-<div class="form-section">- <h3>Skill Pricing</h3>- <p class="form-section-desc">- Set prices for your agent's skills. Payments will be handled on Solana.- </p>- <div id="skill-pricing-list">- <!-- Skills will be dynamically rendered here -->- </div>-</div>-```--## Code Example (JavaScript in `src/agent-edit.js`)--```javascript-// Function to render the pricing UI-function renderSkillPricing(agent) {- const skills = agent.skills || []; // Assuming agent.skills is an array of skill objects/names- const prices = agent.skill_prices || {};- const container = document.getElementById('skill-pricing-list');-- container.innerHTML = skills.map(skill => {- const skillName = typeof skill === 'string' ? skill : skill.name;- const price = prices[skillName];- const amountInUSDC = price ? (price.amount / 1e6).toFixed(2) : '0.00';-- return `- <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">- <label>${escapeHtml(skillName)}</label>- <div class="price-inputs">- <input type="number" step="0.01" min="0" value="${amountInUSDC}" class="price-amount-input">- <select class="price-currency-select">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6T">USDC</option>- </select>- <button class="btn-save-price">Save</button>- </div>- </div>- `;- }).join('');-- // Add event listeners to all save buttons- container.querySelectorAll('.btn-save-price').forEach(button => {- button.addEventListener('click', handleSavePrice);- });-}--// Event handler for saving a price-async function handleSavePrice(event) {- const entry = event.target.closest('.skill-price-entry');- const skillName = entry.dataset.skillName;- const amountInput = entry.querySelector('.price-amount-input');- const currencySelect = entry.querySelector('.price-currency-select');-- const amountInUSDC = parseFloat(amountInput.value);- if (isNaN(amountInUSDC) || amountInUSDC < 0) {- showToast('Invalid amount', 'error');- return;- }-- const payload = {- skill_name: skillName,- amount: Math.round(amountInUSDC * 1e6), // Convert to lamports- currency_mint: currencySelect.value- };-- try {- const response = await fetch(`/api/agents/${currentAgentId}/skills/prices`, {- method: 'POST',- headers: { 'Content-Type': 'application/json', /* ...auth headers */ },- body: JSON.stringify(payload)- });-- if (!response.ok) {- const { error } = await response.json();- throw new Error(error || 'Failed to save price');- }-- showToast(`${skillName} price updated!`, 'success');- } catch (err) {- showToast(err.message, 'error');- }-}-```diff --git a/docs/monetization/04-premium-indicator-marketplace.md b/docs/monetization/04-premium-indicator-marketplace.mddeleted file mode 100644index b437c2359..000000000--- a/docs/monetization/04-premium-indicator-marketplace.md+++ /dev/null@@ -1,86 +0,0 @@-----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/04-solana-pay-frontend-qr.md b/docs/monetization/04-solana-pay-frontend-qr.mddeleted file mode 100644index ae138c0d5..000000000--- a/docs/monetization/04-solana-pay-frontend-qr.md+++ /dev/null@@ -1,99 +0,0 @@-# Prompt 4: Solana Pay QR Code (Frontend)--## Objective-Integrate the frontend with the new payment endpoint to display a Solana Pay QR code when a user clicks the "Purchase" button.--## Explanation-With the backend endpoint ready to generate transactions, we need to update the frontend to request this transaction and display it as a QR code. This allows users to scan the code with their mobile Solana wallet to approve the purchase. We'll use the official `@solana/pay` JavaScript library to generate the QR code.--## Instructions-1. **Add Frontend Dependency:**- * Add the `@solana/pay` library to your frontend `package.json` and install it.--2. **Create a Payment Modal:**- * In `marketplace.html` (or your main HTML file), create the HTML structure for a modal dialog. This modal will be hidden by default and will contain the QR code, transaction details, and a spinner.--3. **Implement the Frontend Logic (`src/marketplace.js`):**- * Add a delegated event listener to the page that listens for clicks on buttons with the `purchase-skill-btn` class.- * When a button is clicked:- * Show the payment modal and a loading spinner.- * Get the `skillName` and `agentId` from data attributes.- * Make a `POST` request to your `/api/payments/prepare-skill-purchase` endpoint.- * On success, use the `createQR` function from `@solana/pay` to generate the QR code from the transaction URL.- * Mount the QR code SVG element into the modal. Hide the spinner.- * Display the transaction message and amount.- * Handle any errors from the API call by showing an error message in the modal.--## Code Example (`src/marketplace.js`)--```javascript-import { createQR } from '@solana/pay';--// ... other imports--function renderPaymentModal(url) {- const modal = $('payment-modal'); // Assuming you have a modal element- const qrCodeContainer = modal.querySelector('.qr-code-container');- const spinner = modal.querySelector('.spinner');-- qrCodeContainer.innerHTML = '';- spinner.hidden = true;-- const qr = createQR(url, 300, 'transparent'); // size, background color- qr.append(qrCodeContainer);-- modal.showModal(); // Using <dialog> element's API-}--async function handlePurchaseClick(event) {- const button = event.target.closest('.purchase-skill-btn');- if (!button) return;-- const skillName = button.dataset.skillName;- const agentId = $('d-id').textContent; // Assuming agent ID is available-- const modal = $('payment-modal');- modal.querySelector('.spinner').hidden = false;- modal.showModal();-- try {- const response = await fetch('/api/payments/prepare-skill-purchase', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ agentId, skillName }),- });-- if (!response.ok) {- throw new Error(`API Error: ${response.statusText}`);- }-- const { transaction, message } = await response.json();-- // The Solana Pay URL is constructed from the API response- const url = `solana:${encodeURIComponent(transaction)}`;-- renderPaymentModal(url, message);-- } catch (error) {- console.error('Purchase failed:', error);- modal.querySelector('.error-message').textContent = 'Failed to prepare transaction. Please try again.';- modal.querySelector('.spinner').hidden = true;- }-}--document.body.addEventListener('click', handlePurchaseClick);-```--## HTML Modal Example--```html-<!-- Add this to your main HTML file -->-<dialog id="payment-modal">- <h2>Complete Your Purchase</h2>- <div class="spinner"></div>- <div class="qr-code-container"></div>- <p class="payment-message"></p>- <p class="error-message"></p>- <button class="close-modal-btn">Close</button>-</dialog>-```diff --git a/docs/monetization/04-wallet-connection.md b/docs/monetization/04-wallet-connection.mddeleted file mode 100644index 9591a5a97..000000000--- a/docs/monetization/04-wallet-connection.md+++ /dev/null@@ -1,84 +0,0 @@-----status: not-started------# Prompt 4: Wallet Connection--## Objective-Integrate a Solana wallet adapter to allow users to connect their wallets, a prerequisite for making payments.--## Explanation-To purchase skills, users will need to connect their Solana wallet (like Phantom or Solflare). We will use the official Solana wallet-adapter library to handle the complexities of wallet detection and connection. The connection button will be placed inside the purchase modal.--## Instructions-- [ ] **Add Solana Wallet-Adapter Dependencies:**- - [ ] Add the necessary Solana wallet-adapter packages to your `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react` (or a vanilla JS equivalent if not using a framework), and adapters for specific wallets like `@solana/wallet-adapter-wallets`. For a vanilla JS project, you may need to use a CDN version or bundle it.-- [ ] **Integrate Wallet-Adapter:**- - [ ] In `src/marketplace.js`, initialize the wallet adapter.- - [ ] Create a `connectWallet` function. This function will be responsible for presenting the user with a list of available wallets and handling the connection logic.-- [ ] **Add Connect Button to UI:**- - [ ] In the purchase modal, instead of a simple "Confirm" button, we'll now have a "Connect Wallet" button if the user's wallet is not already connected.- - [ ] Display the user's public key (wallet address) once connected, and change the button to "Proceed to Payment".--## Code Example (`src/marketplace.js`)--This example assumes you're able to import or include the wallet-adapter libraries. For simplicity, we'll use psuedo-code for the adapter initialization.--```javascript-// Assume walletAdapter is initialized somewhere in your app's entry point.-// This is a simplified example. Refer to wallet-adapter docs for full setup.--let connectedWallet = null;--async function connectWallet() {- try {- // This would typically open the wallet adapter's modal- const wallet = await walletAdapter.connect();- connectedWallet = wallet;- console.log('Wallet connected:', wallet.publicKey.toBase58());- updateModalAfterConnect();- } catch (error) {- console.error('Failed to connect wallet:', error);- // Show an error to the user- }-}--function updateModalAfterConnect() {- const walletAddress = connectedWallet.publicKey.toBase58();- const truncatedAddress = `${walletAddress.slice(0, 4)}...${walletAddress.slice(-4)}`;-- // Update the modal body to show connected status- const modalBody = $('modal-body');- modalBody.innerHTML = `- <p>Wallet Connected: <strong>${truncatedAddress}</strong></p>- <button id="proceed-to-payment-btn">Proceed to Payment</button>- `;-}--// In your event listener for showing the modal:-function showPurchaseModal(skillName) {- let content = '';- if (connectedWallet) {- content = `- <p>You are purchasing "${skillName}". Your wallet is connected.</p>- <button id="proceed-to-payment-btn">Proceed to Payment</button>- `;- } else {- content = `- <p>You need to connect your wallet to purchase "${skillName}".</p>- <button id="connect-wallet-btn">Connect Wallet</button>- `;- }- showModal(`Purchase Skill: ${skillName}`, content);-}--// Add event listener for the new buttons inside the modal-$('modal-body').addEventListener('click', (e) => {- if (e.target.id === 'connect-wallet-btn') {- connectWallet();- }- if (e.target.id === 'proceed-to-payment-btn') {- // Next step: initiate the payment- }-});-```diff --git a/docs/monetization/04_api_for_saving_prices.md b/docs/monetization/04_api_for_saving_prices.mddeleted file mode 100644index 794c3458d..000000000--- a/docs/monetization/04_api_for_saving_prices.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 04: API for Saving Skill Prices--## Objective-Create a secure backend API endpoint for agent creators to save or update the prices for their skills.--## Explanation-The UI for setting skill prices needs a backend endpoint to persist the data. This endpoint must be secure, ensuring that only the owner of an agent can modify its skill prices. It will receive a payload of skill prices, validate it, and update the `agent_skill_prices` table.--## Instructions-1. **Create the API File:**- * Create a new API file, for example, `api/agents/skill-prices.js` or add a new action to an existing agent-related dispatcher. The route could be `POST /api/agents/:id/skill-prices`.--2. **Implement the Endpoint Logic:**- * **Authentication:** The endpoint must first authenticate the user and retrieve their ID.- * **Authorization:** It must verify that the authenticated user is the owner of the agent specified in the URL (`:id`).- * **Validation:** It should validate the incoming payload. The payload should be a JSON object where keys are skill names and values are objects containing `amount` and `currency_mint`. Use a library like `zod` for robust validation.- * **Database Operation:** For each skill price in the payload, perform an "upsert" operation on the `agent_skill_prices` table. If a price for that agent and skill already exists, update it. If not, insert a new row. This is a perfect use case for PostgreSQL's `ON CONFLICT` clause.--## Code Example (Vercel Serverless Function)--```javascript-// Example in: /api/agents/[agentId]/skill-prices.js-import { z } from 'zod';-import { sql } from '../../_lib/db.js';-import { getSessionUser } from '../../_lib/auth.js';-import { error, json, wrap } from '../../_lib/http.js';-import { parse } from '../../_lib/validate.js';--// Define the schema for a single price entry-const PriceSchema = z.object({- amount: z.number().int().positive(),- currency_mint: z.string().min(32).max(44), // Solana public key validation-});--// The incoming body should be a map of skill names to price objects-const BodySchema = z.record(z.string(), PriceSchema);--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- const agentId = req.query.agentId;- const rawBody = await req.json();- const pricesToUpdate = parse(BodySchema, rawBody);-- // 1. Verify ownership of the agent- const [agent] = await sql`- SELECT id FROM agent_identities- WHERE id = ${agentId} AND user_id = ${user.id} AND deleted_at IS NULL- `;- if (!agent) return error(res, 404, 'not_found', 'Agent not found or you do not have permission.');-- // 2. Perform the upsert operation for all prices in a single transaction- await sql.begin(async sql => {- for (const [skillName, price] of Object.entries(pricesToUpdate)) {- await sql`- INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint)- VALUES (${agentId}, ${skillName}, ${price.amount}, ${price.currency_mint})- ON CONFLICT (agent_id, skill_name)- DO UPDATE SET- amount = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- updated_at = NOW();- `;- }- });-- return json(res, 200, { success: true, message: 'Skill prices updated.' });-});-```diff --git a/docs/monetization/05-create-purchase-skill-button.md b/docs/monetization/05-create-purchase-skill-button.mddeleted file mode 100644index f7a443e83..000000000--- a/docs/monetization/05-create-purchase-skill-button.md+++ /dev/null@@ -1,98 +0,0 @@-# Prompt 5: Create "Purchase Skill" Button--## Status-- [ ] Not Started--## Objective-Add a "Purchase" button for priced skills on the agent detail page and a modal to confirm the purchase.--## Explanation-With the front-end now able to display skill prices, the next step is to provide users with a clear call-to-action to initiate a purchase. This prompt covers adding the button and a confirmation modal.--## Instructions-1. **Modify the Skill Rendering Logic:**- * In `src/marketplace.js` within the `renderDetail` function, update the skill rendering logic.- * For skills that have a price, instead of just a badge, render a "Purchase" button.- * The button should include `data-` attributes to store the skill name, price, and currency mint, which will be needed to initiate the transaction.--2. **Create a Purchase Confirmation Modal:**- * Add a hidden modal to your main HTML (`app.html` or `marketplace.html`).- * The modal should display the details of the skill being purchased (name, price) and include "Confirm" and "Cancel" buttons.--3. **Implement Button Logic:**- * Add a click event listener to the "Purchase" buttons.- * When a button is clicked, read the `data-` attributes and populate the confirmation modal with the correct information, then display the modal.--## Code Example (Frontend - `src/marketplace.js`)-```javascript-// Inside renderDetail function-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 actionElement;- if (price) {- const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;- actionElement = `<button class="purchase-skill-btn"- data-skill-name="${escapeHtml(name)}"- data-price-amount="${price.amount}"- data-currency-mint="${price.currency_mint}">- Purchase for ${priceDisplay}- </button>`;- } else {- actionElement = `<span class="price-badge price-free">Free</span>`;- }- return `<div class="skill-entry">- <span>${escapeHtml(name)}</span>- ${actionElement}- </div>`;- }).join('')- : '<div>This Agent has no skills defined.</div>';--// Add event listeners after rendering-document.querySelectorAll('.purchase-skill-btn').forEach(button => {- button.addEventListener('click', handlePurchaseClick);-});-```--## Code Example (HTML for Modal)-```html-<!-- Add to app.html or marketplace.html -->-<div id="purchase-confirm-modal" class="modal-hidden">- <div class="modal-content">- <h2>Confirm Purchase</h2>- <p>You are about to purchase the skill: <b id="modal-skill-name"></b></p>- <p>Price: <b id="modal-skill-price"></b></p>- <div class="modal-actions">- <button id="modal-confirm-btn">Confirm</button>- <button id="modal-cancel-btn">Cancel</button>- </div>- </div>-</div>-```--## Code Example (Event Handling)-```javascript-function handlePurchaseClick(event) {- const button = event.currentTarget;- const skillName = button.dataset.skillName;- const priceAmount = button.dataset.priceAmount;- const currencyMint = button.dataset.currencyMint;-- // Populate and show the modal- document.getElementById('modal-skill-name').textContent = skillName;- document.getElementById('modal-skill-price').textContent = `${(priceAmount / 1e6).toFixed(2)} USDC`;- document.getElementById('purchase-confirm-modal').classList.remove('modal-hidden');-- // Store data for the transaction- document.getElementById('modal-confirm-btn').dataset.skillData = JSON.stringify({- skillName, priceAmount, currencyMint- });-}--// Add event listener for the cancel button to hide the modal-document.getElementById('modal-cancel-btn').addEventListener('click', () => {- document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');-});-```diff --git a/docs/monetization/05-creator-ui-for-pricing.md b/docs/monetization/05-creator-ui-for-pricing.mddeleted file mode 100644index 04fd964a1..000000000--- a/docs/monetization/05-creator-ui-for-pricing.md+++ /dev/null@@ -1,97 +0,0 @@-----status: not-started-completed_at: null-----# Prompt 5: Creator Dashboard UI for Pricing Skills--## Objective-Create a user interface in the Creator Dashboard that allows an agent creator to view their agent's skills and set prices for them.--## Explanation-To enable creators to monetize their work, they need a simple and intuitive interface. This task involves building a new section in the agent editing page of the Creator Dashboard. This section will list all of the agent's skills and provide input fields for creators to set a price for each one. The interface will use the API created in Prompt #3 to save these prices.--## Instructions-1. **Locate the Creator Dashboard Page:**- * Find the HTML file for the agent editor in the Creator Dashboard (e.g., `agent-edit.html`).--2. **Create the Skill Pricing Section:**- * Add a new section to the page titled "Skill Monetization" or "Skill Pricing".- * This section should only be visible to the agent's owner.- * Fetch the agent's details, including their list of skills and any existing `skill_prices`.--3. **Render the Skill List:**- * Iterate through the agent's skills. For each skill, render:- * The skill name (read-only).- * An input field for the `amount`.- * A dropdown/select for the `currency_mint` (initially, this can be hardcoded to just show USDC, but it should be designed to be extensible).- * A "Save" or "Update" button for each skill.- * A "Make Free" or "Remove Price" button.--4. **Implement the API Interaction:**- * When the creator clicks "Save", make a `POST` request to the `/api/creator/agents/:agentId/skills/price` endpoint.- * The request body should include the `skill_name`, `amount` (converted to the smallest unit), and `currency_mint`.- * When the "Make Free" button is clicked, make a similar `POST` request, but set the `amount` to `0` or `null`.- * Provide feedback to the user on success (e.g., a "Saved!" message) or failure (e.g., an error message).- * Use a debounce on the input fields to prevent excessive API calls if you choose to save on input change.--## UI Mockup Idea--```-+------------------------------------------------------+-| Skill Pricing |-+------------------------------------------------------+-| |-| translate [ 1.00 ] [ USDC ▼ ] [ Save ] |-| |-| summarize-document [ 0.00 ] [ USDC ▼ ] [ Set Price ] |-| |-| generate-image [ 5.00 ] [ USDC ▼ ] [ Save ] [ Make Free ] |-| |-+------------------------------------------------------+-```--## Code Example (Frontend JavaScript)--```javascript-// This is a conceptual example for the event handling--async function saveSkillPrice(agentId, skillName, amount, currency) {- // Note: Convert amount to smallest unit, e.g., amount * 1e6 for USDC- const amountInSmallestUnit = Math.round(parseFloat(amount) * 1e6);-- const response = await fetch(`/api/creator/agents/${agentId}/skills/price`, {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- skill_name: skillName,- amount: amountInSmallestUnit,- currency_mint: currency,- }),- });-- if (response.ok) {- // Show success feedback- console.log(`Price for ${skillName} saved successfully!`);- } else {- // Show error feedback- const err = await response.json();- console.error(`Failed to save price:`, err.error);- }-}--// Attach this function to the 'click' event of the save buttons-// e.g., saveButton.addEventListener('click', () => {-// const amount = amountInput.value;-// const currency = currencySelect.value;-// saveSkillPrice('agent-123', 'translate', amount, currency);-// });-```--## Definition of Done-- A new "Skill Pricing" section is visible on the agent editing page for agent owners.-- The section lists all the agent's skills.-- Each skill has corresponding input fields for price and currency.-- The "Save" button correctly calls the API to set/update the price.-- The "Make Free" button correctly calls the API to remove the price.-- The UI provides clear feedback to the user upon success or failure of the operation.-- Existing prices are correctly populated into the input fields when the page loads.diff --git a/docs/monetization/05-filter-marketplace-price.md b/docs/monetization/05-filter-marketplace-price.mddeleted file mode 100644index 6a6ffcfe0..000000000--- a/docs/monetization/05-filter-marketplace-price.md+++ /dev/null@@ -1,84 +0,0 @@-----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/05-frontend-transaction-signing.md b/docs/monetization/05-frontend-transaction-signing.mddeleted file mode 100644index 76f45d943..000000000--- a/docs/monetization/05-frontend-transaction-signing.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 5: Frontend Transaction Signing--## Objective-Implement the frontend logic to take the serialized transaction from the backend, have the user sign it with their connected wallet, and send it to the Solana network.--## Explanation-This is the crucial step where the user approves the purchase. The frontend receives the base64-encoded transaction from the backend purchase endpoint. It then needs to decode it, present it to the user's wallet for signing, and upon approval, submit the signed transaction to the blockchain for confirmation.--## Instructions-1. **Add Frontend API Call:**- * In `src/marketplace.js`, within the event handler for the "Buy Now" button in the purchase modal, make a `fetch` POST request to your new `/api/marketplace/skills/purchase` endpoint.- * Send the `agentId`, `skillName`, and the connected user's public key in the request body.--2. **Sign and Send Transaction:**- * On a successful response from the API, you will receive the serialized transaction.- * You need to deserialize it, request the user's wallet to sign it, and then send the raw, signed transaction to the Solana network.--## Code Example (`src/marketplace.js`)--```javascript-import { Connection, Transaction, clusterApiUrl } from '@solana/web3.js';--// Inside the confirmPurchaseBtn click listener-confirmPurchaseBtn.addEventListener('click', async () => {- const skillName = confirmPurchaseBtn.dataset.skillName;- // Assume `agent` and `walletPublicKey` are available in this scope- const agentId = agent.id;- const purchaserPublicKey = walletPublicKey.toBase58();-- try {- // 1. Get transaction from the backend- const response = await fetch('/api/marketplace/skills/purchase', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ agentId, skillName, purchaserPublicKey }),- });-- if (!response.ok) {- const errData = await response.json();- throw new Error(errData.error || 'Failed to prepare transaction.');- }-- const { transaction: base64Transaction } = await response.json();-- // 2. Deserialize, sign, and send- const provider = getProvider(); // The wallet provider from prompt 2- const connection = new Connection(clusterApiUrl('devnet'));-- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));-- // 3. Request user to sign- const { signature } = await provider.signAndSendTransaction(transaction, connection);-- // 4. Confirm transaction- await connection.confirmTransaction(signature, 'confirmed');-- alert(`Purchase successful! Transaction: ${signature}`);-- // Next step: Call another backend endpoint to formally unlock the skill- // This will be covered in another prompt.- closePurchaseModal();-- } catch (error) {- console.error('Purchase failed:', error);- alert(`Purchase failed: ${error.message}`);- }-});-```diff --git a/docs/monetization/05-initiate-payment-api.md b/docs/monetization/05-initiate-payment-api.mddeleted file mode 100644index 3b98d5b9a..000000000--- a/docs/monetization/05-initiate-payment-api.md+++ /dev/null@@ -1,84 +0,0 @@-----status: not-started------# Prompt 5: Initiate Payment API--## Objective-Create a backend endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend.--## Explanation-For security and reliability, the transaction should be constructed on the backend. The frontend will request a transaction for a specific skill. The backend will look up the skill's price, the creator's payout address, and the platform's fee address, then create an unsigned transaction and send it back to the frontend. The frontend's only job is to get it signed by the user's wallet.--## Instructions-- [ ] **Create the API Endpoint:**- - [ ] Create a new API file, e.g., `api/payments/initiate.js`.- - [ ] This endpoint should accept a `skill_name` and `agent_id` in the request body.-- [ ] **Implement Transaction Logic:**- - [ ] The endpoint needs to perform several lookups:- - [ ] The skill's price from `agent_skill_prices`.- - [ ] The agent creator's payout address.- - [ ] The platform's fee/treasury address (this can be a constant for now).- - [ ] Using the Solana SDK (`@solana/web3.js`), construct a transaction. This will likely be a simple SPL-token transfer (e.g., USDC) from the user to the creator, potentially with a second transfer for the platform fee.- - [ ] Serialize the unsigned transaction and return it in the response, base64-encoded.--## Code Example (Backend - `api/payments/initiate.js`)--```javascript-// This is a simplified example. You'll need error handling and more robust data fetching.-import { Connection, PublicKey, SystemProgram, Transaction } from '@solana/web3.js';-import { getTokenTransferInstruction } from 'your-token-utils'; // Helper for SPL token transfers--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).end();- }-- const { skillName, agentId, userWalletAddress } = req.body;-- // 1. Fetch skill price, creator payout address, etc. from your database- const skillPrice = await db.getSkillPrice(agentId, skillName); // e.g., { amount: 1000000, mint: 'EPj...' }- const creatorAddress = await db.getCreatorPayoutAddress(agentId);- const platformFeeAddress = process.env.PLATFORM_FEE_WALLET;- const platformFeeBps = 500; // 5%-- // 2. Create a new transaction- const connection = new Connection(process.env.SOLANA_RPC_URL);- const transaction = new Transaction({- feePayer: new PublicKey(userWalletAddress),- recentBlockhash: (await connection.getLatestBlockhash()).blockhash,- });-- // 3. Calculate amounts- const creatorAmount = skillPrice.amount * (1 - platformFeeBps / 10000);- const platformAmount = skillPrice.amount - creatorAmount;-- // 4. Add transfer instructions (this part is complex for SPL tokens, pseudo-code shown)- // You need to find the user's Associated Token Account (ATA) for the mint.- const userTokenAccount = await findUserATA(userWalletAddress, skillPrice.mint);-- transaction.add(- createTokenTransferInstruction(- userTokenAccount,- creatorAddress,- userWalletAddress, // User is the owner of their ATA- creatorAmount- )- );- transaction.add(- createTokenTransferInstruction(- userTokenAccount,- platformFeeAddress,- userWalletAddress,- platformAmount- )- );-- // 5. Serialize and return- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });-- res.status(200).json({- transaction: serializedTransaction.toString('base64'),- });-}-```diff --git a/docs/monetization/05-initiate-solana-transaction.md b/docs/monetization/05-initiate-solana-transaction.mddeleted file mode 100644index aebe08381..000000000--- a/docs/monetization/05-initiate-solana-transaction.md+++ /dev/null@@ -1,57 +0,0 @@-# Prompt 5: Initiate Solana Transaction on Purchase--## Objective-Wire up the "Confirm Purchase" button in the modal to construct and request the user to sign a Solana transaction that transfers the specified amount to the creator's wallet.--## Explanation-This is where the user's action translates into an on-chain event. After connecting their wallet, clicking "Confirm" should prompt them, via their wallet extension, to approve a transaction that pays for the skill.--## Instructions-1. **Fetch Creator Wallet:**- * The agent data from the backend must include the creator's public key (wallet address) where funds should be sent.- * Modify the `/api/marketplace/agents/:id` endpoint to include `creator_wallet_address`.--2. **Construct Transaction (`src/marketplace.js`):**- * In the event listener for the `#modal-confirm-purchase` button:- * Get the connected wallet object from the wallet adapter.- * Fetch the skill price (amount) and the creator's wallet address.- * Use `@solana/web3.js` to create a new `Transaction` object.- * Add a `SystemProgram.transfer` instruction to the transaction, specifying the sender (user's public key), recipient (creator's public key), and amount in lamports.--3. **Send and Confirm Transaction:**- * Use the wallet adapter's `sendTransaction` method to send the transaction to the network.- * Await the confirmation of the transaction.- * Provide feedback to the user based on whether the transaction succeeds or fails.--## Code Example (JavaScript - `src/marketplace.js`)-```javascript-import { Connection, SystemProgram, Transaction, PublicKey } from '@solana/web3.js';-// Assume `wallet` is the connected wallet adapter object and `connection` is a Connection object.--document.getElementById('modal-confirm-purchase').addEventListener('click', async () => {- const agent = getCurrentAgentData();- const skillName = document.getElementById('modal-skill-name').textContent;- const price = agent.skill_prices[skillName];-- const recipient = new PublicKey(agent.creator_wallet_address);- const lamports = price.amount;-- const transaction = new Transaction().add(- SystemProgram.transfer({- fromPubkey: wallet.publicKey,- toPubkey: recipient,- lamports: lamports,- })- );-- try {- const signature = await wallet.sendTransaction(transaction, connection);- await connection.confirmTransaction(signature, 'processed');- console.log('Transaction successful with signature:', signature);- // Next step: Mint an NFT to prove ownership.- } catch (error) {- console.error('Transaction failed:', error);- // Show an error message to the user.- }-});-```diff --git a/docs/monetization/05-transaction-confirmation-backend.md b/docs/monetization/05-transaction-confirmation-backend.mddeleted file mode 100644index 0a711e68e..000000000--- a/docs/monetization/05-transaction-confirmation-backend.md+++ /dev/null@@ -1,94 +0,0 @@-# Prompt 5: Transaction Confirmation (Backend)--## Objective-Implement a backend mechanism to verify that a Solana Pay transaction has been successfully processed and confirmed on the blockchain.--## Explanation-After the user approves the transaction in their wallet, we need a reliable way to confirm its success on the backend. The Solana Pay spec provides a mechanism for this. The wallet will make a `GET` request to the same URL it used for the `POST`, and our backend should verify the transaction signature provided by the wallet.--## Instructions-1. **Modify the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**- * Our endpoint needs to handle both `POST` (to create the transaction) and `GET` (to verify it).- * **For the `POST` request:** When creating the transaction, you must associate it with a unique reference `PublicKey`. This reference key allows you to look up the transaction later. Generate a new keypair for each transaction: `const reference = new Keypair().publicKey;`. Add this reference to the `transfer` instruction. Store this reference in your database, linked to the user, skill, and agent.- * **For the `GET` request:** The wallet will include the transaction `signature` in the query string. Your handler should:- * Find the transaction on the blockchain using the `signature`.- * Verify that the transaction was successful and contains the expected transfers (to the creator and the platform).- * Crucially, verify that the transaction includes the `reference` public key you generated, proving it's for this specific purchase.- * If everything checks out, proceed to the next step: granting the user access to the skill.--## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)--This example shows the conceptual additions. You'll need to integrate this with your database logic.--```javascript-// ... imports including Keypair-import { Keypair } from '@solana/web3.js';-import { findTransaction, verifyTransaction } from '@solana/pay';--// ... DB function placeholders-import { savePurchaseReference, findPurchaseByReference, grantSkillToUser } from '../_lib/db';--export default async function handler(req, res) {- const connection = new Connection(process.env.SOLANA_RPC_URL);-- if (req.method === 'POST') {- // ... POST logic from prompt 3 ...-- // 1. Generate a reference keypair- const reference = new Keypair().publicKey;-- // 2. Add it to the transaction so you can find it later- // This is a simplified example; typically added to the transfer instruction- transaction.add(- SystemProgram.transfer({- fromPubkey: buyerPublicKey,- toPubkey: reference, // Using reference here is for lookup- lamports: 0,- })- );-- // 3. Save reference to DB before sending tx to user- await savePurchaseReference(reference.toBase58(), { userId: req.user.id, agentId, skillName });-- // ... continue serializing and sending transaction- } else if (req.method === 'GET') {- try {- const { reference, signature } = req.query;- if (!reference || !signature) {- return res.status(400).json({ error: 'Missing reference or signature' });- }-- // Find the purchase details from your DB using the reference- const purchaseDetails = await findPurchaseByReference(reference);- if (!purchaseDetails) {- return res.status(404).json({ error: 'Purchase reference not found' });- }-- // Use Solana Pay's helper to find and verify the transaction- const { transaction, status } = await findTransaction(connection, new PublicKey(signature));-- if (status !== 'confirmed') {- return res.status(400).json({ error: 'Transaction not confirmed' });- }-- // You should add more robust verification here:- // - Check the amounts transferred- // - Check the destination addresses- // - Check that the buyer was the fee payer- console.log('Transaction verified successfully!');-- // Grant access to the skill- await grantSkillToUser(purchaseDetails.userId, purchaseDetails.skillName);-- res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });-- } catch (error) {- console.error('Verification failed:', error);- res.status(500).json({ error: 'Verification failed' });- }- } else {- res.status(405).json({ error: 'Method Not Allowed' });- }-}--```diff --git a/docs/monetization/05-ui-purchase-skill-button.md b/docs/monetization/05-ui-purchase-skill-button.mddeleted file mode 100644index ea37ff6f6..000000000--- a/docs/monetization/05-ui-purchase-skill-button.md+++ /dev/null@@ -1,48 +0,0 @@-----status: not-started------# Prompt 5: UI for "Purchase Skill" Button--## Objective-Add a "Purchase Skill" button to the agent detail page for skills that are not free.--## Explanation-To allow users to buy skills, a clear call-to-action is needed. This button will be displayed next to paid skills that the user has not yet purchased, and it will trigger the payment flow.--## Instructions-1. **Modify the Frontend UI:**- * In `src/marketplace.js`, in the `renderDetail` function, update the skill rendering logic.- * For each skill, check if it's paid and if the current user has already purchased it.- * If the skill is paid and not purchased, display a "Purchase" or "Unlock" button instead of the price badge.- * If the skill is free or already purchased, display the "Free" or "Owned" badge.--2. **Button State:**- * The button should be clearly visible and clickable.- * Add a `data-skill-name` attribute to the button to identify which skill is being purchased.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail function, an updated version of the skill rendering logic-const skillPrices = a.skill_prices || {};-const ownedSkills = user.owned_skills || []; // Assuming this data is available--$('d-skills').innerHTML = skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];-- let badge;- if (price) {- if (ownedSkills.includes(name)) {- badge = `<span class="price-badge price-owned">Owned</span>`;- } else {- badge = `<button class="purchase-btn" data-skill-name="${name}">Purchase</button>`;- }- } else {- badge = `<span class="price-badge price-free">Free</span>`;- }-- return `<span class="skill-entry">${escapeHtml(name)}${badge}</span>`;-}).join(' ');-```diff --git a/docs/monetization/05-ui-toggle-for-paid-skills.md b/docs/monetization/05-ui-toggle-for-paid-skills.mddeleted file mode 100644index b075a7906..000000000--- a/docs/monetization/05-ui-toggle-for-paid-skills.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 5: UI Toggle for Paid Skills--## Objective-Enhance the skill price management UI with dynamic toggles that intuitively show and hide price input fields.--## Explanation-This prompt focuses on the frontend user experience for creators. Instead of showing price inputs at all times, we'll use a checkbox or toggle switch for each skill. This makes the interface cleaner and the act of setting a price a more deliberate choice.--## Instructions-1. **File to Edit:**- * Continue working in `agent-edit.html` and its associated JavaScript.--2. **Refine the UI Structure:**- * For each skill listed in the pricing management section, ensure you have the following HTML structure:- * The skill name.- * A checkbox/toggle: `<input type="checkbox" class="paid-toggle">`.- * A container for the price inputs (e.g., a `<div>`) that is initially hidden if the skill is free.--3. **Implement JavaScript Logic:**- * Add an event listener to all `.paid-toggle` checkboxes.- * When a checkbox is checked (toggled on):- * The associated price input container should become visible (e.g., `style.display = 'flex'`).- * You might want to focus the amount input field to encourage the user to enter a price.- * When a checkbox is unchecked (toggled off):- * The price input container should be hidden (`style.display = 'none'`).--4. **Initial State:**- * When the UI is first rendered, the state of each checkbox and the visibility of the price inputs must reflect the current pricing data fetched from the backend. If a skill has a price, its checkbox should be checked and its price inputs should be visible.--## Code Example (Frontend - `agent-edit.html` script)--This builds upon the example from Prompt 3.--```html-<!-- Example HTML structure for one skill row within agent-edit.html -->-<div class="form-group skill-price-row">- <label class="form-label">summarize-text</label>- <div class="skill-price-controls">- <input type="checkbox" class="paid-toggle" id="toggle-summarize-text" data-skill="summarize-text">- <label for="toggle-summarize-text" class="toggle-label">Paid Skill</label>-- <div class="price-inputs" style="display: none;">- <input type="number" class="price-amount" value="1.00" step="0.01" min="0">- <span>USDC</span>- </div>- </div>-</div>-```--```css-/* Add some basic styling for the toggle and inputs in your CSS */-.skill-price-controls {- display: flex;- align-items: center;- gap: 10px;-}-.price-inputs {- display: flex;- align-items: center;- gap: 5px;-}-```--```javascript-// JavaScript to handle the dynamic visibility--document.addEventListener('DOMContentLoaded', () => {- // Assume renderSkillPricingUI() has been called and the HTML is on the page-- const container = document.getElementById('skill-pricing-container');-- container.addEventListener('change', (e) => {- if (e.target.classList.contains('paid-toggle')) {- const controls = e.target.closest('.skill-price-controls');- const priceInputs = controls.querySelector('.price-inputs');-- if (e.target.checked) {- priceInputs.style.display = 'flex';- priceInputs.querySelector('.price-amount').focus();- } else {- priceInputs.style.display = 'none';- }- }- });-});-```diff --git a/docs/monetization/05-wallet-integration.md b/docs/monetization/05-wallet-integration.mddeleted file mode 100644index 31e2ef9ed..000000000--- a/docs/monetization/05-wallet-integration.md+++ /dev/null@@ -1,69 +0,0 @@-----status: not-started------# Prompt 5: Wallet Integration--## Objective-Integrate a Solana wallet adapter to allow users to connect their wallets (e.g., Phantom, Solflare) to the web application.--## Explanation-To enable on-chain payments, the first step is allowing users to connect their cryptocurrency wallets. We will use the official Solana wallet-adapter libraries to provide a smooth, standardized connection experience for users. This will add a "Connect Wallet" button to the application's header and make the user's public key available to the frontend.--## Instructions-1. **Install Dependencies:**- * Add the required Solana wallet-adapter libraries to your project's `package.json`. You'll need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-react`, `@solana/wallet-adapter-wallets`, and potentially UI components for your framework (e.g., `@solana/wallet-adapter-react-ui`).- * Run `npm install` or `yarn` to install them.--2. **Set up the Wallet Provider:**- * In your main application component (e.g., `app.js` or a root-level layout component), wrap your application with the `ConnectionProvider`, `WalletProvider`, and `WalletModalProvider`.- * The `ConnectionProvider` needs an RPC endpoint for the Solana cluster you're targeting (e.g., mainnet-beta or devnet).- * The `WalletProvider` needs a list of the wallet adapters you want to support (e.g., `PhantomWalletAdapter`, `SolflareWalletAdapter`).--3. **Add the Connect Button:**- * In your site's header component (e.g., `nav.js` or `header.html`), add the `WalletMultiButton` component from the UI library. This single component handles all connection states (Connect, Connected, Disconnect).- * Ensure you style the button to match your site's aesthetic. You will need to import the adapter's CSS file (`@solana/wallet-adapter-react-ui/styles.css`).--4. **Access Wallet State:**- * Use the `useWallet` hook in your components to access the user's wallet state, such as `publicKey`, `connected`, `signTransaction`, etc.- * For example, you can now show or hide certain UI elements based on whether `connected` is true or false.--## Code Example (React-like, for `app.js` or similar)--```javascript-import React, { useMemo } from 'react';-import { ConnectionProvider, WalletProvider } from '@solana/wallet-adapter-react';-import { WalletAdapterNetwork } from '@solana/wallet-adapter-base';-import { PhantomWalletAdapter, SolflareWalletAdapter } from '@solana/wallet-adapter-wallets';-import { WalletModalProvider, WalletMultiButton } from '@solana/wallet-adapter-react-ui';-import { clusterApiUrl } from '@solana/web3.js';--// Default styles that can be overridden-require('@solana/wallet-adapter-react-ui/styles.css');--export const App = () => {- const network = WalletAdapterNetwork.Mainnet;- const endpoint = useMemo(() => clusterApiUrl(network), [network]);- const wallets = useMemo(() => [- new PhantomWalletAdapter(),- new SolflareWalletAdapter(),- ], [network]);-- return (- <ConnectionProvider endpoint={endpoint}>- <WalletProvider wallets={wallets} autoConnect>- <WalletModalProvider>- {/* Your existing app layout */}- <header>- {/* ... other header items ... */}- <WalletMultiButton />- </header>- <main>- {/* ... rest of your app ... */}- </main>- </WalletModalProvider>- </WalletProvider>- </ConnectionProvider>- );-};-```diff --git a/docs/monetization/05_ui_for_purchasing.md b/docs/monetization/05_ui_for_purchasing.mddeleted file mode 100644index 4e1f1234e..000000000--- a/docs/monetization/05_ui_for_purchasing.md+++ /dev/null@@ -1,116 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 05: UI for Purchasing a Skill--## Objective-On the agent detail page, replace the static price badge for paid skills with an interactive "Purchase" button.--## Explanation-Displaying the price is the first step. The next is to allow users to initiate a purchase. This involves changing the UI from a passive display to an active one. When a user clicks the "Purchase" button, it should trigger the on-chain purchase flow. For this task, we will focus only on creating the button and its initial states.--## Instructions-1. **Identify User's Owned Skills:**- * The API that fetches agent details for the marketplace view should also determine which skills the *currently authenticated user* already owns.- * This requires a new database query to check the `user_purchased_skills` table (which we will create in a later prompt). For now, you can assume the API returns a list of owned skill names, e.g., `agent.owned_skills: ["skill1", "skill2"]`.--2. **Update the UI in `src/marketplace.js`:**- * In the `renderDetail` function, where skills are rendered, implement conditional logic for each skill:- * If the skill is free, show a "Free" badge.- * If the skill is paid and the user already owns it, show an "Owned" badge or checkmark.- * If the skill is paid and the user does not own it, show a "Purchase" button with the price.--3. **Button Styling:**- * Add CSS for the new "Purchase" button and "Owned" badge to make them clear and visually appealing.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside renderDetail function-const skillPrices = a.skill_prices || {};-const ownedSkills = new Set(a.owned_skills || []); // Assume this is passed from the API--$('d-skills').innerHTML = skillsArr.map(s => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- let badgeHtml = '';-- if (price) {- if (ownedSkills.has(name)) {- badgeHtml = `<span class="skill-badge owned">✓ Owned</span>`;- } else {- const priceInUsdc = (price.amount / 1e6).toFixed(2);- badgeHtml = `<button class="btn btn-purchase" data-skill-name="${name}" data-agent-id="${a.id}">- Purchase for ${priceInUsdc} USDC- </button>`;- }- } else {- badgeHtml = `<span class="skill-badge free">Free</span>`;- }-- return `<div class="skill-entry">- <span class="skill-name">${escapeHtml(name)}</span>- ${badgeHtml}- </div>`;-}).join('');--// Add event listener for purchase buttons-document.getElementById('d-skills').addEventListener('click', (e) => {- if (e.target.matches('.btn-purchase')) {- const skillName = e.target.dataset.skillName;- const agentId = e.target.dataset.agentId;- // The purchase flow logic will be implemented in the next prompt- console.log(`Initiating purchase for skill '${skillName}' from agent '${agentId}'`);- e.target.disabled = true;- e.target.textContent = 'Preparing...';- }-});-```--## CSS Example--```css-/* Add to marketplace.css */-.skill-entry {- display: flex;- align-items: center;- justify-content: space-between;- padding: 8px;- border-radius: 6px;- background-color: #1a1a24; /* var(--panel2) */- margin-bottom: 6px;-}--.skill-badge, .btn-purchase {- flex-shrink: 0;-}--.btn-purchase {- font-size: 12px;- padding: 5px 10px;- background-color: var(--accent);- color: white;- border: none;- border-radius: 5px;- cursor: pointer;-}--.btn-purchase:hover {- filter: brightness(1.1);-}--.btn-purchase:disabled {- opacity: 0.6;- cursor: not-allowed;-}--.skill-badge.owned {- color: #4ade80; /* var(--ok) */- font-weight: 600;-}--.skill-badge.free {- color: #888; /* var(--muted) */-}-```diff --git a/docs/monetization/06-backend-payment-transaction-api.md b/docs/monetization/06-backend-payment-transaction-api.mddeleted file mode 100644index d528843f5..000000000--- a/docs/monetization/06-backend-payment-transaction-api.md+++ /dev/null@@ -1,99 +0,0 @@-----status: not-started------# Prompt 6: Backend - Payment Transaction API--## Objective-Create a backend API endpoint that generates a Solana transaction for a specific skill purchase and returns it to the frontend for signing.--## Explanation-To securely handle payments, the backend must be responsible for creating the transaction. The frontend will request a transaction for a specific skill, and this API will construct it, including the correct recipient address (the creator), the currency (e.g., USDC), and the amount. Returning the unsigned transaction to the frontend allows the user to sign it with their wallet without ever exposing their private key to our server.--## Instructions-1. **Create the API Endpoint:**- * Create a new API file, e.g., `api/payments/create-transaction.js`.- * This endpoint will accept `POST` requests at `/api/payments/create-transaction`.--2. **Request Body and Validation:**- * The request body from the frontend must include:- * `agentId`: The ID of the agent whose skill is being purchased.- * `skillName`: The name of the skill.- * `buyerPublicKey`: The public key of the user who is buying the skill.- * Validate this input.--3. **Fetch Skill and Creator Data:**- * From your database, fetch the price (`amount`, `currency_mint`) for the given `skillName` and `agentId` from the `agent_skill_prices` table.- * Fetch the agent creator's payout wallet address from the `creator_payout_wallets` table (or `agent_identities` if stored there). Let's call this `creatorPublicKey`.--4. **Construct the Solana Transaction:**- * Use the `@solana/web3.js` library.- * You will create a **Token Transfer** instruction using the `@solana/spl-token` library.- * The instruction needs:- * The buyer's associated token account for the currency (`source`).- * The creator's associated token account for the currency (`destination`).- * The buyer's main wallet address as the authority (`owner`).- * The `amount` from the database.- * The `currency_mint` from the database.- * **Important:** You may need to create the creator's associated token account if it doesn't exist. Your transaction might need to include the `createAssociatedTokenAccountInstruction`.- * Create a new `Transaction` and add the transfer instruction(s) to it.- * Set the `feePayer` to the `buyerPublicKey`.- * Set a `recentBlockhash`. You can get this from your Solana `Connection` object.--5. **Serialize and Return:**- * Serialize the transaction *without signing it*.- * Return the serialized transaction to the frontend, base64-encoded.--## Code Example (`api/payments/create-transaction.js`)--```javascript-import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';-import { json, wrap } from '../_lib/http.js';-import { sql } from '../_lib/db.js';-// ... other imports--const SOLANA_RPC_ENDPOINT = process.env.SOLANA_RPC_ENDPOINT;-const connection = new Connection(SOLANA_RPC_ENDPOINT);--export default wrap(async (req, res) => {- // ... authentication and input validation ...- const { agentId, skillName, buyerPublicKey } = req.body;- const buyer = new PublicKey(buyerPublicKey);-- // 1. Fetch price and creator wallet from DB- const [priceInfo] = await sql`...`; // Get amount and currency_mint- const [creatorInfo] = await sql`...`; // Get creator's payout wallet- if (!priceInfo || !creatorInfo) {- return json(res, 404, { error: 'Skill or creator wallet not found' });- }-- const creator = new PublicKey(creatorInfo.wallet_address);- const currencyMint = new PublicKey(priceInfo.currency_mint);- const amount = BigInt(priceInfo.amount);-- // 2. Get the buyer's and creator's token accounts- const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, buyer);- const creatorTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, currencyMint, creator);-- // 3. Create the transaction- const transaction = new Transaction();- transaction.add(- createTransferInstruction(- buyerTokenAccount.address, // from- creatorTokenAccount.address, // to- buyer, // owner- amount- )- );-- transaction.feePayer = buyer;- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;-- // 4. Serialize and encode- const serializedTransaction = transaction.serialize({ requireAllSignatures: false });- const base64Transaction = serializedTransaction.toString('base64');-- return json(res, 200, { transaction: base64Transaction });-});-```diff --git a/docs/monetization/06-create-backend-api-for-payments.md b/docs/monetization/06-create-backend-api-for-payments.mddeleted file mode 100644index a30171a24..000000000--- a/docs/monetization/06-create-backend-api-for-payments.md+++ /dev/null@@ -1,81 +0,0 @@-# Prompt 6: Create Backend API for Payment Transactions--## Status-- [ ] Not Started--## Objective-Create a backend API endpoint that prepares a Solana transaction for a skill purchase and sends it to the frontend for signing.--## Explanation-For security and reliability, the transaction should be constructed on the backend. The backend will determine the correct accounts (buyer, seller, mint) and amounts, create an unsigned transaction, serialize it, and send it to the frontend. The frontend's only job is to get the user's signature.--## Instructions-1. **Create a New API Endpoint:**- * Create a new API route, for example, `POST /api/payments/prepare-transaction`.- * This endpoint will require authentication to ensure only logged-in users can make purchases.--2. **Implement the Endpoint Logic:**- * The endpoint should accept a payload containing the `skill_name`, `agent_id`, and the buyer's public key.- * On the backend, retrieve the skill's price and currency mint from the `agent_skill_prices` table.- * Fetch the agent creator's wallet address (the seller).- * Construct a Solana transaction using `@solana/web3.js`. The transaction will be a simple SPL token transfer from the buyer's wallet to the seller's wallet.- * The transaction should be recent and have a recent blockhash.- * Serialize the transaction and send it back to the frontend in a base64-encoded format.--## Code Example (Backend - `/api/payments/prepare-transaction.js`)-```javascript-// /api/payments/prepare-transaction.js-import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';-import { getSkillPrice, getAgentCreatorWallet } from './_db.js'; // Placeholder for DB functions--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- const { skillName, agentId, buyerPublicKey } = req.body;-- // 1. Fetch skill price and seller's address- const priceInfo = await getSkillPrice(agentId, skillName);- const sellerPublicKey = await getAgentCreatorWallet(agentId);-- if (!priceInfo || !sellerPublicKey) {- return res.status(404).json({ error: 'Skill or seller not found' });- }-- // 2. Setup Solana connection- const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');- const buyer = new PublicKey(buyerPublicKey);- const seller = new PublicKey(sellerPublicKey);- const mint = new PublicKey(priceInfo.currency_mint);-- // 3. Get or create token accounts- const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, buyer);- const sellerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, seller);-- // 4. Create the transaction- const transaction = new Transaction();- transaction.add(- createTransferInstruction(- buyerTokenAccount.address,- sellerTokenAccount.address,- buyer,- priceInfo.amount- )- );-- // 5. Set recent blockhash and fee payer- transaction.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;- transaction.feePayer = buyer;-- // 6. Serialize and send to frontend- const serializedTransaction = transaction.serialize({- requireAllSignatures: false, // The buyer's signature is still needed- });-- res.status(200).json({- transaction: serializedTransaction.toString('base64'),- });-}-```diff --git a/docs/monetization/06-create-skill-nft-collection.md b/docs/monetization/06-create-skill-nft-collection.mddeleted file mode 100644index 05685ec03..000000000--- a/docs/monetization/06-create-skill-nft-collection.md+++ /dev/null@@ -1,56 +0,0 @@-# Prompt 6: Create Skill NFT Collection--## Objective-Develop a script or backend process to create a unique NFT collection for each agent. This collection will be used to mint "skill ownership" NFTs to users who purchase them.--## Explanation-Using NFTs to represent ownership provides a verifiable, on-chain record that a user has paid for a skill. The first step is to create a "collection" NFT, which acts as a master identifier for all the skill NFTs belonging to a specific agent. This ensures authenticity and allows for easy verification.--## Instructions-1. **Use Metaplex Umi:**- * The backend will need to interact with the Solana network. Use the Metaplex Umi library, which simplifies creating and managing NFTs.- * Set up a backend wallet (the "collection authority") that will pay the fees for creating the collection.--2. **Create Collection Script/Endpoint:**- * Develop a script (`scripts/create-agent-collection.mjs`) or a secure backend endpoint.- * This function should take an agent ID as input.- * It should generate a new keypair for the collection NFT's mint address.- * Using Umi, it will build and send a transaction to create:- 1. The collection mint account.- 2. The associated token account.- 3. The collection's metadata account (with name, symbol, etc., tied to the agent).- 4. The master edition account.--3. **Store Collection Address:**- * After the collection is created, its mint address must be stored in the database, associated with the agent. Add a `collection_mint` column to the `agents` table.--## Code Example (Backend Script using Umi)-```javascript-import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';-import { createNft, mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';-import { generateSigner, percentAmount } from '@metaplex-foundation/umi';--// 1. Setup Umi-const umi = createUmi('https://api.devnet.solana.com').use(mplTokenMetadata());-// Add your backend keypair to umi--// 2. Define the collection details-const collectionMint = generateSigner(umi);--// 3. Create the Collection NFT-async function createCollection() {- await createNft(umi, {- mint: collectionMint,- name: "Agent 'X' Skills",- symbol: 'AGENTX',- uri: 'URL_TO_JSON_METADATA', // Link to a JSON file with image, description, etc.- sellerFeeBasisPoints: percentAmount(5.5), // 5.5% royalty- isCollection: true,- }).sendAndConfirm(umi);-- console.log('Collection created with mint address:', collectionMint.publicKey);- // 4. Save `collectionMint.publicKey` to the database for the agent.-}--createCollection();-```diff --git a/docs/monetization/06-granting-skill-access.md b/docs/monetization/06-granting-skill-access.mddeleted file mode 100644index 895e68006..000000000--- a/docs/monetization/06-granting-skill-access.md+++ /dev/null@@ -1,69 +0,0 @@-# Prompt 6: Granting Skill Access (Backend)--## Objective-Upon successful purchase confirmation, create a database record that grants the user permanent access to the purchased skill.--## Explanation-This is the final step in the backend purchase flow. After the payment is verified, the system needs to record that the user now owns the skill. This is typically done by adding an entry to a linking table in the database, for example, `user_skill_ownership`. This record will be the source of truth for determining what premium content a user can access.--## Instructions-1. **Database Schema:**- * If it doesn't exist, design and create a `user_skill_ownership` table.- * Essential columns would be `id`, `user_id`, `agent_id`, `skill_name`, and `created_at`.- * The combination of `user_id` and `skill_name` (and perhaps `agent_id` if skills are not globally unique) should be unique.--2. **Create a Database Function (`_lib/db.js`):**- * Write a function, `grantSkillToUser(userId, agentId, skillName)`, that inserts a new record into the `user_skill_ownership` table.- * This function should handle potential errors, such as the user already owning the skill (which shouldn't happen if the purchase button is correctly disabled, but is good for data integrity).--3. **Integrate into Confirmation Flow:**- * In the `GET` handler of your `api/payments/prepare-skill-purchase.js` endpoint, after the transaction has been successfully verified (as per the previous prompt), call your new `grantSkillToUser` function.- * Pass the authenticated user's ID and the skill details that you retrieved from your database using the transaction `reference`.--## Database Schema Example (SQL)--```sql-CREATE TABLE user_skill_ownership (- id SERIAL PRIMARY KEY,- user_id UUID NOT NULL REFERENCES users(id),- agent_id UUID NOT NULL REFERENCES agents(id),- skill_name VARCHAR(255) NOT NULL,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- UNIQUE(user_id, agent_id, skill_name)-);---- Add an index for efficient lookups-CREATE INDEX idx_user_skill_ownership_user_id ON user_skill_ownership(user_id);-```--## Code Example (Backend - `_lib/db.js`)--```javascript-// This is a conceptual example using a generic DB client like 'pg' or 'slonik'-import { db } from './database-client';--export async function grantSkillToUser(userId, agentId, skillName) {- try {- const result = await db.query(- `- INSERT INTO user_skill_ownership (user_id, agent_id, skill_name)- VALUES ($1, $2, $3)- ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING- RETURNING id;- `,- [userId, agentId, skillName]- );-- if (result.rows.length > 0) {- console.log(`Granted skill '${skillName}' for agent '${agentId}' to user '${userId}'`);- return true;- } else {- console.warn(`User '${userId}' already owns skill '${skillName}' for agent '${agentId}'`);- return false; // Already owned- }- } catch (error) {- console.error('Error in grantSkillToUser:', error);- throw error;- }-}-```diff --git a/docs/monetization/06-marketplace-filters.md b/docs/monetization/06-marketplace-filters.mddeleted file mode 100644index 23edd25a1..000000000--- a/docs/monetization/06-marketplace-filters.md+++ /dev/null@@ -1,81 +0,0 @@-# Prompt 6: Marketplace Filters for Paid/Free Skills--## Objective-Add filtering options to the marketplace page (`marketplace.html`) to allow users to easily discover agents with paid skills, free skills, or both.--## Explanation-As the marketplace grows, users will need tools to find the agents that fit their needs and budget. A simple filter for monetization status (Free vs. Paid) is a crucial discovery feature.--## Instructions-1. **Modify Marketplace UI:**- * Open `marketplace.html`.- * Locate the filtering section of the page (where category or search filters might already exist).- * Add a new set of controls for filtering by price. A dropdown menu or a set of radio buttons would work well.- * Options: "All", "Paid Skills", "Free Skills".--2. **Update Frontend JavaScript:**- * Open `src/marketplace.js` (or wherever the marketplace frontend logic resides).- * Modify the function that fetches the list of agents (e.g., `searchAgents` or `loadAgents`).- * This function should now read the value of your new price filter.- * Pass the selected filter value as a query parameter in the API request to the backend. For example:- * `/api/marketplace/agents?pricing=paid`- * `/api/marketplace/agents?pricing=free`- * `/api/marketplace/agents` (for "All")--3. **Update Backend API:**- * Open the backend file that handles agent listings for the marketplace (e.g., `api/marketplace/agents.js`).- * The endpoint should now check for the `pricing` query parameter.- * **If `pricing=paid`:** Modify your database query to only return agents that have at least one entry in the `agent_skill_prices` table. This may require a `JOIN` or a subquery.- * **If `pricing=free`:** Modify your query to only return agents that have zero entries in the `agent_skill_prices` table. This may require a `LEFT JOIN` and a `WHERE ... IS NULL` check.- * **If the parameter is absent:** Return all agents as before.--## Code Example (Frontend - `marketplace.html`)--```html-<!-- Add to the filter section in marketplace.html -->-<div class="filter-group">- <label for="filter-pricing">Pricing</label>- <select id="filter-pricing">- <option value="all">All</option>- <option value="paid">Paid Skills</option>- <option value="free">Free Skills</option>- </select>-</div>-```--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside the function that triggers the agent search-function fetchAndRenderAgents() {- const pricingFilter = document.getElementById('filter-pricing').value;-- const queryParams = new URLSearchParams();- if (pricingFilter !== 'all') {- queryParams.set('pricing', pricingFilter);- }- // ... add other filters like search query, category ...-- const url = `/api/marketplace/agents?${queryParams.toString()}`;-- fetch(url)- .then(res => res.json())- .then(data => {- renderAgentGrid(data.agents);- });-}-```--## Code Example (Backend - SQL Query Idea)--```sql--- For pricing=paid-SELECT agents.* FROM agents-INNER JOIN agent_skill_prices ON agents.id = agent_skill_prices.agent_id-GROUP BY agents.id;---- For pricing=free-SELECT agents.* FROM agents-LEFT JOIN agent_skill_prices ON agents.id = agent_skill_prices.agent_id-WHERE agent_skill_prices.agent_id IS NULL;-```diff --git a/docs/monetization/06-solana-pay-endpoint.md b/docs/monetization/06-solana-pay-endpoint.mddeleted file mode 100644index 6b412ecde..000000000--- a/docs/monetization/06-solana-pay-endpoint.md+++ /dev/null@@ -1,93 +0,0 @@-----status: not-started-completed_at: null-----# Prompt 6: On-Chain Payment API with Solana Pay--## Objective-Create a backend API endpoint that generates a Solana Pay transaction request for purchasing a specific agent skill.--## Explanation-To accept payments for skills, we need to integrate with the Solana blockchain. This prompt outlines the creation of an API endpoint that follows the Solana Pay specification. When a user wants to buy a skill, the frontend will call this endpoint. The endpoint will generate the details for a valid SPL Token transfer transaction, which the user's wallet will then use to approve the payment.--## Instructions-1. **Define the API Endpoint:**- * Create a new route: `GET /api/purchase/skill/:agentId/:skillName`. This will be the main endpoint for initiating a purchase.- * Also, create a `POST` handler for the same route, which will be used by the Solana Pay protocol to validate the transaction after the user signs it.--2. **Implement the `GET` Handler (Transaction Request):**- * **Fetch Skill Price:** From the database, retrieve the `amount` and `currency_mint` for the requested `agentId` and `skillName`. If not found, return a `404 Not Found`.- * **Fetch Creator's Wallet:** Get the agent creator's destination wallet address. This should be stored securely with the creator's user profile.- * **Generate a Unique Reference Key:** Create a new, unique keypair (`Keypair.generate()`). The public key of this keypair will serve as a unique reference for the transaction, preventing double-spending. Store this reference in your database or cache temporarily, associating it with the purchase details (user, skill, agent).- * **Construct the Solana Pay Response:**- * `label`: The name of your platform.- * `icon`: A URL to your platform's logo.- * For the `POST` handler, construct the JSON response which includes the details needed for the wallet to build the transaction:- * `transaction`: A Base64-encoded, serialized, but **unsigned** transaction.- * `message` (optional): A descriptive message, e.g., "Purchase 'translate' skill for Agent 'X'".- * The transaction should be a simple SPL Token transfer from the buyer (the wallet will fill this in) to the creator's wallet address.- * The transaction must include the unique `reference` public key.--3. **Implement the `POST` Handler (Transaction Validation):**- * **Receive Transaction:** The wallet will send the user-signed transaction to this endpoint. The body will contain `{ transaction: "..." }`.- * **Deserialize and Verify:**- * Deserialize the transaction.- * Check that the signature is valid for the expected signer (the user).- * Verify that the transaction details match the expected purchase: correct recipient, correct amount, correct SPL token mint, and the **correct unique reference key**. This is crucial for security.- * **Record the Purchase:** If verification passes, save the purchase details to your `user_skill_purchases` table, including the transaction signature.- * **Return Confirmation:** Respond with a success message including the transaction signature.--## Code Example (Backend `GET` Handler)--```javascript-// Example using Express.js and @solana/web3.js, @solana/spl-token--// GET /api/purchase/skill/:agentId/:skillName-app.get('/api/purchase/skill/:agentId/:skillName', async (req, res) => {- // ... fetch skillPrice, creatorWallet from db ...-- const { amount, currency_mint } = skillPrice;- const recipient = new PublicKey(creatorWallet);- const splToken = new PublicKey(currency_mint);-- // Generate a unique reference for this transaction- const reference = new Keypair().publicKey;- // Store reference in cache/db to validate it in the POST request- await cache.set(`ref_${reference.toBase58()}`, { agentId, skillName, userId: req.user.id });-- res.status(200).json({- label: "My 3D Agent Platform",- icon: "https://my-platform.com/logo.png",- });-});--// POST /api/purchase/skill/:agentId/:skillName-app.post('/api/purchase/skill/:agentId/:skillName', async (req, res) => {- // This endpoint should return the actual transaction details- const { account } = req.body;- if (!account) {- return res.status(400).json({ error: 'Account is required.' });- }- // ... fetch skillPrice, creatorWallet from db ...- // ... generate reference, etc ...-- // Create the unsigned transaction- const transaction = new Transaction();- // ... add SPL token transfer instruction ...- // The instruction needs: source (user's wallet), destination (creator's wallet), amount, mint.- // The wallet will provide the user's source token account.-- res.status(200).json({- transaction: transaction.serialize({ requireAllSignatures: false, verifySignatures: false }).toString('base64'),- message: `Purchase skill for ${(amount / 1e6).toFixed(2)} USDC`,- });-});-```--## Definition of Done-- A `GET` endpoint exists at `/api/purchase/skill/:agentId/:skillName` that returns the `label` and `icon` for a Solana Pay request.-- A `POST` endpoint exists at the same URL that takes a public key `account` and returns a serialized, unsigned transaction.-- The transaction is a valid SPL token transfer for the correct amount and token.-- A unique reference key is generated for each transaction request.-- The `POST` handler for validating the final signed transaction is implemented and secure.-- Successful purchases are recorded in the `user_skill_purchases` table.diff --git a/docs/monetization/06-solana-pay-integration.md b/docs/monetization/06-solana-pay-integration.mddeleted file mode 100644index 446e3c319..000000000--- a/docs/monetization/06-solana-pay-integration.md+++ /dev/null@@ -1,91 +0,0 @@-----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/06-ui-payment-modal.md b/docs/monetization/06-ui-payment-modal.mddeleted file mode 100644index 884a45bd8..000000000--- a/docs/monetization/06-ui-payment-modal.md+++ /dev/null@@ -1,45 +0,0 @@-----status: not-started------# Prompt 6: UI Payment Modal--## Objective-Design and implement a payment confirmation modal that appears when a user clicks the "Purchase Skill" button.--## Explanation-A modal is an excellent way to provide a focused and clear payment experience. This modal will display the details of the skill being purchased, the price, and a final confirmation button to initiate the transaction.--## Instructions-1. **Create the Modal HTML:**- * In `marketplace.html`, add the HTML structure for a modal. It should be hidden by default.- * The modal should have a header, body, and footer.- * The body should contain placeholders for the skill name, price, and other details.- * The footer should have "Cancel" and "Confirm Purchase" buttons.--2. **Implement JavaScript Logic:**- * In `src/marketplace.js`, add an event listener for clicks on the "Purchase" buttons.- * When a button is clicked, populate the modal with the correct skill information and display it.- * The "Confirm Purchase" button will trigger the blockchain transaction.--## Code Example (HTML - `marketplace.html`)--```html-<div id="payment-modal" class="modal-overlay hidden">- <div class="modal">- <div class="modal-header">- <h3>Confirm Purchase</h3>- <button id="close-payment-modal">×</button>- </div>- <div class="modal-body">- <p>You are about to purchase the skill:</p>- <h4 id="modal-skill-name"></h4>- <p>Price: <strong id="modal-skill-price"></strong></p>- </div>- <div class="modal-footer">- <button id="cancel-purchase" class="btn">Cancel</button>- <button id="confirm-purchase" class="btn btn-primary">Confirm</button>- </div>- </div>-</div>-```diff --git a/docs/monetization/06-verifying-purchase-and-unlocking-skill.md b/docs/monetization/06-verifying-purchase-and-unlocking-skill.mddeleted file mode 100644index 5e6f8d51c..000000000--- a/docs/monetization/06-verifying-purchase-and-unlocking-skill.md+++ /dev/null@@ -1,89 +0,0 @@-# Prompt 6: Verifying Purchase and Unlocking Skill--## Objective-Create a backend system to verify that a skill purchase transaction was successful on-chain and then formally grant the user access to that skill in the database.--## Explanation-After the frontend submits the transaction to the Solana network, it gets a transaction signature. The frontend then sends this signature to our backend. The backend's job is to use this signature to query the Solana blockchain, confirm the transaction was successfully processed and finalized, and then update our application's database to reflect that the user now owns the skill. This is a critical step for security and ensuring users get what they paid for.--## Instructions-1. **Create a Verification Endpoint:**- * Create a new API endpoint, e.g., `/api/marketplace/skills/verify-purchase`.- * This endpoint will accept a POST request containing the `transactionSignature`, `agentId`, and `skillName`.--2. **Backend Verification Logic:**- * The endpoint will use the Solana `@solana/web3.js` library to connect to the cluster.- * It will call `connection.getTransaction(transactionSignature)` to fetch the transaction details.- * The backend must parse the transaction to ensure it matches what was expected:- * Was the transfer from the correct buyer?- * Was it to the correct creator treasury?- * Was the amount correct?- * Was the currency (mint) correct?- * This verification prevents users from sending fake transaction signatures or signatures for unrelated transactions.--3. **Update the Database:**- * If the on-chain transaction is fully verified, the backend will add a new record to a `user_purchased_skills` table.- * This table should link a user ID to the agent ID and skill name they purchased.--## Database Schema (`user_purchased_skills`)--```sql-CREATE TABLE user_purchased_skills (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID REFERENCES auth.users(id) NOT NULL,- agent_id UUID REFERENCES agents(id) NOT NULL,- skill_name TEXT NOT NULL,- purchased_at TIMESTAMPTZ DEFAULT NOW(),- transaction_signature TEXT NOT NULL,- UNIQUE(user_id, agent_id, skill_name)-);-```--## Code Example (`api/marketplace/skills/verify-purchase.js`)--```javascript-import { Connection, clusterApiUrl } from '@solana/web3.js';-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';--export default async function handler(req, res) {- const { transactionSignature, agentId, skillName } = req.body;- // Assume we get userId from session/token- const { userId } = await getUserFromRequest(req);-- if (!userId) return error(res, 401, 'Unauthorized');-- const connection = new Connection(clusterApiUrl('devnet'));-- // 1. Confirm the transaction is valid and finalized- const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });-- if (!tx || !tx.meta || tx.meta.err) {- return error(res, 400, 'Transaction not found or failed.');- }-- // 2. Perform deep verification (omitted for brevity, but crucial)- // - Check sender, receiver, amount, mint etc. match expected values- // - This prevents re-using old signatures or sending malicious ones.-- // 3. If verified, record the purchase in the database- const { error: dbError } = await supabase- .from('user_purchased_skills')- .insert({- user_id: userId,- agent_id: agentId,- skill_name: skillName,- transaction_signature: transactionSignature,- });-- if (dbError) {- // Handle potential unique constraint violation (user trying to re-verify)- if (dbError.code === '23505') {- return json(res, { success: true, message: 'Skill already unlocked.' });- }- return error(res, 500, 'Failed to record purchase.');- }-- return json(res, { success: true, message: 'Skill unlocked successfully!' });-}-```diff --git a/docs/monetization/06_db_schema_for_purchases.md b/docs/monetization/06_db_schema_for_purchases.mddeleted file mode 100644index 005c86369..000000000--- a/docs/monetization/06_db_schema_for_purchases.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 06: Database Schema for Purchased Skills--## Objective-Create the necessary database table to track which users have purchased which skills.--## Explanation-To manage access to paid skills, we need to record every successful purchase. A `user_purchased_skills` table will create a permanent record linking a user to a specific agent's skill they have acquired. This table is critical for the access control logic that will be built later.--## Instructions-1. **Design the Table:**- * Create a new table named `user_purchased_skills`.- * The table should have the following columns:- * `id`: Primary key (UUID or SERIAL).- * `user_id`: Foreign key referencing the `users` table.- * `agent_id`: Foreign key referencing the `agent_identities` table.- * `skill_name`: A text field for the name of the skill.- * `purchase_tx_signature`: The on-chain transaction signature of the purchase, for auditing purposes.- * `price_amount`: The amount paid (in lamports or smallest unit).- * `price_currency_mint`: The currency used for the purchase.- * `created_at`: Timestamp of purchase.- * Add a unique constraint on (`user_id`, `agent_id`, `skill_name`) to prevent duplicate purchase records.--2. **Write the SQL Migration:**- * Create a new SQL migration file.- * Write the `CREATE TABLE` statement based on the design.- * Add indexes on `user_id` and `agent_id` to speed up lookups for checking skill ownership.--## SQL Example--Here is the PostgreSQL `CREATE TABLE` statement.--```sql-CREATE TABLE IF NOT EXISTS user_purchased_skills (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL,- agent_id UUID NOT NULL,- skill_name VARCHAR(255) NOT NULL,- purchase_tx_signature VARCHAR(128) NOT NULL,- price_amount BIGINT NOT NULL,- price_currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- CONSTRAINT fk_user- FOREIGN KEY(user_id)- REFERENCES users(id)- ON DELETE CASCADE,-- CONSTRAINT fk_agent- FOREIGN KEY(agent_id)- REFERENCES agent_identities(id)- ON DELETE CASCADE,-- UNIQUE (user_id, agent_id, skill_name)-);--CREATE INDEX idx_user_purchased_skills_user_id ON user_purchased_skills(user_id);-CREATE INDEX idx_user_purchased_skills_agent_id ON user_purchased_skills(agent_id);-```diff --git a/docs/monetization/07-creator-dashboard-monetization-tab.md b/docs/monetization/07-creator-dashboard-monetization-tab.mddeleted file mode 100644index e86b55e0f..000000000--- a/docs/monetization/07-creator-dashboard-monetization-tab.md+++ /dev/null@@ -1,93 +0,0 @@-# Prompt 7: Creator Dashboard Monetization Tab--## Objective-Create the basic structure for a new "Monetization" tab within the agent creator's dashboard, where they will manage skill pricing and view earnings.--## Explanation-To empower creators to sell their skills, they need a dedicated space within the application to manage their monetization settings. This first step involves creating the UI shell for this new section. We will add a new tab to the agent editing interface and create the container where the pricing and earnings components will live.--## Instructions-1. **Add Tab to Dashboard UI:**- * Locate the HTML file for the agent editing/dashboard page (e.g., `agent-edit.html`).- * Add a new tab button for "Monetization" alongside existing tabs like "Profile" or "Skills".- * Add a corresponding tab panel container that will be shown when the Monetization tab is active.--2. **Implement Tab Switching Logic:**- * In the corresponding JavaScript file (e.g., `src/agent-edit.js`), update the tab switching logic to handle the new Monetization tab.- * When the Monetization tab is clicked, its panel should become visible, and others should be hidden.--3. **Create Placeholder Content:**- * Inside the Monetization tab panel, add placeholder sections for "Skill Pricing" and "Earnings". This sets the stage for future prompts where we will build out these features.--## HTML Example (`agent-edit.html`)--```html-<!-- In the tab list -->-<div class="tabs">- <button class="tab-link" data-tab="profile">Profile</button>- <button class="tab-link" data-tab="skills">Skills</button>- <button class="tab-link" data-tab="monetization">Monetization</button>-</div>--<!-- In the tab content area -->-<div class="tab-content-wrapper">- <div id="profile" class="tab-content">...</div>- <div id="skills" class="tab-content">...</div>- <div id="monetization" class="tab-content" style="display: none;">- <h2>Monetization</h2>- <div class="card">- <h3>Skill Pricing</h3>- <p>Set the price for your agent's premium skills.</p>- <div id="skill-pricing-container">- <!-- Pricing UI will go here -->- </div>- </div>- <div class="card">- <h3>Earnings</h3>- <p>View your sales and manage payouts.</p>- <div id="earnings-container">- <!-- Earnings dashboard will go here -->- </div>- </div>- <div class="card">- <h3>Payout Wallet</h3>- <p>Set the Solana wallet address where you will receive payments.</p>- <div id="treasury-wallet-container">- <label for="treasuryWallet">Your Solana Wallet Address:</label>- <input type="text" id="treasuryWallet" placeholder="Enter public key...">- <button id="saveTreasuryWallet">Save</button>- </div>- </div>- </div>-</div>-```--## JavaScript Example (`src/agent-edit.js`)--```javascript-document.addEventListener('DOMContentLoaded', () => {- const tabs = document.querySelectorAll('.tab-link');- const contents = document.querySelectorAll('.tab-content');-- tabs.forEach(tab => {- tab.addEventListener('click', () => {- const target = tab.getAttribute('data-tab');-- // Hide all content- contents.forEach(content => {- content.style.display = 'none';- });-- // Show target content- document.getElementById(target).style.display = 'block';-- // Update active tab style- tabs.forEach(t => t.classList.remove('active'));- tab.classList.add('active');- });- });-- // Default to the first tab- tabs[0].click();-});-```diff --git a/docs/monetization/07-frontend-payment-and-signing.md b/docs/monetization/07-frontend-payment-and-signing.mddeleted file mode 100644index 474fa0c66..000000000--- a/docs/monetization/07-frontend-payment-and-signing.md+++ /dev/null@@ -1,83 +0,0 @@-# Prompt 7: Frontend Payment and Transaction Signing--## Status-- [ ] Not Started--## Objective-Implement the frontend logic to receive the serialized transaction from the backend, prompt the user to sign it with their wallet, and send the signed transaction to the network.--## Explanation-This prompt connects the UI to the backend payment API. When the user confirms a purchase, the frontend will fetch the transaction, use the wallet adapter to sign it, and then broadcast it to the Solana network.--## Instructions-1. **Update Modal Event Listener:**- * In the `handlePurchaseClick` logic, add a click event listener to the `modal-confirm-btn`.- * This listener will trigger the payment process.--2. **Implement the Payment Flow:**- * When the confirm button is clicked, make a `POST` request to your `/api/payments/prepare-transaction` endpoint.- * Send the necessary data: `skillName`, `agentId`, and the connected user's public key.- * The backend will respond with a base64-encoded serialized transaction.--3. **Sign and Send the Transaction:**- * Deserialize the transaction received from the backend.- * Use the connected wallet adapter's `signTransaction` method.- * Once signed, use the `connection.sendRawTransaction` method from `@solana/web3.js` to broadcast it.- * Wait for the transaction to be confirmed and then notify the user of the result (success or failure).--## Code Example (Frontend Payment Logic)-```javascript-// Add this to your marketplace.js or a dedicated payments module-import { Connection, Transaction } from '@solana/web3.js';-import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';--const connection = new Connection(process.env.NEXT_PUBLIC_SOLANA_RPC_URL, 'confirmed');--async function handleConfirmPurchase() {- const skillData = JSON.parse(document.getElementById('modal-confirm-btn').dataset.skillData);- const buyerPublicKey = getConnectedWalletAddress();- const wallet = getConnectedWallet();-- if (!buyerPublicKey || !wallet) {- alert('Please connect your wallet first.');- return;- }-- // 1. Fetch transaction from backend- const response = await fetch('/api/payments/prepare-transaction', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- ...skillData,- buyerPublicKey,- agentId: currentAgent.id, // Assuming 'currentAgent' is available in scope- }),- });-- const { transaction: base64Transaction } = await response.json();- const transactionBuffer = Buffer.from(base64Transaction, 'base64');- const transaction = Transaction.from(transactionBuffer);-- try {- // 2. Sign the transaction- const signedTransaction = await wallet.signTransaction(transaction);-- // 3. Send and confirm the transaction- const signature = await connection.sendRawTransaction(signedTransaction.serialize());- await connection.confirmTransaction(signature, 'confirmed');-- alert(`Purchase successful! Transaction signature: ${signature}`);- // Next step: Update UI to show the user owns the skill.- } catch (error) {- console.error('Purchase failed:', error);- alert('Purchase failed. See console for details.');- } finally {- // Hide the modal- document.getElementById('purchase-confirm-modal').classList.add('modal-hidden');- }-}--// Attach this to the confirm button-document.getElementById('modal-confirm-btn').addEventListener('click', handleConfirmPurchase);--```diff --git a/docs/monetization/07-frontend-unlock-skill-button.md b/docs/monetization/07-frontend-unlock-skill-button.mddeleted file mode 100644index dbe70c21d..000000000--- a/docs/monetization/07-frontend-unlock-skill-button.md+++ /dev/null@@ -1,100 +0,0 @@-----status: not-started------# Prompt 7: Frontend - "Unlock Skill" Button--## Objective-Update the marketplace UI (`marketplace.js` and `marketplace.html`) to show a prominent "Unlock" or "Purchase" button next to paid skills.--## Explanation-Now that we can display prices, the next logical step for the user is an action to purchase the skill. This task involves changing the static price badge into an interactive button for skills that are not free and have not yet been purchased by the user.--## Instructions-1. **Fetch User's Unlocked Skills:**- * You'll need a way to know which skills the currently logged-in user already owns. This requires a new API endpoint, e.g., `GET /api/users/me/unlocked-skills`, which returns an array of skill names or IDs the user has purchased.- * In `marketplace.js`, when the application loads, fetch this list of unlocked skills and store it.--2. **Modify the `renderDetail` function:**- * In `src/marketplace.js`, within the `renderDetail` function where you iterate over skills, you now need three pieces of information for each skill:- 1. The skill's details (name, description).- 2. The skill's price (from `agent.skill_prices`).- 3. Whether the current user has unlocked it (from the list fetched in step 1).--3. **Conditional Rendering Logic:**- * Inside the loop, implement the following logic for each skill:- * **If `price` does not exist:** The skill is free. Render a "Free" badge.- * **If `price` exists AND the user has unlocked the skill:** The skill is already owned. Render an "Unlocked" or "Owned" badge.- * **If `price` exists AND the user has NOT unlocked the skill:** The skill is available for purchase. Render a "Unlock for X USDC" button.--4. **Add Data Attributes:**- * The "Unlock" button needs to have necessary information attached to it so its event handler knows what to do. Use `data-*` attributes to store the `agentId` and `skillName`.--## Code Example (`src/marketplace.js` inside `renderDetail`)--```javascript-// Assume `unlockedSkills` is a Set or array of skill names fetched on page load-const unlockedSkills = new Set(['Jupiter Swapper']); // Example data--// ... inside renderDetail loop ...-const skillPrices = a.skill_prices || {};-$('d-skills').innerHTML = skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];-- let badgeHtml;- if (!price) {- badgeHtml = `<span class="price-badge price-free">Free</span>`;- } else if (unlockedSkills.has(name)) {- badgeHtml = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;- } else {- const amount = (price.amount / 1e6).toFixed(2);- badgeHtml = `- <button- class="btn-unlock-skill"- data-agent-id="${escapeHtml(a.id)}"- data-skill-name="${escapeHtml(name)}">- Unlock for ${amount} USDC- </button>- `;- }-- return `<div class="skill-entry">- <span class="skill-name">${escapeHtml(name)}</span>- ${badgeHtml}- </div>`;-}).join('');-```--## CSS Example (`/marketplace.css`)--```css-.skill-entry {- display: flex;- justify-content: space-between;- align-items: center;- padding: 8px 4px;- border-bottom: 1px solid #333;-}--.price-unlocked {- color: #a7f3d0; /* Same as free, but with a checkmark */- background-color: rgba(52, 211, 153, 0.1);-}--.btn-unlock-skill {- background-color: #4f46e5;- color: white;- border: none;- padding: 4px 10px;- font-size: 11px;- font-weight: 600;- border-radius: 5px;- cursor: pointer;- transition: background-color 0.2s;-}--.btn-unlock-skill:hover {- background-color: #6366f1;-}-```diff --git a/docs/monetization/07-marketplace-paid-indicator.md b/docs/monetization/07-marketplace-paid-indicator.mddeleted file mode 100644index 714c8b12c..000000000--- a/docs/monetization/07-marketplace-paid-indicator.md+++ /dev/null@@ -1,87 +0,0 @@-# Prompt 7: Visual Indicator for Paid Agents in Marketplace--## Objective-Add a visual badge or indicator to agent cards in the main marketplace grid to quickly show users which agents offer paid skills.--## Explanation-While filters are useful, users browsing the full list of agents should be able to identify monetized agents at a glance. A simple, clear visual indicator (like a "$" icon or a "Premium" badge) on the agent card will significantly improve scannability.--## Instructions-1. **Modify Backend API:**- * The marketplace agent list endpoint (`/api/marketplace/agents`) needs to provide a flag indicating if an agent has any paid skills.- * When querying the list of agents, perform a `JOIN` or a subquery with `agent_skill_prices`.- * For each agent in the response, add a boolean field, such as `has_paid_skills: true` or `false`.- * *Optimization Note:* This is more efficient than the frontend making a separate request for each agent.--2. **Update Frontend UI:**- * Open `src/marketplace.js`, and find the function that renders the grid of agent cards (e.g., `renderAgentGrid`).- * Inside the loop that creates each agent card, check for the new `agent.has_paid_skills` flag.- * If the flag is `true`, add an HTML element for the badge to the card's template.--3. **Add CSS Styling:**- * Open `/marketplace.css` (or the relevant stylesheet).- * Add styles for your new badge to make it stand out. Position it in a corner of the agent card, for example.--## Code Example (Backend - SQL Query Idea)--```sql--- A query to fetch agents and a flag indicating if they have priced skills-SELECT- agents.*,- (CASE WHEN COUNT(agent_skill_prices.skill_name) > 0 THEN TRUE ELSE FALSE END) AS has_paid_skills-FROM- agents-LEFT JOIN- agent_skill_prices ON agents.id = agent_skill_prices.agent_id-GROUP BY- agents.id;-```--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside your function that renders the agent grid (e.g., renderAgentGrid)--function renderAgentCard(agent) {- const card = document.createElement('div');- card.className = 'agent-card';-- const premiumBadge = agent.has_paid_skills- ? '<div class="premium-badge" title="Offers paid skills">⚡</div>'- : '';-- card.innerHTML = `- <div class="card-thumbnail" style="background-image: url('${escapeHtml(agent.thumbnail_url)}')">- ${premiumBadge}- </div>- <div class="card-body">- <h3 class="card-title">${escapeHtml(agent.name)}</h3>- <p class="card-description">${escapeHtml(agent.description)}</p>- </div>- `;- return card;-}-```--## Code Example (CSS - `/marketplace.css`)--```css-.agent-card .card-thumbnail {- position: relative;- /* ... existing styles ... */-}--.premium-badge {- position: absolute;- top: 8px;- right: 8px;- background-color: rgba(253, 224, 71, 0.9); /* Same as --paid-bg but more opaque */- color: #18181b; /* Dark text for contrast */- padding: 1px 6px;- font-size: 14px;- font-weight: 700;- border-radius: 6px;- line-height: 1.4;- box-shadow: 0 1px 3px rgba(0,0,0,0.3);-}-```diff --git a/docs/monetization/07-mint-skill-nft-on-purchase.md b/docs/monetization/07-mint-skill-nft-on-purchase.mddeleted file mode 100644index ec7cdb2b9..000000000--- a/docs/monetization/07-mint-skill-nft-on-purchase.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 7: Mint Skill NFT on Purchase--## Objective-After a user's payment transaction is successfully confirmed, the backend should mint a new NFT from the agent's collection to the user's wallet.--## Explanation-This step connects the payment with the proof-of-ownership. Minting an NFT serves as an on-chain receipt and a perpetual license for the user to access the skill. This NFT is a standard SPL token, making it viewable in wallets and on explorers.--## Instructions-1. **Create a Backend Minting Endpoint:**- * Create a new API endpoint, e.g., `/api/skills/mint`. This endpoint should be called by the frontend *after* a payment transaction is confirmed.- * It should accept the `agent_id`, `skill_name`, and the `user_wallet` address as parameters. It should also take the payment `transaction_signature` for verification.--2. **Verify Payment:**- * Before minting, the backend *must* verify that the provided `transaction_signature` is valid, recent, and corresponds to the correct payment (correct amount to the correct creator). This prevents fraudulent minting requests.--3. **Mint the NFT using Umi:**- * Fetch the agent's `collection_mint` address from the database.- * Generate a new signer for the skill NFT's mint address.- * Use Umi's `createNft` function, but this time:- * Set the `collection` property to the agent's collection mint address.- * The `name` and `uri` should be specific to the skill being purchased.- * The `owner` should be the user's public key.--4. **Return NFT Details:**- * The endpoint should return the mint address of the newly created skill NFT to the frontend.--## Code Example (Backend Minting Endpoint using Umi)-```javascript-// Inside the /api/skills/mint endpoint-import { createNft, mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata';--// ... (After setting up umi and verifying payment)--const agentCollectionMint = getAgentCollectionMintFromDB(agentId);-const userPublicKey = new PublicKey(userWallet);-const skillNftMint = generateSigner(umi);--const { signature } = await createNft(umi, {- mint: skillNftMint,- owner: userPublicKey,- name: `Skill: ${skillName}`,- uri: `URL_TO_${skillName}_METADATA.json`,- sellerFeeBasisPoints: percentAmount(0), // No royalties on individual skills- collection: {- verified: false, // The collection authority needs to verify this in a separate transaction- key: agentCollectionMint,- },-}).sendAndConfirm(umi);--// After minting, you must also run a 'verifyCollection' transaction-// so the NFT shows up as part of the official collection in wallets.--res.status(200).json({ nftMint: skillNftMint.publicKey, signature });-```diff --git a/docs/monetization/07-purchase-skill-ui.md b/docs/monetization/07-purchase-skill-ui.mddeleted file mode 100644index a4cf1b907..000000000--- a/docs/monetization/07-purchase-skill-ui.md+++ /dev/null@@ -1,109 +0,0 @@-----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">×</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/07-real-time-ui-update.md b/docs/monetization/07-real-time-ui-update.mddeleted file mode 100644index afb3aafe4..000000000--- a/docs/monetization/07-real-time-ui-update.md+++ /dev/null@@ -1,88 +0,0 @@-# Prompt 7: Real-time UI Update on Purchase--## Objective-Update the agent detail page UI in real-time to reflect a successful skill purchase without requiring a page refresh.--## Explanation-A seamless user experience requires immediate feedback. After a user approves the transaction on their phone, the webpage should detect the successful purchase and automatically update the UI. It should change the "Purchase" button to an "Owned" status indicator. We can achieve this by having the frontend poll a confirmation endpoint while the payment modal is open.--## Instructions-1. **Create a Polling Endpoint (Backend):**- * Create a new, simple endpoint, e.g., `/api/payments/check-purchase-status`.- * This endpoint will take a transaction `reference` ID as a query parameter.- * It will check the `user_skill_ownership` table to see if the record for that purchase exists.- * It should return a status, e.g., `{ status: 'confirmed' }` or `{ status: 'pending' }`.--2. **Implement Polling (Frontend - `src/marketplace.js`):**- * When you first make the `POST` request to prepare the transaction, the response should include the unique `reference` ID.- * Once the QR code is displayed, start a polling mechanism (e.g., using `setInterval`).- * Every 2-3 seconds, make a `GET` request to `/api/payments/check-purchase-status?reference=<reference_id>`.- * If the status comes back as `confirmed`:- * Stop the polling (`clearInterval`).- * Close the payment modal.- * Re-render the skills section or dynamically update the specific skill entry in the DOM to show the "Owned" state.- * Show a success notification (toast).- * The polling should also have a timeout (e.g., 5 minutes) to prevent it from running forever if something goes wrong.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside handlePurchaseClick, after the POST request succeeds-const { transaction, message, reference } = await response.json(); // Backend must return reference--const url = `solana:${encodeURIComponent(transaction)}`;-renderPaymentModal(url, message);--// Start polling for confirmation-const pollInterval = setInterval(async () => {- try {- const statusRes = await fetch(`/api/payments/check-purchase-status?reference=${reference}`);- const { status } = await statusRes.json();-- if (status === 'confirmed') {- clearInterval(pollInterval);- $('payment-modal').close();- showToast('Purchase successful!', 'success');-- // Find the button and replace it with an 'Owned' span- const button = document.querySelector(`.purchase-skill-btn[data-skill-name="${skillName}"]`);- if (button) {- const ownedSpan = document.createElement('span');- ownedSpan.className = 'skill-owned';- ownedSpan.textContent = '✓ Owned';- button.replaceWith(ownedSpan);- }- }- } catch (err) {- // Silently ignore polling errors, or stop polling after too many failures- console.warn('Polling error:', err);- }-}, 2500);--// Add a timeout to stop polling after 5 minutes-setTimeout(() => {- clearInterval(pollInterval);-}, 300000);-```--## Backend Status Endpoint (`api/payments/check-purchase-status.js`)--```javascript-import { findOwnershipByReference } from '../_lib/db'; // Placeholder DB function--export default async function handler(req, res) {- if (req.method !== 'GET') return res.status(405).end();-- const { reference } = req.query;- if (!reference) return res.status(400).json({ error: 'Reference required' });-- // This DB function needs to link the reference to the ownership record- const isOwned = await findOwnershipByReference(reference);-- if (isOwned) {- return res.status(200).json({ status: 'confirmed' });- } else {- return res.status(200).json({ status: 'pending' });- }-}-```diff --git a/docs/monetization/07-solana-payment-integration.md b/docs/monetization/07-solana-payment-integration.mddeleted file mode 100644index b0f5f28c0..000000000--- a/docs/monetization/07-solana-payment-integration.md+++ /dev/null@@ -1,50 +0,0 @@-----status: not-started------# Prompt 7: Solana Payment Integration--## Objective-Integrate the Solana wallet-adapter to process skill purchase transactions on the Solana blockchain.--## Explanation-To handle payments in a decentralized way, we will use the Solana wallet-adapter to connect to the user's wallet (like Phantom) and request them to sign and send the transaction.--## Instructions-1. **Add Wallet-Adapter Dependencies:**- * Include the necessary wallet-adapter scripts in `marketplace.html`.- * You will need `@solana/wallet-adapter-base`, `@solana/wallet-adapter-wallets`, and `@solana/web3.js`.--2. **Implement Connection Logic:**- * In `src/marketplace.js`, add a "Connect Wallet" button and the logic to connect to the user's wallet.- * Store the user's public key when they connect.--3. **Implement the Purchase Transaction:**- * When the user confirms the purchase in the modal, construct a Solana transaction.- * The transaction will transfer the required amount of SOL or SPL tokens (like USDC) from the user's wallet to the creator's wallet.- * Use the wallet-adapter to ask the user to sign and send the transaction.--## Code Example (JavaScript - `src/marketplace.js`)--```javascript-// Inside the 'confirm-purchase' button's event listener--const provider = getProvider(); // From your wallet-adapter setup-const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));--const transaction = new solanaWeb3.Transaction().add(- solanaWeb3.SystemProgram.transfer({- fromPubkey: user.publicKey,- toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),- lamports: price.amount,- })-);--try {- const signature = await provider.sendTransaction(transaction, connection);- await connection.confirmTransaction(signature, 'processed');- // On success, notify the backend to unlock the skill-} catch (error) {- console.error("Transaction failed", error);-}-```diff --git a/docs/monetization/07_api_purchase_prep.md b/docs/monetization/07_api_purchase_prep.mddeleted file mode 100644index dfa0762d9..000000000--- a/docs/monetization/07_api_purchase_prep.md+++ /dev/null@@ -1,83 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 07: Backend API for Purchase Preparation--## Objective-Create a backend endpoint that prepares an on-chain transaction for a user to purchase a skill.--## Explanation-When a user clicks the "Purchase" button, the frontend needs to request a transaction from the backend. This endpoint will not execute the transaction but will prepare it. It will construct a Solana transaction that, when signed by the user, will transfer the correct amount of USDC from the user's wallet to the agent creator's wallet. This is a crucial step for security and a smooth user experience.--## Instructions-1. **Create the API Endpoint:**- * Create a new file or handler, e.g., `POST /api/skills/purchase-prep`.--2. **Implement the Logic:**- * **Authentication:** Ensure the user is authenticated.- * **Input Validation:** The request body should contain the `agent_id` and `skill_name`. Validate these inputs.- * **Fetch Data:**- * Retrieve the skill's price from the `agent_skill_prices` table.- * Retrieve the agent creator's wallet address from the `agent_identities` table (`meta.onchain.wallet`).- * Retrieve the buyer's wallet address from their session or a trusted source.- * **Construct Transaction:**- * Using the Solana Web3.js library (`@solana/web3.js`), create a new transaction.- * The transaction should contain one primary instruction: a `spl-token` transfer from the buyer's USDC associated token account (ATA) to the creator's USDC ATA.- * The amount should be the price fetched from the database.- * The transaction's `feePayer` should be set to the buyer's public key.- * **Serialization:**- * Serialize the transaction without signing it.- * Return the serialized transaction as a base64-encoded string. This is what the frontend will receive and pass to the user's wallet to be signed.- * **Record Preparation:**- * It's good practice to store a temporary record of this preparation step (e.g., in Redis or a `skill_purchase_preparations` table) with an expiration time, to prevent replay attacks and to link it to the confirmation step.--## Code Example (Vercel Serverless Function)--```javascript-import { Connection, PublicKey, Transaction } from '@solana/web3.js';-import { getOrCreateAssociatedTokenAccount, createTransferInstruction } from '@solana/spl-token';-import { sql } from '../../_lib/db.js';-// ... other imports--export default wrap(async (req, res) => {- // ... auth and validation- const { agent_id, skill_name } = req.body;- const user = await getSessionUser(req);- const buyerPublicKey = new PublicKey(user.wallet_address);-- // 1. Fetch skill price and creator wallet- const [skillPrice] = await sql`...`;- const [agent] = await sql`...`;- const creatorPublicKey = new PublicKey(agent.meta.onchain.wallet);- const usdcMint = new PublicKey(skillPrice.currency_mint);-- // 2. Setup connection and ATAs- const connection = new Connection(rpcUrl('mainnet-beta'));- const buyerAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, buyerPublicKey);- const creatorAta = await getOrCreateAssociatedTokenAccount(connection, buyerPublicKey, usdcMint, creatorPublicKey);-- // 3. Create transaction- const { blockhash } = await connection.getLatestBlockhash();- const tx = new Transaction({- feePayer: buyerPublicKey,- recentBlockhash: blockhash,- });-- tx.add(- createTransferInstruction(- buyerAta.address,- creatorAta.address,- buyerPublicKey,- skillPrice.amount- )- );-- // 4. Serialize and return- const serializedTx = tx.serialize({ requireAllSignatures: false }).toString('base64');-- // 5. Save prep record (omitted for brevity)-- return json(res, 200, { transaction: serializedTx });-});-```diff --git a/docs/monetization/08-backend-api-process-payment.md b/docs/monetization/08-backend-api-process-payment.mddeleted file mode 100644index a55480b9d..000000000--- a/docs/monetization/08-backend-api-process-payment.md+++ /dev/null@@ -1,51 +0,0 @@-----status: not-started------# Prompt 8: Backend API to Process Payments--## Objective-Create a backend endpoint to verify and record a skill purchase transaction after it has been confirmed on the blockchain.--## Explanation-After a user's transaction is successfully sent to the Solana network, the frontend needs to notify the backend. The backend will then verify the transaction and, if it's valid, record that the user now owns the skill. This prevents users from accessing paid skills without a valid payment.--## Instructions-1. **Create a New API Endpoint:**- * Create a new endpoint, for example, `POST /api/marketplace/skills/purchase`.- * This endpoint will receive the transaction signature and the skill name being purchased.--2. **Verify the Transaction:**- * In the backend, use the Solana web3 library to fetch the transaction details using the signature.- * Verify that the transaction is valid:- * It transferred the correct amount of the correct currency.- * The funds were sent from the user's wallet to the correct creator's wallet.- * The transaction has been successfully confirmed.--3. **Record the Purchase:**- * If the transaction is valid, insert a new record into the `user_skill_purchases` table to grant the user ownership of the skill.--## Code Example (Backend - Node.js with `@solana/web3.js`)--```javascript-// POST /api/marketplace/skills/purchase-router.post('/skills/purchase', async (req, res) => {- const { signature, skillName, agentId } = req.body;- const userId = req.session.userId;-- // 1. Fetch transaction details from the blockchain- const connection = new solanaWeb3.Connection(solanaWeb3.clusterApiUrl('devnet'));- const tx = await connection.getTransaction(signature);-- // 2. Verify the transaction's details (amount, recipient, etc.)- const isValid = verifyTransaction(tx, { /* expected details */ });-- if (isValid) {- // 3. Record the purchase in the database- await db.recordSkillPurchase(userId, skillName, agentId);- res.status(200).json({ success: true });- } else {- res.status(400).json({ error: 'Invalid transaction' });- }-});-```diff --git a/docs/monetization/08-backend-ownership-verification.md b/docs/monetization/08-backend-ownership-verification.mddeleted file mode 100644index e3f796c3f..000000000--- a/docs/monetization/08-backend-ownership-verification.md+++ /dev/null@@ -1,53 +0,0 @@-# Prompt 8: Backend Ownership Verification--## Objective-Create a secure backend endpoint that can verify whether a given user wallet holds the specific NFT required to access a paid skill.--## Explanation-Gating access to a feature requires a reliable way to check for ownership. This check must be done on the backend to prevent users from simply manipulating frontend code to bypass the restriction. The backend will query the Solana blockchain directly to verify NFT ownership.--## Instructions-1. **Create Verification Endpoint:**- * Create a new API endpoint, e.g., `/api/skills/verify-ownership`.- * It should accept `user_wallet`, `agent_id`, and `skill_name` as query parameters.--2. **Find the Required NFT:**- * This is the challenging part. A user could own many NFTs. You need to find the *correct* one.- * The most robust method is to query all token accounts for the `user_wallet`.- * Then, for each token they own (where `amount > 0`), fetch its metadata.- * Check the metadata to see if the NFT is part of the agent's verified `collection` (the `collection_mint` address you stored earlier).- * Also, check if the NFT's name or a trait in its metadata matches the `skill_name`.--3. **Use a Solana RPC Provider or Indexer:**- * Fetching all this data can be slow using a standard RPC. For performance, use a dedicated NFT indexing service like Helius, Shyft, or SimpleHash. These services provide APIs to quickly fetch all NFTs owned by a wallet and their metadata.--4. **Return Verification Status:**- * The endpoint should return a simple JSON response, like `{ "has_access": true }` or `{ "has_access": false }`.--## Code Example (Backend using Helius API)-```javascript-// This is a conceptual example of using an indexer API--async function verifyOwnership(req, res) {- const { user_wallet, agent_id, skill_name } = req.query;- const agent = await getAgentFromDB(agent_id);- const agentCollectionMint = agent.collection_mint;-- // Use an indexer API to get all assets owned by the user- const response = await fetch(`https://api.helius.xyz/v0/addresses/${user_wallet}/nfts?api-key=YOUR_API_KEY`);- const data = await response.json();-- let has_access = false;- for (const nft of data.items) {- if (nft.grouping?.group_key === 'collection' && nft.grouping?.group_value === agentCollectionMint) {- // This NFT is in the right collection. Now check if it's the right skill.- if (nft.content?.metadata?.name.includes(skill_name)) {- has_access = true;- break;- }- }- }-- res.status(200).json({ has_access });-}-```diff --git a/docs/monetization/08-backend-solana-pay-transaction.md b/docs/monetization/08-backend-solana-pay-transaction.mddeleted file mode 100644index d89c1afce..000000000--- a/docs/monetization/08-backend-solana-pay-transaction.md+++ /dev/null@@ -1,105 +0,0 @@-----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/08-detect-paid-skill-usage.md b/docs/monetization/08-detect-paid-skill-usage.mddeleted file mode 100644index 8ebf510f1..000000000--- a/docs/monetization/08-detect-paid-skill-usage.md+++ /dev/null@@ -1,83 +0,0 @@-# Prompt 8: Detect Paid Skill Usage in Chat--## Objective-In the chat interface, implement logic to detect when a user attempts to use a skill that requires payment.--## Explanation-This is the entry point for the payment flow within the chat itself. When the user's prompt is interpreted by the AI and mapped to a specific skill, the system needs to check if that skill has an associated price before attempting to execute it.--## Instructions-1. **Modify Chat Backend/Orchestrator:**- * Identify the part of your application that receives the AI model's response, which indicates the intent to use a skill. This could be in `/api/chat.js` or a similar backend orchestrator.- * Before executing the skill, this orchestrator needs access to the agent's skill pricing information.- * When fetching the agent's details at the beginning of a chat session, make sure to also fetch its `skill_prices` (as implemented in Prompt 1) and keep them available in the session's context.--2. **Implement the Price Check:**- * After the AI model decides which skill to use (e.g., `skill_name: "generate-image"`), but *before* executing the skill's logic, perform a check:- ```javascript- const skillPrices = agent.skill_prices || {};- const price = skillPrices[skillToExecute.name];-- if (price && price.amount > 0) {- // This is a paid skill.- // Halt execution and proceed to the payment flow.- } else {- // This is a free skill.- // Proceed with normal execution.- }- ```--3. **Check for Existing Access Grants:**- * Before flagging a skill as needing payment, you must first check if the user *already has access*. This requires a new database lookup.- * Query the `skill_access_grants` table (which will be created in a later prompt) for a valid grant for the current `user_id`, `agent_id`, and `skill_name`.- * A grant is valid if `expires_at` is in the future or `uses_left` is greater than 0.- * If a valid grant exists, treat the skill as free and proceed with execution. If not, proceed to the payment flow.--4. **Signal to the Frontend:**- * If payment is required, the backend should not execute the skill. Instead, it must send a specific message back to the chat UI.- * This can be a special message type in your WebSocket or SSE stream, or a structured JSON response via HTTP.- * The message must contain the necessary information to render a payment modal: `skill_name`, `amount`, `currency_mint`.--## Code Example (Backend - `/api/chat.js` or similar)--```javascript-// Inside the main chat processing logic, after receiving the AI's intent to use a skill--async function processUserMessage(message, agent, user) {- // ... logic to get AI response ...- const { skillToExecute, parameters } = ai.interpret(message);-- if (skillToExecute) {- const skillPrices = agent.skill_prices || {};- const price = skillPrices[skillToExecute.name];-- if (price && price.amount > 0) {- // Paid skill detected. First, check if user already has access.- const hasAccess = await db.checkForValidSkillGrant({- userId: user.id,- agentId: agent.id,- skillName: skillToExecute.name- });-- if (!hasAccess) {- // No access. Signal to frontend to start payment flow.- return {- type: 'payment_required',- data: {- skill_name: skillToExecute.name,- amount: price.amount,- currency_mint: price.currency_mint- }- };- }- // User has access, fall through to execution.- }-- // Free skill or user has access, execute it.- const result = await executeSkill(skillToExecute.name, parameters);- return { type: 'message', data: { text: result } };- }-- // ... handle regular text response ...-}-```diff --git a/docs/monetization/08-frontend-payment-flow.md b/docs/monetization/08-frontend-payment-flow.mddeleted file mode 100644index 530ed9f86..000000000--- a/docs/monetization/08-frontend-payment-flow.md+++ /dev/null@@ -1,95 +0,0 @@-----status: not-started------# Prompt 8: Frontend - Payment Flow--## Objective-Implement the client-side logic to handle the entire skill purchase flow: requesting the transaction, getting the user's signature, sending it to the network, and confirming it.--## Explanation-This prompt connects the "Unlock" button to the backend and the user's wallet. When a user clicks the button, the frontend will orchestrate the process of fetching, signing, and broadcasting the payment transaction on the Solana network. This is a critical user-facing step that needs to be smooth and provide clear feedback.--## Instructions-1. **Add Event Listener:**- * In `src/marketplace.js`, add a click event listener to the container of the skills list (or delegate from a higher-level element). When a `.btn-unlock-skill` is clicked, the handler should fire.--2. **Request the Transaction:**- * Inside the event handler, get the `agentId` and `skillName` from the button's `data-*` attributes.- * Get the connected user's public key from the `useWallet` hook. If no wallet is connected, prompt the user to connect first.- * Send a `POST` request to your `/api/payments/create-transaction` endpoint with the `agentId`, `skillName`, and `buyerPublicKey`.- * Show a loading indicator to the user (e.g., disable the button and show a spinner).--3. **Deserialize and Sign:**- * The API will respond with a base64-encoded transaction string.- * Decode the base64 string into a buffer.- * Use `Transaction.from()` from `@solana/web3.js` to deserialize the buffer back into a `Transaction` object.- * Use the `signTransaction` function from the `useWallet` hook to prompt the user to sign the transaction with their wallet. This will open a popup in their wallet extension.--4. **Send and Confirm the Transaction:**- * Once the user signs, the `signTransaction` function will return the signed transaction.- * Serialize the signed transaction and use `connection.sendRawTransaction` to broadcast it to the Solana network. This will return a transaction signature (ID).- * Use `connection.confirmTransaction` with the signature to wait for the transaction to be confirmed by the network. This is crucial for ensuring the payment went through before considering the skill unlocked.--5. **Provide Feedback:**- * While confirming, keep the user informed (e.g., "Confirming transaction...").- * On successful confirmation, show a success message ("Skill unlocked!").- * You should then refresh the UI to show the skill as "Unlocked", either by re-fetching user data or just updating the DOM for that specific skill.- * If any step fails (user rejects signature, transaction fails), show a clear error message.--## Code Example (`src/marketplace.js`)--```javascript-import { useWallet, useConnection } from '@solana/wallet-adapter-react';-import { Transaction } from '@solana/web3.js';-// ... other imports--// Add this listener in your initialization code-document.getElementById('d-skills').addEventListener('click', async (event) => {- if (!event.target.matches('.btn-unlock-skill')) return;-- const button = event.target;- const { agentId, skillName } = button.dataset;- const { publicKey, signTransaction } = useWallet(); // From wallet adapter context- const { connection } = useConnection(); // From wallet adapter context-- if (!publicKey || !signTransaction) {- showToast('Please connect your wallet first.', 'error');- return;- }-- try {- button.disabled = true;- button.textContent = 'Processing...';-- // 1. Fetch transaction from backend- const response = await fetch('/api/payments/create-transaction', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ agentId, skillName, buyerPublicKey: publicKey.toBase58() })- });- if (!response.ok) throw new Error('Failed to create transaction.');- const { transaction: base64Transaction } = await response.json();-- // 2. Deserialize, sign, and send- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));- const signedTransaction = await signTransaction(transaction);- const signature = await connection.sendRawTransaction(signedTransaction.serialize());-- // 3. Confirm transaction- await connection.confirmTransaction(signature, 'confirmed');-- showToast('Skill unlocked successfully!', 'success');-- // 4. Update UI- button.outerHTML = `<span class="price-badge price-unlocked">✅ Unlocked</span>`;- // Optionally, add skillName to a local `unlockedSkills` set.-- } catch (error) {- console.error('Purchase failed:', error);- showToast(error.message || 'Purchase failed. Please try again.', 'error');- button.disabled = false;- button.textContent = 'Unlock for ...'; // Restore original text- }-});-```diff --git a/docs/monetization/08-record-skill-ownership.md b/docs/monetization/08-record-skill-ownership.mddeleted file mode 100644index 9afe7c6db..000000000--- a/docs/monetization/08-record-skill-ownership.md+++ /dev/null@@ -1,103 +0,0 @@-# Prompt 8: Record Skill Ownership in Database--## Status-- [ ] Not Started--## Objective-Create a database table to track which users have purchased which skills, and an API endpoint to record a successful purchase.--## Explanation-After a transaction is successfully confirmed on the blockchain, we need to record the user's ownership of the skill in our own database. This allows us to easily check if a user has access to a skill without needing to query the blockchain every time.--## Instructions-1. **Design `user_owned_skills` Table:**- * Create a new table with columns like:- * `id`: Primary key.- * `user_id`: Foreign key to the `users` table.- * `agent_id`: Foreign key to the `agents` table.- * `skill_name`: The name of the purchased skill.- * `purchase_transaction_signature`: The Solana transaction signature of the purchase.- * `created_at`: Timestamp.- * Add a unique constraint on `(user_id, agent_id, skill_name)`.--2. **Create a "Finalize Purchase" API Endpoint:**- * Create a new endpoint, e.g., `POST /api/payments/finalize-purchase`.- * This endpoint will be called by the frontend *after* a transaction has been confirmed.- * It should accept the `agent_id`, `skill_name`, and `transaction_signature`.--3. **Implement Finalization Logic:**- * The backend should first verify the transaction signature on the Solana network to ensure it's valid and recent.- * It should decode the transaction to confirm that the correct amount was transferred to the correct seller.- * If the transaction is valid, insert a new record into the `user_owned_skills` table.--## SQL Example-```sql-CREATE TABLE user_owned_skills (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- purchase_transaction_signature VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE UNIQUE INDEX idx_user_owned_skills_on_user_agent_skill-ON user_owned_skills (user_id, agent_id, skill_name);-```--## Code Example (Backend - `/api/payments/finalize-purchase.js`)-```javascript-import { Connection } from '@solana/web3.js';-import { recordSkillOwnership } from './_db.js'; // DB function--export default async function handler(req, res) {- const { agentId, skillName, transactionSignature, userId } = req.body;-- // 1. Verify transaction on-chain- const connection = new Connection(process.env.SOLANA_RPC_URL, 'confirmed');- const tx = await connection.getTransaction(transactionSignature, { maxSupportedTransactionVersion: 0 });-- if (!tx) {- return res.status(400).json({ error: 'Transaction not found or not confirmed.' });- }-- // 2. (Recommended) Decode the transaction to verify its contents- // This part can be complex, involving parsing instructions and account keys.- // For simplicity here, we're trusting the client, but in production, you MUST verify:- // - The source wallet matches the user.- // - The destination wallet matches the agent creator.- // - The transfer amount and mint are correct.- const isTransactionValid = true; // Placeholder for real validation logic-- if (!isTransactionValid) {- return res.status(400).json({ error: 'Transaction validation failed.' });- }-- // 3. Record ownership in the database- await recordSkillOwnership(userId, agentId, skillName, transactionSignature);-- res.status(200).json({ success: true });-}-```--## Frontend Update-After a successful purchase, the frontend should call this new endpoint.-```javascript-// Inside the purchase success block in the frontend-const signature = await connection.sendRawTransaction(signedTransaction.serialize());-await connection.confirmTransaction(signature, 'confirmed');--// New part: Finalize with your backend-await fetch('/api/payments/finalize-purchase', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- agentId: currentAgent.id,- skillName: skillData.skillName,- transactionSignature: signature,- userId: currentUser.id // Assuming you have the user's ID- }),-});--alert('Purchase successful and recorded!');-```diff --git a/docs/monetization/08-set-skill-prices-ui.md b/docs/monetization/08-set-skill-prices-ui.mddeleted file mode 100644index 30d07097c..000000000--- a/docs/monetization/08-set-skill-prices-ui.md+++ /dev/null@@ -1,102 +0,0 @@-# Prompt 8: "Set Skill Prices" UI--## Objective-Create a user interface within the agent creation/editing page (`agent-edit.html`) that allows creators to set prices for their agent's skills.--## Explanation-To enable monetization, creators need a simple and intuitive way to manage the prices of their skills. This task involves building the UI components (input fields, selectors) where a creator can assign a price and currency to each skill associated with their agent.--## Instructions-1. **Modify Agent Edit Page (`agent-edit.html`):**- * Locate the section where skills are listed or added for an agent.- * For each skill listed, add input fields for `price` and a dropdown for `currency`.--2. **Structure the UI:**- * The UI should be clear. Next to each skill name, add:- * An `<input type="number">` for the price. It should have `step="0.01"` and `min="0"` for decimal values.- * A `<select>` dropdown for the currency. Initially, this can be hardcoded to just "USDC". In the future, it could be populated with other SPL tokens.- * A "Save Prices" button at the end of the section.--3. **Fetch Existing Prices:**- * When the agent edit page loads, it fetches the agent's data. This data should now include any previously saved skill prices.- * The UI should be populated with these existing prices when the page loads.--## HTML Example (Inside `agent-edit.html`)--```html-<!-- Inside the form for editing an agent -->-<div id="skills-pricing-section">- <h3>Monetize Skills</h3>- <p>Set a price for your skills. Leave the price as 0 for a free skill.</p>- <div id="skill-price-list">- <!-- This list will be populated dynamically by JavaScript -->- </div>- <button type="button" id="save-skill-prices-btn">Save Prices</button>-</div>-```--## JavaScript for Rendering (`src/agent-edit.js`)--```javascript-// Function to render the skill price inputs-function renderSkillPricing(agent) {- const skills = agent.skills || [];- const prices = agent.skill_prices || {};- const container = document.getElementById('skill-price-list');-- if (!skills.length) {- container.innerHTML = '<p>Add skills to your agent to set their prices.</p>';- return;- }-- container.innerHTML = skills.map(skill => {- const skillName = skill.name || skill;- const price = prices[skillName] ? (prices[skillName].amount / 1e6) : 0;- const currency = prices[skillName] ? prices[skillName].currency_mint : 'USDC';-- return `- <div class="skill-price-entry" data-skill-name="${escapeHtml(skillName)}">- <label for="price-${escapeHtml(skillName)}">${escapeHtml(skillName)}</label>- <input- type="number"- id="price-${escapeHtml(skillName)}"- class="skill-price-input"- value="${price}"- min="0"- step="0.01"- placeholder="e.g., 1.99"- />- <select class="skill-currency-select">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d" ${currency === 'USDC' ? 'selected' : ''}>USDC</option>- <!-- Other currencies can be added later -->- </select>- </div>- `;- }).join('');-}--// In your page load logic:-// const agentData = await fetchAgentData(agentId);-// renderSkillPricing(agentData);-```--## CSS for Styling--```css-.skill-price-entry {- display: flex;- align-items: center;- gap: 12px;- margin-bottom: 8px;-}-.skill-price-entry label {- flex: 1;- font-weight: 500;-}-.skill-price-input, .skill-currency-select {- padding: 6px 8px;- border-radius: 4px;- border: 1px solid var(--border);- background: var(--panel);-}-```diff --git a/docs/monetization/08_frontend_signing_logic.md b/docs/monetization/08_frontend_signing_logic.mddeleted file mode 100644index de39a696e..000000000--- a/docs/monetization/08_frontend_signing_logic.md+++ /dev/null@@ -1,97 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 08: Frontend Logic for Signing and Sending Transaction--## Objective-Implement the client-side logic that takes the prepared transaction from the backend, asks the user to sign it with their wallet, and sends it to the Solana network.--## Explanation-This is the core of the on-chain interaction from the user's perspective. The frontend will receive the base64-encoded transaction, deserialize it, prompt the user for a signature via their connected wallet (e.g., Phantom), and then broadcast the signed transaction to the blockchain.--## Instructions-1. **Integrate with Wallet Adapter:**- * Ensure a Solana wallet adapter (like `@solana/wallet-adapter-react` or a vanilla equivalent) is integrated into your frontend to manage wallet connections.--2. **Handle the "Purchase" Button Click:**- * In `src/marketplace.js`, attach an async function to the purchase button's click event.--3. **Implement the Purchase Flow:**- * **Step 1: Fetch Prepared Transaction:**- * When the button is clicked, call the `POST /api/skills/purchase-prep` endpoint created in the previous prompt.- * **Step 2: Deserialize:**- * Take the base64 `transaction` string from the response and deserialize it into a `Transaction` object using the Solana Web3.js library.- * **Step 3: Sign Transaction:**- * Use the connected wallet's `signTransaction` method to ask the user to sign the transaction. This will pop up the wallet interface. Handle potential user rejection of the signature.- * **Step 4: Send Transaction:**- * If signing is successful, use the `connection.sendRawTransaction` method to broadcast the signed transaction to the network.- * **Step 5: Confirm Transaction:**- * Wait for the transaction to be confirmed by the network using `connection.confirmTransaction`. This gives the user feedback that their purchase was successful.- * **Step 6: Finalize with Backend:**- * After on-chain confirmation, call a new backend endpoint (`/api/skills/purchase-confirm`, to be built next) with the transaction signature. This will record the purchase in our database.--## Code Example (`src/marketplace.js`)--```javascript-import { Connection, Transaction } from '@solana/web3.js';-// Assume `wallet` is the connected wallet object from a wallet adapter-// Assume `connection` is an initialized Connection object--async function handlePurchase(agentId, skillName, button) {- try {- // 1. Prepare- button.disabled = true;- button.textContent = 'Preparing...';- const prepRes = await fetch('/api/skills/purchase-prep', {- method: 'POST',- body: JSON.stringify({ agent_id: agentId, skill_name: skillName }),- headers: { 'Content-Type': 'application/json' }- });- if (!prepRes.ok) throw new Error('Failed to prepare transaction.');- const { transaction: base64Tx } = await prepRes.json();-- // 2. Deserialize- const tx = Transaction.from(Buffer.from(base64Tx, 'base64'));-- // 3. Sign- button.textContent = 'Please sign...';- const signedTx = await wallet.signTransaction(tx);-- // 4. Send- button.textContent = 'Sending...';- const signature = await connection.sendRawTransaction(signedTx.serialize());-- // 5. Confirm- button.textContent = 'Confirming...';- await connection.confirmTransaction(signature, 'confirmed');-- // 6. Finalize with our backend- const confirmRes = await fetch('/api/skills/purchase-confirm', {- method: 'POST',- body: JSON.stringify({ agent_id: agentId, skill_name: skillName, signature }),- headers: { 'Content-Type': 'application/json' }- });- if (!confirmRes.ok) throw new Error('Failed to confirm purchase with server.');-- // 7. Update UI- button.textContent = '✓ Owned';- button.classList.add('owned');- // Prevent further clicks- button.replaceWith(button.cloneNode(true));-- } catch (err) {- console.error('Purchase failed:', err);- button.disabled = false;- button.textContent = 'Purchase Failed - Retry';- }-}--// Modify the event listener from Prompt 5-document.getElementById('d-skills').addEventListener('click', (e) => {- if (e.target.matches('.btn-purchase:not(:disabled)')) {- const { skillName, agentId } = e.target.dataset;- handlePurchase(agentId, skillName, e.target);- }-});-```diff --git a/docs/monetization/09-backend-create-skill-ownership-table.md b/docs/monetization/09-backend-create-skill-ownership-table.mddeleted file mode 100644index 7c924d819..000000000--- a/docs/monetization/09-backend-create-skill-ownership-table.md+++ /dev/null@@ -1,55 +0,0 @@-----status: not-started------# Prompt 9: Backend - Create Skill Ownership Table--## Objective-Create a database table to permanently record which users have successfully purchased which skills.--## Explanation-After a user pays for a skill, we need to record their ownership so they don't have to pay for it again. A dedicated table, `user_unlocked_skills`, will store the relationship between a user, an agent, and a specific skill. This table will be the source of truth for checking skill access.--## Instructions-1. **Design the Table Schema:**- * Name the table `user_unlocked_skills`.- * It needs a column to link to the user (`user_id`).- * It needs a column to link to the agent (`agent_id`).- * It needs a column to identify the skill (`skill_name`).- * It's highly recommended to store a reference to the purchase transaction (`purchase_tx_signature`) for auditing and customer support purposes.- * Add a primary key and foreign keys to `users` and `agent_identities`.- * Create a unique constraint on (`user_id`, `agent_id`, `skill_name`) to ensure a user can't have duplicate entries for the same skill.--2. **Create a SQL Migration File:**- * Create a new SQL migration file (e.g., `scripts/migrations/003_create_user_unlocked_skills.sql`).- * Write the `CREATE TABLE` statement.- * Include a `created_at` timestamp to know when the skill was unlocked.--## Code Example (SQL)--```sql--- scripts/migrations/003_create_user_unlocked_skills.sql--CREATE TABLE IF NOT EXISTS user_unlocked_skills (- id SERIAL PRIMARY KEY,- user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id INTEGER NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,-- -- The Solana transaction signature of the purchase- purchase_tx_signature VARCHAR(88) NOT NULL,-- -- Store price info at time of purchase for historical records- purchase_amount BIGINT NOT NULL,- purchase_currency_mint VARCHAR(44) NOT NULL,-- unlocked_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- -- A user can only unlock a specific agent's skill once.- UNIQUE (user_id, agent_id, skill_name)-);---- Add indexes for common queries-CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_user_id ON user_unlocked_skills(user_id);-CREATE INDEX IF NOT EXISTS idx_user_unlocked_skills_agent_id ON user_unlocked_skills(agent_id);-```diff --git a/docs/monetization/09-backend-set-skill-prices.md b/docs/monetization/09-backend-set-skill-prices.mddeleted file mode 100644index b831ed8d3..000000000--- a/docs/monetization/09-backend-set-skill-prices.md+++ /dev/null@@ -1,114 +0,0 @@-# Prompt 9: Backend for Setting Skill Prices--## Objective-Create the backend API endpoint for agent creators to save the prices for their skills.--## Explanation-The UI for setting skill prices needs a corresponding backend endpoint to persist the data. This endpoint will receive the agent ID, skill name, price, and currency, and it will update the `agent_skill_prices` database table accordingly. This requires proper authentication to ensure only the agent's creator can modify prices.--## Instructions-1. **Create New API File:**- * Create a new file, for example, at `api/agents/[id]/pricing.js`. This creates a route like `/api/agents/AGENT_ID/pricing`.--2. **Endpoint Logic (POST/PUT):**- * The endpoint should handle POST or PUT requests.- * It needs to authenticate the request to ensure the logged-in user is the creator of the agent specified by the ID in the URL.- * The request body should contain `skillName`, `amount`, and `currencyMint`.- * The logic will perform an "upsert" operation on the `agent_skill_prices` table:- * If a price for that agent and skill already exists, it will be updated.- * If it doesn't exist, a new record will be created.--3. **Endpoint Logic (GET):**- * The same endpoint should handle GET requests to fetch all existing prices for a given agent, which is used by the UI in the previous prompt.--## Database Schema (`agent_skill_prices`)--```sql-CREATE TABLE agent_skill_prices (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID REFERENCES agents(id) NOT NULL,- skill_name TEXT NOT NULL,- amount BIGINT NOT NULL, -- Price in smallest unit (e.g., lamports)- currency_mint TEXT NOT NULL, -- e.g., PublicKey of the SPL token- created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW(),- UNIQUE(agent_id, skill_name)-);---- Policy: Only agent creator can manage prices-CREATE POLICY "Creators can manage their agent skill prices"-ON agent_skill_prices-FOR ALL-USING (auth.uid() = (SELECT creator_id FROM agents WHERE id = agent_id));-```--## Code Example (`api/agents/[id]/pricing.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';-import { getAuthUser } from '../../_lib/auth';--export default async function handler(req, res) {- const { id: agentId } = req.query;- const user = await getAuthUser(req);-- if (!user) {- return error(res, 401, 'Unauthorized');- }-- // Verify ownership- const { data: agent, error: agentError } = await supabase- .from('agents')- .select('creator_id')- .eq('id', agentId)- .single();-- if (agentError || agent.creator_id !== user.id) {- return error(res, 403, 'You do not own this agent.');- }-- if (req.method === 'POST') {- const { skillName, amount, currencyMint } = req.body;-- if (!skillName || amount == null || !currencyMint) {- return error(res, 400, 'Missing required pricing information.');- }-- const { data, error: upsertError } = await supabase- .from('agent_skill_prices')- .upsert({- agent_id: agentId,- skill_name: skillName,- amount: amount,- currency_mint: currencyMint,- }, { onConflict: 'agent_id, skill_name' })- .select();-- if (upsertError) {- return error(res, 500, 'Failed to save price.');- }- return json(res, data[0]);-- } else if (req.method === 'GET') {- const { data, error: fetchError } = await supabase- .from('agent_skill_prices')- .select('*')- .eq('agent_id', agentId);-- if (fetchError) {- return error(res, 500, 'Failed to fetch prices.');- }-- // Reshape into a map for easier frontend use- const prices = data.reduce((acc, price) => {- acc[price.skill_name] = { amount: price.amount, currency_mint: price.currency_mint };- return acc;- }, {});-- return json(res, prices);- }-- return error(res, 405, 'Method Not Allowed');-}-```diff --git a/docs/monetization/09-db-schema-user-purchases.md b/docs/monetization/09-db-schema-user-purchases.mddeleted file mode 100644index 00010522b..000000000--- a/docs/monetization/09-db-schema-user-purchases.md+++ /dev/null@@ -1,39 +0,0 @@-----status: not-started------# Prompt 9: Database Schema for User Purchases--## Objective-Create a database table to track which users have purchased which skills.--## Explanation-This table is essential for managing skill ownership. It will provide a record of every successful purchase, allowing the application to check if a user has access to a particular paid skill.--## Instructions-1. **Design the Table:**- * Create a new table named `user_skill_purchases`.- * The table should have the following columns:- * `id`: Primary key.- * `user_id`: Foreign key referencing the `users` table.- * `agent_id`: Foreign key referencing the `agents` table.- * `skill_name`: The name of the skill that was purchased.- * `transaction_signature`: The Solana transaction signature of the purchase.- * `created_at`: Timestamp.--2. **Create a Migration:**- * Use your database migration tool to create and apply a migration for the `user_skill_purchases` table.--## SQL Example--```sql-CREATE TABLE user_skill_purchases (- id SERIAL PRIMARY KEY,- user_id UUID NOT NULL REFERENCES users(id),- agent_id UUID NOT NULL REFERENCES agents(id),- skill_name VARCHAR(255) NOT NULL,- transaction_signature VARCHAR(255) NOT NULL,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- UNIQUE(user_id, agent_id, skill_name)-);-```diff --git a/docs/monetization/09-frontend-gating-for-skills.md b/docs/monetization/09-frontend-gating-for-skills.mddeleted file mode 100644index d4027a062..000000000--- a/docs/monetization/09-frontend-gating-for-skills.md+++ /dev/null@@ -1,62 +0,0 @@-# Prompt 9: Frontend Gating for Skills--## Objective-Implement a check in the frontend UI that calls the backend verification endpoint before allowing a user to use a paid skill.--## Explanation-This is the user-facing part of the access control system. When a user tries to interact with a paid skill (e.g., clicking a button in the chat interface that triggers the skill), the frontend must first confirm they have the right to do so.--## Instructions-1. **Identify Skill Triggers:**- * Go through the chat UI or agent interaction logic and identify all the points where a skill is triggered.--2. **Create a Central Skill Dispatcher:**- * Instead of triggering skills directly, create a central function, e.g., `tryUseSkill(skillName)`.- * This function will be responsible for handling the gating logic.--3. **Implement the Check:**- * Inside `tryUseSkill`, first determine if the skill is free or paid by checking the agent's `skill_prices` data.- * If the skill is free, execute it immediately.- * If the skill is paid, call the `/api/skills/verify-ownership` endpoint you created in the previous step.- * Based on the `has_access` response:- * If `true`, execute the skill.- * If `false`, show a message to the user, e.g., "You need to purchase this skill to use it," and provide a link or button to the marketplace page.--4. **Cache Verification Results:**- * To avoid calling the verification endpoint every single time, cache the results on the frontend for the duration of the user's session. A simple JavaScript object or `sessionStorage` can work for this.--## Code Example (Frontend Skill Dispatcher)-```javascript-const skillAccessCache = {};--async function tryUseSkill(skillName) {- const agent = getCurrentAgentData();- const isPaid = skillName in agent.skill_prices;-- if (!isPaid) {- executeSkill(skillName);- return;- }-- // Check cache first- if (skillAccessCache[skillName]) {- executeSkill(skillName);- return;- }-- // If not in cache, verify with backend- const userWallet = wallet.publicKey.toBase58(); // from wallet adapter- const response = await fetch(`/api/skills/verify-ownership?user_wallet=${userWallet}&agent_id=${agent.id}&skill_name=${skillName}`);- const data = await response.json();-- if (data.has_access) {- skillAccessCache[skillName] = true; // Update cache- executeSkill(skillName);- } else {- showPurchasePrompt(skillName); // UI function to tell user to buy the skill- }-}--// Example usage:-// Instead of `runDanceSkill()`, you'd call `tryUseSkill('dance')`.-```diff --git a/docs/monetization/09-frontend-solana-pay-qr.md b/docs/monetization/09-frontend-solana-pay-qr.mddeleted file mode 100644index 9ed47b6fc..000000000--- a/docs/monetization/09-frontend-solana-pay-qr.md+++ /dev/null@@ -1,113 +0,0 @@-----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/09-payment-required-modal.md b/docs/monetization/09-payment-required-modal.mddeleted file mode 100644index 96bca9efd..000000000--- a/docs/monetization/09-payment-required-modal.md+++ /dev/null@@ -1,101 +0,0 @@-# Prompt 9: "Payment Required" Modal in Chat--## Objective-Create a modal dialog in the chat UI that appears when a user needs to pay for a skill, clearly presenting the price and prompting for action.--## Explanation-When the backend signals that a skill requires payment, the frontend must stop the normal message flow and present the user with a clear choice. This modal is the centerpiece of the in-chat purchasing experience.--## Instructions-1. **File to Edit:**- * Open the main JavaScript/Svelte/React component file for your chat interface (e.g., `chat/src/App.svelte` or similar).--2. **Create the Modal HTML/Structure:**- * Add the HTML for a modal dialog. It should be hidden by default.- * The modal should contain:- * A title, e.g., "Premium Skill".- * A descriptive text, e.g., "The skill 'generate-image' requires a one-time payment to use."- * A display for the price (e.g., "Price: 1.00 USDC").- * A "Pay and Continue" button.- * A "Cancel" button or close icon.--3. **Implement Frontend Logic:**- * Listen for the `payment_required` message from your backend (as designed in Prompt 8).- * When this message is received:- * Populate the modal with the `skill_name` and `price` information from the message data. Remember to format the amount from lamports to a user-friendly decimal format.- * Make the modal visible.--4. **Handle Button Clicks:**- * **Cancel:** If the user clicks "Cancel" or closes the modal, hide the modal and perhaps send a "payment cancelled" message to the chat history.- * **Pay and Continue:** If the user clicks the pay button:- * Keep the modal open but show a loading/spinner state.- * Trigger the frontend payment flow function (which will be built in the next prompt). This function will orchestrate the API calls and wallet interaction.--## Code Example (Frontend - Svelte Component)--```svelte-<!-- In your main chat component, e.g., App.svelte -->--{#if paymentRequired}-<div class="modal-backdrop">- <div class="modal">- <h3>Premium Skill</h3>- <p>- The skill <strong>{paymentDetails.skill_name}</strong> requires a payment to continue.- </p>- <div class="price-display">- Price: <span>{(paymentDetails.amount / 1e6).toFixed(2)} USDC</span>- </div>-- {#if isLoadingPayment}- <div class="spinner">Processing...</div>- {:else}- <div class="modal-actions">- <button on:click={cancelPayment}>Cancel</button>- <button class="primary" on:click={initiatePayment}>Pay and Continue</button>- </div>- {/if}- </div>-</div>-{/if}--<script>- let paymentRequired = false;- let paymentDetails = {};- let isLoadingPayment = false;-- // Function to be called when backend sends 'payment_required'- function onPaymentRequired(details) {- paymentDetails = details;- paymentRequired = true;- isLoadingPayment = false;- }-- function cancelPayment() {- paymentRequired = false;- // Optionally add a "Cancelled" message to the chat history- }-- async function initiatePayment() {- isLoadingPayment = true;- try {- // This function will be implemented in the next prompt- const result = await handlePaymentFlow(paymentDetails);- if (result.success) {- paymentRequired = false;- // The backend will now re-run the skill and send the result.- } else {- // Handle payment failure, show an error- isLoadingPayment = false;- }- } catch (err) {- // Handle errors from the payment flow- isLoadingPayment = false;- }- }-</script>--<style>- /* Add styles for .modal-backdrop, .modal, .price-display, etc. */-</style>-```diff --git a/docs/monetization/09-save-skill-prices-backend.md b/docs/monetization/09-save-skill-prices-backend.mddeleted file mode 100644index c7b03071d..000000000--- a/docs/monetization/09-save-skill-prices-backend.md+++ /dev/null@@ -1,100 +0,0 @@-# Prompt 9: Save Skill Prices (Backend)--## Objective-Create a backend API endpoint that allows agent creators to save the prices they have set for their skills.--## Explanation-After a creator sets up the prices for their skills in the UI (from the previous prompt), we need a secure endpoint to save this information to the database. This endpoint will receive a list of skills and their prices, validate the data, and update the `agent_skill_prices` table.--## Instructions-1. **Database Schema:**- * Ensure you have an `agent_skill_prices` table.- * Columns should include `id`, `agent_id`, `skill_name`, `amount` (as a `bigint` to store lamports), and `currency_mint` (as a string).- * The combination of `agent_id` and `skill_name` should be unique.--2. **Create the API Endpoint:**- * Create a new file, e.g., `api/agents/[id]/skill-prices.js`.- * This endpoint should handle `POST` or `PUT` requests.- * It must be protected, ensuring only the agent's creator can update the prices.--3. **Implement the Endpoint Logic:**- * The request body should contain an object or array of skill prices, like: `[{ skillName: 'DataAnalysis', price: 1.99, currency: 'USDC' }, ...]`.- * The handler should:- * Authenticate the user and verify they own the agent specified by `:id`.- * Iterate through the submitted skill prices.- * For each skill, convert the price (e.g., 1.99 USDC) into its smallest unit (lamports, e.g., 1,990,000).- * 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.- * Return a success response.--## SQL for `agent_skill_prices` Table--```sql-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, -- e.g., 1_990_000 for 1.99 USDC- currency_mint VARCHAR(255) NOT NULL,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,- UNIQUE(agent_id, skill_name)-);-```--## Code Example (Backend - `api/agents/[id]/skill-prices.js`)--```javascript-import { db } from '../../_lib/database-client';-import { verifyAgentOwnership } from '../../_lib/auth';--const USDC_DECIMALS = 6;--export default async function handler(req, res) {- if (req.method !== 'POST') return res.status(405).end();-- try {- const agentId = req.query.id;- const userId = req.user.id; // From auth middleware-- // 1. Verify ownership- if (!await verifyAgentOwnership(userId, agentId)) {- return res.status(403).json({ error: 'You do not own this agent.' });- }-- const { prices } = req.body; // Expects: [{ skillName, price, currencyMint }]- if (!Array.isArray(prices)) {- return res.status(400).json({ error: 'Invalid prices format.' });- }-- // 2. Use a transaction to update all prices atomically- await db.tx(async t => {- for (const item of prices) {- const { skillName, price, currencyMint } = item;-- // 3. Convert to lamports (smallest unit)- const amountInLamports = Math.round(parseFloat(price) * (10 ** USDC_DECIMALS));-- await t.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 = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- updated_at = CURRENT_TIMESTAMP;- `,- [agentId, skillName, amountInLamports, currencyMint]- );- }- });-- res.status(200).json({ message: 'Skill prices updated successfully.' });-- } catch (error) {- console.error('Error saving skill prices:', error);- res.status(500).json({ error: 'Internal Server Error' });- }-}-```diff --git a/docs/monetization/09-update-ui-for-owned-skills.md b/docs/monetization/09-update-ui-for-owned-skills.mddeleted file mode 100644index 083e73f25..000000000--- a/docs/monetization/09-update-ui-for-owned-skills.md+++ /dev/null@@ -1,81 +0,0 @@-# Prompt 9: Update UI for Owned Skills--## Status-- [ ] Not Started--## Objective-Modify the agent detail page to visually reflect the skills a user already owns, disabling the "Purchase" button for those skills.--## Explanation-To prevent users from re-purchasing skills they already own, the UI needs to be updated based on their ownership status. This requires fetching the user's owned skills and adjusting the rendering logic.--## Instructions-1. **Backend: Expose Owned Skills:**- * When fetching the agent details (`/api/marketplace/agents/:id`), if a user is authenticated, also query the `user_owned_skills` table.- * Include a list of owned skill names for that specific agent in the API response.--2. **Frontend: Update Rendering Logic:**- * In `src/marketplace.js`, the `renderDetail` function will now receive the list of owned skills.- * In the skill rendering loop, check if the current skill is in the user's owned list.- * If the user owns the skill, display an "Owned" badge or indicator instead of the "Purchase" button.--## Code Example (Backend API Response Snippet)-```json-{- "id": "agent-uuid-123",- "name": "Super Agent",- "skills": ["super-jump", "laser-eyes"],- "skill_prices": {- "laser-eyes": { "amount": 2000000, "currency_mint": "..." }- },- "user_owned_skills": ["super-jump"]-}-```--## Code Example (Frontend - `src/marketplace.js` Update)-```javascript-// Inside renderDetail function-const skillPrices = a.skill_prices || {};-const ownedSkills = new Set(a.user_owned_skills || []); // Use a Set for efficient lookups--$('d-skills').innerHTML = skillsArr.map((s) => {- const name = typeof s === 'string' ? s : (s.name || '');- const price = skillPrices[name];- let actionElement;-- if (ownedSkills.has(name)) {- actionElement = `<span class="ownership-badge">Owned</span>`;- } else if (price) {- const priceDisplay = `${(price.amount / 1e6).toFixed(2)} USDC`;- actionElement = `<button class="purchase-skill-btn"- data-skill-name="${escapeHtml(name)}"- ... >- Purchase for ${priceDisplay}- </button>`;- } else {- // This is a free skill that hasn't been "claimed" or "owned" yet.- // You might have a different state for free skills that are implicitly owned.- actionElement = `<span class="price-badge price-free">Free</span>`;- }-- return `<div class="skill-entry">- <span>${escapeHtml(name)}</span>- ${actionElement}- </div>`;-}).join('');-```--## CSS for "Owned" Badge-```css-/* Add to marketplace.css */-.ownership-badge {- display: inline-block;- padding: 4px 10px;- font-size: 11px;- font-weight: 700;- border-radius: 12px;- background-color: #059669; /* Green */- color: #d1fae5;- border: 1px solid #06c78a;-}-```diff --git a/docs/monetization/09_api_purchase_confirm.md b/docs/monetization/09_api_purchase_confirm.mddeleted file mode 100644index ca4598b48..000000000--- a/docs/monetization/09_api_purchase_confirm.md+++ /dev/null@@ -1,90 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 09: Backend API for Purchase Confirmation--## Objective-Create a backend endpoint to verify a skill purchase transaction on-chain and record it in the database.--## Explanation-After the frontend successfully broadcasts the transaction, it must notify the backend. This endpoint's job is to act as a final "source of truth." It verifies that the transaction signature provided by the client is valid, that it corresponds to the intended purchase, and that it was successful. Only after this verification does it save the purchase record to the `user_purchased_skills` table.--## Instructions-1. **Create the API Endpoint:**- * Create a new file or handler for `POST /api/skills/purchase-confirm`.--2. **Implement the Logic:**- * **Authentication:** The user must be authenticated.- * **Input Validation:** The request body should contain `agent_id`, `skill_name`, and `signature`.- * **Fetch Purchase Details:**- * Retrieve the skill price and creator's wallet address, just as in the "prep" step. This is to ensure the on-chain transaction matches what we expected.- * **On-Chain Verification:**- * Use the Solana `connection.getParsedTransaction` method with the provided `signature`.- * Inspect the transaction details to confirm:- * The transaction was successful ( `tx.meta.err` is null).- * The source account matches the buyer's wallet.- * The destination account matches the creator's wallet.- * The transfer amount matches the skill price.- * The token mint matches the currency (e.g., USDC).- * This step is critical to prevent users from submitting fraudulent or irrelevant transaction signatures.- * **Database Operation:**- * If on-chain verification passes, insert a new record into the `user_purchased_skills` table. Store all relevant details, including the transaction signature, for auditing.--## Code Example (Vercel Serverless Function)--```javascript-import { Connection } from '@solana/web3.js';-import { sql } from '../../_lib/db.js';-// ... other imports--export default wrap(async (req, res) => {- // ... auth and input validation- const { agent_id, skill_name, signature } = req.body;- const user = await getSessionUser(req);- const buyerWallet = user.wallet_address;-- // 1. Fetch expected details for verification- const [skillPrice] = await sql`SELECT ...`;- const [agent] = await sql`SELECT ...`;- const creatorWallet = agent.meta.onchain.wallet;- const expectedAmount = skillPrice.amount;- const currencyMint = skillPrice.currency_mint;-- // 2. Verify transaction on-chain- const connection = new Connection(rpcUrl('mainnet-beta'), 'confirmed');- const tx = await connection.getParsedTransaction(signature, { maxSupportedTransactionVersion: 0 });-- if (!tx || tx.meta.err) {- return error(res, 400, 'tx_failed', 'Transaction failed or not found.');- }-- // Find the token transfer instruction- const transferInstruction = tx.transaction.message.instructions.find(ix =>- ix.parsed?.type === 'transfer' &&- ix.program === 'spl-token'- );-- if (!transferInstruction) {- return error(res, 400, 'invalid_tx', 'No token transfer found in transaction.');- }-- const { source, destination, amount } = transferInstruction.parsed.info;- // Note: A robust implementation would resolve ATAs to owner wallets.- // This is a simplified check.- if (source !== buyerWalletAta || destination !== creatorWalletAta || amount !== expectedAmount) {- return error(res, 400, 'tx_mismatch', 'Transaction details do not match expected purchase.');- }-- // 3. Record the purchase in the database- await sql`- INSERT INTO user_purchased_skills- (user_id, agent_id, skill_name, purchase_tx_signature, price_amount, price_currency_mint)- VALUES- (${user.id}, ${agent_id}, ${skill_name}, ${signature}, ${expectedAmount}, ${currencyMint})- ON CONFLICT (user_id, agent_id, skill_name) DO NOTHING;- `;-- return json(res, 201, { success: true, message: 'Purchase confirmed and recorded.' });-});-```diff --git a/docs/monetization/10-access-control-for-skills.md b/docs/monetization/10-access-control-for-skills.mddeleted file mode 100644index 9fcdbc1fa..000000000--- a/docs/monetization/10-access-control-for-skills.md+++ /dev/null@@ -1,22 +0,0 @@-----status: not-started------# Prompt 10: Access Control for Paid Skills--## Objective-Implement a system to ensure that only users who have purchased a skill can use it.--## Explanation-This is a critical part of the monetization feature. The system needs to check for ownership before allowing the execution of a paid skill. This can be done at the API gateway or within the agent's core logic.--## Instructions-1. **Create a Middleware:**- * Implement a middleware that sits in front of the skill execution endpoint.- * The middleware should extract the user's ID, the agent ID, and the skill name from the request.--2. **Check for Ownership:**- * In the middleware, query the `user_skill_purchases` table to see if a record exists for the user, agent, and skill.- * Also, check if the skill is free by looking at the `agent_skill_prices` table.- * If the skill is free or if the user owns it, allow the request to proceed.- * If the skill is paid and the user does not own it, return a `403 Forbidden` or `402 Payment Required` error.diff --git a/docs/monetization/10-agent-editor-ui-for-pricing.md b/docs/monetization/10-agent-editor-ui-for-pricing.mddeleted file mode 100644index fc483a222..000000000--- a/docs/monetization/10-agent-editor-ui-for-pricing.md+++ /dev/null@@ -1,91 +0,0 @@-# Prompt 10: Create Agent Creation/Editing UI for Pricing--## Status-- [ ] Not Started--## Objective-Develop a user interface for agent creators to set and manage prices for their agent's skills.--## Explanation-For creators to monetize their work, they need a simple way to define which skills are for sale and at what price. This prompt focuses on building the UI for this purpose in the agent creation or editing page.--## Instructions-1. **Locate the Agent Editor:**- * Find the HTML and JavaScript files responsible for the agent creation/editing form (e.g., `agent-edit.html` and `src/agent-editor.js`).--2. **Enhance the Skills Section:**- * In the part of the form where skills are listed or added, add new input fields next to each skill.- * The new fields should be for:- * `Price`: A number input for the skill's price.- * `Currency`: A dropdown/select input to choose the payment currency (e.g., USDC, SOL).--3. **Manage State:**- * The JavaScript for the editor needs to manage this new pricing data.- * When the form is loaded for an existing agent, it should be populated with the current skill prices.- * As the creator changes the prices, the state should be updated.--4. **Handle Form Submission:**- * When the agent creator saves their changes, the pricing information should be collected and sent to the backend.- * The data should be structured in a way that's easy for the backend to process, e.g., an object where keys are skill names.--## Code Example (HTML in `agent-edit.html`)-```html-<div id="skills-editor">- <!-- This part will be dynamically populated by JavaScript -->-</div>--<template id="skill-editor-template">- <div class="skill-price-row">- <input type="text" class="skill-name-input" placeholder="Skill Name" readonly>- <input type="number" class="skill-price-input" placeholder="Price">- <select class="skill-currency-select">- <option value="USDC_MINT_ADDRESS">USDC</option>- <option value="SOL_MINT_ADDRESS">SOL</option>- <!-- Add other supported currencies -->- </select>- </div>-</template>-```--## Code Example (JavaScript in `src/agent-editor.js`)-```javascript-function renderSkillPricer(skills, currentPrices) {- const container = document.getElementById('skills-editor');- const template = document.getElementById('skill-editor-template');- container.innerHTML = '';-- skills.forEach(skillName => {- const skillRow = template.content.cloneNode(true);- const price = currentPrices[skillName];-- skillRow.querySelector('.skill-name-input').value = skillName;- if (price) {- skillRow.querySelector('.skill-price-input').value = price.amount / 1e6; // Display in human-readable format- skillRow.querySelector('.skill-currency-select').value = price.currency_mint;- }-- container.appendChild(skillRow);- });-}--function getSkillPricesFromForm() {- const prices = {};- document.querySelectorAll('#skills-editor .skill-price-row').forEach(row => {- const name = row.querySelector('.skill-name-input').value;- const amountInput = row.querySelector('.skill-price-input').value;- const currency = row.querySelector('.skill-currency-select').value;-- if (amountInput && parseFloat(amountInput) > 0) {- prices[name] = {- amount: parseFloat(amountInput) * 1e6, // Convert to smallest unit- currency_mint: currency- };- }- });- return prices;-}--// On save/submit:-const updatedPrices = getSkillPricesFromForm();-// Now, send 'updatedPrices' to the backend.-```diff --git a/docs/monetization/10-backend-prepare-payment.md b/docs/monetization/10-backend-prepare-payment.mddeleted file mode 100644index 14b969f24..000000000--- a/docs/monetization/10-backend-prepare-payment.md+++ /dev/null@@ -1,101 +0,0 @@-# Prompt 10: Backend Endpoint to Prepare Payment--## Objective-Create a backend endpoint that prepares a Solana transaction for the user to sign to pay for a skill.--## Explanation-This is a critical security step. The server, not the client, must construct the transaction. This prevents tampering with the payment amount or destination. This endpoint will generate an unsigned transaction that transfers the correct amount from the user to the appropriate account and return it to the client for signing.--## Instructions-1. **Create API Route:**- * Set up a new endpoint: `POST /api/payments/prepare-skill-payment`.- * This endpoint must be authenticated.--2. **Request Body:**- * The endpoint should accept a JSON body with `agent_id` and `skill_name`.--3. **Backend Logic:**- * **Fetch Price:** Using `agent_id` and `skill_name`, look up the price (`amount` and `currency_mint`) from the `agent_skill_prices` table. If no price is found, return an error.- * **Identify Payer and Receiver:**- * The **payer** is the authenticated user making the request. Get their public key.- * The **receiver** is the agent's associated treasury or holdings account. This address should be stored with the agent's data.- * **Construct the Transaction:**- * Using the Solana Web3.js library (`@solana/web3.js`), create a new `Transaction`.- * Add a `spl-token` `createTransfer` instruction.- * **Source:** The user's Associated Token Account (ATA) for the given `currency_mint`.- * **Destination:** The agent's treasury ATA for the same `currency_mint`.- * **Amount:** The `amount` from the database.- * **Owner:** The user's public key.- * **Set Blockhash and Fee Payer:**- * Get a recent blockhash from the Solana cluster.- * Set the `recentBlockhash` and `feePayer` (the user) on the transaction.- * **Create Payment Record:**- * Create a record in a new `skill_payments` table with a `pending` status. Include `user_id`, `agent_id`, `skill_name`, `amount`, and the transaction's blockhash for later reference. Store a unique ID for this payment intent.- * **Serialize and Respond:**- * Serialize the *unsigned* transaction and encode it (e.g., in Base64).- * Return the serialized transaction and the unique payment ID to the frontend.--## Code Example (Backend - `/api/payments/prepare-skill-payment.js`)--```javascript-import { Transaction, SystemProgram, PublicKey } from '@solana/web3.js';-import { createTransferInstruction } from '@solana/spl-token';-import { getAssociatedTokenAddress } from '@solana/spl-token';--// --- Inside your API handler -----const { agent_id, skill_name } = req.body;-const user = await getAuthenticatedUser(req);--// 1. Fetch skill price and agent details-const priceInfo = await db.getSkillPrice(agent_id, skill_name);-const agent = await db.getAgentById(agent_id);-if (!priceInfo || !agent) {- return res.status(404).json({ error: 'Skill or agent not found.' });-}--// 2. Define parties-const payerPublicKey = new PublicKey(user.solana_pubkey);-const receiverPublicKey = new PublicKey(agent.treasury_address); // The agent's main treasury wallet-const currencyMint = new PublicKey(priceInfo.currency_mint);--// 3. Find the ATAs for the token transfer-const payerAta = await getAssociatedTokenAddress(currencyMint, payerPublicKey);-const receiverAta = await getAssociatedTokenAddress(currencyMint, receiverPublicKey);--// 4. Create the transfer instruction-const transferInstruction = createTransferInstruction(- payerAta, // from- receiverAta, // to- payerPublicKey, // from's owner- priceInfo.amount // amount-);--// 5. Create the transaction-const connection = new Connection(process.env.SOLANA_RPC_URL);-const { blockhash } = await connection.getRecentBlockhash();--const transaction = new Transaction({- recentBlockhash: blockhash,- feePayer: payerPublicKey,-}).add(transferInstruction);--// 6. Create a pending payment record-const paymentIntent = await db.createPaymentIntent({- userId: user.id,- agentId: agent.id,- skillName: skill_name,- amount: priceInfo.amount,- reference: blockhash, // Use blockhash or a new UUID as a reference-});--// 7. Serialize and respond-const serializedTransaction = transaction.serialize({- requireAllSignatures: false,-}).toString('base64');--res.status(200).json({- paymentId: paymentIntent.id,- transaction: serializedTransaction,-});-```diff --git a/docs/monetization/10-backend-transaction-verification.md b/docs/monetization/10-backend-transaction-verification.mddeleted file mode 100644index 600d7a31c..000000000--- a/docs/monetization/10-backend-transaction-verification.md+++ /dev/null@@ -1,104 +0,0 @@-----status: not-started------# Prompt 10: Backend - Transaction Verification and Fulfillment--## Objective-Create a backend mechanism to securely verify a Solana transaction and, upon success, record the skill ownership in the database.--## Explanation-A crucial security step is to verify the payment on the backend *after* the frontend reports it as confirmed. The frontend can be manipulated, so the server must independently fetch the transaction details from the Solana RPC and validate them before granting access to the skill. This is the "fulfillment" step of the purchase.--## Instructions-1. **Create a Verification API Endpoint:**- * Create a new API file, e.g., `api/payments/verify-transaction.js`.- * This endpoint will accept a `POST` request at `/api/payments/verify-transaction`.- * The frontend will call this endpoint *after* it has successfully confirmed the transaction on its end.--2. **Request Body and Authentication:**- * The request body should contain:- * `signature`: The transaction signature returned by `sendRawTransaction`.- * `agentId`: The agent ID for the skill purchased.- * `skillName`: The name of the skill purchased.- * This endpoint must be authenticated to get the `userId` of the purchaser.--3. **Backend Verification Logic:**- * Inside the API handler:- 1. **Fetch Transaction:** Use the Solana `connection.getParsedTransaction(signature)` method to get the transaction details from the RPC.- 2. **Prevent Replay Attacks:** Check if this `signature` has already been used to unlock a skill in your `user_unlocked_skills` table. If it exists, return an error. This is critical.- 3. **Fetch Skill Price:** Get the expected price (`amount`, `currency_mint`) and the creator's wallet address from your database for the given `agentId` and `skillName`.- 4. **Validate Details:** Parse the fetched transaction and verify that:- * It was successful (the `meta.err` field in the response is `null`).- * It contains a token transfer instruction.- * The transfer's `source` address belongs to the authenticated user (`userId`).- * The transfer's `destination` address belongs to the agent's creator.- * The transfer `amount` matches the expected price from your database.- * The transfer `mint` matches the expected currency from your database.- 5. **Handle Failure:** If any of these checks fail, return a `400 Bad Request` or `422 Unprocessable Entity` error with a clear message.--4. **Record Ownership:**- * If all checks pass, `INSERT` a new row into the `user_unlocked_skills` table with the `userId`, `agentId`, `skillName`, `purchase_tx_signature`, and the price details.--5. **Return Success:**- * Return a `200 OK` response to the frontend to confirm that the backend has successfully verified and fulfilled the purchase.--## Code Example (`api/payments/verify-transaction.js`)--```javascript-import { Connection, PublicKey } from '@solana/web3.js';-import { json, wrap } from '../_lib/http.js';-import { getAuth } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';--const connection = new Connection(process.env.SOLANA_RPC_ENDPOINT);--export default wrap(async (req, res) => {- // ... authentication ...- const { userId } = await getAuth(req);- const { signature, agentId, skillName } = req.body;-- // 1. Check for replay attacks- const [existing] = await sql`SELECT id FROM user_unlocked_skills WHERE purchase_tx_signature = ${signature}`;- if (existing) {- return json(res, 409, { error: 'Transaction has already been used.' });- }-- // 2. Fetch expected price and creator info from DB- // ... query to get priceInfo and creatorWallet ...-- // 3. Fetch and parse the transaction from Solana RPC- const tx = await connection.getParsedTransaction(signature, 'confirmed');- if (!tx || tx.meta.err) {- return json(res, 400, { error: 'Transaction not found or failed.' });- }-- // 4. Validate the transaction details (this is a simplified example)- const transfer = tx.transaction.message.instructions.find(- (ix) => ix.parsed?.type === 'transfer' && ix.program === 'spl-token'- );-- if (!transfer) {- return json(res, 400, { error: 'No valid SPL token transfer found.' });- }-- const { source, destination, amount } = transfer.parsed.info;- // You would also need to verify the owner of the source account matches the user.- // This requires more complex parsing of account data.-- const expectedAmount = priceInfo.amount.toString();- const expectedDestination = creatorTokenAccountAddress; // You need to derive this-- if (amount !== expectedAmount || destination !== expectedDestination) {- return json(res, 400, { error: 'Transaction details do not match expected values.' });- }-- // 5. If all checks pass, record the purchase- await sql`- INSERT INTO user_unlocked_skills (user_id, agent_id, skill_name, purchase_tx_signature, purchase_amount, purchase_currency_mint)- VALUES (${userId}, ${agentId}, ${skillName}, ${signature}, ${priceInfo.amount}, ${priceInfo.currency_mint})- `;-- return json(res, 200, { success: true, message: 'Skill unlocked.' });-});-```diff --git a/docs/monetization/10-creator-payout-wallet-management.md b/docs/monetization/10-creator-payout-wallet-management.mddeleted file mode 100644index f07b8bcf6..000000000--- a/docs/monetization/10-creator-payout-wallet-management.md+++ /dev/null@@ -1,115 +0,0 @@-# Prompt 10: Creator Payout Wallet Management--## Objective-Implement the UI and backend logic for an agent creator to specify their Solana treasury wallet, where they will receive payments from skill sales.--## Explanation-For creators to receive their earnings, they must provide a valid Solana wallet address. This task involves adding an input field in the monetization dashboard for this address and creating a secure backend endpoint to save it. This address will be stored and associated with the agent, to be used later in the payment transaction logic.--## Instructions-1. **Add UI in Dashboard:**- * In the "Monetization" tab in `agent-edit.html`, use the placeholder from prompt #7. It should contain an `<input>` for the wallet public key and a "Save" button.--2. **Frontend Logic:**- * In `src/agent-edit.js`, fetch the agent's current treasury wallet address when the tab loads and populate the input field.- * Add a click event listener to the "Save" button. This handler will read the value from the input, perform basic validation (e.g., check if it's a valid Solana public key format), and send it to the backend.--3. **Backend Endpoint:**- * Create a new endpoint, for example `/api/agents/[id]/treasury`, to handle updating the treasury wallet.- * This endpoint must be secure, verifying that the user making the request is the creator of the agent.- * It will take the `treasuryWallet` public key from the request body and update the `creator_treasury_wallet` column on the `agents` table for the specified agent.--## Database Schema (Alter `agents` table)--```sql--- Add a new column to the agents table to store the payout address-ALTER TABLE agents-ADD COLUMN creator_treasury_wallet TEXT;---- You might want to add a check constraint for valid base58 format--- but this can also be handled at the application layer.-```--## Code Example (`src/agent-edit.js`)--```javascript-// Add to the monetization tab logic-const treasuryInput = document.getElementById('treasuryWallet');-const saveTreasuryBtn = document.getElementById('saveTreasuryWallet');--async function loadTreasuryWallet(agentId) {- const agent = await getAgentData(agentId); // Assuming this function exists- if (agent.creator_treasury_wallet) {- treasuryInput.value = agent.creator_treasury_wallet;- }-}--saveTreasuryBtn.addEventListener('click', async () => {- const agentId = /* get agent id from context */;- const newWallet = treasuryInput.value.trim();-- // Basic validation (more robust validation is recommended)- if (!newWallet || newWallet.length < 32 || newWallet.length > 44) {- alert('Please enter a valid Solana public key.');- return;- }-- try {- const response = await fetch(`/api/agents/${agentId}/treasury`, {- method: 'PUT',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ treasuryWallet: newWallet }),- });-- if (!response.ok) throw new Error('Failed to save wallet address.');-- alert('Payout wallet updated successfully!');- } catch (error) {- alert(`Error: ${error.message}`);- }-});--// Call loadTreasuryWallet when the tab is shown-```--## Code Example (`api/agents/[id]/treasury.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';-import { getAuthUser } from '../../_lib/auth';--export default async function handler(req, res) {- if (req.method !== 'PUT') return error(res, 405, 'Method Not Allowed');-- const { id: agentId } = req.query;- const user = await getAuthUser(req);- const { treasuryWallet } = req.body;-- if (!user) return error(res, 401, 'Unauthorized');- if (!treasuryWallet) return error(res, 400, 'Missing treasuryWallet');-- // Verify ownership- const { data: agent, error: agentError } = await supabase- .from('agents')- .select('creator_id')- .eq('id', agentId)- .single();-- if (agentError || agent.creator_id !== user.id) {- return error(res, 403, 'Forbidden');- }-- // Update the agent's treasury wallet- const { error: updateError } = await supabase- .from('agents')- .update({ creator_treasury_wallet: treasuryWallet })- .eq('id', agentId);-- if (updateError) {- return error(res, 500, 'Failed to update treasury wallet.');- }-- return json(res, { success: true });-}-```diff --git a/docs/monetization/10-creator-payout-wallet.md b/docs/monetization/10-creator-payout-wallet.mddeleted file mode 100644index f8f02810d..000000000--- a/docs/monetization/10-creator-payout-wallet.md+++ /dev/null@@ -1,80 +0,0 @@-# Prompt 10: Creator Payouts Wallet--## Objective-Add a field in the user's settings or profile page for creators to specify the Solana wallet address where they want to receive payments for their paid skills.--## Explanation-To pay creators, we need to know where to send the funds. This task involves adding a UI element and the corresponding backend logic to allow users to save their primary payout wallet address. This address will be used as the destination for all skill purchase transactions.--## Instructions-1. **Database Schema Update:**- * Add a new nullable column to your `users` table, such as `payout_wallet_address` (of type `VARCHAR(255)`).--2. **Update the User Settings UI:**- * In the user's profile or dashboard page (e.g., `profile.html`), add a new section for "Payout Information".- * Include an `<input type="text">` field for the user to enter their Solana wallet address.- * Add a "Save" button for this section.--3. **Frontend Logic:**- * When the page loads, fetch the current user's data and populate the input field with their saved `payout_wallet_address`, if it exists.- * When the "Save" button is clicked:- * Perform basic client-side validation to check if the input looks like a valid Solana address (e.g., check length, base58 characters).- * Make a `PUT` or `POST` request to a new backend endpoint to save the address.--4. **Backend Endpoint:**- * Create an endpoint, e.g., `/api/users/me/payout-wallet`.- * This endpoint should be authenticated.- * It will receive the wallet address in the request body.- * Perform server-side validation to ensure it's a valid public key.- * Update the `payout_wallet_address` column for the authenticated user in the `users` table.--## HTML Example (`profile.html`)--```html-<div class="settings-section">- <h2>Payout Wallet</h2>- <p>Enter the Solana wallet address where you'd like to receive payments.</p>- <div class="form-group">- <label for="payout-wallet">Solana Wallet Address</label>- <input type="text" id="payout-wallet" placeholder="Enter your public key">- <small id="wallet-error" class="error-text"></small>- </div>- <button id="save-payout-wallet-btn">Save Wallet Address</button>-</div>-```--## Frontend JavaScript Example--```javascript-import { PublicKey } from '@solana/web3.js';--const saveBtn = document.getElementById('save-payout-wallet-btn');-const walletInput = document.getElementById('payout-wallet');-const errorEl = document.getElementById('wallet-error');--saveBtn.addEventListener('click', async () => {- const address = walletInput.value.trim();- errorEl.textContent = '';-- // Client-side validation- try {- new PublicKey(address); // Throws an error if invalid- } catch (e) {- errorEl.textContent = 'Invalid Solana address.';- return;- }-- // Send to backend- const response = await fetch('/api/users/me/payout-wallet', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ walletAddress: address }),- });-- if (response.ok) {- showToast('Payout wallet updated!', 'success');- } else {- showToast('Failed to update wallet.', 'error');- }-});-```diff --git a/docs/monetization/10-payment-recipient-setup.md b/docs/monetization/10-payment-recipient-setup.mddeleted file mode 100644index ff5d546fb..000000000--- a/docs/monetization/10-payment-recipient-setup.md+++ /dev/null@@ -1,49 +0,0 @@-# Prompt 10: Creator Payment Address Setup--## Objective-Allow agent creators to specify their own Solana wallet address as the recipient for skill payments.--## Explanation-To make the platform a true marketplace, creators need to be able to receive payments directly. This involves adding a field in the agent creation/editing form for a payout address and storing it securely in the backend.--## Instructions-1. **Update Database Schema:**- * Add a `creator_wallet_address` column to the `agents` table in your database. This will store the public key of the creator's wallet.--2. **Modify Agent Edit UI:**- * In the UI where creators can create or edit their agents (`agent-edit.html`), add a new input field for "Payout Wallet Address."- * Implement frontend validation to ensure the entered string is a valid Solana public key format.--3. **Update Backend API:**- * Modify the agent update endpoint (e.g., `/api/agents/:id` with a `POST` or `PUT` method).- * When an agent is updated, validate the provided `creator_wallet_address` on the backend as well.- * Save the validated address to the new column in the `agents` table.--4. **Use the Address in Transactions:**- * In `prompt-05-initiate-solana-transaction`, the code already assumes the agent object contains `creator_wallet_address`. This prompt ensures that data is actually captured and saved correctly. No changes are needed to the transaction logic itself, as it was designed to be dynamic.--## Code Example (Frontend Validation in `agent-edit.js`)-```javascript-import { PublicKey } from '@solana/web3.js';--const walletInput = document.getElementById('payout-wallet-input');-const saveButton = document.getElementById('save-agent-button');--walletInput.addEventListener('input', () => {- try {- // Validate the public key format- new PublicKey(walletInput.value);- walletInput.setCustomValidity(''); // Valid- } catch (error) {- walletInput.setCustomValidity('Please enter a valid Solana wallet address.'); // Invalid- }-});--saveButton.addEventListener('click', async () => {- // On save, re-validate before sending to backend- if (!walletInput.reportValidity()) {- return; // Don't submit if invalid- }- //... proceed with fetch to backend API-});-```diff --git a/docs/monetization/10_enforce_skill_ownership.md b/docs/monetization/10_enforce_skill_ownership.mddeleted file mode 100644index 3caacc19d..000000000--- a/docs/monetization/10_enforce_skill_ownership.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 10: Enforcing Skill Ownership for API Usage--## Objective-Secure the agent's skill execution endpoint (`/api/chat` or similar) to prevent users from using paid skills they have not purchased.--## Explanation-Currently, the chat API likely allows any user to invoke any of an agent's skills. With paid skills, we must add an ownership check. Before executing a skill, the API needs to determine if the skill is free or, if it's paid, whether the calling user has purchased it.--## Instructions-1. **Locate the Skill Execution Logic:**- * Find the API endpoint responsible for agent chat and skill execution. This is likely a central part of the application, possibly in `api/chat.js`.--2. **Implement the Access Control Check:**- * Inside the handler, just before the point where a skill is about to be executed, insert the access control logic.- * **Step 1: Get Skill and User:**- * You'll have the `agent_id`, the `skill_name` being invoked, and the `user_id` from the session.- * **Step 2: Check if the Skill is Priced:**- * Query the `agent_skill_prices` table to see if a price is set for the `agent_id` and `skill_name`.- * **Step 3: Enforce Ownership:**- * If no price exists, the skill is free, and execution can proceed.- * If a price *does* exist, you must query the `user_purchased_skills` table to check for a record matching the `user_id`, `agent_id`, and `skill_name`.- * If a record exists, the user owns the skill. Proceed with execution.- * If no record exists, the user does not have access. Return a `403 Forbidden` error with a clear message like "You must purchase this skill to use it."--## Code Example (Inside the Chat/Skill Execution API)--```javascript-// This logic should be inserted before the skill execution block--const { agentId, skillName, userId } = /* ... from request context ... */;--// 1. Check if the skill has a price-const [skillPrice] = await sql`- SELECT id FROM agent_skill_prices- WHERE agent_id = ${agentId} AND skill_name = ${skillName}-`;--// If it has no price, it's free, so we can exit the check early-if (!skillPrice) {- // Proceed with skill execution...- return;-}--// 2. If it's priced, check if the user owns it-const [purchaseRecord] = await sql`- SELECT id FROM user_purchased_skills- WHERE user_id = ${userId} AND agent_id = ${agentId} AND skill_name = ${skillName}-`;--if (!purchaseRecord) {- // User does NOT own the skill. Block execution.- return error(res, 403, 'skill_not_owned', `Access denied. You must purchase the '${skillName}' skill to use it.`);-}--// 3. If we reach here, the user owns the skill.-// Proceed with skill execution...--```diff --git a/docs/monetization/11-backend-api-for-skill-prices.md b/docs/monetization/11-backend-api-for-skill-prices.mddeleted file mode 100644index 873d95959..000000000--- a/docs/monetization/11-backend-api-for-skill-prices.md+++ /dev/null@@ -1,78 +0,0 @@-# Prompt 11: Backend API for Saving Skill Prices--## Status-- [ ] Not Started--## Objective-Create the backend API endpoint that allows agent creators to save the prices they've set for their skills.--## Explanation-This prompt complements the previous one by providing the backend infrastructure to persist the pricing information set in the agent editor UI. This endpoint will receive the pricing data and update the `agent_skill_prices` table.--## Instructions-1. **Create the API Endpoint:**- * Create a new route, for example `POST /api/agents/:id/skill-prices`.- * This endpoint must be protected and only accessible by the agent's creator.--2. **Implement the Update Logic:**- * The endpoint will receive the agent's ID and a payload containing the skill prices (e.g., `{ "skill_name": { "amount": ..., "currency_mint": "..." } }`).- * The logic should handle creating, updating, and deleting skill prices. A common approach is to:- * Delete all existing price entries for that agent.- * Insert the new price entries from the payload.- * This "delete-then-insert" pattern is simple to implement, but for more advanced use cases, you might want to perform individual `UPSERT` operations.- * Validate the input data to ensure amounts are valid numbers and currency mints are in the correct format.--## Code Example (Backend - `/api/agents/[id]/skill-prices.js`)-```javascript-// Example using a hypothetical DB utility-import { db } from './_db.js';-import { getUserIdFromRequest } from './_auth.js'; // Auth utility--export default async function handler(req, res) {- if (req.method !== 'POST') {- return res.status(405).json({ error: 'Method Not Allowed' });- }-- const agentId = req.query.id;- const userId = await getUserIdFromRequest(req);-- // 1. Authorization: Check if the user is the agent's creator- const agent = await db.query('SELECT creator_id FROM agents WHERE id = $1', [agentId]);- if (!agent || agent.creator_id !== userId) {- return res.status(403).json({ error: 'Forbidden' });- }-- const skillPrices = req.body.skillPrices;-- // 2. Database transaction for atomicity- const client = await db.getClient();- try {- await client.query('BEGIN');-- // 3. Delete old prices for this agent- await client.query('DELETE FROM agent_skill_prices WHERE agent_id = $1', [agentId]);-- // 4. Insert new prices- for (const skillName in skillPrices) {- const { amount, currency_mint } = skillPrices[skillName];- // Basic validation- if (typeof amount !== 'number' || typeof currency_mint !== 'string') {- throw new Error('Invalid price data for skill: ' + skillName);- }- await client.query(- 'INSERT INTO agent_skill_prices (agent_id, skill_name, amount, currency_mint) VALUES ($1, $2, $3, $4)',- [agentId, skillName, amount, currency_mint]- );- }-- await client.query('COMMIT');- res.status(200).json({ success: true });- } catch (error) {- await client.query('ROLLBACK');- console.error('Failed to save skill prices:', error);- res.status(500).json({ error: 'Internal Server Error' });- } finally {- client.release();- }-}-```diff --git a/docs/monetization/11-backend-creator-wallet-table.md b/docs/monetization/11-backend-creator-wallet-table.mddeleted file mode 100644index dd6006a46..000000000--- a/docs/monetization/11-backend-creator-wallet-table.md+++ /dev/null@@ -1,54 +0,0 @@-----status: not-started------# Prompt 11: Backend - Creator Wallet Table--## Objective-Create a database table for agent creators to securely store their Solana payout wallet address.--## Explanation-To pay creators their share of skill sales, we need to know where to send the funds. A dedicated table, `creator_payout_wallets`, will store a mapping between a `user_id` and their chosen Solana wallet address. This separates the payout wallet from their login credentials or other profile information, providing flexibility and better security.--## Instructions-1. **Design the Table Schema:**- * Name the table `creator_payout_wallets`.- * It needs a column to link to the user (`user_id`), which should be unique. This enforces a one-to-one relationship: one user account has one payout wallet.- * It needs a column to store the Solana wallet public key (`wallet_address` as `VARCHAR(44)`).- * Add a primary key on `user_id` for efficient lookups and to enforce the unique constraint.- * Add a foreign key constraint from `user_id` to the `users(id)` table.- * Include `created_at` and `updated_at` timestamps.--2. **Create a SQL Migration File:**- * Create a new SQL migration file (e.g., `scripts/migrations/004_create_creator_payout_wallets.sql`).- * Write the `CREATE TABLE` statement for `creator_payout_wallets`.- * Set up the `updated_at` trigger for this new table as you've done for previous tables.--## Code Example (SQL)--```sql--- scripts/migrations/004_create_creator_payout_wallets.sql--CREATE TABLE IF NOT EXISTS creator_payout_wallets (- user_id INTEGER PRIMARY KEY,- -- Solana public key address- wallet_address VARCHAR(44) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- CONSTRAINT fk_user- FOREIGN KEY(user_id)- REFERENCES users(id)- ON DELETE CASCADE-);---- Use the existing trigger function for updated_at-CREATE TRIGGER set_timestamp-BEFORE UPDATE ON creator_payout_wallets-FOR EACH ROW-EXECUTE PROCEDURE set_updated_at_timestamp();--```--## Note on Data Integrity-By setting `user_id` as the primary key, we ensure that each user can only have one payout wallet entry. When they want to change their wallet, we will perform an `UPDATE` operation on their existing row rather than inserting a new one.diff --git a/docs/monetization/11-backend-payout-logic.md b/docs/monetization/11-backend-payout-logic.mddeleted file mode 100644index d15c37d5b..000000000--- a/docs/monetization/11-backend-payout-logic.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 11: Backend Logic for Payouts--## Objective-Integrate the creator's saved payout wallet address into the skill purchase transaction logic.--## Explanation-Now that creators can specify their payout wallet, we need to ensure our payment processing logic uses this address as the destination for funds. This task involves modifying the backend Solana Pay endpoint to fetch the creator's payout address and use it when constructing the transaction.--## Instructions-1. **Create a Database Function (`_lib/db.js`):**- * Write a new function, `findCreatorPayoutWallet(agentId)`.- * This function should first find the `creator_id` (a `user_id`) from the `agents` table using the `agentId`.- * Then, it should query the `users` table to get the `payout_wallet_address` for that `creator_id`.- * The function should return the wallet address as a string.--2. **Update the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**- * In the main handler, before you construct the transaction, call your new `findCreatorPayoutWallet` function.- * Use the returned wallet address as the `destination` for the main portion of the SPL token transfer.- * If no payout wallet is configured for the creator, the transaction should fail with an informative error. This prevents funds from being sent to a null or invalid address.--## Code Example (Backend - `_lib/db.js`)--```javascript-import { db } from './database-client';--export async function findCreatorPayoutWallet(agentId) {- try {- const result = await db.one(- `- SELECT u.payout_wallet_address- FROM users u- JOIN agents a ON a.creator_id = u.id- WHERE a.id = $1;- `,- [agentId]- );- return result.payout_wallet_address;- } catch (error) {- // 'one' will throw an error if no row is found- console.error(`Could not find payout wallet for agent ${agentId}:`, error);- return null;- }-}-```--## Updated Payment Endpoint (`api/payments/prepare-skill-purchase.js`)--```javascript-// ... (imports)-import { findCreatorPayoutWallet, findSkillPrice } from '../_lib/db';--// ... (handler start)-- try {- // ... (authentication and body validation)-- // Find the creator's configured payout wallet- const creatorPayoutWalletAddress = await findCreatorPayoutWallet(agentId);- if (!creatorPayoutWalletAddress) {- return res.status(500).json({- error: 'Creator has not configured a payout wallet. Purchase cannot be completed.'- });- }- const creatorPublicKey = new PublicKey(creatorPayoutWalletAddress);-- // ... (find skill price, get blockhash)-- // The rest of the transaction logic now uses creatorPublicKey as the destination- const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, creatorPublicKey);-- // ... (create transfer instructions for creator and platform fee)- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- creatorUsdcAddress, // Use the fetched wallet- buyerPublicKey,- creatorAmount- )- );-- // ... (rest of the logic)-- } catch (error) {- // ... (error handling)- }-```diff --git a/docs/monetization/11-creator-dashboard-ui.md b/docs/monetization/11-creator-dashboard-ui.mddeleted file mode 100644index 1b2a658e0..000000000--- a/docs/monetization/11-creator-dashboard-ui.md+++ /dev/null@@ -1,63 +0,0 @@-# Prompt 11: Creator Dashboard UI--## Objective-Design and create the basic user interface for a new "Creator Dashboard" page, where agent creators can manage their monetization settings and view sales data.--## Explanation-A centralized dashboard is essential for creators to feel in control of their creations and revenue. This initial step focuses on building the static UI layout, which will be populated with dynamic data in subsequent tasks.--## Instructions-1. **Create New HTML File:**- * Create a new file, `dashboard.html`.- * This page should be behind authentication, accessible only to logged-in users.--2. **Design the Layout:**- * The layout should include:- * A main navigation/header shared with the rest of the site.- * A sidebar for dashboard-specific navigation (e.g., "Overview," "My Agents," "Analytics," "Settings").- * A main content area.--3. **Build UI Components (Static):**- * In the "Overview" section, add placeholder components for:- * A summary card for total revenue.- * A summary card for total sales.- * A chart (you can use a library like Chart.js or just use a placeholder image for now) to show sales over time.- * In the "My Agents" section, add a placeholder for a table that will list the user's agents, along with stats like sales and revenue for each.--4. **Add CSS:**- * Create a new CSS file, `dashboard.css`, and link it to your HTML.- * Add styles to create a clean, modern, and professional-looking dashboard layout.--## Code Example (HTML Structure - `dashboard.html`)-```html-<div class="dashboard-container">- <aside class="dashboard-sidebar">- <nav>- <ul>- <li><a href="#" class="active">Overview</a></li>- <li><a href="#">My Agents</a></li>- <li><a href="#">Analytics</a></li>- <li><a href="#">Settings</a></li>- </ul>- </nav>- </aside>- <main class="dashboard-content">- <h1>Overview</h1>- <div class="stats-grid">- <div class="stat-card">- <h2>Total Revenue</h2>- <p>$0.00</p>- </div>- <div class="stat-card">- <h2>Total Sales</h2>- <p>0</p>- </div>- </div>- <div class="chart-container">- <h2>Sales Over Time</h2>- <!-- Placeholder for a chart -->- <canvas id="sales-chart"></canvas>- </div>- </main>-</div>-```diff --git a/docs/monetization/11-creator-earnings-dashboard-ui.md b/docs/monetization/11-creator-earnings-dashboard-ui.mddeleted file mode 100644index f185b2a2f..000000000--- a/docs/monetization/11-creator-earnings-dashboard-ui.md+++ /dev/null@@ -1,99 +0,0 @@-# Prompt 11: Creator Earnings Dashboard UI--## Objective-Design and implement a basic UI for the creator's "Earnings" dashboard, which will display their total revenue, the number of sales, and a list of recent transactions.--## Explanation-To provide value to creators, they need visibility into how their skills are performing. This dashboard is the central place for them to track their sales. This task involves creating the frontend components to display this data. The data itself will be fetched from a new backend endpoint (created in the next prompt).--## Instructions-1. **Design the UI Layout:**- * Inside the `#earnings-container` in `agent-edit.html`, create the HTML structure for the earnings dashboard.- * Include "stat cards" for key metrics like "Total Revenue", "Total Sales", and "Balance".- * Add a table structure for a list of recent transactions, with columns for "Date", "Skill", "Price", and "Transaction ID".--2. **Frontend JavaScript:**- * In `src/agent-edit.js`, create a function `renderEarningsDashboard`.- * This function will be called when the monetization tab is displayed.- * It will make a `fetch` call to a new backend endpoint (e.g., `/api/agents/[id]/earnings`) to get the sales data.- * Upon receiving the data, it will populate the stat cards and dynamically generate the rows for the transaction table.--3. **Styling:**- * Add styles to `/public/agent-edit.css` to format the stat cards and the transaction table, ensuring it's readable and visually appealing.--## HTML Example (`agent-edit.html` inside `#earnings-container`)--```html-<div class="earnings-stats">- <div class="stat-card">- <h4>Total Revenue</h4>- <p id="total-revenue-stat">$0.00</p>- </div>- <div class="stat-card">- <h4>Total Sales</h4>- <p id="total-sales-stat">0</p>- </div>- <div class="stat-card">- <h4>Withdrawable Balance</h4>- <p id="balance-stat">$0.00</p>- </div>-</div>--<h4 class="table-header">Recent Sales</h4>-<div class="transactions-table">- <div class="table-header-row">- <div>Date</div>- <div>Skill</div>- <div>Price</div>- <div>Transaction</div>- </div>- <div id="transactions-list">- <!-- Rows will be injected here by JS -->- <div class="table-empty-state">No sales yet.</div>- </div>-</div>-```--## JavaScript Example (`src/agent-edit.js`)--```javascript-async function renderEarningsDashboard(agentId) {- const response = await fetch(`/api/agents/${agentId}/earnings`);- const data = await response.json();-- document.getElementById('total-revenue-stat').textContent = `$${(data.totalRevenue / 1e6).toFixed(2)}`;- document.getElementById('total-sales-stat').textContent = data.totalSales;- document.getElementById('balance-stat').textContent = `$${(data.balance / 1e6).toFixed(2)}`;-- const listContainer = document.getElementById('transactions-list');- if (data.recentSales && data.recentSales.length > 0) {- listContainer.innerHTML = data.recentSales.map(sale => `- <div class="table-row">- <div>${new Date(sale.purchased_at).toLocaleDateString()}</div>- <div>${escapeHtml(sale.skill_name)}</div>- <div>$${(sale.price / 1e6).toFixed(2)}</div>- <div>- <a href="https://solscan.io/tx/${sale.transaction_signature}?cluster=devnet" target="_blank">- ${sale.transaction_signature.slice(0, 6)}...- </a>- </div>- </div>- `).join('');- } else {- listContainer.innerHTML = '<div class="table-empty-state">No sales yet.</div>';- }-}-```--## CSS Example (`/public/agent-edit.css`)--```css-.earnings-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 16px; margin-bottom: 24px; }-.stat-card { background: #101018; padding: 16px; border-radius: 8px; border: 1px solid var(--border); }-.stat-card h4 { margin: 0 0 8px; color: var(--muted); font-size: 14px; }-.stat-card p { margin: 0; font-size: 24px; font-weight: 600; }-.table-header-row, .table-row { display: grid; grid-template-columns: 1fr 1fr 1fr 2fr; padding: 12px 8px; border-bottom: 1px solid var(--border); }-.table-header-row { font-weight: bold; color: var(--muted); }-.table-row a { color: var(--accent); text-decoration: none; }-.table-row a:hover { text-decoration: underline; }-```diff --git a/docs/monetization/11-creator-payouts-dashboard.md b/docs/monetization/11-creator-payouts-dashboard.mddeleted file mode 100644index ba56df300..000000000--- a/docs/monetization/11-creator-payouts-dashboard.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 11: Creator Payouts & Dashboard--## Objective-Develop a system for creators to see their earnings and withdraw their funds.--## Explanation-Creators need a clear and transparent way to track their sales and access their earnings. This involves building a creator dashboard and a secure withdrawal process.--## Instructions-1. **Create a Creator Dashboard Page:**- * Design a new page for creators to view their sales data.- * Display total earnings, sales per skill, and a list of recent transactions.--2. **Implement a Payouts API:**- * Create a backend process for handling creator withdrawals.- * This might involve a smart contract that holds the funds and allows creators to claim their share, or a centralized system that processes payouts periodically.--3. **Security:**- * Ensure the payout process is secure and that only the legitimate creator can withdraw their funds. This might involve connecting their wallet and signing a message to verify ownership.diff --git a/docs/monetization/11-frontend-payment-flow.md b/docs/monetization/11-frontend-payment-flow.mddeleted file mode 100644index ac8f3d49a..000000000--- a/docs/monetization/11-frontend-payment-flow.md+++ /dev/null@@ -1,90 +0,0 @@-# Prompt 11: Frontend Payment Flow and Wallet Signing--## Objective-Implement the client-side logic to receive the prepared transaction from the backend, prompt the user to sign it with their Solana wallet, and send it to the blockchain.--## Explanation-This prompt connects the UI to the user's wallet (e.g., Phantom, Solflare). It orchestrates the most critical part of the user-facing flow: approving the transaction.--## Instructions-1. **File to Edit:**- * Continue working in your main chat component's JavaScript (e.g., `chat/src/App.svelte`).--2. **Wallet Adapter Integration:**- * Ensure you have a Solana wallet adapter library integrated into your project. If not, you will need to add one (e.g., `@solana/wallet-adapter-react`, `@solana/wallet-adapter-base`). The project seems to have some wallet integration already, so tap into that. A function like `detectSolanaWallet()` is mentioned elsewhere.--3. **Create `handlePaymentFlow` Function:**- * This async function will be called when the user clicks "Pay and Continue" in the modal.- * It should accept the `paymentDetails` (skill\_name, agent\_id, etc.) as an argument.--4. **Step-by-Step Logic within `handlePaymentFlow`:**- * **a. Fetch Transaction:** Make a `POST` request to your `/api/payments/prepare-skill-payment` endpoint, sending the `agent_id` and `skill_name`.- * **b. Deserialize Transaction:** The API will return a Base64 encoded transaction. You need to deserialize it back into a `Transaction` object.- ```javascript- import { Transaction } from '@solana/web3.js';- const { paymentId, transaction: base64Transaction } = await response.json();- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));- ```- * **c. Connect to Wallet:** Ensure the user's wallet is connected. If not, prompt them to connect.- * **d. Sign and Send:** Use the wallet adapter to sign and send the transaction. This is typically a single function call that both prompts the user in their wallet and, upon approval, sends the transaction to the network.- ```javascript- const wallet = getSolanaWallet(); // Your project's way of getting the adapter- const signature = await wallet.sendTransaction(transaction, connection);- ```- * **e. Confirm Transaction:** Wait for the transaction to be confirmed by the Solana cluster.- ```javascript- await connection.confirmTransaction(signature, 'confirmed');- ```- * **f. Notify Backend:** Once confirmed, make a final API call to your backend to verify the payment (this will be built in the next prompt). Pass the `paymentId` and the `signature`.- * **g. Return Status:** Return a success or failure object to the modal's logic.--## Code Example (Frontend - Chat Component)--```javascript-// This function is called from the modal's "Pay" button-async function handlePaymentFlow(paymentDetails) {- try {- // a. Fetch Transaction- const prepRes = await fetch('/api/payments/prepare-skill-payment', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- agent_id: agent.id, // Assuming agent is in scope- skill_name: paymentDetails.skill_name- })- });- if (!prepRes.ok) throw new Error('Failed to prepare payment.');-- const { paymentId, transaction: base64Transaction } = await prepRes.json();-- // b. Deserialize- const transaction = Transaction.from(Buffer.from(base64Transaction, 'base64'));-- // c. & d. Connect, Sign, and Send- const wallet = getSolanaWallet();- if (!wallet.connected) await wallet.connect();-- const connection = new Connection(process.env.SOLANA_RPC_URL);- const signature = await wallet.sendTransaction(transaction, connection);-- // e. Confirm- await connection.confirmTransaction(signature, 'confirmed');-- // f. Notify Backend- const confirmRes = await fetch('/api/payments/confirm-skill-payment', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ paymentId, signature })- });- if (!confirmRes.ok) throw new Error('Payment confirmation failed on server.');-- // g. Return Success- return { success: true };-- } catch (error) {- console.error("Payment failed:", error);- // Optionally display a user-friendly error message- return { success: false, error: error.message };- }-}-```diff --git a/docs/monetization/11-reflect-unlocked-skills.md b/docs/monetization/11-reflect-unlocked-skills.mddeleted file mode 100644index 4abbd17f2..000000000--- a/docs/monetization/11-reflect-unlocked-skills.md+++ /dev/null@@ -1,97 +0,0 @@-----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/11_creator_wallet_ui.md b/docs/monetization/11_creator_wallet_ui.mddeleted file mode 100644index f444475fa..000000000--- a/docs/monetization/11_creator_wallet_ui.md+++ /dev/null@@ -1,87 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 11: Creator Wallet Management UI--## Objective-Create a settings page where agent creators can specify the Solana wallet address where they want to receive payments for skill purchases.--## Explanation-To receive payments, creators must provide a destination wallet. This needs to be a secure and user-friendly process. We will create a dedicated UI in the user's profile or dashboard area to manage this. The chosen wallet address will be linked to the agent's on-chain identity.--## Instructions-1. **Design the UI:**- * Create a new page or a new section in an existing user settings/dashboard page (e.g., `profile.html`).- * The UI should consist of:- * An input field for the user to paste their Solana wallet address.- * A "Save" button.- * A display area showing the currently saved wallet address, if any.- * Clear instructions and warnings (e.g., "Use a wallet you control. Payments are irreversible.").--2. **Connect to Backend:**- * The "Save" button will send the wallet address to a new backend endpoint.--3. **Backend Logic:**- * Create an endpoint like `POST /api/users/payout-wallet`.- * **Authentication:** The user must be logged in.- * **Validation:**- * The provided string must be a valid Solana public key. Use a library like `@solana/web3.js`'s `PublicKey` constructor to validate.- * **Storage:**- * The wallet address should be stored securely. A good place for it is in the `meta` JSONB column of the user's primary `agent_identity` that represents their creator profile, or on the `users` table itself. Let's associate it with their main agent identity.- * Specifically, update the agent's `meta.onchain.wallet` field. This aligns with the on-chain identity of the agent.--## Code Example (HTML in `profile.html`)--```html-<div class="panel">- <h2 class="panel-title">Payout Wallet</h2>- <p class="panel-subtitle">- Enter the Solana wallet address where you'd like to receive payments for skill sales.- </p>- <div class="field">- <label for="payout-wallet">Solana Wallet Address</label>- <input type="text" id="payout-wallet" placeholder="Enter your Solana address">- </div>- <button id="save-wallet-btn" class="btn">Save Wallet</button>- <div id="wallet-save-status"></div>-</div>-```--## Code Example (JavaScript)--```javascript-const saveBtn = document.getElementById('save-wallet-btn');-const walletInput = document.getElementById('payout-wallet');-const statusEl = document.getElementById('wallet-save-status');--// On page load, fetch and display the current wallet-fetch('/api/users/me').then(r => r.json()).then(user => {- const mainAgent = user.identities?.find(id => id.is_primary);- if (mainAgent?.meta?.onchain?.wallet) {- walletInput.value = mainAgent.meta.onchain.wallet;- }-});--saveBtn.addEventListener('click', async () => {- const newAddress = walletInput.value.trim();- saveBtn.disabled = true;- statusEl.textContent = 'Saving...';-- const resp = await fetch('/api/users/payout-wallet', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ wallet_address: newAddress }),- });-- if (resp.ok) {- statusEl.textContent = 'Wallet updated successfully!';- statusEl.style.color = 'var(--ok)';- } else {- const { error_description } = await resp.json();- statusEl.textContent = `Error: ${error_description}`;- statusEl.style.color = 'var(--err)';- }- saveBtn.disabled = false;-});-```diff --git a/docs/monetization/12-backend-confirm-payment.md b/docs/monetization/12-backend-confirm-payment.mddeleted file mode 100644index dab42455a..000000000--- a/docs/monetization/12-backend-confirm-payment.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 12: Backend Endpoint to Confirm Payment--## Objective-Create a backend endpoint to confirm that a user's on-chain payment was successful, and then trigger the logic to grant them access to the skill.--## Explanation-After the user signs and sends the transaction, the frontend informs the backend. The backend must then verify on-chain that the transaction was successful and matches the expected payment details. This server-side confirmation is a crucial security step to prevent fraudulent access claims.--## Instructions-1. **Create API Route:**- * Set up a new endpoint: `POST /api/payments/confirm-skill-payment`.- * This endpoint must be authenticated.--2. **Request Body:**- * The endpoint should accept `paymentId` (from the prepare step) and the `signature` of the confirmed transaction.--3. **Backend Logic:**- * **a. Retrieve Payment Intent:** Use the `paymentId` to fetch the `pending` payment record from your `skill_payments` table. If not found or not pending, return an error. Verify that the payment intent belongs to the authenticated user.- * **b. Fetch and Verify Transaction:**- * Use the `signature` to fetch the transaction details from the Solana cluster using `connection.getTransaction(signature)`.- * **Crucial Verifications:**- * Check that the transaction was successful (`err: null`).- * Parse the transaction's instructions. Find the `spl-token` transfer instruction.- * Verify the **source**, **destination**, and **amount** from the on-chain transaction match the details stored in your `skill_payments` record. This prevents users from submitting a signature for a different, unrelated transaction.- * Verify the transaction's blockhash or a stored reference to prevent replay attacks.- * **c. Update Payment Status:** If all verifications pass, update the `skill_payments` record status from `pending` to `completed`.- * **d. Grant Skill Access:** Call the logic to create a record in the `skill_access_grants` table for this user and skill (to be fully implemented in a later prompt).- * **e. Re-trigger AI Flow:** The chat orchestrator should now re-process the original user message that was paused. Since the access grant now exists, the skill check (Prompt 8) will pass, and the skill will execute. The simplest way to do this is to have the `/confirm` endpoint return a success message, and the frontend, upon seeing this success, resubmits the original chat message.- * **f. Respond:** Return a `200 OK` success message.--## Code Example (Backend - `/api/payments/confirm-skill-payment.js`)--```javascript-// --- Inside your API handler -----const { paymentId, signature } = req.body;-const user = await getAuthenticatedUser(req);--// a. Retrieve Payment Intent-const paymentIntent = await db.getPaymentIntent(paymentId);-if (!paymentIntent || paymentIntent.status !== 'pending' || paymentIntent.userId !== user.id) {- return res.status(404).json({ error: 'Invalid or expired payment session.' });-}--try {- // b. Fetch and Verify Transaction- const connection = new Connection(process.env.SOLANA_RPC_URL);- const tx = await connection.getTransaction(signature, { maxSupportedTransactionVersion: 0 });-- if (tx.meta.err) {- throw new Error('Transaction failed on-chain.');- }-- // Find the relevant token transfer instruction (this logic can be complex)- // You may need a helper to parse instructions based on program ID- const transferInstruction = findSplTransfer(tx.transaction.message.instructions);-- // A simplified check. In reality, you need to parse account keys from the message.- const onChainAmount = transferInstruction.data.amount;- if (onChainAmount < paymentIntent.amount) {- throw new Error('On-chain amount does not match expected amount.');- }- // ... more checks for source, destination, etc.-- // c. Update Payment Status- await db.updatePaymentStatus(paymentId, 'completed', signature);-- // d. Grant Skill Access- await db.createSkillAccessGrant({- userId: user.id,- agentId: paymentIntent.agentId,- skillName: paymentIntent.skillName,- // Define your access rules, e.g., expires in 24 hours- expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000),- });-- // e. Respond for frontend to continue- res.status(200).json({ success: true, message: 'Payment confirmed.' });--} catch (error) {- console.error('Confirmation error:', error);- // Optionally update payment status to 'failed'- await db.updatePaymentStatus(paymentId, 'failed');- res.status(400).json({ error: 'Payment verification failed.', details: error.message });-}-```diff --git a/docs/monetization/12-backend-for-earnings-data.md b/docs/monetization/12-backend-for-earnings-data.mddeleted file mode 100644index ca26894ac..000000000--- a/docs/monetization/12-backend-for-earnings-data.md+++ /dev/null@@ -1,90 +0,0 @@-# Prompt 12: Backend for Earnings Data--## Objective-Create the backend endpoint that calculates and returns the earnings data for an agent creator, including total revenue, sales count, and recent transactions.--## Explanation-The creator's earnings dashboard needs data to display. This endpoint (`/api/agents/[id]/earnings`) will be responsible for querying the database to aggregate sales data for a specific agent. It will calculate key metrics and retrieve the most recent sales to populate the UI created in the previous prompt.--## Instructions-1. **Create New API File:**- * Create a new file at `api/agents/[id]/earnings.js`.--2. **Endpoint Logic (GET):**- * The endpoint must handle a GET request.- * It must be authenticated, ensuring the user making the request is the creator of the agent.- * The logic will perform several database queries:- * Query the `user_purchased_skills` table, filtering by `agent_id`.- * To get the revenue, it will need to join with `agent_skill_prices` to get the `amount` for each sale.- * Calculate the SUM of the `amount` for total revenue.- * Calculate the COUNT of rows for total sales.- * Fetch the 10 most recent sales, ordered by `purchased_at` descending.- * The endpoint should return a JSON object containing `totalRevenue`, `totalSales`, `balance` (for now, same as revenue), and an array of `recentSales`.--## Code Example (`api/agents/[id]/earnings.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';-import { getAuthUser } from '../../_lib/auth';--export default async function handler(req, res) {- if (req.method !== 'GET') return error(res, 405, 'Method Not Allowed');-- const { id: agentId } = req.query;- const user = await getAuthUser(req);-- if (!user) return error(res, 401, 'Unauthorized');-- // Verify ownership- const { data: agent, error: agentError } = await supabase- .from('agents')- .select('creator_id')- .eq('id', agentId)- .single();-- if (agentError || agent.creator_id !== user.id) {- return error(res, 403, 'Forbidden');- }-- // Fetch all sales for this agent- const { data: sales, error: salesError } = await supabase- .from('user_purchased_skills')- .select(`- purchased_at,- skill_name,- transaction_signature,- agent_skill_prices ( amount )- `)- .eq('agent_id', agentId)- .order('purchased_at', { ascending: false });-- if (salesError) {- return error(res, 500, 'Failed to fetch sales data.');- }-- const totalSales = sales.length;- const totalRevenue = sales.reduce((acc, sale) => {- // The price is on the joined table- const price = sale.agent_skill_prices?.amount || 0;- return acc + price;- }, 0);-- const recentSales = sales.slice(0, 10).map(s => ({- purchased_at: s.purchased_at,- skill_name: s.skill_name,- price: s.agent_skill_prices?.amount || 0,- transaction_signature: s.transaction_signature,- }));-- // Balance calculation would be more complex with payouts, for now it's total revenue.- const balance = totalRevenue;-- return json(res, {- totalRevenue,- totalSales,- balance,- recentSales,- });-}-```diff --git a/docs/monetization/12-creator-earnings-dashboard.md b/docs/monetization/12-creator-earnings-dashboard.mddeleted file mode 100644index 4b7407cf0..000000000--- a/docs/monetization/12-creator-earnings-dashboard.md+++ /dev/null@@ -1,81 +0,0 @@-# Prompt 12: Creator Earnings and Dashboard--## Status-- [ ] Not Started--## Objective-Develop a dashboard for agent creators to view their total earnings and a list of their sales.--## Explanation-To create a complete ecosystem, creators need visibility into their monetization performance. This prompt outlines the creation of a private dashboard where they can track their earnings.--## Instructions-1. **Create a Sales/Earnings Table:**- * Design a new database table, e.g., `skill_sales`, to log every successful sale.- * Columns should include: `id`, `agent_id`, `skill_name`, `buyer_id`, `seller_id`, `amount`, `currency_mint`, `transaction_signature`, and `created_at`.--2. **Log Sales on Purchase:**- * Modify the `/api/payments/finalize-purchase` endpoint from Prompt 8.- * After recording skill ownership, add another step to insert a record into the new `skill_sales` table.--3. **Create a Backend API for the Dashboard:**- * Create a new authenticated endpoint, e.g., `GET /api/creator/dashboard`.- * This endpoint should:- * Calculate the creator's total earnings by summing the `amount` from the `skill_sales` table, grouped by currency.- * Fetch a list of recent sales transactions for the creator.--4. **Build the Frontend Dashboard:**- * Create a new page, `creator-dashboard.html`, accessible only to logged-in users.- * On this page, fetch data from the new dashboard API.- * Display the total earnings and the list of recent sales in a clear and readable format.--## SQL for `skill_sales`-```sql-CREATE TABLE skill_sales (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID NOT NULL REFERENCES agents(id),- skill_name VARCHAR(255) NOT NULL,- buyer_id UUID NOT NULL REFERENCES users(id),- seller_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- transaction_signature VARCHAR(255) NOT NULL,- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);--CREATE INDEX idx_skill_sales_on_seller_id ON skill_sales (seller_id);-```--## Code Example (Backend - `/api/creator/dashboard.js`)-```javascript-// Example using a hypothetical DB utility-import { db } from './_db.js';-import { getUserIdFromRequest } from './_auth.js';--export default async function handler(req, res) {- const userId = await getUserIdFromRequest(req);-- // 1. Get total earnings- const earningsResult = await db.query(- `SELECT currency_mint, SUM(amount) as total_earned- FROM skill_sales- WHERE seller_id = $1- GROUP BY currency_mint`,- [userId]- );- const totalEarnings = earningsResult.rows;-- // 2. Get recent sales- const salesResult = await db.query(- `SELECT skill_name, amount, currency_mint, created_at, transaction_signature- FROM skill_sales- WHERE seller_id = $1- ORDER BY created_at DESC- LIMIT 50`,- [userId]- );- const recentSales = salesResult.rows;-- res.status(200).json({ totalEarnings, recentSales });-}-```diff --git a/docs/monetization/12-my-purchased-skills-page.md b/docs/monetization/12-my-purchased-skills-page.mddeleted file mode 100644index 2893af338..000000000--- a/docs/monetization/12-my-purchased-skills-page.md+++ /dev/null@@ -1,77 +0,0 @@-# Prompt 12: "My Purchased Skills" Page--## Objective-Create a new page or a dedicated section in the user's dashboard that lists all the skills they have purchased across all agents.--## Explanation-Users need a central place to see all the premium content they've acquired. This improves user experience and provides a clear overview of their purchases. This task involves creating the UI for this page and wiring it up to a new backend endpoint.--## Instructions-1. **Create a New HTML Page or Section:**- * You can either create a new file, `my-skills.html`, or add a new section to an existing dashboard page (e.g., `dashboard.html`).- * The page should have a clear heading like "My Purchased Skills".- * It should contain a list or grid element that will be populated with the purchased skills.--2. **Frontend JavaScript Logic:**- * Create a new JavaScript file or add to an existing one that's loaded on the dashboard page.- * On page load, make a `GET` request to a new API endpoint (`/api/users/me/owned-skills`) to fetch the list of skills.- * For each skill returned, render an item in the list. Each item should display:- * The skill's name.- * The name of the agent it belongs to (and maybe a link to that agent's page).- * The date of purchase.- * The price paid.--3. **UI/UX Considerations:**- * Include a loading state while the skills are being fetched.- * Display a user-friendly message if the user hasn't purchased any skills yet (e.g., "You haven't purchased any skills yet. Explore the marketplace to find new abilities for your agents!").--## HTML Example (`dashboard.html`)--```html-<!-- Add this section to the dashboard -->-<section id="my-skills">- <h2>My Purchased Skills</h2>- <div id="owned-skills-list" class="skills-grid">- <!-- Skeletons for loading state -->- <div class="skill-card-skeleton"></div>- <div class="skill-card-skeleton"></div>- <div class="skill-card-skeleton"></div>- </div>-</section>-```--## JavaScript Logic Example--```javascript-async function loadOwnedSkills() {- const container = document.getElementById('owned-skills-list');- try {- const response = await fetch('/api/users/me/owned-skills');- if (!response.ok) throw new Error('Failed to fetch skills');-- const skills = await response.json();-- if (skills.length === 0) {- container.innerHTML = '<p>You have not purchased any skills yet.</p>';- return;- }-- container.innerHTML = skills.map(skill => `- <div class="owned-skill-card">- <h3>${escapeHtml(skill.skill_name)}</h3>- <p>From Agent: <a href="/marketplace/agent/${skill.agent_id}">${escapeHtml(skill.agent_name)}</a></p>- <div class="skill-meta">- <span>Purchased: ${new Date(skill.purchase_date).toLocaleDateString()}</span>- <span>Price: ${(skill.price_amount / 1e6).toFixed(2)} USDC</span>- </div>- </div>- `).join('');-- } catch (error) {- container.innerHTML = '<p class="error">Could not load your skills. Please try again later.</p>';- console.error('Error loading skills:', error);- }-}--document.addEventListener('DOMContentLoaded', loadOwnedSkills);-```diff --git a/docs/monetization/12-platform-fee-implementation.md b/docs/monetization/12-platform-fee-implementation.mddeleted file mode 100644index 38a8370a3..000000000--- a/docs/monetization/12-platform-fee-implementation.md+++ /dev/null@@ -1,44 +0,0 @@-----status: not-started------# Prompt 12: Platform Fee Implementation--## Objective-Implement a platform fee on every skill purchase transaction.--## Explanation-To ensure the sustainability of the platform, a small percentage of each sale will be collected as a platform fee. This needs to be calculated and transferred during the payment process.--## Instructions-1. **Modify the Payment Transaction:**- * In `src/marketplace.js`, when constructing the purchase transaction, add a second instruction.- * The first instruction will transfer the creator's share of the payment to their wallet.- * The second instruction will transfer the platform's fee to the platform's treasury wallet.--2. **Configuration:**- * The platform fee percentage should be configurable and stored in a secure location.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// Inside the purchase logic-const platformFee = price.amount * 0.05; // 5% fee-const creatorGets = price.amount - platformFee;--const transaction = new solanaWeb3.Transaction()- .add(- solanaWeb3.SystemProgram.transfer({- fromPubkey: user.publicKey,- toPubkey: new solanaWeb3.PublicKey(creatorWalletAddress),- lamports: creatorGets,- })- )- .add(- solanaWeb3.SystemProgram.transfer({- fromPubkey: user.publicKey,- toPubkey: new solanaWeb3.PublicKey(platformTreasuryAddress),- lamports: platformFee,- })- );-```diff --git a/docs/monetization/12-sales-analytics-api.md b/docs/monetization/12-sales-analytics-api.mddeleted file mode 100644index 7ce7f448e..000000000--- a/docs/monetization/12-sales-analytics-api.md+++ /dev/null@@ -1,66 +0,0 @@-# Prompt 12: Sales Analytics API--## Objective-Create a secure backend API endpoint that retrieves and aggregates sales data for a creator's agents.--## Explanation-The creator dashboard needs data to display. This endpoint will be responsible for querying the database (or blockchain data) to provide the necessary analytics, such as total revenue and sales volume, for the currently logged-in creator.--## Instructions-1. **Record Sales Data:**- * First, you need data to query. In the `/api/skills/mint` endpoint from Prompt 7, after a successful mint, you must save a record of the sale to a new `sales` table in your database.- * The `sales` table should include `id`, `agent_id`, `skill_name`, `price`, `currency`, `buyer_wallet`, `transaction_signature`, and a `timestamp`.--2. **Create Analytics Endpoint:**- * Create a new endpoint, `/api/dashboard/analytics`.- * This endpoint must be authenticated, ensuring a user can only access their own sales data. It should get the `user_id` from the session.--3. **Query and Aggregate Data:**- * In the endpoint logic:- * Find all agents owned by the logged-in user.- * Query the `sales` table for all sales related to those agents.- * Use SQL `SUM()` and `COUNT()` to aggregate the data to calculate:- * Total revenue.- * Total number of sales.- * Sales data grouped by day or month for the chart.--4. **Return Data:**- * Return the aggregated data in a structured JSON format that the frontend can easily consume.--## Code Example (Backend Endpoint - `/api/dashboard/analytics.js`)-```javascript-// This is a conceptual example using a SQL-like query builder--async function getAnalytics(req, res) {- const userId = req.session.userId; // Get user ID from session- if (!userId) {- return res.status(401).json({ error: 'Unauthorized' });- }-- // Query the database- const result = await db.query(- `SELECT- SUM(price) as total_revenue,- COUNT(id) as total_sales,- DATE_TRUNC('day', timestamp) as date,- COUNT(id) as daily_sales- FROM sales- WHERE agent_id IN (SELECT id FROM agents WHERE owner_id = $1)- GROUP BY DATE_TRUNC('day', timestamp)- ORDER BY date ASC;- `, [userId]- );-- // Process and return data- const analyticsData = {- totalRevenue: result.rows.reduce((acc, row) => acc + parseFloat(row.total_revenue), 0),- totalSales: result.rows.reduce((acc, row) => acc + parseInt(row.total_sales), 0),- salesOverTime: result.rows.map(row => ({- date: row.date,- sales: row.daily_sales- }))- };-- res.status(200).json(analyticsData);-}-```diff --git a/docs/monetization/12-user-purchase-history.md b/docs/monetization/12-user-purchase-history.mddeleted file mode 100644index 9c6c51365..000000000--- a/docs/monetization/12-user-purchase-history.md+++ /dev/null@@ -1,115 +0,0 @@-----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/12_creator_payouts_dashboard.md b/docs/monetization/12_creator_payouts_dashboard.mddeleted file mode 100644index d9cc314f2..000000000--- a/docs/monetization/12_creator_payouts_dashboard.md+++ /dev/null@@ -1,86 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 12: Creator Payouts Dashboard--## Objective-Create a dashboard for creators to view their sales history and total earnings.--## Explanation-To provide transparency and a good creator experience, we need a dashboard that shows them how much they've earned from their paid skills. This involves aggregating data from the `user_purchased_skills` table and presenting it in a clear, easy-to-understand format.--## Instructions-1. **Create a New Page:**- * Create a new HTML file for the dashboard, e.g., `creator-dashboard.html`.- * This page will be accessible to logged-in users from their profile or a main navigation link.--2. **Backend API for Sales Data:**- * Create a new endpoint, e.g., `GET /api/creators/sales-data`.- * **Authentication:** Requires a logged-in user.- * **Database Query:**- * The endpoint should query the `user_purchased_skills` table.- * It needs to find all purchases where the `agent_id` belongs to an agent owned by the current user.- * It should aggregate the data to calculate:- * Total revenue (sum of `price_amount`).- * Number of sales.- * A list of recent sales transactions with details (skill name, agent name, price, date).- * The data should be grouped by currency if multiple currencies are supported in the future.--3. **Frontend Implementation:**- * The `creator-dashboard.html` page's JavaScript will call the new API endpoint.- * **Display Key Metrics:** Show "Total Revenue" and "Total Sales" in prominent summary cards.- * **Display Sales History:** Render the list of recent transactions in a table or a list format. Each entry should be clear and provide essential information.- * **Add Charts (Optional but Recommended):** Use a charting library (like Chart.js) to visualize sales over time (e.g., daily or weekly revenue).--## Code Example (Backend API - `GET /api/creators/sales-data`)--```javascript-import { sql } from '../../_lib/db.js';-// ... other imports--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- if (!user) return error(res, 401, 'unauthorized');-- // 1. Get all agents owned by the user- const userAgents = await sql`- SELECT id FROM agent_identities WHERE user_id = ${user.id}- `;- const agentIds = userAgents.map(a => a.id);-- if (agentIds.length === 0) {- return json(res, 200, { totalRevenue: 0, salesCount: 0, recentSales: [] });- }-- // 2. Aggregate sales data for those agents- const [salesData] = await sql`- SELECT- SUM(price_amount) AS total_revenue,- COUNT(id) AS sales_count- FROM user_purchased_skills- WHERE agent_id = ANY(${agentIds})- `;-- // 3. Get recent sales- const recentSales = await sql`- SELECT- p.skill_name,- a.name AS agent_name,- p.price_amount,- p.price_currency_mint,- p.created_at- FROM user_purchased_skills p- JOIN agent_identities a ON p.agent_id = a.id- WHERE p.agent_id = ANY(${agentIds})- ORDER BY p.created_at DESC- LIMIT 20- `;-- return json(res, 200, {- totalRevenue: parseInt(salesData.total_revenue) || 0,- salesCount: parseInt(salesData.sales_count) || 0,- recentSales: recentSales- });-});-```diff --git a/docs/monetization/13-api-for-owned-skills.md b/docs/monetization/13-api-for-owned-skills.mddeleted file mode 100644index cf4a6e4c7..000000000--- a/docs/monetization/13-api-for-owned-skills.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 13: API for Owned Skills (Backend)--## Objective-Create the backend API endpoint that provides a list of skills owned by the currently authenticated user.--## Explanation-This endpoint will power the "My Purchased Skills" page (from the previous prompt). It needs to query the database, joining across several tables (`user_skill_ownership`, `agents`, `agent_skill_prices`) to gather all the necessary information for display.--## Instructions-1. **Create the API Endpoint:**- * Create a new file: `/api/users/me/owned-skills.js`.- * This endpoint should handle `GET` requests and must be protected by authentication.--2. **Implement the Database Query:**- * The core of this endpoint is the SQL query. You need to:- * Select all records from `user_skill_ownership` that match the authenticated `user_id`.- * `JOIN` with the `agents` table on `agent_id` to get the agent's name.- * `LEFT JOIN` with the `agent_skill_prices` table on both `agent_id` and `skill_name` to get the price information. Note that price could have changed, so you might want to store the purchase price in the ownership table itself for historical accuracy (a task for a future prompt). For now, joining to get the *current* price is acceptable.- * Select the required fields: `skill_name`, `agent_id`, `agent_name`, `purchase_date` (`created_at` from the ownership table), and the price info.--3. **Return the Data:**- * Execute the query and return the resulting list of skill objects as a JSON array.--## Code Example (Backend - `api/users/me/owned-skills.js`)--```javascript-import { db } from '../../_lib/database-client';--export default async function handler(req, res) {- if (req.method !== 'GET') return res.status(405).end();-- try {- const userId = req.user.id; // From auth middleware-- const { rows } = await db.query(- `- SELECT- uso.skill_name,- uso.created_at AS purchase_date,- a.id AS agent_id,- a.name AS agent_name,- asp.amount AS price_amount,- asp.currency_mint AS price_currency- FROM- user_skill_ownership AS uso- JOIN- agents AS a ON uso.agent_id = a.id- LEFT JOIN- agent_skill_prices AS asp ON uso.agent_id = asp.agent_id AND uso.skill_name = asp.skill_name- WHERE- uso.user_id = $1- ORDER BY- uso.created_at DESC;- `,- [userId]- );-- res.status(200).json(rows);-- } catch (error) {- console.error('Failed to fetch owned skills:', error);- res.status(500).json({ error: 'Internal Server Error' });- }-}-```--## Future Improvement Note-For true historical accuracy, the `user_skill_ownership` table should be modified to store the `amount` and `currency_mint` at the time of purchase. This prevents the user's purchase history from changing if the creator later updates the skill price. This could be its own future prompt: "Refine Purchase History for Price Accuracy."diff --git a/docs/monetization/13-db-schema-access-grants.md b/docs/monetization/13-db-schema-access-grants.mddeleted file mode 100644index a8c9ebf2c..000000000--- a/docs/monetization/13-db-schema-access-grants.md+++ /dev/null@@ -1,65 +0,0 @@-# Prompt 13: Database Schema for Skill Access Grants--## Objective-Design and create the database table schema for `skill_access_grants` to track which users have permission to use specific paid skills.--## Explanation-After a user pays for a skill, we need a persistent record of their access rights. This table will serve as the source of truth for the backend to check before executing a potentially paid skill. It needs to be flexible enough to support different access models, such as time-based expiry or a fixed number of uses.--## Instructions-1. **Define the Table Schema:**- * Create a new table named `skill_access_grants`.- * The table should include the following columns:- * `id`: A unique primary key (e.g., UUID or auto-incrementing integer).- * `user_id`: Foreign key referencing the `users` table. This identifies who bought the skill.- * `agent_id`: Foreign key referencing the `agents` table.- * `skill_name`: A string that matches the name of the skill.- * `payment_id`: Foreign key referencing the `skill_payments` table, linking the grant to the specific purchase.- * `created_at`: Timestamp of when the grant was created.- * `expires_at`: A nullable timestamp. If set, the grant is valid until this time. This supports time-based access (e.g., 24-hour pass).- * `uses_left`: A nullable integer. If set, the grant is valid for this many uses. This supports pay-per-use models.--2. **Create Indexes:**- * Create a composite index on `(user_id, agent_id, skill_name)` for fast lookups when checking for access before skill execution.- * Also, add an index on `expires_at` to efficiently query for expired grants if you need a cleanup job later.--3. **Write the SQL Migration:**- * Create a new SQL migration file to apply this schema change to your database.--## SQL Schema Example--```sql-CREATE TABLE skill_access_grants (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id UUID NOT NULL REFERENCES agents(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- payment_id UUID NOT NULL REFERENCES skill_payments(id),- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- expires_at TIMESTAMPTZ,- uses_left INTEGER,-- -- A user can have multiple grants for the same skill over time, so a unique constraint isn't on user/agent/skill- CONSTRAINT check_positive_uses_left CHECK (uses_left IS NULL OR uses_left >= 0)-);---- Index for fast access checks-CREATE INDEX idx_skill_access_grants_check ON skill_access_grants(user_id, agent_id, skill_name);---- Index for cleaning up expired grants-CREATE INDEX idx_skill_access_grants_expires_at ON skill_access_grants(expires_at);---- You'll also need a skill_payments table-CREATE TABLE skill_payments (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id),- agent_id UUID NOT NULL,- skill_name VARCHAR(255) NOT NULL,- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, completed, failed- signature VARCHAR(255) UNIQUE, -- The on-chain transaction signature- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()-);-```diff --git a/docs/monetization/13-display-sales-analytics.md b/docs/monetization/13-display-sales-analytics.mddeleted file mode 100644index b6df02995..000000000--- a/docs/monetization/13-display-sales-analytics.md+++ /dev/null@@ -1,58 +0,0 @@-# Prompt 13: Display Sales Analytics in Dashboard--## Objective-Fetch data from the new `/api/dashboard/analytics` endpoint and use it to populate the creator dashboard UI with dynamic charts and statistics.--## Explanation-This prompt brings the creator dashboard to life by replacing the static placeholder elements with real, live data from the backend.--## Instructions-1. **Fetch Data on Page Load:**- * In the JavaScript file for the dashboard (`dashboard.js`), add a function that runs when the page loads.- * This function should make a `fetch` request to the `/api/dashboard/analytics` endpoint.--2. **Populate Stat Cards:**- * Once the data is received, update the content of the summary cards for "Total Revenue" and "Total Sales" with the values from the API response.- * Format the revenue as a currency string (e.g., using `toLocaleString`).--3. **Render the Chart:**- * Use a charting library like Chart.js to render the `salesOverTime` data.- * The X-axis should represent the date, and the Y-axis should represent the number of sales.- * Configure the chart to be a line chart for a clear visual representation of trends.--## Code Example (JavaScript - `dashboard.js`)-```javascript-import Chart from 'chart.js/auto';--async function loadAnalytics() {- try {- const response = await fetch('/api/dashboard/analytics');- if (!response.ok) throw new Error('Failed to fetch analytics');- const data = await response.json();-- // Populate stat cards- document.getElementById('total-revenue').textContent = (data.totalRevenue / 1e6).toLocaleString('en-US', { style: 'currency', currency: 'USD' });- document.getElementById('total-sales').textContent = data.totalSales;-- // Render chart- const ctx = document.getElementById('sales-chart').getContext('2d');- new Chart(ctx, {- type: 'line',- data: {- labels: data.salesOverTime.map(item => new Date(item.date).toLocaleDateString()),- datasets: [{- label: 'Sales per Day',- data: data.salesOverTime.map(item => item.sales),- borderColor: '#4f46e5',- tension: 0.1- }]- }- });- } catch (error) {- console.error('Error loading analytics:', error);- // Display an error message in the UI- }-}--document.addEventListener('DOMContentLoaded', loadAnalytics);-```diff --git a/docs/monetization/13-platform-fee-implementation.md b/docs/monetization/13-platform-fee-implementation.mddeleted file mode 100644index 96f6efeab..000000000--- a/docs/monetization/13-platform-fee-implementation.md+++ /dev/null@@ -1,74 +0,0 @@-# Prompt 13: Platform Fee Implementation--## Status-- [ ] Not Started--## Objective-Implement a platform fee on every skill purchase, where a percentage of the sale amount is sent to a platform-owned treasury wallet.--## Explanation-To ensure the platform is sustainable, a platform fee is essential. This requires modifying the transaction creation logic to split the payment between the seller and the platform.--## Instructions-1. **Configure Treasury Wallet:**- * Store the platform's treasury wallet address in a secure configuration file or environment variable (e.g., `PLATFORM_TREASURY_WALLET`).--2. **Modify Transaction Creation API:**- * In the `/api/payments/prepare-transaction` endpoint, calculate the platform fee based on the total price (e.g., a 5% fee).- * The total price is `priceInfo.amount`.- * `platformFee = priceInfo.amount * 0.05`- * `sellerAmount = priceInfo.amount - platformFee`--3. **Create a Multi-Instruction Transaction:**- * The Solana transaction will now have two `createTransferInstruction` calls:- 1. A transfer of `sellerAmount` from the buyer to the seller.- 2. A transfer of `platformFee` from the buyer to the platform's treasury wallet.- * Add both instructions to the same transaction. This ensures the payment split is atomic—either both transfers succeed, or neither does.--## Code Example (Backend - `/api/payments/prepare-transaction.js` Update)-```javascript-// ... (imports and initial setup)--// Inside the handler function, after fetching priceInfo and sellerPublicKey-const PLATFORM_FEE_BPS = 500; // 500 basis points = 5%-const PLATFORM_TREASURY = new PublicKey(process.env.PLATFORM_TREASURY_WALLET);--const totalAmount = priceInfo.amount;-const platformFee = Math.floor(totalAmount * (PLATFORM_FEE_BPS / 10000));-const sellerAmount = totalAmount - platformFee;--// ... (setup connection, buyer, seller, mint)--const buyerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, buyer);-const sellerTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, seller);-const treasuryTokenAccount = await getOrCreateAssociatedTokenAccount(connection, buyer, mint, PLATFORM_TREASURY);--// Create the transaction with TWO transfer instructions-const transaction = new Transaction();--// 1. Transfer to seller-transaction.add(- createTransferInstruction(- buyerTokenAccount.address,- sellerTokenAccount.address,- buyer,- sellerAmount- )-);--// 2. Transfer to platform treasury-transaction.add(- createTransferInstruction(- buyerTokenAccount.address,- treasuryTokenAccount.address,- buyer,- platformFee- )-);--// ... (set blockhash, feePayer, serialize and send)-```--## Important Considerations-* **Rounding:** Be mindful of potential rounding errors when calculating fees. Using integer math with basis points (BPS) is generally safer.-* **Associated Token Accounts:** Ensure the platform's treasury wallet has an associated token account for each currency you support. The `getOrCreateAssociatedTokenAccount` function helps with this, but the transaction to create it might need to be handled separately or signed by the platform.diff --git a/docs/monetization/13-spl-token-payments.md b/docs/monetization/13-spl-token-payments.mddeleted file mode 100644index 4efc804b2..000000000--- a/docs/monetization/13-spl-token-payments.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 13: Support for SPL Token Payments--## Objective-Extend the payment system to support payments with SPL tokens, such as USDC.--## Explanation-Many users prefer to transact with stablecoins like USDC. Supporting SPL tokens will make the platform more accessible and user-friendly.--## Instructions-1. **Modify the Frontend Transaction:**- * In `src/marketplace.js`, the transaction logic needs to be updated.- * Instead of `SystemProgram.transfer`, you will use the `Token.createTransferInstruction` from the `@solana/spl-token` library.- * This requires knowing the user's and the creator's token accounts for the specific SPL token.--2. **Associated Token Accounts:**- * You will need to find the associated token accounts for the sender and receiver. If they don't exist, you might need to include instructions to create them in the transaction.--3. **Backend Verification:**- * The backend payment verification logic must also be updated to correctly parse and validate SPL token transfers.diff --git a/docs/monetization/13-subscription-model-database-schema.md b/docs/monetization/13-subscription-model-database-schema.mddeleted file mode 100644index ed87d4b73..000000000--- a/docs/monetization/13-subscription-model-database-schema.md+++ /dev/null@@ -1,69 +0,0 @@-# Prompt 13: Subscription Model Database Schema--## Objective-Design and create the necessary database tables to support a subscription-based monetization model for agent skills.--## Explanation-To move beyond one-time purchases, we need to support subscriptions. This will allow creators to offer bundles of skills for a recurring fee (e.g., monthly). This task focuses on the database design, which is the foundation for the subscription feature. We will need tables to manage subscription plans (tiers), and to track which users are subscribed to which plans.--## Instructions-1. **Design `agent_subscription_tiers` Table:**- * This table will store the different subscription plans a creator can offer for an agent.- * It should include columns for the agent it belongs to, a name (e.g., "Pro"), a price, a currency, and a billing interval (e.g., 'month', 'year').- * It should also include an array of skill names that are included in this tier.--2. **Design `user_subscriptions` Table:**- * This table will track active user subscriptions.- * It should link a user to a subscription tier.- * It needs columns to manage the subscription's lifecycle, such as `status` (e.g., 'active', 'canceled'), `current_period_start`, and `current_period_end`.--3. **Write SQL Schema:**- * Write the `CREATE TABLE` SQL statements for these new tables. Include appropriate foreign keys, constraints, and indexes.--## SQL Schema Definition--```sql--- Table to define the subscription plans for an agent-CREATE TABLE agent_subscription_tiers (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- agent_id UUID REFERENCES agents(id) NOT NULL,- name TEXT NOT NULL,- description TEXT,- price_amount BIGINT NOT NULL, -- Price in smallest unit- price_currency_mint TEXT NOT NULL,- billing_interval TEXT NOT NULL CHECK (billing_interval IN ('month', 'year')), -- e.g., monthly, yearly- included_skills TEXT[] NOT NULL, -- An array of skill names included in this tier- is_active BOOLEAN DEFAULT TRUE,- created_at TIMESTAMPTZ DEFAULT NOW(),-- UNIQUE(agent_id, name)-);---- Table to track which user is subscribed to which tier-CREATE TABLE user_subscriptions (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID REFERENCES auth.users(id) NOT NULL,- tier_id UUID REFERENCES agent_subscription_tiers(id) NOT NULL,- status TEXT NOT NULL CHECK (status IN ('active', 'canceled', 'past_due')),- current_period_start TIMESTAMPTZ NOT NULL,- current_period_end TIMESTAMPTZ NOT NULL,- cancel_at_period_end BOOLEAN DEFAULT FALSE,- created_at TIMESTAMPTZ DEFAULT NOW(),- updated_at TIMESTAMPTZ DEFAULT NOW()-);---- Add indexes for performance-CREATE INDEX idx_user_subscriptions_user_id ON user_subscriptions(user_id);-CREATE INDEX idx_user_subscriptions_tier_id ON user_subscriptions(tier_id);---- RLS Policies-ALTER TABLE agent_subscription_tiers ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Creators can manage their own subscription tiers"-ON agent_subscription_tiers FOR ALL-USING (auth.uid() = (SELECT creator_id FROM agents WHERE id = agent_id));--ALTER TABLE user_subscriptions ENABLE ROW LEVEL SECURITY;-CREATE POLICY "Users can view their own subscriptions"-ON user_subscriptions FOR SELECT-USING (auth.uid() = user_id);-```diff --git a/docs/monetization/13-subscription-tiers-db-schema.md b/docs/monetization/13-subscription-tiers-db-schema.mddeleted file mode 100644index 70395d835..000000000--- a/docs/monetization/13-subscription-tiers-db-schema.md+++ /dev/null@@ -1,83 +0,0 @@-----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/13_platform_fee_integration.md b/docs/monetization/13_platform_fee_integration.mddeleted file mode 100644index 8c1d02ee0..000000000--- a/docs/monetization/13_platform_fee_integration.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 13: Platform Fee Integration--## Objective-Modify the skill purchase transaction to include a platform fee that is sent to the company's treasury wallet.--## Explanation-To create a sustainable business model, the platform will take a small percentage of each skill sale. This needs to be handled on-chain and transparently. The backend will now construct a transaction with two transfers instead of one: one for the creator's payout and one for the platform fee.--## Instructions-1. **Update Configuration:**- * Store the platform's treasury wallet address and the fee percentage in a secure configuration file or environment variables (e.g., `PLATFORM_FEE_BPS=500` for 5%, `PLATFORM_TREASURY_WALLET="...address..."`).--2. **Modify the Purchase Preparation API:**- * Locate the `POST /api/skills/purchase-prep` endpoint.- * Inside the transaction construction logic, calculate the platform fee from the total skill price. For example, if the fee is 5% (500 basis points), `fee_amount = total_price * 500 / 10000`.- * The creator's payout is now `creator_amount = total_price - fee_amount`.- * **Add a second `spl-token` transfer instruction** to the transaction.- * The first instruction transfers `creator_amount` to the creator's wallet.- * The second instruction transfers `fee_amount` to the platform's treasury wallet.- * The user still signs a single transaction, but it now atomically handles both the payout and the platform fee.--3. **Update Purchase Confirmation:**- * The `POST /api/skills/purchase-confirm` endpoint should be updated to verify this new transaction structure. It now needs to look for *two* `spl-token` transfers and validate that both the creator payout and the platform fee were sent correctly.--## Code Example (Inside `purchase-prep` API)--```javascript-// ... after fetching price and wallets-const PLATFORM_FEE_BPS = 500; // 5%-const PLATFORM_TREASURY_WALLET = new PublicKey("...");-const totalAmount = skillPrice.amount;--const feeAmount = Math.floor(totalAmount * PLATFORM_FEE_BPS / 10000);-const creatorAmount = totalAmount - feeAmount;--// ...-const tx = new Transaction({ /* ... */ });--// Instruction for Creator Payout-tx.add(- createTransferInstruction(- buyerAta.address,- creatorAta.address,- buyerPublicKey,- creatorAmount- )-);--// Instruction for Platform Fee-const platformTreasuryAta = await getOrCreateAssociatedTokenAccount(- connection,- buyerPublicKey,- usdcMint,- PLATFORM_TREASURY_WALLET-);-tx.add(- createTransferInstruction(- buyerAta.address,- platformTreasuryAta.address,- buyerPublicKey,- feeAmount- )-);--// ... serialize and return the transaction with two instructions-```diff --git a/docs/monetization/14-grant-skill-access.md b/docs/monetization/14-grant-skill-access.mddeleted file mode 100644index ff3f6560e..000000000--- a/docs/monetization/14-grant-skill-access.md+++ /dev/null@@ -1,70 +0,0 @@-# Prompt 14: Grant Skill Access After Payment--## Objective-Integrate the logic for creating a `skill_access_grants` record into the payment confirmation flow.--## Explanation-This prompt links the successful payment confirmation (Prompt 12) with the access grant system (Prompt 13). Once the backend has verified a user's payment on-chain, it must immediately create the corresponding access grant in the database.--## Instructions-1. **File to Edit:**- * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.--2. **Integrate Grant Creation:**- * Locate the spot in your code immediately after the payment status has been successfully updated to `completed`.- * Before sending the final success response to the client, add a call to your database logic to insert a new row into the `skill_access_grants` table.--3. **Determine Grant Rules:**- * You need to decide what kind of access this payment provides. For a simple one-time payment model, you could grant access for a fixed duration.- * **Example Rule:** Grant access for 24 hours from the time of purchase.- * To implement this, calculate the expiry timestamp.--4. **Populate the Grant Record:**- * The new `skill_access_grants` row should be populated with:- * `user_id`: From the authenticated user session.- * `agent_id`, `skill_name`: From the `paymentIntent` record you fetched from the database.- * `payment_id`: The ID of the now-completed payment.- * `expires_at`: The calculated expiry timestamp (e.g., `Date.now() + 24 * 60 * 60 * 1000`).- * `uses_left`: `NULL` for this time-based model.--5. **Transactional Integrity:**- * Ideally, the database operations for updating the payment status and creating the access grant should be wrapped in a database transaction. This ensures that either both operations succeed or both fail, preventing a state where a user pays but doesn't get access.--## Code Example (Backend - `confirm-skill-payment` logic)--This refines the example from Prompt 12.--```javascript-// Inside your /api/payments/confirm-skill-payment endpoint handler--// ... after successfully verifying the on-chain transaction ...--try {- // Use a database transaction to ensure atomicity- await db.transaction(async (trx) => {- // c. Update Payment Status- await trx.update('skill_payments', { status: 'completed', signature: signature })- .where({ id: paymentId });-- // d. Grant Skill Access- const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours from now-- await trx.insert({- user_id: user.id,- agent_id: paymentIntent.agentId,- skill_name: paymentIntent.skillName,- payment_id: paymentId,- expires_at: expiresAt,- uses_left: null, // This is a time-based grant- }).into('skill_access_grants');- });-- // e. Respond for frontend to continue- res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });--} catch (error) {- console.error('Error in confirmation transaction:', error);- // The database transaction should automatically roll back on error- res.status(500).json({ error: 'Failed to finalize payment.' });-}-```diff --git a/docs/monetization/14-payout-management-ui.md b/docs/monetization/14-payout-management-ui.mddeleted file mode 100644index 624872896..000000000--- a/docs/monetization/14-payout-management-ui.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 14: Payout Management UI--## Objective-Add a "Settings" section to the creator dashboard where creators can manage their payout wallet address and view a history of past payouts.--## Explanation-Providing financial controls is crucial for creator trust and usability. This UI will allow creators to easily update where their funds are sent and to track when they have been paid.--## Instructions-1. **Create Settings UI:**- * In `dashboard.html`, create the structure for the "Settings" tab.- * Add an input field, pre-filled with the creator's current payout wallet address.- * Include a "Save" button next to the input field.- * Add a section for "Payout History" with a placeholder for a table. The table should have columns for `Date`, `Amount`, and `Transaction Signature`.--2. **Implement Update Logic:**- * In `dashboard.js`, add an event listener to the "Save" button.- * When clicked, it should take the value from the input field, validate it as a Solana public key, and send it to the backend agent update endpoint (`/api/agents/:id`, similar to Prompt 10).- * Provide feedback (e.g., "Saved successfully" or "Invalid address") to the user.--3. **Fetch and Display Payout History (Future Prompt):**- * This prompt focuses on the UI. A future prompt will cover creating the backend logic and a `payouts` table to store and serve the data for the "Payout History" section. For now, the table can remain empty or contain placeholder data.--## Code Example (HTML - `dashboard.html` Settings Tab)-```html-<div id="settings-tab" class="tab-content hidden">- <h2>Settings</h2>- <div class="setting-item">- <h3>Payout Wallet</h3>- <p>This is the Solana wallet where your earnings will be sent.</p>- <input type="text" id="payout-wallet-input" value="CURRENT_WALLET_ADDRESS_FROM_API">- <button id="save-payout-wallet">Save</button>- </div>- <div class="setting-item">- <h3>Payout History</h3>- <table id="payout-history-table">- <thead>- <tr>- <th>Date</th>- <th>Amount</th>- <th>Transaction</th>- </tr>- </thead>- <tbody>- <!-- Payout rows will be populated here -->- <tr>- <td>2026-05-01</td>- <td>15.50 USDC</td>- <td><a href="#">view on explorer</a></td>- </tr>- </tbody>- </table>- </div>-</div>-```diff --git a/docs/monetization/14-platform-fee.md b/docs/monetization/14-platform-fee.mddeleted file mode 100644index 0dd0d9ecb..000000000--- a/docs/monetization/14-platform-fee.md+++ /dev/null@@ -1,78 +0,0 @@-# Prompt 14: Platform Fee (Backend)--## Objective-Implement a platform fee on every skill purchase transaction, splitting the payment between the skill creator and the platform's treasury wallet.--## Explanation-Platform fees are a standard monetization strategy. This task involves modifying the transaction creation logic to calculate a fee (e.g., 5%) and adding a second transfer instruction to the transaction. This ensures that a portion of every sale is automatically sent to the platform.--## Instructions-1. **Define Platform Wallet and Fee Rate:**- * In your backend configuration (e.g., environment variables), define your platform's Solana wallet address (`PLATFORM_WALLET_ADDRESS`) and the fee percentage (`PLATFORM_FEE_BPS`, in basis points, e.g., 500 for 5%).--2. **Update the Payment Endpoint (`api/payments/prepare-skill-purchase.js`):**- * Inside the handler, after fetching the skill price:- * Calculate the platform fee from the total amount. Be careful with integer division and rounding; it's best to work with `BigInt` for token amounts to avoid precision errors.- * Calculate the amount the creator will receive (total amount - platform fee).- * Create two `createTransferInstruction` calls:- 1. One instruction to transfer the creator's portion to their payout wallet.- 2. A second instruction to transfer the platform fee to the platform's wallet.- * Add both transfer instructions to the same `Transaction` object.--3. **Atomicity:**- * Because both transfers are part of the same transaction, the operation is atomic. If any part of it fails, the entire transaction (both the payment to the creator and the fee to the platform) will fail, ensuring consistency.--## Code Example (Backend - `api/payments/prepare-skill-purchase.js`)--```javascript-// ... (imports)--const PLATFORM_WALLET = new PublicKey(process.env.PLATFORM_WALLET_ADDRESS);-// Fee in basis points (100 bps = 1%)-const PLATFORM_FEE_BPS = BigInt(process.env.PLATFORM_FEE_BPS || 500);--export default async function handler(req, res) {- // ... (handler setup)- try {- // ... (get buyer, creator wallet, price info)-- const transaction = new Transaction({ /* ... */ });- const buyerUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, buyerPublicKey);- const creatorUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, creatorPublicKey);- const platformUsdcAddress = await getAssociatedTokenAddress(USDC_MINT, PLATFORM_WALLET);-- const totalAmount = BigInt(priceInfo.amount);-- // Calculate fees using BigInt for precision- const platformFee = (totalAmount * PLATFORM_FEE_BPS) / 10000n;- const creatorAmount = totalAmount - platformFee;-- // Instruction 1: Transfer to creator- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- creatorUsdcAddress,- buyerPublicKey,- creatorAmount // Use BigInt amount- )- );-- // Instruction 2: Transfer platform fee- if (platformFee > 0) {- transaction.add(- createTransferInstruction(- buyerUsdcAddress,- platformUsdcAddress,- buyerPublicKey,- platformFee // Use BigInt amount- )- );- }-- // ... (serialize and return transaction)-- } catch (error) {- // ... (error handling)- }-}-```diff --git a/docs/monetization/14-subscription-tiers-ui-creator.md b/docs/monetization/14-subscription-tiers-ui-creator.mddeleted file mode 100644index 689a952cb..000000000--- a/docs/monetization/14-subscription-tiers-ui-creator.md+++ /dev/null@@ -1,127 +0,0 @@-----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/14-ui-for-subscription-tiers.md b/docs/monetization/14-ui-for-subscription-tiers.mddeleted file mode 100644index dd4a2a3e0..000000000--- a/docs/monetization/14-ui-for-subscription-tiers.md+++ /dev/null@@ -1,90 +0,0 @@-# Prompt 14: UI for Subscription Tiers--## Objective-Implement the UI in the creator's dashboard that allows them to create, view, and manage subscription tiers for their agents.--## Explanation-Building on the subscription database schema, we now need a user interface for creators. This UI will live in the "Monetization" tab and will provide a form to define a new subscription tier (name, price, included skills) and a list to display existing tiers.--## Instructions-1. **Add UI Structure:**- * In `agent-edit.html`, within the "Monetization" tab panel, add a new section for "Subscription Tiers".- * This section should contain a button "Create New Tier" which reveals a form.- * Also, include a container to list the existing tiers, e.g., `#subscription-tiers-list`.--2. **Create Tier Form:**- * The form should have inputs for tier `name`, `description`, `price`, `currency`, and `billing interval` (monthly/yearly).- * A crucial part will be a multi-select box or a list of checkboxes for the creator to choose which of the agent's skills are included in this tier.--3. **Frontend Logic:**- * In `src/agent-edit.js`, write a function to fetch the agent's skills and existing subscription tiers.- * Populate the skills multi-select in the form.- * Render the list of existing tiers with an "Edit" or "Deactivate" button for each.- * Handle the form submission to collect the data for a new tier, which will be sent to the backend (to be created in the next prompt).--## HTML Example (`agent-edit.html`)--```html-<!-- Inside the 'monetization' tab-content -->-<div class="card">- <h3>Subscription Tiers</h3>- <div id="subscription-tiers-list">- <!-- Existing tiers will be rendered here -->- </div>- <button id="show-create-tier-form-btn">Create New Tier</button>- <div id="create-tier-form-container" style="display:none;">- <h4>New Subscription Tier</h4>- <div class="form-field">- <label for="tier-name">Tier Name</label>- <input type="text" id="tier-name" placeholder="e.g., Pro">- </div>- <div class="form-field">- <label for="tier-price">Price</label>- <input type="number" id="tier-price" placeholder="9.99">- <select id="tier-currency">- <option value="EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d">USDC</option>- </select>- <select id="tier-interval">- <option value="month">per month</option>- <option value="year">per year</option>- </select>- </div>- <div class="form-field">- <label>Included Skills</label>- <div id="tier-skills-checklist">- <!-- Checkboxes for skills will be rendered here -->- </div>- </div>- <button id="save-tier-btn">Save Tier</button>- <button id="cancel-create-tier-btn" type="button">Cancel</button>- </div>-</div>-```--## JavaScript Example (`src/agent-edit.js`)--```javascript-const showCreateTierBtn = document.getElementById('show-create-tier-form-btn');-const createTierContainer = document.getElementById('create-tier-form-container');-const saveTierBtn = document.getElementById('save-tier-btn');--showCreateTierBtn.addEventListener('click', () => {- createTierContainer.style.display = 'block';- showCreateTierBtn.style.display = 'none';- populateSkillsForTierForm(); // a function that fetches and renders skills as checkboxes-});--saveTierBtn.addEventListener('click', async () => {- const tierData = {- name: document.getElementById('tier-name').value,- price_amount: Math.round(parseFloat(document.getElementById('tier-price').value) * 1e6),- price_currency_mint: document.getElementById('tier-currency').value,- billing_interval: document.getElementById('tier-interval').value,- included_skills: Array.from(document.querySelectorAll('#tier-skills-checklist input:checked')).map(cb => cb.value)- };-- const agentId = /* get agent id from context */;- // Backend call will be implemented next- await createSubscriptionTier(agentId, tierData);-});-```diff --git a/docs/monetization/14-ui-transaction-status.md b/docs/monetization/14-ui-transaction-status.mddeleted file mode 100644index 811f6a914..000000000--- a/docs/monetization/14-ui-transaction-status.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 14: UI for Transaction Status--## Objective-Provide real-time feedback to the user about the status of their purchase transaction.--## Explanation-Blockchain transactions are not instant. To provide a good user experience, the UI should show the user that their transaction is being processed and notify them when it's complete.--## Instructions-1. **Update the Payment Modal:**- * After a transaction is sent, update the payment modal to show a "Processing..." state.- * Disable the purchase button to prevent multiple submissions.--2. **Display Confirmation:**- * Once the transaction is confirmed, show a success message in the modal.- * Include a link to the transaction on a block explorer like Solscan.--3. **Handle Errors:**- * If the transaction fails, display a clear error message and allow the user to try again.diff --git a/docs/monetization/14_graceful_tx_failures.md b/docs/monetization/14_graceful_tx_failures.mddeleted file mode 100644index 49b8e8dc0..000000000--- a/docs/monetization/14_graceful_tx_failures.md+++ /dev/null@@ -1,60 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 14: Handling Transaction Failures Gracefully--## Objective-Improve the frontend purchase flow to provide clear feedback to the user when a transaction fails for any reason.--## Explanation-On-chain transactions can fail for many reasons: insufficient funds, user rejection, network congestion, or a dropped connection. Our UI must handle these scenarios gracefully instead of leaving the user in a stuck or confusing state.--## Instructions-1. **Review the Purchase Flow:**- * In `src/marketplace.js`, locate the `handlePurchase` function.- * It should already have a `try...catch` block. We will make the error handling more specific and user-friendly.--2. **Implement Granular Error Handling:**- * **User Rejection:** The `wallet.signTransaction` call will throw a specific error if the user clicks "Reject" in their wallet. Catch this error and display a message like "Purchase cancelled."- * **Insufficient Funds:** While hard to detect pre-emptively without extra calls, RPC errors from `sendRawTransaction` often contain clues. If an error occurs during sending or confirmation, provide a generic but helpful message: "Transaction failed. This could be due to insufficient SOL for gas fees or network issues. Please check your wallet and try again."- * **Timeout:** The `connection.confirmTransaction` can time out. Handle this by informing the user: "Transaction confirmation timed out. It may still succeed. Please check your wallet history or a block explorer."- * **Backend Errors:** Any failure from our own `prep` or `confirm` APIs should be caught and displayed cleanly.--3. **Update UI State:**- * Ensure that no matter what error occurs, the "Purchase" button is re-enabled and reset to its original state (e.g., "Purchase for X USDC"), allowing the user to retry.- * Display the error message in a small, non-intrusive element near the button or as a temporary notification toast.--## Code Example (`src/marketplace.js` - enhanced `catch` block)--```javascript-// ... inside handlePurchase function-} catch (err) {- console.error('Purchase failed:', err);-- let userMessage = 'An unknown error occurred. Please try again.';-- // Check for specific wallet error codes for user rejection- if (err.name === 'WalletSignTransactionError' || err.code === 4001) {- userMessage = 'Purchase cancelled in wallet.';- } else if (err.message.includes('failed to send')) {- userMessage = 'Broadcast failed. Check your connection and wallet balance.';- } else if (err.message.includes('Timed out')) {- userMessage = 'Confirmation timed out. Please check a block explorer for status.';- } else if (err.message.includes('Failed to prepare') || err.message.includes('Failed to confirm')) {- userMessage = 'A server error occurred. Please try again later.';- }-- // Display the message to the user (e.g., in a status element)- const statusEl = document.getElementById('purchase-status-indicator'); // Assume this exists- if (statusEl) {- statusEl.textContent = userMessage;- statusEl.style.color = 'var(--err)';- }-- // Reset the button- button.disabled = false;- // You might need to retrieve the price again to format this text correctly- button.textContent = 'Retry Purchase';-}-```diff --git a/docs/monetization/15-backend-check-active-grant.md b/docs/monetization/15-backend-check-active-grant.mddeleted file mode 100644index 26e94ad66..000000000--- a/docs/monetization/15-backend-check-active-grant.md+++ /dev/null@@ -1,68 +0,0 @@-# Prompt 15: Backend Logic to Check for Active Grant--## Objective-Flesh out the database query and logic for checking if a user has a valid, active grant for a specific skill before execution.--## Explanation-This prompt focuses on completing the check designed in Prompt 8. With the `skill_access_grants` table now defined, we can write the precise database query that powers the access check. This logic is the gatekeeper for all paid skills.--## Instructions-1. **File to Edit:**- * Open your backend chat orchestrator (e.g., `/api/chat.js`) where the initial paid skill detection happens.--2. **Create a Database Query Function:**- * In your database access layer, create a function like `checkForValidSkillGrant({ userId, agentId, skillName })`.--3. **Implement the Query Logic:**- * This function needs to query the `skill_access_grants` table.- * The `WHERE` clause is the most important part. It should find a row where:- * `user_id`, `agent_id`, and `skill_name` all match the function's arguments.- * **AND** the grant is not expired. This requires a sub-clause: `(expires_at IS NULL OR expires_at > NOW())`.- * **AND** the grant has uses remaining: `(uses_left IS NULL OR uses_left > 0)`.- * You only need to know if *any* such grant exists, so you can optimize the query to return just one row or a simple count (`SELECT 1` or `SELECT COUNT(*)`). The function should return `true` if a valid grant is found, and `false` otherwise.--4. **Decrement `uses_left` (for pay-per-use skills):**- * If a grant is found that relies on `uses_left` (i.e., `expires_at` is `NULL`), you must decrement the `uses_left` count in the database as part of this check.- * This should be an atomic `UPDATE` operation: `UPDATE skill_access_grants SET uses_left = uses_left - 1 WHERE id = ...`.- * This decrement should happen within a transaction to avoid race conditions.--## Code Example (Backend - Database Access Layer)--```javascript-// Example using a SQL query builder like Knex.js--async function checkForValidSkillGrant({ userId, agentId, skillName }) {- // Find a grant that is either time-based and not expired, or use-based and has uses left.- const grants = await db('skill_access_grants')- .where({- user_id: userId,- agent_id: agentId,- skill_name: skillName,- })- .where(builder => {- builder.where(q => {- q.whereNotNull('expires_at').andWhere('expires_at', '>', db.fn.now());- }).orWhere(q => {- q.whereNotNull('uses_left').andWhere('uses_left', '>', 0);- })- })- .select('id', 'uses_left')- .limit(1);-- if (grants.length === 0) {- return false; // No valid grant found- }-- const grant = grants[0];-- // If this was a use-based grant, decrement the count.- if (grant.uses_left !== null && grant.uses_left > 0) {- await db('skill_access_grants')- .where({ id: grant.id })- .decrement('uses_left', 1);- }-- return true; // Grant is valid-}-```-This function would then be called from your chat handler as shown in Prompt 8.diff --git a/docs/monetization/15-caching-skill-prices.md b/docs/monetization/15-caching-skill-prices.mddeleted file mode 100644index 2beeb04b8..000000000--- a/docs/monetization/15-caching-skill-prices.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 15: Caching Skill Prices--## Objective-Implement a caching layer to reduce database load and improve the performance of fetching skill prices.--## Explanation-Skill prices are unlikely to change frequently. Caching this data will improve the responsiveness of the marketplace and reduce the number of queries to the database.--## Instructions-1. **Choose a Caching Strategy:**- * Decide on a caching solution, such as Redis or an in-memory cache.--2. **Implement Caching Logic:**- * When fetching agent details, first check the cache for the skill prices.- * If the prices are in the cache, return them directly.- * If not, fetch them from the database and store them in the cache with an expiration time (e.g., 1 hour).--3. **Cache Invalidation:**- * When a creator updates their skill prices, invalidate the corresponding cache entry to ensure the new prices are displayed.diff --git a/docs/monetization/15-save-subscription-tiers-api.md b/docs/monetization/15-save-subscription-tiers-api.mddeleted file mode 100644index b97dfa138..000000000--- a/docs/monetization/15-save-subscription-tiers-api.md+++ /dev/null@@ -1,94 +0,0 @@-----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/15-skill-pricing-management.md b/docs/monetization/15-skill-pricing-management.mddeleted file mode 100644index 9f663cf9c..000000000--- a/docs/monetization/15-skill-pricing-management.md+++ /dev/null@@ -1,45 +0,0 @@-# Prompt 15: Skill Pricing Management--## Objective-Create a UI in the creator dashboard that allows creators to set and update prices for their agent's skills.--## Explanation-Pricing needs to be dynamic. This feature empowers creators to manage their own economy by letting them add, change, and remove prices for their skills without needing to edit code or contact support.--## Instructions-1. **Create Pricing UI:**- * In the "My Agents" tab of the dashboard, for each agent listed, add a "Manage Skills" button.- * Clicking this button should open a modal or a new page dedicated to that agent's skills.- * In this view, list all of the agent's available skills.- * Next to each skill, provide an input field for the price and a dropdown for the currency (e.g., USDC).- * Include a "Save Prices" button.--2. **Backend API for Pricing:**- * Create a new backend endpoint, e.g., `/api/agents/:id/skill-prices`.- * This endpoint should accept a `PUT` or `POST` request with a body containing an object of skill prices, like `{ "skill_one": { "amount": 1000000, "currency": "USDC" }, "skill_two": ... }`.- * The endpoint should be secure, ensuring only the agent's owner can update its prices.--3. **Database for Prices:**- * Create a new table, `agent_skill_prices`, with columns like `id`, `agent_id`, `skill_name`, `amount`, and `currency_mint`.- * The backend endpoint will `INSERT` or `UPDATE` rows in this table based on the incoming data.--4. **Connect UI to API:**- * When the creator clicks "Save Prices," the frontend should gather the data from all the input fields and send it to the new backend endpoint.- * The page that displays prices to customers (`marketplace.html`) will need to be updated to fetch from this new table instead of a hardcoded source. This links back to Prompt 1.--## Code Example (UI Concept)-```html-<!-- Inside the "Manage Skills" modal -->-<h3>Manage Prices for Agent 'X'</h3>-<div class="skill-price-editor">- <label>dance</label>- <input type="number" value="1.00">- <span>USDC</span>-</div>-<div class="skill-price-editor">- <label>tell_joke</label>- <input type="number" placeholder="Not for sale">- <span>USDC</span>-</div>-<button id="save-prices-btn">Save Prices</button>-```diff --git a/docs/monetization/15-transaction-history.md b/docs/monetization/15-transaction-history.mddeleted file mode 100644index fb1b21570..000000000--- a/docs/monetization/15-transaction-history.md+++ /dev/null@@ -1,72 +0,0 @@-# Prompt 15: Transaction History--## Objective-Create a transaction history page or dashboard section for both users (buyers) and creators (sellers) to view past transactions.--## Explanation-Transparency is key for any platform dealing with payments. Users should be able to see a clear record of their purchases, and creators should be able to track their sales. This task involves creating a new database table to log transactions and building the UI and API to display this history.--## Instructions-1. **Database Schema:**- * Create a `transactions` table to log every purchase.- * Columns should include: `id`, `buyer_user_id`, `creator_user_id`, `agent_id`, `skill_name`, `amount`, `platform_fee`, `currency_mint`, `signature`, and `created_at`.--2. **Log Transactions (Backend):**- * In your payment confirmation logic (`api/payments/prepare-skill-purchase.js` `GET` handler), after verifying the transaction and granting skill access, insert a new record into this `transactions` table.--3. **Create API Endpoint(s) (Backend):**- * Create an endpoint `/api/users/me/transaction-history` that returns transactions where the user is either the `buyer_user_id` or the `creator_user_id`.- * You could add a query parameter `?role=buyer` or `?role=seller` to filter the results.--4. **Build the UI (Frontend):**- * In the user's dashboard, create a new "Transaction History" tab or section.- * Fetch data from the new endpoint.- * Display the transactions in a table or list format.- * The view should clearly distinguish between sales and purchases. For each transaction, show details like date, item, amount, role (Buyer/Seller), and a link to the transaction on a block explorer like Solscan.--## Code Example (Backend - Logging the transaction)--```javascript-// Inside the payment confirmation (GET handler) after successful verification--// ...-await grantSkillToUser(purchaseDetails.userId, purchaseDetails.skillName);--// Now, log the transaction-await logTransaction({- buyerUserId: purchaseDetails.userId,- creatorUserId: purchaseDetails.creatorId, // You need to fetch/store this- agentId: purchaseDetails.agentId,- skillName: purchaseDetails.skillName,- amount: purchaseDetails.amount,- platformFee: calculatedPlatformFee,- currencyMint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d',- signature: req.query.signature-});--res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });-```--## UI Table Example (`dashboard.html`)--```html-<section>- <h2>Transaction History</h2>- <div class="table-wrapper">- <table>- <thead>- <tr>- <th>Date</th>- <th>Type</th>- <th>Details</th>- <th>Amount</th>- <th>Tx</th>- </tr>- </thead>- <tbody id="transaction-history-body">- <!-- Rows will be injected here -->- </tbody>- </table>- </div>-</section>-```diff --git a/docs/monetization/15_gasless_transactions.md b/docs/monetization/15_gasless_transactions.mddeleted file mode 100644index d4db344f0..000000000--- a/docs/monetization/15_gasless_transactions.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 15: Gasless Transactions (Payer Sponsorship)--## Objective-Implement a "gasless" transaction system where the platform sponsors the Solana network fees for skill purchases, improving the user experience.--## Explanation-Users often don't have SOL in their wallets, even if they have USDC. Forcing them to acquire SOL just to pay for a minor gas fee is a major point of friction. We can sponsor these transactions. The user still signs the token transfer, but our backend pays the associated SOL fee. This is done using Solana's "Versioned Transactions" with a Payer.--## Instructions-1. **Platform Payer Keypair:**- * Create a dedicated Solana keypair for the platform, which will be used to pay for transaction fees.- * Store this keypair's secret key securely in the backend environment (e.g., in a secrets manager).- * This wallet must be funded with SOL.--2. **Modify Purchase Preparation API (`purchase-prep`):**- * Instead of creating a "Legacy" `Transaction`, you will now create a `VersionedTransaction`.- * The `feePayer` of the transaction will now be the **platform's payer public key**.- * The user's public key is still the one signing the token transfer instruction itself.- * After adding the transfer instructions, the transaction is **partially signed by the platform's payer keypair on the backend**.- * The serialized transaction sent to the frontend is now a partially signed `VersionedTransaction`.--3. **Modify Frontend Signing Logic:**- * The frontend will receive the partially signed, versioned transaction.- * The `wallet.signTransaction` method works the same way for the user; they are just signing a transaction where they are not the fee payer.- * The rest of the flow (send, confirm) remains largely the same.--## Code Example (Backend `purchase-prep` API)--```javascript-import {- Connection,- PublicKey,- TransactionMessage,- VersionedTransaction,- Keypair-} from '@solana/web3.js';-// ...--// Load your platform's payer keypair securely-const platformPayer = Keypair.fromSecretKey(Buffer.from(process.env.PAYER_SECRET_KEY, 'base64'));--// ... Inside the endpoint logic-export default wrap(async (req, res) => {- // ...- // The buyer is still the authority for the transfer, but not the fee payer- const buyerPublicKey = new PublicKey(user.wallet_address);-- const instructions = [- // ... createTransferInstruction for creator payout- // ... createTransferInstruction for platform fee- ];-- const { blockhash } = await connection.getLatestBlockhash();- const messageV0 = new TransactionMessage({- payerKey: platformPayer.publicKey, // PLATFORM pays the fee- recentBlockhash: blockhash,- instructions,- }).compileToV0Message();-- const tx = new VersionedTransaction(messageV0);-- // The user's wallet will provide the signature for the token transfer- // We sign it with our payer key to cover the fees- tx.sign([platformPayer]);-- const serializedTx = Buffer.from(tx.serialize()).toString('base64');-- return json(res, 200, { transaction: serializedTx });-});-```diff --git a/docs/monetization/16-integrate-skills-with-chat.md b/docs/monetization/16-integrate-skills-with-chat.mddeleted file mode 100644index fa039dbb4..000000000--- a/docs/monetization/16-integrate-skills-with-chat.md+++ /dev/null@@ -1,76 +0,0 @@-# Prompt 16: Integrate Owned Skills with Agent Chat--## Objective-Modify the agent chat backend to check if a user owns the required skill before allowing the execution of a premium agent capability.--## Explanation-Monetization is only effective if owning a skill actually unlocks functionality. This task connects the ownership record to the agent's core logic. When an agent is about to perform an action tied to a paid skill, it must first verify that the interacting user has purchased that skill.--## Instructions-1. **Map Agent Actions to Skills (Backend):**- * You need a way to associate specific agent behaviors with skill names. This could be done in your agent's configuration or a database table. For example, a `run_market_analysis` action might require the `MarketAnalysis` skill.--2. **Create a Skill Check Middleware/Function (Backend):**- * In your chat API (`api/chat.js` or similar), create a function `checkSkillOwnership(userId, agentId, requiredSkill)`.- * This function will query the `user_skill_ownership` table to see if a record exists for the given user, agent, and skill.- * It should return `true` or `false`.--3. **Enforce the Check (Backend):**- * In your main chat message handler, before executing a premium action:- * Identify the skill required for the action.- * Call your `checkSkillOwnership` function.- * If the check fails, do not execute the action. Instead, return a specific response to the frontend indicating the required skill is not owned.--## Code Example (Backend - Chat API)--```javascript-import { checkSkillOwnership } from '../_lib/db'; // Your new DB function-import { getSkillForAction } from '../_lib/agent-config'; // Function to map action to skill--export default async function handler(req, res) {- // ... (chat handler setup, get user message and user id)- const userId = req.user.id;- const { agentId, message } = req.body;-- // 1. Determine the agent's intended action based on the message- const action = determineAgentAction(message);-- // 2. Look up the skill required for this action- const requiredSkill = getSkillForAction(agentId, action);-- if (requiredSkill) {- // 3. This is a premium action, so check for ownership- const hasSkill = await checkSkillOwnership(userId, agentId, requiredSkill);-- if (!hasSkill) {- // 4. If user doesn't own it, send a specific response- return res.status(402).json({ // 402 Payment Required- type: 'skill_required',- message: `This action requires the "${requiredSkill}" skill. Please purchase it from the marketplace to continue.`,- skillName: requiredSkill,- });- }- }-- // If we reach here, the user either has the skill or the action is free.- // Proceed with executing the agent's action.- const agentResponse = await executeAgentAction(agentId, action, message);-- res.status(200).json({ response: agentResponse });-}-```--## Database Function (`_lib/db.js`)--```javascript-export async function checkSkillOwnership(userId, agentId, skillName) {- const { rowCount } = await db.query(- `- SELECT 1 FROM user_skill_ownership- WHERE user_id = $1 AND agent_id = $2 AND skill_name = $3;- `,- [userId, agentId, skillName]- );- return rowCount > 0;-}-```diff --git a/docs/monetization/16-skill-bundles-subscriptions.md b/docs/monetization/16-skill-bundles-subscriptions.mddeleted file mode 100644index 5c3708af1..000000000--- a/docs/monetization/16-skill-bundles-subscriptions.md+++ /dev/null@@ -1,24 +0,0 @@-----status: not-started------# Prompt 16: Skill Bundles & Subscriptions--## Objective-Introduce the ability for creators to sell bundles of skills or offer a monthly subscription for access to all their skills.--## Explanation-This is an advanced monetization feature that provides more value to users and more revenue opportunities for creators.--## Instructions-1. **Update Database Schema:**- * Add new tables to support skill bundles and subscriptions.- * A `skill_bundles` table would define which skills are in a bundle and the price.- * A `user_subscriptions` table would track active user subscriptions.--2. **Modify UI:**- * Update the creator UI to allow them to create and manage bundles/subscriptions.- * Update the marketplace UI to display these new purchasing options.--3. **Implement Recurring Payments:**- * For subscriptions, you will need a system to handle recurring payments. This is complex on a blockchain and might require a service like Streamflow or a custom smart contract.diff --git a/docs/monetization/16-subscription-model-database.md b/docs/monetization/16-subscription-model-database.mddeleted file mode 100644index c97913fbd..000000000--- a/docs/monetization/16-subscription-model-database.md+++ /dev/null@@ -1,59 +0,0 @@-# Prompt 16: Subscription Model Database Schema--## Objective-Update the database schema to support recurring subscriptions for agent access, allowing creators to offer monthly or yearly tiers.--## Explanation-Moving beyond individual skill sales, subscriptions offer a predictable revenue stream for creators and a better value proposition for users who want full access. This foundational step involves designing the necessary database tables to track subscription plans and user statuses.--## Instructions-1. **Design `subscription_tiers` Table:**- * Create a new table named `subscription_tiers`.- * This table will define the plans a creator can offer for an agent.- * Columns should include:- * `id`: Primary key.- * `agent_id`: Foreign key to the `agents` table.- * `name`: The name of the tier (e.g., "Pro," "All-Access").- * `price`: The cost of the subscription.- * `currency_mint`: The currency of the price.- * `interval`: The billing period (e.g., 'month', 'year').- * `description`: A brief description of the tier.--2. **Design `user_subscriptions` Table:**- * Create a new table named `user_subscriptions` to track which users are subscribed to which tiers.- * Columns should include:- * `id`: Primary key.- * `user_id`: Foreign key to the `users` table.- * `tier_id`: Foreign key to the `subscription_tiers` table.- * `start_date`: Timestamp when the subscription started.- * `end_date`: Timestamp when the subscription is due to expire.- * `status`: The current status (e.g., 'active', 'cancelled', 'past_due').- * `last_payment_signature`: The transaction signature of the last successful payment.--3. **Apply Migrations:**- * Create and run a new database migration script to apply these schema changes.--## SQL Schema Example-```sql-CREATE TABLE subscription_tiers (- id SERIAL PRIMARY KEY,- agent_id INTEGER REFERENCES agents(id) ON DELETE CASCADE,- name VARCHAR(255) NOT NULL,- price BIGINT NOT NULL, -- in smallest currency unit, e.g., lamports- currency_mint VARCHAR(255) NOT NULL,- interval VARCHAR(50) NOT NULL, -- 'month' or 'year'- description TEXT,- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP-);--CREATE TABLE user_subscriptions (- id SERIAL PRIMARY KEY,- user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,- tier_id INTEGER REFERENCES subscription_tiers(id) ON DELETE CASCADE,- start_date TIMESTAMP WITH TIME ZONE NOT NULL,- end_date TIMESTAMP WITH TIME ZONE NOT NULL,- status VARCHAR(50) NOT NULL,- last_payment_signature VARCHAR(255),- created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP-);-```diff --git a/docs/monetization/16-update-chat-ui-purchased.md b/docs/monetization/16-update-chat-ui-purchased.mddeleted file mode 100644index 55abe9c65..000000000--- a/docs/monetization/16-update-chat-ui-purchased.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 16: Update Chat UI for Purchased Skills--## Objective-Modify the chat UI to visually reflect when a user has purchased access to a premium skill, for example by changing an icon from a "lock" to an "unlock" state.--## Explanation-After a successful purchase, the user needs immediate visual feedback that their action was successful and the skill is now available. This improves user experience and reduces confusion.--## Instructions-1. **Modify the Chat UI Component:**- * Open your main chat component file (e.g., `chat/src/App.svelte`).- * The component needs to maintain a state of which skills the user has purchased access to for the current agent. This could be a `Set` or an `object`.- ```javascript- let purchasedSkills = new Set();- ```--2. **Update State After Purchase:**- * In your `handlePaymentFlow` function from Prompt 11, upon successful confirmation from the backend, add the `skill_name` to your `purchasedSkills` set.- ```javascript- // Inside handlePaymentFlow, after successful confirmation- purchasedSkills.add(paymentDetails.skill_name);- purchasedSkills = purchasedSkills; // Trigger Svelte reactivity- ```--3. **Initial State Loading:**- * When a chat session starts, you should ideally fetch the user's current access grants for the agent from the backend so that previously purchased skills are already shown as unlocked.- * Create a new, simple backend endpoint `GET /api/agents/:id/my-skill-grants` that returns a list of skill names for which the current user has active grants.- * Call this endpoint when the chat loads and populate the `purchasedSkills` set.--4. **Dynamically Render Skill UI:**- * Locate the part of your UI that displays available skills (perhaps in a sidebar or as suggestion chips).- * When rendering each skill, check if its name is in the `purchasedSkills` set.- * Use this check to conditionally apply a class or show a different icon.--## Code Example (Frontend - Svelte Component)--```svelte-<!-- Example of rendering a list of skills in the chat UI -->-<div class="skill-list">- <h4>Available Skills</h4>- {#each agent.skills as skill}- {@const isLocked = skill.is_premium && !purchasedSkills.has(skill.name)}- <div class="skill-chip" class:locked={isLocked}>- {skill.name}- {#if isLocked}- <span>🔒</span>- {:else if skill.is_premium}- <span>✔️</span>- {/if}- </div>- {/each}-</div>--<script>- // ... existing script ...- export let agent;- let purchasedSkills = new Set();-- // Fetch initial grants on component mount- import { onMount } from 'svelte';- onMount(async () => {- const res = await fetch(`/api/agents/${agent.id}/my-skill-grants`);- if (res.ok) {- const { granted_skills } = await res.json();- purchasedSkills = new Set(granted_skills);- }- });-- // This function is called after a successful payment flow- function onSkillPurchased(skillName) {- purchasedSkills.add(skillName);- purchasedSkills = purchasedSkills; // This forces Svelte to update the UI- }-</script>--<style>- .skill-chip.locked {- opacity: 0.6;- cursor: not-allowed;- background-color: #333;- }- .skill-chip span {- margin-left: 8px;- }-</style>-```diff --git a/docs/monetization/16-user-facing-subscription-ui.md b/docs/monetization/16-user-facing-subscription-ui.mddeleted file mode 100644index b8a583fb8..000000000--- a/docs/monetization/16-user-facing-subscription-ui.md+++ /dev/null@@ -1,128 +0,0 @@-----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/16-user-subscription-flow.md b/docs/monetization/16-user-subscription-flow.mddeleted file mode 100644index 1a6a36a74..000000000--- a/docs/monetization/16-user-subscription-flow.md+++ /dev/null@@ -1,82 +0,0 @@-# Prompt 16: User Subscription Flow--## Objective-Implement the frontend and backend logic for users to subscribe to an agent's subscription tier.--## Explanation-This task combines previous concepts (wallet connection, transaction creation, verification) into a subscription context. The user will select a subscription tier, approve a transaction for the first payment, and the backend will create a record in the `user_subscriptions` table to mark the subscription as active. This prompt will not cover recurring payments, but will set up the initial subscription.--## Instructions-1. **Update Marketplace UI:**- * In `src/marketplace.js`, when rendering the agent detail page, fetch and display the available subscription tiers.- * Each tier should have a "Subscribe" button.--2. **Subscription Confirmation Modal:**- * Clicking "Subscribe" should open a confirmation modal, similar to the one-time purchase, showing the tier name, price, and billing cycle.--3. **Backend Subscription Endpoint:**- * Create an endpoint `/api/subscriptions/subscribe`.- * It takes `tierId` and the user's public key.- * It constructs and returns a transaction for the first payment, just like the one-time purchase.--4. **Frontend Transaction Handling:**- * The frontend gets the transaction, has the user sign and send it.--5. **Backend Verification and Activation Endpoint:**- * Create an endpoint `/api/subscriptions/verify`.- * It takes a `transactionSignature` and `tierId`.- * It verifies the transaction on-chain.- * If valid, it creates a new record in the `user_subscriptions` table with a status of 'active'. It calculates `current_period_start` (now) and `current_period_end` (e.g., now + 1 month).--## Code Example (`api/subscriptions/verify.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';-import { getAuthUser } from '../../_lib/auth';--export default async function handler(req, res) {- const { transactionSignature, tierId } = req.body;- const user = await getAuthUser(req);-- if (!user) return error(res, 401, 'Unauthorized');-- // 1. Verify transaction on-chain (similar to prompt #6)- const isTxValid = await verifySubscriptionPayment(transactionSignature, tierId, user.id);- if (!isTxValid) {- return error(res, 400, 'Invalid transaction.');- }-- // 2. Get tier details to calculate the period end- const { data: tier } = await supabase.from('agent_subscription_tiers').select('billing_interval').eq('id', tierId).single();- if (!tier) {- return error(res, 404, 'Subscription tier not found.');- }-- // 3. Create the subscription record- const startDate = new Date();- const endDate = new Date(startDate);- if (tier.billing_interval === 'month') {- endDate.setMonth(startDate.getMonth() + 1);- } else if (tier.billing_interval === 'year') {- endDate.setFullYear(startDate.getFullYear() + 1);- }-- const { error: insertError } = await supabase- .from('user_subscriptions')- .insert({- user_id: user.id,- tier_id: tierId,- status: 'active',- current_period_start: startDate.toISOString(),- current_period_end: endDate.toISOString(),- // `transaction_signature` might be stored on a related `payments` table- });-- if (insertError) {- return error(res, 500, 'Failed to activate subscription.');- }-- return json(res, { success: true, message: 'Subscription activated!' });-}-```diff --git a/docs/monetization/16_refactor_service_class.md b/docs/monetization/16_refactor_service_class.mddeleted file mode 100644index a96458ccf..000000000--- a/docs/monetization/16_refactor_service_class.md+++ /dev/null@@ -1,91 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 16: Refactor Monetization Logic into a Service Class--## Objective-To improve code organization and reusability, refactor the scattered monetization logic (database queries, transaction building) into a dedicated `MonetizationService` class.--## Explanation-As the monetization feature grows, the logic becomes more complex. Keeping it directly inside API handlers makes it hard to maintain, test, and reuse. A service class will encapsulate all the business logic related to skill pricing, purchases, and payouts, providing a clean interface for the API layer.--## Instructions-1. **Create a New Service File:**- * Create a file at `api/_lib/services/MonetizationService.js`.--2. **Design the `MonetizationService` Class:**- * The constructor can take a database connection object (`sql`) and the current user's session as arguments.- * Create methods that map to the core operations we've built:- * `getSkillPricesForAgent(agentId)`- * `setSkillPrices(agentId, prices)`- * `preparePurchaseTransaction(agentId, skillName)`- * `confirmPurchase(agentId, skillName, signature)`- * `checkSkillOwnership(agentId, skillName)`- * `getCreatorSalesData()`--3. **Migrate Logic into the Service:**- * Move the database queries and transaction-building logic from the API handlers (`api/marketplace/[action].js`, `api/skills/purchase-prep.js`, etc.) into the corresponding methods of the new service class.- * The API handlers should become much thinner; their primary role will be handling HTTP requests/responses, validating input, and calling the service methods.--4. **Refactor API Handlers:**- * Update all relevant API handlers to instantiate and use the `MonetizationService`.--## Code Example (`MonetizationService.js`)--```javascript-import { sql } from '../db.js';-import { Connection, ... } from '@solana/web3.js';-// ... other imports--export class MonetizationService {- constructor(user) {- this.user = user;- }-- async setSkillPrices(agentId, prices) {- if (!this.user) throw new Error('Authentication required.');-- // Verify ownership- const [agent] = await sql`...`;- if (!agent) throw new Error('Agent not found or permission denied.');-- // Perform the database upsert logic here...- }-- async preparePurchaseTransaction(agentId, skillName) {- if (!this.user) throw new Error('Authentication required.');-- // All the logic for fetching prices, wallets, and building- // the VersionedTransaction goes here...- // Returns the serialized transaction.- }-- // ... other methods-}-```--## Code Example (Refactored API Handler)--```javascript-// api/skills/purchase-prep.js-import { MonetizationService } from '../../_lib/services/MonetizationService.js';-// ...--export default wrap(async (req, res) => {- const user = await getSessionUser(req);- // ... input validation-- try {- const monetizationService = new MonetizationService(user);- const { transaction } = await monetizationService.preparePurchaseTransaction(- req.body.agent_id,- req.body.skill_name- );- return json(res, 200, { transaction });- } catch (e) {- // Handle specific errors from the service for better status codes- return error(res, 500, 'prep_failed', e.message);- }-});-```diff --git a/docs/monetization/17-access-control-for-skills.md b/docs/monetization/17-access-control-for-skills.mddeleted file mode 100644index d21e09f64..000000000--- a/docs/monetization/17-access-control-for-skills.md+++ /dev/null@@ -1,79 +0,0 @@-# Prompt 17: Access Control for Skills--## Objective-Implement a robust access control layer on the backend to check if a user is permitted to use a specific skill before execution.--## Explanation-Now that users can buy skills or subscribe to tiers, we need to enforce access. Before executing any skill via the API, the backend must check if the skill is free or, if it's paid, whether the user has the right to use it. This is a critical security measure to protect creators' intellectual property.--## Instructions-1. **Create an Access Control Middleware/Function:**- * It's best to centralize this logic. Create a helper function, e.g., `hasSkillAccess(userId, agentId, skillName)`.--2. **Implement Access Logic:**- * The `hasSkillAccess` function will perform the following checks in order:- 1. Check if the skill is priced in `agent_skill_prices`. If not, it's a free skill, so return `true`.- 2. If the skill is priced, check if the user has a one-time purchase record for it in `user_purchased_skills`. If yes, return `true`.- 3. If not purchased individually, check if the user has an active subscription (`user_subscriptions` table).- 4. If they have a subscription, check if the `skillName` is in the `included_skills` array of their subscribed `agent_subscription_tiers`. If yes, return `true`.- 5. If none of the above are true, return `false`.--3. **Integrate into Skill Execution Endpoint:**- * Locate the main API endpoint responsible for executing agent skills (e.g., `/api/chat` or `/api/agent-actions.js`).- * Before running the skill logic, call your new `hasSkillAccess` function.- * If it returns `false`, the endpoint should immediately stop and return a 403 Forbidden error with a message like "You do not have access to this skill. Please purchase it from the marketplace."--## Code Example (Access Control Logic)--```javascript-// In a helper file, e.g., /api/_lib/access-control.js-import { supabase } from './supabase';--export async function hasSkillAccess(userId, agentId, skillName) {- // 1. Check if the skill is free- const { data: price, error: priceError } = await supabase- .from('agent_skill_prices')- .select('amount')- .eq('agent_id', agentId)- .eq('skill_name', skillName)- .single();-- // If there's no price entry, it's considered free- if (!price) return true;-- // User must be logged in to access priced skills- if (!userId) return false;-- // 2. Check for a one-time purchase- const { data: purchase, error: purchaseError } = await supabase- .from('user_purchased_skills')- .select('id')- .eq('user_id', userId)- .eq('agent_id', agentId)- .eq('skill_name', skillName)- .single();-- if (purchase) return true;-- // 3. Check for an active subscription that includes this skill- const { data: subscription, error: subError } = await supabase- .from('user_subscriptions')- .select(`- status,- agent_subscription_tiers ( included_skills )- `)- .eq('user_id', userId)- .eq('status', 'active')- // We need to join through tiers to filter by agent- // This query is simplified; a real one might need an RPC function- // or a more complex join to link user_subscriptions -> tiers -> agents.- .single(); // Assuming one active sub per user/agent for now-- if (subscription && subscription.agent_subscription_tiers.included_skills.includes(skillName)) {- return true;- }-- // 4. If all checks fail- return false;-}-```diff --git a/docs/monetization/17-creator-dashboard-tab.md b/docs/monetization/17-creator-dashboard-tab.mddeleted file mode 100644index c5d689488..000000000--- a/docs/monetization/17-creator-dashboard-tab.md+++ /dev/null@@ -1,97 +0,0 @@-# Prompt 17: Creator Dashboard Monetization Tab--## Objective-Create a new "Earnings" or "Monetization" tab in the agent creator's dashboard to serve as the central hub for managing paid skills and tracking revenue.--## Explanation-Creators need a dedicated space to view their sales performance, manage their payout settings, and see which of their skills are generating revenue. This prompt establishes the foundation for that space.--## Instructions-1. **Identify Dashboard File:**- * Find the main file for the creator dashboard. This might be a file like `dashboard.html` or a route within a frontend framework. The file `agent-edit.html` has tabs, so it's a good candidate for adding a new one.--2. **Add a New Tab:**- * Add a new "Earnings" tab to the tab list in `agent-edit.html`.- * Create the corresponding panel `div` that will be shown when the tab is active.- ```html- <!-- In the tab list -->- <button class="edit-tab" data-tab="earnings" role="tab">Earnings</button>-- <!-- In the main content area -->- <section class="edit-panel" id="panel-earnings" role="tabpanel" hidden>- <!-- Content for the earnings panel will go here -->- </section>- ```--3. **Basic Panel Structure:**- * Inside the `#panel-earnings` div, create the initial layout. This should include:- * A "Summary" section to display key metrics like "Total Revenue," "Platform Fees," and "Net Earnings."- * A "Recent Sales" section that will eventually contain a table or list of the latest skill purchases.- * A "Payouts" section for managing withdrawal settings and viewing payout history.--4. **Backend Data Endpoint:**- * Create a new backend endpoint, e.g., `GET /api/dashboard/earnings`, that is authenticated for the current user.- * This endpoint should gather and return all the necessary data for this page:- * Aggregated earnings stats (total revenue, etc.).- * A list of the 10 most recent sales transactions.- * The creator's current payout wallet settings.--5. **Frontend JavaScript:**- * In the JavaScript for `agent-edit.html`, add logic to handle the new "Earnings" tab.- * When the tab is clicked for the first time, make a call to the new `/api/dashboard/earnings` endpoint.- * Use the returned data to populate the sections you created in the HTML. For now, you can just display the raw data or simple placeholders.--## Code Example (Frontend - `agent-edit.html`)--```html-<!-- Inside the #panel-earnings section -->-<div class="earnings-summary">- <div class="summary-card">- <span class="label">Total Revenue</span>- <span class="value" id="earnings-total-revenue">$0.00</span>- </div>- <div class="summary-card">- <span class="label">Net Earnings</span>- <span class="value" id="earnings-net">$0.00</span>- </div>- <div class="summary-card">- <span class="label">Withdrawable</span>- <span class="value" id="earnings-withdrawable">$0.00</span>- </div>-</div>--<h3>Recent Sales</h3>-<div id="earnings-recent-sales">- <p>No sales yet.</p>-</div>--<h3>Payout Settings</h3>-<div id="earnings-payouts">- <!-- Payout UI will go here, from a later prompt -->-</div>-```--```javascript-// In the script for agent-edit.html--let earningsDataLoaded = false;-function initEarningsTab() {- if (earningsDataLoaded) return;-- fetch('/api/dashboard/earnings')- .then(res => res.json())- .then(data => {- document.getElementById('earnings-total-revenue').textContent = formatCurrency(data.summary.total_revenue);- document.getElementById('earnings-net').textContent = formatCurrency(data.summary.net_earnings);- document.getElementById('earnings-withdrawable').textContent = formatCurrency(data.summary.withdrawable);-- renderRecentSales(data.recent_sales);- earningsDataLoaded = true;- })- .catch(err => {- document.getElementById('panel-earnings').innerHTML = '<p class="error">Could not load earnings data.</p>';- });-}--// In your tab switching logic, call initEarningsTab() when the 'earnings' tab is activated.-```diff --git a/docs/monetization/17-subscription-payment-activation.md b/docs/monetization/17-subscription-payment-activation.mddeleted file mode 100644index e2eacec99..000000000--- a/docs/monetization/17-subscription-payment-activation.md+++ /dev/null@@ -1,67 +0,0 @@-----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/17-subscription-purchase-flow.md b/docs/monetization/17-subscription-purchase-flow.mddeleted file mode 100644index 1570199e3..000000000--- a/docs/monetization/17-subscription-purchase-flow.md+++ /dev/null@@ -1,31 +0,0 @@-# Prompt 17: Subscription Purchase Flow--## Objective-Implement the UI and backend logic for purchasing a monthly subscription to an agent, which grants access to all its skills.--## Explanation-This prompt builds on the subscription database schema by creating the user-facing flow to purchase a subscription. This will involve presenting subscription tiers, handling payment, and creating the `user_subscriptions` record.--## Instructions-1. **Display Subscription Tiers:**- * On the agent detail page in the marketplace, if an agent offers subscriptions, display the available tiers (from the `subscription_tiers` table).- * Each tier should show its name, price, interval (e.g., "$10/month"), and description.- * Add a "Subscribe" button to each tier.--2. **Create Subscription Checkout API:**- * Create a new endpoint, e.g., `/api/subscriptions/purchase`.- * This endpoint will handle the payment logic. Since subscriptions are recurring, a simple transfer is not enough. You need to use a Solana protocol designed for recurring payments, like Solana Pay or a custom smart contract.- * For this prompt, we can simulate the first payment: the endpoint should behave like the skill purchase endpoint, processing a one-time payment for the first month.--3. **Create `user_subscriptions` Record:**- * After the first payment is successfully processed, the backend must:- * Create a new record in the `user_subscriptions` table.- * Set the `user_id`, `tier_id`, and `status` to 'active'.- * Set the `start_date` to the current time.- * Calculate and set the `end_date` (e.g., `start_date` + 1 month).--4. **Connect UI to API:**- * Wire the "Subscribe" button to call the purchase endpoint and handle the transaction with the user's wallet.--## Note on Recurring Payments-True on-chain recurring payments are complex. They often require users to deposit funds into an escrow contract or use token streaming protocols. This prompt simplifies the task to focus on the initial purchase and record creation, which is the first step in any subscription system. A later, more advanced prompt would cover the on-chain automation for renewals.diff --git a/docs/monetization/17-ui-for-insufficient-skills.md b/docs/monetization/17-ui-for-insufficient-skills.mddeleted file mode 100644index 158f1dbfb..000000000--- a/docs/monetization/17-ui-for-insufficient-skills.md+++ /dev/null@@ -1,87 +0,0 @@-# Prompt 17: UI for Insufficient Skills--## Objective-Create a user interface in the chat window that gracefully handles cases where the user tries to use a premium skill they don't own, and prompts them to purchase it.--## Explanation-When the backend blocks an action due to a missing skill (from the previous prompt), the frontend needs to interpret this specific response and present a clear call-to-action to the user. Instead of a generic error, we should guide them directly to the marketplace to acquire the needed skill.--## Instructions-1. **Handle the Specific API Response (Frontend):**- * In your frontend chat logic, when you make a request to the chat API, check the response status code.- * If you receive a `402 Payment Required` status, you know it's a skill-related issue.- * Read the JSON body of the response, which will contain the `skillName` and the message.--2. **Render a Special Chat Bubble:**- * Instead of rendering a normal error message, create a new type of chat bubble.- * This bubble should display the message from the API (e.g., "This action requires the 'MarketAnalysis' skill.").- * Crucially, it must include a button or link that says "Purchase Skill" or "Unlock in Marketplace".- * This button should link directly to the agent's detail page in the marketplace, possibly with a query parameter to highlight the required skill (e.g., `/marketplace/agent/<agent_id>?highlight_skill=MarketAnalysis`).--## Code Example (Frontend - `src/chat.js`)--```javascript-async function sendMessage(messageText) {- const chatHistory = document.getElementById('chat-history');-- try {- const response = await fetch('/api/chat', { /* ... POST data ... */ });-- if (!response.ok) {- if (response.status === 402) {- // This is our special case for a required skill- const data = await response.json();- renderPurchasePrompt(data);- } else {- // Handle other server errors- throw new Error(`Server error: ${response.status}`);- }- return;- }-- const data = await response.json();- renderAgentMessage(data.response);-- } catch (error) {- renderErrorMessage(error.message);- }-}--function renderPurchasePrompt(data) {- const chatHistory = document.getElementById('chat-history');- const agentId = getCurrentAgentId(); // Helper to get the current agent's ID-- const bubble = document.createElement('div');- bubble.className = 'chat-bubble agent-bubble purchase-prompt';- bubble.innerHTML = `- <p>${escapeHtml(data.message)}</p>- <a- href="/marketplace/agent/${agentId}?highlight_skill=${encodeURIComponent(data.skillName)}"- class="purchase-prompt-btn"- >- Unlock Skill- </a>- `;- chatHistory.appendChild(bubble);-}-```--## CSS for the Prompt Bubble--```css-.purchase-prompt {- background-color: rgba(253, 224, 71, 0.1);- border: 1px solid rgba(253, 224, 71, 0.3);-}--.purchase-prompt-btn {- display: inline-block;- margin-top: 10px;- padding: 8px 16px;- background-color: var(--accent);- color: #fff;- text-decoration: none;- border-radius: 6px;- font-weight: 600;-}-```diff --git a/docs/monetization/17-user-purchase-history.md b/docs/monetization/17-user-purchase-history.mddeleted file mode 100644index a70cee103..000000000--- a/docs/monetization/17-user-purchase-history.md+++ /dev/null@@ -1,21 +0,0 @@-----status: not-started------# Prompt 17: User Purchase History--## Objective-Create a page where users can see a history of all the skills they have purchased.--## Explanation-A purchase history page provides transparency and allows users to keep track of their spending and owned assets.--## Instructions-1. **Create a New API Endpoint:**- * Develop an endpoint, e.g., `GET /api/users/me/purchases`, that returns a list of all skills purchased by the authenticated user.- * This will query the `user_skill_purchases` table.--2. **Build the Frontend Page:**- * Create a new page in the user's profile section.- * Fetch the purchase history from the API and display it in a clean and organized table.- * Include details like the skill name, agent name, price paid, and transaction date.diff --git a/docs/monetization/17_caching_layer.md b/docs/monetization/17_caching_layer.mddeleted file mode 100644index 8a6385109..000000000--- a/docs/monetization/17_caching_layer.md+++ /dev/null@@ -1,74 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 17: Caching Layer for On-Chain Data--## Objective-Implement a caching layer (e.g., using Redis) to reduce redundant calls to the Solana RPC and other external APIs, improving performance and reliability.--## Explanation-Our application makes several calls to the Solana network (e.g., `getLatestBlockhash`, `getParsedTransaction`) and potentially other services like CoinGecko. These calls can be slow and are subject to rate limiting. Caching frequently accessed, non-time-sensitive data can significantly speed up our API responses.--## Instructions-1. **Set Up a Caching Client:**- * Add a Redis client library (e.g., `ioredis`) to the project.- * Create a Redis client instance that can be shared across the application, likely in `api/_lib/redis.js`.--2. **Identify Caching Opportunities:**- * **Skill Prices:** Prices set by creators don't change often. They can be cached for several minutes. The cache should be invalidated whenever a creator updates their prices.- * **Agent Details:** Marketplace agent data is a prime candidate for caching.- * **Transaction Details:** A confirmed transaction is immutable. Once we've verified a purchase signature with `getParsedTransaction`, we can cache the result indefinitely. If we check the same signature again, we can serve it from the cache.- * **SOL/USD Price:** The CoinGecko API has rate limits. We should cache the SOL price for at least 60-120 seconds.--3. **Implement Caching Logic:**- * Wrap your data-fetching logic in a "cache-aside" pattern:- * First, try to get the data from the Redis cache using a specific key (e.g., `skill-price:${agentId}:${skillName}`).- * If the data exists in the cache (a "cache hit"), return it immediately.- * If not (a "cache miss"), fetch the data from the primary source (database or external API).- * After fetching, store the data in Redis with a Time-To-Live (TTL) before returning it.--## Code Example (A generic caching function)--```javascript-// In api/_lib/cache.js-import { redis } from './redis.js'; // Assume this exports a Redis client--export async function cacheAside(key, ttlSeconds, fetchDataFn) {- const cachedData = await redis.get(key);- if (cachedData) {- return JSON.parse(cachedData);- }-- const liveData = await fetchDataFn();-- // Set with TTL and handle cases where liveData might be null- if (liveData) {- await redis.set(key, JSON.stringify(liveData), 'EX', ttlSeconds);- }-- return liveData;-}-```--## Code Example (Using the cache in a service)--```javascript-// Inside MonetizationService.js-import { cacheAside } from '../../_lib/cache.js';--class MonetizationService {- async getSkillPrice(agentId, skillName) {- const cacheKey = `skill-price:${agentId}:${skillName}`;- const ttl = 300; // 5 minutes-- return cacheAside(cacheKey, ttl, async () => {- const [price] = await sql`- SELECT amount, currency_mint FROM agent_skill_prices- WHERE agent_id = ${agentId} AND skill_name = ${skillName}- `;- return price;- });- }-}-```diff --git a/docs/monetization/18-db-schema-earnings.md b/docs/monetization/18-db-schema-earnings.mddeleted file mode 100644index 5f873622a..000000000--- a/docs/monetization/18-db-schema-earnings.md+++ /dev/null@@ -1,75 +0,0 @@-# Prompt 18: DB Schema for Earnings and Platform Fees--## Objective-Design and create the database table schema for `skill_payment_earnings` to reliably track revenue for creators and calculate platform fees.--## Explanation-When a payment is successfully completed, the revenue needs to be allocated. This table will store a record of each sale, attributing the earnings to the correct creator, and clearly separating the gross amount, the platform's cut, and the net amount due to the creator. This is fundamental for accurate accounting and payouts.--## Instructions-1. **Define the Table Schema:**- * Create a new table named `skill_payment_earnings`.- * It should include the following columns:- * `id`: Primary key (UUID or auto-incrementing integer).- * `payment_id`: A unique foreign key referencing `skill_payments(id)`. This ensures each payment has only one corresponding earnings entry.- * `agent_id`: Foreign key to `agents(id)`.- * `creator_id`: Foreign key to `users(id)`, identifying the user who gets the earnings.- * `gross_amount`: The total amount paid by the user (in lamports or smallest unit).- * `platform_fee_bps`: The platform fee basis points at the time of the transaction (e.g., `500` for 5%).- * `platform_fee_amount`: The calculated platform fee (`gross_amount * platform_fee_bps / 10000`).- * `net_amount`: The amount due to the creator (`gross_amount - platform_fee_amount`).- * `currency_mint`: The mint address of the currency used.- * `payout_id`: A nullable foreign key that will link to a `payouts` table when the earnings are withdrawn.- * `created_at`: Timestamp.--2. **Create Indexes:**- * Create an index on `creator_id` to quickly query for all earnings belonging to a specific creator for their dashboard.- * Create an index on `payout_id` to find all earnings included in a specific payout batch.--3. **Write the SQL Migration:**- * Create a new SQL migration file to apply this schema change to your database.--## SQL Schema Example--```sql-CREATE TABLE skill_payment_earnings (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- payment_id UUID NOT NULL UNIQUE REFERENCES skill_payments(id) ON DELETE CASCADE,- agent_id UUID NOT NULL REFERENCES agents(id),- creator_id UUID NOT NULL REFERENCES users(id),-- gross_amount BIGINT NOT NULL,- platform_fee_bps INTEGER NOT NULL, -- e.g., 500 for 5.00%- platform_fee_amount BIGINT NOT NULL,- net_amount BIGINT NOT NULL,-- currency_mint VARCHAR(255) NOT NULL,-- -- This will be NULL until the earnings are included in a payout- payout_id UUID REFERENCES payouts(id),-- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- CONSTRAINT check_amounts CHECK (gross_amount = platform_fee_amount + net_amount)-);---- Index for creator dashboard queries-CREATE INDEX idx_skill_earnings_creator_id ON skill_payment_earnings(creator_id);---- Index for finding earnings in a payout-CREATE INDEX idx_skill_earnings_payout_id ON skill_payment_earnings(payout_id);----- You will also need a payouts table for later prompts-CREATE TABLE payouts (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- creator_id UUID NOT NULL REFERENCES users(id),- amount BIGINT NOT NULL,- currency_mint VARCHAR(255) NOT NULL,- status VARCHAR(50) NOT NULL DEFAULT 'pending', -- pending, completed, failed- destination_address VARCHAR(255) NOT NULL,- tx_signature VARCHAR(255),- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- completed_at TIMESTAMPTZ-);-```diff --git a/docs/monetization/18-gifting-skills.md b/docs/monetization/18-gifting-skills.mddeleted file mode 100644index a2f2ad867..000000000--- a/docs/monetization/18-gifting-skills.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 18: Gifting Skills--## Objective-Allow users to purchase a skill and gift it to another user.--## Explanation-Gifting is a great way to encourage user engagement and introduce new users to the platform.--## Instructions-1. **Update the UI:**- * Add a "Gift" option to the purchase modal.- * If selected, an input field will appear for the user to enter the recipient's wallet address or username.--2. **Modify the Backend:**- * The payment processing endpoint will need to accept an optional `recipient_id`.- * When the purchase is recorded in the `user_skill_purchases` table, it will be associated with the recipient's user ID instead of the sender's.--3. **Notifications:**- * Implement a notification system to inform the recipient that they have received a gift.diff --git a/docs/monetization/18-on-chain-program-for-skill-nfts.md b/docs/monetization/18-on-chain-program-for-skill-nfts.mddeleted file mode 100644index 6cc088d80..000000000--- a/docs/monetization/18-on-chain-program-for-skill-nfts.md+++ /dev/null@@ -1,87 +0,0 @@-# Prompt 18: On-Chain Program for Skill NFTs--## Objective-Design and outline the structure of a Solana program (smart contract) that represents ownership of a purchased skill as a Non-Fungible Token (NFT).--## Explanation-To fully embrace decentralization and give users true ownership, purchasing a skill should mint them an NFT that acts as an on-chain access key. This is a significant architectural step. The NFT would be tied to the user's wallet, the agent, and the specific skill. Our backend could then check for the presence of this NFT in a user's wallet as an alternative way to verify access. This prompt focuses on the design of the on-chain program using Anchor.--## Instructions-1. **Define the Program's State:**- * What data needs to be stored on-chain?- * We'll need an account to represent the skill license. Let's call it `SkillLicense`.- * The `SkillLicense` account should store:- * `authority` (the user's wallet that owns it).- * `agent_mint` (the public key of an NFT representing the agent itself, for grouping).- * `skill_name` (a string identifying the skill).- * `purchase_date`.--2. **Define the Program's Instructions:**- * What actions can users take?- * The primary instruction will be `mint_skill_license`.- * This instruction will be called by our backend (acting as a minter authority) after a payment is verified.- * It will create a new `SkillLicense` account and a corresponding NFT for the user.- * We might also need a `burn_skill_license` for refunds or transfers.--3. **Set up an Anchor Project:**- * If not already present, set up a new Anchor project in the `/contracts` directory.- * Define the `SkillLicense` account struct in `lib.rs`.- * Define the `mint_skill_license` instruction handler.--## Anchor (Rust) Code Example (`contracts/src/lib.rs`)--```rust-use anchor_lang::prelude::*;-// We would also use anchor_spl::token for NFT minting--declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");--#[program]-pub mod skill_marketplace {- use super::*;- pub fn mint_skill_license(- ctx: Context<MintSkillLicense>,- skill_name: String- ) -> Result<()> {- let license = &mut ctx.accounts.skill_license;- license.authority = *ctx.accounts.user.key;- license.agent_id = *ctx.accounts.agent.key; // Simplified: agent is an account- license.skill_name = skill_name;- license.purchase_date = Clock::get()?.unix_timestamp;-- // Here, we would also add the logic to mint a Metaplex NFT- // to the user's wallet, using this license account as a basis.- // This is a complex step involving CPIs to the Token and Metaplex programs.-- msg!("Skill license created for skill: {}", license.skill_name);- Ok(())- }-}--#[derive(Accounts)]-pub struct MintSkillLicense<'info> {- #[account(init, payer = minter, space = 8 + 32 + 32 + 32 + 8)]- pub skill_license: Account<'info, SkillLicense>,-- /// CHECK: The agent this skill belongs to- pub agent: AccountInfo<'info>,-- /// CHECK: The user who is receiving the license- #[account(mut)]- pub user: Signer<'info>,-- // The backend's wallet, which has authority to mint licenses- #[account(mut)]- pub minter: Signer<'info>,-- pub system_program: Program<'info, System>,-}--#[account]-pub struct SkillLicense {- pub authority: Pubkey, // User who owns the skill- pub agent_id: Pubkey, // Agent the skill is for- pub skill_name: String,- pub purchase_date: i64,-}-```diff --git a/docs/monetization/18-refactor-to-payment-sdk.md b/docs/monetization/18-refactor-to-payment-sdk.mddeleted file mode 100644index 173109515..000000000--- a/docs/monetization/18-refactor-to-payment-sdk.md+++ /dev/null@@ -1,84 +0,0 @@-# Prompt 18: Refactor to a Payment SDK--## Objective-Abstract the core Solana payment logic into a reusable SDK within the `agent-payments-sdk/` directory to promote code reuse and maintainability.--## Explanation-As the platform grows, you may want to add payments for other items, such as purchasing agents, tipping creators, or buying 3D assets. Repeating the Solana Pay transaction logic in each API endpoint would be inefficient and error-prone. By creating a centralized `PaymentSDK`, we can handle all payment-related operations in one place.--## Instructions-1. **Identify Core Logic:**- * Review your `api/payments/prepare-skill-purchase.js` endpoint.- * Identify the reusable parts:- * Creating and configuring a `Connection`.- * Constructing SPL token transfer instructions.- * Handling platform fees.- * Serializing and structuring the transaction for the Solana Pay response.- * Verifying a transaction signature.--2. **Create the SDK Module (`agent-payments-sdk/src/index.ts`):**- * Create a `PaymentSDK` class or a set of exported functions.- * Move the core logic identified above into methods within this SDK.- * For example, you could have a method `createSplTransferTransaction(buyer, transfers, reference)` where `transfers` is an array of `{ destination, amount }` objects. This method would handle the platform fee calculation internally.- * Another method could be `verifyTransaction(signature, expectedTransfers)`.--3. **Refactor the API Endpoint:**- * Rewrite the `prepare-skill-purchase.js` endpoint to use your new SDK.- * The endpoint will now be much simpler. It will be responsible for fetching the business logic details (like the skill price and creator wallet) and then calling the SDK methods to construct and verify the transaction.--## Code Example (`agent-payments-sdk/src/index.ts`)--```typescript-import { Connection, PublicKey, Transaction, SystemProgram } from '@solana/web3.js';-import { getAssociatedTokenAddress, createTransferInstruction } from '@solana/spl-token';--interface Transfer {- destination: PublicKey;- amount: bigint; // Use BigInt for lamports-}--export class PaymentSDK {- private connection: Connection;- private platformWallet: PublicKey;- private platformFeeBps: bigint;-- constructor(rpcUrl: string, platformWallet: string, feeBps: number) {- this.connection = new Connection(rpcUrl);- this.platformWallet = new PublicKey(platformWallet);- this.platformFeeBps = BigInt(feeBps);- }-- async createPurchaseTransaction(- buyer: PublicKey,- creator: PublicKey,- totalAmount: bigint,- mint: PublicKey,- reference: PublicKey- ): Promise<Transaction> {- const { blockhash } = await this.connection.getLatestBlockhash();- const transaction = new Transaction({ recentBlockhash: blockhash, feePayer: buyer });-- const buyerAta = await getAssociatedTokenAddress(mint, buyer);- const creatorAta = await getAssociatedTokenAddress(mint, creator);- const platformAta = await getAssociatedTokenAddress(mint, this.platformWallet);-- const platformFee = (totalAmount * this.platformFeeBps) / 10000n;- const creatorAmount = totalAmount - platformFee;-- transaction.add(- createTransferInstruction(buyerAta, creatorAta, buyer, creatorAmount),- );- if (platformFee > 0) {- transaction.add(- createTransferInstruction(buyerAta, platformAta, buyer, platformFee),- );- }-- // Add reference for lookup- transaction.add(SystemProgram.transfer({ fromPubkey: buyer, toPubkey: reference, lamports: 0 }));-- return transaction;- }- // ... other methods like verifyTransaction-}-```diff --git a/docs/monetization/18-subscription-token-gating.md b/docs/monetization/18-subscription-token-gating.mddeleted file mode 100644index 49929add9..000000000--- a/docs/monetization/18-subscription-token-gating.md+++ /dev/null@@ -1,44 +0,0 @@-# Prompt 18: Subscription Token Gating--## Objective-Gate agent and skill access based on a user's subscription status.--## Explanation-Similar to gating individual skills with NFT ownership, this prompt applies the same principle to subscriptions. If an agent offers subscriptions, users with an active subscription should get access to all of its paid skills.--## Instructions-1. **Create Subscription Status Endpoint:**- * Create a new backend endpoint, e.g., `/api/subscriptions/status`.- * It should take an `agent_id` and `user_id` (from session) as input.- * The endpoint queries the `user_subscriptions` table to check if there is an 'active' subscription for that user and agent, where the `end_date` is in the future.- * It should return a simple JSON response, like `{ "is_subscribed": true, "tier": "Pro" }`.--2. **Modify Skill Gating Logic:**- * Update the `tryUseSkill` function from Prompt 9.- * Before checking for individual NFT ownership for a paid skill, first check if the user has an active subscription to the agent.- * Call the new `/api/subscriptions/status` endpoint.- * If the user `is_subscribed`, grant them access to the skill immediately, bypassing the NFT check.--3. **Update UI Based on Subscription:**- * On the agent detail page, if a user is already subscribed, the "Unlock" buttons for skills should be hidden or changed to "Use".- * The "Subscribe" buttons for tiers should be replaced with a message like "You are currently subscribed to the Pro plan."--## Code Example (Backend Status Endpoint)-```javascript-async function getSubscriptionStatus(req, res) {- const userId = req.session.userId;- const { agent_id } = req.query;-- const result = await db.query(- `SELECT * FROM user_subscriptions- WHERE user_id = $1 AND agent_id = $2 AND status = 'active' AND end_date > NOW()`,- [userId, agent_id]- );-- if (result.rows.length > 0) {- res.status(200).json({ is_subscribed: true });- } else {- res.status(200).json({ is_subscribed: false });- }-}-```diff --git a/docs/monetization/18-tip-jar-feature.md b/docs/monetization/18-tip-jar-feature.mddeleted file mode 100644index e375ccbfd..000000000--- a/docs/monetization/18-tip-jar-feature.md+++ /dev/null@@ -1,96 +0,0 @@-----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}¤cy=${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/18_testing_the_service.md b/docs/monetization/18_testing_the_service.mddeleted file mode 100644index 8d8aa624b..000000000--- a/docs/monetization/18_testing_the_service.md+++ /dev/null@@ -1,72 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 18: Unit and Integration Tests for Monetization Service--## Objective-Write a suite of tests for the `MonetizationService` to ensure its logic is correct, robust, and reliable.--## Explanation-The monetization logic is critical and involves financial transactions, so it must be thoroughly tested. We need to create both unit tests (testing individual methods in isolation) and integration tests (testing the service's interaction with a real or mock database).--## Instructions-1. **Set Up a Testing Framework:**- * Ensure a testing framework like Jest or Vitest is configured for the backend.- * Set up a separate test database or a mechanism to run tests in a transaction that can be rolled back, to avoid polluting the development database.--2. **Write Unit Tests:**- * **Mock Dependencies:** Mock the `sql` database client and any external APIs.- * **Test Cases:**- * `setSkillPrices`: Test that it correctly formats the SQL query for upserting prices. Test that it throws an error if the user is not the agent owner.- * `preparePurchaseTransaction`: Mock the database calls for price/wallet lookups. Verify that the created transaction has the correct instructions, amounts, and public keys. Test the platform fee calculation.- * `checkSkillOwnership`: Mock database calls to simulate a user owning a skill, not owning it, and the skill being free. Test that it returns the correct access decision.--3. **Write Integration Tests:**- * **Use a Test Database:** Connect to a real test database.- * **Test Scenarios:**- * Create a test user and agent.- * Call `setSkillPrices` and then immediately query the database to verify the price was written correctly.- * Simulate a purchase confirmation by first inserting a record into `user_purchased_skills` and then calling `checkSkillOwnership` to ensure it returns true.- * Test the `getCreatorSalesData` method by seeding some purchase data and verifying that the aggregation (total revenue, counts) is correct.--## Code Example (Jest - Unit Test Snippet)--```javascript-// In tests/services/MonetizationService.test.js-import { MonetizationService } from '../../api/_lib/services/MonetizationService';-import { sql } from '../../api/_lib/db'; // Mock this--// Mock the database-jest.mock('../../api/_lib/db', () => ({- sql: jest.fn().mockResolvedValue([- // mock return values here- ]),-}));--describe('MonetizationService', () => {- let service;- const mockUser = { id: 'user-123' };-- beforeEach(() => {- service = new MonetizationService(mockUser);- sql.mockClear();- });-- it('should block price setting if user is not the owner', async () => {- // Mock the agent ownership check to return no agent- sql.mockResolvedValueOnce([]);- await expect(service.setSkillPrices('agent-abc', {})).rejects.toThrow('permission denied');- });-- it('should correctly calculate platform fee in transaction prep', async () => {- // Mock DB calls to return a price of 1,000,000 lamports- // Mock web3.js calls- // ...- const { transaction } = await service.preparePurchaseTransaction(...);- // Inspect the deserialized transaction to check instruction amounts- // expect(creatorInstruction.amount).toBe(950000); // 95%- // expect(platformFeeInstruction.amount).toBe(50000); // 5%- });-});-```diff --git a/docs/monetization/19-backend-record-earnings.md b/docs/monetization/19-backend-record-earnings.mddeleted file mode 100644index c3112e1e3..000000000--- a/docs/monetization/19-backend-record-earnings.md+++ /dev/null@@ -1,77 +0,0 @@-# Prompt 19: Backend Logic to Record Earnings--## Objective-After a payment is confirmed, implement the backend logic to calculate and record the creator's earnings and the platform fee in the `skill_payment_earnings` table.--## Explanation-This is the accounting step of the monetization flow. It connects the confirmed payment to the creator's ledger. This logic must run immediately after payment confirmation to ensure that revenue is tracked in real-time.--## Instructions-1. **File to Edit:**- * Open the backend endpoint for payment confirmation: `POST /api/payments/confirm-skill-payment`.--2. **Integrate Earnings Calculation:**- * Locate the spot in your code inside the database transaction, immediately after you have updated the `skill_payments` table to `completed` and created the `skill_access_grants` record.- * **Define Platform Fee:** Get the current platform fee. It's best practice to have this as a configurable value (e.g., in an environment variable or a configuration file). For example, `PLATFORM_FEE_BPS = 500` (for 5%).- * **Calculate Amounts:**- * `gross_amount`: This is the `amount` from the `paymentIntent` record.- * `platform_fee_amount`: `Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000)`. Use floor to be safe.- * `net_amount`: `gross_amount - platform_fee_amount`.- * **Get Creator ID:** You'll need the ID of the agent's creator, which should be available on the `agent` object.--3. **Insert the Earnings Record:**- * Within the same database transaction, insert a new row into the `skill_payment_earnings` table with all the calculated values.--## Code Example (Backend - `confirm-skill-payment` logic)--This refines the example from Prompt 14, adding the earnings logic to the transaction.--```javascript-// Inside your /api/payments/confirm-skill-payment endpoint handler--// ... after successfully verifying the on-chain transaction ...--const PLATFORM_FEE_BPS = 500; // 5%--try {- // Use a database transaction to ensure atomicity- await db.transaction(async (trx) => {- // 1. Update Payment Status- await trx.update('skill_payments', { status: 'completed', signature: signature })- .where({ id: paymentId });-- // 2. Grant Skill Access- const expiresAt = new Date(Date.now() + 24 * 60 * 60 * 1000);- await trx.insert({- user_id: user.id,- agent_id: paymentIntent.agentId,- skill_name: paymentIntent.skillName,- payment_id: paymentId,- expires_at: expiresAt,- }).into('skill_access_grants');-- // 3. NEW: Record Earnings- const agent = await trx.select('creator_id').from('agents').where({ id: paymentIntent.agentId }).first();- const gross_amount = paymentIntent.amount;- const platform_fee_amount = Math.floor(gross_amount * PLATFORM_FEE_BPS / 10000);- const net_amount = gross_amount - platform_fee_amount;-- await trx.insert({- payment_id: paymentId,- agent_id: paymentIntent.agentId,- creator_id: agent.creator_id,- gross_amount,- platform_fee_bps: PLATFORM_FEE_BPS,- platform_fee_amount,- net_amount,- currency_mint: paymentIntent.currency_mint,- }).into('skill_payment_earnings');- });-- res.status(200).json({ success: true, message: 'Payment confirmed and access granted.' });--} catch (error) {- console.error('Error in confirmation transaction:', error);- res.status(500).json({ error: 'Failed to finalize payment.' });-}-```diff --git a/docs/monetization/19-creator-revenue-dashboard.md b/docs/monetization/19-creator-revenue-dashboard.mddeleted file mode 100644index 0665f8529..000000000--- a/docs/monetization/19-creator-revenue-dashboard.md+++ /dev/null@@ -1,93 +0,0 @@-----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/19-free-trials-for-skills.md b/docs/monetization/19-free-trials-for-skills.mddeleted file mode 100644index 58cb88776..000000000--- a/docs/monetization/19-free-trials-for-skills.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 19: Free Trials for Paid Skills--## Objective-Implement a "free trial" feature that allows users to try a paid skill for a limited time or a limited number of uses.--## Explanation-Free trials can significantly increase the conversion rate for paid skills by allowing users to experience their value before committing to a purchase.--## Instructions-1. **Update Database Schema:**- * Add a `user_skill_trials` table to track active trials.- * This table would include `user_id`, `skill_name`, `start_date`, and `end_date` or `usage_count`.--2. **Modify Access Control:**- * The access control middleware needs to be updated to check for active trials in addition to ownership.- * If a user has an active trial, they should be allowed to use the skill.--3. **UI for Trials:**- * Update the marketplace UI to show a "Start Free Trial" button for eligible skills.diff --git a/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.md b/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.mddeleted file mode 100644index 6ac82b61e..000000000--- a/docs/monetization/19-integrate-skill-nfts-into-purchase-flow.md+++ /dev/null@@ -1,71 +0,0 @@-# Prompt 19: Integrate Skill NFTs into Purchase Flow--## Objective-Modify the skill purchase and verification flow to mint a "Skill NFT" to the user upon a successful purchase, using the on-chain program designed in the previous prompt.--## Explanation-This task connects our off-chain backend with our on-chain program. After a user's payment is confirmed, instead of just writing to our own database, the backend's primary job will be to call the `mint_skill_license` instruction on our Solana program. This creates a durable, on-chain record of ownership for the user.--## Instructions-1. **Update Verification Endpoint:**- * In the `/api/marketplace/skills/verify-purchase` endpoint, after successfully verifying the user's payment transaction, add a new step.--2. **Call the On-Chain Program:**- * The backend, using its own service wallet (the "minter"), will construct and sign a transaction that calls the `mint_skill_license` instruction of our deployed Solana program.- * It will need the Anchor-generated client library for the program to build this transaction easily.- * The parameters for the instruction (`user`, `agent`, `skill_name`) will come from the context of the purchase.--3. **Update Access Control:**- * Modify the `hasSkillAccess` helper function from prompt #17.- * Add a new check: after checking the local database, if access is still denied, the function should query the blockchain to see if the user's wallet holds the required Skill NFT for that agent and skill. This makes the system more decentralized, as ownership can be proven directly on-chain.--## Code Example (Backend Snippet in `verify-purchase.js`)--```javascript-import { AnchorProvider, Program } from '@coral-xyz/anchor';-import { Connection, Keypair, PublicKey } from '@solana/web3.js';-// Assume `idl` and `programId` are available for our Anchor program-import idl from '../../../../contracts/target/idl/skill_marketplace.json';-const programId = new PublicKey(idl.metadata.address);--// ... inside the verify-purchase handler, after payment is confirmed ...--// 1. Set up connection to the on-chain program-const connection = new Connection(clusterApiUrl('devnet'));-const backendMinterWallet = Keypair.fromSecretKey(Buffer.from(process.env.MINTER_PRIVATE_KEY, 'base64'));-const provider = new AnchorProvider(connection, new Wallet(backendMinterWallet), {});-const program = new Program(idl, programId, provider);--// 2. Prepare accounts for the instruction-const skillLicenseAccount = Keypair.generate();-const userPublicKey = new PublicKey(purchaserPublicKey); // from original request-const agentPublicKey = new PublicKey(agent.on_chain_id); // Assuming agent has an on-chain ID--try {- // 3. Call the 'mint_skill_license' instruction- const txSignature = await program.methods- .mintSkillLicense(skillName)- .accounts({- skillLicense: skillLicenseAccount.publicKey,- agent: agentPublicKey,- user: userPublicKey,- minter: backendMinterWallet.publicKey,- systemProgram: SystemProgram.programId,- })- .signers([skillLicenseAccount, backendMinterWallet]) // Minter and new account need to sign- .rpc();-- console.log(`Successfully minted Skill NFT. Transaction: ${txSignature}`);-- // We might still write to our local DB for caching/performance,- // but the on-chain record is now the source of truth.- await recordPurchaseInLocalDB(userId, agentId, skillName, txSignature);-- return json(res, { success: true, message: 'Skill NFT minted!' });--} catch (e) {- console.error("Failed to mint skill NFT:", e);- // Important: Handle this failure, maybe by retrying or refunding the user.- return error(res, 500, 'Failed to mint on-chain license.');-}-```diff --git a/docs/monetization/19-platform-fee-integration.md b/docs/monetization/19-platform-fee-integration.mddeleted file mode 100644index 51f93f246..000000000--- a/docs/monetization/19-platform-fee-integration.md+++ /dev/null@@ -1,59 +0,0 @@-# Prompt 19: Platform Fee Integration--## Objective-Implement a platform fee on all transactions (both individual skill sales and subscription payments).--## Explanation-To create a sustainable business model, the platform needs to take a small percentage of each transaction. This requires modifying the on-chain payment logic to split the payment between the agent creator and the platform's treasury wallet.--## Instructions-1. **Store Platform Wallet Address:**- * Store the platform's main treasury wallet address in a secure place, like an environment variable (`PLATFORM_TREASURY_WALLET`).--2. **Modify Transaction Logic:**- * Locate the backend code that constructs the payment transaction (from Prompt 5 and Prompt 17).- * Instead of a single `SystemProgram.transfer` instruction, the transaction must now include **two** transfer instructions.--3. **Calculate and Split Payment:**- * Define the platform fee percentage (e.g., 5%).- * When a payment is made, calculate the fee amount and the creator's share.- * `platform_fee = total_price * 0.05`- * `creator_share = total_price * 0.95`- * The first transfer instruction will send `creator_share` to the `creator_wallet_address`.- * The second transfer instruction will send `platform_fee` to the `PLATFORM_TREASURY_WALLET`.--4. **Update Database and UI:**- * Ensure your `sales` table has columns to record the `platform_fee` and `creator_payout` amounts for transparent accounting.- * The UI should clearly state that the price includes a platform fee.--## Code Example (Updated Solana Transaction)-```javascript-// ...inside the purchase logic-const PLATFORM_FEE_PERCENT = 0.05; // 5%-const platformTreasury = new PublicKey(process.env.PLATFORM_TREASURY_WALLET);-const creatorWallet = new PublicKey(agent.creator_wallet_address);-const totalLamports = price.amount;--const platformFeeLamports = Math.round(totalLamports * PLATFORM_FEE_PERCENT);-const creatorShareLamports = totalLamports - platformFeeLamports;--const transaction = new Transaction()- .add(- // First instruction: pay the creator- SystemProgram.transfer({- fromPubkey: wallet.publicKey,- toPubkey: creatorWallet,- lamports: creatorShareLamports,- })- )- .add(- // Second instruction: pay the platform- SystemProgram.transfer({- fromPubkey: wallet.publicKey,- toPubkey: platformTreasury,- lamports: platformFeeLamports,- })- );--// Send and confirm the transaction as before...-```diff --git a/docs/monetization/19-purchase-notifications.md b/docs/monetization/19-purchase-notifications.mddeleted file mode 100644index 82678065f..000000000--- a/docs/monetization/19-purchase-notifications.md+++ /dev/null@@ -1,80 +0,0 @@-# Prompt 19: Purchase Confirmation Notifications--## Objective-After a successful skill purchase, send a confirmation to the user, either via an in-app notification, an email, or both.--## Explanation-Providing post-purchase confirmation is a standard practice that builds user trust and keeps them informed. An in-app notification provides immediate feedback, while an email serves as a permanent receipt. This task involves setting up a notification system and triggering it after a purchase is confirmed.--## Instructions-1. **Choose a Notification System:**- * **In-app:** You can build a simple notification system with a database table (`notifications`) and a UI element in the site header that shows a notification count.- * **Email:** Integrate with an email service provider like SendGrid, Postmark, or Resend.--2. **Create a Notification Service (Backend):**- * Create a new module, e.g., `services/notifications.js`.- * This service will have a function, e.g., `sendPurchaseConfirmation(userId, purchaseDetails)`.- * This function will contain the logic to either:- * Insert a new row into the `notifications` table in your database.- * Or, make an API call to your chosen email service provider to send a templated email.--3. **Integrate into Purchase Flow (Backend):**- * In your payment confirmation endpoint (`api/payments/prepare-skill-purchase.js`), after you have verified the transaction and granted the skill, call your new `sendPurchaseConfirmation` function.- * Pass all the necessary details, such as the user's information (for their email address), the skill name, agent name, and price paid.--## Code Example (Backend - Notification Service using Resend)--```javascript-// services/notifications.js-import { Resend } from 'resend';-import { findUserById } from '../_lib/db'; // DB function to get user details--const resend = new Resend(process.env.RESEND_API_KEY);--export async function sendPurchaseConfirmationEmail(userId, details) {- try {- const user = await findUserById(userId);- if (!user || !user.email) {- console.warn(`Cannot send email: User ${userId} not found or has no email.`);- return;- }-- await resend.emails.send({- from: '[email protected]',- to: user.email,- subject: 'Your Skill Purchase Confirmation',- html: `- <h1>Purchase Confirmed!</h1>- <p>Hi ${user.name || 'there'},</p>- <p>You have successfully purchased the skill "<strong>${details.skillName}</strong>" for the agent "<strong>${details.agentName}</strong>".</p>- <p><strong>Price:</strong> ${(details.amount / 1e6).toFixed(2)} USDC</p>- <p>Thank you for your purchase!</p>- `,- });- } catch (error) {- console.error('Failed to send purchase confirmation email:', error);- }-}-```--## Integration into Payment Endpoint--```javascript-// In api/payments/prepare-skill-purchase.js (GET handler)-// ... after granting skill access--import { sendPurchaseConfirmationEmail } from '../../services/notifications';--// ...-await grantSkillToUser(...);-await logTransaction(...);--// Asynchronously send the notification so it doesn't block the response-sendPurchaseConfirmationEmail(purchaseDetails.userId, {- skillName: purchaseDetails.skillName,- agentName: purchaseDetails.agentName,- amount: purchaseDetails.amount,-});--res.status(200).json({ status: 'ok', message: 'Purchase confirmed!' });-```diff --git a/docs/monetization/19_sale_notifications.md b/docs/monetization/19_sale_notifications.mddeleted file mode 100644index 69f86675d..000000000--- a/docs/monetization/19_sale_notifications.md+++ /dev/null@@ -1,70 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 19: User Experience - Notifications for Sales--## Objective-Implement a system to notify creators in real-time or near-real-time when one of their skills is purchased.--## Explanation-A key part of a positive creator experience is immediate feedback on sales. We will build a notification system that alerts creators when they've made a sale. This could be an on-site notification, an email, or both.--## Instructions-1. **Choose a Notification Channel:**- * **On-site:** A simple bell icon in the navigation that shows a red dot for new notifications. Clicking it reveals a dropdown of recent events.- * **Email:** Send a transactional email to the user's registered email address.- * For this task, we will focus on the backend logic to generate notifications, which can then be used for any channel.--2. **Database Schema for Notifications:**- * Create a `notifications` table:- * `id`: Primary key.- * `user_id`: The user who receives the notification.- * `type`: An enum or text, e.g., `'SKILL_SALE'`.- * `payload`: A JSONB column with details about the event (e.g., `{ "skillName": "...", "price": 1.00, "buyerUsername": "..." }`).- * `is_read`: A boolean flag, default `false`.- * `created_at`: Timestamp.--3. **Trigger Notification on Purchase:**- * In the `POST /api/skills/purchase-confirm` endpoint, after successfully verifying and recording a purchase, insert a new row into the `notifications` table.- * The `user_id` should be the ID of the agent's creator.--4. **API to Fetch Notifications:**- * Create a new endpoint, `GET /api/notifications`.- * This endpoint should fetch all unread notifications for the currently authenticated user.- * It could also fetch a list of recent notifications (both read and unread).--5. **API to Mark Notifications as Read:**- * Create an endpoint like `POST /api/notifications/mark-read`.- * This would update the `is_read` flag for specified notification IDs, so they no longer appear as "new."--## Code Example (Logic in `purchase-confirm` API)--```javascript-// ... after successfully inserting into user_purchased_skills--const [agentOwner] = await sql`- SELECT user_id FROM agent_identities WHERE id = ${agent_id}-`;--if (agentOwner) {- // Create a notification for the agent's creator- await sql`- INSERT INTO notifications (user_id, type, payload)- VALUES (- ${agentOwner.user_id},- 'SKILL_SALE',- ${JSON.stringify({- skillName: skill_name,- agentId: agent_id,- amount: expectedAmount,- currency: currencyMint,- buyerId: user.id,- purchaseSignature: signature- })}::jsonb- )- `;-}--// ... return success response-```diff --git a/docs/monetization/20-analytics-for-creators.md b/docs/monetization/20-analytics-for-creators.mddeleted file mode 100644index c9f1ca54e..000000000--- a/docs/monetization/20-analytics-for-creators.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 20: Analytics for Creators--## Objective-Provide creators with analytics about how their skills are performing in the marketplace.--## Explanation-Data-driven insights can help creators optimize their offerings and pricing.--## Instructions-1. **Track Metrics:**- * Start tracking key metrics, such as skill page views, clicks on the "Purchase" button, and successful purchases.--2. **Create an Analytics Dashboard:**- * In the creator dashboard, add a new section for analytics.- * Display charts and graphs for:- * Sales over time.- * Conversion rate (views to sales).- * Top-performing skills.- * Revenue by skill.diff --git a/docs/monetization/20-creator-revenue-api.md b/docs/monetization/20-creator-revenue-api.mddeleted file mode 100644index 94ff5da63..000000000--- a/docs/monetization/20-creator-revenue-api.md+++ /dev/null@@ -1,76 +0,0 @@-----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/20-display-earnings-dashboard.md b/docs/monetization/20-display-earnings-dashboard.mddeleted file mode 100644index 502b4d4e2..000000000--- a/docs/monetization/20-display-earnings-dashboard.md+++ /dev/null@@ -1,121 +0,0 @@-# Prompt 20: Display Earnings in Creator Dashboard--## Objective-Fetch and display the creator's earnings summary and a list of their recent transactions in the "Earnings" tab of their dashboard.--## Explanation-This prompt brings the creator-facing part of the monetization feature to life. It involves building the backend endpoint to aggregate earnings data and then using that data to populate the UI components created in Prompt 17.--## Instructions-1. **File to Edit (Backend):**- * Open the file for the `GET /api/dashboard/earnings` endpoint.--2. **Implement Backend Logic:**- * **Authentication:** Ensure the user is authenticated.- * **Summary Metrics:**- * Write a SQL query to get the `SUM` of `gross_amount`, `platform_fee_amount`, and `net_amount` from the `skill_payment_earnings` table, `WHERE creator_id` matches the current user.- * Also, calculate the `withdrawable` amount by summing `net_amount` only for earnings where `payout_id` is `NULL`.- * **Recent Sales:**- * Write a query to get the 10 most recent records from `skill_payment_earnings` for the current creator, ordered by `created_at DESC`.- * Join with the `skill_payments` table to get additional details like the `skill_name`.- * **Response:** Return a JSON object containing `summary` and `recent_sales`.--3. **File to Edit (Frontend):**- * Open the JavaScript for `agent-edit.html`.--4. **Implement Frontend Rendering:**- * In the `initEarningsTab` function (from Prompt 17), use the data returned from the API to populate the UI.- * **Summary:** Update the text content of the summary cards (`#earnings-total-revenue`, etc.) with the formatted currency values.- * **Recent Sales:**- * Create a function `renderRecentSales(sales)`.- * If the `sales` array is empty, show a "No sales yet" message.- * If it has data, dynamically create a table or a list of `div`s to display each sale.- * Include columns for `Date`, `Skill Name`, `Gross Revenue`, and `Net Earnings`.- * Format dates and currency values to be human-readable.--## Code Example (Backend - `/api/dashboard/earnings.js`)--```javascript-// Inside the API handler--const user = await getAuthenticatedUser(req);--// Query for summary metrics-const summaryResult = await db('skill_payment_earnings')- .where({ creator_id: user.id })- .sum({- total_revenue: 'gross_amount',- net_earnings: 'net_amount'- })- .first();--const withdrawableResult = await db('skill_payment_earnings')- .where({ creator_id: user.id, payout_id: null })- .sum({ amount: 'net_amount' })- .first();--const summary = {- total_revenue: summaryResult.total_revenue || 0,- net_earnings: summaryResult.net_earnings || 0,- withdrawable: withdrawableResult.amount || 0,-};--// Query for recent sales-const recent_sales = await db('skill_payment_earnings as earn')- .join('skill_payments as pay', 'earn.payment_id', 'pay.id')- .where('earn.creator_id', user.id)- .orderBy('earn.created_at', 'desc')- .limit(10)- .select(- 'earn.created_at',- 'pay.skill_name',- 'earn.gross_amount',- 'earn.net_amount',- 'earn.currency_mint'- );--res.status(200).json({ summary, recent_sales });-```--## Code Example (Frontend - `agent-edit.html` script)--```javascript-function renderRecentSales(sales) {- const container = document.getElementById('earnings-recent-sales');- if (!sales || sales.length === 0) {- container.innerHTML = '<p>No sales yet.</p>';- return;- }-- const table = document.createElement('table');- table.className = 'earnings-table';- table.innerHTML = `- <thead>- <tr>- <th>Date</th>- <th>Skill</th>- <th>Gross</th>- <th>Net</th>- </tr>- </thead>- <tbody>- ${sales.map(sale => `- <tr>- <td>${new Date(sale.created_at).toLocaleDateString()}</td>- <td>${escapeHtml(sale.skill_name)}</td>- <td>${formatCurrency(sale.gross_amount, sale.currency_mint)}</td>- <td>${formatCurrency(sale.net_amount, sale.currency_mint)}</td>- </tr>- `).join('')}- </tbody>- `;- container.innerHTML = '';- container.appendChild(table);-}--function formatCurrency(amount, mint) {- // Basic formatting, assuming 6 decimals for USDC- const value = (amount / 1e6).toFixed(2);- return `$${value} USDC`;-}-```diff --git a/docs/monetization/20-error-handling-frontend.md b/docs/monetization/20-error-handling-frontend.mddeleted file mode 100644index fe371dec4..000000000--- a/docs/monetization/20-error-handling-frontend.md+++ /dev/null@@ -1,76 +0,0 @@-# Prompt 20: Error Handling (Frontend)--## Objective-Implement robust and user-friendly error handling throughout the entire frontend purchase flow.--## Explanation-Things can go wrong during a purchase: the backend API might be down, the Solana network could be congested, or the user might close the modal prematurely. We need to catch these errors and provide clear, helpful feedback to the user instead of leaving them with a broken UI.--## Instructions-1. **Use `try...catch` Blocks:**- * Wrap all `fetch` calls and asynchronous operations in your payment logic (`src/marketplace.js`) within `try...catch` blocks.--2. **Display User-Friendly Messages:**- * When an error is caught, display a message to the user. Don't show raw technical errors like "TypeError: failed to fetch".- * Use a dedicated element in your payment modal or a global "toast" notification system.- * Messages should be actionable. For example:- * "Could not connect to the server. Please check your internet connection and try again."- * "Failed to create the transaction. Please try again in a few moments."- * "The transaction timed out. Please try again."--3. **Manage UI State:**- * Ensure that the UI is correctly reset after an error. For example, if an error occurs while generating the QR code, the loading spinner should be hidden, and the "Purchase" button should become clickable again.- * The payment modal should have a "Close" or "Cancel" button that properly cleans up any polling timers or pending states.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// In your handlePurchaseClick function--const modal = $('payment-modal');-const spinner = modal.querySelector('.spinner');-const errorMessageEl = modal.querySelector('.error-message');-let pollInterval = null; // Keep track of the timer--function showModalError(message) {- spinner.hidden = true;- errorMessageEl.textContent = message;-}--function cleanupModal() {- if (pollInterval) {- clearInterval(pollInterval);- pollInterval = null;- }- modal.close();- spinner.hidden = true;- errorMessageEl.textContent = '';-}--modal.querySelector('.close-modal-btn').addEventListener('click', cleanupModal);--// ...-try {- const response = await fetch('/api/payments/prepare-skill-purchase', { /* ... */ });-- if (!response.ok) {- // Handle specific HTTP errors from the backend- const errorData = await response.json().catch(() => ({})); // Gracefully handle non-JSON error bodies- throw new Error(errorData.error || `The server responded with status ${response.status}. Please try again.`);- }-- // ... (success path with polling)-- pollInterval = setInterval(/* ... */);- setTimeout(() => {- if (pollInterval) {- clearInterval(pollInterval);- showModalError("Confirmation timed out. Please check your wallet and transaction history.");- }- }, 300000);--} catch (error) {- console.error('Purchase failed:', error);- showModalError(error.message || 'An unexpected error occurred.');-}-```diff --git a/docs/monetization/20-referral-system.md b/docs/monetization/20-referral-system.mddeleted file mode 100644index 03aba0eb4..000000000--- a/docs/monetization/20-referral-system.md+++ /dev/null@@ -1,27 +0,0 @@-# Prompt 20: Referral System--## Objective-Design and implement a referral system where users can earn a percentage of sales by referring new customers to purchase skills or subscriptions.--## Explanation-Referral programs are a powerful growth marketing tool. By rewarding users for bringing in new customers, we can create a viral loop that accelerates platform adoption. This involves generating unique referral codes and tracking their usage.--## Instructions-1. **Database Schema:**- * Add a `referral_code` column to the `users` table, which should be a unique, randomly generated string.- * Create a new `referrals` table to track successful referrals. Columns should include `id`, `referrer_user_id`, `new_user_id`, `sale_id`, and `commission_earned`.--2. **Generate Referral Codes:**- * When a user signs up, generate a unique referral code for them and store it in their user record.--3. **Track Referrals:**- * When a new user visits the site via a referral link (e.g., `three.ws/?ref=UNIQUE_CODE`), store the referral code in a cookie or `localStorage`.- * When that new user eventually makes their first purchase, the backend should check for the referral code.- * If a valid referral code is present, record the referral in the `referrals` table.--4. **Split Payments for Commission:**- * The payment transaction logic from Prompt 19 needs to be updated again.- * If a sale is part of a referral, the transaction will now have **three** transfer instructions: one for the creator, one for the platform, and one for the referrer's commission.--5. **Referral Dashboard UI:**- * Create a new section in the user's dashboard where they can find their referral link and track how much commission they have earned.diff --git a/docs/monetization/20-usage-based-billing-model.md b/docs/monetization/20-usage-based-billing-model.mddeleted file mode 100644index 67ac24b80..000000000--- a/docs/monetization/20-usage-based-billing-model.md+++ /dev/null@@ -1,92 +0,0 @@-# Prompt 20: Usage-Based Billing Model--## Objective-Design the database schema and API structure to support usage-based ("pay-per-call") billing for specific agent skills.--## Explanation-Some skills are better monetized by charging for each use rather than a one-time purchase or subscription (e.g., a call to a powerful AI model, or a complex on-chain analysis). This requires a system to track usage, a way for users to pre-fund a balance, and a mechanism to deduct from that balance on each skill execution.--## Instructions-1. **Update `agent_skill_prices` Table:**- * Add a `billing_type` column (e.g., 'one_time', 'per_call').- * The `amount` would now represent the cost per execution for 'per_call' skills.--2. **Create `user_credit_balances` Table:**- * This table will store the pre-paid balance for each user.- * Columns: `user_id`, `balance_amount`, `currency_mint`.--3. **Implement a "Top Up" Flow:**- * Create a UI in the user's profile/dashboard to add credits.- * This will be a standard payment flow where the user transfers funds (e.g., USDC) to a company-owned treasury wallet. A backend endpoint will verify this transaction and update the user's balance in `user_credit_balances`.--4. **Modify Skill Execution Endpoint:**- * In the main skill execution endpoint, before running the skill, check its `billing_type`.- * If it's 'per_call', check if the user has sufficient balance in `user_credit_balances`.- * If they do, deduct the skill's `amount` from their balance *before* executing the skill. This must be an atomic operation.- * If they don't have enough balance, return an error (e.g., 402 Payment Required) with a message prompting them to top up their account.--## Database Schema Changes--```sql--- Add billing type to prices table-ALTER TABLE agent_skill_prices-ADD COLUMN billing_type TEXT NOT NULL DEFAULT 'one_time' CHECK (billing_type IN ('one_time', 'per_call'));---- New table for user credit balances-CREATE TABLE user_credit_balances (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID REFERENCES auth.users(id) NOT NULL UNIQUE,- balance_amount BIGINT NOT NULL DEFAULT 0,- currency_mint TEXT NOT NULL, -- For now, assume one currency like USDC- updated_at TIMESTAMPTZ DEFAULT NOW()-);-```--## Code Example (Skill Execution Endpoint Snippet)--```javascript-// Inside the skill execution endpoint, after checking basic access-// but before running the skill.--const { data: priceInfo } = await supabase.from('agent_skill_prices')- .select('amount, billing_type').eq('agent_id', agentId).eq('skill_name', skillName).single();--if (priceInfo && priceInfo.billing_type === 'per_call') {- // It's a pay-per-call skill, check and deduct balance.- // This should be done in a database transaction (RPC function in Supabase).-- const { error: deductError } = await supabase.rpc('deduct_skill_charge', {- user_id_in: userId,- charge_amount: priceInfo.amount- });-- if (deductError) {- // The RPC function would throw an error if balance is insufficient.- return error(res, 402, 'Payment Required: Insufficient credits for this skill.');- }-}--// ... proceed with skill execution ...-```--### Supabase RPC Function (`deduct_skill_charge`)--```sql-CREATE OR REPLACE FUNCTION deduct_skill_charge(user_id_in UUID, charge_amount BIGINT)-RETURNS void AS $$-DECLARE- current_balance BIGINT;-BEGIN- SELECT balance_amount INTO current_balance- FROM user_credit_balances WHERE user_id = user_id_in;-- IF current_balance IS NULL OR current_balance < charge_amount THEN- RAISE EXCEPTION 'Insufficient balance';- END IF;-- UPDATE user_credit_balances- SET balance_amount = balance_amount - charge_amount, updated_at = NOW()- WHERE user_id = user_id_in;-END;-$$ LANGUAGE plpgsql;-```diff --git a/docs/monetization/20_multiple_currencies.md b/docs/monetization/20_multiple_currencies.mddeleted file mode 100644index af6fff6b7..000000000--- a/docs/monetization/20_multiple_currencies.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 20: Support for Multiple Currencies--## Objective-Extend the monetization system to allow creators to set prices and users to pay in different SPL tokens (e.g., BONK, RENDER) in addition to USDC.--## Explanation-To increase flexibility and appeal to different communities, we should support more than just one currency. This requires changes to how prices are stored, how transactions are built, and how data is displayed.--## Instructions-1. **Currency Whitelist:**- * In the backend configuration, create a whitelist of supported SPL token mints. This should be a list of objects, each containing the mint address, symbol, name, and decimals. This prevents creators from listing arbitrary, untrusted tokens.--2. **Update UI for Setting Prices:**- * In the agent editor (`agent-edit.html`), the price input for each skill should now include a dropdown (`<select>`) menu next to the amount.- * This dropdown should be populated with the symbols of the whitelisted currencies.- * When saving, the chosen `currency_mint` is sent along with the `amount`.--3. **Update Purchase Preparation API:**- * The `purchase-prep` API now needs to handle the `currency_mint` of the skill being purchased.- * All the `spl-token` instructions must be created using the correct mint address from the skill's price data.--4. **Frontend Wallet Interaction:**- * The frontend needs to be aware of the currency being used. When preparing the purchase, it's good practice to check if the user has a sufficient balance of the required token *before* showing the sign prompt. This can be done using `connection.getTokenAccountBalance`.- * The UI should clearly display the correct currency symbol (e.g., "Purchase for 500 BONK").--5. **Update Creator Dashboard:**- * The sales data aggregation must now `GROUP BY currency_mint` to show total earnings for each currency separately.--## Code Example (Currency Whitelist)--```javascript-// In a config file, e.g., api/_lib/config.js-export const SUPPORTED_CURRENCIES = {- 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6a': {- symbol: 'USDC',- decimals: 6,- },- 'DezXAZ8z7PnrnRJjz3wXBoRgixCa6xjnB7YaB1pPB263': {- symbol: 'BONK',- decimals: 5,- }-};-```--## Code Example (Price Setting UI Change)--```javascript-// In agent-edit.js, when rendering price inputs-const selectHtml = `<select class="currency-select" data-skill-name="${skillName}">- ${Object.entries(SUPPORTED_CURRENCIES).map(([mint, {symbol}]) =>- `<option value="${mint}" ${price?.currency_mint === mint ? 'selected' : ''}>- ${symbol}- </option>`- ).join('')}-</select>`;--// The input group would now be: <input type="number"> and the <select>-```diff --git a/docs/monetization/21-affiliate-referral-program.md b/docs/monetization/21-affiliate-referral-program.mddeleted file mode 100644index 4ef9cb4e5..000000000--- a/docs/monetization/21-affiliate-referral-program.md+++ /dev/null@@ -1,21 +0,0 @@-----status: not-started------# Prompt 21: Affiliate/Referral Program--## Objective-Create a referral program that rewards users for bringing new customers to the platform.--## Explanation-A referral program can be a powerful engine for growth, incentivizing users to promote the marketplace.--## Instructions-1. **Generate Referral Codes:**- * Create a system to generate unique referral codes for each user.--2. **Track Referrals:**- * When a new user signs up or makes a purchase using a referral code, track this relationship in the database.--3. **Reward Referrers:**- * Implement a system to reward the referrer, for example, with a percentage of the referred user's first purchase, paid out as a platform credit or directly to their wallet.diff --git a/docs/monetization/21-affiliate-referral-system.md b/docs/monetization/21-affiliate-referral-system.mddeleted file mode 100644index a564ddaf2..000000000--- a/docs/monetization/21-affiliate-referral-system.md+++ /dev/null@@ -1,76 +0,0 @@-# Prompt 21: Affiliate/Referral System--## Objective-Design and implement a basic affiliate system where users can earn a commission for referring new users who purchase agent skills.--## Explanation-A referral system can be a powerful growth engine. This feature will allow users to generate a unique referral code. When a new user signs up using this code and makes a purchase, the original user (the affiliate) will receive a percentage of the sale. This incentivizes word-of-mouth marketing.--## Instructions-1. **Database Schema:**- * Add a `referral_code` column to the `users` table.- * Add a `referred_by` column (nullable foreign key to `users.id`) to the `users` table.- * Create a `referral_payouts` table to track commissions earned.--2. **UI for Affiliates:**- * In the user's dashboard, add a new "Affiliate" section.- * Display the user's unique referral link (e.g., `three.ws/register?ref=CODE`).- * Show stats: number of sign-ups, total purchase volume from referrals, and commission earned.--3. **Backend Logic:**- * **Registration:** When a user registers, check for a `ref` query parameter. If present and valid, store the referrer's user ID in the new user's `referred_by` column.- * **Purchase:** When a skill purchase is successfully verified, check if the purchaser was referred by someone.- * **Commission:** If they were, calculate the commission (e.g., 5% of the sale price) and create a record in the `referral_payouts` table for the affiliate.- * **Payouts:** Create a system (initially can be manual) for paying out earned commissions to affiliates' wallets.--## Database Schema Changes--```sql--- Add columns to your user table (e.g., auth.users)-ALTER TABLE auth.users-ADD COLUMN referral_code TEXT UNIQUE,-ADD COLUMN referred_by UUID REFERENCES auth.users(id);---- Initialize existing users with a referral code--- (Requires a function to generate unique codes)---- Table to track commissions-CREATE TABLE affiliate_earnings (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- affiliate_user_id UUID REFERENCES auth.users(id) NOT NULL,- originating_purchase_id UUID REFERENCES user_purchased_skills(id) NOT NULL,- commission_amount BIGINT NOT NULL,- commission_currency_mint TEXT NOT NULL,- status TEXT NOT NULL DEFAULT 'unpaid' CHECK (status IN ('unpaid', 'paid')),- created_at TIMESTAMPTZ DEFAULT NOW()-);-```--## Code Example (Purchase Verification Snippet)--```javascript-// Inside /api/marketplace/skills/verify-purchase.js-// After the purchase has been successfully recorded...--const { data: purchaser } = await supabase- .from('users') // or auth.users- .select('referred_by')- .eq('id', userId)- .single();--if (purchaser && purchaser.referred_by) {- const affiliateId = purchaser.referred_by;- const saleAmount = /* get price of the skill just sold */;- const commissionRate = 0.05; // 5%- const commissionAmount = Math.round(saleAmount * commissionRate);-- if (commissionAmount > 0) {- await supabase.from('affiliate_earnings').insert({- affiliate_user_id: affiliateId,- originating_purchase_id: newlyCreatedPurchaseRecord.id,- commission_amount: commissionAmount,- commission_currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyB7u6d' // USDC- });- }-}-```diff --git a/docs/monetization/21-loading-states-frontend.md b/docs/monetization/21-loading-states-frontend.mddeleted file mode 100644index 370610aec..000000000--- a/docs/monetization/21-loading-states-frontend.md+++ /dev/null@@ -1,86 +0,0 @@-# Prompt 21: Loading States (Frontend)--## Objective-Implement clear loading states throughout the marketplace and payment UI to provide feedback to the user during asynchronous operations.--## Explanation-A responsive UI should always inform the user when it's busy. Waiting for data to load or a process to complete without any visual feedback can make an application feel slow or broken. This task involves adding loading indicators (like spinners or skeleton screens) to all parts of the monetization feature that involve waiting.--## Instructions-1. **Agent Detail Page:**- * When the agent detail page is loading its data (including skill prices), display a skeleton UI. This means showing grayed-out placeholder boxes where the agent name, description, and skills will eventually appear. This provides a better perceived performance than a blank screen or a single large spinner.--2. **Payment Modal:**- * When the user clicks "Purchase" and the frontend is waiting for the backend to create the transaction, show a spinner in the center of the modal.- * The QR code and payment details should only appear after the API call is successful and the spinner is hidden.--3. **Buttons:**- * Disable buttons and show a loading state on them while their associated action is in progress. For example, the "Save Prices" button on the agent edit page should be disabled and could show text like "Saving..." to prevent double-clicks.--## CSS for Skeleton Loader--```css-.skeleton {- background-color: #2a2a36; /* A darker panel color */- border-radius: 4px;- animation: pulse 1.5s cubic-bezier(0.4, 0, 0.6, 1) infinite;-}--@keyframes pulse {- 50% {- opacity: .5;- }-}--/* Example usage for a skill entry */-.skill-entry-skeleton {- display: inline-block;- width: 120px;- height: 24px;- margin: 4px;-}-```--## HTML/JS for Skeleton State--```javascript-// In src/marketplace.js, before fetching the agent data--function showDetailSkeleton() {- $('d-skills').innerHTML = `- <span class="skill-entry-skeleton skeleton"></span>- <span class="skill-entry-skeleton skeleton"></span>- <span class="skill-entry-skeleton skeleton"></span>- `;- // Also show skeletons for agent name, description, etc.-}--async function renderDetail(id) {- showDetailSkeleton(); // Show skeleton first- try {- const agent = await fetchAgentData(id);- // ... then render the actual data- } catch (e) {- // ... handle error- }-}-```--## Button Loading State--```javascript-// In the save prices click handler-const saveBtn = document.getElementById('save-skill-prices-btn');-saveBtn.disabled = true;-saveBtn.textContent = 'Saving...';--try {- await savePrices();- showToast('Success!');-} catch (e) {- showToast('Error!', 'error');-} finally {- saveBtn.disabled = false;- saveBtn.textContent = 'Save Prices';-}-```diff --git a/docs/monetization/21-payout-system-ui.md b/docs/monetization/21-payout-system-ui.mddeleted file mode 100644index e7b581f21..000000000--- a/docs/monetization/21-payout-system-ui.md+++ /dev/null@@ -1,107 +0,0 @@-# Prompt 21: Payout System UI--## Objective-Create the user interface in the creator dashboard that allows creators to see their withdrawable balance and initiate a payout.--## Explanation-This is the frontend component of the payout system. It should clearly display how much money the creator can withdraw and provide a simple button to start the process. It also needs a way for creators to set the Solana wallet address where they want to receive their funds.--## Instructions-1. **File to Edit:**- * Open `agent-edit.html` and focus on the `#panel-earnings` section created in a previous prompt.--2. **Create Payouts UI Section:**- * Within the "Payout Settings" area of the earnings panel, add the following elements:- * An input field for the user to enter their Solana payout wallet address.- * A "Save Address" button.- * A display area to show the currently saved wallet address.- * A display for the "Withdrawable Balance". This should be the same value shown in the summary card at the top of the page.- * A "Withdraw Funds" button. This button should be disabled if the withdrawable balance is zero.--3. **Implement JavaScript Logic:**- * **Saving Wallet Address:**- * When "Save Address" is clicked, validate that the input contains a plausible Solana address (e.g., check length and characters).- * Make a `POST` request to a new backend endpoint (e.g., `/api/dashboard/payout-settings`) to save the user's payout address.- * **Initiating Withdrawal:**- * When "Withdraw Funds" is clicked:- * Show a confirmation dialog (`confirm()`) to prevent accidental withdrawals.- * If confirmed, make a `POST` request to a new backend endpoint (e.g., `/api/dashboard/request-payout`).- * The button should be disabled and show a "Processing..." state while waiting for the API response.- * On success, show a confirmation message to the user (e.g., "Payout initiated! It may take a few minutes to arrive.").- * On failure, show an error message.--## Code Example (Frontend - `agent-edit.html` HTML)--```html-<!-- Inside the #earnings-payouts div -->-<h4>Payout Wallet</h4>-<div class="form-group">- <label class="form-label">Your Solana Wallet Address</label>- <div class="payout-address-row">- <input class="form-input" id="payout-wallet-input" type="text" placeholder="Enter your SOL address...">- <button class="btn-secondary" id="save-wallet-btn">Save</button>- </div>- <div class="form-status" id="payout-wallet-status"></div>-</div>--<hr class="earnings-divider">--<h4>Withdraw</h4>-<div class="payout-withdraw-row">- <div>- <span class="label">Withdrawable Balance</span>- <span class="value" id="payout-withdrawable-balance">$0.00</span>- </div>- <button class="btn-primary" id="withdraw-btn" disabled>Withdraw Funds</button>-</div>-<div class="form-status" id="withdraw-status"></div>--```--## Code Example (Frontend - `agent-edit.html` JavaScript)--```javascript-// Add this logic to your earnings tab initialization--// Load and display current settings-function loadPayoutSettings(settings) {- const input = document.getElementById('payout-wallet-input');- if (settings.payout_address) {- input.value = settings.payout_address;- }- document.getElementById('payout-withdrawable-balance').textContent = formatCurrency(summary.withdrawable);- document.getElementById('withdraw-btn').disabled = summary.withdrawable <= 0;-}--// Save wallet button-document.getElementById('save-wallet-btn').addEventListener('click', async () => {- const address = document.getElementById('payout-wallet-input').value.trim();- // Add basic validation here-- // API call to save address- const res = await fetch('/api/dashboard/payout-settings', { /* ... */ });- // ... handle response and status message-});--// Withdraw button-document.getElementById('withdraw-btn').addEventListener('click', async () => {- if (!confirm('Are you sure you want to withdraw your available balance?')) return;-- const btn = document.getElementById('withdraw-btn');- const statusEl = document.getElementById('withdraw-status');- btn.disabled = true;- statusEl.textContent = 'Processing...';-- // API call to request payout- const res = await fetch('/api/dashboard/request-payout', { method: 'POST' });- if (res.ok) {- statusEl.textContent = 'Payout initiated!';- // Refresh earnings data to show updated balance- initEarningsTab();- } else {- const { error } = await res.json();- statusEl.textContent = `Error: ${error}`;- btn.disabled = false;- }-});-```diff --git a/docs/monetization/21-platform-fee-mechanism.md b/docs/monetization/21-platform-fee-mechanism.mddeleted file mode 100644index 0b14fc801..000000000--- a/docs/monetization/21-platform-fee-mechanism.md+++ /dev/null@@ -1,79 +0,0 @@-----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/21-transaction-status-notifications.md b/docs/monetization/21-transaction-status-notifications.mddeleted file mode 100644index 0e77734d7..000000000--- a/docs/monetization/21-transaction-status-notifications.md+++ /dev/null@@ -1,43 +0,0 @@-# Prompt 21: Transaction Status Notifications--## Objective-Provide real-time feedback to the user about the status of their purchase transaction, from initiation to final confirmation.--## Explanation-Blockchain transactions aren't instant. A user needs clear, immediate feedback to know that their payment is being processed and to be notified of success or failure. This builds trust and improves the user experience significantly.--## Instructions-1. **Update UI on Submission:**- * When the user clicks "Confirm Purchase" and approves the transaction in their wallet, immediately update the UI.- * Disable the purchase button and show a loading spinner with a message like "Processing transaction on the Solana blockchain..."--2. **Use Connection Methods for Status:**- * The `@solana/web3.js` `Connection` object provides methods to track transaction status.- * After sending the transaction with `sendTransaction`, you get a `signature`.- * Use `connection.confirmTransaction(signature, 'processed')`. The promise returned by this method will resolve when the transaction is processed but not yet finalized. You can update the UI here to "Processing..."- * You can then use a second confirmation with commitment level `'confirmed'` or `'finalized'` for the final success message.--3. **Display Success/Failure Messages:**- * On successful confirmation, hide the spinner and show a clear success message like, "Purchase complete! You now own the skill."- * If the transaction fails at any point (e.g., the promise from `sendTransaction` or `confirmTransaction` rejects), display a descriptive error message.- * Use a library like `notistack` or `react-hot-toast` (if using React) or a simple custom notification component to show these messages as non-modal popups.--## Code Example (Polling for Status)-```javascript-// ... after getting the signature-setUiLoading("Processing transaction...");--try {- const result = await connection.confirmTransaction(signature, 'processed');-- if (result.value.err) {- throw new Error('Transaction failed on-chain');- }-- setUiSuccess("Purchase confirmed! You can now use the skill.");- // Close the modal and update the UI to show ownership-} catch (error) {- console.error(error);- setUiError("Transaction failed. Please try again.");-}-```diff --git a/docs/monetization/21_nft_gating.md b/docs/monetization/21_nft_gating.mddeleted file mode 100644index 1d6b7fa74..000000000--- a/docs/monetization/21_nft_gating.md+++ /dev/null@@ -1,59 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 21: Gating Agent Access Based on NFT Ownership--## Objective-Implement a new monetization mechanism where creators can restrict access to their entire agent (or specific skills) to holders of a specific NFT collection.--## Explanation-Token-gating is a powerful web3-native monetization strategy. It builds community and provides utility for NFT holders. This feature will allow creators to specify an NFT collection's "Verified Creator" address (formerly known as `updateAuthority`), and our system will check if a user holds an NFT from that collection before granting access.--## Instructions-1. **Update UI for Gating Configuration:**- * In `agent-edit.html`, add a new section for "Access Control".- * Include an option to select "Token Gating" and an input field for the "NFT Collection Address" (this will be the Verified Creator address).--2. **Database Changes:**- * Add a column to the `agent_identities` table's `meta` field or a new table to store this gating rule (e.g., `meta.access_rule = { type: 'NFT_HOLD', collection_address: '...' }`).--3. **Backend - Gated Access Check:**- * This check should happen in the same place as the skill ownership check (e.g., `api/chat.js`).- * When a user tries to interact with a gated agent:- * **Fetch User's NFTs:** Use a Solana RPC provider or an indexing service like Helius or Shyft to get all NFTs owned by the user's wallet address. The RPC `getTokenAccountsByOwner` method combined with parsing can work, but indexers are far more efficient.- * **Verify Collection:** Iterate through the user's NFTs. For each NFT, fetch its metadata. The metadata (e.g., from an Arweave URL) will contain a `collection` field or a `creators` array. Check if the collection's `key` or one of the creator's `address` matches the `collection_address` specified by the agent creator.- * If a match is found, grant access.- * If no matching NFT is found, return a `403 Forbidden` error with a message like "You must hold an NFT from the required collection to use this agent."--## Code Example (Backend NFT Check Logic using an Indexer)--```javascript-// This is a conceptual example. The exact API will depend on the indexer used.-// Assume `userWalletAddress` and `requiredCollectionAddress` are known.--async function userHoldsNftFromCollection(userWalletAddress, requiredCollectionAddress) {- const HELIUS_API_URL = `https://api.helius.xyz/v0/addresses/${userWalletAddress}/nfts?api-key=...`;-- const response = await fetch(HELIUS_API_URL);- const data = await response.json();-- for (const nft of data.nfts) {- // Helius provides a verified collection address directly- const collectionInfo = nft.grouping.find(g => g.group_key === 'collection');- if (collectionInfo && collectionInfo.group_value === requiredCollectionAddress) {- return true; // Found a matching NFT- }- }-- return false; // No match found-}--// In the access control middleware/handler:-const isHolder = await userHoldsNftFromCollection(user.wallet_address, agent.meta.access_rule.collection_address);--if (!isHolder) {- return error(res, 403, 'nft_required', 'Access denied. NFT from required collection not found in your wallet.');-}-// Proceed...-```diff --git a/docs/monetization/22-backend-for-payouts.md b/docs/monetization/22-backend-for-payouts.mddeleted file mode 100644index 77b3f03ab..000000000--- a/docs/monetization/22-backend-for-payouts.md+++ /dev/null@@ -1,100 +0,0 @@-# Prompt 22: Backend for Payouts--## Objective-Create the backend infrastructure to process creator payout requests, batch earnings, and prepare the on-chain transaction.--## Explanation-This is the core of the payout system. The backend will be responsible for securely gathering all of a creator's unpaid earnings, marking them as "in-progress," and constructing a single Solana transaction to transfer the total amount to the creator's designated wallet.--## Instructions-1. **Create API Route for Payout Request:**- * Set up the endpoint `POST /api/dashboard/request-payout`.- * This endpoint must be authenticated.--2. **Implement Payout Logic:**- * **a. Get User and Settings:** Get the authenticated `user` and fetch their saved `payout_address` from the database. If no address is set, return a `400 Bad Request` error.- * **b. Lock Earnings and Calculate Total:**- * Start a database transaction.- * Find all records in `skill_payment_earnings` for this `creator_id` where `payout_id` is `NULL`.- * If there are no such earnings, return an error.- * Calculate the `total_net_amount` to be paid out. For simplicity, we'll assume a single currency (USDC) for now.- * **c. Create Payout Record:**- * Create a new record in the `payouts` table with a `pending` status, the `creator_id`, the `total_net_amount`, and the `destination_address`. Store the `payoutId`.- * **d. Associate Earnings with Payout:**- * Update all the earnings records you found in the previous step, setting their `payout_id` to the new `payoutId`. This "locks" them and prevents them from being included in future payouts.- * **e. Commit Transaction:** Commit the database transaction.- * **f. Process the Payout (Asynchronously):**- * The actual on-chain transaction should be handled by a separate, asynchronous process or queue. For this prompt, we can simulate it in a `setTimeout`.- * This background job will:- 1. Construct the `spl-token` transfer transaction from a platform-owned treasury/hot wallet to the creator's `payout_address`.- 2. Sign the transaction with the treasury wallet's key (this key must be securely stored on the server).- 3. Send and confirm the transaction.- 4. Update the `payouts` record with the `completed` status and the `tx_signature`.- * **g. Respond to Client:** Immediately after committing the DB transaction (step e), respond to the client with a success message. Do *not* wait for the on-chain part to finish.--## Code Example (Backend - `/api/dashboard/request-payout.js`)--```javascript-// --- Inside your API handler -----const user = await getAuthenticatedUser(req);--// a. Get user and settings-const payoutSettings = await db.getPayoutSettings(user.id);-if (!payoutSettings?.payout_address) {- return res.status(400).json({ error: 'Payout address not configured.' });-}--let payoutId;-try {- // b., c., d. Transactional logic- await db.transaction(async (trx) => {- const earningsToPay = await trx('skill_payment_earnings')- .where({ creator_id: user.id, payout_id: null })- .select('id', 'net_amount');-- if (earningsToPay.length === 0) {- throw new Error('No withdrawable balance.');- }-- const totalNetAmount = earningsToPay.reduce((sum, e) => sum + e.net_amount, 0);- const currencyMint = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'; // Assume USDC-- // c. Create Payout Record- const [newPayout] = await trx('payouts')- .insert({- creator_id: user.id,- amount: totalNetAmount,- currency_mint: currencyMint,- destination_address: payoutSettings.payout_address,- status: 'pending',- })- .returning('id');- payoutId = newPayout.id;-- // d. Associate Earnings- const earningIds = earningsToPay.map(e => e.id);- await trx('skill_payment_earnings')- .whereIn('id', earningIds)- .update({ payout_id: payoutId });- });--} catch (error) {- return res.status(400).json({ error: error.message });-}--// f. Trigger async payout processing-// DO NOT await this. This should be handled by a background worker queue (e.g., BullMQ, Celery).-// We simulate with a timeout for this example.-processPayout(payoutId);--// g. Respond to client immediately-res.status(202).json({ message: 'Payout initiated.', payoutId });---// --- In a separate background worker file ----async function processPayout(payoutId) {- // Fetch payout details, create/sign/send transaction, update status to 'completed'.- // This part is complex and involves secure key management for the treasury wallet.-}-```diff --git a/docs/monetization/22-creator-revenue-charts.md b/docs/monetization/22-creator-revenue-charts.mddeleted file mode 100644index 5d5cca52b..000000000--- a/docs/monetization/22-creator-revenue-charts.md+++ /dev/null@@ -1,118 +0,0 @@-----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/22-marketplace-analytics-dashboard.md b/docs/monetization/22-marketplace-analytics-dashboard.mddeleted file mode 100644index 1b76301d3..000000000--- a/docs/monetization/22-marketplace-analytics-dashboard.md+++ /dev/null@@ -1,83 +0,0 @@-# Prompt 22: Marketplace Analytics Dashboard--## Objective-Create a dedicated analytics page for the marketplace that displays key metrics about agent and skill performance.--## Explanation-To create a healthy and competitive marketplace, creators and the platform administrators need data. This analytics dashboard will provide insights into which agents are most popular, which skills are selling the most, and overall revenue trends. This helps creators understand what the market wants and helps administrators monitor the health of the economy.--## Instructions-1. **Create a New Page:**- * Create a new route and page, e.g., `marketplace/analytics.html`.- * Design the layout with charts and data tables.--2. **Backend Analytics Endpoint:**- * Create a new API endpoint, `/api/marketplace/analytics`.- * This endpoint will perform aggregation queries to calculate stats. It should be restricted to administrators or perhaps a subset of stats could be public.- * **Metrics to compute:**- * Total marketplace volume (in USD).- * Number of unique buyers.- * Number of unique sellers (creators with at least one sale).- * A time-series chart of daily/weekly sales volume.- * Top 10 best-selling agents (by revenue).- * Top 10 best-selling skills (by revenue).--3. **Frontend Visualization:**- * On the analytics page, fetch data from the new endpoint.- * Use a charting library (e.g., Chart.js, which is lightweight) to visualize the time-series data.- * Render the "Top 10" lists in styled tables.--## Code Example (Backend Analytics Endpoint - `/api/marketplace/analytics.js`)--```javascript-import { supabase } from '../../_lib/supabase';-import { json, error } from '../../_lib/http';--export default async function handler(req, res) {- // Add admin authentication check here-- // Example: Fetching top selling skills- const { data: topSkills, error: skillsError } = await supabase.rpc('get_top_selling_skills', { limit_count: 10 });-- if (skillsError) {- return error(res, 500, 'Failed to calculate analytics.');- }-- // Example: Fetching sales volume by day- const { data: salesVolume } = await supabase.rpc('get_daily_sales_volume');-- // ...fetch other metrics...-- return json(res, {- topSkills,- salesVolume,- // ...other data...- });-}-```--## Supabase RPC Function Example (`get_top_selling_skills`)--```sql-CREATE OR REPLACE FUNCTION get_top_selling_skills(limit_count INT)-RETURNS TABLE(skill_name TEXT, agent_id UUID, total_revenue BIGINT, total_sales BIGINT) AS $$-BEGIN- RETURN QUERY- SELECT- ups.skill_name,- ups.agent_id,- SUM(asp.amount) as total_revenue,- COUNT(ups.id) as total_sales- FROM- user_purchased_skills ups- JOIN- agent_skill_prices asp ON ups.agent_id = asp.agent_id AND ups.skill_name = asp.skill_name- GROUP BY- ups.skill_name, ups.agent_id- ORDER BY- total_revenue DESC- LIMIT- limit_count;-END;-$$ LANGUAGE plpgsql;-```diff --git a/docs/monetization/22-my-collection-page.md b/docs/monetization/22-my-collection-page.mddeleted file mode 100644index b08be866d..000000000--- a/docs/monetization/22-my-collection-page.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 22: "My Collection" Page--## Objective-Create a dedicated page where users can view all the premium skills and agent subscriptions they have purchased.--## Explanation-As users begin to acquire assets on the platform, they need a central place to view their collection. This page acts as their personal inventory, reinforcing the value of their purchases and providing easy access to the agents and skills they've unlocked.--## Instructions-1. **Create New Page:**- * Create a new HTML file, `collection.html`, and its corresponding JavaScript file, `src/collection.js`.- * This page must be accessible only to logged-in users.--2. **Backend API for Owned Assets:**- * Create a new backend endpoint, `/api/users/my-collection`.- * This endpoint will fetch all the assets owned by the currently logged-in user.- * It should query the database to find:- * All purchased skills (by looking at the `sales` table or by querying for their skill NFTs on-chain, though the database is faster).- * All active subscriptions from the `user_subscriptions` table.--3. **Frontend UI:**- * On page load, `src/collection.js` should call the `/api/users/my-collection` endpoint.- * The UI should be divided into two sections: "My Skills" and "My Subscriptions."- * For each skill, display its name, the agent it belongs to, and a link to that agent's page.- * For each subscription, display the agent's name, the subscription tier, and the renewal/expiry date.- * Design the page with clean cards or list items to make the collection easy to browse.--## Code Example (HTML Structure for `collection.html`)-```html-<h1>My Collection</h1>--<section>- <h2>My Subscriptions</h2>- <div id="subscriptions-list" class="collection-grid">- <!-- Subscription cards will be populated here -->- <div class="card">- <h3>Agent 'X' - Pro Tier</h3>- <p>Renews on: 2026-06-04</p>- <a href="/agent/x">View Agent</a>- </div>- </div>-</section>--<section>- <h2>My Skills</h2>- <div id="skills-list" class="collection-grid">- <!-- Skill cards will be populated here -->- <div class="card">- <h3>Skill: dance</h3>- <p>From: Agent 'Y'</p>- <a href="/agent/y">View Agent</a>- </div>- </div>-</section>-```diff --git a/docs/monetization/22-responsive-design-payment-modal.md b/docs/monetization/22-responsive-design-payment-modal.mddeleted file mode 100644index 36f3c8db9..000000000--- a/docs/monetization/22-responsive-design-payment-modal.md+++ /dev/null@@ -1,62 +0,0 @@-# Prompt 22: Responsive Design for Payment Modal--## Objective-Ensure the Solana Pay QR code modal and related monetization UI elements are fully responsive and usable on all screen sizes, especially mobile devices.--## Explanation-A significant portion of users, especially in the web3 space, may interact with the platform on mobile devices. The payment flow, in particular, is centered around mobile wallets. Therefore, the QR code must be easy to scan and the surrounding information must be legible on small screens.--## Instructions-1. **Use CSS Media Queries:**- * In your `marketplace.css` file, add `@media` queries to adjust the styling of the payment modal for smaller screens.--2. **Adjust Modal Size:**- * On mobile, the modal should likely take up the full width and a larger portion of the height of the screen to maximize space for the QR code.- * `width: 95vw; max-width: 400px;` is a common pattern.--3. **Optimize QR Code Size:**- * The QR code itself needs to be large enough to be easily scannable. You might need to adjust the `size` parameter passed to `createQR` based on the screen width, or simply use a larger default size that also works on desktop.--4. **Layout Changes:**- * Consider changing the layout of elements inside the modal on small screens. For example, a two-column layout on desktop might need to stack into a single column on mobile. Use flexbox properties like `flex-direction: column;`.--5. **Test Thoroughly:**- * Use your browser's developer tools to simulate various mobile device screen sizes (e.g., iPhone, Android devices) and test the entire purchase flow.--## CSS Example (`marketplace.css`)--```css-/* Base styles for the payment modal */-#payment-modal {- width: 450px;- padding: 24px;- border-radius: 12px;- /* ... other styles */-}--.qr-code-container {- width: 300px; /* default size */- height: 300px;- margin: 20px auto;-}---/* Media query for mobile devices */-@media (max-width: 600px) {- #payment-modal {- width: 90vw; /* Take up most of the screen width */- padding: 16px;- }-- .qr-code-container {- width: 80vw; /* Make QR code responsive to screen width */- height: 80vw;- max-width: 280px;- max-height: 280px;- }-- #payment-modal h2 {- font-size: 18px; /* Adjust font sizes for readability */- }-}-```diff --git a/docs/monetization/22-user-reviews-for-skills.md b/docs/monetization/22-user-reviews-for-skills.mddeleted file mode 100644index 8d9086c67..000000000--- a/docs/monetization/22-user-reviews-for-skills.md+++ /dev/null@@ -1,20 +0,0 @@-----status: not-started------# Prompt 22: User Reviews and Ratings for Skills--## Objective-Allow users to leave reviews and ratings for the skills they have purchased.--## Explanation-Social proof is a powerful factor in purchasing decisions. Reviews and ratings will help users identify high-quality skills and build trust in the marketplace.--## Instructions-1. **Update Database Schema:**- * Create a `skill_reviews` table with columns for `skill_name`, `user_id`, `rating` (1-5), and a `comment`.--2. **UI for Reviews:**- * On the agent detail page, display the average rating for each skill.- * Add a section where users can read all reviews for a skill.- * Allow users who have purchased a skill to submit a review.diff --git a/docs/monetization/22_skill_subscriptions.md b/docs/monetization/22_skill_subscriptions.mddeleted file mode 100644index a9fceaa72..000000000--- a/docs/monetization/22_skill_subscriptions.md+++ /dev/null@@ -1,55 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 22: Skill Subscriptions (Recurring Revenue)--## Objective-Introduce a subscription model for skills, allowing creators to earn recurring revenue. Users can subscribe to a skill for a monthly fee to maintain access.--## Explanation-One-time purchases are great, but subscriptions provide creators with a predictable income stream and encourage them to keep their skills updated. This is a significant architectural addition, requiring a system to manage subscription state and handle recurring payments. For Solana, we can't use traditional server-side billing, so we'll model it as a system of time-limited access tokens that the user must renew.--## Instructions-1. **Database Schema for Subscriptions:**- * Create a `skill_subscriptions` table:- * `id`: Primary key.- * `user_id`, `agent_id`, `skill_name`: Foreign keys.- * `expires_at`: A timestamp indicating when the current subscription period ends.- * `status`: An enum (e.g., `'active'`, `'expired'`, `'cancelled'`).- * `last_payment_signature`: The signature of the latest renewal transaction.--2. **Update UI for Price Setting:**- * In `agent-edit.html`, allow creators to specify a price as "one-time" or "monthly."- * If monthly, they set a monthly price. This gets stored in `agent_skill_prices` with a new column, e.g., `billing_interval: 'monthly'`.--3. **Modify Purchase Flow:**- * When a user "subscribes," the purchase flow is the same as a one-time purchase.- * However, upon successful confirmation in `purchase-confirm`, a record is created in the `skill_subscriptions` table instead of `user_purchased_skills`. The `expires_at` is set to 30 days from now.--4. **Update Access Control Logic:**- * The skill ownership check (`api/chat.js`) must now also check the `skill_subscriptions` table.- * If a user has an 'active' subscription and `expires_at` is in the future, they are granted access.- * If `expires_at` is in the past, their status should be considered 'expired', and they should be denied access.--5. **Renewal UI:**- * In the marketplace UI, if a user has an expired subscription, the "Purchase" button should reappear as "Renew Subscription."- * Clicking it triggers the same purchase flow, which, upon confirmation, updates the `expires_at` timestamp for the existing subscription record.--## SQL Example (`skill_subscriptions` table)--```sql-CREATE TABLE IF NOT EXISTS skill_subscriptions (- id UUID PRIMARY KEY DEFAULT gen_random_uuid(),- user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,- agent_id UUID NOT NULL REFERENCES agent_identities(id) ON DELETE CASCADE,- skill_name VARCHAR(255) NOT NULL,- expires_at TIMESTAMPTZ NOT NULL,- status VARCHAR(50) NOT NULL DEFAULT 'active', -- e.g., 'active', 'expired'- last_payment_signature VARCHAR(128),- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),-- UNIQUE(user_id, agent_id, skill_name)-);-```diff --git a/docs/monetization/23-e2e-testing-purchase-flow.md b/docs/monetization/23-e2e-testing-purchase-flow.mddeleted file mode 100644index a4a7852c7..000000000--- a/docs/monetization/23-e2e-testing-purchase-flow.md+++ /dev/null@@ -1,78 +0,0 @@-# Prompt 23: E2E Testing for Purchase Flow--## Objective-Write an end-to-end (E2E) test using a framework like Playwright or Cypress to simulate and validate the entire skill purchase flow.--## Explanation-As the monetization feature becomes more complex, manual testing becomes time-consuming and prone to error. An automated E2E test will ensure the core purchase functionality remains stable as we add new features or refactor code. This test will mock the blockchain interaction but validate the entire UI and API flow.--## Instructions-1. **Set Up the Test Environment:**- * Ensure you have Playwright or your chosen E2E testing framework installed and configured in the project.- * You will need to set up a test that can handle authentication, likely by pre-setting an auth token in local storage.--2. **Mock the Backend API:**- * The test should not make real payments. You need to mock the API endpoints.- * Mock `/api/payments/prepare-skill-purchase`: It should return a fake, but correctly structured, Solana Pay transaction response.- * Mock `/api/payments/check-purchase-status`: The test should control this endpoint's response, initially returning `{ status: 'pending' }` and later switching to `{ status: 'confirmed' }` to simulate a successful purchase.--3. **Write the Test Script:**- * The test should perform the following steps:- 1. Navigate to a specific agent's marketplace page.- 2. Verify that the "Purchase" button is visible for a paid skill.- 3. Click the "Purchase" button.- 4. Assert that the payment modal appears and the QR code is rendered.- 5. Trigger the mock API to switch to a "confirmed" status.- 6. Wait for the polling mechanism to detect the change.- 7. Assert that the modal closes automatically.- 8. Assert that the "Purchase" button has been replaced with the "Owned" status indicator on the main page.--## Test Script Example (Playwright)--```javascript-// tests/monetization.spec.ts-import { test, expect } from '@playwright/test';--test.describe('Skill Purchase Flow', () => {- test('should allow a user to successfully purchase a skill', async ({ page }) => {- const agentId = 'some-test-agent-id';- const skillName = 'TestSkill';-- // Mock the backend APIs before navigating- await page.route(`/api/payments/prepare-skill-purchase`, async route => {- const json = {- transaction: 'fake-serialized-transaction-base64',- message: 'Test Purchase',- reference: 'test-reference-123',- };- await route.fulfill({ json });- });-- let purchaseStatus = 'pending';- await page.route(`/api/payments/check-purchase-status?reference=test-reference-123`, async route => {- await route.fulfill({ json: { status: purchaseStatus } });- });-- // 1. Navigate to the page- await page.goto(`/marketplace/agent/${agentId}`);-- // 2. Find and click the purchase button- const purchaseButton = page.locator(`.purchase-skill-btn[data-skill-name="${skillName}"]`);- await expect(purchaseButton).toBeVisible();- await purchaseButton.click();-- // 3. Assert modal and QR code are visible- await expect(page.locator('#payment-modal')).toBeVisible();- await expect(page.locator('.qr-code-container svg')).toBeVisible();-- // 4. Simulate the successful payment confirmation- purchaseStatus = 'confirmed';-- // 5. Assert that the modal closes and the UI updates- await expect(page.locator('#payment-modal')).not.toBeVisible({ timeout: 10000 }); // Wait for poll- const ownedIndicator = page.locator(`.skill-owned:has-text("Owned")`);- await expect(ownedIndicator).toBeVisible();- await expect(purchaseButton).not.toBeVisible();- });-});-```diff --git a/docs/monetization/23-email-and-in-app-notifications.md b/docs/monetization/23-email-and-in-app-notifications.mddeleted file mode 100644index ac2ae83cf..000000000--- a/docs/monetization/23-email-and-in-app-notifications.md+++ /dev/null@@ -1,70 +0,0 @@-# Prompt 23: Email and In-App Notifications--## Objective-Implement a notification system to alert users and creators about important monetization events, such as a new sale or a subscription renewal.--## Explanation-To create an engaging user experience, the platform should proactively inform users about events relevant to them. For creators, a "You've made a sale!" notification is highly motivating. For users, a receipt or a reminder about an upcoming subscription renewal is essential. This task involves setting up the infrastructure for both in-app and email notifications.--## Instructions-1. **Choose a Notification Service:**- * For emails, we can integrate a transactional email service like Resend, SendGrid, or Postmark.- * For in-app notifications, we'll create a new database table and a UI component.--2. **Database Schema for In-App Notifications:**- * Create a `notifications` table.- * Columns: `id`, `user_id` (who the notification is for), `type` (e.g., 'sale_made', 'skill_purchased'), `message`, `is_read`, `link_url` (e.g., link to the transaction), `created_at`.--3. **Backend Integration:**- * In the backend logic where monetization events occur (e.g., in `verify-purchase.js`), add calls to a new notification helper function.- * This function, `createNotification(userId, type, data)`, will:- * Insert a record into the `notifications` table.- * (Optional) Trigger an email to be sent via the chosen email service.--4. **Frontend UI:**- * Add a "notification bell" icon to the main site header.- * When clicked, it should show a dropdown or a dedicated page listing the user's unread notifications, fetched from a new `/api/notifications` endpoint.- * Clicking a notification should mark it as read and, if it has a `link_url`, navigate the user there.--## Code Example (Backend Notification Trigger)--```javascript-// /api/_lib/notifications.js-import { supabase } from './supabase';-// import { Resend } from 'resend';-// const resend = new Resend(process.env.RESEND_API_KEY);--export async function createSaleNotification(purchase) {- // Notify the creator- const creatorMessage = `You sold the skill "${purchase.skillName}" for agent "${purchase.agentName}"!`;- await supabase.from('notifications').insert({- user_id: purchase.creatorId,- type: 'sale_made',- message: creatorMessage,- link_url: `/marketplace/agents/${purchase.agentId}`- });- // await resend.emails.send({ ... });-- // Notify the buyer- const buyerMessage = `You successfully purchased the skill "${purchase.skillName}".`;- await supabase.from('notifications').insert({- user_id: purchase.buyerId,- type: 'skill_purchased',- message: buyerMessage,- link_url: `/users/me/library`- });- // await resend.emails.send({ ... }); // Send receipt-}--// In /api/marketplace/skills/verify-purchase.js-// After successfully verifying and recording a purchase...-import { createSaleNotification } from '../../_lib/notifications';--await createSaleNotification({- creatorId: agent.creator_id,- buyerId: userId,- skillName: skillName,- agentName: agent.name,- agentId: agentId,-});-```diff --git a/docs/monetization/23-gifting-skills.md b/docs/monetization/23-gifting-skills.mddeleted file mode 100644index ac64711e0..000000000--- a/docs/monetization/23-gifting-skills.md+++ /dev/null@@ -1,55 +0,0 @@-# Prompt 23: Gifting Skills--## Objective-Implement a feature that allows a user to purchase a skill and have the ownership NFT sent to another user's wallet address.--## Explanation-Gifting is a powerful social and commercial feature. It allows users to introduce others to the platform and expands the potential market for creators' skills.--## Instructions-1. **Add "Gift" Option to UI:**- * In the purchase modal (from Prompt 3), add a checkbox or button that says "This is a gift."- * When checked, reveal a new input field for the user to enter the recipient's Solana wallet address.--2. **Modify Backend Minting Logic:**- * Update the `/api/skills/mint` endpoint (from Prompt 7).- * The endpoint should now optionally accept a `recipient_address` in the request body.- * If `recipient_address` is provided, the backend must use *that* address as the owner when minting the NFT.- * If it's not provided, it should default to the wallet address of the user making the purchase (the `user_wallet`).--3. **Update Frontend Request:**- * In `src/marketplace.js`, when the purchase is confirmed, check if the gift option is enabled.- * If it is, validate the recipient address on the frontend, and then include it in the body of the `fetch` request to the `/api/skills/mint` endpoint.--4. **Transaction Payer:**- * The transaction for the *payment* is still paid and signed by the person buying the gift. The only thing that changes is the *destination address* for the NFT being minted.--## Code Example (Frontend `marketplace.js`)-```javascript-// Inside the 'Confirm Purchase' click handler-const isGift = document.getElementById('gift-checkbox').checked;-let recipientAddress = null;--if (isGift) {- const input = document.getElementById('recipient-address-input');- // Validate the address- try {- new PublicKey(input.value);- recipientAddress = input.value;- } catch (e) {- alert('Invalid recipient address');- return;- }-}--// ... after payment is confirmed, call the mint endpoint-const response = await fetch('/api/skills/mint', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({- // ... other params like agent_id, skill_name- user_wallet: wallet.publicKey.toBase58(),- recipient_address: recipientAddress // will be null if not a gift- })-});-```diff --git a/docs/monetization/23-on-chain-royalties.md b/docs/monetization/23-on-chain-royalties.mddeleted file mode 100644index 8d7c070e4..000000000--- a/docs/monetization/23-on-chain-royalties.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 23: On-Chain Royalties for Skills--## Objective-Use an NFT-based approach to represent skill ownership, enabling on-chain royalties for creators.--## Explanation-This is a more decentralized and advanced approach to monetization. Each purchased skill could be represented as an NFT in the user's wallet. The NFT's metadata would grant access to the skill, and royalties could be enforced at the smart contract level.--## Instructions-1. **Smart Contract Development:**- * Develop a smart contract (e.g., using Anchor for Solana) that can mint "Skill NFTs".- * The contract would handle the logic for purchasing and transferring these NFTs.- * Implement the Metaplex protocol for on-chain royalties, so that every time a Skill NFT is resold on a secondary market, the original creator gets a percentage.--2. **Frontend Integration:**- * The frontend would interact with this smart contract instead of a traditional backend API for purchases.--3. **Access Control:**- * The access control middleware would check the user's wallet for the presence of the required Skill NFT.diff --git a/docs/monetization/23-skill-gating-api.md b/docs/monetization/23-skill-gating-api.mddeleted file mode 100644index c95fa9de6..000000000--- a/docs/monetization/23-skill-gating-api.md+++ /dev/null@@ -1,87 +0,0 @@-----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/23-ui-payout-wallet-config.md b/docs/monetization/23-ui-payout-wallet-config.mddeleted file mode 100644index 5f4eb6a64..000000000--- a/docs/monetization/23-ui-payout-wallet-config.md+++ /dev/null@@ -1,104 +0,0 @@-# Prompt 23: UI for Payout Wallet Configuration--## Objective-Implement the UI and the corresponding backend endpoint for creators to securely save and update their Solana payout wallet address.--## Explanation-Before creators can receive payouts, they must specify where the funds should be sent. This prompt covers creating a simple form for this purpose and the API to persist this setting.--## Instructions-1. **Database Schema:**- * Ensure your `users` table (or a related `user_settings` table) has a column to store the payout address, e.g., `payout_sol_address` (nullable `VARCHAR`).--2. **File to Edit (Frontend):**- * Open `agent-edit.html` and its associated JavaScript. Focus on the "Payout Settings" section of the "Earnings" tab.--3. **Implement Frontend Logic:**- * **Display Current Address:** When the earnings tab loads, the data from `/api/dashboard/earnings` should include the user's currently saved `payout_address`. Display this in or below the input field.- * **Save Button Event Listener:**- * Attach a `click` event listener to the "Save Address" button (`#save-wallet-btn`).- * When clicked, get the value from the input field (`#payout-wallet-input`).- * **Validation:** Perform basic client-side validation. A simple check is to ensure the address is between 32 and 44 characters and contains only Base58 characters. For a more robust check, you could use a library.- * If valid, make a `POST` request to a new `/api/dashboard/payout-settings` endpoint.- * Display status messages (e.g., "Saving...", "Saved!", "Invalid address.") in the status element (`#payout-wallet-status`).--4. **Create Backend Endpoint (Backend):**- * Create the new endpoint: `POST /api/dashboard/payout-settings`.- * **Authentication:** Ensure the user is authenticated.- * **Validation:**- * The request body should contain the `address`.- * Perform robust server-side validation to ensure it's a valid Solana public key. You can do this by trying to construct a `new PublicKey(address)` from `@solana/web3.js` inside a try-catch block.- * **Database Update:** Update the `payout_sol_address` column for the authenticated user in your `users` (or `user_settings`) table.- * Return a success message.--## Code Example (Frontend - `agent-edit.html` script)--```javascript-// In the script for agent-edit.html--const saveWalletBtn = document.getElementById('save-wallet-btn');-const walletInput = document.getElementById('payout-wallet-input');-const walletStatus = document.getElementById('payout-wallet-status');--saveWalletBtn.addEventListener('click', async () => {- const address = walletInput.value.trim();-- // Basic client-side validation- if (address.length < 32 || address.length > 44) {- walletStatus.textContent = 'Invalid address length.';- return;- }-- walletStatus.textContent = 'Saving...';- saveWalletBtn.disabled = true;-- try {- const res = await fetch('/api/dashboard/payout-settings', {- method: 'POST',- headers: { 'Content-Type': 'application/json' },- body: JSON.stringify({ address: address })- });-- if (!res.ok) {- const { error } = await res.json();- throw new Error(error || 'Failed to save.');- }-- walletStatus.textContent = 'Saved!';- } catch (err) {- walletStatus.textContent = `Error: ${err.message}`;- } finally {- saveWalletBtn.disabled = false;- }-});-```--## Code Example (Backend - `/api/dashboard/payout-settings.js`)--```javascript-import { PublicKey } from '@solana/web3.js';--// --- Inside your API handler -----const { address } = req.body;-const user = await getAuthenticatedUser(req);--// Server-side validation-try {- // This will throw an error if the address is not a valid base58 string- new PublicKey(address);-} catch (error) {- return res.status(400).json({ error: 'Invalid Solana address format.' });-}--try {- // Update the user's record in the database- await db('users')- .where({ id: user.id })- .update({ payout_sol_address: address });-- res.status(200).json({ message: 'Payout address updated.' });-} catch (dbError) {- res.status(500).json({ error: 'Database error.' });-}-```diff --git a/docs/monetization/23_free_trials.md b/docs/monetization/23_free_trials.mddeleted file mode 100644index 5f1d3e478..000000000--- a/docs/monetization/23_free_trials.md+++ /dev/null@@ -1,64 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 23: Free Trials for Subscriptions--## Objective-Allow creators to offer a limited-time free trial for their subscription-based skills to attract more users.--## Explanation-Free trials are a proven strategy for converting users to paid subscribers. This feature lets a user try a skill for a set period (e.g., 7 days) without paying. After the trial, they must subscribe to retain access.--## Instructions-1. **Update Price Setting UI:**- * In `agent-edit.html`, next to the monthly subscription price setting, add a checkbox and an input for "Offer free trial" and "Trial days".--2. **Database Changes:**- * In the `agent_skill_prices` table, add a new column, `trial_days` (integer).- * In the `skill_subscriptions` table, add a `is_in_trial` boolean flag.--3. **Implement Trial Activation Flow:**- * In the marketplace UI, for a skill with a trial, the button should say "Start Free Trial."- * Clicking this button will NOT trigger a payment transaction. Instead, it will call a new, simple API endpoint, e.g., `POST /api/skills/start-trial`.- * This endpoint verifies the user hasn't already used a trial for this skill.- * It then creates a record in the `skill_subscriptions` table with `is_in_trial = true`, `status = 'active'`, and `expires_at` set to `NOW() + trial_days`.--4. **Update Access Control Logic:**- * The existing subscription check already verifies `status = 'active'` and `expires_at` > `NOW()`, so it will automatically grant access to users in their trial period.--5. **UI for Conversion:**- * When a user is in a trial, the marketplace UI for that skill should change. Instead of "Purchase," it should show a message like "Trial active: X days remaining" and a button to "Subscribe Now."- * If the trial expires, the button reverts to "Subscribe." The access control logic will automatically block them until they pay.--## Code Example (Trial Activation Endpoint)--```javascript-// POST /api/skills/start-trial-export default wrap(async (req, res) => {- // ... auth, validation for agent_id, skill_name- const user = await getSessionUser(req);-- // 1. Check if skill offers a trial- const [skillPrice] = await sql`- SELECT trial_days FROM agent_skill_prices- WHERE agent_id = ${agent_id} AND skill_name = ${skill_name} AND trial_days > 0- `;- if (!skillPrice) return error(res, 400, 'no_trial_offered');-- // 2. Check if user already had a subscription/trial for this skill- const [existingSub] = await sql`- SELECT id FROM skill_subscriptions WHERE ...- `;- if (existingSub) return error(res, 409, 'trial_already_used');-- // 3. Create the trial subscription record- const expiresAt = new Date(Date.now() + skillPrice.trial_days * 24 * 60 * 60 * 1000);- await sql`- INSERT INTO skill_subscriptions (user_id, agent_id, skill_name, expires_at, status, is_in_trial)- VALUES (${user.id}, ${agent_id}, ${skill_name}, ${expiresAt}, 'active', true)- `;-- return json(res, 201, { success: true, expires_at: expiresAt });-});-```diff --git a/docs/monetization/24-analytics-and-tracking.md b/docs/monetization/24-analytics-and-tracking.mddeleted file mode 100644index 679148791..000000000--- a/docs/monetization/24-analytics-and-tracking.md+++ /dev/null@@ -1,82 +0,0 @@-# Prompt 24: Analytics and Tracking--## Objective-Integrate analytics events to track key user interactions throughout the monetization funnel, providing insights into user behavior and conversion rates.--## Explanation-To understand how users are interacting with the new payment features and to identify potential drop-off points, we need to track key events. This data is invaluable for making informed decisions on how to improve the feature. We can use a service like Segment, Amplitude, or a simple internal logging system.--## Instructions-1. **Choose an Analytics Provider:**- * Select and set up an analytics service. For this example, we'll assume a simple global `analytics.track()` function is available (often provided by a Segment or similar script).--2. **Define Key Events:**- * Identify the most important events to track in the monetization funnel:- * `Skill Purchase Initiated`: Fired when a user clicks the "Purchase" button.- * `Payment QR Code Displayed`: Fired when the QR code is successfully rendered.- * `Skill Purchase Succeeded`: Fired when the frontend confirms a successful purchase.- * `Skill Purchase Failed`: Fired when any error occurs during the process.- * `Skill Prices Saved`: Fired when a creator successfully saves new prices.--3. **Implement Tracking Calls (Frontend):**- * In your frontend JavaScript (`src/marketplace.js`, `src/agent-edit.js`), call `analytics.track()` at the appropriate points in the code.- * Include relevant properties with each event, such as `agentId`, `skillName`, `price`, and `currency`.--## Code Example (Frontend - `src/marketplace.js`)--```javascript-// This is a placeholder for your analytics library's API-// e.g., window.analytics.track(...)-const trackEvent = (eventName, properties) => {- console.log('[Analytics]', eventName, properties);- // In a real app, this would send data to Segment, Amplitude, etc.- if (window.analytics) {- window.analytics.track(eventName, properties);- }-};--// In handlePurchaseClick function-async function handlePurchaseClick(event) {- // ...- const skillName = button.dataset.skillName;- const agentId = /* ... */;- const price = /* ... get price ... */;-- // 1. Track when the purchase is initiated- trackEvent('Skill Purchase Initiated', {- agentId: agentId,- skillName: skillName,- price: price,- currency: 'USDC',- });-- try {- // ... (API call to prepare purchase)-- // 2. Track when the QR code is shown- trackEvent('Payment QR Code Displayed', {- agentId: agentId,- skillName: skillName,- });-- // ... (Polling logic)- if (status === 'confirmed') {- // 3. Track successful purchase- trackEvent('Skill Purchase Succeeded', {- agentId: agentId,- skillName: skillName,- price: price,- });- }-- } catch (error) {- // 4. Track failure- trackEvent('Skill Purchase Failed', {- agentId: agentId,- skillName: skillName,- error: error.message,- });- // ...- }-}-```diff --git a/docs/monetization/24-dynamic-pricing.md b/docs/monetization/24-dynamic-pricing.mddeleted file mode 100644index 620131f2d..000000000--- a/docs/monetization/24-dynamic-pricing.md+++ /dev/null@@ -1,20 +0,0 @@-----status: not-started------# Prompt 24: Dynamic Pricing--## Objective-Allow creators to set dynamic pricing rules for their skills, for example, based on demand or time.--## Explanation-Dynamic pricing can help creators maximize their revenue. For example, they could offer a discount for the first 100 buyers or increase the price as the skill becomes more popular.--## Instructions-1. **UI for Pricing Rules:**- * In the creator UI, add an advanced section for setting up pricing rules.- * Example rules: "First 100 purchases cost X", "Price increases by Y after every Z sales".--2. **Backend Logic:**- * The backend will need a rules engine to calculate the current price of a skill based on these rules and the sales history.- * This will be a complex piece of logic that needs to be carefully designed and tested.diff --git a/docs/monetization/24-end-to-end-monetization-testing.md b/docs/monetization/24-end-to-end-monetization-testing.mddeleted file mode 100644index 3dd6e3fc1..000000000--- a/docs/monetization/24-end-to-end-monetization-testing.md+++ /dev/null@@ -1,79 +0,0 @@-# Prompt 24: End-to-End Monetization Testing--## Objective-Write a suite of end-to-end (E2E) tests to validate the entire skill monetization flow, from a user connecting their wallet to a creator seeing the sale in their dashboard.--## Explanation-The monetization flow is complex, involving multiple frontend components, backend APIs, database interactions, and on-chain transactions. Manual testing is error-prone and time-consuming. An automated E2E test suite using a framework like Playwright is essential to ensure the system is robust, secure, and reliable, especially before and after deploying changes.--## Instructions-1. **Set up Playwright:**- * If not already in the project, add Playwright: `npm install -D playwright`.- * Configure it in `playwright.config.js`. You'll need to set up a base URL and potentially a test user account.--2. **Set up a Test Wallet:**- * The tests will need a Solana wallet with devnet funds. The private key for this test wallet can be stored as a secret environment variable and used to programmatically sign transactions during the test run.--3. **Write Test Scenarios:**- * Create a new test file, e.g., `tests/monetization.spec.js`.- * **Scenario 1: One-Time Purchase**- * `test.beforeAll()`: Create a test agent and a test creator user via API. Set a price on one of the agent's skills.- * Test that a guest user cannot purchase the skill.- * Test that a logged-in user can connect their wallet, navigate to the agent, click the skill, confirm, and "sign" the transaction. (Playwright can mock the wallet interaction).- * Test that after purchase, the skill appears as "owned".- * Test that the creator can log in and see the sale in their earnings dashboard.- * **Scenario 2: Subscription**- * Similar setup, but test subscribing to a tier.- * Test that the user gains access to all skills within that tier.- * Test that access is revoked after the subscription period ends (requires time-mocking or a special test setup).--## Playwright Test Example (`tests/monetization.spec.js`)--```javascript-import { test, expect } from '@playwright/test';-import { login, createTestAgent } from './test-helpers'; // Assume helper functions exist--test.describe('Skill Monetization E2E', () => {- let agentId;- let creatorToken;- const skillName = 'premium_skill';-- test.beforeAll(async ({ request }) => {- // Create a creator and an agent with a priced skill- const creator = await login(request, 'creator');- creatorToken = creator.token;- const agent = await createTestAgent(request, creatorToken, {- skills: [{ name: skillName }],- prices: { [skillName]: { amount: 1000000, currency_mint: 'USDC_MINT' } }- });- agentId = agent.id;- });-- test('a user can purchase a skill', async ({ page, context }) => {- // Login as a buyer- const buyer = await login(context);-- // TODO: Inject a mock wallet into the browser context for the buyer- // This is an advanced setup but crucial for testing.-- await page.goto(`/marketplace/agents/${agentId}`);-- // Find the skill and its price badge- const skillEntry = page.locator('.skill-entry', { hasText: skillName });- await expect(skillEntry.locator('.price-paid')).toBeVisible();-- // Click to open purchase modal- await skillEntry.click();- await expect(page.locator('#purchaseModal')).toBeVisible();-- // Click "Buy Now"- await page.locator('#confirmPurchaseBtn').click();-- // The test would now need to handle the mock wallet signing prompt- // and wait for the post-purchase confirmation.-- // Assert that the UI updates to show ownership- await expect(page.locator('.skill-entry', { hasText: skillName }).locator('.owned-badge')).toBeVisible();- });-});-```diff --git a/docs/monetization/24-skill-bundles.md b/docs/monetization/24-skill-bundles.mddeleted file mode 100644index 79a86465e..000000000--- a/docs/monetization/24-skill-bundles.md+++ /dev/null@@ -1,94 +0,0 @@-----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/24-skill-bundling.md b/docs/monetization/24-skill-bundling.mddeleted file mode 100644index ce8ea4329..000000000--- a/docs/monetization/24-skill-bundling.md+++ /dev/null@@ -1,42 +0,0 @@-# Prompt 24: Skill Bundling--## Objective-Allow creators to bundle multiple skills together for a single, often discounted, price.--## Explanation-Bundles are a classic marketing strategy. They increase the average transaction value for creators and provide better value for users who want to acquire multiple skills from a single agent.--## Instructions-1. **Database Schema for Bundles:**- * Create a `skill_bundles` table. Columns should include `id`, `agent_id`, `name`, `price`, `currency_mint`.- * Create a `bundle_items` table to link bundles to skills. Columns: `id`, `bundle_id`, `skill_name`.--2. **UI for Creating Bundles:**- * In the creator dashboard, add a new section for "Manage Bundles."- * Here, a creator can create a new bundle, give it a name and price, and select which of their existing skills to include in it.--3. **Backend API for Bundles:**- * Create CRUD endpoints (`/api/agents/:id/bundles`) for creating, updating, and deleting skill bundles.--4. **Display Bundles in Marketplace:**- * On the agent detail page, display any available bundles, perhaps in their own section above the individual skills.- * Each bundle should show its name, price, and the list of skills included.- * Add a "Purchase Bundle" button.--5. **Purchase Logic for Bundles:**- * When a bundle is purchased, the payment logic is the same (transferring the bundle price).- * However, the minting logic is different. After the payment is confirmed, the `/api/skills/mint` endpoint must be called in a loop, once for **each skill** included in the bundle, minting multiple NFTs to the user's wallet.--## Code Example (UI Concept on Marketplace Page)-```html-<div class="bundle-card">- <h3>The 'Dancer's Pack' Bundle</h3>- <p class="bundle-price">5.00 USDC (Save 20%)</p>- <ul class="bundle-contents">- <li>Skill: ballet</li>- <li>Skill: hip_hop</li>- <li>Skill: tango</li>- </ul>- <button class="purchase-bundle-btn" data-bundle-id="123">Purchase Bundle</button>-</div>-```diff --git a/docs/monetization/24-subscription-model.md b/docs/monetization/24-subscription-model.mddeleted file mode 100644index 78efb3e29..000000000--- a/docs/monetization/24-subscription-model.md+++ /dev/null@@ -1,82 +0,0 @@-# Prompt 24: Subscription Pricing Model for Skills--## Objective-Extend the monetization system to support a subscription model, where a user pays a recurring fee for access to all of an agent's paid skills.--## Explanation-A one-time payment per skill is a good start, but subscriptions offer creators a predictable revenue stream and users a more convenient way to access a suite of premium skills. This prompt covers the necessary database and backend changes to introduce a subscription option.--## Instructions-1. **Database Schema Changes:**- * **`agents` table:** Add columns to the `agents` table (or a new `agent_subscriptions` table) to store subscription pricing:- * `subscription_amount` (BIGINT)- * `subscription_interval` (VARCHAR, e.g., 'month')- * `subscription_currency_mint` (VARCHAR)- * **`user_agent_subscriptions` table:** Create a new table to track active user subscriptions.- * `id`: Primary key.- * `user_id`: Foreign key to `users`.- * `agent_id`: Foreign key to `agents`.- * `status`: VARCHAR (e.g., 'active', 'cancelled', 'past_due').- * `current_period_ends_at`: TIMESTAMPTZ.- * `created_at`, `updated_at`.--2. **UI for Creators:**- * In `agent-edit.html`, under the new "Earnings" or a dedicated "Monetization" tab, add a form for creators to enable and configure subscriptions for their agent.- * This includes inputs for price, currency, and interval (e.g., a dropdown for "monthly").--3. **Modify Skill Access Check:**- * Update the `checkForValidSkillGrant` logic (from Prompt 15).- * Before checking for individual skill grants in `skill_access_grants`, it must **first** check if the user has an `active` subscription to the agent in the `user_agent_subscriptions` table where `current_period_ends_at` is in the future.- * If an active subscription exists, the check should immediately return `true`, granting access to all of the agent's skills.--4. **Subscription Payment Flow:**- * Create a new "Subscribe" button on the agent's detail page in the marketplace.- * This will trigger a new payment flow, similar to the single-skill payment:- * A new "prepare subscription" endpoint that creates a transaction for the subscription amount.- * A "confirm subscription" endpoint that verifies the payment and creates the initial record in `user_agent_subscriptions`.--5. **Recurring Billing (Advanced):**- * True recurring billing on Solana is complex. For this prompt, the focus is on a manual renewal model. The user's subscription is valid until `current_period_ends_at`.- * A separate, more advanced feature would involve setting up a cron job or on-chain program to handle automatic renewals.--## Code Example (Backend - Skill Access Check Logic)--```javascript-// The updated access check logic--async function checkForAccess({ userId, agentId, skillName }) {- // 1. Check for an active agent-level subscription first- const activeSubscription = await db('user_agent_subscriptions')- .where({- user_id: userId,- agent_id: agentId,- status: 'active',- })- .where('current_period_ends_at', '>', db.fn.now())- .first();-- if (activeSubscription) {- return true; // Subscription grants access to all skills- }-- // 2. If no subscription, check for a specific, single-skill grant- const skillGrant = await db('skill_access_grants')- .where({- user_id: userId,- agent_id: agentId,- skill_name: skillName,- })- .where(builder => {- builder.where('expires_at', '>', db.fn.now())- .orWhere('uses_left', '>', 0);- })- .first();-- if (skillGrant) {- // Decrement uses_left if applicable (as in Prompt 15)- return true;- }-- return false;-}-```diff --git a/docs/monetization/24_creator_analytics.md b/docs/monetization/24_creator_analytics.mddeleted file mode 100644index ce4b0e4f2..000000000--- a/docs/monetization/24_creator_analytics.md+++ /dev/null@@ -1,62 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 24: Analytics for Creators--## Objective-Provide creators with analytics on how users are interacting with their paid skills, helping them understand what's popular and what's not.--## Explanation-Beyond sales data, creators need insight into skill usage to improve their offerings. We will track every time a paid skill is executed and present this data in the creator dashboard.--## Instructions-1. **Database Schema for Skill Usage:**- * Create a new table `skill_usage_logs`.- * Columns: `id`, `user_id`, `agent_id`, `skill_name`, `created_at`, `status` ('success' or 'failure'), `execution_time_ms`.--2. **Log Skill Executions:**- * In the main skill execution API (`api/chat.js`), after the ownership/access control check passes, add a logging step.- * Before executing the skill, record the start time.- * After execution, record the end time and whether it succeeded or failed.- * Asynchronously (to avoid slowing down the chat response), insert a new record into the `skill_usage_logs` table with this information.--3. **Backend API for Analytics:**- * Create a new endpoint, `GET /api/creators/skill-analytics`.- * This endpoint will query the `skill_usage_logs` table for agents owned by the current user.- * It should aggregate the data to provide metrics like:- * Total usage count per skill.- * Unique users per skill.- * Success/failure rate per skill.- * Average execution time per skill.--4. **Frontend Dashboard UI:**- * In `creator-dashboard.html`, add a new section for "Skill Analytics."- * Fetch data from the new analytics endpoint.- * Display the aggregated data in a table. This gives creators a clear overview of which of their skills are most used, most reliable, and fastest.- * Optionally, add charts to visualize usage trends over time.--## Code Example (Logging in `api/chat.js`)--```javascript-// ... after access control checks pass-const startTime = Date.now();-let status = 'success';-let result;--try {- result = await executeSkill(skillName, ...);-} catch (e) {- status = 'failure';- throw e; // Re-throw the error to the user-} finally {- const executionTimeMs = Date.now() - startTime;- // Log asynchronously without waiting- sql`- INSERT INTO skill_usage_logs (user_id, agent_id, skill_name, status, execution_time_ms)- VALUES (${userId}, ${agentId}, ${skillName}, ${status}, ${executionTimeMs})- `.catch(dbErr => console.error("Failed to log skill usage:", dbErr));-}--return result;-```diff --git a/docs/monetization/25-affiliate-referral-system.md b/docs/monetization/25-affiliate-referral-system.mddeleted file mode 100644index b4af2cdbf..000000000--- a/docs/monetization/25-affiliate-referral-system.md+++ /dev/null@@ -1,52 +0,0 @@-----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/docs/monetization/25-creator-documentation.md b/docs/monetization/25-creator-documentation.mddeleted file mode 100644index 5fb037697..000000000--- a/docs/monetization/25-creator-documentation.md+++ /dev/null@@ -1,80 +0,0 @@-# Prompt 25: Documentation for Creators--## Objective-Create a well-written documentation page that explains the monetization features to agent creators, covering how to set prices, how payouts work, and the platform fees.--## Explanation-To encourage adoption of the new monetization features, we need to provide clear and comprehensive documentation for our creators. This page should be the go-to resource for any creator looking to start selling their skills.--## Instructions-1. **Create a New Docs Page:**- * In the `docs/` directory, create a new file, e.g., `monetization.md` or `selling-skills.md`.- * Add a link to this new page in your main documentation navigation.--2. **Write the Content:**- * Structure the document with clear headings.- * **Introduction:** Briefly explain the opportunity for creators to earn revenue.- * **Getting Started:** A step-by-step guide:- 1. "Set up your Payout Wallet": Explain where to find this setting in their dashboard and why it's important. Include a screenshot.- 2. "Pricing Your Skills": Show them where to go in the agent editor to set prices. Explain that a price of 0 means the skill is free.- * **How Payouts Work:**- * Explain that payments are made instantly on the Solana blockchain.- * Clarify that funds are sent directly to their configured payout wallet.- * **Platform Fees:**- * Be transparent about the platform fee. State the percentage clearly (e.g., "three.ws takes a 5% platform fee on every sale.").- * Explain that this fee is automatically deducted from the transaction.- * **FAQ Section:**- * "What currency can I sell in?" (Initially, just USDC).- * "When do I get paid?" (Instantly).- * "Where can I see my sales?" (Link to their Transaction History dashboard).--3. **Review and Publish:**- * Read through the documentation to ensure it's clear, concise, and free of jargon.- * Publish the page so it's accessible to creators.--## Markdown Example (`docs/selling-skills.md`)--```markdown-# Monetizing Your Agent's Skills--Welcome, creator! This guide will walk you through setting up your account to sell your agent's unique skills on the marketplace.--## How It Works--Our platform allows you to set a price for any skill your agent possesses. When a user wants to unlock that capability, they can purchase it directly from your agent's page. Payments are handled instantly and securely on the Solana blockchain.--## Getting Started: 2 Simple Steps--### 1. Set Your Payout Wallet--Before you can receive payments, you need to tell us where to send the funds.--- Go to your **Dashboard**.-- Navigate to the **Settings** tab.-- In the "Payout Wallet" section, enter your Solana public key. This is where all your earnings will be sent.-- Click "Save".----### 2. Price Your Skills--Now you're ready to set prices.--- Go to **My Agents** and select the agent you wish to edit.-- In the agent editor, find the "Skills" section.-- Next to each skill, you'll see an input field for the price in USDC.-- To make a skill free, simply leave the price as 0.-- Click "Save Prices" when you're done.--## Platform Fees--three.ws takes a 5% platform fee on every sale. This fee is automatically deducted from the purchase amount during the transaction. For example, if you price a skill at 1.00 USDC, you will receive 0.95 USDC.--## Frequently Asked Questions--**Q: When do I get paid?**-A: Instantly. The payment is sent to your wallet as soon as the user's transaction is confirmed on the blockchain.--**Q: Where can I track my sales?**-A: You can see a full list of all your sales in the "Transaction History" section of your dashboard.-```diff --git a/docs/monetization/25-documentation-for-creators.md b/docs/monetization/25-documentation-for-creators.mddeleted file mode 100644index 1cd337977..000000000--- a/docs/monetization/25-documentation-for-creators.md+++ /dev/null@@ -1,71 +0,0 @@-# Prompt 25: Documentation for Creators--## Objective-Create a comprehensive guide for agent creators that explains how to use the monetization features, including setting up their payout wallet, pricing their skills, and understanding the fee structure.--## Explanation-To ensure a successful launch of the monetization features, creators need clear and accessible documentation. A well-written guide reduces support requests and empowers creators to get started quickly. This document will be a new page in the main `docs` section of the website.--## Instructions-1. **Create a New Markdown File:**- * Create `docs/for-creators/monetization.md`.--2. **Write the Content:**- * Structure the document with clear headings and a logical flow.- * **Introduction:** Briefly explain the benefits of monetizing agent skills.- * **Getting Started (Checklist):**- 1. Create an Agent.- 2. Set up your Payout Wallet.- 3. Price your Skills.- 4. Publish your Agent.- * **Payout Wallet Setup:**- * Provide a step-by-step guide on where to find the monetization dashboard.- * Explain the importance of using a secure, self-custody Solana wallet.- * Show a screenshot of the input field.- * **Pricing Models:**- * Explain the "One-Time Purchase" model.- * Explain the "Subscription" model and how tiers work.- * Explain the "Pay-per-call" model for usage-based skills.- * Provide best-practice recommendations for pricing.- * **Fee Structure:**- * Be transparent about any platform fees. For example: "The platform takes a 5% fee on all primary sales to support development and maintain the marketplace."- * Explain how Solana network fees work.- * **Viewing Earnings:**- * Guide the user through the Earnings Dashboard, explaining each metric.- * **FAQ Section:**- * "How often are payouts processed?"- * "What currencies are supported?"- * "Can I change the price of a skill after it's published?"--3. **Link to the New Doc:**- * Add a link to this new documentation page from the creator dashboard UI to make it easily discoverable.--## Excerpt from `monetization.md`--```markdown-----title: Monetizing Your Agent-description: A guide for creators on how to sell access to their agent's skills on the marketplace.------# Monetizing Your Agent--Welcome, creator! The three.ws platform provides powerful tools to help you earn revenue from the unique skills you build for your AI agents. This guide will walk you through the entire process, from setting up your wallet to understanding your earnings.--## How It Works--You can monetize your agent's skills in three ways:--1. **One-Time Purchase:** Users pay once to unlock permanent access to a specific skill.-2. **Subscriptions:** Users pay a recurring fee (e.g., monthly) for access to a bundle of skills defined in a "tier."-3. **Pay-per-Call:** For resource-intensive skills, you can charge users a small amount for each time they use the skill.--## Getting Started: Your 4-Step Checklist--1. **Have an Agent:** You need an agent with at least one custom skill. You can create one in the [Agent Editor](/agent-edit).-2. **Set Your Payout Wallet:** Go to the "Monetization" tab in the editor and enter your Solana wallet address. This is where your earnings will be sent.-3. **Price Your Skills:** Use the tools in the Monetization tab to set prices for individual skills or group them into subscription tiers.-4. **Publish:** Once your agent is public in the marketplace, users can start buying your skills!--... (continue with detailed sections) ...-```diff --git a/docs/monetization/25-fiat-on-ramp-integration.md b/docs/monetization/25-fiat-on-ramp-integration.mddeleted file mode 100644index 5ce22c19b..000000000--- a/docs/monetization/25-fiat-on-ramp-integration.md+++ /dev/null@@ -1,23 +0,0 @@-----status: not-started------# Prompt 25: Fiat On-Ramp Integration--## Objective-Integrate a fiat on-ramp service (like Crossmint or Moonpay) to allow users to purchase skills with a credit card.--## Explanation-To reach the widest possible audience, it's essential to offer a way for non-crypto-native users to participate. A fiat on-ramp will handle the conversion from fiat to the required cryptocurrency, making the process seamless for the user.--## Instructions-1. **Choose a Provider:**- * Research and select a fiat on-ramp provider that offers a good developer experience and supports Solana.--2. **Integrate their SDK:**- * In the frontend, integrate the provider's SDK.- * The "Purchase" button would open their widget, where the user can complete the payment with a credit card.--3. **Webhook for Confirmation:**- * The on-ramp service will typically send a webhook to your backend when the crypto transaction is complete.- * Your backend will listen for this webhook, verify it, and then unlock the skill for the user.diff --git a/docs/monetization/25-free-trials-for-skills.md b/docs/monetization/25-free-trials-for-skills.mddeleted file mode 100644index e1fedaf70..000000000--- a/docs/monetization/25-free-trials-for-skills.md+++ /dev/null@@ -1,35 +0,0 @@-# Prompt 25: Free Trials for Skills--## Objective-Implement a "free trial" mechanism that allows users to temporarily access a paid skill for a limited time or a limited number of uses before needing to purchase it.--## Explanation-Free trials are a highly effective way to convert users by letting them experience the value of a premium feature firsthand. This can be implemented using temporary, off-chain access tokens.--## Instructions-1. **Database for Trials:**- * Create a `skill_trials` table.- * Columns should include `id`, `user_id`, `skill_name`, `agent_id`, `expiry_date` (for time-based trials) or `uses_remaining` (for usage-based trials).--2. **UI to Start a Trial:**- * On the marketplace page, next to a paid skill, add a "Start Free Trial" button.--3. **Backend API to Grant Trial:**- * Create an endpoint, `/api/skills/start-trial`.- * When a user clicks the button, this endpoint is called.- * It checks if the user has already had a trial for this skill.- * If not, it creates a new record in the `skill_trials` table for that user and skill, setting an `expiry_date` (e.g., 24 hours from now) or a `uses_remaining` count (e.g., 3).--4. **Update Gating Logic:**- * Modify the `tryUseSkill` function from Prompt 9 and Prompt 18.- * This function now has a more complex order of checks:- 1. Is the skill free? If yes, allow.- 2. Does the user have an active subscription? If yes, allow.- 3. Does the user have a valid NFT for the skill? If yes, allow.- 4. **New:** Does the user have an active free trial for the skill?- * To check this, call a new backend endpoint `/api/skills/check-trial`.- * This endpoint checks the `skill_trials` table. If a valid trial exists, it decrements `uses_remaining` (if applicable) and returns `{"has_trial_access": true}`.- 5. If all checks fail, deny access and prompt the user to purchase.--## Note on Security-Since trial status is stored in your central database (off-chain), this is less decentralized than NFT ownership but offers more flexibility for implementing complex trial logic (like limiting trials per IP address to prevent abuse).diff --git a/docs/monetization/25-user-purchases-page.md b/docs/monetization/25-user-purchases-page.mddeleted file mode 100644index 244b8ac1e..000000000--- a/docs/monetization/25-user-purchases-page.md+++ /dev/null@@ -1,116 +0,0 @@-# Prompt 25: User-Facing "My Purchased Skills" Page--## Objective-Create a new page for authenticated users where they can view all the premium skills and agent subscriptions they have purchased.--## Explanation-Users need a central place to see what premium content they have access to, when it expires, or how many uses are left. This page improves transparency and helps users manage their purchases.--## Instructions-1. **Create New Frontend Page:**- * Create a new HTML file, e.g., `purchases.html`.- * Add basic HTML structure and link to your standard CSS and a new JavaScript file, e.g., `src/purchases.js`.- * Add a link to this new page in the main user navigation menu (e.g., in the user dropdown after they log in).--2. **Create Backend Endpoint:**- * Create a new authenticated endpoint: `GET /api/users/my-purchases`.- * This endpoint should query two tables for the currently logged-in user:- * **`skill_access_grants`**: Fetch all active grants (not expired, or uses > 0). Join with the `agents` table to get agent names.- * **`user_agent_subscriptions`**: Fetch all active subscriptions. Join with `agents` to get agent names.- * Return a JSON object containing two arrays: `skill_grants` and `subscriptions`.--3. **Implement Frontend Logic:**- * In `src/purchases.js`, on page load, make a request to the `/api/users/my-purchases` endpoint.- * **Render Subscriptions:**- * Create a section for "Active Subscriptions".- * Iterate through the `subscriptions` array and render a card for each one, showing:- * Agent Name (linked to the agent's page).- * "Access until [formatted date]".- * **Render Skill Grants:**- * Create a section for "Individual Skill Purchases".- * Iterate through the `skill_grants` array and render a card or table row for each, showing:- * Skill Name.- * Agent Name.- * Access status (e.g., "Expires on [date]" or "[N] uses left").--## Code Example (Backend - `/api/users/my-purchases.js`)--```javascript-// --- Inside your API handler -----const user = await getAuthenticatedUser(req);--const skill_grants = await db('skill_access_grants as grants')- .join('agents', 'agents.id', 'grants.agent_id')- .where('grants.user_id', user.id)- .where(q => {- q.where('grants.expires_at', '>', db.fn.now())- .orWhere('grants.uses_left', '>', 0);- })- .select(- 'agents.name as agent_name',- 'agents.id as agent_id',- 'grants.skill_name',- 'grants.expires_at',- 'grants.uses_left'- );--const subscriptions = await db('user_agent_subscriptions as subs')- .join('agents', 'agents.id', 'subs.agent_id')- .where({- 'subs.user_id': user.id,- 'subs.status': 'active'- })- .where('subs.current_period_ends_at', '>', db.fn.now())- .select(- 'agents.name as agent_name',- 'agents.id as agent_id',- 'subs.current_period_ends_at'- );--res.status(200).json({ skill_grants, subscriptions });-```--## Code Example (Frontend - `purchases.html` + `src/purchases.js`)--```html-<!-- purchases.html -->-<body>- <!-- Header/Nav -->- <main class="container">- <h1>My Purchases</h1>-- <h2>Active Subscriptions</h2>- <div id="subscriptions-list" class="purchase-list">- <p>Loading...</p>- </div>-- <h2>Individual Skills</h2>- <div id="skills-list" class="purchase-list">- <p>Loading...</p>- </div>- </main>- <!-- Footer -->- <script type="module" src="/src/purchases.js"></script>-</body>-```--```javascript-// src/purchases.js--function render(data) {- const subsContainer = document.getElementById('subscriptions-list');- // ... logic to map over data.subscriptions and render HTML ...-- const skillsContainer = document.getElementById('skills-list');- // ... logic to map over data.skill_grants and render HTML ...- // For each grant, display either expires_at or uses_left.-}--fetch('/api/users/my-purchases')- .then(res => res.json())- .then(render)- .catch(err => {- document.querySelector('main').innerHTML = 'Error loading your purchases.';- });-```diff --git a/docs/monetization/25_admin_panel.md b/docs/monetization/25_admin_panel.mddeleted file mode 100644index c0006ae5e..000000000--- a/docs/monetization/25_admin_panel.md+++ /dev/null@@ -1,61 +0,0 @@-----status: not-started-last_updated: 2026-05-04-----# Prompt 25: Admin Panel for Monetization Management--## Objective-Create a secure admin-only panel to oversee and manage all monetization-related activities on the platform.--## Explanation-A robust platform needs an internal dashboard for administrators to monitor the health of the monetization system, manage disputes, and configure global settings. This is a critical tool for operations and support.--## Instructions-1. **Admin Authentication/Authorization:**- * Implement a role-based access control (RBAC) system. In the `users` table, add an `is_admin` boolean flag.- * Create a backend middleware that checks this flag for all admin API endpoints. If `is_admin` is not true, reject the request.--2. **Create the Admin UI:**- * Create a new, separate frontend application or a secured route (e.g., `/admin`) for the admin panel.- * This UI will be built to consume new, admin-only API endpoints.--3. **Backend APIs for Admin:**- * Create a new set of API routes under `/api/admin/`.- * **Global Stats (`/api/admin/stats`):**- * Display platform-wide revenue, total sales, new subscriptions, etc.- * **Transaction Viewer (`/api/admin/transactions`):**- * A searchable, paginated view of the `user_purchased_skills` and `skill_subscriptions` tables. Allows admins to look up any purchase.- * **Currency Management (`/api/admin/currencies`):**- * An interface to manage the `SUPPORTED_CURRENCIES` whitelist. Admins can add or disable currencies without a code deployment.- * **Platform Fee Configuration (`/api/admin/settings`):**- * Allow admins to view and update the platform fee percentage and treasury wallet address.--4. **Key Admin Features:**- * **Revenue Monitoring:** Dashboards with charts showing total platform revenue over time.- * **Dispute Resolution:** A feature that would allow an admin to, for example, manually credit a user with a skill if a purchase failed in a way our system didn't catch. This would involve manually inserting a row into `user_purchased_skills`.- * **User Lookup:** The ability to look up a user and see all their purchases and subscriptions.--## Code Example (Admin Auth Middleware)--```javascript-// In api/_lib/auth.js or a new middleware file--export async function requireAdmin(req, res) {- const user = await getSessionUser(req);- if (!user || !user.is_admin) {- error(res, 403, 'forbidden', 'You do not have administrative privileges.');- return null; // Stop execution- }- return user; // Proceed-}--// In an admin API handler-import { requireAdmin } from '../../_lib/auth.js';--export default wrap(async (req, res) => {- const adminUser = await requireAdmin(req, res);- if (!adminUser) return; // Stop if not admin-- // ... proceed with admin-only logic-});-```